public static ImageCor20HeaderTreeNode Create(HexDocument doc, IPEImage peImage)
 {
     var dnDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
     if (dnDir.VirtualAddress != 0 && dnDir.Size >= 0x48)
         return new ImageCor20HeaderTreeNode(doc, (ulong)peImage.ToFileOffset(dnDir.VirtualAddress));
     return null;
 }
 /// <summary>
 ///     Reads all bytes from the PE image. This may fail if the PE image has been loaded
 ///     by the OS loader since there may be memory holes.
 /// </summary>
 /// <param name="self">this</param>
 /// <returns>All bytes of the PE image</returns>
 public static byte[] GetImageAsByteArray(this IPEImage self)
 {
     using (var reader = self.CreateFullStream())
     {
         return(reader.ReadAllBytes());
     }
 }
 static void DisableMemoryMappedIO(HashSet <string> filenames, IPEImage peImage)
 {
     if (peImage != null && filenames.Contains(peImage.Filename))
     {
         MemoryMappedIOHelper.DisableMemoryMappedIO(peImage);
     }
 }
Exemple #4
0
 static void DisableMemoryMappedIO(HashSet <string> filenames, IPEImage peImage)
 {
     if (peImage != null && filenames.Contains(peImage.FileName))
     {
         peImage.UnsafeDisableMemoryMappedIO();
     }
 }
Exemple #5
0
        /// <summary>
        /// Gets the RVA of the func field that the stub jumps to
        /// </summary>
        /// <param name="reader">Reader, positioned at the stub func</param>
        /// <param name="peImage">PE image</param>
        /// <param name="funcRva">Updated with RVA of func field</param>
        /// <returns></returns>
        public bool TryGetExportedRvaFromStub(IBinaryReader reader, IPEImage peImage, out uint funcRva)
        {
            bool b = TryGetExportedRvaFromStubCore(reader, peImage, out funcRva);

            Debug.Assert(b);
            return(b);
        }
Exemple #6
0
        protected override bool TryGetExportedRvaFromStubCore(ref DataReader reader, IPEImage peImage, out uint funcRva)
        {
            funcRva = 0;

            // 48A1xxxxxxxxxxxxxxxx		movabs	rax,[xxxxxxxxxxxxxxxx]
            // FFE0						jmp		rax
            if (reader.ReadUInt16() != 0xA148)
            {
                return(false);
            }
            ulong absAddr = reader.ReadUInt64();

            if (reader.ReadUInt16() != 0xE0FF)
            {
                return(false);
            }
            ulong rva = absAddr - peImage.ImageNTHeaders.OptionalHeader.ImageBase;

            if (rva > uint.MaxValue)
            {
                return(false);
            }
            funcRva = (uint)rva;
            return(true);
        }
        /// <summary>
        /// Create a <see cref="MetadataBase"/> instance
        /// </summary>
        /// <param name="addr">Address of a .NET file in memory</param>
        /// <returns>A new <see cref="MetadataBase"/> instance</returns>
        internal static MetadataBase Load(IntPtr addr)
        {
            IPEImage peImage = null;

            // We don't know what layout it is. Memory is more common so try that first.
            try {
                return(Load(peImage = new PEImage(addr, ImageLayout.Memory, true)));
            }
            catch {
                if (peImage != null)
                {
                    peImage.Dispose();
                }
                peImage = null;
            }

            try {
                return(Load(peImage = new PEImage(addr, ImageLayout.File, true)));
            }
            catch {
                if (peImage != null)
                {
                    peImage.Dispose();
                }
                throw;
            }
        }
Exemple #8
0
        // Old CS versions
        byte[] UnpackNativeFile1(IPEImage peImage)
        {
            const int dataDirNum   = 6;                 // debug dir
            const int dotNetDirNum = 14;

            var optHeader = peImage.ImageNTHeaders.OptionalHeader;

            if (optHeader.DataDirectories[dataDirNum].VirtualAddress == 0)
            {
                return(null);
            }
            if (optHeader.DataDirectories[dataDirNum].Size != 0x48)
            {
                return(null);
            }

            var  fileData          = peImage.GetImageAsByteArray();
            long dataDirBaseOffset = (long)optHeader.DataDirectories[0].StartOffset;
            int  dataDir           = (int)dataDirBaseOffset + dataDirNum * 8;
            int  dotNetDir         = (int)dataDirBaseOffset + dotNetDirNum * 8;

            WriteUInt32(fileData, dotNetDir, BitConverter.ToUInt32(fileData, dataDir));
            WriteUInt32(fileData, dotNetDir + 4, BitConverter.ToUInt32(fileData, dataDir + 4));
            WriteUInt32(fileData, dataDir, 0);
            WriteUInt32(fileData, dataDir + 4, 0);
            ModuleBytes = fileData;
            return(fileData);
        }
Exemple #9
0
        /// <summary>
        /// Dispose method
        /// </summary>
        /// <param name="disposing"><c>true</c> if called by <see cref="Dispose()"/></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            Dispose(peImage);
            Dispose(stringsStream);
            Dispose(usStream);
            Dispose(blobStream);
            Dispose(guidStream);
            Dispose(tablesStream);
            var as2 = allStreams;

            if (as2 != null)
            {
                foreach (var stream in as2.GetSafeEnumerable())
                {
                    Dispose(stream);
                }
            }
            peImage                   = null;
            cor20Header               = null;
            mdHeader                  = null;
            stringsStream             = null;
            usStream                  = null;
            blobStream                = null;
            guidStream                = null;
            tablesStream              = null;
            allStreams                = null;
            fieldRidToTypeDefRid      = null;
            methodRidToTypeDefRid     = null;
            typeDefRidToNestedClasses = null;
        }
 internal MetadataBase(MetadataHeader mdHeader, bool isStandalonePortablePdb)
 {
     allStreams    = new List <DotNetStream>();
     peImage       = null;
     cor20Header   = null;
     this.mdHeader = mdHeader;
     this.isStandalonePortablePdb = isStandalonePortablePdb;
 }
Exemple #11
0
        void InitializeExeFieldsFrom(IPEImage peImage)
        {
            isExe     = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0;
            timestamp = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;

            using (var mod = ModuleDefMD.Load(peImage))
                version = mod.Assembly?.Version;
        }
Exemple #12
0
 internal MetaData(MetaDataHeader mdHeader, bool isStandalonePortablePdb)
 {
     this.allStreams              = ThreadSafeListCreator.Create <DotNetStream>();
     this.peImage                 = null;
     this.cor20Header             = null;
     this.mdHeader                = mdHeader;
     this.isStandalonePortablePdb = isStandalonePortablePdb;
 }
 internal void InitializeReusedMethodBodies(IPEImage peImage, uint fileOffsetDelta)
 {
     foreach (var info in reusedMethods)
     {
         var offset = peImage.ToFileOffset(info.RVA) + fileOffsetDelta;
         info.MethodBody.SetOffset(offset, info.RVA);
     }
 }
        private static void ReplaceBodyWithNativeCode(IPEImage image, CodeSegment body, bool is32bit)
        {
            // Adjust image flags appropriately.
            image.DotNetDirectory.Flags &= ~DotNetDirectoryFlags.ILOnly;

            if (is32bit)
            {
                image.MachineType            = MachineType.I386;
                image.PEKind                 = OptionalHeaderMagic.Pe32;
                image.DotNetDirectory.Flags |= DotNetDirectoryFlags.Bit32Required;
            }
            else
            {
                image.MachineType = MachineType.Amd64;
                image.PEKind      = OptionalHeaderMagic.Pe32Plus;
            }

            // Access metadata.
            var metadata      = image.DotNetDirectory.Metadata;
            var stringsStream = metadata.GetStream <StringsStream>();
            var tablesStream  = metadata.GetStream <TablesStream>();
            var typeTable     = tablesStream.GetTable <TypeDefinitionRow>();
            var methodTable   = tablesStream.GetTable <MethodDefinitionRow>();

            // Find the method to replace its body of.
            int index = -1;

            for (int i = 0; i < methodTable.Count && index == -1; i++)
            {
                if (stringsStream.GetStringByIndex(methodTable[i].Name) == "GetTheAnswer")
                {
                    index = i;
                }
            }

            // Replace body.
            var methodRow = methodTable[index];

            methodTable[index] = new MethodDefinitionRow(
                new SegmentReference(body),
                methodRow.ImplAttributes | MethodImplAttributes.Native | MethodImplAttributes.Unmanaged
                | MethodImplAttributes.PreserveSig,
                methodRow.Attributes | MethodAttributes.PInvokeImpl,
                methodRow.Name,
                methodRow.Signature,
                methodRow.ParameterList);

            // Move to <Module>
            var typeRow = typeTable[1];

            typeTable[1] = new TypeDefinitionRow(
                typeRow.Attributes,
                typeRow.Name,
                typeRow.Namespace,
                typeRow.Extends,
                typeRow.FieldList,
                (uint)(index + 2));
        }
        /// <summary>
        /// Create a <see cref="MetadataBase"/> instance
        /// </summary>
        /// <param name="peImage">The PE image</param>
        /// <param name="verify"><c>true</c> if we should verify that it's a .NET PE file</param>
        /// <returns>A new <see cref="MetadataBase"/> instance</returns>
        static MetadataBase Create(IPEImage peImage, bool verify)
        {
            MetadataBase md = null;

            try {
                var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
                // Mono doesn't check that the Size field is >= 0x48
                if (dotNetDir.VirtualAddress == 0)
                {
                    throw new BadImageFormatException(".NET data directory RVA is 0");
                }
                var cor20HeaderReader = peImage.CreateReader(dotNetDir.VirtualAddress, 0x48);
                var cor20Header       = new ImageCor20Header(ref cor20HeaderReader, verify);
                if (cor20Header.Metadata.VirtualAddress == 0)
                {
                    throw new BadImageFormatException(".NET metadata RVA is 0");
                }
                var mdRva = cor20Header.Metadata.VirtualAddress;
                // Don't use the size field, Mono ignores it. Create a reader that can read to EOF.
                var mdHeaderReader = peImage.CreateReader(mdRva);
                var mdHeader       = new MetadataHeader(ref mdHeaderReader, verify);
                if (verify)
                {
                    foreach (var sh in mdHeader.StreamHeaders)
                    {
                        if ((ulong)sh.Offset + sh.StreamSize > mdHeaderReader.EndOffset)
                        {
                            throw new BadImageFormatException("Invalid stream header");
                        }
                    }
                }

                switch (GetMetadataType(mdHeader.StreamHeaders))
                {
                case MetadataType.Compressed:
                    md = new CompressedMetadata(peImage, cor20Header, mdHeader);
                    break;

                case MetadataType.ENC:
                    md = new ENCMetadata(peImage, cor20Header, mdHeader);
                    break;

                default:
                    throw new BadImageFormatException("No #~ or #- stream found");
                }
                md.Initialize(null);

                return(md);
            }
            catch {
                if (md != null)
                {
                    md.Dispose();
                }
                throw;
            }
        }
        /// <summary>
        /// Interprets a PE image as a .NET module.
        /// </summary>
        /// <param name="peImage">The image to interpret as a .NET module.</param>
        /// <param name="readerParameters">The parameters to use while reading the module.</param>
        public SerializedModuleDefinition(IPEImage peImage, ModuleReaderParameters readerParameters)
            : base(new MetadataToken(TableIndex.Module, 1))
        {
            if (peImage is null)
            {
                throw new ArgumentNullException(nameof(peImage));
            }
            if (readerParameters is null)
            {
                throw new ArgumentNullException(nameof(readerParameters));
            }

            var metadata = peImage.DotNetDirectory?.Metadata;

            if (metadata is null)
            {
                throw new BadImageFormatException("Input PE image does not contain a .NET metadata directory.");
            }

            var tablesStream = metadata.GetStream <TablesStream>();

            if (tablesStream is null)
            {
                throw new BadImageFormatException(".NET metadata directory does not define a tables stream.");
            }

            var moduleTable = tablesStream.GetTable <ModuleDefinitionRow>(TableIndex.Module);

            if (!moduleTable.TryGetByRid(1, out _row))
            {
                throw new BadImageFormatException("Module definition table does not contain any rows.");
            }

            // Store parameters in fields.
            ReaderContext = new ModuleReaderContext(peImage, this, readerParameters);

            // Copy over PE header fields.
            FilePath            = peImage.FilePath;
            MachineType         = peImage.MachineType;
            FileCharacteristics = peImage.Characteristics;
            PEKind             = peImage.PEKind;
            SubSystem          = peImage.SubSystem;
            DllCharacteristics = peImage.DllCharacteristics;
            TimeDateStamp      = peImage.TimeDateStamp;

            // Copy over "simple" columns.
            Generation = _row.Generation;
            Attributes = peImage.DotNetDirectory.Flags;

            // Initialize member factory.
            _memberFactory = new CachedSerializedMemberFactory(ReaderContext);

            // Find assembly definition and corlib assembly.
            Assembly = FindParentAssembly();
            var corLib = FindMostRecentCorLib();

            if (corLib is {})
Exemple #17
0
        public static uint GetHeadersSize(this IPEImage peImage)
        {
            if (peImage is null)
            {
                throw new ArgumentNullException(nameof(peImage));
            }

            return((uint)peImage.SectionHeaders[peImage.SectionHeaders.Length - 1].FileOffset + IMAGE_SECTION_HEADER.UnmanagedSize);
        }
        private byte[] GetHashToSign(
            Stream imageStream,
            IPEFile file,
            IPEImage image,
            AssemblyHashAlgorithm hashAlgorithm)
        {
            var hashBuilder = new StrongNameDataHashBuilder(imageStream, hashAlgorithm);

            // Include DOS, NT and section headers in the hash.
            hashBuilder.IncludeRange(new OffsetRange(0,
                                                     (uint)(file.DosHeader.GetPhysicalSize()
                                                            + sizeof(uint)
                                                            + file.FileHeader.GetPhysicalSize()
                                                            + file.OptionalHeader.GetPhysicalSize()
                                                            + file.Sections.Count * SectionHeader.SectionHeaderSize)));

            // Include section data.
            foreach (var section in file.Sections)
            {
                hashBuilder.IncludeRange(new OffsetRange(
                                             section.Offset,
                                             section.Offset + section.GetPhysicalSize()));
            }

            // Zero checksum in optional header.
            ulong peChecksumOffset = file.OptionalHeader.Offset + 0x40;

            hashBuilder.ZeroRange(new OffsetRange(peChecksumOffset, peChecksumOffset + sizeof(uint)));

            // Zero certificate directory entry.
            uint optionalHeaderSize = file.OptionalHeader.Magic == OptionalHeaderMagic.Pe32
                ? OptionalHeader.OptionalHeader32SizeExcludingDataDirectories
                : OptionalHeader.OptionalHeader64SizeExcludingDataDirectories;
            ulong certificateEntryOffset = file.OptionalHeader.Offset
                                           + optionalHeaderSize
                                           + (int)DataDirectoryIndex.CertificateDirectory * DataDirectory.DataDirectorySize;

            hashBuilder.ZeroRange(new OffsetRange(certificateEntryOffset, certificateEntryOffset + DataDirectory.DataDirectorySize));

            // Exclude certificate directory contents.
            var certificateDirectory = file.OptionalHeader.GetDataDirectory(DataDirectoryIndex.CertificateDirectory);

            if (certificateDirectory.IsPresentInPE)
            {
                ulong offset = file.RvaToFileOffset(certificateDirectory.VirtualAddress);
                hashBuilder.ExcludeRange(new OffsetRange(offset, offset + certificateDirectory.Size));
            }

            // Exclude strong name directory.
            var strongNameDirectory = image.DotNetDirectory.StrongName;

            hashBuilder.ExcludeRange(new OffsetRange(
                                         strongNameDirectory.Offset,
                                         strongNameDirectory.Offset + strongNameDirectory.GetPhysicalSize()));

            return(hashBuilder.ComputeHash());
        }
Exemple #19
0
        public static uint AlignUpByFile(this IPEImage peImage, uint value)
        {
            if (peImage is null)
            {
                throw new ArgumentNullException(nameof(peImage));
            }

            return(MdlibUtils.AlignUp(value, !peImage.Is64Bit ? peImage.NtHeader.OptionalHeader.RawValue32->FileAlignment : peImage.NtHeader.OptionalHeader.RawValue64->FileAlignment));
        }
        /// <summary>
        /// Initializes MD tables
        /// </summary>
        /// <param name="peImage">The PEImage</param>
        public void Initialize(IPEImage peImage)
        {
            reserved1    = imageStream.ReadUInt32();
            majorVersion = imageStream.ReadByte();
            minorVersion = imageStream.ReadByte();
            flags        = (MDStreamFlags)imageStream.ReadByte();
            log2Rid      = imageStream.ReadByte();
            validMask    = imageStream.ReadUInt64();
            sortedMask   = imageStream.ReadUInt64();

            int maxPresentTables;
            var dnTableSizes = new DotNetTableSizes();
            var tableInfos   = dnTableSizes.CreateTables(majorVersion, minorVersion, out maxPresentTables);

            mdTables = new MDTable[tableInfos.Length];

            ulong valid = validMask;
            var   sizes = new uint[64];

            for (int i = 0; i < 64; valid >>= 1, i++)
            {
                uint rows = (valid & 1) == 0 ? 0 : imageStream.ReadUInt32();
                if (i >= maxPresentTables)
                {
                    rows = 0;
                }
                sizes[i] = rows;
                if (i < mdTables.Length)
                {
                    mdTables[i] = new MDTable((Table)i, rows, tableInfos[i]);
                }
            }

            if (HasExtraData)
            {
                extraData = imageStream.ReadUInt32();
            }

            dnTableSizes.InitializeSizes(HasBigStrings, HasBigGUID, HasBigBlob, sizes);

            var currentRva = peImage.ToRVA(imageStream.FileOffset) + (uint)imageStream.Position;

            foreach (var mdTable in mdTables)
            {
                var dataLen = (long)mdTable.TableInfo.RowSize * (long)mdTable.Rows;
                mdTable.ImageStream = peImage.CreateStream(currentRva, dataLen);
                var newRva = currentRva + (uint)dataLen;
                if (newRva < currentRva)
                {
                    throw new BadImageFormatException("Too big MD table");
                }
                currentRva = newRva;
            }

            InitializeTables();
        }
 /// <summary>
 /// Creates a new managed PE file builder context.
 /// </summary>
 /// <param name="image">The image to build.</param>
 public ManagedPEBuilderContext(IPEImage image)
 {
     ImportDirectory      = new ImportDirectoryBuffer(image.PEKind == OptionalHeaderMagic.Pe32);
     ExportDirectory      = new ExportDirectoryBuffer();
     DotNetSegment        = new DotNetSegmentBuffer(image.DotNetDirectory);
     ResourceDirectory    = new ResourceDirectoryBuffer();
     RelocationsDirectory = new RelocationsDirectoryBuffer();
     FieldRvaDataReader   = new FieldRvaDataReader();
     Bootstrapper         = CreateBootstrapper(image);
 }
Exemple #22
0
        public static ImageCor20HeaderTreeNode Create(HexDocument doc, IPEImage peImage)
        {
            var dnDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];

            if (dnDir.VirtualAddress != 0 && dnDir.Size >= 0x48)
            {
                return(new ImageCor20HeaderTreeNode(doc, (ulong)peImage.ToFileOffset(dnDir.VirtualAddress)));
            }
            return(null);
        }
Exemple #23
0
 static ImageDebugDirectory TryGetEmbeddedDebugDirectory(IPEImage peImage)
 {
     foreach (var idd in peImage.ImageDebugDirectories)
     {
         if (idd.Type == ImageDebugType.EmbeddedPortablePdb)
         {
             return(idd);
         }
     }
     return(null);
 }
Exemple #24
0
        // CS 1.x
        byte[] UnpackNativeFile2(IPEImage peImage)
        {
            var data = peImage.FindWin32ResourceData("ASSEMBLY", 101, 0);

            if (data == null)
            {
                return(null);
            }

            return(ModuleBytes = data.Data.ReadAllBytes());
        }
Exemple #25
0
 public static void ShowRawData(IApp app, IDataModel model, IPEImage image, long begin, long end)
 {
     TreeNavigator.Create()
     .Path <dnModuleModel>(m => m.Module.Image == image ? NavigationState.In : NavigationState.Next)
     .Path <RawDataModel>(m => NavigationState.Done)
     .Handler(node => {
         var targetView = (RawDataView)app.Views.LocateViews(node.Model).Single();
         targetView.Select(begin, end);
     })
     .Goto(model);
 }
            private X86BootstrapperSegment CreateBootstrapper(IPEImage image)
            {
                return(image.MachineType switch
                {
                    MachineType.I386 => new X86BootstrapperSegment(
                        (image.Characteristics & Characteristics.Dll) != 0,
                        (uint)image.ImageBase, ImportDirectory.ImportAddressDirectory),

                    MachineType.Amd64 => null,

                    _ => throw new NotSupportedException($"Machine type {image.MachineType} is not supported.")
                });
Exemple #27
0
        /// <summary>
        /// Updates the fields in the file header of the PE file.
        /// </summary>
        /// <param name="peFile">The (incomplete) PE file to update.</param>
        /// <param name="image">The image that the PE file was based on.</param>
        /// <param name="context">The object containing the intermediate values used during the PE file construction.</param>
        protected virtual void ComputeFileHeaderFields(PEFile peFile, IPEImage image, TContext context)
        {
            var header = peFile.FileHeader;

            header.Machine              = image.MachineType;
            header.NumberOfSections     = (ushort)peFile.Sections.Count;
            header.TimeDateStamp        = (uint)(image.TimeDateStamp - new DateTime(1970, 1, 1)).TotalSeconds;
            header.NumberOfSymbols      = 0;
            header.PointerToSymbolTable = 0;
            header.SizeOfOptionalHeader = (ushort)peFile.OptionalHeader.GetPhysicalSize();
            header.Characteristics      = image.Characteristics;
        }
Exemple #28
0
        protected override bool TryGetExportedRvaFromStubCore(ref DataReader reader, IPEImage peImage, out uint funcRva)
        {
            funcRva = 0;

            // FF25xxxxxxxx		jmp DWORD PTR [xxxxxxxx]
            if (reader.ReadUInt16() != 0x25FF)
            {
                return(false);
            }
            funcRva = reader.ReadUInt32() - (uint)peImage.ImageNTHeaders.OptionalHeader.ImageBase;
            return(true);
        }
Exemple #29
0
 /// <summary>
 /// Dispose method
 /// </summary>
 /// <param name="disposing"><c>true</c> if called by <see cref="Dispose()"/></param>
 protected virtual void Dispose(bool disposing)
 {
     if (!disposing)
     {
         return;
     }
     if (peImage != null)
     {
         peImage.Dispose();
     }
     if (stringsStream != null)
     {
         stringsStream.Dispose();
     }
     if (usStream != null)
     {
         usStream.Dispose();
     }
     if (blobStream != null)
     {
         blobStream.Dispose();
     }
     if (guidStream != null)
     {
         guidStream.Dispose();
     }
     if (tablesStream != null)
     {
         tablesStream.Dispose();
     }
     if (allStreams != null)
     {
         foreach (var stream in allStreams)
         {
             if (stream != null)
             {
                 stream.Dispose();
             }
         }
     }
     peImage                   = null;
     cor20Header               = null;
     mdHeader                  = null;
     stringsStream             = null;
     usStream                  = null;
     blobStream                = null;
     guidStream                = null;
     tablesStream              = null;
     allStreams                = null;
     fieldRidToTypeDefRid      = null;
     methodRidToTypeDefRid     = null;
     typeDefRidToNestedClasses = null;
 }
Exemple #30
0
        private static CodeSegment GetNewCodeSegment(IPEImage image)
        {
            var methodTable = image.DotNetDirectory.Metadata
                              .GetStream <TablesStream>()
                              .GetTable <MethodDefinitionRow>(TableIndex.Method);
            var row = methodTable.First(r => (r.ImplAttributes & MethodImplAttributes.Native) != 0);

            Assert.True(row.Body.IsBounded);
            var segment = Assert.IsAssignableFrom <CodeSegment>(row.Body.GetSegment());

            return(segment);
        }
 public static ImageSectionHeader ToImageSectionHeader(this IPEImage image, RVA rva)
 {
     foreach (var section in image.ImageSectionHeaders)
     {
         if (rva >= section.VirtualAddress &&
             rva < section.VirtualAddress + Math.Max(section.VirtualSize, section.SizeOfRawData))
         {
             return(section);
         }
     }
     return(null);
 }
Exemple #32
0
 /// <summary>
 /// Creates a <see cref="ModuleDefMD"/> instance
 /// </summary>
 /// <param name="peImage">PE image</param>
 /// <returns>A new <see cref="ModuleDefMD"/> instance</returns>
 public static ModuleDefMD Load(IPEImage peImage)
 {
     return Load(MetaDataCreator.Load(peImage), (ModuleCreationOptions)null);
 }
Exemple #33
0
 public LoadedFile(IPEImage peImage, ModuleDef module)
 {
     this.PEImage = peImage;
     this.ModuleDef = module;
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="peImage">The PE image</param>
		/// <param name="rsrcReader">Reader for the whole Win32 resources section (usually
		/// the .rsrc section) or <c>null</c> if we should create one from the resource data
		/// directory in the optional header. This instance owns the reader.</param>
		public Win32ResourcesPE(IPEImage peImage, IBinaryReader rsrcReader) {
			this.rvaConverter = peImage;
			this.dataReader = peImage.CreateFullStream();
			if (rsrcReader != null)
				this.rsrcReader = rsrcReader;
			else {
				var dataDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[2];
				if (dataDir.VirtualAddress != 0 && dataDir.Size != 0)
					this.rsrcReader = peImage.CreateStream(dataDir.VirtualAddress, dataDir.Size);
				else
					this.rsrcReader = MemoryImageStream.CreateEmpty();
			}
			Initialize();
		}
Exemple #35
0
		void InitializeExeFieldsFrom(IPEImage peImage) {
			isExe = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0;
			timestamp = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;

			using (var mod = ModuleDefMD.Load(peImage)) {
				var asm = mod.Assembly;
				version = asm == null ? null : asm.Version;
			}
		}
		// Old CS versions
		byte[] UnpackNativeFile1(IPEImage peImage) {
			const int dataDirNum = 6;	// debug dir
			const int dotNetDirNum = 14;

			var optHeader = peImage.ImageNTHeaders.OptionalHeader;
			if (optHeader.DataDirectories[dataDirNum].VirtualAddress == 0)
				return null;
			if (optHeader.DataDirectories[dataDirNum].Size != 0x48)
				return null;

			var fileData = peImage.GetImageAsByteArray();
			long dataDirBaseOffset = (long)optHeader.DataDirectories[0].StartOffset;
			int dataDir = (int)dataDirBaseOffset + dataDirNum * 8;
			int dotNetDir = (int)dataDirBaseOffset + dotNetDirNum * 8;
			WriteUInt32(fileData, dotNetDir, BitConverter.ToUInt32(fileData, dataDir));
			WriteUInt32(fileData, dotNetDir + 4, BitConverter.ToUInt32(fileData, dataDir + 4));
			WriteUInt32(fileData, dataDir, 0);
			WriteUInt32(fileData, dataDir + 4, 0);
			ModuleBytes = fileData;
			return fileData;
		}
Exemple #37
0
		/// <inheritdoc/>
		public CompressedMetaData(IPEImage peImage, ImageCor20Header cor20Header, MetaDataHeader mdHeader)
			: base(peImage, cor20Header, mdHeader) {
		}
Exemple #38
0
 /// <summary>
 /// Dispose method
 /// </summary>
 /// <param name="disposing"><c>true</c> if called by <see cref="Dispose()"/></param>
 protected virtual void Dispose(bool disposing)
 {
     if (!disposing)
         return;
     Dispose(peImage);
     Dispose(stringsStream);
     Dispose(usStream);
     Dispose(blobStream);
     Dispose(guidStream);
     Dispose(tablesStream);
     var as2 = allStreams;
     if (as2 != null) {
         foreach (var stream in as2.GetSafeEnumerable())
             Dispose(stream);
     }
     peImage = null;
     cor20Header = null;
     mdHeader = null;
     stringsStream = null;
     usStream = null;
     blobStream = null;
     guidStream = null;
     tablesStream = null;
     allStreams = null;
     fieldRidToTypeDefRid = null;
     methodRidToTypeDefRid = null;
     typeDefRidToNestedClasses = null;
 }
Exemple #39
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="peImage">The PE image</param>
 /// <param name="cor20Header">The .NET header</param>
 /// <param name="mdHeader">The MD header</param>
 protected MetaData(IPEImage peImage, ImageCor20Header cor20Header, MetaDataHeader mdHeader)
 {
     try {
         this.allStreams = ThreadSafeListCreator.Create<DotNetStream>();
         this.peImage = peImage;
         this.cor20Header = cor20Header;
         this.mdHeader = mdHeader;
     }
     catch {
         if (peImage != null)
             peImage.Dispose();
         throw;
     }
 }
		/// <summary>
		/// Initializes MD tables
		/// </summary>
		/// <param name="peImage">The PEImage</param>
		public void Initialize(IPEImage peImage) {
			if (initialized)
				throw new Exception("Initialize() has already been called");
			initialized = true;

			reserved1 = imageStream.ReadUInt32();
			majorVersion = imageStream.ReadByte();
			minorVersion = imageStream.ReadByte();
			flags = (MDStreamFlags)imageStream.ReadByte();
			log2Rid = imageStream.ReadByte();
			validMask = imageStream.ReadUInt64();
			sortedMask = imageStream.ReadUInt64();

			int maxPresentTables;
			var dnTableSizes = new DotNetTableSizes();
			var tableInfos = dnTableSizes.CreateTables(majorVersion, minorVersion, out maxPresentTables);
			mdTables = new MDTable[tableInfos.Length];

			ulong valid = validMask;
			var sizes = new uint[64];
			for (int i = 0; i < 64; valid >>= 1, i++) {
				uint rows = (valid & 1) == 0 ? 0 : imageStream.ReadUInt32();
				if (i >= maxPresentTables)
					rows = 0;
				sizes[i] = rows;
				if (i < mdTables.Length)
					mdTables[i] = new MDTable((Table)i, rows, tableInfos[i]);
			}

			if (HasExtraData)
				extraData = imageStream.ReadUInt32();

			dnTableSizes.InitializeSizes(HasBigStrings, HasBigGUID, HasBigBlob, sizes);

			var currentRva = peImage.ToRVA(imageStream.FileOffset) + (uint)imageStream.Position;
			foreach (var mdTable in mdTables) {
				var dataLen = (long)mdTable.TableInfo.RowSize * (long)mdTable.Rows;
				mdTable.ImageStream = peImage.CreateStream(currentRva, dataLen);
				var newRva = currentRva + (uint)dataLen;
				if (newRva < currentRva)
					throw new BadImageFormatException("Too big MD table");
				currentRva = newRva;
			}

			InitializeTables();
		}
		public ImageReference GetImageReference(IPEImage peImage) {
			return GetImageReference(peImage.ImageNTHeaders.FileHeader.Characteristics);
		}
		public override byte[] UnpackNativeFile(IPEImage peImage) {
			var data = new NativeImageUnpacker(peImage).Unpack();
			if (data == null)
				return null;

			unpackedNativeFile = true;
			ModuleBytes = data;
			return data;
		}
Exemple #43
0
 /// <summary>
 /// Creates a <see cref="ModuleDefMD"/> instance
 /// </summary>
 /// <param name="peImage">PE image</param>
 /// <param name="context">Module context or <c>null</c></param>
 /// <returns>A new <see cref="ModuleDefMD"/> instance</returns>
 public static ModuleDefMD Load(IPEImage peImage, ModuleContext context)
 {
     return Load(MetaDataCreator.Load(peImage), new ModuleCreationOptions(context));
 }
Exemple #44
0
		static void DisableMemoryMappedIO(HashSet<string> filenames, IPEImage peImage) {
			if (peImage != null && filenames.Contains(peImage.FileName))
				peImage.UnsafeDisableMemoryMappedIO();
		}
Exemple #45
0
 /// <summary>
 /// Creates a <see cref="ModuleDefMD"/> instance
 /// </summary>
 /// <param name="peImage">PE image</param>
 /// <param name="options">Module creation options or <c>null</c></param>
 /// <returns>A new <see cref="ModuleDefMD"/> instance</returns>
 public static ModuleDefMD Load(IPEImage peImage, ModuleCreationOptions options)
 {
     return Load(MetaDataCreator.Load(peImage), options);
 }
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="peImage">The PE image</param>
		/// <param name="verify"><c>true</c> if we should verify that it's a .NET PE file</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(IPEImage peImage, bool verify) {
			IImageStream cor20HeaderStream = null, mdHeaderStream = null;
			MetaData md = null;
			try {
				var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
				if (dotNetDir.VirtualAddress == 0)
					throw new BadImageFormatException(".NET data directory RVA is 0");
				if (dotNetDir.Size < 0x48)
					throw new BadImageFormatException(".NET data directory size < 0x48");
				var cor20Header = new ImageCor20Header(cor20HeaderStream = peImage.CreateStream(dotNetDir.VirtualAddress, 0x48), verify);
				if (cor20Header.MetaData.VirtualAddress == 0)
					throw new BadImageFormatException(".NET MetaData RVA is 0");
				if (cor20Header.MetaData.Size < 16)
					throw new BadImageFormatException(".NET MetaData size is too small");
				var mdSize = cor20Header.MetaData.Size;
				var mdRva = cor20Header.MetaData.VirtualAddress;
				var mdHeader = new MetaDataHeader(mdHeaderStream = peImage.CreateStream(mdRva, mdSize), verify);
				if (verify) {
					foreach (var sh in mdHeader.StreamHeaders) {
						if (sh.Offset + sh.StreamSize < sh.Offset || sh.Offset + sh.StreamSize > mdSize)
							throw new BadImageFormatException("Invalid stream header");
					}
				}

				switch (GetMetaDataType(mdHeader.StreamHeaders)) {
				case MetaDataType.Compressed:
					md = new CompressedMetaData(peImage, cor20Header, mdHeader);
					break;

				case MetaDataType.ENC:
					md = new ENCMetaData(peImage, cor20Header, mdHeader);
					break;

				default:
					throw new BadImageFormatException("No #~ or #- stream found");
				}
				md.Initialize();

				return new DotNetFile(md);
			}
			catch {
				if (md != null)
					md.Dispose();
				throw;
			}
			finally {
				if (cor20HeaderStream != null)
					cor20HeaderStream.Dispose();
				if (mdHeaderStream != null)
					mdHeaderStream.Dispose();
			}
		}
		public override byte[] UnpackNativeFile(IPEImage peImage) {
			return UnpackNativeFile1(peImage) ?? UnpackNativeFile2(peImage);
		}
Exemple #48
0
		void Initialize(IPEImage peImage) {
			this.peImage = peImage;
			this.peStream = peImage.CreateFullStream();
		}
		// CS 1.x
		byte[] UnpackNativeFile2(IPEImage peImage) {
			var data = peImage.FindWin32ResourceData("ASSEMBLY", 101, 0);
			if (data == null)
				return null;

			return ModuleBytes = data.Data.ReadAllBytes();
		}
Exemple #50
0
		public PECLIModel(IPEImage image, ImageCor20Header header) {
			Image = image;
			CLIHeader = header;
		}
Exemple #51
0
		public void Dispose() {
			if (ownPeImage) {
				if (metaData != null)
					metaData.Dispose();
				if (peImage != null)
					peImage.Dispose();
			}
			if (peStream != null)
				peStream.Dispose();

			metaData = null;
			peImage = null;
			peStream = null;
		}
Exemple #52
0
		public AsmEdHexDocument GetOrCreate(IPEImage peImage) {
			var filename = GetFullPath(peImage.FileName);

			lock (lockObj) {
				var doc = TryGet_NoLock(filename);
				if (doc != null)
					return doc;

				using (var stream = peImage.CreateFullStream()) {
					var data = stream.ReadAllBytes();
					doc = new AsmEdHexDocument(data, filename);
					filenameToDoc[filename] = new WeakReference(doc);
					return doc;
				}
			}
		}
Exemple #53
0
 static bool IsExe(IPEImage peImage)
 {
     return peImage != null && (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0;
 }
 public NativeImageUnpacker(IPEImage peImage)
 {
     this.peImage = new MyPEImage(peImage);
 }
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="peImage">The PE image</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(IPEImage peImage) {
			return Load(peImage, true);
		}
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="module">The module</param>
		/// <param name="options">Options or <c>null</c></param>
		public NativeModuleWriter(ModuleDefMD module, NativeModuleWriterOptions options) {
			this.module = module;
			this.options = options;
			this.peImage = module.MetaData.PEImage;
		}
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="peImage">The PE image</param>
		public Win32ResourcesPE(IPEImage peImage)
			: this(peImage, null) {
		}
Exemple #58
0
		public MyPEImage(IPEImage peImage) {
			Initialize(peImage);
		}
		public ApplicationModeUnpacker(IPEImage peImage) {
			this.peImage = peImage;
		}
Exemple #60
0
		public override byte[] UnpackNativeFile(IPEImage peImage) {
			var unpacker = new ApplicationModeUnpacker(peImage);
			var data = unpacker.Unpack();
			if (data == null)
				return null;

			unpackedFiles.AddRange(unpacker.EmbeddedAssemblies);
			unpackedNativeFile = true;
			ModuleBytes = data;
			return data;
		}