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