2 // ikvm.cs: IKVM.Reflection and IKVM.Reflection.Emit specific implementations
4 // Author: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2010 Novell, Inc.
9 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
15 using MetaType = IKVM.Reflection.Type;
16 using IKVM.Reflection;
17 using IKVM.Reflection.Emit;
19 using System.Configuration.Assemblies;
24 public class StaticImporter
26 public StaticImporter (BuiltinTypes builtin)
28 throw new NotSupportedException ();
31 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
33 throw new NotSupportedException ();
36 public void ImportModule (Module module, RootNamespace targetNamespace)
38 throw new NotSupportedException ();
41 public TypeSpec ImportType (System.Type type)
43 throw new NotSupportedException ();
49 sealed class StaticImporter : MetadataImporter
51 public StaticImporter (ModuleContainer module)
56 public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
58 assembly_2_definition.Add (assembly.Builder, assembly);
61 public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
63 compiled_types.Add (type, spec);
66 protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
68 string name = baseType.Name;
70 if (name == "ValueType" && baseType.Namespace == "System")
71 return MemberKind.Struct;
73 if (name == "Enum" && baseType.Namespace == "System")
74 return MemberKind.Enum;
76 if (name == "MulticastDelegate" && baseType.Namespace == "System")
77 return MemberKind.Delegate;
79 return MemberKind.Class;
82 protected override bool HasVolatileModifier (MetaType[] modifiers)
84 foreach (var t in modifiers) {
85 if (t.Name == "IsVolatile" && t.Namespace == CompilerServicesNamespace)
92 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
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);
100 var all_types = assembly.GetTypes ();
101 ImportTypes (all_types, targetNamespace, true);
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);
111 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
113 var module_definition = new ImportedModuleDefinition (module);
114 module_definition.ReadAttributes ();
116 var all_types = module.GetTypes ();
117 ImportTypes (all_types, targetNamespace, false);
119 return module_definition;
122 void ImportForwardedTypes (MetaType[] types, Namespace targetNamespace)
124 Namespace ns = targetNamespace;
125 string prev_namespace = null;
126 foreach (var t in types) {
127 if (!t.__IsTypeForwarder)
130 // IsMissing tells us the type has been forwarded and target assembly is missing
134 if (t.Name[0] == '<')
137 var it = CreateType (t, null, new DynamicTypeReader (t), true);
141 if (prev_namespace != t.Namespace) {
142 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
143 prev_namespace = t.Namespace;
146 ns.AddType (module, it);
150 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
153 // Setup mapping for build-in types to avoid duplication of their definition
155 foreach (var type in builtin.AllTypes) {
156 compiled_types.Add (corlib.GetType (type.FullName), type);
162 class AssemblyDefinitionStatic : AssemblyDefinition
164 readonly StaticLoader loader;
167 // Assembly container with file output
169 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
170 : base (module, name, fileName)
172 this.loader = loader;
173 Importer = loader.MetadataImporter;
177 // Initializes the assembly SRE domain
179 public void Create (Universe domain)
181 ResolveAssemblySecurityAttributes ();
182 var an = CreateAssemblyName ();
184 Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
185 module.Create (this, CreateModuleBuilder ());
188 public override void Emit ()
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);
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);
200 case RuntimeVersion.v2:
201 Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
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);
209 throw new NotImplementedException ();
213 builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
218 public Module IncludeModule (RawModule moduleFile)
220 return Builder.__AddModule (moduleFile);
223 protected override List<string[]> GetNotUnifiedReferences (AssemblyName assemblyName)
225 return loader.GetNotUnifiedReferences (assemblyName);
228 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
230 module.Builder.__Save (pekind, machine);
234 class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
236 readonly StaticImporter importer;
237 readonly Universe domain;
239 readonly List<Tuple<AssemblyName, string, Assembly>> loaded_names;
240 static readonly Dictionary<string, string[]> sdk_directory;
241 Dictionary<AssemblyName, List<string[]>> resolved_version_mismatches;
243 static StaticLoader ()
245 sdk_directory = new Dictionary<string, string[]> ();
246 sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
247 sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
248 sdk_directory.Add ("4.5", new string[] { "4.5", "net_4_x", "v4.0.30319" });
251 public StaticLoader (StaticImporter importer, CompilerContext compiler)
254 this.importer = importer;
255 domain = new Universe (UniverseOptions.MetadataOnly | UniverseOptions.ResolveMissingMembers |
256 UniverseOptions.DisableFusion | UniverseOptions.DecodeVersionInfoAttributeBlobs |
257 UniverseOptions.DeterministicOutput);
259 domain.AssemblyResolve += AssemblyReferenceResolver;
260 loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
262 if (compiler.Settings.StdLib) {
263 var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
264 string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
266 string sdk_path = null;
268 string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
269 string[] sdk_sub_dirs;
271 if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
272 sdk_sub_dirs = new string[] { sdk_version };
274 foreach (var dir in sdk_sub_dirs) {
275 sdk_path = Path.Combine (fx_path, dir);
276 if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
282 if (sdk_path == null) {
283 compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
284 sdk_path = corlib_path;
287 paths.Add (sdk_path);
293 public Assembly Corlib {
299 public AssemblyDefinitionStatic CompiledAssembly { get; set; }
301 public Universe Domain {
307 public StaticImporter MetadataImporter {
315 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
317 var refname = args.Name;
318 if (refname == "mscorlib")
321 Assembly version_mismatch = null;
322 bool is_fx_assembly = false;
324 foreach (var assembly in domain.GetAssemblies ()) {
325 AssemblyComparisonResult result;
326 if (!domain.CompareAssemblyIdentity (refname, false, assembly.FullName, false, out result)) {
327 if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
328 (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
330 version_mismatch = assembly;
336 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
337 result == AssemblyComparisonResult.EquivalentWeakNamed ||
338 result == AssemblyComparisonResult.EquivalentPartialMatch) {
342 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
343 is_fx_assembly = true;
345 if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
346 version_mismatch = assembly;
351 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
354 if (version_mismatch != null) {
355 if (version_mismatch is AssemblyBuilder)
356 return version_mismatch;
358 var v1 = new AssemblyName (refname).Version;
359 var v2 = version_mismatch.GetName ().Version;
362 if (resolved_version_mismatches == null)
363 resolved_version_mismatches = new Dictionary<AssemblyName, List<string[]>> ();
365 var an = args.RequestingAssembly.GetName ();
366 List<string[]> names;
367 if (!resolved_version_mismatches.TryGetValue (an, out names)) {
368 names = new List<string[]> ();
369 resolved_version_mismatches.Add (an, names);
373 args.RequestingAssembly.Location,
374 string.Format ("Assembly `{0}' depends on `{1}' which has a higher version number than referenced assembly `{2}'",
375 args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName)
378 return version_mismatch;
381 if (!is_fx_assembly) {
382 if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
383 compiler.Report.Warning (1701, 2,
384 "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
385 refname, version_mismatch.GetName ().FullName);
387 compiler.Report.Warning (1702, 3,
388 "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
389 refname, version_mismatch.GetName ().FullName);
393 return version_mismatch;
397 // Recursive reference to compiled assembly checks name only. Any other
398 // details (PublicKey, Version, etc) are not yet known hence cannot be checked
400 ParsedAssemblyName referenced_assembly;
401 if (Fusion.ParseAssemblyName (args.Name, out referenced_assembly) == ParseAssemblyResult.OK && CompiledAssembly.Name == referenced_assembly.Name)
402 return CompiledAssembly.Builder;
404 // AssemblyReference has not been found in the domain
405 // create missing reference and continue
406 return domain.CreateMissingAssembly (args.Name);
409 public void Dispose ()
414 protected override string[] GetDefaultReferences ()
417 // For now the "default config" is harcoded into the compiler
418 // we can move this outside later
420 var default_references = new List<string> (4);
422 default_references.Add ("System.dll");
423 default_references.Add ("System.Xml.dll");
424 default_references.Add ("System.Core.dll");
426 if (corlib != null && corlib.GetName ().Version.Major >= 4) {
427 default_references.Add ("Microsoft.CSharp.dll");
430 return default_references.ToArray ();
433 public List<string[]> GetNotUnifiedReferences (AssemblyName assemblyName)
435 List<string[]> list = null;
436 if (resolved_version_mismatches != null)
437 resolved_version_mismatches.TryGetValue (assemblyName, out list);
442 public override bool HasObjectType (Assembly assembly)
445 return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
446 } catch (Exception e) {
447 throw new InternalErrorException (e, "Failed to load assembly `{0}'", assembly.FullName);
451 public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
453 bool? has_extension = null;
454 foreach (var path in paths) {
455 var file = Path.Combine (path, fileName);
456 if (compiler.Settings.DebugFlags > 0)
457 Console.WriteLine ("Probing assembly location `{0}'", file);
459 if (!File.Exists (file)) {
460 if (!has_extension.HasValue)
461 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
463 if (has_extension.Value)
467 if (!File.Exists (file))
472 using (var stream = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.Read)) {
473 using (RawModule module = domain.OpenRawModule (stream, file)) {
474 if (!module.IsManifestModule) {
475 Error_AssemblyIsModule (fileName);
480 // check whether the assembly can be actually imported without
483 var an = module.GetAssemblyName ();
484 foreach (var entry in loaded_names) {
485 var loaded_name = entry.Item1;
486 if (an.Name != loaded_name.Name)
489 if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
492 if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
493 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
494 compiler.Report.SymbolRelatedToPreviousError (fileName);
495 compiler.Report.Error (1704,
496 "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
501 if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey)) {
502 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
503 compiler.Report.SymbolRelatedToPreviousError (fileName);
504 compiler.Report.Error (1703,
505 "An assembly `{0}' with the same identity has already been imported. Consider removing one of the references",
511 if (compiler.Settings.DebugFlags > 0)
512 Console.WriteLine ("Loading assembly `{0}'", fileName);
514 var assembly = domain.LoadAssembly (module);
515 if (assembly != null)
516 loaded_names.Add (Tuple.Create (an, fileName, assembly));
521 } catch (Exception e) {
522 if (compiler.Settings.DebugFlags > 0)
523 Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
525 if (!isImplicitReference)
526 Error_FileCorrupted (file);
532 if (!isImplicitReference)
533 Error_FileNotFound (fileName);
538 public RawModule LoadModuleFile (string moduleName)
540 foreach (var path in paths) {
541 var file = Path.Combine (path, moduleName);
542 if (!File.Exists (file)) {
543 if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
546 file += ".netmodule";
547 if (!File.Exists (file))
552 return domain.OpenRawModule (file);
554 Error_FileCorrupted (file);
559 Error_FileNotFound (moduleName);
563 public override void LoadReferences (ModuleContainer module)
565 List<Tuple<RootNamespace, Assembly>> loaded;
566 base.LoadReferencesCore (module, out corlib, out loaded);
568 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
570 if (corlib == null) {
571 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
572 corlib = module.DeclaringAssembly.Builder;
574 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
575 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
578 foreach (var entry in loaded) {
579 importer.ImportAssembly (entry.Item2, entry.Item1);
582 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
585 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
587 foreach (var moduleName in compiler.Settings.Modules) {
588 var m = LoadModuleFile (moduleName);
592 if (m.IsManifestModule) {
593 Error_ModuleIsAssembly (moduleName);
597 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
598 assembly.AddModule (md);
603 class AssemblyBuilderIKVM : AssemblyBuilderExtension
605 readonly AssemblyBuilder builder;
607 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
610 this.builder = builder;
613 public override void AddTypeForwarder (TypeSpec type, Location loc)
615 builder.__AddTypeForwarder (type.GetMetaInfo ());
618 public override void DefineWin32IconResource (string fileName)
620 builder.__DefineIconResource (File.ReadAllBytes (fileName));
623 public override AssemblyName[] GetReferencedAssemblies ()
625 foreach (var m in builder.Modules) {
626 if (m is ModuleBuilder)
627 return m.__GetReferencedAssemblies ();
630 return new AssemblyName [0];
633 public override void SetAlgorithmId (uint value, Location loc)
635 builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
638 public override void SetCulture (string culture, Location loc)
640 builder.__SetAssemblyCulture (culture);
643 public override void SetFlags (uint flags, Location loc)
645 builder.__AssemblyFlags = (AssemblyNameFlags) flags;
648 public override void SetVersion (Version version, Location loc)
650 builder.__SetAssemblyVersion (version);