Exemple #1
0
        void WriteAttributeId(BamlContext ctx, ushort id)
        {
            string declType;
            string name;

            if (id > 0x7fff)
            {
                var knownMember = ctx.KnownThings.Members((KnownMembers)(-id));
                declType = knownMember.DeclaringType.FullName;
                name     = knownMember.Name;
            }
            else if (ctx.AttributeIdMap.ContainsKey(id))
            {
                var attrInfo = ctx.AttributeIdMap[id];
                if (attrInfo.OwnerTypeId > 0x7fff)
                {
                    declType = ctx.KnownThings.Types((KnownTypes)(-attrInfo.OwnerTypeId)).FullName;
                }
                else if (ctx.TypeIdMap.ContainsKey(attrInfo.OwnerTypeId))
                {
                    declType = ctx.TypeIdMap[attrInfo.OwnerTypeId].TypeFullName;
                }
                else
                {
                    declType = string.Format("(0x{0:x4})", attrInfo.OwnerTypeId);
                }
                name = attrInfo.Name;
            }
            else
            {
                declType = name = null;
            }

            string reference = null;

            if (declType != null && name != null)
            {
                reference = string.Format("{0}::{1}", IdentifierEscaper.Escape(declType), IdentifierEscaper.Escape(name));
            }
            output.WriteReference(string.Format("0x{0:x4}", id), reference, TextTokenType.Number, true);
        }
Exemple #2
0
        void WriteDefinition(string value, string def = null)
        {
            string str = string.Format("\"{0}\"", TextWriterTokenWriter.ConvertString(value));

            output.WriteDefinition(str, def ?? IdentifierEscaper.Escape(value), TextTokenType.String, true);
        }
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, IdentifierEscaper.Escape(r.Name));
 }
Exemple #4
0
        public void Write()
        {
            project.OnWrite();
            var settings = new XmlWriterSettings {
                Encoding = Encoding.UTF8,
                Indent   = true,
            };

            if (projectVersion == ProjectVersion.VS2005)
            {
                settings.OmitXmlDeclaration = true;
            }
            using (var writer = XmlWriter.Create(project.Filename, settings)) {
                project.Platform = GetPlatformString();

                writer.WriteStartDocument();
                writer.WriteStartElement("Project", "http://schemas.microsoft.com/developer/msbuild/2003");
                var toolsVersion = GetToolsVersion();
                if (!(toolsVersion is null))
                {
                    writer.WriteAttributeString("ToolsVersion", toolsVersion);
                }
                if (projectVersion <= ProjectVersion.VS2015)
                {
                    writer.WriteAttributeString("DefaultTargets", "Build");
                }
                if (projectVersion >= ProjectVersion.VS2012)
                {
                    writer.WriteStartElement("Import");
                    writer.WriteAttributeString("Project", @"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
                    writer.WriteAttributeString("Condition", @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')");
                    writer.WriteEndElement();
                }

                // Default property group
                writer.WriteStartElement("PropertyGroup");

                writer.WriteStartElement("Configuration");
                writer.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
                writer.WriteString("Debug");
                writer.WriteEndElement();

                writer.WriteStartElement("Platform");
                writer.WriteAttributeString("Condition", " '$(Platform)' == '' ");
                writer.WriteString(project.Platform);
                writer.WriteEndElement();

                writer.WriteElementString("ProjectGuid", project.Guid.ToString("B").ToUpperInvariant());
                writer.WriteElementString("OutputType", GetOutputType());
                var appDesignFolder = GetAppDesignerFolder();
                if (!(appDesignFolder is null))
                {
                    writer.WriteElementString("AppDesignerFolder", appDesignFolder);
                }
                writer.WriteElementString("RootNamespace", GetRootNamespace());
                var asmName = GetAssemblyName();
                if (!string.IsNullOrEmpty(asmName))
                {
                    writer.WriteElementString("AssemblyName", GetAssemblyName());
                }
                var fwkInfo = TargetFrameworkInfo.Create(project.Module);
                if (projectVersion > ProjectVersion.VS2005 || !fwkInfo.IsDotNetFramework || fwkInfo.Version != "2.0")
                {
                    writer.WriteElementString("TargetFrameworkVersion", "v" + fwkInfo.Version);
                }
                if (!string.IsNullOrEmpty(fwkInfo.Profile))
                {
                    writer.WriteElementString("TargetFrameworkProfile", fwkInfo.Profile);
                }
                if (!fwkInfo.IsDotNetFramework)
                {
                    writer.WriteElementString("TargetFrameworkIdentifier", fwkInfo.Framework);
                }
                writer.WriteElementString("FileAlignment", GetFileAlignment());
                if (project.ProjectTypeGuids.Count != 0)
                {
                    var text = string.Join(";", project.ProjectTypeGuids.Select(a => a.ToString("B").ToUpperInvariant()).ToArray());
                    writer.WriteElementString("ProjectTypeGuids", text);
                }
                //TODO: VB includes a "MyType"
                if (!(project.ApplicationManifest is null))
                {
                    writer.WriteElementString("ApplicationManifest", GetRelativePath(project.ApplicationManifest.Filename));
                }
                if (!(project.ApplicationIcon is null))
                {
                    writer.WriteElementString("ApplicationIcon", GetRelativePath(project.ApplicationIcon.Filename));
                }
                if (!(project.StartupObject is null))
                {
                    writer.WriteElementString("StartupObject", project.StartupObject);
                }
                writer.WriteEndElement();

                // Debug property group
                var noWarnList = GetNoWarnList();
                writer.WriteStartElement("PropertyGroup");
                writer.WriteAttributeString("Condition", $" '$(Configuration)|$(Platform)' == 'Debug|{project.Platform}' ");
                writer.WriteElementString("PlatformTarget", project.Platform);
                writer.WriteElementString("DebugSymbols", "true");
                writer.WriteElementString("DebugType", "full");
                writer.WriteElementString("Optimize", "false");
                writer.WriteElementString("OutputPath", @"bin\Debug\");
                writer.WriteElementString("DefineConstants", "DEBUG;TRACE");
                writer.WriteElementString("ErrorReport", "prompt");
                writer.WriteElementString("WarningLevel", "4");
                if (project.Options.DontReferenceStdLib)
                {
                    writer.WriteElementString("NoStdLib", "true");
                }
                if (project.AllowUnsafeBlocks)
                {
                    writer.WriteElementString("AllowUnsafeBlocks", "true");
                }
                if (!(noWarnList is null))
                {
                    writer.WriteElementString("NoWarn", noWarnList);
                }
                writer.WriteEndElement();

                // Release property group
                writer.WriteStartElement("PropertyGroup");
                writer.WriteAttributeString("Condition", $" '$(Configuration)|$(Platform)' == 'Release|{project.Platform}' ");
                writer.WriteElementString("PlatformTarget", project.Platform);
                writer.WriteElementString("DebugType", "pdbonly");
                writer.WriteElementString("Optimize", "true");
                writer.WriteElementString("OutputPath", @"bin\Release\");
                writer.WriteElementString("DefineConstants", "TRACE");
                writer.WriteElementString("ErrorReport", "prompt");
                writer.WriteElementString("WarningLevel", "4");
                if (project.Options.DontReferenceStdLib)
                {
                    writer.WriteElementString("NoStdLib", "true");
                }
                if (project.AllowUnsafeBlocks)
                {
                    writer.WriteElementString("AllowUnsafeBlocks", "true");
                }
                if (!(noWarnList is null))
                {
                    writer.WriteElementString("NoWarn", noWarnList);
                }
                writer.WriteEndElement();

                // GAC references
                var gacRefs = project.Module.GetAssemblyRefs().Where(a => a.Name != "mscorlib").OrderBy(a => a.Name.String, StringComparer.OrdinalIgnoreCase).ToArray();
                if (gacRefs.Length > 0 || project.ExtraAssemblyReferences.Count > 0)
                {
                    writer.WriteStartElement("ItemGroup");
                    var hash = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    foreach (var r in gacRefs)
                    {
                        var asm = project.Module.Context.AssemblyResolver.Resolve(r, project.Module);
                        if (!(asm is null) && ExistsInProject(asm.ManifestModule.Location))
                        {
                            continue;
                        }
                        hash.Add(r.Name);
                        writer.WriteStartElement("Reference");
                        writer.WriteAttributeString("Include", IdentifierEscaper.Escape(r.Name));
                        var hintPath = GetHintPath(asm);
                        if (!(hintPath is null))
                        {
                            writer.WriteElementString("HintPath", hintPath);
                        }
                        writer.WriteEndElement();
                    }
                    foreach (var r in project.ExtraAssemblyReferences)
                    {
                        if (hash.Contains(r) || AssemblyExistsInProject(r))
                        {
                            continue;
                        }
                        hash.Add(r);
                        writer.WriteStartElement("Reference");
                        writer.WriteAttributeString("Include", IdentifierEscaper.Escape(r));
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }

                writer.WriteStartElement("ItemGroup");
                writer.WriteStartElement("AppDesigner");
                writer.WriteAttributeString("Include", project.PropertiesFolder + "\\");
                writer.WriteEndElement();
                writer.WriteEndElement();

                Write(writer, BuildAction.Compile);
                Write(writer, BuildAction.EmbeddedResource);

                // Project references
                var projRefs = project.Module.GetAssemblyRefs().
                               Select(a => project.Module.Context.AssemblyResolver.Resolve(a, project.Module)).
                               Select(a => a is null ? null : FindOtherProject(a.ManifestModule.Location)).
                               OfType <Project>().OrderBy(a => a.Filename, StringComparer.OrdinalIgnoreCase).ToArray();
                if (projRefs.Length > 0)
                {
                    writer.WriteStartElement("ItemGroup");
                    foreach (var otherProj in projRefs)
                    {
                        writer.WriteStartElement("ProjectReference");
                        writer.WriteAttributeString("Include", GetRelativePath(otherProj.Filename));
                        writer.WriteStartElement("Project");
                        var guidString = otherProj.Guid.ToString("B");
                        if (projectVersion < ProjectVersion.VS2012)
                        {
                            guidString = guidString.ToUpperInvariant();
                        }
                        writer.WriteString(guidString);
                        writer.WriteEndElement();
                        writer.WriteStartElement("Name");
                        writer.WriteString(IdentifierEscaper.Escape(otherProj.Module.Assembly is null ? string.Empty : otherProj.Module.Assembly.Name.String));
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }

                Write(writer, BuildAction.None);
                Write(writer, BuildAction.ApplicationDefinition);
                Write(writer, BuildAction.Page);
                Write(writer, BuildAction.Resource);
                Write(writer, BuildAction.SplashScreen);

                writer.WriteStartElement("Import");
                writer.WriteAttributeString("Project", GetLanguageTargets());
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Exemple #5
0
        void CreateUI(ITextOutput output, object o, bool includeNamespace)
        {
            var ns = o as NamespaceSearchResult;

            if (ns != null)
            {
                NamespaceTreeNode.Write(output, ns.Namespace);
                return;
            }

            var td = o as TypeDef;

            if (td != null)
            {
                Debug.Assert(Language != null);
                Language.TypeToString(output, td, includeNamespace);
                return;
            }

            var md = o as MethodDef;

            if (md != null)
            {
                output.Write(IdentifierEscaper.Escape(md.Name), TextTokenHelper.GetTextTokenType(md));
                return;
            }

            var fd = o as FieldDef;

            if (fd != null)
            {
                output.Write(IdentifierEscaper.Escape(fd.Name), TextTokenHelper.GetTextTokenType(fd));
                return;
            }

            var pd = o as PropertyDef;

            if (pd != null)
            {
                output.Write(IdentifierEscaper.Escape(pd.Name), TextTokenHelper.GetTextTokenType(pd));
                return;
            }

            var ed = o as EventDef;

            if (ed != null)
            {
                output.Write(IdentifierEscaper.Escape(ed.Name), TextTokenHelper.GetTextTokenType(ed));
                return;
            }

            var asm = o as AssemblyDef;

            if (asm != null)
            {
                Write(output, asm);
                return;
            }

            var mod = o as ModuleDef;

            if (mod != null)
            {
                output.Write(mod.FullName, TextTokenType.Module);
                return;
            }

            var asmRef = o as AssemblyRef;

            if (asmRef != null)
            {
                Write(output, asmRef);
                return;
            }

            var modRef = o as ModuleRef;

            if (modRef != null)
            {
                output.Write(modRef.FullName, TextTokenType.Module);
                return;
            }

            // non-.NET file
            var loadedAsm = o as LoadedAssembly;

            if (loadedAsm != null)
            {
                output.Write(loadedAsm.ShortName, TextTokenType.Text);
                return;
            }

            var s = o as string;

            if (s != null)
            {
                output.Write(s, TextTokenType.Text);
                return;
            }

            Debug.Assert(s == null);
        }
Exemple #6
0
        void CreateUI(ITextColorWriter output, object o, bool includeNamespace)
        {
            var ns = o as NamespaceSearchResult;

            if (ns != null)
            {
                output.WriteNamespace(ns.Namespace);
                return;
            }

            var td = o as TypeDef;

            if (td != null)
            {
                Debug.Assert(Context.Decompiler != null);
                Context.Decompiler.WriteType(output, td, includeNamespace);
                return;
            }

            var md = o as MethodDef;

            if (md != null)
            {
                output.Write(TextColorHelper.GetColor(md), IdentifierEscaper.Escape(md.Name));
                return;
            }

            var fd = o as FieldDef;

            if (fd != null)
            {
                output.Write(TextColorHelper.GetColor(fd), IdentifierEscaper.Escape(fd.Name));
                return;
            }

            var pd = o as PropertyDef;

            if (pd != null)
            {
                output.Write(TextColorHelper.GetColor(pd), IdentifierEscaper.Escape(pd.Name));
                return;
            }

            var ed = o as EventDef;

            if (ed != null)
            {
                output.Write(TextColorHelper.GetColor(ed), IdentifierEscaper.Escape(ed.Name));
                return;
            }

            var asm = o as AssemblyDef;

            if (asm != null)
            {
                output.Write(asm);
                return;
            }

            var mod = o as ModuleDef;

            if (mod != null)
            {
                output.WriteModule(mod.FullName);
                return;
            }

            var asmRef = o as AssemblyRef;

            if (asmRef != null)
            {
                output.Write(asmRef);
                return;
            }

            var modRef = o as ModuleRef;

            if (modRef != null)
            {
                output.WriteModule(modRef.FullName);
                return;
            }

            var paramDef = o as ParamDef;

            if (paramDef != null)
            {
                output.Write(BoxedTextColor.Parameter, IdentifierEscaper.Escape(paramDef.Name));
                return;
            }

            // non-.NET file
            var document = o as IDsDocument;

            if (document != null)
            {
                output.Write(BoxedTextColor.Text, document.GetShortName());
                return;
            }

            var resNode = o as ResourceNode;

            if (resNode != null)
            {
                output.WriteFilename(resNode.Name);
                return;
            }

            var resElNode = o as ResourceElementNode;

            if (resElNode != null)
            {
                output.WriteFilename(resElNode.Name);
                return;
            }

            var em = o as ErrorMessage;

            if (em != null)
            {
                output.Write(em.Color, em.Text);
                return;
            }

            Debug.Assert(o == null);
        }
Exemple #7
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
            };

            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);
        }
Exemple #8
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;
                    }
                }
            }
        }
Exemple #9
0
        void CreateUI(ITextColorWriter output, object o, bool includeNamespace)
        {
            if (o is NamespaceSearchResult ns)
            {
                output.WriteNamespace(ns.Namespace);
                return;
            }

            if (o is TypeDef td)
            {
                Debug.Assert(Context.Decompiler != null);
                Context.Decompiler.WriteType(output, td, includeNamespace);
                return;
            }

            if (o is MethodDef md)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(md), IdentifierEscaper.Escape(md.Name));
                return;
            }

            if (o is FieldDef fd)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(fd), IdentifierEscaper.Escape(fd.Name));
                return;
            }

            if (o is PropertyDef pd)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(pd), IdentifierEscaper.Escape(pd.Name));
                return;
            }

            if (o is EventDef ed)
            {
                output.Write(Context.Decompiler.MetadataTextColorProvider.GetColor(ed), IdentifierEscaper.Escape(ed.Name));
                return;
            }

            if (o is AssemblyDef asm)
            {
                output.Write(asm);
                return;
            }

            if (o is ModuleDef mod)
            {
                output.WriteModule(mod.FullName);
                return;
            }

            if (o is AssemblyRef asmRef)
            {
                output.Write(asmRef);
                return;
            }

            if (o is ModuleRef modRef)
            {
                output.WriteModule(modRef.FullName);
                return;
            }

            if (o is ParamDef paramDef)
            {
                output.Write(BoxedTextColor.Parameter, IdentifierEscaper.Escape(paramDef.Name));
                return;
            }

            // non-.NET file
            if (o is IDsDocument document)
            {
                output.Write(BoxedTextColor.Text, document.GetShortName());
                return;
            }

            if (o is ResourceNode resNode)
            {
                output.WriteFilename(resNode.Name);
                return;
            }

            if (o is ResourceElementNode resElNode)
            {
                output.WriteFilename(resElNode.Name);
                return;
            }

            if (o is ErrorMessage em)
            {
                output.Write(em.Color, em.Text);
                return;
            }

            Debug.Assert(o == null);
        }