Example #1
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);
                            }
                        }
                    }
                }
            }
        }
Example #2
0
        static int Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: HelloContracts [path]fileName.Contracts.dll [-libpaths ...]* [-p [-i] | -inject]");
                return(1);
            }
            #region Parse options
            var options = new Options();
            options.Parse(args);
            if (options.HelpRequested)
            {
                options.PrintOptions("");
                return(1);
            }
            if (options.HasErrors)
            {
                options.PrintErrorsAndExit(Console.Out);
            }
            #endregion

            var fileName = String.IsNullOrEmpty(options.assembly) ? options.GeneralArguments[0] : options.assembly;

            if (options.printContracts)
            {
                #region Collect and write contracts
                using (var host = new CodeContractAwareHostEnvironment(options.libpaths)) {
                    IModule module = host.LoadUnitFrom(fileName) as IModule;
                    if (module == null || module is Dummy)
                    {
                        Console.WriteLine("'{0}' is not a PE file containing a CLR module or assembly.", fileName);
                        Environment.Exit(1);
                    }
                    var t = new Traverser(host, options.inherited);
                    t.Traverse(module);
                }
                #endregion
                return(0);
            }
            else
            {
                using (var host = new CodeContractAwareHostEnvironment(options.libpaths, true, true)) {
                    // Read the Metadata Model from the PE file
                    var module = host.LoadUnitFrom(fileName) as IModule;
                    if (module == null || module is Dummy)
                    {
                        Console.WriteLine(fileName + " is not a PE file containing a CLR module or assembly.");
                        return(1);
                    }

                    // Get a PDB reader if there is a PDB file.
                    PdbReader /*?*/ pdbReader = null;
                    string          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;

                        // Construct a Code Model from the Metadata model via decompilation
                        var mutableModule = Decompiler.GetCodeModelFromMetadataModel(host, module, pdbReader, DecompilerOptions.AnonymousDelegates | DecompilerOptions.Loops);
                        ILocalScopeProvider localScopeProvider = new Decompiler.LocalScopeProvider(pdbReader);

                        // Extract contracts (side effect: removes them from the method bodies)
                        var contractProvider = Microsoft.Cci.MutableContracts.ContractHelper.ExtractContracts(host, mutableModule, pdbReader, localScopeProvider);

                        // Inject non-null postconditions
                        if (options.inject)
                        {
                            new NonNullInjector(host, contractProvider).Traverse(mutableModule);
                        }

                        // Put the contracts back in as method calls at the beginning of each method
                        Microsoft.Cci.MutableContracts.ContractHelper.InjectContractCalls(host, mutableModule, contractProvider, sourceLocationProvider);

                        // Write out the resulting module. Each method's corresponding IL is produced
                        // lazily using CodeModelToILConverter via the delegate that the mutator stored in the method bodies.
                        using (var peStream = File.Create(mutableModule.Location + ".pe")) {
                            if (pdbReader == null)
                            {
                                PeWriter.WritePeToStream(mutableModule, host, peStream);
                            }
                            else
                            {
                                using (var pdbWriter = new PdbWriter(mutableModule.Location + ".pdb", sourceLocationProvider)) {
                                    PeWriter.WritePeToStream(mutableModule, host, peStream, sourceLocationProvider, localScopeProvider, pdbWriter);
                                }
                            }
                        }
                    }
                }
                return(0);
            }
        }
Example #3
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
                }
            }
        }