PageRenderTime 91ms CodeModel.GetById 15ms app.highlight 67ms RepoModel.GetById 2ms app.codeStats 0ms

/Mono.Cecil/ModuleDefinition.cs

http://github.com/jbevain/cecil
C# | 1337 lines | 1049 code | 279 blank | 9 comment | 150 complexity | fd1c92cfcb2ac725182a20bcb51a1088 MD5 | raw file
   1//
   2// Author:
   3//   Jb Evain (jbevain@gmail.com)
   4//
   5// Copyright (c) 2008 - 2015 Jb Evain
   6// Copyright (c) 2008 - 2011 Novell, Inc.
   7//
   8// Licensed under the MIT/X11 license.
   9//
  10
  11using System;
  12using System.Collections.Generic;
  13using System.IO;
  14using System.Threading;
  15using SR = System.Reflection;
  16
  17using Mono.Cecil.Cil;
  18using Mono.Cecil.Metadata;
  19using Mono.Cecil.PE;
  20using Mono.Collections.Generic;
  21
  22namespace Mono.Cecil {
  23
  24	public enum ReadingMode {
  25		Immediate = 1,
  26		Deferred = 2,
  27	}
  28
  29	public sealed class ReaderParameters {
  30
  31		ReadingMode reading_mode;
  32		internal IAssemblyResolver assembly_resolver;
  33		internal IMetadataResolver metadata_resolver;
  34		internal IMetadataImporterProvider metadata_importer_provider;
  35		internal IReflectionImporterProvider reflection_importer_provider;
  36		Stream symbol_stream;
  37		ISymbolReaderProvider symbol_reader_provider;
  38		bool read_symbols;
  39		bool throw_symbols_mismatch;
  40		bool projections;
  41		bool in_memory;
  42		bool read_write;
  43
  44		public ReadingMode ReadingMode {
  45			get { return reading_mode; }
  46			set { reading_mode = value; }
  47		}
  48
  49		public bool InMemory {
  50			get { return in_memory; }
  51			set { in_memory = value; }
  52		}
  53
  54		public IAssemblyResolver AssemblyResolver {
  55			get { return assembly_resolver; }
  56			set { assembly_resolver = value; }
  57		}
  58
  59		public IMetadataResolver MetadataResolver {
  60			get { return metadata_resolver; }
  61			set { metadata_resolver = value; }
  62		}
  63
  64		public IMetadataImporterProvider MetadataImporterProvider {
  65			get { return metadata_importer_provider; }
  66			set { metadata_importer_provider = value; }
  67		}
  68
  69		public IReflectionImporterProvider ReflectionImporterProvider {
  70			get { return reflection_importer_provider; }
  71			set { reflection_importer_provider = value; }
  72		}
  73
  74		public Stream SymbolStream {
  75			get { return symbol_stream; }
  76			set { symbol_stream = value; }
  77		}
  78
  79		public ISymbolReaderProvider SymbolReaderProvider {
  80			get { return symbol_reader_provider; }
  81			set { symbol_reader_provider = value; }
  82		}
  83
  84		public bool ReadSymbols {
  85			get { return read_symbols; }
  86			set { read_symbols = value; }
  87		}
  88
  89		public bool ThrowIfSymbolsAreNotMatching {
  90			get { return throw_symbols_mismatch; }
  91			set { throw_symbols_mismatch = value; }
  92		}
  93
  94		public bool ReadWrite {
  95			get { return read_write; }
  96			set { read_write = value; }
  97		}
  98
  99		public bool ApplyWindowsRuntimeProjections {
 100			get { return projections; }
 101			set { projections = value; }
 102		}
 103
 104		public ReaderParameters ()
 105			: this (ReadingMode.Deferred)
 106		{
 107		}
 108
 109		public ReaderParameters (ReadingMode readingMode)
 110		{
 111			this.reading_mode = readingMode;
 112			this.throw_symbols_mismatch = true;
 113		}
 114	}
 115
 116	public sealed class ModuleParameters {
 117
 118		ModuleKind kind;
 119		TargetRuntime runtime;
 120		uint? timestamp;
 121		TargetArchitecture architecture;
 122		IAssemblyResolver assembly_resolver;
 123		IMetadataResolver metadata_resolver;
 124		IMetadataImporterProvider metadata_importer_provider;
 125		IReflectionImporterProvider reflection_importer_provider;
 126
 127		public ModuleKind Kind {
 128			get { return kind; }
 129			set { kind = value; }
 130		}
 131
 132		public TargetRuntime Runtime {
 133			get { return runtime; }
 134			set { runtime = value; }
 135		}
 136
 137		public uint? Timestamp {
 138			get { return timestamp; }
 139			set { timestamp = value; }
 140		}
 141
 142		public TargetArchitecture Architecture {
 143			get { return architecture; }
 144			set { architecture = value; }
 145		}
 146
 147		public IAssemblyResolver AssemblyResolver {
 148			get { return assembly_resolver; }
 149			set { assembly_resolver = value; }
 150		}
 151
 152		public IMetadataResolver MetadataResolver {
 153			get { return metadata_resolver; }
 154			set { metadata_resolver = value; }
 155		}
 156
 157		public IMetadataImporterProvider MetadataImporterProvider {
 158			get { return metadata_importer_provider; }
 159			set { metadata_importer_provider = value; }
 160		}
 161
 162		public IReflectionImporterProvider ReflectionImporterProvider {
 163			get { return reflection_importer_provider; }
 164			set { reflection_importer_provider = value; }
 165		}
 166
 167		public ModuleParameters ()
 168		{
 169			this.kind = ModuleKind.Dll;
 170			this.Runtime = GetCurrentRuntime ();
 171			this.architecture = TargetArchitecture.I386;
 172		}
 173
 174		static TargetRuntime GetCurrentRuntime ()
 175		{
 176			return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime ();
 177		}
 178	}
 179
 180	public sealed class WriterParameters {
 181
 182		uint? timestamp;
 183		Stream symbol_stream;
 184		ISymbolWriterProvider symbol_writer_provider;
 185		bool write_symbols;
 186		byte [] key_blob;
 187		string key_container;
 188		SR.StrongNameKeyPair key_pair;
 189
 190		public uint? Timestamp {
 191			get { return timestamp; }
 192			set { timestamp = value; }
 193		}
 194
 195		public Stream SymbolStream {
 196			get { return symbol_stream; }
 197			set { symbol_stream = value; }
 198		}
 199
 200		public ISymbolWriterProvider SymbolWriterProvider {
 201			get { return symbol_writer_provider; }
 202			set { symbol_writer_provider = value; }
 203		}
 204
 205		public bool WriteSymbols {
 206			get { return write_symbols; }
 207			set { write_symbols = value; }
 208		}
 209
 210		public bool HasStrongNameKey {
 211			get { return key_pair != null || key_blob != null || key_container != null; }
 212		}
 213
 214		public byte [] StrongNameKeyBlob {
 215			get { return key_blob; }
 216			set { key_blob = value; }
 217		}
 218
 219		public string StrongNameKeyContainer {
 220			get { return key_container; }
 221			set { key_container = value; }
 222		}
 223
 224		public SR.StrongNameKeyPair StrongNameKeyPair {
 225			get { return key_pair; }
 226			set { key_pair = value; }
 227		}
 228
 229		public bool DeterministicMvid { get; set; }
 230	}
 231
 232	public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider, ICustomDebugInformationProvider, IDisposable {
 233
 234		internal Image Image;
 235		internal MetadataSystem MetadataSystem;
 236		internal ReadingMode ReadingMode;
 237		internal ISymbolReaderProvider SymbolReaderProvider;
 238
 239		internal ISymbolReader symbol_reader;
 240		internal Disposable<IAssemblyResolver> assembly_resolver;
 241		internal IMetadataResolver metadata_resolver;
 242		internal TypeSystem type_system;
 243		internal readonly MetadataReader reader;
 244		readonly string file_name;
 245
 246		internal string runtime_version;
 247		internal ModuleKind kind;
 248		WindowsRuntimeProjections projections;
 249		MetadataKind metadata_kind;
 250		TargetRuntime runtime;
 251		TargetArchitecture architecture;
 252		ModuleAttributes attributes;
 253		ModuleCharacteristics characteristics;
 254		Guid mvid;
 255
 256		internal ushort linker_version = 8;
 257		internal ushort subsystem_major = 4;
 258		internal ushort subsystem_minor = 0;
 259		internal uint timestamp;
 260
 261		internal AssemblyDefinition assembly;
 262		MethodDefinition entry_point;
 263
 264		internal IReflectionImporter reflection_importer;
 265		internal IMetadataImporter metadata_importer;
 266
 267		Collection<CustomAttribute> custom_attributes;
 268		Collection<AssemblyNameReference> references;
 269		Collection<ModuleReference> modules;
 270		Collection<Resource> resources;
 271		Collection<ExportedType> exported_types;
 272		TypeDefinitionCollection types;
 273
 274		internal Collection<CustomDebugInformation> custom_infos;
 275
 276		internal MetadataBuilder metadata_builder;
 277
 278		public bool IsMain {
 279			get { return kind != ModuleKind.NetModule; }
 280		}
 281
 282		public ModuleKind Kind {
 283			get { return kind; }
 284			set { kind = value; }
 285		}
 286
 287		public MetadataKind MetadataKind {
 288			get { return metadata_kind; }
 289			set { metadata_kind = value; }
 290		}
 291
 292		internal WindowsRuntimeProjections Projections {
 293			get {
 294				if (projections == null)
 295					Interlocked.CompareExchange (ref projections, new WindowsRuntimeProjections (this), null);
 296
 297				return projections;
 298			}
 299		}
 300
 301		public TargetRuntime Runtime {
 302			get { return runtime; }
 303			set {
 304				runtime = value;
 305				runtime_version = runtime.RuntimeVersionString ();
 306			}
 307		}
 308
 309		public string RuntimeVersion {
 310			get { return runtime_version; }
 311			set {
 312				runtime_version = value;
 313				runtime = runtime_version.ParseRuntime ();
 314			}
 315		}
 316
 317		public TargetArchitecture Architecture {
 318			get { return architecture; }
 319			set { architecture = value; }
 320		}
 321
 322		public ModuleAttributes Attributes {
 323			get { return attributes; }
 324			set { attributes = value; }
 325		}
 326
 327		public ModuleCharacteristics Characteristics {
 328			get { return characteristics; }
 329			set { characteristics = value; }
 330		}
 331
 332		[Obsolete ("Use FileName")]
 333		public string FullyQualifiedName {
 334			get { return file_name; }
 335		}
 336
 337		public string FileName {
 338			get { return file_name; }
 339		}
 340
 341		public Guid Mvid {
 342			get { return mvid; }
 343			set { mvid = value; }
 344		}
 345
 346		internal bool HasImage {
 347			get { return Image != null; }
 348		}
 349
 350		public bool HasSymbols {
 351			get { return symbol_reader != null; }
 352		}
 353
 354		public ISymbolReader SymbolReader {
 355			get { return symbol_reader; }
 356		}
 357
 358		public override MetadataScopeType MetadataScopeType {
 359			get { return MetadataScopeType.ModuleDefinition; }
 360		}
 361
 362		public AssemblyDefinition Assembly {
 363			get { return assembly; }
 364		}
 365
 366		internal IReflectionImporter ReflectionImporter {
 367			get {
 368				if (reflection_importer == null)
 369					Interlocked.CompareExchange (ref reflection_importer, new DefaultReflectionImporter (this), null);
 370
 371				return reflection_importer;
 372			}
 373		}
 374
 375		internal IMetadataImporter MetadataImporter {
 376			get {
 377				if (metadata_importer == null)
 378					Interlocked.CompareExchange (ref metadata_importer, new DefaultMetadataImporter (this), null);
 379
 380				return metadata_importer;
 381			}
 382		}
 383
 384		public IAssemblyResolver AssemblyResolver {
 385			get {
 386				if (assembly_resolver.value == null) {
 387					lock (module_lock) {
 388						assembly_resolver = Disposable.Owned (new DefaultAssemblyResolver () as IAssemblyResolver);
 389					}
 390				}
 391
 392				return assembly_resolver.value;
 393			}
 394		}
 395
 396		public IMetadataResolver MetadataResolver {
 397			get {
 398				if (metadata_resolver == null)
 399					Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null);
 400
 401				return metadata_resolver;
 402			}
 403		}
 404
 405		public TypeSystem TypeSystem {
 406			get {
 407				if (type_system == null)
 408					Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null);
 409
 410				return type_system;
 411			}
 412		}
 413
 414		public bool HasAssemblyReferences {
 415			get {
 416				if (references != null)
 417					return references.Count > 0;
 418
 419				return HasImage && Image.HasTable (Table.AssemblyRef);
 420			}
 421		}
 422
 423		public Collection<AssemblyNameReference> AssemblyReferences {
 424			get {
 425				if (references != null)
 426					return references;
 427
 428				if (HasImage)
 429					return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ());
 430
 431				Interlocked.CompareExchange (ref references, new Collection<AssemblyNameReference> (), null);
 432				return references;
 433			}
 434		}
 435
 436		public bool HasModuleReferences {
 437			get {
 438				if (modules != null)
 439					return modules.Count > 0;
 440
 441				return HasImage && Image.HasTable (Table.ModuleRef);
 442			}
 443		}
 444
 445		public Collection<ModuleReference> ModuleReferences {
 446			get {
 447				if (modules != null)
 448					return modules;
 449
 450				if (HasImage)
 451					return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ());
 452
 453				Interlocked.CompareExchange (ref modules, new Collection<ModuleReference> (), null);
 454				return modules;
 455			}
 456		}
 457
 458		public bool HasResources {
 459			get {
 460				if (resources != null)
 461					return resources.Count > 0;
 462
 463				if (HasImage)
 464					return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ());
 465
 466				return false;
 467			}
 468		}
 469
 470		public Collection<Resource> Resources {
 471			get {
 472				if (resources != null)
 473					return resources;
 474
 475				if (HasImage)
 476					return Read (ref resources, this, (_, reader) => reader.ReadResources ());
 477
 478				Interlocked.CompareExchange (ref resources, new Collection<Resource> (), null);
 479				return resources;
 480			}
 481		}
 482
 483		public bool HasCustomAttributes {
 484			get {
 485				if (custom_attributes != null)
 486					return custom_attributes.Count > 0;
 487
 488				return this.GetHasCustomAttributes (this);
 489			}
 490		}
 491
 492		public Collection<CustomAttribute> CustomAttributes {
 493			get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); }
 494		}
 495
 496		public bool HasTypes {
 497			get {
 498				if (types != null)
 499					return types.Count > 0;
 500
 501				return HasImage && Image.HasTable (Table.TypeDef);
 502			}
 503		}
 504
 505		public Collection<TypeDefinition> Types {
 506			get {
 507				if (types != null)
 508					return types;
 509
 510				if (HasImage)
 511					return Read (ref types, this, (_, reader) => reader.ReadTypes ());
 512
 513				Interlocked.CompareExchange (ref types, new TypeDefinitionCollection (this), null);
 514				return types;
 515			}
 516		}
 517
 518		public bool HasExportedTypes {
 519			get {
 520				if (exported_types != null)
 521					return exported_types.Count > 0;
 522
 523				return HasImage && Image.HasTable (Table.ExportedType);
 524			}
 525		}
 526
 527		public Collection<ExportedType> ExportedTypes {
 528			get {
 529				if (exported_types != null)
 530					return exported_types;
 531
 532				if (HasImage)
 533					return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ());
 534
 535				Interlocked.CompareExchange (ref exported_types, new Collection<ExportedType> (), null);
 536				return exported_types;
 537			}
 538		}
 539
 540		public MethodDefinition EntryPoint {
 541			get {
 542				if (entry_point != null)
 543					return entry_point;
 544
 545				if (HasImage)
 546					return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ());
 547
 548				return entry_point = null;
 549			}
 550			set { entry_point = value; }
 551		}
 552
 553		public bool HasCustomDebugInformations {
 554			get {
 555				return custom_infos != null && custom_infos.Count > 0;
 556			}
 557		}
 558
 559		public Collection<CustomDebugInformation> CustomDebugInformations {
 560			get {
 561				if (custom_infos == null)
 562					Interlocked.CompareExchange (ref custom_infos, new Collection<CustomDebugInformation> (), null);
 563
 564				return custom_infos;
 565			}
 566		}
 567
 568		internal ModuleDefinition ()
 569		{
 570			this.MetadataSystem = new MetadataSystem ();
 571			this.token = new MetadataToken (TokenType.Module, 1);
 572		}
 573
 574		internal ModuleDefinition (Image image)
 575			: this ()
 576		{
 577			this.Image = image;
 578			this.kind = image.Kind;
 579			this.RuntimeVersion = image.RuntimeVersion;
 580			this.architecture = image.Architecture;
 581			this.attributes = image.Attributes;
 582			this.characteristics = image.Characteristics;
 583			this.linker_version = image.LinkerVersion;
 584			this.subsystem_major = image.SubSystemMajor;
 585			this.subsystem_minor = image.SubSystemMinor;
 586			this.file_name = image.FileName;
 587			this.timestamp = image.Timestamp;
 588
 589			this.reader = new MetadataReader (this);
 590		}
 591
 592		public void Dispose ()
 593		{
 594			if (Image != null)
 595				Image.Dispose ();
 596
 597			if (symbol_reader != null)
 598				symbol_reader.Dispose ();
 599
 600			if (assembly_resolver.value != null)
 601				assembly_resolver.Dispose ();
 602		}
 603
 604		public bool HasTypeReference (string fullName)
 605		{
 606			return HasTypeReference (string.Empty, fullName);
 607		}
 608
 609		public bool HasTypeReference (string scope, string fullName)
 610		{
 611			Mixin.CheckFullName (fullName);
 612
 613			if (!HasImage)
 614				return false;
 615
 616			return GetTypeReference (scope, fullName) != null;
 617		}
 618
 619		public bool TryGetTypeReference (string fullName, out TypeReference type)
 620		{
 621			return TryGetTypeReference (string.Empty, fullName, out type);
 622		}
 623
 624		public bool TryGetTypeReference (string scope, string fullName, out TypeReference type)
 625		{
 626			Mixin.CheckFullName (fullName);
 627
 628			if (!HasImage) {
 629				type = null;
 630				return false;
 631			}
 632
 633			return (type = GetTypeReference (scope, fullName)) != null;
 634		}
 635
 636		TypeReference GetTypeReference (string scope, string fullname)
 637		{
 638			return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2));
 639		}
 640
 641		public IEnumerable<TypeReference> GetTypeReferences ()
 642		{
 643			if (!HasImage)
 644				return Empty<TypeReference>.Array;
 645
 646			return Read (this, (_, reader) => reader.GetTypeReferences ());
 647		}
 648
 649		public IEnumerable<MemberReference> GetMemberReferences ()
 650		{
 651			if (!HasImage)
 652				return Empty<MemberReference>.Array;
 653
 654			return Read (this, (_, reader) => reader.GetMemberReferences ());
 655		}
 656
 657		public IEnumerable<CustomAttribute> GetCustomAttributes ()
 658		{
 659			if (!HasImage)
 660				return Empty<CustomAttribute>.Array;
 661
 662			return Read (this, (_, reader) => reader.GetCustomAttributes ());
 663		}
 664
 665		public TypeReference GetType (string fullName, bool runtimeName)
 666		{
 667			return runtimeName
 668				? TypeParser.ParseType (this, fullName, typeDefinitionOnly: true)
 669				: GetType (fullName);
 670		}
 671
 672		public TypeDefinition GetType (string fullName)
 673		{
 674			Mixin.CheckFullName (fullName);
 675
 676			var position = fullName.IndexOf ('/');
 677			if (position > 0)
 678				return GetNestedType (fullName);
 679
 680			return ((TypeDefinitionCollection) this.Types).GetType (fullName);
 681		}
 682
 683		public TypeDefinition GetType (string @namespace, string name)
 684		{
 685			Mixin.CheckName (name);
 686
 687			return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
 688		}
 689
 690		public IEnumerable<TypeDefinition> GetTypes ()
 691		{
 692			return GetTypes (Types);
 693		}
 694
 695		static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
 696		{
 697			for (int i = 0; i < types.Count; i++) {
 698				var type = types [i];
 699
 700				yield return type;
 701
 702				if (!type.HasNestedTypes)
 703					continue;
 704
 705				foreach (var nested in GetTypes (type.NestedTypes))
 706					yield return nested;
 707			}
 708		}
 709
 710		TypeDefinition GetNestedType (string fullname)
 711		{
 712			var names = fullname.Split ('/');
 713			var type = GetType (names [0]);
 714
 715			if (type == null)
 716				return null;
 717
 718			for (int i = 1; i < names.Length; i++) {
 719				var nested_type = type.GetNestedType (names [i]);
 720				if (nested_type == null)
 721					return null;
 722
 723				type = nested_type;
 724			}
 725
 726			return type;
 727		}
 728
 729		internal FieldDefinition Resolve (FieldReference field)
 730		{
 731			return MetadataResolver.Resolve (field);
 732		}
 733
 734		internal MethodDefinition Resolve (MethodReference method)
 735		{
 736			return MetadataResolver.Resolve (method);
 737		}
 738
 739		internal TypeDefinition Resolve (TypeReference type)
 740		{
 741			return MetadataResolver.Resolve (type);
 742		}
 743
 744		static void CheckContext (IGenericParameterProvider context, ModuleDefinition module)
 745		{
 746			if (context == null)
 747				return;
 748
 749			if (context.Module != module)
 750				throw new ArgumentException ();
 751		}
 752
 753		[Obsolete ("Use ImportReference", error: false)]
 754		public TypeReference Import (Type type)
 755		{
 756			return ImportReference (type, null);
 757		}
 758
 759		public TypeReference ImportReference (Type type)
 760		{
 761			return ImportReference (type, null);
 762		}
 763
 764		[Obsolete ("Use ImportReference", error: false)]
 765		public TypeReference Import (Type type, IGenericParameterProvider context)
 766		{
 767			return ImportReference (type, context);
 768		}
 769
 770		public TypeReference ImportReference (Type type, IGenericParameterProvider context)
 771		{
 772			Mixin.CheckType (type);
 773			CheckContext (context, this);
 774
 775			return ReflectionImporter.ImportReference (type, context);
 776		}
 777
 778		[Obsolete ("Use ImportReference", error: false)]
 779		public FieldReference Import (SR.FieldInfo field)
 780		{
 781			return ImportReference (field, null);
 782		}
 783
 784		[Obsolete ("Use ImportReference", error: false)]
 785		public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context)
 786		{
 787			return ImportReference (field, context);
 788		}
 789
 790		public FieldReference ImportReference (SR.FieldInfo field)
 791		{
 792			return ImportReference (field, null);
 793		}
 794
 795		public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
 796		{
 797			Mixin.CheckField (field);
 798			CheckContext (context, this);
 799
 800			return ReflectionImporter.ImportReference (field, context);
 801		}
 802
 803		[Obsolete ("Use ImportReference", error: false)]
 804		public MethodReference Import (SR.MethodBase method)
 805		{
 806			return ImportReference (method, null);
 807		}
 808
 809		[Obsolete ("Use ImportReference", error: false)]
 810		public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context)
 811		{
 812			return ImportReference (method, context);
 813		}
 814
 815		public MethodReference ImportReference (SR.MethodBase method)
 816		{
 817			return ImportReference (method, null);
 818		}
 819
 820		public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
 821		{
 822			Mixin.CheckMethod (method);
 823			CheckContext (context, this);
 824
 825			return ReflectionImporter.ImportReference (method, context);
 826		}
 827
 828		[Obsolete ("Use ImportReference", error: false)]
 829		public TypeReference Import (TypeReference type)
 830		{
 831			return ImportReference (type, null);
 832		}
 833
 834		[Obsolete ("Use ImportReference", error: false)]
 835		public TypeReference Import (TypeReference type, IGenericParameterProvider context)
 836		{
 837			return ImportReference (type, context);
 838		}
 839
 840		public TypeReference ImportReference (TypeReference type)
 841		{
 842			return ImportReference (type, null);
 843		}
 844
 845		public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
 846		{
 847			Mixin.CheckType (type);
 848
 849			if (type.Module == this)
 850				return type;
 851
 852			CheckContext (context, this);
 853
 854			return MetadataImporter.ImportReference (type, context);
 855		}
 856
 857		[Obsolete ("Use ImportReference", error: false)]
 858		public FieldReference Import (FieldReference field)
 859		{
 860			return ImportReference (field, null);
 861		}
 862
 863		[Obsolete ("Use ImportReference", error: false)]
 864		public FieldReference Import (FieldReference field, IGenericParameterProvider context)
 865		{
 866			return ImportReference (field, context);
 867		}
 868
 869		public FieldReference ImportReference (FieldReference field)
 870		{
 871			return ImportReference (field, null);
 872		}
 873
 874		public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
 875		{
 876			Mixin.CheckField (field);
 877
 878			if (field.Module == this)
 879				return field;
 880
 881			CheckContext (context, this);
 882
 883			return MetadataImporter.ImportReference (field, context);
 884		}
 885
 886		[Obsolete ("Use ImportReference", error: false)]
 887		public MethodReference Import (MethodReference method)
 888		{
 889			return ImportReference (method, null);
 890		}
 891
 892		[Obsolete ("Use ImportReference", error: false)]
 893		public MethodReference Import (MethodReference method, IGenericParameterProvider context)
 894		{
 895			return ImportReference (method, context);
 896		}
 897
 898		public MethodReference ImportReference (MethodReference method)
 899		{
 900			return ImportReference (method, null);
 901		}
 902
 903		public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
 904		{
 905			Mixin.CheckMethod (method);
 906
 907			if (method.Module == this)
 908				return method;
 909
 910			CheckContext (context, this);
 911
 912			return MetadataImporter.ImportReference (method, context);
 913		}
 914
 915		public IMetadataTokenProvider LookupToken (int token)
 916		{
 917			return LookupToken (new MetadataToken ((uint) token));
 918		}
 919
 920		public IMetadataTokenProvider LookupToken (MetadataToken token)
 921		{
 922			return Read (token, (t, reader) => reader.LookupToken (t));
 923		}
 924
 925		readonly object module_lock = new object();
 926
 927		internal object SyncRoot {
 928			get { return module_lock; }
 929		}
 930
 931		internal void Read<TItem> (TItem item, Action<TItem, MetadataReader> read)
 932		{
 933			lock (module_lock) {
 934				var position = reader.position;
 935				var context = reader.context;
 936
 937				read (item, reader);
 938
 939				reader.position = position;
 940				reader.context = context;
 941			}
 942		}
 943
 944		internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read)
 945		{
 946			lock (module_lock) {
 947				var position = reader.position;
 948				var context = reader.context;
 949
 950				var ret = read (item, reader);
 951
 952				reader.position = position;
 953				reader.context = context;
 954
 955				return ret;
 956			}
 957		}
 958
 959		internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class
 960		{
 961			lock (module_lock) {
 962				if (variable != null)
 963					return variable;
 964
 965				var position = reader.position;
 966				var context = reader.context;
 967
 968				var ret = read (item, reader);
 969
 970				reader.position = position;
 971				reader.context = context;
 972
 973				return variable = ret;
 974			}
 975		}
 976
 977		public bool HasDebugHeader {
 978			get { return Image != null && Image.DebugHeader != null; }
 979		}
 980
 981		public ImageDebugHeader GetDebugHeader ()
 982		{
 983			return Image.DebugHeader ?? new ImageDebugHeader ();
 984		}
 985
 986		public static ModuleDefinition CreateModule (string name, ModuleKind kind)
 987		{
 988			return CreateModule (name, new ModuleParameters { Kind = kind });
 989		}
 990
 991		public static ModuleDefinition CreateModule (string name, ModuleParameters parameters)
 992		{
 993			Mixin.CheckName (name);
 994			Mixin.CheckParameters (parameters);
 995
 996			var module = new ModuleDefinition {
 997				Name = name,
 998				kind = parameters.Kind,
 999				timestamp = parameters.Timestamp ?? Mixin.GetTimestamp (),
1000				Runtime = parameters.Runtime,
1001				architecture = parameters.Architecture,
1002				mvid = Guid.NewGuid (),
1003				Attributes = ModuleAttributes.ILOnly,
1004				Characteristics = (ModuleCharacteristics) 0x8540,
1005			};
1006
1007			if (parameters.AssemblyResolver != null)
1008				module.assembly_resolver = Disposable.NotOwned (parameters.AssemblyResolver);
1009
1010			if (parameters.MetadataResolver != null)
1011				module.metadata_resolver = parameters.MetadataResolver;
1012
1013			if (parameters.MetadataImporterProvider != null)
1014				module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module);
1015
1016			if (parameters.ReflectionImporterProvider != null)
1017				module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module);
1018
1019			if (parameters.Kind != ModuleKind.NetModule) {
1020				var assembly = new AssemblyDefinition ();
1021				module.assembly = assembly;
1022				module.assembly.Name = CreateAssemblyName (name);
1023				assembly.main_module = module;
1024			}
1025
1026			module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic));
1027
1028			return module;
1029		}
1030
1031		static AssemblyNameDefinition CreateAssemblyName (string name)
1032		{
1033			if (name.EndsWith (".dll") || name.EndsWith (".exe"))
1034				name = name.Substring (0, name.Length - 4);
1035
1036			return new AssemblyNameDefinition (name, Mixin.ZeroVersion);
1037		}
1038
1039		public void ReadSymbols ()
1040		{
1041			if (string.IsNullOrEmpty (file_name))
1042				throw new InvalidOperationException ();
1043
1044			var provider = new DefaultSymbolReaderProvider (throwIfNoSymbol: true);
1045			ReadSymbols (provider.GetSymbolReader (this, file_name), throwIfSymbolsAreNotMaching: true);
1046		}
1047
1048		public void ReadSymbols (ISymbolReader reader)
1049		{
1050			ReadSymbols(reader, throwIfSymbolsAreNotMaching: true);
1051		}
1052
1053		public void ReadSymbols (ISymbolReader reader, bool throwIfSymbolsAreNotMaching)
1054		{
1055			if (reader == null)
1056				throw new ArgumentNullException ("reader");
1057
1058			symbol_reader = reader;
1059
1060			if (!symbol_reader.ProcessDebugHeader (GetDebugHeader ())) {
1061				symbol_reader = null;
1062
1063				if (throwIfSymbolsAreNotMaching)
1064					throw new SymbolsNotMatchingException ("Symbols were found but are not matching the assembly");
1065
1066				return;
1067			}
1068
1069			if (HasImage && ReadingMode == ReadingMode.Immediate) {
1070				var immediate_reader = new ImmediateModuleReader (Image);
1071				immediate_reader.ReadSymbols (this);
1072			}
1073		}
1074
1075		public static ModuleDefinition ReadModule (string fileName)
1076		{
1077			return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred));
1078		}
1079
1080		public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
1081		{
1082			var stream = GetFileStream (fileName, FileMode.Open, parameters.ReadWrite ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read);
1083
1084			if (parameters.InMemory) {
1085				var memory = new MemoryStream (stream.CanSeek ? (int) stream.Length : 0);
1086				using (stream)
1087					stream.CopyTo (memory);
1088
1089				memory.Position = 0;
1090				stream = memory;
1091			}
1092
1093			try {
1094				return ReadModule (Disposable.Owned (stream), fileName, parameters);
1095			} catch (Exception) {
1096				stream.Dispose ();
1097				throw;
1098			}
1099		}
1100
1101		static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share)
1102		{
1103			Mixin.CheckFileName (fileName);
1104
1105			return new FileStream (fileName, mode, access, share);
1106		}
1107
1108		public static ModuleDefinition ReadModule (Stream stream)
1109		{
1110			return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred));
1111		}
1112
1113		public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters)
1114		{
1115			Mixin.CheckStream (stream);
1116			Mixin.CheckReadSeek (stream);
1117
1118			return ReadModule (Disposable.NotOwned (stream), stream.GetFileName (), parameters);
1119		}
1120
1121		static ModuleDefinition ReadModule (Disposable<Stream> stream, string fileName, ReaderParameters parameters)
1122		{
1123			Mixin.CheckParameters (parameters);
1124
1125			return ModuleReader.CreateModule (
1126				ImageReader.ReadImage (stream, fileName),
1127				parameters);
1128		}
1129
1130		public void Write (string fileName)
1131		{
1132			Write (fileName, new WriterParameters ());
1133		}
1134
1135		public void Write (string fileName, WriterParameters parameters)
1136		{
1137			Mixin.CheckParameters (parameters);
1138			var file = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
1139			ModuleWriter.WriteModule (this, Disposable.Owned (file), parameters);
1140		}
1141
1142		public void Write ()
1143		{
1144			Write (new WriterParameters ());
1145		}
1146
1147		public void Write (WriterParameters parameters)
1148		{
1149			if (!HasImage)
1150				throw new InvalidOperationException ();
1151
1152			Write (Image.Stream.value, parameters);
1153		}
1154
1155		public void Write (Stream stream)
1156		{
1157			Write (stream, new WriterParameters ());
1158		}
1159
1160		public void Write (Stream stream, WriterParameters parameters)
1161		{
1162			Mixin.CheckStream (stream);
1163			Mixin.CheckWriteSeek (stream);
1164			Mixin.CheckParameters (parameters);
1165
1166			ModuleWriter.WriteModule (this, Disposable.NotOwned (stream), parameters);
1167		}
1168	}
1169
1170	static partial class Mixin {
1171
1172		public enum Argument {
1173			name,
1174			fileName,
1175			fullName,
1176			stream,
1177			type,
1178			method,
1179			field,
1180			parameters,
1181			module,
1182			modifierType,
1183			eventType,
1184			fieldType,
1185			declaringType,
1186			returnType,
1187			propertyType,
1188			interfaceType,
1189			constraintType,
1190		}
1191
1192		public static void CheckName (object name)
1193		{
1194			if (name == null)
1195				throw new ArgumentNullException (Argument.name.ToString ());
1196		}
1197
1198		public static void CheckName (string name)
1199		{
1200			if (string.IsNullOrEmpty (name))
1201				throw new ArgumentNullOrEmptyException (Argument.name.ToString ());
1202		}
1203
1204		public static void CheckFileName (string fileName)
1205		{
1206			if (string.IsNullOrEmpty (fileName))
1207				throw new ArgumentNullOrEmptyException (Argument.fileName.ToString ());
1208		}
1209
1210		public static void CheckFullName (string fullName)
1211		{
1212			if (string.IsNullOrEmpty (fullName))
1213				throw new ArgumentNullOrEmptyException (Argument.fullName.ToString ());
1214		}
1215
1216		public static void CheckStream (object stream)
1217		{
1218			if (stream == null)
1219				throw new ArgumentNullException (Argument.stream.ToString ());
1220		}
1221
1222		public static void CheckWriteSeek (Stream stream)
1223		{
1224			if (!stream.CanWrite || !stream.CanSeek)
1225				throw new ArgumentException ("Stream must be writable and seekable.");
1226		}
1227
1228		public static void CheckReadSeek (Stream stream)
1229		{
1230			if (!stream.CanRead || !stream.CanSeek)
1231				throw new ArgumentException ("Stream must be readable and seekable.");
1232		}
1233
1234		public static void CheckType (object type)
1235		{
1236			if (type == null)
1237				throw new ArgumentNullException (Argument.type.ToString ());
1238		}
1239
1240		public static void CheckType (object type, Argument argument)
1241		{
1242			if (type == null)
1243				throw new ArgumentNullException (argument.ToString ());
1244		}
1245
1246		public static void CheckField (object field)
1247		{
1248			if (field == null)
1249				throw new ArgumentNullException (Argument.field.ToString ());
1250		}
1251
1252		public static void CheckMethod (object method)
1253		{
1254			if (method == null)
1255				throw new ArgumentNullException (Argument.method.ToString ());
1256		}
1257
1258		public static void CheckParameters (object parameters)
1259		{
1260			if (parameters == null)
1261				throw new ArgumentNullException (Argument.parameters.ToString ());
1262		}
1263
1264		public static uint GetTimestamp ()
1265		{
1266			return (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
1267		}
1268
1269		public static bool HasImage (this ModuleDefinition self)
1270		{
1271			return self != null && self.HasImage;
1272		}
1273
1274		public static string GetFileName (this Stream self)
1275		{
1276			var file_stream = self as FileStream;
1277			if (file_stream == null)
1278				return string.Empty;
1279
1280			return Path.GetFullPath (file_stream.Name);
1281		}
1282
1283		public static TargetRuntime ParseRuntime (this string self)
1284		{
1285			if (string.IsNullOrEmpty (self))
1286				return TargetRuntime.Net_4_0;
1287
1288			switch (self [1]) {
1289			case '1':
1290				return self [3] == '0'
1291					? TargetRuntime.Net_1_0
1292					: TargetRuntime.Net_1_1;
1293			case '2':
1294				return TargetRuntime.Net_2_0;
1295			case '4':
1296			default:
1297				return TargetRuntime.Net_4_0;
1298			}
1299		}
1300
1301		public static string RuntimeVersionString (this TargetRuntime runtime)
1302		{
1303			switch (runtime) {
1304			case TargetRuntime.Net_1_0:
1305				return "v1.0.3705";
1306			case TargetRuntime.Net_1_1:
1307				return "v1.1.4322";
1308			case TargetRuntime.Net_2_0:
1309				return "v2.0.50727";
1310			case TargetRuntime.Net_4_0:
1311			default:
1312				return "v4.0.30319";
1313			}
1314		}
1315
1316		public static bool IsWindowsMetadata (this ModuleDefinition module)
1317		{
1318			return module.MetadataKind != MetadataKind.Ecma335;
1319		}
1320
1321		public static byte [] ReadAll (this Stream self)
1322		{
1323			int read;
1324			var memory = new MemoryStream ((int) self.Length);
1325			var buffer = new byte [1024];
1326
1327			while ((read = self.Read (buffer, 0, buffer.Length)) != 0)
1328				memory.Write (buffer, 0, read);
1329
1330			return memory.ToArray ();
1331		}
1332
1333		public static void Read (object o)
1334		{
1335		}
1336	}
1337}