Beispiel #1
0
		public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) {
			WriteCommentBegin(output, true);
			output.Write("Method: ", BoxedTextColor.Comment);
			output.Write(IdentifierEscaper.Escape(method.FullName), method, DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
			WriteCommentEnd(output, true);
			output.WriteLine();

			if (!method.HasBody) {
				return;
			}

			StartKeywordBlock(output, ".body", method);

			ILAstBuilder astBuilder = new ILAstBuilder();
			ILBlock ilMethod = new ILBlock();
			DecompilerContext context = new DecompilerContext(method.Module, MetadataTextColorProvider) { CurrentType = method.DeclaringType, CurrentMethod = method };
			ilMethod.Body = astBuilder.Build(method, inlineVariables, context);

			if (abortBeforeStep != null) {
				new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
			}

			if (context.CurrentMethodIsAsync) {
				output.Write("async", BoxedTextColor.Keyword);
				output.Write("/", BoxedTextColor.Punctuation);
				output.WriteLine("await", BoxedTextColor.Keyword);
			}

			var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
				.Where(v => v != null && !v.IsParameter).Distinct();
			foreach (ILVariable v in allVariables) {
				output.Write(IdentifierEscaper.Escape(v.Name), v, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, v.IsParameter ? BoxedTextColor.Parameter : BoxedTextColor.Local);
				if (v.Type != null) {
					output.Write(" ", BoxedTextColor.Text);
					output.Write(":", BoxedTextColor.Punctuation);
					output.Write(" ", BoxedTextColor.Text);
					if (v.IsPinned) {
						output.Write("pinned", BoxedTextColor.Keyword);
						output.Write(" ", BoxedTextColor.Text);
					}
					v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
				}
				if (v.GeneratedByDecompiler) {
					output.Write(" ", BoxedTextColor.Text);
					output.Write("[", BoxedTextColor.Punctuation);
					output.Write("generated", BoxedTextColor.Keyword);
					output.Write("]", BoxedTextColor.Punctuation);
				}
				output.WriteLine();
			}

			var builder = new MethodDebugInfoBuilder(method);
			foreach (ILNode node in ilMethod.Body) {
				node.WriteTo(output, builder);
				if (!node.WritesNewLine)
					output.WriteLine();
			}
			output.AddDebugInfo(builder.Create());
			EndKeywordBlock(output);
		}
Beispiel #2
0
        /// <inheritdoc/>
        public virtual void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset)
        {
            decompiler.WriteCommentBegin(output, true);
            output.WriteOffsetComment(this, showOffset);
            const string LTR = "\u200E";

            output.Write(NameUtilities.CleanName(Name) + LTR, this, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
            string extra = null;

            switch (Resource.ResourceType)
            {
            case ResourceType.AssemblyLinked:
                extra = ((AssemblyLinkedResource)Resource).Assembly.FullName;
                break;

            case ResourceType.Linked:
                var file = ((LinkedResource)Resource).File;
                extra = $"{file.Name}, {(file.ContainsNoMetadata ? "ContainsNoMetaData" : "ContainsMetaData")}, {SimpleTypeConverter.ByteArrayToString(file.HashValue)}";
                break;

            case ResourceType.Embedded:
                extra = string.Format(dnSpy_Contracts_DnSpy_Resources.NumberOfBytes, ((EmbeddedResource)Resource).Length);
                break;
            }
            output.Write($" ({(extra == null ? string.Empty : $"{extra}, ")}{Resource.ResourceType}, {Resource.Attributes})", BoxedTextColor.Comment);
Beispiel #3
0
 /// <summary>
 /// Writes a comment and a new line
 /// </summary>
 /// <param name="self">This</param>
 /// <param name="output">Output</param>
 /// <param name="comment">Comment</param>
 public static void WriteCommentLine(this IDecompiler self, IDecompilerOutput output, string comment)
 {
     self.WriteCommentBegin(output, true);
     output.Write(comment, BoxedTextColor.Comment);
     self.WriteCommentEnd(output, true);
     output.WriteLine();
 }
Beispiel #4
0
 /// <summary>
 /// Writes XML documentation
 /// </summary>
 /// <param name="output">Output</param>
 /// <param name="xmlDocText">XML documentation</param>
 public static void WriteXmlDoc(this IDecompilerOutput output, string xmlDocText)
 {
     foreach (var info in SimpleXmlParser.Parse(xmlDocText))
     {
         output.Write(info.text, info.color);
     }
 }
        public void Write(IDecompilerOutput output, string text, string contentType)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            var ct = contentTypeRegistryService.GetContentType(contentType);

            if (ct == null)
            {
                throw new ArgumentException($"Invalid content type: {contentType}");
            }

            var writer = GetDocumentWriter(ct);

            if (writer != null)
            {
                writer.Write(output, text);
            }
            else
            {
                output.Write(text, BoxedTextColor.Text);
            }
        }
Beispiel #6
0
 protected void WriteCommentLineDeclaringType(IDecompilerOutput output, IMemberDef member)
 {
     WriteCommentBegin(output, true);
     output.Write(TypeToString(member.DeclaringType, includeNamespace: true), member.DeclaringType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
     WriteCommentEnd(output, true);
     output.WriteLine();
 }
Beispiel #7
0
        void Decompile(ModuleDef module, BamlDocument document, ILanguage lang,
                       IDecompilerOutput output, CancellationToken token)
        {
            var decompiler = new XamlDecompiler();
            var xaml       = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null);

            output.Write(xaml.ToString(), BoxedTextColor.Text);
        }
Beispiel #8
0
 protected virtual void FormatPropertyName(IDecompilerOutput output, PropertyDef property, bool?isIndexer = null)
 {
     if (property == null)
     {
         throw new ArgumentNullException(nameof(property));
     }
     output.Write(IdentifierEscaper.Escape(property.Name), MetadataTextColorProvider.GetColor(property));
 }
Beispiel #9
0
 protected virtual void FormatTypeName(IDecompilerOutput output, TypeDef type)
 {
     if (type == null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     output.Write(IdentifierEscaper.Escape(type.Name), MetadataTextColorProvider.GetColor(type));
 }
Beispiel #10
0
        public void WriteHeader(IDecompilerOutput output)
        {
            var cols = MetadataTableVM.TableInfo.Columns;

            output.Write($"{dnSpy_AsmEditor_Resources.RowIdentifier}\t{dnSpy_AsmEditor_Resources.Token}\t{dnSpy_AsmEditor_Resources.Offset}", BoxedTextColor.Comment);
            for (int i = 0; i < cols.Count; i++)
            {
                output.Write("\t", BoxedTextColor.Comment);
                output.Write(MetadataTableVM.GetColumnName(i), BoxedTextColor.Comment);
            }
            if (MetadataTableVM.HasInfo)
            {
                output.Write("\t", BoxedTextColor.Comment);
                output.Write(MetadataTableVM.InfoName, BoxedTextColor.Comment);
            }
            output.WriteLine();
        }
Beispiel #11
0
 bool WriteRefIfByRef(IDecompilerOutput output, TypeSig typeSig, ParamDef pd)
 {
     if (typeSig.RemovePinnedAndModifiers() is ByRefSig)
     {
         if (pd != null && (!pd.IsIn && pd.IsOut))
         {
             output.Write("out", BoxedTextColor.Keyword);
             output.Write(" ", BoxedTextColor.Text);
         }
         else
         {
             output.Write("ref", BoxedTextColor.Keyword);
             output.Write(" ", BoxedTextColor.Text);
         }
         return(true);
     }
     return(false);
 }
Beispiel #12
0
        public void WriteTo(IDecompilerOutput output)
        {
#if DEBUG
            for (int i = 1; i < references.Count; i++)
            {
                if (references[i - 1].Span.End > references[i].Span.Start)
                {
                    throw new InvalidOperationException();
                }
            }
#endif

            int outputStart = output.Length;
            int pos         = 0;
            var textLocal   = text;
            foreach (var info in references)
            {
                if (info.Span.Length == 0)
                {
                    continue;
                }
                if (pos < info.Span.Start)
                {
                    output.Write(textLocal, pos, info.Span.Start - pos, BoxedTextColor.Text);
                }
                var flags = DecompilerReferenceFlags.Local;
                if (info.IsDefinition)
                {
                    flags |= DecompilerReferenceFlags.Definition;
                }
                output.Write(textLocal, info.Span.Start, info.Span.Length, info.Reference, flags, BoxedTextColor.Text);
                pos = info.Span.End;
            }
            if (pos < textLocal.Length)
            {
                output.Write(textLocal, pos, textLocal.Length - pos, BoxedTextColor.Text);
            }
            Debug.Assert(output.Length - outputStart == textLocal.Length);

            foreach (var info in bracesInfo)
            {
                output.AddCodeBracesRange(info);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Writes the offset
        /// </summary>
        /// <param name="output">Output</param>
        /// <param name="node">Node</param>
        /// <param name="showOffsetComment">true if the offset and comment should be written</param>
        public static void WriteOffsetComment(this IDecompilerOutput output, IResourceDataProvider node, bool showOffsetComment)
        {
            if (!showOffsetComment)
            {
                return;
            }

            ulong fo = node.FileOffset;

            if (fo == 0)
            {
                return;
            }

            var mod      = (node as IDocumentTreeNodeData).GetModule();
            var filename = mod == null ? null : mod.Location;

            output.Write($"0x{fo:X8}", new AddressReference(filename, false, fo, node.Length), DecompilerReferenceFlags.None, BoxedTextColor.Comment);
            output.Write(": ", BoxedTextColor.Comment);
        }
Beispiel #14
0
        void TypeToString(IDecompilerOutput output, ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null)
        {
            var envProvider = new ILSpyEnvironmentProvider();
            var converter   = new CSharpToVBConverterVisitor(type.Module, envProvider);
            var astType     = AstBuilder.ConvertType(type, new StringBuilder(), typeAttributes, options);

            if (type.TryGetByRefSig() != null)
            {
                output.Write("ByRef", BoxedTextColor.Keyword);
                output.Write(" ", BoxedTextColor.Text);
                if (astType is ICSharpCode.NRefactory.CSharp.ComposedType && ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank > 0)
                {
                    ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank--;
                }
            }

            var vbAstType = astType.AcceptVisitor(converter, null);

            vbAstType.AcceptVisitor(new OutputVisitor(new VBTextOutputFormatter(output), new VBFormattingOptions()), null);
        }
Beispiel #15
0
        public override void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx)
        {
            this.WriteCommentLine(output, $"Type: {type.FullName}");
            if (type.BaseType != null)
            {
                WriteCommentBegin(output, true);
                output.Write("Base type: ", BoxedTextColor.Comment);
                output.Write(IdentifierEscaper.Escape(type.BaseType.FullName), type.BaseType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
                WriteCommentEnd(output, true);
                output.WriteLine();
            }
            foreach (var nested in type.NestedTypes)
            {
                Decompile(nested, output, ctx);
                output.WriteLine();
            }

            foreach (var field in type.Fields)
            {
                Decompile(field, output, ctx);
                output.WriteLine();
            }

            foreach (var property in type.Properties)
            {
                Decompile(property, output, ctx);
                output.WriteLine();
            }

            foreach (var @event in type.Events)
            {
                Decompile(@event, output, ctx);
                output.WriteLine();
            }

            foreach (var method in type.Methods)
            {
                Decompile(method, output, ctx);
                output.WriteLine();
            }
        }
Beispiel #16
0
		public virtual void DecompileNamespace(string @namespace, IEnumerable<TypeDef> types, IDecompilerOutput output, DecompilationContext ctx) {
			this.WriteCommentLine(output, string.IsNullOrEmpty(@namespace) ? string.Empty : IdentifierEscaper.Escape(@namespace));
			this.WriteCommentLine(output, string.Empty);
			this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Namespace_Types);
			this.WriteCommentLine(output, string.Empty);
			foreach (var type in types) {
				WriteCommentBegin(output, true);
				output.Write(IdentifierEscaper.Escape(type.Name), type, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
		}
Beispiel #17
0
        public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset)
        {
            if (output is IDocumentViewerOutput documentViewerOutput)
            {
                decompiler.WriteCommentBegin(output, true);
                output.WriteOffsetComment(this, showOffset);
                documentViewerOutput.AddUIElement(() => {
                    return(new System.Windows.Controls.Image {
                        Source = imageSource,
                    });
                });
                output.Write(" = ", BoxedTextColor.Comment);
                const string LTR = "\u200E";
                output.Write(NameUtilities.CleanName(Name) + LTR, this, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
                decompiler.WriteCommentEnd(output, true);
                output.WriteLine();
                return;
            }

            base.WriteShort(output, decompiler, showOffset);
        }
Beispiel #18
0
        void WriteTimestampComment(IDecompilerOutput output, IPEImage peImage)
        {
            WriteCommentBegin(output, true);
            output.Write(dnSpy_Decompiler_Resources.Decompile_Timestamp, BoxedTextColor.Comment);
            output.Write(" ", BoxedTextColor.Comment);
            uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;

            if ((int)ts > 0)
            {
                var date       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts).ToLocalTime();
                var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
                output.Write($"{ts:X8} ({dateString})", BoxedTextColor.Comment);
            }
            else
            {
                output.Write(dnSpy_Decompiler_Resources.UnknownValue, BoxedTextColor.Comment);
                output.Write($" ({ts:X8})", BoxedTextColor.Comment);
            }
            WriteCommentEnd(output, true);
            output.WriteLine();
        }
        public void WriteIdentifier(string identifier, object data, object extraData)
        {
            var definition = GetCurrentDefinition();

            if (!(definition is null))
            {
                output.Write(IdentifierEscaper.Escape(identifier), definition, DecompilerReferenceFlags.Definition, data);
                return;
            }

            var memberRef = GetCurrentMemberReference() ?? (object?)(extraData as NamespaceReference);

            if (!(memberRef is null))
            {
                output.Write(IdentifierEscaper.Escape(identifier), memberRef, DecompilerReferenceFlags.None, data);
                return;
            }

            definition = GetCurrentLocalDefinition();
            if (!(definition is null))
            {
                output.Write(IdentifierEscaper.Escape(identifier), definition, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, data);
                return;
            }

            memberRef = GetCurrentLocalReference();
            if (!(memberRef is null))
            {
                output.Write(IdentifierEscaper.Escape(identifier), memberRef, DecompilerReferenceFlags.Local, data);
                return;
            }

            output.Write(IdentifierEscaper.Escape(identifier), data);
        }
Beispiel #20
0
        void EndKeywordBlock(IDecompilerOutput output, BraceInfo info, CodeBracesRangeFlags flags, bool addLineSeparator = false)
        {
            output.DecreaseIndent();
            var end = output.NextPosition;

            output.Write("}", BoxedTextColor.Punctuation);
            output.AddBracePair(new TextSpan(info.Start, 1), new TextSpan(end, 1), flags);
            if (addLineSeparator)
            {
                output.AddLineSeparator(end);
            }
            output.WriteLine();
        }
Beispiel #21
0
        protected void PrintEntryPoint(ModuleDef mod, IDecompilerOutput output)
        {
            var ep = GetEntryPoint(mod);

            if (ep is uint)
            {
                this.WriteCommentLine(output, string.Format(dnSpy_Decompiler_Resources.Decompile_NativeEntryPoint, (uint)ep));
            }
            else if (ep is MethodDef epMethod)
            {
                WriteCommentBegin(output, true);
                output.Write(dnSpy_Decompiler_Resources.Decompile_EntryPoint + " ", BoxedTextColor.Comment);
                if (epMethod.DeclaringType != null)
                {
                    output.Write(IdentifierEscaper.Escape(epMethod.DeclaringType.FullName), epMethod.DeclaringType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
                    output.Write(".", BoxedTextColor.Comment);
                }
                output.Write(IdentifierEscaper.Escape(epMethod.Name), epMethod, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
                WriteCommentEnd(output, true);
                output.WriteLine();
            }
        }
Beispiel #22
0
 public virtual void DecompileNamespace(string @namespace, IEnumerable <TypeDef> types, IDecompilerOutput output, DecompilationContext ctx)
 {
     this.WriteCommentLine(output, string.IsNullOrEmpty(@namespace) ? string.Empty : IdentifierEscaper.Escape(@namespace));
     this.WriteCommentLine(output, string.Empty);
     this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Namespace_Types);
     this.WriteCommentLine(output, string.Empty);
     foreach (var type in types)
     {
         WriteCommentBegin(output, true);
         output.Write(IdentifierEscaper.Escape(type.Name), type, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
         WriteCommentEnd(output, true);
         output.WriteLine();
     }
 }
Beispiel #23
0
        protected void WriteModule(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx)
        {
            DecompileInternal(mod, output, ctx);
            output.WriteLine();
            if (mod.Types.Count > 0)
            {
                this.WriteCommentBegin(output, true);
                output.Write(dnSpy_Languages_Resources.Decompile_GlobalType + " ", BoxedTextColor.Comment);
                output.Write(IdentifierEscaper.Escape(mod.GlobalType.FullName), mod.GlobalType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
                output.WriteLine();
            }
            this.PrintEntryPoint(mod, output);
            this.WriteCommentLine(output, dnSpy_Languages_Resources.Decompile_Architecture + " " + GetPlatformDisplayName(mod));
            if (!mod.IsILOnly)
            {
                this.WriteCommentLine(output, dnSpy_Languages_Resources.Decompile_ThisAssemblyContainsUnmanagedCode);
            }
            string runtimeName = GetRuntimeDisplayName(mod);

            if (runtimeName != null)
            {
                this.WriteCommentLine(output, dnSpy_Languages_Resources.Decompile_Runtime + " " + runtimeName);
            }
            var peImage = TryGetPEImage(mod);

            if (peImage != null)
            {
                this.WriteCommentBegin(output, true);
                uint ts         = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
                var  date       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts);
                var  dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
                output.Write(string.Format(dnSpy_Languages_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment);
                this.WriteCommentEnd(output, true);
                output.WriteLine();
            }
            output.WriteLine();
        }
Beispiel #24
0
        public void WriteTo(IDecompilerOutput output)
        {
            references.Sort(ReferenceInfoSorter.Instance);

            int outputStart = output.Length;
            int pos         = 0;

            foreach (var info in references)
            {
                if (info.Span.Length == 0)
                {
                    continue;
                }
                if (pos < info.Span.Start)
                {
                    output.Write(text, pos, info.Span.Start - pos, BoxedTextColor.Text);
                }
                var refText = text.Substring(info.Span.Start, info.Span.Length);
                var flags   = DecompilerReferenceFlags.Local;
                if (info.IsDefinition)
                {
                    flags |= DecompilerReferenceFlags.Definition;
                }
                output.Write(refText, info.Reference, flags, BoxedTextColor.Text);
                pos = info.Span.End;
            }
            if (pos < text.Length)
            {
                output.Write(text, pos, text.Length - pos, BoxedTextColor.Text);
            }
            Debug.Assert(output.Length - outputStart == text.Length);

            foreach (var info in bracesInfo)
            {
                output.AddCodeBracesRange(info);
            }
        }
Beispiel #25
0
        public void Write(IDecompilerOutput output, MetadataTableRecordVM mdVM)
        {
            var cols = MetadataTableVM.TableInfo.Columns;

            output.Write(mdVM.RidString, BoxedTextColor.Comment);
            output.Write("\t", BoxedTextColor.Comment);
            output.Write(mdVM.TokenString, BoxedTextColor.Comment);
            output.Write("\t", BoxedTextColor.Comment);
            output.Write(mdVM.OffsetString, BoxedTextColor.Comment);
            for (int j = 0; j < cols.Count; j++)
            {
                output.Write("\t", BoxedTextColor.Comment);
                output.Write(mdVM.GetField(j).DataFieldVM.StringValue, BoxedTextColor.Comment);
            }
            if (MetadataTableVM.HasInfo)
            {
                output.Write("\t", BoxedTextColor.Comment);
                output.Write(mdVM.Info, BoxedTextColor.Comment);
            }
            output.WriteLine();
        }
Beispiel #26
0
        protected void WriteAssembly(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx)
        {
            DecompileInternal(asm, output, ctx);
            output.WriteLine();
            this.PrintEntryPoint(asm.ManifestModule, output);
            var peImage = TryGetPEImage(asm.ManifestModule);

            if (peImage != null)
            {
                this.WriteCommentBegin(output, true);
                uint ts         = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
                var  date       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts);
                var  dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
                output.Write(string.Format(dnSpy_Languages_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment);
                this.WriteCommentEnd(output, true);
                output.WriteLine();
            }
            output.WriteLine();
        }
Beispiel #27
0
        public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset)
        {
            if (output is IDocumentViewerOutput documentViewerOutput)
            {
                for (int i = 0; i < imageListOptions.ImageSources.Count; i++)
                {
                    if (i > 0)
                    {
                        output.Write(" ", BoxedTextColor.Text);
                    }
                    var imageSource = imageListOptions.ImageSources[i];
                    documentViewerOutput.AddUIElement(() => {
                        return(new System.Windows.Controls.Image {
                            Source = imageSource,
                        });
                    });
                }
            }

            base.WriteShort(output, decompiler, showOffset);
        }
        private void BlocksListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ILView.Document.Blocks.Clear();

            var  options  = new DisassemblerOptions(new System.Threading.CancellationToken(), null);
            uint rva      = (uint)method.RVA;
            uint baseRva  = rva == 0 ? 0 : rva + method.Body.HeaderSize;
            long baseOffs = baseRva == 0 ? 0 : method.Module.ToFileOffset(baseRva) ?? 0;
            int  startLocation;

            foreach (var instr in cflowDeobfuscator.UnsolvedBlocks[BlocksListView.SelectedIndex].Block.Instructions)
            {
                instr.Instruction.WriteTo(ilOutput, options, baseRva, baseOffs, null, method, out startLocation);
                ilOutput.Write("\r", BoxedTextColor.Text);
            }

            ExprView.Document.Blocks.Clear();

            var expr = cflowDeobfuscator.UnsolvedBlocks[BlocksListView.SelectedIndex].Expression;

            exprOutput.Write(TextColor.String, expr.ToString());

            Consts.Items.Clear();

            GetConsts(expr);

            Consts.IsEnabled = true;

            if (Consts.Items.Count > 0)
            {
                Consts.SelectedIndex = 0;
            }
            else
            {
                Consts.IsEnabled = false;
            }
        }
Beispiel #29
0
        protected override void FormatPropertyName(IDecompilerOutput output, PropertyDef property, bool?isIndexer)
        {
            if (property == null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            if (!isIndexer.HasValue)
            {
                isIndexer = property.IsIndexer();
            }
            if (isIndexer.Value)
            {
                var accessor = property.GetMethod ?? property.SetMethod;
                if (accessor != null && accessor.HasOverrides)
                {
                    var methDecl      = accessor.Overrides.First().MethodDeclaration;
                    var declaringType = methDecl == null ? null : methDecl.DeclaringType;
                    TypeToString(output, declaringType, includeNamespace: true);
                    output.Write(".", BoxedTextColor.Operator);
                }
                output.Write("this", BoxedTextColor.Keyword);
                output.Write("[", BoxedTextColor.Punctuation);
                bool addSeparator = false;
                foreach (var p in property.PropertySig.GetParams())
                {
                    if (addSeparator)
                    {
                        output.Write(",", BoxedTextColor.Punctuation);
                        output.Write(" ", BoxedTextColor.Text);
                    }
                    else
                    {
                        addSeparator = true;
                    }
                    TypeToString(output, p.ToTypeDefOrRef(), includeNamespace: true);
                }
                output.Write("]", BoxedTextColor.Punctuation);
            }
            else
            {
                WriteIdentifier(output, property.Name, TextColorHelper.GetColor(property));
            }
        }
Beispiel #30
0
		protected virtual void TypeToString(IDecompilerOutput output, ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null) {
			if (type == null)
				return;
			if (includeNamespace)
				output.Write(IdentifierEscaper.Escape(type.FullName), MetadataTextColorProvider.GetColor(type));
			else
				output.Write(IdentifierEscaper.Escape(type.Name), MetadataTextColorProvider.GetColor(type));
		}
Beispiel #31
0
		void EndKeywordBlock(IDecompilerOutput output) {
			output.DecreaseIndent();
			output.Write("}", BoxedTextColor.Punctuation);
			output.WriteLine();
		}
Beispiel #32
0
		/// <summary>
		/// Writes a comment and a new line
		/// </summary>
		/// <param name="self">This</param>
		/// <param name="output">Output</param>
		/// <param name="comment">Comment</param>
		public static void WriteCommentLine(this IDecompiler self, IDecompilerOutput output, string comment) {
			self.WriteCommentBegin(output, true);
			output.Write(comment, BoxedTextColor.Comment);
			self.WriteCommentEnd(output, true);
			output.WriteLine();
		}
Beispiel #33
0
		public void Write(IDecompilerOutput output, MetaDataTableRecordVM mdVM) {
			var cols = MetaDataTableVM.TableInfo.Columns;

			output.Write(mdVM.RidString, BoxedTextColor.Comment);
			output.Write("\t", BoxedTextColor.Comment);
			output.Write(mdVM.TokenString, BoxedTextColor.Comment);
			output.Write("\t", BoxedTextColor.Comment);
			output.Write(mdVM.OffsetString, BoxedTextColor.Comment);
			for (int j = 0; j < cols.Count; j++) {
				output.Write("\t", BoxedTextColor.Comment);
				output.Write(mdVM.GetField(j).DataFieldVM.StringValue, BoxedTextColor.Comment);
			}
			if (MetaDataTableVM.HasInfo) {
				output.Write("\t", BoxedTextColor.Comment);
				output.Write(mdVM.Info, BoxedTextColor.Comment);
			}
			output.WriteLine();
		}
Beispiel #34
0
		protected void WriteModule(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx) {
			DecompileInternal(mod, output, ctx);
			output.WriteLine();
			if (mod.Types.Count > 0) {
				WriteCommentBegin(output, true);
				output.Write(dnSpy_Decompiler_Resources.Decompile_GlobalType + " ", BoxedTextColor.Comment);
				output.Write(IdentifierEscaper.Escape(mod.GlobalType.FullName), mod.GlobalType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
				output.WriteLine();
			}
			PrintEntryPoint(mod, output);
			this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Architecture + " " + GetPlatformDisplayName(mod));
			if (!mod.IsILOnly) {
				this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_ThisAssemblyContainsUnmanagedCode);
			}
			string runtimeName = GetRuntimeDisplayName(mod);
			if (runtimeName != null) {
				this.WriteCommentLine(output, dnSpy_Decompiler_Resources.Decompile_Runtime + " " + runtimeName);
			}
			var peImage = TryGetPEImage(mod);
			if (peImage != null) {
				WriteCommentBegin(output, true);
				uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
				var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts);
				var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
				output.Write(string.Format(dnSpy_Decompiler_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
			output.WriteLine();
		}
Beispiel #35
0
		bool WriteRefIfByRef(IDecompilerOutput output, TypeSig typeSig, ParamDef pd) {
			if (typeSig.RemovePinnedAndModifiers() is ByRefSig) {
				if (pd != null && (!pd.IsIn && pd.IsOut)) {
					output.Write("out", BoxedTextColor.Keyword);
					output.Write(" ", BoxedTextColor.Text);
				}
				else {
					output.Write("ref", BoxedTextColor.Keyword);
					output.Write(" ", BoxedTextColor.Text);
				}
				return true;
			}
			return false;
		}
Beispiel #36
0
		static void WriteIdentifier(IDecompilerOutput output, string id, object tokenKind) {
			if (isKeyword.Contains(id))
				output.Write("@", tokenKind);
			output.Write(IdentifierEscaper.Escape(id), tokenKind);
		}
Beispiel #37
0
 void ISimpleILPrinter.Write(IDecompilerOutput output, MethodSig?sig) => output.Write(sig);
		/// <inheritdoc/>
		public virtual void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) {
			decompiler.WriteCommentBegin(output, true);
			output.WriteOffsetComment(this, showOffset);
			const string LTR = "\u200E";
			output.Write(NameUtilities.CleanName(Name) + LTR, this, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
			output.Write($" = {ValueString}", BoxedTextColor.Comment);
			decompiler.WriteCommentEnd(output, true);
			output.WriteLine();
		}
Beispiel #39
0
		protected override void FormatPropertyName(IDecompilerOutput output, PropertyDef property, bool? isIndexer) {
			if (property == null)
				throw new ArgumentNullException(nameof(property));

			if (!isIndexer.HasValue) {
				isIndexer = property.IsIndexer();
			}
			if (isIndexer.Value) {
				var accessor = property.GetMethod ?? property.SetMethod;
				if (accessor != null && accessor.HasOverrides) {
					var methDecl = accessor.Overrides.First().MethodDeclaration;
					var declaringType = methDecl == null ? null : methDecl.DeclaringType;
					TypeToString(output, declaringType, includeNamespace: true);
					output.Write(".", BoxedTextColor.Operator);
				}
				output.Write("this", BoxedTextColor.Keyword);
				output.Write("[", BoxedTextColor.Punctuation);
				bool addSeparator = false;
				foreach (var p in property.PropertySig.GetParams()) {
					if (addSeparator) {
						output.Write(",", BoxedTextColor.Punctuation);
						output.Write(" ", BoxedTextColor.Text);
					}
					else
						addSeparator = true;
					TypeToString(output, p.ToTypeDefOrRef(), includeNamespace: true);
				}
				output.Write("]", BoxedTextColor.Punctuation);
			}
			else
				WriteIdentifier(output, property.Name, MetadataTextColorProvider.GetColor(property));
		}
Beispiel #40
0
		public override void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) {
			this.WriteCommentLine(output, $"Type: {type.FullName}");
			if (type.BaseType != null) {
				WriteCommentBegin(output, true);
				output.Write("Base type: ", BoxedTextColor.Comment);
				output.Write(IdentifierEscaper.Escape(type.BaseType.FullName), type.BaseType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
			foreach (var nested in type.NestedTypes) {
				Decompile(nested, output, ctx);
				output.WriteLine();
			}

			foreach (var field in type.Fields) {
				Decompile(field, output, ctx);
				output.WriteLine();
			}

			foreach (var property in type.Properties) {
				Decompile(property, output, ctx);
				output.WriteLine();
			}

			foreach (var @event in type.Events) {
				Decompile(@event, output, ctx);
				output.WriteLine();
			}

			foreach (var method in type.Methods) {
				Decompile(method, output, ctx);
				output.WriteLine();
			}
		}
Beispiel #41
0
		public override void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) {
			output.Write(IdentifierEscaper.Escape(field.FieldType.GetFullName()), field.FieldType.ToTypeDefOrRef(), DecompilerReferenceFlags.None, MetadataTextColorProvider.GetColor(field.FieldType));
			output.Write(" ", BoxedTextColor.Text);
			output.Write(IdentifierEscaper.Escape(field.Name), field, DecompilerReferenceFlags.Definition, MetadataTextColorProvider.GetColor(field));
			var c = field.Constant;
			if (c != null) {
				output.Write(" ", BoxedTextColor.Text);
				output.Write("=", BoxedTextColor.Operator);
				output.Write(" ", BoxedTextColor.Text);
				if (c.Value == null)
					output.Write("null", BoxedTextColor.Keyword);
				else {
					switch (c.Type) {
					case ElementType.Boolean:
						if (c.Value is bool)
							output.Write((bool)c.Value ? "true" : "false", BoxedTextColor.Keyword);
						else
							goto default;
						break;

					case ElementType.Char:
						output.Write($"'{c.Value}'", BoxedTextColor.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($"{c.Value}", BoxedTextColor.Number);
						break;

					case ElementType.String:
						output.Write($"{c.Value}", BoxedTextColor.String);
						break;

					default:
						output.Write($"{c.Value}", BoxedTextColor.Text);
						break;
					}
				}
			}
		}
Beispiel #42
0
		protected virtual void FormatPropertyName(IDecompilerOutput output, PropertyDef property, bool? isIndexer = null) {
			if (property == null)
				throw new ArgumentNullException(nameof(property));
			output.Write(IdentifierEscaper.Escape(property.Name), MetadataTextColorProvider.GetColor(property));
		}
Beispiel #43
0
		public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) {
			var documentViewerOutput = output as IDocumentViewerOutput;
			if (documentViewerOutput != null) {
				decompiler.WriteCommentBegin(output, true);
				output.WriteOffsetComment(this, showOffset);
				documentViewerOutput.AddUIElement(() => {
					return new System.Windows.Controls.Image {
						Source = imageSource,
					};
				});
				output.Write(" = ", BoxedTextColor.Comment);
				const string LTR = "\u200E";
				output.Write(NameUtilities.CleanName(Name) + LTR, this, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
				decompiler.WriteCommentEnd(output, true);
				output.WriteLine();
				return;
			}

			base.WriteShort(output, decompiler, showOffset);
		}
Beispiel #44
0
		protected virtual void FormatTypeName(IDecompilerOutput output, TypeDef type) {
			if (type == null)
				throw new ArgumentNullException(nameof(type));
			output.Write(IdentifierEscaper.Escape(type.Name), MetadataTextColorProvider.GetColor(type));
		}
Beispiel #45
0
		private void WriteError(IDecompilerOutput output) =>
			output.Write(errorText, BoxedTextColor.Error);
Beispiel #46
0
		protected void WriteAssembly(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) {
			DecompileInternal(asm, output, ctx);
			output.WriteLine();
			PrintEntryPoint(asm.ManifestModule, output);
			var peImage = TryGetPEImage(asm.ManifestModule);
			if (peImage != null) {
				WriteCommentBegin(output, true);
				uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
				var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts);
				var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
				output.Write(string.Format(dnSpy_Decompiler_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
			output.WriteLine();
		}
Beispiel #47
0
		void ISimpleILPrinter.Write(IDecompilerOutput output, MethodSig sig) => output.Write(sig);
Beispiel #48
0
			public void Write(IDecompilerOutput output, string text, string contentType) =>
				output.Write(text, BoxedTextColor.Text);
Beispiel #49
0
		protected void PrintEntryPoint(ModuleDef mod, IDecompilerOutput output) {
			var ep = GetEntryPoint(mod);
			if (ep is uint)
				this.WriteCommentLine(output, string.Format(dnSpy_Decompiler_Resources.Decompile_NativeEntryPoint, (uint)ep));
			else if (ep is MethodDef) {
				var epMethod = (MethodDef)ep;
				WriteCommentBegin(output, true);
				output.Write(dnSpy_Decompiler_Resources.Decompile_EntryPoint + " ", BoxedTextColor.Comment);
				if (epMethod.DeclaringType != null) {
					output.Write(IdentifierEscaper.Escape(epMethod.DeclaringType.FullName), epMethod.DeclaringType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
					output.Write(".", BoxedTextColor.Comment);
				}
				output.Write(IdentifierEscaper.Escape(epMethod.Name), epMethod, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
		}
Beispiel #50
0
        public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx)
        {
            WriteCommentBegin(output, true);
            output.Write("Method: ", BoxedTextColor.Comment);
            output.Write(IdentifierEscaper.Escape(method.FullName), method, DecompilerReferenceFlags.Definition, BoxedTextColor.Comment);
            WriteCommentEnd(output, true);
            output.WriteLine();

            if (!method.HasBody)
            {
                return;
            }

            var bodyInfo = StartKeywordBlock(output, ".body", method);

            ILAstBuilder      astBuilder = new ILAstBuilder();
            ILBlock           ilMethod   = new ILBlock(CodeBracesRangeFlags.MethodBraces);
            DecompilerContext context    = new DecompilerContext(method.Module, MetadataTextColorProvider)
            {
                CurrentType       = method.DeclaringType,
                CurrentMethod     = method,
                CalculateBinSpans = ctx.CalculateBinSpans,
            };

            ilMethod.Body = astBuilder.Build(method, inlineVariables, context);

            if (abortBeforeStep != null)
            {
                new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
            }

            if (context.CurrentMethodIsYieldReturn)
            {
                output.Write("yield", BoxedTextColor.Keyword);
                output.Write(" ", BoxedTextColor.Text);
                output.WriteLine("return", BoxedTextColor.Keyword);
            }
            if (context.CurrentMethodIsAsync)
            {
                output.Write("async", BoxedTextColor.Keyword);
                output.Write("/", BoxedTextColor.Punctuation);
                output.WriteLine("await", BoxedTextColor.Keyword);
            }

            var allVariables = ilMethod.GetSelfAndChildrenRecursive <ILExpression>().Select(e => e.Operand as ILVariable)
                               .Where(v => v != null && !v.IsParameter).Distinct();

            foreach (ILVariable v in allVariables)
            {
                output.Write(IdentifierEscaper.Escape(v.Name), (object)v.OriginalVariable ?? (object)v.OriginalParameter ?? v.Id, DecompilerReferenceFlags.Local | DecompilerReferenceFlags.Definition, v.IsParameter ? BoxedTextColor.Parameter : BoxedTextColor.Local);
                if (v.Type != null)
                {
                    output.Write(" ", BoxedTextColor.Text);
                    output.Write(":", BoxedTextColor.Punctuation);
                    output.Write(" ", BoxedTextColor.Text);
                    if (v.IsPinned)
                    {
                        output.Write("pinned", BoxedTextColor.Keyword);
                        output.Write(" ", BoxedTextColor.Text);
                    }
                    v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
                }
                if (v.GeneratedByDecompiler)
                {
                    output.Write(" ", BoxedTextColor.Text);
                    var start = output.NextPosition;
                    output.Write("[", BoxedTextColor.Punctuation);
                    output.Write("generated", BoxedTextColor.Keyword);
                    var end = output.NextPosition;
                    output.Write("]", BoxedTextColor.Punctuation);
                    output.AddBracePair(new TextSpan(start, 1), new TextSpan(end, 1), CodeBracesRangeFlags.SquareBrackets);
                }
                output.WriteLine();
            }

            var builder = new MethodDebugInfoBuilder(method);

            foreach (ILNode node in ilMethod.Body)
            {
                node.WriteTo(output, builder);
                if (!node.WritesNewLine)
                {
                    output.WriteLine();
                }
            }
            output.AddDebugInfo(builder.Create());
            EndKeywordBlock(output, bodyInfo, CodeBracesRangeFlags.MethodBraces, addLineSeparator: true);
        }
Beispiel #51
0
		protected void WriteCommentLineDeclaringType(IDecompilerOutput output, IMemberDef member) {
			WriteCommentBegin(output, true);
			output.Write(TypeToString(member.DeclaringType, includeNamespace: true), member.DeclaringType, DecompilerReferenceFlags.None, BoxedTextColor.Comment);
			WriteCommentEnd(output, true);
			output.WriteLine();
		}
Beispiel #52
0
		public void WriteHeader(IDecompilerOutput output) {
			var cols = MetaDataTableVM.TableInfo.Columns;

			output.Write(string.Format("{0}\t{1}\t{2}", dnSpy_AsmEditor_Resources.RowIdentifier, dnSpy_AsmEditor_Resources.Token, dnSpy_AsmEditor_Resources.Offset), BoxedTextColor.Comment);
			for (int i = 0; i < cols.Count; i++) {
				output.Write("\t", BoxedTextColor.Comment);
				output.Write(MetaDataTableVM.GetColumnName(i), BoxedTextColor.Comment);
			}
			if (MetaDataTableVM.HasInfo) {
				output.Write("\t", BoxedTextColor.Comment);
				output.Write(MetaDataTableVM.InfoName, BoxedTextColor.Comment);
			}
			output.WriteLine();
		}
Beispiel #53
0
		public virtual void WriteCommentBegin(IDecompilerOutput output, bool addSpace) {
			if (addSpace)
				output.Write("// ", BoxedTextColor.Comment);
			else
				output.Write("//", BoxedTextColor.Comment);
		}
Beispiel #54
0
		void StartKeywordBlock(IDecompilerOutput output, string keyword, IMemberDef member) {
			output.Write(keyword, BoxedTextColor.Keyword);
			output.Write(" ", BoxedTextColor.Text);
			output.Write(IdentifierEscaper.Escape(member.Name), member, DecompilerReferenceFlags.Definition, MetadataTextColorProvider.GetColor(member));
			output.Write(" ", BoxedTextColor.Text);
			output.Write("{", BoxedTextColor.Punctuation);
			output.WriteLine();
			output.IncreaseIndent();
		}
Beispiel #55
0
		public override void WriteCommentBegin(IDecompilerOutput output, bool addSpace) {
			if (addSpace)
				output.Write("' ", BoxedTextColor.Comment);
			else
				output.Write("'", BoxedTextColor.Comment);
		}
Beispiel #56
0
 void Write(IDecompilerOutput output, object value)
 {
     output.Write(string.Format("Missing ISimpleILPrinter: {0}", value), BoxedTextColor.Text);
 }
Beispiel #57
0
		void TypeToString(IDecompilerOutput output, ConvertTypeOptions options, ITypeDefOrRef type, IHasCustomAttribute typeAttributes = null) {
			var envProvider = new ILSpyEnvironmentProvider();
			var converter = new CSharpToVBConverterVisitor(type.Module, envProvider);
			var astType = AstBuilder.ConvertType(type, new StringBuilder(), typeAttributes, options);

			if (type.TryGetByRefSig() != null) {
				output.Write("ByRef", BoxedTextColor.Keyword);
				output.Write(" ", BoxedTextColor.Text);
				if (astType is ICSharpCode.NRefactory.CSharp.ComposedType && ((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank > 0)
					((ICSharpCode.NRefactory.CSharp.ComposedType)astType).PointerRank--;
			}

			var vbAstType = astType.AcceptVisitor(converter, null);

			vbAstType.AcceptVisitor(new OutputVisitor(new VBTextOutputFormatter(output), new VBFormattingOptions()), null);
		}