Esempio n. 1
0
        void ProcessMethodActions(MethodDefinition method, Method entry)
        {
            Context.AddMethodEntry(method, entry);

            switch (entry.Action ?? MethodAction.None)
            {
            case MethodAction.Debug:
                Context.LogMessage(MessageImportance.High, $"Debug method: {method}");
                Context.Debug();
                break;

            case MethodAction.Throw:
                CodeRewriter.ReplaceWithPlatformNotSupportedException(Context, method);
                break;

            case MethodAction.ReturnFalse:
                CodeRewriter.ReplaceWithReturnFalse(Context, method);
                break;

            case MethodAction.ReturnTrue:
                CodeRewriter.ReplaceWithReturnTrue(Context, method);
                break;

            case MethodAction.ReturnNull:
                CodeRewriter.ReplaceWithReturnNull(Context, method);
                break;
            }
        }
Esempio n. 2
0
        public void Test1()
        {
            var    path = @"../../../ExampleClass.cs";
            string code = null;

            using (var sr = new StreamReader(path))
                code = sr.ReadToEnd();

            var codeRewriter = new CodeRewriter(new CodeRewriterConfig()
            {
                Logger = _output.WriteLine
            }, new TemplateExtractor());
            var str = codeRewriter.Wrap(code);

            _output.WriteLine(str);

            using (var sw = new StreamWriter(path.Replace(".cs", ".out.cs.txt")))
                sw.Write(str);

            Assert.True(false);
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: PeToPe [path]fileName.ext [noStack]");
                return;
            }
            bool noStack = args.Length == 2;

            using (var host = new PeReader.DefaultHost()) {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(args[0]) as IModule;
                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Get a PDB reader if there is a PDB file.
                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = Path.ChangeExtension(module.Location, "pdb");
                if (File.Exists(pdbFile))
                {
                    Stream pdbStream = File.OpenRead(pdbFile);
                    pdbReader = new PdbReader(pdbStream, host);
                }
                using (pdbReader) {
                    //Construct a Code Model from the Metadata model via decompilation
                    var options = DecompilerOptions.None;
                    if (noStack)
                    {
                        options |= DecompilerOptions.Unstack;
                    }
                    var decompiledModule = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, options);
                    ISourceLocationProvider sourceLocationProvider = pdbReader; //The decompiler preserves the Locations from the IOperation values, so the PdbReader still works.
                    //Recompiling the CodeModel to IL might change the IL offsets, so a new provider is needed.
                    ILocalScopeProvider localScopeProvider = new Decompiler.LocalScopeProvider(pdbReader);

                    //Get a mutable copy of the Code Model. The ISourceLocationProvider is needed to provide copied source method bodies with the
                    //ability to find out where to mark sequence points when compiling themselves back into IL.
                    //(ISourceMethodBody does not know about the Source Model, so this information must be provided explicitly.)
                    var copier        = new CodeDeepCopier(host, sourceLocationProvider);
                    var mutableModule = copier.Copy(decompiledModule);

                    //Traverse the mutable copy. In a real application the traversal will collect information to be used during rewriting.
                    var traverser = new CodeTraverser()
                    {
                        PreorderVisitor = new CodeVisitor()
                    };
                    traverser.Traverse(mutableModule);

                    //Rewrite the mutable Code Model. In a real application CodeRewriter would be a subclass that actually does something.
                    //(This is why decompiled source method bodies must recompile themselves, rather than just use the IL from which they were decompiled.)
                    var rewriter        = new CodeRewriter(host);
                    var rewrittenModule = rewriter.Rewrite(mutableModule);

                    //Write out the Code Model by traversing it as the Metadata Model that it also is.
                    using (var peStream = File.Create(rewrittenModule.Location + ".pe")) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(rewrittenModule, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(rewrittenModule.Location + ".pdb", pdbReader)) {
                                PeWriter.WritePeToStream(rewrittenModule, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: PeToPe [path]fileName.ext [decompile] [noStack]");
                return;
            }
            bool decompile = args.Length >= 2;
            bool noStack   = args.Length >= 3;

            using (var host = new HostEnvironment()) {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(args[0]) as IModule;
                if (module == null || module is Dummy)
                {
                    Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Get a PDB reader if there is a PDB file.
                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = module.DebugInformationLocation;
                if (string.IsNullOrEmpty(pdbFile) || !File.Exists(pdbFile))
                {
                    pdbFile = Path.ChangeExtension(module.Location, "pdb");
                }
                if (File.Exists(pdbFile))
                {
                    using (var pdbStream = File.OpenRead(pdbFile)) {
                        pdbReader = new PdbReader(pdbStream, host);
                    }
                }
                using (pdbReader) {
                    ISourceLocationProvider sourceLocationProvider = pdbReader;
                    ILocalScopeProvider     localScopeProvider     = pdbReader;
                    if (decompile)
                    {
                        //Construct a Code Model from the Metadata model via decompilation
                        var options = DecompilerOptions.AnonymousDelegates | DecompilerOptions.Iterators | DecompilerOptions.Loops;
                        if (noStack)
                        {
                            options |= DecompilerOptions.Unstack;
                        }
                        module = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, options);
                        if (pdbReader != null)
                        {
                            localScopeProvider = new Decompiler.LocalScopeProvider(pdbReader);
                        }
                    }

                    MetadataRewriter   rewriter;
                    MetadataDeepCopier copier;
                    if (decompile)
                    {
                        copier   = new CodeDeepCopier(host, pdbReader, pdbReader);
                        rewriter = new CodeRewriter(host);
                    }
                    else
                    {
                        copier   = new MetadataDeepCopier(host);
                        rewriter = new MetadataRewriter(host);
                    }

                    var mutableModule = copier.Copy(module);
                    module = rewriter.Rewrite(mutableModule);

                    //var validator = new MetadataValidator(host);
                    //List<Microsoft.Cci.ErrorEventArgs> errorEvents = new List<Microsoft.Cci.ErrorEventArgs>();
                    //host.Errors += (object sender, Microsoft.Cci.ErrorEventArgs e) => errorEvents.Add(e);
                    //var assem = module as IAssembly;
                    //validator.Validate(assem);
                    //if (errorEvents.Count != 0)
                    //{
                    //    foreach (var e in errorEvents)
                    //    {
                    //        foreach (var err in e.Errors)
                    //        {
                    //            Console.WriteLine(err.Message);
                    //        }
                    //    }
                    //}

#if DEBUG
                    var newRoot = Path.GetFileNameWithoutExtension(module.Location) + "1";
                    var newName = newRoot + Path.GetExtension(module.Location);
                    using (Stream peStream = File.Create(newName)) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(module, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(newRoot + ".pdb", pdbReader, emitTokenSourceInfo: true)) {
                                PeWriter.WritePeToStream(module, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                            }
                        }
                    }
#else
                    using (Stream peStream = File.Create(module.Location)) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(module, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(pdbFile, pdbReader, emitTokenSourceInfo: true)) {
                                PeWriter.WritePeToStream(module, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                            }
                        }
                    }
#endif
                }
            }
        }