void Decompile(ModuleDef module, BamlDocument document, IDecompiler lang,
			IDecompilerOutput output, CancellationToken token) {
			var decompiler = new XamlDecompiler();
			var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null);
			var xamlText = new XamlOutputCreator(xamlOutputOptionsProvider.Default).CreateText(xaml);
			documentWriterService.Write(output, xamlText, ContentTypes.Xaml);
		}
Example #2
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);
		}
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="output">Output</param>
		/// <param name="ctx">Context</param>
		/// <param name="module">Type</param>
		public DecompileAssemblyInfo(IDecompilerOutput output, DecompilationContext ctx, ModuleDef module)
			: base(output, ctx) {
			if (module == null)
				throw new ArgumentNullException(nameof(module));
			Module = module;
			KeepAllAttributes = false;
		}
Example #4
0
		public static bool Write(IDecompilerOutput output, IMemberRef member) {
			var method = member as IMethod;
			if (method != null && method.IsMethod) {
				method.WriteMethodTo(output);
				return true;
			}

			var field = member as IField;
			if (field != null && field.IsField) {
				field.WriteFieldTo(output);
				return true;
			}

			var prop = member as PropertyDef;
			if (prop != null) {
				var dis = new ReflectionDisassembler(output, false, new DisassemblerOptions(new System.Threading.CancellationToken(), null));
				dis.DisassembleProperty(prop, false);
				return true;
			}

			var evt = member as EventDef;
			if (evt != null) {
				var dis = new ReflectionDisassembler(output, false, new DisassemblerOptions(new System.Threading.CancellationToken(), null));
				dis.DisassembleEvent(evt, false);
				return true;
			}

			var type = member as ITypeDefOrRef;
			if (type != null) {
				type.WriteTo(output, ILNameSyntax.TypeName);
				return true;
			}

			return false;
		}
Example #5
0
		protected virtual void DecompileFields(IDecompiler decompiler, IDecompilerOutput output) {
			foreach (var vm in HexVMs) {
				decompiler.WriteCommentLine(output, string.Empty);
				decompiler.WriteCommentLine(output, string.Format("{0}:", vm.Name));
				foreach (var field in vm.HexFields)
					decompiler.WriteCommentLine(output, string.Format("{0:X8} - {1:X8} {2} = {3}", field.Span.Start.ToUInt64(), field.Span.End.ToUInt64() - 1, field.FormattedValue, field.Name));
			}
		}
Example #6
0
		protected override void Decompile(DecompileContext ctx, IDecompilerOutput output) {
			var opts = new DecompilePartialType(output, decompilationContext, Type);
			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()));
			decompiler.Decompile(DecompilationType.PartialType, opts);
		}
Example #7
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="output">Output</param>
		/// <param name="ctx">Context</param>
		protected DecompileTypeBase(IDecompilerOutput output, DecompilationContext ctx) {
			if (output == null)
				throw new ArgumentNullException(nameof(output));
			if (ctx == null)
				throw new ArgumentNullException(nameof(ctx));
			Output = output;
			Context = ctx;
		}
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="output">Output</param>
		/// <param name="ctx">Context</param>
		/// <param name="type">Type</param>
		public DecompileTypeMethods(IDecompilerOutput output, DecompilationContext ctx, TypeDef type)
			: base(output, ctx) {
			if (type == null)
				throw new ArgumentNullException(nameof(type));
			Type = type;
			Methods = new HashSet<MethodDef>();
			DecompileHidden = false;
		}
Example #9
0
		public NodeDecompiler(Func<Func<object>, object> execInThread, IDecompilerOutput output, IDecompiler decompiler, DecompilationContext decompilationContext, IDecompileNodeContext decompileNodeContext = null) {
			this.execInThread = execInThread;
			this.output = output;
			this.decompiler = decompiler;
			this.decompilationContext = decompilationContext;
			this.decompileNodeContext = decompileNodeContext;
			this.decompileNodeContext.ContentTypeString = decompiler.ContentTypeString;
		}
		public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) {
			base.WriteShort(output, decompiler, showOffset);
			var documentViewerOutput = output as IDocumentViewerOutput;
			if (documentViewerOutput != null) {
				documentViewerOutput.AddButton(dnSpy_Resources.SaveResourceButton, () => Save());
				documentViewerOutput.WriteLine();
				documentViewerOutput.WriteLine();
			}
		}
Example #11
0
		protected override void Decompile(DecompileContext ctx, IDecompilerOutput output) {
			if (!decompiler.CanDecompile(DecompilationType.PartialType))
				base.Decompile(ctx, output);
			else {
				var opts = new DecompilePartialType(output, decompilationContext, Type);
				foreach (var d in GetDefsToRemove())
					opts.Definitions.Add(d);
				decompiler.Decompile(DecompilationType.PartialType, opts);
			}
		}
		public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset) {
			var documentViewerOutput = output as IDocumentViewerOutput;
			if (documentViewerOutput != null) {
				documentViewerOutput.AddUIElement(() => {
					return new System.Windows.Controls.Image {
						Source = ImageSource,
					};
				});
			}

			base.WriteShort(output, decompiler, showOffset);
		}
Example #13
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();
			}
		}
Example #14
0
		protected override void DecompileFields(IDecompiler decompiler, IDecompilerOutput output) {
			decompiler.WriteCommentLine(output, string.Empty);
			decompiler.WriteCommentBegin(output, true);
			WriteHeader(output);
			decompiler.WriteCommentEnd(output, true);
			output.WriteLine();

			for (int i = 0; i < (int)MetaDataTableVM.Rows; i++) {
				var obj = MetaDataTableVM.Get(i);
				decompiler.WriteCommentBegin(output, true);
				Write(output, obj);
				decompiler.WriteCommentEnd(output, true);
				output.WriteLine();
			}
		}
Example #15
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();
		}
Example #16
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 DocumentTreeNodeData).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);
        }
Example #17
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);
        }
Example #18
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();
            }
        }
Example #19
0
        ReflectionDisassembler CreateReflectionDisassembler(IDecompilerOutput output, DecompilationContext ctx, ModuleDef ownerModule)
        {
            var disOpts = new DisassemblerOptions(ctx.CancellationToken, ownerModule);

            if (langSettings.Settings.ShowILComments)
            {
                disOpts.GetOpCodeDocumentation = ILLanguageHelper.GetOpCodeDocumentation;
            }
            var sb = new StringBuilder();

            if (langSettings.Settings.ShowXmlDocumentation)
            {
                disOpts.GetXmlDocComments = a => GetXmlDocComments(a, sb);
            }
            disOpts.CreateInstructionBytesReader = m => InstructionBytesReader.Create(m, ctx.IsBodyModified != null && ctx.IsBodyModified(m));
            disOpts.ShowTokenAndRvaComments      = langSettings.Settings.ShowTokenAndRvaComments;
            disOpts.ShowILBytes = langSettings.Settings.ShowILBytes;
            disOpts.SortMembers = langSettings.Settings.SortMembers;
            disOpts.ShowPdbInfo = langSettings.Settings.ShowPdbInfo;
            return(new ReflectionDisassembler(output, detectControlStructure, disOpts));
        }
Example #20
0
        public override void WriteShort(IDecompilerOutput output, IDecompiler decompiler, bool showOffset)
        {
            var documentViewerOutput = output as IDocumentViewerOutput;

            if (documentViewerOutput is not null)
            {
                documentViewerOutput.AddUIElement(() => {
                    return(new System.Windows.Controls.Image {
                        Source = imageSource,
                    });
                });
            }

            base.WriteShort(output, decompiler, showOffset);
            if (documentViewerOutput is not null)
            {
                documentViewerOutput.AddButton(dnSpy_Resources.SaveResourceButton, () => Save());
                documentViewerOutput.WriteLine();
                documentViewerOutput.WriteLine();
            }
        }
Example #21
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();
        }
Example #22
0
        public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx)
        {
            ReflectionDisassembler rd = CreateReflectionDisassembler(output, ctx, ev);

            rd.DisassembleEvent(ev, addLineSep: true);
            if (ev.AddMethod != null)
            {
                output.WriteLine();
                rd.DisassembleMethod(ev.AddMethod, true);
            }
            if (ev.RemoveMethod != null)
            {
                output.WriteLine();
                rd.DisassembleMethod(ev.RemoveMethod, true);
            }
            foreach (var m in ev.OtherMethods)
            {
                output.WriteLine();
                rd.DisassembleMethod(m, true);
            }
        }
Example #23
0
        public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx)
        {
            ReflectionDisassembler rd = CreateReflectionDisassembler(output, ctx, property);

            rd.DisassembleProperty(property, addLineSep: true);
            if (property.GetMethod != null)
            {
                output.WriteLine();
                rd.DisassembleMethod(property.GetMethod, true);
            }
            if (property.SetMethod != null)
            {
                output.WriteLine();
                rd.DisassembleMethod(property.SetMethod, true);
            }
            foreach (var m in property.OtherMethods)
            {
                output.WriteLine();
                rd.DisassembleMethod(m, true);
            }
        }
Example #24
0
        public override void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx)
        {
            WriteCommentLineDeclaringType(output, field);
            var state = CreateAstBuilder(ctx, langSettings.Settings, currentType: field.DeclaringType, isSingleMember: true);

            try {
                if (field.IsLiteral)
                {
                    state.AstBuilder.AddField(field);
                }
                else
                {
                    // also decompile ctors so that the field initializer can be shown
                    AddFieldsAndCtors(state.AstBuilder, field.DeclaringType, field.IsStatic);
                }
                RunTransformsAndGenerateCode(ref state, output, ctx, new SelectFieldTransform(field));
            }
            finally {
                state.Dispose();
            }
        }
Example #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();
        }
Example #26
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);
        }
Example #27
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);
        }
Example #28
0
        void RunTransformsAndGenerateCode(ref BuilderState state, IDecompilerOutput output, DecompilationContext ctx, IAstTransform additionalTransform = null)
        {
            var astBuilder = state.AstBuilder;

            astBuilder.RunTransformations(transformAbortCondition);
            if (additionalTransform != null)
            {
                additionalTransform.Run(astBuilder.SyntaxTree);
            }
            CSharpDecompiler.AddXmlDocumentation(ref state, langSettings.Settings, astBuilder);
            var csharpUnit = astBuilder.SyntaxTree;

            csharpUnit.AcceptVisitor(new ICSharpCode.NRefactory.CSharp.InsertParenthesesVisitor()
            {
                InsertParenthesesForReadability = true
            });
            var unit             = csharpUnit.AcceptVisitor(new CSharpToVBConverterVisitor(state.AstBuilder.Context.CurrentModule, new ILSpyEnvironmentProvider(state.State.XmlDoc_StringBuilder)), null);
            var outputFormatter  = new VBTextOutputFormatter(output);
            var formattingPolicy = new VBFormattingOptions();

            unit.AcceptVisitor(new OutputVisitor(outputFormatter, formattingPolicy), null);
        }
Example #29
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();
            }
        }
Example #30
0
        public override void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx)
        {
            WriteCommentLineDeclaringType(output, method);
            var state = CreateAstBuilder(ctx, langSettings.Settings, currentType: method.DeclaringType, isSingleMember: true);

            try {
                if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType)
                {
                    // also fields and other ctors so that the field initializers can be shown as such
                    AddFieldsAndCtors(state.AstBuilder, method.DeclaringType, method.IsStatic);
                    RunTransformsAndGenerateCode(ref state, output, ctx, new SelectCtorTransform(method));
                }
                else
                {
                    state.AstBuilder.AddMethod(method);
                    RunTransformsAndGenerateCode(ref state, output, ctx);
                }
            }
            finally {
                state.Dispose();
            }
        }
Example #31
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);
            }
        }
Example #32
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();
        }
Example #33
0
        public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx)
        {
            StartKeywordBlock(output, ".event", ev);

            if (ev.AddMethod != null)
            {
                StartKeywordBlock(output, ".add", ev.AddMethod);
                EndKeywordBlock(output);
            }

            if (ev.InvokeMethod != null)
            {
                StartKeywordBlock(output, ".invoke", ev.InvokeMethod);
                EndKeywordBlock(output);
            }

            if (ev.RemoveMethod != null)
            {
                StartKeywordBlock(output, ".remove", ev.RemoveMethod);
                EndKeywordBlock(output);
            }

            EndKeywordBlock(output);
        }
Example #34
0
        public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx)
        {
            StartKeywordBlock(output, ".property", property);

            foreach (var getter in property.GetMethods)
            {
                StartKeywordBlock(output, ".get", getter);
                EndKeywordBlock(output);
            }

            foreach (var setter in property.SetMethods)
            {
                StartKeywordBlock(output, ".set", setter);
                EndKeywordBlock(output);
            }

            foreach (var other in property.OtherMethods)
            {
                StartKeywordBlock(output, ".other", other);
                EndKeywordBlock(output);
            }

            EndKeywordBlock(output);
        }
Example #35
0
        void Write(IDecompilerOutput output)
        {
#if NETFRAMEWORK
            const string frameworkName = ".NET Framework";
#elif NET
            const string frameworkName = ".NET";
#else
#error Unknown target framework
#endif
            output.WriteLine($"{Constants.DnSpy} {appWindow.AssemblyInformationalVersion} ({frameworkName})", BoxedTextColor.Text);
            output.WriteLine();
            output.WriteLine(dnSpy_Resources.AboutScreen_LicenseInfo, BoxedTextColor.Text);
            output.WriteLine();
            output.WriteLine(dnSpy_Resources.AboutScreen_LoadedFiles, BoxedTextColor.Text);
            foreach (var info in GetInfos())
            {
                output.WriteLine();
                WriteShortInfo(output, info.NameAndVersion);
                WriteShortInfo(output, info.Copyright);
                WriteShortInfo(output, info.ShortDescription);
            }
            output.WriteLine();
            WriteResourceFile(output, "dnSpy.LicenseInfo.CREDITS.txt");
        }
Example #36
0
        public static bool Write(IDecompilerOutput output, IMemberRef member)
        {
            if (member is IMethod method && method.IsMethod)
            {
                method.WriteMethodTo(output);
                return(true);
            }

            if (member is IField field && field.IsField)
            {
                field.WriteFieldTo(output);
                return(true);
            }

            if (member is PropertyDef prop)
            {
                var dis = new ReflectionDisassembler(output, false, new DisassemblerOptions(0, new System.Threading.CancellationToken(), null));
                dis.DisassembleProperty(prop, false);
                return(true);
            }

            if (member is EventDef evt)
            {
                var dis = new ReflectionDisassembler(output, false, new DisassemblerOptions(0, new System.Threading.CancellationToken(), null));
                dis.DisassembleEvent(evt, false);
                return(true);
            }

            if (member is ITypeDefOrRef type)
            {
                type.WriteTo(output, ILNameSyntax.TypeName);
                return(true);
            }

            return(false);
        }
Example #37
0
        public override void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx)
        {
            var propInfo = StartKeywordBlock(output, ".property", property);

            foreach (var getter in property.GetMethods)
            {
                var info = StartKeywordBlock(output, ".get", getter);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            foreach (var setter in property.SetMethods)
            {
                var info = StartKeywordBlock(output, ".set", setter);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            foreach (var other in property.OtherMethods)
            {
                var info = StartKeywordBlock(output, ".other", other);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            EndKeywordBlock(output, propInfo, CodeBracesRangeFlags.PropertyBraces, addLineSeparator: true);
        }
Example #38
0
        public override void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx)
        {
            var eventInfo = StartKeywordBlock(output, ".event", ev);

            if (ev.AddMethod != null)
            {
                var info = StartKeywordBlock(output, ".add", ev.AddMethod);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            if (ev.InvokeMethod != null)
            {
                var info = StartKeywordBlock(output, ".invoke", ev.InvokeMethod);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            if (ev.RemoveMethod != null)
            {
                var info = StartKeywordBlock(output, ".remove", ev.RemoveMethod);
                EndKeywordBlock(output, info, CodeBracesRangeFlags.AccessorBraces);
            }

            EndKeywordBlock(output, eventInfo, CodeBracesRangeFlags.EventBraces, addLineSeparator: true);
        }
Example #39
0
 void ISimpleILPrinter.Write(IDecompilerOutput output, TypeSig?type) => type.WriteTo(output);
Example #40
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();
		}
Example #41
0
 public void Write(IDecompilerOutput output, MethodSig sig)
 {
     Write(output, sig);
 }
Example #42
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();
		}
Example #43
0
		public virtual void Decompile(FieldDef field, IDecompilerOutput output, DecompilationContext ctx) =>
			this.WriteCommentLine(output, TypeToString(field.DeclaringType, true) + "." + field.Name);
Example #44
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));
		}
Example #45
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));
		}
Example #46
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));
		}
Example #47
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();
		}
Example #48
0
		public virtual void Decompile(MethodDef method, IDecompilerOutput output, DecompilationContext ctx) =>
			this.WriteCommentLine(output, TypeToString(method.DeclaringType, true) + "." + method.Name);
Example #49
0
		public virtual void Decompile(TypeDef type, IDecompilerOutput output, DecompilationContext ctx) =>
			this.WriteCommentLine(output, TypeToString(type, true));
Example #50
0
		public virtual void Decompile(EventDef ev, IDecompilerOutput output, DecompilationContext ctx) =>
			this.WriteCommentLine(output, TypeToString(ev.DeclaringType, true) + "." + ev.Name);
Example #51
0
 bool ISimpleILPrinter.Write(IDecompilerOutput output, IMemberRef?member) => ILDecompilerUtils.Write(output, member);
Example #52
0
		public virtual void WriteCommentEnd(IDecompilerOutput output, bool addSpace) { }
Example #53
0
 public override void WriteCommentEnd(IDecompilerOutput output, bool addSpace)
 {
 }
Example #54
0
		public virtual void Decompile(PropertyDef property, IDecompilerOutput output, DecompilationContext ctx) =>
			this.WriteCommentLine(output, TypeToString(property.DeclaringType, true) + "." + property.Name);
Example #55
0
 void ISimpleILPrinter.Write(IDecompilerOutput output, MethodSig?sig) => output.Write(sig);
Example #56
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();
			}
		}
Example #57
0
 public void Write(IDecompilerOutput output, TypeSig type)
 {
     Write(output, type);
 }
Example #58
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();
		}
Example #59
0
 void Write(IDecompilerOutput output, object value)
 {
     output.Write(string.Format("Missing ISimpleILPrinter: {0}", value), BoxedTextColor.Text);
 }
Example #60
0
		public virtual void WriteCommentBegin(IDecompilerOutput output, bool addSpace) {
			if (addSpace)
				output.Write("// ", BoxedTextColor.Comment);
			else
				output.Write("//", BoxedTextColor.Comment);
		}