Ejemplo n.º 1
0
        CSharpDecompiler CreateDecompiler(PEFile module, DecompilationOptions options)
        {
            CSharpDecompiler decompiler = new CSharpDecompiler(module, module.GetAssemblyResolver(), options.DecompilerSettings);

            decompiler.CancellationToken = options.CancellationToken;
            decompiler.DebugInfoProvider = module.GetDebugInfoOrNull();
            while (decompiler.AstTransforms.Count > transformCount)
            {
                decompiler.AstTransforms.RemoveAt(decompiler.AstTransforms.Count - 1);
            }
            if (options.EscapeInvalidIdentifiers)
            {
                decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
            }
            return(decompiler);
        }
Ejemplo n.º 2
0
 public override void Disassemble(PEFile module, MethodDefinitionHandle handle)
 {
     try {
         var csharpOutput            = new StringWriter();
         CSharpDecompiler decompiler = CreateDecompiler(module, options);
         var st = decompiler.Decompile(handle);
         WriteCode(csharpOutput, options.DecompilerSettings, st, decompiler.TypeSystem);
         var mapping = decompiler.CreateSequencePoints(st).FirstOrDefault(kvp => (kvp.Key.MoveNextMethod ?? kvp.Key.Method).MetadataToken == handle);
         this.sequencePoints = mapping.Value ?? (IList <SequencePoint>)EmptyList <SequencePoint> .Instance;
         this.codeLines      = csharpOutput.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
         base.Disassemble(module, handle);
     } finally {
         this.sequencePoints = null;
         this.codeLines      = null;
     }
 }
Ejemplo n.º 3
0
        private void AddToProviderMap(CSharpDecompiler dc, string assemblyPath, IEntity entity)
        {
            if (!_tokenToProviderMap.ContainsKey(assemblyPath))
            {
                _tokenToProviderMap.Add(assemblyPath, new Dictionary <MetadataToken, IEntity>());
            }

            var token = entity is ITypeDefinition type
                ? dc.TypeSystem.GetCecil(type)?.MetadataToken
                : dc.TypeSystem.GetCecil((IMember)entity)?.MetadataToken;

            if (token.HasValue)
            {
                _tokenToProviderMap[assemblyPath][token.Value] = entity;
            }
        }
        public static string ToSourceCode(this Type source)
        {
            if (source.IsNested)
            {
                throw new NotSupportedException("Decompilation of nested types is not supported");
            }

            if (!source.IsClass)
            {
                throw new NotSupportedException("Decompilation of non-reference types is not supported");
            }

            var decompiler = new CSharpDecompiler(source.Assembly.Location, new DecompilerSettings());

            return(decompiler.DecompileTypeAsString(new FullTypeName(source.FullName)));
        }
Ejemplo n.º 5
0
        protected static void AssertRoundtripCode(string fileName, bool optimize = false, bool useDebug = false, int compilerVersion = 4)
        {
            var code = RemoveIgnorableLines(File.ReadLines(fileName));
            AssemblyDefinition assembly = CompileLegacy(code, optimize, useDebug, compilerVersion);

            CSharpDecompiler decompiler = new CSharpDecompiler(assembly.MainModule, new DecompilerSettings());

            decompiler.AstTransforms.Insert(0, new RemoveCompilerAttribute());

            var syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();

            var options = FormattingOptionsFactory.CreateAllman();

            options.IndentSwitchBody = false;
            CodeAssert.AreEqual(code, syntaxTree.ToString(options));
        }
Ejemplo n.º 6
0
            public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
            {
                base.DecompileMethod(method, output, options);
                var module    = method.ParentModule.PEFile;
                var metadata  = module.Metadata;
                var methodDef = metadata.GetMethodDefinition((SRM.MethodDefinitionHandle)method.MetadataToken);

                if (!methodDef.HasBody())
                {
                    return;
                }
                IAssemblyResolver assemblyResolver = module.GetAssemblyResolver();
                var typeSystem = new DecompilerTypeSystem(module, assemblyResolver);
                var reader     = new ILReader(typeSystem.MainModule);

                reader.UseDebugSymbols = options.DecompilerSettings.UseDebugSymbols;
                var        methodBody = module.Reader.GetMethodBody(methodDef.RelativeVirtualAddress);
                ILFunction il         = reader.ReadIL((SRM.MethodDefinitionHandle)method.MetadataToken, methodBody, kind: ILFunctionKind.TopLevelFunction, cancellationToken: options.CancellationToken);
                var        decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings)
                {
                    CancellationToken = options.CancellationToken
                };
                ILTransformContext context = decompiler.CreateILTransformContext(il);

                context.Stepper.StepLimit = options.StepLimit;
                context.Stepper.IsDebug   = options.IsDebug;
                try {
                    il.RunTransforms(transforms, context);
                } catch (StepLimitReachedException) {
                } catch (Exception ex) {
                    output.WriteLine(ex.ToString());
                    output.WriteLine();
                    output.WriteLine("ILAst after the crash:");
                } finally {
                    // update stepper even if a transform crashed unexpectedly
                    if (options.StepLimit == int.MaxValue)
                    {
                        Stepper = context.Stepper;
                        OnStepperUpdated(new EventArgs());
                    }
                }
                (output as ISmartTextOutput)?.AddButton(Images.ViewCode, "Show Steps", delegate {
                    Docking.DockWorkspace.Instance.ShowToolPane(DebugStepsPaneModel.PaneContentId);
                });
                output.WriteLine();
                il.WriteTo(output, DebugSteps.Options);
            }
Ejemplo n.º 7
0
        IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(Metadata.PEFile module, CancellationToken cancellationToken)
        {
            var metadata = module.Metadata;
            var files    = module.Metadata.GetTopLevelTypeDefinitions().Where(td => IncludeTypeWhenDecompilingProject(module, td)).GroupBy(
                delegate(TypeDefinitionHandle h) {
                var type    = metadata.GetTypeDefinition(h);
                string file = CleanUpFileName(metadata.GetString(type.Name)) + ".cs";
                if (string.IsNullOrEmpty(metadata.GetString(type.Namespace)))
                {
                    return(file);
                }
                else
                {
                    string dir = CleanUpFileName(metadata.GetString(type.Namespace));
                    if (directories.Add(dir))
                    {
                        Directory.CreateDirectory(Path.Combine(targetDirectory, dir));
                    }
                    return(Path.Combine(dir, file));
                }
            }, StringComparer.OrdinalIgnoreCase).ToList();
            int total               = files.Count;
            var progress            = this.ProgressIndicator;
            DecompilerTypeSystem ts = new DecompilerTypeSystem(module, AssemblyResolver, settings);

            Parallel.ForEach(
                files,
                new ParallelOptions {
                MaxDegreeOfParallelism = this.MaxDegreeOfParallelism,
                CancellationToken      = cancellationToken
            },
                delegate(IGrouping <string, TypeDefinitionHandle> file) {
                using (StreamWriter w = new StreamWriter(Path.Combine(targetDirectory, file.Key))) {
                    try {
                        CSharpDecompiler decompiler  = CreateDecompiler(ts);
                        decompiler.CancellationToken = cancellationToken;
                        var syntaxTree = decompiler.DecompileTypes(file.ToArray());
                        syntaxTree.AcceptVisitor(new CSharpOutputVisitor(w, settings.CSharpFormattingOptions));
                    } catch (Exception innerException) when(!(innerException is OperationCanceledException || innerException is DecompilerException))
                    {
                        throw new DecompilerException(module, $"Error decompiling for '{file.Key}'", innerException);
                    }
                }
                progress?.Report(new DecompilationProgress(total, file.Key));
            });
            return(files.Select(f => Tuple.Create("Compile", f.Key)).Concat(WriteAssemblyInfo(ts, cancellationToken)));
        }
Ejemplo n.º 8
0
        public bool DllCompare(string srcPath, string dstPath, out List <string> errorList)
        {
            errorList = new List <string>();
            string[] separators = { "\r\n" };

            var module           = ModuleDefinition.ReadModule(srcPath);
            var typeFullNameList = (from type in module.Types where type.IsPublic select type.FullName).ToList();

            var dllequal = true;

            foreach (var typeFullName in typeFullNameList)
            {
                try
                {
                    var name        = new FullTypeName(typeFullName);
                    var decompiler1 = new CSharpDecompiler(srcPath, new ICSharpCode.Decompiler.DecompilerSettings());
                    var x1          = decompiler1.DecompileTypeAsString(name);
                    var lines1      = x1.Split(separators, StringSplitOptions.None);

                    var decompiler2 = new CSharpDecompiler(dstPath, new ICSharpCode.Decompiler.DecompilerSettings());
                    var x2          = decompiler2.DecompileTypeAsString(name);
                    var lines2      = x2.Split(separators, StringSplitOptions.None);

                    if (lines1.Length != lines2.Length)
                    {
                        dllequal = false;
                        errorList.Add("\t" + srcPath + "\t" + typeFullName + "\t" + "(decompilable)");
                        continue;
                    }

                    if (!lines1.Where((t, i) => t != lines2[i]).Any())
                    {
                        continue;
                    }

                    dllequal = false;
                    errorList.Add("\t" + srcPath + "\t" + typeFullName + "\t" + "(decompilable)");
                }
                catch (Exception ex)
                {
                    errorList.Add("\t\t" + ex.Message);
                    return(false);
                }
            }

            return(dllequal);
        }
        public DocumentationGenerator(string assemblyFilePath, string documentationFilePath, string homePageName, string linksFiles)
        {
            _decompiler            = new CSharpDecompiler(assemblyFilePath, new DecompilerSettings());
            _documentationProvider = new XmlDocumentationProvider(documentationFilePath);

            _docItems = new Dictionary <string, DocItem>();
            foreach (DocItem item in GetDocItems(homePageName))
            {
                _docItems.Add(item.Id, item);
            }

            _links = new Dictionary <string, string>();
            foreach ((string id, string link) in GetExternalLinks(linksFiles))
            {
                _links[id] = link;
            }
        }
Ejemplo n.º 10
0
        protected override void ProcessRecord()
        {
            string path = GetUnresolvedProviderPathFromPSPath(LiteralPath);

            try {
                var decompiler = new CSharpDecompiler(path, new DecompilerSettings(LanguageVersion)
                {
                    ThrowOnAssemblyResolveErrors = false,
                    RemoveDeadCode   = RemoveDeadCode,
                    RemoveDeadStores = RemoveDeadStores
                });
                WriteObject(decompiler);
            } catch (Exception e) {
                WriteVerbose(e.ToString());
                WriteError(new ErrorRecord(e, ErrorIds.AssemblyLoadFailed, ErrorCategory.OperationStopped, null));
            }
        }
        private static string getMethod(string id, CSharpDecompiler decompiler)
        {
            string[] split  = id.Split("|");
            string   type   = split[0];
            string   method = split[1];

            string[] param = split[2].Split(",");

            try
            {
                return(decompiler.DecompileAsString(decompiler.TypeSystem.MainModule.Compilation.FindType(new FullTypeName(type)).GetDefinition().Methods.Where(x => x.Name.Equals(method) && (!x.Parameters.Any() || (x.Parameters.ToList().Select(y => y.Type.ReflectionName).SequenceEqual(param)))).First().MetadataToken));
            }
            catch (InvalidOperationException)
            {
                return("-1");
            }
        }
Ejemplo n.º 12
0
        internal static void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                MessageBox.Show(string.Format(Resources.CannotCreatePDBFile, Path.GetFileName(assembly.FileName)));
                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.FileName         = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filter           = Resources.PortablePDBPdbAllFiles;
            dlg.InitialDirectory = Path.GetDirectoryName(assembly.FileName);
            if (dlg.ShowDialog() != true)
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();
            string fileName = dlg.FileName;

            Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task <AvalonEditTextOutput> .Factory.StartNew(() => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                Stopwatch stopwatch         = Stopwatch.StartNew();
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    try
                    {
                        var decompiler = new CSharpDecompiler(file, assembly.GetAssemblyResolver(), options.DecompilerSettings);
                        PortablePdbWriter.WritePdb(file, decompiler, options.DecompilerSettings, stream);
                    }
                    catch (OperationCanceledException)
                    {
                        output.WriteLine();
                        output.WriteLine(Resources.GenerationWasCancelled);
                        throw;
                    }
                }
                stopwatch.Stop();
                output.WriteLine(Resources.GenerationCompleteInSeconds, stopwatch.Elapsed.TotalSeconds.ToString("F1"));
                output.WriteLine();
                output.AddButton(null, Resources.OpenExplorer, delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => Docking.DockWorkspace.Instance.ShowText(output)).HandleExceptions();
        }
Ejemplo n.º 13
0
        public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
        {
            AddReferenceWarningMessage(method.Module.Assembly, output);
            WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
            CSharpDecompiler decompiler = CreateDecompiler(method.Module, options);

            if (method.IsConstructor && !method.DeclaringType.IsValueType)
            {
                List <IMemberDefinition> members = CollectFieldsAndCtors(method.DeclaringType, method.IsStatic);
                decompiler.AstTransforms.Add(new SelectCtorTransform(decompiler.TypeSystem.Resolve(method)));
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
            }
            else
            {
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(method), decompiler.TypeSystem);
            }
        }
Ejemplo n.º 14
0
        public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
        {
            AddReferenceWarningMessage(field.Module.Assembly, output);
            WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
            CSharpDecompiler decompiler = CreateDecompiler(field.Module, options);

            if (field.IsLiteral)
            {
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(field), decompiler.TypeSystem);
            }
            else
            {
                List <IMemberDefinition> members = CollectFieldsAndCtors(field.DeclaringType, field.IsStatic);
                decompiler.AstTransforms.Add(new SelectFieldTransform(decompiler.TypeSystem.Resolve(field)));
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
            }
        }
        public static string[] compareRich(string[] ids, string decompiler1t, string decompiler2t)
        {
            CSharpDecompiler decompiler1 = new CSharpDecompiler(decompiler1t, new DecompilerSettings());
            CSharpDecompiler decompiler2 = new CSharpDecompiler(decompiler2t, new DecompilerSettings());

            List <string> list = new List <string>();

            for (int i = 0; i < ids.Length; i++)
            {
                if (!compare(ids[i], decompiler1, decompiler2))
                {
                    string[] split = ids[0].Split("|");
                    list.Add(split[0] + "." + split[1] + "(" + String.Join(", ", split[2].Split(",")) + ")");
                }
            }

            return(list.ToArray());
        }
        public static Boolean compare(string id, CSharpDecompiler decompiler1, CSharpDecompiler decompiler2)
        {
            try
            {
                string method1 = getMethod(id, decompiler2);
                string method2 = getMethod(id, decompiler1);
                if (method1 == "-1" || method2 == "-1")
                {
                    return(false);
                }

                return(method1.Equals(method2));
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        public static CSharpDecompiler GetDecompilerForSnippet(string csharpText)
        {
            var syntaxTree  = SyntaxFactory.ParseSyntaxTree(csharpText);
            var compilation = CSharpCompilation.Create(
                "TestAssembly",
                new[] { syntaxTree },
                defaultReferences.Value,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var peStream   = new MemoryStream();
            var emitResult = compilation.Emit(peStream);

            peStream.Position = 0;

            var moduleDefinition = ModuleDefinition.ReadModule(peStream);
            var decompiler       = new CSharpDecompiler(moduleDefinition, new DecompilerSettings());

            return(decompiler);
        }
Ejemplo n.º 18
0
        public bool AddAssembly(string path)
        {
            try
            {
                var decompiler = new CSharpDecompiler(path, new DecompilerSettings()
                {
                    ThrowOnAssemblyResolveErrors = false
                });
                _decompilers[path] = decompiler;
                return(true);
            }
            catch (Exception ex)
            {
                _logger?.LogError("An exception occurred when reading assembly {assembly}: {exception}", path, ex);
            }

            return(false);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Instianciates a CSharpDecompiler from a given assemblyfilename and applies decompilersettings
 /// </summary>
 /// <param name="assemblyFileName">path for assemblyfile to decompile</param>
 /// <param name="settings">optional decompiler settings</param>
 /// <returns>Instance of CSharpDecompiler</returns>
 public CSharpDecompiler GetCSharpDecompiler(string assemblyFileName, DecompilerSettings settings = null)
 {
     if (settings == null)
     {
         settings = new DecompilerSettings();
     }
     using (var file = new FileStream(assemblyFileName, FileMode.Open, FileAccess.Read))
     {
         var module   = new PEFile(assemblyFileName, file, PEStreamOptions.PrefetchEntireImage);
         var resolver = new UniversalAssemblyResolver(assemblyFileName, false,
                                                      module.Reader.DetectTargetFrameworkId(), PEStreamOptions.PrefetchMetadata);
         resolver.AddSearchDirectory(Path.GetDirectoryName(module.FullName));
         var typeSystem = new DecompilerTypeSystem(module, resolver, settings);
         var decompiler = new CSharpDecompiler(typeSystem, settings);
         decompiler.DebugInfoProvider = DebugInfoLoader.LoadSymbols(module);
         return(decompiler);
     }
 }
Ejemplo n.º 20
0
            public override void Disassemble(MethodBody body)
            {
                var method = body.Method;

                try {
                    var csharpOutput            = new StringWriter();
                    CSharpDecompiler decompiler = CreateDecompiler(method.Module, options);
                    var st = decompiler.Decompile(method);
                    WriteCode(csharpOutput, options.DecompilerSettings, st, decompiler.TypeSystem);
                    var mapping = decompiler.CreateSequencePoints(st).FirstOrDefault(kvp => kvp.Key.CecilMethod == method);
                    this.sequencePoints = mapping.Value ?? (IList <IL.SequencePoint>)EmptyList <IL.SequencePoint> .Instance;
                    this.codeLines      = csharpOutput.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                    base.Disassemble(body);
                } finally {
                    this.sequencePoints = null;
                    this.codeLines      = null;
                }
            }
Ejemplo n.º 21
0
        private void TestGeneratePdb([CallerMemberName] string testName = null)
        {
            const PdbToXmlOptions options = PdbToXmlOptions.IncludeEmbeddedSources | PdbToXmlOptions.ThrowOnError | PdbToXmlOptions.IncludeTokens | PdbToXmlOptions.ResolveTokens | PdbToXmlOptions.IncludeMethodSpans;

            string    xmlFile    = Path.Combine(TestCasePath, testName + ".xml");
            string    xmlContent = File.ReadAllText(xmlFile);
            XDocument document   = XDocument.Parse(xmlContent);
            var       files      = document.Descendants("file").ToDictionary(f => f.Attribute("name").Value, f => f.Value);

            Tester.CompileCSharpWithPdb(Path.Combine(TestCasePath, testName + ".expected"), files);

            string peFileName       = Path.Combine(TestCasePath, testName + ".expected.dll");
            string pdbFileName      = Path.Combine(TestCasePath, testName + ".expected.pdb");
            var    moduleDefinition = new PEFile(peFileName);
            var    resolver         = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Reader.DetectTargetFrameworkId(), PEStreamOptions.PrefetchEntireImage);
            var    decompiler       = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings());

            using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, testName + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                pdbStream.SetLength(0);
                PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true);
                pdbStream.Position = 0;
                using (Stream peStream = File.OpenRead(peFileName))
                    using (Stream expectedPdbStream = File.OpenRead(pdbFileName))
                    {
                        using (StreamWriter writer = new StreamWriter(Path.ChangeExtension(pdbFileName, ".xml"), false, Encoding.UTF8))
                        {
                            PdbToXmlConverter.ToXml(writer, expectedPdbStream, peStream, options);
                        }
                        peStream.Position = 0;
                        using (StreamWriter writer = new StreamWriter(Path.ChangeExtension(xmlFile, ".generated.xml"), false, Encoding.UTF8))
                        {
                            PdbToXmlConverter.ToXml(writer, pdbStream, peStream, options);
                        }
                    }
            }
            string expectedFileName = Path.ChangeExtension(xmlFile, ".expected.xml");

            ProcessXmlFile(expectedFileName);
            string generatedFileName = Path.ChangeExtension(xmlFile, ".generated.xml");

            ProcessXmlFile(generatedFileName);
            Assert.AreEqual(Normalize(expectedFileName), Normalize(generatedFileName));
        }
Ejemplo n.º 22
0
        public static string DecompileCSharp(string assemblyFileName)
        {
            using (var module = ModuleDefinition.ReadModule(assemblyFileName)) {
                var typeSystem = new DecompilerTypeSystem(module);
                CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, new DecompilerSettings());
                decompiler.AstTransforms.Insert(0, new RemoveCompilerAttribute());
                decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
                var syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();

                StringWriter output  = new StringWriter();
                var          visitor = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());
                syntaxTree.AcceptVisitor(visitor);

                string fileName = Path.GetTempFileName();
                File.WriteAllText(fileName, output.ToString());

                return(fileName);
            }
        }
Ejemplo n.º 23
0
            public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
            {
                base.DecompileMethod(method, output, options);
                if (!method.HasBody)
                {
                    return;
                }
                var typeSystem             = new DecompilerTypeSystem(method.Module);
                var specializingTypeSystem = typeSystem.GetSpecializingTypeSystem(new SimpleTypeResolveContext(typeSystem.Resolve(method)));
                var reader = new ILReader(specializingTypeSystem);

                reader.UseDebugSymbols = options.DecompilerSettings.UseDebugSymbols;
                ILFunction il         = reader.ReadIL(method.Body, options.CancellationToken);
                var        namespaces = new HashSet <string>();
                var        decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings)
                {
                    CancellationToken = options.CancellationToken
                };
                ILTransformContext context = decompiler.CreateILTransformContext(il);

                context.Stepper.StepLimit = options.StepLimit;
                context.Stepper.IsDebug   = options.IsDebug;
                try {
                    il.RunTransforms(transforms, context);
                } catch (StepLimitReachedException) {
                } catch (Exception ex) {
                    output.WriteLine(ex.ToString());
                    output.WriteLine();
                    output.WriteLine("ILAst after the crash:");
                } finally {
                    // update stepper even if a transform crashed unexpectedly
                    if (options.StepLimit == int.MaxValue)
                    {
                        Stepper = context.Stepper;
                        OnStepperUpdated(new EventArgs());
                    }
                }
                (output as ISmartTextOutput)?.AddButton(Images.ViewCode, "Show Steps", delegate {
                    DebugSteps.Show();
                });
                output.WriteLine();
                il.WriteTo(output, DebugSteps.Options);
            }
Ejemplo n.º 24
0
        private void PopulateTokenToProviderMap(CSharpDecompiler dc, string assemblyPath, ITypeDefinition typeDefinition)
        {
            if (typeDefinition == null)
            {
                return;
            }

            AddToProviderMap(dc, assemblyPath, typeDefinition);

            foreach (var member in typeDefinition.Members)
            {
                AddToProviderMap(dc, assemblyPath, member);
            }

            foreach (var nestedType in typeDefinition.NestedTypes)
            {
                PopulateTokenToProviderMap(dc, assemblyPath, nestedType);
            }
        }
Ejemplo n.º 25
0
        public static CSharpDecompiler GetDecompilerForSnippet(string csharpText)
        {
            var syntaxTree  = SyntaxFactory.ParseSyntaxTree(csharpText);
            var compilation = CSharpCompilation.Create(
                "TestAssembly",
                new[] { syntaxTree },
                defaultReferences.Value,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var peStream   = new MemoryStream();
            var emitResult = compilation.Emit(peStream);

            peStream.Position = 0;

            var moduleDefinition = new PEFile("TestAssembly.dll", peStream, PEStreamOptions.PrefetchEntireImage);
            var resolver         = new UniversalAssemblyResolver("TestAssembly.dll", false, moduleDefinition.Reader.DetectTargetFrameworkId(), PEStreamOptions.PrefetchEntireImage);
            var decompiler       = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings());

            return(decompiler);
        }
Ejemplo n.º 26
0
        private Document PerformDecompilation(Document document, string fullName, Compilation compilation, string assemblyLocation)
        {
            // Load the assembly.
            var file = new PEFile(assemblyLocation, PEStreamOptions.PrefetchEntireImage);

            // Initialize a decompiler with default settings.
            var decompiler = new CSharpDecompiler(file, new AssemblyResolver(compilation), new DecompilerSettings());

            // Escape invalid identifiers to prevent Roslyn from failing to parse the generated code.
            // (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.)
            decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());

            var fullTypeName = new FullTypeName(fullName);

            // Try to decompile; if an exception is thrown the caller will handle it
            var text = decompiler.DecompileTypeAsString(fullTypeName);

            return(document.WithText(SourceText.From(text)));
        }
Ejemplo n.º 27
0
        internal static void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                MessageBox.Show($"Cannot create PDB file for {Path.GetFileName(assembly.FileName)}, because it does not contain a PE Debug Directory Entry of type 'CodeView'.");
                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.FileName         = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filter           = "Portable PDB|*.pdb|All files|*.*";
            dlg.InitialDirectory = Path.GetDirectoryName(assembly.FileName);
            if (dlg.ShowDialog() != true)
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();
            string fileName = dlg.FileName;

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvalonEditTextOutput> .Factory.StartNew(() => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                Stopwatch stopwatch         = Stopwatch.StartNew();
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)) {
                    try {
                        var decompiler = new CSharpDecompiler(file, assembly.GetAssemblyResolver(), options.DecompilerSettings);
                        PortablePdbWriter.WritePdb(file, decompiler, options.DecompilerSettings, stream);
                    } catch (OperationCanceledException) {
                        output.WriteLine();
                        output.WriteLine("Generation was cancelled.");
                        throw;
                    }
                }
                stopwatch.Stop();
                output.WriteLine("Generation complete in " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                output.WriteLine();
                output.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
        }
Ejemplo n.º 28
0
        public override void DecompileField(IField field, ITextOutput output, DecompilationOptions options)
        {
            PEFile           assembly   = field.ParentModule.PEFile;
            CSharpDecompiler decompiler = CreateDecompiler(assembly, options);

            AddReferenceAssemblyWarningMessage(assembly, output);
            AddReferenceWarningMessage(assembly, output);
            WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
            if (field.IsConst)
            {
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(field.MetadataToken), decompiler.TypeSystem);
            }
            else
            {
                var members       = CollectFieldsAndCtors(field.DeclaringTypeDefinition, field.IsStatic);
                var resolvedField = decompiler.TypeSystem.MainModule.GetDefinition((FieldDefinitionHandle)field.MetadataToken);
                decompiler.AstTransforms.Add(new SelectFieldTransform(resolvedField));
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
            }
        }
Ejemplo n.º 29
0
        public override void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
        {
            PEFile assembly = method.ParentModule.PEFile;

            AddReferenceWarningMessage(assembly, output);
            WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
            CSharpDecompiler decompiler = CreateDecompiler(assembly, options);
            var methodDefinition        = decompiler.TypeSystem.MainModule.ResolveEntity(method.MetadataToken) as IMethod;

            if (methodDefinition.IsConstructor && methodDefinition.DeclaringType.IsReferenceType != false)
            {
                var members = CollectFieldsAndCtors(methodDefinition.DeclaringTypeDefinition, methodDefinition.IsStatic);
                decompiler.AstTransforms.Add(new SelectCtorTransform(methodDefinition));
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(members), decompiler.TypeSystem);
            }
            else
            {
                WriteCode(output, options.DecompilerSettings, decompiler.Decompile(method.MetadataToken), decompiler.TypeSystem);
            }
        }
Ejemplo n.º 30
0
        public Task HandleAsync(WorkspaceFile file, HandleFileOptions options, CancellationToken cancellationToken)
        {
            try
            {
                var decompiler = new CSharpDecompiler(
                    file.Path,
                    new DecompilerSettings());

                file.Content = decompiler.DecompileWholeModuleAsString();

                file.Meta.Language = "csharp";
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Could not decompile: {File}", file.Path);
            }


            return(Task.CompletedTask);
        }