Exemplo n.º 1
0
        public Helper(IModule module, PeReader.DefaultHost host, Log.Log logger)
        {
            this.host = host;
            this.logger = logger;
            this.module = module;

            // get all needed functions and namespaces
            this.systemString = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.String");
            this.systemIOTextWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.TextWriter");
            this.systemIOStreamWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.StreamWriter");
            this.systemInt32 = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Int32");
            this.systemObject = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Object");
            this.systemConsole = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Console");
            this.systemRandom = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Random");

            ITypeReference[] concatThreeParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] concatTwoParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString };
            ITypeReference[] streamWriterAppendTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemBoolean };

            this.stringConcatThree = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatThreeParameterTypes);
            this.stringConcatTwo = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatTwoParameterTypes);
            this.textWriterWriteLine = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("WriteLine"), this.host.PlatformType.SystemString);
            this.streamWriterCtor = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), this.host.PlatformType.SystemString);
            this.streamWriterCtorAppend = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), streamWriterAppendTypes);
            this.textWriterWrite = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Write"), this.host.PlatformType.SystemString);
            this.int32ToString = TypeHelper.GetMethod(systemInt32, this.host.NameTable.GetNameFor("ToString"));
            this.textWriterClose = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Close"));
            this.objectGetHashCode = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor("GetHashCode"));
            this.systemConsoleWriteLine = TypeHelper.GetMethod(systemConsole, host.NameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);
            this.objectCtor = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomCtor = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor(".ctor"));
            this.systemRandomNext = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor("Next"), host.PlatformType.SystemInt32);
        }
            public override void Initialize()
            {
               // CoreAssembly = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity);

                var host = new PeReader.DefaultHost();
                IModule module = OperatorUtils.CompileModuleFromCode(
@"public class GenException : Exception
{
    public GenException()
    {
    }

    public GenException(object o1) 
    {
    }
    public GenException(object o1, object o2)
    {
    }
}", host);
             /*   GeneratedType = (NamespaceTypeDefinition)module.GetAllTypes().Single(t => t.Name.Value == "VisualMutatorGeneratedClass");
                var methodBody = TypeHelper.GetMethod(GeneratedType,
                    host.NameTable.GetNameFor("FailOnZero"), host.PlatformType.SystemInt32).Body;
                var generatedBody = (SourceMethodBody)methodBody;
                GeneratedBlock = generatedBody.Block;*/
                host.Dispose();
            }
Exemplo n.º 3
0
        public CfgManipulator(IModule module, PeReader.DefaultHost host, Log.Log logger, MethodCfg methodCfg) {
            this.host = host;
            this.logger = logger;
            this.module = module;

            this.methodCfg = methodCfg;
        }
Exemplo n.º 4
0
    static void Main(string[] args) {
      if (args.Length < 1) {
        Console.WriteLine("Must specify at least one input file.");
        return;
      }
      using (var host = new PeReader.DefaultHost()) {
        foreach (string assemblyName in args) {
          var assembly = host.LoadUnitFrom(assemblyName) as IAssembly;
          if (assembly == null || assembly == Dummy.Assembly) {
            Console.WriteLine("The file '" + assemblyName + "' is not a PE file" +
            " containing a CLR assembly, or an error occurred when loading it.");
            continue;
          }

          Console.WriteLine("Generic Methods in generic types from '"+assembly.Name.Value+"':");
          foreach (INamedTypeDefinition type in assembly.GetAllTypes()) {
            if (!type.IsGeneric) continue;
            foreach (IMethodDefinition methodDefinition in type.Methods) {
              if (methodDefinition.IsGeneric) {
                Console.WriteLine(MemberHelper.GetMemberSignature(methodDefinition,
                  NameFormattingOptions.Signature | NameFormattingOptions.TypeParameters | NameFormattingOptions.TypeConstraints | NameFormattingOptions.ParameterName));
              }
            }
          }
        }
      }
    }
Exemplo n.º 5
0
    static void Main(string[] args) {
      if (args == null || args.Length == 0) {
        Console.WriteLine("usage: peToText [path]fileName.ext");
        return;
      }
      using (var host = new PeReader.DefaultHost()) {
        IModule/*?*/ 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;
        }

        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) {
          string txtFile = Path.ChangeExtension(pdbFile, "txt");
          using (var writer = new StreamWriter(txtFile)) {
            SourceEmitter csSourceEmitter = new SourceEmitter(writer, host, pdbReader);
            csSourceEmitter.Traverse((INamespaceDefinition)module.UnitNamespaceRoot);
            writer.Close();
          }
        }
      }
    }
        public InterfaceTransformer(IModule module, PeReader.DefaultHost host, Log.Log logger) {

            this.host = host;
            this.logger = logger;
            this.module = module;
            this.helperClass = new Helper(module, host, logger);

        }
Exemplo n.º 7
0
    static int Main(string[] args) {

        /*
      if (args == null || args.Length < 1) {
        Console.WriteLine("Usage: ILMutator <assembly> [<outputPath>]");
        return 1;
      }
         */

        String inputFile = @"c:\Users\typ\Documents\Visual Studio 2013\Projects\vererbung\vererbung\bin\Debug\vererbung.exe";


      using (var host = new PeReader.DefaultHost()) {
        //IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule;
        IModule/*?*/ module = host.LoadUnitFrom(inputFile) as IModule;
        if (module == null || module is Dummy) {
          Console.WriteLine(args[0] + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");
          return 1;
        }
        module = new MetadataDeepCopier(host).Copy(module);

        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);
          }
        } else {
          Console.WriteLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");
        }
        using (pdbReader) {
          var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader);

          module = RewriteStoreLocal.RewriteModule(host, localScopeProvider, pdbReader, module);

          string newName;
          if (args.Length == 2) {
            //newName = args[1];
            newName = @"e:\mutated.exe";
          } else {
            var loc = module.Location;
            var path = Path.GetDirectoryName(loc)??"";
            var fileName = Path.GetFileNameWithoutExtension(loc);
            var ext = Path.GetExtension(loc);
            newName = Path.Combine(path, fileName + "1" + ext);
            newName = @"e:\mutated.exe";
          }

          using (var peStream = File.Create(newName)) {
            using (var pdbWriter = new PdbWriter(Path.ChangeExtension(newName, ".pdb"), pdbReader)) {
              PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter);
            }
          }
        }
        return 0; // success
      }
    }
Exemplo n.º 8
0
        /// <summary>
        ///     Not Even Started.
        /// </summary>
        /// <param name="filename"> </param>
        public static void Load(string filename) {
            MetadataReaderHost _host = new PeReader.DefaultHost();

            var module = _host.LoadUnitFrom(filename) as IModule;

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

            Console.WriteLine("module: {0}", module);
        }
        protected override IEnumerable<ITypeDetails> GetTypes(string assemblyPath)
        {
            var host = new PeReader.DefaultHost();
            var assy = host.LoadUnitFrom(assemblyPath) as IAssembly;

            if (assy == null || assy == Dummy.Assembly)
            {
                throw new InvalidOperationException(string.Format("Failed to load assembly from '{0}'", assemblyPath));
            }

            return assy.GetAllTypes().Select(x => new CciTypeDetails(x));
        }
Exemplo n.º 10
0
        public static void Process(ILoggerContext logger, ProjectDetails assemblyDetails, string tempFolder = null)
        {
            if (!assemblyDetails.Verify(logger))
                return;

            tempFolder = tempFolder ?? Path.GetTempPath();

            string pdbFile = Path.ChangeExtension(assemblyDetails.AssemblyPath, ".pdb");

            var newAssemblyPath = Path.Combine(tempFolder, String.Format("{0}.weavr{1}", Path.GetFileNameWithoutExtension(assemblyDetails.AssemblyPath), Path.GetExtension(assemblyDetails.AssemblyPath)));
            var newPdbPath = File.Exists(pdbFile) ? Path.ChangeExtension(newAssemblyPath, ".pdb") : null;

            using (var host = new PeReader.DefaultHost())
            {
                var targetAssembly = (IAssembly)host.LoadUnitFrom(assemblyDetails.AssemblyPath);

                using (var pdbStream = newPdbPath != null ? File.OpenRead(pdbFile) : null)
                using (var pdbReader = newPdbPath != null ? new PdbReader(pdbStream, host) : null)
                {
                    var decompiled = Decompiler.GetCodeModelFromMetadataModel(host, targetAssembly, pdbReader);
                    decompiled = new CodeDeepCopier(host, pdbReader).Copy(decompiled);

                    var engine = new Engine(logger, host);
                    engine.Process(assemblyDetails, decompiled);

                    using (var peStream = File.Create(newAssemblyPath))
                    {
                        if (pdbReader == null)
                        {
                            PeWriter.WritePeToStream(decompiled, host, peStream);
                        }
                        else
                        {
                            using (var pdbWriter = new PdbWriter(newPdbPath, pdbReader))
                            {
                                PeWriter.WritePeToStream(decompiled, host, peStream, pdbReader, pdbReader, pdbWriter);
                            }
                        }
                    }
                }
            }

            File.Delete(assemblyDetails.AssemblyPath);
            File.Move(newAssemblyPath, assemblyDetails.AssemblyPath);

            if (!string.IsNullOrEmpty(newPdbPath))
            {
                File.Delete(pdbFile);
                File.Move(newPdbPath, pdbFile);
            }
        }
Exemplo n.º 11
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);
              }
            }
          }
        }
      }
    }
Exemplo n.º 12
0
        public static AssemblyApi Traverse(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentException("Assembly Path should not be empty.");

            using (MetadataReaderHost host = new PeReader.DefaultHost())
            {
                IModule module = host.LoadUnitFrom(path) as IModule;
                if (module == null || module is Dummy)
                {
                    Environment.Exit(1);
                    throw new ArgumentException("'{0}' is not a PE file containing a CLR module or assembly.", path);
                }
                var t = new ApiTraverser(host, module.ContainingAssembly);
                t.Traverse(module);
                return t.Assembly;
            }
        }
Exemplo n.º 13
0
    static void Main(string[] args) {
      if (args == null || args.Length == 0) {
        Console.WriteLine("usage: EdgeProfiler [path]fileName.ext");
        return;
      }
      using (var host = new PeReader.DefaultHost()) {
        IModule/*?*/ 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;
        }

        var coreIdentity = host.CoreAssemblySymbolicIdentity; //force host to let args[0] determine the target platform
        var profiler = (IAssembly)host.LoadUnitFrom(typeof(Program).Assembly.Location);
        var logger = (INamespaceTypeDefinition)UnitHelper.FindType(host.NameTable, profiler, "Logger");

        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) {
          var instrumentedModule = Instrumenter.GetInstrumented(host, module, pdbReader, logger);
          var newRoot = Path.GetFileNameWithoutExtension(module.Location)+".instrumented";
          var newName = newRoot+Path.GetExtension(module.Location);
          using (var peStream = File.Create(newName)) {
            if (pdbReader == null) {
              PeWriter.WritePeToStream(instrumentedModule, host, peStream);
            } else {
              var localScopeProvider = new ILGenerator.LocalScopeProvider(pdbReader);
              using (var pdbWriter = new PdbWriter(newRoot + ".pdb", pdbReader)) {
                PeWriter.WritePeToStream(instrumentedModule, host, peStream, pdbReader, localScopeProvider, pdbWriter);
              }
            }
          }
        }
      }
    }
Exemplo n.º 14
0
    static void Main(string[] args) {
      if (args == null || args.Length == 0) {
        Console.WriteLine("usage: FindThrowArgumentNull [path]fileName.ext");
        return;
      }

      using (var host = new PeReader.DefaultHost()) {
        var module = host.LoadUnitFrom(args[0]) as IModule;

        if (module == null) {
          Console.WriteLine(args[0] + " is not a PE file containing a CLR module or assembly.");
          return;
        }

        var platformType = new MyPlatformType(host);
        INamespaceTypeReference systemArgumentNullException = platformType.SystemArgumentNullException;
        IName ctor = host.NameTable.Ctor;

        //write out the signature of every method that contains the IL equivalent of "throw new System.ArgumentNullException();"
        foreach (var type in module.GetAllTypes()) {
          foreach (var methodDefinition in type.Methods) {
            var lastInstructionWasNewObjSystemArgumentNull = false;
            foreach (var operation in methodDefinition.Body.Operations) {
              if (operation.OperationCode == OperationCode.Newobj) {
                var consRef = operation.Value as IMethodReference;
                if (consRef != null && consRef.Name == ctor &&
                  TypeHelper.TypesAreEquivalent(consRef.ContainingType, systemArgumentNullException)) {
                  lastInstructionWasNewObjSystemArgumentNull = true;
                }
              } else if (lastInstructionWasNewObjSystemArgumentNull && operation.OperationCode == OperationCode.Throw) {
                Console.WriteLine(MemberHelper.GetMethodSignature(methodDefinition,
                  NameFormattingOptions.ReturnType|NameFormattingOptions.TypeParameters|NameFormattingOptions.Signature));
                break;
              } else {
                lastInstructionWasNewObjSystemArgumentNull = false;
              }
            }
          }
        }
      }
    }
Exemplo n.º 15
0
        public GraphRandomStateGenerator(IModule module, PeReader.DefaultHost host, Log.Log logger, CfgManipulator cfgManipulator, Helper helperClass, Graph.Graph graph, MethodCfg methodCfg, bool debugging) {

            this.module = module;
            this.host = host;
            this.logger = logger;
            this.cfgManipulator = cfgManipulator;            
            this.helperClass = helperClass;
            this.graph = graph;
            this.methodCfg = methodCfg;
            this.debugging = debugging;

            // add local random generator variable
            this.tempRandomLocal = new LocalDefinition();
            this.tempRandomLocal.IsReference = false;
            this.tempRandomLocal.IsPinned = false;
            this.tempRandomLocal.IsModified = false;
            this.tempRandomLocal.Type = this.helperClass.systemRandom;
            this.tempRandomLocal.MethodDefinition = methodCfg.method;
            cfgManipulator.addLocalVariable(this.tempRandomLocal);


        }
Exemplo n.º 16
0
 public CfgBuilder(IModule module, PeReader.DefaultHost host, Log.Log logger) {
     this.host = host;
     this.logger = logger;
     this.module = module;
 }
Exemplo n.º 17
0
        static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ILWeave [Assembly]");

                return 1;
            }

            string tmpDir, newName, newPdb;

            using (var host = new PeReader.DefaultHost())
            {
                var module = host.LoadUnitFrom(args[0]) as IModule;

                if (module == null || module is Dummy)
                {
                    Console.WriteLine("{0} is not a PE file containing a CLR assembly, or an error occurred when loading it.", args[0]);

                    return 1;
                }

                module = new MetadataDeepCopier(host).Copy(module);
                PdbReader pdbReader = null;
                var pdbFile = Path.ChangeExtension(module.Location, "pdb");

                if (File.Exists(pdbFile))
                {
                    using (var pdbStream = File.OpenRead(pdbFile))
                    {
                        pdbReader = new PdbReader(pdbStream, host);
                    }
                }
                else
                {
                    Console.WriteLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");
                }
                using (pdbReader)
                {
                    var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader);

                    try
                    {
                        module = PropertyChangedWeaver.RewriteModule(
                            host,
                            localScopeProvider,
                            pdbReader,
                            module);
                    }
                    catch (InvalidOperationException e)
                    {
                        Console.WriteLine("Error: {0}", e);
                        Environment.Exit(5);
                    }

                    tmpDir = Directory.CreateDirectory(Path.GetRandomFileName()).FullName;
                    newName = Path.Combine(tmpDir, Path.GetFileName(args[0]));

                    using (var peStream = File.Create(newName))
                    {
                        newPdb = Path.ChangeExtension(newName, ".pdb");

                        using (var pdbWriter = new PdbWriter(newPdb, pdbReader))
                        {
                            PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter);
                        }
                    }
                }
            }

            var dst = Path.GetDirectoryName(args[0]);

            foreach (var s in Directory.GetFiles(tmpDir))
            {
                File.Copy(s, Path.Combine(dst, Path.GetFileName(s)), true);
            }

            Directory.Delete(tmpDir, true);

            return 0;
        }
    static void CompileSourcesAndRun(string[] sources, string extension, CompiledResultDelegate resultDelegate) {
      TemporaryFile[] compiledAssemblyPaths = CompileSources(sources, extension);

      using (var host = new PeReader.DefaultHost()) {

        IAssembly[] loadedAssemblies = compiledAssemblyPaths.Select(pathToAssembly => {
          var assembly = host.LoadUnitFrom(pathToAssembly.Path) as IAssembly;
          Assert.IsNotNull(assembly);
          return assembly;
        }).ToArray();

        IAssembly mainAssembly = loadedAssemblies.Last();
        IAssembly[] referencedAssemblies = loadedAssemblies.Take(loadedAssemblies.Length - 1).ToArray();

        TestCompilerResults results = new TestCompilerResults(mainAssembly, referencedAssemblies, host);

        resultDelegate(results);
      }

      foreach (var tempFile in compiledAssemblyPaths) {
        tempFile.Dispose();
      }
    }
Exemplo n.º 19
0
        static void Main(string[] args) {

            //String inputFile = @"c:\Users\typ\Documents\Visual Studio 2013\Projects\vererbung\vererbung\bin\Debug\vererbung.exe";
            String inputFile = @"e:\dile_v0_2_12_x86\Dile.exe";

            

            globalLog = new Log(@"e:\merge_logfile.txt");

            System.Console.WriteLine(inputFile);

            /*
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Usage: ILMutator <assembly> [<outputPath>]");
                return;
            }
            */




            using (var host = new PeReader.DefaultHost()) {
                //IModule/*?*/ module = host.LoadUnitFrom(args[0]) as IModule;
                IModule/*?*/ module = host.LoadUnitFrom(inputFile) 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.");
                    Console.WriteLine(inputFile + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                module = new MetadataDeepCopier(host).Copy(module);

                if (module as Assembly == null) {
                    globalLog.writeLine("File does not have CIL assembly");
                    return;
                }


                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);
                    }
                }
                else {
                    globalLog.writeLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");
                }

                using (pdbReader) {

                    Microsoft.Cci.ILGenerator.LocalScopeProvider localScopeProvider = null;
                    if (pdbReader != null) {
                        localScopeProvider = new ILGenerator.LocalScopeProvider(pdbReader);
                    }











                    // AB HIER DER INTERESSANTE PART ZUM MERGEN, DAVOR NUR INIT CRAP

                    // search for class in namespace
                    NamespaceTypeDefinition foundClass = null;
                    foreach (var asdf in module.GetAllTypes()) {
                        //if (asdf.ToString() == "vererbung.Erber") {
                        if (asdf.ToString() == "Dile.Disassemble.Assembly") {                            
                            foundClass = (asdf as NamespaceTypeDefinition);
                            break;
                        }
                    }
                    if (foundClass == null) {
                        globalLog.writeLine("Class not found!");
                        return;
                    }

                    // merge class
                    globalLog.writeLine("Merge class \"" + foundClass.ToString() + "\" with all ancestors");
                    mergeClassWithAllAncestors(foundClass, host);






                    string newName;
                    if (args.Length == 2) {
                        newName = args[1];
                        //newName = @"e:\dile_v0_2_12_x86\dile_classes.exe";
                        newName = @"e:\test.exe";
                    }
                    else {
                        var loc = module.Location;
                        var path = Path.GetDirectoryName(loc) ?? "";
                        var fileName = Path.GetFileNameWithoutExtension(loc);
                        var ext = Path.GetExtension(loc);
                        newName = Path.Combine(path, fileName + "1" + ext);
                        //newName = @"e:\dile_v0_2_12_x86\dile_classes.exe";
                        newName = @"e:\test.exe";
                    }

                    using (var peStream = File.Create(newName)) {
                        using (var pdbWriter = new PdbWriter(Path.ChangeExtension(newName, ".pdb"), pdbReader)) {
                            PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
 public void Analyze(string assemblyPath)
 {
     Report = new MetricsReport();
     using (var host = new PeReader.DefaultHost())
         TryToAnalyzeInHost(assemblyPath, host);
 }
Exemplo n.º 21
0
    static void Main(string[] args) {
      var nameTable = new NameTable();
      using (var host = new PeReader.DefaultHost(nameTable)) {
        var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity);

        var assembly = new Assembly() {
          Name = nameTable.GetNameFor("hello"),
          ModuleName = nameTable.GetNameFor("hello.exe"),
          PlatformType = host.PlatformType,
          Kind = ModuleKind.ConsoleApplication,
          RequiresStartupStub = host.PointerSize == 4,
          TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion,
        };
        assembly.AssemblyReferences.Add(coreAssembly);

        var rootUnitNamespace = new RootUnitNamespace();
        assembly.UnitNamespaceRoot = rootUnitNamespace;
        rootUnitNamespace.Unit = assembly;

        var moduleClass = new NamespaceTypeDefinition() {
          ContainingUnitNamespace = rootUnitNamespace,
          InternFactory = host.InternFactory,
          IsClass = true,
          Name = nameTable.GetNameFor("<Module>"),
        };
        assembly.AllTypes.Add(moduleClass);

        var testClass = new NamespaceTypeDefinition() {
          ContainingUnitNamespace = rootUnitNamespace,
          InternFactory = host.InternFactory,
          IsClass = true,
          IsPublic = true,
          Methods = new List<IMethodDefinition>(1),
          Name = nameTable.GetNameFor("Test"),
        };
        rootUnitNamespace.Members.Add(testClass);
        assembly.AllTypes.Add(testClass);
        testClass.BaseClasses = new List<ITypeReference>() { host.PlatformType.SystemObject };

        var mainMethod = new MethodDefinition() {
          ContainingTypeDefinition = testClass,
          InternFactory = host.InternFactory,
          IsCil = true,
          IsStatic = true,
          Name = nameTable.GetNameFor("Main"),
          Type = host.PlatformType.SystemVoid,
          Visibility = TypeMemberVisibility.Public,
        };
        assembly.EntryPoint = mainMethod;
        testClass.Methods.Add(mainMethod);

        var ilGenerator = new ILGenerator(host, mainMethod);

        var systemConsole = UnitHelper.FindType(nameTable, coreAssembly, "System.Console");
        var writeLine = TypeHelper.GetMethod(systemConsole, nameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString);

        ilGenerator.Emit(OperationCode.Ldstr, "hello");
        ilGenerator.Emit(OperationCode.Call, writeLine);
        ilGenerator.Emit(OperationCode.Ret);

        var body = new ILGeneratorMethodBody(ilGenerator, true, 1, mainMethod, Enumerable<ILocalDefinition>.Empty, Enumerable<ITypeDefinition>.Empty);
        mainMethod.Body = body;

        using (var peStream = File.Create("hello.exe")) {
          PeWriter.WritePeToStream(assembly, host, peStream);
        }
      }
    }
Exemplo n.º 22
0
        internal static void Amend(params string[] targets)
        {
            // Ensure that at least one target assembly was specified
            if (targets == null || targets.Length == 0)
                throw new ArgumentException("At least one target assembly must be specified.");

            // Ensure that the target assemblies exist
            for (int i = 0; i < targets.Length; i++)
            {
                var path = targets[i] = Path.GetFullPath(targets[i]);
                if (!File.Exists(path))
                    throw new ArgumentException("The specified target assembly, " + path + ", does not exist.");
            }

            // Determine the set of target directories and backup locations
            var directories = targets
                .Select(path => Path.GetDirectoryName(path).ToLower())
                .Distinct()
                .Select(directory => new { SourcePath = directory, BackupPath = Directory.CreateDirectory(Path.Combine(directory, "Backup")).FullName });

            // Determine the set of dlls, pdbs, and backup files
            var assemblies = targets
                .Select(dllPath => new
                {
                    DllPath = dllPath,
                    DllBackupPath = Path.Combine(Path.Combine(Path.GetDirectoryName(dllPath), "Backup"), Path.GetFileName(dllPath)),
                    PdbPath = Path.Combine(Path.GetDirectoryName(dllPath), Path.GetFileNameWithoutExtension(dllPath) + ".pdb"),
                    PdbBackupPath = Path.Combine(Path.Combine(Path.GetDirectoryName(dllPath), "Backup"), Path.GetFileNameWithoutExtension(dllPath) + ".pdb")
                });

            // Backup the directories containing the targeted dll and pdb files
            foreach (var directory in directories)
            {
                foreach (var file in Directory.GetFiles(directory.SourcePath))
                {
                    if (file.ToLower().EndsWith("exe") || file.ToLower().EndsWith("dll") || file.ToLower().EndsWith("pdb"))
                    {
                        var backupPath = Path.Combine(directory.BackupPath, Path.GetFileName(file));
                        if (File.Exists(backupPath))
                            File.SetAttributes(backupPath, File.GetAttributes(backupPath) & ~FileAttributes.ReadOnly);
                        File.Copy(file, backupPath, true);
                    }
                }
            }

            // Register an assembly resolver to look in backup folders when resolving assemblies
            AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
            {
                var assemblyName = new AssemblyName(e.Name).Name + ".dll";

                // First see if the assembly is located in one of the target backup directories
                foreach (var directory in directories)
                {
                    var dependency = Path.Combine(directory.BackupPath, assemblyName);
                    if (File.Exists(dependency))
                        return System.Reflection.Assembly.LoadFrom(dependency);
                }

                return null;
            };

            // Get the set of amendments to apply from all of the specified assemblies
            var amendments = AmendmentAttribute.GetAmendments(assemblies.Select(a => System.Reflection.Assembly.LoadFrom(a.DllBackupPath)).ToArray()).ToList();

            // Exit immediately if there are no amendments in the target assemblies
            if (amendments.Count == 0)
                return;

            // Process each target assembly individually
            foreach (var assembly in assemblies)
            {
                var assemblyAmendments = amendments.Where(a => a.Type.Assembly.Location == assembly.DllBackupPath).ToArray();
                if (assemblyAmendments.Length == 0)
                    continue;

                Console.Write("Amending " + Path.GetFileName(assembly.DllPath));
                var start = DateTime.Now;

                using (var host = new PeReader.DefaultHost())
                {
                    // Load the target assembly
                    IModule module = host.LoadUnitFrom(assembly.DllBackupPath) as IModule;
                    if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                        throw new ArgumentException(assembly.DllBackupPath + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");

                    // Copy the assembly to enable it to be mutated
                    module = new MetadataDeepCopier(host).Copy(module);

                    // Load the debug file if it exists
                    PdbReader pdbReader = null;
                    if (File.Exists(assembly.PdbBackupPath))
                    {
                        using (var pdbStream = File.OpenRead(assembly.PdbBackupPath))
                        {
                            pdbReader = new PdbReader(pdbStream, host);
                        }
                    }

                    // Amend and persist the target assembly
                    using (pdbReader)
                    {
                        // Create and execute a new assembly amender
                        AssemblyAmender amender = new AssemblyAmender(host, pdbReader, assemblyAmendments);
                        amender.TargetRuntimeVersion = module.TargetRuntimeVersion;
                        module = amender.Visit(module);

                        // Save the amended assembly back to the original directory
                        using (var pdbWriter = pdbReader != null ? new PdbWriter(assembly.PdbPath, pdbReader) : null)
                        {
                            using (var dllStream = File.Create(assembly.DllPath))
                            {
                                PeWriter.WritePeToStream(module, host, dllStream, pdbReader, null, pdbWriter);
                            }
                        }
                    }
                }
                Console.WriteLine(" (" + DateTime.Now.Subtract(start).TotalSeconds.ToString("0.000") + " seconds)");
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args) {
            String inputFile;
            String targetFile;
            String targetNamespace;
            String targetClass;
            String targetMethod;
            int depth;
            int dimension;
            int numberValidPaths;
            int duplicateBasicBlockWeight;
            int duplicateBasicBlockCorrectionValue;
            int stateChangeWeight;
            int stateChangeCorrectionValue;
            int insertOpaquePredicateWeight;
            int seed;

            // Add debugging code into the obfuscated method (dump obfuscation graphs and so on)
            bool graphTransformerDebug = false;

            // Should the obfuscated code contain information to trace the control flow?
            bool basicBlockTrace = false;

            // When debugging is active, should the whole obfuscation graph be dumped or only the vpaths in it?
            bool graphOnlyDumpVPaths = true;

            // The number of random interfaces that are added to the program
            int numberRandomInterfaces = 100;

            if (args.Length != 14) {
                System.Console.WriteLine("Needed parameters: <inputBinary> <outputBinary> <namespace> <class> <method> <depth> <dimension> <numberValidPaths> <duplicateBasicBlockWeight> <duplicateBasicBlockCorrectionValue> <stateChangeWeight> <stateChangeCorrectionValue> <insertOpaquePredicateWeight> <seed>");
                return;
            }
            else {
                inputFile = args[0];
                targetFile = args[1];
                targetNamespace = args[2];
                targetClass = args[3];
                targetMethod = args[4];
                depth = Convert.ToInt32(args[5]);
                dimension = Convert.ToInt32(args[6]);
                numberValidPaths = Convert.ToInt32(args[7]);
                duplicateBasicBlockWeight = Convert.ToInt32(args[8]);
                duplicateBasicBlockCorrectionValue = Convert.ToInt32(args[9]);
                stateChangeWeight = Convert.ToInt32(args[10]);
                stateChangeCorrectionValue = Convert.ToInt32(args[11]);
                insertOpaquePredicateWeight = Convert.ToInt32(args[12]);
                seed = Convert.ToInt32(args[13]);
            }

            String logDir = Path.GetDirectoryName(targetFile);
            Log.Log logger = new Log.Log(logDir, "probfuscation_logfile.txt");

            System.Console.WriteLine("Obfuscating: " + inputFile);
            logger.writeLine("Obfuscating: " + inputFile);
            System.Console.WriteLine("Output file: " + targetFile);
            logger.writeLine("Output file: " + targetFile);
            System.Console.WriteLine("Target namespace: " + targetNamespace);
            logger.writeLine("Target namespace: " + targetNamespace);
            System.Console.WriteLine("Target class: " + targetClass);
            logger.writeLine("Target class: " + targetClass);
            System.Console.WriteLine("Target method: " + targetMethod);
            logger.writeLine("Target method: " + targetMethod);
            System.Console.WriteLine("Depth: " + depth);
            logger.writeLine("Depth: " + depth);
            System.Console.WriteLine("Dimension: " + dimension);
            logger.writeLine("Dimension: " + dimension);
            System.Console.WriteLine("Number of vpaths: " + numberValidPaths);
            logger.writeLine("Number of vpaths: " + numberValidPaths);
            System.Console.WriteLine("Basic Block duplication weight: " + duplicateBasicBlockWeight);
            logger.writeLine("Basic Block duplication weight: " + duplicateBasicBlockWeight);
            System.Console.WriteLine("Basic Block duplication correction value: " + duplicateBasicBlockCorrectionValue);
            logger.writeLine("Basic Block duplication correction value: " + duplicateBasicBlockCorrectionValue);
            System.Console.WriteLine("State change weight: " + stateChangeWeight);
            logger.writeLine("State change weight: " + stateChangeWeight);
            System.Console.WriteLine("State change correction value: " + stateChangeCorrectionValue);
            logger.writeLine("State change correction value: " + stateChangeCorrectionValue);
            System.Console.WriteLine("Opaque predicate weight: " + insertOpaquePredicateWeight);
            logger.writeLine("Opaque predicate weight: " + insertOpaquePredicateWeight);
            System.Console.WriteLine("Seed: " + seed);
            logger.writeLine("Seed: " + seed);

            // Seed PRNG for interfaces
            PRNGRandomInterfaces = new Random(seed);

            using (var host = new PeReader.DefaultHost()) {
                IModule/*?*/ module = host.LoadUnitFrom(inputFile) as IModule;

                if (module == null || module == Dummy.Module || module == Dummy.Assembly) {
                    Console.WriteLine(inputFile + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                module = new MetadataDeepCopier(host).Copy(module);

                if (module as Assembly == null) {
                    logger.writeLine("File does not have CIL assembly");
                    return;
                }

                // create analyzer object object                
                CfgBuilder analyze = new Cfg.CfgBuilder(module, host, logger);

                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);
                    }
                }
                else {
                    logger.writeLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");
                }

                using (pdbReader) {

                    Microsoft.Cci.ILGenerator.LocalScopeProvider localScopeProvider = null;
                    if (pdbReader != null) {
                        localScopeProvider = new ILGenerator.LocalScopeProvider(pdbReader);
                    }

                    // search the namespace the interface should be added to
                    IUnitNamespace foundNamespace = null;
                    foreach (var tempMember in module.UnitNamespaceRoot.Members) {

                        if ((tempMember as IUnitNamespace) == null) {
                            continue;
                        }

                        IUnitNamespace tempNamespace = (tempMember as IUnitNamespace);

                        if (tempNamespace.ToString() == targetNamespace) {
                            foundNamespace = tempNamespace;
                            break;
                        }
                    }
                    if (foundNamespace == null) {
                        throw new ArgumentException("Not able to find target namespace.");
                    }

                    // add created interface (and implemented methods) to all classes
                    bool classFound = false;
                    foreach (var tempClass in module.GetAllTypes()) {
                        if ((tempClass as NamespaceTypeDefinition) == null
                            || tempClass.IsAbstract) {
                            continue;
                        }

                        NamespaceTypeDefinition foundClass = (tempClass as NamespaceTypeDefinition);

                        if (foundClass.ContainingUnitNamespace.ToString() == "") {
                            continue;
                        }
                        if (foundClass.ToString() != targetNamespace + "." + targetClass) {
                            continue;
                        }
                        classFound = true;

                        Random prng = new Random();
                        GraphTransformer graphTransformer = new GraphTransformer(module, host, logger, prng, foundNamespace, foundClass, depth, dimension, graphTransformerDebug);

                        graphTransformer.duplicateBasicBlockWeight = duplicateBasicBlockWeight;
                        graphTransformer.duplicateBasicBlockCorrectionValue = duplicateBasicBlockCorrectionValue;
                        graphTransformer.stateChangeWeight = stateChangeWeight;
                        graphTransformer.stateChangeCorrectionValue = stateChangeCorrectionValue;
                        graphTransformer.insertOpaquePredicateWeight = insertOpaquePredicateWeight;
                        graphTransformer.trace = basicBlockTrace;
                        graphTransformer.graphOnlyDumpVPaths = graphOnlyDumpVPaths;
                        graphTransformer.debuggingDumpLocation = logDir;

                        // Add 100 random interfaces to the namespace
                        Helper testHelper = new Helper(module, host, logger);
                        List<NamespaceTypeDefinition> randomInterfaces = new List<NamespaceTypeDefinition>();
                        for (int i = 0; i < numberRandomInterfaces; i++) {
                            String randName = randomString(20);
                            NamespaceTypeDefinition temp = testHelper.createNewInterface(randName, foundNamespace);
                            randomInterfaces.Add(temp);
                        }

                        InterfaceTransformer interfaceTransformer = new InterfaceTransformer(module, host, logger);
                        foreach (var classToAdd in module.GetAllTypes()) {
                            if ((classToAdd as NamespaceTypeDefinition) == null
                                || classToAdd.IsAbstract
                                || classToAdd.IsInterface
                                || classToAdd.IsEnum
                                || classToAdd.IsDelegate
                                || classToAdd.IsGeneric
                                || classToAdd.IsStruct) {
                                continue;
                            }

                            if (((NamespaceTypeDefinition)classToAdd).ContainingUnitNamespace.ToString() == "") {
                                continue;
                            }

                            /*
                            // Use this code if you want to add standard interfaces to the target class
                            interfaceTransformer.addStdInterfacesGivenByFile(@"e:\code\dotnet_standard_interfaces.txt");

                            // add std interfaces to class
                            if (foundClass != (classToAdd as NamespaceTypeDefinition)) {
                                foreach (ITypeDefinition temp in interfaceTransformer.getInterfacesList()) {
                                    interfaceTransformer.addInterface((classToAdd as NamespaceTypeDefinition), temp);
                                }
                            }
                            */

                            // Add random interfaces to the classes
                            List<NamespaceTypeDefinition> alreadyAdded = new List<NamespaceTypeDefinition>();
                            int max = PRNGRandomInterfaces.Next(numberRandomInterfaces);
                            NamespaceTypeDefinition interfaceClass = (classToAdd as NamespaceTypeDefinition);
                            logger.writeLine("Adding " + max + " random interfaces to class \"" + interfaceClass.ToString() + "\"");
                            for (int i = 0; i < max; i++) {
                                NamespaceTypeDefinition randInterface = randomInterfaces.ElementAt(PRNGRandomInterfaces.Next(randomInterfaces.Count));
                                if (alreadyAdded.Contains(randInterface)) {
                                    continue;
                                }
                                alreadyAdded.Add(randInterface);
                                logger.writeLine("Adding interface: \"" + randInterface.ToString() + "\"");

                                // add nodes interface to class
                                if (interfaceClass.Interfaces != null) {
                                    interfaceClass.Interfaces.Add(randInterface);
                                }
                                else {
                                    interfaceClass.Interfaces = new List<ITypeReference>();
                                    interfaceClass.Interfaces.Add(randInterface);
                                }
                            }
                            logger.writeLine("");

                            // Add special interface for the obfuscation scheme to the class
                            // (makes sure that all needed attributes and methods are implemented)
                            graphTransformer.addNodeInterfaceToTargetClass((classToAdd as NamespaceTypeDefinition));
                        }

                        // Prepare obfuscation graph
                        graphTransformer.generateGraph(numberValidPaths);
                        graphTransformer.createGraphMethods();

                        // Search method to obfuscate
                        MethodDefinition methodToObfu = null;
                        foreach (MethodDefinition tempMethod in foundClass.Methods) {
                            if (tempMethod.Name.ToString() == targetMethod) {
                                methodToObfu = tempMethod;
                                break;
                            }
                        }
                        if (methodToObfu == null) {
                            throw new ArgumentException("Not able to find target method.");
                        }

                        // Obfuscate target method
                        MethodCfg cfg = analyze.buildCfgForMethod(methodToObfu);
                        logger.dumpMethodCfg(cfg, "before");
                        graphTransformer.addObfuscationToMethod(cfg);
                        analyze.createMethodFromCfg(cfg);
                        logger.dumpMethodCfg(cfg, "after");

                        break;
                    }
                    if (!classFound) {
                        throw new ArgumentException("Not able to find target class.");
                    }


                    /*
                     * This code can be used if not only one specific method should be obfuscated,
                     * but the whole class.
                    List<ClassCfg> classCfgList = new List<ClassCfg>();
                    foreach (var tempClass in module.GetAllTypes()) {
                        if ((tempClass as NamespaceTypeDefinition) == null
                            || tempClass.IsAbstract) {
                            continue;
                        }

                        // create basic blocks
                        NamespaceTypeDefinition foundClass = (tempClass as NamespaceTypeDefinition);

                        logger.writeLine("Create CFG for class \"" + foundClass.Name.ToString() + "\"");
                        ClassCfg temp = analyze.buildCfgForClass(foundClass);
                        classCfgList.Add(temp);
                        logger.writeLine("\n---------------------------------\n");
                    }

                    // transform each function
                    NopTransformer transformator = new NopTransformer(module, host, logger);
                    foreach (ClassCfg tempClassCfg in classCfgList) {
                        foreach (MethodCfg tempMethodCfg in tempClassCfg.methodCfgs) {
                            logger.writeLine("Transform method CFG of \"" + tempMethodCfg.method.ToString() + "\"");
                            transformator.addNopsToCfg(tempMethodCfg);
                            logger.writeLine("\n---------------------------------\n");
                        }
                    }

                    foreach (ClassCfg tempClassCfg in classCfgList) {
                        logger.writeLine("Create class from CFG for \"" + tempClassCfg.classObj.Name.ToString() + "\"");
                        analyze.createClassFromCfg(tempClassCfg);
                        logger.writeLine("\n---------------------------------\n");
                    }
                    */

                    using (var peStream = File.Create(targetFile)) {
                        using (var pdbWriter = new PdbWriter(Path.ChangeExtension(targetFile, ".pdb"), pdbReader)) {
                            PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter);
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
    private static MetadataReaderHost GetHostFromOptions(ILGarbageCollectorOptions options) {
      MetadataReaderHost host;

      switch (options.profile) {
        case TargetProfile.Phone:
          host = new PhoneMetadataHost(GetRootAssemblyParentDirectoriesFromOptions(options));
          break;

        default:
          host = new PeReader.DefaultHost();
          break;
      }

      return host;
    }
Exemplo n.º 25
0
        public void Compile(string fileName)
        {
            string appName = Path.GetFileNameWithoutExtension(fileName);
            string exeName = appName + ".exe";
            string src = "";
            using (TextReader file = new StreamReader(fileName))
            {
                src = file.ReadToEnd();
            }

            var nameTable = new NameTable();
            using (var host = new PeReader.DefaultHost(nameTable))
            {
                // Load Mirage types

                IModule module = host.LoadUnitFrom("Mirage.dll") as IModule;
                if (module == null || module is Dummy)
                {
                    return;
                }
                var machineType = module.GetAllTypes().First(x => x.Name.Value == "Machine");
                var inputType = module.GetAllTypes().First(x => x.Name.Value == "ConsoleInput");
                var outputType = module.GetAllTypes().First(x => x.Name.Value == "ConsoleOutput");

                // Create assembly

                var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity);
                var assembly = new Assembly()
                {
                    Name = nameTable.GetNameFor(appName),
                    ModuleName = nameTable.GetNameFor(exeName),
                    PlatformType = host.PlatformType,
                    Kind = ModuleKind.ConsoleApplication,
                    RequiresStartupStub = host.PointerSize == 4,
                    TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion,
                };
                assembly.AssemblyReferences.Add(coreAssembly);

                // Create namespace

                var rootUnitNamespace = new RootUnitNamespace();
                assembly.UnitNamespaceRoot = rootUnitNamespace;
                rootUnitNamespace.Unit = assembly;

                // Create module class

                var moduleClass = new NamespaceTypeDefinition()
                {
                    ContainingUnitNamespace = rootUnitNamespace,
                    InternFactory = host.InternFactory,
                    IsClass = true,
                    Name = nameTable.GetNameFor("<Module>"),
                };
                assembly.AllTypes.Add(moduleClass);

                // Create program class

                var programClass = new NamespaceTypeDefinition()
                {
                    ContainingUnitNamespace = rootUnitNamespace,
                    InternFactory = host.InternFactory,
                    IsClass = true,
                    IsPublic = true,
                    Methods = new List<IMethodDefinition>(1),
                    Name = nameTable.GetNameFor("Program"),
                };
                programClass.BaseClasses = new List<ITypeReference>() { host.PlatformType.SystemObject };
                rootUnitNamespace.Members.Add(programClass);

                // Add types to the assembly

                assembly.AllTypes.Add(machineType);
                foreach (var t in machineType.NestedTypes)
                {
                    assembly.AllTypes.Add(t);
                }
                assembly.AllTypes.Add(inputType);
                assembly.AllTypes.Add(outputType);
                assembly.AllTypes.Add(programClass);

                // Create main method

                var mainMethod = new MethodDefinition()
                {
                    ContainingTypeDefinition = programClass,
                    InternFactory = host.InternFactory,
                    IsCil = true,
                    IsStatic = true,
                    Name = nameTable.GetNameFor("Main"),
                    Type = host.PlatformType.SystemVoid,
                    Visibility = TypeMemberVisibility.Public,
                };
                assembly.EntryPoint = mainMethod;
                programClass.Methods.Add(mainMethod);

                // Create constructors and methods

                IMethodReference machineConstructor = new Microsoft.Cci.MethodReference(
                    host,
                    machineType,
                    CallingConvention.HasThis,
                    host.PlatformType.SystemVoid,
                    host.NameTable.Ctor,
                    0
                );

                IMethodReference inputConstructor = new Microsoft.Cci.MethodReference(
                    host,
                    inputType,
                    CallingConvention.HasThis,
                    host.PlatformType.SystemVoid,
                    host.NameTable.Ctor,
                    0
                );
                var inputCast = TypeHelper.GetMethod(inputType, nameTable.GetNameFor("op_Implicit"), inputType);

                IMethodReference outputConstructor = new Microsoft.Cci.MethodReference(
                    host,
                    outputType,
                    CallingConvention.HasThis,
                    host.PlatformType.SystemVoid,
                    host.NameTable.Ctor,
                    0
                );
                var outputCast = TypeHelper.GetMethod(outputType, nameTable.GetNameFor("op_Implicit"), outputType);

                var opIncPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("IncPointers"));
                var opDecPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DecPointers"));
                var opIncHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("IncHiPointer"));
                var opDecHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DecHiPointer"));
                var opReflectHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("ReflectHiPointer"));
                var opLoadHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("LoadHiPointer"));
                var opDragLoPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DragLoPointer"));
                var opXchPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("XchPointers"));

                var opClear = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Clear"));
                var opAdd = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Add"));
                var opDec = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Dec"));
                var opNot = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Not"));
                var opAnd = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("And"));
                var opOr = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Or"));
                var opXor = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Xor"));
                var opSal = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Sal"));
                var opSar = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Sar"));

                var opLoadData = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("LoadData"), host.PlatformType.SystemString);
                var opInput = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Input"), inputCast.Type);
                var opOutput = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Output"), outputCast.Type);

                var opJz = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Jz"));

                // Create program code

                var labels = new Stack<ILGeneratorLabel>(100);

                var ilGenerator = new ILGenerator(host, mainMethod);
                ilGenerator.Emit(OperationCode.Newobj, machineConstructor);
                ilGenerator.Emit(OperationCode.Stloc_0);
                ilGenerator.Emit(OperationCode.Newobj, inputConstructor);
                ilGenerator.Emit(OperationCode.Stloc_1);
                ilGenerator.Emit(OperationCode.Newobj, outputConstructor);
                ilGenerator.Emit(OperationCode.Stloc_2);

                int pc = 0;
                while (pc < src.Length)
                {
                    char opcode = src[pc++];

                    switch (opcode)
                    {
                        case '>':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opIncPointers);
                            break;
                        case '<':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opDecPointers);
                            break;
                        case ']':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opIncHiPointer);
                            break;
                        case '[':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opDecHiPointer);
                            break;
                        case '#':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opReflectHiPointer);
                            break;
                        case '$':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opLoadHiPointer);
                            break;
                        case '=':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opDragLoPointer);
                            break;
                        case '%':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opXchPointers);
                            break;
                        case '_':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opClear);
                            break;
                        case '+':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opAdd);
                            break;
                        case '-':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opDec);
                            break;
                        case '~':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opNot);
                            break;
                        case '&':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opAnd);
                            break;
                        case '|':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opOr);
                            break;
                        case '^':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opXor);
                            break;
                        case '*':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opSal);
                            break;
                        case '/':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opSar);
                            break;
                        case '(':
                            int dataStart = pc;
                            int dataEnd = dataStart;
                            while (src[pc++] != ')')
                            {
                                dataEnd = pc;
                            }
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Ldstr, src.Substring(dataStart, dataEnd - dataStart));
                            ilGenerator.Emit(OperationCode.Callvirt, opLoadData);
                            break;
                        case '?':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Ldloc_1);
                            ilGenerator.Emit(OperationCode.Call, inputCast);
                            ilGenerator.Emit(OperationCode.Callvirt, opInput);
                            break;
                        case '!':
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Ldloc_2);
                            ilGenerator.Emit(OperationCode.Call, outputCast);
                            ilGenerator.Emit(OperationCode.Callvirt, opOutput);
                            break;
                        case '{':
                            var cycleStart = new ILGeneratorLabel();
                            var cycleEnd = new ILGeneratorLabel();
                            labels.Push(cycleStart);
                            labels.Push(cycleEnd);
                            ilGenerator.Emit(OperationCode.Br, cycleEnd);
                            ilGenerator.MarkLabel(cycleStart);
                            break;
                        case '}':
                            ilGenerator.MarkLabel(labels.Pop());
                            ilGenerator.Emit(OperationCode.Ldloc_0);
                            ilGenerator.Emit(OperationCode.Callvirt, opJz);
                            ilGenerator.Emit(OperationCode.Ldc_I4_0);
                            ilGenerator.Emit(OperationCode.Ceq);
                            ilGenerator.Emit(OperationCode.Stloc_3);
                            ilGenerator.Emit(OperationCode.Ldloc_3);
                            ilGenerator.Emit(OperationCode.Brtrue, labels.Pop());
                            break;
                        default:
                            break;
                    }
                }

                ilGenerator.Emit(OperationCode.Ret);

                mainMethod.Body = new ILGeneratorMethodBody(
                    ilGenerator,
                    true,
                    8,
                    mainMethod,
                    new List<ILocalDefinition>() {
                        new LocalDefinition() { Type = machineType },
                        new LocalDefinition() { Type = inputType },
                        new LocalDefinition() { Type = outputType },
                        new LocalDefinition() { Type = host.PlatformType.SystemInt32 },
                    },
                    Enumerable<ITypeDefinition>.Empty
                );

                using (var peStream = File.Create(exeName))
                {
                    PeWriter.WritePeToStream(assembly, host, peStream);
                }
            }
        }
Exemplo n.º 26
0
		/// <summary>
		/// Amends the specified target assembly, optionally using assembly amendments defined in the 
		/// specified amendment assemblies.
		/// </summary>
		/// <param name="targetAssembly"></param>
		/// <param name="amendmentAssemblies"></param>
		internal static void Amend(string targetAssembly, string[] amendmentAssemblies, string[] referenceAssemblies)
		{
			// Verify the target assembly exists
			targetAssembly = Path.GetFullPath(targetAssembly);
			if (!File.Exists(targetAssembly))
				throw new ArgumentException("The specified target assembly, " + targetAssembly + ", does not exist.");

			// Verify the amendment assemblies exist
			if (amendmentAssemblies == null)
				amendmentAssemblies = new string[0];
			for (int i = 0; i < amendmentAssemblies.Length; i++)
			{
				var path = amendmentAssemblies[i] = Path.GetFullPath(amendmentAssemblies[i]);
				if (!File.Exists(path))
					throw new ArgumentException("The specified amendment assembly, " + path + ", does not exist.");
			}

			// Verify that the target has not already been amended
			var afterthoughtTracker = targetAssembly + ".afterthought";
			if (File.Exists(afterthoughtTracker) && File.GetLastWriteTime(targetAssembly) == File.GetLastWriteTime(afterthoughtTracker))
				return;

			// Determine the set of target directories and backup locations
			var targetWriteTime = File.GetLastWriteTime(targetAssembly);
			var backupTargetAssembly = targetAssembly + ".backup";
			var targetDirectory = Path.GetDirectoryName(targetAssembly);
			File.Delete(backupTargetAssembly);
			File.Move(targetAssembly, backupTargetAssembly);

			// Build up a set of paths with resolving assemblies
			var referencePaths = new Dictionary<string, string>();
			foreach (string path in amendmentAssemblies
				.Union(referenceAssemblies)
				.Union(Directory.GetFiles(targetDirectory).Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && p != targetAssembly)))
				referencePaths[Path.GetFileName(path)] = path;

			// Register an assembly resolver to look in assembly directories when resolving assemblies
			AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
			{
				var assemblyName = new System.Reflection.AssemblyName(e.Name).Name + ".dll";
				string referencePath;
				if (referencePaths.TryGetValue(assemblyName, out referencePath))
					return System.Reflection.Assembly.LoadFrom(referencePath);

				return null;
			};

			// Get the set of amendments to apply from all of the specified assemblies
			var assemblies = new System.Reflection.Assembly[] { System.Reflection.Assembly.LoadFrom(backupTargetAssembly) }.Union(amendmentAssemblies.Select(a => System.Reflection.Assembly.LoadFrom(a)));
			var amendments = AmendmentAttribute.GetAmendments(assemblies.First(), assemblies.Skip(1).ToArray()).ToList();

			// Exit immediately if there are no amendments in the target assemblies
			if (amendments.Count == 0)
			    return;

			// Amend the target assembly
			Console.Write("Amending " + Path.GetFileName(targetAssembly));
			var start = DateTime.Now;

			using (var host = new PeReader.DefaultHost())
			{
				foreach (var referencePath in referencePaths.Select(p => Path.GetDirectoryName(p.Value)).Distinct())
					host.AddLibPath(referencePath);

				// Load the target assembly
				IModule module = host.LoadUnitFrom(backupTargetAssembly) as IModule;
				if (module == null || module == Dummy.Module || module == Dummy.Assembly)
					throw new ArgumentException(backupTargetAssembly + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");

				// Copy the assembly to enable it to be mutated
				module = new MetadataDeepCopier(host).Copy(module);

				// Load the debug file if it exists
				PdbReader pdbReader = null;
				var pdbFile = Path.Combine(targetDirectory, Path.GetFileNameWithoutExtension(targetAssembly) + ".pdb");
				var backupPdbFile = pdbFile + ".backup";
				if (File.Exists(pdbFile))
				{
					File.Delete(backupPdbFile);
					File.Move(pdbFile, backupPdbFile);
					using (var pdbStream = File.OpenRead(backupPdbFile))
					{
						pdbReader = new PdbReader(pdbStream, host);
					}
				}
					
				// Amend and persist the target assembly
				using (pdbReader)
				{
					// Create and execute a new assembly amender
					AssemblyAmender amender = new AssemblyAmender(host, pdbReader, amendments, assemblies);
					amender.TargetRuntimeVersion = module.TargetRuntimeVersion;
					module = amender.Visit(module);

					// Save the amended assembly back to the original directory
					var localScopeProvider = pdbReader == null ? null : new ILGenerator.LocalScopeProvider(pdbReader);
					using (var pdbWriter = pdbReader != null ? new PdbWriter(pdbFile, pdbReader) : null)
					{
						using (var dllStream = File.Create(targetAssembly))
						{
							PeWriter.WritePeToStream(module, host, dllStream, pdbReader, localScopeProvider, pdbWriter);
						}
					}
				}

				File.SetLastWriteTime(targetAssembly, targetWriteTime);
				if (pdbReader != null)
					File.SetLastWriteTime(pdbFile, targetWriteTime);
			}

			Console.WriteLine(" (" + DateTime.Now.Subtract(start).TotalSeconds.ToString("0.000") + " seconds)");

			// Set the last write time of the afterthought tracker to match the amended assembly to prevent accidental reamending
			File.WriteAllText(afterthoughtTracker, "");
			File.SetLastWriteTime(afterthoughtTracker, File.GetLastWriteTime(targetAssembly));
		}
Exemplo n.º 27
0
 public NopTransformer(IModule module, PeReader.DefaultHost host, Log.Log logger) {
     this.host = host;
     this.logger = logger;
     this.module = module;
 }
    static void Main(string[] argv) {
      if (argv == null || argv.Length < 1) {
        Console.WriteLine("Usage: Main <assemblys> [<outputPath>]");
      }

      using (var host = new PeReader.DefaultHost()) {
        var module = host.LoadUnitFrom(argv[0]) as IModule;
        if (module == null || module == Dummy.Module || module == Dummy.Assembly) {
          throw new Exception(argv[0] + " is not a PE file containing a CLR assembly, or an error occurred when loading it.");
        } 

        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);
          }
        } else
          Console.WriteLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");

        using (pdbReader) {

          var copy = new MetadataDeepCopier(host).Copy(module);
          var shadowFieldsAddedAssembly = new ShadowFieldRewriter(host).Rewrite(copy);
          var shadowFieldsAndMethodsAddedAssembly = new ShadowMethodRewriter(host).Rewrite(shadowFieldsAddedAssembly);
          var rewrittenAssembly = new FinalizeMethodRewriter(host).Rewrite(shadowFieldsAndMethodsAddedAssembly);

          var main = rewrittenAssembly.EntryPoint.ResolvedMethod;
          if (main != Dummy.Method) {
            var body = main.Body as MethodBody;
            if (body != null)
              new AddGCWaitForFinalization(host, body).Rewrite();
          }

          var validator = new MetadataValidator(host);
          validator.Validate(rewrittenAssembly as IAssembly);

          string outputPath = rewrittenAssembly.Location + ".meta";
          var outputFileName = Path.GetFileNameWithoutExtension(outputPath);

          // Need to not pass in a local scope provider until such time as we have one that will use the mutator
          // to remap things (like the type of a scope constant) from the original assembly to the mutated one.
          using (var peStream = File.Create(outputPath)) {
            using (var pdbWriter = new PdbWriter(outputFileName + ".pdb", pdbReader)) {
              PeWriter.WritePeToStream(rewrittenAssembly, host, peStream, pdbReader, null, pdbWriter);
            }
          }
        }
      }
    }
Exemplo n.º 29
0
 private static void AnalyzeFile(string toAnalyse)
 {
     using (var host = new PeReader.DefaultHost())
         AnalyzeFileInHost(toAnalyse, host);
 }
Exemplo n.º 30
0
        static void Main2(string[] args)
        {

   var tree = SyntaxTree.ParseText(@"using System;
namespace HelloWorld
{
    public class Program
    {
        public static void Tain(int x)
        {
           
            Console.ReadKey();
        }
    }
}");

        var mscorlib = new MetadataFileReference(
            typeof(object).Assembly.Location);

        var comp = Compilation.Create("MyCompilation", new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
            .AddSyntaxTrees(tree).AddReferences(mscorlib);
        

        var outputFileName = Path.Combine(Path.GetTempPath(), "MyCompilation.lib");
        var ilStream = new FileStream(outputFileName, FileMode.OpenOrCreate);

        var result = comp.Emit(ilStream);
        ilStream.Close();

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

        //Construct a Code Model from the Metadata model via decompilation
            Module decompiledModule = Decompiler.GetCodeModelFromMetadataModel(host, module, null);
        //    decompiledModule.UnitNamespaceRoot.GetMembersNamed(host.NameTable.GetNameFor("Tain"), true);
            var type = decompiledModule.AllTypes.Single(t => t.Name.Value == "Program");
            //type.Methods.Single(m=>m.)
            
        }
           
        if (result.Success)
        {
            // Run the compiled program.
            Process.Start(outputFileName);
        }
        else
        {
            foreach (var diag in result.Diagnostics)
            {
                Console.WriteLine(diag.ToString());
            }
        }
    

            /*
     var   sourceText =     @"using System; 
using System.Collections; 
using System.Linq; 
using System.Text; 
  
namespace HelloWorld 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine(""Hello, World!""); 
        } 
    } 
}"; 

            SyntaxTree tree = SyntaxTree.ParseText(sourceText);

            MetadataReference mscorlib = MetadataReference.CreateAssemblyReference(
                                             "mscorlib");


            Compilation compilation = Compilation.Create("HelloWorld", new CompilationOptions(OutputKind.ConsoleApplication))
                            .AddReferences(mscorlib)
                            .AddSyntaxTrees(tree);

         
            //Directory.CreateDirectory(@"C:\Ttemp")
            compilation.Emit(@"C:\VisualMutatorTemp\Test.exe");*/

        }