Options passed to the decompiler.
Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        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();
            }
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
		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;
		}
Ejemplo n.º 5
0
		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);
		}
Ejemplo n.º 6
0
		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();
			}
		}
Ejemplo n.º 7
0
		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));
		}
Ejemplo n.º 8
0
		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);
		}
Ejemplo n.º 9
0
        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();
            }
        }
Ejemplo n.º 10
0
 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);
     }
 }
Ejemplo n.º 11
0
		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);
		}
Ejemplo n.º 12
0
		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);
			}
		}
Ejemplo n.º 13
0
 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);
     }
 }
Ejemplo n.º 14
0
        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);
Ejemplo n.º 15
0
        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("}");
            
        }
Ejemplo n.º 16
0
		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);
			}
		}
Ejemplo n.º 17
0
		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);
			}
		}
Ejemplo n.º 18
0
        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);
            }
        }
Ejemplo n.º 19
0
        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();
        }
Ejemplo n.º 20
0
        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();
        }
Ejemplo n.º 21
0
        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);
        }
Ejemplo n.º 22
0
		// 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());
			}
		}
Ejemplo n.º 23
0
 public ILSpyWholeProjectDecompiler(LoadedAssembly assembly, DecompilationOptions options)
     : base(options.DecompilerSettings, assembly.GetAssemblyResolver(), assembly.GetAssemblyReferenceClassifier(), assembly.GetDebugInfoOrNull())
 {
     this.assembly = assembly;
     this.options  = options;
 }
Ejemplo n.º 24
0
 public virtual void DecompileProperty(IProperty property, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(property.DeclaringTypeDefinition, includeNamespace: true) + "." + property.Name);
 }
Ejemplo n.º 25
0
        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;
            }
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        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);
            }
        }
Ejemplo n.º 28
0
 public virtual void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name);
 }
Ejemplo n.º 29
0
 public virtual void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name);
 }
Ejemplo n.º 30
0
 public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleField(field);
 }
Ejemplo n.º 31
0
        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}");
            }
        }
Ejemplo n.º 32
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);
                    }
                    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);
                }
            }
        }
Ejemplo n.º 33
0
        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);
        }
Ejemplo n.º 34
0
        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);
            }
        }
Ejemplo n.º 35
0
 public virtual void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name);
 }
Ejemplo n.º 36
0
 public virtual void DecompileType(ITypeDefinition type, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(type, includeNamespace: true));
 }
Ejemplo n.º 37
0
 public virtual void DecompileEvent(IEvent @event, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(@event.DeclaringTypeDefinition, includeNamespace: true) + "." + @event.Name);
 }
Ejemplo n.º 38
0
 public virtual void DecompileField(IField field, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(field.DeclaringTypeDefinition, includeNamespace: true) + "." + field.Name);
 }
Ejemplo n.º 39
0
 public virtual void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name);
 }
Ejemplo n.º 40
0
        public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
        {
            var dis = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            dis.DisassembleMethod(method);
        }
Ejemplo n.º 41
0
 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);
     }
 }
Ejemplo n.º 42
0
 public virtual void DecompileNamespace(string nameSpace, IEnumerable <ITypeDefinition> types, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, nameSpace);
 }
Ejemplo n.º 43
0
        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)));
        }
Ejemplo n.º 44
0
 ReflectionDisassembler CreateReflectionDisassembler(ITextOutput output, DecompilationOptions options, IMemberDef member)
 {
     return CreateReflectionDisassembler(output, options, member.Module);
 }
Ejemplo n.º 45
0
		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);
		}
Ejemplo n.º 46
0
        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);
            }
        }
Ejemplo n.º 47
0
        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) });
            }
        }
Ejemplo n.º 48
0
        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);
                }
            }
        }
Ejemplo n.º 49
0
 public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleProperty(property);
 }
Ejemplo n.º 50
0
        //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);
            }
        }
Ejemplo n.º 51
0
 public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
 {
     var dis = CreateReflectionDisassembler(output, options, method);
     dis.DisassembleMethod(method);
 }
Ejemplo n.º 52
0
 public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleEvent(ev);
 }
Ejemplo n.º 53
0
 public override void DecompileType(TypeDef type, ITextOutput output, DecompilationOptions options)
 {
     var dis = CreateReflectionDisassembler(output, options, type);
     dis.DisassembleType(type);
 }
Ejemplo n.º 54
0
 public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleType(type);
 }
Ejemplo n.º 55
0
		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;
					}
				}
			}
		}
Ejemplo n.º 56
0
 public override void DecompileNamespace(string nameSpace, IEnumerable <TypeDefinition> types, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleNamespace(nameSpace, types);
 }
Ejemplo n.º 57
0
		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();
			}
		}
Ejemplo n.º 58
0
 public virtual void DecompileMethod(IMethod method, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, TypeToString(method.DeclaringTypeDefinition, includeNamespace: true) + "." + method.Name);
 }
Ejemplo n.º 59
0
		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);
			}
		}
Ejemplo n.º 60
0
        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));
        }