public PeFile Parse(IEnumerable <byte> bytes) { if (bytes.Count() < 336) { throw new ArgumentException("the size is not correct. At least > to 336"); } var result = new PeFile { MsDosHeader = MsDosHeader.Parse(bytes), MsDosStub = ParseMsdosStub(bytes), PeSignature = ParsePeSignature(bytes), CoffHeader = CoffHeader.Parse(bytes) }; if (result.CoffHeader.SizeOfOptionalHeader > 0) { result.PeHeader = PeHeader.Parse(bytes, result.CoffHeader.SizeOfOptionalHeader); } return(result); }
internal static PeHeader Parse(IEnumerable <byte> peBytes, short size) { var peHeaderBytes = peBytes.Skip(152).Take(size); var bMagic = BitConverter.ToInt16(new[] { peHeaderBytes.ElementAt(0), peHeaderBytes.ElementAt(1) }, 0); MagicNumbers magic; if (!EnumHelper.TryGetValue(bMagic, out magic)) { throw new ArgumentException(string.Format("the magic {0} is not supproted", bMagic)); } var majorLinkerVersion = peHeaderBytes.ElementAt(2); var minorLinkerVersion = peHeaderBytes.ElementAt(3); var sizeOfCode = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(4), peHeaderBytes.ElementAt(5), peHeaderBytes.ElementAt(6), peHeaderBytes.ElementAt(7) }, 0); var sizeOfInitializedData = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(8), peHeaderBytes.ElementAt(9), peHeaderBytes.ElementAt(10), peHeaderBytes.ElementAt(11) }, 0); var sizeOfUnitalizedData = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(12), peHeaderBytes.ElementAt(13), peHeaderBytes.ElementAt(14), peHeaderBytes.ElementAt(15) }, 0); var addressOfEntryPoint = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(16), peHeaderBytes.ElementAt(17), peHeaderBytes.ElementAt(18), peHeaderBytes.ElementAt(19) }, 0); var baseOfCode = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(20), peHeaderBytes.ElementAt(21), peHeaderBytes.ElementAt(22), peHeaderBytes.ElementAt(23) }, 0); var result = new PeHeader { Magic = magic, MajorLinkerVersion = majorLinkerVersion, MinorLinkerVersion = minorLinkerVersion, SizeOfCode = sizeOfCode, SizeOfInitializedData = sizeOfInitializedData, SizeOfUnitializedData = sizeOfUnitalizedData, AddressOfEntryPoint = addressOfEntryPoint, BaseOfCode = baseOfCode }; if (magic == MagicNumbers.PE32) { var baseOfData = BitConverter.ToInt32(new[] { peHeaderBytes.ElementAt(24), peHeaderBytes.ElementAt(25), peHeaderBytes.ElementAt(26), peHeaderBytes.ElementAt(27) }, 0); result.BaseOfData = baseOfData; } return(result); }