1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
|
//
// reflection.cs: System.Reflection and System.Reflection.Emit specific implementations
//
// Author: Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2009-2010 Novell, Inc.
//
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Security;
namespace Mono.CSharp
{
#if STATIC
public class ReflectionImporter
{
public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
{
throw new NotSupportedException ();
}
public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
{
throw new NotSupportedException ();
}
public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
{
throw new NotSupportedException ();
}
public TypeSpec ImportType (Type type)
{
throw new NotSupportedException ();
}
}
#else
public sealed class ReflectionImporter : MetadataImporter
{
public ReflectionImporter (ModuleContainer module, BuiltinTypes builtin)
: base (module)
{
Initialize (builtin);
}
public override void AddCompiledType (TypeBuilder builder, TypeSpec spec)
{
}
protected override MemberKind DetermineKindFromBaseType (Type baseType)
{
if (baseType == typeof (ValueType))
return MemberKind.Struct;
if (baseType == typeof (System.Enum))
return MemberKind.Enum;
if (baseType == typeof (MulticastDelegate))
return MemberKind.Delegate;
return MemberKind.Class;
}
protected override bool HasVolatileModifier (Type[] modifiers)
{
foreach (var t in modifiers) {
if (t == typeof (IsVolatile))
return true;
}
return false;
}
public void ImportAssembly (Assembly assembly, RootNamespace targetNamespace)
{
// It can be used more than once when importing same assembly
// into 2 or more global aliases
GetAssemblyDefinition (assembly);
//
// This part tries to simulate loading of top-level
// types only, any missing dependencies are ignores here.
// Full error report is reported later when the type is
// actually used
//
Type[] all_types;
try {
all_types = assembly.GetTypes ();
} catch (ReflectionTypeLoadException e) {
all_types = e.Types;
}
ImportTypes (all_types, targetNamespace, true);
}
public ImportedModuleDefinition ImportModule (Module module, RootNamespace targetNamespace)
{
var module_definition = new ImportedModuleDefinition (module);
module_definition.ReadAttributes ();
Type[] all_types;
try {
all_types = module.GetTypes ();
} catch (ReflectionTypeLoadException e) {
all_types = e.Types;
}
ImportTypes (all_types, targetNamespace, false);
return module_definition;
}
void Initialize (BuiltinTypes builtin)
{
//
// Setup mapping for build-in types to avoid duplication of their definition
//
compiled_types.Add (typeof (object), builtin.Object);
compiled_types.Add (typeof (System.ValueType), builtin.ValueType);
compiled_types.Add (typeof (System.Attribute), builtin.Attribute);
compiled_types.Add (typeof (int), builtin.Int);
compiled_types.Add (typeof (long), builtin.Long);
compiled_types.Add (typeof (uint), builtin.UInt);
compiled_types.Add (typeof (ulong), builtin.ULong);
compiled_types.Add (typeof (byte), builtin.Byte);
compiled_types.Add (typeof (sbyte), builtin.SByte);
compiled_types.Add (typeof (short), builtin.Short);
compiled_types.Add (typeof (ushort), builtin.UShort);
compiled_types.Add (typeof (System.Collections.IEnumerator), builtin.IEnumerator);
compiled_types.Add (typeof (System.Collections.IEnumerable), builtin.IEnumerable);
compiled_types.Add (typeof (System.IDisposable), builtin.IDisposable);
compiled_types.Add (typeof (char), builtin.Char);
compiled_types.Add (typeof (string), builtin.String);
compiled_types.Add (typeof (float), builtin.Float);
compiled_types.Add (typeof (double), builtin.Double);
compiled_types.Add (typeof (decimal), builtin.Decimal);
compiled_types.Add (typeof (bool), builtin.Bool);
compiled_types.Add (typeof (System.IntPtr), builtin.IntPtr);
compiled_types.Add (typeof (System.UIntPtr), builtin.UIntPtr);
compiled_types.Add (typeof (System.MulticastDelegate), builtin.MulticastDelegate);
compiled_types.Add (typeof (System.Delegate), builtin.Delegate);
compiled_types.Add (typeof (System.Enum), builtin.Enum);
compiled_types.Add (typeof (System.Array), builtin.Array);
compiled_types.Add (typeof (void), builtin.Void);
compiled_types.Add (typeof (System.Type), builtin.Type);
compiled_types.Add (typeof (System.Exception), builtin.Exception);
compiled_types.Add (typeof (System.RuntimeFieldHandle), builtin.RuntimeFieldHandle);
compiled_types.Add (typeof (System.RuntimeTypeHandle), builtin.RuntimeTypeHandle);
}
}
[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Explicit)]
struct SingleConverter
{
[System.Runtime.InteropServices.FieldOffset (0)]
int i;
#pragma warning disable 414
[System.Runtime.InteropServices.FieldOffset (0)]
float f;
#pragma warning restore 414
public static int SingleToInt32Bits (float v)
{
SingleConverter c = new SingleConverter ();
c.f = v;
return c.i;
}
}
#endif
public class AssemblyDefinitionDynamic : AssemblyDefinition
{
//
// In-memory only assembly container
//
public AssemblyDefinitionDynamic (ModuleContainer module, string name)
: base (module, name)
{
}
//
// Assembly container with file output
//
public AssemblyDefinitionDynamic (ModuleContainer module, string name, string fileName)
: base (module, name, fileName)
{
}
public Module IncludeModule (string moduleFile)
{
return builder_extra.AddModule (moduleFile);
}
#if !STATIC
public override ModuleBuilder CreateModuleBuilder ()
{
if (file_name == null)
return Builder.DefineDynamicModule (Name, false);
return base.CreateModuleBuilder ();
}
#endif
//
// Initializes the code generator
//
public bool Create (AppDomain domain, AssemblyBuilderAccess access)
{
#if STATIC
throw new NotSupportedException ();
#else
ResolveAssemblySecurityAttributes ();
var an = CreateAssemblyName ();
Builder = file_name == null ?
domain.DefineDynamicAssembly (an, access) :
domain.DefineDynamicAssembly (an, access, Dirname (file_name));
module.Create (this, CreateModuleBuilder ());
builder_extra = new AssemblyBuilderMonoSpecific (Builder, Compiler);
return true;
#endif
}
static string Dirname (string name)
{
int pos = name.LastIndexOf ('/');
if (pos != -1)
return name.Substring (0, pos);
pos = name.LastIndexOf ('\\');
if (pos != -1)
return name.Substring (0, pos);
return ".";
}
#if !STATIC
protected override void SaveModule (PortableExecutableKinds pekind, ImageFileMachine machine)
{
try {
var module_only = typeof (AssemblyBuilder).GetProperty ("IsModuleOnly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var set_module_only = module_only.GetSetMethod (true);
set_module_only.Invoke (Builder, new object[] { true });
} catch {
base.SaveModule (pekind, machine);
}
Builder.Save (file_name, pekind, machine);
}
#endif
}
//
// Extension to System.Reflection.Emit.AssemblyBuilder to have fully compatible
// compiler
//
class AssemblyBuilderMonoSpecific : AssemblyBuilderExtension
{
static MethodInfo adder_method;
static MethodInfo add_permission;
static MethodInfo add_type_forwarder;
static MethodInfo win32_icon_define;
static FieldInfo assembly_version;
static FieldInfo assembly_algorithm;
static FieldInfo assembly_culture;
static FieldInfo assembly_flags;
AssemblyBuilder builder;
public AssemblyBuilderMonoSpecific (AssemblyBuilder ab, CompilerContext ctx)
: base (ctx)
{
this.builder = ab;
}
public override Module AddModule (string module)
{
try {
if (adder_method == null)
adder_method = typeof (AssemblyBuilder).GetMethod ("AddModule", BindingFlags.Instance | BindingFlags.NonPublic);
return (Module) adder_method.Invoke (builder, new object[] { module });
} catch {
return base.AddModule (module);
}
}
public override void AddPermissionRequests (PermissionSet[] permissions)
{
try {
if (add_permission == null)
add_permission = typeof (AssemblyBuilder).GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
add_permission.Invoke (builder, permissions);
} catch {
base.AddPermissionRequests (permissions);
}
}
public override void AddTypeForwarder (TypeSpec type, Location loc)
{
try {
if (add_type_forwarder == null) {
add_type_forwarder = typeof (AssemblyBuilder).GetMethod ("AddTypeForwarder", BindingFlags.NonPublic | BindingFlags.Instance);
}
add_type_forwarder.Invoke (builder, new object[] { type.GetMetaInfo () });
} catch {
base.AddTypeForwarder (type, loc);
}
}
public override void DefineWin32IconResource (string fileName)
{
try {
if (win32_icon_define == null)
win32_icon_define = typeof (AssemblyBuilder).GetMethod ("DefineIconResource", BindingFlags.Instance | BindingFlags.NonPublic);
win32_icon_define.Invoke (builder, new object[] { fileName });
} catch {
base.DefineWin32IconResource (fileName);
}
}
public override void SetAlgorithmId (uint value, Location loc)
{
try {
if (assembly_algorithm == null)
assembly_algorithm = typeof (AssemblyBuilder).GetField ("algid", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
assembly_algorithm.SetValue (builder, value);
} catch {
base.SetAlgorithmId (value, loc);
}
}
public override void SetCulture (string culture, Location loc)
{
try {
if (assembly_culture == null)
assembly_culture = typeof (AssemblyBuilder).GetField ("culture", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
assembly_culture.SetValue (builder, culture);
} catch {
base.SetCulture (culture, loc);
}
}
public override void SetFlags (uint flags, Location loc)
{
try {
if (assembly_flags == null)
assembly_flags = typeof (AssemblyBuilder).GetField ("flags", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
assembly_flags.SetValue (builder, flags);
} catch {
base.SetFlags (flags, loc);
}
}
public override void SetVersion (Version version, Location loc)
{
try {
if (assembly_version == null)
assembly_version = typeof (AssemblyBuilder).GetField ("version", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField);
assembly_version.SetValue (builder, version.ToString (4));
} catch {
base.SetVersion (version, loc);
}
}
}
//
// Reflection based references loader
//
class DynamicLoader : AssemblyReferencesLoader<Assembly>
{
readonly ReflectionImporter importer;
public DynamicLoader (ReflectionImporter importer, CompilerContext compiler)
: base (compiler)
{
paths.Add (GetSystemDir ());
this.importer = importer;
}
public ReflectionImporter Importer {
get {
return importer;
}
}
protected override string[] GetDefaultReferences ()
{
//
// For now the "default config" is harcoded into the compiler
// we can move this outside later
//
var default_references = new List<string> (8);
default_references.Add ("System");
default_references.Add ("System.Xml");
#if NET_2_1
default_references.Add ("System.Net");
default_references.Add ("System.Windows");
default_references.Add ("System.Windows.Browser");
#endif
if (compiler.Settings.Version > LanguageVersion.ISO_2)
default_references.Add ("System.Core");
if (compiler.Settings.Version > LanguageVersion.V_3)
default_references.Add ("Microsoft.CSharp");
return default_references.ToArray ();
}
//
// Returns the directory where the system assemblies are installed
//
static string GetSystemDir ()
{
return Path.GetDirectoryName (typeof (object).Assembly.Location);
}
public override bool HasObjectType (Assembly assembly)
{
return assembly.GetType (compiler.BuiltinTypes.Object.FullName) != null;
}
public override Assembly LoadAssemblyFile (string assembly, bool isImplicitReference)
{
Assembly a = null;
try {
try {
char[] path_chars = { '/', '\\' };
if (assembly.IndexOfAny (path_chars) != -1) {
a = Assembly.LoadFrom (assembly);
} else {
string ass = assembly;
if (ass.EndsWith (".dll") || ass.EndsWith (".exe"))
ass = assembly.Substring (0, assembly.Length - 4);
a = Assembly.Load (ass);
}
} catch (FileNotFoundException) {
bool err = !isImplicitReference;
foreach (string dir in paths) {
string full_path = Path.Combine (dir, assembly);
if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
full_path += ".dll";
try {
a = Assembly.LoadFrom (full_path);
err = false;
break;
} catch (FileNotFoundException) {
}
}
if (err) {
Error_FileNotFound (assembly);
return a;
}
}
} catch (BadImageFormatException) {
Error_FileCorrupted (assembly);
}
return a;
}
Module LoadModuleFile (AssemblyDefinitionDynamic assembly, string module)
{
string total_log = "";
try {
try {
return assembly.IncludeModule (module);
} catch (FileNotFoundException) {
bool err = true;
foreach (string dir in paths) {
string full_path = Path.Combine (dir, module);
if (!module.EndsWith (".netmodule"))
full_path += ".netmodule";
try {
return assembly.IncludeModule (full_path);
} catch (FileNotFoundException ff) {
total_log += ff.FusionLog;
}
}
if (err) {
Error_FileNotFound (module);
return null;
}
}
} catch (BadImageFormatException) {
Error_FileCorrupted (module);
}
return null;
}
public void LoadModules (AssemblyDefinitionDynamic assembly, RootNamespace targetNamespace)
{
foreach (var moduleName in compiler.Settings.Modules) {
var m = LoadModuleFile (assembly, moduleName);
if (m == null)
continue;
var md = importer.ImportModule (m, targetNamespace);
assembly.AddModule (md);
}
}
public override void LoadReferences (ModuleContainer module)
{
Assembly corlib;
List<Tuple<RootNamespace, Assembly>> loaded;
base.LoadReferencesCore (module, out corlib, out loaded);
if (corlib == null)
return;
importer.ImportAssembly (corlib, module.GlobalRootNamespace);
foreach (var entry in loaded) {
importer.ImportAssembly (entry.Item2, entry.Item1);
}
}
}
}
|