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