コード例 #1
0
        private AsmReference GetReferences(IAssembly currentAssembly, AsmReference referenceDictionary, uint currentRecursionLimit = uint.MaxValue)
        {
            Contract.Requires<ArgumentNullException>(currentAssembly != null);
            Contract.Requires<ArgumentNullException>(referenceDictionary != null);

            if (referenceDictionary.ContainsKey(currentAssembly))
            {
                return referenceDictionary;
            }

            if (currentRecursionLimit == 0)
            {
                return referenceDictionary;
            }

            referenceDictionary.Add(currentAssembly, currentAssembly.References);
            currentRecursionLimit--;
            foreach (var referencedAssembly in currentAssembly.References)
            {
                var assemblyReferences = GetReferences(referencedAssembly, referenceDictionary, currentRecursionLimit);
                referenceDictionary.Add(assemblyReferences);
            }

            return referenceDictionary;
        }
コード例 #2
0
 internal static WindowsServiceManager GetInstance(
     IConsoleHarness harness,
     IAssembly assembly,
     ManagedInstallerProxy installerProxy)
 {
     return new Implementation(harness, assembly, installerProxy);
 }
コード例 #3
0
ファイル: AssemblyDispatcher.cs プロジェクト: dfr0/moon
 public AssemblyDispatcher(UnitTestHarness testHarness, IUnitTestProvider provider, 
     IAssembly testAssembly) : base(testHarness, provider)
 {
     _assembly = testAssembly;
     _testClasses = new TestWorkItemDispatcher();
     _classInstances = new TestClassInstanceCollection();
 }
コード例 #4
0
 public ConstructorCallWeave(IAssembly parentAssembly, MethodDefinition parentMethod, Instruction newInstruction, MethodDefinition constructor)
 {
     _parentAssembly = parentAssembly;
       _parentMethod = parentMethod;
       _constructor = constructor;
       _newInstruction = newInstruction;
 }
コード例 #5
0
ファイル: WindowsService.cs プロジェクト: LionFree/Cush
        private WindowsService(bool interactive, IServiceWrapper wrapper, ILogger logger,
            ICommandLineParser parser, IConsoleHarness console, IAssembly assembly, 
            ServiceAttributeReader reader, WindowsServiceManager manager, HostFactory hostFactory)
        {
            Logger = logger;
            _metadata = reader.GetMetadata(this);

            _interactive = interactive;
            _assembly = assembly;
            Console = console;
            _manager = manager;
            _manager.SetMetadata(_metadata);
            _hostFactory = hostFactory;

            CommandLineParser = parser
                .SetApplicationName(reader.GetAttribute(this).DisplayName)
                .SetDescription(reader.GetAttribute(this).Description)
                .AddOption("quiet", "q", "Enable quiet mode. Will display only errors on the console.",
                    noArgs => _metadata.Quiet = true)
                .AddOption("silent", "si", "Enable silent mode. Will display nothing (not even errors) on the console.",
                    noArgs => _metadata.Silent = true)
                .AddOption("logtoconsole", "l", "Instructs the installer/uninstaller to log the output to the console.",
                    noArgs => _manager.LogToConsole = true)
                .AddOption("debug", "d", "Pauses to attach a debugger.", noArgs => EnableDebugMode())
                .AddOption("uninstall", "u", "Uninstalls the service.", noArgs => _manager.Uninstall())
                .AddOption("install", "i", "Installs the service.", noArgs => _manager.Install())
                .AddOption("installandstart", "is", "Installs and then starts the service.",
                    noArgs => _manager.InstallAndStart())
                .AddOption("start", "s", "Starts the service.", noArgs => _manager.StartService())
                .AddOption("stop", "x", "Stops the service.", noArgs => _manager.StopService())
                .AddOption("status", "st", "Displays the status of the service.", noArgs => _manager.ShowStatus());

            Harness = wrapper.WrapService(this);
        }
コード例 #6
0
 public virtual List<ITestClass> GetTestClasses(IAssembly assembly, TestClassInstanceDictionary instances)
 {
     List<ITestClass> classes = new List<ITestClass>(assembly.GetTestClasses());
     FilterTestClasses(classes, instances);
     SortTestClasses(classes);
     return classes;
 }
コード例 #7
0
 public override void TraverseChildren(IAssembly assembly) {
   foreach (IModule module in assembly.MemberModules) {
     assemblyBeingTranslated = module.ContainingAssembly;
     this.Traverse(module);
   }
   firstPassDone = true;
 }
コード例 #8
0
		private string Process(IList<JsStatement> stmts, IAssembly mainAssembly, IMetadataImporter metadata = null, INamer namer = null) {
			var compilation = new Mock<ICompilation>();
			compilation.SetupGet(_ => _.MainAssembly).Returns(mainAssembly);
			var obj = new Linker(metadata ?? new MockMetadataImporter(), namer ?? new MockNamer(), compilation.Object);
			var processed = obj.Process(stmts);
			return string.Join("", processed.Select(s => OutputFormatter.Format(s, allowIntermediates: false)));
		}
コード例 #9
0
		public NSObjectProjectInfo (TypeSystemService.ProjectContentWrapper dom, NSObjectInfoService infoService, IAssembly lookinAssembly)
		{
			this.infoService = infoService;
			this.dom = dom;
			this.lookinAssembly = lookinAssembly;
			needsUpdating = true;
		}
コード例 #10
0
 public override void Visit(IAssembly assembly)
 {
     this.module = assembly;
     this.Visit((IModule)assembly);
     this.Visit(assembly.GetFiles(Context));
     this.Visit(assembly.GetResources(Context));
 }
コード例 #11
0
		internal static ITypeDefinition FindMyFormsClass(IAssembly asm, string myNamespace)
		{
			if (asm != null) {
				return asm.GetTypeDefinition(myNamespace, "MyForms", 0);
			}
			return null;
		}
コード例 #12
0
        public static void extract_all_resources_to_relative_directory(IFileSystem fileSystem, IAssembly assembly, string directoryPath, IList<string> relativeDirectories, string resourcesToInclude, bool overwriteExisting = false, bool logOutput = false)
        {
            var resourceString = new StringBuilder();
            foreach (var resourceName in assembly.GetManifestResourceNames())
            {
                if (!resourceName.StartsWith(resourcesToInclude))
                {
                    continue;
                }
                resourceString.Clear();
                resourceString.Append(resourceName);

                //var fileExtensionLocation = resourceName.LastIndexOf('.');
                //resourceString.Remove(fileExtensionLocation, resourceString.Length - fileExtensionLocation);
                resourceString.Replace(resourcesToInclude + ".", "");
                foreach (var directory in relativeDirectories)
                {
                    resourceString.Replace("{0}".format_with(directory), "{0}{1}".format_with(directory, fileSystem.get_path_directory_separator_char()));
                }

                // replacing \. with \
                resourceString.Replace("{0}.".format_with(fileSystem.get_path_directory_separator_char()), "{0}".format_with(fileSystem.get_path_directory_separator_char()));

                var fileLocation = resourceString.ToString();
                //var fileLocation = fileSystem.combine_paths("", resourceString.ToString().Split('.')) + resourceName.Substring(fileExtensionLocation);

                var filePath = fileSystem.combine_paths(directoryPath, fileLocation);
                if (logOutput) "chocolatey".Log().Debug("Unpacking {0} to '{1}'".format_with(fileLocation,filePath));
                extract_binary_file_from_assembly(fileSystem, assembly, resourceName, filePath, overwriteExisting);
            }
        }
コード例 #13
0
		public SimpleTypeResolveContext(IAssembly assembly)
		{
			if (assembly == null)
				throw new ArgumentNullException("assembly");
			this.compilation = assembly.Compilation;
			this.currentAssembly = assembly;
		}
コード例 #14
0
		private SimpleTypeResolveContext(ICompilation compilation, IAssembly currentAssembly, ITypeDefinition currentTypeDefinition, IMember currentMember)
		{
			this.compilation = compilation;
			this.currentAssembly = currentAssembly;
			this.currentTypeDefinition = currentTypeDefinition;
			this.currentMember = currentMember;
		}
コード例 #15
0
ファイル: AssemblyVisitor.cs プロジェクト: halllo/MTSS12
 private void AnalyzeAssemblyInHost(IMetadataHost host, IAssembly assembly, string pdbPath)
 {
     if (pdbPath != null)
         AnalyzeAssemblyInHostWithProgramDatabase(assembly, host, pdbPath);
     else
         AnalyzeTypes(assembly, null, host, Report);
 }
コード例 #16
0
 public override List<ITestClass> GetTestClasses(IAssembly assembly, TestClassInstanceDictionary instances)
 {
     return new List<ITestClass>
     {
         _test
     };
 }
コード例 #17
0
        public void LocatesAllServiceRouteMappers()
        {
            var assemblyLocator = new Mock<IAssemblyLocator>();

            //including the assembly with object ensures that the assignabliity is done correctly
            var assembliesToReflect = new IAssembly[2];
            assembliesToReflect[0] = new AssemblyWrapper(GetType().Assembly);
            assembliesToReflect[1] = new AssemblyWrapper(typeof (Object).Assembly);

            assemblyLocator.Setup(x => x.Assemblies).Returns(assembliesToReflect);

            var locator = new TypeLocator {AssemblyLocator = assemblyLocator.Object};

            List<Type> types = locator.GetAllMatchingTypes(ServicesRoutingManager.IsValidServiceRouteMapper).ToList();

            //if new ServiceRouteMapper classes are added to the assembly they willl likely need to be added here
            CollectionAssert.AreEquivalent(
                new[]
                    {
                        typeof (FakeServiceRouteMapper),
                        typeof (ReflectedServiceRouteMappers.EmbeddedServiceRouteMapper),
                        typeof (ExceptionOnCreateInstanceServiceRouteMapper),
                        typeof (ExceptionOnRegisterServiceRouteMapper)
                    }, types);
        }
コード例 #18
0
ファイル: BlobReader.cs プロジェクト: sphynx79/dotfiles
		public BlobReader(byte[] buffer, IAssembly currentResolvedAssembly)
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");
			this.buffer = buffer;
			this.currentResolvedAssembly = currentResolvedAssembly;
		}
コード例 #19
0
        public BVE5Compilation(ISolutionSnapshot solutionSnapshot, IUnresolvedAssembly mainAssembly,
                               IEnumerable<IAssemblyReference> assemblyReferences)
        {
            if(solutionSnapshot == null)
                throw new ArgumentNullException("solutionSnapshot");

            if(mainAssembly == null)
                throw new ArgumentNullException("mainAssembly");

            if(assemblyReferences == null)
                throw new ArgumentNullException("assemblyReferences");

            solution_snapshot = solutionSnapshot;
            context = new SimpleTypeResolveContext(this);
            main_assembly = mainAssembly.Resolve(context);
            var assemblies = new List<IAssembly>{main_assembly};
            var referenced_assemblies = new List<IAssembly>();
            foreach(var asm_ref in assemblyReferences){
                IAssembly asm = asm_ref.Resolve(context);
                if(asm != null && !assemblies.Contains(asm))
                    assemblies.Add(asm);

                if(asm != null && !referenced_assemblies.Contains(asm))
                    referenced_assemblies.Add(asm);
            }

            this.assemblies = assemblies.AsReadOnly();
            this.referenced_assemblies = referenced_assemblies.AsReadOnly();
            this.type_cache = new PrimitiveTypeCache(this);
        }
コード例 #20
0
 public IProject GetProject(IAssembly assembly)
 {
     if (assembly != null)
         return GetProject(assembly.UnresolvedAssembly as IProjectContent);
     else
         return null;
 }
コード例 #21
0
		public NSObjectProjectInfo GetProjectInfo (DotNetProject project, IAssembly lookinAssembly = null)
		{
			var dom = TypeSystemService.GetProjectContentWrapper (project);
			project.ReferenceAddedToProject += HandleDomReferencesUpdated;
			project.ReferenceRemovedFromProject += HandleDomReferencesUpdated;
			return GetProjectInfo (dom, lookinAssembly);
		}
コード例 #22
0
    /// <summary>
    /// Initializes a new instance of the <see cref="DerivedTypeInformation"/> class.
    /// </summary>
    /// <param name="assemblyManager">The assembly manager.</param>
    /// <param name="visibility">The visibility.</param>
    public DerivedTypeInformation(IAssemblyManager assemblyManager, IVisibilityConfiguration visibility)
    {
      this.table = new Dictionary<ITypeReference, List<ITypeDeclaration>>();

      IAssembly[] assemblies = new IAssembly[assemblyManager.Assemblies.Count];
      assemblyManager.Assemblies.CopyTo(assemblies, 0);

      FastTypeEnumerator enumerator = new FastTypeEnumerator(assemblies);
      foreach (ITypeDeclaration typeDeclaration in enumerator.Types)
      {
        if (ReflectorHelper.IsVisible(typeDeclaration, visibility))
        {
          ITypeReference baseType = typeDeclaration.BaseType;
          if (baseType != null)
          {
            if (baseType.GenericType != null)
            {
              this.AddToTable(baseType.GenericType, typeDeclaration);
            }
            else
            {
              this.AddToTable(baseType, typeDeclaration);
            }
          }

          foreach (ITypeReference interfaceType in typeDeclaration.Interfaces)
          {
            this.AddToTable(interfaceType, typeDeclaration);
          }
        }
      }
    }
コード例 #23
0
 public IEnumerable<ConstructorCallWeave> FindConstructorCallWeaves(IAssembly assembly, FactoryMap factories)
 {
     List<ConstructorCallWeave> spots = new List<ConstructorCallWeave>();
       foreach (TypeDefinition type in GetTypes(assembly, factories))
       {
     foreach (MethodDefinition method in type.Methods)
     {
       if (method.Body == null)
       {
     continue;
       }
       foreach (Instruction instruction in method.Body.Instructions)
       {
     if (instruction.OpCode == OpCodes.Newobj)
     {
       MethodDefinition constructor = instruction.Operand as MethodDefinition;
       if (constructor != null && constructor.Parameters.Count == 0)
       {
         if (factories.HasForObjectType(constructor.DeclaringType))
         {
           spots.Add(new ConstructorCallWeave(assembly, method, instruction, constructor));
         }
       }
     }
       }
     }
       }
       return spots;
 }
		public override void ApplyTo(IAssembly assembly, IAttributeStore attributeStore, IErrorReporter errorReporter) {
			foreach (var t in assembly.GetAllTypeDefinitions()) {
				if (!attributeStore.AttributesFor(t).HasAttribute<DefaultMemberReflectabilityAttribute>()) {
					ApplyTo(t, attributeStore, errorReporter);
				}
			}
		}
コード例 #25
0
		public IList<IAttribute> Resolve(IAssembly currentAssembly)
		{
			// TODO: make this a per-assembly cache
//				CacheManager cache = currentAssembly.Compilation.CacheManager;
//				IList<IAttribute> result = (IList<IAttribute>)cache.GetShared(this);
//				if (result != null)
//					return result;
			
			ITypeResolveContext context = new SimpleTypeResolveContext(currentAssembly);
			BlobReader reader = new BlobReader(blob, currentAssembly);
			if (reader.ReadByte() != '.') {
				// should not use UnresolvedSecurityDeclaration for XML secdecls
				throw new InvalidOperationException();
			}
			ResolveResult securityActionRR = securityAction.Resolve(context);
			uint attributeCount = reader.ReadCompressedUInt32();
			IAttribute[] attributes = new IAttribute[attributeCount];
			try {
				ReadSecurityBlob(reader, attributes, context, securityActionRR);
			} catch (NotSupportedException) {
				// ignore invalid blobs
				//Debug.WriteLine(ex.ToString());
			}
			for (int i = 0; i < attributes.Length; i++) {
				if (attributes[i] == null)
					attributes[i] = new CecilResolvedAttribute(context, SpecialType.UnknownType);
			}
			return attributes;
//				return (IList<IAttribute>)cache.GetOrAddShared(this, attributes);
		}
コード例 #26
0
 /// <summary>
 /// Create a new assembly manager, takes in the harness, provider 
 /// reference and actual IAssembly object.
 /// </summary>
 /// <param name="runFilter">The test run filter object.</param>
 /// <param name="testHarness">Harness object.</param>
 /// <param name="provider">The unit test metadata provider.</param>
 /// <param name="testAssembly">The test assembly metadata object.</param>
 public AssemblyManager(TestRunFilter runFilter, UnitTestHarness testHarness, IUnitTestProvider provider, IAssembly testAssembly) : base(testHarness, provider)
 {
     _filter = runFilter;
     _assembly = testAssembly;
     _testClasses = new CompositeWorkItem();
     ClassInstances = new TestClassInstanceDictionary();
 }
コード例 #27
0
		public SimpleCompilation(ISolutionSnapshot solutionSnapshot, IUnresolvedAssembly mainAssembly, IEnumerable<IAssemblyReference> assemblyReferences)
		{
			if (solutionSnapshot == null)
				throw new ArgumentNullException("solutionSnapshot");
			if (mainAssembly == null)
				throw new ArgumentNullException("mainAssembly");
			if (assemblyReferences == null)
				throw new ArgumentNullException("assemblyReferences");
			this.solutionSnapshot = solutionSnapshot;
			this.context = new SimpleTypeResolveContext(this);
			this.mainAssembly = mainAssembly.Resolve(context);
			List<IAssembly> assemblies = new List<IAssembly>();
			assemblies.Add(this.mainAssembly);
			List<IAssembly> referencedAssemblies = new List<IAssembly>();
			foreach (var asmRef in assemblyReferences) {
				IAssembly asm;
				try {
					asm = asmRef.Resolve(context);
				} catch (InvalidOperationException) {
					throw new InvalidOperationException("Tried to initialize compilation with an invalid assembly reference. (Forgot to load the assembly reference ? - see CecilLoader)");
				}
				if (asm != null && !assemblies.Contains(asm))
					assemblies.Add(asm);
				if (asm != null && !referencedAssemblies.Contains(asm))
					referencedAssemblies.Add(asm);
			}
			this.assemblies = assemblies.AsReadOnly();
			this.referencedAssemblies = referencedAssemblies.AsReadOnly();
			this.knownTypeCache = new KnownTypeCache(this);
		}
コード例 #28
0
ファイル: AssemblyResolver.cs プロジェクト: arkanoid1/dnSpy
		DnSpyFile ResolveNormal(IAssembly assembly, ModuleDef sourceModule, bool delayLoad) {
			var existingFile = fileList.FindAssembly(assembly);
			if (existingFile != null)
				return existingFile;

			var file = LookupFromSearchPaths(assembly, sourceModule, true);
			if (file != null)
				return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);

			if (fileList.UseGAC) {
				var gacFile = GacInterop.FindAssemblyInNetGac(assembly);
				if (gacFile != null)
					return fileList.GetOrCreate(gacFile, fileList.AssemblyLoadEnabled, true, delayLoad);
				foreach (var path in GacInfo.OtherGacPaths) {
					file = TryLoadFromDir(assembly, true, path);
					if (file != null)
						return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);
				}
			}

			file = LookupFromSearchPaths(assembly, sourceModule, false);
			if (file != null)
				return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);

			return null;
		}
コード例 #29
0
		public SimpleCompilation(ISolutionSnapshot solutionSnapshot, IUnresolvedAssembly mainAssembly, IEnumerable<IAssemblyReference> assemblyReferences)
		{
			if (solutionSnapshot == null)
				throw new ArgumentNullException("solutionSnapshot");
			if (mainAssembly == null)
				throw new ArgumentNullException("mainAssembly");
			if (assemblyReferences == null)
				throw new ArgumentNullException("assemblyReferences");
			this.solutionSnapshot = solutionSnapshot;
			this.context = new SimpleTypeResolveContext(this);
			this.mainAssembly = mainAssembly.Resolve(context);
			List<IAssembly> assemblies = new List<IAssembly>();
			assemblies.Add(this.mainAssembly);
			List<IAssembly> referencedAssemblies = new List<IAssembly>();
			foreach (var asmRef in assemblyReferences) {
				IAssembly asm = asmRef.Resolve(context);
				if (asm != null && !assemblies.Contains(asm))
					assemblies.Add(asm);
				if (asm != null && !referencedAssemblies.Contains(asm))
					referencedAssemblies.Add(asm);
			}
			this.assemblies = assemblies.AsReadOnly();
			this.referencedAssemblies = referencedAssemblies.AsReadOnly();
			this.knownTypeCache = new KnownTypeCache(this);
		}
コード例 #30
0
 /// <summary>
 ///   Extract binary file from an assembly to a location on disk
 /// </summary>
 /// <param name="fileSystem">The file system.</param>
 /// <param name="assembly">The assembly.</param>
 /// <param name="manifestLocation">The manifest location.</param>
 /// <param name="filePath">The file path.</param>
 /// <param name="overwriteExisting">
 ///   if set to <c>true</c> [overwrite existing].
 /// </param>
 public static void extract_binary_file_from_assembly(IFileSystem fileSystem, IAssembly assembly, string manifestLocation, string filePath, bool overwriteExisting = false)
 {
     if (overwriteExisting || !fileSystem.file_exists(filePath))
     {
         fileSystem.create_directory_if_not_exists(fileSystem.get_directory_name(filePath));
         fileSystem.write_file(filePath, () => assembly.get_manifest_stream(manifestLocation));
     }
 }
コード例 #31
0
ファイル: GenFacades.cs プロジェクト: chargen/buildtools
        private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null)
        {
            bool   needsConversion    = false;
            string pdbOutputPath      = Path.Combine(facadePath, contract.Name + ".pdb");
            string finalPdbOutputPath = pdbOutputPath;

            // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name.
            string facadeFileName   = Path.GetFileName(contract.Location);
            string facadeOutputPath = Path.Combine(facadePath, facadeFileName);

            using (Stream peOutStream = File.Create(facadeOutputPath))
            {
                if (pdbLocation != null)
                {
                    if (File.Exists(pdbLocation))
                    {
                        // Convert from portable to windows PDBs if necessary.  If we convert
                        // set the pdbOutput path to a *.windows.pdb file so we can convert it back
                        // to 'finalPdbOutputPath'.
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            needsConversion = ConvertFromPortableIfNecessary(facade.Location, ref pdbLocation);
                        }
                        if (needsConversion)
                        {
                            // We want to keep the same file name for the PDB because it is used as a key when looking it up on a symbol server
                            string pdbOutputPathPdbDir = Path.Combine(Path.GetDirectoryName(pdbOutputPath), "WindowsPdb");
                            Directory.CreateDirectory(pdbOutputPathPdbDir);
                            pdbOutputPath = Path.Combine(pdbOutputPathPdbDir, Path.GetFileName(pdbOutputPath));
                        }

                        // do the main GenFacades logic (which today only works with windows PDBs).
                        using (Stream pdbReadStream = File.OpenRead(pdbLocation))
                            using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost))
                                using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader))
                                {
                                    PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter);
                                }
                    }
                    else
                    {
                        throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation);
                    }
                }
                else
                {
                    PeWriter.WritePeToStream(facade, seedHost, peOutStream);
                }
            }

            // If we started with Portable PDBs we need to convert the output to portable again.
            // We have to do this after facadeOutputPath is closed for writing.
            if (needsConversion)
            {
                Trace.TraceInformation("Converting PDB generated by GenFacades " + pdbOutputPath + " to portable format " + finalPdbOutputPath);
                ConvertFromWindowsPdb(facadeOutputPath, pdbOutputPath, finalPdbOutputPath);
            }
        }
コード例 #32
0
 public static IEnumerable <ITypeDefinition> GetAllTypeDefinitions(this IAssembly assembly)
 {
     return(TreeTraversal.PreOrder(assembly.TopLevelTypeDefinitions, t => t.NestedTypes));
 }
コード例 #33
0
 public bool IsInternalAccessible(IAssembly asm)
 {
     return(genericType.IsInternalAccessible(asm));
 }
コード例 #34
0
ファイル: UnitHelper.cs プロジェクト: rasiths/visual-profiler
        /// <summary>
        /// True if assembly1 has an attribute that allows assembly2 to access internal members of assembly1.
        /// </summary>
        /// <param name="assembly1">The assembly whose attribute is to be inspected.</param>
        /// <param name="assembly2">The assembly that must be mentioned in the attribute of assembly1.</param>
        /// <returns></returns>
        public static bool AssemblyOneAllowsAssemblyTwoToAccessItsInternals(IAssembly assembly1, IAssembly assembly2)
        {
            var name2       = assembly2.Name.Value;
            var name2Length = assembly2.Name.Value.Length;

            foreach (var attribute in assembly1.AssemblyAttributes)
            {
                if (!TypeHelper.TypesAreEquivalent(attribute.Type, assembly1.PlatformType.SystemRuntimeCompilerServicesInternalsVisibleToAttribute))
                {
                    continue;
                }
                foreach (var argument in attribute.Arguments)
                {
                    var metadataConst = argument as IMetadataConstant;
                    if (metadataConst == null)
                    {
                        break;
                    }
                    var assemblyName = metadataConst.Value as string;
                    if (assemblyName == null)
                    {
                        break;
                    }
                    var assemblyNameLength = assemblyName.Length;
                    if (assemblyNameLength < name2Length)
                    {
                        break;
                    }
                    if (assemblyNameLength > name2Length)
                    {
                        var len = assemblyName.IndexOf(' ');
                        if (len < 0)
                        {
                            len = assemblyName.IndexOf(',');
                        }
                        if (len != name2Length)
                        {
                            break;
                        }
                    }
                    if (string.Compare(assemblyName, 0, assembly2.Name.Value, 0, name2Length, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
コード例 #35
0
ファイル: GenFacades.cs プロジェクト: sungam3r/arcade
            public Assembly GenerateFacade(IAssembly contractAssembly,
                                           IAssemblyReference seedCoreAssemblyReference,
                                           bool ignoreMissingTypes, IAssembly overrideContractAssembly = null,
                                           bool buildPartialReferenceFacade          = false,
                                           bool forceAssemblyReferenceVersionsToZero = false)
            {
                Assembly assembly;

                if (overrideContractAssembly != null)
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost);
                    assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present
                }
                else
                {
                    MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost);
                    assembly = copier.Copy(contractAssembly);

                    // if building a reference facade don't strip the contract
                    if (!buildPartialReferenceFacade)
                    {
                        ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null);
                        rewriter.Rewrite(assembly);
                    }
                }

                if (forceAssemblyReferenceVersionsToZero)
                {
                    foreach (AssemblyReference ar in assembly.AssemblyReferences)
                    {
                        ar.Version = new Version(0, 0, 0, 0);
                    }
                }

                string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value;
                IEnumerable <string> docIds = _docIdTable[contractAssemblyName];

                // Add all the type forwards
                bool error = false;

                Dictionary <string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef);
                IEnumerable <string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id));
                Dictionary <string, INamedTypeReference> forwardedTypes = new Dictionary <string, INamedTypeReference>();

                foreach (string docId in docIdsToForward)
                {
                    IReadOnlyList <INamedTypeDefinition> seedTypes;
                    if (!_typeTable.TryGetValue(docId, out seedTypes))
                    {
                        if (!ignoreMissingTypes && !buildPartialReferenceFacade)
                        {
                            Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId);
                            error = true;
                        }
                        continue;
                    }

                    INamedTypeDefinition seedType = GetSeedType(docId, seedTypes);
                    if (seedType == null)
                    {
                        TraceDuplicateSeedTypeError(docId, seedTypes);
                        error = true;
                        continue;
                    }

                    if (buildPartialReferenceFacade)
                    {
                        // honor preferSeedType for keeping contract type
                        string preferredSeedAssembly;
                        bool   keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) &&
                                          contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase);

                        if (keepType)
                        {
                            continue;
                        }

                        assembly.AllTypes.Remove(existingDocIds[docId]);
                        forwardedTypes.Add(docId, seedType);
                    }

                    AddTypeForward(assembly, seedType);
                }

                if (buildPartialReferenceFacade)
                {
                    if (forwardedTypes.Count == 0)
                    {
                        Trace.TraceError("Did not find any types in any of the seed assemblies.");
                        return(null);
                    }
                    else
                    {
                        // for any thing that's now a typeforward, make sure typerefs point to that rather than
                        // the type previously inside the assembly.
                        TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType =>
                        {
                            INamedTypeReference newType = null;
                            return(forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType);
                        });

                        var remainingTypes = assembly.AllTypes.Where(t => t.Name.Value != "<Module>");

                        if (!remainingTypes.Any())
                        {
                            Trace.TraceInformation($"Removed all types from {contractAssembly.Name} thus will remove ReferenceAssemblyAttribute.");
                            assembly.AssemblyAttributes.RemoveAll(ca => ca.FullName() == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute");
                            assembly.Flags &= ~ReferenceAssemblyFlag;
                        }

                        typeRefRewriter.Rewrite(assembly);
                    }
                }

                if (error)
                {
                    return(null);
                }

                if (_assemblyFileVersion != null)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString()));
                }

                if (_buildDesignTimeFacades)
                {
                    assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly));
                    assembly.Flags |= ReferenceAssemblyFlag;
                }

                if (_clearBuildAndRevision)
                {
                    assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0);
                }

                AddWin32VersionResource(contractAssembly.Location, assembly);

                return(assembly);
            }
コード例 #36
0
 public static void Write(XmlWriter writer, IAssembly assembly)
 {
     Write(writer, assembly, TypeFilter);
 }
コード例 #37
0
 public void addAnalyzedIncomingDependency(IAssembly a)
 {
     this.incomingDependencies.Add(a);
 }
コード例 #38
0
 public void addAnalyzedOutgoingDependency(IAssembly a)
 {
     this.outgoingDependencies.Add(a);
 }
コード例 #39
0
ファイル: AssemblyResolver.cs プロジェクト: zzzsleepsin/dnSpy
 AssemblyDef?IAssemblyResolver.Resolve(IAssembly assembly, ModuleDef?sourceModule) =>
 Resolve(assembly, sourceModule)?.AssemblyDef;
コード例 #40
0
        public override DifferenceType Diff(IDifferences differences, IAssembly impl, IAssembly contract)
        {
            if (impl == null || contract == null)
            {
                return(DifferenceType.Unknown);
            }

            bool added = false;

            added |= AnyAttributeAdded(differences, impl, impl.AssemblyAttributes, contract.AssemblyAttributes);
            added |= AnyAttributeAdded(differences, impl, impl.ModuleAttributes, contract.ModuleAttributes);
            added |= AnySecurityAttributeAdded(differences, impl, impl.SecurityAttributes, contract.SecurityAttributes);

            if (added)
            {
                return(DifferenceType.Changed);
            }

            return(DifferenceType.Unknown);
        }
コード例 #41
0
ファイル: CSDeclarationWriter.cs プロジェクト: wli3/arcade
 public void WriteAssemblyDeclaration(IAssembly assembly)
 {
     WriteAttributes(assembly.Attributes, prefix: "assembly");
     WriteAttributes(assembly.SecurityAttributes, prefix: "assembly");
 }
コード例 #42
0
ファイル: GenFacades.cs プロジェクト: sungam3r/arcade
        public static bool Execute(
            string seeds,
            string contracts,
            string facadePath,
            Version assemblyFileVersion               = null,
            bool clearBuildAndRevision                = false,
            bool ignoreMissingTypes                   = false,
            bool ignoreBuildAndRevisionMismatch       = false,
            bool buildDesignTimeFacades               = false,
            string inclusionContracts                 = null,
            ErrorTreatment seedLoadErrorTreatment     = ErrorTreatment.Default,
            ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default,
            string[] seedTypePreferencesUnsplit       = null,
            bool forceZeroVersionSeeds                = false,
            bool producePdb = true,
            string partialFacadeAssemblyPath = null,
            bool buildPartialReferenceFacade = false)
        {
            if (!Directory.Exists(facadePath))
            {
                Directory.CreateDirectory(facadePath);
            }

            var nameTable     = new NameTable();
            var internFactory = new InternFactory();

            try
            {
                Dictionary <string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit);

                using (var contractHost = new HostEnvironment(nameTable, internFactory))
                    using (var seedHost = new HostEnvironment(nameTable, internFactory))
                    {
                        contractHost.LoadErrorTreatment = contractLoadErrorTreatment;
                        seedHost.LoadErrorTreatment     = seedLoadErrorTreatment;

                        var contractAssemblies = LoadAssemblies(contractHost, contracts);
                        IReadOnlyDictionary <string, IEnumerable <string> > docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts);

                        IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray();

                        IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef;

                        if (forceZeroVersionSeeds)
                        {
                            // Create a deep copier, copy the seed assemblies, and zero out their versions.
                            var copier = new MetadataDeepCopier(seedHost);

                            for (int i = 0; i < seedAssemblies.Length; i++)
                            {
                                var mutableSeed = copier.Copy(seedAssemblies[i]);
                                mutableSeed.Version = new Version(0, 0, 0, 0);
                                // Copy the modified seed assembly back.
                                seedAssemblies[i] = mutableSeed;

                                if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey)
                                {
                                    seedCoreAssemblyRef = mutableSeed;
                                }
                            }
                        }

                        var typeTable       = GenerateTypeTable(seedAssemblies);
                        var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion);

                        if (buildPartialReferenceFacade && ignoreMissingTypes)
                        {
                            throw new FacadeGenerationException(
                                      "When buildPartialReferenceFacade is specified ignoreMissingTypes must not be specified.");
                        }

                        if (partialFacadeAssemblyPath != null)
                        {
                            if (contractAssemblies.Count() != 1)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified.");
                            }

                            if (buildPartialReferenceFacade)
                            {
                                throw new FacadeGenerationException(
                                          "When partialFacadeAssemblyPath is specified, buildPartialReferenceFacade must not be specified.");
                            }

                            IAssembly contractAssembly      = contractAssemblies.First();
                            IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath);
                            if (contractAssembly.Name != partialFacadeAssembly.Name ||
                                contractAssembly.Version.Major != partialFacadeAssembly.Version.Major ||
                                contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) ||
                                (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) ||
                                contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken())
                            {
                                throw new FacadeGenerationException(
                                          string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}",
                                                        contractAssembly.AssemblyIdentity,
                                                        partialFacadeAssembly.AssemblyIdentity));
                            }

                            Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes,
                                                                                          overrideContractAssembly: partialFacadeAssembly,
                                                                                          forceAssemblyReferenceVersionsToZero: forceZeroVersionSeeds);

                            if (filledPartialFacade == null)
                            {
                                Trace.TraceError("Errors were encountered while generating the facade.");
                                return(false);
                            }

                            string pdbLocation = null;

                            if (producePdb)
                            {
                                string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath);
                                pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb");
                                if (producePdb && !File.Exists(pdbLocation))
                                {
                                    pdbLocation = null;
                                    Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated.");
                                }
                            }

                            OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation);
                        }
                        else
                        {
                            foreach (var contract in contractAssemblies)
                            {
                                Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes, buildPartialReferenceFacade: buildPartialReferenceFacade);
                                if (facade == null)
                                {
#if !COREFX
                                    Debug.Assert(Environment.ExitCode != 0);
#endif
                                    return(false);
                                }

                                OutputFacadeToFile(facadePath, seedHost, facade, contract);
                            }
                        }
                    }

                return(true);
            }
            catch (FacadeGenerationException ex)
            {
                Trace.TraceError(ex.Message);
#if !COREFX
                Debug.Assert(Environment.ExitCode != 0);
#endif
                return(false);
            }
        }
コード例 #43
0
 public static byte[] CreateIVTBlob(IAssembly sourceAssembly) => CreateIVTBlob(GetIVTString(sourceAssembly));
コード例 #44
0
ファイル: DsDocumentService.cs プロジェクト: xisuo67/dnSpy
 public IDsDocument?FindAssembly(IAssembly assembly) => FindAssembly(assembly, DefaultOptions);
コード例 #45
0
 internal static ISet <IAssembly> CloseAndResolveOverReferencedAssemblies(IAssembly rootAssembly)
 {
     return(CloseAndResolveOverReferencedAssemblies(new IAssembly[] { rootAssembly }));
 }
コード例 #46
0
        private static void CloseAndResolveOverReferencedAssembliesHelper(ISet <IAssembly> collectedAssemblies, IAssembly assembly)
        {
            Contract.Requires(!(assembly is Dummy));
            Contract.Ensures(collectedAssemblies.Contains(assembly));

            if (collectedAssemblies.Contains(assembly))
            {
                return; // Base Case
            }
            else
            {
                collectedAssemblies.Add(assembly);

                foreach (IAssemblyReference referencedAssemblyReference in assembly.AssemblyReferences)
                {
                    IAssembly referencedAssembly = referencedAssemblyReference.ResolvedAssembly;

                    if (!(referencedAssembly is Dummy))
                    {
                        CloseAndResolveOverReferencedAssembliesHelper(collectedAssemblies, referencedAssembly);
                    }
                    else
                    {
                        throw new Exception("Couldn't resolve assembly " + referencedAssemblyReference + " referenced in " + assembly);
                    }
                }
            }

            return; // Recursive Case
        }
コード例 #47
0
 static string GetId(IAssembly assembly)
 {
     return(new SR.AssemblyName(assembly.FullName).FullName.ToUpperInvariant());
 }
コード例 #48
0
 /// <summary>
 /// Creates a new AssemblyManager.
 /// </summary>
 /// <param name="provider">The unit test provider.</param>
 /// <param name="filter">The run filter.</param>
 /// <param name="assembly">The unit test assembly metadata object.</param>
 /// <returns>Returns a new AssemblyManager.</returns>
 public AssemblyManager CreateAssemblyManager(IUnitTestProvider provider, TestRunFilter filter, IAssembly assembly)
 {
     return(new AssemblyManager(filter, _harness, provider, assembly));
 }
コード例 #49
0
        public static IMemberReference ParseMemberReference(String reference)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference", "The value specified for the 'reference' argument must not be null.");
            }

            if (reference.Length == 0)
            {
                throw new ArgumentException("The value specified for the 'reference' argument must not be zero length.", "reference");
            }

            // Parse the assembly
            if (reference[0] != '[')
            {
                throw new ApplicationException("Expected '[' character at position 0");
            }

            int position = 1;

            while (reference[position++] != ']')
            {
                if (position == reference.Length)
                {
                    throw new ApplicationException("Unexpected end of string while parsing assembly name");
                }
            }

            String assemblyName = reference.Substring(1, position - 2);

            if (assemblyName.Length == 0)
            {
                throw new ApplicationException("Unable to parse assembly name.");
            }

            IAssembly[] assemblies = Assemblies;

            IAssembly assembly = null;

            for (int i = 0; i < assemblies.Length; i++)
            {
                if (assemblyName.Equals(assemblies[i].Name, StringComparison.InvariantCulture))
                {
                    assembly = assemblies[i];
                    break;
                }
            }

            if ((position == reference.Length) || (assembly == null))
            {
                return(assembly);
            }

            // Parse the namespace
            int startPosition = position;

            while ((position < reference.Length) && (reference[position++] != ':'))
            {
            }

            if (position < reference.Length)
            {
                position--;
            }

            String         typeName      = reference.Substring(startPosition, position - startPosition);
            ITypeReference typeReference = null;

            foreach (IModule module in assembly.Modules)
            {
                foreach (ITypeDeclaration type in module.Types)
                {
                    if (typeName == type.Namespace + "." + type.Name)
                    {
                        typeReference = type;
                        break;
                    }
                }
            }

            if ((position == reference.Length) || (typeReference == null))
            {
                return(typeReference);
            }

            String memberName = reference.Substring(position + 2);

            foreach (IMethodDeclaration methodReference in typeReference.Resolve().Methods)
            {
                if (methodReference.Name == memberName)
                {
                    return(methodReference);
                }
            }

            foreach (IPropertyDeclaration propertyDeclaration in typeReference.Resolve().Properties)
            {
                if (propertyDeclaration.Name == memberName)
                {
                    return(propertyDeclaration);
                }

                if ((propertyDeclaration.GetMethod != null) && propertyDeclaration.GetMethod.Name == memberName)
                {
                    return(propertyDeclaration.GetMethod);
                }

                if ((propertyDeclaration.SetMethod != null) && propertyDeclaration.SetMethod.Name == memberName)
                {
                    return(propertyDeclaration.SetMethod);
                }
            }

            return(null);
        }
コード例 #50
0
 /// <summary>
 /// Creates a new <see cref="ModuleBase"/> instance
 /// with the <paramref name="parent"/> provided.
 /// </summary>
 /// <param name="parent">The <see cref="IAssembly"/>
 /// that created the <see cref="ModuleBase"/>.</param>
 protected ModuleBase(IAssembly parent)
 {
     this.parent = parent;
 }
コード例 #51
0
 protected static IMethod AssertGetMethod(IAssembly assembly, string qualifiedName)
 {
     Assert.True(assembly.TryGetMethod(QualifiedName(qualifiedName), out var method));
     return(method !);
 }
コード例 #52
0
 protected static IInterface AssertGetInterface(IAssembly assembly, string qualifiedName)
 {
     Assert.True(assembly.TryGetInterface(QualifiedName(qualifiedName), out var @interface));
     return(@interface !);
 }
コード例 #53
0
 public override void Visit(IAssembly assembly)
 {
     Debug.Assert(assembly == module);
     this.Visit((IModule)assembly);
 }
コード例 #54
0
ファイル: NullResolver.cs プロジェクト: liangran10000/dnlib-1
 /// <inheritdoc/>
 public AssemblyDef Resolve(IAssembly assembly, ModuleDef sourceModule)
 {
     return(null);
 }
コード例 #55
0
        public DnSpyFile Resolve(IAssembly assembly, ModuleDef sourceModule = null, bool delayLoad = false)
        {
            FrameworkRedirect.ApplyFrameworkRedirect(ref assembly, sourceModule);

            if (assembly.IsContentTypeWindowsRuntime)
            {
                return(ResolveWinMD(assembly, sourceModule, delayLoad));
            }

            // WinMD files have a reference to mscorlib but its version is always 255.255.255.255
            // since mscorlib isn't really loaded. The resolver only loads exact versions, so
            // we must change the version or the resolve will fail.
            if (assembly.Name == "mscorlib" && assembly.Version == invalidMscorlibVersion)
            {
                assembly = new AssemblyNameInfo(assembly)
                {
                    Version = newMscorlibVersion
                }
            }
            ;

            return(ResolveNormal(assembly, sourceModule, delayLoad));
        }

        DnSpyFile ResolveNormal(IAssembly assembly, ModuleDef sourceModule, bool delayLoad)
        {
            var existingFile = fileList.FindAssembly(assembly);

            if (existingFile != null)
            {
                return(existingFile);
            }

            var file = LookupFromSearchPaths(assembly, sourceModule, true);

            if (file != null)
            {
                return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
            }

            if (fileList.UseGAC)
            {
                var gacFile = GacInterop.FindAssemblyInNetGac(assembly);
                if (gacFile != null)
                {
                    return(fileList.GetOrCreate(gacFile, fileList.AssemblyLoadEnabled, true, delayLoad));
                }
                foreach (var path in GacInfo.OtherGacPaths)
                {
                    file = TryLoadFromDir(assembly, true, path);
                    if (file != null)
                    {
                        return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
                    }
                }
            }

            file = LookupFromSearchPaths(assembly, sourceModule, false);
            if (file != null)
            {
                return(fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad));
            }

            return(null);
        }

        DnSpyFile LookupFromSearchPaths(IAssembly asmName, ModuleDef sourceModule, bool exactCheck)
        {
            DnSpyFile file;
            string    sourceModuleDir = null;

            if (sourceModule != null && File.Exists(sourceModule.Location))
            {
                sourceModuleDir = Path.GetDirectoryName(sourceModule.Location);
                file            = TryLoadFromDir(asmName, exactCheck, sourceModuleDir);
                if (file != null)
                {
                    return(file);
                }
            }
            var ary = asmSearchPathsArray;

            foreach (var path in ary)
            {
                file = TryLoadFromDir(asmName, exactCheck, path);
                if (file != null)
                {
                    return(file);
                }
            }

            return(null);
        }

        DnSpyFile TryLoadFromDir(IAssembly asmName, bool exactCheck, string dirPath)
        {
            string baseName;

            try {
                baseName = Path.Combine(dirPath, asmName.Name);
            }
            catch (ArgumentException) {             // eg. invalid chars in asmName.Name
                return(null);
            }
            return(TryLoadFromDir2(asmName, exactCheck, baseName + ".dll") ??
                   TryLoadFromDir2(asmName, exactCheck, baseName + ".exe"));
        }

        DnSpyFile TryLoadFromDir2(IAssembly asmName, bool exactCheck, string filename)
        {
            if (!File.Exists(filename))
            {
                return(null);
            }

            DnSpyFile file  = null;
            bool      error = true;

            try {
                file = fileList.CreateDnSpyFile(filename);
                file.IsAutoLoaded = true;
                var asm = file.AssemblyDef;
                if (asm == null)
                {
                    return(null);
                }
                bool b = exactCheck ?
                         AssemblyNameComparer.CompareAll.Equals(asmName, asm) :
                         AssemblyNameComparer.NameAndPublicKeyTokenOnly.Equals(asmName, asm);
                if (!b)
                {
                    return(null);
                }

                error = false;
                return(file);
            }
            finally {
                if (error)
                {
                    if (file != null)
                    {
                        file.Dispose();
                    }
                }
            }
        }

        DnSpyFile ResolveWinMD(IAssembly assembly, ModuleDef sourceModule, bool delayLoad)
        {
            var existingFile = fileList.FindAssembly(assembly);

            if (existingFile != null)
            {
                return(existingFile);
            }

            foreach (var winmdPath in GacInfo.WinmdPaths)
            {
                string file;
                try {
                    file = Path.Combine(winmdPath, assembly.Name + ".winmd");
                }
                catch (ArgumentException) {
                    continue;
                }
                if (File.Exists(file))
                {
                    return(fileList.GetOrCreate(file, fileList.AssemblyLoadEnabled, true, delayLoad));
                }
            }
            return(null);
        }
    }
コード例 #56
0
 public override abstract void Visit(IAssembly assembly);
コード例 #57
0
        private Type GetRuntimeType(ITypeResolver typeResolver, ProjectContextType typeId)
        {
            Type type;

            if (RuntimeGeneratedTypesHelper.IsControlEditingAssembly(typeId.assembly))
            {
                Type sourceType = ControlEditingDesignTypeGenerator.GetSourceType(typeId.RuntimeType);
                if (sourceType != null)
                {
                    ProjectContextType projectContextType = typeResolver.GetType(sourceType) as ProjectContextType;
                    if (projectContextType != null)
                    {
                        Type runtimeType = projectContextType.GetRuntimeType();
                        if (runtimeType != sourceType && runtimeType != null)
                        {
                            Type type1 = (new ControlEditingDesignTypeGenerator(typeResolver)).DefineType(runtimeType);
                            if (type1 != typeId.RuntimeType)
                            {
                                this.assemblyName = AssemblyHelper.GetAssemblyName(type1.Assembly).Name;
                                this.assembly     = this.GetAssembly(this.typeResolver, this.assemblyName);
                                return(type1);
                            }
                        }
                    }
                }
            }
            if (typeId.arrayItemType == null)
            {
                IAssembly runtimeAssembly = typeId.RuntimeAssembly;
                if (runtimeAssembly != null)
                {
                    runtimeAssembly = this.GetAssembly(typeResolver, runtimeAssembly.Name);
                }
                if (runtimeAssembly != null)
                {
                    Type type2 = PlatformTypeHelper.GetType(runtimeAssembly, typeId.FullName);
                    if (type2 != null)
                    {
                        if (!typeId.IsGenericType)
                        {
                            return(type2);
                        }
                        IList <IType> genericTypeArguments = typeId.GetGenericTypeArguments();
                        int           count = genericTypeArguments.Count;
                        if (count > 0)
                        {
                            Type[] typeArray = new Type[count];
                            for (int i = 0; i < count; i++)
                            {
                                Type runtimeType1 = this.GetRuntimeType(genericTypeArguments[i]);
                                if (runtimeType1 == null)
                                {
                                    return(null);
                                }
                                typeArray[i] = runtimeType1;
                            }
                            try
                            {
                                type = type2.MakeGenericType(typeArray);
                            }
                            catch (ArgumentException argumentException)
                            {
                                return(null);
                            }
                            return(type);
                        }
                    }
                }
            }
            else
            {
                Type runtimeType2 = this.GetRuntimeType(typeId.arrayItemType);
                if (runtimeType2 != null)
                {
                    if (typeId.arrayRank <= 1)
                    {
                        return(runtimeType2.MakeArrayType());
                    }
                    return(runtimeType2.MakeArrayType(typeId.arrayRank));
                }
            }
            return(null);
        }
コード例 #58
0
        public bool Refresh()
        {
            ITypeId     typeId      = this.baseType;
            IPropertyId propertyId  = this.nameProperty;
            IPropertyId propertyId1 = this.defaultContentProperty;
            ITypeId     typeId1     = this.itemType;
            ITypeId     typeId2     = this.nullableType;

            System.ComponentModel.TypeConverter typeConverter = this.typeConverter;
            IAssembly assembly = this.GetAssembly(this.typeResolver, this.assemblyName);

            if (!assembly.IsLoaded)
            {
                return(true);
            }
            this.assembly                = assembly;
            this.type                    = this.GetRuntimeType();
            this.typeConverter           = null;
            this.initializationException = null;
            if (this.type != null)
            {
                this.lastResolvedType = this.type;
                this.isBuilt          = true;
            }
            this.Cache();
            bool flag = true;

            if (this.constructors != null)
            {
                foreach (Constructor constructor in this.constructors)
                {
                    ICachedMemberInfo cachedMemberInfo = constructor;
                    if (cachedMemberInfo == null || cachedMemberInfo.Refresh())
                    {
                        continue;
                    }
                    flag = false;
                }
                if (flag && this.type != null)
                {
                    int num = 0;
                    ConstructorInfo[] constructors = PlatformTypeHelper.GetConstructors(this.type);
                    if (constructors != null)
                    {
                        ConstructorInfo[] constructorInfoArray = constructors;
                        for (int i = 0; i < (int)constructorInfoArray.Length; i++)
                        {
                            if (PlatformTypeHelper.IsAccessibleConstructor(constructorInfoArray[i]))
                            {
                                num++;
                            }
                        }
                    }
                    if (num != this.constructors.Count)
                    {
                        flag = false;
                    }
                }
            }
            if (!this.members.Refresh())
            {
                flag = false;
            }
            if (flag && (typeId != this.baseType || typeId1 != this.itemType || typeId2 != this.nullableType))
            {
                flag = false;
            }
            if (flag && (propertyId != this.nameProperty || propertyId1 != this.defaultContentProperty))
            {
                flag = false;
            }
            if (flag && ProjectContextType.GetTypeConverterId(typeConverter) != ProjectContextType.GetTypeConverterId(this.typeConverter))
            {
                flag = false;
            }
            if (flag && this.constructorArgumentProperties != null)
            {
                IConstructorArgumentProperties constructorArgumentProperties = PlatformTypeHelper.GetConstructorArgumentProperties(this);
                if (constructorArgumentProperties.Count == this.constructorArgumentProperties.Count)
                {
                    foreach (string constructorArgumentProperty in constructorArgumentProperties)
                    {
                        if (constructorArgumentProperties[constructorArgumentProperty] == this.constructorArgumentProperties[constructorArgumentProperty])
                        {
                            continue;
                        }
                        flag = false;
                        break;
                    }
                }
                else
                {
                    flag = false;
                }
            }
            return(flag);
        }
コード例 #59
0
        AssemblyDef IAssemblyResolver.Resolve(IAssembly assembly, ModuleDef sourceModule)
        {
            var file = Resolve(assembly, sourceModule, true);

            return(file == null ? null : file.AssemblyDef);
        }
コード例 #60
0
 public IAssembly GetDesignAssembly(IAssembly assembly)
 {
     throw new NotImplementedException();
 }