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