コード例 #1
0
 public static ModuleDefMD OpenModule(string filename)
 {
     var ctx = ModuleDefMD.CreateModuleContext();
     var peImage = new PEImage(File.ReadAllBytes(filename), filename);
     var mod = ModuleDefMD.Load(peImage, ctx);
     ctx.AssemblyResolver.AddToCache(mod);
     return mod;
 }
コード例 #2
0
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="fileName">The file to load</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(string fileName) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(fileName));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #3
0
ファイル: MetaDataCreator.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="data">The .NET file data</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(byte[] data) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(data));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #4
0
ファイル: MetaDataCreator.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="fileName">The file to load</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(string fileName) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(fileName));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #5
0
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="data">The .NET file data</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(byte[] data) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(data));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #6
0
ファイル: ECallManager.cs プロジェクト: lovebanyi/dnSpy
 public ECallListReader(string filename)
 {
     this.peImage = new PEImage(filename);
     this.reader = peImage.CreateFullStream();
     this.is32bit = peImage.ImageNTHeaders.OptionalHeader.Magic == 0x010B;
     this.ptrSize = is32bit ? 4U : 8;
     var last = peImage.ImageSectionHeaders[peImage.ImageSectionHeaders.Count - 1];
     this.endRva = (uint)last.VirtualAddress + last.VirtualSize;
     this.list = new List<ECClass>();
     this.tableFormat = null;
     Read();
 }
コード例 #7
0
ファイル: dnModule.cs プロジェクト: mamingxiu/dnExplorer
		public dnModule(byte[] module, string fileName, ModuleContext ctx) {
			RawData = module;
			ErrorMessage = null;
			Name = Path.GetFileName(fileName);

			var creator = new dnModuleStreamCreator(module, fileName);
			try {
				Image = new PEImage(creator, ImageLayout.File, true);
			}
			catch (Exception ex) {
				ErrorMessage += string.Format("Error while loading PE Image:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				Image = null;
				return;
			}

			try {
				MetaData = MetaDataCreator.CreateMetaData(Image);
			}
			catch (Exception ex) {
				ErrorMessage += string.Format("Error while loading MetaData:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				MetaData = null;
				return;
			}

			try {
				ModuleDef = (ModuleDefMD)loadInternal.Invoke(null, new object[] {
					MetaData, new ModuleCreationOptions {
						TryToLoadPdbFromDisk = true,
						Context = ctx
					}
				});
				ModuleDef.EnableTypeDefFindCache = true;
			}
			catch (Exception ex) {
				ErrorMessage = string.Format("Error while loading ModuleDef:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				ModuleDef = null;
				return;
			}

			if (ModuleDef.Assembly != null)
				Name = ModuleDef.Assembly.Name;
			else
				Name = ModuleDef.Name;
			if (string.IsNullOrEmpty(Name))
				Name = Path.GetFileName(fileName);
		}
コード例 #8
0
        public frmSecView(dnlib.PE.PEImage myPe, string peFileName)
        {
            //Debug.WriteLine("[frmSecView]");
            log.Log(LogType.Normal, "frmSecView");

            this.is64 = myPe.ImageNTHeaders.FileHeader.Machine == Machine.AMD64 |
                        myPe.ImageNTHeaders.FileHeader.Machine == Machine.IA64;

            this.InitializeComponent();
            this.myPeFileName = peFileName;
            foreach (var a in myPe.ImageSectionHeaders)
            {
                this.reaperListView1.Items.Add(new ListViewItem(new[] { Encoding.ASCII.GetString(a.Name), ((uint)a.VirtualAddress).ToString("X8"), ((uint)a.VirtualSize).ToString("X8"), ((uint)myPe.ToFileOffset(a.VirtualAddress)).ToString("X8"), (a.SizeOfRawData).ToString("X8"), (a.Characteristics).ToString("X8") }));
            }
        }
コード例 #9
0
ファイル: MetaDataCreator.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData 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;
			}
		}
コード例 #10
0
ファイル: BreakProcessHelper.cs プロジェクト: lovebanyi/dnSpy
        static uint GetEntryPointToken(string filename, out string otherModuleName)
        {
            otherModuleName = null;
            IImageStream cor20HeaderStream = null;
            try {
                using (var peImage = new PEImage(filename)) {
                    var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
                    if (dotNetDir.VirtualAddress == 0)
                        return 0;
                    if (dotNetDir.Size < 0x48)
                        return 0;
                    var cor20Header = new ImageCor20Header(cor20HeaderStream = peImage.CreateStream(dotNetDir.VirtualAddress, 0x48), true);
                    if ((cor20Header.Flags & ComImageFlags.NativeEntryPoint) != 0)
                        return 0;
                    uint token = cor20Header.EntryPointToken_or_RVA;
                    if ((Table)(token >> 24) != Table.File)
                        return token;

                    using (var mod = ModuleDefMD.Load(peImage)) {
                        var file = mod.ResolveFile(token & 0x00FFFFFF);
                        if (file == null || !file.ContainsMetaData)
                            return 0;

                        otherModuleName = file.Name;
                        return token;
                    }
                }
            }
            catch {
            }
            finally {
                if (cor20HeaderStream != null)
                    cor20HeaderStream.Dispose();
            }
            return 0;
        }
コード例 #11
0
			uint GetRuntimeTimeStamp() {
				string path = module.Location;
				if (string.IsNullOrEmpty(path))
					return 0;

				try {
					var rtNames = new List<string>();
					foreach (var rtModRef in mainType.RuntimeModuleRefs) {
						string dllName = rtModRef.Name;
						if (!dllName.ToUpperInvariant().EndsWith(".DLL"))
							dllName += ".dll";
						rtNames.Add(dllName);
					}
					if (rtNames.Count == 0)
						return 0;

					for (var di = new DirectoryInfo(Path.GetDirectoryName(path)); di != null; di = di.Parent) {
						foreach (var dllName in rtNames) {
							try {
								using (var peImage = new PEImage(Path.Combine(di.FullName, dllName))) {
									if (peImage.ImageNTHeaders.FileHeader.Machine == Machine.I386)
										return peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
								}
							}
							catch {
							}
						}
					}
				}
				catch {
				}

				return 0;
			}
コード例 #12
0
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <param name="imageLayout">Image layout of the file in memory</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(IntPtr addr, ImageLayout imageLayout) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(addr, imageLayout, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #13
0
ファイル: MetaDataCreator.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <param name="imageLayout">Image layout of the file in memory</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(IntPtr addr, ImageLayout imageLayout) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(addr, imageLayout, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
コード例 #14
0
ファイル: ObfuscatedFile.cs プロジェクト: GodLesZ/de4dot
		bool UnpackNativeImage(IEnumerable<IDeobfuscator> deobfuscators) {
			using (var peImage = new PEImage(Filename)) {
				foreach (var deob in deobfuscators) {
					byte[] unpackedData = null;
					try {
						unpackedData = deob.UnpackNativeFile(peImage);
					}
					catch {
					}
					if (unpackedData == null)
						continue;

					var oldModule = module;
					try {
						module = assemblyModule.Load(unpackedData);
					}
					catch {
						Logger.w("Could not load unpacked data. File: {0}, deobfuscator: {0}", peImage.FileName ?? "(unknown filename)", deob.TypeLong);
						continue;
					}
					finally {
						if (oldModule != null)
							oldModule.Dispose();
					}
					this.deob = deob;
					return true;
				}
			}

			return false;
		}
コード例 #15
0
ファイル: PEFilesSaver.cs プロジェクト: arkanoid1/dnSpy
		// Very simple, will probably fail if various fields have been overwritten with invalid values
		void WritePEFile(byte[] raw, byte[] dst, int rawSize, out int finalSize) {
			progress.ThrowIfCancellationRequested();
			for (int i = 0; i < rawSize; i++)
				dst[i] = 0;
			try {
				var peImage = new PEImage(raw, ImageLayout.Memory, true);
				int offset = 0;
				Array.Copy(raw, 0, dst, 0, (int)peImage.ImageNTHeaders.OptionalHeader.SizeOfHeaders);
				offset += (int)peImage.ImageNTHeaders.OptionalHeader.SizeOfHeaders;

				foreach (var sect in peImage.ImageSectionHeaders)
					Array.Copy(raw, (int)sect.VirtualAddress, dst, (int)sect.PointerToRawData, (int)sect.SizeOfRawData);

				var lastSect = peImage.ImageSectionHeaders[peImage.ImageSectionHeaders.Count - 1];
				var fa = peImage.ImageNTHeaders.OptionalHeader.FileAlignment;
				finalSize = (int)((lastSect.PointerToRawData + lastSect.SizeOfRawData + fa - 1) & ~(fa - 1));
			}
			catch {
				finalSize = rawSize;
				Array.Copy(raw, dst, rawSize);
			}
		}
コード例 #16
0
ファイル: CorModuleDefHelper.cs プロジェクト: lovebanyi/dnSpy
        ImageSectionHeader[] GetOrCreateSectionHeaders()
        {
            var h = sectionHeaders;
            if (h != null)
                return h;

            try {
                ulong addr = module.Address;
                if (addr == 0)
                    return sectionHeaders = new ImageSectionHeader[0];
                var data = new byte[0x1000];
                int sizeRead;
                this.module.Process.CorProcess.ReadMemory(this.module.Address, data, 0, data.Length, out sizeRead);
                using (var peImage = new PEImage(data, !module.IsDynamic && module.IsInMemory ? ImageLayout.File : ImageLayout.Memory, true))
                    return sectionHeaders = peImage.ImageSectionHeaders.ToArray();
            }
            catch {
                Debug.Fail("Couldn't read section headers");
            }
            return sectionHeaders = new ImageSectionHeader[0];
        }
コード例 #17
0
		public static MemoryModuleDefFile Create(DnModule dnModule, bool loadSyms) {
			Debug.Assert(!dnModule.IsDynamic);
			Debug.Assert(dnModule.Address != 0);
			ulong address = dnModule.Address;
			var process = dnModule.Process;
			var data = new byte[dnModule.Size];
			string location = dnModule.IsInMemory ? string.Empty : dnModule.Name;

			ProcessMemoryUtils.ReadMemory(process, address, data, 0, data.Length);

			var peImage = new PEImage(data, GetImageLayout(dnModule), true);
			var module = ModuleDefMD.Load(peImage);
			module.Location = location;
			bool autoUpdateMemory = false;//TODO: Init to default value
			if (GacInfo.IsGacPath(dnModule.Name))
				autoUpdateMemory = false;	// GAC files are not likely to decrypt methods in memory
			return new MemoryModuleDefFile(process, address, data, dnModule.IsInMemory, module, loadSyms, autoUpdateMemory);
		}
コード例 #18
0
ファイル: ModuleVM.cs プロジェクト: arkanoid1/dnSpy
		void InitializeExeFields() {
			if (exeFieldsInitialized)
				return;
			exeFieldsInitialized = true;

			isExe = false;
			timestamp = null;
			version = null;

			if (!module.IsDynamic && module.IsInMemory) {
				var bytes = module.Process.CorProcess.ReadMemory(module.Address, (int)module.Size);
				if (bytes != null) {
					try {
						using (var peImage = new PEImage(bytes))
							InitializeExeFieldsFrom(peImage);
					}
					catch {
					}
				}
			}
			else if (module.IsDynamic || module.IsInMemory) {
				if (module.CorModule.IsManifestModule)
					version = new AssemblyNameInfo(module.Assembly.FullName).Version;
			}
			else {
				try {
					using (var peImage = new PEImage(module.Name))
						InitializeExeFieldsFrom(peImage);
				}
				catch {
				}
			}
		}
コード例 #19
0
ファイル: ModuleVM.cs プロジェクト: andyhebear/dnSpy
        void InitializeExeFields()
        {
            if (exeFieldsInitialized)
                return;
            exeFieldsInitialized = true;

            isExe = false;
            timestamp = null;
            version = null;

            if (!module.IsDynamic && module.IsInMemory) {
                var bytes = module.Process.CorProcess.ReadMemory(module.Address, (int)module.Size);
                if (bytes != null) {
                    try {
                        using (var peImage = new PEImage(bytes))
                            InitializeExeFieldsFrom(peImage);
                    }
                    catch {
                    }
                }
            }
            else if (module.IsDynamic || module.IsInMemory) {
                //TODO: Support dynamic modules
            }
            else {
                try {
                    using (var peImage = new PEImage(module.Name))
                        InitializeExeFieldsFrom(peImage);
                }
                catch {
                }
            }
        }
コード例 #20
0
ファイル: DebuggerModule.cs プロジェクト: GreenDamTan/dnSpy
		PEState CreatePEState() {
			try {
				ulong addr = Address;
				if (addr == 0)
					return PEState.Null;
				var data = new byte[0x1000];
				debugger.Read(Address, data, 0, data.Length);
				using (var peImage = new PEImage(data, IsFileLayout ? ImageLayout.File : ImageLayout.Memory, true))
					return new PEState(peImage.ImageSectionHeaders.ToArray());
			}
			catch {
				Debug.Fail("Couldn't read section headers");
				return PEState.Null;
			}
		}
コード例 #21
0
ファイル: LoadedAssembly.cs プロジェクト: rhowlerose/dnSpy
        LoadedFile LoadAssembly(object state)
        {
            IPEImage peImage;

            if (OtherSettings.Instance.UseMemoryMappedIO)
                peImage = new PEImage(fileName);
            else
                peImage = new PEImage(File.ReadAllBytes(fileName));

            var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
            bool isDotNet = dotNetDir.VirtualAddress != 0 && dotNetDir.Size >= 0x48;

            if (isDotNet) {
                try {
                    ModuleDef module;
                    var opts = new ModuleCreationOptions(CreateModuleContext());
                    if (OtherSettings.Instance.UseMemoryMappedIO)
                        module = ModuleDefMD.Load(peImage, opts);
                    else
                        module = ModuleDefMD.Load(peImage, opts);
                    return InitializeModule(module);
                }
                catch {
                }
            }

            return new LoadedFile(peImage, null);
        }