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.
13 using System.Collections.Generic;
14 using MetaType = IKVM.Reflection.Type;
15 using IKVM.Reflection;
16 using IKVM.Reflection.Emit;
18 using System.Configuration.Assemblies;
23 public class StaticImporter
25 public StaticImporter (BuiltinTypes builtin)
27 throw new NotSupportedException ();
30 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
32 throw new NotSupportedException ();
35 public void ImportModule (Module module, RootNamespace targetNamespace)
37 throw new NotSupportedException ();
40 public TypeSpec ImportType (System.Type type)
42 throw new NotSupportedException ();
48 sealed class StaticImporter : MetadataImporter
50 public StaticImporter (ModuleContainer module)
55 public void AddCompiledAssembly (AssemblyDefinitionStatic assembly)
57 assembly_2_definition.Add (assembly.Builder, assembly);
60 public override void AddCompiledType (TypeBuilder type, TypeSpec spec)
62 compiled_types.Add (type, spec);
65 protected override MemberKind DetermineKindFromBaseType (MetaType baseType)
67 string name = baseType.Name;
69 if (name == "ValueType" && baseType.Namespace == "System")
70 return MemberKind.Struct;
72 if (name == "Enum" && baseType.Namespace == "System")
73 return MemberKind.Enum;
75 if (name == "MulticastDelegate" && baseType.Namespace == "System")
76 return MemberKind.Delegate;
78 return MemberKind.Class;
81 protected override bool HasVolatileModifier (MetaType[] modifiers)
83 foreach (var t in modifiers) {
84 if (t.Name == "IsVolatile" && t.Namespace == CompilerServicesNamespace)
91 public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
93 // It can be used more than once when importing same assembly
94 // into 2 or more global aliases
95 var definition = GetAssemblyDefinition (assembly);
97 var all_types = assembly.GetTypes ();
98 ImportTypes (all_types, targetNamespace, definition.HasExtensionMethod);
101 public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
103 var module_definition = new ImportedModuleDefinition (module);
104 module_definition.ReadAttributes ();
106 var all_types = module.GetTypes ();
107 ImportTypes (all_types, targetNamespace, false);
109 return module_definition;
112 public void InitializeBuiltinTypes (BuiltinTypes builtin, Assembly corlib)
115 // Setup mapping for build-in types to avoid duplication of their definition
117 foreach (var type in builtin.AllTypes) {
118 compiled_types.Add (corlib.GetType (type.FullName), type);
124 class AssemblyDefinitionStatic : AssemblyDefinition
126 readonly StaticLoader loader;
129 // Assembly container with file output
131 public AssemblyDefinitionStatic (ModuleContainer module, StaticLoader loader, string name, string fileName)
132 : base (module, name, fileName)
134 this.loader = loader;
135 Importer = loader.MetadataImporter;
139 // Initializes the assembly SRE domain
141 public void Create (Universe domain)
143 ResolveAssemblySecurityAttributes ();
144 var an = CreateAssemblyName ();
146 Builder = domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, Path.GetDirectoryName (file_name));
147 module.Create (this, CreateModuleBuilder ());
150 public override void Emit ()
152 if (loader.Corlib != null && !(loader.Corlib is AssemblyBuilder)) {
153 Builder.__SetImageRuntimeVersion (loader.Corlib.ImageRuntimeVersion, 0x20000);
155 // Sets output file metadata version when there is no mscorlib
156 switch (module.Compiler.Settings.StdLibRuntimeVersion) {
157 case RuntimeVersion.v4:
158 Builder.__SetImageRuntimeVersion ("v4.0.30319", 0x20000);
160 case RuntimeVersion.v2:
161 Builder.__SetImageRuntimeVersion ("v2.0.50727", 0x20000);
163 case RuntimeVersion.v1:
164 // Compiler does not do any checks whether the produced metadata
165 // are valid in the context of 1.0 stream version
166 Builder.__SetImageRuntimeVersion ("v1.1.4322", 0x10000);
169 throw new NotImplementedException ();
173 builder_extra = new AssemblyBuilderIKVM (Builder, Compiler);
178 public Module IncludeModule (RawModule moduleFile)
180 return Builder.__AddModule (moduleFile);
183 protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
185 module.Builder.__Save (pekind, machine);
189 class StaticLoader : AssemblyReferencesLoader<Assembly>, IDisposable
191 readonly StaticImporter importer;
192 readonly Universe domain;
194 List<Tuple<AssemblyName, string, Assembly>> loaded_names;
195 static readonly Dictionary<string, string[]> sdk_directory;
197 static StaticLoader ()
199 sdk_directory = new Dictionary<string, string[]> ();
200 sdk_directory.Add ("2", new string[] { "2.0", "net_2_0", "v2.0.50727" });
201 sdk_directory.Add ("4", new string[] { "4.0", "net_4_0", "v4.0.30319" });
204 public StaticLoader (StaticImporter importer, CompilerContext compiler)
207 this.importer = importer;
208 domain = new Universe ();
209 domain.EnableMissingMemberResolution ();
210 domain.AssemblyResolve += AssemblyReferenceResolver;
211 loaded_names = new List<Tuple<AssemblyName, string, Assembly>> ();
213 var corlib_path = Path.GetDirectoryName (typeof (object).Assembly.Location);
214 string fx_path = corlib_path.Substring (0, corlib_path.LastIndexOf (Path.DirectorySeparatorChar));
215 string sdk_path = null;
217 string sdk_version = compiler.Settings.SdkVersion ?? "4";
218 string[] sdk_sub_dirs;
220 if (!sdk_directory.TryGetValue (sdk_version, out sdk_sub_dirs))
221 sdk_sub_dirs = new string[] { sdk_version };
223 foreach (var dir in sdk_sub_dirs) {
224 sdk_path = Path.Combine (fx_path, dir);
225 if (File.Exists (Path.Combine (sdk_path, "mscorlib.dll")))
231 if (sdk_path == null) {
232 compiler.Report.Warning (-1, 1, "SDK path could not be resolved");
233 sdk_path = corlib_path;
236 paths.Add (sdk_path);
241 public Assembly Corlib {
250 public Universe Domain {
256 public StaticImporter MetadataImporter {
264 Assembly AssemblyReferenceResolver (object sender, IKVM.Reflection.ResolveEventArgs args)
266 var refname = args.Name;
267 if (refname == "mscorlib")
270 Assembly version_mismatch = null;
271 bool is_fx_assembly = false;
273 foreach (var assembly in domain.GetAssemblies ()) {
274 AssemblyComparisonResult result;
275 if (!Fusion.CompareAssemblyIdentityPure (refname, false, assembly.FullName, false, out result)) {
276 if ((result == AssemblyComparisonResult.NonEquivalentVersion || result == AssemblyComparisonResult.NonEquivalentPartialVersion) &&
277 (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version) &&
279 version_mismatch = assembly;
285 if (result == AssemblyComparisonResult.EquivalentFullMatch ||
286 result == AssemblyComparisonResult.EquivalentWeakNamed ||
287 result == AssemblyComparisonResult.EquivalentPartialMatch) {
291 if (result == AssemblyComparisonResult.EquivalentFXUnified) {
292 is_fx_assembly = true;
294 if (version_mismatch == null || version_mismatch.GetName ().Version < assembly.GetName ().Version)
295 version_mismatch = assembly;
300 throw new NotImplementedException ("Assembly equality = " + result.ToString ());
303 if (version_mismatch != null) {
304 if (version_mismatch is AssemblyBuilder)
305 return version_mismatch;
307 var v1 = new AssemblyName (refname).Version;
308 var v2 = version_mismatch.GetName ().Version;
311 // compiler.Report.SymbolRelatedToPreviousError (args.RequestingAssembly.Location);
312 compiler.Report.Error (1705, "Assembly `{0}' references `{1}' which has a higher version number than imported assembly `{2}'",
313 args.RequestingAssembly.FullName, refname, version_mismatch.GetName ().FullName);
315 return domain.CreateMissingAssembly (args.Name);
318 if (!is_fx_assembly) {
319 if (v1.Major != v2.Major || v1.Minor != v2.Minor) {
320 compiler.Report.Warning (1701, 2,
321 "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
322 refname, version_mismatch.GetName ().FullName);
324 compiler.Report.Warning (1702, 3,
325 "Assuming assembly reference `{0}' matches assembly `{1}'. You may need to supply runtime policy",
326 refname, version_mismatch.GetName ().FullName);
330 return version_mismatch;
333 // AssemblyReference has not been found in the domain
334 // create missing reference and continue
335 return domain.CreateMissingAssembly (args.Name);
338 public void Dispose ()
343 protected override string[] GetDefaultReferences ()
346 // For now the "default config" is harcoded into the compiler
347 // we can move this outside later
349 var default_references = new List<string> (4);
351 default_references.Add ("System.dll");
352 default_references.Add ("System.Xml.dll");
353 default_references.Add ("System.Core.dll");
355 if (corlib != null && corlib.GetName ().Version.Major >= 4) {
356 default_references.Add ("Microsoft.CSharp.dll");
359 if (compiler.Settings.Version == LanguageVersion.Future)
360 default_references.Add ("Mono.Async.dll");
362 return default_references.ToArray ();
365 public override bool HasObjectType (Assembly assembly)
367 return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
370 public override Assembly LoadAssemblyFile (string fileName)
372 bool? has_extension = null;
373 foreach (var path in paths) {
374 var file = Path.Combine (path, fileName);
375 if (compiler.Settings.DebugFlags > 0)
376 Console.WriteLine ("Probing assembly location `{0}'", file);
378 if (!File.Exists (file)) {
379 if (!has_extension.HasValue)
380 has_extension = fileName.EndsWith (".dll", StringComparison.Ordinal) || fileName.EndsWith (".exe", StringComparison.Ordinal);
382 if (has_extension.Value)
386 if (!File.Exists (file))
391 using (RawModule module = domain.OpenRawModule (file)) {
392 if (!module.IsManifestModule) {
393 Error_AssemblyIsModule (fileName);
398 // check whether the assembly can be actually imported without
401 var an = module.GetAssemblyName ();
402 foreach (var entry in loaded_names) {
403 var loaded_name = entry.Item1;
404 if (an.Name != loaded_name.Name)
407 if (an.CodeBase == loaded_name.CodeBase)
410 if (((an.Flags | loaded_name.Flags) & AssemblyNameFlags.PublicKey) == 0) {
411 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
412 compiler.Report.SymbolRelatedToPreviousError (fileName);
413 compiler.Report.Error (1704,
414 "An assembly with the same name `{0}' has already been imported. Consider removing one of the references or sign the assembly",
419 if ((an.Flags & AssemblyNameFlags.PublicKey) == (loaded_name.Flags & AssemblyNameFlags.PublicKey) && an.Version.Equals (loaded_name.Version)) {
420 compiler.Report.SymbolRelatedToPreviousError (entry.Item2);
421 compiler.Report.SymbolRelatedToPreviousError (fileName);
422 compiler.Report.Error (1703,
423 "An assembly with the same identity `{0}' has already been imported. Consider removing one of the references",
429 if (compiler.Settings.DebugFlags > 0)
430 Console.WriteLine ("Loading assembly `{0}'", fileName);
432 var assembly = domain.LoadAssembly (module);
433 if (assembly != null)
434 loaded_names.Add (Tuple.Create (an, fileName, assembly));
439 Error_FileCorrupted (file);
444 Error_FileNotFound (fileName);
448 public RawModule LoadModuleFile (string moduleName)
450 foreach (var path in paths) {
451 var file = Path.Combine (path, moduleName);
452 if (!File.Exists (file)) {
453 if (moduleName.EndsWith (".netmodule", StringComparison.Ordinal))
456 file += ".netmodule";
457 if (!File.Exists (file))
462 return domain.OpenRawModule (file);
464 Error_FileCorrupted (file);
469 Error_FileNotFound (moduleName);
474 // Optimized default assembly loader version
476 public override Assembly LoadAssemblyDefault (string assembly)
478 foreach (var path in paths) {
479 var file = Path.Combine (path, assembly);
481 if (compiler.Settings.DebugFlags > 0)
482 Console.WriteLine ("Probing default assembly location `{0}'", file);
484 if (!File.Exists (file))
488 if (compiler.Settings.DebugFlags > 0)
489 Console.WriteLine ("Loading default assembly `{0}'", file);
491 var a = domain.LoadFile (file);
493 loaded_names.Add (Tuple.Create (a.GetName (), file, a));
498 // Default assemblies can fail to load without error
506 public override void LoadReferences (ModuleContainer module)
508 List<Tuple<RootNamespace, Assembly>> loaded;
509 base.LoadReferencesCore (module, out corlib, out loaded);
511 compiler.TimeReporter.Start (TimeReporter.TimerType.ReferencesImporting);
513 if (corlib == null) {
514 // System.Object was not found in any referenced assembly, use compiled assembly as corlib
515 corlib = module.DeclaringAssembly.Builder;
517 importer.InitializeBuiltinTypes (compiler.BuiltinTypes, corlib);
518 importer.ImportAssembly (corlib, module.GlobalRootNamespace);
521 foreach (var entry in loaded) {
522 importer.ImportAssembly (entry.Item2, entry.Item1);
525 compiler.TimeReporter.Stop (TimeReporter.TimerType.ReferencesImporting);
528 public void LoadModules (AssemblyDefinitionStatic assembly, RootNamespace targetNamespace)
530 foreach (var moduleName in compiler.Settings.Modules) {
531 var m = LoadModuleFile (moduleName);
535 if (m.IsManifestModule) {
536 Error_ModuleIsAssembly (moduleName);
540 var md = importer.ImportModule (assembly.IncludeModule (m), targetNamespace);
541 assembly.AddModule (md);
546 class AssemblyBuilderIKVM : AssemblyBuilderExtension
548 readonly AssemblyBuilder builder;
550 public AssemblyBuilderIKVM (AssemblyBuilder builder, CompilerContext ctx)
553 this.builder = builder;
556 public override void AddTypeForwarder (TypeSpec type, Location loc)
558 builder.__AddTypeForwarder (type.GetMetaInfo ());
561 public override void DefineWin32IconResource (string fileName)
563 builder.__DefineIconResource (File.ReadAllBytes (fileName));
566 public override void SetAlgorithmId (uint value, Location loc)
568 builder.__SetAssemblyAlgorithmId ((AssemblyHashAlgorithm) value);
571 public override void SetCulture (string culture, Location loc)
573 builder.__SetAssemblyCulture (culture);
576 public override void SetFlags (uint flags, Location loc)
578 builder.__SetAssemblyFlags ((AssemblyNameFlags) flags);
581 public override void SetVersion (Version version, Location loc)
583 builder.__SetAssemblyVersion (version);