/// <summary> /// Reads elf header /// </summary> /// <param name="reader">The reader.</param> public void Read32(EndianAwareBinaryReader reader) { Ident = reader.ReadBytes(16); // Check for magic number if (Ident[0] != MagicNumber[0] || Ident[1] != MagicNumber[1] || Ident[2] != MagicNumber[2] || Ident[3] != MagicNumber[3]) { // Magic number not present, so it seems to be an invalid ELF file throw new NotSupportedException("This is not a valid ELF file"); } Type = (FileType)reader.ReadUInt16(); Machine = (MachineType)reader.ReadUInt16(); Version = (Version)reader.ReadUInt32(); EntryAddress = reader.ReadUInt32(); ProgramHeaderOffset = reader.ReadUInt32(); SectionHeaderOffset = reader.ReadUInt32(); Flags = reader.ReadUInt32(); //ElfHeaderSize = reader.ReadUInt16(); //ProgramHeaderEntrySize = reader.ReadUInt16(); ProgramHeaderNumber = reader.ReadUInt16(); //SectionHeaderEntrySize = reader.ReadUInt16(); SectionHeaderNumber = reader.ReadUInt16(); SectionHeaderStringIndex = reader.ReadUInt16(); }
internal void Read(EndianAwareBinaryReader reader) { this.majorVersion = reader.ReadUInt16(); this.minorVersion = reader.ReadUInt16(); this.buildNumber = reader.ReadUInt16(); this.revision = reader.ReadUInt16(); }
internal void Read(EndianAwareBinaryReader reader) { this.signature = reader.ReadUInt32(); if (signature != peSignature) { throw new BadImageFormatException(); } this.machine = (PEImageMachine)reader.ReadUInt16(); this.sectionCount = reader.ReadUInt16(); this.secondsElapsedSinceEpoc = reader.ReadUInt32(); this.symbolTableRVAndSize.Read(reader); this.optionalHeaderSize = reader.ReadUInt16(); this.characteristics = (CoffStandardCharacteristics)reader.ReadUInt16(); }
// FIXME: public byte[] ImageHash; #endregion Data members #region Methods /// <summary> /// Loads the CLI_HEADER from the reader. /// </summary> /// <param name="reader">The reader.</param> public void Read(EndianAwareBinaryReader reader) { Cb = reader.ReadUInt32(); MajorRuntimeVersion = reader.ReadUInt16(); MinorRuntimeVersion = reader.ReadUInt16(); Metadata.Read(reader); Flags = (RuntimeImageFlags)reader.ReadUInt32(); EntryPointToken = reader.ReadUInt32(); Resources.Read(reader); StrongNameSignature.Read(reader); CodeManagerTable.Read(reader); VTableFixups.Read(reader); ExportAddressTableJumps.Read(reader); ManagedNativeHeader.Read(reader); }
internal void Read(EndianAwareBinaryReader reader) { this.imageKind = (PEImageKind)reader.ReadUInt16(); this.lMajor = reader.ReadByte(); this.lMinor = reader.ReadByte(); this.codeSize = reader.ReadUInt32(); this.initializedDataSize = reader.ReadUInt32(); this.uninitializedDataSize = reader.ReadUInt32(); this.entryPointRVA = reader.ReadUInt32(); this.baseOfCode = reader.ReadUInt32(); switch (this.imageKind) { case PEImageKind.x86Image: this.baseOfData = reader.ReadUInt32(); break; case PEImageKind.x64Image: break; case PEImageKind.RomImage: throw new NotImplementedException(); default: throw new BadImageFormatException(); } }
internal static CoffSection Read(EndianAwareBinaryReader reader, bool keepImageOpen) { byte[] name = new byte[sizeOfName]; reader.Read(name, 0, sizeOfName); var actualName = GetNameFor(name); CoffSection result; switch (actualName) { case ".reloc": result = new CoffRelocSection(); break; default: result = new CoffSection(); break; } result.name = name; result._name = actualName; result.virtualSize = reader.ReadUInt32(); result.virtualAddress = reader.ReadUInt32(); result.sizeOfRawData = reader.ReadUInt32(); result.pointerToRawData = reader.ReadUInt32(); result.pointerToRelocations = reader.ReadUInt32(); result.pointerToLineNumbers = reader.ReadUInt32(); result.numberOfRelocations = reader.ReadUInt16(); result.numberOfLineNumbers = reader.ReadUInt16(); result.characteristics = (CoffSectionCharacteristics)reader.ReadUInt32(); result.sectionData = new Substream(reader.BaseStream, result.pointerToRawData, result.virtualSize); result.keepImageOpen = keepImageOpen; if (result.HasCustomRead) { using (var subReader = new EndianAwareBinaryReader(result.sectionData, reader.TargetEndianess, reader.BitEndianness, true)) result.CustomRead(subReader); } //if (bufferSectionData) //{ // if (!reader.BaseStream.CanSeek) // throw new InvalidOperationException(); // ReadSectionData(reader, result); //} //else // result.sectionDataReader = reader; return(result); }
internal uint ReadIndex(EndianAwareBinaryReader reader) { if (this.Size > ushort.MaxValue) { return(reader.ReadUInt32()); } return(reader.ReadUInt16()); }
private string GetServerVersionFromResponse(Stream stream) { using (var reader = new EndianAwareBinaryReader(stream, Encoding.UTF8, true, false)) { //Read Type (should be response = 4) int type = reader.ReadByte(); if (type != 4) { throw new NAMEException($"{SupportedDependencies.SqlServer}: Server responded with wrong Type ({type}).", NAMEStatusLevel.Error); } //Skip Status bit mask reader.ReadByte(); //Read the full message length ushort length = reader.ReadUInt16(); //Skip Channel reader.ReadUInt16(); //Skip Packet Number reader.ReadByte(); //Skip Window reader.ReadByte(); //Read the rest of the message //preLoginBuffer = reader.ReadBytes(length - 2 - 1 - 1 - 2 - 1 - 1); //Read first option token (should be Version = 0) int token = reader.ReadByte(); if (token != 0) { throw new NAMEException($"{SupportedDependencies.SqlServer}: Server responded with wrong Token ({token}).", NAMEStatusLevel.Error); } //Read the offset ushort offset = reader.ReadUInt16(); //Read the length (should be 6) ushort optionlength = reader.ReadUInt16(); if (optionlength != 6) { throw new NAMEException($"{SupportedDependencies.SqlServer}: Server responded with an invalid version length ({length}).", NAMEStatusLevel.Error); } //Skip everything until the version. reader.ReadBytes(offset - 2 - 2 - 1); int major = reader.ReadByte(); int minor = reader.ReadByte(); int build = reader.ReadUInt16(); return($"{major}.{minor}.{build}"); } }
public unsafe void Read(EndianAwareBinaryReader reader) { this._relativeVirtualAddressAndSize.Read(reader); var elementCount = (this.RelativeVirtualAddressAndSize.Size - Marshal.SizeOf(typeof(RVAndSize))) / Marshal.SizeOf(typeof(CoffRelocEntry)); for (int i = 0; i < elementCount; i++) { var typeOffset = reader.ReadUInt16(); base.baseList.Add(*(CoffRelocEntry *)&typeOffset); } }
internal void Read(EndianAwareBinaryReader reader) { this.imageBase = reader.ReadUInt32(); this.sectionAlignment = reader.ReadUInt32(); this.fileAlignment = reader.ReadUInt32(); this.osVersion.Read(reader); this.binaryVersion.Read(reader); this.subsystemVersion.Read(reader); this.reserved = reader.ReadUInt32(); this.imageSize = reader.ReadUInt32(); this.headerSize = reader.ReadUInt32(); this.fileChecksum = reader.ReadUInt32(); this.subsystem = (PEImageSubsystem)reader.ReadUInt16(); this.dllCharacteristics = (PEImageDllCharacteristics)reader.ReadUInt16(); this.stackReserveSize = reader.ReadUInt32(); this.stackCommitSize = reader.ReadUInt32(); this.heapReserveSize = reader.ReadUInt32(); this.heapCommitSize = reader.ReadUInt32(); this.loaderFlags = reader.ReadUInt32(); this.dataDirectoryCount = reader.ReadUInt32(); }
/// <summary> /// Loads the header from the reader. /// </summary> /// <param name="reader">The reader.</param> public void Read(EndianAwareBinaryReader reader) { Magic = reader.ReadUInt16(); if (IMAGE_OPTIONAL_HEADER_MAGIC != Magic) { throw new BadImageFormatException(); } MajorLinkerVersion = reader.ReadByte(); MinorLinkerVersion = reader.ReadByte(); SizeOfCode = reader.ReadUInt32(); SizeOfInitializedData = reader.ReadUInt32(); SizeOfUninitializedData = reader.ReadUInt32(); AddressOfEntryPoint = reader.ReadUInt32(); BaseOfCode = reader.ReadUInt32(); BaseOfData = reader.ReadUInt32(); ImageBase = reader.ReadUInt32(); SectionAlignment = reader.ReadUInt32(); FileAlignment = reader.ReadUInt32(); MajorOperatingSystemVersion = reader.ReadUInt16(); MinorOperatingSystemVersion = reader.ReadUInt16(); MajorImageVersion = reader.ReadUInt16(); MinorImageVersion = reader.ReadUInt16(); MajorSubsystemVersion = reader.ReadUInt16(); MinorSubsystemVersion = reader.ReadUInt16(); Win32VersionValue = reader.ReadUInt32(); SizeOfImage = reader.ReadUInt32(); SizeOfHeaders = reader.ReadUInt32(); CheckSum = reader.ReadUInt32(); Subsystem = reader.ReadUInt16(); DllCharacteristics = reader.ReadUInt16(); SizeOfStackReserve = reader.ReadUInt32(); SizeOfStackCommit = reader.ReadUInt32(); SizeOfHeapReserve = reader.ReadUInt32(); SizeOfHeapCommit = reader.ReadUInt32(); LoaderFlags = reader.ReadUInt32(); NumberOfRvaAndSizes = reader.ReadUInt32(); DataDirectory = new ImageDataDirectory[NumberOfRvaAndSizes]; for (int i = 0; i < NumberOfRvaAndSizes; i++) { DataDirectory[i].Read(reader); } }
public uint GetTypeFromMethodIndex(uint methodIndex) { /* * * String occupies Bit 2 * Extends Occupies Bit 3 * Field Occupies Bit 0 * Method Occupies Bit 1 * */ bool s = (this.state & 0x4) == 0x4, e = (this.state & 0x8) == 0x8, f = (this.state & 0x1) == 0x1, m = (this.state & 0x2) == 0x2; long offset = this.streamOffset; int miOffset = 4 + (s ? 8 : 4) + (e ? 4 : 2) + (f ? 4 : 2); var size = this.__size; bool possibleMatch = false; for (uint i = 1; i <= this.Count - 1; i++, offset += size) { uint methodStartIndex; if (this.ItemLoaded(i)) { methodStartIndex = this[(int)i].MethodStartIndex; } else { lock (this.syncObject) { this.reader.BaseStream.Seek(offset + miOffset, SeekOrigin.Begin); if (m) { methodStartIndex = reader.ReadUInt32(); } else { methodStartIndex = reader.ReadUInt16(); } } } if (!possibleMatch && methodStartIndex <= methodIndex) { possibleMatch = true; } else if (possibleMatch && methodStartIndex > methodIndex) { return(i - 1); } } return((uint)this.Count); }
//#endregion public void Read(EndianAwareBinaryReader reader) { this.magic = reader.ReadUInt16(); if (magic != magicConst) { throw new BadImageFormatException(); } this.lastPageSize = reader.ReadUInt16(); this.pageCount = reader.ReadUInt16(); this.relocations = reader.ReadUInt16(); this.headerSize = reader.ReadUInt16(); this.minimumParagraphsNeeded = reader.ReadUInt16(); this.maximumParagraphsNeeded = reader.ReadUInt16(); this.initialStackSegment = reader.ReadUInt16(); this.initialStackPointer = reader.ReadUInt16(); this.checksum = reader.ReadUInt16(); this.initialInstructionPointer = reader.ReadUInt16(); this.initialCodeSegment = reader.ReadUInt16(); this.relocationTablePtr = reader.ReadUInt16(); this.overlayNumber = reader.ReadUInt16(); this.reserved = reader.ReadUInt64(); this.oemIdentifier = reader.ReadUInt16(); this.oemInformation = reader.ReadUInt16(); this.reserved2A = reader.ReadUInt64(); this.reserved2B = reader.ReadUInt64(); this.reserved2C = reader.ReadUInt32(); this.peHeaderPointer = reader.ReadUInt32(); }
public object Deserialize(EndianAwareBinaryReader reader, SerializedType serializedType, int?length = null) { int?effectiveLength = null; var typeParent = TypeNode.Parent as TypeNode; if (length != null) { effectiveLength = length.Value; } else if (TypeNode.FieldLengthBinding != null) { object lengthValue = TypeNode.FieldLengthBinding.GetValue(this); effectiveLength = Convert.ToInt32(lengthValue); } else if (typeParent != null && typeParent.ItemLengthBinding != null) { object lengthValue = typeParent.ItemLengthBinding.GetValue((ValueNode)Parent); effectiveLength = Convert.ToInt32(lengthValue); } else if (TypeNode.FieldCountBinding != null) { object countValue = TypeNode.FieldCountBinding.GetValue(this); effectiveLength = Convert.ToInt32(countValue); } else if (serializedType == SerializedType.ByteArray || serializedType == SerializedType.SizedString) { checked { effectiveLength = (int)_remainder; } } object value; switch (serializedType) { case SerializedType.Int1: value = reader.ReadSByte(); break; case SerializedType.UInt1: value = reader.ReadByte(GetBitSize()); break; case SerializedType.Int2: value = reader.ReadInt16(); break; case SerializedType.UInt2: value = reader.ReadUInt16(); break; case SerializedType.Int4: value = reader.ReadInt32(); break; case SerializedType.UInt4: value = reader.ReadUInt32(); break; case SerializedType.Int8: value = reader.ReadInt64(); break; case SerializedType.UInt8: value = reader.ReadUInt64(); break; case SerializedType.Float4: value = reader.ReadSingle(); break; case SerializedType.Float8: value = reader.ReadDouble(); break; case SerializedType.ByteArray: { Debug.Assert(effectiveLength != null, "effectiveLength != null"); value = reader.ReadBytes(effectiveLength.Value); break; } case SerializedType.NullTerminatedString: { byte[] data = ReadNullTerminatedString(reader).ToArray(); value = Encoding.GetString(data, 0, data.Length); break; } case SerializedType.SizedString: { Debug.Assert(effectiveLength != null, "effectiveLength != null"); byte[] data = reader.ReadBytes(effectiveLength.Value); value = Encoding.GetString(data, 0, data.Length).TrimEnd('\0'); break; } case SerializedType.LengthPrefixedString: { value = reader.ReadString(); break; } default: throw new NotSupportedException(); } return(value); }
/// <summary> /// Loads and validates the DOS header. /// </summary> public void Read(EndianAwareBinaryReader reader) { e_magic = reader.ReadUInt16(); e_cblp = reader.ReadUInt16(); e_cp = reader.ReadUInt16(); e_crlc = reader.ReadUInt16(); e_cparhdr = reader.ReadUInt16(); e_minalloc = reader.ReadUInt16(); e_maxalloc = reader.ReadUInt16(); e_ss = reader.ReadUInt16(); e_sp = reader.ReadUInt16(); e_csum = reader.ReadUInt16(); e_ip = reader.ReadUInt16(); e_cs = reader.ReadUInt16(); e_lfarlc = reader.ReadUInt16(); e_ovno = reader.ReadUInt16(); e_res00 = reader.ReadUInt16(); e_res01 = reader.ReadUInt16(); e_res02 = reader.ReadUInt16(); e_res03 = reader.ReadUInt16(); e_oemid = reader.ReadUInt16(); e_oeminfo = reader.ReadUInt16(); e_res20 = reader.ReadUInt16(); e_res21 = reader.ReadUInt16(); e_res22 = reader.ReadUInt16(); e_res23 = reader.ReadUInt16(); e_res24 = reader.ReadUInt16(); e_res25 = reader.ReadUInt16(); e_res26 = reader.ReadUInt16(); e_res27 = reader.ReadUInt16(); e_res28 = reader.ReadUInt16(); e_res29 = reader.ReadUInt16(); e_lfanew = reader.ReadUInt32(); if (DOS_HEADER_MAGIC != e_magic) throw new BadImageFormatException(); }
private static string GetVersionFromServerReponse(TcpClient client) { EndianAwareBinaryReader reader = new EndianAwareBinaryReader(client.GetStream(), false); try { byte type = reader.ReadByte(); if (type != 1) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server responded with wrong type ({type})."); } //Skip channel reader.ReadUInt16(); //Read Length uint length = reader.ReadUInt32(); //Read the rest of the message into memory. The length of Connection.Start will never be bigger than int.max byte[] buffer = reader.ReadBytes((int)length); reader.Dispose(); reader = new EndianAwareBinaryReader(new MemoryStream(buffer), false); //Read class (should be Connection (10)) ushort rClass = reader.ReadUInt16(); if (rClass != 10) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server responded with wrong class ({rClass})."); } //Read method (should be Start (10)) ushort rMethod = reader.ReadUInt16(); if (rMethod != 10) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server responded with wrong method ({rMethod})."); } //Read AMQP major version (should be 0) byte major = reader.ReadByte(); if (major != 0) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server responded with wrong AMQP major version ({major})."); } //Read AMQP minor version (should be 9) byte minor = reader.ReadByte(); if (major != 0) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server responded with wrong AMQP minor version ({minor})."); } IDictionary <string, object> serverProperties = AmqpTypesReader.ReadTable(reader); if (!serverProperties.ContainsKey("version")) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server did not send a server-properties table!"); } if (!(serverProperties["version"] is byte[])) { throw new NAMEException($"{SupportedDependencies.RabbitMq}: Server returned a version which is not a string!"); } var versionStr = Encoding.UTF8.GetString((byte[])serverProperties["version"]); return(versionStr); } finally { if (reader != null) { reader.Dispose(); } } }
/// <summary> /// Reads the specified reader. /// </summary> /// <param name="reader">The reader.</param> public void Read(EndianAwareBinaryReader reader) { Ident = reader.ReadBytes(16); // Check for magic number if (Ident[0] != MagicNumber[0] || Ident[1] != MagicNumber[1] || Ident[2] != MagicNumber[2] || Ident[3] != MagicNumber[3]) { // Magic number not present, so it seems to be an invalid ELF file throw new NotSupportedException("This is not a valid ELF file"); } Type = (FileType)reader.ReadUInt16(); Machine = (MachineType)reader.ReadUInt16(); Version = (Version)reader.ReadUInt32(); EntryAddress = reader.ReadUInt32(); ProgramHeaderOffset = reader.ReadUInt32(); SectionHeaderOffset = reader.ReadUInt32(); Flags = reader.ReadUInt32(); ElfHeaderSize = reader.ReadUInt16(); ProgramHeaderEntrySize = reader.ReadUInt16(); ProgramHeaderNumber = reader.ReadUInt16(); SectionHeaderEntrySize = reader.ReadUInt16(); SectionHeaderNumber = reader.ReadUInt16(); SectionHeaderStringIndex = reader.ReadUInt16(); }
public static void PatchSyslinux_6_03(PartitionDevice partitionDevice, FatFileSystem fat) { // Locate ldlinux.sys file for patching string filename = "ldlinux.sys"; string name = (Path.GetFileNameWithoutExtension(filename) + Path.GetExtension(filename).PadRight(4).Substring(0, 4)).ToUpper(); var location = fat.FindEntry(new Mosa.FileSystem.FAT.Find.WithName(name), 0); if (!location.IsValid) throw new InvalidProgramException("Unable to find syslinux.sys"); // Get the file size & number of sectors used uint fileSize = fat.GetFileSize(location.DirectorySector, location.DirectorySectorIndex); var sectors = new List<uint>(); // Create list of the sectors of the file for (uint cluster = location.FirstCluster; (cluster != 0); cluster = fat.GetNextCluster(cluster)) { uint sec = fat.GetSectorByCluster(cluster); for (uint i = 0; i < fat.SectorsPerCluster; i++) { sectors.Add(sec + i); } } // Get the ldlinux.sys file stream var ldlinux = new FatFileStream(fat, location); var ldlinuxReader = new EndianAwareBinaryReader(ldlinux, Endianness.Little); // Search for 0x3EB202FE (magic) while ((ldlinuxReader.ReadUInt32() != Syslinux.LDLINUX_MAGIC) && (ldlinux.Position < ldlinux.Length)) ; if (ldlinux.Position >= ldlinux.Length || ldlinux.Position <= 0) throw new InvalidProgramException("Unable to find patch location for syslinux"); uint patchArea = (uint)ldlinux.Position - 4; // Get Extended Patch Area offset ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.EPAOffset; ushort epa = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr0; uint sect1Ptr0 = (uint)ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr1; uint sect1Ptr1 = (uint)ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrOffset; uint ex = (uint)ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrCnt; uint nptrs = (uint)ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.AdvPtrOffset; uint advptrs = (uint)ldlinuxReader.ReadUInt16(); if (sectors.Count > nptrs) throw new InvalidProgramException("Insufficient space for patching syslinux"); var ldlinuxWriter = new EndianAwareBinaryWriter(ldlinux, Endianness.Little); // Set up the totals ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)sectors.Count); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)2); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((uint)fileSize >> 2); // Generate Extents var extents = GenerateExtents(sectors); ldlinux.Position = ex; // Write out extents foreach (var extent in extents) { ldlinuxWriter.Write((ulong)extent.Start); ldlinuxWriter.Write((ushort)extent.Length); } // Write out ADV ldlinux.Position = advptrs; ldlinuxWriter.Write((ulong)sectors[sectors.Count - 2]); ldlinuxWriter.Write((ulong)sectors[sectors.Count - 1]); // Clear out checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write((uint)0); // Write back the updated cluster ldlinuxWriter.Flush(); // Re-Calculate checksum ldlinux.Position = 0; uint csum = Syslinux.LDLINUX_MAGIC; for (uint index = 0; index < (ldlinux.Length >> 2); index++) { csum = csum + ldlinuxReader.ReadUInt32(); } // Set the checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write(csum); // Write patched cluster back to disk ldlinuxWriter.Flush(); // Read boot sector var fatBootSector = new BinaryFormat(partitionDevice.ReadBlock(0, 1)); // Set the first sector location of the file fatBootSector.SetUInt(sect1Ptr0, fat.GetSectorByCluster(location.FirstCluster)); fatBootSector.SetUInt(sect1Ptr1, 0); // since only 32-bit offsets are support, the high portion of 64-bit value is zero // Write back patched boot sector partitionDevice.WriteBlock(0, 1, fatBootSector.Data); }
/// <summary> /// Loads and validates the DOS header. /// </summary> public void Read(EndianAwareBinaryReader reader) { e_magic = reader.ReadUInt16(); e_cblp = reader.ReadUInt16(); e_cp = reader.ReadUInt16(); e_crlc = reader.ReadUInt16(); e_cparhdr = reader.ReadUInt16(); e_minalloc = reader.ReadUInt16(); e_maxalloc = reader.ReadUInt16(); e_ss = reader.ReadUInt16(); e_sp = reader.ReadUInt16(); e_csum = reader.ReadUInt16(); e_ip = reader.ReadUInt16(); e_cs = reader.ReadUInt16(); e_lfarlc = reader.ReadUInt16(); e_ovno = reader.ReadUInt16(); e_res00 = reader.ReadUInt16(); e_res01 = reader.ReadUInt16(); e_res02 = reader.ReadUInt16(); e_res03 = reader.ReadUInt16(); e_oemid = reader.ReadUInt16(); e_oeminfo = reader.ReadUInt16(); e_res20 = reader.ReadUInt16(); e_res21 = reader.ReadUInt16(); e_res22 = reader.ReadUInt16(); e_res23 = reader.ReadUInt16(); e_res24 = reader.ReadUInt16(); e_res25 = reader.ReadUInt16(); e_res26 = reader.ReadUInt16(); e_res27 = reader.ReadUInt16(); e_res28 = reader.ReadUInt16(); e_res29 = reader.ReadUInt16(); e_lfanew = reader.ReadUInt32(); if (DOS_HEADER_MAGIC != e_magic) { throw new BadImageFormatException(); } }
/// <summary> /// Loads the CLI_HEADER from the reader. /// </summary> /// <param name="reader">The reader.</param> public void Read(EndianAwareBinaryReader reader) { Cb = reader.ReadUInt32(); MajorRuntimeVersion = reader.ReadUInt16(); MinorRuntimeVersion = reader.ReadUInt16(); Metadata.Read(reader); Flags = (RuntimeImageFlags)reader.ReadUInt32(); EntryPointToken = reader.ReadUInt32(); Resources.Read(reader); StrongNameSignature.Read(reader); CodeManagerTable.Read(reader); VTableFixups.Read(reader); ExportAddressTableJumps.Read(reader); ManagedNativeHeader.Read(reader); }
/// <summary> /// Reads the method header from the instruction stream. /// </summary> /// <param name="reader">The reader used to decode the instruction stream.</param> /// <returns></returns> private MethodHeader ReadMethodHeader(EndianAwareBinaryReader reader) { MethodHeader header = new MethodHeader(); // Read first byte header.Flags = (MethodFlags)reader.ReadByte(); // Check least significant 2 bits switch (header.Flags & MethodFlags.HeaderMask) { case MethodFlags.TinyFormat: header.CodeSize = ((uint)(header.Flags & MethodFlags.TinyCodeSizeMask) >> 2); header.Flags &= MethodFlags.HeaderMask; break; case MethodFlags.FatFormat: // Read second byte of flags header.Flags = (MethodFlags)(reader.ReadByte() << 8 | (byte)header.Flags); if (MethodFlags.ValidHeader != (header.Flags & MethodFlags.HeaderSizeMask)) throw new InvalidDataException(@"Invalid method header."); header.MaxStack = reader.ReadUInt16(); header.CodeSize = reader.ReadUInt32(); header.LocalsSignature = new Token(reader.ReadUInt32()); // ReadStandAloneSigRow break; default: throw new InvalidDataException(@"Invalid method header while trying to decode " + this.methodCompiler.Method.ToString() + ". (Flags = " + header.Flags.ToString("X") + ", Rva = " + this.methodCompiler.Method.Rva + ")"); } // Are there sections following the code? if (MethodFlags.MoreSections != (header.Flags & MethodFlags.MoreSections)) return header; // Yes, seek to them and process those sections long codepos = reader.BaseStream.Position; // Seek to the end of the code... long dataSectPos = codepos + header.CodeSize; if (0 != (dataSectPos & 3)) dataSectPos += (4 - (dataSectPos % 4)); reader.BaseStream.Position = dataSectPos; // Read all headers, so the IL decoder knows how to handle these... byte flags; do { flags = reader.ReadByte(); bool isFat = (0x40 == (flags & 0x40)); int length; int blocks; if (isFat) { byte a = reader.ReadByte(); byte b = reader.ReadByte(); byte c = reader.ReadByte(); length = (c << 24) | (b << 16) | a; blocks = (length - 4) / 24; } else { length = reader.ReadByte(); blocks = (length - 4) / 12; /* Read & skip the padding. */ reader.ReadInt16(); } Debug.Assert(0x01 == (flags & 0x3F), @"Unsupported method data section."); // Read the clause for (int i = 0; i < blocks; i++) { ExceptionHandlingClause clause = new ExceptionHandlingClause(); clause.Read(reader, isFat); methodCompiler.ExceptionClauseHeader.AddClause(clause); } } while (0x80 == (flags & 0x80)); reader.BaseStream.Position = codepos; return header; }
/// <summary> /// Reads the method header from the instruction stream. /// </summary> /// <param name="reader">The reader used to decode the instruction stream.</param> /// <returns></returns> public MethodHeader(EndianAwareBinaryReader reader) { Clauses = new List <ExceptionHandlingClause>(); // Read first byte Flags = (MethodFlags)reader.ReadByte(); // Check least significant 2 bits switch (Flags & MethodFlags.HeaderMask) { case MethodFlags.TinyFormat: CodeSize = ((int)(Flags & MethodFlags.TinyCodeSizeMask) >> 2); Flags &= MethodFlags.HeaderMask; break; case MethodFlags.FatFormat: // Read second byte of flags Flags = (MethodFlags)(reader.ReadByte() << 8 | (byte)Flags); if (MethodFlags.ValidHeader != (Flags & MethodFlags.HeaderSizeMask)) { throw new CompilerException("Invalid method "); } MaxStack = reader.ReadUInt16(); CodeSize = reader.ReadInt32(); LocalVarSigTok = new Token(reader.ReadUInt32()); // ReadStandAloneSigRow break; default: throw new CompilerException("Invalid method header"); } // Are there sections following the code? if (MethodFlags.MoreSections != (Flags & MethodFlags.MoreSections)) { return; } // Yes, seek to them and process those sections long codepos = reader.BaseStream.Position; // Seek to the end of the code... long dataSectPos = codepos + CodeSize; if (0 != (dataSectPos & 3)) { dataSectPos += (4 - (dataSectPos % 4)); } reader.BaseStream.Position = dataSectPos; // Read all headers, so the IL decoder knows how to handle these... byte flags; do { flags = reader.ReadByte(); bool isFat = (0x40 == (flags & 0x40)); int length; int blocks; if (isFat) { byte a = reader.ReadByte(); byte b = reader.ReadByte(); byte c = reader.ReadByte(); length = (c << 24) | (b << 16) | a; blocks = (length - 4) / 24; } else { length = reader.ReadByte(); blocks = (length - 4) / 12; /* Read & skip the padding. */ reader.ReadInt16(); } Debug.Assert(0x01 == (flags & 0x3F), "Unsupported method data section."); // Read the clause for (int i = 0; i < blocks; i++) { ExceptionHandlingClause clause = new ExceptionHandlingClause(); clause.Read(reader, isFat); Clauses.Add(clause); } }while (0x80 == (flags & 0x80)); reader.BaseStream.Position = codepos; }
private void ReadWide(EndianAwareBinaryReader reader, ICliMetadataRoot metadataRoot, Action <byte[]> bodyBuilder) { var flagsAndSize = reader.ReadUInt16(); this.flags = ((MethodHeaderFlags)(flagsAndSize & 0x0FFF)) & ~MethodHeaderFlags.WideFormat; this.headerSize = (byte)((flagsAndSize & 0xF000) >> 0xA); this.maxStack = reader.ReadUInt16(); this.codeSize = reader.ReadUInt32(); var localVarSigToken = reader.ReadUInt32(); if (localVarSigToken != 0) { var sigTableKind = (CliMetadataTableKinds)(1UL << (int)((localVarSigToken & 0xFF000000) >> 24)); var sigIndex = localVarSigToken & 0x00FFFFFF; ICliMetadataTable table; if (metadataRoot.TableStream.TryGetValue(sigTableKind, out table)) { if (table is ICliMetadataStandAloneSigTable) { ICliMetadataStandAloneSigTable sigTable = (ICliMetadataStandAloneSigTable)table; var entry = sigTable[(int)sigIndex]; if (entry.Signature is ICliMetadataLocalVarSignature) { var sigEntry = (ICliMetadataLocalVarSignature)entry.Signature; this.locals = sigEntry; } } } long codePosition = reader.BaseStream.Position; bodyBuilder(reader.ReadBytes((int)this.codeSize)); if ((reader.BaseStream.Position % 4) != 0) { reader.BaseStream.Position += 4 - reader.BaseStream.Position % 4; } var ehTable = new byte[0]; if ((flags & MethodHeaderFlags.ContainsMoreSections) == MethodHeaderFlags.ContainsMoreSections) { readSection: MethodHeaderSectionFlags sectionFlags = (MethodHeaderSectionFlags)reader.ReadByte(); var smallFormat = ((sectionFlags & MethodHeaderSectionFlags.FatFormat) != MethodHeaderSectionFlags.FatFormat); int dataSize = 0; if (smallFormat) { dataSize = reader.ReadByte(); reader.ReadUInt16(); } else { dataSize = (int)new BitVector(new byte[] { reader.ReadByte(), reader.ReadByte(), reader.ReadByte() }).GetUInt32Nibbits(0, 24); } if ((sectionFlags & MethodHeaderSectionFlags.ExceptionHandlerTable) == MethodHeaderSectionFlags.ExceptionHandlerTable) { ehTable = ehTable.AddInlineArray(reader.ReadBytes(dataSize - 4)); } else { reader.BaseStream.Position += dataSize - 4; } if ((sectionFlags & MethodHeaderSectionFlags.ContainsMoreSections) == MethodHeaderSectionFlags.ContainsMoreSections) { goto readSection; } } if (ehTable.Length > 0) { this.exceptionTable = new CliMetadataMethodExceptionTable(ehTable); } reader.BaseStream.Position = codePosition; } }
public void Read(EndianAwareBinaryReader reader) { this.majorVersion = reader.ReadUInt16(); this.minorVersion = reader.ReadUInt16(); }
private uint CalculateChecksum(string file) { uint csum = 0; using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BinaryReader reader = new EndianAwareBinaryReader(stream, true)) { uint l = (uint)stream.Length; for (uint p = 0; p < l; p += 2) { csum += reader.ReadUInt16(); if (csum > 0x0000FFFF) { csum = (csum & 0xFFFF) + (csum >> 16); } } csum = (csum & 0xFFFF) + (csum >> 16); csum += l; } } return csum; }
public static void PatchSyslinux_6_03(PartitionDeviceDriver partitionDevice, FatFileSystem fat) { // Locate ldlinux.sys file for patching string filename = "ldlinux.sys"; string name = (Path.GetFileNameWithoutExtension(filename) + Path.GetExtension(filename).PadRight(4).Substring(0, 4)).ToUpper(); var location = fat.FindEntry(name); if (!location.IsValid) { throw new InvalidProgramException("Unable to find syslinux.sys"); } // Get the file size & number of sectors used uint fileSize = fat.GetFileSize(location.DirectorySector, location.DirectorySectorIndex); var sectors = new List <uint>(); // Create list of the sectors of the file for (uint cluster = location.FirstCluster; (cluster != 0); cluster = fat.GetNextCluster(cluster)) { uint sec = fat.GetSectorByCluster(cluster); for (uint i = 0; i < fat.SectorsPerCluster; i++) { sectors.Add(sec + i); } } // Get the ldlinux.sys file stream var ldlinux = new FatFileStream(fat, location); var ldlinuxReader = new EndianAwareBinaryReader(ldlinux, Endianness.Little); // Search for 0x3EB202FE (magic) while ((ldlinuxReader.ReadUInt32() != Syslinux.LDLINUX_MAGIC) && (ldlinux.Position < ldlinux.Length)) { ; } if (ldlinux.Position >= ldlinux.Length || ldlinux.Position <= 0) { throw new InvalidProgramException("Unable to find patch location for syslinux"); } uint patchArea = (uint)ldlinux.Position - 4; // Get Extended Patch Area offset ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.EPAOffset; ushort epa = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr0; uint sect1Ptr0 = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.Sect1Ptr1; uint sect1Ptr1 = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrOffset; uint ex = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.SecPtrCnt; uint nptrs = ldlinuxReader.ReadUInt16(); ldlinux.Position = epa + Syslinux.ExtendedPatchAreaOffset.AdvPtrOffset; uint advptrs = ldlinuxReader.ReadUInt16(); if (sectors.Count > nptrs) { throw new InvalidProgramException("Insufficient space for patching syslinux"); } var ldlinuxWriter = new EndianAwareBinaryWriter(ldlinux, Endianness.Little); // Set up the totals ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)sectors.Count); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write((ushort)2); ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.DataSectors; ldlinuxWriter.Write(fileSize >> 2); // Generate Extents var extents = GenerateExtents(sectors); ldlinux.Position = ex; // Write out extents foreach (var extent in extents) { ldlinuxWriter.Write(extent.Start); ldlinuxWriter.Write(extent.Length); } // Write out ADV ldlinux.Position = advptrs; ldlinuxWriter.Write((ulong)sectors[sectors.Count - 2]); ldlinuxWriter.Write((ulong)sectors[sectors.Count - 1]); // Clear out checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write((uint)0); // Write back the updated cluster ldlinuxWriter.Flush(); // Re-Calculate checksum ldlinux.Position = 0; uint csum = Syslinux.LDLINUX_MAGIC; for (uint index = 0; index < (ldlinux.Length >> 2); index++) { csum = csum + ldlinuxReader.ReadUInt32(); } // Set the checksum ldlinux.Position = patchArea + Syslinux.PatchAreaOffset.Checksum; ldlinuxWriter.Write(csum); // Write patched cluster back to disk ldlinuxWriter.Flush(); // Read boot sector var fatBootSector = new DataBlock(partitionDevice.ReadBlock(0, 1)); // Set the first sector location of the file fatBootSector.SetUInt(sect1Ptr0, fat.GetSectorByCluster(location.FirstCluster)); fatBootSector.SetUInt(sect1Ptr1, 0); // since only 32-bit offsets are support, the high portion of 64-bit value is zero // Write back patched boot sector partitionDevice.WriteBlock(0, 1, fatBootSector.Data); }
/// <summary> /// Reads the root structure from the metadata. /// </summary> /// <param name="header">The <see cref="CliHeader"/> which denotes the location of the information.</param> /// <param name="originalStream">The <see cref="FileStream"/> being read from.</param> /// <param name="reader">The <see cref="EndianAwareBinaryReader"/> which handles reads.</param> /// <param name="relativeVirtualAddress">The <see cref="UInt32"/> value which denotes the relative /// virtual address of the metadata header.</param> /// <param name="sourceImage"></param> internal void Read(CliHeader header, FileStream originalStream, EndianAwareBinaryReader reader, uint relativeVirtualAddress, PEImage sourceImage) { this.originalStream = originalStream; this.header = header; this.streamPosition = relativeVirtualAddress; this.signature = reader.ReadUInt32(); if (this.signature != metadataSignature) { throw new BadImageFormatException(); } this.depreciatedVersion.Read(reader); this.reserved = reader.ReadUInt32(); this.realVersionLength = reader.ReadInt32(); byte[] version = new byte[(this.realVersionLength + 3) & ~3];//Make it a multiple of four. reader.Read(version, 0, version.Length); this.version = version; this.reservedFlags = reader.ReadUInt16(); int streamCount = 0; streamCount = reader.ReadUInt16(); this.sourceImage = sourceImage; for (int i = 0; i < streamCount; i++) { var currentHeader = new CliMetadataStreamHeader(); currentHeader.Read(reader, sourceImage); switch (currentHeader.Name) { case "#Strings": if (this.strings != null) { goto sectionExists; } this.strings = new CliMetadataStringsHeaderAndHeap(currentHeader, sourceImage.SyncObject); this.ScanAndReadSection(sourceImage, strings, this.strings.Read); break; case "#Blob": if (this.blob != null) { goto sectionExists; } this.blob = new CliMetadataBlobHeaderAndHeap(currentHeader, this); this.ScanAndReadSection(sourceImage, blob, this.blob.Read); break; case "#US": if (this.userStrings != null) { goto sectionExists; } this.userStrings = new CliMetadataUserStringsHeaderAndHeap(currentHeader, sourceImage.SyncObject); this.ScanAndReadSection(sourceImage, this.userStrings, this.userStrings.Read); break; case "#GUID": if (this.guids != null) { goto sectionExists; } this.guids = new CliMetadataGuidHeaderAndHeap(currentHeader, sourceImage.SyncObject); this.ScanAndReadSection(sourceImage, guids, this.guids.Read); break; case "#-": //https://github.com/jbevain/cecil/blob/8b689ecdc890cbf3715ba8775de1d713d71f09f3/Mono.Cecil.PE/ImageReader.cs#L359 case "#~": if (this.tableStream != null) { goto sectionExists; } this.tableStream = new CliMetadataTableStreamAndHeader(currentHeader); this.ScanAndReadSection(sourceImage, tableStream, sdReader => this.tableStream.Read(sdReader, this)); break; } continue; sectionExists: throw new BadImageFormatException(string.Format("Duplicate {0} section encountered.", currentHeader.Name)); } if (this.tableStream == null) { throw new BadImageFormatException("#~ or #- stream not present in image."); } }