1 // ==++==
2 //
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 //
5 // ==--==
6 
7 //*************************************************************************************************************
8 // For each dynamic assembly there will be two AssemblyBuilder objects: the "internal"
9 // AssemblyBuilder object and the "external" AssemblyBuilder object.
10 //  1.  The "internal" object is the real assembly object that the VM creates and knows about. However,
11 //      you can perform RefEmit operations on it only if you have its granted permission. From the AppDomain
12 //      and other "internal" objects like the "internal" ModuleBuilders and runtime types, you can only
13 //      get the "internal" objects. This is to prevent low-trust code from getting a hold of the dynamic
14 //      AssemblyBuilder/ModuleBuilder/TypeBuilder/MethodBuilder/etc other people have created by simply
15 //      enumerating the AppDomain and inject code in it.
16 //  2.  The "external" object is merely an wrapper of the "internal" object and all operations on it
17 //      are directed to the internal object. This is the one you get by calling DefineDynamicAssembly
18 //      on AppDomain and the one you can always perform RefEmit operations on. You can get other "external"
19 //      objects from the "external" AssemblyBuilder, ModuleBuilder, TypeBuilder, MethodBuilder, etc. Note
20 //      that VM doesn't know about this object. So every time we call into the VM we need to pass in the
21 //      "internal" object.
22 //
23 // "internal" and "external" ModuleBuilders are similar
24 //*************************************************************************************************************
25 
26 // <OWNER>Microsoft</OWNER>
27 namespace System.Reflection.Emit
28 {
29     using System;
30     using System.Collections.Generic;
31     using System.Diagnostics;
32     using System.Diagnostics.Contracts;
33     using System.Diagnostics.SymbolStore;
34     using CultureInfo = System.Globalization.CultureInfo;
35     using System.IO;
36     using System.Reflection;
37     using System.Resources;
38     using System.Runtime.CompilerServices;
39     using System.Runtime.InteropServices;
40     using System.Runtime.Serialization;
41     using System.Runtime.Versioning;
42     using System.Security;
43     using System.Security.Permissions;
44     using System.Security.Policy;
45     using System.Threading;
46 
47     // These must match the definitions in Assembly.hpp
48     [Flags]
49     internal enum DynamicAssemblyFlags
50     {
51         None = 0x00000000,
52 
53         // Security attributes which affect the module security descriptor
54         AllCritical             = 0x00000001,
55         Aptca                   = 0x00000002,
56         Critical                = 0x00000004,
57         Transparent             = 0x00000008,
58         TreatAsSafe             = 0x00000010,
59     }
60 
61     // When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder.
62     // This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code.
63     // In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the
64     // Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which
65     // origionally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
66     // because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
67 
68     // Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
69     // There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder.
70     // AssemblyBuilder is composed of its InternalAssemblyBuilder.
71     // The AssemblyBuilder data members (e.g. m_foo) were changed to properties which then delegate
72     // the access to the composed InternalAssemblyBuilder. This way, AssemblyBuilder simply wraps
73     // InternalAssemblyBuilder and still operates on InternalAssemblyBuilder members.
74     // This also makes the change transparent to the loader. This is good because most of the complexity
75     // of Assembly building is in the loader code so not touching that code reduces the chance of
76     // introducing new bugs.
77     internal sealed class InternalAssemblyBuilder : RuntimeAssembly
78     {
InternalAssemblyBuilder()79         private InternalAssemblyBuilder() { }
80 
81         #region object overrides
Equals(object obj)82         public override bool Equals(object obj)
83         {
84             if (obj == null)
85                 return false;
86 
87             if (obj is InternalAssemblyBuilder)
88                 return ((object)this == obj);
89 
90             return obj.Equals(this);
91         }
92         // Need a dummy GetHashCode to pair with Equals
GetHashCode()93         public override int GetHashCode() { return base.GetHashCode(); }
94         #endregion
95 
96         // Assembly methods that are overridden by AssemblyBuilder should be overridden by InternalAssemblyBuilder too
97         #region Methods inherited from Assembly
GetManifestResourceNames()98         public override String[] GetManifestResourceNames()
99         {
100             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
101         }
102 
103         #if FEATURE_CORECLR
104         [System.Security.SecurityCritical] // auto-generated
105         #endif
GetFile(String name)106         public override FileStream GetFile(String name)
107         {
108             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
109         }
110 
111         #if FEATURE_CORECLR
112         [System.Security.SecurityCritical] // auto-generated
113         #endif
GetFiles(bool getResourceModules)114         public override FileStream[] GetFiles(bool getResourceModules)
115         {
116             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
117         }
118 
GetManifestResourceStream(Type type, String name)119         public override Stream GetManifestResourceStream(Type type, String name)
120         {
121             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
122         }
123 
GetManifestResourceStream(String name)124         public override Stream GetManifestResourceStream(String name)
125         {
126             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
127         }
128 
GetManifestResourceInfo(String resourceName)129         public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
130         {
131             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
132         }
133 
134         public override String Location
135         {
136 #if FEATURE_CORECLR
137             [SecurityCritical]
138 #endif // FEATURE_CORECLR
139             get
140             {
141                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
142             }
143         }
144 
145         public override String CodeBase
146         {
147 #if FEATURE_CORECLR
148             [SecurityCritical]
149 #endif // FEATURE_CORECLR
150             get
151             {
152                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
153             }
154         }
155 
GetExportedTypes()156         public override Type[] GetExportedTypes()
157         {
158             throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
159         }
160 
161         public override String ImageRuntimeVersion
162         {
163             get
164             {
165                 return RuntimeEnvironment.GetSystemVersion();
166             }
167         }
168         #endregion
169     }
170 
171     // AssemblyBuilder class.
172     // deliberately not [serializable]
173     [HostProtection(MayLeakOnAbort = true)]
174     [ClassInterface(ClassInterfaceType.None)]
175     [ComDefaultInterface(typeof(_AssemblyBuilder))]
176     [ComVisible(true)]
177     public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
178     {
179         #region FCALL
180         [System.Security.SecurityCritical]  // auto-generated
181         [ResourceExposure(ResourceScope.None)]
182         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetInMemoryAssemblyModule(RuntimeAssembly assembly)183         private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);
184 
185         [System.Security.SecurityCritical]  // auto-generated
nGetInMemoryAssemblyModule()186         private Module nGetInMemoryAssemblyModule()
187         {
188             return AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle());
189         }
190 
191 #if !FEATURE_CORECLR
192         [System.Security.SecurityCritical]  // auto-generated
193         [MethodImplAttribute(MethodImplOptions.InternalCall)]
GetOnDiskAssemblyModule(RuntimeAssembly assembly)194         private static extern RuntimeModule GetOnDiskAssemblyModule(RuntimeAssembly assembly);
195 
196         [System.Security.SecurityCritical]  // auto-generated
GetOnDiskAssemblyModuleBuilder()197         private ModuleBuilder GetOnDiskAssemblyModuleBuilder()
198         {
199             if (m_onDiskAssemblyModuleBuilder == null)
200             {
201                 Module module = AssemblyBuilder.GetOnDiskAssemblyModule(InternalAssembly.GetNativeHandle());
202                 ModuleBuilder modBuilder = new ModuleBuilder(this, (InternalModuleBuilder)module);
203                 modBuilder.Init("RefEmit_OnDiskManifestModule", null, 0);
204                 m_onDiskAssemblyModuleBuilder = modBuilder;
205             }
206 
207             return m_onDiskAssemblyModuleBuilder;
208         }
209 #endif // FEATURE_CORECLR
210 
211         #endregion
212 
213         #region Internal Data Members
214         // This is only valid in the "external" AssemblyBuilder
215         internal AssemblyBuilderData m_assemblyData;
216         private InternalAssemblyBuilder m_internalAssemblyBuilder;
217         private ModuleBuilder m_manifestModuleBuilder;
218         // Set to true if the manifest module was returned by code:DefineDynamicModule to the user
219         private bool m_fManifestModuleUsedAsDefinedModule;
220         internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
221 #if !FEATURE_CORECLR
222         private ModuleBuilder m_onDiskAssemblyModuleBuilder;
223 #endif // !FEATURE_CORECLR
224 
225 #if FEATURE_APPX
226         private bool m_profileAPICheck;
227 #endif
228 
GetModuleBuilder(InternalModuleBuilder module)229         internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
230         {
231             Contract.Requires(module != null);
232             Contract.Assert(this.InternalAssembly == module.Assembly);
233 
234             lock(SyncRoot)
235             {
236 #if !FEATURE_CORECLR
237                 foreach (ModuleBuilder modBuilder in m_assemblyData.m_moduleBuilderList)
238                 {
239                     if (modBuilder.InternalModule == module)
240                         return modBuilder;
241                 }
242 
243                 // m_onDiskAssemblyModuleBuilder is null before Save
244                 if (m_onDiskAssemblyModuleBuilder != null && m_onDiskAssemblyModuleBuilder.InternalModule == module)
245                     return m_onDiskAssemblyModuleBuilder;
246 #endif // !FEATURE_CORECLR
247 
248                 // in CoreCLR there is only one module in each dynamic assembly, the manifest module
249                 if (m_manifestModuleBuilder.InternalModule == module)
250                     return m_manifestModuleBuilder;
251 
252                 throw new ArgumentException("module");
253             }
254         }
255 
256         internal object SyncRoot
257         {
258             get
259             {
260                 return InternalAssembly.SyncRoot;
261             }
262         }
263 
264         internal InternalAssemblyBuilder InternalAssembly
265         {
266             get
267             {
268                 return m_internalAssemblyBuilder;
269             }
270         }
271 
GetNativeHandle()272         internal RuntimeAssembly GetNativeHandle()
273         {
274             return InternalAssembly.GetNativeHandle();
275         }
276 
277         [SecurityCritical]
GetVersion()278         internal Version GetVersion()
279         {
280             return InternalAssembly.GetVersion();
281         }
282 
283 #if FEATURE_APPX
284         internal bool ProfileAPICheck
285         {
286             get
287             {
288                 return m_profileAPICheck;
289             }
290         }
291 #endif
292         #endregion
293 
294         #region Constructor
295         [System.Security.SecurityCritical]  // auto-generated
AssemblyBuilder(AppDomain domain, AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource)296         internal AssemblyBuilder(AppDomain domain,
297                                  AssemblyName name,
298                                  AssemblyBuilderAccess access,
299                                  String dir,
300                                  Evidence evidence,
301                                  PermissionSet requiredPermissions,
302                                  PermissionSet optionalPermissions,
303                                  PermissionSet refusedPermissions,
304                                  ref StackCrawlMark stackMark,
305                                  IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
306                                  SecurityContextSource securityContextSource)
307         {
308             if (name == null)
309                 throw new ArgumentNullException("name");
310 
311             if (access != AssemblyBuilderAccess.Run
312 #if !FEATURE_CORECLR
313                 && access != AssemblyBuilderAccess.Save
314                 && access != AssemblyBuilderAccess.RunAndSave
315 #endif // !FEATURE_CORECLR
316 #if FEATURE_REFLECTION_ONLY_LOAD
317                 && access != AssemblyBuilderAccess.ReflectionOnly
318 #endif // FEATURE_REFLECTION_ONLY_LOAD
319 #if FEATURE_COLLECTIBLE_TYPES
320                 && access != AssemblyBuilderAccess.RunAndCollect
321 #endif // FEATURE_COLLECTIBLE_TYPES
322                 )
323             {
324                 throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access");
325             }
326 
327             if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
328                 securityContextSource > SecurityContextSource.CurrentAssembly)
329             {
330                 throw new ArgumentOutOfRangeException("securityContextSource");
331             }
332 
333             // Clone the name in case the caller modifies it underneath us.
334             name = (AssemblyName)name.Clone();
335 
336 #if !FEATURE_CORECLR
337             // Set the public key from the key pair if one has been provided.
338             // (Overwite any public key in the Assembly name, since it's no
339             // longer valid to have a disparity).
340             if (name.KeyPair != null)
341                 name.SetPublicKey(name.KeyPair.PublicKey);
342 #endif
343 
344             // If the caller is trusted they can supply identity
345             // evidence for the new assembly. Otherwise we copy the
346             // current grant and deny sets from the caller's assembly,
347             // inject them into the new assembly and mark policy as
348             // resolved. If/when the assembly is persisted and
349             // reloaded, the normal rules for gathering evidence will
350             // be used.
351             if (evidence != null)
352 #pragma warning disable 618
353                 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
354 #pragma warning restore 618
355 
356 #if FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
357             // Collectible assemblies require FullTrust. This demand may be removed if we deem the
358             // feature robust enough to be used directly by untrusted API consumers.
359             if (access == AssemblyBuilderAccess.RunAndCollect)
360                 new PermissionSet(PermissionState.Unrestricted).Demand();
361 #endif // FEATURE_COLLECTIBLE_TYPES && !FEATURE_CORECLR
362 
363             // Scan the assembly level attributes for any attributes which modify how we create the
364             // assembly. Currently, we look for any attribute which modifies the security transparency
365             // of the assembly.
366             List<CustomAttributeBuilder> assemblyAttributes = null;
367             DynamicAssemblyFlags assemblyFlags = DynamicAssemblyFlags.None;
368             byte[] securityRulesBlob = null;
369             byte[] aptcaBlob = null;
370             if (unsafeAssemblyAttributes != null)
371             {
372                 // Create a copy to ensure that it cannot be modified from another thread
373                 // as it is used further below.
374                 assemblyAttributes = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes);
375 
376 #pragma warning disable 618 // We deal with legacy attributes here as well for compat
377                 foreach (CustomAttributeBuilder attribute in assemblyAttributes)
378                 {
379                     if (attribute.m_con.DeclaringType == typeof(SecurityTransparentAttribute))
380                     {
381                         assemblyFlags |= DynamicAssemblyFlags.Transparent;
382                     }
383                     else if (attribute.m_con.DeclaringType == typeof(SecurityCriticalAttribute))
384                     {
385 #if !FEATURE_CORECLR
386                         SecurityCriticalScope scope = SecurityCriticalScope.Everything;
387                         if (attribute.m_constructorArgs != null &&
388                             attribute.m_constructorArgs.Length == 1 &&
389                             attribute.m_constructorArgs[0] is SecurityCriticalScope)
390                         {
391                             scope = (SecurityCriticalScope)attribute.m_constructorArgs[0];
392                         }
393 
394                         assemblyFlags |= DynamicAssemblyFlags.Critical;
395                         if (scope == SecurityCriticalScope.Everything)
396 #endif // !FEATURE_CORECLR
397                         {
398                             assemblyFlags |= DynamicAssemblyFlags.AllCritical;
399                         }
400                     }
401 #if !FEATURE_CORECLR
402                     else if (attribute.m_con.DeclaringType == typeof(SecurityRulesAttribute))
403                     {
404                         securityRulesBlob = new byte[attribute.m_blob.Length];
405                         Array.Copy(attribute.m_blob, securityRulesBlob, securityRulesBlob.Length);
406                     }
407                     else if (attribute.m_con.DeclaringType == typeof(SecurityTreatAsSafeAttribute))
408                     {
409                         assemblyFlags |= DynamicAssemblyFlags.TreatAsSafe;
410                     }
411 #endif // !FEATURE_CORECLR
412 #if FEATURE_APTCA
413                     else if (attribute.m_con.DeclaringType == typeof(AllowPartiallyTrustedCallersAttribute))
414                     {
415                         assemblyFlags |= DynamicAssemblyFlags.Aptca;
416                         aptcaBlob = new byte[attribute.m_blob.Length];
417                         Array.Copy(attribute.m_blob, aptcaBlob, aptcaBlob.Length);
418                     }
419 #endif // FEATURE_APTCA
420                 }
421 #pragma warning restore 618
422             }
423 
424             m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain,
425                                                                                         name,
426                                                                                         evidence,
427                                                                                         ref stackMark,
428                                                                                         requiredPermissions,
429                                                                                         optionalPermissions,
430                                                                                         refusedPermissions,
431                                                                                         securityRulesBlob,
432                                                                                         aptcaBlob,
433                                                                                         access,
434                                                                                         assemblyFlags,
435                                                                                         securityContextSource);
436 
437             m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder,
438                                                      name.Name,
439                                                      access,
440                                                      dir);
441             m_assemblyData.AddPermissionRequests(requiredPermissions,
442                                                  optionalPermissions,
443                                                  refusedPermissions);
444 
445 #if FEATURE_APPX
446             if (AppDomain.ProfileAPICheck)
447             {
448                 RuntimeAssembly creator = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
449                 if (creator != null && !creator.IsFrameworkAssembly())
450                     m_profileAPICheck = true;
451             }
452 #endif
453             // Make sure that ManifestModule is properly initialized
454             // We need to do this before setting any CustomAttribute
455             InitManifestModule();
456 
457             if (assemblyAttributes != null)
458             {
459                 foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes)
460                     SetCustomAttribute(assemblyAttribute);
461             }
462         }
463 
464         [System.Security.SecurityCritical]  // auto-generated
InitManifestModule()465         private void InitManifestModule()
466         {
467             InternalModuleBuilder modBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
468 
469             // Note that this ModuleBuilder cannot be used for RefEmit yet
470             // because it hasn't been initialized.
471             // However, it can be used to set the custom attribute on the Assembly
472             m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder);
473 
474             // We are only setting the name in the managed ModuleBuilderData here.
475             // The name in the underlying metadata will be set when the
476             // manifest module is created during nCreateDynamicAssembly.
477 
478             // This name needs to stay in sync with that used in
479             // Assembly::Init to call ReflectionModule::Create (in VM)
480             m_manifestModuleBuilder.Init(AssemblyBuilder.MANIFEST_MODULE_NAME, null, 0);
481 
482             m_fManifestModuleUsedAsDefinedModule = false;
483         }
484         #endregion
485 
486         #region DefineDynamicAssembly
487 
488         /**********************************************
489         * If an AssemblyName has a public key specified, the assembly is assumed
490         * to have a strong name and a hash will be computed when the assembly
491         * is saved.
492         **********************************************/
493         [System.Security.SecuritySafeCritical]  // auto-generated
494         [ResourceExposure(ResourceScope.None)]
495         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
496         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access)497         public static AssemblyBuilder DefineDynamicAssembly(
498             AssemblyName name,
499             AssemblyBuilderAccess access)
500         {
501             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
502 
503             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
504             return InternalDefineDynamicAssembly(name, access, null,
505                                                  null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
506         }
507 
508         [System.Security.SecuritySafeCritical]  // auto-generated
509         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> assemblyAttributes)510         public static AssemblyBuilder DefineDynamicAssembly(
511             AssemblyName name,
512             AssemblyBuilderAccess access,
513             IEnumerable<CustomAttributeBuilder> assemblyAttributes)
514         {
515             Contract.Ensures(Contract.Result<AssemblyBuilder>() != null);
516 
517             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
518             return InternalDefineDynamicAssembly(name,
519                                                  access,
520                                                  null, null, null, null, null,
521                                                  ref stackMark,
522                                                  assemblyAttributes, SecurityContextSource.CurrentAssembly);
523         }
524 
525 
526         [System.Security.SecurityCritical]  // auto-generated
527         [ResourceExposure(ResourceScope.None)]
528         [MethodImplAttribute(MethodImplOptions.InternalCall)]
nCreateDynamicAssembly(AppDomain domain, AssemblyName name, Evidence identity, ref StackCrawlMark stackMark, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, byte[] securityRulesBlob, byte[] aptcaBlob, AssemblyBuilderAccess access, DynamicAssemblyFlags flags, SecurityContextSource securityContextSource)529         private static extern Assembly nCreateDynamicAssembly(AppDomain domain,
530                                                               AssemblyName name,
531                                                               Evidence identity,
532                                                               ref StackCrawlMark stackMark,
533                                                               PermissionSet requiredPermissions,
534                                                               PermissionSet optionalPermissions,
535                                                               PermissionSet refusedPermissions,
536                                                               byte[] securityRulesBlob,
537                                                               byte[] aptcaBlob,
538                                                               AssemblyBuilderAccess access,
539                                                               DynamicAssemblyFlags flags,
540                                                               SecurityContextSource securityContextSource);
541 
542         private class AssemblyBuilderLock { }
543 
544         [System.Security.SecurityCritical]  // auto-generated
545         [ResourceExposure(ResourceScope.Machine)]
546         [ResourceConsumption(ResourceScope.Machine)]
InternalDefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, String dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource)547         internal static AssemblyBuilder InternalDefineDynamicAssembly(
548             AssemblyName name,
549             AssemblyBuilderAccess access,
550             String dir,
551             Evidence evidence,
552             PermissionSet requiredPermissions,
553             PermissionSet optionalPermissions,
554             PermissionSet refusedPermissions,
555             ref StackCrawlMark stackMark,
556             IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes,
557             SecurityContextSource securityContextSource)
558         {
559 #if FEATURE_CAS_POLICY
560             if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
561             {
562                 throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
563             }
564 #endif // FEATURE_CAS_POLICY
565 
566             lock (typeof(AssemblyBuilderLock))
567             {
568                 // we can only create dynamic assemblies in the current domain
569                 return new AssemblyBuilder(AppDomain.CurrentDomain,
570                                            name,
571                                            access,
572                                            dir,
573                                            evidence,
574                                            requiredPermissions,
575                                            optionalPermissions,
576                                            refusedPermissions,
577                                            ref stackMark,
578                                            unsafeAssemblyAttributes,
579                                            securityContextSource);
580             } //lock(typeof(AssemblyBuilderLock))
581         }
582         #endregion
583 
584         #region DefineDynamicModule
585         /**********************************************
586         *
587         * Defines a named dynamic module. It is an error to define multiple
588         * modules within an Assembly with the same name. This dynamic module is
589         * a transient module.
590         *
591         **********************************************/
592         [System.Security.SecuritySafeCritical]  // auto-generated
593         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicModule( String name)594         public ModuleBuilder DefineDynamicModule(
595             String      name)
596         {
597             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
598 
599             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
600             return DefineDynamicModuleInternal(name, false, ref stackMark);
601         }
602 
603         [System.Security.SecuritySafeCritical]  // auto-generated
604         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicModule( String name, bool emitSymbolInfo)605         public ModuleBuilder DefineDynamicModule(
606             String      name,
607             bool        emitSymbolInfo)         // specify if emit symbol info or not
608         {
609             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
610 
611             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
612             return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark );
613         }
614 
615         [System.Security.SecurityCritical]  // auto-generated
DefineDynamicModuleInternal( String name, bool emitSymbolInfo, ref StackCrawlMark stackMark)616         private ModuleBuilder DefineDynamicModuleInternal(
617             String      name,
618             bool        emitSymbolInfo,         // specify if emit symbol info or not
619             ref StackCrawlMark stackMark)
620         {
621             lock(SyncRoot)
622             {
623                 return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark);
624             }
625         }
626 
627         [System.Security.SecurityCritical]  // auto-generated
628         [ResourceExposure(ResourceScope.None)]
629         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
DefineDynamicModuleInternalNoLock( String name, bool emitSymbolInfo, ref StackCrawlMark stackMark)630         private ModuleBuilder DefineDynamicModuleInternalNoLock(
631             String      name,
632             bool        emitSymbolInfo,         // specify if emit symbol info or not
633             ref StackCrawlMark stackMark)
634         {
635             if (name == null)
636                 throw new ArgumentNullException("name");
637             if (name.Length == 0)
638                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
639             if (name[0] == '\0')
640                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
641             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
642             Contract.EndContractBlock();
643 
644             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + " )");
645 
646             Contract.Assert(m_assemblyData != null, "m_assemblyData is null in DefineDynamicModuleInternal");
647 
648             ModuleBuilder dynModule;
649             ISymbolWriter writer = null;
650             IntPtr pInternalSymWriter = new IntPtr();
651 
652             // create the dynamic module
653 
654 #if FEATURE_MULTIMODULE_ASSEMBLIES
655 
656 #if FEATURE_CORECLR
657 #error FEATURE_MULTIMODULE_ASSEMBLIES should always go with !FEATURE_CORECLR
658 #endif //FEATURE_CORECLR
659 
660             m_assemblyData.CheckNameConflict(name);
661 
662             if (m_fManifestModuleUsedAsDefinedModule == true)
663             {   // We need to define a new module
664                 int tkFile;
665                 InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule(
666                     InternalAssembly,
667                     emitSymbolInfo,
668                     name,
669                     name,
670                     ref stackMark,
671                     ref pInternalSymWriter,
672                     true /*fIsTransient*/,
673                     out tkFile);
674                 dynModule = new ModuleBuilder(this, internalDynModule);
675 
676                 // initialize the dynamic module's managed side information
677                 dynModule.Init(name, null, tkFile);
678             }
679             else
680             {   // We will reuse the manifest module
681                 m_manifestModuleBuilder.ModifyModuleName(name);
682                 dynModule = m_manifestModuleBuilder;
683 
684                 if (emitSymbolInfo)
685                 {
686                     pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, name);
687                 }
688             }
689 
690 #else // FEATURE_MULTIMODULE_ASSEMBLIES
691             // Without FEATURE_MULTIMODULE_ASSEMBLIES only one ModuleBuilder per AssemblyBuilder can be created
692             if (m_fManifestModuleUsedAsDefinedModule == true)
693                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoMultiModuleAssembly"));
694 
695             // Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule()
696             dynModule = m_manifestModuleBuilder;
697 #endif // FEATURE_MULTIMODULE_ASSEMBLIES
698 
699             // Create the symbol writer
700             if (emitSymbolInfo)
701             {
702 #if FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR
703                 // this is the code path for the desktop runtime
704 
705                 // create the default SymWriter
706                 Assembly assem = LoadISymWrapper();
707                 Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false);
708                 if (symWriter != null && !symWriter.IsVisible)
709                     symWriter = null;
710 
711                 if (symWriter == null)
712                 {
713                     // cannot find SymWriter - throw TypeLoadException since we couldnt find the type.
714                     throw new TypeLoadException(Environment.GetResourceString(ResId.MissingType, "SymWriter"));
715                 }
716 
717                 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
718 
719                 try
720                 {
721                     (new PermissionSet(PermissionState.Unrestricted)).Assert();
722                     writer = (ISymbolWriter)Activator.CreateInstance(symWriter);
723 
724                     // Set the underlying writer for the managed writer
725                     // that we're using.  Note that this function requires
726                     // unmanaged code access.
727                     writer.SetUnderlyingWriter(pInternalSymWriter);
728                 }
729                 finally
730                 {
731                     CodeAccessPermission.RevertAssert();
732                 }
733 #endif // FEATURE_MULTIMODULE_ASSEMBLIES && !FEATURE_CORECLR
734 
735 #if !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR
736                 // this is the code path for CoreCLR
737 
738                 writer = SymWrapperCore.SymWriter.CreateSymWriter();
739                 // Set the underlying writer for the managed writer
740                 // that we're using.  Note that this function requires
741                 // unmanaged code access.
742 #pragma warning disable 618
743                 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
744 #pragma warning restore 618
745 
746                 String fileName = "Unused"; // this symfile is never written to disk so filename does not matter.
747 
748                 // Pass the "real" module to the VM
749                 pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName);
750 
751                 // In Telesto, we took the SetUnderlyingWriter method private as it's a very rickety method.
752                 // This might someday be a good move for the desktop CLR too.
753                 ((SymWrapperCore.SymWriter)writer).InternalSetUnderlyingWriter(pInternalSymWriter);
754 #endif // !FEATURE_MULTIMODULE_ASSEMBLIES && FEATURE_CORECLR
755             } // Creating the symbol writer
756 
757             dynModule.SetSymWriter(writer);
758             m_assemblyData.AddModule(dynModule);
759 
760             if (dynModule == m_manifestModuleBuilder)
761             {   // We are reusing manifest module as user-defined dynamic module
762                 m_fManifestModuleUsedAsDefinedModule = true;
763             }
764 
765             return dynModule;
766         } // DefineDynamicModuleInternalNoLock
767 
768 #if !FEATURE_CORECLR
769         // All dynamic modules in SilverLight are transient so we removed this overload of DefineDynamicModule
770         // Note that it is assumed that !FEATURE_CORECLR always goes with FEATURE_MULTIMODULE_ASSEMBLIES
771         // If we ever will build a non coreclr version of the runtime without FEATURE_MULTIMODULE_ASSEMBLIES
772         // we will need to make the same changes here as the ones we made in the transient overload
773 
774         /**********************************************
775         *
776         * Defines a named dynamic module. It is an error to define multiple
777         * modules within an Assembly with the same name. No symbol information
778         * will be emitted.
779         *
780         **********************************************/
781         [System.Security.SecuritySafeCritical]  // auto-generated
782         [ResourceExposure(ResourceScope.Machine)]
783         [ResourceConsumption(ResourceScope.Machine)]
784         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicModule( String name, String fileName)785         public ModuleBuilder DefineDynamicModule(
786             String name,
787             String fileName)
788         {
789             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
790 
791             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
792 
793             // delegate to the next DefineDynamicModule
794             return DefineDynamicModuleInternal(name, fileName, false, ref stackMark);
795         }
796 
797         /**********************************************
798         *
799         * Emit symbol information if emitSymbolInfo is true using the
800         * default symbol writer interface.
801         * An exception will be thrown if the assembly is transient.
802         *
803         **********************************************/
804         [System.Security.SecuritySafeCritical]  // auto-generated
805         [ResourceExposure(ResourceScope.Machine)]
806         [ResourceConsumption(ResourceScope.Machine)]
807         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
DefineDynamicModule( String name, String fileName, bool emitSymbolInfo)808         public ModuleBuilder DefineDynamicModule(
809             String name,                   // module name
810             String fileName,               // module file name
811             bool emitSymbolInfo)         // specify if emit symbol info or not
812         {
813             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
814 
815             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
816             return DefineDynamicModuleInternal(name, fileName, emitSymbolInfo, ref stackMark);
817         }
818 
819         [System.Security.SecurityCritical]  // auto-generated
820         [ResourceExposure(ResourceScope.Machine)]
821         [ResourceConsumption(ResourceScope.Machine)]
DefineDynamicModuleInternal( String name, String fileName, bool emitSymbolInfo, ref StackCrawlMark stackMark)822         private ModuleBuilder DefineDynamicModuleInternal(
823             String name,                   // module name
824             String fileName,               // module file name
825             bool emitSymbolInfo,         // specify if emit symbol info or not
826             ref StackCrawlMark stackMark)       // stack crawl mark used to find caller
827         {
828             lock(SyncRoot)
829             {
830                 return DefineDynamicModuleInternalNoLock(name, fileName, emitSymbolInfo, ref stackMark);
831             }
832         }
833 
834         // "name" will be used for:
835         //     1. The Name field in the Module table.
836         //     2. ModuleBuilder.GetModule(string).
837         // "fileName" will be used for:
838         //     1. The name field in the ModuleRef table when this module is being referenced by
839         //        another module in the same assembly.
840         //     2. .file record in the in memory assembly manifest when the module is created in memory
841         //     3. .file record in the on disk assembly manifest when the assembly is saved to disk
842         //     4. The file name of the saved module.
843         [System.Security.SecurityCritical]  // auto-generated
844         [ResourceExposure(ResourceScope.Machine)]
845         [ResourceConsumption(ResourceScope.Machine)]
DefineDynamicModuleInternalNoLock( String name, String fileName, bool emitSymbolInfo, ref StackCrawlMark stackMark)846         private ModuleBuilder DefineDynamicModuleInternalNoLock(
847             String name,                        // module name
848             String fileName,                    // module file name
849             bool   emitSymbolInfo,              // specify if emit symbol info or not
850             ref    StackCrawlMark stackMark)    // stack crawl mark used to find caller
851         {
852             if (name == null)
853                 throw new ArgumentNullException("name");
854             if (name.Length == 0)
855                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
856             if (name[0] == '\0')
857                 throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
858 
859             if (fileName == null)
860                 throw new ArgumentNullException("fileName");
861             if (fileName.Length == 0)
862                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName");
863             if (!String.Equals(fileName, Path.GetFileName(fileName)))
864                 throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
865             Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
866             Contract.EndContractBlock();
867 
868             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineDynamicModule( " + name + ", " + fileName + ", " + emitSymbolInfo + " )");
869             if (m_assemblyData.m_access == AssemblyBuilderAccess.Run)
870             {
871                 // Error! You cannot define a persistable module within a transient data.
872                 throw new NotSupportedException(Environment.GetResourceString("Argument_BadPersistableModuleInTransientAssembly"));
873             }
874 
875             if (m_assemblyData.m_isSaved == true)
876             {
877                 // assembly has been saved before!
878                 throw new InvalidOperationException(Environment.GetResourceString(
879                     "InvalidOperation_CannotAlterAssembly"));
880             }
881 
882             ModuleBuilder dynModule;
883             ISymbolWriter writer = null;
884             IntPtr pInternalSymWriter = new IntPtr();
885 
886             // create the dynamic module
887 
888             m_assemblyData.CheckNameConflict(name);
889             m_assemblyData.CheckFileNameConflict(fileName);
890 
891             int tkFile;
892             InternalModuleBuilder internalDynModule = (InternalModuleBuilder)DefineDynamicModule(
893                 InternalAssembly,
894                 emitSymbolInfo,
895                 name,
896                 fileName,
897                 ref stackMark,
898                 ref pInternalSymWriter,
899                 false /*fIsTransient*/,
900                 out tkFile);
901             dynModule = new ModuleBuilder(this, internalDynModule);
902 
903             // initialize the dynamic module's managed side information
904             dynModule.Init(name, fileName, tkFile);
905 
906             // Create the symbol writer
907             if (emitSymbolInfo)
908             {
909                 // create the default SymWriter
910                 Assembly assem = LoadISymWrapper();
911                 Type symWriter = assem.GetType("System.Diagnostics.SymbolStore.SymWriter", true, false);
912                 if (symWriter != null && !symWriter.IsVisible)
913                     symWriter = null;
914 
915                 if (symWriter == null)
916                 {
917                     // cannot find SymWriter - throw TypeLoadException since we couldnt find the type.
918                     throw new TypeLoadException(Environment.GetResourceString("MissingType", "SymWriter"));
919                 }
920                 try
921                 {
922                     (new PermissionSet(PermissionState.Unrestricted)).Assert();
923                     writer = (ISymbolWriter)Activator.CreateInstance(symWriter);
924 
925                     // Set the underlying writer for the managed writer
926                     // that we're using.  Note that this function requires
927                     // unmanaged code access.
928                     writer.SetUnderlyingWriter(pInternalSymWriter);
929                 }
930                 finally
931                 {
932                     CodeAccessPermission.RevertAssert();
933                 }
934             }
935 
936             dynModule.SetSymWriter(writer);
937 
938             m_assemblyData.AddModule(dynModule);
939 
940             return dynModule;
941         } // DefineDynamicModuleInternalNoLock
942 #endif // !FEATURE_CORECLR
943         #endregion
944 
LoadISymWrapper()945         private Assembly LoadISymWrapper()
946         {
947             if (m_assemblyData.m_ISymWrapperAssembly != null)
948                 return m_assemblyData.m_ISymWrapperAssembly;
949 
950             Assembly assem = Assembly.Load("ISymWrapper, Version=" + ThisAssembly.Version +
951                 ", Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken);
952 
953             m_assemblyData.m_ISymWrapperAssembly = assem;
954             return assem;
955         }
956 
CheckContext(params Type[][] typess)957         internal void CheckContext(params Type[][] typess)
958         {
959             if (typess == null)
960                 return;
961 
962             foreach(Type[] types in typess)
963                 if (types != null)
964                     CheckContext(types);
965         }
966 
CheckContext(params Type[] types)967         internal void CheckContext(params Type[] types)
968         {
969             if (types == null)
970                 return;
971 
972             foreach (Type type in types)
973             {
974                 if (type == null)
975                     continue;
976 
977                 if (type.Module == null || type.Module.Assembly == null)
978                     throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotValid"));
979 
980                 if (type.Module.Assembly == typeof(object).Module.Assembly)
981                     continue;
982 
983                 if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly)
984                     throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext1", type.AssemblyQualifiedName));
985 
986                 if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly)
987                     throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext2", type.AssemblyQualifiedName));
988             }
989         }
990 
991 #if !FEATURE_CORECLR
992         /**********************************************
993         *
994         * Define stand alone managed resource for Assembly
995         *
996         **********************************************/
997         [ResourceExposure(ResourceScope.Machine)]
998         [ResourceConsumption(ResourceScope.Machine)]
DefineResource( String name, String description, String fileName)999         public IResourceWriter DefineResource(
1000             String      name,
1001             String      description,
1002             String      fileName)
1003         {
1004             return DefineResource(name, description, fileName, ResourceAttributes.Public);
1005         }
1006 
1007         /**********************************************
1008         *
1009         * Define stand alone managed resource for Assembly
1010         *
1011         **********************************************/
1012         [ResourceExposure(ResourceScope.Machine)]
1013         [ResourceConsumption(ResourceScope.Machine)]
DefineResource( String name, String description, String fileName, ResourceAttributes attribute)1014         public IResourceWriter DefineResource(
1015             String      name,
1016             String      description,
1017             String      fileName,
1018             ResourceAttributes attribute)
1019         {
1020             lock(SyncRoot)
1021             {
1022                 return DefineResourceNoLock(name, description, fileName, attribute);
1023             }
1024         }
1025 
1026         [ResourceExposure(ResourceScope.Machine)]
1027         [ResourceConsumption(ResourceScope.Machine)]
DefineResourceNoLock( String name, String description, String fileName, ResourceAttributes attribute)1028         private IResourceWriter DefineResourceNoLock(
1029             String      name,
1030             String      description,
1031             String      fileName,
1032             ResourceAttributes attribute)
1033         {
1034             if (name == null)
1035                 throw new ArgumentNullException("name");
1036             if (name.Length == 0)
1037                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
1038             if (fileName == null)
1039                 throw new ArgumentNullException("fileName");
1040             if (fileName.Length == 0)
1041                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName");
1042             if (!String.Equals(fileName, Path.GetFileName(fileName)))
1043                 throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
1044             Contract.EndContractBlock();
1045 
1046             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.DefineResource( " + name + ", " + fileName + ")");
1047 
1048             m_assemblyData.CheckResNameConflict(name);
1049             m_assemblyData.CheckFileNameConflict(fileName);
1050 
1051             ResourceWriter resWriter;
1052             String  fullFileName;
1053 
1054             if (m_assemblyData.m_strDir == null)
1055             {
1056                 // If assembly directory is null, use current directory
1057                 fullFileName = Path.Combine(Environment.CurrentDirectory, fileName);
1058                 resWriter = new ResourceWriter(fullFileName);
1059             }
1060             else
1061             {
1062                 // Form the full path given the directory provided by user
1063                 fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
1064                 resWriter = new ResourceWriter(fullFileName);
1065             }
1066             // get the full path
1067             fullFileName = Path.GetFullPath(fullFileName);
1068 
1069             // retrieve just the file name
1070             fileName = Path.GetFileName(fullFileName);
1071 
1072             m_assemblyData.AddResWriter( new ResWriterData( resWriter, null, name, fileName, fullFileName, attribute) );
1073             return resWriter;
1074         }
1075 
1076 #endif // !FEATURE_CORECLR
1077 
1078         /**********************************************
1079         *
1080         * Add an existing resource file to the Assembly
1081         *
1082         **********************************************/
1083         #if FEATURE_CORECLR
1084         [System.Security.SecurityCritical] // auto-generated
1085         #endif
1086         [ResourceExposure(ResourceScope.Machine)]
1087         [ResourceConsumption(ResourceScope.Machine)]
AddResourceFile( String name, String fileName)1088         public void AddResourceFile(
1089             String      name,
1090             String      fileName)
1091         {
1092             AddResourceFile(name, fileName, ResourceAttributes.Public);
1093         }
1094 
1095         /**********************************************
1096         *
1097         * Add an existing resource file to the Assembly
1098         *
1099         **********************************************/
1100         #if FEATURE_CORECLR
1101         [System.Security.SecurityCritical] // auto-generated
1102         #endif
1103         [ResourceExposure(ResourceScope.Machine)]
1104         [ResourceConsumption(ResourceScope.Machine)]
AddResourceFile( String name, String fileName, ResourceAttributes attribute)1105         public void AddResourceFile(
1106             String      name,
1107             String      fileName,
1108             ResourceAttributes attribute)
1109         {
1110             lock(SyncRoot)
1111             {
1112                 AddResourceFileNoLock(name, fileName, attribute);
1113             }
1114         }
1115 
1116         [System.Security.SecuritySafeCritical]
1117         [ResourceExposure(ResourceScope.Machine)]
1118         [ResourceConsumption(ResourceScope.Machine)]
AddResourceFileNoLock( String name, String fileName, ResourceAttributes attribute)1119         private void AddResourceFileNoLock(
1120             String      name,
1121             String      fileName,
1122             ResourceAttributes attribute)
1123         {
1124             if (name == null)
1125                 throw new ArgumentNullException("name");
1126             if (name.Length == 0)
1127                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
1128             if (fileName == null)
1129                 throw new ArgumentNullException("fileName");
1130             if (fileName.Length == 0)
1131                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), fileName);
1132             if (!String.Equals(fileName, Path.GetFileName(fileName)))
1133                 throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
1134             Contract.EndContractBlock();
1135 
1136             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.AddResourceFile( " + name + ", " + fileName + ")");
1137 
1138             m_assemblyData.CheckResNameConflict(name);
1139             m_assemblyData.CheckFileNameConflict(fileName);
1140 
1141             String  fullFileName;
1142 
1143             if (m_assemblyData.m_strDir == null)
1144             {
1145                 // If assembly directory is null, use current directory
1146                 fullFileName = Path.Combine(Environment.CurrentDirectory, fileName);
1147             }
1148             else
1149             {
1150                 // Form the full path given the directory provided by user
1151                 fullFileName = Path.Combine(m_assemblyData.m_strDir, fileName);
1152             }
1153 
1154             // get the full path
1155             fullFileName = Path.UnsafeGetFullPath(fullFileName);
1156 
1157             // retrieve just the file name
1158             fileName = Path.GetFileName(fullFileName);
1159 
1160             if (File.UnsafeExists(fullFileName) == false)
1161                 throw new FileNotFoundException(Environment.GetResourceString(
1162                     "IO.FileNotFound_FileName",
1163                     fileName), fileName);
1164             m_assemblyData.AddResWriter( new ResWriterData( null, null, name, fileName, fullFileName, attribute) );
1165         }
1166 
1167         #region object overrides
Equals(object obj)1168         public override bool Equals(object obj)
1169         {
1170             return InternalAssembly.Equals(obj);
1171         }
1172         // Need a dummy GetHashCode to pair with Equals
GetHashCode()1173         public override int GetHashCode() { return InternalAssembly.GetHashCode(); }
1174         #endregion
1175 
1176         #region ICustomAttributeProvider Members
GetCustomAttributes(bool inherit)1177         public override Object[] GetCustomAttributes(bool inherit)
1178         {
1179             return InternalAssembly.GetCustomAttributes(inherit);
1180         }
1181 
GetCustomAttributes(Type attributeType, bool inherit)1182         public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
1183         {
1184             return InternalAssembly.GetCustomAttributes(attributeType, inherit);
1185         }
1186 
IsDefined(Type attributeType, bool inherit)1187         public override bool IsDefined(Type attributeType, bool inherit)
1188         {
1189             return InternalAssembly.IsDefined(attributeType, inherit);
1190         }
1191 
GetCustomAttributesData()1192         public override IList<CustomAttributeData> GetCustomAttributesData()
1193         {
1194             return InternalAssembly.GetCustomAttributesData();
1195         }
1196         #endregion
1197 
1198         #region Assembly overrides
1199         // Returns the names of all the resources
GetManifestResourceNames()1200         public override String[] GetManifestResourceNames()
1201         {
1202             return InternalAssembly.GetManifestResourceNames();
1203         }
1204 
1205         #if FEATURE_CORECLR
1206         [System.Security.SecurityCritical] // auto-generated
1207         #endif
GetFile(String name)1208         public override FileStream GetFile(String name)
1209         {
1210             return InternalAssembly.GetFile(name);
1211         }
1212 
1213         #if FEATURE_CORECLR
1214         [System.Security.SecurityCritical] // auto-generated
1215         #endif
GetFiles(bool getResourceModules)1216         public override FileStream[] GetFiles(bool getResourceModules)
1217         {
1218             return InternalAssembly.GetFiles(getResourceModules);
1219         }
1220 
GetManifestResourceStream(Type type, String name)1221         public override Stream GetManifestResourceStream(Type type, String name)
1222         {
1223             return InternalAssembly.GetManifestResourceStream(type, name);
1224         }
1225 
GetManifestResourceStream(String name)1226         public override Stream GetManifestResourceStream(String name)
1227         {
1228             return InternalAssembly.GetManifestResourceStream(name);
1229         }
1230 
GetManifestResourceInfo(String resourceName)1231         public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
1232         {
1233             return InternalAssembly.GetManifestResourceInfo(resourceName);
1234         }
1235 
1236         public override String Location
1237         {
1238             #if FEATURE_CORECLR
1239             [System.Security.SecurityCritical] // auto-generated
1240             #endif
1241             get
1242             {
1243                 return InternalAssembly.Location;
1244             }
1245         }
1246 
1247         public override String ImageRuntimeVersion
1248         {
1249             get
1250             {
1251                 return InternalAssembly.ImageRuntimeVersion;
1252             }
1253         }
1254 
1255         public override String CodeBase
1256         {
1257             #if FEATURE_CORECLR
1258             [System.Security.SecurityCritical] // auto-generated
1259             #endif
1260             get
1261             {
1262                 return InternalAssembly.CodeBase;
1263             }
1264         }
1265 
1266         // Override the EntryPoint method on Assembly.
1267         // This doesn't need to be synchronized because it is simple enough
1268         public override MethodInfo EntryPoint
1269         {
1270             get
1271             {
1272                 return m_assemblyData.m_entryPointMethod;
1273             }
1274         }
1275 
1276         // Get an array of all the public types defined in this assembly
GetExportedTypes()1277         public override Type[] GetExportedTypes()
1278         {
1279             return InternalAssembly.GetExportedTypes();
1280         }
1281 
1282         #if FEATURE_CORECLR
1283         [System.Security.SecurityCritical] // auto-generated
1284         #endif
1285         [ResourceExposure(ResourceScope.None)]
1286         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
GetName(bool copiedName)1287         public override AssemblyName GetName(bool copiedName)
1288         {
1289             return InternalAssembly.GetName(copiedName);
1290         }
1291 
1292         public override String FullName
1293         {
1294             get
1295             {
1296                 return InternalAssembly.FullName;
1297             }
1298         }
1299 
GetType(String name, bool throwOnError, bool ignoreCase)1300         public override Type GetType(String name, bool throwOnError, bool ignoreCase)
1301         {
1302             return InternalAssembly.GetType(name, throwOnError, ignoreCase);
1303         }
1304 
1305 #if FEATURE_CAS_POLICY
1306         public override Evidence Evidence
1307         {
1308             get
1309             {
1310                 return InternalAssembly.Evidence;
1311             }
1312         }
1313 
1314         public override PermissionSet PermissionSet
1315         {
1316             [SecurityCritical]
1317             get
1318             {
1319                 return InternalAssembly.PermissionSet;
1320             }
1321         }
1322 
1323         public override SecurityRuleSet SecurityRuleSet
1324         {
1325             get
1326             {
1327                 return InternalAssembly.SecurityRuleSet;
1328             }
1329         }
1330 #endif // FEATURE_CAS_POLICY
1331 
1332         public override Module ManifestModule
1333         {
1334             get
1335             {
1336                 return m_manifestModuleBuilder.InternalModule;
1337             }
1338         }
1339 
1340         public override bool ReflectionOnly
1341         {
1342             get
1343             {
1344                 return InternalAssembly.ReflectionOnly;
1345             }
1346         }
1347 
GetModule(String name)1348         public override Module GetModule(String name)
1349         {
1350             return InternalAssembly.GetModule(name);
1351         }
1352 
GetReferencedAssemblies()1353         public override AssemblyName[] GetReferencedAssemblies()
1354         {
1355             return InternalAssembly.GetReferencedAssemblies();
1356         }
1357 
1358         public override bool GlobalAssemblyCache
1359         {
1360             get
1361             {
1362                 return InternalAssembly.GlobalAssemblyCache;
1363             }
1364         }
1365 
1366         public override Int64 HostContext
1367         {
1368             get
1369             {
1370                 return InternalAssembly.HostContext;
1371             }
1372         }
1373 
1374         [ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
1375         [ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
GetModules(bool getResourceModules)1376         public override Module[] GetModules(bool getResourceModules)
1377         {
1378             return InternalAssembly.GetModules(getResourceModules);
1379         }
1380 
1381         [ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
1382         [ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
GetLoadedModules(bool getResourceModules)1383         public override Module[] GetLoadedModules(bool getResourceModules)
1384         {
1385             return InternalAssembly.GetLoadedModules(getResourceModules);
1386         }
1387 
1388         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
GetSatelliteAssembly(CultureInfo culture)1389         public override Assembly GetSatelliteAssembly(CultureInfo culture)
1390         {
1391             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1392             return InternalAssembly.InternalGetSatelliteAssembly(culture, null, ref stackMark);
1393         }
1394 
1395         // Useful for binding to a very specific version of a satellite assembly
1396         [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
GetSatelliteAssembly(CultureInfo culture, Version version)1397         public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
1398         {
1399             StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
1400             return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark);
1401         }
1402 
1403         public override bool IsDynamic
1404         {
1405             get {
1406                 return true;
1407             }
1408         }
1409         #endregion
1410 
1411 
1412 #if !FEATURE_PAL
1413         /**********************************************
1414         *
1415         * Add an unmanaged Version resource to the
1416         *  assembly
1417         *
1418         **********************************************/
DefineVersionInfoResource( String product, String productVersion, String company, String copyright, String trademark)1419         public void DefineVersionInfoResource(
1420             String      product,
1421             String      productVersion,
1422             String      company,
1423             String      copyright,
1424             String      trademark)
1425         {
1426             lock(SyncRoot)
1427             {
1428                 DefineVersionInfoResourceNoLock(
1429                     product,
1430                     productVersion,
1431                     company,
1432                     copyright,
1433                     trademark);
1434             }
1435         }
1436 
DefineVersionInfoResourceNoLock( String product, String productVersion, String company, String copyright, String trademark)1437         private void DefineVersionInfoResourceNoLock(
1438             String product,
1439             String productVersion,
1440             String company,
1441             String copyright,
1442             String trademark)
1443         {
1444             if (m_assemblyData.m_strResourceFileName != null ||
1445                 m_assemblyData.m_resourceBytes != null ||
1446                 m_assemblyData.m_nativeVersion != null)
1447                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1448 
1449             m_assemblyData.m_nativeVersion = new NativeVersionInfo();
1450 
1451             m_assemblyData.m_nativeVersion.m_strCopyright = copyright;
1452             m_assemblyData.m_nativeVersion.m_strTrademark = trademark;
1453             m_assemblyData.m_nativeVersion.m_strCompany = company;
1454             m_assemblyData.m_nativeVersion.m_strProduct = product;
1455             m_assemblyData.m_nativeVersion.m_strProductVersion = productVersion;
1456             m_assemblyData.m_hasUnmanagedVersionInfo = true;
1457             m_assemblyData.m_OverrideUnmanagedVersionInfo = true;
1458 
1459         }
1460 
DefineVersionInfoResource()1461         public void DefineVersionInfoResource()
1462         {
1463             lock(SyncRoot)
1464             {
1465                 DefineVersionInfoResourceNoLock();
1466             }
1467         }
1468 
DefineVersionInfoResourceNoLock()1469         private void DefineVersionInfoResourceNoLock()
1470         {
1471             if (m_assemblyData.m_strResourceFileName != null ||
1472                 m_assemblyData.m_resourceBytes != null ||
1473                 m_assemblyData.m_nativeVersion != null)
1474                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1475 
1476             m_assemblyData.m_hasUnmanagedVersionInfo = true;
1477             m_assemblyData.m_nativeVersion = new NativeVersionInfo();
1478         }
1479 
DefineUnmanagedResource(Byte[] resource)1480         public void DefineUnmanagedResource(Byte[] resource)
1481         {
1482             if (resource == null)
1483                 throw new ArgumentNullException("resource");
1484             Contract.EndContractBlock();
1485 
1486             lock(SyncRoot)
1487             {
1488                 DefineUnmanagedResourceNoLock(resource);
1489             }
1490         }
1491 
DefineUnmanagedResourceNoLock(Byte[] resource)1492         private void DefineUnmanagedResourceNoLock(Byte[] resource)
1493         {
1494             if (m_assemblyData.m_strResourceFileName != null ||
1495                 m_assemblyData.m_resourceBytes != null ||
1496                 m_assemblyData.m_nativeVersion != null)
1497                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1498 
1499             m_assemblyData.m_resourceBytes = new byte[resource.Length];
1500             System.Array.Copy(resource, m_assemblyData.m_resourceBytes, resource.Length);
1501         }
1502 
1503         [System.Security.SecuritySafeCritical]  // auto-generated
1504         [ResourceExposure(ResourceScope.Machine)]
1505         [ResourceConsumption(ResourceScope.Machine)]
DefineUnmanagedResource(String resourceFileName)1506         public void DefineUnmanagedResource(String resourceFileName)
1507         {
1508             if (resourceFileName == null)
1509                 throw new ArgumentNullException("resourceFileName");
1510             Contract.EndContractBlock();
1511 
1512             lock(SyncRoot)
1513             {
1514                 DefineUnmanagedResourceNoLock(resourceFileName);
1515             }
1516         }
1517 
1518         [System.Security.SecurityCritical]  // auto-generated
1519         [ResourceExposure(ResourceScope.Machine)]
1520         [ResourceConsumption(ResourceScope.Machine)]
DefineUnmanagedResourceNoLock(String resourceFileName)1521         private void DefineUnmanagedResourceNoLock(String resourceFileName)
1522         {
1523             if (m_assemblyData.m_strResourceFileName != null ||
1524                 m_assemblyData.m_resourceBytes != null ||
1525                 m_assemblyData.m_nativeVersion != null)
1526                 throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1527 
1528             // Check caller has the right to read the file.
1529             string      strFullFileName;
1530             if (m_assemblyData.m_strDir == null)
1531             {
1532                 // If assembly directory is null, use current directory
1533                 strFullFileName = Path.Combine(Environment.CurrentDirectory, resourceFileName);
1534             }
1535             else
1536             {
1537                 // Form the full path given the directory provided by user
1538                 strFullFileName = Path.Combine(m_assemblyData.m_strDir, resourceFileName);
1539             }
1540             strFullFileName = Path.GetFullPath(resourceFileName);
1541             new FileIOPermission(FileIOPermissionAccess.Read, strFullFileName).Demand();
1542 
1543             if (File.Exists(strFullFileName) == false)
1544                 throw new FileNotFoundException(Environment.GetResourceString(
1545                     "IO.FileNotFound_FileName",
1546                     resourceFileName), resourceFileName);
1547             m_assemblyData.m_strResourceFileName = strFullFileName;
1548         }
1549 #endif // !FEATURE_PAL
1550 
1551 
1552 
1553         /**********************************************
1554         *
1555         * return a dynamic module with the specified name.
1556         *
1557         **********************************************/
GetDynamicModule( String name)1558         public ModuleBuilder GetDynamicModule(
1559             String      name)                   // the name of module for the look up
1560         {
1561             lock(SyncRoot)
1562             {
1563                 return GetDynamicModuleNoLock(name);
1564             }
1565         }
1566 
GetDynamicModuleNoLock( String name)1567         private ModuleBuilder GetDynamicModuleNoLock(
1568             String      name)                   // the name of module for the look up
1569         {
1570             if (name == null)
1571                 throw new ArgumentNullException("name");
1572             if (name.Length == 0)
1573                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1574             Contract.EndContractBlock();
1575 
1576             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )");
1577             int size = m_assemblyData.m_moduleBuilderList.Count;
1578             for (int i = 0; i < size; i++)
1579             {
1580                 ModuleBuilder moduleBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
1581                 if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name))
1582                 {
1583                     return moduleBuilder;
1584                 }
1585             }
1586             return null;
1587         }
1588 
1589         /**********************************************
1590         *
1591         * Setting the entry point if the assembly builder is building
1592         * an exe.
1593         *
1594         **********************************************/
1595         #if FEATURE_CORECLR
1596         [System.Security.SecurityCritical] // auto-generated
1597         #endif
SetEntryPoint( MethodInfo entryMethod)1598         public void SetEntryPoint(
1599             MethodInfo  entryMethod)
1600         {
1601             SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
1602         }
1603         #if FEATURE_CORECLR
1604         [System.Security.SecurityCritical] // auto-generated
1605         #endif
SetEntryPoint( MethodInfo entryMethod, PEFileKinds fileKind)1606         public void SetEntryPoint(
1607             MethodInfo  entryMethod,        // entry method for the assembly. We use this to determine the entry module
1608             PEFileKinds fileKind)           // file kind for the assembly.
1609         {
1610             lock(SyncRoot)
1611             {
1612                 SetEntryPointNoLock(entryMethod, fileKind);
1613             }
1614         }
1615 
SetEntryPointNoLock( MethodInfo entryMethod, PEFileKinds fileKind)1616         private void SetEntryPointNoLock(
1617             MethodInfo  entryMethod,        // entry method for the assembly. We use this to determine the entry module
1618             PEFileKinds fileKind)           // file kind for the assembly.
1619         {
1620 
1621             if (entryMethod == null)
1622                 throw new ArgumentNullException("entryMethod");
1623             Contract.EndContractBlock();
1624 
1625             BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.SetEntryPoint");
1626 
1627             Module tmpModule = entryMethod.Module;
1628             if (tmpModule == null || !InternalAssembly.Equals(tmpModule.Assembly))
1629                 throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly"));
1630 
1631             m_assemblyData.m_entryPointMethod = entryMethod;
1632             m_assemblyData.m_peFileKind = fileKind;
1633 
1634 #if !FEATURE_CORECLR
1635             // Setting the entry point
1636             ModuleBuilder tmpMB = tmpModule as ModuleBuilder;
1637             if (tmpMB != null)
1638                 m_assemblyData.m_entryPointModule = tmpMB;
1639             else
1640                 m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)tmpModule);
1641 
1642             MethodToken entryMethodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod);
1643             m_assemblyData.m_entryPointModule.SetEntryPoint(entryMethodToken);
1644 #endif //!FEATURE_CORECLR
1645         }
1646 
1647 
1648         /**********************************************
1649         * Use this function if client decides to form the custom attribute blob themselves
1650         **********************************************/
1651         #if FEATURE_CORECLR
1652         [System.Security.SecurityCritical] // auto-generated
1653         #else
1654         [System.Security.SecuritySafeCritical]
1655         #endif
1656         [System.Runtime.InteropServices.ComVisible(true)]
SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)1657         public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
1658         {
1659             if (con == null)
1660                 throw new ArgumentNullException("con");
1661             if (binaryAttribute == null)
1662                 throw new ArgumentNullException("binaryAttribute");
1663             Contract.EndContractBlock();
1664 
1665             lock(SyncRoot)
1666             {
1667                 SetCustomAttributeNoLock(con, binaryAttribute);
1668             }
1669         }
1670 
1671         [System.Security.SecurityCritical]  // auto-generated
SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)1672         private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
1673         {
1674             TypeBuilder.DefineCustomAttribute(
1675                 m_manifestModuleBuilder,     // pass in the in-memory assembly module
1676                 AssemblyBuilderData.m_tkAssembly,           // This is the AssemblyDef token
1677                 m_manifestModuleBuilder.GetConstructorToken(con).Token,
1678                 binaryAttribute,
1679                 false,
1680                 typeof(System.Diagnostics.DebuggableAttribute) == con.DeclaringType);
1681 
1682             // Track the CA for persistence
1683             if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
1684             {
1685                 // tracking the CAs for persistence
1686                 m_assemblyData.AddCustomAttribute(con, binaryAttribute);
1687             }
1688         }
1689 
1690         /**********************************************
1691         * Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
1692         **********************************************/
1693         [System.Security.SecuritySafeCritical]  // auto-generated
SetCustomAttribute(CustomAttributeBuilder customBuilder)1694         public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
1695         {
1696             if (customBuilder == null)
1697             {
1698                 throw new ArgumentNullException("customBuilder");
1699             }
1700             Contract.EndContractBlock();
1701 
1702             lock(SyncRoot)
1703             {
1704                 SetCustomAttributeNoLock(customBuilder);
1705             }
1706         }
1707 
1708         [System.Security.SecurityCritical]  // auto-generated
SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)1709         private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
1710         {
1711             customBuilder.CreateCustomAttribute(
1712                 m_manifestModuleBuilder,
1713                 AssemblyBuilderData.m_tkAssembly);          // This is the AssemblyDef token
1714 
1715             // Track the CA for persistence
1716             if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
1717             {
1718                 m_assemblyData.AddCustomAttribute(customBuilder);
1719             }
1720         }
1721 
1722 
1723         /**********************************************
1724         *
1725         * Saves the assembly to disk. Also saves all dynamic modules defined
1726         * in this dynamic assembly. Assembly file name can be the same as one of
1727         * the module's name. If so, assembly info is stored within that module.
1728         * Assembly file name can be different from all of the modules underneath. In
1729         * this case, assembly is stored stand alone.
1730         *
1731         **********************************************/
1732 
1733         [ResourceExposure(ResourceScope.Machine)]
1734         [ResourceConsumption(ResourceScope.Machine)]
Save(String assemblyFileName)1735         public void Save(String assemblyFileName)       // assembly file name
1736         {
1737             Save(assemblyFileName, System.Reflection.PortableExecutableKinds.ILOnly, System.Reflection.ImageFileMachine.I386);
1738         }
1739 
1740         [System.Security.SecuritySafeCritical]  // auto-generated
1741         [ResourceExposure(ResourceScope.Machine)]
1742         [ResourceConsumption(ResourceScope.Machine)]
Save(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)1743         public void Save(String assemblyFileName,
1744             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
1745         {
1746             lock(SyncRoot)
1747             {
1748                 SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
1749             }
1750         }
1751 
1752 #if FEATURE_CORECLR
1753         [ResourceExposure(ResourceScope.Machine)]
1754         [ResourceConsumption(ResourceScope.Machine)]
SaveNoLock(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)1755         private void SaveNoLock(String assemblyFileName,
1756             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
1757         {
1758             // AssemblyBuilderAccess.Save can never be set with FEATURE_CORECLR
1759             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
1760         }
1761 #else // FEATURE_CORECLR
1762         [System.Security.SecurityCritical]  // auto-generated
1763         [ResourceExposure(ResourceScope.Machine)]
1764         [ResourceConsumption(ResourceScope.Machine)]
SaveNoLock(String assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)1765         private void SaveNoLock(String assemblyFileName,
1766             PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
1767         {
1768             if (assemblyFileName == null)
1769                 throw new ArgumentNullException("assemblyFileName");
1770             if (assemblyFileName.Length == 0)
1771                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "assemblyFileName");
1772             if (!String.Equals(assemblyFileName, Path.GetFileName(assemblyFileName)))
1773                 throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "assemblyFileName");
1774             Contract.EndContractBlock();
1775 
1776             int i;
1777             int         size;
1778             Type        type;
1779             TypeBuilder typeBuilder;
1780             ModuleBuilder modBuilder;
1781             String      strModFileName;
1782             ModuleBuilder assemblyModule;
1783             ResWriterData tempRes;
1784             int[]       tkAttrs = null;
1785             int[]       tkAttrs2 = null;
1786             ModuleBuilder onDiskAssemblyModule;
1787 
1788             BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilder.Save( " + assemblyFileName + " )");
1789 
1790             String tmpVersionFile = null;
1791 
1792             try
1793             {
1794                 if (m_assemblyData.m_iCABuilder != 0)
1795                     tkAttrs = new int[m_assemblyData.m_iCABuilder];
1796                 if ( m_assemblyData.m_iCAs != 0)
1797                     tkAttrs2 = new int[m_assemblyData.m_iCAs];
1798 
1799                 if (m_assemblyData.m_isSaved == true)
1800                 {
1801                     // assembly has been saved before!
1802                     throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_AssemblyHasBeenSaved,
1803                         InternalAssembly.GetSimpleName()));
1804                 }
1805 
1806                 if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save)
1807                 {
1808                     throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
1809                 }
1810 
1811                 // Check if assembly info is supposed to be stored with one of the module files.
1812                 assemblyModule = m_assemblyData.FindModuleWithFileName(assemblyFileName);
1813 
1814                 if (assemblyModule != null)
1815                 {
1816                     m_onDiskAssemblyModuleBuilder = assemblyModule;
1817 
1818                     // In memory this module is not the manifest module and has a valid file token
1819                     // On disk it will be the manifest module so lets clean the file token
1820                     // We should not retrive FileToken after the assembly has been saved
1821                     // If that is absolutely necessary, we need two separate fields on ModuleBuilderData:
1822                     // the in memory file token and the on disk file token.
1823                     assemblyModule.m_moduleData.FileToken = 0;
1824                 }
1825                 else
1826                 {   // If assembly is to be stored alone, then no file name should conflict with it.
1827                     // This check will ensure resource file names are different assembly file name.
1828                     m_assemblyData.CheckFileNameConflict(assemblyFileName);
1829                 }
1830 
1831                 if (m_assemblyData.m_strDir == null)
1832                 {
1833                     // set it to current directory
1834                     m_assemblyData.m_strDir = Environment.CurrentDirectory;
1835                 }
1836                 else if (Directory.Exists(m_assemblyData.m_strDir) == false)
1837                 {
1838                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory",
1839                         m_assemblyData.m_strDir));
1840                 }
1841 
1842                 // after this point, assemblyFileName is the full path name.
1843                 assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName);
1844                 assemblyFileName = Path.GetFullPath(assemblyFileName);
1845 
1846                 // Check caller has the right to create the assembly file itself.
1847                 new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand();
1848 
1849                 // 1. setup/create the IMetaDataAssemblyEmit for the on disk version
1850                 if (assemblyModule != null)
1851                 {
1852                     // prepare saving CAs on assembly def. We need to introduce the MemberRef for
1853                     // the CA's type first of all. This is for the case the we have embedded manifest.
1854                     // We need to introduce these MRs before we call PreSave where we will snap
1855                     // into a ondisk metadata. If we do it after this, the ondisk metadata will
1856                     // not contain the proper MRs.
1857                     //
1858                     for (i=0; i < m_assemblyData.m_iCABuilder; i++)
1859                     {
1860                         tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
1861                             assemblyModule);
1862                     }
1863                     for (i=0; i < m_assemblyData.m_iCAs; i++)
1864                     {
1865                         tkAttrs2[i] = assemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
1866                     }
1867                     assemblyModule.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine);
1868                 }
1869 
1870                 RuntimeModule runtimeAssemblyModule = (assemblyModule != null) ? assemblyModule.ModuleHandle.GetRuntimeModule() : null;
1871                 PrepareForSavingManifestToDisk(GetNativeHandle(), runtimeAssemblyModule);
1872 
1873                 // This function will return the embedded manifest module, an already exposed ModuleBuilder
1874                 // created by user, or make the stand alone manifest module exposed through managed code.
1875                 //
1876                 onDiskAssemblyModule = GetOnDiskAssemblyModuleBuilder();
1877 
1878     #if !FEATURE_PAL
1879                 // Set any native resources on the OnDiskAssemblyModule.
1880                 if (m_assemblyData.m_strResourceFileName != null)
1881                     onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName);
1882                 else if (m_assemblyData.m_resourceBytes != null)
1883                     onDiskAssemblyModule.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes);
1884                 else if (m_assemblyData.m_hasUnmanagedVersionInfo == true)
1885                 {
1886                     // calculate unmanaged version info from assembly's custom attributes
1887                     m_assemblyData.FillUnmanagedVersionInfo();
1888 
1889                     String strFileVersion = m_assemblyData.m_nativeVersion.m_strFileVersion;
1890                     if (strFileVersion == null)
1891                         strFileVersion = GetVersion().ToString();
1892 
1893                     // Create the file.
1894                     CreateVersionInfoResource(
1895                          assemblyFileName,
1896                          m_assemblyData.m_nativeVersion.m_strTitle,   // title
1897                          null, // Icon filename
1898                          m_assemblyData.m_nativeVersion.m_strDescription,   // description
1899                          m_assemblyData.m_nativeVersion.m_strCopyright,
1900                          m_assemblyData.m_nativeVersion.m_strTrademark,
1901                          m_assemblyData.m_nativeVersion.m_strCompany,
1902                          m_assemblyData.m_nativeVersion.m_strProduct,
1903                          m_assemblyData.m_nativeVersion.m_strProductVersion,
1904                          strFileVersion,
1905                          m_assemblyData.m_nativeVersion.m_lcid,
1906                          m_assemblyData.m_peFileKind == PEFileKinds.Dll,
1907                          JitHelpers.GetStringHandleOnStack(ref tmpVersionFile));
1908 
1909                     onDiskAssemblyModule.DefineUnmanagedResourceFileInternalNoLock(tmpVersionFile);
1910                 }
1911     #endif // !FEATURE_PAL
1912 
1913                 if (assemblyModule == null)
1914                 {
1915 
1916                     // This is for introducing the MRs for CA's type. This case is for stand alone
1917                     // manifest. We need to wait till PrepareForSavingManifestToDisk is called.
1918                     // That will trigger the creation of the on-disk stand alone manifest module.
1919                     //
1920                     for (i=0; i < m_assemblyData.m_iCABuilder; i++)
1921                     {
1922                         tkAttrs[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(
1923                             onDiskAssemblyModule);
1924                     }
1925                     for (i=0; i < m_assemblyData.m_iCAs; i++)
1926                     {
1927                         tkAttrs2[i] = onDiskAssemblyModule.InternalGetConstructorToken(m_assemblyData.m_CACons[i], true).Token;
1928                     }
1929                 }
1930 
1931                 // 2. save all of the persistable modules contained by this AssemblyBuilder except the module that is going to contain
1932                 // Assembly information
1933                 //
1934                 // 3. create the file list in the manifest and track the file token. If it is embedded assembly,
1935                 // the assembly file should not be on the file list.
1936                 //
1937                 size = m_assemblyData.m_moduleBuilderList.Count;
1938                 for (i = 0; i < size; i++)
1939                 {
1940                     ModuleBuilder mBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
1941                     if (mBuilder.IsTransient() == false && mBuilder != assemblyModule)
1942                     {
1943                         strModFileName = mBuilder.m_moduleData.m_strFileName;
1944                         if (m_assemblyData.m_strDir != null)
1945                         {
1946                             strModFileName = Path.Combine(m_assemblyData.m_strDir, strModFileName);
1947                             strModFileName = Path.GetFullPath(strModFileName);
1948                         }
1949 
1950                         // Check caller has the right to create the Module file itself.
1951                         new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, strModFileName).Demand();
1952 
1953                         mBuilder.m_moduleData.FileToken = AddFile(GetNativeHandle(), mBuilder.m_moduleData.m_strFileName);
1954                         mBuilder.PreSave(strModFileName, portableExecutableKind, imageFileMachine);
1955                         mBuilder.Save(strModFileName, false, portableExecutableKind, imageFileMachine);
1956 
1957                         // Cannot set the hash value when creating the file since the file token
1958                         // is needed to created the entries for the embedded resources in the
1959                         // module and the resources need to be there before you figure the hash.
1960                         SetFileHashValue(GetNativeHandle(), mBuilder.m_moduleData.FileToken, strModFileName);
1961                     }
1962                 }
1963 
1964                 // 4. Add the public ComType
1965                 for (i=0; i < m_assemblyData.m_iPublicComTypeCount; i++)
1966                 {
1967                     type = m_assemblyData.m_publicComTypeList[i];
1968                     // If the type that was added as a Public Com Type was obtained via Reflection,
1969                     //  it will be a System.RuntimeType, even if it was really, at the same time,
1970                     //  a TypeBuilder.  Unfortunately, you can't get back to the TypeBuilder, so
1971                     //  this code has to deal with either-or.
1972                     if (type is RuntimeType)
1973                     {
1974                         // If type is a runtime type, it must be a baked TypeBuilder,
1975                         // ttype.Module should be an InternalModuleBuilder
1976 
1977                         InternalModuleBuilder internalMB = (InternalModuleBuilder)type.Module;
1978                         modBuilder = this.GetModuleBuilder(internalMB);
1979                         if (modBuilder != assemblyModule)
1980                             DefineNestedComType(type, modBuilder.m_moduleData.FileToken, type.MetadataToken);
1981                     }
1982                     else
1983                     {
1984                         // Could assert that "type" is a TypeBuilder, but next statement throws if it isn't.
1985                         typeBuilder = (TypeBuilder) type;
1986                         // If type is a TypeBuilder, type.Module must be a ModuleBuilder.
1987                         modBuilder = typeBuilder.GetModuleBuilder();
1988                         if (modBuilder != assemblyModule)
1989                             DefineNestedComType(type, modBuilder.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal);
1990                     }
1991                 }
1992 
1993                 // 5. write AssemblyDef's CAs (only if we are not saving directly the manifest module itself)
1994                 if (onDiskAssemblyModule != m_manifestModuleBuilder)
1995                 {
1996                     for (i = 0; i < m_assemblyData.m_iCABuilder; i++)
1997                     {
1998                         m_assemblyData.m_CABuilders[i].CreateCustomAttribute(
1999                             onDiskAssemblyModule,
2000                             AssemblyBuilderData.m_tkAssembly,   // This is the AssemblyDef token
2001                             tkAttrs[i], true);
2002                     }
2003 
2004                     for (i = 0; i < m_assemblyData.m_iCAs; i++)
2005                     {
2006                         TypeBuilder.DefineCustomAttribute(
2007                             onDiskAssemblyModule,               // pass in the in-memory assembly module
2008                             AssemblyBuilderData.m_tkAssembly,   // This is the AssemblyDef token
2009                             tkAttrs2[i],
2010                             m_assemblyData.m_CABytes[i],
2011                             true, false);
2012                     }
2013                 }
2014 
2015                 // 6. write security permission requests to the manifest.
2016 #pragma warning disable 618
2017                 if (m_assemblyData.m_RequiredPset != null)
2018                     AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum);
2019 
2020                 if (m_assemblyData.m_RefusedPset != null)
2021                     AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse);
2022 
2023                 if (m_assemblyData.m_OptionalPset != null)
2024                     AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional);
2025 #pragma warning restore 618
2026 
2027                 // 7. Save the stand alone managed resources
2028                 size = m_assemblyData.m_resWriterList.Count;
2029                 for (i = 0; i < size; i++)
2030                 {
2031                     tempRes = null;
2032 
2033                     try
2034                     {
2035                         tempRes = (ResWriterData)m_assemblyData.m_resWriterList[i];
2036 
2037                         // If the user added an existing resource to the manifest, the
2038                         // corresponding ResourceWriter will be null.
2039                         if (tempRes.m_resWriter != null)
2040                             // Check caller has the right to create the Resource file itself.
2041                             new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, tempRes.m_strFullFileName).Demand();
2042                     }
2043                     finally
2044                     {
2045                         if (tempRes != null && tempRes.m_resWriter != null)
2046                             tempRes.m_resWriter.Close();
2047                     }
2048 
2049                     // Add entry to manifest for this stand alone resource
2050                     AddStandAloneResource(GetNativeHandle(), tempRes.m_strName, tempRes.m_strFileName, tempRes.m_strFullFileName, (int)tempRes.m_attribute);
2051                 }
2052 
2053                 // Save now!!
2054                 if (assemblyModule == null)
2055                 {
2056                     onDiskAssemblyModule.DefineNativeResource(portableExecutableKind, imageFileMachine);
2057 
2058                     // Stand alone manifest
2059                     int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0;
2060 
2061                     SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind,
2062                             (int)portableExecutableKind, (int)imageFileMachine);
2063                     }
2064                 else
2065                 {
2066                     // embedded manifest
2067 
2068                     // If the module containing the entry point is not the manifest file, we need to
2069                     // let the manifest file point to the module which contains the entry point.
2070                     //
2071                     //
2072                     //
2073                     //
2074                     if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != assemblyModule)
2075                         assemblyModule.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken));
2076                     assemblyModule.Save(assemblyFileName, true, portableExecutableKind, imageFileMachine);
2077                 }
2078                 m_assemblyData.m_isSaved = true;
2079             }
2080             finally
2081             {
2082                 if (tmpVersionFile != null)
2083                 {
2084                     // Delete file.
2085                     System.IO.File.Delete(tmpVersionFile);
2086                 }
2087             }
2088         }
2089 #endif // FEATURE_CORECLR
2090 
2091 #if FEATURE_CAS_POLICY
2092         [System.Security.SecurityCritical]  // auto-generated
AddDeclarativeSecurity(PermissionSet pset, SecurityAction action)2093         private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action)
2094         {
2095             // Translate sets into internal encoding (uses standard binary serialization).
2096             byte[] blob = pset.EncodeXml();
2097             AddDeclarativeSecurity(GetNativeHandle(), action, blob, blob.Length);
2098         }
2099 #endif // FEATURE_CAS_POLICY
2100 
IsPersistable()2101         internal bool IsPersistable()
2102         {
2103 #if !FEATURE_CORECLR // AssemblyBuilderAccess.Save is never set in CoreCLR
2104             if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save)
2105             {
2106                 return true;
2107             }
2108             else
2109 #endif // FEATURE_CORECLR
2110             {
2111                 return false;
2112             }
2113         }
2114 
2115         /**********************************************
2116         *
2117         * Internal helper to walk the nested type hierachy
2118         *
2119         **********************************************/
2120         [System.Security.SecurityCritical]  // auto-generated
DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)2121         private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
2122         {
2123             Type        enclosingType = type.DeclaringType;
2124             if (enclosingType == null)
2125             {
2126                 // Use full type name for non-nested types.
2127                 return AddExportedTypeOnDisk(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
2128             }
2129 
2130             tkResolutionScope = DefineNestedComType(enclosingType, tkResolutionScope, tkTypeDef);
2131             // Use simple name for nested types.
2132             return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
2133         }
2134 
2135         [System.Security.SecurityCritical]  // auto-generated
DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)2136         internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
2137         {
2138             Type enclosingType = type.DeclaringType;
2139             if (enclosingType == null)
2140             {
2141                 // Use full type name for non-nested types.
2142                 return AddExportedTypeInMemory(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
2143             }
2144 
2145             tkResolutionScope = DefineExportedTypeInMemory(enclosingType, tkResolutionScope, tkTypeDef);
2146             // Use simple name for nested types.
2147             return AddExportedTypeInMemory(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
2148         }
2149 
2150         /**********************************************
2151          *
2152          * Private methods
2153          *
2154          **********************************************/
2155 
2156         /**********************************************
2157          * Make a private constructor so these cannot be constructed externally.
2158          * @internonly
2159          **********************************************/
AssemblyBuilder()2160         private AssemblyBuilder() {}
2161 
2162 #if !FEATURE_CORECLR
_AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)2163         void _AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)
2164         {
2165             throw new NotImplementedException();
2166         }
2167 
_AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)2168         void _AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
2169         {
2170             throw new NotImplementedException();
2171         }
2172 
_AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)2173         void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
2174         {
2175             throw new NotImplementedException();
2176         }
2177 
2178         // If you implement this method, make sure to include _AssemblyBuilder.Invoke in VM\DangerousAPIs.h and
2179         // include _AssemblyBuilder in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
_AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)2180         void _AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
2181         {
2182             throw new NotImplementedException();
2183         }
2184 #endif
2185 
2186         // Create a new module in which to emit code. This module will not contain the manifest.
2187         [System.Security.SecurityCritical]  // auto-generated
2188         [ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
2189         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2190         [SuppressUnmanagedCodeSecurity]
DefineDynamicModule(RuntimeAssembly containingAssembly, bool emitSymbolInfo, String name, String filename, StackCrawlMarkHandle stackMark, ref IntPtr pInternalSymWriter, ObjectHandleOnStack retModule, bool fIsTransient, out int tkFile)2191         static private extern void DefineDynamicModule(RuntimeAssembly containingAssembly,
2192                                                        bool emitSymbolInfo,
2193                                                        String name,
2194                                                        String filename,
2195                                                        StackCrawlMarkHandle stackMark,
2196                                                        ref IntPtr pInternalSymWriter,
2197                                                        ObjectHandleOnStack retModule,
2198                                                        bool fIsTransient,
2199                                                        out int tkFile);
2200 
2201         [System.Security.SecurityCritical]  // auto-generated
DefineDynamicModule(RuntimeAssembly containingAssembly, bool emitSymbolInfo, String name, String filename, ref StackCrawlMark stackMark, ref IntPtr pInternalSymWriter, bool fIsTransient, out int tkFile)2202         private static Module DefineDynamicModule(RuntimeAssembly containingAssembly,
2203                                            bool emitSymbolInfo,
2204                                            String name,
2205                                            String filename,
2206                                            ref StackCrawlMark stackMark,
2207                                            ref IntPtr pInternalSymWriter,
2208                                            bool fIsTransient,
2209                                            out int tkFile)
2210         {
2211             RuntimeModule retModule = null;
2212 
2213             DefineDynamicModule(containingAssembly.GetNativeHandle(),
2214                                 emitSymbolInfo,
2215                                 name,
2216                                 filename,
2217                                 JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
2218                                 ref pInternalSymWriter,
2219                                 JitHelpers.GetObjectHandleOnStack(ref retModule),
2220                                 fIsTransient,
2221                                 out tkFile);
2222 
2223             return retModule;
2224         }
2225 
2226         // The following functions are native helpers for creating on-disk manifest
2227         [System.Security.SecurityCritical]  // auto-generated
2228         [ResourceExposure(ResourceScope.None)]
2229         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2230         [SuppressUnmanagedCodeSecurity]
PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule)2231         static private extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule);  // module to contain assembly information if assembly is embedded
2232 
2233         [System.Security.SecurityCritical]  // auto-generated
2234         [ResourceExposure(ResourceScope.Machine)]
2235         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2236         [SuppressUnmanagedCodeSecurity]
SaveManifestToDisk(RuntimeAssembly assembly, String strFileName, int entryPoint, int fileKind, int portableExecutableKind, int ImageFileMachine)2237         static private extern void SaveManifestToDisk(RuntimeAssembly assembly,
2238                                                 String strFileName,
2239                                                 int entryPoint,
2240                                                 int fileKind,
2241                                                 int portableExecutableKind,
2242                                                 int ImageFileMachine);
2243 
2244         [System.Security.SecurityCritical]  // auto-generated
2245         [ResourceExposure(ResourceScope.Machine)]
2246         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2247         [SuppressUnmanagedCodeSecurity]
AddFile(RuntimeAssembly assembly, String strFileName)2248         static private extern int AddFile(RuntimeAssembly assembly, String strFileName);
2249 
2250         [System.Security.SecurityCritical]  // auto-generated
2251         [ResourceExposure(ResourceScope.Machine)]
2252         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2253         [SuppressUnmanagedCodeSecurity]
SetFileHashValue(RuntimeAssembly assembly, int tkFile, String strFullFileName)2254         static private extern void SetFileHashValue(RuntimeAssembly assembly,
2255                                                     int tkFile,
2256                                                     String strFullFileName);
2257 
2258         [System.Security.SecurityCritical]  // auto-generated
2259         [ResourceExposure(ResourceScope.None)]
2260         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2261         [SuppressUnmanagedCodeSecurity]
AddExportedTypeInMemory(RuntimeAssembly assembly, String strComTypeName, int tkAssemblyRef, int tkTypeDef, TypeAttributes flags)2262         static private extern int AddExportedTypeInMemory(RuntimeAssembly assembly,
2263                                                           String strComTypeName,
2264                                                           int tkAssemblyRef,
2265                                                           int tkTypeDef,
2266                                                           TypeAttributes flags);
2267 
2268         [System.Security.SecurityCritical]  // auto-generated
2269         [ResourceExposure(ResourceScope.None)]
2270         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2271         [SuppressUnmanagedCodeSecurity]
AddExportedTypeOnDisk(RuntimeAssembly assembly, String strComTypeName, int tkAssemblyRef, int tkTypeDef, TypeAttributes flags)2272         static private extern int AddExportedTypeOnDisk(RuntimeAssembly assembly,
2273                                                         String strComTypeName,
2274                                                         int tkAssemblyRef,
2275                                                         int tkTypeDef,
2276                                                         TypeAttributes flags);
2277 
2278         // Add an entry to assembly's manifestResource table for a stand alone resource.
2279         [System.Security.SecurityCritical]  // auto-generated
2280         [ResourceExposure(ResourceScope.Machine)]
2281         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2282         [SuppressUnmanagedCodeSecurity]
AddStandAloneResource(RuntimeAssembly assembly, String strName, String strFileName, String strFullFileName, int attribute)2283         static private extern void AddStandAloneResource(RuntimeAssembly assembly,
2284                                                          String strName,
2285                                                          String strFileName,
2286                                                          String strFullFileName,
2287                                                          int attribute);
2288 
2289         [System.Security.SecurityCritical]  // auto-generated
2290         [ResourceExposure(ResourceScope.None)]
2291         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2292         [SuppressUnmanagedCodeSecurity]
2293 #pragma warning disable 618
AddDeclarativeSecurity(RuntimeAssembly assembly, SecurityAction action, byte[] blob, int length)2294         static private extern void AddDeclarativeSecurity(RuntimeAssembly assembly, SecurityAction action, byte[] blob, int length);
2295 #pragma warning restore 618
2296 
2297 #if !FEATURE_PAL
2298         // Functions for defining unmanaged resources.
2299         [System.Security.SecurityCritical]  // auto-generated
2300         [ResourceExposure(ResourceScope.Machine)]
2301         [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
2302         [SuppressUnmanagedCodeSecurity]
CreateVersionInfoResource(String filename, String title, String iconFilename, String description, String copyright, String trademark, String company, String product, String productVersion, String fileVersion, int lcid, bool isDll, StringHandleOnStack retFileName)2303         static private extern void CreateVersionInfoResource(String filename, String title, String iconFilename, String description,
2304                                                              String copyright, String trademark, String company, String product,
2305                                                              String productVersion, String fileVersion, int lcid, bool isDll,
2306                                                              StringHandleOnStack retFileName);
2307 #endif // !FEATURE_PAL
2308 
2309     }
2310 }
2311