/// <summary>Dumps a module to the given stream. The section headers of the pe header get fixed to build a valid pe file.</summary> /// <param name="module">The module to dump.</param> /// <param name="stream">The stream to dump to.</param> public void DumpModule(Module module, Stream stream) { Contract.Requires(module != null); Contract.Requires(stream != null); var data = process.ReadRemoteMemory(module.Start, module.Size.ToInt32()); SimplePeHeader.FixSectionHeaders(data); stream.Write(data, 0, data.Length); }
/// <summary> /// Rewrites the section headers to build a valid pe file. /// </summary> /// <param name="data">The memory of a dumped module.</param> public static void FixSectionHeaders(byte[] data) { var pe = new SimplePeHeader(data); using var ms = new MemoryStream(data); using var bw = new BinaryWriter(ms); for (var i = 0; i < pe.NumberOfSections; ++i) { var offset = pe.SectionOffset(i); bw.Seek(offset + 16, SeekOrigin.Begin); bw.Write(BitConverter.ToUInt32(data, offset + 8)); // SizeOfRawData = VirtualSize bw.Write(BitConverter.ToUInt32(data, offset + 12)); // PointerToRawData = VirtualAddress } }
/// <summary>Dumps a module to the given stream. The section headers of the pe header get fixed to make a valid pe file.</summary> /// <param name="address">The begin of the module.</param> /// <param name="size">The size of the module.</param> /// <param name="stream">The stream to dump to.</param> public void DumpModule(IntPtr address, int size, Stream stream) { Contract.Requires(size >= 0); Contract.Requires(stream != null); var data = process.ReadRemoteMemory(address, size); var pe = new SimplePeHeader(data); // Fix the section headers. using (var bw = new BinaryWriter(new MemoryStream(data))) { for (var i = 0; i < pe.NumberOfSections; ++i) { var offset = pe.SectionOffset(i); bw.Seek(offset + 16, SeekOrigin.Begin); bw.Write(BitConverter.ToUInt32(data, offset + 8)); // SizeOfRawData = VirtualSize bw.Write(BitConverter.ToUInt32(data, offset + 12)); // PointerToRawData = VirtualAddress } } stream.Write(data, 0, data.Length); }