상속: BaseAssemblyResolver
예제 #1
1
파일: CecilUtils.cs 프로젝트: chartly/flood
        public static AssemblyDefinition GetAssemblyDef(string assemblyPath)
        {
            if (assemblies.ContainsKey(assemblyPath))
                return assemblies[assemblyPath];

            var assemblyResolver = new DefaultAssemblyResolver();
            var assemblyLocation = Path.GetDirectoryName(assemblyPath);
            assemblyResolver.AddSearchDirectory(assemblyLocation);

            var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver };

            var pdbName = Path.ChangeExtension(assemblyPath, "pdb");
            if (File.Exists(pdbName))
            {
                var symbolReaderProvider = new PdbReaderProvider();
                readerParameters.SymbolReaderProvider = symbolReaderProvider;
                readerParameters.ReadSymbols = true;
            }

            var assemblyDef = AssemblyDefinition.ReadAssembly(assemblyPath, readerParameters);

            assemblies.Add(assemblyPath,assemblyDef);

            return assemblyDef;
        }
        private static ModuleDefinition ResolveInterceptorModuleDefinition()
        {
            const string InterceptorAssemblyName = "StaticProxy.Interceptor";

            AssemblyDefinition definition = ModuleWeaver.Instance.AssemblyResolver.Resolve(InterceptorAssemblyName);
            if (definition == null)
            {
                // todo use an integration test to test this!
                DirectoryInfo nugetPackagesDirectory = Directory.GetParent(ModuleWeaver.Instance.AddinDirectoryPath);
                var assemblyResolver = new DefaultAssemblyResolver();

                DirectoryInfo[] packageDirectores = nugetPackagesDirectory.GetDirectories();
                foreach (DirectoryInfo packageDirectory in packageDirectores)
                {
                    assemblyResolver.AddSearchDirectory(packageDirectory.FullName);
                }

                definition = assemblyResolver.Resolve(InterceptorAssemblyName);
                if (definition == null)
                {
                    throw new WeavingException("Can't find StaticProxy.Interceptor assembly. Make sure you've downloaded and installed the nuget package!");
                }
            }

            return definition.MainModule;
        }
		public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
		{
			string text = "tmplink.xml";
			usedClasses.SynchronizeClasses();
			using (TextWriter textWriter = new StreamWriter(Path.Combine(librariesFolder, text)))
			{
				textWriter.WriteLine("<linker>");
				textWriter.WriteLine("<assembly fullname=\"UnityEngine\">");
				foreach (string current in usedClasses.GetAllManagedClassesAsString())
				{
					textWriter.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", current, usedClasses.GetRetentionLevel(current)));
				}
				textWriter.WriteLine("</assembly>");
				DefaultAssemblyResolver defaultAssemblyResolver = new DefaultAssemblyResolver();
				defaultAssemblyResolver.AddSearchDirectory(librariesFolder);
				for (int i = 0; i < allAssemblies.Length; i++)
				{
					string path = allAssemblies[i];
					AssemblyDefinition assemblyDefinition = defaultAssemblyResolver.Resolve(Path.GetFileNameWithoutExtension(path), new ReaderParameters
					{
						AssemblyResolver = defaultAssemblyResolver
					});
					textWriter.WriteLine("<assembly fullname=\"{0}\">", assemblyDefinition.Name.Name);
					MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
					textWriter.WriteLine("</assembly>");
				}
				textWriter.WriteLine("</linker>");
			}
			return text;
		}
예제 #4
0
파일: Program.cs 프로젝트: tritao/flood
        private static void WeaveAssembly(string assemblyPath)
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            var assemblyLocation = Path.GetDirectoryName(assemblyPath);
            assemblyResolver.AddSearchDirectory(assemblyLocation);
            //if (!string.IsNullOrEmpty(HintPath))
            //{
               // assemblyResolver.AddSearchDirectory(HintPath);
               // }
               // var silverlightAssemblyPath = Environment.ExpandEnvironmentVariables(@”%ProgramFiles%\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\”);
               // assemblyResolver.AddSearchDirectory(silverlightAssemblyPath);
            var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver };
            var writerParameters = new WriterParameters();
            var pdbName = Path.ChangeExtension(assemblyPath, "pdb");
            if (File.Exists(pdbName))
            {
                var symbolReaderProvider = new PdbReaderProvider();
                readerParameters.SymbolReaderProvider = symbolReaderProvider;
                readerParameters.ReadSymbols = true;
                writerParameters.WriteSymbols = true;
            }
            var assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyPath, readerParameters);

            var weaver = new NotifierWeaver();
            weaver.WeaveModule(assemblyDefinition.MainModule);

            assemblyDefinition.Write(assemblyPath, writerParameters);
        }
예제 #5
0
		//Adapted from: https://stackoverflow.com/questions/9262464/tool-to-show-assembly-dependencies
		public static void PoC(IEnumerable<AssemblyDefinition> assemblies, TextWriter writer, IEnumerable<string> searchfolders)
		{
			var resolver = new DefaultAssemblyResolver();
			searchfolders.ToList().ForEach(x => resolver.AddSearchDirectory(x));

			//writer.WriteLine("digraph Dependencies {");
			var loaded = assemblies
				.SelectMany(a => a.Modules.Cast<ModuleDefinition>())
				.SelectMany(m => m.AssemblyReferences.Cast<AssemblyNameReference>())
				.Distinct()
				.Select(asm => {
					var dllname = asm.Name + ".dll";
					//Console.WriteLine("Probing for {0}", dllname);
					try { return AssemblyDefinition.ReadAssembly(dllname); }
					catch { } 
					try { return resolver.Resolve(asm.FullName); }
					catch { }

					return null;
				})
				.Where(assembly => assembly != null)
				.ToList();

			//loaded.ForEach(a => a.MainModule.ReadSymbols());

			loaded.Select(x => x.FullName).Distinct().OrderBy(x => x).ToList().ForEach(x => writer.WriteLine("{0}", x));
			/*loaded.ForEach(a =>
				{
					foreach (var r in a.MainModule.AssemblyReferences.Cast<AssemblyNameReference>())
						writer.WriteLine(@"""{0}"" -> ""{1}"";", r.Name, a.Name.Name);
				} );*/

			//writer.WriteLine("}");
		}
예제 #6
0
 public static AssemblyDefinition Load(string fileName)
 {
     var resolver = new DefaultAssemblyResolver();
     resolver.AddSearchDirectory(new FileInfo(fileName).DirectoryName);
     var parameters = new ReaderParameters
     {
         SymbolReaderProvider = new PdbReaderProvider(),
         ReadingMode = ReadingMode.Immediate,
         AssemblyResolver = resolver
     };
     AssemblyDefinition assemblyDef;
     try
     {
         assemblyDef = AssemblyDefinition.ReadAssembly(fileName, parameters);
     }
     catch (FileNotFoundException)
     {
         // Perhaps we have an MDB file (Mono), or there is no symbol file to load.
         // Try MDB first!
         parameters.SymbolReaderProvider = new MdbReaderProvider();
         try
         {
             assemblyDef = AssemblyDefinition.ReadAssembly(fileName, parameters);
         }
         catch (FileNotFoundException)
         {
             parameters.SymbolReaderProvider = null;
             assemblyDef = AssemblyDefinition.ReadAssembly(fileName, parameters);
         }
     }
     return assemblyDef;
 }
예제 #7
0
        private Program()
        {
            defaultResolver = new DefaultAssemblyResolver();
            defaultResolver.AddSearchDirectory(@"..\..\..\..\..\Bin\Desktop\");
            writer = new StringWriter();

            indexWriter = new StreamWriter("index.md");
        }
예제 #8
0
        private static IAssemblyResolver AssemblyResolverFor(IEnumerable<string> assemblies)
        {
            var resolver = new DefaultAssemblyResolver();

            foreach (var directory in assemblies.Select(a => Path.GetFullPath(Path.GetDirectoryName(a))).ToHashSet())
                resolver.AddSearchDirectory(directory);

            return resolver;
        }
예제 #9
0
        public Assembly LoadAssembly(Stream stream)
        {
            Cecil.ModuleDefinition        module           = Cecil.ModuleDefinition.ReadModule(stream);
            Cecil.DefaultAssemblyResolver assemblyResolver = module.AssemblyResolver as Cecil.DefaultAssemblyResolver;
            Assembly assembly = ExtractAssembly(module);

            ourHost.Assemblies.Add(assembly);
            return(assembly);
        }
예제 #10
0
        public Assembly LoadAssembly(string fileName)
        {
            Cecil.ModuleDefinition        module           = Cecil.ModuleDefinition.ReadModule(fileName);
            Cecil.DefaultAssemblyResolver assemblyResolver = module.AssemblyResolver as Cecil.DefaultAssemblyResolver;
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(Path.GetFullPath(fileName)));
            Assembly assembly = ExtractAssembly(module);

            ourHost.Assemblies.Add(assembly);
            return(assembly);
        }
예제 #11
0
		void RunTest(string name, string asmPath, string sourcePath)
		{
			var resolver = new DefaultAssemblyResolver();
			var assembly = AssemblyDefinition.ReadAssembly(asmPath, new ReaderParameters { AssemblyResolver = resolver });
			Resource res = assembly.MainModule.Resources.First();
			Stream bamlStream = LoadBaml(res, name + ".baml");
			Assert.IsNotNull(bamlStream);
			XDocument document = BamlResourceEntryNode.LoadIntoDocument(resolver, assembly, bamlStream);

			CodeAssert.AreEqual(File.ReadAllText(sourcePath), document.ToString());
		}
 private AssemblyDefinition ReadAssembly(string assemblyPath, string searchDir)
 {
     var assemblyResolver = new DefaultAssemblyResolver();
     assemblyResolver.AddSearchDirectory(searchDir);
     return
         AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters
                                         {
                                             AssemblyResolver = assemblyResolver,
                                             ReadingMode = ReadingMode.Deferred
                                         });
 }
예제 #13
0
        private static MachineType GetDllMachineType(string dllPath)
        {
            if (string.IsNullOrEmpty(dllPath) || !File.Exists(dllPath))
            {
                return MachineType.Unknown;
            }
            var resolver = new DefaultAssemblyResolver(GlobalAssemblyResolver.CurrentAssemblyPathCache);

            AssemblyDefinition assemblyDefinition = resolver.GetAssemblyDefinition(dllPath);

            return assemblyDefinition == null ? MachineType.Unknown : MachineType.CLR;
        }
예제 #14
0
 public void LoadAsm(string f)
 {
     source = f;
     var ar = new DefaultAssemblyResolver();
     ar.AddSearchDirectory(Path.GetDirectoryName(f));
     string[] searchDirs = new string[] { @"C:\Program Files\Reference Assemblies", @"C:\Program Files (x86)\Reference Assemblies" };
     foreach (string sd in searchDirs) if (Directory.Exists(sd)) ar.AddSearchDirectory(sd);
     ar.ResolveFailure += new AssemblyResolveEventHandler(ResolveFailure);
     ReaderParameters rp = new ReaderParameters() { AssemblyResolver = ar };
     assembly = AssemblyDefinition.ReadAssembly(source, rp);
     LoadAssemblyTree();
 }
        public static AssemblyDefinition LoadCecilAssembly(string fileName, bool immediateLoad = false, bool? readSymbols = null)
        {
            using (var t = new Tracer(Level.L5, myType, "LoadCecilAssembly"))
            {
                var pdbPath = Path.ChangeExtension(fileName, "pdb");
                var tryReadSymbols = readSymbols ?? File.Exists(pdbPath);
                var fileInfo = new FileInfo(fileName);
                if (fileInfo.Length == 0)
                {
                    t.Info("File {0} has zero byte length", fileName);
                    return null;
                }

                try
                {
                    var readingMode = immediateLoad ? ReadingMode.Immediate : ReadingMode.Deferred;
                    var assemblyResolver = new DefaultAssemblyResolver();
                    assemblyResolver.AddSearchDirectory(fileInfo.Directory.FullName);
                    var readerParameters = new ReaderParameters { ReadSymbols = tryReadSymbols, ReadingMode = readingMode, AssemblyResolver = assemblyResolver };
                    var assemblyDef = AssemblyDefinition.ReadAssembly(fileName, readerParameters);

                    // Managed C++ assemblies are not supported by Mono Cecil
                    if (IsManagedCppAssembly(assemblyDef))
                    {
                        t.Info("File {0} is a managed C++ assembly", fileName);
                        return null;
                    }

                    return assemblyDef;
                }
                catch (BadImageFormatException) // Ignore invalid images
                {
                }
                catch (IndexOutOfRangeException)
                {
                    t.Info("File {0} is a managed C++ assembly", fileName);
                }
                catch (NullReferenceException) // ignore managed c++ targets
                {
                    t.Info("File {0} is a managed C++ assembly", fileName);
                }
                catch (ArgumentOutOfRangeException)
                {
                    t.Info("File {0} is a managed C++ assembly", fileName);
                }
                catch (Exception ex)
                {
                    t.Error(Level.L1, "Could not read assembly {0}: {1}", fileName, ex);
                }

                return null;
            }
        }
 public void Simple()
 {
     var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "ScriptBuilder.Tests.dll");
     var assemblyResolver = new DefaultAssemblyResolver();
     assemblyResolver.AddSearchDirectory(TestContext.CurrentContext.TestDirectory);
     var readerParameters = new ReaderParameters(ReadingMode.Deferred)
     {
         AssemblyResolver = assemblyResolver
     };
     var module = ModuleDefinition.ReadModule(path, readerParameters);
     ObjectApprover.VerifyWithJson(SqlVarientReader.Read(module).ToList());
 }
    static FodyAssemblyPostProcessor()
    {
        try
        {
            //Debug.Log( "Fody processor running" );

            // Lock assemblies while they may be altered
            EditorApplication.LockReloadAssemblies();

            var assetPath = Path.GetFullPath(Application.dataPath);

            // This will hold the paths to all the assemblies that will be processed
            HashSet<string> assemblyPaths = new HashSet<string>();
            // This will hold the search directories for the resolver
            HashSet<string> assemblySearchDirectories = new HashSet<string>();

            // Add all assemblies in the project to be processed, and add their directory to
            // the resolver search directories.
            foreach( System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() )
            {
                // Only process assemblies which are in the project
                if( assembly.Location.Replace( '\\', '/' ).StartsWith( Application.dataPath.Substring( 0, Application.dataPath.Length - 7 ) )  &&
                    !Path.GetFullPath(assembly.Location).StartsWith(assetPath)) //but not in the assets folder
                {
                    assemblyPaths.Add( assembly.Location );
                }
                // But always add the assembly folder to the search directories
                assemblySearchDirectories.Add( Path.GetDirectoryName( assembly.Location ) );
            }

            // Create resolver
            var assemblyResolver = new DefaultAssemblyResolver();
            // Add all directories found in the project folder
            foreach( String searchDirectory in assemblySearchDirectories )
            {
                assemblyResolver.AddSearchDirectory( searchDirectory );
            }
            // Add path to the Unity managed dlls
            assemblyResolver.AddSearchDirectory( Path.GetDirectoryName( EditorApplication.applicationPath ) + "/Data/Managed" );

            ProcessAssembliesIn(assemblyPaths, assemblyResolver);

            // Unlock now that we're done
            EditorApplication.UnlockReloadAssemblies();
        }
        catch( Exception e )
        {
            Debug.LogError( e );
        }

        //Debug.Log("Fody processor finished");
    }
예제 #18
0
        private static ReaderParameters CreateReaderParameters( IEnumerable<string> dirs )
        {
            var resolver = new DefaultAssemblyResolver();
            foreach( var dir in dirs )
            {
                resolver.AddSearchDirectory( dir );
            }

            return new ReaderParameters
            {
                AssemblyResolver = resolver,
            };
        }
예제 #19
0
        public static string GeneratePublicApi(Assembly assemby, Type[] includeTypes = null, bool shouldIncludeAssemblyAttributes = true)
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            var assemblyPath = assemby.Location;
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));

            var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
            var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
            {
                ReadSymbols = readSymbols,
                AssemblyResolver = assemblyResolver,
            });

            return CreatePublicApiForAssembly(asm, tr => includeTypes == null || includeTypes.Any(t => t.FullName == tr.FullName && t.Assembly.FullName == tr.Module.Assembly.FullName), shouldIncludeAssemblyAttributes);
        }
예제 #20
0
 public void Parse(string asm)
 {
     _file = new FileRef(asm, null);
     AssemblyDefinition assembly;
     if (File.Exists(_file.File))
         assembly = AssemblyDefinition.ReadAssembly(_file.File);
     else
         assembly = new DefaultAssemblyResolver().Resolve(_file.File);
     _writer.WriteFile(_file);
     assembly
         .Modules.ToList()
         .ForEach(x =>
             x.GetTypes().ToList()
             .ForEach(y => handleType(y)));
 }
        public static void ApprovePublicApi(string assemblyPath)
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));

            var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
            var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
            {
                ReadSymbols = readSymbols,
                AssemblyResolver = assemblyResolver,
            });

            var publicApi = PublicApiGenerator.CreatePublicApiForAssembly(asm);
            var writer = new ApprovalTextWriter(publicApi, "cs");
            ApprovalTests.Approvals.Verify(writer, new UnitTestFrameworkNamer(), ApprovalTests.Approvals.GetReporter());
        }
예제 #22
0
        public static void ApprovePublicApi(string assemblyPath)
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));

            var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
            var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
            {
                ReadSymbols = readSymbols,
                AssemblyResolver = assemblyResolver,
            });

            var publicApi = PublicApiGenerator.CreatePublicApiForAssembly(asm);
            publicApi.ShouldMatchApproved(c => c
                .WithFileExtension(".cs")
                .UseCallerLocation());
        }
        public void approve_public_api()
        {
            var assemblyPath = typeof(StringHumanizeExtensions).Assembly.Location;

            var assemblyResolver = new DefaultAssemblyResolver();
            assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));

            var readSymbols = File.Exists(Path.ChangeExtension(assemblyPath, ".pdb"));
            var asm = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters(ReadingMode.Deferred)
            {
                ReadSymbols = readSymbols,
                AssemblyResolver = assemblyResolver
            });

            var publicApi = PublicApiGenerator.CreatePublicApiForAssembly(asm);
            Approvals.Verify(publicApi);
        }
    public ModuleWeaverTestHelper(string inputAssembly)
    {
      BeforeAssemblyPath = Path.GetFullPath(inputAssembly);
#if (!DEBUG)
      BeforeAssemblyPath = BeforeAssemblyPath.Replace("Debug", "Release");
#endif
      AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
      var oldPdb = BeforeAssemblyPath.Replace(".dll", ".pdb");
      var newPdb = BeforeAssemblyPath.Replace(".dll", "2.pdb");
      File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
      File.Copy(oldPdb, newPdb, true);

      Errors = new List<string>();

      var assemblyResolver = new MockAssemblyResolver
      {
        Directory = Path.GetDirectoryName(BeforeAssemblyPath)
      };

      using (var symbolStream = File.OpenRead(newPdb))
      {
        var resolver = new DefaultAssemblyResolver();
        resolver.AddSearchDirectory(Directory.GetParent(BeforeAssemblyPath).FullName);

        var readerParameters = new ReaderParameters
        {
          ReadSymbols = true,
          SymbolStream = symbolStream,
          SymbolReaderProvider = new PdbReaderProvider(),
          AssemblyResolver = resolver
        };
        var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath, readerParameters);

        var weavingTask = new ModuleWeaver
        {
          ModuleDefinition = moduleDefinition,
          AssemblyResolver = assemblyResolver,
          LogError = s => Errors.Add(s)
        };

        weavingTask.Execute();
        moduleDefinition.Write(AfterAssemblyPath);
      }

      Assembly = Assembly.LoadFile(AfterAssemblyPath);
    }
예제 #25
0
        /// <summary>
        /// Returns the code for a specific algorithm.
        /// </summary>
        /// <returns>The algorithm code.</returns>
        /// <param name="algorithmType">Algorithm type.</param>
        public static MethodDeclaration GetMethodCode(Type algorithmType, out AstBuilder astBuilder, string methodName)
        {
            var resolver = new DefaultAssemblyResolver();
            resolver.AddSearchDirectory(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName);
            var parameters = new ReaderParameters
            {
                AssemblyResolver = resolver,
            };

            // Load Tychaia.ProceduralGeneration into Mono.Cecil.
            var module = AssemblyDefinition.ReadAssembly(
                Assembly.GetExecutingAssembly().Location,
                parameters).MainModule;

            // Now we have a reference to the method we want to decompile.
            TypeDefinition cecilType;
            MethodDefinition processCell;
            FindMethodName(module, algorithmType, methodName, out processCell, out cecilType);
            var decompilerSettings = new DecompilerSettings();
            astBuilder =
                new AstBuilder(new DecompilerContext(module) { CurrentType = cecilType, Settings = decompilerSettings });
            astBuilder.AddMethod(processCell);
            try
            {
                astBuilder.RunTransformations();
            }
            catch (AssemblyResolutionException ex)
            {
                throw new Exception(
                    "Unable to decompile algorithm source code for " + algorithmType.FullName + ".",
                    ex);
            }

            astBuilder.CompilationUnit.AcceptVisitor(new InsertParenthesesVisitor
            {
                InsertParenthesesForReadability = true
            });

            // Return.
            return
                astBuilder.CompilationUnit.Members.Where(v => v is MethodDeclaration).Cast<MethodDeclaration>().First();
        }
예제 #26
0
        private static ReflectionModel BuildReflectionModel(IEnumerable<string> paths)
        {
            var assemblyPaths = FilterFilesOnExtension(paths, ".dll").ToArray();
            var definitions = new List<AssemblyDefinition>();

            var resolver = new DefaultAssemblyResolver();
            foreach (var assemblyPath in assemblyPaths)
            {
                resolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));
            }
            var parameters = new ReaderParameters {
                AssemblyResolver = resolver,
            };

            foreach (var assemblyPath in assemblyPaths)
            {
                definitions.Add(AssemblyDefinition.ReadAssembly(assemblyPath, parameters));
            }
            return ReflectionModelBuilder.Build(definitions);
        }
예제 #27
0
파일: ivt-detect.cs 프로젝트: snorp/moon
	static void Check (string filename)
	{
		var resolver = new DefaultAssemblyResolver ();
		resolver.AddSearchDirectory (RuntimePath);
		resolver.AddSearchDirectory (SdkClientPath);

		AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly (filename, new ReaderParameters { AssemblyResolver = resolver });

		foreach (ModuleDefinition module in assembly.Modules) {
			foreach (TypeDefinition type in module.GetAllTypes ()) {
				foreach (MethodDefinition md in type.Methods) {
					Check (assembly, md);
				}
			}
		}

		Console.WriteLine ("# Assembly: {0} [{1} items]", assembly, internals.Count);
		internals.Sort ();
		foreach (string s in internals)
			Console.WriteLine (s);
		Console.WriteLine ();

		internals.Clear ();
	}
예제 #28
0
        private static ReflectionModel BuildReflectionModel(IDictionary<string, IDocumentationMetadata> paths)
        {
            var items = FilterFilesOnExtension(paths, ".dll");
            var definitions = new Dictionary<AssemblyDefinition, IDocumentationMetadata>();

            var resolver = new DefaultAssemblyResolver();
            foreach (var item in items)
            {
                resolver.AddSearchDirectory(Path.GetDirectoryName(item.Key));
            }

            var parameters = new ReaderParameters
            {
                AssemblyResolver = resolver,
            };

            foreach (var item in items)
            {
                var definition = AssemblyDefinition.ReadAssembly(item.Key, parameters);
                definitions.Add(definition, item.Value);
            }

            return ReflectionModelBuilder.Build(definitions);
        }
예제 #29
0
 public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies)
 {
     string str = "tmplink.xml";
     usedClasses.SynchronizeClasses();
     using (TextWriter writer = new StreamWriter(Path.Combine(librariesFolder, str)))
     {
         writer.WriteLine("<linker>");
         writer.WriteLine("<assembly fullname=\"UnityEngine\">");
         foreach (string str2 in usedClasses.GetAllManagedClassesAsString())
         {
             writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str2, usedClasses.GetRetentionLevel(str2)));
         }
         writer.WriteLine("</assembly>");
         DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
         resolver.AddSearchDirectory(librariesFolder);
         foreach (string str3 in allAssemblies)
         {
             ReaderParameters parameters = new ReaderParameters {
                 AssemblyResolver = resolver
             };
             AssemblyDefinition definition = resolver.Resolve(Path.GetFileNameWithoutExtension(str3), parameters);
             writer.WriteLine("<assembly fullname=\"{0}\">", definition.Name.Name);
             if (definition.Name.Name.StartsWith("UnityEngine."))
             {
                 foreach (string str4 in usedClasses.GetAllManagedClassesAsString())
                 {
                     writer.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", str4, usedClasses.GetRetentionLevel(str4)));
                 }
             }
             GenerateBlackListTypeXML(writer, definition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
             writer.WriteLine("</assembly>");
         }
         writer.WriteLine("</linker>");
     }
     return str;
 }
예제 #30
0
        static Configuration ParseCommandLine(
            IEnumerable<string> arguments, List<BuildGroup> buildGroups, 
            Dictionary<string, IProfile> profiles
        )
        {
            var baseConfig = new Configuration();
            var commandLineConfig = new Configuration();
            IProfile defaultProfile = new Profiles.Default();
            var profileAssemblies = new List<string>();
            bool[] autoloadProfiles = new bool[] { true };
            string[] newDefaultProfile = new string[] { null };
            List<string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    {"o=|out=",
                        "Specifies the output directory for generated javascript and manifests.",
                        (path) => commandLineConfig.OutputDirectory = Path.GetFullPath(path) },
                    {"nac|noautoconfig",
                        "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                        (b) => commandLineConfig.AutoLoadConfigFiles = b == null },
                    {"nt|nothreads",
                        "Suppresses use of multiple threads to speed up the translation process.",
                        (b) => commandLineConfig.UseThreads = b == null },
                    {"sbc|suppressbugcheck",
                        "Suppresses JSIL bug checks that detect bugs in .NET runtimes and standard libraries.",
                        (b) => commandLineConfig.RunBugChecks = b == null },

                    "Solution Builder options",
                    {"configuration=",
                        "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                        (v) => commandLineConfig.SolutionBuilder.Configuration = v },
                    {"platform=",
                        "When building one or more solution files, specifies the build platform to use (like 'x86').",
                        (v) => commandLineConfig.SolutionBuilder.Platform = v },
                    {"target=",
                        "When building one or more solution files, specifies the build target to use (like 'Build'). The default is 'Build'.",
                        (v) => commandLineConfig.SolutionBuilder.Target = v },
                    {"logVerbosity=",
                        "When building one or more solution files, specifies the level of log verbosity. Valid options are 'Quiet', 'Minimal', 'Normal', 'Detailed', and 'Diagnostic'.",
                        (v) => commandLineConfig.SolutionBuilder.LogVerbosity = v },

                    "Assembly options",
                    {"p=|proxy=",
                        "Loads a type proxy assembly to provide type information for the translator.",
                        (name) => commandLineConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    {"i=|ignore=",
                        "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                        (regex) => commandLineConfig.Assemblies.Ignored.Add(regex) },
                    {"s=|stub=",
                        "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                        "Stubbing forces all methods to be externals.",
                        (regex) => commandLineConfig.Assemblies.Stubbed.Add(regex) },
                    {"nd|nodeps",
                        "Suppresses the automatic loading and translation of assembly dependencies.",
                        (b) => commandLineConfig.IncludeDependencies = b == null},
                    {"nodefaults",
                        "Suppresses the default list of stubbed assemblies.",
                        (b) => commandLineConfig.ApplyDefaults = b == null},
                    {"nolocal",
                        "Disables using local proxy types from translated assemblies.",
                        (b) => commandLineConfig.UseLocalProxies = b == null},
                    {"fv=|frameworkVersion=",
                        "Specifies the version of the .NET framework proxies to use. " +
                        "This ensures that correct type information is provided (as different versions of the framework use different standard libraries). " +
                        "The only accepted value is currently '4.0'. Default: '4.0'",
                        (fv) => commandLineConfig.FrameworkVersion = double.Parse(fv)},

                    "Profile options",
                    {"nap|noautoloadprofiles",
                        "Disables automatic loading of profile assemblies from the compiler directory.",
                        (b) => autoloadProfiles[0] = (b == null)},
                    {"pa=|profileAssembly=",
                        "Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
                        (filename) => profileAssemblies.Add(filename)},
                    {"dp=|defaultProfile=",
                        "Overrides the default profile to use for projects by specifying the name of the new default profile.",
                        (profileName) => newDefaultProfile[0] = profileName},

                    "CodeGenerator options",
                    {"os",
                        "Suppresses struct copy elimination.",
                        (b) => commandLineConfig.CodeGenerator.EliminateStructCopies = b == null},
                    {"ot",
                        "Suppresses temporary local variable elimination.",
                        (b) => commandLineConfig.CodeGenerator.EliminateTemporaries = b == null},
                    {"oo",
                        "Suppresses simplification of operator expressions and special method calls.",
                        (b) => commandLineConfig.CodeGenerator.SimplifyOperators = b == null},
                    {"ol",
                        "Suppresses simplification of loop blocks.",
                        (b) => commandLineConfig.CodeGenerator.SimplifyLoops = b == null},
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0) {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return null;
                }
            }

            {
                if (autoloadProfiles[0])
                    profileAssemblies.AddRange(Directory.GetFiles(
                        GetJSILDirectory(),
                        "JSIL.Profiles.*.dll"
                    ));

                foreach (var filename in profileAssemblies) {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        var assembly = Assembly.LoadFile(fullPath);

                        foreach (var type in assembly.GetTypes()) {
                            if (
                                type.FindInterfaces(
                                    (interfaceType, o) => interfaceType == (Type)o, typeof(IProfile)
                                ).Length != 1
                            )
                                continue;

                            var ctor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance,
                                null, System.Type.EmptyTypes, null
                            );
                            var profileInstance = (IProfile)ctor.Invoke(new object[0]);

                            profiles.Add(type.Name, profileInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
                    }
                }
            }

            commandLineConfig = MergeConfigurations(
                commandLineConfig,
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select LoadConfiguration(fn)).ToArray()
            );

            if (commandLineConfig.ApplyDefaults.GetValueOrDefault(true)) {
                baseConfig = MergeConfigurations(
                    LoadConfiguration(Path.Combine(
                        GetJSILDirectory(),
                        "defaults.jsilconfig"
                    )),
                    baseConfig
                );
            }

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                    ) {

                var solutionFullPath = Path.GetFullPath(solution);
                var solutionDir = Path.GetDirectoryName(solutionFullPath);

                if ((solutionDir == null) || (solutionFullPath == null)) {
                    Console.Error.WriteLine("// Can't process solution '{0}' - path seems malformed", solution);
                    continue;
                }

                var solutionConfigPath = Path.Combine(
                    solutionDir,
                    String.Format("{0}.jsilconfig", Path.GetFileName(solutionFullPath))
                );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] {  };

                var mergedSolutionConfig = MergeConfigurations(baseConfig, solutionConfig);
                var config = MergeConfigurations(mergedSolutionConfig, commandLineConfig);
                var buildStarted = DateTime.UtcNow.Ticks;

                var buildResult = SolutionBuilder.SolutionBuilder.Build(
                    solutionFullPath,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform,
                    config.SolutionBuilder.Target ?? "Build",
                    config.SolutionBuilder.LogVerbosity
                );

                var jss = new JavaScriptSerializer();
                jss.MaxJsonLength = (1024 * 1024) * 64;
                var buildResultJson = jss.Serialize(buildResult);
                buildResult = jss.Deserialize<SolutionBuilder.BuildResult>(buildResultJson);

                var buildEnded = DateTime.UtcNow.Ticks;

                IProfile profile = defaultProfile;

                foreach (var candidateProfile in profiles.Values) {
                    if (!candidateProfile.IsAppropriateForSolution(buildResult))
                        continue;

                    Console.Error.WriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
                    profile = candidateProfile;
                    break;
                }

                var localVariables = config.ApplyTo(new VariableSet());
                localVariables["SolutionDirectory"] = () => solutionDir;

                var processStarted = DateTime.UtcNow.Ticks;
                profile.ProcessBuildResult(
                    localVariables,
                    profile.GetConfiguration(config),
                    buildResult
                );
                var processEnded = DateTime.UtcNow.Ticks;

                {
                    var logPath = localVariables.ExpandPath(String.Format(
                        "%outputdirectory%/{0}.buildlog", Path.GetFileName(solution)
                    ), false);

                    if (!Directory.Exists(Path.GetDirectoryName(logPath)))
                        Directory.CreateDirectory(Path.GetDirectoryName(logPath));

                    using (var logWriter = new StreamWriter(logPath, false, Encoding.UTF8)) {
                        logWriter.WriteLine(
                            "Build of solution '{0}' processed {1} task(s) and produced {2} result file(s):",
                            solution, buildResult.AllItemsBuilt.Length, buildResult.OutputFiles.Length
                        );

                        foreach (var of in buildResult.OutputFiles)
                            logWriter.WriteLine(of);

                        logWriter.WriteLine("----");
                        logWriter.WriteLine("Elapsed build time: {0:0000.0} second(s).", TimeSpan.FromTicks(buildEnded - buildStarted).TotalSeconds);
                        logWriter.WriteLine("Selected profile '{0}' to process results of this build.", profile.GetType().Name);
                        logWriter.WriteLine("Elapsed processing time: {0:0000.0} second(s).", TimeSpan.FromTicks(processEnded - processStarted).TotalSeconds);
                    }
                }

                var outputFiles = buildResult.OutputFiles.Concat(
                    (from eo in config.SolutionBuilder.ExtraOutputs
                     let expanded = localVariables.ExpandPath(eo, true)
                     select expanded)
                ).ToArray();

                if (outputFiles.Length > 0) {
                    buildGroups.Add(new BuildGroup {
                        BaseConfiguration = mergedSolutionConfig,
                        BaseVariables = localVariables,
                        FilesToBuild = outputFiles,
                        Profile = profile,
                    });
                }
            }

            var assemblyNames = (from fn in filenames
                                 where Path.GetExtension(fn).Contains(",") ||
                                    Path.GetExtension(fn).Contains(" ") ||
                                    Path.GetExtension(fn).Contains("=")
                                 select fn).ToArray();

            var resolver = new Mono.Cecil.DefaultAssemblyResolver();
            var metaResolver = new CachingMetadataResolver(resolver);
            var resolverParameters = new ReaderParameters {
                AssemblyResolver = resolver,
                MetadataResolver = metaResolver,
                ReadSymbols = false,
                ReadingMode = ReadingMode.Deferred,
            };
            var resolvedAssemblyPaths = (from an in assemblyNames
                                      let asm = resolver.Resolve(an, resolverParameters)
                                      where asm != null
                                      select asm.MainModule.FullyQualifiedName).ToArray();

            var mainGroup = (from fn in filenames
                             where
                                 (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn)
                             .Concat(resolvedAssemblyPaths)
                             .ToArray();

            if (mainGroup.Length > 0) {
                var variables = commandLineConfig.ApplyTo(new VariableSet());

                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = baseConfig,
                    BaseVariables = variables,
                    FilesToBuild = mainGroup,
                    Profile = defaultProfile
                });
            }

            return commandLineConfig;
        }
예제 #31
0
파일: detect-sc.cs 프로젝트: snorp/moon
	static int Main (string [] args)
	{
		int input;
		string output;

		switch (args.Length) {
		case 0:
			Console.WriteLine ("Usage: detect-sc input-dir [input-dir [...]] [output-dir]");
			return 1;
		case 1:
			output = args [0];
			input = 1;
			break;
		default:
			input = args.Length - 1;
			output = args [input];
			break;
		}

		foreach (string assembly in PlatformCode.Assemblies) {
			Console.Write ("{0}.dll:", assembly);

			string fullpath = null;
			for (int i = 0; i < input; i++) {
				fullpath = Path.Combine (args [i], assembly) + ".dll";
				if (File.Exists (fullpath))
					break;

				fullpath = null;
			}

			if (fullpath == null) {
				Console.WriteLine (" NOT FOUND!", assembly);
				continue;
			}

			var resolver = new DefaultAssemblyResolver ();
			resolver.AddSearchDirectory (args [0]);

			AssemblyDefinition ad = AssemblyDefinition.ReadAssembly (fullpath, new ReaderParameters { AssemblyResolver = resolver });
			ProcessAssembly (ad);

			string outfile = Path.Combine (output, assembly) + ".auto.sc";
			using (StreamWriter sw = new StreamWriter (outfile)) {
				sw.WriteLine ("# [SecurityCritical] needed to execute code inside '{0}'.", ad.Name.FullName);
				sw.WriteLine ("# {0} methods needs to be decorated.", methods.Count);
				sw.WriteLine ();
				Console.Write (" {0} methods", methods.Count);
				foreach (KeyValuePair<string, string> kvp in methods) {
					sw.WriteLine ("# {0}", kvp.Value);
					sw.WriteLine ("+SC-M: {0}", kvp.Key);
					sw.WriteLine ();
				}
			}

			methods.Clear ();
			Console.WriteLine (".");
		}

		return 0;
	}
예제 #32
0
        private ReaderParameters GetReaderParameters()
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            var assemblyLocation = Path.GetDirectoryName(_assemblyLocation);
            assemblyResolver.AddSearchDirectory(assemblyLocation);

            var readerParameters = new ReaderParameters { AssemblyResolver = assemblyResolver };

            if (!File.Exists(PdbName)) return readerParameters;

            var symbolReaderProvider = new PdbReaderProvider();
            readerParameters.SymbolReaderProvider = symbolReaderProvider;
            readerParameters.ReadSymbols = _mode == PatchMode.Debug;
            readerParameters.ReadingMode = ReadingMode.Deferred;

            return readerParameters;
        }
예제 #33
0
        static Configuration ParseCommandLine(
            IEnumerable <string> arguments, List <BuildGroup> buildGroups,
            Dictionary <string, IProfile> profiles, Dictionary <string, IAnalyzer> analyzers,
            AssemblyCache assemblyCache
            )
        {
            var      baseConfig         = new Configuration();
            var      commandLineConfig  = new Configuration();
            IProfile defaultProfile     = new Profiles.Default();
            var      profileAssemblies  = new List <string>();
            var      analyzerAssemblies = new List <string>();

            bool[]        autoloadProfiles  = new bool[] { true };
            bool[]        autoloadAnalyzers = new bool[] { true };
            string[]      newDefaultProfile = new string[] { null };
            List <string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    { "o=|out=",
                      "Specifies the output directory for generated javascript and manifests.",
                      (path) => commandLineConfig.OutputDirectory = Path.GetFullPath(path) },
                    { "nac|noautoconfig",
                      "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                      (b) => commandLineConfig.AutoLoadConfigFiles = b == null },
                    { "nt|nothreads",
                      "Suppresses use of multiple threads to speed up the translation process.",
                      (b) => commandLineConfig.UseThreads = b == null },
                    { "sbc|suppressbugcheck",
                      "Suppresses JSIL bug checks that detect bugs in .NET runtimes and standard libraries.",
                      (b) => commandLineConfig.RunBugChecks = b == null },

                    "Solution Builder options",
                    { "configuration=",
                      "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                      (v) => commandLineConfig.SolutionBuilder.Configuration = v },
                    { "platform=",
                      "When building one or more solution files, specifies the build platform to use (like 'x86').",
                      (v) => commandLineConfig.SolutionBuilder.Platform = v },
                    { "target=",
                      "When building one or more solution files, specifies the build target to use (like 'Build'). The default is 'Build'.",
                      (v) => commandLineConfig.SolutionBuilder.Target = v },
                    { "logVerbosity=",
                      "When building one or more solution files, specifies the level of log verbosity. Valid options are 'Quiet', 'Minimal', 'Normal', 'Detailed', and 'Diagnostic'.",
                      (v) => commandLineConfig.SolutionBuilder.LogVerbosity = v },

                    "Assembly options",
                    { "p=|proxy=",
                      "Loads a type proxy assembly to provide type information for the translator.",
                      (name) => commandLineConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    { "i=|ignore=",
                      "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                      (regex) => commandLineConfig.Assemblies.Ignored.Add(regex) },
                    { "s=|stub=",
                      "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                      "Stubbing forces all methods to be externals.",
                      (regex) => commandLineConfig.Assemblies.Stubbed.Add(regex) },
                    { "nd|nodeps",
                      "Suppresses the automatic loading and translation of assembly dependencies.",
                      (b) => commandLineConfig.IncludeDependencies = b == null },
                    { "nodefaults",
                      "Suppresses the default list of stubbed assemblies.",
                      (b) => commandLineConfig.ApplyDefaults = b == null },
                    { "nolocal",
                      "Disables using local proxy types from translated assemblies.",
                      (b) => commandLineConfig.UseLocalProxies = b == null },
                    { "fv=|frameworkVersion=",
                      "Specifies the version of the .NET framework proxies to use. " +
                      "This ensures that correct type information is provided (as different versions of the framework use different standard libraries). " +
                      "The only accepted value is currently '4.0'. Default: '4.0'",
                      (fv) => commandLineConfig.FrameworkVersion = double.Parse(fv) },

                    "Profile options",
                    { "nap|noautoloadprofiles",
                      "Disables automatic loading of profile assemblies from the compiler directory.",
                      (b) => autoloadProfiles[0] = (b == null) },
                    { "pa=|profileAssembly=",
                      "Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
                      profileAssemblies.Add },
                    { "dp=|defaultProfile=",
                      "Overrides the default profile to use for projects by specifying the name of the new default profile.",
                      (profileName) => newDefaultProfile[0] = profileName },

                    "CodeGenerator options",
                    { "os",
                      "Suppresses struct copy elimination.",
                      (b) => commandLineConfig.CodeGenerator.EliminateStructCopies = b == null },
                    { "ot",
                      "Suppresses temporary local variable elimination.",
                      (b) => commandLineConfig.CodeGenerator.EliminateTemporaries = b == null },
                    { "oo",
                      "Suppresses simplification of operator expressions and special method calls.",
                      (b) => commandLineConfig.CodeGenerator.SimplifyOperators = b == null },
                    { "ol",
                      "Suppresses simplification of loop blocks.",
                      (b) => commandLineConfig.CodeGenerator.SimplifyLoops = b == null },
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0)
                {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return(null);
                }
            }

            {
                if (autoloadProfiles[0])
                {
                    profileAssemblies.AddRange(Directory.GetFiles(
                                                   GetJSILDirectory(),
                                                   "JSIL.Profiles.*.dll"
                                                   ));
                }

                if (autoloadAnalyzers[0])
                {
                    analyzerAssemblies.AddRange(Directory.GetFiles(
                                                    GetJSILDirectory(),
                                                    "JSIL.Analysis.*.dll"
                                                    ));
                }

                foreach (var filename in profileAssemblies)
                {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        IProfile profileInstance = CreateExtensionInstance <IProfile>(fullPath);
                        if (profileInstance != null)
                        {
                            profiles.Add(profileInstance.GetType().Name, profileInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
                    }
                }

                foreach (var filename in analyzerAssemblies)
                {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        IAnalyzer analyzerInstance = CreateExtensionInstance <IAnalyzer>(fullPath);
                        if (analyzerInstance != null)
                        {
                            analyzers.Add(analyzerInstance.GetType().Name, analyzerInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load analyzer '{0}': {1}", filename, exc);
                    }
                }
            }

            var commandLineConfigFilenames =
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select fn).ToArray();

            // Fail early on nonexistent configuration files
            foreach (var filename in commandLineConfigFilenames)
            {
                if (!File.Exists(filename))
                {
                    throw new FileNotFoundException(filename);
                }
            }

            commandLineConfig = MergeConfigurations(
                commandLineConfig,
                (from fn in commandLineConfigFilenames
                 select LoadConfiguration(fn)).ToArray()
                );

            if (commandLineConfig.ApplyDefaults.GetValueOrDefault(true))
            {
                baseConfig = MergeConfigurations(
                    LoadConfiguration(Path.Combine(
                                          GetJSILDirectory(),
                                          "defaults.jsilconfig"
                                          )),
                    baseConfig
                    );
            }

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                     )
            {
                var solutionFullPath = Path.GetFullPath(solution);
                var solutionDir      = Path.GetDirectoryName(solutionFullPath);

                if (solutionDir == null)
                {
                    Console.Error.WriteLine("// Can't process solution '{0}' - path seems malformed", solution);
                    continue;
                }

                // Fail early if a solution file is missing
                if (!File.Exists(solutionFullPath))
                {
                    throw new FileNotFoundException(solutionFullPath);
                }

                var solutionConfigPath = Path.Combine(
                    solutionDir,
                    String.Format("{0}.jsilconfig", Path.GetFileName(solutionFullPath))
                    );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] {  };

                var mergedSolutionConfig = MergeConfigurations(baseConfig, solutionConfig);
                var config       = MergeConfigurations(mergedSolutionConfig, commandLineConfig);
                var buildStarted = DateTime.UtcNow.Ticks;

                var buildResult = SolutionBuilder.SolutionBuilder.Build(
                    solutionFullPath,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform,
                    config.SolutionBuilder.Target ?? "Build",
                    config.SolutionBuilder.LogVerbosity
                    );

                var jss = new JavaScriptSerializer {
                    MaxJsonLength = (1024 * 1024) * 64
                };

                var buildResultJson = jss.Serialize(buildResult);
                buildResult = jss.Deserialize <SolutionBuilder.BuildResult>(buildResultJson);

                var buildEnded = DateTime.UtcNow.Ticks;

                IProfile profile = defaultProfile;

                foreach (var candidateProfile in profiles.Values)
                {
                    if (!candidateProfile.IsAppropriateForSolution(buildResult))
                    {
                        continue;
                    }

                    Console.Error.WriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
                    profile = candidateProfile;
                    break;
                }

                var localVariables = config.ApplyTo(new VariableSet());
                localVariables["SolutionDirectory"] = () => solutionDir;

                // HACK to let you use assemblyname/etc when copying output files.
                var buildResultAssembly =
                    buildResult.OutputFiles.FirstOrDefault((fn) => Path.GetExtension(fn) == ".exe") ??
                    buildResult.OutputFiles.FirstOrDefault((fn) => Path.GetExtension(fn) == ".dll");

                if (buildResultAssembly != null)
                {
                    localVariables.SetAssemblyPath(buildResultAssembly);
                }

                var processStarted = DateTime.UtcNow.Ticks;
                profile.ProcessBuildResult(
                    localVariables,
                    profile.GetConfiguration(config),
                    buildResult
                    );
                var processEnded = DateTime.UtcNow.Ticks;

                {
                    var logPath = localVariables.ExpandPath(String.Format(
                                                                "%outputdirectory%/{0}.buildlog", Path.GetFileName(solution)
                                                                ), false);

                    if (!Directory.Exists(Path.GetDirectoryName(logPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(logPath));
                    }

                    using (var logWriter = new StreamWriter(logPath, false, Encoding.UTF8)) {
                        logWriter.WriteLine(
                            "Build of solution '{0}' processed {1} task(s) and produced {2} result file(s):",
                            solution, buildResult.AllItemsBuilt.Length, buildResult.OutputFiles.Length
                            );

                        foreach (var of in buildResult.OutputFiles)
                        {
                            logWriter.WriteLine(of);
                        }

                        logWriter.WriteLine("----");
                        logWriter.WriteLine("Elapsed build time: {0:0000.0} second(s).", TimeSpan.FromTicks(buildEnded - buildStarted).TotalSeconds);
                        logWriter.WriteLine("Selected profile '{0}' to process results of this build.", profile.GetType().Name);
                        logWriter.WriteLine("Elapsed processing time: {0:0000.0} second(s).", TimeSpan.FromTicks(processEnded - processStarted).TotalSeconds);
                    }
                }

                var outputFiles = buildResult.OutputFiles.Concat(
                    (from eo in config.SolutionBuilder.ExtraOutputs
                     let expanded = localVariables.ExpandPath(eo, true)
                                    select expanded)
                    ).ToArray();

                if (outputFiles.Length > 0)
                {
                    var sa = new HashSet <string>();

                    var group = new BuildGroup {
                        BaseConfiguration = mergedSolutionConfig,
                        BaseVariables     = localVariables,
                        FilesToBuild      = PurgeDuplicateFilesFromBuildGroup(outputFiles, assemblyCache, sa),
                        Profile           = profile,
                    };
                    group.SkippedAssemblies = sa.ToArray();

                    buildGroups.Add(group);
                }
            }

            var assemblyNames = (from fn in filenames
                                 where Path.GetExtension(fn).Contains(",") ||
                                 Path.GetExtension(fn).Contains(" ") ||
                                 Path.GetExtension(fn).Contains("=")
                                 select fn).ToArray();

            var resolver           = new Mono.Cecil.DefaultAssemblyResolver();
            var metaResolver       = new CachingMetadataResolver(resolver);
            var resolverParameters = new ReaderParameters {
                AssemblyResolver = resolver,
                MetadataResolver = metaResolver,
                ReadSymbols      = false,
                ReadingMode      = ReadingMode.Deferred,
            };
            var resolvedAssemblyPaths = (from an in assemblyNames
                                         let asm = resolver.Resolve(an, resolverParameters)
                                                   where asm != null
                                                   select asm.MainModule.FullyQualifiedName).ToArray();

            var mainGroup = (from fn in filenames
                             where
                             (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn)
                            .Concat(resolvedAssemblyPaths)
                            .ToArray();

            if (mainGroup.Length > 0)
            {
                var variables = commandLineConfig.ApplyTo(new VariableSet());

                // Fail early if any assemblies are missing
                foreach (var filename in mainGroup)
                {
                    if (!File.Exists(filename))
                    {
                        throw new FileNotFoundException(filename);
                    }
                }

                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = baseConfig,
                    BaseVariables     = variables,
                    FilesToBuild      = mainGroup,
                    Profile           = defaultProfile
                });
            }

            return(commandLineConfig);
        }
예제 #34
0
        public static AssemblyDefinition[] ToDefinitions(IEnumerable <string> assemblyLocations)
        {
            if (assemblyLocations == null || !assemblyLocations.Any())
            {
                return(new AssemblyDefinition[0]);
            }

            assemblyLocations = assemblyLocations.Select(x =>
            {
                if (!File.Exists(x))
                {
                    return(x);
                }

                var path    = Path.GetDirectoryName(x);
                var asmInfo = Path.Combine(path, "__AssemblyInfo__.ini");
                if (!File.Exists(asmInfo))
                {
                    return(x);
                }

                var content = File.ReadAllText(asmInfo, System.Text.Encoding.Unicode);
                var idx     = content.LastIndexOf("\0file:///");
                if (idx < 0)
                {
                    return(x);
                }

                var end = content.IndexOf('\0', idx + 9);
                if (end < 0)
                {
                    return(x);
                }

                var location = content.Substring(idx + 9, end - idx - 9).Replace('/', '\\');
                if (File.Exists(location))
                {
                    return(location);
                }

                return(x);
            }).ToList();

#if COREFX
            var resolver = ICSharpCode.Decompiler.UniversalAssemblyResolver
                           .LoadMainModule(assemblyLocations.First(), inMemory: true).AssemblyResolver
                           as ICSharpCode.Decompiler.UniversalAssemblyResolver;
#else
            var resolver = new Mono.Cecil.DefaultAssemblyResolver();
#endif

            foreach (var assembly in assemblyLocations)
            {
                resolver.AddSearchDirectory(Path.GetDirectoryName(assembly));
            }

            var assemblyDefinitions = new List <AssemblyDefinition>();
            foreach (var assembly in assemblyLocations)
            {
                assemblyDefinitions.Add(Mono.Cecil.AssemblyDefinition.ReadAssembly(
                                            assembly, new Mono.Cecil.ReaderParameters
                {
                    AssemblyResolver = resolver,
                    InMemory         = true
                }));
            }

            return(assemblyDefinitions.ToArray());
        }
예제 #35
0
파일: Program.cs 프로젝트: xen2/JSIL
        static void ParseCommandLine(IEnumerable <string> arguments, List <BuildGroup> buildGroups, Dictionary <string, IProfile> profiles)
        {
            var      baseConfig        = new Configuration();
            IProfile defaultProfile    = new Profiles.Default();
            var      profileAssemblies = new List <string>();

            bool[]        autoloadProfiles  = new bool[] { true };
            string[]      newDefaultProfile = new string[] { null };
            List <string> filenames;

            {
                var os = new Mono.Options.OptionSet {
                    { "o=|out=",
                      "Specifies the output directory for generated javascript and manifests. " +
                      "You can use '%configpath%' in jsilconfig files to refer to the directory containing the configuration file, and '%assemblypath%' to refer to the directory containing the assembly being translated.",
                      (path) => baseConfig.OutputDirectory = Path.GetFullPath(path) },
                    { "nac|noautoconfig",
                      "Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
                      (b) => baseConfig.AutoLoadConfigFiles = b == null },
                    { "nt|nothreads",
                      "Suppresses use of multiple threads to speed up the translation process.",
                      (b) => baseConfig.UseThreads = b == null },

                    "Solution Builder options",
                    { "configuration=",
                      "When building one or more solution files, specifies the build configuration to use (like 'Debug').",
                      (v) => baseConfig.SolutionBuilder.Configuration = v },
                    { "platform=",
                      "When building one or more solution files, specifies the build platform to use (like 'x86').",
                      (v) => baseConfig.SolutionBuilder.Platform = v },
                    { "target=",
                      "When building one or more solution files, specifies the build target to use (like 'Build'). The default is 'Build'.",
                      (v) => baseConfig.SolutionBuilder.Target = v },
                    { "logVerbosity=",
                      "When building one or more solution files, specifies the level of log verbosity. Valid options are 'Quiet', 'Minimal', 'Normal', 'Detailed', and 'Diagnostic'.",
                      (v) => baseConfig.SolutionBuilder.LogVerbosity = v },

                    "Assembly options",
                    { "p=|proxy=",
                      "Loads a type proxy assembly to provide type information for the translator.",
                      (name) => baseConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
                    { "i=|ignore=",
                      "Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
                      (regex) => baseConfig.Assemblies.Ignored.Add(regex) },
                    { "s=|stub=",
                      "Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
                      "Stubbing forces all methods to be externals.",
                      (regex) => baseConfig.Assemblies.Stubbed.Add(regex) },
                    { "nd|nodeps",
                      "Suppresses the automatic loading and translation of assembly dependencies.",
                      (b) => baseConfig.IncludeDependencies = b == null },
                    { "nodefaults",
                      "Suppresses the default list of stubbed assemblies.",
                      (b) => baseConfig.ApplyDefaults = b == null },
                    { "nolocal",
                      "Disables using local proxy types from translated assemblies.",
                      (b) => baseConfig.UseLocalProxies = b == null },
                    { "fv=|frameworkVersion=",
                      "Specifies the version of the .NET framework proxies to use. " +
                      "This ensures that correct type information is provided (as 3.5 and 4.0 use different standard libraries). " +
                      "Accepted values are '3.5' and '4.0'. Default: '4.0'",
                      (fv) => baseConfig.FrameworkVersion = double.Parse(fv) },

                    "Profile options",
                    { "nap|noautoloadprofiles",
                      "Disables automatic loading of profile assemblies from the compiler directory.",
                      (b) => autoloadProfiles[0] = (b == null) },
                    { "pa=|profileAssembly=",
                      "Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
                      (filename) => profileAssemblies.Add(filename) },
                    { "dp=|defaultProfile=",
                      "Overrides the default profile to use for projects by specifying the name of the new default profile..",
                      (profileName) => newDefaultProfile[0] = profileName },

                    "Optimizer options",
                    { "os",
                      "Suppresses struct copy elimination.",
                      (b) => baseConfig.Optimizer.EliminateStructCopies = b == null },
                    { "ot",
                      "Suppresses temporary local variable elimination.",
                      (b) => baseConfig.Optimizer.EliminateTemporaries = b == null },
                    { "oo",
                      "Suppresses simplification of operator expressions and special method calls.",
                      (b) => baseConfig.Optimizer.SimplifyOperators = b == null },
                    { "ol",
                      "Suppresses simplification of loop blocks.",
                      (b) => baseConfig.Optimizer.SimplifyLoops = b == null },
                };

                filenames = os.Parse(arguments);

                if (filenames.Count == 0)
                {
                    var asmName = Assembly.GetExecutingAssembly().GetName();
                    Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
                    Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
                    Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
                    Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");

                    os.WriteOptionDescriptions(Console.Out);

                    return;
                }
            }

            {
                if (autoloadProfiles[0])
                {
                    profileAssemblies.AddRange(Directory.GetFiles(".", "JSIL.Profiles.*.dll"));
                }

                foreach (var filename in profileAssemblies)
                {
                    var fullPath = Path.GetFullPath(filename);

                    try {
                        var assembly = Assembly.LoadFile(fullPath);

                        foreach (var type in assembly.GetTypes())
                        {
                            if (
                                type.FindInterfaces(
                                    (interfaceType, o) => interfaceType == (Type)o, typeof(IProfile)
                                    ).Length != 1
                                )
                            {
                                continue;
                            }

                            var ctor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance,
                                null, System.Type.EmptyTypes, null
                                );
                            var profileInstance = (IProfile)ctor.Invoke(new object[0]);

                            profiles.Add(type.Name, profileInstance);
                        }
                    } catch (Exception exc) {
                        Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
                    }
                }
            }

            baseConfig = MergeConfigurations(
                baseConfig,
                (from fn in filenames
                 where Path.GetExtension(fn) == ".jsilconfig"
                 select LoadConfiguration(fn)).ToArray()
                );

            foreach (var solution in
                     (from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
                     )
            {
                var solutionConfigPath = Path.Combine(
                    Path.GetDirectoryName(solution),
                    String.Format("{0}.jsilconfig", Path.GetFileName(solution))
                    );
                var solutionConfig = File.Exists(solutionConfigPath)
                    ? new Configuration[] { LoadConfiguration(solutionConfigPath) }
                    : new Configuration[] { };

                var config      = MergeConfigurations(baseConfig, solutionConfig);
                var buildResult = SolutionBuilder.Build(
                    solution,
                    config.SolutionBuilder.Configuration,
                    config.SolutionBuilder.Platform,
                    config.SolutionBuilder.Target ?? "Build"
                    );

                IProfile profile = defaultProfile;

                foreach (var candidateProfile in profiles.Values)
                {
                    if (!candidateProfile.IsAppropriateForSolution(buildResult))
                    {
                        continue;
                    }

                    Console.Error.WriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
                    profile = candidateProfile;
                    break;
                }

                profile.ProcessBuildResult(
                    profile.GetConfiguration(config),
                    buildResult
                    );

                if (buildResult.OutputFiles.Length > 0)
                {
                    buildGroups.Add(new BuildGroup {
                        BaseConfiguration = config,
                        FilesToBuild      = buildResult.OutputFiles,
                        Profile           = profile
                    });
                }
            }

            var assemblyNames = (from fn in filenames
                                 where Path.GetExtension(fn).Contains(",") ||
                                 Path.GetExtension(fn).Contains(" ") ||
                                 Path.GetExtension(fn).Contains("=")
                                 select fn).ToArray();

            var resolver           = new Mono.Cecil.DefaultAssemblyResolver();
            var metaResolver       = new CachingMetadataResolver(resolver);
            var resolverParameters = new ReaderParameters {
                AssemblyResolver = resolver,
                MetadataResolver = metaResolver,
                ReadSymbols      = false,
                ReadingMode      = ReadingMode.Deferred,
            };
            var resolvedAssemblyPaths = (from an in assemblyNames
                                         let asm = resolver.Resolve(an, resolverParameters)
                                                   where asm != null
                                                   select asm.MainModule.FullyQualifiedName).ToArray();

            var mainGroup = (from fn in filenames
                             where
                             (new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
                             select fn)
                            .Concat(resolvedAssemblyPaths)
                            .ToArray();

            if (mainGroup.Length > 0)
            {
                buildGroups.Add(new BuildGroup {
                    BaseConfiguration = baseConfig,
                    FilesToBuild      = mainGroup,
                    Profile           = defaultProfile
                });
            }
        }