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