public void Apply(IList<IElement> elements, DecompilationContext context) { var results = new List<IElement>(); this.ProcessRange(elements, 0, results, new Dictionary<IElement, IElement>()); elements.Clear(); elements.AddRange(results); }
/// <summary> /// Constructor /// </summary> /// <param name="output">Output</param> /// <param name="ctx">Context</param> /// <param name="module">Type</param> public DecompileAssemblyInfo(IDecompilerOutput output, DecompilationContext ctx, ModuleDef module) : base(output, ctx) { if (module == null) throw new ArgumentNullException(nameof(module)); Module = module; KeepAllAttributes = false; }
public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) { WriteCommentBegin(output, true); output.Write("Method: ", BoxedTextColor.Comment); output.Write(IdentifierEscaper.Escape(method.FullName), method, DecompilerReferenceFlags.Definition, BoxedTextColor.Comment); WriteCommentEnd(output, true); output.WriteLine(); if (!method.HasBody) { return; } StartKeywordBlock(output, ".body", method); ILAstBuilder astBuilder = new ILAstBuilder(); ILBlock ilMethod = new ILBlock(); DecompilerContext context = new DecompilerContext(method.Module, MetadataTextColorProvider) { 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", BoxedTextColor.Keyword); output.Write("/", BoxedTextColor.Punctuation); output.WriteLine("await", BoxedTextColor.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.Write(IdentifierEscaper.Escape(v.Name), v, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, v.IsParameter ? BoxedTextColor.Parameter : BoxedTextColor.Local); if (v.Type != null) { output.Write(" ", BoxedTextColor.Text); output.Write(":", BoxedTextColor.Punctuation); output.Write(" ", BoxedTextColor.Text); if (v.IsPinned) { output.Write("pinned", BoxedTextColor.Keyword); output.Write(" ", BoxedTextColor.Text); } v.Type.WriteTo(output, ILNameSyntax.ShortTypeName); } if (v.GeneratedByDecompiler) { output.Write(" ", BoxedTextColor.Text); output.Write("[", BoxedTextColor.Punctuation); output.Write("generated", BoxedTextColor.Keyword); output.Write("]", BoxedTextColor.Punctuation); } output.WriteLine(); } var builder = new MethodDebugInfoBuilder(method); foreach (ILNode node in ilMethod.Body) { node.WriteTo(output, builder); if (!node.WritesNewLine) output.WriteLine(); } output.AddDebugInfo(builder.Create()); EndKeywordBlock(output); }
private BlockStatement body;///This is left to make debugging easier public BlockStatement Process(DecompilationContext context, BlockStatement body) { this.methodContext = context.MethodContext; this.body = body; RemoveGotoStatements(); return body; }
protected override void ApplyToSpecificElement(ref int index, IList<IElement> elements, Stack<BranchStackFrame> branchStack, DecompilationContext context) { var instruction = elements[index] as InstructionElement; if (instruction != null && instruction.OpCode == OpCodes.Nop) { elements.RemoveAt(index); index -= 1; } }
public NodeDecompiler(Func<Func<object>, object> execInThread, IDecompilerOutput output, IDecompiler decompiler, DecompilationContext decompilationContext, IDecompileNodeContext decompileNodeContext = null) { this.execInThread = execInThread; this.output = output; this.decompiler = decompiler; this.decompilationContext = decompilationContext; this.decompileNodeContext = decompileNodeContext; this.decompileNodeContext.ContentTypeString = decompiler.ContentTypeString; }
protected override void ApplyToSpecificElement(ref int index, IList<IElement> elements, Stack<BranchStackFrame> branchStack, DecompilationContext context) { var branching = elements[index] as BranchingElement; if (branching != null && (branching.OpCode == OpCodes.Br || branching.OpCode == OpCodes.Br_S)) { elements.RemoveAt(index); index -= 1; } }
/// <summary> /// Constructor /// </summary> /// <param name="output">Output</param> /// <param name="ctx">Context</param> /// <param name="type">Type</param> public DecompileTypeMethods(IDecompilerOutput output, DecompilationContext ctx, TypeDef type) : base(output, ctx) { if (type == null) throw new ArgumentNullException(nameof(type)); Type = type; Methods = new HashSet<MethodDef>(); DecompileHidden = false; }
/// <summary> /// Constructor /// </summary> /// <param name="output">Output</param> /// <param name="ctx">Context</param> protected DecompileTypeBase(IDecompilerOutput output, DecompilationContext ctx) { if (output == null) throw new ArgumentNullException(nameof(output)); if (ctx == null) throw new ArgumentNullException(nameof(ctx)); Output = output; Context = ctx; }
public BlockStatement Process(DecompilationContext context, BlockStatement body) { this.typeSystem = context.MethodContext.Method.Module.TypeSystem; Visit(body); CleanupRedundantAssignments(); CleanupEmptyIfs(body); return body; }
public Ast.Statements.BlockStatement Process(DecompilationContext context, Ast.Statements.BlockStatement body) { this.context = context; if (ShouldExecuteStep()) { ProcessTheCFG(); AnalyzeAssignments(); } return body; }
public ClassHierarchyBuilder(Dictionary<int, Expression> offsetToExpression, Dictionary<int, Instruction> offsetToInstruction, DecompilationContext context) { this.typeNameToNode = new Dictionary<string, ClassHierarchyNode>(); this.variableNameToNode = new Dictionary<string, ClassHierarchyNode>(); this.resultingGraph = new HashSet<ClassHierarchyNode>(); this.offsetToExpression = offsetToExpression; this.offsetToInstruction = offsetToInstruction; this.methodContext = context.MethodContext; this.typeSystem = context.MethodContext.Method.Module.TypeSystem; }
public BlockStatement Process (DecompilationContext context, BlockStatement block) { for (int i = 0; i < context.Variables.Count; i++) { block.Statements.Insert ( i, new ExpressionStatement ( new VariableDeclarationExpression (context.Variables [i]))); } return block; }
public virtual void DecompileNamespace(string @namespace, IEnumerable<TypeDef> types, IDecompilerOutput output, DecompilationContext ctx) { this.WriteCommentLine(output, string.IsNullOrEmpty(@namespace) ? string.Empty : IdentifierEscaper.Escape(@namespace)); this.WriteCommentLine(output, string.Empty); this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Namespace_Types); this.WriteCommentLine(output, string.Empty); foreach (var type in types) { WriteCommentBegin(output, true); output.Write(IdentifierEscaper.Escape(type.Name), type, DecompilerReferenceFlags.None, BoxedTextColor.Comment); WriteCommentEnd(output, true); output.WriteLine(); } }
public BlockStatement Process (DecompilationContext context, BlockStatement block) { var index = block.Statements.Count - 1; var ret = block.Statements [index] as ReturnStatement; if (ret == null) return block; if (ret.Expression != null) return block; block.Statements.RemoveAt (index); return block; }
public ProjectModuleOptions(ModuleDef module, IDecompiler decompiler, DecompilationContext decompilationContext) { if (decompiler == null) throw new ArgumentNullException(nameof(decompiler)); if (decompilationContext == null) throw new ArgumentNullException(nameof(decompilationContext)); if (module == null) throw new ArgumentNullException(nameof(module)); Module = module; Decompiler = decompiler; DecompilationContext = decompilationContext; ProjectGuid = Guid.NewGuid(); UnpackResources = true; CreateResX = true; DecompileXaml = true; }
protected void WriteAssembly(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) { DecompileInternal(asm, output, ctx); output.WriteLine(); PrintEntryPoint(asm.ManifestModule, output); var peImage = TryGetPEImage(asm.ManifestModule); if (peImage != null) { WriteCommentBegin(output, true); uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp; var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts); var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat); output.Write(string.Format(dnSpy_Decompiler_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment); WriteCommentEnd(output, true); output.WriteLine(); } output.WriteLine(); }
/// <summary> /// The entry point for the class. /// </summary> /// <param name="context">The decompilation context.</param> /// <param name="body">The body of the method.</param> /// <returns>Returns the updated body of the method.</returns> public BlockStatement Process(DecompilationContext context, BlockStatement body) { this.methodContext = context.MethodContext; this.controlFlowGraph = this.methodContext.ControlFlowGraph; this.exceptionHandlers = controlFlowGraph.RawExceptionHandlers; this.blockToInitialStackMap = new int[controlFlowGraph.Blocks.Length][]; this.blockToExitStackMap = new int[controlFlowGraph.Blocks.Length][]; /// Perform the analysis. AnalyzeStackUsage(); GenerateStackVariables(); GenerateStackData(); return body; }
private void ApplyRecursive(IList<IElement> elements, Stack<BranchStackFrame> branchStack, DecompilationContext context) { for (var i = 0; i < elements.Count; i++) { var element = elements[i]; var branching = element as BranchingElement; if (branching != null) { foreach (var branch in branching.GetBranches()) { var frame = new BranchStackFrame(elements, branching, i); branchStack.Push(frame); this.ApplyRecursive(branch, branchStack, context); branchStack.Pop(); i = frame.CurrentIndex; } } this.ApplyToSpecificElement(ref i, elements, branchStack, context); } }
/// <summary> /// The entry point of the step. /// </summary> /// <param name="context">The decompilation context for the current method.</param> /// <param name="body">The body of the current method.</param> /// <returns>Returns the updated body of the current method.</returns> public virtual BlockStatement Process(DecompilationContext context, BlockStatement body) { this.methodContext = context.MethodContext; this.typeSystem = methodContext.Method.Module.TypeSystem; this.body = body; RemoveGotoStatements(); methodContext.Variables.AddRange(switchVariables); methodContext.VariablesToRename.UnionWith(switchVariables); methodContext.Variables.AddRange(labelToVariable.Values); methodContext.VariablesToRename.UnionWith(labelToVariable.Values); CleanupUnneededVariables(); AddDefaultAssignmentsToNewConditionalVariables(body); return body; }
protected override void ApplyToSpecificElement(ref int index, IList<IElement> elements, Stack<BranchStackFrame> branchStack, DecompilationContext context) { var individualContext = new IndividualDecompilationContext(elements, branchStack); var element = elements[index]; var indexFixed = index; var interpretation = this.Interpretations.FirstOrDefault(x => x.CanInterpret(elements[indexFixed])); if (interpretation == null) return; individualContext.CurrentIndex = index; var result = interpretation.Interpret(element, individualContext); index = individualContext.CurrentIndex; // some elements may have been captured, changing the collection, so index resync is needed if (result != null) { elements[index] = result; } else { elements.RemoveAt(index); index -= 1; } }
public BlockStatement Process(DecompilationContext context, BlockStatement body) { this.methodContext = context.MethodContext; TypeSystem typeSystem = context.MethodContext.Method.Module.TypeSystem; logicalBuilderContext = new LogicalFlowBuilderContext(context.MethodContext.ControlFlowGraph); cfgBlockSplitter = new CFGBlockSplitter(logicalBuilderContext); conditionBuilder = new ConditionBuilder(logicalBuilderContext, typeSystem); loopBuilder = new LoopBuilder(logicalBuilderContext, typeSystem); switchBuilder = new SwitchBuilder(logicalBuilderContext); ifBuilder = new IfBuilder(logicalBuilderContext, methodContext.Method.Module.TypeSystem); followNodeDeterminator = new FollowNodeDeterminator(typeSystem); yieldGuardedBlocksBuilder = new YieldGuardedBlocksBuilder(logicalBuilderContext, context); GetMaxIndexOfBlock(); InitializeTheBlock(); guardedBlocksBuilder = new GuardedBlocksBuilder(logicalBuilderContext); context.MethodContext.LogicalConstructsTree = BuildLogicalConstructTree(); context.MethodContext.LogicalConstructsContext = logicalBuilderContext; return body; }
public virtual void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) => this.WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name);
void RunTransformsAndGenerateCode(ref BuilderState state, IDecompilerOutput output, DecompilationContext ctx, IAstTransform additionalTransform = null) { var astBuilder = state.AstBuilder; astBuilder.RunTransformations(transformAbortCondition); if (additionalTransform != null) { additionalTransform.Run(astBuilder.SyntaxTree); } AddXmlDocumentation(ref state, langSettings.Settings, astBuilder); astBuilder.GenerateCode(output); }
public virtual void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx) => this.WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name);
ReflectionDisassembler CreateReflectionDisassembler(IDecompilerOutput output, DecompilationContext ctx, ModuleDef ownerModule) { var disOpts = new DisassemblerOptions(ctx.CancellationToken, ownerModule); if (langSettings.Settings.ShowILComments) { disOpts.GetOpCodeDocumentation = ILLanguageHelper.GetOpCodeDocumentation; } var sb = new StringBuilder(); if (langSettings.Settings.ShowXmlDocumentation) { disOpts.GetXmlDocComments = a => GetXmlDocComments(a, sb); } disOpts.CreateInstructionBytesReader = m => InstructionBytesReader.Create(m, ctx.IsBodyModified != null && ctx.IsBodyModified(m)); disOpts.ShowTokenAndRvaComments = langSettings.Settings.ShowTokenAndRvaComments; disOpts.ShowILBytes = langSettings.Settings.ShowILBytes; disOpts.SortMembers = langSettings.Settings.SortMembers; return(new ReflectionDisassembler(output, detectControlStructure, disOpts)); }
ReflectionDisassembler CreateReflectionDisassembler(IDecompilerOutput output, DecompilationContext ctx, IMemberDef member) => CreateReflectionDisassembler(output, ctx, member.Module);
public override void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) { var dis = CreateReflectionDisassembler(output, ctx, type); dis.DisassembleType(type, true); }
public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) { ReflectionDisassembler rd = CreateReflectionDisassembler(output, ctx, property); rd.DisassembleProperty(property, addLineSep: true); if (property.GetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.GetMethod, true); } if (property.SetMethod != null) { output.WriteLine(); rd.DisassembleMethod(property.SetMethod, true); } foreach (var m in property.OtherMethods) { output.WriteLine(); rd.DisassembleMethod(m, true); } }
public override void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) { var dis = CreateReflectionDisassembler(output, ctx, field); dis.DisassembleField(field, false); }
public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) { var dis = CreateReflectionDisassembler(output, ctx, method); dis.DisassembleMethod(method, true); }
void DecompileInternal(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx) { this.WriteCommentLine(output, mod.Location); this.WriteCommentLine(output, mod.Name); }
public virtual void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) => this.WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name);
public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) { WriteCommentLineDeclaringType(output, property); var state = CreateAstBuilder(ctx, GetDecompilerSettings(), currentType: property.DeclaringType, isSingleMember: true); try { state.AstBuilder.AddProperty(property); RunTransformsAndGenerateCode(ref state, output, ctx); } finally { state.Dispose(); } }
public SettingsTypeProjectFile(TypeDef type, string filename, DecompilationContext decompilationContext, ILanguage language, Func <TextWriter, IDecompilerOutput> createDecompilerOutput) : base(type, filename, decompilationContext, language, createDecompilerOutput) { }
void RunTransformsAndGenerateCode(ref BuilderState state, IDecompilerOutput output, DecompilationContext ctx, IAstTransform?additionalTransform = null) { var astBuilder = state.AstBuilder; astBuilder.RunTransformations(transformAbortCondition); if (!(additionalTransform is null)) { additionalTransform.Run(astBuilder.SyntaxTree); } CSharpDecompiler.AddXmlDocumentation(ref state, GetDecompilerSettings(), astBuilder); var csharpUnit = astBuilder.SyntaxTree; csharpUnit.AcceptVisitor(new ICSharpCode.NRefactory.CSharp.InsertParenthesesVisitor() { InsertParenthesesForReadability = true }); var unit = csharpUnit.AcceptVisitor(new CSharpToVBConverterVisitor(state.AstBuilder.Context.CurrentModule, new ILSpyEnvironmentProvider(state.State.XmlDoc_StringBuilder)), null); var outputFormatter = new VBTextOutputFormatter(output, astBuilder.Context); var formattingPolicy = new VBFormattingOptions(); unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null); }
public virtual void Initialize(DecompilationContext context) { }
public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);
// This pipeline is used by the PropertyDecompiler to finish the decompilation of properties, which are partially decompiled // using the steps from the IntermediateRepresenationPipeline. public override BlockDecompilationPipeline CreatePropertyPipeline(MethodDefinition method, DecompilationContext context) { return(new BlockDecompilationPipeline(CSharpDecompilationSteps(method, false), context)); }
public virtual void DecompileNamespace(string @namespace, IEnumerable <TypeDef> types, IDecompilerOutput output, DecompilationContext ctx) { this.WriteCommentLine(output, string.IsNullOrEmpty(@namespace) ? string.Empty : IdentifierEscaper.Escape(@namespace)); this.WriteCommentLine(output, string.Empty); this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Namespace_Types); this.WriteCommentLine(output, string.Empty); foreach (var type in types) { WriteCommentBegin(output, true); output.Write(IdentifierEscaper.Escape(type.Name), type, DecompilerReferenceFlags.None, BoxedTextColor.Comment); WriteCommentEnd(output, true); output.WriteLine(); } }
public override DecompilationPipeline CreateLambdaPipeline(MethodDefinition method, DecompilationContext context) { return(CreatePipelineInternal(method, context, true)); }
protected void WriteModule(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx) { DecompileInternal(mod, output, ctx); output.WriteLine(); if (mod.Types.Count > 0) { WriteCommentBegin(output, true); output.Write(dnSpy_Decompiler_Resources.Decompile_GlobalType + " ", BoxedTextColor.Comment); output.Write(IdentifierEscaper.Escape(mod.GlobalType.FullName), mod.GlobalType, DecompilerReferenceFlags.None, BoxedTextColor.Comment); output.WriteLine(); } PrintEntryPoint(mod, output); this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Architecture + " " + GetPlatformDisplayName(mod)); if (!mod.IsILOnly) { this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_ThisAssemblyContainsUnmanagedCode); } string runtimeName = GetRuntimeDisplayName(mod); if (runtimeName != null) { this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Runtime + " " + runtimeName); } var peImage = TryGetPEImage(mod); if (peImage != null) { WriteCommentBegin(output, true); uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp; var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts); var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat); output.Write(string.Format(dnSpy_Decompiler_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment); WriteCommentEnd(output, true); output.WriteLine(); } output.WriteLine(); }
public virtual void Decompile(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx) => DecompileInternal(mod, output, ctx);
public virtual void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) => this.WriteCommentLine(output, TypeToString(type, true));
public BlockStatement Process(DecompilationContext context, BlockStatement body) { this.context = context; this.VisitBlockStatement(body); return(body); }
ReflectionDisassembler CreateReflectionDisassembler(ITextOutput output, DecompilationContext ctx, IMemberDef member) { return(CreateReflectionDisassembler(output, ctx, member.Module)); }
public virtual void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) => this.WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name);
public BuilderState(DecompilationContext ctx, BuilderCache cache) { this.ctx = ctx; this.cache = cache; this.State = cache.AllocateAstBuilderState(); }
private DecompilationPipeline CreatePipelineInternal(MethodDefinition method, DecompilationContext context, bool inlineAggressively) { DecompilationPipeline result = base.CreatePipeline(method, context); result.AddSteps(CSharpDecompilationSteps(method, inlineAggressively)); return(result); }
public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);
public override void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);
public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);
public BlockStatement Process (DecompilationContext context, BlockStatement body) { return (BlockStatement) VisitBlockStatement (body); }
public override void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);