public override void DecompileAssembly(AssemblyDefinition assembly, string fileName, ITextOutput output, DecompilationOptions options) { output.WriteLine("// " + fileName); output.WriteLine(); new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).WriteAssemblyHeader(assembly); }
public override void DecompileMethod(ilspy::Mono.Cecil.MethodDefinition method, ICSharpCode.Decompiler.ITextOutput output, DecompilationOptions options) { var cmethod = GetCompiledMethod(method); if ((cmethod != null) && (cmethod.DexMethod != null)) { try { var f = new MethodBodyDisassemblyFormatter(cmethod.DexMethod, MapFile); var formatOptions = FormatOptions.EmbedSourceCode | FormatOptions.ShowJumpTargets; if(ShowFullNames) formatOptions |= FormatOptions.FullTypeNames; if(DebugOperandTypes) formatOptions |= FormatOptions.DebugOperandTypes; var s = f.Format(formatOptions); output.Write(s); } catch (Exception) { output.Write("\n\n// Formatting error. Using Fallback.\n\n"); FallbackFormatting(output, cmethod); } } else { output.Write("Method not found in dex"); output.WriteLine(); } }
public override void DecompileMethod(ilspy::Mono.Cecil.MethodDefinition method, ITextOutput output, DecompilationOptions options) { var xMethod = GetXMethodDefinition(method); var ilMethod = xMethod as XBuilder.ILMethodDefinition; CompiledMethod cmethod; if (ilMethod == null || !ilMethod.OriginalMethod.HasBody) { output.Write(""); output.WriteLine("// not an il method or method without body."); return; } var methodSource = new MethodSource(xMethod, ilMethod.OriginalMethod); var target = (DexTargetPackage) AssemblyCompiler.TargetPackage; var dMethod = (MethodDefinition)xMethod.GetReference(target); DexMethodBodyCompiler.TranslateToRL(AssemblyCompiler, target, methodSource, dMethod, GenerateSetNextInstructionCode, out cmethod); var rlBody = cmethod.RLBody; // Optimize RL code string lastApplied = RLTransformations.Transform(target.DexFile, rlBody, StopOptimizationAfter == -1?int.MaxValue:StopOptimizationAfter); if(lastApplied != null) output.WriteLine("// Stop after " + lastApplied); PrintMethod(cmethod, output, options); }
public string WriteResourceToFile(LoadedAssembly assembly, string fileName, Stream stream, DecompilationOptions options) { var document = BamlResourceEntryNode.LoadIntoDocument(assembly.GetAssemblyResolver(), assembly.AssemblyDefinition, stream); fileName = Path.ChangeExtension(fileName, ".xaml"); document.Save(Path.Combine(options.SaveAsProjectDirectory, fileName)); return fileName; }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true)); AstBuilder codeDomBuilder = CreateAstBuilder(options, method.DeclaringType); codeDomBuilder.AddMethod(method); codeDomBuilder.GenerateCode(output, transformAbortCondition); }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { if (!method.HasBody) { return; } ILAstBuilder astBuilder = new ILAstBuilder(); ILBlock ilMethod = new ILBlock(); ilMethod.Body = astBuilder.Build(method, inlineVariables); if (abortBeforeStep != null) { DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method }; new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value); } var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable) .Where(v => v != null && !v.IsParameter).Distinct(); foreach (ILVariable v in allVariables) { output.WriteDefinition(v.Name, v); if (v.Type != null) { output.Write(" : "); if (v.IsPinned) output.Write("pinned "); v.Type.WriteTo(output, ILNameSyntax.ShortTypeName); } output.WriteLine(); } output.WriteLine(); foreach (ILNode node in ilMethod.Body) { node.WriteTo(output); output.WriteLine(); } }
public override void Execute(object parameter) { MainWindow.Instance.TextView.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => { AvalonEditTextOutput output = new AvalonEditTextOutput(); Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate(LoadedAssembly asm) { if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); Exception exception = null; using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) { try { var options = new DecompilationOptions { FullDecompilation = true, CancellationToken = ct }; var textOutput = new Decompiler.PlainTextOutput(writer); textOutput.SetIndentationString(options.DecompilerSettings.IndentString); new CSharpLanguage().DecompileAssembly(asm, textOutput, options); } catch (Exception ex) { writer.WriteLine(ex.ToString()); exception = ex; } } lock (output) { output.Write(asm.ShortName + " - " + w.Elapsed); if (exception != null) { output.Write(" - "); output.Write(exception.GetType().Name); } output.WriteLine(); } } }); return output; }, ct), task => MainWindow.Instance.TextView.ShowText(task.Result)); }
public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options) { WriteComment(output, "Method: "); output.WriteDefinition(IdentifierEscaper.Escape(method.FullName), method, TextTokenType.Comment, false); output.WriteLine(); if (!method.HasBody) { return; } StartKeywordBlock(output, ".body", method); ILAstBuilder astBuilder = new ILAstBuilder(); ILBlock ilMethod = new ILBlock(); DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method }; ilMethod.Body = astBuilder.Build(method, inlineVariables, context); if (abortBeforeStep != null) { new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value); } if (context.CurrentMethodIsAsync) { output.Write("async", TextTokenType.Keyword); output.Write('/', TextTokenType.Operator); output.WriteLine("await", TextTokenType.Keyword); } var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable) .Where(v => v != null && !v.IsParameter).Distinct(); foreach (ILVariable v in allVariables) { output.WriteDefinition(IdentifierEscaper.Escape(v.Name), v, v.IsParameter ? TextTokenType.Parameter : TextTokenType.Local); if (v.Type != null) { output.WriteSpace(); output.Write(':', TextTokenType.Operator); output.WriteSpace(); if (v.IsPinned) { output.Write("pinned", TextTokenType.Keyword); output.WriteSpace(); } v.Type.WriteTo(output, ILNameSyntax.ShortTypeName); } if (v.IsGenerated) { output.WriteSpace(); output.Write('[', TextTokenType.Operator); output.Write("generated", TextTokenType.Keyword); output.Write(']', TextTokenType.Operator); } output.WriteLine(); } var memberMapping = new MemberMapping(method); foreach (ILNode node in ilMethod.Body) { node.WriteTo(output, memberMapping); if (!node.WritesNewLine) output.WriteLine(); } output.AddDebugSymbols(memberMapping); EndKeywordBlock(output); }
private void PrintMethod(CompiledMethod cmethod, ITextOutput output, DecompilationOptions options) { if ((cmethod != null) && (cmethod.RLBody != null)) { var body = cmethod.RLBody; var basicBlocks = BasicBlock.Find(body); foreach (var block in basicBlocks) { output.Write(string.Format("D_{0:X4}:", block.Entry.Index)); output.WriteLine(); output.Indent(); foreach (var ins in block.Instructions) { if (ShowHasSeqPoint) { if (ins.SequencePoint != null) output.Write(ins.SequencePoint.IsSpecial ? "!" : "~"); } output.Write(ins.ToString()); output.WriteLine(); } output.Unindent(); } if (body.Exceptions.Any()) { output.WriteLine(); output.Write("Exception handlers:"); output.WriteLine(); output.Indent(); foreach (var handler in body.Exceptions) { output.Write(string.Format("{0:x4}-{1:x4}", handler.TryStart.Index, handler.TryEnd.Index)); output.WriteLine(); output.Indent(); foreach (var c in handler.Catches) { output.Write(string.Format("{0} => {1:x4}", c.Type, c.Instruction.Index)); output.WriteLine(); } if (handler.CatchAll != null) { output.Write(string.Format("{0} => {1:x4}", "<any>", handler.CatchAll.Index)); output.WriteLine(); } output.Unindent(); } output.Unindent(); } } else { output.Write("Method not found in dex"); output.WriteLine(); } }
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureChildrenFiltered)); language.WriteCommentLine(output, "PE"); language.WriteCommentLine(output, "All tree nodes below use the hex editor to modify the PE file"); foreach (HexTreeNode node in Children) { language.WriteCommentLine(output, string.Empty); node.Decompile(language, output, options); } }
ReflectionDisassembler CreateReflectionDisassembler(ITextOutput output, DecompilationOptions options, ModuleDef ownerModule) { var disOpts = new DisassemblerOptions(options.CancellationToken, ownerModule); if (options.DecompilerSettings.ShowILComments) disOpts.GetOpCodeDocumentation = GetOpCodeDocumentation; if (options.DecompilerSettings.ShowXmlDocumentation) disOpts.GetXmlDocComments = GetXmlDocComments; disOpts.CreateInstructionBytesReader = InstructionBytesReader.Create; disOpts.ShowTokenAndRvaComments = options.DecompilerSettings.ShowTokenAndRvaComments; disOpts.ShowILBytes = options.DecompilerSettings.ShowILBytes; disOpts.SortMembers = options.DecompilerSettings.SortMembers; return new ReflectionDisassembler(output, detectControlStructure, disOpts); }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true)); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true); if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType) { // also fields and other ctors so that the field initializers can be shown as such AddFieldsAndCtors(codeDomBuilder, method.DeclaringType, method.IsStatic); RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectCtorTransform(method)); } else { codeDomBuilder.AddMethod(method); RunTransformsAndGenerateCode(codeDomBuilder, output, options); } }
public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, assembly.FileName); if (assembly.AssemblyDefinition != null) { if (assembly.AssemblyDefinition.IsContentTypeWindowsRuntime) { WriteCommentLine(output, assembly.AssemblyDefinition.Name + " [WinRT]"); } else { WriteCommentLine(output, assembly.AssemblyDefinition.FullName); } } else { WriteCommentLine(output, assembly.ModuleDefinition.Name); } }
public AssemblyCompiler AssemblyCompiler { get { return compiler.AssemblyCompiler; } } public MapFileLookup MapFile { get { return compiler.MapFile; } } public static bool GenerateSetNextInstructionCode { get { return compiler.GenerateSetNextInstructionCode; } set { compiler.GenerateSetNextInstructionCode = value; } } public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { compiler.CompileIfRequired(assembly.AssemblyDefinition);
public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options) { var xType = GetXTypeDefinition(type); output.WriteLine("class " + type.Name); output.WriteLine("{"); foreach (var field in xType.Fields) { if (!field.IsReachable) continue; output.WriteLine("\t{0} {1};", field.FieldType.Name, field.Name); } output.WriteLine(); foreach (var method in xType.Methods) { var ilMethod = method as XBuilder.ILMethodDefinition; if (ilMethod != null && !ilMethod.OriginalMethod.IsReachable) continue; output.Write("\t{0} {1}(", method.ReturnType.Name, method.Name); List<string> parms = method.Parameters.Select(p => string.Format("{0}{1} {2}", KindToStringAndSpace(p.Kind), p.ParameterType.Name, p.Name)) .ToList(); if (method.NeedsGenericInstanceTypeParameter) parms.Add("Type[] git"); if (method.NeedsGenericInstanceMethodParameter) parms.Add("Type[] gim"); output.Write(string.Join(", ", parms)); output.WriteLine(")"); output.WriteLine("\t{"); DecompileMethod(method, output, 2); output.WriteLine("\t}"); output.WriteLine(); } output.WriteLine("}"); }
public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) { ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); rd.DisassembleProperty(property); if (property.GetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.GetMethod); } if (property.SetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.SetMethod); } foreach (var m in property.OtherMethods) { output.WriteLine(); rd.DisassembleMethod(m); } }
public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options) { ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); rd.DisassembleEvent(ev); if (ev.AddMethod != null) { output.WriteLine(); rd.DisassembleMethod(ev.AddMethod); } if (ev.RemoveMethod != null) { output.WriteLine(); rd.DisassembleMethod(ev.RemoveMethod); } foreach (var m in ev.OtherMethods) { output.WriteLine(); rd.DisassembleMethod(m); } }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { output.WriteLine("// " + assembly.FileName); output.WriteLine(); ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); //if (options.FullDecompilation) // rd.WriteAssemblyReferences(assembly.ModuleDefinition); if (assembly.AssemblyDefinition != null) rd.WriteAssemblyHeader(assembly.AssemblyDefinition); output.WriteLine(); rd.WriteModuleHeader(assembly.ModuleDefinition); if (options.FullDecompilation) { output.WriteLine(); output.WriteLine(); rd.WriteModuleContents(assembly.ModuleDefinition); } }
public string Decompile(string language, object o) { if (o == null) return String.Empty; Language l = CreateLanguage(language); if (l == null) return String.Format("Can't create language: {0}", language); ITextOutput output = new RtfTextOutput(); DecompilationOptions options = new DecompilationOptions(); if (o is AssemblyDefinition) l.DecompileAssembly((AssemblyDefinition)o, output, options); else if (o is TypeDefinition) l.DecompileType((TypeDefinition)o, output, options); else if (o is MethodDefinition) l.DecompileMethod((MethodDefinition)o, output, options); else if (o is FieldDefinition) l.DecompileField((FieldDefinition)o, output, options); else if (o is PropertyDefinition) l.DecompileProperty((PropertyDefinition)o, output, options); else if (o is EventDefinition) l.DecompileEvent((EventDefinition)o, output, options); else if (o is AssemblyNameReference) { output.Write("// Assembly Reference "); output.WriteDefinition(o.ToString(), null); output.WriteLine(); } else if(o is ModuleReference) { output.Write("// Module Reference "); output.WriteDefinition(o.ToString(), null); output.WriteLine(); } else { output.Write(String.Format("// {0} ", o.GetType().Name)); output.WriteDefinition(o.ToString(), null); output.WriteLine(); } return output.ToString(); }
public string Decompile(object @object) { if (@object == null) return String.Empty; Language l = new CSharpLanguage(); ITextOutput output = new RtfTextOutput(); var options = new DecompilationOptions(); if (@object is AssemblyDefinition) l.DecompileAssembly((AssemblyDefinition)@object, output, options); else if (@object is TypeDefinition) l.DecompileType((TypeDefinition)@object, output, options); else if (@object is MethodDefinition) l.DecompileMethod((MethodDefinition)@object, output, options); else if (@object is FieldDefinition) l.DecompileField((FieldDefinition)@object, output, options); else if (@object is PropertyDefinition) l.DecompileProperty((PropertyDefinition)@object, output, options); else if (@object is EventDefinition) l.DecompileEvent((EventDefinition)@object, output, options); else if (@object is AssemblyNameReference) { output.Write("// Assembly Reference "); output.WriteDefinition(@object.ToString(), null); output.WriteLine(); } else if(@object is ModuleReference) { output.Write("// Module Reference "); output.WriteDefinition(@object.ToString(), null); output.WriteLine(); } else { output.Write(String.Format("// {0} ", @object.GetType().Name)); output.WriteDefinition(@object.ToString(), null); output.WriteLine(); } return output.ToString(); }
public override void DecompileEvent(EventDef ev, ITextOutput output, DecompilationOptions options) { StartKeywordBlock(output, ".event", ev); if (ev.AddMethod != null) { StartKeywordBlock(output, ".add", ev.AddMethod); EndKeywordBlock(output); } if (ev.InvokeMethod != null) { StartKeywordBlock(output, ".invoke", ev.InvokeMethod); EndKeywordBlock(output); } if (ev.RemoveMethod != null) { StartKeywordBlock(output, ".remove", ev.RemoveMethod); EndKeywordBlock(output); } EndKeywordBlock(output); }
// There are several methods available to override; in this sample, we deal with methods only public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { if (method.Body != null) { output.WriteLine("Size of method: {0} bytes", method.Body.CodeSize); ISmartTextOutput smartOutput = output as ISmartTextOutput; if (smartOutput != null) { // when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons: smartOutput.AddButton(null, "Click me!", (sender, e) => (sender as Button).Content = "I was clicked!"); smartOutput.WriteLine(); } // ICSharpCode.Decompiler.Ast.AstBuilder can be used to decompile to C# AstBuilder b = new AstBuilder(new DecompilerContext(method.Module) { Settings = options.DecompilerSettings, CurrentType = method.DeclaringType }); b.AddMethod(method); b.RunTransformations(); output.WriteLine("Decompiled AST has {0} nodes", b.CompilationUnit.DescendantsAndSelf.Count()); } }
public ILSpyWholeProjectDecompiler(LoadedAssembly assembly, DecompilationOptions options) : base(options.DecompilerSettings, assembly.GetAssemblyResolver(), assembly.GetAssemblyReferenceClassifier(), assembly.GetDebugInfoOrNull()) { this.assembly = assembly; this.options = options; }
public virtual void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(property.DeclaringTypeDefinition, includeNamespace: true) + "." + property.Name); }
public override void Decompile(ICSharpCode.ILSpy.Language language, ITextOutput output, ICSharpCode.ILSpy.DecompilationOptions options) { //Switches on the token switch (_tokenProvider.MetadataToken.TokenType) { case TokenType.Module: language.DecompileModule((ModuleDefinition)_tokenProvider, output, options); break; case TokenType.Assembly: language.WriteCommentLine(output, ((AssemblyNameReference)_tokenProvider).FullName); break; case TokenType.TypeDef: language.DecompileType((TypeDefinition)_tokenProvider, output, options); break; case TokenType.Field: language.DecompileField((FieldDefinition)_tokenProvider, output, options); break; case TokenType.Method: language.DecompileMethod((MethodDefinition)_tokenProvider, output, options); break; case TokenType.Event: language.DecompileEvent((EventDefinition)_tokenProvider, output, options); break; case TokenType.Property: language.DecompileProperty((PropertyDefinition)_tokenProvider, output, options); break; case TokenType.MemberRef: var memberRef = (MemberReference)_tokenProvider; if (memberRef.DeclaringType != null && memberRef.DeclaringType is GenericInstanceType) { var giType = (GenericInstanceType)memberRef.DeclaringType; var type = giType.ElementType.Resolve(); var memberDef = type.Fields.Cast <IMemberDefinition>() .Concat(type.Methods) .Concat(type.Properties) .Concat(type.Events) .FirstOrDefault(m => m.Name == memberRef.Name); if (memberDef != null) { new ILEditTreeNode(memberDef, true).Decompile(language, output, options); } } break; default: language.WriteCommentLine(output, (string)this.Text); break; } }
public virtual ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, assembly.FileName); var asm = assembly.GetPEFileOrNull(); if (asm == null) { return(null); } 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); }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true)); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true); if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType) { // also fields and other ctors so that the field initializers can be shown as such AddFieldsAndCtors(codeDomBuilder, method.DeclaringType, method.IsStatic); RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectCtorTransform(method)); } else { codeDomBuilder.AddMethod(method); RunTransformsAndGenerateCode(codeDomBuilder, output, options); } }
public virtual void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name); }
public virtual void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name); }
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleField(field); }
void WriteProject(LoadedAssembly loadedAssembly, Language language, string targetDirectory, CancellationToken ct) { targetDirectory = Path.Combine(targetDirectory, loadedAssembly.ShortName); if (language.ProjectFileExtension == null) { statusOutput.Add("-------------"); statusOutput.Add($"Language '{language.Name}' does not support exporting assemblies as projects!"); return; } string projectFileName = Path.Combine(targetDirectory, loadedAssembly.ShortName + language.ProjectFileExtension); if (File.Exists(targetDirectory)) { statusOutput.Add("-------------"); statusOutput.Add($"Failed to create a directory '{targetDirectory}':{Environment.NewLine}A file with the same name already exists!"); return; } if (!Directory.Exists(targetDirectory)) { try { Directory.CreateDirectory(targetDirectory); } catch (Exception e) { statusOutput.Add("-------------"); statusOutput.Add($"Failed to create a directory '{targetDirectory}':{Environment.NewLine}{e}"); return; } } try { using (var projectFileWriter = new StreamWriter(projectFileName)) { var projectFileOutput = new PlainTextOutput(projectFileWriter); var options = new DecompilationOptions() { FullDecompilation = true, CancellationToken = ct, SaveAsProjectDirectory = targetDirectory }; var projectInfo = language.DecompileAssembly(loadedAssembly, projectFileOutput, options); if (projectInfo != null) { projects.Add(new ProjectItem(projectFileName, projectInfo.PlatformName, projectInfo.Guid, projectInfo.TypeGuid)); } } } catch (NotSupportedException e) { statusOutput.Add("-------------"); statusOutput.Add($"Failed to decompile the assembly '{loadedAssembly.FileName}':{Environment.NewLine}{e.Message}"); } catch (PathTooLongException e) { statusOutput.Add("-------------"); statusOutput.Add(string.Format(Properties.Resources.ProjectExportPathTooLong, loadedAssembly.FileName) + Environment.NewLine + Environment.NewLine + e.ToString()); } catch (Exception e) when(!(e is OperationCanceledException)) { statusOutput.Add("-------------"); statusOutput.Add($"Failed to decompile the assembly '{loadedAssembly.FileName}':{Environment.NewLine}{e}"); } }
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); } if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.StrongNameSigned) != 0) { output.WriteLine("// This assembly is signed with a strong name key."); } if (metadata.IsAssembly) { var asm = metadata.GetAssemblyDefinition(); if (asm.HashAlgorithm != System.Reflection.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; SyntaxTree st; if (options.FullDecompilation) { st = decompiler.DecompileWholeModuleAsSingleFile(); } else { st = decompiler.DecompileModuleAndAssemblyAttributes(); } WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem); } } }
public override void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options) { PEFile assembly = property.ParentModule.PEFile; CSharpDecompiler decompiler = CreateDecompiler(assembly, options); AddReferenceAssemblyWarningMessage(assembly, output); AddReferenceWarningMessage(assembly, output); WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true)); WriteCode(output, options.DecompilerSettings, decompiler.Decompile(property.MetadataToken), decompiler.TypeSystem); }
public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) { ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); rd.DisassembleProperty(property); if (property.GetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.GetMethod); } if (property.SetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.SetMethod); } foreach (var m in property.OtherMethods) { output.WriteLine(); rd.DisassembleMethod(m); } }
public virtual void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name); }
public virtual void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(type, includeNamespace: true)); }
public virtual void DecompileEvent(IEvent @event, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(@event.DeclaringTypeDefinition, includeNamespace: true) + "." + @event.Name); }
public virtual void DecompileField(IField field, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(field.DeclaringTypeDefinition, includeNamespace: true) + "." + field.Name); }
public virtual void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name); }
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options) { var dis = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); dis.DisassembleMethod(method); }
public override void DecompileProperty(PropertyDef property, ITextOutput output, DecompilationOptions options) { ReflectionDisassembler rd = CreateReflectionDisassembler(output, options, property); rd.DisassembleProperty(property); if (property.GetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.GetMethod); } if (property.SetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.SetMethod); } foreach (var m in property.OtherMethods) { output.WriteLine(); rd.DisassembleMethod(m); } }
public virtual void DecompileNamespace(string nameSpace, IEnumerable <ITypeDefinition> types, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, nameSpace); }
IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(ModuleDefinition module, DecompilationOptions options, HashSet <string> directories) { var files = module.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy( delegate(TypeDefinition type) { string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension; // TODO Find more proper way to know root namespace? string rootNs = type.Module.Assembly.Name.Name; // Cut root namespace from sub-directory name for decompiled source files // TODO Control namespaces cutting with some assembly settings option? if (string.IsNullOrEmpty(type.Namespace) || type.Namespace.Equals(rootNs, StringComparison.Ordinal)) { return(file); } else { string dir = type.Namespace; if (dir.StartsWith(rootNs + ".", StringComparison.Ordinal)) { dir = dir.Substring(rootNs.Length + 1); } // Create sub-directories for each namespace part dir = TextView.DecompilerTextView.CleanUpName(dir).Replace('.', Path.DirectorySeparatorChar); if (directories.Add(dir)) { Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dir)); } return(Path.Combine(dir, file)); } }, StringComparer.OrdinalIgnoreCase).ToList(); AstMethodBodyBuilder.ClearUnhandledOpcodes(); Parallel.ForEach( files, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, delegate(IGrouping <string, TypeDefinition> file) { using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module); foreach (TypeDefinition type in file) { codeDomBuilder.AddType(type); } codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(new PlainTextOutput(w)); } }); AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes(); return(files.Select(f => Tuple.Create("Compile", f.Key)).Concat(WriteAssemblyInfo(module, options, directories))); }
ReflectionDisassembler CreateReflectionDisassembler(ITextOutput output, DecompilationOptions options, IMemberDef member) { return CreateReflectionDisassembler(output, options, member.Module); }
public override void DecompileProperty(PropertyDef property, ITextOutput output, DecompilationOptions options) { StartKeywordBlock(output, ".property", property); foreach (var getter in property.GetMethods) { StartKeywordBlock(output, ".get", getter); EndKeywordBlock(output); } foreach (var setter in property.SetMethods) { StartKeywordBlock(output, ".set", setter); EndKeywordBlock(output); } foreach (var other in property.OtherMethods) { StartKeywordBlock(output, ".other", other); EndKeywordBlock(output); } EndKeywordBlock(output); }
public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, assembly.FileName); var name = assembly.AssemblyDefinition.Name; if ((name.Attributes & (AssemblyAttributes)0x0200) != 0) { WriteCommentLine(output, name.Name + " [WinRT]"); } else { WriteCommentLine(output, name.FullName); } }
IEnumerable <Tuple <string, string> > WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options, HashSet <string> directories) { // don't automatically load additional assemblies when an assembly node is selected in the tree view using (LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module); codeDomBuilder.AddAssembly(module, onlyAssemblyLevel: true); codeDomBuilder.RunTransformations(transformAbortCondition); string prop = "Properties"; if (directories.Add("Properties")) { Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, prop)); } string assemblyInfo = Path.Combine(prop, "AssemblyInfo" + this.FileExtension); using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, assemblyInfo))) codeDomBuilder.GenerateCode(new PlainTextOutput(w)); return(new Tuple <string, string>[] { Tuple.Create("Compile", assemblyInfo) }); } }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly.ModuleDefinition); } else { base.DecompileAssembly(assembly, output, options); output.WriteLine(); ModuleDefinition mainModule = assembly.ModuleDefinition; if (mainModule.Types.Count > 0) { output.Write("// Global type: "); output.WriteReference(mainModule.Types[0].FullName, mainModule.Types[0]); output.WriteLine(); } if (mainModule.EntryPoint != null) { output.Write("// Entry point: "); output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint); output.WriteLine(); } output.WriteLine("// Architecture: " + GetPlatformDisplayName(mainModule)); if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) { output.WriteLine("// This assembly contains unmanaged code."); } string runtimeName = GetRuntimeDisplayName(mainModule); if (runtimeName != null) { output.WriteLine("// Runtime: " + runtimeName); } output.WriteLine(); // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition); codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation); codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(output); } } }
public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleProperty(property); }
//wicky.patch.start public override void DecompileAssembly(AssemblyDefinition assembly, ITextOutput output, DecompilationOptions options) { output.WriteLine("// " + assembly.MainModule.FullyQualifiedName); output.WriteLine(); ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken); if (options.FullDecompilation) { rd.WriteAssemblyReferences(assembly.MainModule); } rd.WriteAssemblyHeader(assembly); output.WriteLine(); rd.WriteModuleHeader(assembly.MainModule); if (options.FullDecompilation) { output.WriteLine(); output.WriteLine(); rd.WriteModuleContents(assembly.MainModule); } }
public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options) { var dis = CreateReflectionDisassembler(output, options, method); dis.DisassembleMethod(method); }
public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleEvent(ev); }
public override void DecompileType(TypeDef type, ITextOutput output, DecompilationOptions options) { var dis = CreateReflectionDisassembler(output, options, type); dis.DisassembleType(type); }
public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleType(type); }
public override void DecompileField(FieldDef field, ITextOutput output, DecompilationOptions options) { output.WriteReference(IdentifierEscaper.Escape(field.FieldType.GetFullName()), field.FieldType.ToTypeDefOrRef(), TextTokenHelper.GetTextTokenType(field.FieldType)); output.WriteSpace(); output.WriteDefinition(IdentifierEscaper.Escape(field.Name), field, TextTokenHelper.GetTextTokenType(field), false); var c = field.Constant; if (c != null) { output.WriteSpace(); output.Write('=', TextTokenType.Operator); output.WriteSpace(); if (c.Value == null) output.Write("null", TextTokenType.Keyword); else { switch (c.Type) { case ElementType.Boolean: if (c.Value is bool) output.Write((bool)c.Value ? "true" : "false", TextTokenType.Keyword); else goto default; break; case ElementType.Char: output.Write(string.Format("'{0}'", c.Value), TextTokenType.Char); break; case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.I: case ElementType.U: output.Write(string.Format("{0}", c.Value), TextTokenType.Number); break; case ElementType.String: output.Write(string.Format("{0}", c.Value), TextTokenType.String); break; default: output.Write(string.Format("{0}", c.Value), TextTokenType.Text); break; } } } }
public override void DecompileNamespace(string nameSpace, IEnumerable <TypeDefinition> types, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleNamespace(nameSpace, types); }
public override void DecompileType(TypeDef type, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, string.Format("Type: {0}", type.FullName)); if (type.BaseType != null) { WriteComment(output, string.Format("Base type: ")); output.WriteReference(IdentifierEscaper.Escape(type.BaseType.FullName), type.BaseType, TextTokenType.Comment); output.WriteLine(); } foreach (var nested in type.NestedTypes) { DecompileType(nested, output, options); output.WriteLine(); } foreach (var field in type.Fields) { DecompileField(field, output, options); output.WriteLine(); } foreach (var property in type.Properties) { DecompileProperty(property, output, options); output.WriteLine(); } foreach (var @event in type.Events) { DecompileEvent(@event, output, options); output.WriteLine(); } foreach (var method in type.Methods) { DecompileMethod(method, output, options); output.WriteLine(); } }
public virtual void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(method.DeclaringTypeDefinition, includeNamespace: true) + "." + method.Name); }
void OnExportAssembly(Task<ModuleDefinition> moduleTask, string path) { AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(moduleTask.Result); if (asmNode != null) { string file = DecompilerTextView.CleanUpName(asmNode.LoadedAssembly.ShortName); Language language = sessionSettings.FilterSettings.Language; DecompilationOptions options = new DecompilationOptions(); options.FullDecompilation = true; options.SaveAsProjectDirectory = Path.Combine(App.CommandLineArguments.SaveDirectory, file); if (!Directory.Exists(options.SaveAsProjectDirectory)) { Directory.CreateDirectory(options.SaveAsProjectDirectory); } string fullFile = Path.Combine(options.SaveAsProjectDirectory, file + language.ProjectFileExtension); TextView.SaveToDisk(language, new[] { asmNode }, options, fullFile); } }
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) { WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true)); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: field.DeclaringType, isSingleMember: true); if (field.IsLiteral) { codeDomBuilder.AddField(field); } else { // also decompile ctors so that the field initializer can be shown AddFieldsAndCtors(codeDomBuilder, field.DeclaringType, field.IsStatic); } RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectFieldTransform(field)); }