コード例 #1
0
ファイル: ResolveTests.cs プロジェクト: edgardozoppi/cecil
        public void ResolvePortableClassLibraryReference()
        {
            var resolver   = new DefaultAssemblyResolver();
            var parameters = new ReaderParameters {
                AssemblyResolver = resolver
            };
            var pcl = GetResourceModule("PortableClassLibrary.dll", parameters);

            foreach (var reference in pcl.AssemblyReferences)
            {
                Assert.IsTrue(reference.IsRetargetable);
                var assembly = resolver.Resolve(reference);
                Assert.IsNotNull(assembly);
                Assert.AreEqual(typeof(object).Assembly.GetName().Version, assembly.Name.Version);
            }
        }
コード例 #2
0
        private static void GetReferences(AssemblyDefinition assembly)
        {
            TypeDefinition sys_NonSerializedAttribute, sys_TypeForwardedToAttribute, sys_Type;

            sys_NonSerializedAttribute = sys_TypeForwardedToAttribute = sys_Type = null;
            foreach (ModuleDefinition module in assembly.Modules)
            {
                foreach (AssemblyNameReference reffedAssembly in module.AssemblyReferences)
                {
                    AssemblyDefinition asm = resolver.Resolve(reffedAssembly);
                    if (asm is null)
                    {
                        continue;
                    }
                    foreach (ModuleDefinition reffedModule in asm.Modules)
                    {
                        if (reffedModule.GetType(typeof(TypeForwardedToAttribute).FullName) is TypeDefinition def1)
                        {
                            sys_TypeForwardedToAttribute = def1;
                        }
                        if (reffedModule.GetType(typeof(NonSerializedAttribute).FullName) is TypeDefinition def2)
                        {
                            sys_NonSerializedAttribute = def2;
                        }
                        if (reffedModule.GetType("System", "Type") is TypeDefinition def3)
                        {
                            sys_Type = def3;
                        }
                    }
                }
            }

            if (sys_NonSerializedAttribute is null)
            {
                Console.WriteLine($"Unable to resolve type {nameof(NonSerializedAttribute)}, make sure that you are running on an assembly that is in its normal location");
            }
            if (sys_TypeForwardedToAttribute is null)
            {
                Console.WriteLine($"Unable to resolve type {nameof(TypeForwardedToAttribute)}, make sure that you are running on an assembly that is in its normal location");
            }
            if (sys_Type is null)
            {
                Console.WriteLine($"Unable to resolve type {nameof(Type)}, make sure that you are running on an assembly that is in its normal location");
            }

            system_type = sys_Type;
コード例 #3
0
        internal static IEnumerable <(IMemberDefinition member, CustomAttribute ca)> GetMemberAssertions(Type type)
        {
            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(Path.GetDirectoryName(type.Assembly.Location));
            var assembly = resolver.Resolve(new AssemblyNameReference(type.Assembly.GetName().Name, null));
            var t        = assembly.MainModule.GetType(type.Namespace + "." + type.Name);

            if (t == null)
            {
                throw new InvalidOperationException($"type {type} not found in {assembly}");
            }
            var results = new List <(IMemberDefinition, CustomAttribute)> ();

            CollectMemberAssertions(t, results);
            return(results);
        }
コード例 #4
0
        private IList <AssemblyDefinition> GetReferencedAssemblies(ModuleDefinition module)
        {
            if (module == null)
            {
                return(null);
            }

            List <AssemblyDefinition> referencedAssemblies = new List <AssemblyDefinition>();

            foreach (var assemblyNameReference in module.AssemblyReferences)
            {
                var assemblyResolver = new DefaultAssemblyResolver();
                assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(module.FileName));
                referencedAssemblies.Add(assemblyResolver.Resolve(assemblyNameReference));
            }
            return(referencedAssemblies);
        }
コード例 #5
0
            public override AssemblyDefinition Resolve(AssemblyNameReference name)
            {
                // Try first to match from the list of assemblies
                // Get all the assemblies which are matching
                var matchingAssemblies = _moduleDefinitions.Select(module => module.Assembly)
                                         .Where(assembly => name.FullName == assembly.FullName).ToList();

                if (matchingAssemblies.Any())
                {
                    // Just take the first assembly
                    Debug.Assert(matchingAssemblies.Count == 1);
                    return(matchingAssemblies.First());
                }

                // Use default resolver
                return(_defaultResolver.Resolve(name));
            }
コード例 #6
0
        public ModuleDefinition GetModule(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return(_assembly);
            }

            try
            {
                var moduleName = name.ToLower().Replace(".dll", "").Replace(".exe", "");
                var assembly   = _resolver.Resolve(new AssemblyNameDefinition(moduleName, new Version(0, 0)));
                return(assembly?.MainModule);
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #7
0
        public override AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            Console.WriteLine(name.ToString());
            AssemblyDefinition assembly = null;

            try { assembly = m_assemblyResolver.Resolve(name); } catch (AssemblyResolutionException) {
                foreach (string assPath in m_assemblyPaths)
                {
                    string [] libraries  = Directory.GetFiles(assPath, "*.dll", SearchOption.AllDirectories);
                    string    missingLib = libraries.Where(lib => lib.Contains(name.Name)).SingleOrDefault();
                    Console.WriteLine(missingLib != null ? "found" : "not found");
                    if (missingLib != null)
                    {
                        return(AssemblyDefinition.ReadAssembly(missingLib));
                    }
                }
            }

            return(assembly);
        }
コード例 #8
0
ファイル: AopTests.cs プロジェクト: aniongithub/Cilador
        public void OneTimeSetUp()
        {
            using (var resolver = new DefaultAssemblyResolver())
                using (var targetAssembly = resolver.Resolve(AssemblyNameReference.Parse("Cilador.TestAopTarget"), new ReaderParameters {
                    ReadWrite = true
                }))
                {
                    var loom        = new Loom();
                    var graphGetter = new CilGraphGetter();

                    using (var runWithoutReplacementDecoration = new ActionDecorator <string[]>(resolver, graphGetter, RunWithoutReplacementDecoration, name => $"{name}_Decorated"))
                        using (var runWithReplacementDecorator = new ActionDecorator <string>(resolver, graphGetter, RunWithReplacementDecorator))
                        {
                            loom.WeavableConcepts.Add(new WeavableConcept <MethodDefinition>(new PointCut <MethodDefinition>(m => m.Name == "RunWithoutReplacement"), runWithoutReplacementDecoration));
                            loom.WeavableConcepts.Add(new WeavableConcept <MethodDefinition>(new PointCut <MethodDefinition>(m => m.Name == "RunWithReplacement"), runWithReplacementDecorator));

                            loom.Weave(targetAssembly);
                        }
                    targetAssembly.Write();
                }
        }
コード例 #9
0
        public override bool Execute()
        {
            if (LogDebug == null)
            {
                LogDebug = message => BuildEngine?.LogMessageEvent(new BuildMessageEventArgs(
                                                                       $"WeaveRealmAssembly: {message}",
                                                                       string.Empty,
                                                                       "BuildTasks",
                                                                       MessageImportance.Normal));
            }

            _resolver = new DefaultAssemblyResolver();
            _resolver.AddSearchDirectory(IntermediateDirectory);
            _resolver.ResolveFailure += (sender, reference) =>
            {
                return(_resolver.Resolve("mscorlib"));
            };

            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += OnCurrentDomainAssemblyResolve;
                var path = GetAssemblyPath(AssemblyName, isRealmAssembly: false);
                if (!File.Exists(path))
                {
                    return(false);
                }

                var currentAssembly = AssemblyDefinition.ReadAssembly(path);

                WeaveAssembly("Realm", currentAssembly);
                WeaveAssembly("Realm.Sync", currentAssembly);

                return(true);
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= OnCurrentDomainAssemblyResolve;
            }
        }
コード例 #10
0
        public override AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            AssemblyDefinition assembly;

            try
            {
                assembly = defaultResolver.Resolve(name);
            }
            catch (AssemblyResolutionException)
            {
                var assemblyPath = Path.Combine(managedDirectory, name.Name + ".dll");

                if (!File.Exists(assemblyPath))
                {
                    throw;
                }

                assembly = ModuleDefinition.ReadModule(assemblyPath).Assembly;
            }

            return(assembly);
        }
コード例 #11
0
        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);
                    if (assemblyDefinition.Name.Name.StartsWith("UnityEngine."))
                    {
                        foreach (string current2 in usedClasses.GetAllManagedClassesAsString())
                        {
                            textWriter.WriteLine(string.Format("<type fullname=\"UnityEngine.{0}\" preserve=\"{1}\"/>", current2, usedClasses.GetRetentionLevel(current2)));
                        }
                    }
                    MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
                    textWriter.WriteLine("</assembly>");
                }
                textWriter.WriteLine("</linker>");
            }
            return(text);
        }
コード例 #12
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);
        }
コード例 #13
0
        public sealed override String[] GetReferences(bool keepextension)
        {
            List <string>           references = new List <string>();
            DefaultAssemblyResolver resolver   = new DefaultAssemblyResolver();

            Directory.SetCurrentDirectory(Path.GetDirectoryName(_mdefsource.DeclaringType.Module.Image.FileName));

            foreach (AssemblyNameReference asmref in CompileReferences)
            {
                string reference;

                if (asmref.Name == "mscorlib" || asmref.Name.StartsWith("System"))
                {
                    reference = asmref.Name + ((keepextension) ? ".dll": string.Empty);
                }
                else
                {
                    try
                    {
                        AssemblyDefinition asmdef = resolver.Resolve(asmref);
                        reference = asmdef.MainModule.Image.FileName;
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                if (!references.Contains(reference))
                {
                    references.Add(reference);
                }
            }

            return(references.ToArray());
        }
コード例 #14
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("}");
        }
コード例 #15
0
        /// <summary>
        /// Background processing of a single PE file.
        /// It can be lengthy since there are disk access (and misses).
        /// </summary>
        /// <param name="NewTreeContexts"> This variable is passed as reference to be updated since this function is run in a separate thread. </param>
        /// <param name="newPe"> Current PE file analyzed </param>
        private void ProcessPe(Dictionary <string, ImportContext> NewTreeContexts, PE newPe)
        {
            List <PeImportDll> PeImports = newPe.GetImports();

            Environment.SpecialFolder WindowsSystemFolder = (this.Pe.IsWow64Dll()) ?
                                                            Environment.SpecialFolder.SystemX86 :
                                                            Environment.SpecialFolder.System;
            string User32Filepath  = Path.Combine(Environment.GetFolderPath(WindowsSystemFolder), "user32.dll");
            string MsCoreeFilepath = Path.Combine(Environment.GetFolderPath(WindowsSystemFolder), "mscoree.dll");

            foreach (PeImportDll DllImport in PeImports)
            {
                ImportContext ImportModule = new ImportContext();
                ImportModule.PeFilePath       = null;
                ImportModule.PeProperties     = null;
                ImportModule.ModuleName       = DllImport.Name;
                ImportModule.ApiSetModuleName = null;
                ImportModule.Flags            = 0;
                if (DllImport.IsDelayLoad())
                {
                    ImportModule.Flags |= ModuleFlag.DelayLoad;
                }

                if (NewTreeContexts.ContainsKey(DllImport.Name))
                {
                    continue;
                }

                // Find Dll in "paths"
                Tuple <ModuleSearchStrategy, PE> ResolvedModule = BinaryCache.ResolveModule(this.Pe, DllImport.Name, this.SxsEntriesCache);
                ImportModule.ModuleLocation = ResolvedModule.Item1;
                if (ImportModule.ModuleLocation != ModuleSearchStrategy.NOT_FOUND)
                {
                    ImportModule.PeProperties = ResolvedModule.Item2;
                    ImportModule.PeFilePath   = ResolvedModule.Item2.Filepath;
                }

                // special case for apiset schema
                ImportModule.IsApiSet = (ImportModule.ModuleLocation == ModuleSearchStrategy.ApiSetSchema);
                if (ImportModule.IsApiSet)
                {
                    ImportModule.ApiSetModuleName = BinaryCache.LookupApiSetLibrary(DllImport.Name);
                }

                // add warning for appv isv applications
                if (String.Compare(DllImport.Name, "AppvIsvSubsystems32.dll", StringComparison.OrdinalIgnoreCase) == 0 ||
                    String.Compare(DllImport.Name, "AppvIsvSubsystems64.dll", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (!this._DisplayWarning)
                    {
                        MessageBoxResult result = MessageBox.Show(
                            "This binary use the App-V containerization technology which fiddle with search directories and PATH env in ways Dependencies can't handle.\n\nFollowing results are probably not quite exact.",
                            "App-V ISV disclaimer"
                            );

                        this._DisplayWarning = true; // prevent the same warning window to popup several times
                    }
                }

                NewTreeContexts.Add(DllImport.Name, ImportModule);


                // AppInitDlls are triggered by user32.dll, so if the binary does not import user32.dll they are not loaded.
                if (ImportModule.PeFilePath == User32Filepath)
                {
                    string AppInitRegistryKey = (this.Pe.IsWow64Dll()) ?
                                                "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows" :
                                                "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows";

                    int    LoadAppInitDlls = (int)Registry.GetValue(AppInitRegistryKey, "LoadAppInit_DLLs", 0);
                    string AppInitDlls     = (string)Registry.GetValue(AppInitRegistryKey, "AppInit_DLLs", "");

                    if ((LoadAppInitDlls != 0) && (AppInitDlls != ""))
                    {
                        // Extremely crude parser. TODO : Add support for quotes wrapped paths with spaces
                        foreach (var AppInitDll in AppInitDlls.Split(' '))
                        {
                            Debug.WriteLine("AppInit loading " + AppInitDll);

                            // Do not process twice the same imported module
                            if (null != PeImports.Find(module => module.Name == AppInitDll))
                            {
                                continue;
                            }

                            if (NewTreeContexts.ContainsKey(AppInitDll))
                            {
                                continue;
                            }

                            ImportContext AppInitImportModule = new ImportContext();
                            AppInitImportModule.PeFilePath       = null;
                            AppInitImportModule.PeProperties     = null;
                            AppInitImportModule.ModuleName       = AppInitDll;
                            AppInitImportModule.ApiSetModuleName = null;
                            AppInitImportModule.Flags            = 0;
                            AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.AppInitDLL;



                            Tuple <ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(this.Pe, AppInitDll, this.SxsEntriesCache);
                            if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
                            {
                                AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
                                AppInitImportModule.PeFilePath   = ResolvedAppInitModule.Item2.Filepath;
                            }

                            NewTreeContexts.Add(AppInitDll, AppInitImportModule);
                        }
                    }
                }


                // if mscoree.dll is imported, it means the module is a C# assembly, and we can use Mono.Cecil to enumerate its references
                if (ImportModule.PeFilePath == MsCoreeFilepath)
                {
                    var resolver = new DefaultAssemblyResolver();
                    resolver.AddSearchDirectory(RootFolder);

                    AssemblyDefinition PeAssembly = AssemblyDefinition.ReadAssembly(newPe.Filepath);

                    foreach (var module in PeAssembly.Modules)
                    {
                        // Process CLR referenced assemblies
                        foreach (var assembly in module.AssemblyReferences)
                        {
                            AssemblyDefinition definition = resolver.Resolve(assembly);

                            foreach (var AssemblyModule in definition.Modules)
                            {
                                Debug.WriteLine("Referenced Assembling loading " + AssemblyModule.Name + " : " + AssemblyModule.FileName);

                                // Do not process twice the same imported module
                                if (null != PeImports.Find(mod => mod.Name == Path.GetFileName(AssemblyModule.FileName)))
                                {
                                    continue;
                                }

                                ImportContext AppInitImportModule = new ImportContext();
                                AppInitImportModule.PeFilePath       = null;
                                AppInitImportModule.PeProperties     = null;
                                AppInitImportModule.ModuleName       = Path.GetFileName(AssemblyModule.FileName);
                                AppInitImportModule.ApiSetModuleName = null;
                                AppInitImportModule.Flags            = ModuleFlag.ClrReference;
                                AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.ClrAssembly;

                                Tuple <ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(this.Pe, AssemblyModule.FileName, this.SxsEntriesCache);
                                if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
                                {
                                    AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
                                    AppInitImportModule.PeFilePath   = ResolvedAppInitModule.Item2.Filepath;
                                }

                                if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
                                {
                                    NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
                                }
                            }
                        }

                        // Process unmanaged dlls for native calls
                        foreach (var UnmanagedModule in module.ModuleReferences)
                        {
                            // some clr dll have a reference to an "empty" dll
                            if (UnmanagedModule.Name.Length == 0)
                            {
                                continue;
                            }

                            Debug.WriteLine("Referenced module loading " + UnmanagedModule.Name);

                            // Do not process twice the same imported module
                            if (null != PeImports.Find(m => m.Name == UnmanagedModule.Name))
                            {
                                continue;
                            }



                            ImportContext AppInitImportModule = new ImportContext();
                            AppInitImportModule.PeFilePath       = null;
                            AppInitImportModule.PeProperties     = null;
                            AppInitImportModule.ModuleName       = UnmanagedModule.Name;
                            AppInitImportModule.ApiSetModuleName = null;
                            AppInitImportModule.Flags            = ModuleFlag.ClrReference;
                            AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.ClrAssembly;

                            Tuple <ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(this.Pe, UnmanagedModule.Name, this.SxsEntriesCache);
                            if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
                            {
                                AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
                                AppInitImportModule.PeFilePath   = ResolvedAppInitModule.Item2.Filepath;
                            }

                            if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
                            {
                                NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
        public void AddLib(AssemblyNameReference name)
        {
            var assembly = Resolve(name) ?? _defaultAssemblyResolver.Resolve(name);

            AddLib(name, assembly ?? throw new AssemblyResolutionException(name));
        }
コード例 #17
0
ファイル: CSCompiler.cs プロジェクト: snowdream1985/ILPatcher
        private bool CodeCompile()
        {
            if (isCompiled)
            {
                return(true);
            }

            CompilerParameters cp = new CompilerParameters();

            if (parentAssembly != null)
            {
                DefaultAssemblyResolver dar = new DefaultAssemblyResolver();

                List <AssemblyDefinition> adList = new List <AssemblyDefinition>();
                adList.Add(parentAssembly);
                foreach (AssemblyNameReference anr in parentAssembly.MainModule.AssemblyReferences)
                {
                    AssemblyDefinition adref = dar.Resolve(anr);
                    //string fullname = adref.MainModule.FullyQualifiedName;
                    if (!adList.Exists(adcomp => adcomp.MainModule.Name == adref.MainModule.Name &&
                                       adcomp.Name.PublicKeyToken.SequenceEqual(adref.Name.PublicKeyToken)))
                    {
                        adList.Add(adref);
                    }
                    //if (!cp.ReferencedAssemblies.Contains(fullname))
                    //.Add(fullname);
                }
                cp.ReferencedAssemblies.AddRange(adList.ConvertAll(ad => ad.MainModule.FullyQualifiedName).ToArray());
            }

            cp.WarningLevel       = 3;
            cp.CompilerOptions    = "/target:library";          // /optimize
            cp.GenerateExecutable = false;
            cp.GenerateInMemory   = false;
            cp.OutputAssembly     = "tmpILData.dll";

            using (CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"))
            {
                CompilerResults cr = provider.CompileAssemblyFromSource(cp, Code);

                if (cr.Errors.Count > 0)
                {
                    StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                    foreach (CompilerError error in cr.Errors)
                    {
                        errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
                    }
                    Log.Write(Log.Level.Error, $"Compiler Error: \"{errors}\"");
                    if (cr.Errors.HasErrors)
                    {
                        return(false);
                    }
                }

                //FileStream fs
                //ModuleDefinition moddef = ModuleDefinition.ReadModule("tmpILData.dll");
                compiledAssembly = AssemblyDefinition.ReadAssembly("tmpILData.dll");
                isCompiled       = true;
            }
            return(true);
        }
コード例 #18
0
 public void SetUp()
 {
     Corlib = Resolver.Resolve("mscorlib");
 }
コード例 #19
0
        private void ProcessClrImports(Dictionary <string, ImportContext> NewTreeContexts, PE AnalyzedPe, ImportContext ImportModule)
        {
            List <PeImportDll> PeImports = AnalyzedPe.GetImports();

            // only mscorre triggers clr parsing
            string User32Filepath = Path.Combine(FindPe.GetSystemPath(this.Pe), "mscoree.dll");

            if (ImportModule.PeFilePath != User32Filepath)
            {
                return;
            }

            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(RootFolder);

            // Parse it via cecil
            AssemblyDefinition PeAssembly = null;

            try
            {
                PeAssembly = AssemblyDefinition.ReadAssembly(AnalyzedPe.Filepath);
            }
            catch (BadImageFormatException)
            {
                MessageBoxResult result = MessageBox.Show(
                    String.Format("Cecil could not correctly parse {0:s}, which can happens on .NET Core executables. CLR imports will be not shown", AnalyzedPe.Filepath),
                    "CLR parsing fail"
                    );

                return;
            }

            foreach (var module in PeAssembly.Modules)
            {
                // Process CLR referenced assemblies
                foreach (var assembly in module.AssemblyReferences)
                {
                    AssemblyDefinition definition;
                    try
                    {
                        definition = resolver.Resolve(assembly);
                    }
                    catch (AssemblyResolutionException)
                    {
                        ImportContext AppInitImportModule = new ImportContext();
                        AppInitImportModule.PeFilePath       = null;
                        AppInitImportModule.PeProperties     = null;
                        AppInitImportModule.ModuleName       = Path.GetFileName(assembly.Name);
                        AppInitImportModule.ApiSetModuleName = null;
                        AppInitImportModule.Flags            = ModuleFlag.ClrReference;
                        AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.ClrAssembly;
                        AppInitImportModule.Flags           |= ModuleFlag.NotFound;

                        if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
                        {
                            NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
                        }

                        continue;
                    }

                    foreach (var AssemblyModule in definition.Modules)
                    {
                        Debug.WriteLine("Referenced Assembling loading " + AssemblyModule.Name + " : " + AssemblyModule.FileName);

                        // Do not process twice the same imported module
                        if (null != PeImports.Find(mod => mod.Name == Path.GetFileName(AssemblyModule.FileName)))
                        {
                            continue;
                        }

                        ImportContext AppInitImportModule = new ImportContext();
                        AppInitImportModule.PeFilePath       = null;
                        AppInitImportModule.PeProperties     = null;
                        AppInitImportModule.ModuleName       = Path.GetFileName(AssemblyModule.FileName);
                        AppInitImportModule.ApiSetModuleName = null;
                        AppInitImportModule.Flags            = ModuleFlag.ClrReference;
                        AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.ClrAssembly;

                        Tuple <ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(
                            this.Pe,
                            AssemblyModule.FileName,
                            this.SxsEntriesCache,
                            this.CustomSearchFolders,
                            this.WorkingDirectory
                            );
                        if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
                        {
                            AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
                            AppInitImportModule.PeFilePath   = ResolvedAppInitModule.Item2.Filepath;
                        }
                        else
                        {
                            AppInitImportModule.Flags |= ModuleFlag.NotFound;
                        }

                        if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
                        {
                            NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
                        }
                    }
                }

                // Process unmanaged dlls for native calls
                foreach (var UnmanagedModule in module.ModuleReferences)
                {
                    // some clr dll have a reference to an "empty" dll
                    if (UnmanagedModule.Name.Length == 0)
                    {
                        continue;
                    }

                    Debug.WriteLine("Referenced module loading " + UnmanagedModule.Name);

                    // Do not process twice the same imported module
                    if (null != PeImports.Find(m => m.Name == UnmanagedModule.Name))
                    {
                        continue;
                    }



                    ImportContext AppInitImportModule = new ImportContext();
                    AppInitImportModule.PeFilePath       = null;
                    AppInitImportModule.PeProperties     = null;
                    AppInitImportModule.ModuleName       = UnmanagedModule.Name;
                    AppInitImportModule.ApiSetModuleName = null;
                    AppInitImportModule.Flags            = ModuleFlag.ClrReference;
                    AppInitImportModule.ModuleLocation   = ModuleSearchStrategy.ClrAssembly;

                    Tuple <ModuleSearchStrategy, PE> ResolvedAppInitModule = BinaryCache.ResolveModule(
                        this.Pe,
                        UnmanagedModule.Name,
                        this.SxsEntriesCache,
                        this.CustomSearchFolders,
                        this.WorkingDirectory
                        );
                    if (ResolvedAppInitModule.Item1 != ModuleSearchStrategy.NOT_FOUND)
                    {
                        AppInitImportModule.PeProperties = ResolvedAppInitModule.Item2;
                        AppInitImportModule.PeFilePath   = ResolvedAppInitModule.Item2.Filepath;
                    }

                    if (!NewTreeContexts.ContainsKey(AppInitImportModule.ModuleName))
                    {
                        NewTreeContexts.Add(AppInitImportModule.ModuleName, AppInitImportModule);
                    }
                }
            }
        }
コード例 #20
0
        internal static Dictionary <string, AssemblyTuple> smethod_1(IEnumerable <AssemblyFileInfo> coreAssemblyFiles)
        {
            Dictionary <string, AssemblyTuple> dictionary = new Dictionary <string, AssemblyTuple>();
            DefaultAssemblyResolver            defaultAssemblyResolver = new DefaultAssemblyResolver();

            foreach (string current in BfCache.list_0)
            {
                if (Directory.Exists(current))
                {
                    defaultAssemblyResolver.AddSearchDirectory(current);
                }
            }
            foreach (AssemblyFileInfo current2 in coreAssemblyFiles)
            {
                if (current2.Name == "Search Directory")
                {
                    defaultAssemblyResolver.AddSearchDirectory(current2.Path);
                }
                else
                {
                    string directoryName = Path.GetDirectoryName(current2.Path);
                    defaultAssemblyResolver.AddSearchDirectory(directoryName);
                }
            }
            foreach (AssemblyFileInfo current2 in coreAssemblyFiles)
            {
                if (!(current2.Name == "Search Directory"))
                {
                    AssemblyDefinition assembly;
                    try
                    {
                        assembly = AssemblyFactory.GetAssembly(current2.Path);
                    }
                    catch (ImageFormatException)
                    {
                        throw new NitriqException("NotManagedAssembly", "The assembly \"" + current2.Name + "\" is not a managed assembly");
                    }
                    if (!dictionary.ContainsKey(assembly.Name.FullName))
                    {
                        AssemblyTuple assemblyTuple = new AssemblyTuple(assembly);
                        assemblyTuple.IsCoreAssembly = true;
                        assemblyTuple.Directory      = Path.GetDirectoryName(current2.Path);
                        dictionary.Add(assembly.Name.FullName, assemblyTuple);
                    }
                }
            }
            List <AssemblyTuple> list = new List <AssemblyTuple>(dictionary.Values);

            foreach (AssemblyTuple current3 in list)
            {
                foreach (ModuleDefinition moduleDefinition in current3.Assembly.Modules)
                {
                    foreach (AssemblyNameReference assemblyNameReference in moduleDefinition.AssemblyReferences)
                    {
                        AssemblyDefinition assemblyDefinition;
                        try
                        {
                            assemblyDefinition = defaultAssemblyResolver.Resolve(assemblyNameReference);
                        }
                        catch (FileNotFoundException)
                        {
                            throw new NitriqException("CantResolve", "Nitriq couldn't resolve the below assembly, consider adding a search directory where this assembly can be found \r\n\r\n" + assemblyNameReference.FullName);
                        }
                        string fullName  = assemblyNameReference.FullName;
                        string fullName2 = assemblyDefinition.Name.FullName;
                        if (fullName2 == fullName)
                        {
                            if (!dictionary.ContainsKey(fullName))
                            {
                                dictionary.Add(fullName, new AssemblyTuple(assemblyDefinition)
                                {
                                    Directory      = "",
                                    IsCoreAssembly = false
                                });
                            }
                        }
                        else if (dictionary.ContainsKey(fullName) || dictionary.ContainsKey(fullName2))
                        {
                            if (!dictionary.ContainsKey(fullName))
                            {
                                dictionary.Add(fullName, dictionary[fullName2]);
                            }
                            if (!dictionary.ContainsKey(fullName2))
                            {
                                dictionary.Add(fullName2, dictionary[fullName]);
                            }
                        }
                        else
                        {
                            AssemblyTuple assemblyTuple2 = new AssemblyTuple(assemblyDefinition);
                            assemblyTuple2.Directory      = "";
                            assemblyTuple2.IsCoreAssembly = false;
                            dictionary.Add(fullName, assemblyTuple2);
                            dictionary.Add(fullName2, assemblyTuple2);
                        }
                    }
                }
            }
            return(dictionary);
        }
コード例 #21
0
        public static string GenerateLinkXmlToPreserveDerivedTypes(string stagingArea, string librariesFolder, RuntimeClassRegistry usedClasses)
        {
            string fullPath = Path.GetFullPath(Path.Combine(stagingArea, "preserved_derived_types.xml"));
            DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(librariesFolder);
            using (TextWriter textWriter = new StreamWriter(fullPath))
            {
                textWriter.WriteLine("<linker>");
                foreach (AssemblyDefinition current in MonoAssemblyStripping.CollectAssembliesRecursive(from s in usedClasses.GetUserAssemblies()
                                                                                                        where usedClasses.IsDLLUsed(s)
                                                                                                        select s into file
                                                                                                        select resolver.Resolve(Path.GetFileNameWithoutExtension(file), new ReaderParameters
                {
                    AssemblyResolver = resolver
                })))
                {
                    if (!(current.Name.Name == "UnityEngine"))
                    {
                        HashSet <TypeDefinition> hashSet = new HashSet <TypeDefinition>();
                        MonoAssemblyStripping.CollectBlackListTypes(hashSet, current.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString());
                        if (hashSet.Count != 0)
                        {
                            textWriter.WriteLine("<assembly fullname=\"{0}\">", current.Name.Name);
                            foreach (TypeDefinition current2 in hashSet)
                            {
                                textWriter.WriteLine("<type fullname=\"{0}\" preserve=\"all\"/>", current2.FullName);
                            }
                            textWriter.WriteLine("</assembly>");
                        }
                    }
                }
                textWriter.WriteLine("</linker>");
            }
            return(fullPath);
        }
コード例 #22
0
        static void Main(string[] args)
        {
            Arguments arguments = Arguments.Parse(args);

            if (arguments.Values.Count == 0 || arguments.Flag("help"))
            {
                LogMessage("Usage: NDirect.Generator.exe [--verbose] [--help] ( <.NET framework .exe> | --hook [--strip] <.NET assembly to install hook in> )");
                return;
            }

            if (arguments.Flag("verbose"))
            {
                Verbose = true;
            }

            string exeName = arguments.Values[0];

            if (arguments.Flag("hook"))
            {
                string outputPath = Path.Combine(Path.GetDirectoryName(exeName),
                                                 Path.GetFileNameWithoutExtension(exeName) + "-proxy" +
                                                 Path.GetExtension(exeName));

                using var assemblyDefinition = AssemblyDefinition.ReadAssembly(exeName);

                InstallHook(assemblyDefinition, outputPath, arguments.Flag("strip"));

                LogMessage("Finished!");
                return;
            }

            if (!exeName.EndsWith(".exe") || !File.Exists(exeName))
            {
                LogError("Please specify an executable file to generate a proxy for");
                return;
            }

            string exeDirectory = Path.GetDirectoryName(exeName);
            string configName   = Path.ChangeExtension(exeName, ".exe.config");

            LogVerbose($"Target executable: {exeName}");
            LogVerbose($"Target executable directory: {exeDirectory}");
            LogVerbose($"Target configuration file: {configName}");
            LogVerbose("");


            using var assembly = AssemblyDefinition.ReadAssembly(exeName);

            var assemblyNamePaths = new Dictionary <AssemblyNameReference, string>();

            foreach (var file in Directory.EnumerateFiles(exeDirectory, "*.dll", SearchOption.AllDirectories))
            {
                try
                {
                    if (Path.GetFileNameWithoutExtension(file).EndsWith("-proxy"))
                    {
                        continue;
                    }

                    using var refAssembly = AssemblyDefinition.ReadAssembly(file);

                    bool isMixedMode = (refAssembly.MainModule.Attributes & ModuleAttributes.ILOnly) == 0;

                    if (isMixedMode)
                    {
                        continue;
                    }

                    assemblyNamePaths.Add(AssemblyNameReference.Parse(refAssembly.Name.FullName), file);

                    LogVerbose($"Found reference: '{refAssembly.Name.FullName}' => {file}");
                }
                catch (Exception ex)
                {
                    LogVerbose($"Unable to parse dll: '{file}' => {ex.Message}");
                }
            }

            LogVerbose($"Found {assemblyNamePaths.Count} possible reference assemblies\r\n");

            List <AssemblyNamePath> foundReferences = new List <AssemblyNamePath>();
            var resolver = new DefaultAssemblyResolver();

            foreach (var reference in assembly.MainModule.AssemblyReferences)
            {
                if (UnusableAssemblies.Contains(reference.Name))
                {
                    continue;
                }

                if (assemblyNamePaths.TryFind(out var foundPair, x => x.Key.FullName == reference.FullName))
                {
                    foundReferences.Add(new AssemblyNamePath(foundPair.Key, foundPair.Value));
                    continue;
                }

                AssemblyDefinition resolvedAssembly;

                try
                {
                    resolvedAssembly = resolver.Resolve(reference);
                }
                catch (AssemblyResolutionException)
                {
                    continue;
                }

                bool   isMixedMode = (resolvedAssembly.MainModule.Attributes & ModuleAttributes.ILOnly) == 0;
                string path        = resolvedAssembly.MainModule.FileName;

                resolvedAssembly.Dispose();

                if (isMixedMode)
                {
                    continue;
                }

                if (resolvedAssembly.Name.HasPublicKey)
                {
                    continue;
                }

                foundReferences.Add(new AssemblyNamePath(reference, path));
            }

            if (foundReferences.Count == 0)
            {
                LogError("Couldn't find a suitable dll");
                return;
            }

            var foundRef = foundReferences.First();

            LogMessage($"Using '{foundRef.AssemblyLocation}' as library to generate a proxy for");

            string proxyPath = Path.Combine(exeDirectory, foundRef.NameReference.Name + "-proxy.dll");


            using (var originalAssembly = AssemblyDefinition.ReadAssembly(foundRef.AssemblyLocation))
            {
                InstallHook(originalAssembly, proxyPath, true);
            }

            ConfigGenerator generator;

            if (foundRef.NameReference.PublicKeyToken.Length > 0)
            {
                generator = new ConfigGenerator(foundRef.NameReference.Name, foundRef.NameReference.Version, new Version(99, 0, 0),
                                                Utility.ByteArrayToHexString(foundRef.NameReference.PublicKeyToken), Path.GetFileName(proxyPath));
            }
            else
            {
                generator = new ConfigGenerator(foundRef.NameReference.Name, foundRef.NameReference.Version,
                                                Path.GetFileName(proxyPath));
            }

            generator.BuildAndWriteConfig(configName);

            LogMessage("Finished!");
        }
コード例 #23
0
        public ILModule(Stack <ILAssembly> allAssemblies, ILAssembly assembly, bool loadReferences, ModuleDefinition moduleDefinition, ISymbolReader symbolReader, DefaultAssemblyResolver assemblyResolver)
        {
            this.assembly         = assembly;
            this.moduleDefinition = moduleDefinition;
            this.symbolReader     = symbolReader;

            // create dependency ordered type list
            typesDependencyOrdered = moduleDefinition.Types.ToList();
            typesDependencyOrdered.Sort(delegate(TypeDefinition x, TypeDefinition y)
            {
                if (x == y)
                {
                    return(0);
                }

                // if we're a struct, make sure we are put after any fields we depend on
                if (x.IsValueType)
                {
                    foreach (var field in x.Fields)
                    {
                        if (field.FieldType.FullName == y.FullName)
                        {
                            return(1);
                        }
                    }
                }

                // validate we are put in front of our base types
                var baseType = x.BaseType;
                while (baseType != null)
                {
                    if (!baseType.IsDefinition)
                    {
                        return(0);                                           // if our base type lives in a different module, ignore
                    }
                    if (baseType.FullName == y.FullName)
                    {
                        return(1);                                                    // make sure we are put after our base type
                    }
                    var baseTypeDef = (TypeDefinition)baseType;
                    baseType        = baseTypeDef.BaseType;
                }

                return(0);
            });

            // load references
            references = new Stack <ILAssembly>();
            if (loadReferences)
            {
                foreach (var nameReference in moduleDefinition.AssemblyReferences)
                {
                    using (var assemblyDefinition = assemblyResolver.Resolve(nameReference))
                    {
                        var ilAssembly = allAssemblies.FirstOrDefault(x => x.assemblyDefinition.FullName == assemblyDefinition.FullName);
                        if (ilAssembly == null)
                        {
                            ilAssembly = new ILAssembly(allAssemblies, assemblyDefinition.MainModule.FileName, loadReferences, assemblyResolver);
                        }
                        references.Push(ilAssembly);
                    }
                }
            }
        }
コード例 #24
0
        private static (AssemblyInformation assembly, AssemblyDefinition?monoAssembly) CreateManagedAssemblyInformation(AssemblyNameReference assemblyName, string?baseDirectory, string extension = "dll")
        {
            var assemblyPath = FilePathProvider.GetAssemblyPath($"{assemblyName.Name}.{extension}", baseDirectory);

            AssemblyDefinition?assembly = null;

            try
            {
                using var resolver = new DefaultAssemblyResolver();
                assembly           = assemblyPath != null?AssemblyDefinition.ReadAssembly(assemblyPath) : resolver.Resolve(assemblyName);
            }
            catch
            {
                // do nothing, assembly is not found
            }

            var info = new AssemblyInformation(assemblyName.Name, assembly?.Name.Version.ToString() ?? assemblyName.Version.ToString(), assemblyPath)
            {
                IsLocalAssembly = assemblyPath != null || assembly == null,
                AssemblyName    = assembly?.FullName ?? assemblyName.FullName,
                IsResolved      = assembly != null,
                HasEntryPoint   = assembly?.EntryPoint != null
            };

            info.EnhancePropertiesWithFile();
            info.EnhanceProperties(assembly);

            return(info, assembly);
        }
コード例 #25
0
        /// <summary>
        /// Search for type name.
        /// </summary>
        /// <param name="list">Array of items where to search.</param>
        /// <param name="filter">Filter to search.</param>
        /// <returns><c>true</c>, if call succeded, <c>false</c> otherwise.</returns>
        bool SearchTypesName(ListViewItem[] list, string filter)
        {
            // return null if list is null
            if (list == null)
            {
                return(false);
            }

            // return if filter is empty
            if (string.IsNullOrEmpty(filter))
            {
                resultList = list.ToList();
                return(true);
            }

            // clear result
            resultList.Clear();

            // scan the list
            for (int i = 0; i < list.Length; ++i)
            {
                ListViewItem    item = list[i];
                DomAssemblyName asm  = item.Tag as DomAssemblyName;

                // search path
                if (asm.FullName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    resultList.Add(item);
                }
                else
                {
                    if (worker.CancellationPending)
                    {
                        return(false);
                    }

                    // search using Mono.Cecil the class/interface/structs names
                    AssemblyDefinition currentAssembly;
                    if (!assembliesCache.ContainsKey(asm.FullName))
                    {
                        try {
                            currentAssembly = resolver.Resolve(asm.FullName);
                        }
                        catch {
                            continue;
                        }
                        assembliesCache.Add(asm.FullName, currentAssembly);
                    }
                    else
                    {
                        currentAssembly = assembliesCache[asm.FullName];
                    }

                    // search types in modules
                    if (currentAssembly != null)
                    {
                        foreach (var module in currentAssembly.Modules)
                        {
                            foreach (var type in module.Types)
                            {
                                if (type.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0 &&
                                    !resultList.Contains(item))
                                {
                                    resultList.Add(item);
                                }
                            }
                        }
                    }

                    // report
                    worker.ReportProgress((int)(((i * 1.0) / list.Length) * 100));
                }
            }

            return(true);
        }
コード例 #26
0
        static void Main(string[] args)
        {
            var arguments = new Arguments();

            try
            {
                if (args.Length < 1)
                {
                    arguments.Usage();
                }
                arguments.Parse(args);
                isRemoving           = arguments.IsRemoving;
                isFailing            = arguments.IsFailing;
                preInvokeMethodName  = arguments.PreInvokeMethod;
                postInvokeMethodName = arguments.PostInvokeMethod;
                inputFilePath        = arguments.FilePaths[0];
                var outputFilePath = arguments.FilePaths.Count > 1 ? arguments.FilePaths[1] : inputFilePath;
                resolver = new DefaultAssemblyResolver();
                string inputFolderPath = Path.GetDirectoryName(inputFilePath);
                resolver.RemoveSearchDirectory(".");
                resolver.RemoveSearchDirectory("bin");
                var searchFolders = new List <string>();
                searchFolders.Add(inputFolderPath);
                searchFolders.AddRange(arguments.SearchFolderPaths);
                searchFolders.AddRange(arguments.Assemblies.Select(s => Path.GetDirectoryName(s)));
                if (arguments.FrameworkFolder != null)
                {
                    searchFolders.Add(arguments.FrameworkFolder);
                }
                else
                {
                    var nakedModule       = ModuleDefinition.ReadModule(inputFilePath);
                    var assemblyReference = nakedModule.AssemblyReferences.FirstOrDefault(a => a.Name == "mscorlib");
                    if (assemblyReference != null)
                    {
                        if (Enumerable.SequenceEqual(assemblyReference.PublicKeyToken, new byte[] { 0x7c, 0xec, 0x85, 0xd7, 0xbe, 0xa7, 0x79, 0x8e }))
                        {
                            // This is Silverlight.
                            string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                            string silverlightFolder  = Path.Combine(programFilesFolder, "Microsoft Silverlight");
                            silverlightFolder = Directory.GetDirectories(silverlightFolder).OrderByDescending(s => s).First();
                            searchFolders.Add(silverlightFolder);
                            // The following also works.
                            //searchFolders.Add(@"C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0");
                        }
                        else
                        {
                            // Assume it's the full .NET framework.
                            // TODO:  handle WP7.
                            string programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                            string frameworkFolder    = Path.Combine(programFilesFolder, @"Reference Assemblies\Microsoft\Framework\.NETFramework");
                            frameworkFolder = Directory.GetDirectories(frameworkFolder).OrderByDescending(s => s).First();
                            searchFolders.Add(frameworkFolder);
                        }
                    }
                }
                searchFolders = searchFolders.Select(s => Path.GetFullPath(s).ToLowerInvariant()).Distinct().ToList();
                searchFolders.ForEach(s => resolver.AddSearchDirectory(s));
                module = ReadModule(inputFilePath, resolver);
                var q = from p in arguments.Assemblies
                        let n = Path.GetFileNameWithoutExtension(p)
                                select resolver.Resolve(n).MainModule;

                modules      = new[] { module }.Concat(q).ToList();
                symbolReader = new SymbolReader(module);
                if (WeaveDependency() | WeaveNotify() | WeaveOnDemand() | WeaveInitialValue() | WeavePrePost() | WeaveXmlSerializable() | (arguments.IsRenaming && WeaveRename()))
                {
                    WriteModule(module, outputFilePath);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                Console.Error.Flush();
                Console.WriteLine();
                arguments.Usage(1);
            }
            if (HasFailed)
            {
                Environment.ExitCode = 1;
            }
        }
コード例 #27
0
        private void DecompileAssembly(AssemblyDefinition adef, string outputDir, string location)
        {
            Utils.WriteToConsole("Decompiling assembly: " + adef.FullName);
            //Each visitor is responsible of changing the file if necessary (from here it is ipmossible to know the file names)
            ICSharpCode.Decompiler.ITextOutput textOutput = new ICSharpCode.Decompiler.FileTextOutput(outputDir);
            FileWritterManager.WorkingPath = outputDir;

            ICSharpCode.ILSpy.Language lang = null;
            //CONFIGURE OUTPUT LANGUAGE
            if (Config.ToCSharp)
            {
                lang = OutputLanguage("C#");
            }
            else
            {
                lang = OutputLanguage("CXX");
            }

            if (Config.RecursiveDependencies)
            {
                var resolver = new DefaultAssemblyResolver();
                Utils.WriteToConsole("Adding " + location + " to resolver search directories");
                resolver.AddSearchDirectory(location);
                foreach (AssemblyNameReference anref in adef.MainModule.AssemblyReferences)
                {
                    if (!Config.IgnoreReferences.Contains(anref.Name))
                    {
                        AssemblyDefinition assembly = resolver.Resolve(anref);

                        //TODO: Change directory ?
                        DecompileAssembly(assembly, outputDir, location);
                        if (assembly == null)
                        {
                            Utils.WriteToConsole("alternative: ");
                            Utils.WriteToConsole("ERROR - could not resolve assembly " + anref.FullName + " .");
                        }
                    }
                }
            }

            //DECOMPILE FIRST TIME AND FILL THE TABLES
            foreach (TypeDefinition tdef in adef.MainModule.Types)
            {
                if (!tdef.Name.Contains("<"))
                {
                    lang.DecompileType(tdef, textOutput, new ICSharpCode.ILSpy.DecompilationOptions()
                    {
                        FullDecompilation = false
                    });
                }
            }

            //DECOMPILE
            foreach (TypeDefinition tdef in adef.MainModule.Types)
            {
                if (!tdef.Name.Contains("<"))
                {
                    lang.DecompileType(tdef, textOutput, new ICSharpCode.ILSpy.DecompilationOptions()
                    {
                        FullDecompilation = false
                    });
                    Utils.WriteToConsole("Decompiled: " + tdef.FullName);
                }
            }
        }
コード例 #28
0
        static int Main(string [] args)
        {
            var    assemblyPaths = new List <string> ();
            string baseUnrealBindingsNamespace = "UnrealEngine";
            bool   showHelp  = false;
            bool   verify    = false;
            string outputDir = null;
            var    options   = new OptionSet()
            {
                { "p|path=", "Additional search paths for assemblies", v => assemblyPaths.Add(StripQuotes(v)) },
                { "n|namespace=", "Base unreal bindings namespace", v => baseUnrealBindingsNamespace = v },
                { "o|output=", "Output directory", v => outputDir = v },
                { "h|help", "Show this message and exit", v => showHelp = v != null },
                { "verify", "Verify processed assemblies", v => verify = v != null }
            };

            List <string> extra;

            try {
                extra = options.Parse(args);
            } catch (OptionException e) {
                Console.Error.Write("MonoAssemblyProcess: ");
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine("Try 'MonoAssemblyProcess --help' for more information");
                return(1);
            }

            if (showHelp)
            {
                ShowHelp(options);
                return(0);
            }

            if (extra.Count == 0)
            {
                Console.Error.WriteLine("Need at least one assembly to process!");
                Console.Error.WriteLine("Try 'MonoAssemblyProcess --help' for more information");
                return(2);
            }

            NativeTypeManifest      manifest = new NativeTypeManifest();
            DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();

            foreach (var lookupPath in assemblyPaths)
            {
                if (Directory.Exists(lookupPath))
                {
                    string nativeClassManifest = Path.Combine(lookupPath, "AllNativeClasses.manifest");

                    if (File.Exists(nativeClassManifest))
                    {
                        manifest = new NativeTypeManifest(nativeClassManifest);
                    }
                    resolver.AddSearchDirectory(lookupPath);
                }
                else
                {
                    Console.Error.WriteLine("Warning: Assembly resolve path {0} does not exist, skipping", lookupPath);
                }
            }

            string [] knownPaths = assemblyPaths.ToArray();

            BaseUnrealNamespace = baseUnrealBindingsNamespace;
            BindingsNamespace   = baseUnrealBindingsNamespace + "." + BindingsSubnamespace;

            AssemblyDefinition bindingsAssembly = resolver.Resolve(new AssemblyNameReference(BindingsNamespace, new Version(0, 0, 0, 0)));

            if (null == bindingsAssembly)
            {
                Console.Error.WriteLine("Could not find bindings assembly: " + BindingsNamespace);
                return(3);
            }

            foreach (var quotedAssemblyPath in extra)
            {
                var assemblyPath = StripQuotes(quotedAssemblyPath);
                if (outputDir == null)
                {
                    if (!ProcessAssemblyInPlace(bindingsAssembly, assemblyPath, resolver, knownPaths, manifest, verify))
                    {
                        return(4);
                    }
                }
                else
                {
                    var    outputPath          = Path.Combine(outputDir, Path.GetFileName(assemblyPath));
                    string nativeClassManifest = Path.Combine(outputPath, "AllNativeClasses.manifest");

                    if (File.Exists(nativeClassManifest))
                    {
                        manifest = new NativeTypeManifest(nativeClassManifest);
                    }

                    Directory.CreateDirectory(outputDir);
                    try {
                        ProcessAssembly(bindingsAssembly, assemblyPath, outputPath, resolver, knownPaths, manifest, verify);
                    } catch (MonoAssemblyProcessError error) {
                        ErrorEmitter.Error(error);
                    } catch (Exception ex) {
                        Console.Error.WriteLine("Exception processing {0}", assemblyPath);
                        Console.Error.WriteLine(ex.Message);
                        Console.Error.WriteLine(ex.StackTrace);
                        return(4);
                    }
                }
            }

            return(0);
        }
コード例 #29
0
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(resolver.Resolve(name));
 }
コード例 #30
0
        public string[] TestHelper(Func <MethodDefinition, bool> inclusionTest, string[] keywords, string warning = "Potential Injection")
        {
            var apiEndpoint  = GetApiEndpoint();
            var callEndpoint = !string.IsNullOrEmpty(apiEndpoint);
            var dict         = new Dictionary <string, AssemblyDefinition>();
            var resolver     = new DefaultAssemblyResolver();
            var types        = new List <TypeDefinition>();

            var assemblies = new List <AssemblyDefinition>();

            if (typeof(T) != typeof(object))
            {
                var path     = new Uri(typeof(T).Module.Assembly.CodeBase).LocalPath;
                var assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly(path);
                types.Add(assembly.MainModule.GetType(typeof(T).Namespace, typeof(T).Name));
                dict.Add(path, assembly);
            }

            GetReferenceTypes().ForEach(x =>
            {
                var directory = Path.GetDirectoryName(x.Path);
                var assembly  = Mono.Cecil.AssemblyDefinition.ReadAssembly(x.Path);
                var t         = assembly.MainModule.GetType(x.Namespace, x.Name);
                if (t != null)
                {
                    types.Add(t);
                    if (!dict.ContainsKey(x.Path))
                    {
                        dict.Add(x.Path, assembly);
                        resolver.AddSearchDirectory(directory);
                    }
                }
            });

            assemblies = dict.Select(x => x.Value).Where(x => !EXCLUDE.Any(y => x.FullName.StartsWith(y))).Distinct().ToList();;

            assemblies.ToArray().ToList().ForEach(asm =>
            {
                assemblies = assemblies.Union(asm.MainModule.AssemblyReferences.Select(x =>
                {
                    try
                    {
                        return(resolver.Resolve(x));
                    }
                    catch { return(null); }
                }).Where(x => x != null)).ToList();
            });

            assemblies = assemblies.Where(x => !EXCLUDE.Any(y => x.FullName.StartsWith(y))).Distinct().ToList();

            var other = assemblies.SelectMany(asm => asm.MainModule.GetTypes().Where(x => types.Any(t => x.IsSubclassOf(t))));

            var all = other.SelectMany(x => x.Methods).ToList();

            all.AddRange(types.SelectMany(x => x.Methods));

            var filteredMethods = all
                                  .ExcludeMethods(MethodExclusions())
                                  .Where(x =>
                                         (typeof(T) != typeof(object) || x.IsPublic) &&
                                         x.Parameters.Count > 0 &&
                                         !x.Parameters.All(y => y.ParameterType.IsValueType) &&
                                         !x.CustomAttributes.Any(y => y.AttributeType.Name.Contains("MarkSafe"))
                                         ).ToList();

            var failures = new ConcurrentBag <string>();
            var dump     = new ConcurrentBag <IEnumerable <IEnumerable <String> > >();

            filteredMethods.AsParallel().ForAll(m =>
            {
                var paths = m.DrillIn(assemblies, methodExclusions: MethodExclusions(), stopWhen: inclusionTest)
                            .GroupBy(x => string.Join("", x)).Select(x => x.First())
                            .Where(x => x.Any(inclusionTest)).ToList();
                var dangeroudPaths = paths
                                     .Select(x => new { Path = x.ToList(), DangerousStrings = x.SelectMany(y => y.DangerousStrings().Where(z => true == keywords?.Any(kw => z.ToLower().Contains(kw)))).ToList() })
                                     .Where(x => x.Path.Count == 1 || keywords == null || x.DangerousStrings.Count > 0)
                                     .ToList();
                var results = dangeroudPaths.Select(x => x.Path).ToList();
                if (results.Count > 0)
                {
                    foreach (var r in results)
                    {
                        if (callEndpoint)
                        {
                            dump.Add(r.Select(x => new[] { x.Module.FileName, x.FullName }));
                        }

                        failures.Add($"{Environment.NewLine}{warning} in: {Environment.NewLine}{string.Join(Environment.NewLine, r.Select((x, y) => $"{string.Join("", Enumerable.Range(0, y).Select(z => "\t"))}{x.DeclaringType.Module.Assembly.Name.Name}::{x.DeclaringType.Name}.{x.Name}"))}");
                    }
                }
            });

            if (callEndpoint && dump.Count > 0)
            {
                try
                {
                    using (var wc = new WebClient())
                    {
                        wc.UploadData(apiEndpoint, "POST", System.Text.UTF8Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dump.ToArray(), new JsonSerializerSettings()
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        })));
                    }
                }
                catch (Exception ex)
                {
                    ex = ex;
                }
            }
            return(failures.ToArray());
        }