Merge pull request #900 from Blewzman/FixAggregateExceptionGetBaseException
[mono.git] / mcs / mcs / ikvm.cs
1 //
2 // ikvm.cs: IKVM.Reflection and IKVM.Reflection.Emit specific implementations
3 //
4 // Author: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2009-2010 Novell, Inc. 
9 // Copyright 2011 Xamarin Inc
10 //
11 //
12
13 using System;
14 using System.Collections.Generic;
15 using MetaType = IKVM.Reflection.Type;
16 using IKVM.Reflection;
17 using IKVM.Reflection.Emit;
18 using System.IO;
19 using System.Configuration.Assemblies;
20
21 namespace Mono.CSharp
22 {
23 #if !STATIC
24         public class StaticImporter
25         {
26                 public StaticImporter (BuiltinTypes builtin)
27                 {
28                         throw new NotSupportedException ();
29                 }
30
31                 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
32                 {
33                         throw new NotSupportedException ();
34                 }
35
36                 public void ImportModule (Module module, RootNamespace targetNamespace)
37                 {
38                         throw new NotSupportedException ();
39                 }
40
41                 public TypeSpec ImportType (System.Type type)
42                 {
43                         throw new NotSupportedException ();
44                 }
45         }
46
47 #else
48
49         sealed class StaticImporter : MetadataImporter
50         {
51                 public StaticImporter (ModuleContainer module)
52                         : base (module)
53                 {
54                 }
55
56                 public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
57                 {
58                         assembly_2_definition.Add (assembly.Builder, assembly);
59                 }
60
61                 public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
62                 {
63                         compiled_types.Add (type, spec);
64                 }
65
66                 protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
67                 {
68                         string name = baseType.Name;
69
70                         if (name == "ValueType" && baseType.Namespace == "System")
71                                 return MemberKind.Struct;
72
73                         if (name == "Enum" && baseType.Namespace == "System")
74                                 return MemberKind.Enum;
75
76                         if (name == "MulticastDelegate" && baseType.Namespace == "System")
77                                 return MemberKind.Delegate;
78
79                         return MemberKind.Class;
80                 }
81
82                 protected override bool HasVolatileModifier (MetaType[] modifiers)
83                 {
84                         foreach (var t in modifiers) {
85                                 if (t.Name == "IsVolatile" && t.Namespace == CompilerServicesNamespace)
86                                         return true;
87                         }
88
89                         return false;
90                 }
91
92                 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
93                 {
94                         try {
95                                 // It can be used more than once when importing same assembly
96                                 // into 2 or more global aliases
97                                 // TODO: Should be just Add
98                                 GetAssemblyDefinition (assembly);
99
100                                 var all_types = assembly.GetTypes ();
101                                 ImportTypes (all_types, targetNamespace, true);
102
103                                 all_types = assembly.ManifestModule.__GetExportedTypes ();
104                                 if (all_types.Length != 0)
105                                         ImportForwardedTypes (all_types, targetNamespace);
106                         } catch (Exception e) {
107                                 throw new InternalErrorException (e, "Failed to import assembly `{0}'", assembly.FullName);
108                         }
109                 }
110
111                 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
112                 {
113                         var module_definition = new ImportedModuleDefinition (module);
114                         module_definition.ReadAttributes ();
115
116                         var all_types = module.GetTypes ();
117                         ImportTypes (all_types, targetNamespace, false);
118
119                         return module_definition;
120                 }
121
122                 void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
123                 {
124                         Namespace ns = targetNamespace;
125                         string prev_namespace = null;
126                         foreach (var t in types) {
127                                 if (!t.__IsTypeForwarder)
128                                         continue;
129
130                                 // IsMissing tells us the type has been forwarded and target assembly is missing 
131                                 if (!t.__IsMissing)
132                                         continue;
133
134                                 if (t.Name[0] == '<')
135                                         continue;
136
137                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
138                                 if (it == null)
139                                         continue;
140
141                                 if (prev_namespace != t.Namespace) {
142                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
143                                         prev_namespace = t.Namespace;
144                                 }
145
146                                 ns.AddType (module, it);
147                         }
148                 }
149
150                 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
151                 {
152                         //
153                         // Setup mapping for build-in types to avoid duplication of their definition
154                         //
155                         foreach (var type in builtin.AllTypes) {
156                                 compiled_types.Add (corlib.GetType (type.FullName), type);
157                         }
158                 }
159         }
160 #endif
161
162         class AssemblyDefinitionStatic : AssemblyDefinition
163         {
164                 readonly StaticLoader loader;
165
166                 //
167                 // Assembly container with file output
168                 //
169                 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
170                         : base (module, name, fileName)
171                 {
172                         this.loader = loader;
173                         Importer = loader.MetadataImporter;
174                 }
175
176                 //
177                 // Initializes the assembly SRE domain
178                 //
179                 public void Create (Universe domain)
180                 {
181                         ResolveAssemblySecurityAttributes ();
182                         var an = CreateAssemblyName ();
183
184                         Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
185                         module.Create (this, CreateModuleBuilder ());
186                 }
187
188                 public override void Emit ()
189                 {
190                         if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
191                                 Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
192                         } else {
193                                 // Sets output file metadata version when there is no mscorlib
194                                 switch (module.Compiler.Settings.StdLibRuntimeVersion) {
195                                 case RuntimeVersion.v4:
196                                         Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
197                                         break;
198                                 case RuntimeVersion.v2:
199                                         Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
200                                         break;
201                                 case RuntimeVersion.v1:
202                                         // Compiler does not do any checks whether the produced metadata
203                                         // are valid in the context of 1.0 stream version
204                                         Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
205                                         break;
206                                 default:
207                                         throw new NotImplementedException ();
208                                 }
209                         }
210
211                         builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
212
213                         base.Emit ();
214                 }
215
216                 public Module IncludeModule (RawModule moduleFile)
217                 {
218                         return Builder.__AddModule (moduleFile);
219                 }
220
221                 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
222                 {
223                         module.Builder.__Save (pekind, machine);
224                 }
225         }
226
227         class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
228         {
229                 readonly StaticImporter importer;
230                 readonly Universe domain;
231                 Assembly corlib;
232                 readonly List<Tuple<AssemblyName, string, Assembly>> loaded_names;
233                 static readonly Dictionary<string, string[]> sdk_directory;
234
235                 static StaticLoader ()
236                 {
237                         sdk_directory = new Dictionary<string, string[]> ();
238                         sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
239                         sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
240                         sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_5", "v4.0.30319" });
241                 }
242
243                 public StaticLoader (StaticImporter importer, CompilerContext compiler)
244                         : base (compiler)
245                 {
246                         this.importer = importer;
247                         domain = new Universe (UniverseOptions.MetadataOnly | UniverseOptions.ResolveMissingMembers | UniverseOptions.DisableFusion);
248                         domain.AssemblyResolve += AssemblyReferenceResolver;
249                         loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
250
251                         if (compiler.Settings.StdLib) {
252                                 var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
253                                 string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
254
255                                 string sdk_path = null;
256
257                                 string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
258                                 string[] sdk_sub_dirs;
259
260                                 if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
261                                         sdk_sub_dirs = new string[] { sdk_version };
262
263                                 foreach (var dir in sdk_sub_dirs) {
264                                         sdk_path = Path.Combine (fx_path, dir);
265                                         if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
266                                                 break;
267
268                                         sdk_path = null;
269                                 }
270
271                                 if (sdk_path == null) {
272                                         compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
273                                         sdk_path = corlib_path;
274                                 }
275
276                                 paths.Add (sdk_path);
277                         }
278                 }
279
280                 #region Properties
281
282                 public Assembly Corlib {
283                         get {
284                                 return corlib;
285                         }
286                 }
287
288                 public AssemblyDefinitionStatic CompiledAssembly {  get; set; }
289
290                 public Universe Domain {
291                         get {
292                                 return domain;
293                         }
294                 }
295
296                 public StaticImporter MetadataImporter {
297                         get {
298                                 return importer;
299                         }
300                 }
301
302                 #endregion
303
304                 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
305                 {
306                         var refname = args.Name;
307                         if (refname == "mscorlib")
308                                 return corlib;
309
310                         Assembly version_mismatch = null;
311                         bool is_fx_assembly = false;
312
313                         foreach (var assembly in domain.GetAssemblies ()) {
314                                 AssemblyComparisonResult result;
315                                 if (!domain.CompareAssemblyIdentity (refname, false, assembly.FullName, false, out result)) {
316                                         if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
317                                                 (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
318                                                 !is_fx_assembly) {
319                                                 version_mismatch = assembly;
320                                         }
321
322                                         continue;
323                                 }
324
325                                 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
326                                         result == AssemblyComparisonResult.EquivalentWeakNamed ||
327                                         result == AssemblyComparisonResult.EquivalentPartialMatch) {
328                                         return assembly;
329                                 }
330
331                                 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
332                                         is_fx_assembly = true;
333
334                                         if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
335                                                 version_mismatch = assembly;
336
337                                         continue;
338                                 }
339
340                                 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
341                         }
342
343                         if (version_mismatch != null) {
344                                 if (version_mismatch is AssemblyBuilder)
345                                         return version_mismatch;
346
347                                 var v1 = new AssemblyName (refname).Version;
348                                 var v2 = version_mismatch.GetName ().Version;
349
350                                 if (v1 > v2) {
351 //                                      compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
352                                         compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
353                                                 args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);
354
355                                         return domain.CreateMissingAssembly (args.Name);
356                                 }
357
358                                 if (!is_fx_assembly) {
359                                         if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
360                                                 compiler.Report.Warning (1701, 2,
361                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
362                                                         refname, version_mismatch.GetName ().FullName);
363                                         } else {
364                                                 compiler.Report.Warning (1702, 3,
365                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
366                                                         refname, version_mismatch.GetName ().FullName);
367                                         }
368                                 }
369
370                                 return version_mismatch;
371                         }
372
373                         //
374                         // Recursive reference to compiled assembly checks name only. Any other
375                         // details (PublicKey, Version, etc) are not yet known hence cannot be checked
376                         //
377                         ParsedAssemblyName referenced_assembly;
378                         if (Fusion.ParseAssemblyName (args.Name, out referenced_assembly) == ParseAssemblyResult.OK && CompiledAssembly.Name == referenced_assembly.Name)
379                                 return CompiledAssembly.Builder;
380
381                         // AssemblyReference has not been found in the domain
382                         // create missing reference and continue
383                         return domain.CreateMissingAssembly (args.Name);
384                 }
385
386                 public void Dispose ()
387                 {
388                         domain.Dispose ();
389                 }
390
391                 protected override string[] GetDefaultReferences ()
392                 {
393                         //
394                         // For now the "default config" is harcoded into the compiler
395                         // we can move this outside later
396                         //
397                         var default_references = new List<string> (4);
398
399                         default_references.Add ("System.dll");
400                         default_references.Add ("System.Xml.dll");
401                         default_references.Add ("System.Core.dll");
402
403                         if (corlib != null && corlib.GetName ().Version.Major >= 4) {
404                                 default_references.Add ("Microsoft.CSharp.dll");
405                         }
406
407                         return default_references.ToArray ();
408                 }
409
410                 public override bool HasObjectType (Assembly assembly)
411                 {
412                         return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
413                 }
414
415                 public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
416                 {
417                         bool? has_extension = null;
418                         foreach (var path in paths) {
419                                 var file = Path.Combine (path, fileName);
420                                 if (compiler.Settings.DebugFlags > 0)
421                                         Console.WriteLine ("Probing assembly location `{0}'", file);
422
423                                 if (!File.Exists (file)) {
424                                         if (!has_extension.HasValue)
425                                                 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
426
427                                         if (has_extension.Value)
428                                                 continue;
429
430                                         file += ".dll";
431                                         if (!File.Exists (file))
432                                                 continue;
433                                 }
434
435                                 try {
436                                         using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
437                                                 using (RawModule module = domain.OpenRawModule (stream, file)) {
438                                                         if (!module.IsManifestModule) {
439                                                                 Error_AssemblyIsModule (fileName);
440                                                                 return null;
441                                                         }
442
443                                                         //
444                                                         // check whether the assembly can be actually imported without
445                                                         // collision
446                                                         //
447                                                         var an = module.GetAssemblyName ();
448                                                         foreach (var entry in loaded_names) {
449                                                                 var loaded_name = entry.Item1;
450                                                                 if (an.Name != loaded_name.Name)
451                                                                         continue;
452
453                                                                 if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
454                                                                         return entry.Item3;
455                                                         
456                                                                 if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
457                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
458                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
459                                                                         compiler.Report.Error (1704,
460                                                                                 "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
461                                                                                 an.Name);
462                                                                         return null;
463                                                                 }
464
465                                                                 if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
466                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
467                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
468                                                                         compiler.Report.Error (1703,
469                                                                                 "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
470                                                                                 an.FullName);
471                                                                         return null;
472                                                                 }
473                                                         }
474
475                                                         if (compiler.Settings.DebugFlags > 0)
476                                                                 Console.WriteLine ("Loading assembly `{0}'", fileName);
477
478                                                         var assembly = domain.LoadAssembly (module);
479                                                         if (assembly != null)
480                                                                 loaded_names.Add (Tuple.Create (an, fileName, assembly));
481
482                                                         return assembly;
483                                                 }
484                                         }
485                                 } catch (Exception e) {
486                                         if (compiler.Settings.DebugFlags > 0)
487                                                 Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
488
489                                         if (!isImplicitReference)
490                                                 Error_FileCorrupted (file);
491
492                                         return null;
493                                 }
494                         }
495
496                         if (!isImplicitReference)
497                                 Error_FileNotFound (fileName);
498
499                         return null;
500                 }
501
502                 public RawModule LoadModuleFile (string moduleName)
503                 {
504                         foreach (var path in paths) {
505                                 var file = Path.Combine (path, moduleName);
506                                 if (!File.Exists (file)) {
507                                         if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
508                                                 continue;
509
510                                         file += ".netmodule";
511                                         if (!File.Exists (file))
512                                                 continue;
513                                 }
514
515                                 try {
516                                         return domain.OpenRawModule (file);
517                                 } catch {
518                                         Error_FileCorrupted (file);
519                                         return null;
520                                 }
521                         }
522
523                         Error_FileNotFound (moduleName);
524                         return null;                            
525                 }
526
527                 public override void LoadReferences (ModuleContainer module)
528                 {
529                         List<Tuple<RootNamespace, Assembly>> loaded;
530                         base.LoadReferencesCore (module, out corlib, out loaded);
531
532                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
533
534                         if (corlib == null) {
535                                 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
536                                 corlib = module.DeclaringAssembly.Builder;
537                         } else {
538                                 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
539                                 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
540                         }
541
542                         foreach (var entry in loaded) {
543                                 importer.ImportAssembly (entry.Item2, entry.Item1);
544                         }
545
546                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
547                 }
548
549                 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
550                 {
551                         foreach (var moduleName in compiler.Settings.Modules) {
552                                 var m = LoadModuleFile (moduleName);
553                                 if (m == null)
554                                         continue;
555
556                                 if (m.IsManifestModule) {
557                                         Error_ModuleIsAssembly (moduleName);
558                                         continue;
559                                 }
560
561                                 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
562                                 assembly.AddModule (md);
563                         }
564                 }
565         }
566
567         class AssemblyBuilderIKVM : AssemblyBuilderExtension
568         {
569                 readonly AssemblyBuilder builder;
570
571                 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
572                         : base (ctx)
573                 {
574                         this.builder = builder;
575                 }
576
577                 public override void AddTypeForwarder (TypeSpec type, Location loc)
578                 {
579                         builder.__AddTypeForwarder (type.GetMetaInfo ());
580                 }
581
582                 public override void DefineWin32IconResource (string fileName)
583                 {
584                         builder.__DefineIconResource (File.ReadAllBytes (fileName));
585                 }
586
587                 public override void SetAlgorithmId (uint value, Location loc)
588                 {
589                         builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
590                 }
591
592                 public override void SetCulture (string culture, Location loc)
593                 {
594                         builder.__SetAssemblyCulture (culture);
595                 }
596
597                 public override void SetFlags (uint flags, Location loc)
598                 {
599                         builder.__AssemblyFlags = (AssemblyNameFlags) flags;
600                 }
601
602                 public override void SetVersion (Version version, Location loc)
603                 {
604                         builder.__SetAssemblyVersion (version);
605                 }
606         }
607 }