public AssemblySet(string name, IEnumerable <string> paths, IEnumerable <string> resolverSearchPaths, IEnumerable <string> imports = null, string version = null, string id = null) { cachedResolver = cachedResolver ?? new CachedResolver(resolver); metadataResolver = metadataResolver ?? new Frameworks.MDocMetadataResolver(cachedResolver); Name = name; Version = version; Id = id; foreach (var path in paths) { assemblyPaths.Add(path); string pathName = Path.GetFileName(path); if (!assemblyPathsMap.ContainsKey(pathName)) { assemblyPathsMap.Add(pathName, true); } } // add default search paths var assemblyDirectories = paths .Where(p => p.Contains(Path.DirectorySeparatorChar)) .Select(p => Path.GetDirectoryName(p)); foreach (var searchPath in resolverSearchPaths.Union(assemblyDirectories)) { assemblySearchPaths.Add(searchPath); } char oppositeSeparator = Path.DirectorySeparatorChar == '/' ? '\\' : '/'; Func <string, string> sanitize = p => p.Replace(oppositeSeparator, Path.DirectorySeparatorChar); foreach (var searchPath in assemblySearchPaths.Select(sanitize)) { resolver.AddSearchDirectory(searchPath); } this.importPaths = imports; if (this.importPaths != null) { this.Importers = this.importPaths.Select(p => MDocUpdater.Instance.GetImporter(p, supportsEcmaDoc: false)).ToArray(); } else { this.Importers = new DocumentationImporter[0]; } }
/// <summary>Check an assembly and return an array of violations.</summary> /// <remarks>OnlyType is used to check only the types that contain a string in the array which may be null. /// Severity is the minimum rule severity to use. IgnoreBreaks is true if we want to /// ignore rules that break binary compatibility. Note that this should only be called once: /// if you want to smoke multiple assemblies create a new AnalyzeAssembly object.</remarks> public Error[] Analyze(string imagePath, string[] onlyType, Severity severity, bool ignoreBreaks) { DBC.Assert(!m_analyzed, "Analyze can only be called once"); // TODO: would be nice to relax this, maybe add an overload to allow another assembly to be checked with the same settings m_analyzed = true; Profile.Start("AssemblyFactory"); AssemblyDefinition assemblyDef = AssemblyFactory.GetAssembly(imagePath); Profile.Stop("AssemblyFactory"); string path = Path.GetFullPath(imagePath); // need to add a cecil search directory so that it finds assemblies in the same directory as the assembly we're checking string dir = Path.GetDirectoryName(path); BaseAssemblyResolver resolver = assemblyDef.Resolver as BaseAssemblyResolver; DBC.Assert(resolver != null, "assemblyDef.Resolver isn't a BaseAssemblyResolver"); resolver.AddSearchDirectory(dir); m_symbols = new SymbolTable(); AssemblyCache cache = new AssemblyCache(m_symbols, assemblyDef, m_callback); var assembly = System.Reflection.Assembly.GetExecutingAssembly(); m_checker.LoadRules(assembly, cache, severity, ignoreBreaks); Error[] errors = DoCheckAssembly(assemblyDef, cache, onlyType); return(errors); }
private static List <MethodDefinition> GetMethodsInsideAssembly(String assemblyToLoad, bool includeMethodDefinition, Func <MethodReference, bool> condition) { string directory = Path.GetDirectoryName(assemblyToLoad); BaseAssemblyResolver resolver = (GlobalAssemblyResolver.Instance as BaseAssemblyResolver); if (!resolver.GetSearchDirectories().Contains(directory)) { resolver.AddSearchDirectory(directory); } var methods = new List <MethodDefinition>(); foreach (MethodDefinition methodDefinition in GetMethods(assemblyToLoad)) { if ((methodDefinition.HasBody || includeMethodDefinition) && (condition(methodDefinition))) { //if (includeMethodsCalled) //{ // methodsCalled.Add(MethodDetailBuilder.Create(methodDefinition, GetMethodsCalledInsideMethod(methodDefinition, condition))); //} //else //{ // methodsCalled.Add(MethodDetailBuilder.Create(methodDefinition)); //} methods.Add(methodDefinition); } } return(methods); }
public Instrumenter(params string[] searchDirectories) { foreach (string dir in searchDirectories) { _resolver.AddSearchDirectory(dir); } }
private static void AddSearchDirectories(BaseAssemblyResolver resolver) { //Add search directories based on platform if (platform == RuntimePlatform.WindowsEditor || platform == RuntimePlatform.OSXEditor) { resolver.AddSearchDirectory(Path.GetDirectoryName(typeof(UnityEngine.Object).Assembly.Location)); resolver.AddSearchDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Assets")); foreach (string directory in Directory.GetDirectories(Directory.GetCurrentDirectory(), "ModTool", SearchOption.AllDirectories)) { resolver.AddSearchDirectory(directory); } resolver.AddSearchDirectory(Directory.GetCurrentDirectory()); } if (platform == RuntimePlatform.WindowsPlayer || platform == RuntimePlatform.LinuxPlayer || platform == RuntimePlatform.OSXPlayer) { foreach (string directory in Directory.GetDirectories(Directory.GetCurrentDirectory(), "Managed", SearchOption.AllDirectories)) { resolver.AddSearchDirectory(directory); } resolver.AddSearchDirectory(Directory.GetCurrentDirectory()); } //android - extracted assemblies from apk in persistentDatapath/Assemblies if (platform == RuntimePlatform.Android) { resolver.AddSearchDirectory(Path.Combine(persistentDataPath, "Assemblies")); } }
/// <summary> /// /// </summary> /// <param name="assemblyPath"></param> /// <param name="currentPath"></param> /// <param name="savePath"></param> /// <returns></returns> public static bool BuildToFile(string assemblyPath, string currentPath, string savePath = null) { bool setSuccess = false; if (string.IsNullOrEmpty(savePath)) { savePath = assemblyPath; } string pdbFile = Path.ChangeExtension(assemblyPath, "pdb"); PdbReaderProvider readerProvider = null; PdbWriterProvider writerProvider = null; bool debug = false; if (File.Exists(pdbFile)) { debug = true; readerProvider = new PdbReaderProvider(); writerProvider = new PdbWriterProvider(); } //huhu modify reason: Support for model debugging. var ass = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters { SymbolReaderProvider = readerProvider, ReadSymbols = debug }); BaseAssemblyResolver resolver = ass.MainModule.AssemblyResolver as BaseAssemblyResolver; if (resolver != null) { resolver.AddSearchDirectory(currentPath); } foreach (TypeDefinition type in ass.MainModule.GetTypes()) { if (type.IsEnum) { continue; } setSuccess = ProcessEntityType(type, setSuccess, currentPath); } //modify reason: no model. ass.Write(savePath, new WriterParameters { SymbolWriterProvider = writerProvider, WriteSymbols = debug }); return(true); }
public bool AddAssemblyResolveDir(string dir) { if (_resolveDirs.Contains(dir) || !Directory.Exists(dir)) { return(false); } _resolveDirs.Add(dir); BaseAssemblyResolver bar = GlobalAssemblyResolver.Instance as BaseAssemblyResolver; if (bar != null) { bar.AddSearchDirectory(dir); } return(true); }
public TestCecilExtensions() { // Add location of current assembly to MonoCecil search path. assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(typeof(TestCecilExtensions).Assembly.Location)); }
public static void Main(string[] args) { Logger.onLog += onLoggerLog; Logger.showModuleNames = false; Logger.showTimestamps = false; Logger.Begin("installer.log"); asmResolver = new DefaultAssemblyResolver(); FileInfo assemblyFilePath = getAssemblyFilePath(); if (assemblyFilePath == null) { error("Couldn't find assembly"); return; } if (!canOpenFile(assemblyFilePath)) { error("Could not open file " + assemblyFilePath.FullName); } log("Found the file at " + assemblyFilePath.FullName); asmResolver.AddSearchDirectory(assemblyFilePath.Directory.FullName); string loaderFilePath = getLoaderFilePath(); if (!canOpenFile(loaderFilePath)) { error("Could not open file " + loaderFilePath); } string gamePath = assemblyFilePath.Directory.Parent.FullName; string fileName = Path.DirectorySeparatorChar + LOADER_ASSEMBLY_NAME; log("Finding files..."); if (!File.Exists(gamePath + fileName)) { File.Copy(loaderFilePath, gamePath + fileName); } loaderFilePath = gamePath + fileName; if (!canOpenFile(loaderFilePath)) { error("Could not open file " + loaderFilePath); } // Load both modules log("Loading modules..."); ModuleDefinition assemblyModule = ModuleDefinition.ReadModule(assemblyFilePath.FullName, new ReaderParameters { AssemblyResolver = asmResolver, ReadingMode = ReadingMode.Immediate }); ModuleDefinition loaderModule = ModuleDefinition.ReadModule(loaderFilePath, new ReaderParameters { AssemblyResolver = asmResolver, ReadingMode = ReadingMode.Immediate }); log("Finding loader entry point type..."); // Find loader entry point type TypeDefinition loaderEntryPointType = loaderModule.GetType(LOADER_ENTRY_POINT_TYPE); if (loaderEntryPointType == null) { error("Could not find entry point type in loader: " + LOADER_ENTRY_POINT_TYPE); } log("Injecting type import..."); loaderEntryPointType = assemblyModule.ImportReference(loaderEntryPointType).Resolve(); log("Finding loader entry point method..."); // Find loader entry point method MethodReference loaderEntryPointMethod = loaderEntryPointType.Methods.FirstOrDefault(x => x.Name == LOADER_ENTRY_POINT_METHOD ); if (loaderEntryPointMethod == null) { error("Could not find entry point method in loader: " + LOADER_ENTRY_POINT_TYPE + "." + LOADER_ENTRY_POINT_METHOD); } log("Injecting method import..."); loaderEntryPointMethod = assemblyModule.ImportReference(loaderEntryPointMethod); log("Finding game entry point..."); // Find assembly entry point type TypeDefinition assemblyEntryPointType = assemblyModule.GetType(ASSEMBLY_ENTRY_POINT_TYPE); if (assemblyEntryPointType == null) { error("Could not find entry point type in game: " + ASSEMBLY_ENTRY_POINT_TYPE); } // Find assembly entry point method MethodDefinition assemblyEntryPointMethod = assemblyEntryPointType.Methods.FirstOrDefault(x => x.Name == ASSEMBLY_ENTRY_POINT_METHOD ); if (assemblyEntryPointMethod == null || !assemblyEntryPointMethod.HasBody) { error("Could not find entry point method in game: " + ASSEMBLY_ENTRY_POINT_TYPE + "." + ASSEMBLY_ENTRY_POINT_METHOD); } log("Finding instruction..."); ILProcessor methodILProcessor = assemblyEntryPointMethod.Body.GetILProcessor(); Instruction entryPoint = methodILProcessor.Create(OpCodes.Call, loaderEntryPointMethod); // Check if the entry point has already been injected if (findMatchingInstruction(assemblyEntryPointMethod.Body.Instructions, entryPoint) != -1) { error("Entry point already found, the loader has already been installed!"); } FieldDefinition searchField = assemblyEntryPointType.Fields.Single(x => x.Name == "wasInMultiplayer"); Instruction entryPointIndicator = methodILProcessor.Create(OpCodes.Stsfld, searchField); int entryPointIndex = findMatchingInstruction(assemblyEntryPointMethod.Body.Instructions, entryPointIndicator); if (entryPointIndex < 0) { error("Could not find entry point instruction"); } log("Injecting entry point"); assemblyEntryPointMethod.Body.Instructions.Insert(entryPointIndex + 1, entryPoint); // We should insert instructions to load any arguments we need here // Temporary dll path string tmpPath = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "tmp.dll"; log("Saving to " + tmpPath); // Write assembly changes assemblyModule.Write(tmpPath); // Backup original assembly if (File.Exists(assemblyFilePath.FullName)) { log("Backing up game assembly to " + assemblyFilePath + ".old"); File.Move(assemblyFilePath.FullName, assemblyFilePath + ".old"); } // Move modified assembly log("Moving new assembly"); File.Move(tmpPath, assemblyFilePath.FullName); Logger.Info("Installer", "Installation complete\nPress any key to continue"); Console.ReadLine(); }
void InitializeResolvers(LinkedTestCaseResult linkedResult) { _originalsResolver.AddSearchDirectory(linkedResult.ExpectationsAssemblyPath.Parent.ToString()); _linkedResolver.AddSearchDirectory(linkedResult.OutputAssemblyPath.Parent.ToString()); }
static void LoadConfiguration( string[] args, out List <Regex> attributeNames, out List <string> dllFileNames, out bool parallel, out string?logFile, BaseAssemblyResolver assemblyResolver ) { attributeNames = new List <Regex>(); dllFileNames = new List <string>(); parallel = false; logFile = null; for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "-l": logFile = args[i + 1]; i++; break; case "-a": // eg: -a ./Client/Temp/StagingArea/Data/Managed/Assembly-CSharp.dll dllFileNames.Add(args[i + 1]); i += 1; break; case "-d": assemblyResolver.AddSearchDirectory(args[i + 1]); i += 1; break; case "-p": parallel = true; break; case "-x": // eg: -x ./Client/Assets/link.xml var xmlFile = args[i + 1]; if (File.Exists(xmlFile)) { try { var xml = XDocument.Load(xmlFile); var attrRoot = xml.Element("strip-attribute"); if (attrRoot == null) { throw new Exception("Can't find root <strip-attribute> tag in the XML."); } var elements = attrRoot.Elements("type").ToArray(); for (var idx = 0; idx < elements.Length; idx++) { var typeElement = elements[idx]; var regex = typeElement.Attribute("regex"); if (regex == null) { throw new Exception($"Can't find regex attribute on <type> index {idx}"); } attributeNames.Add(new Regex(regex.Value)); } } catch (Exception e) { throw new Exception($"Parsing XML file error. File={xmlFile}", e); } } else { throw new Exception($"File does not exist: {xmlFile}"); } i += 1; break; } } }
public static void Main(string[] args) { bool showHelp = false; bool listDependenciesOnly = false; foreach (var s in assemblyResolver.GetSearchDirectories()) { assemblyResolver.RemoveSearchDirectory(s); } var p = new OptionSet() { { "a|assembly-search-directory=", "add a search directory into the assembly resolver", v => assemblyResolver.AddSearchDirectory(v) }, { "d|list-dependencies-only", "output a list of detected dependencies and exit", v => listDependenciesOnly = v != null }, { "k|key-pair-file=", "resign assembly with the key pair in file (.snk)", v => LoadKeyPairFile(v) }, { "v", "increase verbosity", v => { if (v != null) { ++verbosity; } } }, { "h|help", "show this message and exit", v => showHelp = v != null }, }; if (0 == args.Length) { TryHelp(); return; } List <string> assemblies; try { assemblies = p.Parse(args); } catch (OptionException e) { Error(e.Message); TryHelp(); return; } if (showHelp) { ShowHelp(p); return; } if (0 == assemblies.Count) { Error("No assembly names were given."); TryHelp(); return; } if (0 == assemblyResolver.GetSearchDirectories().Length) { assemblyResolver.AddSearchDirectory("."); } IEnumerable <AssemblyDefinition> dependendAssemblies; try { dependendAssemblies = FindDependendAssemblies(assemblies).ToList(); } catch (Exception exception) { Error("Unable find dependend assemblies: {0}", exception.ToString()); return; } if (listDependenciesOnly) { foreach (var a in dependendAssemblies) { Console.WriteLine(a.MainModule.FullyQualifiedName); } return; } foreach (var d in ProcessAssemblies(dependendAssemblies).ToList()) { try { WriteAssembly(d); } catch (Exception exception) { Error("Unable to write assembly: {0}", exception.ToString()); continue; } } }