Example #1
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();
			}
		}
Example #2
0
		void DoDisassemble(IDnlibDef item, ITextOutput output, ReflectionDisassembler disassembler) {
			if (item is ModuleDef) {
				var module = (ModuleDef)item;
				disassembler.WriteAssemblyReferences(module);
				if (module.Assembly != null)
					disassembler.WriteAssemblyHeader(module.Assembly);
				output.WriteLine();
				disassembler.WriteModuleHeader(module);
			}
			else if (item is TypeDef) {
				disassembler.DisassembleType((TypeDef)item);
			}
			else if (item is MethodDef) {
				disassembler.DisassembleMethod((MethodDef)item);
			}
			else if (item is FieldDef) {
				disassembler.DisassembleField((FieldDef)item);
			}
			else if (item is PropertyDef) {
				disassembler.DisassembleProperty((PropertyDef)item);
			}
			else if (item is EventDef) {
				disassembler.DisassembleEvent((EventDef)item);
			}
		}
Example #3
0
		public static ITextOutput Write(ITextOutput output, MethodDef method, Language language) {
			output.Write(UIUtils.CleanUpIdentifier(method.Name), TextTokenHelper.GetTextTokenType(method));
			output.Write('(', TextTokenType.Operator);
			for (int i = 0; i < method.Parameters.Count; i++) {
				if (method.Parameters[i].IsHiddenThisParameter)
					continue;
				if (method.Parameters[i].MethodSigIndex > 0) {
					output.Write(',', TextTokenType.Operator);
					output.WriteSpace();
				}
				language.TypeToString(output, method.Parameters[i].Type.ToTypeDefOrRef(), false, method.Parameters[i].ParamDef);
			}
			if (method.CallingConvention == CallingConvention.VarArg || method.CallingConvention == CallingConvention.NativeVarArg) {
				if (method.MethodSig.GetParamCount() > 0) {
					output.Write(',', TextTokenType.Operator);
					output.WriteSpace();
				}
				output.Write("...", TextTokenType.Operator);
			}
			output.Write(')', TextTokenType.Operator);
			output.WriteSpace();
			output.Write(':', TextTokenType.Operator);
			output.WriteSpace();
			language.TypeToString(output, method.ReturnType.ToTypeDefOrRef(), false, method.Parameters.ReturnParameter.ParamDef);
			method.MDToken.WriteSuffixString(output);
			return output;
		}
Example #4
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     EnsureChildrenFiltered();
     base.Decompile(language, output, options);
     if (stringTableEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     var textView = options.DecompilerTextView;
                     if (textView != null)
                         return new ResourceStringTable(stringTableEntries, textView) { Cursor = Cursors.Arrow };
                     return new TextBlock { Text = "no active tab!" };
                 }
             );
         }
         output.WriteLine();
         output.WriteLine();
     }
     if (otherEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     var textView = options.DecompilerTextView;
                     if (textView != null)
                         return new ResourceObjectTable(otherEntries, textView) { Cursor = Cursors.Arrow };
                     return new TextBlock { Text = "no active tab!" };
                 }
             );
         }
         output.WriteLine();
     }
 }
Example #5
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureChildrenFiltered));
			foreach (ILSpyTreeNode child in this.Children) {
				child.Decompile(language, output, options);
			}
		}
 protected override void Write(ITextOutput output, Language language)
 {
     var isExe = analyzedAssembly.Assembly != null &&
         analyzedAssembly.IsManifestModule &&
         (analyzedAssembly.Characteristics & dnlib.PE.Characteristics.Dll) == 0;
     output.Write(UIUtils.CleanUpIdentifier(analyzedAssembly.Name), isExe ? TextTokenType.AssemblyExe : TextTokenType.Assembly);
 }
Example #7
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);
        }
Example #8
0
        public override void AcceptWriter(ITextOutput writer)
        {
            List<string> keyList = new List<string>(Values.Keys);
            int keyCount = keyList.Count;

            JsonValue jsonValue;
            bool isFirst = true;
            for (int i = 0; i < keyCount; i++)
            {
                if (isFirst)
                {
                    writer.Write('{');
                    isFirst = false;
                }
                else
                {
                    writer.Write(", ");
                }
                writer.Write('"');
                writer.Write(keyList[i]);
                writer.Write('"');
                writer.Write(':');
                if (Values.TryGetValue(keyList[i], out jsonValue))
                {
                    jsonValue.AcceptWriter(writer);
                }
            }
            if (!isFirst)
                writer.Write('}');
        }
Example #9
0
		public static void WriteTo(this Instruction instruction, ITextOutput writer, Func<OpCode, string> getOpCodeDocumentation)
		{
			writer.WriteDefinition(DnlibExtensions.OffsetToString(instruction.GetOffset()), instruction, TextTokenType.Label, false);
			writer.Write(':', TextTokenType.Operator);
			writer.WriteSpace();
			writer.WriteReference(instruction.OpCode.Name, instruction.OpCode, TextTokenType.OpCode);
			if (instruction.Operand != null) {
				writer.WriteSpace();
				if (instruction.OpCode == OpCodes.Ldtoken) {
					var member = instruction.Operand as IMemberRef;
					if (member != null && member.IsMethod) {
						writer.Write("method", TextTokenType.Keyword);
						writer.WriteSpace();
					}
					else if (member != null && member.IsField) {
						writer.Write("field", TextTokenType.Keyword);
						writer.WriteSpace();
					}
				}
				WriteOperand(writer, instruction.Operand);
			}
			if (getOpCodeDocumentation != null) {
				var doc = getOpCodeDocumentation(instruction.OpCode);
				if (doc != null) {
					writer.Write("\t", TextTokenType.Text);
					writer.Write("// " + doc, TextTokenType.Comment);
				}
			}
		}
Example #10
0
		static void WriteILOffset(ITextOutput output, uint offset) {
			// Offsets are always in hex
			if (offset <= ushort.MaxValue)
				output.Write(string.Format(GetHexFormatUInt16(), offset), TextTokenType.Number);
			else
				output.Write(string.Format(GetHexFormatUInt32(), offset), TextTokenType.Number);
		}
 protected override void Write(ITextOutput output, Language language)
 {
     if (name != null)
         output.Write(name, TextTokenType.Keyword);
     else
         base.Write(output, language);
 }
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     EnsureLazyChildren();
     base.Decompile(language, output, options);
     if (stringTableEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     return new ResourceStringTable(stringTableEntries,
                         new System.Windows.Size(MainWindow.Instance.mainPane.ActualWidth - 45,
                                                 MainWindow.Instance.mainPane.ActualHeight));
                 }
             );
         }
         output.WriteLine();
         output.WriteLine();
     }
     if (otherEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     return new ResourceObjectTable(otherEntries,
                         new System.Windows.Size(MainWindow.Instance.mainPane.ActualWidth - 45,
                                                 MainWindow.Instance.mainPane.ActualHeight));
                 }
             );
         }
         output.WriteLine();
     }
 }
		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);
			codeDomBuilder.AddMethod(method);
			RunTransformsAndGenerateCode(codeDomBuilder, output, options, method.Module);
		}
Example #14
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);
        }
Example #15
0
 public VBTextOutputFormatter(ITextOutput output, VBFormattingOptions formattingPolicy)
 {
     if (output == null)
         throw new ArgumentNullException("output");
     this.output = output;
     this.policy = formattingPolicy;
 }
Example #16
0
		public static void WriteTo(this ExceptionHandler exceptionHandler, ITextOutput writer, MethodDef method)
		{
			writer.Write("Try", TextTokenType.Keyword);
			writer.WriteSpace();
			WriteOffsetReference(writer, exceptionHandler.TryStart, method);
			writer.Write('-', TextTokenType.Operator);
			WriteOffsetReference(writer, exceptionHandler.TryEnd, method);
			writer.WriteSpace();
			writer.Write(exceptionHandler.HandlerType.ToString(), TextTokenType.Keyword);
			if (exceptionHandler.FilterStart != null) {
				writer.WriteSpace();
				WriteOffsetReference(writer, exceptionHandler.FilterStart, method);
				writer.WriteSpace();
				writer.Write("handler", TextTokenType.Keyword);
				writer.WriteSpace();
			}
			if (exceptionHandler.CatchType != null) {
				writer.WriteSpace();
				exceptionHandler.CatchType.WriteTo(writer);
			}
			writer.WriteSpace();
			WriteOffsetReference(writer, exceptionHandler.HandlerStart, method);
			writer.Write('-', TextTokenType.Operator);
			WriteOffsetReference(writer, exceptionHandler.HandlerEnd, method);
		}
Example #17
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);
		}
 public CppTextOutputFormatter(ITextOutput output)
 {
     if (output == null)
         throw new ArgumentNullException("output");
     this.output = output;
     this.IndentationString = "\t";
 }
Example #19
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);
		}
		void Decompile(ModuleDef module, BamlDocument document, ILanguage lang,
			ITextOutput output, out string ext, CancellationToken token) {
			var decompiler = new XamlDecompiler();
			var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null);

			output.Write(xaml.ToString(), TextTokenKind.Text);
			ext = ".xml";
		}
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) {
			App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureChildrenFiltered));
			// Show metadata order of references
			foreach (var r in module.GetAssemblyRefs())
				new AssemblyReferenceTreeNode(r, parentAssembly, dnSpyFileListTreeNode).Decompile(language, output, options);
			foreach (var r in module.GetModuleRefs())
				language.WriteCommentLine(output, IdentifierEscaper.Escape(r.Name));
		}
		public MethodBodyDisassembler(ITextOutput output, bool detectControlStructure, Action verifyProgress)
		{
			if (output == null)
				throw new ArgumentNullException("output");
			this.output = output;
			this.detectControlStructure = detectControlStructure;
			this.verifyProgress = verifyProgress;
		}
Example #23
0
		void Decompile(ModuleDef module, BamlDocument document, Language lang,
			ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) {
			var decompiler = new XamlDecompiler();
			var xaml = decompiler.Decompile(module, document, token);

			output.Write(xaml.ToString(), TextTokenType.Text);
			highlight = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
		}
Example #24
0
		protected virtual void DecompileFields(ILanguage language, ITextOutput output) {
			foreach (var vm in HexVMs) {
				language.WriteCommentLine(output, string.Empty);
				language.WriteCommentLine(output, string.Format("{0}:", vm.Name));
				foreach (var field in vm.HexFields)
					language.WriteCommentLine(output, string.Format("{0:X8} - {1:X8} {2} = {3}", field.StartOffset, field.EndOffset, field.FormattedValue, field.Name));
			}
		}
Example #25
0
 public NodeDecompiler(Func<Func<object>, object> execInThread, ITextOutput output, ILanguage language, DecompilationContext decompilationContext, IDecompileNodeContext decompileNodeContext = null)
 {
     this.execInThread = execInThread;
     this.output = output;
     this.language = language;
     this.decompilationContext = decompilationContext;
     this.decompileNodeContext = decompileNodeContext;
 }
Example #26
0
		protected override void Decompile(DecompileContext ctx, ITextOutput output) {
			var opts = new DecompilePartialType(type, output, decompilationContext);
			foreach (var d in GetDefsToRemove())
				opts.Definitions.Add(d);
			opts.InterfacesToRemove.Add(new TypeRefUser(type.Module, "System.Windows.Markup", "IComponentConnector", new AssemblyNameInfo("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35").ToAssemblyRef()));
			opts.InterfacesToRemove.Add(new TypeRefUser(type.Module, "System.Windows.Markup", "IComponentConnector", new AssemblyNameInfo("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ToAssemblyRef()));
			language.Decompile(DecompilationType.PartialType, opts);
		}
		public MethodBodyDisassembler(ITextOutput output, bool detectControlStructure, CancellationToken cancellationToken)
		{
			if (output == null)
				throw new ArgumentNullException("output");
			this.output = output;
			this.detectControlStructure = detectControlStructure;
			this.cancellationToken = cancellationToken;
		}
Example #28
0
 public MethodBodyDisassembler(ITextOutput output, bool detectControlStructure, DisassemblerOptions options)
 {
     if (output == null)
         throw new ArgumentNullException("output");
     this.output = output;
     this.detectControlStructure = detectControlStructure;
     this.options = options;
 }
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			if (r.IsWindowsRuntime) {
				language.WriteCommentLine(output, r.Name + " [WinRT]");
			} else {
				language.WriteCommentLine(output, r.FullName);
			}
		}
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			if ((r.Attributes & (AssemblyAttributes)0x0200) != 0) {
				language.WriteCommentLine(output, r.Name + " [WinRT]");
			} else {
				language.WriteCommentLine(output, r.FullName);
			}
		}
Example #31
0
 public override void TypeToString(ITextOutput output, ITypeDefOrRef t, bool includeNamespace, IHasCustomAttribute attributeProvider = null)
 {
     t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName);
 }
        public override void WriteTo(ITextOutput output)
        {
            if (Operand is ILVariable && ((ILVariable)Operand).IsGenerated)
            {
                if (Code == ILCode.Stloc && this.InferredType == null)
                {
                    output.Write(((ILVariable)Operand).Name);

                    output.Write(" = ");
                    Arguments.First().WriteTo(output);
                    return;
                }
                else if (Code == ILCode.Ldloc)
                {
                    output.Write(((ILVariable)Operand).Name);
                    if (this.InferredType != null)
                    {
                        output.Write(':');
                        this.InferredType.WriteTo(output, ILNameSyntax.ShortTypeName);
                        if (this.ExpectedType != null && this.ExpectedType.FullName != this.InferredType.FullName)
                        {
                            output.Write("[exp:");
                            this.ExpectedType.WriteTo(output, ILNameSyntax.ShortTypeName);
                            output.Write(']');
                        }
                    }
                    return;
                }
            }

            if (this.Prefixes != null)
            {
                foreach (var prefix in this.Prefixes)
                {
                    output.Write(prefix.Code.GetName());
                    output.Write(". ");
                }
            }

            output.Write(Code.GetName());
            if (this.InferredType != null)
            {
                output.Write(':');
                this.InferredType.WriteTo(output, ILNameSyntax.ShortTypeName);
                if (this.ExpectedType != null && this.ExpectedType.FullName != this.InferredType.FullName)
                {
                    output.Write("[exp:");
                    this.ExpectedType.WriteTo(output, ILNameSyntax.ShortTypeName);
                    output.Write(']');
                }
            }
            else if (this.ExpectedType != null)
            {
                output.Write("[exp:");
                this.ExpectedType.WriteTo(output, ILNameSyntax.ShortTypeName);
                output.Write(']');
            }
            output.Write('(');
            bool first = true;

            if (Operand != null)
            {
                if (Operand is ILLabel)
                {
                    output.WriteReference(((ILLabel)Operand).Name, Operand);
                }
                else if (Operand is ILLabel[])
                {
                    ILLabel[] labels = (ILLabel[])Operand;
                    for (int i = 0; i < labels.Length; i++)
                    {
                        if (i > 0)
                        {
                            output.Write(", ");
                        }
                        output.WriteReference(labels[i].Name, labels[i]);
                    }
                }
                else if (Operand is MemberRef)
                {
                    MemberRef member = (MemberRef)Operand;
                    if (member.DeclaringType != null)
                    {
                        member.DeclaringType.WriteTo(output, ILNameSyntax.ShortTypeName);
                        output.Write("::");
                    }
                    output.WriteReference(member.Name, member);
                }
                else if (Operand is IMethod)
                {
                    IMethod method = (IMethod)Operand;
                    if (method.DeclaringType != null)
                    {
                        method.DeclaringType.WriteTo(output, ILNameSyntax.ShortTypeName);
                        output.Write("::");
                    }
                    output.WriteReference(method.Name, method);
                }
                else if (Operand is IField)
                {
                    IField field = (IField)Operand;
                    field.DeclaringType.WriteTo(output, ILNameSyntax.ShortTypeName);
                    output.Write("::");
                    output.WriteReference(field.Name, field);
                }
                else
                {
                    DisassemblerHelpers.WriteOperand(output, Operand);
                }
                first = false;
            }
            foreach (ILExpression arg in this.Arguments)
            {
                if (!first)
                {
                    output.Write(", ");
                }
                arg.WriteTo(output);
                first = false;
            }
            output.Write(')');
        }
Example #33
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileProperty(PropertyDefinition, output, options);
 }
Example #34
0
 public TextOutputWithRollback(ITextOutput target)
 {
     this.target  = target;
     this.actions = new List <Action <ITextOutput> >();
 }
Example #35
0
 protected abstract void Write(ITextOutput output);
Example #36
0
 public override void DecompileNamespace(string nameSpace, IEnumerable <TypeDef> types, ITextOutput output, DecompilationOptions options)
 {
     new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleNamespace(nameSpace, types);
 }
Example #37
0
        private static ReflectionDisassembler CreateDisassembler(string assemblyPath, MetadataModule module, ITextOutput textOutput)
        {
            var dis = new ReflectionDisassembler(textOutput, CancellationToken.None)
            {
                DetectControlStructure  = true,
                ShowSequencePoints      = false,
                ShowMetadataTokens      = true,
                ExpandMemberDefinitions = true,
            };
            var resolver = new UniversalAssemblyResolver(assemblyPath,
                                                         throwOnError: true,
                                                         targetFramework: module.PEFile.Reader.DetectTargetFrameworkId());

            dis.AssemblyResolver = resolver;
            dis.DebugInfo        = null;

            return(dis);
        }
Example #38
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileNamespace(name, this.Children.OfType <TypeTreeNode>().Select(t => t.TypeDefinition), output, options);
 }
Example #39
0
        public override void DecompileField(FieldDef field, ITextOutput output, DecompilationOptions options)
        {
            var dis = CreateReflectionDisassembler(output, options, field);

            dis.DisassembleField(field);
        }
Example #40
0
        public override void DecompileField(FieldDef field, ITextOutput output, DecompilationOptions options)
        {
            var dis = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            dis.DisassembleField(field);
        }
Example #41
0
 public static void WriteTo(this IMember member, ITextOutput output)
 {
     if (member is IMethod method && method.IsConstructor)
     {
         output.WriteReference(member, method.DeclaringType?.Name + "." + method.Name);
     }
Example #42
0
 public static void Write(this ITextOutput output, StackType stackType)
 {
     output.Write(stackType.ToString().ToLowerInvariant());
 }
Example #43
0
 public static void WriteTo(this IType type, ITextOutput output)
 {
     output.WriteReference(type, type.ReflectionName);
 }
Example #44
0
        public override void DecompileType(TypeDef type, ITextOutput output, DecompilationOptions options)
        {
            var dis = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            dis.DisassembleType(type);
        }
Example #45
0
 public static void Write(this ITextOutput output, PrimitiveType primitiveType)
 {
     output.Write(primitiveType.ToString().ToLowerInvariant());
 }
Example #46
0
        public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
        {
            var dis = CreateReflectionDisassembler(output, options, method);

            dis.DisassembleMethod(method);
        }
Example #47
0
 public static void Write(this ITextOutput output, OpCode opCode)
 {
     output.Write(originalOpCodeNames[(int)opCode]);
 }
Example #48
0
 public override void WriteCommentLine(ITextOutput output, string comment)
 {
     output.WriteLine("; " + comment);
 }
Example #49
0
 protected sealed override void Write(ITextOutput output, Language language)
 {
     Write(output);
 }
Example #50
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            var module = assembly.GetPEFileOrNull();

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

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                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 != 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);
                }
                return(null);
            }
        }
Example #51
0
		public abstract void Decompile(Language language, ITextOutput output, DecompilationOptions options);
Example #52
0
        public static void WriteOperand(ITextOutput writer, object operand)
        {
            if (operand == null)
            {
                throw new ArgumentNullException("operand");
            }

            Instruction targetInstruction = operand as Instruction;

            if (targetInstruction != null)
            {
                WriteOffsetReference(writer, targetInstruction);
                return;
            }

            Instruction[] targetInstructions = operand as Instruction[];
            if (targetInstructions != null)
            {
                WriteLabelList(writer, targetInstructions);
                return;
            }

            VariableReference variableRef = operand as VariableReference;

            if (variableRef != null)
            {
                if (string.IsNullOrEmpty(variableRef.Name))
                {
                    writer.WriteReference(variableRef.Index.ToString(), variableRef);
                }
                else
                {
                    writer.WriteReference(Escape(variableRef.Name), variableRef);
                }
                return;
            }

            ParameterReference paramRef = operand as ParameterReference;

            if (paramRef != null)
            {
                if (string.IsNullOrEmpty(paramRef.Name))
                {
                    writer.WriteReference(paramRef.Index.ToString(), paramRef);
                }
                else
                {
                    writer.WriteReference(Escape(paramRef.Name), paramRef);
                }
                return;
            }

            MethodReference methodRef = operand as MethodReference;

            if (methodRef != null)
            {
                methodRef.WriteTo(writer);
                return;
            }

            TypeReference typeRef = operand as TypeReference;

            if (typeRef != null)
            {
                typeRef.WriteTo(writer, ILNameSyntax.TypeName);
                return;
            }

            FieldReference fieldRef = operand as FieldReference;

            if (fieldRef != null)
            {
                fieldRef.WriteTo(writer);
                return;
            }

            string s = operand as string;

            if (s != null)
            {
                writer.Write("\"" + NRefactory.CSharp.TextWriterTokenWriter.ConvertString(s) + "\"");
            }
            else if (operand is char)
            {
                writer.Write(((int)(char)operand).ToString());
            }
            else if (operand is float)
            {
                float val = (float)operand;
                if (val == 0)
                {
                    if (1 / val == float.NegativeInfinity)
                    {
                        // negative zero is a special case
                        writer.Write('-');
                    }
                    writer.Write("0.0");
                }
                else if (float.IsInfinity(val) || float.IsNaN(val))
                {
                    byte[] data = BitConverter.GetBytes(val);
                    writer.Write('(');
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (i > 0)
                        {
                            writer.Write(' ');
                        }
                        writer.Write(data[i].ToString("X2"));
                    }
                    writer.Write(')');
                }
                else
                {
                    writer.Write(val.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
                }
            }
            else if (operand is double)
            {
                double val = (double)operand;
                if (val == 0)
                {
                    if (1 / val == double.NegativeInfinity)
                    {
                        // negative zero is a special case
                        writer.Write('-');
                    }
                    writer.Write("0.0");
                }
                else if (double.IsInfinity(val) || double.IsNaN(val))
                {
                    byte[] data = BitConverter.GetBytes(val);
                    writer.Write('(');
                    for (int i = 0; i < data.Length; i++)
                    {
                        if (i > 0)
                        {
                            writer.Write(' ');
                        }
                        writer.Write(data[i].ToString("X2"));
                    }
                    writer.Write(')');
                }
                else
                {
                    writer.Write(val.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
                }
            }
            else if (operand is bool)
            {
                writer.Write((bool)operand ? "true" : "false");
            }
            else
            {
                s = ToInvariantCultureString(operand);
                writer.Write(s);
            }
        }
Example #53
0
 public static void WriteOffsetReference(ITextOutput writer, Instruction instruction)
 {
     writer.WriteReference(CecilExtensions.OffsetToString(instruction.Offset), instruction);
 }
Example #54
0
 ReflectionDisassembler CreateReflectionDisassembler(ITextOutput output, DecompilationOptions options, IMemberDef member)
 {
     return(CreateReflectionDisassembler(output, options, member.Module));
 }
Example #55
0
        public static void WriteTo(this TypeReference type, ITextOutput writer, ILNameSyntax syntax = ILNameSyntax.Signature)
        {
            ILNameSyntax syntaxForElementTypes = syntax == ILNameSyntax.SignatureNoNamedTypeParameters ? syntax : ILNameSyntax.Signature;

            if (type is PinnedType)
            {
                ((PinnedType)type).ElementType.WriteTo(writer, syntaxForElementTypes);
                writer.Write(" pinned");
            }
            else if (type is ArrayType)
            {
                ArrayType at = (ArrayType)type;
                at.ElementType.WriteTo(writer, syntaxForElementTypes);
                writer.Write('[');
                writer.Write(string.Join(", ", at.Dimensions));
                writer.Write(']');
            }
            else if (type is GenericParameter)
            {
                writer.Write('!');
                if (((GenericParameter)type).Owner.GenericParameterType == GenericParameterType.Method)
                {
                    writer.Write('!');
                }
                if (string.IsNullOrEmpty(type.Name) || type.Name[0] == '!' || syntax == ILNameSyntax.SignatureNoNamedTypeParameters)
                {
                    writer.Write(((GenericParameter)type).Position.ToString());
                }
                else
                {
                    writer.Write(Escape(type.Name));
                }
            }
            else if (type is ByReferenceType)
            {
                ((ByReferenceType)type).ElementType.WriteTo(writer, syntaxForElementTypes);
                writer.Write('&');
            }
            else if (type is PointerType)
            {
                ((PointerType)type).ElementType.WriteTo(writer, syntaxForElementTypes);
                writer.Write('*');
            }
            else if (type is GenericInstanceType)
            {
                type.GetElementType().WriteTo(writer, syntaxForElementTypes);
                writer.Write('<');
                var arguments = ((GenericInstanceType)type).GenericArguments;
                for (int i = 0; i < arguments.Count; i++)
                {
                    if (i > 0)
                    {
                        writer.Write(", ");
                    }
                    arguments[i].WriteTo(writer, syntaxForElementTypes);
                }
                writer.Write('>');
            }
            else if (type is OptionalModifierType)
            {
                ((OptionalModifierType)type).ElementType.WriteTo(writer, syntax);
                writer.Write(" modopt(");
                ((OptionalModifierType)type).ModifierType.WriteTo(writer, ILNameSyntax.TypeName);
                writer.Write(") ");
            }
            else if (type is RequiredModifierType)
            {
                ((RequiredModifierType)type).ElementType.WriteTo(writer, syntax);
                writer.Write(" modreq(");
                ((RequiredModifierType)type).ModifierType.WriteTo(writer, ILNameSyntax.TypeName);
                writer.Write(") ");
            }
            else
            {
                string name = PrimitiveTypeName(type.FullName);
                if (syntax == ILNameSyntax.ShortTypeName)
                {
                    if (name != null)
                    {
                        writer.Write(name);
                    }
                    else
                    {
                        writer.WriteReference(Escape(type.Name), type);
                    }
                }
                else if ((syntax == ILNameSyntax.Signature || syntax == ILNameSyntax.SignatureNoNamedTypeParameters) && name != null)
                {
                    writer.Write(name);
                }
                else
                {
                    if (syntax == ILNameSyntax.Signature || syntax == ILNameSyntax.SignatureNoNamedTypeParameters)
                    {
                        writer.Write(type.IsValueType ? "valuetype " : "class ");
                    }

                    if (type.DeclaringType != null)
                    {
                        type.DeclaringType.WriteTo(writer, ILNameSyntax.TypeName);
                        writer.Write('/');
                        writer.WriteReference(Escape(type.Name), type);
                    }
                    else
                    {
                        if (!type.IsDefinition && type.Scope != null && !(type is TypeSpecification))
                        {
                            writer.Write("[{0}]", Escape(type.Scope.Name));
                        }
                        writer.WriteReference(Escape(type.FullName), type);
                    }
                }
            }
        }
Example #56
0
 protected override void Write(ITextOutput output, Language language)
 {
     Language.TypeToString(output, analyzedType, true);
     analyzedType.MDToken.WriteSuffixString(output);
 }
 public abstract void WriteTo(ITextOutput output);
Example #58
0
 public OutputConverter(ITextOutput output)
 {
     this.output = output;
 }
Example #59
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, "EventMap");
 }
Example #60
0
        public override void DecompileType(TypeDef type, ITextOutput output, DecompilationOptions options)
        {
            var dis = CreateReflectionDisassembler(output, options, type);

            dis.DisassembleType(type);
        }