Merge pull request #780 from miniBill/master
[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 Universe Domain {
289                         get {
290                                 return domain;
291                         }
292                 }
293
294                 public StaticImporter MetadataImporter {
295                         get {
296                                 return importer;
297                         }
298                 }
299
300                 #endregion
301
302                 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
303                 {
304                         var refname = args.Name;
305                         if (refname == "mscorlib")
306                                 return corlib;
307
308                         Assembly version_mismatch = null;
309                         bool is_fx_assembly = false;
310
311                         foreach (var assembly in domain.GetAssemblies ()) {
312                                 AssemblyComparisonResult result;
313                                 if (!domain.CompareAssemblyIdentity (refname, false, assembly.FullName, false, out result)) {
314                                         if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
315                                                 (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
316                                                 !is_fx_assembly) {
317                                                 version_mismatch = assembly;
318                                         }
319
320                                         continue;
321                                 }
322
323                                 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
324                                         result == AssemblyComparisonResult.EquivalentWeakNamed ||
325                                         result == AssemblyComparisonResult.EquivalentPartialMatch) {
326                                         return assembly;
327                                 }
328
329                                 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
330                                         is_fx_assembly = true;
331
332                                         if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
333                                                 version_mismatch = assembly;
334
335                                         continue;
336                                 }
337
338                                 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
339                         }
340
341                         if (version_mismatch != null) {
342                                 if (version_mismatch is AssemblyBuilder)
343                                         return version_mismatch;
344
345                                 var v1 = new AssemblyName (refname).Version;
346                                 var v2 = version_mismatch.GetName ().Version;
347
348                                 if (v1 > v2) {
349 //                                      compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
350                                         compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
351                                                 args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);
352
353                                         return domain.CreateMissingAssembly (args.Name);
354                                 }
355
356                                 if (!is_fx_assembly) {
357                                         if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
358                                                 compiler.Report.Warning (1701, 2,
359                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
360                                                         refname, version_mismatch.GetName ().FullName);
361                                         } else {
362                                                 compiler.Report.Warning (1702, 3,
363                                                         "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
364                                                         refname, version_mismatch.GetName ().FullName);
365                                         }
366                                 }
367
368                                 return version_mismatch;
369                         }
370
371                         // AssemblyReference has not been found in the domain
372                         // create missing reference and continue
373                         return domain.CreateMissingAssembly (args.Name);
374                 }
375
376                 public void Dispose ()
377                 {
378                         domain.Dispose ();
379                 }
380
381                 protected override string[] GetDefaultReferences ()
382                 {
383                         //
384                         // For now the "default config" is harcoded into the compiler
385                         // we can move this outside later
386                         //
387                         var default_references = new List<string> (4);
388
389                         default_references.Add ("System.dll");
390                         default_references.Add ("System.Xml.dll");
391                         default_references.Add ("System.Core.dll");
392
393                         if (corlib != null && corlib.GetName ().Version.Major >= 4) {
394                                 default_references.Add ("Microsoft.CSharp.dll");
395                         }
396
397                         return default_references.ToArray ();
398                 }
399
400                 public override bool HasObjectType (Assembly assembly)
401                 {
402                         return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
403                 }
404
405                 public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
406                 {
407                         bool? has_extension = null;
408                         foreach (var path in paths) {
409                                 var file = Path.Combine (path, fileName);
410                                 if (compiler.Settings.DebugFlags > 0)
411                                         Console.WriteLine ("Probing assembly location `{0}'", file);
412
413                                 if (!File.Exists (file)) {
414                                         if (!has_extension.HasValue)
415                                                 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
416
417                                         if (has_extension.Value)
418                                                 continue;
419
420                                         file += ".dll";
421                                         if (!File.Exists (file))
422                                                 continue;
423                                 }
424
425                                 try {
426                                         using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
427                                                 using (RawModule module = domain.OpenRawModule (stream, file)) {
428                                                         if (!module.IsManifestModule) {
429                                                                 Error_AssemblyIsModule (fileName);
430                                                                 return null;
431                                                         }
432
433                                                         //
434                                                         // check whether the assembly can be actually imported without
435                                                         // collision
436                                                         //
437                                                         var an = module.GetAssemblyName ();
438                                                         foreach (var entry in loaded_names) {
439                                                                 var loaded_name = entry.Item1;
440                                                                 if (an.Name != loaded_name.Name)
441                                                                         continue;
442
443                                                                 if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
444                                                                         return entry.Item3;
445                                                         
446                                                                 if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
447                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
448                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
449                                                                         compiler.Report.Error (1704,
450                                                                                 "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
451                                                                                 an.Name);
452                                                                         return null;
453                                                                 }
454
455                                                                 if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
456                                                                         compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
457                                                                         compiler.Report.SymbolRelatedToPreviousError (fileName);
458                                                                         compiler.Report.Error (1703,
459                                                                                 "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
460                                                                                 an.FullName);
461                                                                         return null;
462                                                                 }
463                                                         }
464
465                                                         if (compiler.Settings.DebugFlags > 0)
466                                                                 Console.WriteLine ("Loading assembly `{0}'", fileName);
467
468                                                         var assembly = domain.LoadAssembly (module);
469                                                         if (assembly != null)
470                                                                 loaded_names.Add (Tuple.Create (an, fileName, assembly));
471
472                                                         return assembly;
473                                                 }
474                                         }
475                                 } catch (Exception e) {
476                                         if (compiler.Settings.DebugFlags > 0)
477                                                 Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
478
479                                         if (!isImplicitReference)
480                                                 Error_FileCorrupted (file);
481
482                                         return null;
483                                 }
484                         }
485
486                         if (!isImplicitReference)
487                                 Error_FileNotFound (fileName);
488
489                         return null;
490                 }
491
492                 public RawModule LoadModuleFile (string moduleName)
493                 {
494                         foreach (var path in paths) {
495                                 var file = Path.Combine (path, moduleName);
496                                 if (!File.Exists (file)) {
497                                         if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
498                                                 continue;
499
500                                         file += ".netmodule";
501                                         if (!File.Exists (file))
502                                                 continue;
503                                 }
504
505                                 try {
506                                         return domain.OpenRawModule (file);
507                                 } catch {
508                                         Error_FileCorrupted (file);
509                                         return null;
510                                 }
511                         }
512
513                         Error_FileNotFound (moduleName);
514                         return null;                            
515                 }
516
517                 public override void LoadReferences (ModuleContainer module)
518                 {
519                         List<Tuple<RootNamespace, Assembly>> loaded;
520                         base.LoadReferencesCore (module, out corlib, out loaded);
521
522                         compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
523
524                         if (corlib == null) {
525                                 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
526                                 corlib = module.DeclaringAssembly.Builder;
527                         } else {
528                                 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
529                                 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
530                         }
531
532                         foreach (var entry in loaded) {
533                                 importer.ImportAssembly (entry.Item2, entry.Item1);
534                         }
535
536                         compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
537                 }
538
539                 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
540                 {
541                         foreach (var moduleName in compiler.Settings.Modules) {
542                                 var m = LoadModuleFile (moduleName);
543                                 if (m == null)
544                                         continue;
545
546                                 if (m.IsManifestModule) {
547                                         Error_ModuleIsAssembly (moduleName);
548                                         continue;
549                                 }
550
551                                 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
552                                 assembly.AddModule (md);
553                         }
554                 }
555         }
556
557         class AssemblyBuilderIKVM : AssemblyBuilderExtension
558         {
559                 readonly AssemblyBuilder builder;
560
561                 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
562                         : base (ctx)
563                 {
564                         this.builder = builder;
565                 }
566
567                 public override void AddTypeForwarder (TypeSpec type, Location loc)
568                 {
569                         builder.__AddTypeForwarder (type.GetMetaInfo ());
570                 }
571
572                 public override void DefineWin32IconResource (string fileName)
573                 {
574                         builder.__DefineIconResource (File.ReadAllBytes (fileName));
575                 }
576
577                 public override void SetAlgorithmId (uint value, Location loc)
578                 {
579                         builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
580                 }
581
582                 public override void SetCulture (string culture, Location loc)
583                 {
584                         builder.__SetAssemblyCulture (culture);
585                 }
586
587                 public override void SetFlags (uint flags, Location loc)
588                 {
589                         builder.__AssemblyFlags = (AssemblyNameFlags) flags;
590                 }
591
592                 public override void SetVersion (Version version, Location loc)
593                 {
594                         builder.__SetAssemblyVersion (version);
595                 }
596         }
597 }