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