示例#1
0
        public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, assembly.FileName);
            var asm = assembly.GetPEFileOrNull();

            if (asm == null)
            {
                return;
            }
            var metadata = asm.Metadata;

            if (metadata.IsAssembly)
            {
                var name = metadata.GetAssemblyDefinition();
                if ((name.Flags & System.Reflection.AssemblyFlags.WindowsRuntime) != 0)
                {
                    WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]");
                }
                else
                {
                    WriteCommentLine(output, metadata.GetFullAssemblyName());
                }
            }
            else
            {
                WriteCommentLine(output, metadata.GetString(metadata.GetModuleDefinition().Name));
            }
        }
示例#2
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();
            var module   = assembly.GetPEFileOrNull();
            var metadata = module.Metadata;
            var dis      = CreateDisassembler(output, options);

            // don't automatically load additional assemblies when an assembly node is selected in the tree view
            using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
                dis.AssemblyResolver = module.GetAssemblyResolver();
                dis.DebugInfo        = module.GetDebugInfoOrNull();
                if (options.FullDecompilation)
                {
                    dis.WriteAssemblyReferences(metadata);
                }
                if (metadata.IsAssembly)
                {
                    dis.WriteAssemblyHeader(module);
                }
                output.WriteLine();
                dis.WriteModuleHeader(module);
                if (options.FullDecompilation)
                {
                    output.WriteLine();
                    output.WriteLine();
                    dis.WriteModuleContents(module);
                }
            }
        }
示例#3
0
文件: Language.cs 项目: tmcmil/ILSpy
        public virtual ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, assembly.FileName);
            var asm = assembly.GetPEFileOrNull();

            if (asm == null)
            {
                return(null);
            }
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                throw new NotSupportedException($"Language '{Name}' does not support exporting assemblies as projects!");
            }
            var metadata = asm.Metadata;

            if (metadata.IsAssembly)
            {
                var name = metadata.GetAssemblyDefinition();
                if ((name.Flags & System.Reflection.AssemblyFlags.WindowsRuntime) != 0)
                {
                    WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]");
                }
                else
                {
                    WriteCommentLine(output, metadata.GetFullAssemblyName());
                }
            }
            else
            {
                WriteCommentLine(output, metadata.GetString(metadata.GetModuleDefinition().Name));
            }
            return(null);
        }
示例#4
0
        internal static async void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                await 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.Title           = "Save file";
            dlg.InitialFileName = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filters         = new List <FileDialogFilter> {
                new FileDialogFilter {
                    Name = "Portable PDB", Extensions = { "pdb" }
                }, new FileDialogFilter {
                    Name = "All files", Extensions = { "*" }
                }
            };
            dlg.Directory = Path.GetDirectoryName(assembly.FileName);
            string fileName = await dlg.ShowAsync(App.Current.GetMainWindow());

            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvaloniaEditTextOutput> .Factory.StartNew(() => {
                AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                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();
        }
        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();
        }
示例#6
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();
            var module   = assembly.GetPEFileOrNull();
            var metadata = module.Metadata;
            var dis      = CreateDisassembler(output, options);

            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                throw new NotSupportedException($"Language '{Name}' does not support exporting assemblies as projects!");
            }

            // don't automatically load additional assemblies when an assembly node is selected in the tree view
            using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad(assembly.AssemblyList))
            {
                dis.AssemblyResolver = module.GetAssemblyResolver();
                dis.DebugInfo        = module.GetDebugInfoOrNull();
                if (options.FullDecompilation)
                {
                    dis.WriteAssemblyReferences(metadata);
                }
                if (metadata.IsAssembly)
                {
                    dis.WriteAssemblyHeader(module);
                }
                output.WriteLine();
                dis.WriteModuleHeader(module);
                if (options.FullDecompilation)
                {
                    output.WriteLine();
                    output.WriteLine();
                    dis.WriteModuleContents(module);
                }
            }
            return(null);
        }
示例#7
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            var module = assembly.GetPEFileOrNull();

            if (module == null)
            {
                return(null);
            }
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                if (!WholeProjectDecompiler.CanUseSdkStyleProjectFormat(module))
                {
                    options.DecompilerSettings.UseSdkStyleProjectFormat = false;
                }
                var decompiler = new ILSpyWholeProjectDecompiler(assembly, options);
                return(decompiler.DecompileProject(module, options.SaveAsProjectDirectory, new TextOutputWriter(output), options.CancellationToken));
            }
            else
            {
                AddReferenceAssemblyWarningMessage(module, output);
                AddReferenceWarningMessage(module, output);
                output.WriteLine();
                base.DecompileAssembly(assembly, output, options);

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                IAssemblyResolver assemblyResolver = assembly.GetAssemblyResolver(loadOnDemand: options.FullDecompilation);
                var typeSystem = new DecompilerTypeSystem(module, assemblyResolver, options.DecompilerSettings);
                var globalType = typeSystem.MainModule.TypeDefinitions.FirstOrDefault();
                if (globalType != null)
                {
                    output.Write("// Global type: ");
                    output.WriteReference(globalType, globalType.FullName);
                    output.WriteLine();
                }
                var metadata         = module.Metadata;
                var corHeader        = module.Reader.PEHeaders.CorHeader;
                var entrypointHandle = MetadataTokenHelpers.EntityHandleOrNil(corHeader.EntryPointTokenOrRelativeVirtualAddress);
                if (!entrypointHandle.IsNil && entrypointHandle.Kind == HandleKind.MethodDefinition)
                {
                    var entrypoint = typeSystem.MainModule.ResolveMethod(entrypointHandle, new Decompiler.TypeSystem.GenericContext());
                    if (entrypoint != null)
                    {
                        output.Write("// Entry point: ");
                        output.WriteReference(entrypoint, entrypoint.DeclaringType.FullName + "." + entrypoint.Name);
                        output.WriteLine();
                    }
                }
                output.WriteLine("// Architecture: " + GetPlatformDisplayName(module));
                if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.ILOnly) == 0)
                {
                    output.WriteLine("// This assembly contains unmanaged code.");
                }
                string runtimeName = GetRuntimeDisplayName(module);
                if (runtimeName != null)
                {
                    output.WriteLine("// Runtime: " + runtimeName);
                }
                if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.StrongNameSigned) != 0)
                {
                    output.WriteLine("// This assembly is signed with a strong name key.");
                }
                if (module.Reader.ReadDebugDirectory().Any(d => d.Type == DebugDirectoryEntryType.Reproducible))
                {
                    output.WriteLine("// This assembly was compiled using the /deterministic option.");
                }
                if (metadata.IsAssembly)
                {
                    var asm = metadata.GetAssemblyDefinition();
                    if (asm.HashAlgorithm != AssemblyHashAlgorithm.None)
                    {
                        output.WriteLine("// Hash algorithm: " + asm.HashAlgorithm.ToString().ToUpper());
                    }
                    if (!asm.PublicKey.IsNil)
                    {
                        output.Write("// Public key: ");
                        var reader = metadata.GetBlobReader(asm.PublicKey);
                        while (reader.RemainingBytes > 0)
                        {
                            output.Write(reader.ReadByte().ToString("x2"));
                        }
                        output.WriteLine();
                    }
                }
                var debugInfo = assembly.GetDebugInfoOrNull();
                if (debugInfo != null)
                {
                    output.WriteLine("// Debug info: " + debugInfo.Description);
                }
                output.WriteLine();

                CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings);
                decompiler.CancellationToken = options.CancellationToken;
                if (options.EscapeInvalidIdentifiers)
                {
                    decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
                }
                SyntaxTree st;
                if (options.FullDecompilation)
                {
                    st = decompiler.DecompileWholeModuleAsSingleFile();
                }
                else
                {
                    st = decompiler.DecompileModuleAndAssemblyAttributes();
                }
                WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem);
                return(null);
            }
        }
示例#8
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            var module = assembly.GetPEFileOrNull();

            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                var decompiler = new ILSpyWholeProjectDecompiler(assembly, options);
                decompiler.DecompileProject(module, options.SaveAsProjectDirectory, new TextOutputWriter(output), options.CancellationToken);
            }
            else
            {
                AddReferenceAssemblyWarningMessage(module, output);
                AddReferenceWarningMessage(module, output);
                output.WriteLine();
                base.DecompileAssembly(assembly, output, options);

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
                    IAssemblyResolver assemblyResolver = assembly.GetAssemblyResolver();
                    var typeSystem = new DecompilerTypeSystem(module, assemblyResolver, options.DecompilerSettings);
                    var globalType = typeSystem.MainModule.TypeDefinitions.FirstOrDefault();
                    if (globalType != null)
                    {
                        output.Write("// Global type: ");
                        output.WriteReference(globalType, globalType.FullName);
                        output.WriteLine();
                    }
                    var metadata         = module.Metadata;
                    var corHeader        = module.Reader.PEHeaders.CorHeader;
                    var entrypointHandle = MetadataTokenHelpers.EntityHandleOrNil(corHeader.EntryPointTokenOrRelativeVirtualAddress);
                    if (!entrypointHandle.IsNil && entrypointHandle.Kind == HandleKind.MethodDefinition)
                    {
                        var entrypoint = typeSystem.MainModule.ResolveMethod(entrypointHandle, new Decompiler.TypeSystem.GenericContext());
                        if (entrypoint != null)
                        {
                            output.Write("// Entry point: ");
                            output.WriteReference(entrypoint, entrypoint.DeclaringType.FullName + "." + entrypoint.Name);
                            output.WriteLine();
                        }
                    }
                    output.WriteLine("// Architecture: " + GetPlatformDisplayName(module));
                    if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.ILOnly) == 0)
                    {
                        output.WriteLine("// This assembly contains unmanaged code.");
                    }
                    string runtimeName = GetRuntimeDisplayName(module);
                    if (runtimeName != null)
                    {
                        output.WriteLine("// Runtime: " + runtimeName);
                    }
                    var debugInfo = assembly.GetDebugInfoOrNull();
                    if (debugInfo != null)
                    {
                        output.WriteLine("// Debug info: " + debugInfo.Description);
                    }
                    output.WriteLine();

                    CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings);
                    decompiler.CancellationToken = options.CancellationToken;
                    SyntaxTree st;
                    if (options.FullDecompilation)
                    {
                        st = decompiler.DecompileWholeModuleAsSingleFile();
                    }
                    else
                    {
                        st = decompiler.DecompileModuleAndAssemblyAttributes();
                    }
                    WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem);
                }
            }
        }