SetCustomAttribute() public method

public SetCustomAttribute ( System customBuilder ) : void
customBuilder System
return void
Esempio n. 1
0
        /**
         *
         */
        public void EmitDecls()
        {
            Manager.Solver.Enqueue(() =>
            {
                compile_all_tyinfos(false);
                foreach (var (attr, shouldEmit) in Manager.AttributeCompiler.GetCompiledAssemblyAttributes(
                    assembly_attributes))
                {
                    if (shouldEmit)
                    {
                        _assembly_builder.SetCustomAttribute(attr);
                    }
                }

                // emit debug attributes
                if (Manager.Options.EmitDebug)
                {
                    var attr = Manager.AttributeCompiler.MakeEmittedAttribute(SystemTypeCache.DebuggableAttribute,
                        new[] {SystemTypeCache.DebuggableAttribute_DebuggingModes},
                        DebuggableAttribute.DebuggingModes.DisableOptimizations |
                        DebuggableAttribute.DebuggingModes.Default);
                    _assembly_builder.SetCustomAttribute(attr);
                }

                // do not require string literals interning
                var attr2 = Manager.AttributeCompiler.MakeEmittedAttribute(
                    SystemTypeCache.CompilationRelaxationsAttribute, 8);
                _assembly_builder.SetCustomAttribute(attr2);

                // wrap non exception throws
                /* uncomment it after we get dependency upon mono 1.1.10, since mono 1.1.9.x do not support this attribute
                */
            });
        }
        static EmitInterfaceImplementorBase()
        {
            if (IsDirty && SaveCache)
            {
                AppDomain.CurrentDomain.ProcessExit += (sender, args) => AssemblyBuilder.Save(AsmFileName);
            } 
            
            ResolveMethodInfo = null;
            foreach (var methodInfo in typeof(AppScope).GetMethods())
            {
                if (methodInfo.Name == "Resolve" && methodInfo.IsGenericMethod)
                {
                    ResolveMethodInfo = methodInfo;
                    break;
                }
            }
            var idx = 0;
            foreach (var asmFileName in Directory.EnumerateFiles(".", AsmFileName + "*.dll"))
            {
                idx++;
                try
                {
                    var asm1 = Assembly.LoadFrom(asmFileName);
                    foreach (var type in asm1.GetTypes())
                    {
                        var iface = type.GetInterfaces().FirstOrDefault();
                        if (iface != null) Types[iface] = type;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            AsmFileName = string.Format("{0}.{1}.dll", AsmFileName, idx);
            AssemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(AsmFileName)
                {
                    Version = new Version(1, 0, 0, 0),
                    VersionCompatibility = AssemblyVersionCompatibility.SameMachine,
                }, AssemblyBuilderAccess.RunAndSave);
            //AssemblyBuilder.
            //AssemblyBuilder.DefineVersionInfoResource(AsmFileName, "1.0.0.0", "Zen", "(c) 2013 by FruT", "ZenCore");
            var verAttrType = typeof(AssemblyVersionAttribute); //("1.0.0.0")
            var verAttrCtor = verAttrType.GetConstructor(new[] { typeof(string) });
            var attrBuilder = new CustomAttributeBuilder(verAttrCtor, new object[] { "1.0.0.0" });
            AssemblyBuilder.SetCustomAttribute(attrBuilder);

            var fverAttrType = typeof(AssemblyVersionAttribute); //("1.0.0.0")
            var fverAttrCtor = fverAttrType.GetConstructor(new[] { typeof(string) });
            var fattrBuilder = new CustomAttributeBuilder(fverAttrCtor, new object[] { "1.0.0.0" });
            AssemblyBuilder.SetCustomAttribute(fattrBuilder);

            ModuleBuilder = AssemblyBuilder.DefineDynamicModule("EmitedImplementors", AsmFileName);
        }
		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;
		}
Esempio n. 4
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);
            }
        }
Esempio n. 5
0
 public Emitter(EmitterOptions options)
 {
     _options = options;
     _assemblyName = new AssemblyName(_options.AssemblyName);
     _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);// TODO: temp for debugging .RunAndCollect);
     if (_options.DebugOn)
         _assembly.SetCustomAttribute
         (
             new CustomAttributeBuilder
             (
                 typeof(DebuggableAttribute).GetConstructor
                 (
                     new System.Type[] { typeof(DebuggableAttribute.DebuggingModes) }
                 ),
                 new object[]
                 {
                     DebuggableAttribute.DebuggingModes.DisableOptimizations |
                     DebuggableAttribute.DebuggingModes.Default
                 }
             )
         );
     _module = _assembly.DefineDynamicModule(_assemblyName.Name, _assemblyName.Name + ".dll", _options.DebugOn);
     if (_options.DebugOn)
         _symbolWriter = _module.DefineDocument(_options.SourceFileName, Guid.Empty, Guid.Empty, Guid.Empty);
     _tupleToNative = new Dictionary<Type.TupleType, System.Type>();
 }
 private static void AddDebuggingAttribute(AssemblyBuilder assembly)
 {
     var debugAttribute = typeof(DebuggableAttribute);
     var debugConstructor = debugAttribute.GetConstructor(
         new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
     var debugBuilder = new CustomAttributeBuilder(
         debugConstructor, new object[] {
             DebuggableAttribute.DebuggingModes.DisableOptimizations |
             DebuggableAttribute.DebuggingModes.Default });
     assembly.SetCustomAttribute(debugBuilder);
 }
		public static void ApplyTo(AssemblyBuilder assemblyBuilder, Dictionary<CacheKey, string> mappings)
		{
			using (var stream = new MemoryStream())
			{
				var formatter = new BinaryFormatter();
				formatter.Serialize(stream, mappings);
				var bytes = stream.ToArray();
				var attributeBuilder = new CustomAttributeBuilder(constructor, new object[] { bytes });
				assemblyBuilder.SetCustomAttribute(attributeBuilder);
			}
		}
Esempio n. 8
0
        public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable <CustomAttributeBuilder>?assemblyAttributes)
        {
            AssemblyBuilder ab = DefineDynamicAssembly(name, access);

            if (assemblyAttributes != null)
            {
                foreach (CustomAttributeBuilder attr in assemblyAttributes)
                {
                    ab.SetCustomAttribute(attr);
                }
            }

            return(ab);
        }
Esempio n. 9
0
        setDebuggable(System.Reflection.Emit.AssemblyBuilder assemblyBuilder)
        {
            Type            daType = typeof(DebuggableAttribute);
            ConstructorInfo daCtor =
                daType.GetConstructor(new Type[] {
                typeof(DebuggableAttribute.DebuggingModes)
            });
            CustomAttributeBuilder daBuilder =
                new CustomAttributeBuilder(daCtor, new object[] {
                DebuggableAttribute.DebuggingModes.DisableOptimizations |
                DebuggableAttribute.DebuggingModes.Default
            });

            assemblyBuilder.SetCustomAttribute(daBuilder);
        }
Esempio n. 10
0
        private void EmitAttribute(AssemblyBuilder parent, CodeAttributeDeclaration attribute)
        {
            var type = (Type) attribute.AttributeType.UserData[Parser.RawData];
            var vals = new object[attribute.Arguments.Count];
            var args = new Type[vals.Length];

            for (int i = 0; i < vals.Length; i++)
            {
                vals[i] = ((CodePrimitiveExpression) attribute.Arguments[i].Value).Value;
                args[i] = vals[i].GetType();
            }

            var ctor = type.GetConstructor(args);
            var builder = new CustomAttributeBuilder(ctor, vals);
            parent.SetCustomAttribute(builder);
        }
Esempio n. 11
0
        public Emitter(EmitterOptions options)
        {
            _options = options;

            //// TODO: setup separate app domain with appropriate cache path, shadow copying etc.
            //var domainName = "plan" + DateTime.Now.Ticks.ToString();
            //var domain = AppDomain.CreateDomain(domainName);

            _assemblyName = new AssemblyName(_options.AssemblyName);
            _assembly =
                AppDomain.CurrentDomain.DefineDynamicAssembly
                (
                    _assemblyName,
                    _options.DebugOn ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.RunAndCollect
                );
            if (_options.DebugOn)
                _assembly.SetCustomAttribute
                (
                    new CustomAttributeBuilder
                    (
                        typeof(DebuggableAttribute).GetConstructor
                        (
                            new System.Type[] { typeof(DebuggableAttribute.DebuggingModes) }
                        ),
                        new object[]
                        {
                            DebuggableAttribute.DebuggingModes.DisableOptimizations |
                            DebuggableAttribute.DebuggingModes.Default
                        }
                    )
                );

            _module = _assembly.DefineDynamicModule(_assemblyName.Name, _assemblyName.Name + ".dll", _options.DebugOn);
            if (_options.DebugOn)
                _symbolWriter = _module.DefineDocument(_options.SourceFileName, Guid.Empty, Guid.Empty, Guid.Empty);
            _tupleToNative = new Dictionary<TupleType, System.Type>();
        }
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, Object typeLib)
        {
            Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
            ConstructorInfo TypeLibVerCons = typeof(TypeLibVersionAttribute).GetConstructor(aConsParams);

            // Get the typelib version
            int major;
            int minor;
            Marshal.GetTypeLibVersion((ITypeLib)typeLib, out major, out minor);
            
            // Create an instance of the custom attribute builder.
            Object[] aArgs = new Object[2] {major, minor};
            CustomAttributeBuilder TypeLibVerBuilder = new CustomAttributeBuilder(TypeLibVerCons, aArgs);

            // Set the attribute on the assembly builder.
            asmBldr.SetCustomAttribute(TypeLibVerBuilder);
        }
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
        {
            // Retrieve the ImportedFromTypeLibAttribute constructor.
            Type []aConsParams = new Type[1] {typeof(String)};
            ConstructorInfo ImpFromComAttrCons = typeof(ImportedFromTypeLibAttribute).GetConstructor(aConsParams);

            // Retrieve the name of the typelib.
            String strTypeLibName = Marshal.GetTypeLibName((ITypeLib)typeLib);

            // Create an instance of the custom attribute builder.
            Object[] aArgs = new Object[1] {strTypeLibName};
            CustomAttributeBuilder ImpFromComCABuilder = new CustomAttributeBuilder(ImpFromComAttrCons, aArgs);

            // Set the ImportedFromTypeLibAttribute on the assembly builder.
            asmBldr.SetCustomAttribute(ImpFromComCABuilder);
        }
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
        {
            // Retrieve the GuidAttribute constructor.
            Type []aConsParams = new Type[1] {typeof(String)};
            ConstructorInfo GuidAttrCons = typeof(GuidAttribute).GetConstructor(aConsParams);

            // Create an instance of the custom attribute builder.
            Object[] aArgs = new Object[1] {Marshal.GetTypeLibGuid((ITypeLib)typeLib).ToString()};
            CustomAttributeBuilder GuidCABuilder = new CustomAttributeBuilder(GuidAttrCons, aArgs);

            // Set the GuidAttribute on the assembly builder.
            asmBldr.SetCustomAttribute(GuidCABuilder);
        }
 /// <summary>
 /// Applies custom attributes to generated assembly.
 /// </summary>
 /// <param name="assembly">Dynamic assembly to apply attributes to.</param>
 private void ApplyAssemblyAttributes(AssemblyBuilder assembly)
 {
     assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(ApplicationNameAttribute), applicationName));
     assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(ApplicationActivationAttribute), activationMode));
     if (applicationId != null)
     {
         assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(ApplicationIDAttribute), applicationId));
     }
     if (description != null)
     {
         assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(DescriptionAttribute), description));
         assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(AssemblyDescriptionAttribute), description));
     }
     if (accessControl != null)
     {
         assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(accessControl));
     }
     if (applicationQueuing != null)
     {
         assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(applicationQueuing));
     }
     if (roles != null)
     {
         foreach (SecurityRoleAttribute role in roles)
         {
             assembly.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute(typeof(SecurityRoleAttribute),
                                                                               new object[] { role.Role }, role));
         }
     }
 }
	[Test] // DefineVersionInfoResource (String, String, String, String, String)
	public void TestDefineVersionInfoResource2_Culture_NotSupported ()
	{
		AssemblyName aname = new AssemblyName ();
		aname.CultureInfo = new CultureInfo ("nl-BE");
		aname.Name = "lib";
		aname.Version = new Version (3, 5, 7);

		AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
			aname, AssemblyBuilderAccess.RunAndSave,
			tempDir);

		// AssemblyCulture
		Type attrType = typeof (AssemblyCultureAttribute);
		ConstructorInfo ci = attrType.GetConstructor (new Type [] { typeof (String) });
		CustomAttributeBuilder cab = new CustomAttributeBuilder (
			ci, new object [1] { "doesnotexist" });
		ab.SetCustomAttribute (cab);

		ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");

		try {
			ab.Save ("lib.dll");
			Assert.Fail ("#A1");
		} catch (ArgumentException ex) {
			// Culture name doesnotexist is not supported
			Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
			Assert.IsNull (ex.InnerException, "#A3");
			Assert.IsNotNull (ex.Message, "#A4");
			Assert.IsTrue (ex.Message.IndexOf ("doesnotexist") != -1, "#A5");
			Assert.AreEqual ("name", ex.ParamName, "#A6");
		}

		ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname,
			AssemblyBuilderAccess.RunAndSave, tempDir);

		// AssemblyCulture
		attrType = typeof (AssemblyCultureAttribute);
		ci = attrType.GetConstructor (new Type [] { typeof (String) });
		cab = new CustomAttributeBuilder (ci, new object [1] { "neutral" });
		ab.SetCustomAttribute (cab);

		ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");

		try {
			ab.Save ("lib.dll");
			Assert.Fail ("#B1");
		} catch (ArgumentException ex) {
			// Culture name neutral is not supported
			Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
			Assert.IsNull (ex.InnerException, "#B3");
			Assert.IsNotNull (ex.Message, "#B4");
			Assert.IsTrue (ex.Message.IndexOf ("neutral") != -1, "#B5");
			Assert.AreEqual ("name", ex.ParamName, "#B6");
		}
	}
Esempio n. 17
0
 // Make this assembly fully debuggable.
 void AddDebuggable(AssemblyBuilder ab)
 {
     Type type = typeof(DebuggableAttribute);
     ConstructorInfo ctor = type.GetConstructor(new [] { typeof(DebuggableAttribute.DebuggingModes) } );
     CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(ctor, new object[] {
                                                 DebuggableAttribute.DebuggingModes.DisableOptimizations |
                                                 DebuggableAttribute.DebuggingModes.Default });
     ab.SetCustomAttribute(caBuilder);
 }
Esempio n. 18
0
        void SetUpAssembly()
        {
            var outputFile = BuildOutputAssemblyName();
            var asmName = CreateAssemblyName(outputFile);
            var assemblyBuilderAccess = GetAssemblyBuilderAccess();
            var targetDirectory = GetTargetDirectory(outputFile);
            _asmBuilder = string.IsNullOrEmpty(targetDirectory)
                ? AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, assemblyBuilderAccess)
                : AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, assemblyBuilderAccess, targetDirectory);

            if (Parameters.Debug)
            {
                // ikvm tip:  Set DebuggableAttribute to assembly before
                // creating the module, to make sure Visual Studio (Whidbey)
                // picks up the attribute when debugging dynamically generated code.
                _asmBuilder.SetCustomAttribute(CreateDebuggableAttribute());
            }

            _asmBuilder.SetCustomAttribute(CreateRuntimeCompatibilityAttribute());
            _moduleBuilder = _asmBuilder.DefineDynamicModule(asmName.Name, Path.GetFileName(outputFile), Parameters.Debug);

            if (Parameters.Unsafe)
            {
                _asmBuilder.SetCustomAttribute(CreateSecurityPermissionAttribute("SkipVerification"));
                _moduleBuilder.SetCustomAttribute(CreateUnverifiableCodeAttribute());
            }

            _sreResourceService = new SREResourceService (_asmBuilder, _moduleBuilder);
            ContextAnnotations.SetAssemblyBuilder(Context, _asmBuilder);

            Context.GeneratedAssemblyFileName = outputFile;
        }
Esempio n. 19
0
 internal AssemblyBuilder InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes)
 {
     lock (typeof(AssemblyBuilderLock))
     {
         AssemblyBuilder builder2;
         if (name == null)
         {
             throw new ArgumentNullException("name");
         }
         if (((access != AssemblyBuilderAccess.Run) && (access != AssemblyBuilderAccess.Save)) && ((access != AssemblyBuilderAccess.RunAndSave) && (access != AssemblyBuilderAccess.ReflectionOnly)))
         {
             throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", new object[] { (int) access }), "access");
         }
         if (name.KeyPair != null)
         {
             name.SetPublicKey(name.KeyPair.PublicKey);
         }
         if (evidence != null)
         {
             new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
         }
         List<CustomAttributeBuilder> list = null;
         DynamicAssemblyFlags none = DynamicAssemblyFlags.None;
         if (unsafeAssemblyAttributes != null)
         {
             list = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes);
             foreach (CustomAttributeBuilder builder in list)
             {
                 if (builder.m_con.DeclaringType == typeof(SecurityTransparentAttribute))
                 {
                     none |= DynamicAssemblyFlags.Transparent;
                 }
             }
         }
         builder2 = new AssemblyBuilder((AssemblyBuilder) this.nCreateDynamicAssembly(name, evidence, ref stackMark, requiredPermissions, optionalPermissions, refusedPermissions, access, none)) {
             m_assemblyData = new AssemblyBuilderData(builder2, name.Name, access, dir)
         };
         builder2.m_assemblyData.AddPermissionRequests(requiredPermissions, optionalPermissions, refusedPermissions);
         if (list != null)
         {
             foreach (CustomAttributeBuilder builder3 in list)
             {
                 builder2.SetCustomAttribute(builder3);
             }
         }
         builder2.m_assemblyData.GetInMemoryAssemblyModule();
         return builder2;
     }
 }
 private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, object typeLib)
 {
     Type[] types = new Type[] { typeof(string) };
     ConstructorInfo constructor = typeof(ImportedFromTypeLibAttribute).GetConstructor(types);
     string typeLibName = Marshal.GetTypeLibName((ITypeLib) typeLib);
     object[] constructorArgs = new object[] { typeLibName };
     CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);
     asmBldr.SetCustomAttribute(customBuilder);
 }
 private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, object typeLib)
 {
     Type[] types = new Type[] { typeof(string) };
     ConstructorInfo constructor = typeof(GuidAttribute).GetConstructor(types);
     object[] constructorArgs = new object[] { Marshal.GetTypeLibGuid((ITypeLib) typeLib).ToString() };
     CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);
     asmBldr.SetCustomAttribute(customBuilder);
 }
Esempio n. 22
0
	[Test] // DefineVersionInfoResource (String, String, String, String, String)
	public void TestDefineVersionInfoResource2_Culture_NotSupported ()
	{
		AssemblyName aname = new AssemblyName ();
		aname.CultureInfo = new CultureInfo ("nl-BE");
		aname.Name = "lib";
		aname.Version = new Version (3, 5, 7);

		AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
			aname, AssemblyBuilderAccess.RunAndSave,
			tempDir);

		// AssemblyCulture
		Type attrType = typeof (AssemblyCultureAttribute);
		ConstructorInfo ci = attrType.GetConstructor (new Type [] { typeof (String) });
		CustomAttributeBuilder cab = new CustomAttributeBuilder (
			ci, new object [1] { "doesnotexist" });
		ab.SetCustomAttribute (cab);

		ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");

		try {
			ab.Save ("lib.dll");
			Assert.Fail ("#A1");
		} catch (CultureNotFoundException ex) {
		}

		ab = AppDomain.CurrentDomain.DefineDynamicAssembly (aname,
			AssemblyBuilderAccess.RunAndSave, tempDir);

		// AssemblyCulture
		attrType = typeof (AssemblyCultureAttribute);
		ci = attrType.GetConstructor (new Type [] { typeof (String) });
		cab = new CustomAttributeBuilder (ci, new object [1] { "neutral" });
		ab.SetCustomAttribute (cab);

		ab.DefineVersionInfoResource ("A", "1.0", "C", "D", "E");

		try {
			ab.Save ("lib.dll");
			Assert.Fail ("#B1");
		} catch (CultureNotFoundException ex) {
		}
	}
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
        {
            IntPtr pAttr = IntPtr.Zero;
            _TYPELIBATTR Attr;
            ITypeLib pTLB = (ITypeLib)typeLib;
            int Major = 0;
            int Minor = 0;

            // Retrieve the PrimaryInteropAssemblyAttribute constructor.
            Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
            ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams);

            // Retrieve the major and minor version from the typelib.
            try
            {
                pTLB.GetLibAttr(out pAttr);
                Attr = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR));
                Major = Attr.wMajorVerNum;
                Minor = Attr.wMinorVerNum;
            }
            finally
            {
                // Release the typelib attributes.
                if (pAttr != IntPtr.Zero)
                    pTLB.ReleaseTLibAttr(pAttr);
            }

            // Create an instance of the custom attribute builder.
            Object[] aArgs = new Object[2] {Major, Minor};
            CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs);

            // Set the PrimaryInteropAssemblyAttribute on the assembly builder.
            asmBldr.SetCustomAttribute(PIACABuilder);
        }
Esempio n. 24
0
		public void EmitAttribute (AssemblyBuilder builder)
		{
			if (ResolveBuilder ())
				builder.SetCustomAttribute (cab);
		}
Esempio n. 25
0
 private void EmitCustomAttributes(AssemblyBuilder assemblyBuilder, IEnumerable<Cci.ICustomAttribute> attributes)
 {
     foreach (var attribute in attributes)
     {
         assemblyBuilder.SetCustomAttribute(CreateCustomAttributeBuilder(attribute));
     }
 }
        internal RegexTypeCompiler(AssemblyName an, CustomAttributeBuilder[] attribs, String resourceFile, Evidence evidence) {
            new ReflectionPermission(PermissionState.Unrestricted).Assert();
            try {
                Debug.Assert(an != null, "AssemblyName should not be null");
                _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave, evidence);
                _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();
            }
        }
Esempio n. 27
0
        void SetUpAssembly()
        {
            string fname = Parameters.OutputAssembly;
            if (0 == fname.Length)
            {
                fname = CompileUnit.Modules[0].Name;
            }

            string outputFile = BuildOutputAssemblyName(fname);

            AssemblyName asmName = CreateAssemblyName(outputFile);
            _asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, GetAssemblyBuilderAccess(), GetTargetDirectory(outputFile));
            if (Parameters.Debug)
            {
                // ikvm tip:  Set DebuggableAttribute to assembly before
                // creating the module, to make sure Visual Studio (Whidbey)
                // picks up the attribute when debugging dynamically generated code.
                _asmBuilder.SetCustomAttribute(CreateDebuggableAttribute());
            }
            _asmBuilder.SetCustomAttribute(CreateRuntimeCompatibilityAttribute());
            _moduleBuilder = _asmBuilder.DefineDynamicModule(asmName.Name, Path.GetFileName(outputFile), Parameters.Debug);
            _sreResourceService = new SREResourceService (_asmBuilder, _moduleBuilder);
            ContextAnnotations.SetAssemblyBuilder(Context, _asmBuilder);

            Context.GeneratedAssemblyFileName = outputFile;
        }
	[Test] // SetCustomAttribute (CustomAttributeBuilder)
	public void TestSetCustomAttribute1 ()
	{
		Assembly a;
		AssemblyName an;
		AssemblyName check;
		Attribute attr;
		string filename;
		
		an = new AssemblyName ();
		an.Name = "TestSetCustomAttributeA";

		ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir);
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute).
			GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4"}));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute).
			GetConstructor (new Type [] { typeof (string) }), new object [] { "bar"}));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute).
			GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }),
			new object [] { AssemblyHashAlgorithm.MD5 }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute).
			GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint)0xff }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).
			GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute).
			GetConstructor (Type.EmptyTypes), new object [0]));
		ab.Save ("TestSetCustomAttributeA.dll");

		filename = Path.Combine (tempDir, "TestSetCustomAttributeA.dll");
		check = AssemblyName.GetAssemblyName (filename);
		Assert.AreEqual (CultureInfo.InvariantCulture, check.CultureInfo, "#A1");
#if NET_2_0
		Assert.AreEqual (AssemblyNameFlags.None, check.Flags, "#A2");
#else
		Assert.AreEqual (AssemblyNameFlags.PublicKey, check.Flags, "#A2");
#endif
		Assert.AreEqual ("TestSetCustomAttributeA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", check.FullName, "#A3");
#if NET_2_0
		Assert.IsNull (check.GetPublicKey (), "#A4");
#else
		Assert.AreEqual (new byte [0], check.GetPublicKey (), "#A4");
#endif
#if NET_2_0
		Assert.AreEqual (new byte [0], check.GetPublicKeyToken (), "#A5");
#else
		Assert.IsNull (check.GetPublicKeyToken (), "#A5");
#endif
		Assert.AreEqual (AssemblyHashAlgorithm.SHA1, check.HashAlgorithm, "#A6");
		Assert.IsNull (check.KeyPair, "#A7");
		Assert.AreEqual ("TestSetCustomAttributeA", check.Name, "#A8");
#if NET_2_0
		//Assert.AreEqual (ProcessorArchitecture.MSIL, check.ProcessorArchitecture, "#A9");
#endif
		Assert.AreEqual (new Version (0, 0, 0, 0), check.Version, "#A10");
		Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, check.VersionCompatibility, "#A11");

		using (FileStream fs = File.OpenRead (filename)) {
			byte [] buffer = new byte [fs.Length];
			fs.Read (buffer, 0, buffer.Length);
			a = Assembly.Load (buffer);
		}

		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyVersionAttribute));
		Assert.IsNotNull (attr, "#A12a");
		Assert.AreEqual ("1.2.3.4", ((AssemblyVersionAttribute) attr).Version, "#A12b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyCultureAttribute));
		Assert.IsNotNull (attr, "#A13a");
		Assert.AreEqual ("bar", ((AssemblyCultureAttribute) attr).Culture, "#A13b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyAlgorithmIdAttribute));
		Assert.IsNotNull (attr, "#A14a");
		Assert.AreEqual ((uint) AssemblyHashAlgorithm.MD5, ((AssemblyAlgorithmIdAttribute) attr).AlgorithmId, "#A14b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyFlagsAttribute));
		Assert.IsNotNull (attr, "#A15a");
		Assert.AreEqual ((uint) 0xff, ((AssemblyFlagsAttribute) attr).Flags, "#A15b");
		attr = Attribute.GetCustomAttribute (a, typeof (FooAttribute));
		Assert.IsNotNull (attr, "#A16");

		an = new AssemblyName ();
		an.CultureInfo = new CultureInfo ("nl-BE");
		an.Flags = AssemblyNameFlags.Retargetable;
		an.Name = "TestSetCustomAttributeB";
#if NET_2_0
		an.ProcessorArchitecture = ProcessorArchitecture.IA64;
#endif
		an.Version = new Version (1, 3, 5, 7);
		an.VersionCompatibility = AssemblyVersionCompatibility.SameDomain;

		ab = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, tempDir);
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyVersionAttribute).
			GetConstructor (new Type [] { typeof (string) }), new object [] { "1.2.3.4" }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyCultureAttribute).
			GetConstructor (new Type [] { typeof (string) }), new object [] { "en-US" }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyAlgorithmIdAttribute).
			GetConstructor (new Type [] { typeof (AssemblyHashAlgorithm) }),
			new object [] { AssemblyHashAlgorithm.MD5 }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyFlagsAttribute).
			GetConstructor (new Type [] { typeof (uint) }), new object [] { (uint) 0x0100 }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (AssemblyDelaySignAttribute).
			GetConstructor (new Type [] { typeof (bool) }), new object [] { true }));
		ab.SetCustomAttribute (new CustomAttributeBuilder (typeof (FooAttribute).
			GetConstructor (Type.EmptyTypes), new object [0]));
		ab.Save ("TestSetCustomAttributeB.dll");

		filename = Path.Combine (tempDir, "TestSetCustomAttributeB.dll");
		check = AssemblyName.GetAssemblyName (filename);
		Assert.AreEqual ("nl-BE", check.CultureInfo.Name, "#B1");
#if NET_2_0
		Assert.AreEqual (AssemblyNameFlags.Retargetable, check.Flags, "#B2");
#else
		Assert.AreEqual (AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, check.Flags, "#B2");
#endif
		Assert.AreEqual ("TestSetCustomAttributeB, Version=1.3.5.7, Culture=nl-BE, PublicKeyToken=null, Retargetable=Yes", check.FullName, "#B3");
#if NET_2_0
		Assert.IsNull (check.GetPublicKey (), "#B4");
#else
		Assert.AreEqual (new byte [0], check.GetPublicKey (), "#B4");
#endif
#if NET_2_0
		Assert.AreEqual (new byte [0], check.GetPublicKeyToken (), "#B5");
#else
		Assert.IsNull (check.GetPublicKeyToken (), "#B5");
#endif
		Assert.AreEqual (AssemblyHashAlgorithm.SHA1, check.HashAlgorithm, "#B6");
		Assert.IsNull (check.KeyPair, "#B7");
		Assert.AreEqual ("TestSetCustomAttributeB", check.Name, "#B8");
#if NET_2_0
		//Assert.AreEqual (ProcessorArchitecture.MSIL, check.ProcessorArchitecture, "#B9");
#endif
		Assert.AreEqual (new Version (1, 3, 5, 7), check.Version, "#B10");
		Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, check.VersionCompatibility, "#B11");

		using (FileStream fs = File.OpenRead (filename)) {
			byte [] buffer = new byte [fs.Length];
			fs.Read (buffer, 0, buffer.Length);
			a = Assembly.Load (buffer);
		}

		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyVersionAttribute));
		Assert.IsNotNull (attr, "#B12a");
		Assert.AreEqual ("1.2.3.4", ((AssemblyVersionAttribute) attr).Version, "#B12b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyCultureAttribute));
		Assert.IsNotNull (attr, "#B13a");
		Assert.AreEqual ("en-US", ((AssemblyCultureAttribute) attr).Culture, "#B13b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyAlgorithmIdAttribute));
		Assert.IsNotNull (attr, "#B14a");
		Assert.AreEqual ((uint) AssemblyHashAlgorithm.MD5, ((AssemblyAlgorithmIdAttribute) attr).AlgorithmId, "#B14b");
		attr = Attribute.GetCustomAttribute (a, typeof (AssemblyFlagsAttribute));
		Assert.IsNotNull (attr, "#B15a");
		Assert.AreEqual ((uint) 0x0100, ((AssemblyFlagsAttribute) attr).Flags, "#B15b");
		attr = Attribute.GetCustomAttribute (a, typeof (FooAttribute));
		Assert.IsNotNull (attr, "#B16");
	}
Esempio n. 29
0
        internal CodegenUnit(AssemblyName asmName)
        {
            var fileName = asmName.Name + ".dll";
            var pdbName = asmName + ".pdb";

            // so that we can run multiple tests at once and not lose the info
            if (UnitTest.CurrentTest != null)
            {
                fileName = asmName + ", " + UnitTest.PersistentId + ".dll";
                pdbName = asmName + ".pdb";
            }

#if TRACE
            try
            {
                _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
                _mod = _asm.DefineDynamicModule(fileName, true);

                // Mark generated code as debuggable.
                // See http://blogs.msdn.com/jmstall/archive/2005/02/03/366429.aspx for explanation.
                var daCtor = typeof(DebuggableAttribute).GetConstructor(new []{typeof(DebuggableAttribute.DebuggingModes)});
                var daBuilder = new CustomAttributeBuilder(daCtor, new object[] { 
                    DebuggableAttribute.DebuggingModes.DisableOptimizations | 
                    DebuggableAttribute.DebuggingModes.Default });
                _asm.SetCustomAttribute(daBuilder);

                // Mark generated code as non-user code.
                // See http://stackoverflow.com/questions/1423733/how-to-tell-if-a-net-assembly-is-dynamic for explanation.
                var cgCtor = typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes);
                var cgBuilder = new CustomAttributeBuilder(cgCtor, new object []{});
                _asm.SetCustomAttribute(cgBuilder);

                var hasAlreadyBeenDumped = false;
                Action dumpAssembly = () =>
                {
                    if (!hasAlreadyBeenDumped && _asm != null)
                    {
                        try
                        {
                            // todo. before dumping make sure that all types are completed or else the dump will simply crash
                            // this is a complex task, but it needs to be resolved for generic case

                            _asm.Save(fileName);
                        }
                        catch (Exception ex)
                        {
                            var trace = String.Format("Codegen unit '{0}' has failed to dump the asm:{1}{2}",
                                asmName.FullName, Environment.NewLine, ex);
                            Log.WriteLine(trace);

                            SafetyTools.SafeDo(() => 
                            {
                                File.WriteAllText(fileName, trace);
                                File.Delete(pdbName);
                            });
                        }
                        finally
                        {
                            hasAlreadyBeenDumped = true;
                        }
                    }
                };
                _dumpAssembly = dumpAssembly;

                // do not use DomainUnload here because it never gets fired for default domain
                // however, we need not to neglect because R#'s unit-test runner never exits process
                AppDomain.CurrentDomain.DomainUnload += (o, e) => dumpAssembly();
                AppDomain.CurrentDomain.ProcessExit += (o, e) => dumpAssembly();
                AppDomain.CurrentDomain.UnhandledException += (o, e) => dumpAssembly();
            }
            catch (Exception ex)
            {
                var trace = String.Format("Codegen unit '{0}' has failed to initialize:{1}{2}",
                    asmName.FullName, Environment.NewLine, ex);
                Log.WriteLine(trace);

                SafetyTools.SafeDo(() =>
                {
                    File.WriteAllText(fileName, trace);
                    File.Delete(pdbName);
                });

                throw;
            }
#else
            _asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
            _asm.SetCustomAttribute(new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), new object[] { }));
            _mod = _asm.DefineDynamicModule(fileName, false);
#endif
        }
 private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, object typeLib)
 {
     IntPtr nULL = Win32Native.NULL;
     ITypeLib lib = (ITypeLib) typeLib;
     int wMajorVerNum = 0;
     int wMinorVerNum = 0;
     Type[] types = new Type[] { typeof(int), typeof(int) };
     ConstructorInfo constructor = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(types);
     try
     {
         lib.GetLibAttr(out nULL);
         System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR) Marshal.PtrToStructure(nULL, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
         wMajorVerNum = typelibattr.wMajorVerNum;
         wMinorVerNum = typelibattr.wMinorVerNum;
     }
     finally
     {
         if (nULL != Win32Native.NULL)
         {
             lib.ReleaseTLibAttr(nULL);
         }
     }
     object[] constructorArgs = new object[] { wMajorVerNum, wMinorVerNum };
     CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);
     asmBldr.SetCustomAttribute(customBuilder);
 }
Esempio n. 31
0
        private void InitDebugging()
        {
            if (!_debugEnabled)
            {
                return;
            }

            _debugText = new StringBuilder();
            var instanceId = _parseCounter++;

            _debugAssemblyName = $"BfAssembly{instanceId}";

            _debugAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName(_debugAssemblyName), AssemblyBuilderAccess.RunAndSave,
                _debugTempPath);

            var daType = typeof (DebuggableAttribute);
            var daCtor = daType.GetConstructor(new[] {typeof (DebuggableAttribute.DebuggingModes)});
            var daBuilder = new CustomAttributeBuilder(daCtor, new object[]
            {
                DebuggableAttribute.DebuggingModes.DisableOptimizations |
                DebuggableAttribute.DebuggingModes.Default
            });
            _debugAssembly.SetCustomAttribute(daBuilder);
            var module = _debugAssembly.DefineDynamicModule(_debugAssemblyName, true);
            _debugType = module.DefineType($"BfType{instanceId}", TypeAttributes.Public);

            //int[] memory, BfBuffer input, BfBuffer output
            _debugMethod = _debugType.DefineMethod("Execute",
                MethodAttributes.Public | MethodAttributes.Static,
                typeof (void), new[] {typeof (int[]), typeof (BfStream), typeof (BfStream) });
            _debugTempPath = Path.Combine(_debugTempPath, $"BfSource{instanceId}X.bf");
            _debugSymbols = Expression.SymbolDocument(_debugTempPath);
        }
		internal static void SetUpAssemblyBuilderAttributes( AssemblyBuilder dedicatedAssemblyBuilder, bool isDebuggable )
		{
			if ( isDebuggable )
			{
				dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( _debuggableAttributeCtor, _debuggableAttributeCtorArguments ) );
			}
			else
			{
				dedicatedAssemblyBuilder.SetCustomAttribute(
					new CustomAttributeBuilder(
						// ReSharper disable once AssignNullToNotNullAttribute
						typeof( DebuggableAttribute ).GetConstructor( new[] { typeof( DebuggableAttribute.DebuggingModes ) } ),
						new object[] { DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints }
					)
				);
			}

			dedicatedAssemblyBuilder.SetCustomAttribute(
				new CustomAttributeBuilder(
					// ReSharper disable once AssignNullToNotNullAttribute
					typeof( System.Runtime.CompilerServices.CompilationRelaxationsAttribute ).GetConstructor( new[] { typeof( int ) } ),
					new object[] { 8 }
				)
			);
#if !SILVERLIGHT && !NETFX_35
			dedicatedAssemblyBuilder.SetCustomAttribute(
				new CustomAttributeBuilder(
					// ReSharper disable once AssignNullToNotNullAttribute
					typeof( SecurityRulesAttribute ).GetConstructor( new[] { typeof( SecurityRuleSet ) } ),
					new object[] { SecurityRuleSet.Level2 },
					new[] { typeof( SecurityRulesAttribute ).GetProperty( "SkipVerificationInFullTrust" ) },
					new object[] { true }
				)
			);
#endif // !SILVERLIGHT
		}
 private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, object typeLib)
 {
     int num;
     int num2;
     Type[] types = new Type[] { typeof(int), typeof(int) };
     ConstructorInfo constructor = typeof(TypeLibVersionAttribute).GetConstructor(types);
     Marshal.GetTypeLibVersion((ITypeLib) typeLib, out num, out num2);
     object[] constructorArgs = new object[] { num, num2 };
     CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);
     asmBldr.SetCustomAttribute(customBuilder);
 }