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