示例#1
0
        static void ReadMutateAndResolve(string sourceLocation)
        {
            ExtractAndCompile(sourceLocation);
            string dllLocation = Path.ChangeExtension(sourceLocation, ".dll");

            using (var host = new PeReader.DefaultHost()) {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(dllLocation) as IModule;
                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    Console.WriteLine(dllLocation + " 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);
                }

                module = MetadataCopier.DeepCopy(host, module);
                module = new MetadataRewriter(host).Rewrite(module);
                TestResolution resolver = new TestResolution(host);
                resolver.Visit(module);

                string result = resolver.Output.ToString();
                Assert.True(!result.Contains("Dummy"));
            }
        }
示例#2
0
    IAssembly VisitAndMutate(MetadataRewriter mutator, IAssembly assembly)
    {
        var mutableAssembly = new MetadataDeepCopier(host).Copy(assembly);

        assembly = mutator.Rewrite(mutableAssembly);
        Assert.NotNull(assembly);
        return(assembly);
    }
    static void Main(string[] args) {
      if (args == null || args.Length == 0) {
        Console.WriteLine("usage: PeToPe [path]fileName.ext");
        return;
      }

      using (var host = new PeReader.DefaultHost()) {
        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;
        }

        PdbReader/*?*/ pdbReader = null;
        string pdbFile = module.DebugInformationLocation;
        if (string.IsNullOrEmpty(pdbFile))
          pdbFile = Path.ChangeExtension(module.Location, "pdb");
        if (File.Exists(pdbFile)) {
          Stream pdbStream = File.OpenRead(pdbFile);
          pdbReader = new PdbReader(pdbStream, host);
        }

        using (pdbReader) {
          //Make a mutable copy of the module.
          var copier = new MetadataDeepCopier(host);
          var mutableModule = copier.Copy(module);

          //Traverse the module. In a real application the MetadataVisitor and/or the MetadataTravers will be subclasses
          //and the traversal will gather information to use during rewriting.
          var traverser = new MetadataTraverser() { PreorderVisitor = new MetadataVisitor(), TraverseIntoMethodBodies = true };
          traverser.Traverse(mutableModule);

          //Rewrite the mutable copy. In a real application the rewriter would be a subclass of MetadataRewriter that actually does something.
          var rewriter = new MetadataRewriter(host);
          var rewrittenModule = rewriter.Rewrite(mutableModule); 

          //Write out rewritten module.
          using (var peStream = File.Create(rewrittenModule.Location + ".pe")) {
            if (pdbReader == null) {
              PeWriter.WritePeToStream(rewrittenModule, host, peStream);
            } else {
              //Note that the default copier and rewriter preserves the locations collections, so the original pdbReader is still a valid ISourceLocationProvider.
              //However, if IL instructions were rewritten, the pdbReader will no longer be an accurate ILocalScopeProvider
              using (var pdbWriter = new PdbWriter(pdbFile + ".pdb", pdbReader)) {
                PeWriter.WritePeToStream(rewrittenModule, host, peStream, pdbReader, pdbReader, pdbWriter);
              }
            }
          }
        }
      }
    }
示例#4
0
        private Task LoadManagedData()
        {
            return _loadingManagedData ?? (_loadingManagedData = _tasks.Start(() => {
                if (_loadOptions.HasFlag(BinaryLoadOptions.NoManaged)) {
                    return;
                }
                // load managed data from working file
                if (!IsManaged) {
                    ILOnly.Value = false;
                    return;
                }
                // copy this to a temporary file, because it locks the file until we're *really* done.

                try {
                    var module = _host.LoadUnitFrom(WorkingCopy) as IModule;

                    if (module == null || module is Dummy) {
                        throw new CoAppException("{0} is not a PE file containing a CLR module or assembly.".format(Filename));
                    }

                    ILOnly.Value = module.ILOnly;

                    //Make a mutable copy of the module.
                    var copier = new MetadataDeepCopier(_host);
                    var mutableModule = copier.Copy(module);

                    //Traverse the module. In a real application the MetadataVisitor and/or the MetadataTravers will be subclasses
                    //and the traversal will gather information to use during rewriting.
                    var traverser = new MetadataTraverser {
                        PreorderVisitor = new MetadataVisitor(),
                        TraverseIntoMethodBodies = true
                    };
                    traverser.Traverse(mutableModule);

                    //Rewrite the mutable copy. In a real application the rewriter would be a subclass of MetadataRewriter that actually does something.
                    var rewriter = new MetadataRewriter(_host);
                    _mutableAssembly = rewriter.Rewrite(mutableModule) as Assembly;
                    AssemblyCulture.Value = _mutableAssembly.Culture;
                    AssemblyVersion.Value = _mutableAssembly.Version;
                } finally {
                    // delete it, or at least trash it & queue it up for next reboot.
                    // temporaryCopy.TryHardToDelete();
                }

                try {
                    if (_mutableAssembly != null) {
                        // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones.
                        foreach (var a in _mutableAssembly.ContainingAssembly.AssemblyAttributes) {
                            var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant);
                            if (attributeArgument != null) {
                                var attributeValue = attributeArgument.Value.ToString();
                                if (!string.IsNullOrEmpty(attributeValue)) {
                                    switch (a.Type.ToString()) {
                                        case "System.Reflection.AssemblyTitleAttribute":
                                            _fileDescription = _fileDescription ?? attributeValue;
                                            break;
                                        case "System.Reflection.AssemblyCompanyAttribute":
                                            _companyName = _companyName ?? attributeValue;
                                            break;
                                        case "System.Reflection.AssemblyProductAttribute":
                                            _productName = _productName ?? attributeValue;
                                            break;
                                            // case "System.Reflection.AssemblyVersionAttribute":
                                            //  _assemblyVersion = _assemblyVersion == 0L ? (FourPartVersion)attributeValue : _assemblyVersion;
                                            // break;
                                        case "System.Reflection.AssemblyFileVersionAttribute":
                                            _fileVersion = _fileVersion == 0L ? (FourPartVersion)attributeValue : _fileVersion;
                                            _productVersion = _productVersion == 0L ? (FourPartVersion)attributeValue : _productVersion;
                                            break;
                                        case "System.Reflection.AssemblyCopyrightAttribute":
                                            _legalCopyright = _legalCopyright ?? attributeValue;
                                            break;
                                        case "System.Reflection.AssemblyTrademarkAttribute":
                                            _legalTrademarks = _legalTrademarks ?? attributeValue;
                                            break;
                                        case "System.Reflection.AssemblyDescriptionAttribute":
                                            _comments = _comments ?? attributeValue;
                                            break;
                                        case "BugTrackerAttribute":
                                            _bugTracker = _bugTracker ?? attributeValue;
                                            break;
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    Console.WriteLine("{0} -- {1}", e.Message, e.StackTrace);
                }

                // if there are dependencies, this will load them.
                if (_loadOptions.HasFlag(BinaryLoadOptions.UnsignedManagedDependencies)) {
                    LoadUnsignedManagedDependencies();
                }
            }));
        }
示例#5
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("usage: PeToPe [path]fileName.ext");
                return;
            }

            using (var host = new PeReader.DefaultHost()) {
                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;
                }

                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = module.DebugInformationLocation;
                if (string.IsNullOrEmpty(pdbFile))
                {
                    pdbFile = Path.ChangeExtension(module.Location, "pdb");
                }
                if (File.Exists(pdbFile))
                {
                    Stream pdbStream = File.OpenRead(pdbFile);
                    pdbReader = new PdbReader(pdbStream, host);
                }

                using (pdbReader) {
                    //Make a mutable copy of the module.
                    var copier        = new MetadataDeepCopier(host);
                    var mutableModule = copier.Copy(module);

                    //Traverse the module. In a real application the MetadataVisitor and/or the MetadataTravers will be subclasses
                    //and the traversal will gather information to use during rewriting.
                    var traverser = new MetadataTraverser()
                    {
                        PreorderVisitor = new MetadataVisitor(), TraverseIntoMethodBodies = true
                    };
                    traverser.Traverse(mutableModule);

                    //Rewrite the mutable copy. In a real application the rewriter would be a subclass of MetadataRewriter that actually does something.
                    var rewriter        = new MetadataRewriter(host);
                    var rewrittenModule = rewriter.Rewrite(mutableModule);

                    //Write out rewritten module.
                    using (var peStream = File.Create(rewrittenModule.Location + ".pe")) {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(rewrittenModule, host, peStream);
                        }
                        else
                        {
                            //Note that the default copier and rewriter preserves the locations collections, so the original pdbReader is still a valid ISourceLocationProvider.
                            //However, if IL instructions were rewritten, the pdbReader will no longer be an accurate ILocalScopeProvider
                            using (var pdbWriter = new PdbWriter(pdbFile + ".pdb", pdbReader)) {
                                PeWriter.WritePeToStream(rewrittenModule, host, peStream, pdbReader, pdbReader, pdbWriter);
                            }
                        }
                    }
                }
            }
        }
示例#6
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
                }
            }
        }
示例#7
0
 void VisitAndMutate(MetadataRewriter mutator, ref IAssembly assembly)
 {
     assembly = mutator.Rewrite(assembly);
     Assert.NotNull(assembly);
 }
示例#8
0
 void RoundTripWithMutator(PeVerifyResult expectedResult, IAssembly assembly, MetadataRewriter mutator)
 {
     this.VisitAndMutate(mutator, ref assembly);
     AssertWriteToPeFile(expectedResult, assembly);
 }
示例#9
0
    void RoundTripWithMutator(PeVerifyResult expectedResult, IAssembly assembly, MetadataRewriter mutator, string pdbPath)
    {
        var result = this.VisitAndMutate(mutator, assembly);

        AssertWriteToPeFile(expectedResult, result, pdbPath);
    }
 IAssembly VisitAndMutate(MetadataRewriter mutator, IAssembly assembly) {
   var mutableAssembly = new MetadataDeepCopier(host).Copy(assembly);
   assembly = mutator.Rewrite(mutableAssembly);
   Assert.NotNull(assembly);
   return assembly;
 }
 void RoundTripWithMutator(PeVerifyResult expectedResult, IAssembly assembly, MetadataRewriter mutator, string pdbPath) {
   var result = this.VisitAndMutate(mutator, assembly);
   AssertWriteToPeFile(expectedResult, result, pdbPath);
 }