mscorlib(4.0.0.0) API with additions
AssemblyBuilder.cs
2 using System.Diagnostics;
5 using System.IO;
6 using System.Resources;
9 using System.Security;
11 using System.Security.Policy;
12 using System.Threading;
13 
14 namespace System.Reflection.Emit
15 {
17  [ClassInterface(ClassInterfaceType.None)]
18  [ComDefaultInterface(typeof(_AssemblyBuilder))]
19  [ComVisible(true)]
20  [HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
21  public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder
22  {
23  private class AssemblyBuilderLock
24  {
25  }
26 
27  internal AssemblyBuilderData m_assemblyData;
28 
29  private InternalAssemblyBuilder m_internalAssemblyBuilder;
30 
31  private ModuleBuilder m_manifestModuleBuilder;
32 
33  private bool m_fManifestModuleUsedAsDefinedModule;
34 
35  internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
36 
37  private ModuleBuilder m_onDiskAssemblyModuleBuilder;
38 
39  private bool m_profileAPICheck;
40 
41  internal object SyncRoot => InternalAssembly.SyncRoot;
42 
43  internal InternalAssemblyBuilder InternalAssembly => m_internalAssemblyBuilder;
44 
45  internal bool ProfileAPICheck => m_profileAPICheck;
46 
51  public override string Location => InternalAssembly.Location;
52 
56  public override string ImageRuntimeVersion => InternalAssembly.ImageRuntimeVersion;
57 
62  public override string CodeBase => InternalAssembly.CodeBase;
63 
67  public override MethodInfo EntryPoint => m_assemblyData.m_entryPointMethod;
68 
71  public override string FullName => InternalAssembly.FullName;
72 
75  public override Evidence Evidence => InternalAssembly.Evidence;
76 
79  public override PermissionSet PermissionSet
80  {
81  [SecurityCritical]
82  get
83  {
84  return InternalAssembly.PermissionSet;
85  }
86  }
87 
90  public override SecurityRuleSet SecurityRuleSet => InternalAssembly.SecurityRuleSet;
91 
94  public override Module ManifestModule => m_manifestModuleBuilder.InternalModule;
95 
99  public override bool ReflectionOnly => InternalAssembly.ReflectionOnly;
100 
103  public override bool GlobalAssemblyCache => InternalAssembly.GlobalAssemblyCache;
104 
107  public override long HostContext => InternalAssembly.HostContext;
108 
111  public override bool IsDynamic => true;
112 
113  [MethodImpl(MethodImplOptions.InternalCall)]
114  [SecurityCritical]
115  private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly);
116 
117  [SecurityCritical]
118  private Module nGetInMemoryAssemblyModule()
119  {
120  return GetInMemoryAssemblyModule(GetNativeHandle());
121  }
122 
123  [MethodImpl(MethodImplOptions.InternalCall)]
124  [SecurityCritical]
125  private static extern RuntimeModule GetOnDiskAssemblyModule(RuntimeAssembly assembly);
126 
127  [SecurityCritical]
128  private ModuleBuilder GetOnDiskAssemblyModuleBuilder()
129  {
130  if (m_onDiskAssemblyModuleBuilder == null)
131  {
132  Module onDiskAssemblyModule = GetOnDiskAssemblyModule(InternalAssembly.GetNativeHandle());
133  ModuleBuilder moduleBuilder = new ModuleBuilder(this, (InternalModuleBuilder)onDiskAssemblyModule);
134  moduleBuilder.Init("RefEmit_OnDiskManifestModule", null, 0);
135  m_onDiskAssemblyModuleBuilder = moduleBuilder;
136  }
137  return m_onDiskAssemblyModuleBuilder;
138  }
139 
140  internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
141  {
142  lock (SyncRoot)
143  {
144  foreach (ModuleBuilder moduleBuilder in m_assemblyData.m_moduleBuilderList)
145  {
146  if (moduleBuilder.InternalModule == module)
147  {
148  return moduleBuilder;
149  }
150  }
151  if (m_onDiskAssemblyModuleBuilder != null && m_onDiskAssemblyModuleBuilder.InternalModule == module)
152  {
153  return m_onDiskAssemblyModuleBuilder;
154  }
155  if (!(m_manifestModuleBuilder.InternalModule == module))
156  {
157  throw new ArgumentException("module");
158  }
159  return m_manifestModuleBuilder;
160  }
161  }
162 
163  internal RuntimeAssembly GetNativeHandle()
164  {
165  return InternalAssembly.GetNativeHandle();
166  }
167 
168  [SecurityCritical]
169  internal Version GetVersion()
170  {
171  return InternalAssembly.GetVersion();
172  }
173 
174  [SecurityCritical]
175  internal 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)
176  {
177  if (name == null)
178  {
179  throw new ArgumentNullException("name");
180  }
181  if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.Save && access != AssemblyBuilderAccess.RunAndSave && access != AssemblyBuilderAccess.ReflectionOnly && access != AssemblyBuilderAccess.RunAndCollect)
182  {
183  throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), "access");
184  }
185  if (securityContextSource < SecurityContextSource.CurrentAppDomain || securityContextSource > SecurityContextSource.CurrentAssembly)
186  {
187  throw new ArgumentOutOfRangeException("securityContextSource");
188  }
189  name = (AssemblyName)name.Clone();
190  if (name.KeyPair != null)
191  {
192  name.SetPublicKey(name.KeyPair.PublicKey);
193  }
194  if (evidence != null)
195  {
196  new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand();
197  }
198  if (access == AssemblyBuilderAccess.RunAndCollect)
199  {
200  new PermissionSet(PermissionState.Unrestricted).Demand();
201  }
202  List<CustomAttributeBuilder> list = null;
203  DynamicAssemblyFlags dynamicAssemblyFlags = DynamicAssemblyFlags.None;
204  byte[] array = null;
205  byte[] array2 = null;
206  if (unsafeAssemblyAttributes != null)
207  {
208  list = new List<CustomAttributeBuilder>(unsafeAssemblyAttributes);
209  foreach (CustomAttributeBuilder item in list)
210  {
211  if (item.m_con.DeclaringType == typeof(SecurityTransparentAttribute))
212  {
213  dynamicAssemblyFlags |= DynamicAssemblyFlags.Transparent;
214  }
215  else if (item.m_con.DeclaringType == typeof(SecurityCriticalAttribute))
216  {
217  SecurityCriticalScope securityCriticalScope = SecurityCriticalScope.Everything;
218  if (item.m_constructorArgs != null && item.m_constructorArgs.Length == 1 && item.m_constructorArgs[0] is SecurityCriticalScope)
219  {
220  securityCriticalScope = (SecurityCriticalScope)item.m_constructorArgs[0];
221  }
222  dynamicAssemblyFlags |= DynamicAssemblyFlags.Critical;
223  if (securityCriticalScope == SecurityCriticalScope.Everything)
224  {
225  dynamicAssemblyFlags |= DynamicAssemblyFlags.AllCritical;
226  }
227  }
228  else if (item.m_con.DeclaringType == typeof(SecurityRulesAttribute))
229  {
230  array = new byte[item.m_blob.Length];
231  Array.Copy(item.m_blob, array, array.Length);
232  }
233  else if (item.m_con.DeclaringType == typeof(SecurityTreatAsSafeAttribute))
234  {
235  dynamicAssemblyFlags |= DynamicAssemblyFlags.TreatAsSafe;
236  }
237  else if (item.m_con.DeclaringType == typeof(AllowPartiallyTrustedCallersAttribute))
238  {
239  dynamicAssemblyFlags |= DynamicAssemblyFlags.Aptca;
240  array2 = new byte[item.m_blob.Length];
241  Array.Copy(item.m_blob, array2, array2.Length);
242  }
243  }
244  }
245  m_internalAssemblyBuilder = (InternalAssemblyBuilder)nCreateDynamicAssembly(domain, name, evidence, ref stackMark, requiredPermissions, optionalPermissions, refusedPermissions, array, array2, access, dynamicAssemblyFlags, securityContextSource);
246  m_assemblyData = new AssemblyBuilderData(m_internalAssemblyBuilder, name.Name, access, dir);
247  m_assemblyData.AddPermissionRequests(requiredPermissions, optionalPermissions, refusedPermissions);
248  if (AppDomain.ProfileAPICheck)
249  {
250  RuntimeAssembly executingAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
251  if (executingAssembly != null && !executingAssembly.IsFrameworkAssembly())
252  {
253  m_profileAPICheck = true;
254  }
255  }
256  InitManifestModule();
257  if (list != null)
258  {
259  foreach (CustomAttributeBuilder item2 in list)
260  {
261  SetCustomAttribute(item2);
262  }
263  }
264  }
265 
266  [SecurityCritical]
267  private void InitManifestModule()
268  {
269  InternalModuleBuilder internalModuleBuilder = (InternalModuleBuilder)nGetInMemoryAssemblyModule();
270  m_manifestModuleBuilder = new ModuleBuilder(this, internalModuleBuilder);
271  m_manifestModuleBuilder.Init("RefEmit_InMemoryManifestModule", null, 0);
272  m_fManifestModuleUsedAsDefinedModule = false;
273  }
274 
279  [MethodImpl(MethodImplOptions.NoInlining)]
280  [SecuritySafeCritical]
282  {
283  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
284  return InternalDefineDynamicAssembly(name, access, null, null, null, null, null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
285  }
286 
292  [MethodImpl(MethodImplOptions.NoInlining)]
293  [SecuritySafeCritical]
295  {
296  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
297  return InternalDefineDynamicAssembly(name, access, null, null, null, null, null, ref stackMark, assemblyAttributes, SecurityContextSource.CurrentAssembly);
298  }
299 
300  [MethodImpl(MethodImplOptions.InternalCall)]
301  [SecurityCritical]
302  private static extern Assembly 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);
303 
304  [SecurityCritical]
305  internal static AssemblyBuilder InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, ref StackCrawlMark stackMark, IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes, SecurityContextSource securityContextSource)
306  {
307  if (evidence != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
308  {
309  throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyExplicit"));
310  }
311  lock (typeof(AssemblyBuilderLock))
312  {
313  return new AssemblyBuilder(AppDomain.CurrentDomain, name, access, dir, evidence, requiredPermissions, optionalPermissions, refusedPermissions, ref stackMark, unsafeAssemblyAttributes, securityContextSource);
314  }
315  }
316 
326  [MethodImpl(MethodImplOptions.NoInlining)]
327  [SecuritySafeCritical]
328  public ModuleBuilder DefineDynamicModule(string name)
329  {
330  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
331  return DefineDynamicModuleInternal(name, emitSymbolInfo: false, ref stackMark);
332  }
333 
345  [MethodImpl(MethodImplOptions.NoInlining)]
346  [SecuritySafeCritical]
347  public ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo)
348  {
349  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
350  return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark);
351  }
352 
353  [SecurityCritical]
354  private ModuleBuilder DefineDynamicModuleInternal(string name, bool emitSymbolInfo, ref StackCrawlMark stackMark)
355  {
356  lock (SyncRoot)
357  {
358  return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark);
359  }
360  }
361 
362  [SecurityCritical]
363  private ModuleBuilder DefineDynamicModuleInternalNoLock(string name, bool emitSymbolInfo, ref StackCrawlMark stackMark)
364  {
365  if (name == null)
366  {
367  throw new ArgumentNullException("name");
368  }
369  if (name.Length == 0)
370  {
371  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
372  }
373  if (name[0] == '\0')
374  {
375  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
376  }
377  ISymbolWriter symbolWriter = null;
378  IntPtr pInternalSymWriter = default(IntPtr);
379  m_assemblyData.CheckNameConflict(name);
380  ModuleBuilder moduleBuilder;
381  if (m_fManifestModuleUsedAsDefinedModule)
382  {
383  int tkFile;
384  InternalModuleBuilder internalModuleBuilder = (InternalModuleBuilder)DefineDynamicModule(InternalAssembly, emitSymbolInfo, name, name, ref stackMark, ref pInternalSymWriter, fIsTransient: true, out tkFile);
385  moduleBuilder = new ModuleBuilder(this, internalModuleBuilder);
386  moduleBuilder.Init(name, null, tkFile);
387  }
388  else
389  {
390  m_manifestModuleBuilder.ModifyModuleName(name);
391  moduleBuilder = m_manifestModuleBuilder;
392  if (emitSymbolInfo)
393  {
394  pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(moduleBuilder.InternalModule, name);
395  }
396  }
397  if (emitSymbolInfo)
398  {
399  Assembly assembly = LoadISymWrapper();
400  Type type = assembly.GetType("System.Diagnostics.SymbolStore.SymWriter", throwOnError: true, ignoreCase: false);
401  if (type != null && !type.IsVisible)
402  {
403  type = null;
404  }
405  if (type == null)
406  {
407  throw new TypeLoadException(Environment.GetResourceString("MissingType", "SymWriter"));
408  }
409  new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
410  try
411  {
412  new PermissionSet(PermissionState.Unrestricted).Assert();
413  symbolWriter = (ISymbolWriter)Activator.CreateInstance(type);
414  symbolWriter.SetUnderlyingWriter(pInternalSymWriter);
415  }
416  finally
417  {
419  }
420  }
421  moduleBuilder.SetSymWriter(symbolWriter);
422  m_assemblyData.AddModule(moduleBuilder);
423  if (moduleBuilder == m_manifestModuleBuilder)
424  {
425  m_fManifestModuleUsedAsDefinedModule = true;
426  }
427  return moduleBuilder;
428  }
429 
442  [MethodImpl(MethodImplOptions.NoInlining)]
443  [SecuritySafeCritical]
444  public ModuleBuilder DefineDynamicModule(string name, string fileName)
445  {
446  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
447  return DefineDynamicModuleInternal(name, fileName, emitSymbolInfo: false, ref stackMark);
448  }
449 
463  [MethodImpl(MethodImplOptions.NoInlining)]
464  [SecuritySafeCritical]
465  public ModuleBuilder DefineDynamicModule(string name, string fileName, bool emitSymbolInfo)
466  {
467  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
468  return DefineDynamicModuleInternal(name, fileName, emitSymbolInfo, ref stackMark);
469  }
470 
471  [SecurityCritical]
472  private ModuleBuilder DefineDynamicModuleInternal(string name, string fileName, bool emitSymbolInfo, ref StackCrawlMark stackMark)
473  {
474  lock (SyncRoot)
475  {
476  return DefineDynamicModuleInternalNoLock(name, fileName, emitSymbolInfo, ref stackMark);
477  }
478  }
479 
480  [SecurityCritical]
481  private ModuleBuilder DefineDynamicModuleInternalNoLock(string name, string fileName, bool emitSymbolInfo, ref StackCrawlMark stackMark)
482  {
483  if (name == null)
484  {
485  throw new ArgumentNullException("name");
486  }
487  if (name.Length == 0)
488  {
489  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
490  }
491  if (name[0] == '\0')
492  {
493  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
494  }
495  if (fileName == null)
496  {
497  throw new ArgumentNullException("fileName");
498  }
499  if (fileName.Length == 0)
500  {
501  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName");
502  }
503  if (!string.Equals(fileName, Path.GetFileName(fileName)))
504  {
505  throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
506  }
507  if (m_assemblyData.m_access == AssemblyBuilderAccess.Run)
508  {
509  throw new NotSupportedException(Environment.GetResourceString("Argument_BadPersistableModuleInTransientAssembly"));
510  }
511  if (m_assemblyData.m_isSaved)
512  {
513  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotAlterAssembly"));
514  }
515  ISymbolWriter symbolWriter = null;
516  IntPtr pInternalSymWriter = default(IntPtr);
517  m_assemblyData.CheckNameConflict(name);
518  m_assemblyData.CheckFileNameConflict(fileName);
519  int tkFile;
520  InternalModuleBuilder internalModuleBuilder = (InternalModuleBuilder)DefineDynamicModule(InternalAssembly, emitSymbolInfo, name, fileName, ref stackMark, ref pInternalSymWriter, fIsTransient: false, out tkFile);
521  ModuleBuilder moduleBuilder = new ModuleBuilder(this, internalModuleBuilder);
522  moduleBuilder.Init(name, fileName, tkFile);
523  if (emitSymbolInfo)
524  {
525  Assembly assembly = LoadISymWrapper();
526  Type type = assembly.GetType("System.Diagnostics.SymbolStore.SymWriter", throwOnError: true, ignoreCase: false);
527  if (type != null && !type.IsVisible)
528  {
529  type = null;
530  }
531  if (type == null)
532  {
533  throw new TypeLoadException(Environment.GetResourceString("MissingType", "SymWriter"));
534  }
535  try
536  {
537  new PermissionSet(PermissionState.Unrestricted).Assert();
538  symbolWriter = (ISymbolWriter)Activator.CreateInstance(type);
539  symbolWriter.SetUnderlyingWriter(pInternalSymWriter);
540  }
541  finally
542  {
544  }
545  }
546  moduleBuilder.SetSymWriter(symbolWriter);
547  m_assemblyData.AddModule(moduleBuilder);
548  return moduleBuilder;
549  }
550 
551  private Assembly LoadISymWrapper()
552  {
553  if (m_assemblyData.m_ISymWrapperAssembly != null)
554  {
555  return m_assemblyData.m_ISymWrapperAssembly;
556  }
557  Assembly assembly = Assembly.Load("ISymWrapper, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
558  m_assemblyData.m_ISymWrapperAssembly = assembly;
559  return assembly;
560  }
561 
562  internal void CheckContext(params Type[][] typess)
563  {
564  if (typess == null)
565  {
566  return;
567  }
568  foreach (Type[] array in typess)
569  {
570  if (array != null)
571  {
572  CheckContext(array);
573  }
574  }
575  }
576 
577  internal void CheckContext(params Type[] types)
578  {
579  if (types == null)
580  {
581  return;
582  }
583  int num = 0;
584  Type type;
585  while (true)
586  {
587  if (num >= types.Length)
588  {
589  return;
590  }
591  type = types[num];
592  if (!(type == null))
593  {
594  if (type.Module == null || type.Module.Assembly == null)
595  {
596  throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotValid"));
597  }
598  if (!(type.Module.Assembly == typeof(object).Module.Assembly))
599  {
600  if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly)
601  {
602  throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext1", type.AssemblyQualifiedName));
603  }
604  if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly)
605  {
606  break;
607  }
608  }
609  }
610  num++;
611  }
612  throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext2", type.AssemblyQualifiedName));
613  }
614 
626  public IResourceWriter DefineResource(string name, string description, string fileName)
627  {
628  return DefineResource(name, description, fileName, ResourceAttributes.Public);
629  }
630 
643  public IResourceWriter DefineResource(string name, string description, string fileName, ResourceAttributes attribute)
644  {
645  lock (SyncRoot)
646  {
647  return DefineResourceNoLock(name, description, fileName, attribute);
648  }
649  }
650 
651  private IResourceWriter DefineResourceNoLock(string name, string description, string fileName, ResourceAttributes attribute)
652  {
653  if (name == null)
654  {
655  throw new ArgumentNullException("name");
656  }
657  if (name.Length == 0)
658  {
659  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
660  }
661  if (fileName == null)
662  {
663  throw new ArgumentNullException("fileName");
664  }
665  if (fileName.Length == 0)
666  {
667  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "fileName");
668  }
669  if (!string.Equals(fileName, Path.GetFileName(fileName)))
670  {
671  throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
672  }
673  m_assemblyData.CheckResNameConflict(name);
674  m_assemblyData.CheckFileNameConflict(fileName);
675  ResourceWriter resourceWriter;
676  string text;
677  if (m_assemblyData.m_strDir == null)
678  {
679  text = Path.Combine(Environment.CurrentDirectory, fileName);
680  resourceWriter = new ResourceWriter(text);
681  }
682  else
683  {
684  text = Path.Combine(m_assemblyData.m_strDir, fileName);
685  resourceWriter = new ResourceWriter(text);
686  }
687  text = Path.GetFullPath(text);
688  fileName = Path.GetFileName(text);
689  m_assemblyData.AddResWriter(new ResWriterData(resourceWriter, null, name, fileName, text, attribute));
690  return resourceWriter;
691  }
692 
702  public void AddResourceFile(string name, string fileName)
703  {
704  AddResourceFile(name, fileName, ResourceAttributes.Public);
705  }
706 
718  public void AddResourceFile(string name, string fileName, ResourceAttributes attribute)
719  {
720  lock (SyncRoot)
721  {
722  AddResourceFileNoLock(name, fileName, attribute);
723  }
724  }
725 
726  [SecuritySafeCritical]
727  private void AddResourceFileNoLock(string name, string fileName, ResourceAttributes attribute)
728  {
729  if (name == null)
730  {
731  throw new ArgumentNullException("name");
732  }
733  if (name.Length == 0)
734  {
735  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), name);
736  }
737  if (fileName == null)
738  {
739  throw new ArgumentNullException("fileName");
740  }
741  if (fileName.Length == 0)
742  {
743  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), fileName);
744  }
745  if (!string.Equals(fileName, Path.GetFileName(fileName)))
746  {
747  throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "fileName");
748  }
749  m_assemblyData.CheckResNameConflict(name);
750  m_assemblyData.CheckFileNameConflict(fileName);
751  string path = (m_assemblyData.m_strDir != null) ? Path.Combine(m_assemblyData.m_strDir, fileName) : Path.Combine(Environment.CurrentDirectory, fileName);
752  path = Path.UnsafeGetFullPath(path);
753  fileName = Path.GetFileName(path);
754  if (!File.UnsafeExists(path))
755  {
756  throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", fileName), fileName);
757  }
758  m_assemblyData.AddResWriter(new ResWriterData(null, null, name, fileName, path, attribute));
759  }
760 
765  public override bool Equals(object obj)
766  {
767  return InternalAssembly.Equals(obj);
768  }
769 
772  public override int GetHashCode()
773  {
774  return InternalAssembly.GetHashCode();
775  }
776 
780  public override object[] GetCustomAttributes(bool inherit)
781  {
782  return InternalAssembly.GetCustomAttributes(inherit);
783  }
784 
793  public override object[] GetCustomAttributes(Type attributeType, bool inherit)
794  {
795  return InternalAssembly.GetCustomAttributes(attributeType, inherit);
796  }
797 
803  public override bool IsDefined(Type attributeType, bool inherit)
804  {
805  return InternalAssembly.IsDefined(attributeType, inherit);
806  }
807 
811  {
812  return InternalAssembly.GetCustomAttributesData();
813  }
814 
819  public override string[] GetManifestResourceNames()
820  {
821  return InternalAssembly.GetManifestResourceNames();
822  }
823 
829  public override FileStream GetFile(string name)
830  {
831  return InternalAssembly.GetFile(name);
832  }
833 
840  public override FileStream[] GetFiles(bool getResourceModules)
841  {
842  return InternalAssembly.GetFiles(getResourceModules);
843  }
844 
851  public override Stream GetManifestResourceStream(Type type, string name)
852  {
853  return InternalAssembly.GetManifestResourceStream(type, name);
854  }
855 
861  public override Stream GetManifestResourceStream(string name)
862  {
863  return InternalAssembly.GetManifestResourceStream(name);
864  }
865 
872  public override ManifestResourceInfo GetManifestResourceInfo(string resourceName)
873  {
874  return InternalAssembly.GetManifestResourceInfo(resourceName);
875  }
876 
881  public override Type[] GetExportedTypes()
882  {
883  return InternalAssembly.GetExportedTypes();
884  }
885 
890  public override AssemblyName GetName(bool copiedName)
891  {
892  return InternalAssembly.GetName(copiedName);
893  }
894 
902  public override Type GetType(string name, bool throwOnError, bool ignoreCase)
903  {
904  return InternalAssembly.GetType(name, throwOnError, ignoreCase);
905  }
906 
910  public override Module GetModule(string name)
911  {
912  return InternalAssembly.GetModule(name);
913  }
914 
918  {
919  return InternalAssembly.GetReferencedAssemblies();
920  }
921 
926  public override Module[] GetModules(bool getResourceModules)
927  {
928  return InternalAssembly.GetModules(getResourceModules);
929  }
930 
935  public override Module[] GetLoadedModules(bool getResourceModules)
936  {
937  return InternalAssembly.GetLoadedModules(getResourceModules);
938  }
939 
948  [MethodImpl(MethodImplOptions.NoInlining)]
949  public override Assembly GetSatelliteAssembly(CultureInfo culture)
950  {
951  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
952  return InternalAssembly.InternalGetSatelliteAssembly(culture, null, ref stackMark);
953  }
954 
964  [MethodImpl(MethodImplOptions.NoInlining)]
965  public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
966  {
967  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
968  return InternalAssembly.InternalGetSatelliteAssembly(culture, version, ref stackMark);
969  }
970 
979  public void DefineVersionInfoResource(string product, string productVersion, string company, string copyright, string trademark)
980  {
981  lock (SyncRoot)
982  {
983  DefineVersionInfoResourceNoLock(product, productVersion, company, copyright, trademark);
984  }
985  }
986 
987  private void DefineVersionInfoResourceNoLock(string product, string productVersion, string company, string copyright, string trademark)
988  {
989  if (m_assemblyData.m_strResourceFileName != null || m_assemblyData.m_resourceBytes != null || m_assemblyData.m_nativeVersion != null)
990  {
991  throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
992  }
993  m_assemblyData.m_nativeVersion = new NativeVersionInfo();
994  m_assemblyData.m_nativeVersion.m_strCopyright = copyright;
995  m_assemblyData.m_nativeVersion.m_strTrademark = trademark;
996  m_assemblyData.m_nativeVersion.m_strCompany = company;
997  m_assemblyData.m_nativeVersion.m_strProduct = product;
998  m_assemblyData.m_nativeVersion.m_strProductVersion = productVersion;
999  m_assemblyData.m_hasUnmanagedVersionInfo = true;
1000  m_assemblyData.m_OverrideUnmanagedVersionInfo = true;
1001  }
1002 
1007  {
1008  lock (SyncRoot)
1009  {
1010  DefineVersionInfoResourceNoLock();
1011  }
1012  }
1013 
1014  private void DefineVersionInfoResourceNoLock()
1015  {
1016  if (m_assemblyData.m_strResourceFileName != null || m_assemblyData.m_resourceBytes != null || m_assemblyData.m_nativeVersion != null)
1017  {
1018  throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1019  }
1020  m_assemblyData.m_hasUnmanagedVersionInfo = true;
1021  m_assemblyData.m_nativeVersion = new NativeVersionInfo();
1022  }
1023 
1030  public void DefineUnmanagedResource(byte[] resource)
1031  {
1032  if (resource == null)
1033  {
1034  throw new ArgumentNullException("resource");
1035  }
1036  lock (SyncRoot)
1037  {
1038  DefineUnmanagedResourceNoLock(resource);
1039  }
1040  }
1041 
1042  private void DefineUnmanagedResourceNoLock(byte[] resource)
1043  {
1044  if (m_assemblyData.m_strResourceFileName != null || m_assemblyData.m_resourceBytes != null || m_assemblyData.m_nativeVersion != null)
1045  {
1046  throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1047  }
1048  m_assemblyData.m_resourceBytes = new byte[resource.Length];
1049  Array.Copy(resource, m_assemblyData.m_resourceBytes, resource.Length);
1050  }
1051 
1062  [SecuritySafeCritical]
1063  public void DefineUnmanagedResource(string resourceFileName)
1064  {
1065  if (resourceFileName == null)
1066  {
1067  throw new ArgumentNullException("resourceFileName");
1068  }
1069  lock (SyncRoot)
1070  {
1071  DefineUnmanagedResourceNoLock(resourceFileName);
1072  }
1073  }
1074 
1075  [SecurityCritical]
1076  private void DefineUnmanagedResourceNoLock(string resourceFileName)
1077  {
1078  if (m_assemblyData.m_strResourceFileName != null || m_assemblyData.m_resourceBytes != null || m_assemblyData.m_nativeVersion != null)
1079  {
1080  throw new ArgumentException(Environment.GetResourceString("Argument_NativeResourceAlreadyDefined"));
1081  }
1082  string text;
1083  if (m_assemblyData.m_strDir == null)
1084  {
1085  text = Path.Combine(Environment.CurrentDirectory, resourceFileName);
1086  }
1087  else
1088  {
1089  text = Path.Combine(m_assemblyData.m_strDir, resourceFileName);
1090  }
1091  text = Path.GetFullPath(resourceFileName);
1093  if (!File.Exists(text))
1094  {
1095  throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", resourceFileName), resourceFileName);
1096  }
1097  m_assemblyData.m_strResourceFileName = text;
1098  }
1099 
1107  public ModuleBuilder GetDynamicModule(string name)
1108  {
1109  lock (SyncRoot)
1110  {
1111  return GetDynamicModuleNoLock(name);
1112  }
1113  }
1114 
1115  private ModuleBuilder GetDynamicModuleNoLock(string name)
1116  {
1117  if (name == null)
1118  {
1119  throw new ArgumentNullException("name");
1120  }
1121  if (name.Length == 0)
1122  {
1123  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name");
1124  }
1125  int count = m_assemblyData.m_moduleBuilderList.Count;
1126  for (int i = 0; i < count; i++)
1127  {
1128  ModuleBuilder moduleBuilder = m_assemblyData.m_moduleBuilderList[i];
1129  if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name))
1130  {
1131  return moduleBuilder;
1132  }
1133  }
1134  return null;
1135  }
1136 
1144  public void SetEntryPoint(MethodInfo entryMethod)
1145  {
1146  SetEntryPoint(entryMethod, PEFileKinds.ConsoleApplication);
1147  }
1148 
1157  public void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind)
1158  {
1159  lock (SyncRoot)
1160  {
1161  SetEntryPointNoLock(entryMethod, fileKind);
1162  }
1163  }
1164 
1165  private void SetEntryPointNoLock(MethodInfo entryMethod, PEFileKinds fileKind)
1166  {
1167  if (entryMethod == null)
1168  {
1169  throw new ArgumentNullException("entryMethod");
1170  }
1171  Module module = entryMethod.Module;
1172  if (module == null || !InternalAssembly.Equals(module.Assembly))
1173  {
1174  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EntryMethodNotDefinedInAssembly"));
1175  }
1176  m_assemblyData.m_entryPointMethod = entryMethod;
1177  m_assemblyData.m_peFileKind = fileKind;
1178  ModuleBuilder moduleBuilder = module as ModuleBuilder;
1179  if (moduleBuilder != null)
1180  {
1181  m_assemblyData.m_entryPointModule = moduleBuilder;
1182  }
1183  else
1184  {
1185  m_assemblyData.m_entryPointModule = GetModuleBuilder((InternalModuleBuilder)module);
1186  }
1187  MethodToken methodToken = m_assemblyData.m_entryPointModule.GetMethodToken(entryMethod);
1188  m_assemblyData.m_entryPointModule.SetEntryPoint(methodToken);
1189  }
1190 
1199  [SecuritySafeCritical]
1200  [ComVisible(true)]
1201  public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
1202  {
1203  if (con == null)
1204  {
1205  throw new ArgumentNullException("con");
1206  }
1207  if (binaryAttribute == null)
1208  {
1209  throw new ArgumentNullException("binaryAttribute");
1210  }
1211  lock (SyncRoot)
1212  {
1213  SetCustomAttributeNoLock(con, binaryAttribute);
1214  }
1215  }
1216 
1217  [SecurityCritical]
1218  private void SetCustomAttributeNoLock(ConstructorInfo con, byte[] binaryAttribute)
1219  {
1220  TypeBuilder.DefineCustomAttribute(m_manifestModuleBuilder, 536870913, m_manifestModuleBuilder.GetConstructorToken(con).Token, binaryAttribute, toDisk: false, typeof(DebuggableAttribute) == con.DeclaringType);
1221  if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
1222  {
1223  m_assemblyData.AddCustomAttribute(con, binaryAttribute);
1224  }
1225  }
1226 
1232  [SecuritySafeCritical]
1233  public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
1234  {
1235  if (customBuilder == null)
1236  {
1237  throw new ArgumentNullException("customBuilder");
1238  }
1239  lock (SyncRoot)
1240  {
1241  SetCustomAttributeNoLock(customBuilder);
1242  }
1243  }
1244 
1245  [SecurityCritical]
1246  private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
1247  {
1248  customBuilder.CreateCustomAttribute(m_manifestModuleBuilder, 536870913);
1249  if (m_assemblyData.m_access != AssemblyBuilderAccess.Run)
1250  {
1251  m_assemblyData.AddCustomAttribute(customBuilder);
1252  }
1253  }
1254 
1265  public void Save(string assemblyFileName)
1266  {
1267  Save(assemblyFileName, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
1268  }
1269 
1282  [SecuritySafeCritical]
1283  public void Save(string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
1284  {
1285  lock (SyncRoot)
1286  {
1287  SaveNoLock(assemblyFileName, portableExecutableKind, imageFileMachine);
1288  }
1289  }
1290 
1291  [SecurityCritical]
1292  private void SaveNoLock(string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
1293  {
1294  if (assemblyFileName == null)
1295  {
1296  throw new ArgumentNullException("assemblyFileName");
1297  }
1298  if (assemblyFileName.Length == 0)
1299  {
1300  throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "assemblyFileName");
1301  }
1302  if (!string.Equals(assemblyFileName, Path.GetFileName(assemblyFileName)))
1303  {
1304  throw new ArgumentException(Environment.GetResourceString("Argument_NotSimpleFileName"), "assemblyFileName");
1305  }
1306  int[] array = null;
1307  int[] array2 = null;
1308  string s = null;
1309  try
1310  {
1311  if (m_assemblyData.m_iCABuilder != 0)
1312  {
1313  array = new int[m_assemblyData.m_iCABuilder];
1314  }
1315  if (m_assemblyData.m_iCAs != 0)
1316  {
1317  array2 = new int[m_assemblyData.m_iCAs];
1318  }
1319  if (m_assemblyData.m_isSaved)
1320  {
1321  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AssemblyHasBeenSaved", InternalAssembly.GetSimpleName()));
1322  }
1323  if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) != AssemblyBuilderAccess.Save)
1324  {
1325  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CantSaveTransientAssembly"));
1326  }
1327  ModuleBuilder moduleBuilder = m_assemblyData.FindModuleWithFileName(assemblyFileName);
1328  if (moduleBuilder != null)
1329  {
1330  m_onDiskAssemblyModuleBuilder = moduleBuilder;
1331  moduleBuilder.m_moduleData.FileToken = 0;
1332  }
1333  else
1334  {
1335  m_assemblyData.CheckFileNameConflict(assemblyFileName);
1336  }
1337  if (m_assemblyData.m_strDir == null)
1338  {
1339  m_assemblyData.m_strDir = Environment.CurrentDirectory;
1340  }
1341  else if (!Directory.Exists(m_assemblyData.m_strDir))
1342  {
1343  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectory", m_assemblyData.m_strDir));
1344  }
1345  assemblyFileName = Path.Combine(m_assemblyData.m_strDir, assemblyFileName);
1346  assemblyFileName = Path.GetFullPath(assemblyFileName);
1347  new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, assemblyFileName).Demand();
1348  if (moduleBuilder != null)
1349  {
1350  for (int i = 0; i < m_assemblyData.m_iCABuilder; i++)
1351  {
1352  array[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(moduleBuilder);
1353  }
1354  for (int i = 0; i < m_assemblyData.m_iCAs; i++)
1355  {
1356  array2[i] = moduleBuilder.InternalGetConstructorToken(m_assemblyData.m_CACons[i], usingRef: true).Token;
1357  }
1358  moduleBuilder.PreSave(assemblyFileName, portableExecutableKind, imageFileMachine);
1359  }
1360  RuntimeModule assemblyModule = (moduleBuilder != null) ? moduleBuilder.ModuleHandle.GetRuntimeModule() : null;
1361  PrepareForSavingManifestToDisk(GetNativeHandle(), assemblyModule);
1362  ModuleBuilder onDiskAssemblyModuleBuilder = GetOnDiskAssemblyModuleBuilder();
1363  if (m_assemblyData.m_strResourceFileName != null)
1364  {
1365  onDiskAssemblyModuleBuilder.DefineUnmanagedResourceFileInternalNoLock(m_assemblyData.m_strResourceFileName);
1366  }
1367  else if (m_assemblyData.m_resourceBytes != null)
1368  {
1369  onDiskAssemblyModuleBuilder.DefineUnmanagedResourceInternalNoLock(m_assemblyData.m_resourceBytes);
1370  }
1371  else if (m_assemblyData.m_hasUnmanagedVersionInfo)
1372  {
1373  m_assemblyData.FillUnmanagedVersionInfo();
1374  string text = m_assemblyData.m_nativeVersion.m_strFileVersion;
1375  if (text == null)
1376  {
1377  text = GetVersion().ToString();
1378  }
1379  CreateVersionInfoResource(assemblyFileName, m_assemblyData.m_nativeVersion.m_strTitle, null, m_assemblyData.m_nativeVersion.m_strDescription, m_assemblyData.m_nativeVersion.m_strCopyright, m_assemblyData.m_nativeVersion.m_strTrademark, m_assemblyData.m_nativeVersion.m_strCompany, m_assemblyData.m_nativeVersion.m_strProduct, m_assemblyData.m_nativeVersion.m_strProductVersion, text, m_assemblyData.m_nativeVersion.m_lcid, m_assemblyData.m_peFileKind == PEFileKinds.Dll, JitHelpers.GetStringHandleOnStack(ref s));
1380  onDiskAssemblyModuleBuilder.DefineUnmanagedResourceFileInternalNoLock(s);
1381  }
1382  if (moduleBuilder == null)
1383  {
1384  for (int i = 0; i < m_assemblyData.m_iCABuilder; i++)
1385  {
1386  array[i] = m_assemblyData.m_CABuilders[i].PrepareCreateCustomAttributeToDisk(onDiskAssemblyModuleBuilder);
1387  }
1388  for (int i = 0; i < m_assemblyData.m_iCAs; i++)
1389  {
1390  array2[i] = onDiskAssemblyModuleBuilder.InternalGetConstructorToken(m_assemblyData.m_CACons[i], usingRef: true).Token;
1391  }
1392  }
1393  int count = m_assemblyData.m_moduleBuilderList.Count;
1394  for (int i = 0; i < count; i++)
1395  {
1396  ModuleBuilder moduleBuilder2 = m_assemblyData.m_moduleBuilderList[i];
1397  if (!moduleBuilder2.IsTransient() && moduleBuilder2 != moduleBuilder)
1398  {
1399  string text2 = moduleBuilder2.m_moduleData.m_strFileName;
1400  if (m_assemblyData.m_strDir != null)
1401  {
1402  text2 = Path.Combine(m_assemblyData.m_strDir, text2);
1403  text2 = Path.GetFullPath(text2);
1404  }
1406  moduleBuilder2.m_moduleData.FileToken = AddFile(GetNativeHandle(), moduleBuilder2.m_moduleData.m_strFileName);
1407  moduleBuilder2.PreSave(text2, portableExecutableKind, imageFileMachine);
1408  moduleBuilder2.Save(text2, isAssemblyFile: false, portableExecutableKind, imageFileMachine);
1409  SetFileHashValue(GetNativeHandle(), moduleBuilder2.m_moduleData.FileToken, text2);
1410  }
1411  }
1412  for (int i = 0; i < m_assemblyData.m_iPublicComTypeCount; i++)
1413  {
1414  Type type = m_assemblyData.m_publicComTypeList[i];
1415  if (type is RuntimeType)
1416  {
1417  InternalModuleBuilder module = (InternalModuleBuilder)type.Module;
1418  ModuleBuilder moduleBuilder3 = GetModuleBuilder(module);
1419  if (moduleBuilder3 != moduleBuilder)
1420  {
1421  DefineNestedComType(type, moduleBuilder3.m_moduleData.FileToken, type.MetadataToken);
1422  }
1423  }
1424  else
1425  {
1426  TypeBuilder typeBuilder = (TypeBuilder)type;
1427  ModuleBuilder moduleBuilder3 = typeBuilder.GetModuleBuilder();
1428  if (moduleBuilder3 != moduleBuilder)
1429  {
1430  DefineNestedComType(type, moduleBuilder3.m_moduleData.FileToken, typeBuilder.MetadataTokenInternal);
1431  }
1432  }
1433  }
1434  if (onDiskAssemblyModuleBuilder != m_manifestModuleBuilder)
1435  {
1436  for (int i = 0; i < m_assemblyData.m_iCABuilder; i++)
1437  {
1438  m_assemblyData.m_CABuilders[i].CreateCustomAttribute(onDiskAssemblyModuleBuilder, 536870913, array[i], toDisk: true);
1439  }
1440  for (int i = 0; i < m_assemblyData.m_iCAs; i++)
1441  {
1442  TypeBuilder.DefineCustomAttribute(onDiskAssemblyModuleBuilder, 536870913, array2[i], m_assemblyData.m_CABytes[i], toDisk: true, updateCompilerFlags: false);
1443  }
1444  }
1445  if (m_assemblyData.m_RequiredPset != null)
1446  {
1447  AddDeclarativeSecurity(m_assemblyData.m_RequiredPset, SecurityAction.RequestMinimum);
1448  }
1449  if (m_assemblyData.m_RefusedPset != null)
1450  {
1451  AddDeclarativeSecurity(m_assemblyData.m_RefusedPset, SecurityAction.RequestRefuse);
1452  }
1453  if (m_assemblyData.m_OptionalPset != null)
1454  {
1455  AddDeclarativeSecurity(m_assemblyData.m_OptionalPset, SecurityAction.RequestOptional);
1456  }
1457  count = m_assemblyData.m_resWriterList.Count;
1458  for (int i = 0; i < count; i++)
1459  {
1460  ResWriterData resWriterData = null;
1461  try
1462  {
1463  resWriterData = m_assemblyData.m_resWriterList[i];
1464  if (resWriterData.m_resWriter != null)
1465  {
1466  new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, resWriterData.m_strFullFileName).Demand();
1467  }
1468  }
1469  finally
1470  {
1471  if (resWriterData != null && resWriterData.m_resWriter != null)
1472  {
1473  resWriterData.m_resWriter.Close();
1474  }
1475  }
1476  AddStandAloneResource(GetNativeHandle(), resWriterData.m_strName, resWriterData.m_strFileName, resWriterData.m_strFullFileName, (int)resWriterData.m_attribute);
1477  }
1478  if (moduleBuilder == null)
1479  {
1480  onDiskAssemblyModuleBuilder.DefineNativeResource(portableExecutableKind, imageFileMachine);
1481  int entryPoint = (m_assemblyData.m_entryPointModule != null) ? m_assemblyData.m_entryPointModule.m_moduleData.FileToken : 0;
1482  SaveManifestToDisk(GetNativeHandle(), assemblyFileName, entryPoint, (int)m_assemblyData.m_peFileKind, (int)portableExecutableKind, (int)imageFileMachine);
1483  }
1484  else
1485  {
1486  if (m_assemblyData.m_entryPointModule != null && m_assemblyData.m_entryPointModule != moduleBuilder)
1487  {
1488  moduleBuilder.SetEntryPoint(new MethodToken(m_assemblyData.m_entryPointModule.m_moduleData.FileToken));
1489  }
1490  moduleBuilder.Save(assemblyFileName, isAssemblyFile: true, portableExecutableKind, imageFileMachine);
1491  }
1492  m_assemblyData.m_isSaved = true;
1493  }
1494  finally
1495  {
1496  if (s != null)
1497  {
1498  File.Delete(s);
1499  }
1500  }
1501  }
1502 
1503  [SecurityCritical]
1504  private void AddDeclarativeSecurity(PermissionSet pset, SecurityAction action)
1505  {
1506  byte[] array = pset.EncodeXml();
1507  AddDeclarativeSecurity(GetNativeHandle(), action, array, array.Length);
1508  }
1509 
1510  internal bool IsPersistable()
1511  {
1512  if ((m_assemblyData.m_access & AssemblyBuilderAccess.Save) == AssemblyBuilderAccess.Save)
1513  {
1514  return true;
1515  }
1516  return false;
1517  }
1518 
1519  [SecurityCritical]
1520  private int DefineNestedComType(Type type, int tkResolutionScope, int tkTypeDef)
1521  {
1522  Type declaringType = type.DeclaringType;
1523  if (declaringType == null)
1524  {
1525  return AddExportedTypeOnDisk(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
1526  }
1527  tkResolutionScope = DefineNestedComType(declaringType, tkResolutionScope, tkTypeDef);
1528  return AddExportedTypeOnDisk(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
1529  }
1530 
1531  [SecurityCritical]
1532  internal int DefineExportedTypeInMemory(Type type, int tkResolutionScope, int tkTypeDef)
1533  {
1534  Type declaringType = type.DeclaringType;
1535  if (declaringType == null)
1536  {
1537  return AddExportedTypeInMemory(GetNativeHandle(), type.FullName, tkResolutionScope, tkTypeDef, type.Attributes);
1538  }
1539  tkResolutionScope = DefineExportedTypeInMemory(declaringType, tkResolutionScope, tkTypeDef);
1540  return AddExportedTypeInMemory(GetNativeHandle(), type.Name, tkResolutionScope, tkTypeDef, type.Attributes);
1541  }
1542 
1543  private AssemblyBuilder()
1544  {
1545  }
1546 
1550  void _AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)
1551  {
1552  throw new NotImplementedException();
1553  }
1554 
1560  void _AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
1561  {
1562  throw new NotImplementedException();
1563  }
1564 
1572  void _AssemblyBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1573  {
1574  throw new NotImplementedException();
1575  }
1576 
1587  void _AssemblyBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1588  {
1589  throw new NotImplementedException();
1590  }
1591 
1592  [DllImport("QCall", CharSet = CharSet.Unicode)]
1593  [SecurityCritical]
1594  [SuppressUnmanagedCodeSecurity]
1595  private static extern void DefineDynamicModule(RuntimeAssembly containingAssembly, bool emitSymbolInfo, string name, string filename, StackCrawlMarkHandle stackMark, ref IntPtr pInternalSymWriter, ObjectHandleOnStack retModule, bool fIsTransient, out int tkFile);
1596 
1597  [SecurityCritical]
1598  private static Module DefineDynamicModule(RuntimeAssembly containingAssembly, bool emitSymbolInfo, string name, string filename, ref StackCrawlMark stackMark, ref IntPtr pInternalSymWriter, bool fIsTransient, out int tkFile)
1599  {
1600  RuntimeModule o = null;
1601  DefineDynamicModule(containingAssembly.GetNativeHandle(), emitSymbolInfo, name, filename, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), ref pInternalSymWriter, JitHelpers.GetObjectHandleOnStack(ref o), fIsTransient, out tkFile);
1602  return o;
1603  }
1604 
1605  [DllImport("QCall", CharSet = CharSet.Unicode)]
1606  [SecurityCritical]
1607  [SuppressUnmanagedCodeSecurity]
1608  private static extern void PrepareForSavingManifestToDisk(RuntimeAssembly assembly, RuntimeModule assemblyModule);
1609 
1610  [DllImport("QCall", CharSet = CharSet.Unicode)]
1611  [SecurityCritical]
1612  [SuppressUnmanagedCodeSecurity]
1613  private static extern void SaveManifestToDisk(RuntimeAssembly assembly, string strFileName, int entryPoint, int fileKind, int portableExecutableKind, int ImageFileMachine);
1614 
1615  [DllImport("QCall", CharSet = CharSet.Unicode)]
1616  [SecurityCritical]
1617  [SuppressUnmanagedCodeSecurity]
1618  private static extern int AddFile(RuntimeAssembly assembly, string strFileName);
1619 
1620  [DllImport("QCall", CharSet = CharSet.Unicode)]
1621  [SecurityCritical]
1622  [SuppressUnmanagedCodeSecurity]
1623  private static extern void SetFileHashValue(RuntimeAssembly assembly, int tkFile, string strFullFileName);
1624 
1625  [DllImport("QCall", CharSet = CharSet.Unicode)]
1626  [SecurityCritical]
1627  [SuppressUnmanagedCodeSecurity]
1628  private static extern int AddExportedTypeInMemory(RuntimeAssembly assembly, string strComTypeName, int tkAssemblyRef, int tkTypeDef, TypeAttributes flags);
1629 
1630  [DllImport("QCall", CharSet = CharSet.Unicode)]
1631  [SecurityCritical]
1632  [SuppressUnmanagedCodeSecurity]
1633  private static extern int AddExportedTypeOnDisk(RuntimeAssembly assembly, string strComTypeName, int tkAssemblyRef, int tkTypeDef, TypeAttributes flags);
1634 
1635  [DllImport("QCall", CharSet = CharSet.Unicode)]
1636  [SecurityCritical]
1637  [SuppressUnmanagedCodeSecurity]
1638  private static extern void AddStandAloneResource(RuntimeAssembly assembly, string strName, string strFileName, string strFullFileName, int attribute);
1639 
1640  [DllImport("QCall", CharSet = CharSet.Unicode)]
1641  [SecurityCritical]
1642  [SuppressUnmanagedCodeSecurity]
1643  private static extern void AddDeclarativeSecurity(RuntimeAssembly assembly, SecurityAction action, byte[] blob, int length);
1644 
1645  [DllImport("QCall", CharSet = CharSet.Unicode)]
1646  [SecurityCritical]
1647  [SuppressUnmanagedCodeSecurity]
1648  private static extern void 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);
1649  }
1650 }
Performs reflection on a module.
Definition: Module.cs:17
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
Maps a set of names to a corresponding set of dispatch identifiers.
virtual Assembly Assembly
Gets the appropriate T:System.Reflection.Assembly for this instance of T:System.Reflection....
Definition: Module.cs:133
override Stream GetManifestResourceStream(Type type, string name)
Loads the specified manifest resource, scoped by the namespace of the specified type,...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
FileIOPermissionAccess
Specifies the type of file access requested.
override object [] GetCustomAttributes(Type attributeType, bool inherit)
Returns all the custom attributes that have been applied to the current T:System.Reflection....
void Save(string assemblyFileName)
Saves this dynamic assembly to disk.
override string [] GetManifestResourceNames()
Loads the specified manifest resource from this assembly.
Provides the base functionality for writing resources to an output file or stream.
static bool Exists(string path)
Determines whether the specified file exists.
Definition: File.cs:435
static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
Defines a dynamic assembly that has the specified name and access rights.
override Type GetType(string name, bool throwOnError, bool ignoreCase)
Gets the specified type from the types that have been defined and created in the current T:System....
static string Combine(string path1, string path2)
Combines two strings into a path.
Definition: Path.cs:1107
void DefineUnmanagedResource(byte[] resource)
Defines an unmanaged resource for this assembly as an opaque blob of bytes.
Discovers the attributes of a method and provides access to method metadata.
Definition: MethodInfo.cs:13
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
Specifies that an assembly cannot cause an elevation of privilege.
void SetUnderlyingWriter(IntPtr underlyingWriter)
Sets the underlying ISymUnmanagedWriter (the corresponding unmanaged interface) that a managed T:Syst...
Exposes the T:System.Reflection.Emit.AssemblyBuilder class to unmanaged code.
override AssemblyName [] GetReferencedAssemblies()
Gets an incomplete list of T:System.Reflection.AssemblyName objects for the assemblies that are refer...
void AddResourceFile(string name, string fileName)
Adds an existing resource file to this assembly.
Discovers the attributes of a class constructor and provides access to constructor metadata.
override string FullName
Gets the display name of the current dynamic assembly.
Definition: __Canon.cs:3
override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
Gets the specified version of the satellite assembly for the specified culture.
ImageFileMachine
Identifies the platform targeted by an executable.
override FileStream GetFile(string name)
Gets a T:System.IO.FileStream for the specified file in the file table of the manifest of this assemb...
SecurityContextSource
Identifies the source for the security context.
ModuleBuilder GetDynamicModule(string name)
Returns the dynamic module with the specified name.
ModuleBuilder DefineDynamicModule(string name)
Defines a named transient dynamic module in this assembly.
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
Retrieves the type information for an object, which can be used to get the type information for an in...
override Module [] GetModules(bool getResourceModules)
Gets all the modules that are part of this assembly, and optionally includes resource modules.
Defines and represents a dynamic assembly.
Exposes the enumerator, which supports a simple iteration over a collection of a specified type....
Definition: IEnumerable.cs:9
void SetCustomAttribute(CustomAttributeBuilder customBuilder)
Set a custom attribute on this assembly using a custom attribute builder.
static string GetFileName(string path)
Returns the file name and extension of the specified path string.
Definition: Path.cs:914
void DefineVersionInfoResource()
Defines an unmanaged version information resource using the information specified in the assembly's A...
AssemblyBuilderAccess
Defines the access modes for a dynamic assembly.
Allows an assembly to be called by partially trusted code. Without this declaration,...
override AssemblyName GetName(bool copiedName)
Gets the T:System.Reflection.AssemblyName that was specified when the current dynamic assembly was cr...
Evidence()
Initializes a new empty instance of the T:System.Security.Policy.Evidence class.
Definition: Evidence.cs:505
static AppDomain CurrentDomain
Gets the current application domain for the current T:System.Threading.Thread.
Definition: AppDomain.cs:274
Represents an application domain, which is an isolated environment where applications execute....
Definition: AppDomain.cs:33
void SetEntryPoint(MethodInfo entryMethod, PEFileKinds fileKind)
Sets the entry point for this assembly and defines the type of the portable executable (PE file) bein...
void DefineVersionInfoResource(string product, string productVersion, string company, string copyright, string trademark)
Defines an unmanaged version information resource for this assembly with the given specifications.
MethodToken GetConstructorToken(ConstructorInfo constructor, IEnumerable< Type > optionalParameterTypes)
Returns the token used to identify the constructor that has the specified attributes and parameter ty...
override string ToString()
Converts the value of the current T:System.Version object to its equivalent T:System....
Definition: Version.cs:437
Modifies code generation for runtime just-in-time (JIT) debugging. This class cannot be inherited.
SecurityAction
Specifies the security actions that can be performed using declarative security.
override MethodInfo EntryPoint
Returns the entry point of this assembly.
Indicates the set of security rules the common language runtime should enforce for an assembly.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
override Module [] GetLoadedModules(bool getResourceModules)
Returns all the loaded modules that are part of this assembly, and optionally includes resource modul...
override FileStream [] GetFiles(bool getResourceModules)
Gets the files in the file table of an assembly manifest, specifying whether to include resource modu...
Represents a collection that can contain many different types of permissions.
override IList< CustomAttributeData > GetCustomAttributesData()
Returns T:System.Reflection.CustomAttributeData objects that contain information about the attributes...
Defines and creates new instances of classes during run time.
Definition: TypeBuilder.cs:15
override Stream GetManifestResourceStream(string name)
Loads the specified manifest resource from this assembly.
Exposes static methods for creating, moving, and enumerating through directories and subdirectories....
Definition: Directory.cs:14
override string ImageRuntimeVersion
Gets the version of the common language runtime that will be saved in the file containing the manifes...
Defines and represents a module in a dynamic assembly.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
override Module GetModule(string name)
Gets the specified module in this assembly.
Represents an assembly, which is a reusable, versionable, and self-describing building block of a com...
Definition: Assembly.cs:22
Defines the underlying structure of all code access permissions.
Specifies that code or an assembly performs security-critical operations.
void AddResourceFile(string name, string fileName, ResourceAttributes attribute)
Adds an existing resource file to this assembly.
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
Provides access to properties and methods exposed by an object.
static bool Exists(string path)
Determines whether the given path refers to an existing directory on disk.
Definition: Directory.cs:312
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Definition: Array.cs:17
Represents type declarations: class types, interface types, array types, value types,...
Definition: Type.cs:18
Represents the version number of an assembly, operating system, or the common language runtime....
Definition: Version.cs:11
void GetTypeInfoCount(out uint pcTInfo)
Retrieves the number of type information interfaces that an object provides (either 0 or 1).
Provides access to manifest resources, which are XML files that describe application dependencies.
static string GetFullPath(string path)
Returns the absolute path for the specified path string.
Definition: Path.cs:446
MethodImplOptions
Defines the details of how a method is implemented.
ModuleBuilder DefineDynamicModule(string name, string fileName)
Defines a persistable dynamic module with the given name that will be saved to the specified file....
IResourceWriter DefineResource(string name, string description, string fileName, ResourceAttributes attribute)
Defines a standalone managed resource for this assembly. Attributes can be specified for the managed ...
CharSet
Dictates which character set marshaled strings should use.
Definition: CharSet.cs:7
void SetEntryPoint(MethodInfo entryMethod)
Sets the entry point for this dynamic assembly, assuming that a console application is being built.
override bool GlobalAssemblyCache
Gets a value that indicates whether the assembly was loaded from the global assembly cache.
override Module ManifestModule
Gets the module in the current T:System.Reflection.Emit.AssemblyBuilder that contains the assembly ma...
TypeAttributes
Specifies type attributes.
override long HostContext
Gets the host context where the dynamic assembly is being created.
static void RevertAssert()
Causes any previous M:System.Security.CodeAccessPermission.Assert for the current frame to be removed...
Describes an assembly's unique identity in full.
Definition: AssemblyName.cs:19
Type DeclaringType
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
Represents a collection of objects that can be individually accessed by index.
Definition: IList.cs:9
SecurityRuleSet
Identifies the set of security rules the common language runtime should enforce for an assembly.
Attribute can be applied to an assembly.
The exception that is thrown when one of the arguments provided to a method is not valid.
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
override bool IsDynamic
Gets a value that indicates that the current assembly is a dynamic assembly.
override PermissionSet PermissionSet
Gets the grant set of the current dynamic assembly.
Attribute can be applied to a module.
The exception that is thrown when an attempt to access a file that does not exist on disk fails.
override bool ReflectionOnly
Gets a value indicating whether the dynamic assembly is in the reflection-only context.
ResourceAttributes
Specifies the attributes for a manifest resource.
static void Copy(Array sourceArray, Array destinationArray, int length)
Copies a range of elements from an T:System.Array starting at the first element and pastes them into ...
Definition: Array.cs:1275
Writes resources in the system-default format to an output file or an output stream....
static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable< CustomAttributeBuilder > assemblyAttributes)
Defines a new assembly that has the specified name, access rights, and attributes.
IResourceWriter DefineResource(string name, string description, string fileName)
Defines a standalone managed resource for this assembly with the default public resource attribute.
void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
Set a custom attribute on this assembly using a specified custom attribute blob.
Represents a symbol writer for managed code.
Definition: ISymbolWriter.cs:8
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search...
Definition: List.cs:14
Identifies which of the nonpublic T:System.Security.SecurityCriticalAttribute members are accessible ...
PermissionState
Specifies whether a permission should have all or no access to resources at creation.
int Token
Returns the metadata token for this method.
Definition: MethodToken.cs:17
override Assembly GetSatelliteAssembly(CultureInfo culture)
Gets the satellite assembly for the specified culture.
override Type [] GetExportedTypes()
Gets the exported types defined in this assembly.
virtual Module Module
Gets the module in which the type that declares the member represented by the current T:System....
Definition: MemberInfo.cs:78
Defines the set of information that constitutes input to security policy decisions....
Definition: Evidence.cs:17
PortableExecutableKinds
Identifies the nature of the code in an executable file.
ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo)
Defines a named transient dynamic module in this assembly and specifies whether symbol information sh...
override object [] GetCustomAttributes(bool inherit)
Returns all the custom attributes that have been applied to the current T:System.Reflection....
void DefineUnmanagedResource(string resourceFileName)
Defines an unmanaged resource file for this assembly given the name of the resource file.
override bool IsDefined(Type attributeType, bool inherit)
Returns a value that indicates whether one or more instances of the specified attribute type is appli...
The exception that is thrown when a method call is invalid for the object's current state.
Provides static methods for the creation, copying, deletion, moving, and opening of a single file,...
Definition: File.cs:14
static Type GetType(string typeName, bool throwOnError, bool ignoreCase)
Gets the T:System.Type with the specified name, specifying whether to throw an exception if the type ...
Definition: Type.cs:853
ClassInterfaceType
Identifies the type of class interface that is generated for a class.
void Assert()
Declares that the calling code can access the resource protected by a permission demand through the c...
override int GetHashCode()
Returns the hash code for this instance.
override ManifestResourceInfo GetManifestResourceInfo(string resourceName)
Returns information about how the given resource has been persisted.
static void Delete(string path)
Deletes the specified file.
Definition: File.cs:324
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
The exception that is thrown when an invoked method is not supported, or when there is an attempt to ...
Controls the ability to access files and folders. This class cannot be inherited.
override bool Equals(object obj)
Returns a value that indicates whether this instance is equal to the specified object.
SecurityPermissionFlag
Specifies access flags for the security permission object.
override string CodeBase
Gets the location of the assembly, as specified originally (such as in an T:System....
static string CurrentDirectory
Gets or sets the fully qualified path of the current working directory.
Definition: Environment.cs:356
void Save(string assemblyFileName, PortableExecutableKinds portableExecutableKind, ImageFileMachine imageFileMachine)
Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and ...
SecurityCriticalScope
Specifies the scope of a T:System.Security.SecurityCriticalAttribute.
ModuleBuilder DefineDynamicModule(string name, string fileName, bool emitSymbolInfo)
Defines a persistable dynamic module, specifying the module name, the name of the file to which the m...
Performs operations on T:System.String instances that contain file or directory path information....
Definition: Path.cs:13
override string Location
Gets the location, in codebase format, of the loaded file that contains the manifest if it is not sha...
PEFileKinds
Specifies the type of the portable executable (PE) file.
Definition: PEFileKinds.cs:8
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16