Beispiel #1
0
        public void PersistentVarFileInfo()
        {
            // Prepare mock data.
            var versionInfo = new VersionInfoResource();

            var varFileInfo = new VarFileInfo();
            var table       = new VarTable();

            for (ushort i = 0; i < 10; i++)
            {
                table.Values.Add(i);
            }
            varFileInfo.Tables.Add(table);

            versionInfo.AddEntry(varFileInfo);

            // Serialize.
            var tempStream = new MemoryStream();

            versionInfo.Write(new BinaryStreamWriter(tempStream));

            // Reload.
            var infoReader     = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newVersionInfo = VersionInfoResource.FromReader(ref infoReader);

            // Verify.
            var newVarFileInfo = newVersionInfo.GetChild <VarFileInfo>(VarFileInfo.VarFileInfoKey);

            Assert.NotNull(newVarFileInfo);
            Assert.Single(newVarFileInfo.Tables);

            var newTable = newVarFileInfo.Tables[0];

            Assert.Equal(table.Values, newTable.Values);
        }
Beispiel #2
0
        public void PreserveMetadataNoChange()
        {
            var peFile   = PEFile.FromBytes(Properties.Resources.HelloWorld);
            var peImage  = PEImage.FromFile(peFile);
            var metadata = peImage.DotNetDirectory.Metadata;

            using var tempStream = new MemoryStream();
            metadata.Write(new BinaryStreamWriter(tempStream));

            var reader      = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newMetadata = new SerializedMetadata(new PEReaderContext(peFile), ref reader);

            Assert.Equal(metadata.MajorVersion, newMetadata.MajorVersion);
            Assert.Equal(metadata.MinorVersion, newMetadata.MinorVersion);
            Assert.Equal(metadata.Reserved, newMetadata.Reserved);
            Assert.Equal(metadata.VersionString, newMetadata.VersionString);
            Assert.Equal(metadata.Flags, newMetadata.Flags);

            Assert.Equal(metadata.Streams.Count, newMetadata.Streams.Count);
            for (int i = 0; i < metadata.Streams.Count; i++)
            {
                var oldStream = metadata.Streams[i];
                var newStream = newMetadata.Streams[i];

                Assert.Equal(oldStream.Name, newStream.Name);
                var oldData = oldStream.CreateReader().ReadToEnd();
                var newData = newStream.CreateReader().ReadToEnd();
                Assert.Equal(oldData, newData);
            }
        }
Beispiel #3
0
        public void NewForkTooLong()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            Assert.Throws <EndOfStreamException>(() => reader.ForkAbsolute(6, 4));
        }
Beispiel #4
0
        public void NewForkInvalidStart()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            Assert.Throws <ArgumentOutOfRangeException>(() => reader.ForkAbsolute(9, 3));
        }
Beispiel #5
0
        public void EmptyArray()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[0]);

            Assert.Equal(0u, reader.Length);

            Assert.Throws <EndOfStreamException>(() => reader.ReadByte());
            Assert.Equal(0, reader.ReadBytes(new byte[10], 0, 10));
        }
Beispiel #6
0
        public void ForkReadsSameData()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            var fork = reader.ForkAbsolute(0, 2);

            Assert.Equal(0x0201, fork.ReadUInt16());
        }
Beispiel #7
0
        public void ForkStartAtMiddle()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            var fork = reader.ForkAbsolute(4, 2);

            Assert.Equal(0x0605, fork.ReadUInt16());
        }
Beispiel #8
0
        public void ForkOfFork()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            var fork  = reader.ForkAbsolute(2, 4);
            var fork2 = fork.ForkAbsolute(3, 2);

            Assert.Equal(0x04, fork2.ReadByte());
        }
Beispiel #9
0
        public void ReadInt16()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x80,
                0x02, 0x80
            });

            Assert.Equal((ushort)0x8001, reader.ReadUInt16());
            Assert.Equal(2u, reader.Offset);
            Assert.Equal((short)-32766, reader.ReadInt16());
            Assert.Equal(4u, reader.Offset);
        }
Beispiel #10
0
        public void ReadInt32()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x04, 0x03, 0x02, 0x81,
                0x08, 0x07, 0x06, 0x85
            });

            Assert.Equal(0x81020304u, reader.ReadUInt32());
            Assert.Equal(4u, reader.Offset);
            Assert.Equal(-2063202552, reader.ReadInt32());
            Assert.Equal(8u, reader.Offset);
        }
Beispiel #11
0
        public void ReadInt64()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x80,
                0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x88,
            });

            Assert.Equal(0x8001020304050607ul, reader.ReadUInt64());
            Assert.Equal(8u, reader.Offset);
            Assert.Equal(-8644366967197856241, reader.ReadInt64());
            Assert.Equal(16u, reader.Offset);
        }
Beispiel #12
0
        public void NewForkSubRange()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            var fork = reader.ForkAbsolute(2, 3);

            Assert.Equal(2u, fork.StartOffset);
            Assert.Equal(2u, fork.Offset);
            Assert.Equal(3u, fork.Length);
        }
Beispiel #13
0
        public static void AssertWriteThenReadIsSame <TRow>(TRow expected,
                                                            SerializedMetadataTable <TRow> .ReadRowExtendedDelegate readRow)
            where TRow : struct, IMetadataRow
        {
            var tablesStream = new TablesStream();
            var table        = tablesStream.GetTable <TRow>();

            using var tempStream = new MemoryStream();
            expected.Write(new BinaryStreamWriter(tempStream), table.Layout);
            var reader = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newRow = readRow(new PEReaderContext(new PEFile()), ref reader, table.Layout);

            Assert.Equal(expected, newRow);
        }
Beispiel #14
0
        public void ForkMovesIndependentOfOriginal()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
            });

            var fork = reader.ForkAbsolute(0, 2);

            fork.ReadUInt16();

            Assert.Equal(0u, reader.Offset);
            Assert.Equal(2u, fork.Offset);
        }
Beispiel #15
0
        public void ReadByte()
        {
            var reader = ByteArrayDataSource.CreateReader(new byte[]
            {
                0x80,
                0x80
            });

            Assert.Equal((byte)0x80, reader.ReadByte());
            Assert.Equal(1u, reader.Offset);
            Assert.Equal((sbyte)-128, reader.ReadSByte());

            Assert.Throws <EndOfStreamException>(() => reader.ReadByte());
        }
        public void PersistentConstructor()
        {
            var module = ModuleDefinition.FromFile(typeof(CustomAttributesTestClass).Assembly.Location);

            using var stream = new MemoryStream();
            module.Write(stream);

            module = ModuleDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray()));

            var type = module.TopLevelTypes.First(t => t.Name == nameof(CustomAttributesTestClass));

            Assert.All(type.CustomAttributes, a =>
                       Assert.Equal(nameof(TestCaseAttribute), a.Constructor.DeclaringType.Name));
        }
Beispiel #17
0
        private static MethodDefinition LookupMethod(string methodName, bool rebuild)
        {
            var module = ModuleDefinition.FromFile(typeof(SecurityAttributes).Assembly.Location);

            if (rebuild)
            {
                var stream = new MemoryStream();
                module.Write(stream);
                module = ModuleDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray()));
            }

            var type = module.TopLevelTypes.First(t => t.Name == nameof(SecurityAttributes));

            return(type.Methods.First(m => m.Name == methodName));
        }
Beispiel #18
0
        public void PersistentStrongNamePublicKey()
        {
            using var rsa = RSA.Create();
            var rsaParameters = rsa.ExportParameters(true);
            var publicKey     = new StrongNamePublicKey(rsaParameters);

            using var tempStream = new MemoryStream();
            publicKey.Write(new BinaryStreamWriter(tempStream));

            var reader       = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newPublicKey = StrongNamePublicKey.FromReader(ref reader);

            Assert.Equal(publicKey.Modulus, newPublicKey.Modulus);
            Assert.Equal(publicKey.PublicExponent, newPublicKey.PublicExponent);
        }
        public static void ReadLocalVariables(CilMethodBody methodBody, MethodDefinition method, byte[] localSig)
        {
            if (!(method.Module is SerializedModuleDefinition module))
            {
                throw new ArgumentException("Method body should reference a serialized module.");
            }

            var reader          = ByteArrayDataSource.CreateReader(localSig);
            var localsSignature = (LocalVariablesSignature)CallingConventionSignature.FromReader(
                new BlobReadContext(module.ReaderContext),
                ref reader);

            for (int i = 0; i < localsSignature?.VariableTypes.Count; i++)
            {
                methodBody.LocalVariables.Add(new CilLocalVariable(localsSignature.VariableTypes[i]));
            }
        }
        /// <summary>
        /// Interprets the raw data stored in the <see cref="Data"/> property as a literal.
        /// </summary>
        /// <param name="elementType">The type of the literal.</param>
        /// <returns>The deserialized literal.</returns>
        public object InterpretData(ElementType elementType)
        {
            var reader = ByteArrayDataSource.CreateReader(Data);

            return(elementType switch
            {
                ElementType.Boolean => (object)(reader.ReadByte() != 0),
                ElementType.Char => (char)reader.ReadUInt16(),
                ElementType.I1 => reader.ReadSByte(),
                ElementType.U1 => reader.ReadByte(),
                ElementType.I2 => reader.ReadInt16(),
                ElementType.U2 => reader.ReadUInt16(),
                ElementType.I4 => reader.ReadInt32(),
                ElementType.U4 => reader.ReadUInt32(),
                ElementType.I8 => reader.ReadInt64(),
                ElementType.U8 => reader.ReadUInt64(),
                ElementType.R4 => reader.ReadSingle(),
                ElementType.R8 => reader.ReadDouble(),
                ElementType.String => Encoding.Unicode.GetString(reader.ReadToEnd()),
                _ => throw new ArgumentOutOfRangeException(nameof(elementType))
            });
Beispiel #21
0
        public void PersistentStringFileInfo()
        {
            // Prepare mock data.
            var versionInfo = new VersionInfoResource();

            var stringFileInfo = new StringFileInfo();
            var table          = new StringTable(0, 0x4b0)
            {
                [StringTable.ProductNameKey]     = "Sample product",
                [StringTable.FileVersionKey]     = "1.2.3.4",
                [StringTable.ProductVersionKey]  = "1.0.0.0",
                [StringTable.FileDescriptionKey] = "This is a sample description"
            };

            stringFileInfo.Tables.Add(table);

            versionInfo.AddEntry(stringFileInfo);

            // Serialize.
            var tempStream = new MemoryStream();

            versionInfo.Write(new BinaryStreamWriter(tempStream));

            // Reload.
            var infoReader     = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newVersionInfo = VersionInfoResource.FromReader(ref infoReader);

            // Verify.
            var newStringFileInfo = newVersionInfo.GetChild <StringFileInfo>(StringFileInfo.StringFileInfoKey);

            Assert.NotNull(newStringFileInfo);
            Assert.Single(newStringFileInfo.Tables);

            var newTable = newStringFileInfo.Tables[0];

            foreach ((string key, string value) in table)
            {
                Assert.Equal(value, newTable[key]);
            }
        }
Beispiel #22
0
        public void PersistentFixedVersionInfo()
        {
            // Prepare mock data.
            var versionInfo      = new VersionInfoResource();
            var fixedVersionInfo = new FixedVersionInfo
            {
                FileVersion    = new System.Version(1, 2, 3, 4),
                ProductVersion = new System.Version(1, 2, 3, 4),
                FileDate       = 0x12345678_9ABCDEF,
                FileFlags      = FileFlags.SpecialBuild,
                FileFlagsMask  = FileFlags.ValidBitMask,
                FileType       = FileType.App,
                FileOS         = FileOS.NT,
                FileSubType    = FileSubType.DriverInstallable,
            };

            versionInfo.FixedVersionInfo = fixedVersionInfo;

            // Serialize.
            var tempStream = new MemoryStream();

            versionInfo.Write(new BinaryStreamWriter(tempStream));

            // Reload.
            var infoReader          = ByteArrayDataSource.CreateReader(tempStream.ToArray());
            var newVersionInfo      = VersionInfoResource.FromReader(ref infoReader);
            var newFixedVersionInfo = newVersionInfo.FixedVersionInfo;

            // Verify.
            Assert.Equal(fixedVersionInfo.FileVersion, newFixedVersionInfo.FileVersion);
            Assert.Equal(fixedVersionInfo.ProductVersion, newFixedVersionInfo.ProductVersion);
            Assert.Equal(fixedVersionInfo.FileDate, newFixedVersionInfo.FileDate);
            Assert.Equal(fixedVersionInfo.FileFlags, newFixedVersionInfo.FileFlags);
            Assert.Equal(fixedVersionInfo.FileFlagsMask, newFixedVersionInfo.FileFlagsMask);
            Assert.Equal(fixedVersionInfo.FileType, newFixedVersionInfo.FileType);
            Assert.Equal(fixedVersionInfo.FileOS, newFixedVersionInfo.FileOS);
            Assert.Equal(fixedVersionInfo.FileSubType, newFixedVersionInfo.FileSubType);
        }
        public void PersistentResources()
        {
            var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);

            // Add new directory.
            const string directoryName = "Test";
            var          entryData     = new byte[] { 0, 1, 2, 3, 4 };
            var          directory     = new ResourceDirectory(directoryName)
            {
                Entries =
                {
                    new ResourceDirectory(1)
                    {
                        Entries ={ new ResourceData(1234,               new DataSegment(entryData)) }
                    }
                }
            };

            module.NativeResourceDirectory.Entries.Add(directory);

            // Write and rebuild.
            using var stream = new MemoryStream();
            module.Write(stream);
            var newModule = ModuleDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray()));

            // Assert contents.
            var newDirectory = (IResourceDirectory)newModule.NativeResourceDirectory.Entries
                               .First(entry => entry.Name == directoryName);

            newDirectory = (IResourceDirectory)newDirectory.Entries[0];

            var newData     = (IResourceData)newDirectory.Entries[0];
            var newContents = (IReadableSegment)newData.Contents;

            Assert.Equal(entryData, newContents.ToArray());
        }
Beispiel #24
0
 private static AssemblyDefinition Rebuild(AssemblyDefinition assembly)
 {
     using var stream = new MemoryStream();
     assembly.ManifestModule.Write(stream);
     return(AssemblyDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray())));
 }
        /// <inheritdoc />
        public override object ResolveMember(MetadataToken token)
        {
            switch (token.Table)
            {
            case TableIndex.TypeDef:
                var type = _tokens[(int)token.Rid];
                if (type is RuntimeTypeHandle runtimeTypeHandle)
                {
                    return(_importer.ImportType(Type.GetTypeFromHandle(runtimeTypeHandle)));
                }
                break;

            case TableIndex.Field:
                var field = _tokens[(int)token.Rid];

                if (field is null)
                {
                    return(null);
                }

                if (field is RuntimeFieldHandle runtimeFieldHandle)
                {
                    return(_importer.ImportField(FieldInfo.GetFieldFromHandle(runtimeFieldHandle)));
                }

                if (field.GetType().FullName == "System.Reflection.Emit.GenericFieldInfo")
                {
                    bool result = FieldReader.TryReadField <RuntimeFieldHandle>(field, "m_field", out var mField);
                    var  ctx    = FieldReader.ReadField <RuntimeTypeHandle>(field, "m_context");
                    return(_importer.ImportField(FieldInfo.GetFieldFromHandle(result
                            ? mField
                            : FieldReader.ReadField <RuntimeFieldHandle>(field, "m_fieldHandle"), ctx)));
                }

                break;

            case TableIndex.Method:
            case TableIndex.MemberRef:
                var obj = _tokens[(int)token.Rid];

                if (obj is RuntimeMethodHandle methodHandle)
                {
                    return(_importer.ImportMethod(MethodBase.GetMethodFromHandle(methodHandle)));
                }

                if (obj.GetType().FullName == "System.Reflection.Emit.GenericMethodInfo")
                {
                    var  context   = FieldReader.ReadField <RuntimeTypeHandle>(obj, "m_context");
                    bool hasHandle = FieldReader.TryReadField <RuntimeMethodHandle>(obj, "m_method", out var mMethod);
                    var  mHandle   = FieldReader.ReadField <RuntimeMethodHandle>(obj, "m_methodHandle");
                    var  method    = MethodBase.GetMethodFromHandle(
                        hasHandle ? mMethod : mHandle,
                        context);

                    return(_importer.ImportMethod(method));
                }

                if (obj.GetType().FullName == "System.Reflection.Emit.VarArgMethod")
                {
                    return(_importer.ImportMethod(FieldReader.ReadField <MethodInfo>(obj, "m_method")));
                }

                break;

            case TableIndex.StandAloneSig:
                var reader = ByteArrayDataSource.CreateReader((byte[])_tokens[(int)token.Rid]);
                return(CallingConventionSignature.FromReader(new BlobReadContext(_readerContext), ref reader));
            }

            return(token);
        }
        /// <summary>
        /// Reads a private key from an input file.
        /// </summary>
        /// <param name="path">The path to the strong-name key file.</param>
        /// <returns>The private key.</returns>
        /// <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>
        public static StrongNamePublicKey FromFile(string path)
        {
            var reader = ByteArrayDataSource.CreateReader(System.IO.File.ReadAllBytes(path));

            return(FromReader(ref reader));
        }
 private static ModuleDefinition Rebuild(ModuleDefinition module)
 {
     using var stream = new MemoryStream();
     module.Write(stream);
     return(ModuleDefinition.FromReader(ByteArrayDataSource.CreateReader(stream.ToArray())));
 }
Beispiel #28
0
 /// <summary>
 /// Creates a new tables stream based on a byte array.
 /// </summary>
 /// <param name="context">The reader context.</param>
 /// <param name="name">The name of the stream.</param>
 /// <param name="rawData">The raw contents of the stream.</param>
 public SerializedTableStream(PEReaderContext context, string name, byte[] rawData)
     : this(context, name, ByteArrayDataSource.CreateReader(rawData))
 {
 }
Beispiel #29
0
 /// <summary>
 /// Creates a new GUID stream based on a byte array.
 /// </summary>
 /// <param name="name">The name of the stream.</param>
 /// <param name="rawData">The raw contents of the stream.</param>
 public SerializedGuidStream(string name, byte[] rawData)
     : this(name, ByteArrayDataSource.CreateReader(rawData))
 {
 }