예제 #1
0
        public static uint?ReadCompressedUInt32(this BinaryStreamReader reader)
        {
            byte b0 = reader.ReadByte();

            switch (b0 & 0xC0)
            {
            case 0x00:
            case 0x40:
                return(b0);

            case 0x80:
            {
                byte b1 = reader.ReadByte();
                return((uint)(
                           ((b0 & 0x3F) << 8)
                           | b1));
            }

            case 0xFF:
                return(null);

            default:
            {
                byte b1 = reader.ReadByte();
                byte b2 = reader.ReadByte();
                byte b3 = reader.ReadByte();
                return((uint)(
                           ((b0 & 0x3F) << 24)
                           | (b1 << 16)
                           | (b2 << 8)
                           | b3));
            }
            }
        }
예제 #2
0
 /// <summary>
 /// Reads a single constant row from an input stream.
 /// </summary>
 /// <param name="reader">The input stream.</param>
 /// <param name="layout">The layout of the constants table.</param>
 /// <returns>The row.</returns>
 public static ConstantRow FromReader(ref BinaryStreamReader reader, TableLayout layout)
 {
     return(new ConstantRow(
                (ElementType)reader.ReadByte(),
                reader.ReadByte(),
                reader.ReadIndex((IndexSize)layout.Columns[2].Size),
                reader.ReadIndex((IndexSize)layout.Columns[3].Size)));
 }
예제 #3
0
        /// <summary>
        /// Reads a single exception handler from the provided input stream.
        /// </summary>
        /// <param name="body">The method body containing the exception handler.</param>
        /// <param name="reader">The input stream.</param>
        /// <param name="isFat"><c>true</c> if the fat format should be used, <c>false</c> otherwise.</param>
        /// <returns>The exception handler.</returns>
        public static CilExceptionHandler FromReader(CilMethodBody body, ref BinaryStreamReader reader, bool isFat)
        {
            CilExceptionHandlerType handlerType;
            int tryStartOffset;
            int tryEndOffset;
            int handlerStartOffset;
            int handlerEndOffset;

            // Read raw structure.
            if (isFat)
            {
                handlerType        = (CilExceptionHandlerType)reader.ReadUInt32();
                tryStartOffset     = reader.ReadInt32();
                tryEndOffset       = tryStartOffset + reader.ReadInt32();
                handlerStartOffset = reader.ReadInt32();
                handlerEndOffset   = handlerStartOffset + reader.ReadInt32();
            }
            else
            {
                handlerType        = (CilExceptionHandlerType)reader.ReadUInt16();
                tryStartOffset     = reader.ReadUInt16();
                tryEndOffset       = tryStartOffset + reader.ReadByte();
                handlerStartOffset = reader.ReadUInt16();
                handlerEndOffset   = handlerStartOffset + reader.ReadByte();
            }

            int exceptionTokenOrFilterStart = reader.ReadInt32();

            // Create handler.
            var handler = new CilExceptionHandler
            {
                HandlerType  = handlerType,
                TryStart     = body.Instructions.GetLabel(tryStartOffset),
                TryEnd       = body.Instructions.GetLabel(tryEndOffset),
                HandlerStart = body.Instructions.GetLabel(handlerStartOffset),
                HandlerEnd   = body.Instructions.GetLabel(handlerEndOffset),
            };

            // Interpret last field.
            switch (handler.HandlerType)
            {
            case CilExceptionHandlerType.Exception when body.Owner.Module.TryLookupMember(exceptionTokenOrFilterStart, out var member):
                handler.ExceptionType = member as ITypeDefOrRef;

                break;

            case CilExceptionHandlerType.Filter:
                handler.FilterStart = body.Instructions.GetByOffset(exceptionTokenOrFilterStart)?.CreateLabel()
                                      ?? new CilOffsetLabel(exceptionTokenOrFilterStart);
                break;;
            }

            return(handler);
        }
예제 #4
0
        public static CustomMod[] ReadCustomModArray(out ElementType leadByte, BinaryStreamReader signatureBlobReader)
        {
            List <CustomMod> customMods = null;

            leadByte = (ElementType)signatureBlobReader.ReadByte();
            while (true)
            {
                var cmod = CustomMod.Read(signatureBlobReader, leadByte);
                if (cmod == null)
                {
                    break;
                }

                if (customMods == null)
                {
                    customMods = new List <CustomMod>();
                }

                customMods.Add(cmod);
            }

            if (customMods == null)
            {
                return(null);
            }
            else
            {
                return(customMods.ToArray());
            }
        }
예제 #5
0
 /// <summary>
 /// Reads an icon group resource entry from an input stream.
 /// </summary>
 /// <param name="reader">The input stream.</param>
 /// <returns>The parsed group icon resource entry.</returns>
 public static IconGroupDirectoryEntry FromReader(ref BinaryStreamReader reader)
 {
     return(new IconGroupDirectoryEntry
     {
         Offset = reader.Offset,
         Rva = reader.Rva,
         Width = reader.ReadByte(),
         Height = reader.ReadByte(),
         ColorCount = reader.ReadByte(),
         Reserved = reader.ReadByte(),
         ColorPlanes = reader.ReadUInt16(),
         PixelBitCount = reader.ReadUInt16(),
         BytesInRes = reader.ReadUInt32(),
         Id = reader.ReadUInt16()
     });
 }
예제 #6
0
파일: Param.cs 프로젝트: BGCX261/zoompe-git
        public static Param Read(BinaryStreamReader signatureBlobReader)
        {
            ElementType leadByte;

            var customMods = CustomMod.ReadCustomModArray(out leadByte, signatureBlobReader);

            switch (leadByte)
            {
            case ElementType.ByRef:
                leadByte = (ElementType)signatureBlobReader.ReadByte();
                return(new ByRef
                {
                    Type = Type.Read(leadByte, signatureBlobReader)
                });

            case ElementType.TypedByRef:
                return(new TypedByRef());

            default:
                return(new DirectType
                {
                    Type = Type.Read(leadByte, signatureBlobReader)
                });
            }
        }
예제 #7
0
        public static RefType Read(BinaryStreamReader signatureBlobReader)
        {
            var leadByte = (ElementType)signatureBlobReader.ReadByte();

            if (leadByte == ElementType.ByRef)
            {
                Type t = Type.Read(leadByte, signatureBlobReader);
                return(new ByRef
                {
                    Type = t
                });
            }
            else if (leadByte == ElementType.TypedByRef)
            {
                return(TypedByRef.Instance);
            }
            else if (leadByte == ElementType.Void)
            {
                return(Void.Instance);
            }
            else
            {
                Type t = Type.Read(leadByte, signatureBlobReader);
                return(new DirectType
                {
                    Type = t
                });
            }
        }
 /// <summary>
 /// Reads and verifies the blob header at the provided input stream.
 /// </summary>
 /// <param name="reader">The input stream.</param>
 /// <param name="expectedType">The expected structure type to read.</param>
 /// <param name="expectedVersion">The expected structure version to read.</param>
 /// <param name="expectedAlgorithm">The expected algorithm.</param>
 /// <exception cref="FormatException">Occurs when the input stream is not in the correct format.</exception>
 /// <exception cref="NotSupportedException">Occurs when an invalid or unsupported algorithm is specified.</exception>
 protected static void ReadBlobHeader(
     ref BinaryStreamReader reader,
     StrongNameKeyStructureType expectedType,
     byte expectedVersion,
     SignatureAlgorithm expectedAlgorithm)
 {
     // Read RSAPUBKEY
     if ((StrongNameKeyStructureType)reader.ReadByte() != expectedType)
     {
         throw new FormatException("Input stream does not contain the expected structure type.");
     }
     if (reader.ReadByte() != expectedVersion)
     {
         throw new NotSupportedException("Invalid or unsupported public/private key pair structure version number.");
     }
     reader.ReadUInt16();
     if ((SignatureAlgorithm)reader.ReadUInt32() != expectedAlgorithm)
     {
         throw new NotSupportedException("Invalid or unsupported public key algorithm.");
     }
 }
예제 #9
0
            static string ReadAsciiZ(BinaryStreamReader reader)
            {
                var resultBuilder = new StringBuilder();
                for (int i = 0; i < 1000; i++)
                {
                    byte b = reader.ReadByte();
                    if (b == 0)
                        break;

                    char c = (char)b;
                    resultBuilder.Append(c);
                }
                return resultBuilder.ToString();
            }
예제 #10
0
        public static HandshakeResponse Deserialize(byte[] bytes, int offset, int length)
        {
            using (var stream = new MemoryStream(bytes, offset, length))
            {
                var response = new HandshakeResponse();
                var reader   = new BinaryStreamReader(stream);

                response.Type           = (QueryPacketType)reader.ReadByte();
                response.Session        = new Session(reader.ReadInt32(ByteOrder.LittleEndian));
                response.ChallengeToken = int.Parse(reader.ReadString());

                return(response);
            }
        }
예제 #11
0
        public static uint ReadCompressedUInt(ref BinaryStreamReader reader)
        {
            uint num   = 0;
            var  shift = 0;
            byte current;

            do
            {
                current = reader.ReadByte();
                num    |= (current & 0x7fu) << shift;
                shift  += 7;
            } while((current & 0x80) != 0);
            return(num);
        }
예제 #12
0
        public void Read(BinaryStreamReader signatureBlobReader)
        {
            byte genericInst = signatureBlobReader.ReadByte();

            if (genericInst != 0x0a)
            {
                throw new BadImageFormatException("Invalid leading byte in MethodSpec: " + genericInst + ".");
            }

            uint?genArgCount = signatureBlobReader.ReadCompressedUInt32();

            if (genArgCount == null)
            {
                throw new BadImageFormatException("Null value for MethodSpec.GenArgCount is not supported.");
            }

            this.GenArgs = new TypeReference[genArgCount.Value];
        }
예제 #13
0
        public static MethodSig Read(BinaryStreamReader signatureBlobReader)
        {
            var callingConvention = (CallingConventions)signatureBlobReader.ReadByte();

            MethodSig result;

            switch (callingConvention & ~CallingConventions.HasThis & ~CallingConventions.ExplicitThis)
            {
            case CallingConventions.Default:
                result = new Default();
                break;

            case CallingConventions.C:
                result = new C();
                break;

            case CallingConventions.StdCall:
                result = new StdCall();
                break;

            case CallingConventions.FastCall:
                result = new FastCall();
                break;

            case CallingConventions.VarArg:
                result = new VarArg();
                break;

            case CallingConventions.Generic:
            {
                var typed = new Generic();
                typed.ReadDetails(signatureBlobReader);
                result = typed;
            }
            break;

            default:
                throw new BadImageFormatException("Invalid calling convention byte " + callingConvention + ".");
            }

            result.ReadParameters(signatureBlobReader);

            return(result);
        }
예제 #14
0
        public static VMFunctionSignature FromReader(ref BinaryStreamReader reader)
        {
            var result = new VMFunctionSignature
            {
                Flags = reader.ReadByte()
            };

            uint count = Utils.ReadCompressedUInt(ref reader);

            for (var i = 0; i < count; i++)
            {
                result.ParameterTokens.Add(
                    new MetadataToken(Utils.FromCodedToken(Utils.ReadCompressedUInt(ref reader))));
            }

            result.ReturnToken = new MetadataToken(Utils.FromCodedToken(Utils.ReadCompressedUInt(ref reader)));

            return(result);
        }
예제 #15
0
        /// <summary>
        /// Reads a marshal descriptor signature from the provided input stream.
        /// </summary>
        /// <param name="parentModule">The module that defines the marshal descriptor</param>
        /// <param name="reader">The input stream.</param>
        /// <returns>The marshal descriptor.</returns>
        public static MarshalDescriptor FromReader(ModuleDefinition parentModule, ref BinaryStreamReader reader)
        {
            var nativeType = (NativeType)reader.ReadByte();
            MarshalDescriptor descriptor = nativeType switch
            {
                NativeType.SafeArray => SafeArrayMarshalDescriptor.FromReader(parentModule, ref reader),
                NativeType.FixedArray => FixedArrayMarshalDescriptor.FromReader(ref reader),
                NativeType.LPArray => LPArrayMarshalDescriptor.FromReader(ref reader),
                NativeType.CustomMarshaller => CustomMarshalDescriptor.FromReader(parentModule, ref reader),
                NativeType.FixedSysString => FixedSysStringMarshalDescriptor.FromReader(ref reader),
                NativeType.Interface => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader),
                NativeType.IDispatch => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader),
                NativeType.IUnknown => ComInterfaceMarshalDescriptor.FromReader(nativeType, ref reader),
                _ => new SimpleMarshalDescriptor(nativeType)
            };

            descriptor.ExtraData = reader.ReadToEnd();
            return(descriptor);
        }
예제 #16
0
        static void Main(string[] args)
        {
            var pe            = new PEFile();
            var originalBytes = Properties.Resources.console_anycpu;
            var reader        = new BinaryStreamReader(new MemoryStream(originalBytes), new byte[1024]);

            pe.ReadFrom(reader);

            using (var output = File.Create("console.anycpu.exe"))
            {
                var writer = new BinaryStreamWriter(output);
                pe.WriteTo(writer);

                while (reader.Position < originalBytes.Length)
                {
                    writer.WriteByte(reader.ReadByte());
                }
            }
        }
예제 #17
0
        private static string ReadAlignedNameString(BinaryStreamReader reader)
        {
            var bytes = new List <byte>();

            while (true)
            {
                var b = reader.ReadByte();
                if (b == 0)
                {
                    break;
                }

                bytes.Add(b);
            }

            int skipCount = -1 + ((bytes.Count + 4) & ~3) - bytes.Count;

            reader.Position += skipCount;

            return(Encoding.UTF8.GetString(bytes.ToArray(), 0, bytes.Count));
        }
예제 #18
0
        /// <summary>
        /// Reads a raw method body from the given binary input stream using the tiny method body format.
        /// </summary>
        /// <param name="errorListener">The object responsible for recording parser errors.</param>
        /// <param name="reader">The binary input stream to read from.</param>
        /// <returns>The raw method body.</returns>
        /// <exception cref="FormatException">Occurs when the method header indicates an method body that is not in the
        /// tiny format.</exception>
        public new static CilRawTinyMethodBody FromReader(IErrorListener errorListener, ref BinaryStreamReader reader)
        {
            ulong fileOffset = reader.Offset;
            uint  rva        = reader.Rva;

            var flag = (CilMethodBodyAttributes)reader.ReadByte();

            if ((flag & CilMethodBodyAttributes.Tiny) != CilMethodBodyAttributes.Tiny)
            {
                errorListener.BadImage("Invalid tiny CIL method body header.");
                return(null);
            }

            int codeSize = (byte)flag >> 2;
            var code     = new byte[codeSize];

            reader.ReadBytes(code, 0, codeSize);

            var methodBody = new CilRawTinyMethodBody(code);

            methodBody.UpdateOffsets(fileOffset, rva);
            return(methodBody);
        }
예제 #19
0
        private static string ReadAsciiZ(BinaryStreamReader reader)
        {
            var result = new StringBuilder();

            while (true)
            {
                byte b = reader.ReadByte();
                if (b == 0)
                {
                    break;
                }

                const int maxLength = 512;

                if (result.Length > maxLength)
                {
                    throw new InvalidOperationException("String is too long, for safety reasons the size limit for ASCIIZ strings is set to " + maxLength + ".");
                }

                result.Append((char)b);
            }

            return(result.ToString());
        }
예제 #20
0
        public static BasicStatsResponse Deserialize(byte[] bytes, int offset, int length)
        {
            using (var stream = new MemoryStream(bytes, offset, length))
            {
                var response = new BasicStatsResponse();
                var reader   = new BinaryStreamReader(stream);

                response.Type    = (QueryPacketType)reader.ReadByte();
                response.Session = new Session(reader.ReadInt32(ByteOrder.LittleEndian));

                response.Stats = new BasicStats()
                {
                    Motd       = reader.ReadString(),
                    GameType   = reader.ReadString(),
                    Map        = reader.ReadString(),
                    NumPlayers = int.Parse(reader.ReadString()),
                    MaxPlayers = int.Parse(reader.ReadString()),
                    HostPort   = reader.ReadUShort(ByteOrder.LittleEndian),
                    HostIp     = reader.ReadString()
                };

                return(response);
            }
        }
        /// <summary>
        /// Reads a single array marshal descriptor at the current position of the binary stream reader.
        /// </summary>
        /// <param name="reader">The reader to use.</param>
        /// <returns>The read array descriptor.</returns>
        /// <remarks>
        /// This method assumes the native type has already been read from the binary stream reader.
        /// </remarks>
        public static LPArrayMarshalDescriptor FromReader(ref BinaryStreamReader reader)
        {
            var descriptor = new LPArrayMarshalDescriptor((NativeType)reader.ReadByte());

            if (!reader.TryReadCompressedUInt32(out uint value))
            {
                return(descriptor);
            }
            descriptor.ParameterIndex = (int)value;

            if (!reader.TryReadCompressedUInt32(out value))
            {
                return(descriptor);
            }
            descriptor.NumberOfElements = (int)value;

            if (!reader.TryReadCompressedUInt32(out value))
            {
                return(descriptor);
            }
            descriptor.Flags = (LPArrayFlags)value;

            return(descriptor);
        }
예제 #22
0
        public static Type Read(ElementType leadByte, BinaryStreamReader signatureBlobReader)
        {
            switch (leadByte)
            {
            case ElementType.End:
                break;

            case ElementType.Void:
                break;

            case ElementType.Boolean: return(Boolean.Instance);

            case ElementType.Char: return(Char.Instance);

            case ElementType.I1: return(I1.Instance);

            case ElementType.U1: return(U1.Instance);

            case ElementType.I2: return(I2.Instance);

            case ElementType.U2: return(U2.Instance);

            case ElementType.I4: return(I4.Instance);

            case ElementType.U4: return(U4.Instance);

            case ElementType.I8: return(I8.Instance);

            case ElementType.U8: return(U8.Instance);

            case ElementType.R4: return(R4.Instance);

            case ElementType.R8: return(R8.Instance);

            case ElementType.String: return(String.Instance);

            case ElementType.Ptr:
                ElementType ptrLeadByte;
                var         ptrCustomMod = CustomMod.ReadCustomModArray(out ptrLeadByte, signatureBlobReader);
                Ptr         resultPtr;
                if (ptrLeadByte == ElementType.Void)
                {
                    resultPtr = Ptr.Void.Instance;
                }
                else
                {
                    Type ptrType = Type.Read(ptrLeadByte, signatureBlobReader);
                    resultPtr = new Ptr.Type
                    {
                        PtrType = ptrType
                    };
                }
                resultPtr.CustomMods = ptrCustomMod;
                return(resultPtr);

            case ElementType.ByRef:
                break;

            case ElementType.ValueType:
                var valueTypeTypeDefOrRefOrSpecEncoded = signatureBlobReader.ReadTypeDefOrRefOrSpecEncoded();
                return(new ValueType {
                    TypeDefOrRefEncoded = valueTypeTypeDefOrRefOrSpecEncoded
                });

            case ElementType.Class:
                var classTypeDefOrRefOrSpecEncoded = signatureBlobReader.ReadTypeDefOrRefOrSpecEncoded();
                return(new Class {
                    TypeDefOrRefEncoded = classTypeDefOrRefOrSpecEncoded
                });

            case ElementType.Var:
                uint?varNumber = signatureBlobReader.ReadCompressedUInt32();
                return(new Var
                {
                    Number = varNumber
                });

            case ElementType.Array:
                // TODO: implement ArrayShape (ECMA-335 §23.2.13)
                throw new NotImplementedException("TODO: implement ArrayShape (ECMA-335 §23.2.13).");

            case ElementType.GenericInst:
                var         genericLeadByte = (ElementType)signatureBlobReader.ReadByte();
                GenericInst genericInst;
                switch (genericLeadByte)
                {
                case ElementType.Class:
                    genericInst = new GenericInst.Class();
                    break;

                case ElementType.ValueType:
                    genericInst = new GenericInst.ValueType();
                    break;

                default:
                    throw new BadImageFormatException("Invalid lead byte for " + ElementType.GenericInst + " class/valuetype value.");
                }

                var typeDefOrRefOrSpecEncoded = signatureBlobReader.ReadTypeDefOrRefOrSpecEncoded();
                genericInst.TypeDefOrRefOrSpecEncoded = typeDefOrRefOrSpecEncoded;

                uint?genArgCount = signatureBlobReader.ReadCompressedUInt32();
                if (genArgCount == null)
                {
                    throw new BadImageFormatException("Invalid null value for GenArgCount value in " + ElementType.GenericInst + ".");
                }

                var genericInstTypes = new Type[genArgCount.Value];
                for (int i = 0; i < genericInstTypes.Length; i++)
                {
                    var genericInstTypeLeadByte = (ElementType)signatureBlobReader.ReadByte();
                    genericInstTypes[i] = Type.Read(genericInstTypeLeadByte, signatureBlobReader);
                }

                genericInst.Types = genericInstTypes;
                return(genericInst);

            case ElementType.TypedByRef:
                break;

            case ElementType.I: return(I.Instance);

            case ElementType.U: return(U.Instance);

            case ElementType.FnPtr:
                var methodDefSig = MethodSig.Read(signatureBlobReader);
                return(new FnPtr
                {
                    MethodDefSig = methodDefSig
                });

            case ElementType.Object: return(Object.Instance);

            case ElementType.SZArray:
                ElementType szArrayLeadByte;
                var         szArrayCustomMod = CustomMod.ReadCustomModArray(out szArrayLeadByte, signatureBlobReader);
                var         szArrayType      = Type.Read(szArrayLeadByte, signatureBlobReader);
                return(new SZArray
                {
                    CustomMods = szArrayCustomMod,
                    Type = szArrayType
                });

            case ElementType.MVar:
                uint?mvarNumber = signatureBlobReader.ReadCompressedUInt32();
                return(new MVar
                {
                    Number = mvarNumber
                });

            case ElementType.CMod_ReqD:
                break;

            case ElementType.CMod_Opt:
                break;

            case ElementType.Internal:
                break;

            case ElementType.Modifier:
                break;

            case ElementType.Sentinel:
                break;

            case ElementType.Pinned:
                break;

            case ElementType.R4_Hfa:
                break;

            case ElementType.R8_Hfa:
                break;

            case ElementType.ArgumentType_:
                break;

            case ElementType.CustomAttribute_BoxedObject_:
                break;

            case ElementType.CustomAttribute_Field_:
                break;

            case ElementType.CustomAttribute_Property_:
                break;

            case ElementType.CustomAttribute_Enum_:
                break;

            default:
                break;
            }

            throw new BadImageFormatException("Invalid lead byte " + leadByte + ".");
        }
예제 #23
0
        /// <summary>
        /// Reads an optional header from the provided input stream.
        /// </summary>
        /// <param name="reader">The input stream.</param>
        /// <param name="ignoreNumberOfRvasAndSizes">Indicates whether the number of data directories should be ignored
        /// and <see cref="DefaultNumberOfRvasAndSizes"/> should be used instead.</param>
        /// <returns>The optional header.</returns>
        /// <exception cref="BadImageFormatException">Occurs when the input stream is malformed.</exception>
        public static OptionalHeader FromReader(ref BinaryStreamReader reader, bool ignoreNumberOfRvasAndSizes = true)
        {
            var header = new OptionalHeader
            {
                Offset                  = reader.Offset,
                Rva                     = reader.Rva,
                Magic                   = (OptionalHeaderMagic)reader.ReadUInt16(),
                MajorLinkerVersion      = reader.ReadByte(),
                MinorLinkerVersion      = reader.ReadByte(),
                SizeOfCode              = reader.ReadUInt32(),
                SizeOfInitializedData   = reader.ReadUInt32(),
                SizeOfUninitializedData = reader.ReadUInt32(),
                AddressOfEntrypoint     = reader.ReadUInt32(),
                BaseOfCode              = reader.ReadUInt32()
            };

            switch (header.Magic)
            {
            case OptionalHeaderMagic.Pe32:
                header.BaseOfData = reader.ReadUInt32();
                header.ImageBase  = reader.ReadUInt32();
                break;

            case OptionalHeaderMagic.Pe32Plus:
                header.ImageBase = reader.ReadUInt64();
                break;

            default:
                throw new BadImageFormatException("Unrecognized or unsupported optional header format.");
            }

            header.SectionAlignment            = reader.ReadUInt32();
            header.FileAlignment               = reader.ReadUInt32();
            header.MajorOperatingSystemVersion = reader.ReadUInt16();
            header.MinorOperatingSystemVersion = reader.ReadUInt16();
            header.MajorImageVersion           = reader.ReadUInt16();
            header.MinorImageVersion           = reader.ReadUInt16();
            header.MajorSubsystemVersion       = reader.ReadUInt16();
            header.MinorSubsystemVersion       = reader.ReadUInt16();
            header.Win32VersionValue           = reader.ReadUInt32();
            header.SizeOfImage        = reader.ReadUInt32();
            header.SizeOfHeaders      = reader.ReadUInt32();
            header.CheckSum           = reader.ReadUInt32();
            header.SubSystem          = (SubSystem)reader.ReadUInt16();
            header.DllCharacteristics = (DllCharacteristics)reader.ReadUInt16();

            if (header.Magic == OptionalHeaderMagic.Pe32)
            {
                header.SizeOfStackReserve = reader.ReadUInt32();
                header.SizeOfStackCommit  = reader.ReadUInt32();
                header.SizeOfHeapReserve  = reader.ReadUInt32();
                header.SizeOfHeapCommit   = reader.ReadUInt32();
            }
            else
            {
                header.SizeOfStackReserve = reader.ReadUInt64();
                header.SizeOfStackCommit  = reader.ReadUInt64();
                header.SizeOfHeapReserve  = reader.ReadUInt64();
                header.SizeOfHeapCommit   = reader.ReadUInt64();
            }

            header.LoaderFlags         = reader.ReadUInt32();
            header.NumberOfRvaAndSizes = reader.ReadUInt32();

            int dataDirectories = ignoreNumberOfRvasAndSizes
                ? DefaultNumberOfRvasAndSizes
                : (int)header.NumberOfRvaAndSizes;

            for (int i = 0; i < dataDirectories; i++)
            {
                header.DataDirectories.Add(DataDirectory.FromReader(ref reader));
            }

            return(header);
        }
예제 #24
0
        void ReadOptionalHeader(BinaryStreamReader reader)
        {
            if (this.OptionalHeader == null)
            {
                this.OptionalHeader = new OptionalHeader();
            }

            var peMagic = (PEMagic)reader.ReadInt16();

            if (peMagic != PEMagic.NT32 &&
                peMagic != PEMagic.NT64)
            {
                throw new BadImageFormatException("Unsupported PE magic value " + peMagic + ".");
            }

            this.OptionalHeader.PEMagic = peMagic;

            this.OptionalHeader.MajorLinkerVersion      = reader.ReadByte();
            this.OptionalHeader.MinorLinkerVersion      = reader.ReadByte();
            this.OptionalHeader.SizeOfCode              = reader.ReadUInt32();
            this.OptionalHeader.SizeOfInitializedData   = reader.ReadUInt32();
            this.OptionalHeader.SizeOfUninitializedData = reader.ReadUInt32();
            this.OptionalHeader.AddressOfEntryPoint     = reader.ReadUInt32();
            this.OptionalHeader.BaseOfCode              = reader.ReadUInt32();

            if (peMagic == PEMagic.NT32)
            {
                this.OptionalHeader.BaseOfData = reader.ReadUInt32();
                this.OptionalHeader.ImageBase  = reader.ReadUInt32();
            }
            else
            {
                this.OptionalHeader.ImageBase = reader.ReadUInt64();
            }

            this.OptionalHeader.SectionAlignment            = reader.ReadUInt32();
            this.OptionalHeader.FileAlignment               = reader.ReadUInt32();
            this.OptionalHeader.MajorOperatingSystemVersion = reader.ReadUInt16();
            this.OptionalHeader.MinorOperatingSystemVersion = reader.ReadUInt16();
            this.OptionalHeader.MajorImageVersion           = reader.ReadUInt16();
            this.OptionalHeader.MinorImageVersion           = reader.ReadUInt16();
            this.OptionalHeader.MajorSubsystemVersion       = reader.ReadUInt16();
            this.OptionalHeader.MinorSubsystemVersion       = reader.ReadUInt16();
            this.OptionalHeader.Win32VersionValue           = reader.ReadUInt32();
            this.OptionalHeader.SizeOfImage        = reader.ReadUInt32();
            this.OptionalHeader.SizeOfHeaders      = reader.ReadUInt32();
            this.OptionalHeader.CheckSum           = reader.ReadUInt32();
            this.OptionalHeader.Subsystem          = (Subsystem)reader.ReadUInt16();
            this.OptionalHeader.DllCharacteristics = (DllCharacteristics)reader.ReadUInt16();

            if (peMagic == PEMagic.NT32)
            {
                this.OptionalHeader.SizeOfStackReserve = reader.ReadUInt32();
                this.OptionalHeader.SizeOfStackCommit  = reader.ReadUInt32();
                this.OptionalHeader.SizeOfHeapReserve  = reader.ReadUInt32();
                this.OptionalHeader.SizeOfHeapCommit   = reader.ReadUInt32();
            }
            else
            {
                this.OptionalHeader.SizeOfStackReserve = reader.ReadUInt64();
                this.OptionalHeader.SizeOfStackCommit  = reader.ReadUInt64();
                this.OptionalHeader.SizeOfHeapReserve  = reader.ReadUInt64();
                this.OptionalHeader.SizeOfHeapCommit   = reader.ReadUInt64();
            }

            this.OptionalHeader.LoaderFlags         = reader.ReadUInt32();
            this.OptionalHeader.NumberOfRvaAndSizes = reader.ReadUInt32();

            if (this.OptionalHeader.DataDirectories == null ||
                this.OptionalHeader.DataDirectories.Length != this.OptionalHeader.NumberOfRvaAndSizes)
            {
                this.OptionalHeader.DataDirectories = new DataDirectory[this.OptionalHeader.NumberOfRvaAndSizes];
            }

            for (int i = 0; i < this.OptionalHeader.DataDirectories.Length; i++)
            {
                var dd = new DataDirectory();
                dd.Read(reader);
                this.OptionalHeader.DataDirectories[i] = dd;
            }
        }
예제 #25
0
        public static FullStatsResponse Deserialize(byte[] bytes, int offset, int length)
        {
            using (var stream = new MemoryStream(bytes, offset, length))
            {
                var response = new FullStatsResponse();
                var reader   = new BinaryStreamReader(stream);

                response.Type    = (QueryPacketType)reader.ReadByte();
                response.Session = new Session(reader.ReadInt32(ByteOrder.LittleEndian));

                // Skip padding
                stream.Seek(11, SeekOrigin.Current);

                // Read K, V section
                Dictionary <string, string> pairs = new Dictionary <string, string>();

                while (true)
                {
                    var key = reader.ReadString();

                    if (key.Length == 0)
                    {
                        break;
                    }

                    var value = reader.ReadString();
                    pairs.Add(key, value);
                }

                // Skip padding
                stream.Seek(10, SeekOrigin.Current);

                // Read players
                List <string> players = new List <string>();

                while (true)
                {
                    var player = reader.ReadString();
                    if (player.Length == 0)
                    {
                        break;
                    }
                    players.Add(player);
                }

                response.Stats = new FullStats()
                {
                    Motd       = pairs["hostname"],
                    GameType   = pairs["gametype"],
                    GameId     = pairs["game_id"],
                    Version    = pairs["version"],
                    Plugins    = pairs["plugins"],
                    Map        = pairs["map"],
                    NumPlayers = int.Parse(pairs["numplayers"]),
                    MaxPlayers = int.Parse(pairs["maxplayers"]),
                    HostPort   = ushort.Parse(pairs["hostport"]),
                    HostIp     = pairs["hostip"],
                    Players    = players.ToArray()
                };

                return(response);
            }
        }