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)
94 // It can be used more than once when importing same assembly
95 // into 2 or more global aliases
96 // TODO: Should be just Add
97 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 // IsMissing tells us the type has been forwarded and target assembly is missing
131 if (t.Name[0] == '<')
134 var it = CreateType (t, null, new DynamicTypeReader (t), true);
138 if (prev_namespace != t.Namespace) {
139 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
140 prev_namespace = t.Namespace;
143 ns.AddType (module, it);
147 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
150 // Setup mapping for build-in types to avoid duplication of their definition
152 foreach (var type in builtin.AllTypes) {
153 compiled_types.Add (corlib.GetType (type.FullName), type);
159 class AssemblyDefinitionStatic : AssemblyDefinition
161 readonly StaticLoader loader;
164 // Assembly container with file output
166 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
167 : base (module, name, fileName)
169 this.loader = loader;
170 Importer = loader.MetadataImporter;
174 // Initializes the assembly SRE domain
176 public void Create (Universe domain)
178 ResolveAssemblySecurityAttributes ();
179 var an = CreateAssemblyName ();
181 Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
182 module.Create (this, CreateModuleBuilder ());
185 public override void Emit ()
187 if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
188 Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
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);
195 case RuntimeVersion.v2:
196 Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
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);
204 throw new NotImplementedException ();
208 builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
213 public Module IncludeModule (RawModule moduleFile)
215 return Builder.__AddModule (moduleFile);
218 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
220 module.Builder.__Save (pekind, machine);
224 class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
226 readonly StaticImporter importer;
227 readonly Universe domain;
229 List<Tuple<AssemblyName, string, Assembly>> loaded_names;
230 static readonly Dictionary<string, string[]> sdk_directory;
232 static StaticLoader ()
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" });
240 public StaticLoader (StaticImporter importer, CompilerContext compiler)
243 this.importer = importer;
244 domain = new Universe (UniverseOptions.MetadataOnly | UniverseOptions.ResolveMissingMembers);
245 domain.AssemblyResolve += AssemblyReferenceResolver;
246 loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
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));
252 string sdk_path = null;
254 string sdk_version = compiler.Settings.SdkVersion ?? "4.5";
255 string[] sdk_sub_dirs;
257 if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
258 sdk_sub_dirs = new string[] { sdk_version };
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")))
268 if (sdk_path == null) {
269 compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
270 sdk_path = corlib_path;
273 paths.Add (sdk_path);
279 public Assembly Corlib {
285 public Universe Domain {
291 public StaticImporter MetadataImporter {
299 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
301 var refname = args.Name;
302 if (refname == "mscorlib")
305 Assembly version_mismatch = null;
306 bool is_fx_assembly = false;
308 foreach (var assembly in domain.GetAssemblies ()) {
309 AssemblyComparisonResult result;
310 if (!Fusion.CompareAssemblyIdentityPure (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) &&
314 version_mismatch = assembly;
320 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
321 result == AssemblyComparisonResult.EquivalentWeakNamed ||
322 result == AssemblyComparisonResult.EquivalentPartialMatch) {
326 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
327 is_fx_assembly = true;
329 if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
330 version_mismatch = assembly;
335 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
338 if (version_mismatch != null) {
339 if (version_mismatch is AssemblyBuilder)
340 return version_mismatch;
342 var v1 = new AssemblyName (refname).Version;
343 var v2 = version_mismatch.GetName ().Version;
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);
350 return domain.CreateMissingAssembly (args.Name);
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);
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);
365 return version_mismatch;
368 // AssemblyReference has not been found in the domain
369 // create missing reference and continue
370 return domain.CreateMissingAssembly (args.Name);
373 public void Dispose ()
378 protected override string[] GetDefaultReferences ()
381 // For now the "default config" is harcoded into the compiler
382 // we can move this outside later
384 var default_references = new List<string> (4);
386 default_references.Add ("System.dll");
387 default_references.Add ("System.Xml.dll");
388 default_references.Add ("System.Core.dll");
390 if (corlib != null && corlib.GetName ().Version.Major >= 4) {
391 default_references.Add ("Microsoft.CSharp.dll");
394 return default_references.ToArray ();
397 public override bool HasObjectType (Assembly assembly)
399 return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
402 public override Assembly LoadAssemblyFile (string fileName, bool isImplicitReference)
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);
410 if (!File.Exists (file)) {
411 if (!has_extension.HasValue)
412 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
414 if (has_extension.Value)
418 if (!File.Exists (file))
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);
431 // check whether the assembly can be actually imported without
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)
440 if (module.ModuleVersionId == entry.Item3.ManifestModule.ModuleVersionId)
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",
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",
462 if (compiler.Settings.DebugFlags > 0)
463 Console.WriteLine ("Loading assembly `{0}'", fileName);
465 var assembly = domain.LoadAssembly (module);
466 if (assembly != null)
467 loaded_names.Add (Tuple.Create (an, fileName, assembly));
472 } catch (Exception e) {
473 if (compiler.Settings.DebugFlags > 0)
474 Console.WriteLine ("Exception during loading: {0}'", e.ToString ());
476 if (!isImplicitReference)
477 Error_FileCorrupted (file);
483 if (!isImplicitReference)
484 Error_FileNotFound (fileName);
489 public RawModule LoadModuleFile (string moduleName)
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))
497 file += ".netmodule";
498 if (!File.Exists (file))
503 return domain.OpenRawModule (file);
505 Error_FileCorrupted (file);
510 Error_FileNotFound (moduleName);
514 public override void LoadReferences (ModuleContainer module)
516 List<Tuple<RootNamespace, Assembly>> loaded;
517 base.LoadReferencesCore (module, out corlib, out loaded);
519 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
521 if (corlib == null) {
522 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
523 corlib = module.DeclaringAssembly.Builder;
525 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
526 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
529 foreach (var entry in loaded) {
530 importer.ImportAssembly (entry.Item2, entry.Item1);
533 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
536 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
538 foreach (var moduleName in compiler.Settings.Modules) {
539 var m = LoadModuleFile (moduleName);
543 if (m.IsManifestModule) {
544 Error_ModuleIsAssembly (moduleName);
548 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
549 assembly.AddModule (md);
554 class AssemblyBuilderIKVM : AssemblyBuilderExtension
556 readonly AssemblyBuilder builder;
558 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
561 this.builder = builder;
564 public override void AddTypeForwarder (TypeSpec type, Location loc)
566 builder.__AddTypeForwarder (type.GetMetaInfo ());
569 public override void DefineWin32IconResource (string fileName)
571 builder.__DefineIconResource (File.ReadAllBytes (fileName));
574 public override void SetAlgorithmId (uint value, Location loc)
576 builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
579 public override void SetCulture (string culture, Location loc)
581 builder.__SetAssemblyCulture (culture);
584 public override void SetFlags (uint flags, Location loc)
586 builder.__AssemblyFlags = (AssemblyNameFlags) flags;
589 public override void SetVersion (Version version, Location loc)
591 builder.__SetAssemblyVersion (version);