コード例 #1
0
ファイル: Clump.cs プロジェクト: katalist5296/SanAndreasUnity
        public Clump(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var data = ReadSection<Data>(); // Struct
            if (data == null) return;

            var reader = new BinaryReader(new MemoryStream(data.Value));

            AtomicCount = reader.ReadUInt32();
            LightCount = reader.ReadUInt32();
            CameraCount = reader.ReadUInt32();

            FrameList = ReadSection<FrameList>(); // Frame List
            GeometryList = ReadSection<GeometryList>(); // Geometry List

            Atomics = new Atomic[AtomicCount];

            for (int i = 0; i < AtomicCount; ++i)
            {
                Atomics[i] = ReadSection<Atomic>(); // Atomic
            }

            var section = ReadSection<SectionData>();
            var extension = section as Extension;

            if (extension != null) {
                var collision = extension.FirstOrDefault<CollisionModel>();
                if (collision != null) {
                    Collision = collision.Collision;
                }
            }
        }
コード例 #2
0
        public FrameList(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var data = ReadSection<Data>();
            var reader = new BinaryReader(new MemoryStream(data.Value));

            FrameCount = reader.ReadUInt32();

            Frames = new Frame[FrameCount];

            for (var i = 0; i < FrameCount; ++i)
            {
                Frames[i] = new Frame(i, reader);
            }

            for (var i = 0; i < FrameCount; ++i)
            {
                var extension = ReadSection<Extension>();

                var frameName = extension.FirstOrDefault<FrameName>();
                var hierarchyAnimation = extension.FirstOrDefault<HierarchyAnimation>();

                if (frameName != null)
                {
                    Frames[i].Name = frameName.Name;
                }

                if (hierarchyAnimation != null)
                {
                    Frames[i].HAnim = hierarchyAnimation;
                }
            }
        }
コード例 #3
0
        public Material(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            SectionHeader.Read(stream);
            var reader = new BinaryReader(stream);

            Flags = reader.ReadUInt32();
            Colour = new Color4(reader);
            reader.ReadUInt32();
            TextureCount = reader.ReadUInt32();
            Textures = new Texture[TextureCount];
            Ambient = reader.ReadSingle();
            Smoothness = reader.ReadSingle();
            Specular = 1f - reader.ReadSingle();

            for (var i = 0; i < TextureCount; ++i) {
                Textures[i] = ReadSection<Texture>();
            }

            var extensions = ReadSection<Extension>();

            var smoothness = Smoothness;
            var specular = Specular;

            extensions.ForEach<ReflectionMaterial>(x => specular = x.Intensity);
            extensions.ForEach<SpecularMaterial>(x => smoothness = x.SpecularLevel);

            Smoothness = smoothness;
            Specular = specular;
        }
コード例 #4
0
        public TextureNative(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            SectionHeader.Read(stream);
            var reader = new BinaryReader(stream);

            PlatformID = reader.ReadUInt32();
            FilterFlags = (Filter) reader.ReadUInt16();
            WrapV = (WrapMode) reader.ReadByte();
            WrapU = (WrapMode) reader.ReadByte();
            DiffuseName = reader.ReadString(32);
            AlphaName = reader.ReadString(32);
            Format = (RasterFormat) reader.ReadUInt32();

            if (PlatformID == 9) {
                var dxt = reader.ReadString(4);
                switch (dxt) {
                    case "DXT1":
                        Compression = CompressionMode.DXT1;
                        break;
                    case "DXT3":
                        Compression = CompressionMode.DXT3; break;
                    default:
                        Compression = CompressionMode.None; break;
                }
            } else {
                Alpha = reader.ReadUInt32() == 0x1;
            }

            Width = reader.ReadUInt16();
            Height = reader.ReadUInt16();
            BPP = (byte) (reader.ReadByte() >> 3);
            MipMapCount = reader.ReadByte();
            RasterType = reader.ReadByte();

            if (RasterType != 0x4) {
                throw new Exception("Unexpected RasterType, expected 0x04.");
            }

            if (PlatformID == 9) {
                Alpha = (reader.ReadByte() & 0x1) == 0x1;
            } else {
                Compression = (CompressionMode) reader.ReadByte();
            }

            ImageDataSize = reader.ReadInt32();

            ImageData = reader.ReadBytes(ImageDataSize);

            if ((Format & RasterFormat.ExtMipMap) != 0) {
                var tot = ImageDataSize;
                for (var i = 0; i < MipMapCount; ++i) {
                    tot += ImageDataSize >> (2 * i);
                }

                ImageLevelData = reader.ReadBytes(tot);
            } else {
                ImageLevelData = ImageData;
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: wwh1004/Mdlib
#pragma warning restore IDE0059

        private static unsafe void PrintSectionHeader(SectionHeader value, int indent)
        {
            PrintRawData(value, indent);
            Print($"Name: {value.DisplayName}", indent);
            Print($"VirtualAddress: {value.RawValue->VirtualAddress:X8}", indent);
            Print($"VirtualSize: {value.RawValue->VirtualSize:X8}", indent);
            Print($"RawAddress: {value.RawValue->VirtualAddress:X8}", indent);
            Print($"RawSize: {value.RawValue->SizeOfRawData:X8}", indent);
        }
コード例 #6
0
        public void SectionHeader_WhenCreated_OffsetIsMovedOn()
        {
            byte[] contents = new byte[50];
            Offset offset   = 0;

            SectionHeader header = new SectionHeader(contents, offset);

            Assert.AreEqual(40, offset.Current);
        }
コード例 #7
0
        private static SectionHeader CreateSectionHeader(uint virtualAddress, uint size, uint startOfData)
        {
            SectionHeader header = new SectionHeader();

            header.VirtualAddress   = virtualAddress;
            header.SizeOfRawData    = size;
            header.PointerToRawData = startOfData;
            return(header);
        }
コード例 #8
0
        public MaterialListSectionData( SectionHeader header, FramedStream stream )
        {
            Section data = new Section( stream );
            MaterialCount = BitConverter.ToUInt32( ( data.Data as DataSectionData ).Value, 0 );
            Materials = new MaterialSectionData[ MaterialCount ];

            for ( int i = 0; i < MaterialCount; ++i )
                Materials[ i ] = new Section( stream ).Data as MaterialSectionData;
        }
コード例 #9
0
        private bool Validate32BitImage(BinaryAnalyzerContext context)
        {
            PEBinary    target       = context.PEBinary();
            PEHeader    peHeader     = target.PE.PEHeaders.PEHeader;
            SafePointer sp           = new SafePointer(target.PE.ImageBytes, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
            SafePointer loadConfigVA = target.PE.RVA2VA(sp);
            ImageLoadConfigDirectory32 loadConfig = new ImageLoadConfigDirectory32(peHeader, loadConfigVA);

            UInt32 cookieVA    = (UInt32)loadConfig.GetField(ImageLoadConfigDirectory32.Fields.SecurityCookie);
            UInt32 baseAddress = (UInt32)peHeader.ImageBase;

            // we need to find the offset in the file based on the cookie's VA
            UInt32        sectionSize, sectionVA = 0;
            SectionHeader ish = new SectionHeader();
            bool          foundCookieSection = false;

            foreach (SectionHeader t in target.PE.PEHeaders.SectionHeaders)
            {
                sectionVA   = (UInt32)t.VirtualAddress + baseAddress;
                sectionSize = (UInt32)t.VirtualSize;
                if ((cookieVA >= sectionVA) &&
                    (cookieVA < sectionVA + sectionSize))
                {
                    ish = t;
                    foundCookieSection = true;
                    break;
                }
            }

            if (!foundCookieSection)
            {
                LogCouldNotLocateCookie(context);
                return(false);
            }

            UInt64      fileCookieOffset = (cookieVA - baseAddress) - (sectionVA - baseAddress) + (UInt32)ish.PointerToRawData;
            SafePointer fileCookiePtr    = loadConfigVA;

            fileCookiePtr.Address = (int)fileCookieOffset;

            SafePointer boundsCheck = fileCookiePtr + 4;

            if (!CookieOffsetValid(context, boundsCheck))
            {
                return(false);
            }

            UInt32 cookie = BitConverter.ToUInt32(fileCookiePtr.GetBytes(4), 0);

            if (!StackProtectionUtilities.DefaultCookiesX86.Contains(cookie) && target.PE.Machine == Machine.I386)
            {
                LogFailure(context, cookie.ToString("x"));
                return(false);
            }

            return(true);
        }
コード例 #10
0
ファイル: ElfHeader.cs プロジェクト: gibbed/DemonsSoulsDebug
        public static ElfHeader Read(Stream input)
        {
            var fileHeader = input.ReadStructure <FileHeader>();

            fileHeader.Swap();

            if (fileHeader.HeaderSize != Marshal.SizeOf(fileHeader))
            {
                throw new FormatException("size mismatch for ELF header size");
            }

            input.Seek(fileHeader.ProgramHeadersOffset, SeekOrigin.Begin);
            var programHeaders = new ProgramHeader[fileHeader.ProgramHeaderCount];

            for (int i = 0; i < programHeaders.Length; i++)
            {
                programHeaders[i] = input.ReadStructure <ProgramHeader>();
                if (fileHeader.ProgramHeaderEntrySize != Marshal.SizeOf(programHeaders[i]))
                {
                    throw new FormatException("size mismatch for ELF program header size");
                }
                programHeaders[i].Swap();
            }

            input.Seek(fileHeader.SectionHeadersOffset, SeekOrigin.Begin);
            var sectionHeaders = new SectionHeader[fileHeader.SectionHeaderCount];

            for (int i = 0; i < sectionHeaders.Length; i++)
            {
                sectionHeaders[i] = input.ReadStructure <SectionHeader>();
                if (fileHeader.SectionHeaderEntrySize != Marshal.SizeOf(sectionHeaders[i]))
                {
                    throw new FormatException("size mismatch for ELF section header size");
                }
                sectionHeaders[i].Swap();
            }

            var sectionNames = new string[fileHeader.SectionHeaderCount];

            if (fileHeader.SectionHeaderStringTableIndex < fileHeader.SectionHeaderCount)
            {
                var stringTableHeader = sectionHeaders[fileHeader.SectionHeaderStringTableIndex];
                for (int i = 0; i < sectionHeaders.Length; i++)
                {
                    input.Seek(stringTableHeader.FileOffset + sectionHeaders[i].Name, SeekOrigin.Begin);
                    sectionNames[i] = input.ReadStringZ(Encoding.ASCII);
                }
            }

            return(new ElfHeader()
            {
                _FileHeader = fileHeader,
                _ProgramHeaders = programHeaders,
                _SectionHeaders = sectionHeaders,
                _SectionNames = sectionNames,
            });
        }
コード例 #11
0
ファイル: Section.cs プロジェクト: vashage/SA-World-Viewer
 public Section( FramedStream stream )
 {
     stream.PushFrame( 12 );
     Header = new SectionHeader( stream );
     stream.PopFrame();
     stream.PushFrame( Header.Size );
     Data = SectionData.FromStream( Header,  stream );
     stream.PopFrame();
 }
コード例 #12
0
        public TextureNativeSectionData( SectionHeader header, FramedStream stream )
        {
            SectionHeader dataHeader = new SectionHeader( stream );
            BinaryReader reader = new BinaryReader( stream );

            PlatformID = reader.ReadUInt32();
            FilterFlags = (Filter) reader.ReadUInt16();
            WrapV = (WrapMode) reader.ReadByte();
            WrapU = (WrapMode) reader.ReadByte();
            DiffuseName = reader.ReadString( 32 );
            AlphaName = reader.ReadString( 32 );
            Format = (RasterFormat) reader.ReadUInt32();

            if ( PlatformID == 9 )
            {
                String dxt = reader.ReadString( 4 );
                switch ( dxt )
                {
                    case "DXT1":
                        Compression = CompressionMode.DXT1; break;
                    case "DXT3":
                        Compression = CompressionMode.DXT3; break;
                    default:
                        Compression = CompressionMode.None; break;
                }
            }
            else
                Alpha = reader.ReadUInt32() == 0x1;

            Width = reader.ReadUInt16();
            Height = reader.ReadUInt16();
            BPP = (byte) ( reader.ReadByte() >> 3 );
            MipMapCount = reader.ReadByte();
            RasterType = reader.ReadByte();

            if ( RasterType != 0x4 )
                throw new Exception( "Unexpected RasterType, expected 0x04." );

            if ( PlatformID == 9 )
                Alpha = ( reader.ReadByte() & 0x1 ) == 0x1;
            else
                Compression = (CompressionMode) reader.ReadByte();

            ImageDataSize = reader.ReadUInt32();
            if ( ( Format & RasterFormat.ExtMipMap ) != 0 )
            {
                ImageLevelData = new byte[ MipMapCount ][];
                for ( int i = 0; i < MipMapCount; ++i )
                    ImageLevelData[ i ] = reader.ReadBytes( (int) ImageDataSize >> ( 2 * i ) );
            }
            else
            {
                ImageLevelData = new byte[ 1 ][];
                ImageLevelData[ 0 ] = reader.ReadBytes( (int) ImageDataSize );
            }
        }
コード例 #13
0
ファイル: StartSection.cs プロジェクト: sassembla/cs-wasm
        /// <summary>
        /// Reads the start section with the given header.
        /// </summary>
        /// <param name="header">The section header.</param>
        /// <param name="reader">The WebAssembly file reader.</param>
        /// <returns>The parsed section.</returns>
        public static StartSection ReadSectionPayload(SectionHeader header, BinaryWasmReader reader)
        {
            long startPos = reader.Position;
            // Read the start function index.
            uint startIndex = reader.ReadVarUInt32();
            // Skip any remaining bytes.
            var extraPayload = reader.ReadRemainingPayload(startPos, header);

            return(new StartSection(startIndex, extraPayload));
        }
コード例 #14
0
        public ClumpSectionData( SectionHeader header, FramedStream stream )
        {
            DataSectionData dat = (DataSectionData) new Section( stream ).Data;
            if ( dat == null )
                return;

            ObjectCount = BitConverter.ToUInt32( dat.Value, 0 );
            var frameList = new Section( stream );
            GeometryList = (GeometryListSectionData) new Section( stream ).Data;
        }
コード例 #15
0
        public LookAtConstrRotationController(BinaryReader br, SectionHeader sh)
        {
            this.SectionId = sh.id;

            HashName = new HashName(br.ReadUInt64());
            Unknown1 = br.ReadUInt32();
            PostLoadRef <ISection>(br.ReadUInt32(), s => Unknown2 = s);
            PostLoadRef <ISection>(br.ReadUInt32(), s => Unknown3 = s);
            PostLoadRef <ISection>(br.ReadUInt32(), s => Unknown4 = s);
        }
コード例 #16
0
ファイル: ChunkWriter.cs プロジェクト: yycmmc/Swiddler
        public PcapChunkWriter(Stream stream, ProtocolType protocolType)
        {
            _encoder = new IPBuilder(protocolType);

            var sh = SectionHeader.CreateEmptyHeader();

            sh.LinkType             = LinkTypes.Raw;
            sh.MaximumCaptureLength = 0x40000;
            _pcap = new PcapWriter(stream, sh);
        }
コード例 #17
0
ファイル: Model.cs プロジェクト: RubenHamelink/PD2ModelParser
        public sealed override void StreamReadData(BinaryReader instream, SectionHeader section)
        {
            id       = section.id;
            size     = section.size;
            object3D = new Object3D(instream);
            version  = instream.ReadUInt32();
            if (version == 6U)
            {
                v6_unknown5.X = instream.ReadSingle();
                v6_unknown5.Y = instream.ReadSingle();
                v6_unknown5.Z = instream.ReadSingle();
                v6_unknown6.X = instream.ReadSingle();
                v6_unknown6.Y = instream.ReadSingle();
                v6_unknown6.Z = instream.ReadSingle();
                v6_unknown7   = instream.ReadUInt32();
                v6_unknown8   = instream.ReadUInt32();
            }
            else
            {
                passthroughGP_ID = instream.ReadUInt32();
                topologyIP_ID    = instream.ReadUInt32();
                count            = instream.ReadUInt32();
                for (int index = 0; (long)index < (long)count; ++index)
                {
                    items.Add(new ModelItem
                    {
                        unknown1    = instream.ReadUInt32(),
                        vertCount   = instream.ReadUInt32(),
                        unknown2    = instream.ReadUInt32(),
                        faceCount   = instream.ReadUInt32(),
                        material_id = instream.ReadUInt32()
                    });
                }
                material_group_section_id = instream.ReadUInt32();
                unknown10    = instream.ReadUInt32();
                bounds_min.Z = instream.ReadSingle();
                bounds_min.X = instream.ReadSingle();
                bounds_min.Y = instream.ReadSingle();
                bounds_max.Z = instream.ReadSingle();
                bounds_max.X = instream.ReadSingle();
                bounds_max.Y = instream.ReadSingle();
                unknown11    = instream.ReadUInt32();
                unknown12    = instream.ReadUInt32();
                unknown13    = instream.ReadUInt32();
                skinbones_ID = instream.ReadUInt32();
            }

            remaining_data = null;
            if (section.offset + 12L + section.size <= instream.BaseStream.Position)
            {
                return;
            }
            remaining_data =
                instream.ReadBytes((int)(section.offset + 12L + section.size - instream.BaseStream.Position));
        }
コード例 #18
0
        public Unknown(BinaryReader instream, SectionHeader section)
        {
            this.SectionId = section.id;
            this.size      = section.size;

            this.tag = instream.ReadUInt32();

            instream.BaseStream.Position = section.offset + 12;

            this.data = instream.ReadBytes((int)section.size);
        }
コード例 #19
0
 public TopologyIP(BinaryReader br, SectionHeader sh)
 {
     this.SectionId = sh.id;
     this.size      = sh.size;
     PostLoadRef <Topology>(br.ReadUInt32(), i => Topology = i);
     this.remaining_data = null;
     if ((sh.offset + 12 + sh.size) > br.BaseStream.Position)
     {
         this.remaining_data = br.ReadBytes((int)((sh.offset + 12 + sh.size) - br.BaseStream.Position));
     }
 }
コード例 #20
0
        public Atomic(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var data = ReadSection<Data>(); // Struct
            var reader = new BinaryReader(new MemoryStream(data.Value));

            FrameIndex = reader.ReadUInt32();
            GeometryIndex = reader.ReadUInt32();
            Flags = (AtomicFlag)reader.ReadUInt32();
            Unused = reader.ReadUInt32();
        }
コード例 #21
0
        private Section <T> GetSectionFromSectionHeader(SectionHeader header)
        {
            Section <T> returned;

            switch (header.Type)
            {
            case SectionType.Null:
                goto default;

            case SectionType.ProgBits:
                returned = new ProgBitsSection <T>(header, readerSource);
                break;

            case SectionType.SymbolTable:
                returned = new SymbolTable <T>(header, readerSource, objectsStringTable, this);
                break;

            case SectionType.StringTable:
                returned = new StringTable <T>(header, readerSource);
                break;

            case SectionType.RelocationAddends:
                goto default;

            case SectionType.HashTable:
                goto default;

            case SectionType.Dynamic:
                goto default;

            case SectionType.Note:
                returned = new NoteSection <T>(header, Class, readerSource);
                break;

            case SectionType.NoBits:
                goto default;

            case SectionType.Relocation:
                goto default;

            case SectionType.Shlib:
                goto default;

            case SectionType.DynamicSymbolTable:
                returned = new SymbolTable <T>(header, readerSource, dynamicStringTable, this);
                break;

            default:
                Console.WriteLine(header.Type);
                returned = new Section <T>(header, readerSource);
                break;
            }
            return(returned);
        }
コード例 #22
0
ファイル: PEAction.cs プロジェクト: pombredanne/EatPdb
        internal void AppendSection(SectionHeader header)
        {
            var lastSec = NtHeader.FileHeader.NumberOfSections;

            NtHeader.FileHeader.NumberOfSections += 1;
            File.Seek(NTHeaderOffset, SeekOrigin.Begin);
            Writer.WriteStruct(NtHeader);
            File.Seek(16 * Marshal.SizeOf <DataDir>() + lastSec * Marshal.SizeOf <SectionHeader>(), SeekOrigin.Current);
            Writer.WriteStruct(header);
            Resolver.Put(header);
        }
コード例 #23
0
        public void Section()
        {
            var sh = new SectionHeader();

            sh.Name             = "Dummy";
            sh.PointerToRawData = 0x14e;
            sh.SizeOfRawData    = 0x1aff0;
            sh.VirtualAddress   = 0x1234c0;
            sh.VirtualSize      = 0x320ff;

            Assert.AreEqual("Dummy [14E:1AFF0h]=>Virtual[1234C0:320FFh]", sh.ToString());
        }
コード例 #24
0
 public TopologyIP(BinaryReader br, SectionHeader sh)
 {
     this.id             = sh.id;
     this.size           = sh.size;
     this.sectionID      = br.ReadUInt32();
     this.remaining_data = (byte[])null;
     if (sh.offset + 12L + (long)sh.size <= br.BaseStream.Position)
     {
         return;
     }
     this.remaining_data = br.ReadBytes((int)(sh.offset + 12L + (long)sh.size - br.BaseStream.Position));
 }
コード例 #25
0
        public TextureDictionarySectionData( SectionHeader header, FramedStream stream )
        {
            SectionHeader dataHeader = new SectionHeader( stream );
            BinaryReader reader = new BinaryReader( stream );

            TextureCount = reader.ReadUInt16();
            Textures = new TextureNativeSectionData[ TextureCount ];
            reader.ReadUInt16(); // Unknown

            for ( int i = 0; i < TextureCount; ++i )
                Textures[ i ] = new Section( stream ).Data as TextureNativeSectionData;
        }
コード例 #26
0
        public Texture(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            SectionHeader.Read(stream);
            var reader = new BinaryReader(stream);

            FilterMode = (Filter) reader.ReadUInt16();
            reader.ReadUInt16(); // Unknown

            TextureName = ReadSection<String>().Value;
            MaskName = ReadSection<String>().Value;
        }
コード例 #27
0
        /// <summary>
        /// Get the index in the image byte array corresponding to the RVA
        /// </summary>
        /// <param name="rva">The relative virtual address</param>
        public int GetOffset(int rva)
        {
            int index = PEReader.PEHeaders.GetContainingSectionIndex(rva);

            if (index == -1)
            {
                throw new BadImageFormatException("Failed to convert invalid RVA to offset: " + rva);
            }
            SectionHeader containingSection = PEReader.PEHeaders.SectionHeaders[index];

            return(rva - containingSection.VirtualAddress + containingSection.PointerToRawData);
        }
コード例 #28
0
        /// <summary>
        /// Reads the name section with the given header.
        /// </summary>
        /// <param name="Header">The section header.</param>
        /// <param name="Reader">The WebAssembly file reader.</param>
        /// <returns>The parsed section.</returns>
        public static NameSection ReadSectionPayload(SectionHeader Header, BinaryWasmReader Reader)
        {
            var  section  = new NameSection();
            long startPos = Reader.Position;

            while (Reader.Position - startPos < Header.PayloadLength)
            {
                // Read entries until we've read the entire section.
                section.Names.Add(NameEntry.Read(Reader));
            }
            return(section);
        }
コード例 #29
0
        public void Inject(WpdEntry entry, Stream input, Lazy <Stream> headers, Lazy <Stream> content, Byte[] buff)
        {
            int sourceSize = (int)input.Length;

            headers.Value.Position = entry.Offset;

            SectionHeader sectionHeader = headers.Value.ReadContent <SectionHeader>();
            VtexHeader    textureHeader = headers.Value.ReadContent <VtexHeader>();

            byte[] unknownData = new byte[textureHeader.GtexOffset - VtexHeader.Size];
            headers.Value.Read(unknownData, 0, unknownData.Length);

            GtexData data = headers.Value.ReadContent <GtexData>();

            if (data.MipMapData.Length != 1)
            {
                throw new NotImplementedException();
            }

            DdsHeader ddsHeader = DdsHeaderDecoder.FromFileStream(input);

            DdsHeaderEncoder.ToGtexHeader(ddsHeader, data.Header);

            GtexMipMapLocation mipMapLocation = data.MipMapData[0];
            int dataSize = sourceSize - 128;

            if (dataSize <= mipMapLocation.Length)
            {
                content.Value.Seek(mipMapLocation.Offset, SeekOrigin.Begin);
            }
            else
            {
                content.Value.Seek(0, SeekOrigin.End);
                mipMapLocation.Offset = (int)content.Value.Position;
            }

            input.CopyToStream(content.Value, dataSize, buff);
            mipMapLocation.Length = dataSize;

            using (MemoryStream ms = new MemoryStream(180))
            {
                sectionHeader.WriteToStream(ms);
                textureHeader.WriteToStream(ms);

                ms.Write(unknownData, 0, unknownData.Length);
                data.WriteToStream(ms);

                ms.SetPosition(0);

                DefaultWpdEntryInjector defaultInjector = new DefaultWpdEntryInjector();
                defaultInjector.Inject(entry, ms, headers, content, buff);
            }
        }
コード例 #30
0
        public Camera(BinaryReader instream, SectionHeader section) : base(instream)
        {
            this.SectionId = section.id;
            this.size      = section.size;

            Unknown1 = instream.ReadSingle();
            Unknown2 = instream.ReadSingle();
            Unknown3 = instream.ReadSingle();
            Unknown4 = instream.ReadSingle();
            Unknown5 = instream.ReadSingle();
            Unknown6 = instream.ReadSingle();
        }
コード例 #31
0
        public GeometryList(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var data = ReadSection<Data>();

            GeometryCount = BitConverter.ToUInt32(data.Value, 0);
            Geometry = new Geometry[GeometryCount];

            for (var i = 0; i < GeometryCount; ++i) {
                Geometry[i] = ReadSection<Geometry>();
            }
        }
コード例 #32
0
ファイル: Bones.cs プロジェクト: kythyria/payday2-model-tool
        public Bones(BinaryReader instream, SectionHeader section) : this(instream)
        {
            Log.Default.Warn("Model contains a Bones that isn't a SkinBones!");
            this.SectionId = section.id;
            this.size      = section.size;

            if ((section.offset + 12 + section.size) > instream.BaseStream.Position)
            {
                remaining_data =
                    instream.ReadBytes((int)((section.offset + 12 + section.size) - instream.BaseStream.Position));
            }
        }
コード例 #33
0
ファイル: RESFile.cs プロジェクト: zheka20012/KOTRMobile
        public static RESFile OpenFile(string filePath)
        {
            using (BinaryReader reader = new BinaryReader(File.OpenRead(filePath)))
            {
                RESFile file = new RESFile();

                long fileLength = reader.BaseStream.Length;

                while (reader.BaseStream.Position < fileLength) //TODO: Caching
                {
                    SectionHeader header = new SectionHeader(reader);

                    switch (header.Type)
                    {
                    case SectionType.COLORS:
                        file.ReadColors(reader, header.Count);
                        break;

                    case SectionType.TEXTUREFILES:
                        file.ReadTextureFiles(reader, header.Count);
                        break;

                    case SectionType.PALETTEFILES:
                        file.ReadPalettes(reader, header.Count);
                        break;

                    case SectionType.SOUNDFILES:
                        file.ReadSoundFiles(reader, header.Count);
                        break;

                    case SectionType.BACKFILES:
                        break;

                    case SectionType.MASKFILES:
                        file.ReadMaskFiles(reader, header.Count);
                        break;

                    case SectionType.MATERIALS:
                        file.ReadMaterials(reader, header.Count);
                        break;

                    case SectionType.SOUNDS:
                        file.ReadSoundNames(reader, header.Count);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                return(file);
            }
        }
コード例 #34
0
        public MaterialList(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var data = ReadSection<Data>();
            MaterialCount = BitConverter.ToUInt32(data.Value, 0);

            Materials = new Material[MaterialCount];

            for (var i = 0; i < MaterialCount; ++i) {
                Materials[i] = ReadSection<Material>();
            }
        }
コード例 #35
0
 public PassthroughGP(BinaryReader instream, SectionHeader section)
 {
     this.SectionId = section.id;
     this.size      = section.size;
     PostLoadRef <Geometry>(instream.ReadUInt32(), i => this.Geometry = i);
     PostLoadRef <Topology>(instream.ReadUInt32(), i => this.Topology = i);
     this.remaining_data = null;
     if ((section.offset + 12 + section.size) > instream.BaseStream.Position)
     {
         this.remaining_data = instream.ReadBytes((int)((section.offset + 12 + section.size) - instream.BaseStream.Position));
     }
 }
コード例 #36
0
        private void ProcessSection(SectionHeader parent)
        {
            var end = reader.Position + parent.Size;

            while (reader.Position < end)
            {
                var header = new SectionHeader(reader);

                switch (header.Type)
                {
                case SectionType.Extension:
                case SectionType.Texture:
                case SectionType.Material:
                case SectionType.MaterialList:
                case SectionType.FrameList:
                case SectionType.Geometry:
                case SectionType.Clump:
                case SectionType.Atomic:
                case SectionType.GeometryList:
                    ProcessSection(header);
                    break;

                case SectionType.BinMesh:
                    ParseBinaryMesh(header.Size);
                    break;

                case SectionType.Frame:
                    ParseFrame(header.Size);
                    break;

                case SectionType.Struct:
                    ParseStruct(header, parent.Type);
                    break;

                case SectionType.String:
                    ParseStringSection(header.Size, parent.Type);
                    break;

                case SectionType.MaterialSpecular:
                    ParseMaterialSpecular();
                    break;

                case SectionType.MaterialReflection:
                    ParseMaterialReflection();
                    break;

                default:
                    reader.SkipStream(header.Size);
                    break;
                }
            }
        }
コード例 #37
0
        private void AlignSection(SectionHeader header)
        {
            int written = (int)BaseStream.Position - (int)header.PointerToRawData;
            int rest    = (int)header.SizeOfRawData - written;

            if (rest <= 0)
            {
                return;
            }

            Advance(rest - 1);
            WriteUInt8(0);
        }
コード例 #38
0
 static void ReadSectionHeader(BinaryStreamReader reader, SectionHeader section)
 {
     section.Name                 = reader.ReadFixedZeroFilledAsciiString(SectionHeader.MaximumNameSize);
     section.VirtualSize          = reader.ReadUInt32();
     section.VirtualAddress       = reader.ReadUInt32();
     section.SizeOfRawData        = reader.ReadUInt32();
     section.PointerToRawData     = reader.ReadUInt32();
     section.PointerToRelocations = reader.ReadUInt32();
     section.PointerToLinenumbers = reader.ReadUInt32();
     section.NumberOfRelocations  = reader.ReadUInt16();
     section.NumberOfLinenumbers  = reader.ReadUInt16();
     section.Characteristics      = (SectionCharacteristics)reader.ReadUInt32();
 }
コード例 #39
0
 static void WriteSectionHeader(BinaryStreamWriter writer, SectionHeader section)
 {
     writer.WriteFixedZeroFilledAsciiString(section.Name, SectionHeader.MaximumNameSize);
     writer.WriteUInt32(section.VirtualSize);
     writer.WriteUInt32(section.VirtualAddress);
     writer.WriteUInt32(section.SizeOfRawData);
     writer.WriteUInt32(section.PointerToRawData);
     writer.WriteUInt32(section.PointerToRelocations);
     writer.WriteUInt32(section.PointerToLinenumbers);
     writer.WriteUInt16(section.NumberOfRelocations);
     writer.WriteUInt16(section.NumberOfLinenumbers);
     writer.WriteUInt32((uint)section.Characteristics);
 }
コード例 #40
0
        public XPeParser(String path)
        {
            f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryReader br = new BinaryReader(f);

            /* Check the main signature */
            ushort dosSig = br.ReadUInt16();

            if (dosSig != IMAGE_DOS_SIGNATURE)
            {
                throw new Exception("Invalid DOS Signature for the executable!");
            }

            /* Seek to the PE header */
            br.BaseStream.Seek(0x3C, SeekOrigin.Begin);
            uint peOffset = br.ReadUInt32();

            /* Check the PE signature */
            br.BaseStream.Seek(peOffset, SeekOrigin.Begin);

            uint peSign = br.ReadUInt32();

            if (peSign != IMAGE_NT_SIGNATURE)
            {
                throw new Exception("Invalid PE Signature for the executable!");
            }

            /* Read the rest of PE header, then check some fields */
            imHdr = new ImageFileHeader(br);

            /* Specific machine value to indicate Xbox 360 */
            if (imHdr.Machine != 0x1F2)
            {
                throw new Exception("The PE is valid but it's not an Xbox 360 executable.");
            }

            /*
             * The strange thing is that imHdr.Characteristics is set to 0x102
             * (usually), indicating a 32bit architecture, while the Xenon is 64-bit.
             * Microsoft likes to mess with their own specifications...
             */
            optHdr = new OptionalHeader(br);

            sectHdrs = new SectionHeader[imHdr.NumberOfSections];
            for (int i = 0; i < imHdr.NumberOfSections; i++)
            {
                sectHdrs[i] = new SectionHeader(br);
            }

            FileName = path;
        }
コード例 #41
0
        public MaterialSplitList(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var reader = new BinaryReader(stream);

            TriangleStrip = reader.ReadUInt32() == 1;
            SplitCount = reader.ReadUInt32();
            MaterialSplits = new MaterialSplit[SplitCount];
            FaceCount = reader.ReadUInt32();

            for (var i = 0; i < SplitCount; ++i) {
                MaterialSplits[i] = new MaterialSplit(stream);
            }
        }
コード例 #42
0
ファイル: VolFile.cs プロジェクト: TechCor8/OP2UtilityDotNet
 private void ExtractFileUncompressed(int index, Stream destination)
 {
     try
     {
         // Calling GetSectionHeader moves the streamReader's position to just past the SectionHeader
         SectionHeader sectionHeader = GetSectionHeader(index);
         byte[]        buffer        = archiveFileReader.ReadBytes((int)sectionHeader.length);
         destination.Write(buffer, 0, buffer.Length);
     }
     catch (System.Exception e)
     {
         throw new System.Exception("Error attempting to extracted uncompressed file " + index + ". Internal Error Message: " + e);
     }
 }
コード例 #43
0
        internal int getRelocationOffset()
        {
            int limit = ntHeader.numberOfSections;

            for (int i = 0; i < limit; i++)
            {
                SectionHeader section = this.sectionArray[i];
                if (section.name.StartsWith(".reloc"))
                {
                    return(this.VaToOffset(section.virtualAddress));
                }
            }
            return(0);
        }
コード例 #44
0
        public TextureDictionary(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            SectionHeader.Read(stream);
            var reader = new BinaryReader(stream);

            TextureCount = reader.ReadUInt16();
            Textures = new TextureNative[TextureCount];
            reader.ReadUInt16(); // Unknown

            for (var i = 0; i < TextureCount; ++i) {
                Textures[i] = ReadSection<TextureNative>();
            }
        }
コード例 #45
0
        /// <summary>
        /// Reads a type section's payload from the given binary WebAssembly reader.
        /// </summary>
        /// <param name="header">The type section's header.</param>
        /// <param name="reader">A reader for a binary WebAssembly file.</param>
        /// <returns>A parsed type section.</returns>
        public static TypeSection ReadSectionPayload(SectionHeader header, BinaryWasmReader reader)
        {
            long initPos   = reader.Position;
            uint typeCount = reader.ReadVarUInt32();
            var  types     = new List <FunctionType>((int)typeCount);

            for (uint i = 0; i < typeCount; i++)
            {
                types.Add(FunctionType.ReadFrom(reader));
            }
            var extraBytes = reader.ReadRemainingPayload(initPos, header);

            return(new TypeSection(types, extraBytes));
        }
コード例 #46
0
ファイル: Skin.cs プロジェクト: katalist5296/SanAndreasUnity
        public Skin(SectionHeader header, Stream stream)
            : base(header, stream)
        {
            var reader = new BinaryReader(stream);

            Int32 boneCount = (Int32)reader.ReadByte();
            Int32 boneIdCount = (Int32)reader.ReadByte();
            UInt16 weightsPerVertex = reader.ReadUInt16();

            byte[] boneIds = reader.ReadBytes(boneIdCount);

            var vertexCount = header.GetParent<Geometry>().VertexCount;

            VertexBoneIndices = new SkinBoneIndices[vertexCount];
            VertexBoneWeights = new SkinBoneWeights[vertexCount];

            for (int i = 0; i < vertexCount; ++i)
            {
                VertexBoneIndices[i] = new SkinBoneIndices(reader);
            }

            for (int i = 0; i < vertexCount; ++i)
            {
                VertexBoneWeights[i] = new SkinBoneWeights(reader);
            }

            SkinToBoneMatrices = new Matrix4x4[boneCount];

            for (int i = 0; i < boneCount; ++i)
            {
                if (boneIdCount == 0)
                {
                    reader.BaseStream.Seek(4, SeekOrigin.Current);
                }

                SkinToBoneMatrices[i] = new Matrix4x4(reader);
            }

            UInt32 boneLimit = reader.ReadUInt32();
            UInt32 meshCount = reader.ReadUInt32();
            UInt32 RLE = reader.ReadUInt32();

            if (meshCount > 0)
            {
                MeshBoneRemapIndices = reader.ReadBytes((Int32)(boneCount + 2 * (RLE + meshCount)));
            }
        }
コード例 #47
0
        public MaterialSectionData( SectionHeader header, FramedStream stream )
        {
            SectionHeader dataHeader = new SectionHeader( stream );
            BinaryReader reader = new BinaryReader( stream );

            reader.ReadUInt32(); // Unknown
            Colour = new Color4( reader.ReadByte(), reader.ReadByte(), reader.ReadByte(), reader.ReadByte() );
            var unk = reader.ReadUInt32(); // Unknown
            TextureCount = reader.ReadUInt32();
            Textures = new TextureSectionData[ TextureCount ];
            reader.ReadSingle(); // Unknown
            reader.ReadSingle(); // Unknown
            reader.ReadSingle(); // Unknown

            for ( int i = 0; i < TextureCount; ++i )
                Textures[ i ] = new Section( stream ).Data as TextureSectionData;
        }
コード例 #48
0
        public MaterialSplitSectionData( SectionHeader header, FramedStream stream )
        {
            BinaryReader reader = new BinaryReader( stream );

            TriangleStrip = reader.ReadUInt32() == 1;
            SplitCount = reader.ReadUInt32();
            MaterialSplits = new MaterialSplit[ SplitCount ];
            FaceCount = reader.ReadUInt32();

            IndexCount = 0;
            for ( UInt16 i = 0; i < SplitCount; ++i )
            {
                MaterialSplits[ i ] = new MaterialSplit( IndexCount, stream );
                IndexCount += MaterialSplits[ i ].VertexCount;
            }

            if ( FaceCount + SplitCount != IndexCount )
                throw new Exception( "Bad model format" );
        }
コード例 #49
0
ファイル: Model.cs プロジェクト: vashage/SA-World-Viewer
        public Model( String name, FramedStream stream )
        {
            Name = name;

            List<GeometrySectionData> geos = new List<GeometrySectionData>();
            while ( stream.CanRead )
            {
                SectionHeader header = new SectionHeader( stream );
                if ( header.Type == SectionType.Clump )
                {
                    ClumpSectionData data = SectionData.FromStream<ClumpSectionData>( header, stream );
                    if( data.GeometryList != null )
                        geos.AddRange( data.GeometryList.Geometry );
                }
                break;
            }
            myGeometry = geos.ToArray();

            VertexBuffer = null;
        }
コード例 #50
0
ファイル: Writer.cs プロジェクト: Norbyte/lslib
        private SectionHeader InitHeader()
        {
            var header = new SectionHeader();
            header.compression = 0;
            header.offsetInFile = 0; // Set after serialization is finished
            header.compressedSize = 0; // Set after serialization is finished
            header.uncompressedSize = 0; // Set after serialization is finished
            if (Type == SectionType.RigidVertex || Type == SectionType.DeformableVertex)
                header.alignment = 32;
            else
                header.alignment = 4;
            header.first16bit = 0; // Set after serialization is finished
            header.first8bit = 0; // Set after serialization is finished
            header.relocationsOffset = 0; // Set after serialization is finished
            header.numRelocations = 0; // Set after serialization is finished
            header.mixedMarshallingDataOffset = 0; // Set after serialization is finished
            header.numMixedMarshallingData = 0; // Set after serialization is finished

            return header;
        }
コード例 #51
0
ファイル: XPeParser.cs プロジェクト: aomega08/X360Decompiler
        public XPeParser(String path)
        {
            f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            BinaryReader br = new BinaryReader(f);

            /* Check the main signature */
            ushort dosSig = br.ReadUInt16();
            if (dosSig != IMAGE_DOS_SIGNATURE)
                throw new Exception("Invalid DOS Signature for the executable!");

            /* Seek to the PE header */
            br.BaseStream.Seek(0x3C, SeekOrigin.Begin);
            uint peOffset = br.ReadUInt32();

            /* Check the PE signature */
            br.BaseStream.Seek(peOffset, SeekOrigin.Begin);

            uint peSign = br.ReadUInt32();
            if (peSign != IMAGE_NT_SIGNATURE)
                throw new Exception("Invalid PE Signature for the executable!");

            /* Read the rest of PE header, then check some fields */
            imHdr = new ImageFileHeader(br);

            /* Specific machine value to indicate Xbox 360 */
            if (imHdr.Machine != 0x1F2)
                throw new Exception("The PE is valid but it's not an Xbox 360 executable.");

            /*
             * The strange thing is that imHdr.Characteristics is set to 0x102
             * (usually), indicating a 32bit architecture, while the Xenon is 64-bit.
             * Microsoft likes to mess with their own specifications...
             */
            optHdr = new OptionalHeader(br);

            sectHdrs = new SectionHeader[imHdr.NumberOfSections];
            for (int i = 0; i < imHdr.NumberOfSections; i++)
                sectHdrs[i] = new SectionHeader(br);

            FileName = path;
        }
コード例 #52
0
        public void Ctor(
            string name,
            int virtualSize,
            int virtualAddress,
            int sizeOfRawData,
            int ptrToRawData,
            int ptrToRelocations,
            int ptrToLineNumbers,
            ushort numRelocations,
            ushort numLineNumbers,
            SectionCharacteristics characteristics)
        {
            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
            writer.Write(PadSectionName(name));
            writer.Write(virtualSize);
            writer.Write(virtualAddress);
            writer.Write(sizeOfRawData);
            writer.Write(ptrToRawData);
            writer.Write(ptrToRelocations);
            writer.Write(ptrToLineNumbers);
            writer.Write(numRelocations);
            writer.Write(numLineNumbers);
            writer.Write((uint) characteristics);
            writer.Dispose();

            stream.Position = 0;
            var reader = new PEBinaryReader(stream, (int) stream.Length);

            var header = new SectionHeader(ref reader);

            Assert.Equal(name, header.Name);
            Assert.Equal(virtualSize, header.VirtualSize);
            Assert.Equal(virtualAddress, header.VirtualAddress);
            Assert.Equal(sizeOfRawData, header.SizeOfRawData);
            Assert.Equal(ptrToRawData, header.PointerToRawData);
            Assert.Equal(ptrToLineNumbers, header.PointerToLineNumbers);
            Assert.Equal(numRelocations, header.NumberOfRelocations);
            Assert.Equal(numLineNumbers, header.NumberOfLineNumbers);
            Assert.Equal(characteristics, header.SectionCharacteristics);
        }
コード例 #53
0
ファイル: PeImage.cs プロジェクト: Predator75/de4dot
        void init()
        {
            seek(0);
            if (reader.ReadUInt16() != 0x5A4D)
                throw new BadImageFormatException("Not a PE file");
            skip(29 * 2);
            seek(reader.ReadUInt32());

            if (reader.ReadUInt32() != 0x4550)
                throw new BadImageFormatException("Not a PE file");
            fileHeader = new FileHeader(reader);
            optionalHeader = new OptionalHeader(reader);

            sectionHeaders = new SectionHeader[fileHeader.numberOfSections];
            for (int i = 0; i < sectionHeaders.Length; i++)
                sectionHeaders[i] = new SectionHeader(reader);

            uint netRva = optionalHeader.dataDirectories[14].virtualAddress;
            if (netRva != 0) {
                seekRva(netRva);
                cor20Header = new Cor20Header(reader);
                dotNetSection = getSectionHeader(netRva);
                seekRva(cor20Header.metadataDirectory.virtualAddress);
                cor20Header.initMetadataTable();
            }

            uint resourceRva = optionalHeader.dataDirectories[2].virtualAddress;
            uint resourceOffset = 0;
            if (resourceRva != 0)
                resourceOffset = rvaToOffset(resourceRva);
            resources = new Resources(reader, resourceOffset, optionalHeader.dataDirectories[2].size);
        }
コード例 #54
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
        private List<SectionHeader> CreateSectionHeaders(MetadataSizes metadataSizes, int sectionCount)
        {
            var sectionHeaders = new List<SectionHeader>();
            SectionHeader lastSection;
            int sizeOfPeHeaders = ComputeSizeOfPeHeaders(sectionCount);
            int sizeOfTextSection = ComputeSizeOfTextSection(metadataSizes);

            sectionHeaders.Add(lastSection = new SectionHeader(
                characteristics: SectionCharacteristics.MemRead |
                                 SectionCharacteristics.MemExecute |
                                 SectionCharacteristics.ContainsCode,
                name: ".text",
                numberOfLinenumbers: 0,
                numberOfRelocations: 0,
                pointerToLinenumbers: 0,
                pointerToRawData: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.FileAlignment),
                pointerToRelocations: 0,
                relativeVirtualAddress: BitArithmeticUtilities.Align(sizeOfPeHeaders, _properties.SectionAlignment),
                sizeOfRawData: BitArithmeticUtilities.Align(sizeOfTextSection, _properties.FileAlignment),
                virtualSize: sizeOfTextSection
            ));

            int resourcesRva = BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment);
            int sizeOfWin32Resources = this.ComputeSizeOfWin32Resources(resourcesRva);

            if (sizeOfWin32Resources > 0)
            {
                sectionHeaders.Add(lastSection = new SectionHeader(
                    characteristics: SectionCharacteristics.MemRead |
                                     SectionCharacteristics.ContainsInitializedData,
                    name: ResourceSectionName,
                    numberOfLinenumbers: 0,
                    numberOfRelocations: 0,
                    pointerToLinenumbers: 0,
                    pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData,
                    pointerToRelocations: 0,
                    relativeVirtualAddress: resourcesRva,
                    sizeOfRawData: BitArithmeticUtilities.Align(sizeOfWin32Resources, _properties.FileAlignment),
                    virtualSize: sizeOfWin32Resources
                ));
            }

            if (_properties.RequiresStartupStub)
            {
                var size = (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet) ? 14 : 12; // TODO: constants

                sectionHeaders.Add(lastSection = new SectionHeader(
                    characteristics: SectionCharacteristics.MemRead |
                                     SectionCharacteristics.MemDiscardable |
                                     SectionCharacteristics.ContainsInitializedData,
                    name: RelocationSectionName,
                    numberOfLinenumbers: 0,
                    numberOfRelocations: 0,
                    pointerToLinenumbers: 0,
                    pointerToRawData: lastSection.PointerToRawData + lastSection.SizeOfRawData,
                    pointerToRelocations: 0,
                    relativeVirtualAddress: BitArithmeticUtilities.Align(lastSection.RelativeVirtualAddress + lastSection.VirtualSize, _properties.SectionAlignment),
                    sizeOfRawData: BitArithmeticUtilities.Align(size, _properties.FileAlignment),
                    virtualSize: size));
            }

            Debug.Assert(sectionHeaders.Count == sectionCount);
            return sectionHeaders;
        }
コード例 #55
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
 private void WriteResourceSection(Stream peStream, SectionHeader resourceSection)
 {
     peStream.Position = resourceSection.PointerToRawData;
     _win32ResourceWriter.PadTo(resourceSection.SizeOfRawData);
     _win32ResourceWriter.WriteContentTo(peStream);
 }
コード例 #56
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
        private void WriteRelocSection(Stream peStream, SectionHeader relocSection, int entryPointAddress)
        {
            peStream.Position = relocSection.PointerToRawData;
            var writer = new BlobBuilder(relocSection.SizeOfRawData);
            writer.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000);
            writer.WriteUInt32(_properties.Requires64bits && !_properties.RequiresAmdInstructionSet ? 14u : 12u);
            uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000;
            uint relocType = _properties.Requires64bits ? 10u : 3u;
            ushort s = (ushort)((relocType << 12) | offsetWithinPage);
            writer.WriteUInt16(s);
            if (_properties.Requires64bits && !_properties.RequiresAmdInstructionSet)
            {
                writer.WriteUInt32(relocType << 12);
            }

            writer.WriteUInt16(0); // next chunk's RVA
            writer.PadTo(relocSection.SizeOfRawData);
            writer.WriteContentTo(peStream);
        }
コード例 #57
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
        private void WriteDebugTable(Stream peStream, SectionHeader textSection, ContentId nativePdbContentId, ContentId portablePdbContentId, MetadataSizes metadataSizes)
        {
            Debug.Assert(nativePdbContentId.IsDefault ^ portablePdbContentId.IsDefault);

            var writer = PooledBlobBuilder.GetInstance();

            // characteristics:
            writer.WriteUInt32(0);

            // PDB stamp & version
            if (portablePdbContentId.IsDefault)
            {
                writer.WriteBytes(nativePdbContentId.Stamp);
                writer.WriteUInt32(0);
            }
            else
            {
                writer.WriteBytes(portablePdbContentId.Stamp);
                writer.WriteUInt32('P' << 24 | 'M' << 16 | 0x00 << 8 | 0x01);
            }
            
            // type: 
            const int ImageDebugTypeCodeView = 2;
            writer.WriteUInt32(ImageDebugTypeCodeView);

            // size of data:
            writer.WriteUInt32((uint)ComputeSizeOfDebugDirectoryData());

            uint dataOffset = (uint)ComputeOffsetToDebugTable(metadataSizes) + ImageDebugDirectoryBaseSize;

            // PointerToRawData (RVA of the data):
            writer.WriteUInt32((uint)textSection.RelativeVirtualAddress + dataOffset);

            // AddressOfRawData (position of the data in the PE stream):
            writer.WriteUInt32((uint)textSection.PointerToRawData + dataOffset);

            writer.WriteByte((byte)'R');
            writer.WriteByte((byte)'S');
            writer.WriteByte((byte)'D');
            writer.WriteByte((byte)'S');

            // PDB id:
            writer.WriteBytes(nativePdbContentId.Guid ?? portablePdbContentId.Guid);

            // age
            writer.WriteUInt32(PdbWriter.Age);

            // UTF-8 encoded zero-terminated path to PDB
            writer.WriteUTF8(_pdbPathOpt, allowUnpairedSurrogates: true);
            writer.WriteByte(0);

            writer.WriteContentTo(peStream);
            writer.Free();
        }
コード例 #58
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
        private void WriteTextSection(
            Stream peStream,
            SectionHeader textSection,
            int importTableRva,
            int importAddressTableRva,
            int entryPointToken,
            BlobBuilder metadataWriter,
            BlobBuilder ilWriter,
            BlobBuilder mappedFieldDataWriter,
            BlobBuilder managedResourceWriter,
            MetadataSizes metadataSizes,
            ContentId nativePdbContentId,
            ContentId portablePdbContentId,
            out long metadataPosition)
        {
            // TODO: zero out all bytes:
            peStream.Position = textSection.PointerToRawData;

            if (_properties.RequiresStartupStub)
            {
                WriteImportAddressTable(peStream, importTableRva);
            }

            var corHeader = CreateCorHeader(metadataSizes, textSection.RelativeVirtualAddress, entryPointToken);
            WriteCorHeader(peStream, corHeader);

            // IL:
            ilWriter.Align(4);
            ilWriter.WriteContentTo(peStream);

            // metadata:
            metadataPosition = peStream.Position;
            Debug.Assert(metadataWriter.Count % 4 == 0);
            metadataWriter.WriteContentTo(peStream);

            // managed resources:
            Debug.Assert(managedResourceWriter.Count % 4 == 0);
            managedResourceWriter.WriteContentTo(peStream);

            // strong name signature:
            WriteSpaceForHash(peStream, metadataSizes.StrongNameSignatureSize);

            if (EmitPdb)
            {
                WriteDebugTable(peStream, textSection, nativePdbContentId, portablePdbContentId, metadataSizes);
            }

            if (_properties.RequiresStartupStub)
            {
                WriteImportTable(peStream, importTableRva, importAddressTableRva);
                WriteNameTable(peStream);
                WriteRuntimeStartupStub(peStream, importAddressTableRva);
            }

            // mapped field data:            
            mappedFieldDataWriter.WriteContentTo(peStream);

            // TODO: zero out all bytes:
            int alignedPosition = textSection.PointerToRawData + textSection.SizeOfRawData;
            if (peStream.Position != alignedPosition)
            {
                peStream.Position = alignedPosition - 1;
                peStream.WriteByte(0);
            }
        }
コード例 #59
0
ファイル: PeWriter.cs プロジェクト: noahfalk/roslyn
        private static void WriteSectionHeader(SectionHeader sectionHeader, BlobBuilder writer)
        {
            if (sectionHeader.VirtualSize == 0)
            {
                return;
            }

            for (int j = 0, m = sectionHeader.Name.Length; j < 8; j++)
            {
                if (j < m)
                {
                    writer.WriteByte((byte)sectionHeader.Name[j]);
                }
                else
                {
                    writer.WriteByte(0);
                }
            }

            writer.WriteUInt32((uint)sectionHeader.VirtualSize);
            writer.WriteUInt32((uint)sectionHeader.RelativeVirtualAddress);
            writer.WriteUInt32((uint)sectionHeader.SizeOfRawData);
            writer.WriteUInt32((uint)sectionHeader.PointerToRawData);
            writer.WriteUInt32((uint)sectionHeader.PointerToRelocations);
            writer.WriteUInt32((uint)sectionHeader.PointerToLinenumbers);
            writer.WriteUInt16(sectionHeader.NumberOfRelocations);
            writer.WriteUInt16(sectionHeader.NumberOfLinenumbers);
            writer.WriteUInt32((uint)sectionHeader.Characteristics);
        }
コード例 #60
0
 public String(SectionHeader header, Stream stream)
     : base(header, stream)
 {
     Value = Encoding.UTF8.GetString(stream.ReadBytes((int) header.Size)).TrimNullChars();
 }