public void AddStringReference()
        {
            const string testConstant = "Lorem ipsum.";

            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var methodTable = tableStream.GetTable<MethodDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // write code.
            var body = methodTable[0].MethodBody;
            body.Instructions.Clear();
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldstr, testConstant));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Call,
                importer.ImportMethod(typeof(Console).GetMethod("WriteLine", new Type[]
                    {
                        typeof(string)
                    }))));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Call,
                importer.ImportMethod(typeof(Console).GetMethod("ReadKey", Type.EmptyTypes))));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ret));

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            methodTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<MethodDefinition>();

            var operand = methodTable[0].MethodBody.Instructions[0].Operand;
            Assert.IsInstanceOfType(operand, typeof(string));
            Assert.AreEqual(testConstant, operand);
        }
        public void CreateArrayField()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // create field.
            var arraySignature = new ArrayTypeSignature(typeSystem.Int32);
            arraySignature.Dimensions.Add(new ArrayDimension(2, 1));
            arraySignature.Dimensions.Add(new ArrayDimension(2));
            arraySignature.Dimensions.Add(new ArrayDimension());

            var field = new FieldDefinition(FieldName, FieldAttributes.Public | FieldAttributes.Static,
                new FieldSignature(importer.ImportTypeSignature(arraySignature)));
            fieldTable.Add(field);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            fieldTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<FieldDefinition>();
            field = fieldTable.First(x => x.Name == FieldName);

            Assert.IsInstanceOfType(field.Signature.FieldType, typeof(ArrayTypeSignature));
            Utilities.ValidateType(arraySignature, field.Signature.FieldType);
        }
        public void CreateSimpleSecurityDeclaration()
        {
            const string typeNamespace = "System.WitchCraft";
            const string typeName = "MagicalWand";

            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var typeTable = tableStream.GetTable<TypeDefinition>();
            var declarationTable = tableStream.GetTable<SecurityDeclaration>();
            var importer = new ReferenceImporter(tableStream);

            // create temp type.
            var type = new TypeDefinition(typeNamespace, typeName);
            type.MetadataRow.Column5 = 1; // FieldList
            type.MetadataRow.Column6 = 2; // MethodList.
            typeTable.Add(type);

            // create attribute.
            var securityAttribute = new SecurityAttributeSignature()
            {
                TypeName = typeof(TypeDescriptorPermissionAttribute).AssemblyQualifiedName,
            };

            // create permission set.
            var permissionSet = new PermissionSetSignature();
            permissionSet.Attributes.Add(securityAttribute);

            // create declaration.
            var declaration = new SecurityDeclaration(SecurityAction.Assert, permissionSet);
            type.SecurityDeclarations.Add(declaration);
            declarationTable.Add(declaration);

            assembly = Utilities.RebuildNetAssembly(assembly);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            typeTable = tableStream.GetTable<TypeDefinition>();
            type = typeTable.First(x => x.IsTypeOf(typeNamespace, typeName));

            Assert.IsTrue(type.SecurityDeclarations.Count > 0);
            var newDeclaration = type.SecurityDeclarations[0];

            Assert.AreEqual(declaration.Action, newDeclaration.Action);
            Assert.AreEqual(declaration.PermissionSet.Attributes.Count, newDeclaration.PermissionSet.Attributes.Count);

            for (int i = 0; i < declaration.PermissionSet.Attributes.Count; i++)
            {
                var attribute = declaration.PermissionSet.Attributes[i];
                var newAttribute = newDeclaration.PermissionSet.Attributes[i];

                Assert.AreEqual(attribute.TypeName, newAttribute.TypeName);

            }
        }
        public void CreateAttributeWithEnumArgument()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var assemblyTable = tableStream.GetTable<AssemblyDefinition>();
            var attributeTable = tableStream.GetTable<CustomAttribute>();
            var importer = new ReferenceImporter(tableStream);

            var assemblyDef = assemblyTable[0];

            // create custom attribute.
            var signature = new CustomAttributeSignature();
            signature.FixedArguments.Add(
                new CustomAttributeArgument(importer.ImportTypeSignature(typeof(DebuggableAttribute.DebuggingModes)),
                    new ElementSignature((int)DebuggableAttribute.DebuggingModes.Default)));

            var attribute = new CustomAttribute(importer.ImportMethod(typeof(DebuggableAttribute).GetConstructor(new Type[]
                {
                    typeof(DebuggableAttribute.DebuggingModes)
                })), signature);
            assemblyDef.CustomAttributes.Add(attribute);
            attributeTable.Add(attribute);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            assemblyTable = tableStream.GetTable<AssemblyDefinition>();
            assemblyDef = assemblyTable[0];
            attributeTable = tableStream.GetTable<CustomAttribute>();
            var newAttribute = attributeTable[0];

            Assert.IsTrue(assemblyDef.CustomAttributes.Contains(newAttribute));
            Assert.AreEqual(attribute.Constructor.FullName, newAttribute.Constructor.FullName);
            Assert.AreEqual(attribute.Signature.FixedArguments.Count, newAttribute.Signature.FixedArguments.Count);

            for (int i = 0; i < attribute.Signature.FixedArguments.Count; i++)
                Utilities.ValidateArgument(attribute.Signature.FixedArguments[i], newAttribute.Signature.FixedArguments[i]);
        }
Exemple #5
0
        public void TestInterpretAsArray()
        {
            var elementType = ElementType.I4;
            int[] expected = new int[] { 1, 2, 3 };
            byte[] data = new byte[] { 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0 };

            var assembly = Utilities.CreateTempNetAssembly();
            var importer = new ReferenceImporter(assembly.NetDirectory.MetadataHeader.GetStream<TableStream>());
            var fieldType = new TypeDefinition(string.Empty, "__StaticArrayInitTypeSize=" + data.Length,
                 importer.ImportType(typeof(ValueType)));

            var field = new FieldDefinition(FieldName,
                FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.HasFieldRva,
                new FieldSignature(new TypeDefOrRefSignature(fieldType) { IsValueType = true }));

            var fieldRva = new FieldRva(field, data);

            int[] actual = fieldRva.InterpretAsArray(elementType).Cast<int>().ToArray();

            Assert.AreEqual(expected.Length, actual.Length, "Length of arrays differ.");
            for (int i = 0; i < actual.Length; i++)
                Assert.AreEqual(expected[i], actual[i], "Element " + i + " differs from expected.");
        }
Exemple #6
0
        public void CreateCustomSizeFieldRva()
        {
            const int dataSize = 128;

            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var typeTable = tableStream.GetTable<TypeDefinition>();
            var classLayoutTable = tableStream.GetTable<ClassLayout>();
            var importer = new ReferenceImporter(tableStream);

            var type = new TypeDefinition(string.Empty, "__StaticArrayInitTypeSize=" + dataSize,
                importer.ImportType(typeof(ValueType)));
            type.MetadataRow.Column5 = 2; // FieldList
            type.MetadataRow.Column6 = 2; // MethodList
            typeTable.Add(type);

            var layout = new ClassLayout(type, 128, 1);
            type.ClassLayout = layout;
            classLayoutTable.Add(layout);

            TestFieldRva(assembly, new TypeDefOrRefSignature(type),
                Enumerable.Repeat((byte)1, dataSize).ToArray(), false);
        }
        public void CreateSimpleField()
        {
            var type = typeof(Process);

            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // create field.
            var field = new FieldDefinition(FieldName, FieldAttributes.Public | FieldAttributes.Static,
                new FieldSignature(importer.ImportTypeSignature(type)));
            fieldTable.Add(field);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            fieldTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<FieldDefinition>();
            field = fieldTable.First(x => x.Name == FieldName);

            Utilities.ValidateType(type, field.Signature.FieldType);
        }
        public void CreateRequiredModifierField()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // create field.
            var typeSignature = new RequiredModifierSignature(importer.ImportType(typeof(IsVolatile)), typeSystem.Int32);
            var field = new FieldDefinition(FieldName, FieldAttributes.Public | FieldAttributes.Static,
                new FieldSignature(typeSignature));
            fieldTable.Add(field);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            fieldTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<FieldDefinition>();
            field = fieldTable.First(x => x.Name == FieldName);

            Assert.IsInstanceOfType(field.Signature.FieldType, typeof(RequiredModifierSignature));
            var newTypeSignature = (RequiredModifierSignature)field.Signature.FieldType;
            Utilities.ValidateType(typeSignature.ModifierType, newTypeSignature.ModifierType);
            Utilities.ValidateType(typeSignature.BaseType, newTypeSignature.BaseType);
        }
        public void CreateGenericInstanceFieldReflection()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // create field.
            var typeSignature = (GenericInstanceTypeSignature)importer.ImportTypeSignature(typeof(List<string>));
            var field = new FieldDefinition(FieldName, FieldAttributes.Public | FieldAttributes.Static,
                new FieldSignature(typeSignature));
            fieldTable.Add(field);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            fieldTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<FieldDefinition>();
            field = fieldTable.First(x => x.Name == FieldName);

            Assert.IsInstanceOfType(field.Signature.FieldType, typeof(GenericInstanceTypeSignature));
            var newTypeSignature = (GenericInstanceTypeSignature)field.Signature.FieldType;
            Utilities.ValidateType(typeSignature.GenericType, newTypeSignature.GenericType);
            Assert.AreEqual(typeSignature.GenericArguments.Count, newTypeSignature.GenericArguments.Count);
            for (int i = 0; i < typeSignature.GenericArguments.Count; i++)
                Assert.AreEqual(typeSignature.GenericArguments[i].FullName,
                    newTypeSignature.GenericArguments[i].FullName);
        }
        public void CreateAttributeWithNamedArgument()
        {
            const string fieldName = "MyField";
            const string argumentValue = "MyXmlAttribute";
            const string propertyName = "IsNullable";
            const bool propertyValue = true;

            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var attributeTable = tableStream.GetTable<CustomAttribute>();
            var importer = new ReferenceImporter(tableStream);

            // create temp field.
            var field = new FieldDefinition(fieldName, FieldAttributes.Static, new FieldSignature(typeSystem.String));
            fieldTable.Add(field);

            // create custom attribute.
            var signature = new CustomAttributeSignature();
            signature.FixedArguments.Add(
                new CustomAttributeArgument(typeSystem.String,
                    new ElementSignature(argumentValue)));
            signature.NamedArguments.Add(
                new CustomAttributeNamedArgument()
                {
                    ArgumentMemberType = CustomAttributeArgumentMemberType.Property,
                    ArgumentType = typeSystem.Boolean,
                    MemberName = propertyName,
                    Argument = new CustomAttributeArgument(typeSystem.Boolean, new ElementSignature(propertyValue))
                });

            var attribute = new CustomAttribute(importer.ImportMethod(typeof(XmlAttributeAttribute).GetConstructor(new Type[]
                {
                    typeof(string)
                })), signature);

            field.CustomAttributes.Add(attribute);
            attributeTable.Add(attribute);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            fieldTable = tableStream.GetTable<FieldDefinition>();
            field = fieldTable.First(x => x.Name == fieldName);
            attributeTable = tableStream.GetTable<CustomAttribute>();
            var newAttribute = attributeTable[0];

            Assert.IsTrue(field.CustomAttributes.Contains(newAttribute));
            Assert.AreEqual(attribute.Constructor.FullName, newAttribute.Constructor.FullName);

            Assert.AreEqual(attribute.Signature.FixedArguments.Count, newAttribute.Signature.FixedArguments.Count);
            for (int i = 0; i < attribute.Signature.FixedArguments.Count; i++)
            {
                Utilities.ValidateArgument(attribute.Signature.FixedArguments[i],
                    newAttribute.Signature.FixedArguments[i]);
            }

            Assert.AreEqual(attribute.Signature.NamedArguments.Count, newAttribute.Signature.NamedArguments.Count);
            for (int i = 0; i < attribute.Signature.NamedArguments.Count; i++)
            {
                Utilities.ValidateNamedArgument(attribute.Signature.NamedArguments[i],
                    newAttribute.Signature.NamedArguments[i]);
            }
        }
        public void CreateSimpleAttribute()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var attributeTable = tableStream.GetTable<CustomAttribute>();
            var importer = new ReferenceImporter(tableStream);

            // create field.
            var field = new FieldDefinition("MyField", FieldAttributes.Public | FieldAttributes.Static,
                new FieldSignature(typeSystem.String));
            fieldTable.Add(field);

            // create custom attribute.
            var signature = new CustomAttributeSignature();
            signature.FixedArguments.Add(new CustomAttributeArgument(typeSystem.String, new ElementSignature("Lorem ipsum dolor sit amet.")));
            signature.FixedArguments.Add(new CustomAttributeArgument(typeSystem.Boolean, new ElementSignature(true)));

            var attribute = new CustomAttribute(importer.ImportMethod(typeof(ObsoleteAttribute).GetConstructor(new Type[]
                {
                    typeof(string),
                    typeof(bool)
                })), signature);
            field.CustomAttributes.Add(attribute);
            attributeTable.Add(attribute);

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            fieldTable = tableStream.GetTable<FieldDefinition>();
            field = fieldTable[0];
            attributeTable = tableStream.GetTable<CustomAttribute>();
            var newAttribute = attributeTable[0];

            Assert.IsTrue(field.CustomAttributes.Contains(newAttribute));
            Assert.AreEqual(attribute.Constructor.FullName, newAttribute.Constructor.FullName);
            Assert.AreEqual(attribute.Signature.FixedArguments.Count, newAttribute.Signature.FixedArguments.Count);

            for (int i = 0; i < attribute.Signature.FixedArguments.Count; i++)
                Assert.AreEqual(attribute.Signature.FixedArguments[i].Elements[0].Value,
                    newAttribute.Signature.FixedArguments[i].Elements[0].Value);
        }
        public void ImportUsingReflection()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var methodTable = tableStream.GetTable<MethodDefinition>();
            var importer = new ReferenceImporter(tableStream);

            // import members.
            var originalWriteLine = typeof(Console).GetMethod("WriteLine", new Type[]
            {
                typeof(int)
            });
            var newWriteLine = importer.ImportMethod(originalWriteLine);
            Utilities.ValidateMethod(originalWriteLine, newWriteLine);

            var originalReadKey = typeof(Console).GetMethod("ReadKey", Type.EmptyTypes);
            var newReadKey = importer.ImportMethod(originalReadKey);
            Utilities.ValidateMethod(originalReadKey, newReadKey);

            // write code.
            var body = methodTable[0].MethodBody;
            body.Instructions.Clear();
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldc_I4, 1337));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Call, newWriteLine));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Call, newReadKey));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ret));

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly);
            methodTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<MethodDefinition>();

            var writeLineReference = methodTable[methodTable.Count - 1].MethodBody.Instructions[1].Operand;
            Assert.IsInstanceOfType(writeLineReference, typeof(MemberReference));
            Utilities.ValidateMethod(originalWriteLine, (MemberReference)writeLineReference);

            var readKeyReference = methodTable[methodTable.Count - 1].MethodBody.Instructions[2].Operand;
            Assert.IsInstanceOfType(readKeyReference, typeof(MemberReference));
            Utilities.ValidateMethod(originalReadKey, (MemberReference)readKeyReference);
        }