Inheritance: _CustomAttributeBuilder
Beispiel #1
0
        // In here, we're defining a class, foo_Task, derived from our DefinedTask class. This allows us to write the bulk of the code
        // in real C#, rather than attempting to build it here.
        // This means that we have Task <- DefinedTask <- foo_Task.
        // We also need a module and an assembly to hold the class, so we do that, too.
        protected override void ExecuteTask()
        {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = _taskName + "_Assembly";

            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(_taskName + "_Module");

            // Now we've got an assembly and a module for the task to live in, we can define the actual task class.
            TypeBuilder typeBuilder = moduleBuilder.DefineType(_taskName + "_Task", TypeAttributes.Public);
            typeBuilder.SetParent(typeof(DefinedTask));

            // It needs a [TaskName] attribute.
            ConstructorInfo taskNameAttributeConstructor =
                typeof(TaskNameAttribute).GetConstructor(new Type[] { typeof(string) });
            CustomAttributeBuilder taskNameAttributeBuilder =
                new CustomAttributeBuilder(taskNameAttributeConstructor, new object[] { _taskName });
            typeBuilder.SetCustomAttribute(taskNameAttributeBuilder);

            // We're done. Create it.
            Type taskType = typeBuilder.CreateType();

            // Stash the XML in our static. We'll need it in DefinedTask later.
            DefinedTaskDefinitions.Add(_taskName, XmlNode);

            // Hook that up into NAnt.
            TaskBuilder taskBuilder = new TaskBuilder(taskType.Assembly, taskType.FullName);
            TypeFactory.TaskBuilders.Add(taskBuilder);
        }
Beispiel #2
0
		public static void CompileToAssembly
			(RegexCompilationInfo[] regexes, AssemblyName aname,
			 CustomAttributeBuilder[] attribs, string resourceFile)
		{
			throw new NotImplementedException ();
			// TODO : Make use of attribs and resourceFile parameters
			/*
			AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave);
			ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("InnerRegexModule",aname.Name);
			Parser psr = new Parser ();	
			
			System.Console.WriteLine("CompileToAssembly");
			       
			for(int i=0; i < regexes.Length; i++)
				{
					System.Console.WriteLine("Compiling expression :" + regexes[i].Pattern);
					RegularExpression re = psr.ParseRegularExpression (regexes[i].Pattern, regexes[i].Options);
					
					// compile
										
					CILCompiler cmp = new CILCompiler (modBuilder, i);
					bool reverse = (regexes[i].Options & RegexOptions.RightToLeft) !=0;
					re.Compile (cmp, reverse);
					cmp.Close();
					
				}
		       

			// Define a runtime class with specified name and attributes.
			TypeBuilder builder = modBuilder.DefineType("ITest");
			builder.CreateType();
			asmBuilder.Save(aname.Name);
			*/
		}
        protected ParameterDescriptor ParseQueueTrigger(JObject trigger, Type triggerParameterType = null)
        {
            if (triggerParameterType == null)
            {
                triggerParameterType = typeof(string);
            }

            ConstructorInfo ctorInfo = typeof(QueueTriggerAttribute).GetConstructor(new Type[] { typeof(string) });
            string queueName = (string)trigger["queueName"];
            CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(ctorInfo, new object[] { queueName });

            string parameterName = (string)trigger["name"];
            ParameterDescriptor triggerParameter = new ParameterDescriptor
            {
                Name = parameterName,
                Type = triggerParameterType,
                Attributes = ParameterAttributes.None,
                CustomAttributes = new Collection<CustomAttributeBuilder>
                {
                    attributeBuilder
                }
            };

            return triggerParameter;
        }
Beispiel #4
0
        protected RegexDynamicModule(int moduleNum, AssemblyName an, CustomAttributeBuilder[] attribs, String resourceFile) {
            new ReflectionPermission(PermissionState.Unrestricted).Assert();
            try {
                if (an == null) {
                    an = new AssemblyName();
                    an.Name = "RegexAssembly" +  AppDomain.CurrentDomain.GetHashCode().ToString() + "_" + moduleNum.ToString();
                    _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
                }
                else {
                    _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
                }

                _module = _assembly.DefineDynamicModule(an.Name + ".dll");

                if (attribs != null) {
                    for (int i=0; i<attribs.Length; i++) {
                        _assembly.SetCustomAttribute(attribs[i]);
                    }
                }

                if (resourceFile != null) {
		    // unmanaged resources are not supported
                    throw new ArgumentOutOfRangeException("resourceFile");
	        }
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
        }
        private static TypeBuilder Create(string tableName, List<FieldItem> fields)
        {
            //在模块中创建类型
            TypeBuilder typeBuilder = GetTypeBuilder(tableName);

            //设置类型的父类
            //typeBuilder.SetParent(typeof(Core));

            //创建构造函数
            ConstructorBuilder consBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
            ILGenerator ctorIL = consBuilder.GetILGenerator();
            ctorIL.Emit(OpCodes.Ret);
            ConstructorInfo classCtorInfo = typeof(DMTableAttribute).GetConstructor(new Type[] { typeof(string), typeof(string), typeof(bool) });
            CustomAttributeBuilder attr = new CustomAttributeBuilder(
                        classCtorInfo,
                        new object[] { tableName, "ContentID", true });

            typeBuilder.SetCustomAttribute(attr);

            foreach (var pi in fields)
            {
                CreateProperty(typeBuilder, pi.Name, pi.PropertyType);
            }

            return typeBuilder;
        }
Beispiel #6
0
		public static void Main()
		{			
			AssemblyName assemblyName = new AssemblyName();
			assemblyName.Name = "DynamicllyGeneratedAssembly";
			AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
			
			ConstructorInfo daCtor = typeof(DebuggableAttribute).GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
			CustomAttributeBuilder daBuilder = new CustomAttributeBuilder(daCtor, new object[] { DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default });
			assemblyBuilder.SetCustomAttribute(daBuilder);
			
			ModuleBuilder module = assemblyBuilder.DefineDynamicModule("DynamicllyGeneratedModule.exe", true);
			
			ISymbolDocumentWriter doc = module.DefineDocument(@"Source.txt", Guid.Empty, Guid.Empty, Guid.Empty);
			TypeBuilder typeBuilder = module.DefineType("DynamicllyGeneratedType", TypeAttributes.Public | TypeAttributes.Class);
			MethodBuilder methodbuilder = typeBuilder.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string[]) });
			ILGenerator ilGenerator = methodbuilder.GetILGenerator();
			
			ilGenerator.MarkSequencePoint(doc, 1, 1, 1, 100);
			ilGenerator.Emit(OpCodes.Ldstr, "Hello world!");
			MethodInfo infoWriteLine = typeof(System.Console).GetMethod("WriteLine", new Type[] { typeof(string) });
			ilGenerator.EmitCall(OpCodes.Call, infoWriteLine, null);
			
			ilGenerator.MarkSequencePoint(doc, 2, 1, 2, 100);
			ilGenerator.Emit(OpCodes.Ret);
			
			Type helloWorldType = typeBuilder.CreateType();			
			
			System.Diagnostics.Debugger.Break();
			helloWorldType.GetMethod("Main").Invoke(null, new string[] { null });
		}
 public static void AddAttribute(this AssemblyBuilder assemblyBuilder, Type attributeType)
 {
     ConstructorInfo attributeCtor = attributeType.GetConstructor(new Type[] { });
     CustomAttributeBuilder attributeBuilder =
         new CustomAttributeBuilder(attributeCtor, new object[] { });
     assemblyBuilder.SetCustomAttribute(attributeBuilder);
 }
 internal RegexTypeCompiler(AssemblyName an, CustomAttributeBuilder[] attribs, string resourceFile)
 {
     new ReflectionPermission(PermissionState.Unrestricted).Assert();
     try
     {
         List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
         CustomAttributeBuilder item = new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
         assemblyAttributes.Add(item);
         CustomAttributeBuilder builder2 = new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level2 });
         assemblyAttributes.Add(builder2);
         this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave, assemblyAttributes);
         this._module = this._assembly.DefineDynamicModule(an.Name + ".dll");
         if (attribs != null)
         {
             for (int i = 0; i < attribs.Length; i++)
             {
                 this._assembly.SetCustomAttribute(attribs[i]);
             }
         }
         if (resourceFile != null)
         {
             this._assembly.DefineUnmanagedResource(resourceFile);
         }
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
 }
        public void Create_class()
        {
            ILGenerator ilGenerator;
            AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName("Scenarios"), AssemblyBuilderAccess.RunAndSave);

            ModuleBuilder moduleBuilder = asmBuilder.DefineDynamicModule("Scenarios", "Scenarios.dll");

            var typeBuilder = moduleBuilder.DefineType("Scenario_Checkout", TypeAttributes.Class | TypeAttributes.Public);
            var attrBuilder = new CustomAttributeBuilder(typeof(TestFixtureAttribute).GetConstructor(new Type[]{ }), new Object[]{ });
            typeBuilder.SetCustomAttribute(attrBuilder);

            var method = typeBuilder.DefineMethod("ShouldGetLatestChangeset", MethodAttributes.Public);
            attrBuilder = new CustomAttributeBuilder(typeof(TestAttribute).GetConstructor(new Type[]{ }), new Object[]{ });
            method.SetCustomAttribute(attrBuilder);
            ilGenerator = method.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ldstr, "Hello world");
            ilGenerator.Emit(OpCodes.Call,
                typeof(Console).GetMethod("WriteLine",
                    new Type[] { typeof(string)}));
            //ilGenerator.Emit(OpCodes.Ldc_I4_0);
            ilGenerator.Emit(OpCodes.Ret);
            /*
            var thisType = typeof(CreateCodeAtRuntimeTests);
            var methodBody = thisType.GetMethod("Haldis").GetMethodBody().GetILAsByteArray();
            method.CreateMethodBody(methodBody, methodBody.Length);
            */
            typeBuilder.CreateType();

            asmBuilder.Save("Scenarios.dll");
        }
            public CustAttr(CustomAttributeBuilder customBuilder)
            {
                if (customBuilder == null)
                    throw new ArgumentNullException("customBuilder");

                m_customBuilder = customBuilder;
            }
Beispiel #11
0
        public DynamicAssembly()
        {
            int assemblyNumber = Interlocked.Increment(ref _assemblyCount);
            _assemblyName = new AssemblyName {
                Name = String.Format("Quokka.DynamicAssembly.N{0}", assemblyNumber)
            };
            string moduleName = AssemblyName.Name;
            _dynamicClassNamespace = AssemblyName.Name;

            if (CreateFiles)
            {
                _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
                    AssemblyName, AssemblyBuilderAccess.RunAndSave);

                // Add a debuggable attribute to the assembly saying to disable optimizations
                // See http://blogs.msdn.com/rmbyers/archive/2005/06/26/432922.aspx
                Type daType = typeof (DebuggableAttribute);
                ConstructorInfo daCtor = daType.GetConstructor(new[] {typeof (bool), typeof (bool)});
                var daBuilder = new CustomAttributeBuilder(daCtor, new object[] {true, true});
                _assemblyBuilder.SetCustomAttribute(daBuilder);

                _moduleBuilder = _assemblyBuilder.DefineDynamicModule(moduleName);
                _canSave = true;
            }
            else
            {
                _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.Run);
                _moduleBuilder = _assemblyBuilder.DefineDynamicModule(moduleName);
            }
        }
Beispiel #12
0
        private static Type CreateDelegateType(BasicSignature signature)
        {
            string delTypeName = signature.UniqueName;

            TypeAttributes typeAttr = TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass;
            TypeBuilder del = CppLibrary.interopModule.DefineType (delTypeName, typeAttr, typeof(MulticastDelegate));

            if (signature.CallingConvention.HasValue) {
                ConstructorInfo ufpa = typeof (UnmanagedFunctionPointerAttribute).GetConstructor (new Type [] { typeof (CallingConvention) });
                CustomAttributeBuilder unmanagedPointer = new CustomAttributeBuilder (ufpa, new object [] { signature.CallingConvention.Value });
                del.SetCustomAttribute (unmanagedPointer);
            }

            MethodAttributes ctorAttr = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
            ConstructorBuilder ctor = del.DefineConstructor (ctorAttr, CallingConventions.Standard, new Type[] { typeof(object), typeof(System.IntPtr) });
            ctor.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            Type [] parameterTypes = signature.ParameterTypes.ToArray ();
            MethodAttributes methodAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;

            MethodBuilder invokeMethod = del.DefineMethod ("Invoke", methodAttr, signature.ReturnType, parameterTypes);
            invokeMethod.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            return del.CreateType ();
        }
        private Type GenerateAnonymousType(ModuleBuilder dynamicTypeModule)
        {
            var dynamicType = dynamicTypeModule.DefineType(ClassName, TypeAttributes.BeforeFieldInit | TypeAttributes.Sealed);
            var builderArray = dynamicType.DefineGenericParameters(GenericClassParameterNames);
            var fields = new List<FieldBuilder>();
            for (var i = 0; i < FieldNames.Length; i++)
            {
                var item = dynamicType.DefineField(FieldNames[i], builderArray[i], FieldAttributes.InitOnly | FieldAttributes.Private);
                var type = typeof(DebuggerBrowsableAttribute);
                var customBuilder = new CustomAttributeBuilder(type.GetConstructor(new Type[] { typeof(DebuggerBrowsableState) }), new object[] { DebuggerBrowsableState.Never });
                item.SetCustomAttribute(customBuilder);
                fields.Add(item);
            }
            var list2 = new List<PropertyBuilder>();
            for (var j = 0; j < PropertyNames.Length; j++)
            {
                var builder4 = GenerateProperty(dynamicType, PropertyNames[j], fields[j]);
//                var type = typeof(JsonPropertyAttribute);
//                var customBuilder2 = new CustomAttributeBuilder(type.GetConstructor(new Type[0]), new object[0]);
//                builder4.SetCustomAttribute(customBuilder2);
                list2.Add(builder4);
            }
            GenerateClassAttributes(dynamicType, PropertyNames);
            GenerateConstructor(dynamicType, PropertyNames, fields);
            GenerateEqualsMethod(dynamicType, fields.ToArray());
            GenerateGetHashCodeMethod(dynamicType, fields.ToArray());
            GenerateToStringMethod(dynamicType, PropertyNames, fields.ToArray());
            return dynamicType.CreateType().MakeGenericType(PropertyTypes);
        }
Beispiel #14
0
        public static Type CreateTest()
        {
            AppDomain currentDomain = Thread.GetDomain();

            AssemblyName assName = new AssemblyName();
            assName.Name = "DynamicTest";
            AssemblyBuilder assemblyBuilder = currentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.Run);
            
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");

            TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);

            CustomAttributeBuilder customTypeAttributeBuilder = new CustomAttributeBuilder(typeof(TestClassAttribute).GetConstructors()[0], new object[]{});
            typeBuilder.SetCustomAttribute(customTypeAttributeBuilder);

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("DynamicTestMethod", MethodAttributes.Public, null, new Type[] { });
            CustomAttributeBuilder customMethodAttributeBuilder = new CustomAttributeBuilder(typeof(TestMethodAttribute).GetConstructors()[0], new object[] { });
            methodBuilder.SetCustomAttribute(customMethodAttributeBuilder);


            ILGenerator il = methodBuilder.GetILGenerator();

            il.EmitWriteLine("Hello world");
            il.Emit(OpCodes.Ret);
            return typeBuilder.CreateType();

        }
 public void PosTest1()
 {
     TypeBuilder typebuilder = GetTypeBuilder();
     ConstructorInfo constructorinfo = typeof(ClassCreator).GetConstructor(new Type[] { typeof(string) });
     CustomAttributeBuilder cuatbu = new CustomAttributeBuilder(constructorinfo, new object[] { "hello" });
     typebuilder.SetCustomAttribute(cuatbu);
 }
        public void TestSetCustomAttribute()
        {
            MethodAttributes getMethodAttr = MethodAttributes.Public |
                                             MethodAttributes.SpecialName |
                                             MethodAttributes.HideBySig;
            Type returnType = typeof(int);
            Type[] ctorParamTypes = new Type[] { typeof(int) };
            int expectedValue = _generator.GetInt32();
            object[] ctorParamValues = new object[] { expectedValue };
            CustomAttributeBuilder customAttrBuilder = new CustomAttributeBuilder(
                                                            typeof(PBMyAttribute).GetConstructor(ctorParamTypes),
                                                            ctorParamValues);
            object[] actualCustomAttrs;

            actualCustomAttrs = ExecutePosTest(
                                        customAttrBuilder,
                                        getMethodAttr,
                                        returnType,
                                        new Type[0],
                                        BindingFlags.Public |
                                        BindingFlags.Instance |
                                        BindingFlags.NonPublic |
                                        BindingFlags.Static);
            Assert.Equal(1, actualCustomAttrs.Length);
            Assert.True(actualCustomAttrs[0] is PBMyAttribute);
            Assert.Equal(expectedValue, (actualCustomAttrs[0] as PBMyAttribute).Value);
        }
        public void PosTest1()
        {
            string name = "Assembly1";
            AssemblyName asmname = new AssemblyName();
            asmname.Name = name;

            AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run);

            ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1");
            TypeBuilder tpbuild = modbuild.DefineType("C1");

            Type attrType = typeof(TBMyAttribute1);
            ConstructorInfo ci = attrType.GetConstructors()[0];
            FieldInfo fi = attrType.GetField("Field12345");


            CustomAttributeBuilder cab = new CustomAttributeBuilder(ci,
                                                                    new object[] { 4 },
                                                                    new FieldInfo[] { fi },
                                                                    new object[] { "hello" });
            tpbuild.SetCustomAttribute(cab);
            tpbuild.CreateTypeInfo().AsType();

            // VERIFY
            object[] attribs = tpbuild.GetCustomAttributes(false).Select(a => (object)a).ToArray();

            Assert.Equal(1, attribs.Length);
            TBMyAttribute1 obj = (TBMyAttribute1)attribs[0];

            Assert.Equal("hello", obj.Field12345);
            Assert.Equal(4, obj.m_ctorType2);
        }
        private object[] ExecutePosTest(
                            CustomAttributeBuilder customAttrBuilder,
                            MethodAttributes getMethodAttr,
                            Type returnType,
                            Type[] paramTypes,
                            BindingFlags bindingAttr)
        {
            TypeBuilder myTypeBuilder = GetTypeBuilder(TypeAttributes.Class | TypeAttributes.Public);

            PropertyBuilder myPropertyBuilder = myTypeBuilder.DefineProperty(DynamicPropertyName,
                                                                             PropertyAttributes.HasDefault,
                                                                             returnType, null);
            myPropertyBuilder.SetCustomAttribute(customAttrBuilder);
            // Define the "get" accessor method for DynamicPropertyName
            MethodBuilder myMethodBuilder = myTypeBuilder.DefineMethod(DynamicMethodName,
                                                                       getMethodAttr, returnType, paramTypes);
            ILGenerator methodILGenerator = myMethodBuilder.GetILGenerator();
            methodILGenerator.Emit(OpCodes.Ldarg_0);
            methodILGenerator.Emit(OpCodes.Ret);

            // Map the 'get' method created above to our PropertyBuilder
            myPropertyBuilder.SetGetMethod(myMethodBuilder);

            Type myType = myTypeBuilder.CreateTypeInfo().AsType();

            PropertyInfo myProperty = myType.GetProperty(DynamicPropertyName, bindingAttr);
            return myProperty.GetCustomAttributes(false).Select(a => (object)a).ToArray();
        }
		public static CodeCustomAttribute Create (Type attributeType, Type [] ctorArgTypes, CodeLiteral [] ctorArgs, MemberInfo [] members, CodeLiteral [] values)
		{
			ArrayList props = new ArrayList ();
			ArrayList pvalues  = new ArrayList ();
			ArrayList fields = new ArrayList ();
			ArrayList fvalues = new ArrayList ();
			for (int i = 0; i < members.Length; i++) {
				if (members [i] == null)
					throw new ArgumentException (String.Format ("MemberInfo at {0} was null for type {1}.", i, attributeType));
				if (members [i] is PropertyInfo) {
					props.Add ((PropertyInfo) members [i]);
					pvalues.Add (values [i].Value);
				} else {
					fields.Add ((FieldInfo) members [i]);
					fvalues.Add (values [i].Value);
				}
			}

			ConstructorInfo ci = attributeType.GetConstructor (ctorArgTypes);
			CustomAttributeBuilder cab = new CustomAttributeBuilder (
				ci, ctorArgs,
				(PropertyInfo []) props.ToArray (typeof (PropertyInfo)), pvalues.ToArray (),
				(FieldInfo []) fields.ToArray (typeof (FieldInfo)), fvalues.ToArray ());

			CodeCustomAttribute attr = new CodeCustomAttribute (
				cab, attributeType, ci, ctorArgs, members, values);

			return attr;
		}
		public AssemblyAlgorithmIdAttributeTest ()
		{
			//create a dynamic assembly with the required attribute
			//and check for the validity

			dynAsmName.Name = "TestAssembly";

			dynAssembly = Thread.GetDomain ().DefineDynamicAssembly (
				dynAsmName,AssemblyBuilderAccess.Run
				);

			// Set the required Attribute of the assembly.
			Type attribute = typeof (AssemblyAlgorithmIdAttribute);
			ConstructorInfo ctrInfo = attribute.GetConstructor (
				new Type [] { typeof (AssemblyHashAlgorithm) }
				);
			CustomAttributeBuilder attrBuilder =
				new CustomAttributeBuilder (
				ctrInfo,
				new object [1] { AssemblyHashAlgorithm.MD5 }
				);
			dynAssembly.SetCustomAttribute (attrBuilder);
			object [] attributes = dynAssembly.GetCustomAttributes (true);
			attr = attributes [0] as AssemblyAlgorithmIdAttribute;
		}
Beispiel #21
0
 internal static void Compile(EnumMetadataEnum enumMetadata)
 {
     Type type;
     EnumBuilder builder2;
     string enumFullName = GetEnumFullName(enumMetadata);
     if (enumMetadata.UnderlyingType != null)
     {
         type = (Type) LanguagePrimitives.ConvertTo(enumMetadata.UnderlyingType, typeof(Type), CultureInfo.InvariantCulture);
     }
     else
     {
         type = typeof(int);
     }
     ModuleBuilder builder = _moduleBuilder.Value;
     lock (_moduleBuilderUsageLock)
     {
         builder2 = builder.DefineEnum(enumFullName, TypeAttributes.Public, type);
     }
     if (enumMetadata.BitwiseFlagsSpecified && enumMetadata.BitwiseFlags)
     {
         CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(typeof(FlagsAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
         builder2.SetCustomAttribute(customBuilder);
     }
     foreach (EnumMetadataEnumValue value2 in enumMetadata.Value)
     {
         string name = value2.Name;
         object literalValue = LanguagePrimitives.ConvertTo(value2.Value, type, CultureInfo.InvariantCulture);
         builder2.DefineLiteral(name, literalValue);
     }
     builder2.CreateType();
 }
        /// <summary>
        /// Copies the EventSourceAttribute from the interfaceType to a CustomAttributeBuilder.
        /// </summary>
        /// <param name="type">The interfaceType to copy.</param>
        /// <returns>A CustomAttributeBuilder that can be assigned to a type.</returns>
        internal static CustomAttributeBuilder GetEventSourceAttributeBuilder(Type type)
        {
            var attribute = type.GetCustomAttribute<EventSourceAttribute>() ?? new EventSourceAttribute();
            var implementation = type.GetCustomAttribute<EventSourceImplementationAttribute>() ?? new EventSourceImplementationAttribute();

            // by default, we will use a null guid, which will tell EventSource to generate the guid from the name
            // but if we have already generated this type, we will have to generate a new one
            string guid = implementation.Guid ?? attribute.Guid ?? null;
            if (guid == null)
            {
                lock (_typesImplemented)
                {
                    if (_typesImplemented.Contains(type))
                        guid = Guid.NewGuid().ToString();
                    else
                        _typesImplemented.Add(type);
                }
            }

            var propertyValues = new object[]
            {
                implementation.Name ?? attribute.Name ?? (type.IsGenericType ? type.FullName : type.Name),
                guid,
                implementation.LocalizationResources ?? attribute.LocalizationResources ?? null
            };

            CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(
                _eventSourceAttributeConstructor,
                _emptyParameters,
                _eventSourceAttributePropertyInfo,
                propertyValues);

            return attributeBuilder;
        }
        public void PosTest1()
        {
            string testString1 = null;
            string testString2 = null;
            int testInt1 = 0;
            int testInt2 = 0;

            testString1 = "PosTest1_TestString1";
            testString2 = "PosTest1_TestString2";
            testInt1 = _generator.GetInt32();
            testInt2 = _generator.GetInt32();

            Type CustomAttributeBuilderTestType = typeof(CustomAttributeBuilderTest);

            Type[] ctorParams = new Type[]
            {
                typeof(string),
                typeof(int)
            };
            object[] constructorArgs = new object[]
            {
                testString1,
                testInt1
            };
            PropertyInfo[] namedProperty = new PropertyInfo[]
            {
                CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
                CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
            };
            object[] propertyValues = new object[]
            {
                testInt2,
                testString2
            };

            CustomAttributeBuilder cab = new CustomAttributeBuilder(
                CustomAttributeBuilderTestType.GetConstructor(ctorParams),
                constructorArgs,
                namedProperty,
                propertyValues);
            Assert.NotNull(cab);

            PropertyInfo[] verifyFields = new PropertyInfo[]
            {
                CustomAttributeBuilderTestType.GetProperty(PropertyTestInt32Name),
                CustomAttributeBuilderTestType.GetProperty(PropertyTestStringName),
                CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyStringName),
                CustomAttributeBuilderTestType.GetProperty(PropertyGetOnlyIntName)
            };
            object[] verifyFieldValues = new object[]
            {
                testInt2,
                testString2,
                testString1,
                testInt1
            };

            Assert.True(VerifyCustomAttribute(cab, CustomAttributeBuilderTestType, verifyFields, verifyFieldValues));
        }
 private AssemblyGen()
 {
     AssemblyName name = new AssemblyName("Snippets");
     CustomAttributeBuilder[] assemblyAttributes = new CustomAttributeBuilder[] { new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0]) };
     this._myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run, assemblyAttributes);
     this._myModule = this._myAssembly.DefineDynamicModule(name.Name, false);
     this._myAssembly.DefineVersionInfoResource();
 }
Beispiel #25
0
		// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
        /// <include file='doc\ParameterBuilder.uex' path='docs/doc[@for="ParameterBuilder.SetCustomAttribute1"]/*' />
        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
    			throw new ArgumentNullException("customBuilder");
            }
            customBuilder.CreateCustomAttribute((ModuleBuilder) (m_methodBuilder .GetModule()), m_pdToken.Token);
        }
 public DynamicProperty(string name, Type type, CustomAttributeBuilder attributeBuilder = null)
 {
     if (name == null) throw new ArgumentNullException("name");
     if (type == null) throw new ArgumentNullException("type");
     this.name = name;
     this.type = type;
     this.CustomAttributeBuilder = attributeBuilder;
 }
        public void PosTest1()
        {
            FieldBuilder field = TypeBuilder.DefineField("Field_PosTest1", typeof(object), FieldAttributes.Public);
            ConstructorInfo con = typeof(FBTestAttribute2).GetConstructor(new Type[] { });
            CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[] { });

            field.SetCustomAttribute(attribute);
        }
        public void PosTest1()
        {
            EventBuilder ev = TypeBuilder.DefineEvent("Event_PosTest1", EventAttributes.None, typeof(TestEventHandler));
            ConstructorInfo con = typeof(EvBMyAttribute2).GetConstructor(new Type[] { });
            CustomAttributeBuilder attribute = new CustomAttributeBuilder(con, new object[] { });

            ev.SetCustomAttribute(attribute);
        }
Beispiel #29
0
            public CustAttr(CustomAttributeBuilder customBuilder)
            {
                if (customBuilder == null)
                    throw new ArgumentNullException(nameof(customBuilder));
                Contract.EndContractBlock();

                m_customBuilder = customBuilder;
            }
        private static void AddEntityElementIdAnnotation(TypeBuilder typeBuilder, EntityElement entity)
        {
            var id = entity.Identity.Id.ToString();
            var constructor = typeof(EntityElementIdAttribute).GetConstructors().First();
            var customAttributeBuilder = new CustomAttributeBuilder(constructor, new object[] { id });

            typeBuilder.SetCustomAttribute(customAttributeBuilder);
        }
    public Object Register(string dllName, string strReturnType,
                           string methodName, string strInputParameterTypes, ref object objParameters)
    {
        //COM has no Type class, so do the necessary conversions
        Type returnType = Type.GetType(strReturnType);
        //Input Parameter Types
        int countOfInputParameters = (strInputParameterTypes.Length - 2);

        Type[] parameterTypes = new Type[countOfInputParameters];
        for (int i = 2, j = 0; i < strInputParameterTypes.Length; i++, j++)
        {
            parameterTypes[j] = ConvertStringNameToType(strInputParameterTypes[i]);
        }



        // Begin to build the dynamic assembly
        AppDomain       domain   = AppDomain.CurrentDomain;
        AssemblyName    name     = new System.Reflection.AssemblyName("PInvokeAssembly");
        AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
        ModuleBuilder   module   = assembly.DefineDynamicModule("PInvokeModule");
        TypeBuilder     type     = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);

        // Define the actual P/Invoke method
        MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes);

        // Apply the P/Invoke constructor
        ConstructorInfo        ctor = typeof(DllImportAttribute).GetConstructor(new Type [] { typeof(string) });
        CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName });

        method.SetCustomAttribute(attr);


        Object[] parameters = ConvertJsArray(objParameters);
        // Create the temporary type, and invoke the method.
        Type realType = type.CreateType();

        return(realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters));
    }
    static bool Regex_CompileToAssembly__RegexCompilationInfo_Array__AssemblyName__CustomAttributeBuilder_Array__String(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 4)
        {
            System.Text.RegularExpressions.RegexCompilationInfo[] arg0 = JSDataExchangeMgr.GetJSArg <System.Text.RegularExpressions.RegexCompilationInfo[]>(() =>
            {
                int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);
                int length  = JSApi.getArrayLength(jsObjID);
                var ret     = new System.Text.RegularExpressions.RegexCompilationInfo[length];
                for (var i = 0; i < length; i++)
                {
                    JSApi.getElement(jsObjID, i);
                    ret[i] = (System.Text.RegularExpressions.RegexCompilationInfo)JSMgr.datax.getObject((int)JSApi.GetType.SaveAndRemove);
                }
                return(ret);
            });
            System.Reflection.AssemblyName arg1 = (System.Reflection.AssemblyName)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            System.Reflection.Emit.CustomAttributeBuilder[] arg2 = JSDataExchangeMgr.GetJSArg <System.Reflection.Emit.CustomAttributeBuilder[]>(() =>
            {
                int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);
                int length  = JSApi.getArrayLength(jsObjID);
                var ret     = new System.Reflection.Emit.CustomAttributeBuilder[length];
                for (var i = 0; i < length; i++)
                {
                    JSApi.getElement(jsObjID, i);
                    ret[i] = (System.Reflection.Emit.CustomAttributeBuilder)JSMgr.datax.getObject((int)JSApi.GetType.SaveAndRemove);
                }
                return(ret);
            });
            System.String arg3 = (System.String)JSApi.getStringS((int)JSApi.GetType.Arg);
            System.Text.RegularExpressions.Regex.CompileToAssembly(arg0, arg1, arg2, arg3);
        }

        return(true);
    }
    public Object InvokeWin32(string dllName, Type returnType,
                              string methodName, Type[] parameterTypes, Object[] parameters)
    {
        // Begin to build the dynamic assembly
        AppDomain       domain   = AppDomain.CurrentDomain;
        AssemblyName    name     = new System.Reflection.AssemblyName("PInvokeAssembly");
        AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
        ModuleBuilder   module   = assembly.DefineDynamicModule("PInvokeModule");
        TypeBuilder     type     = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);

        // Define the actual P/Invoke method
        MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes);

        // Apply the P/Invoke constructor
        ConstructorInfo        ctor = typeof(DllImportAttribute).GetConstructor(new Type [] { typeof(string) });
        CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName });

        method.SetCustomAttribute(attr);

        // Create the temporary type, and invoke the method.
        Type realType = type.CreateType();

        return(realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters));
    }
Beispiel #34
0
        /// <summary>
        /// Generate the declaration for the IgnoresAccessChecksToAttribute type.
        /// This attribute will be both defined and used in the dynamic assembly.
        /// Each usage identifies the name of the assembly containing non-public
        /// types the dynamic assembly needs to access.  Normally those types
        /// would be inaccessible, but this attribute allows them to be visible.
        /// It works like a reverse InternalsVisibleToAttribute.
        /// This method returns the ConstructorInfo of the generated attribute.
        /// </summary>
        public static ConstructorInfo AddToModule(ModuleBuilder mb)
        {
            TypeBuilder attributeTypeBuilder =
                mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
                              TypeAttributes.Public | TypeAttributes.Class,
                              typeof(Attribute));

            // Create backing field as:
            // private string assemblyName;
            FieldBuilder assemblyNameField =
                attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private);

            // Create ctor as:
            // public IgnoresAccessChecksToAttribute(string)
            ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public,
                                                                                           CallingConventions.HasThis,
                                                                                           new Type[] { assemblyNameField.FieldType });

            ILGenerator il = constructorBuilder.GetILGenerator();

            // Create ctor body as:
            // this.assemblyName = {ctor parameter 0}
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg, 1);
            il.Emit(OpCodes.Stfld, assemblyNameField);

            // return
            il.Emit(OpCodes.Ret);

            // Define property as:
            // public string AssemblyName {get { return this.assemblyName; } }
            _ = attributeTypeBuilder.DefineProperty(
                "AssemblyName",
                PropertyAttributes.None,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod(
                "get_AssemblyName",
                MethodAttributes.Public,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            // Generate body:
            // return this.assemblyName;
            il = getterMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, assemblyNameField);
            il.Emit(OpCodes.Ret);

            // Generate the AttributeUsage attribute for this attribute type:
            // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
            TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo();

            // Find the ctor that takes only AttributeTargets
            ConstructorInfo attributeUsageConstructorInfo =
                attributeUsageTypeInfo.DeclaredConstructors
                .Single(c => c.GetParameters().Length == 1 &&
                        c.GetParameters()[0].ParameterType == typeof(AttributeTargets));

            // Find the property to set AllowMultiple
            PropertyInfo allowMultipleProperty =
                attributeUsageTypeInfo.DeclaredProperties
                .Single(f => string.Equals(f.Name, "AllowMultiple"));

            // Create a builder to construct the instance via the ctor and property
            CustomAttributeBuilder customAttributeBuilder =
                new CustomAttributeBuilder(attributeUsageConstructorInfo,
                                           new object[] { AttributeTargets.Assembly },
                                           new PropertyInfo[] { allowMultipleProperty },
                                           new object[] { true });

            // Attach this attribute instance to the newly defined attribute type
            attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder);

            // Make the TypeInfo real so the constructor can be used.
            return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single());
        }
Beispiel #35
0
 public void SetCustomAttribute(CustomAttributeBuilder !customBuilder)
 {
     CodeContract.Requires(customBuilder != null);
 }
Beispiel #36
0
        private void Initialize(ConstructorInfo con, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues)
        {
            this.ctor = con;
            if (con == null)
            {
                throw new ArgumentNullException("con");
            }
            if (constructorArgs == null)
            {
                throw new ArgumentNullException("constructorArgs");
            }
            if (namedProperties == null)
            {
                throw new ArgumentNullException("namedProperties");
            }
            if (propertyValues == null)
            {
                throw new ArgumentNullException("propertyValues");
            }
            if (namedFields == null)
            {
                throw new ArgumentNullException("namedFields");
            }
            if (fieldValues == null)
            {
                throw new ArgumentNullException("fieldValues");
            }
            if (con.GetParameterCount() != constructorArgs.Length)
            {
                throw new ArgumentException("Parameter count does not match passed in argument value count.");
            }
            if (namedProperties.Length != propertyValues.Length)
            {
                throw new ArgumentException("Array lengths must be the same.", "namedProperties, propertyValues");
            }
            if (namedFields.Length != fieldValues.Length)
            {
                throw new ArgumentException("Array lengths must be the same.", "namedFields, fieldValues");
            }
            if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
            {
                throw new ArgumentException("Cannot have private or static constructor.");
            }
            Type declaringType = this.ctor.DeclaringType;
            int  num           = 0;

            foreach (FieldInfo fieldInfo in namedFields)
            {
                Type declaringType2 = fieldInfo.DeclaringType;
                if (!this.IsValidType(declaringType2))
                {
                    throw new ArgumentException("Field '" + fieldInfo.Name + "' does not have a valid type.");
                }
                if (declaringType != declaringType2 && !declaringType2.IsSubclassOf(declaringType) && !declaringType.IsSubclassOf(declaringType2))
                {
                    throw new ArgumentException("Field '" + fieldInfo.Name + "' does not belong to the same class as the constructor");
                }
                if (fieldValues[num] != null && !(fieldInfo.FieldType is TypeBuilder) && !fieldInfo.FieldType.IsEnum && !fieldInfo.FieldType.IsInstanceOfType(fieldValues[num]) && !fieldInfo.FieldType.IsArray)
                {
                    throw new ArgumentException(string.Concat(new object[]
                    {
                        "Value of field '",
                        fieldInfo.Name,
                        "' does not match field type: ",
                        fieldInfo.FieldType
                    }));
                }
                num++;
            }
            num = 0;
            foreach (PropertyInfo propertyInfo in namedProperties)
            {
                if (!propertyInfo.CanWrite)
                {
                    throw new ArgumentException("Property '" + propertyInfo.Name + "' does not have a setter.");
                }
                Type declaringType3 = propertyInfo.DeclaringType;
                if (!this.IsValidType(declaringType3))
                {
                    throw new ArgumentException("Property '" + propertyInfo.Name + "' does not have a valid type.");
                }
                if (declaringType != declaringType3 && !declaringType3.IsSubclassOf(declaringType) && !declaringType.IsSubclassOf(declaringType3))
                {
                    throw new ArgumentException("Property '" + propertyInfo.Name + "' does not belong to the same class as the constructor");
                }
                if (propertyValues[num] != null && !(propertyInfo.PropertyType is TypeBuilder) && !propertyInfo.PropertyType.IsEnum && !propertyInfo.PropertyType.IsInstanceOfType(propertyValues[num]) && !propertyInfo.PropertyType.IsArray)
                {
                    throw new ArgumentException(string.Concat(new object[]
                    {
                        "Value of property '",
                        propertyInfo.Name,
                        "' does not match property type: ",
                        propertyInfo.PropertyType,
                        " -> ",
                        propertyValues[num]
                    }));
                }
                num++;
            }
            num = 0;
            foreach (ParameterInfo parameterInfo in CustomAttributeBuilder.GetParameters(con))
            {
                if (parameterInfo != null)
                {
                    Type parameterType = parameterInfo.ParameterType;
                    if (!this.IsValidType(parameterType))
                    {
                        throw new ArgumentException("Argument " + num + " does not have a valid type.");
                    }
                    if (constructorArgs[num] != null && !(parameterType is TypeBuilder) && !parameterType.IsEnum && !parameterType.IsInstanceOfType(constructorArgs[num]) && !parameterType.IsArray)
                    {
                        throw new ArgumentException(string.Concat(new object[]
                        {
                            "Value of argument ",
                            num,
                            " does not match parameter type: ",
                            parameterType,
                            " -> ",
                            constructorArgs[num]
                        }));
                    }
                }
                num++;
            }
            this.data = CustomAttributeBuilder.GetBlob(declaringType.Assembly, con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues);
        }
Beispiel #37
0
        internal static UnmanagedMarshal get_umarshal(CustomAttributeBuilder customBuilder, bool is_field)
        {
            byte[]        array          = customBuilder.Data;
            UnmanagedType elemType       = (UnmanagedType)80;
            int           num            = -1;
            int           sizeParamIndex = -1;
            bool          flag           = false;
            string        text           = null;
            Type          typeref        = null;
            string        cookie         = string.Empty;
            int           num2           = (int)array[2];

            num2 |= (int)array[3] << 8;
            string fullName = CustomAttributeBuilder.GetParameters(customBuilder.Ctor)[0].ParameterType.FullName;
            int    num3     = 6;

            if (fullName == "System.Int16")
            {
                num3 = 4;
            }
            int num4 = (int)array[num3++];

            num4 |= (int)array[num3++] << 8;
            int i = 0;

            while (i < num4)
            {
                num3++;
                int num5 = (int)array[num3++];
                if (num5 == 85)
                {
                    int num6 = CustomAttributeBuilder.decode_len(array, num3, out num3);
                    CustomAttributeBuilder.string_from_bytes(array, num3, num6);
                    num3 += num6;
                }
                int    num7  = CustomAttributeBuilder.decode_len(array, num3, out num3);
                string text2 = CustomAttributeBuilder.string_from_bytes(array, num3, num7);
                num3 += num7;
                string text3 = text2;
                if (text3 != null)
                {
                    if (CustomAttributeBuilder.< > f__switch$map1C == null)
                    {
                        CustomAttributeBuilder.< > f__switch$map1C = new Dictionary <string, int>(9)
                        {
                            {
                                "ArraySubType",
                                0
                            },
                            {
                                "SizeConst",
                                1
                            },
                            {
                                "SafeArraySubType",
                                2
                            },
                            {
                                "IidParameterIndex",
                                3
                            },
                            {
                                "SafeArrayUserDefinedSubType",
                                4
                            },
                            {
                                "SizeParamIndex",
                                5
                            },
                            {
                                "MarshalType",
                                6
                            },
                            {
                                "MarshalTypeRef",
                                7
                            },
                            {
                                "MarshalCookie",
                                8
                            }
                        };
                    }
                    int num8;
                    if (CustomAttributeBuilder.< > f__switch$map1C.TryGetValue(text3, out num8))
                    {
                        switch (num8)
                        {
                        case 0:
                        {
                            int num9 = (int)array[num3++];
                            num9    |= (int)array[num3++] << 8;
                            num9    |= (int)array[num3++] << 16;
                            num9    |= (int)array[num3++] << 24;
                            elemType = (UnmanagedType)num9;
                            break;
                        }

                        case 1:
                        {
                            int num9 = (int)array[num3++];
                            num9 |= (int)array[num3++] << 8;
                            num9 |= (int)array[num3++] << 16;
                            num9 |= (int)array[num3++] << 24;
                            num   = num9;
                            flag  = true;
                            break;
                        }

                        case 2:
                        {
                            int num9 = (int)array[num3++];
                            num9    |= (int)array[num3++] << 8;
                            num9    |= (int)array[num3++] << 16;
                            num9    |= (int)array[num3++] << 24;
                            elemType = (UnmanagedType)num9;
                            break;
                        }

                        case 3:
                            num3 += 4;
                            break;

                        case 4:
                            num7 = CustomAttributeBuilder.decode_len(array, num3, out num3);
                            CustomAttributeBuilder.string_from_bytes(array, num3, num7);
                            num3 += num7;
                            break;

                        case 5:
                        {
                            int num9 = (int)array[num3++];
                            num9          |= (int)array[num3++] << 8;
                            sizeParamIndex = num9;
                            flag           = true;
                            break;
                        }

                        case 6:
                            num7  = CustomAttributeBuilder.decode_len(array, num3, out num3);
                            text  = CustomAttributeBuilder.string_from_bytes(array, num3, num7);
                            num3 += num7;
                            break;

                        case 7:
                            num7    = CustomAttributeBuilder.decode_len(array, num3, out num3);
                            text    = CustomAttributeBuilder.string_from_bytes(array, num3, num7);
                            typeref = Type.GetType(text);
                            num3   += num7;
                            break;

                        case 8:
                            num7   = CustomAttributeBuilder.decode_len(array, num3, out num3);
                            cookie = CustomAttributeBuilder.string_from_bytes(array, num3, num7);
                            num3  += num7;
                            break;

                        default:
                            goto IL_34F;
                        }
                        i++;
                        continue;
                    }
                }
IL_34F:
                throw new Exception("Unknown MarshalAsAttribute field: " + text2);
            }
            UnmanagedType unmanagedType = (UnmanagedType)num2;

            switch (unmanagedType)
            {
            case UnmanagedType.LPArray:
                if (flag)
                {
                    return(UnmanagedMarshal.DefineLPArrayInternal(elemType, num, sizeParamIndex));
                }
                return(UnmanagedMarshal.DefineLPArray(elemType));

            default:
                if (unmanagedType == UnmanagedType.SafeArray)
                {
                    return(UnmanagedMarshal.DefineSafeArray(elemType));
                }
                if (unmanagedType != UnmanagedType.ByValArray)
                {
                    if (unmanagedType != UnmanagedType.ByValTStr)
                    {
                        return(UnmanagedMarshal.DefineUnmanagedMarshal((UnmanagedType)num2));
                    }
                    return(UnmanagedMarshal.DefineByValTStr(num));
                }
                else
                {
                    if (!is_field)
                    {
                        throw new ArgumentException("Specified unmanaged type is only valid on fields");
                    }
                    return(UnmanagedMarshal.DefineByValArray(num));
                }
                break;

            case UnmanagedType.CustomMarshaler:
                return(UnmanagedMarshal.DefineCustom(typeref, cookie, text, Guid.Empty));
            }
        }
Beispiel #38
0
        internal static CustomAttributeBuilder.CustomAttributeInfo decode_cattr(CustomAttributeBuilder customBuilder)
        {
            byte[]          array           = customBuilder.Data;
            ConstructorInfo constructorInfo = customBuilder.Ctor;
            int             num             = 0;

            CustomAttributeBuilder.CustomAttributeInfo result = default(CustomAttributeBuilder.CustomAttributeInfo);
            if (array.Length < 2)
            {
                throw new Exception("Custom attr length is only '" + array.Length + "'");
            }
            if (array[0] != 1 || array[1] != 0)
            {
                throw new Exception("Prolog invalid");
            }
            num = 2;
            ParameterInfo[] parameters = CustomAttributeBuilder.GetParameters(constructorInfo);
            result.ctor     = constructorInfo;
            result.ctorArgs = new object[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                result.ctorArgs[i] = CustomAttributeBuilder.decode_cattr_value(parameters[i].ParameterType, array, num, out num);
            }
            int num2 = (int)array[num] + (int)array[num + 1] * 256;

            num += 2;
            result.namedParamNames  = new string[num2];
            result.namedParamValues = new object[num2];
            for (int j = 0; j < num2; j++)
            {
                int    num3 = (int)array[num++];
                int    num4 = (int)array[num++];
                string text = null;
                if (num4 == 85)
                {
                    int num5 = CustomAttributeBuilder.decode_len(array, num, out num);
                    text = CustomAttributeBuilder.string_from_bytes(array, num, num5);
                    num += num5;
                }
                int    num6  = CustomAttributeBuilder.decode_len(array, num, out num);
                string text2 = CustomAttributeBuilder.string_from_bytes(array, num, num6);
                result.namedParamNames[j] = text2;
                num += num6;
                if (num3 != 83)
                {
                    throw new Exception("Unknown named type: " + num3);
                }
                FieldInfo field = constructorInfo.DeclaringType.GetField(text2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (field == null)
                {
                    throw new Exception(string.Concat(new object[]
                    {
                        "Custom attribute type '",
                        constructorInfo.DeclaringType,
                        "' doesn't contain a field named '",
                        text2,
                        "'"
                    }));
                }
                object obj = CustomAttributeBuilder.decode_cattr_value(field.FieldType, array, num, out num);
                if (text != null)
                {
                    Type type = Type.GetType(text);
                    obj = Enum.ToObject(type, obj);
                }
                result.namedParamValues[j] = obj;
            }
            return(result);
        }
Beispiel #39
0
        unsafe static void Main(string[] args)
        {
            Console.WriteLine("[*] Searching the Vaults...");
            var OSVersion = Environment.OSVersion.Version;
            var OSMajor   = OSVersion.Major;
            var OSMinor   = OSVersion.Minor;

            /* Begin PInvoke Region */
            var DynAssembly     = new System.Reflection.AssemblyName("VaultUtil");
            var AssemblyBuilder = System.AppDomain.CurrentDomain.DefineDynamicAssembly(DynAssembly, System.Reflection.Emit.AssemblyBuilderAccess.Run);
            var ModuleBuilder   = AssemblyBuilder.DefineDynamicModule("VaultUtil", false);

            var EnumBuilder = ModuleBuilder.DefineEnum("VaultLib.VAULT_ELEMENT_TYPE", TypeAttributes.Public, typeof(Int32));

            EnumBuilder.DefineLiteral("Undefined", -1);
            EnumBuilder.DefineLiteral("Boolean", 0);
            EnumBuilder.DefineLiteral("Short", 1);
            EnumBuilder.DefineLiteral("UnsignedShort", 2);
            EnumBuilder.DefineLiteral("Int", 3);
            EnumBuilder.DefineLiteral("UnsignedInt", 4);
            EnumBuilder.DefineLiteral("Double", 5);
            EnumBuilder.DefineLiteral("Guid", 6);
            EnumBuilder.DefineLiteral("String", 7);
            EnumBuilder.DefineLiteral("ByteArray", 8);
            EnumBuilder.DefineLiteral("TimeStamp", 9);
            EnumBuilder.DefineLiteral("ProtectedArray", 10);
            EnumBuilder.DefineLiteral("Attribute", 11);
            EnumBuilder.DefineLiteral("Sid", 12);
            EnumBuilder.DefineLiteral("Last", 13);
            var VAULT_ELEMENT_TYPE = EnumBuilder.CreateType();

            EnumBuilder = ModuleBuilder.DefineEnum("VaultLib.VAULT_SCHEMA_ELEMENT_ID", TypeAttributes.Public, typeof(Int32));
            EnumBuilder.DefineLiteral("Illegal", 0);
            EnumBuilder.DefineLiteral("Resource", 1);
            EnumBuilder.DefineLiteral("Identity", 2);
            EnumBuilder.DefineLiteral("Authenticator", 3);
            EnumBuilder.DefineLiteral("Tag", 4);
            EnumBuilder.DefineLiteral("PackageSid", 5);
            EnumBuilder.DefineLiteral("AppStart", 100);
            EnumBuilder.DefineLiteral("AppEnd", 10000);
            var VAULT_SCHEMA_ELEMENT_ID = EnumBuilder.CreateType();

            Type[]          LayoutConstructorArgs = new Type[] { typeof(System.Runtime.InteropServices.LayoutKind) };
            ConstructorInfo LayoutConstructor     = typeof(System.Runtime.InteropServices.StructLayoutAttribute).GetConstructor(LayoutConstructorArgs);
            var             CharsetField          = typeof(System.Runtime.InteropServices.StructLayoutAttribute).GetField("CharSet");

            Object[]    ConstructorArgs             = new Object[] { System.Runtime.InteropServices.LayoutKind.Explicit };
            FieldInfo[] FieldInfoArgs               = new FieldInfo[] { CharsetField };
            Object[]    FieldValueArgs              = new Object[] { System.Runtime.InteropServices.CharSet.Ansi };
            var         StructLayoutCustomAttribute = new System.Reflection.Emit.CustomAttributeBuilder(
                LayoutConstructor,
                ConstructorArgs,
                FieldInfoArgs,
                FieldValueArgs
                );

            // VAULT_ITEM
            var TypeBuilder = ModuleBuilder.DefineType(
                "VaultLib.VAULT_ITEM",
                TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.SequentialLayout | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                typeof(Object),
                (int)System.Reflection.Emit.PackingSize.Size4
                );

            TypeBuilder.DefineField("SchemaId", typeof(System.Guid), FieldAttributes.Public);
            TypeBuilder.DefineField("pszCredentialFriendlyName", typeof(System.IntPtr), FieldAttributes.Public);
            TypeBuilder.DefineField("pResourceElement", typeof(IntPtr), FieldAttributes.Public);
            TypeBuilder.DefineField("pIdentityElement", typeof(IntPtr), FieldAttributes.Public);
            TypeBuilder.DefineField("pAuthenticatorElement", typeof(IntPtr), FieldAttributes.Public);
            if (OSMajor >= 6 && OSMinor >= 2)
            {
                TypeBuilder.DefineField("pPackageSid", typeof(IntPtr), FieldAttributes.Public);
            }
            TypeBuilder.DefineField("LastModified", typeof(UInt64), FieldAttributes.Public);
            TypeBuilder.DefineField("dwFlags", typeof(UInt32), FieldAttributes.Public);
            TypeBuilder.DefineField("dwPropertiesCount", typeof(UInt32), FieldAttributes.Public);
            TypeBuilder.DefineField("pPropertyElements", typeof(IntPtr), FieldAttributes.Public);
            var VAULT_ITEM = TypeBuilder.CreateType();

            // VAULT_ITEM_ELEMENT
            TypeBuilder = ModuleBuilder.DefineType(
                "VaultLib.VAULT_ITEM_ELEMENT",
                TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.SequentialLayout | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
                typeof(object),
                (int)System.Reflection.Emit.PackingSize.Size4
                );
            TypeBuilder.SetCustomAttribute(StructLayoutCustomAttribute);
            TypeBuilder.DefineField("SchemaElementId", VAULT_SCHEMA_ELEMENT_ID, FieldAttributes.Public).SetOffset(0);
            TypeBuilder.DefineField("Type", VAULT_ELEMENT_TYPE, FieldAttributes.Public).SetOffset(8);
            var VAULT_ITEM_ELEMENT = TypeBuilder.CreateType();

            // Vaultcli
            TypeBuilder = ModuleBuilder.DefineType("VaultLib.Vaultcli", TypeAttributes.Public | TypeAttributes.Class);
            Type[] PInvokeTypeArgs = new Type[] { typeof(Guid *), typeof(UInt32), typeof(IntPtr *) };
            TypeBuilder.DefinePInvokeMethod(
                "VaultOpenVault",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );

            PInvokeTypeArgs = new Type[] { typeof(IntPtr *) };
            TypeBuilder.DefinePInvokeMethod(
                "VaultCloseVault",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );

            TypeBuilder.DefinePInvokeMethod(
                "VaultFree",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );

            PInvokeTypeArgs = new Type[] { typeof(Int32), typeof(Int32 *), typeof(IntPtr *) };
            TypeBuilder.DefinePInvokeMethod(
                "VaultEnumerateVaults",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );

            PInvokeTypeArgs = new Type[] { typeof(IntPtr), typeof(Int32), typeof(Int32 *), typeof(IntPtr *) };
            TypeBuilder.DefinePInvokeMethod(
                "VaultEnumerateItems",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );

            if (OSMajor >= 6 && OSMinor >= 2)
            {
                PInvokeTypeArgs = new Type[]
                {
                    typeof(IntPtr),
                    typeof(Guid *),
                    typeof(IntPtr),
                    typeof(IntPtr),
                    typeof(IntPtr),
                    typeof(IntPtr),
                    typeof(Int32),
                    typeof(IntPtr *)
                };
            }
            else
            {
                PInvokeTypeArgs = new Type[]
                {
                    typeof(IntPtr),
                    typeof(Guid *),
                    typeof(IntPtr),
                    typeof(IntPtr),
                    typeof(IntPtr),
                    typeof(Int32),
                    typeof(IntPtr *)
                };
            }
            TypeBuilder.DefinePInvokeMethod(
                "VaultGetItem",
                "vaultcli.dll",
                MethodAttributes.Public | MethodAttributes.Static,
                System.Reflection.CallingConventions.Standard,
                typeof(Int32),
                PInvokeTypeArgs,
                System.Runtime.InteropServices.CallingConvention.Winapi,
                System.Runtime.InteropServices.CharSet.Auto
                );
            /* Define the VaultCli and Methods we'll be calling */
            Type       VaultCli             = TypeBuilder.CreateType();
            MethodInfo VaultEnumerateVaults = VaultCli.GetMethod("VaultEnumerateVaults");
            MethodInfo VaultOpenVault       = VaultCli.GetMethod("VaultOpenVault");
            MethodInfo VaultEnumerateItems  = VaultCli.GetMethod("VaultEnumerateItems");
            MethodInfo VaultGetItem         = VaultCli.GetMethod("VaultGetItem");

            /* End PInvoke Region */

            /* Helper function to extract the ItemValue field from a VAULT_ITEM_ELEMENT struct */
            object GetVaultElementValue(IntPtr vaultElementPtr)
            {
                object    results;
                object    partialElement     = System.Runtime.InteropServices.Marshal.PtrToStructure(vaultElementPtr, VAULT_ITEM_ELEMENT);
                FieldInfo partialElementInfo = partialElement.GetType().GetField("Type");
                var       partialElementType = partialElementInfo.GetValue(partialElement);

                IntPtr elementPtr = (IntPtr)(vaultElementPtr.ToInt64() + 16);

                switch ((int)partialElementType)
                {
                case 7:     // VAULT_ELEMENT_TYPE == String; These are the plaintext passwords!
                    IntPtr StringPtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr);
                    results = System.Runtime.InteropServices.Marshal.PtrToStringUni(StringPtr);
                    break;

                case 0:     // VAULT_ELEMENT_TYPE == bool
                    results = System.Runtime.InteropServices.Marshal.ReadByte(elementPtr);
                    results = (bool)results;
                    break;

                case 1:     // VAULT_ELEMENT_TYPE == Short
                    results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr);
                    break;

                case 2:     // VAULT_ELEMENT_TYPE == Unsigned Short
                    results = System.Runtime.InteropServices.Marshal.ReadInt16(elementPtr);
                    break;

                case 3:     // VAULT_ELEMENT_TYPE == Int
                    results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr);
                    break;

                case 4:     // VAULT_ELEMENT_TYPE == Unsigned Int
                    results = System.Runtime.InteropServices.Marshal.ReadInt32(elementPtr);
                    break;

                case 5:     // VAULT_ELEMENT_TYPE == Double
                    results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Double));
                    break;

                case 6:     // VAULT_ELEMENT_TYPE == GUID
                    results = System.Runtime.InteropServices.Marshal.PtrToStructure(elementPtr, typeof(Guid));
                    break;

                case 12:     // VAULT_ELEMENT_TYPE == Sid
                    IntPtr sidPtr    = System.Runtime.InteropServices.Marshal.ReadIntPtr(elementPtr);
                    var    sidObject = new System.Security.Principal.SecurityIdentifier(sidPtr);
                    results = sidObject.Value;
                    break;

                default:
                    /* Several VAULT_ELEMENT_TYPES are currently unimplemented according to
                     * Lord Graeber. Thus we do not implement them. */
                    results = null;
                    break;
                }
                return(results);
            }

            /* End helper function */

            Int32  vaultCount         = 0;
            Int32 *vaultCountPtr      = &vaultCount;
            object boxedVaultCountPtr = Pointer.Box(vaultCountPtr, typeof(Int32 *));
            IntPtr vaultGuidPtr       = IntPtr.Zero;
            // Lord help me for this naming convention
            IntPtr *vaultGuidPtrPtr   = &vaultGuidPtr;
            object  boxedVaultGuidPtr = Pointer.Box(vaultGuidPtrPtr, typeof(IntPtr *));

            object[] vaultEnumVaultArgs = { 0, boxedVaultCountPtr, boxedVaultGuidPtr };
            var      result             = VaultEnumerateVaults.Invoke(null, vaultEnumVaultArgs);

            //var result = CallVaultEnumerateVaults(VaultEnum, 0, ref vaultCount, ref vaultGuidPtr);

            if ((int)result != 0)
            {
                throw new Exception("[ERROR] Unable to enumerate vaults. Error (0x" + result.ToString() + ")");
            }

            // Create dictionary to translate Guids to human readable elements
            IntPtr guidAddress = vaultGuidPtr;
            Dictionary <Guid, string> vaultSchema = new Dictionary <Guid, string>();

            vaultSchema.Add(new Guid("2F1A6504-0641-44CF-8BB5-3612D865F2E5"), "Windows Secure Note");
            vaultSchema.Add(new Guid("3CCD5499-87A8-4B10-A215-608888DD3B55"), "Windows Web Password Credential");
            vaultSchema.Add(new Guid("154E23D0-C644-4E6F-8CE6-5069272F999F"), "Windows Credential Picker Protector");
            vaultSchema.Add(new Guid("4BF4C442-9B8A-41A0-B380-DD4A704DDB28"), "Web Credentials");
            vaultSchema.Add(new Guid("77BC582B-F0A6-4E15-4E80-61736B6F3B29"), "Windows Credentials");
            vaultSchema.Add(new Guid("E69D7838-91B5-4FC9-89D5-230D4D4CC2BC"), "Windows Domain Certificate Credential");
            vaultSchema.Add(new Guid("3E0E35BE-1B77-43E7-B873-AED901B6275B"), "Windows Domain Password Credential");
            vaultSchema.Add(new Guid("3C886FF3-2669-4AA2-A8FB-3F6759A77548"), "Windows Extended Credential");
            vaultSchema.Add(new Guid("00000000-0000-0000-0000-000000000000"), null);

            for (int i = 0; i < vaultCount; i++)
            {
                // Open vault block
                object vaultGuidString = System.Runtime.InteropServices.Marshal.PtrToStructure(guidAddress, typeof(Guid));
                Guid   vaultGuid       = new Guid(vaultGuidString.ToString());
                Guid * tmpVaultGuidPtr = &vaultGuid;
                boxedVaultGuidPtr = Pointer.Box(tmpVaultGuidPtr, typeof(Guid *));
                guidAddress       = (IntPtr)(guidAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(typeof(Guid)));
                IntPtr  vaultHandle         = IntPtr.Zero;
                IntPtr *vaultHandlePtr      = &vaultHandle;
                object  boxedVaultHandlePtr = Pointer.Box(vaultHandlePtr, typeof(IntPtr *));
                string  vaultType;
                if (vaultSchema.ContainsKey(vaultGuid))
                {
                    vaultType = vaultSchema[vaultGuid];
                }
                else
                {
                    vaultType = vaultGuid.ToString();
                }
                object[] openVaultArgs = { boxedVaultGuidPtr, (UInt32)0, boxedVaultHandlePtr };
                result = VaultOpenVault.Invoke(null, openVaultArgs);
                if ((int)result != 0)
                {
                    throw new Exception("Unable to open the following vault: " + vaultType + ". Error: 0x" + result.ToString());
                }
                // Vault opened successfully! Continue.

                // Fetch all items within Vault
                int      vaultItemCount          = 0;
                int *    vaultItemCountPtr       = &vaultItemCount;
                object   boxedVaultItemCountPtr  = Pointer.Box(vaultItemCountPtr, typeof(int *));
                IntPtr   vaultItemPtr            = IntPtr.Zero;
                IntPtr * vaultItemPtrPtr         = &vaultItemPtr;
                object   boxedVaultItemPtr       = Pointer.Box(vaultItemPtrPtr, typeof(IntPtr *));
                object[] vaultEnumerateItemsArgs = { vaultHandle, 512, boxedVaultItemCountPtr, boxedVaultItemPtr };
                result = VaultEnumerateItems.Invoke(null, vaultEnumerateItemsArgs);
                if ((int)result != 0)
                {
                    throw new Exception("[ERROR] Unable to enumerate vault items from the following vault: " + vaultType + ". Error 0x" + result.ToString());
                }
                var structAddress = vaultItemPtr;
                if (vaultItemCount > 0)
                {
                    // For each vault item...
                    for (int j = 1; j <= vaultItemCount; j++)
                    {
                        // Begin fetching vault item...
                        var currentItem = System.Runtime.InteropServices.Marshal.PtrToStructure(structAddress, VAULT_ITEM);
                        structAddress = (IntPtr)(structAddress.ToInt64() + System.Runtime.InteropServices.Marshal.SizeOf(VAULT_ITEM));

                        IntPtr  passwordVaultItem     = IntPtr.Zero;
                        IntPtr *passwordVaultPtr      = &passwordVaultItem;
                        object  boxedPasswordVaultPtr = Pointer.Box(passwordVaultPtr, typeof(IntPtr *));
                        // Field Info retrieval
                        FieldInfo schemaIdInfo         = currentItem.GetType().GetField("SchemaId");
                        Guid      schemaId             = new Guid(schemaIdInfo.GetValue(currentItem).ToString());
                        Guid *    schemaIdPtr          = &schemaId;
                        object    boxedSchemaIdPtr     = Pointer.Box(schemaIdPtr, typeof(Guid *));
                        FieldInfo pResourceElementInfo = currentItem.GetType().GetField("pResourceElement");
                        IntPtr    pResourceElement     = (IntPtr)pResourceElementInfo.GetValue(currentItem);
                        FieldInfo pIdentityElementInfo = currentItem.GetType().GetField("pIdentityElement");
                        IntPtr    pIdentityElement     = (IntPtr)pIdentityElementInfo.GetValue(currentItem);
                        FieldInfo dateTimeInfo         = currentItem.GetType().GetField("LastModified");
                        UInt64    lastModified         = (UInt64)dateTimeInfo.GetValue(currentItem);

                        object[] vaultGetItemArgs;
                        if (OSMajor >= 6 && OSMinor >= 2)
                        {
                            vaultGetItemArgs    = new object[8];
                            vaultGetItemArgs[0] = vaultHandle;
                            vaultGetItemArgs[1] = boxedSchemaIdPtr;
                            vaultGetItemArgs[2] = pResourceElement;
                            vaultGetItemArgs[3] = pIdentityElement;
                            // Newer versions have package sid
                            FieldInfo pPackageSidInfo = currentItem.GetType().GetField("pPackageSid");
                            IntPtr    pPackageSid     = (IntPtr)pPackageSidInfo.GetValue(currentItem);
                            vaultGetItemArgs[4] = pPackageSid;
                            vaultGetItemArgs[5] = IntPtr.Zero;
                            vaultGetItemArgs[6] = 0;
                            vaultGetItemArgs[7] = boxedPasswordVaultPtr;
                        }
                        else
                        {
                            vaultGetItemArgs    = new object[7];
                            vaultGetItemArgs[0] = vaultHandle;
                            vaultGetItemArgs[1] = boxedSchemaIdPtr;
                            vaultGetItemArgs[2] = pResourceElement;
                            vaultGetItemArgs[3] = pIdentityElement;
                            vaultGetItemArgs[4] = IntPtr.Zero;
                            vaultGetItemArgs[5] = 0;
                            vaultGetItemArgs[6] = boxedPasswordVaultPtr;
                        }
                        // Where the actual fetching happens
                        result = VaultGetItem.Invoke(null, vaultGetItemArgs);
                        if ((int)result != 0)
                        {
                            throw new Exception("Error occured while retrieving vault item. Error: 0x" + result.ToString());
                        }
                        object    passwordItem = System.Runtime.InteropServices.Marshal.PtrToStructure(passwordVaultItem, VAULT_ITEM);
                        FieldInfo pAuthenticatorElementInfo = passwordItem.GetType().GetField("pAuthenticatorElement");
                        IntPtr    pAuthenticatorElement     = (IntPtr)pAuthenticatorElementInfo.GetValue(passwordItem);
                        // Fetch the credential from the authenticator element
                        object cred       = GetVaultElementValue(pAuthenticatorElement);
                        object packageSid = null;
                        if (vaultGetItemArgs.Length == 8 && (IntPtr)vaultGetItemArgs[4] != IntPtr.Zero)
                        {
                            packageSid = GetVaultElementValue((IntPtr)vaultGetItemArgs[4]);
                        }
                        if (cred != null) // Indicates successful fetch
                        {
                            Console.WriteLine("--- Result ---");
                            Console.WriteLine("Vault Type   : {0}", vaultType);
                            object resource = GetVaultElementValue(pResourceElement);
                            if (resource != null)
                            {
                                Console.WriteLine("Resource     : {0}", resource);
                            }
                            object identity = GetVaultElementValue(pIdentityElement);
                            if (identity != null)
                            {
                                Console.WriteLine("Identity     : {0}", identity);
                            }
                            if (packageSid != null)
                            {
                                Console.WriteLine("PacakgeSid  : {0}", packageSid);
                            }
                            Console.WriteLine("Credential   : {0}", cred);
                            // Stupid datetime
                            Console.WriteLine("LastModified : {0}", System.DateTime.FromFileTimeUtc((long)lastModified));
                        }
                    }
                }
            }
            Console.WriteLine("[*] All vaults searched. Exiting.");
        }
Beispiel #40
0
 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
 {
     m_type.SetGenParamCustomAttribute(customBuilder);
 }
 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
 {
     _tb.SetCustomAttribute(customBuilder);
 }
Beispiel #42
0
 private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
 {
     customBuilder.CreateCustomAttribute(_manifestModuleBuilder, AssemblyBuilderData.AssemblyDefToken);
 }
Beispiel #43
0
        internal static UnmanagedMarshal get_umarshal(CustomAttributeBuilder customBuilder, bool is_field)
        {
            byte[]        data           = customBuilder.Data;
            UnmanagedType subtype        = (UnmanagedType)0x50;      /* NATIVE_MAX */
            int           sizeConst      = -1;
            int           sizeParamIndex = -1;
            bool          hasSize        = false;
            int           value;
            int           utype;   /* the (stupid) ctor takes a short or an enum ... */
            string        marshalTypeName = null;
            Type          marshalTypeRef  = null;
            string        marshalCookie   = String.Empty;

            utype  = (int)data [2];
            utype |= ((int)data [3]) << 8;

            string first_type_name = GetParameters(customBuilder.Ctor) [0].ParameterType.FullName;
            int    pos             = 6;

            if (first_type_name == "System.Int16")
            {
                pos = 4;
            }
            int nnamed = (int)data [pos++];

            nnamed |= ((int)data [pos++]) << 8;

            for (int i = 0; i < nnamed; ++i)
            {
                int paramType;                 // What is this ?

                /* Skip field/property signature */
                pos++;
                /* Read type */
                paramType = ((int)data [pos++]);
                if (paramType == 0x55)
                {
                    /* enums, the value is preceeded by the type */
                    int len2 = decode_len(data, pos, out pos);
                    string_from_bytes(data, pos, len2);
                    pos += len2;
                }
                int    len        = decode_len(data, pos, out pos);
                string named_name = string_from_bytes(data, pos, len);
                pos += len;

                switch (named_name)
                {
                case "ArraySubType":
                    value   = (int)data [pos++];
                    value  |= ((int)data [pos++]) << 8;
                    value  |= ((int)data [pos++]) << 16;
                    value  |= ((int)data [pos++]) << 24;
                    subtype = (UnmanagedType)value;
                    break;

                case "SizeConst":
                    value     = (int)data [pos++];
                    value    |= ((int)data [pos++]) << 8;
                    value    |= ((int)data [pos++]) << 16;
                    value    |= ((int)data [pos++]) << 24;
                    sizeConst = value;
                    hasSize   = true;
                    break;

                case "SafeArraySubType":
                    value   = (int)data[pos++];
                    value  |= ((int)data[pos++]) << 8;
                    value  |= ((int)data[pos++]) << 16;
                    value  |= ((int)data[pos++]) << 24;
                    subtype = (UnmanagedType)value;
                    break;

                case "IidParameterIndex":
                    pos += 4;
                    break;

                case "SafeArrayUserDefinedSubType":
                    len = decode_len(data, pos, out pos);
                    string_from_bytes(data, pos, len);
                    pos += len;
                    break;

                case "SizeParamIndex":
                    value          = (int)data [pos++];
                    value         |= ((int)data [pos++]) << 8;
                    sizeParamIndex = value;
                    hasSize        = true;
                    break;

                case "MarshalType":
                    len             = decode_len(data, pos, out pos);
                    marshalTypeName = string_from_bytes(data, pos, len);
                    pos            += len;
                    break;

                case "MarshalTypeRef":
                    len             = decode_len(data, pos, out pos);
                    marshalTypeName = string_from_bytes(data, pos, len);
                    marshalTypeRef  = Type.GetType(marshalTypeName);
                    pos            += len;
                    break;

                case "MarshalCookie":
                    len           = decode_len(data, pos, out pos);
                    marshalCookie = string_from_bytes(data, pos, len);
                    pos          += len;
                    break;

                default:
                    throw new Exception("Unknown MarshalAsAttribute field: " + named_name);
                }
            }

            switch ((UnmanagedType)utype)
            {
            case UnmanagedType.LPArray:
                if (hasSize)
                {
                    return(UnmanagedMarshal.DefineLPArrayInternal(subtype, sizeConst, sizeParamIndex));
                }
                else
                {
                    return(UnmanagedMarshal.DefineLPArray(subtype));
                }

            case UnmanagedType.SafeArray:
                return(UnmanagedMarshal.DefineSafeArray(subtype));

            case UnmanagedType.ByValArray:
                if (!is_field)
                {
                    throw new ArgumentException("Specified unmanaged type is only valid on fields");
                }

                return(UnmanagedMarshal.DefineByValArray(sizeConst));

            case UnmanagedType.ByValTStr:
                return(UnmanagedMarshal.DefineByValTStr(sizeConst));

            case UnmanagedType.CustomMarshaler:
                return(UnmanagedMarshal.DefineCustom(marshalTypeRef, marshalCookie, marshalTypeName, Guid.Empty));

            default:
                return(UnmanagedMarshal.DefineUnmanagedMarshal((UnmanagedType)utype));
            }
        }
Beispiel #44
0
        internal static CustomAttributeInfo decode_cattr(CustomAttributeBuilder customBuilder)
        {
            byte[]          data = customBuilder.Data;
            ConstructorInfo ctor = customBuilder.Ctor;
            int             pos  = 0;

            CustomAttributeInfo info = new CustomAttributeInfo();

            // Prolog
            if (data.Length < 2)
            {
                throw new Exception("Custom attr length is only '" + data.Length + "'");
            }
            if ((data [0] != 0x1) || (data [1] != 0x00))
            {
                throw new Exception("Prolog invalid");
            }
            pos = 2;

            ParameterInfo [] pi = GetParameters(ctor);
            info.ctor     = ctor;
            info.ctorArgs = new object [pi.Length];
            for (int i = 0; i < pi.Length; ++i)
            {
                info.ctorArgs [i] = decode_cattr_value(pi [i].ParameterType, data, pos, out pos);
            }

            int num_named = data [pos] + (data [pos + 1] * 256);

            pos += 2;

            info.namedParamNames  = new string [num_named];
            info.namedParamValues = new object [num_named];
            for (int i = 0; i < num_named; ++i)
            {
                int    named_type     = data [pos++];
                int    data_type      = data [pos++];
                string enum_type_name = null;

                if (data_type == 0x55)
                {
                    int len2 = decode_len(data, pos, out pos);
                    enum_type_name = string_from_bytes(data, pos, len2);
                    pos           += len2;
                }

                int    len  = decode_len(data, pos, out pos);
                string name = string_from_bytes(data, pos, len);
                info.namedParamNames [i] = name;
                pos += len;

                if (named_type == 0x53)
                {
                    /* Field */
                    FieldInfo fi = ctor.DeclaringType.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                    if (fi == null)
                    {
                        throw new Exception("Custom attribute type '" + ctor.DeclaringType + "' doesn't contain a field named '" + name + "'");
                    }

                    object val = decode_cattr_value(fi.FieldType, data, pos, out pos);
                    if (enum_type_name != null)
                    {
                        Type enumType = Type.GetType(enum_type_name);
                        val = Enum.ToObject(enumType, val);
                    }

                    info.namedParamValues [i] = val;
                }
                else
                {
                    // FIXME:
                    throw new Exception("Unknown named type: " + named_type);
                }
            }

            return(info);
        }
Beispiel #45
0
 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
 {
     m_methodBuilder.SetCustomAttribute(customBuilder);
 }
Beispiel #46
0
        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
                throw new ArgumentNullException("customBuilder");
            }

            switch (customBuilder.Ctor.ReflectedType.FullName)
            {
            case "System.Runtime.CompilerServices.MethodImplAttribute":
                byte[] data = customBuilder.Data;
                int    impla;                      // the (stupid) ctor takes a short or an int ...
                impla   = (int)data [2];
                impla  |= ((int)data [3]) << 8;
                iattrs |= (MethodImplAttributes)impla;
                return;

            case "System.Runtime.InteropServices.DllImportAttribute":
                CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr(customBuilder);
                bool preserveSig = true;

                /*
                 * It would be easier to construct a DllImportAttribute from
                 * the custom attribute builder, but the DllImportAttribute
                 * does not contain all the information required here, ie.
                 * - some parameters, like BestFitMapping has three values
                 *   ("on", "off", "missing"), but DllImportAttribute only
                 *   contains two (on/off).
                 * - PreserveSig is true by default, while it is false by
                 *   default in DllImportAttribute.
                 */

                pi_dll = (string)attr.ctorArgs[0];
                if (pi_dll == null || pi_dll.Length == 0)
                {
                    throw new ArgumentException("DllName cannot be empty");
                }

                native_cc = System.Runtime.InteropServices.CallingConvention.Winapi;

                for (int i = 0; i < attr.namedParamNames.Length; ++i)
                {
                    string name  = attr.namedParamNames [i];
                    object value = attr.namedParamValues [i];

                    if (name == "CallingConvention")
                    {
                        native_cc = (CallingConvention)value;
                    }
                    else if (name == "CharSet")
                    {
                        charset = (CharSet)value;
                    }
                    else if (name == "EntryPoint")
                    {
                        pi_entry = (string)value;
                    }
                    else if (name == "ExactSpelling")
                    {
                        ExactSpelling = (bool)value;
                    }
                    else if (name == "SetLastError")
                    {
                        SetLastError = (bool)value;
                    }
                    else if (name == "PreserveSig")
                    {
                        preserveSig = (bool)value;
                    }
                    else if (name == "BestFitMapping")
                    {
                        BestFitMapping = (bool)value;
                    }
                    else if (name == "ThrowOnUnmappableChar")
                    {
                        ThrowOnUnmappableChar = (bool)value;
                    }
                }

                attrs |= MethodAttributes.PinvokeImpl;
                if (preserveSig)
                {
                    iattrs |= MethodImplAttributes.PreserveSig;
                }
                return;

            case "System.Runtime.InteropServices.PreserveSigAttribute":
                iattrs |= MethodImplAttributes.PreserveSig;
                return;

            case "System.Runtime.CompilerServices.SpecialNameAttribute":
                attrs |= MethodAttributes.SpecialName;
                return;

            case "System.Security.SuppressUnmanagedCodeSecurityAttribute":
                attrs |= MethodAttributes.HasSecurity;
                break;
            }

            if (cattrs != null)
            {
                CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1];
                cattrs.CopyTo(new_array, 0);
                new_array [cattrs.Length] = customBuilder;
                cattrs = new_array;
            }
            else
            {
                cattrs     = new CustomAttributeBuilder [1];
                cattrs [0] = customBuilder;
            }
        }
Beispiel #47
0
 public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
 {
     throw new NotImplementedException();
 }