[mini] bump AOT version - WrapperType changed
[mono.git] / mcs / class / corlib / System.Reflection / Assembly.cs
1 //
2 // System.Reflection/Assembly.cs
3 //
4 // Author:
5 //   Paolo Molaro (lupus@ximian.com)
6 //
7 // (C) 2001 Ximian, Inc.  http://www.ximian.com
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
9 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System.Security;
32 using System.Security.Policy;
33 using System.Security.Permissions;
34 using System.Runtime.Serialization;
35 using System.Reflection;
36 using System.IO;
37 using System.Globalization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
40 using System.Collections.Generic;
41 using System.Configuration.Assemblies;
42 using System.Threading;
43 using System.Text;
44 using System.Diagnostics.Contracts;
45
46 using Mono.Security;
47
48 namespace System.Reflection {
49
50         [ComVisible (true)]
51         [ComDefaultInterfaceAttribute (typeof (_Assembly))]
52         [Serializable]
53         [ClassInterface(ClassInterfaceType.None)]
54         [StructLayout (LayoutKind.Sequential)]
55 #if MOBILE
56         public partial class Assembly : ICustomAttributeProvider {
57 #else
58         public abstract class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
59 #endif
60                 internal class ResolveEventHolder {
61                         public event ModuleResolveEventHandler ModuleResolve;
62                 }
63
64                 internal class UnmanagedMemoryStreamForModule : UnmanagedMemoryStream
65                 {
66                         Module module;
67
68                         public unsafe UnmanagedMemoryStreamForModule (byte* pointer, long length, Module module)
69                                 : base (pointer, length)
70                         {
71                                 this.module = module;
72                         }
73
74                         protected override void Dispose (bool disposing)
75                         {
76                                 if (_isOpen) {
77                                         /* 
78                                          * The returned pointer points inside metadata, so
79                                          * we have to increase the refcount of the module, and decrease
80                                          * it when the stream is finalized.
81                                          */
82                                         module = null;
83                                 }
84
85                                 base.Dispose (disposing);
86                         }
87                 }
88
89                 // Note: changes to fields must be reflected in _MonoReflectionAssembly struct (object-internals.h)
90 #pragma warning disable 649
91                 private IntPtr _mono_assembly;
92 #pragma warning restore 649
93
94                 private ResolveEventHolder resolve_event_holder;
95 #if !MOBILE
96                 private Evidence _evidence;
97                 internal PermissionSet _minimum;        // for SecurityAction.RequestMinimum
98                 internal PermissionSet _optional;       // for SecurityAction.RequestOptional
99                 internal PermissionSet _refuse;         // for SecurityAction.RequestRefuse
100                 private PermissionSet _granted;         // for the resolved assembly granted permissions
101                 private PermissionSet _denied;          // for the resolved assembly denied permissions
102 #else
103                 object _evidence, _minimum, _optional, _refuse, _granted, _denied;
104 #endif
105                 private bool fromByteArray;
106                 private string assemblyName;
107
108                 protected
109                 Assembly () 
110                 {
111                         resolve_event_holder = new ResolveEventHolder ();
112                 }
113
114                 //
115                 // We can't store the event directly in this class, since the
116                 // compiler would silently insert the fields before _mono_assembly
117                 //
118                 public event ModuleResolveEventHandler ModuleResolve {
119                         [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
120                         add {
121                                 resolve_event_holder.ModuleResolve += value;
122                         }
123                         [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
124                         remove {
125                                 resolve_event_holder.ModuleResolve -= value;
126                         }
127                 }
128
129                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
130                 private extern string get_code_base (bool escaped);
131
132                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
133                 private extern string get_fullname ();
134
135                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
136                 private extern string get_location ();
137
138                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
139                 private extern string InternalImageRuntimeVersion ();
140
141                 // SECURITY: this should be the only caller to icall get_code_base
142                 private string GetCodeBase (bool escaped)
143                 {
144                         string cb = get_code_base (escaped);
145 #if !NET_2_1
146                         if (SecurityManager.SecurityEnabled) {
147                                 // we cannot divulge local file informations
148                                 if (String.Compare ("FILE://", 0, cb, 0, 7, true, CultureInfo.InvariantCulture) == 0) {
149                                         string file = cb.Substring (7);
150                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, file).Demand ();
151                                 }
152                         }
153 #endif
154                         return cb;
155                 }
156
157                 public virtual string CodeBase {
158                         get { return GetCodeBase (false); }
159                 }
160
161                 public virtual string EscapedCodeBase {
162                         get { return GetCodeBase (true); }
163                 }
164
165                 public virtual string FullName {
166                         get {
167                                 //
168                                 // FIXME: This is wrong, but it gets us going
169                                 // in the compiler for now
170                                 //
171                                 return ToString ();
172                         }
173                 }
174
175                 public virtual extern MethodInfo EntryPoint {
176                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
177                         get;
178                 }
179
180                 public virtual Evidence Evidence {
181                         [SecurityPermission (SecurityAction.Demand, ControlEvidence = true)]
182                         get { return UnprotectedGetEvidence (); }
183                 }
184
185                 // note: the security runtime requires evidences but may be unable to do so...
186                 internal Evidence UnprotectedGetEvidence ()
187                 {
188 #if MOBILE
189                         return null;
190 #else
191                         // if the host (runtime) hasn't provided it's own evidence...
192                         if (_evidence == null) {
193                                 // ... we will provide our own
194                                 lock (this) {
195                                         _evidence = Evidence.GetDefaultHostEvidence (this);
196                                 }
197                         }
198                         return _evidence;
199 #endif
200                 }
201
202                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
203                 internal extern bool get_global_assembly_cache ();
204
205                 internal bool FromByteArray {
206                         set { fromByteArray = value; }
207                 }
208
209                 public virtual String Location {
210                         get {
211                                 if (fromByteArray)
212                                         return String.Empty;
213
214                                 string loc = get_location ();
215 #if !NET_2_1
216                                 if ((loc != String.Empty) && SecurityManager.SecurityEnabled) {
217                                         // we cannot divulge local file informations
218                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, loc).Demand ();
219                                 }
220 #endif
221                                 return loc;
222                         }
223                 }
224
225                 [ComVisible (false)]
226                 public virtual string ImageRuntimeVersion {
227                         get {
228                                 return InternalImageRuntimeVersion ();
229                         }
230                 }
231
232                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
233                 {
234                         throw new NotImplementedException ();
235                 }
236
237                 public virtual bool IsDefined (Type attributeType, bool inherit)
238                 {
239                         return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
240                 }
241
242                 public virtual object [] GetCustomAttributes (bool inherit)
243                 {
244                         return MonoCustomAttrs.GetCustomAttributes (this, inherit);
245                 }
246
247                 public virtual object [] GetCustomAttributes (Type attributeType, bool inherit)
248                 {
249                         return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
250                 }
251
252                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
253                 private extern object GetFilesInternal (String name, bool getResourceModules);
254
255                 public virtual FileStream[] GetFiles ()
256                 {
257                         return GetFiles (false);
258                 }
259
260                 public virtual FileStream [] GetFiles (bool getResourceModules)
261                 {
262                         string[] names = (string[]) GetFilesInternal (null, getResourceModules);
263                         if (names == null)
264                                 return EmptyArray<FileStream>.Value;
265
266                         string location = Location;
267
268                         FileStream[] res;
269                         if (location != String.Empty) {
270                                 res = new FileStream [names.Length + 1];
271                                 res [0] = new FileStream (location, FileMode.Open, FileAccess.Read);
272                                 for (int i = 0; i < names.Length; ++i)
273                                         res [i + 1] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
274                         } else {
275                                 res = new FileStream [names.Length];
276                                 for (int i = 0; i < names.Length; ++i)
277                                         res [i] = new FileStream (names [i], FileMode.Open, FileAccess.Read);
278                         }
279                         return res;
280                 }
281
282                 public virtual FileStream GetFile (String name)
283                 {
284                         if (name == null)
285                                 throw new ArgumentNullException (null, "Name cannot be null.");
286                         if (name.Length == 0)
287                                 throw new ArgumentException ("Empty name is not valid");
288
289                         string filename = (string)GetFilesInternal (name, true);
290                         if (filename != null)
291                                 return new FileStream (filename, FileMode.Open, FileAccess.Read);
292                         else
293                                 return null;
294                 }
295
296                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
297                 internal extern IntPtr GetManifestResourceInternal (String name, out int size, out Module module);
298
299                 public virtual Stream GetManifestResourceStream (String name)
300                 {
301                         if (name == null)
302                                 throw new ArgumentNullException ("name");
303                         if (name.Length == 0)
304                                 throw new ArgumentException ("String cannot have zero length.",
305                                         "name");
306
307                         ManifestResourceInfo info = GetManifestResourceInfo (name);
308                         if (info == null) {
309                                 Assembly a = AppDomain.CurrentDomain.DoResourceResolve (name, this);
310                                 if (a != null && a != this)
311                                         return a.GetManifestResourceStream (name);
312                                 else
313                                         return null;
314                         }
315
316                         if (info.ReferencedAssembly != null)
317                                 return info.ReferencedAssembly.GetManifestResourceStream (name);
318                         if ((info.FileName != null) && (info.ResourceLocation == 0)) {
319                                 if (fromByteArray)
320                                         throw new FileNotFoundException (info.FileName);
321
322                                 string location = Path.GetDirectoryName (Location);
323                                 string filename = Path.Combine (location, info.FileName);
324                                 return new FileStream (filename, FileMode.Open, FileAccess.Read);
325                         }
326
327                         int size;
328                         Module module;
329                         IntPtr data = GetManifestResourceInternal (name, out size, out module);
330                         if (data == (IntPtr) 0)
331                                 return null;
332                         else {
333                                 UnmanagedMemoryStream stream;
334                                 unsafe {
335                                         stream = new UnmanagedMemoryStreamForModule ((byte*) data, size, module);
336                                 }
337                                 return stream;
338                         }
339                 }
340
341                 public virtual Stream GetManifestResourceStream (Type type, String name)
342                 {
343                         StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
344                         return GetManifestResourceStream(type, name, false, ref stackMark);
345                 }
346
347                 internal Stream GetManifestResourceStream (Type type, String name, bool skipSecurityCheck, ref StackCrawlMark stackMark)
348                 {
349                         StringBuilder sb = new StringBuilder ();
350                         if (type == null) {
351                                 if (name == null)
352                                                 throw new ArgumentNullException ("type");
353                         } else {
354                                 String nameSpace = type.Namespace;
355                                 if (nameSpace != null) {
356                                         sb.Append (nameSpace);
357                                         if (name != null)
358                                                 sb.Append (Type.Delimiter);
359                                 }
360                         }
361
362                         if (name != null)
363                                 sb.Append(name);
364
365                         return GetManifestResourceStream (sb.ToString());
366                 }
367
368                 internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck)
369                 {
370                         return GetManifestResourceStream (null, name, skipSecurityCheck, ref stackMark);
371                 }
372
373                 internal String GetSimpleName()
374                 {
375                         AssemblyName aname = GetName (true);
376                         return aname.Name;
377                 }
378
379                 internal byte[] GetPublicKey()
380                 {
381                         AssemblyName aname = GetName (true);
382                         return aname.GetPublicKey ();
383                 }
384
385                 internal Version GetVersion()
386                 {
387                         AssemblyName aname = GetName (true);
388                         return aname.Version;
389                 }
390
391                 private AssemblyNameFlags GetFlags()
392                 {
393                         AssemblyName aname = GetName (true);
394                         return aname.Flags;
395                 }
396
397                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
398                 internal virtual extern Type[] GetTypes (bool exportedOnly);
399                 
400                 public virtual Type[] GetTypes ()
401                 {
402                         return GetTypes (false);
403                 }
404
405                 public virtual Type[] GetExportedTypes ()
406                 {
407                         return GetTypes (true);
408                 }
409
410                 public virtual Type GetType (String name, Boolean throwOnError)
411                 {
412                         return GetType (name, throwOnError, false);
413                 }
414
415                 public virtual Type GetType (String name) {
416                         return GetType (name, false, false);
417                 }
418
419                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
420                 internal extern Type InternalGetType (Module module, String name, Boolean throwOnError, Boolean ignoreCase);
421
422                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
423                 internal extern static void InternalGetAssemblyName (string assemblyFile, AssemblyName aname);
424
425                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
426                 static extern internal void FillName (Assembly ass, AssemblyName aname);
427
428                 public virtual AssemblyName GetName (Boolean copiedName)
429                 {
430                         throw new NotImplementedException ();
431                 }
432
433                 public virtual AssemblyName GetName ()
434                 {
435                         return GetName (false);
436                 }
437
438                 public override string ToString ()
439                 {
440                         // note: ToString work without requiring CodeBase (so no checks are needed)
441
442                         if (assemblyName != null)
443                                 return assemblyName;
444
445                         assemblyName = get_fullname ();
446                         return assemblyName;
447                 }
448
449                 public static String CreateQualifiedName (String assemblyName, String typeName) 
450                 {
451                         return typeName + ", " + assemblyName;
452                 }
453
454                 public static Assembly GetAssembly (Type type)
455                 {
456                         if (type != null)
457                                 return type.Assembly;
458                         throw new ArgumentNullException ("type");
459                 }
460
461
462                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
463                 public static extern Assembly GetEntryAssembly();
464
465                 internal Assembly GetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnError)
466                 {
467                         if (culture == null)
468                                 throw new ArgumentNullException("culture");
469                         Contract.EndContractBlock();
470
471                         StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
472                         String name = GetSimpleName() + ".resources";
473                         return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
474                 }
475
476                 internal RuntimeAssembly InternalGetSatelliteAssembly (String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark)
477                 {
478                         AssemblyName an = new AssemblyName ();
479
480                         an.SetPublicKey (GetPublicKey ());
481                         an.Flags = GetFlags () | AssemblyNameFlags.PublicKey;
482
483                         if (version == null)
484                                 an.Version = GetVersion ();
485                         else
486                                 an.Version = version;
487
488                         an.CultureInfo = culture;
489                         an.Name = name;
490
491                         Assembly assembly;
492
493                         try {
494                                 assembly = AppDomain.CurrentDomain.LoadSatellite (an, false);
495                                 if (assembly != null)
496                                         return (RuntimeAssembly)assembly;
497                         } catch (FileNotFoundException) {
498                                 assembly = null;
499                                 // ignore
500                         }
501
502                         if (String.IsNullOrEmpty (Location))
503                                 return null;
504
505                         // Try the assembly directory
506                         string location = Path.GetDirectoryName (Location);
507                         string fullName = Path.Combine (location, Path.Combine (culture.Name, an.Name + ".dll"));
508                         if (!throwOnFileNotFound && !File.Exists (fullName))
509                                 return null;
510
511                         return (RuntimeAssembly)LoadFrom (fullName);
512                 }
513
514 #if !MOBILE
515                 Type _Assembly.GetType ()
516                 {
517                         // Required or object::GetType becomes virtual final
518                         return base.GetType ();
519                 }               
520 #endif
521
522                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523                 private extern static Assembly LoadFrom (String assemblyFile, bool refonly);
524
525                 public static Assembly LoadFrom (String assemblyFile)
526                 {
527                         return LoadFrom (assemblyFile, false);
528                 }
529
530                 [Obsolete]
531                 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence)
532                 {
533                         Assembly a = LoadFrom (assemblyFile, false);
534 #if !NET_2_1
535                         if ((a != null) && (securityEvidence != null)) {
536                                 // merge evidence (i.e. replace defaults with provided evidences)
537                                 a.Evidence.Merge (securityEvidence);
538                         }
539 #endif
540                         return a;
541                 }
542
543                 [Obsolete]
544                 [MonoTODO("This overload is not currently implemented")]
545                 // FIXME: What are we missing?
546                 public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
547                 {
548                         throw new NotImplementedException ();
549                 }
550
551                 [MonoTODO]
552                 public static Assembly LoadFrom (String assemblyFile, byte [] hashValue, AssemblyHashAlgorithm hashAlgorithm)
553                 {
554                         throw new NotImplementedException ();
555                 }
556
557                 public static Assembly UnsafeLoadFrom (String assemblyFile)
558                 {
559                         return LoadFrom (assemblyFile);
560                 }
561
562                 [Obsolete]
563                 public static Assembly LoadFile (String path, Evidence securityEvidence)
564                 {
565                         if (path == null)
566                                 throw new ArgumentNullException ("path");
567                         if (path == String.Empty)
568                                 throw new ArgumentException ("Path can't be empty", "path");
569                         // FIXME: Make this do the right thing
570                         return LoadFrom (path, securityEvidence);
571                 }
572
573                 public static Assembly LoadFile (String path)
574                 {
575                         return LoadFile (path, null);
576                 }
577
578                 public static Assembly Load (String assemblyString)
579                 {
580                         return AppDomain.CurrentDomain.Load (assemblyString);
581                 }
582
583                 [Obsolete]
584                 public static Assembly Load (String assemblyString, Evidence assemblySecurity)
585                 {
586                         return AppDomain.CurrentDomain.Load (assemblyString, assemblySecurity);
587                 }
588
589                 public static Assembly Load (AssemblyName assemblyRef)
590                 {
591                         return AppDomain.CurrentDomain.Load (assemblyRef);
592                 }
593
594                 [Obsolete]
595                 public static Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
596                 {
597                         return AppDomain.CurrentDomain.Load (assemblyRef, assemblySecurity);
598                 }
599
600                 public static Assembly Load (Byte[] rawAssembly)
601                 {
602                         return AppDomain.CurrentDomain.Load (rawAssembly);
603                 }
604
605                 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore)
606                 {
607                         return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore);
608                 }
609
610                 [Obsolete]
611                 public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore,
612                                              Evidence securityEvidence)
613                 {
614                         return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore, securityEvidence);
615                 }
616
617                 [MonoLimitation ("Argument securityContextSource is ignored")]
618                 public static Assembly Load (byte [] rawAssembly, byte [] rawSymbolStore, SecurityContextSource securityContextSource)
619                 {
620                         return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore);
621                 }
622
623                 public static Assembly ReflectionOnlyLoad (byte[] rawAssembly)
624                 {
625                         return AppDomain.CurrentDomain.Load (rawAssembly, null, null, true);
626                 }
627
628                 public static Assembly ReflectionOnlyLoad (string assemblyString) 
629                 {
630                         return AppDomain.CurrentDomain.Load (assemblyString, null, true);
631                 }
632
633                 public static Assembly ReflectionOnlyLoadFrom (string assemblyFile) 
634                 {
635                         if (assemblyFile == null)
636                                 throw new ArgumentNullException ("assemblyFile");
637                         
638                         return LoadFrom (assemblyFile, true);
639                 }
640
641                 [Obsolete]
642                 public static Assembly LoadWithPartialName (string partialName)
643                 {
644                         return LoadWithPartialName (partialName, null);
645                 }
646
647                 [MonoTODO ("Not implemented")]
648                 public Module LoadModule (string moduleName, byte [] rawModule)
649                 {
650                         throw new NotImplementedException ();
651                 }
652
653                 [MonoTODO ("Not implemented")]
654                 public
655                 virtual
656                 Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
657                 {
658                         throw new NotImplementedException ();
659                 }
660
661                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
662                 private static extern Assembly load_with_partial_name (string name, Evidence e);
663
664                 [Obsolete]
665                 public static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence)
666                 {
667                         return LoadWithPartialName (partialName, securityEvidence, true);
668                 }
669
670                 /**
671                  * LAMESPEC: It is possible for this method to throw exceptions IF the name supplied
672                  * is a valid gac name and contains filesystem entry charachters at the end of the name
673                  * ie System/// will throw an exception. However ////System will not as that is canocolized
674                  * out of the name.
675                  */
676
677                 // FIXME: LoadWithPartialName must look cache (no CAS) or read from disk (CAS)
678                 internal static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence, bool oldBehavior)
679                 {
680                         if (!oldBehavior)
681                                 throw new NotImplementedException ();
682
683                         if (partialName == null)
684                                 throw new NullReferenceException ();
685
686                         return load_with_partial_name (partialName, securityEvidence);
687                 }
688
689                 public Object CreateInstance (String typeName) 
690                 {
691                         return CreateInstance (typeName, false);
692                 }
693
694                 public Object CreateInstance (String typeName, Boolean ignoreCase)
695                 {
696                         Type t = GetType (typeName, false, ignoreCase);
697                         if (t == null)
698                                 return null;
699
700                         try {
701                                 return Activator.CreateInstance (t);
702                         } catch (InvalidOperationException) {
703                                 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
704                         }
705                 }
706
707                 public
708                 virtual
709                 Object CreateInstance (String typeName, Boolean ignoreCase,
710                                               BindingFlags bindingAttr, Binder binder,
711                                               Object[] args, CultureInfo culture,
712                                               Object[] activationAttributes)
713                 {
714                         Type t = GetType (typeName, false, ignoreCase);
715                         if (t == null)
716                                 return null;
717
718                         try {
719                                 return Activator.CreateInstance (t, bindingAttr, binder, args, culture, activationAttributes);
720                         } catch (InvalidOperationException) {
721                                 throw new ArgumentException ("It is illegal to invoke a method on a Type loaded via ReflectionOnly methods.");
722                         }
723                 }
724
725                 public Module[] GetLoadedModules ()
726                 {
727                         return GetLoadedModules (false);
728                 }
729
730                 public Module[] GetModules ()
731                 {
732                         return GetModules (false);
733                 }
734
735                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
736                 internal virtual extern Module[] GetModulesInternal ();
737                 
738                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
739                 public extern virtual String[] GetManifestResourceNames ();
740
741                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
742                 public extern static Assembly GetExecutingAssembly ();
743
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 public extern static Assembly GetCallingAssembly ();
746
747                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
748                 internal static extern AssemblyName[] GetReferencedAssemblies (Assembly module);
749
750                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
751                 private extern bool GetManifestResourceInfoInternal (String name, ManifestResourceInfo info);
752
753                 public virtual ManifestResourceInfo GetManifestResourceInfo (String resourceName)
754                 {
755                         if (resourceName == null)
756                                 throw new ArgumentNullException ("resourceName");
757                         if (resourceName.Length == 0)
758                                 throw new ArgumentException ("String cannot have zero length.");
759                         ManifestResourceInfo result = new ManifestResourceInfo (null, null, 0);
760                         bool found = GetManifestResourceInfoInternal (resourceName, result);
761                         if (found)
762                                 return result;
763                         else
764                                 return null;
765                 }
766
767                 [MonoTODO ("Currently it always returns zero")]
768                 [ComVisible (false)]
769                 public
770                 virtual
771                 long HostContext {
772                         get { return 0; }
773                 }
774
775
776                 internal virtual Module GetManifestModule () {
777                         return GetManifestModuleInternal ();
778                 }
779
780                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
781                 internal extern Module GetManifestModuleInternal ();
782
783                 [ComVisible (false)]
784                 public virtual extern bool ReflectionOnly {
785                         [MethodImplAttribute (MethodImplOptions.InternalCall)]
786                         get;
787                 }
788                 
789                 public override int GetHashCode ()
790                 {
791                         return base.GetHashCode ();
792                 }
793
794                 public override bool Equals (object o)
795                 {
796                         if (((object) this) == o)
797                                 return true;
798
799                         if (o == null)
800                                 return false;
801                         
802                         Assembly other = (Assembly) o;
803                         return other._mono_assembly == _mono_assembly;
804                 }
805
806 #if !NET_2_1
807                 // Code Access Security
808
809                 internal void Resolve () 
810                 {
811                         lock (this) {
812                                 // FIXME: As we (currently) delay the resolution until the first CAS
813                                 // Demand it's too late to evaluate the Minimum permission set as a 
814                                 // condition to load the assembly into the AppDomain
815                                 LoadAssemblyPermissions ();
816                                 Evidence e = new Evidence (UnprotectedGetEvidence ()); // we need a copy to add PRE
817                                 e.AddHost (new PermissionRequestEvidence (_minimum, _optional, _refuse));
818                                 _granted = SecurityManager.ResolvePolicy (e,
819                                         _minimum, _optional, _refuse, out _denied);
820                         }
821                 }
822
823                 internal PermissionSet GrantedPermissionSet {
824                         get {
825                                 if (_granted == null) {
826                                         if (SecurityManager.ResolvingPolicyLevel != null) {
827                                                 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
828                                                         return DefaultPolicies.FullTrust;
829                                                 else
830                                                         return null; // we can't resolve during resolution
831                                         }
832                                         Resolve ();
833                                 }
834                                 return _granted;
835                         }
836                 }
837
838                 internal PermissionSet DeniedPermissionSet {
839                         get {
840                                 // yes we look for granted, as denied may be null
841                                 if (_granted == null) {
842                                         if (SecurityManager.ResolvingPolicyLevel != null) {
843                                                 if (SecurityManager.ResolvingPolicyLevel.IsFullTrustAssembly (this))
844                                                         return null;
845                                                 else
846                                                         return DefaultPolicies.FullTrust; // deny unrestricted
847                                         }
848                                         Resolve ();
849                                 }
850                                 return _denied;
851                         }
852                 }
853
854                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
855                 extern internal static bool LoadPermissions (Assembly a, 
856                         ref IntPtr minimum, ref int minLength,
857                         ref IntPtr optional, ref int optLength,
858                         ref IntPtr refused, ref int refLength);
859
860                 // Support for SecurityAction.RequestMinimum, RequestOptional and RequestRefuse
861                 private void LoadAssemblyPermissions ()
862                 {
863                         IntPtr minimum = IntPtr.Zero, optional = IntPtr.Zero, refused = IntPtr.Zero;
864                         int minLength = 0, optLength = 0, refLength = 0;
865                         if (LoadPermissions (this, ref minimum, ref minLength, ref optional,
866                                 ref optLength, ref refused, ref refLength)) {
867
868                                 // Note: no need to cache these permission sets as they will only be created once
869                                 // at assembly resolution time.
870                                 if (minLength > 0) {
871                                         byte[] data = new byte [minLength];
872                                         Marshal.Copy (minimum, data, 0, minLength);
873                                         _minimum = SecurityManager.Decode (data);
874                                 }
875                                 if (optLength > 0) {
876                                         byte[] data = new byte [optLength];
877                                         Marshal.Copy (optional, data, 0, optLength);
878                                         _optional = SecurityManager.Decode (data);
879                                 }
880                                 if (refLength > 0) {
881                                         byte[] data = new byte [refLength];
882                                         Marshal.Copy (refused, data, 0, refLength);
883                                         _refuse = SecurityManager.Decode (data);
884                                 }
885                         }
886                 }
887                 
888                 public virtual PermissionSet PermissionSet {
889                         get { return this.GrantedPermissionSet; }
890                 }
891                 
892                 public virtual SecurityRuleSet SecurityRuleSet {
893                         get { throw CreateNIE (); }
894                 }
895
896 #endif
897
898                 static Exception CreateNIE ()
899                 {
900                         return new NotImplementedException ("Derived classes must implement it");
901                 }
902                 
903                 public virtual IList<CustomAttributeData> GetCustomAttributesData ()
904                 {
905                         return CustomAttributeData.GetCustomAttributes (this);
906                 }
907
908                 [MonoTODO]
909                 public bool IsFullyTrusted {
910                         get { return true; }
911                 }
912
913                 public virtual Type GetType (string name, bool throwOnError, bool ignoreCase)
914                 {
915                         throw CreateNIE ();
916                 }
917
918                 public virtual Module GetModule (String name)
919                 {
920                         throw CreateNIE ();
921                 }
922
923                 public virtual AssemblyName[] GetReferencedAssemblies ()
924                 {
925                         throw CreateNIE ();
926                 }
927
928                 public virtual Module[] GetModules (bool getResourceModules)
929                 {
930                         throw CreateNIE ();
931                 }
932
933                 [MonoTODO ("Always returns the same as GetModules")]
934                 public virtual Module[] GetLoadedModules (bool getResourceModules)
935                 {
936                         throw CreateNIE ();
937                 }
938
939                 public virtual Assembly GetSatelliteAssembly (CultureInfo culture)
940                 {
941                         throw CreateNIE ();
942                 }
943
944                 public virtual Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
945                 {
946                         throw CreateNIE ();
947                 }
948
949                 public virtual Module ManifestModule {
950                         get { throw CreateNIE (); }
951                 }
952
953                 public virtual bool GlobalAssemblyCache {
954                         get { throw CreateNIE (); }
955                 }
956
957                 public virtual bool IsDynamic {
958                         get { return false; }
959                 }
960
961                 public static bool operator == (Assembly left, Assembly right)
962                 {
963                         if ((object)left == (object)right)
964                                 return true;
965                         if ((object)left == null ^ (object)right == null)
966                                 return false;
967                         return left.Equals (right);
968                 }
969
970                 public static bool operator != (Assembly left, Assembly right)
971                 {
972                         if ((object)left == (object)right)
973                                 return false;
974                         if ((object)left == null ^ (object)right == null)
975                                 return true;
976                         return !left.Equals (right);
977                 }
978
979                 public virtual IEnumerable<TypeInfo> DefinedTypes {
980                         get {
981                                 foreach (var type in GetTypes ()) {
982                                         yield return type.GetTypeInfo ();
983                                 }
984                         }
985                 }
986
987                 public virtual IEnumerable<Type> ExportedTypes {
988                         get { return GetExportedTypes (); }
989                 }
990
991                 public virtual IEnumerable<Module> Modules {
992                         get { return GetModules (); }
993                 }
994
995                 public virtual IEnumerable<CustomAttributeData> CustomAttributes {
996                         get { return GetCustomAttributesData (); }
997                 }
998         }
999 }