Esempio n. 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"));
            }
        }
Esempio n. 2
0
            public override void Initialize()
            {
                CoreAssembly = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity);

                var     host   = new PeReader.DefaultHost();
                IModule module = OperatorUtils.CompileModuleFromCode(
                    @"using System;
namespace VisualMutatorGeneratedNamespace
{
    public class VisualMutatorGeneratedClass
    {
        public static int FailOnZero(int x)
        {
            if(x == 0) throw new InvalidOperationException(""FailOnZero: x"");
            return x;
        }
    }
}", 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();
            }
Esempio n. 3
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();
                    }
                }
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            MetadataReaderHost host     = new PeReader.DefaultHost();
            string             file     = null; // yeah i know i'm lazy
            Assembly           assembly = (Assembly)host.LoadUnitFrom(file);

            foreach (var type in assembly.AllTypes)
            {
                foreach (MethodDefinition method in type.Methods)
                {
                    var arguments = from IParameterDefinition param in method.Parameters
                                    select string.Format("{0} {1}", param.Type.ToString(), param.Name.Value);

                    string signature = string.Format("{0} {1}::{2}({3})", method.Type.ToString(), type.Name.ToString(), method.Name.ToString(), string.Join(",", arguments.ToArray()));



                    Block block = new Block();
                    block = block
                            [Ops.Ldstr, "]"]
                            [Ops.Call, () => System.Diagnostics.Trace.WriteLine(null)];
                    //[Ops.Ldstr, "["];

                    Injector.Inject(method, block);
                }
            }
        }
Esempio n. 5
0
            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();
            }
Esempio n. 6
0
        static void Main(string[] args)
        {
            const string root = @"..\..\..";
            //const string root = @"C:"; // casa
            //const string root = @"C:\Users\Edgar\Projects"; // facu

            const string input = root + @"\Test\bin\Debug\Test.dll";

            using (var host = new PeReader.DefaultHost())
                using (var assembly = new Assembly(host))
                {
                    assembly.Load(input);

                    Types.Initialize(host);

                    //var extractor = new TypesExtractor(host);
                    //extractor.Extract(assembly.Module);

                    var visitor = new MethodVisitor(host, assembly.PdbReader);
                    visitor.Rewrite(assembly.Module);
                }

            System.Console.WriteLine("Done!");
            System.Console.ReadKey();
        }
Esempio n. 7
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 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);
 }
Esempio n. 9
0
        public static void RunZeroAnalysisExample()
        {
            string liveVariableExample = CompileZeroAnalysisExample();

            using (var host = new PeReader.DefaultHost())
                using (var assembly = new Assembly(host))
                {
                    // load binaries that are gonna be analyzed
                    Types.Initialize(host);
                    assembly.Load(liveVariableExample);

                    // search for the method definition in the assembly
                    // if you inspect this method definitions they are defined using the .NET IL instructions (aka bytecode)

                    var allDefinedMethodsInAssembly = assembly.Module.GetAllTypes()                          // get all defined types in the assembly (these are cci objects)
                                                      .SelectMany(typeDefinition => typeDefinition.Methods); /// get all defined methods (these are cci objects)

                    var targetMethod = allDefinedMethodsInAssembly.Where(m => m.Name.Value.Contains("TestZero")).First();

                    // transform it into a typed stackless three addres code representation
                    // this is a result of analysis-net framework
                    ControlFlowGraph cfg        = null;
                    MethodBody       methodBody = Transformations.ThreeAddressCode(targetMethod, host, out cfg);

                    // on top of the three address representation we apply a live variable analysis
                    // it is far easier to implement such analysis on this representation
                    // if you intent to apply it on top of the IL bytecode, you will have to guess what you have in the stack for each instruction
                    ZeroAnalysis zeroAnalysis = new ZeroAnalysis(cfg);
                    var          r            = zeroAnalysis.Analyze();
                }
        }
Esempio n. 10
0
        static void Run(string sourceName)
        {
            var path = ExtractAndCompile(sourceName);

            try
            {
                Assembly assembly;

                using (var host = new PeReader.DefaultHost())
                    using (var pdbStream = File.OpenRead(Path.ChangeExtension(path, ".pdb")))
                    {
                        var pdbreader     = new PdbReader(pdbStream, host);
                        var loaded        = host.LoadAssembly(new AssemblyIdentity(host.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(path)), null, new Version(), null, path));
                        var dynamicLoader = new DynamicLoader(pdbreader, pdbreader);
                        assembly = dynamicLoader.Load(loaded);
                    }

                var type   = assembly.GetTypes().Single(t => t.Name == sourceName && Attribute.GetCustomAttribute(t, typeof(CompilerGeneratedAttribute)) == null);
                var foo    = Activator.CreateInstance(type);
                var method = type.GetMethod("Run");
                var action = (Action)Delegate.CreateDelegate(typeof(Action), foo, method);
                action();
            }
            finally
            {
                File.Delete(path);
            }
        }
Esempio n. 11
0
        private static void ReadMethodLocations(Dictionary <string, string> methodLocations, string pdbFixturePath, string peFixturePath)
        {
            var host = new PeReader.DefaultHost();

            var pdbFileStream = File.OpenRead(pdbFixturePath);

            var peReader  = new PeReader(host);
            var pdbReader = new PdbReader(pdbFileStream, host);

            var assembly = peReader.OpenAssembly(
                BinaryDocument.GetBinaryDocumentForFile(peFixturePath, host)
                );

            foreach (var type in assembly.GetAllTypes())
            {
                foreach (var member in type.Members)
                {
                    foreach (var sourceLocation in pdbReader.GetPrimarySourceLocationsFor(member.Locations))
                    {
                        var memberName = $"{member}";

                        if (!methodLocations.ContainsKey(memberName))
                        {
                            methodLocations.Add(
                                memberName,
                                $"{sourceLocation.SourceDocument.Name}:{sourceLocation.StartLine}"
                                );
                        }
                    }
                }
            }
        }
        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);
                        }
                    }
                }
            }
        }
Esempio n. 13
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;
        }
Esempio n. 14
0
        static int Main(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                Console.WriteLine("Usage: ILMutator <assembly> [<outputPath>]");
                return(1);
            }

            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 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);
                    ILMutator mutator            = new ILMutator(host, pdbReader);
                    module = mutator.Rewrite(module);

                    string newName;
                    if (args.Length == 2)
                    {
                        newName = args[1];
                    }
                    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);
                    }

                    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
            }
        }
Esempio n. 15
0
        public static Tuple <List <Assembly>, List <Assembly> > LoadAssemblies(PeReader.DefaultHost host, Options options)
        {
            // First, load all the reference assemblies.
            var refs = new List <Assembly>();

            foreach (var rassembly in options.ReferenceAssemblies)
            {
                try
                {
                    //TODO: is this a CCI bug?
                    if (rassembly.EndsWith("__ScopeCodeGen__.dll"))
                    {
                        continue;
                    }

                    var rasm = new Assembly(host);
                    rasm.Load(rassembly);
                    refs.Add(rasm);
                    Utils.WriteLine("Successfully loaded reference assembly: " + rassembly);
                }
                catch (AccessViolationException e)
                {
                    Utils.WriteLine("Warning: perhaps this is a library with unmanaged code?");
                }

                catch (Exception e)
                {
                    Utils.WriteLine(String.Format("Warning: failed to load reference assembly {0} ({1})", rassembly, e.Message));
                }
            }

            // Now, load the main assemblies.
            var assemblies = new List <Assembly>();

            foreach (var assembly in options.Assemblies)
            {
                try
                {
                    var asm = new Assembly(host);
                    asm.Load(assembly);
                    assemblies.Add(asm);
                    Utils.WriteLine("Successfully loaded main assembly: " + assembly);
                }
                catch (AccessViolationException e)
                {
                    Utils.WriteLine("Warning: perhaps this is a library with unmanaged code?");
                }
                catch (Exception e)
                {
                    Utils.WriteLine(String.Format("LOAD FAILURE: failed to load main assembly {0} ({1})", assembly, e.Message));
                }
            }

            Types.Initialize(host);

            return(new Tuple <List <Assembly>, List <Assembly> >(assemblies, refs));
        }
        private Tuple <IMetadataHost, Assembly, IEnumerable <Assembly> > Initialize()
        {
            var options        = Options.ParseCommandLineArguments(args);
            var host           = new PeReader.DefaultHost();
            var data           = ScopeAnalyzer.Program.LoadAssemblies(host, options);
            var mainAssemblies = data.Item1;

            Assert.AreEqual(mainAssemblies.Count, 1);
            return(new Tuple <IMetadataHost, Assembly, IEnumerable <Assembly> >(host, mainAssemblies[0], data.Item2));
        }
Esempio n. 17
0
        public static ScopeAnalysisStats AnalyzeAssemblies(Options options)
        {
            Utils.IsVerbose = options.Verbose;

            var vertexDef          = LoadVertexDef(options);
            var processorIdMapping = LoadProcessorMapping(options);

            var host       = new PeReader.DefaultHost();
            var assemblies = LoadAssemblies(host, options);
            var stats      = new ScopeAnalysisStats();

            stats.Assemblies = options.Assemblies.Count;

            var mainAssemblies = assemblies.Item1;

            stats.AssembliesLoaded = mainAssemblies.Count;
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            foreach (var mAssembly in mainAssemblies)
            {
                try
                {
                    Utils.WriteLine("\n====== Analyzing assembly: " + mAssembly.FileName + " =========\n");

                    // If processor to id mapping and xml with id information are both available,
                    // then we ask ScopeAnalysis to analyze only those processors mentioned in the mapping.
                    ScopeAnalysis analysis = new ScopeAnalysis(host, mAssembly, assemblies.Item2,
                                                               processorIdMapping == null || vertexDef == null? null : processorIdMapping.Keys);
                    analysis.Analyze();

                    //Update the stats.
                    UpdateStats(analysis.Results, ref stats, vertexDef, processorIdMapping);

                    Utils.WriteLine("\n====== Done analyzing the assembly  =========\n");
                }
                catch (ScopeAnalysis.MissingScopeMetadataException e)
                {
                    Utils.WriteLine("ASSEMBLY WARNING: " + e.Message);
                }
                catch (Exception e)
                {
                    Utils.WriteLine("ASSEMBLY FAILURE: " + e.Message);
                }
            }

            stopWatch.Stop();
            var ts = stopWatch.Elapsed;

            Utils.WriteLine(String.Format("Total analysis time: {0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));

            return(stats);
        }
Esempio n. 18
0
        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)));
        }
Esempio n. 19
0
        private static bool CreateProcessorIdMapping(string subdir, IEnumerable <string> libs, string outpath)
        {
            var mainDll = subdir + "\\" + Utils.MAIN_DLL_NAME;

            if (!libs.Contains(mainDll))
            {
                Utils.WriteLine("Did not find main scope dll: " + subdir);
                return(false);
            }

            // delete existing processor id mapping file
            var directory = Path.GetDirectoryName(outpath);

            if (Directory.Exists(directory))
            {
                File.Delete(outpath);
            }
            else
            {
                Directory.CreateDirectory(directory);
            }

            Assembly asm;

            try
            {
                var host = new PeReader.DefaultHost();
                asm = new Assembly(host);
                asm.Load(mainDll);

                var mappingAnalyzer = new ProcessorMappingAnalyzer(asm);
                mappingAnalyzer.Analyze();
                var results = mappingAnalyzer.ProcessorIdMapping;
                var summary = String.Empty;
                foreach (var k in results.Keys)
                {
                    summary += k + "\t" + results[k] + "\r\n";
                }

                using (StreamWriter file = new StreamWriter(outpath))
                {
                    file.Write(summary);
                }
                Utils.WriteLine("Successfully extracted processor to id mapping for the main dll: " + subdir);
            }
            catch (Exception e)
            {
                Utils.WriteLine("WARNING: failed to extract processor to id mapping the main dll: " + subdir);
                Utils.WriteLine("Exception: " + e.Message);
                return(false);
            }
            return(true);
        }
Esempio n. 20
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;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 21
0
 public static void GenerateEDBFacts(string input)
 {
     using (var host = new PeReader.DefaultHost())
     {
         Types.Initialize(host);
         var     visitor     = new ClassAndMethodVisitor(host);
         IModule rootModule  = GetModule(host, input);
         IModule stubsModule = GetModule(host, ConfigParams.StubsPath);
         DoRTA(host, visitor, rootModule, stubsModule);
         GenerateFacts(visitor);
     }
 }
Esempio n. 22
0
        public CodeGenerator(IModule module, PeReader.DefaultHost host, Log.Log logger, Random prng, MethodCfg methodCfg,
                             bool debugging = false, CfgManipulator manipulator = null)
        {
            this.host        = host;
            this.logger      = logger;
            this.module      = module;
            this.prng        = prng;
            this.methodCfg   = methodCfg;
            this.debugging   = debugging;
            this.manipulator = manipulator;

            callableMethods = retrieveCallableMethods();
        }
Esempio n. 23
0
 public static IEnumerable <Tuple <string, IEnumerable <string> > > GetUsedColumns(string assemblyPath, string libPath)
 {
     try
     {
         var host = new PeReader.DefaultHost();
         var referenceAssemblies = Utils.CollectAssemblies(libPath);
         var assemblies          = LoadAssemblies(host, referenceAssemblies, new string[] { assemblyPath, });
         var mainAssemblies      = assemblies.Item1;
         var a       = mainAssemblies[0];
         var results = AnalyzeAssembly(host, a, null, assemblies.Item2, null);
         return(GetUsedColumns(results));
     }
     catch { return(Enumerable <Tuple <string, IEnumerable <string> > > .Empty); }
 }
Esempio n. 24
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);
        }
Esempio n. 25
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);
                            }
                        }
                    }
                }
            }
        }
Esempio n. 26
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);
        }
Esempio n. 27
0
        public Form1()
        {
            InitializeComponent();

            var console = new ConsoleWidget.ConsoleForm();

            using (var dialog = new OpenFileDialog())
            {
                var res = dialog.ShowDialog();

                using (var host = new PeReader.DefaultHost())
                {
                    var x = new VVVV.Core.AssemblyNodeDefinitionCollector(host);

                    foreach (string assemblyName in dialog.FileNames)
                    {
                        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;
                        }

                        foreach (var n in x.Collect(assembly))
                        {
                            Console.WriteLine(n.Systemname);
                            if (n is IDataflowNodeDefinition)
                            {
                                foreach (var p in (n as IDataflowNodeDefinition).Inputs)
                                {
                                    Console.WriteLine("  " + TypeHelper.GetTypeName(p.Type, NameFormattingOptions.SmartTypeName) + " " + p.Name +
                                                      (p.HasDefaultValue ? " = " + p.DefaultValue.Value.ToString() : ""));
                                }
                                foreach (var p in (n as IDataflowNodeDefinition).Outputs)
                                {
                                    Console.WriteLine("  out " + TypeHelper.GetTypeName(p.Type, NameFormattingOptions.SmartTypeName) + " " + p.Name);
                                }
                            }
                        }
                    }
                }
            }

            console.Show();
        }
Esempio n. 28
0
        public CodeMutator(IModule module, PeReader.DefaultHost host, Log.Log logger, Random prng, MethodCfg methodCfg,
                           CfgManipulator manipulator, bool debugging = false)
        {
            this.host        = host;
            this.logger      = logger;
            this.module      = module;
            this.prng        = prng;
            this.methodCfg   = methodCfg;
            this.debugging   = debugging;
            this.manipulator = manipulator;

            returnBlock = new BasicBlock();
            var exitBranch = new ExitBranchTarget();

            returnBlock.exitBranch = exitBranch;
            returnBlock.operations.Add(createNewOperation(OperationCode.Ret));

            methodCfg.basicBlocks.Add(returnBlock);
        }
Esempio n. 29
0
            public TinyBCTHost()
            {
                host = new PeReader.DefaultHost();
                Assembly coreLib = new Assembly(host);

                var pathToSelf   = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                var assemblyPath = Path.Combine(pathToSelf, "..", "..", "..", "DLLs");
                //var assemblyPath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319";
                var systemCoreDll = Path.Combine(assemblyPath, "System.Core.dll");

                if (!File.Exists(systemCoreDll))
                {
                    throw new FileNotFoundException("System.Core.dll not found: " + systemCoreDll);
                }

                coreLib.Load(systemCoreDll);

                this.LoadAssembly(coreLib.Module.ContainingAssembly.AssemblyIdentity);
            }
Esempio n. 30
0
        public void DoStuff()
        {
            var host = new PeReader.DefaultHost();

            foreach (string file in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.exe"))
            {
                Console.WriteLine(file);
                IAssembly assembly = host.LoadUnitFrom(file) as IAssembly;
                if (assembly != null)
                {
                    foreach (INamedTypeDefinition type in assembly.GetAllTypes())
                    {
                        foreach (IMethodDefinition method in type.Methods)
                        {
                            Console.WriteLine(String.Format("{0}::{1}", type.Name, method.Name));
                        }
                    }
                }
            }
        }