Esempio n. 1
0
        public override void DecompileAssembly(DnSpyFileList dnSpyFileList, DnSpyFile file, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
        {
            bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
            bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;

            output.WriteLine("// " + file.Filename, TextTokenType.Comment);
            if (decompileMod || decompileAsm)
            {
                PrintEntryPoint(file, output);
            }
            output.WriteLine();

            ReflectionDisassembler rd = CreateReflectionDisassembler(output, options, file.ModuleDef);

            if (decompileMod && options.FullDecompilation)
            {
                rd.WriteAssemblyReferences(file.ModuleDef);
            }
            if (decompileAsm && file.AssemblyDef != null)
            {
                rd.WriteAssemblyHeader(file.AssemblyDef);
            }
            if (decompileMod)
            {
                output.WriteLine();
                rd.WriteModuleHeader(file.ModuleDef);
                if (options.FullDecompilation)
                {
                    output.WriteLine();
                    output.WriteLine();
                    rd.WriteModuleContents(file.ModuleDef);
                }
            }
        }
Esempio n. 2
0
 public DerivedTypesTreeNode(DnSpyFileList list, TypeDef type)
 {
     this.list        = list;
     this.type        = type;
     this.LazyLoading = true;
     this.threading   = new ThreadingSupport();
 }
Esempio n. 3
0
        DnSpyFileList DoLoadList(DNSpySettings spySettings, string listName)
        {
            var doc = GetFileListsElement(spySettings);

            if (listName != null)
            {
                foreach (var listElem in doc.Elements(LIST_SECTION_NAME))
                {
                    if (SessionSettings.Unescape((string)listElem.Attribute("name")) == listName)
                    {
                        return(Initialize(Create(listElem)));
                    }
                }
            }
            XElement      firstList = doc.Elements(LIST_SECTION_NAME).FirstOrDefault();
            DnSpyFileList list;

            if (firstList != null)
            {
                list = Create(firstList);
            }
            else
            {
                list = new DnSpyFileList(options, listName ?? DefaultListName);
            }
            return(Initialize(list));
        }
Esempio n. 4
0
 protected override void LoadChildren()
 {
     if (Parent is AssemblyTreeNode || dnSpyFile.AssemblyDef == null)
     {
         LoadModuleChildren(dnSpyFile.PEImage, dnSpyFile.ModuleDef);
     }
     else
     {
         // Add all modules in this assembly
         foreach (var mod in dnSpyFile.AssemblyDef.Modules)
         {
             if (mod == dnSpyFile.ModuleDef)
             {
                 this.Children.Add(new AssemblyTreeNode(dnSpyFile));
             }
             else
             {
                 var file = dnSpyFile.CreateDnSpyFile(mod);
                 if (file == null)
                 {
                     file = DnSpyFileList.CreateDnSpyFile(mod);
                 }
                 file.IsAutoLoaded = dnSpyFile.IsAutoLoaded;
                 this.Children.Add(new AssemblyTreeNode(file));
             }
         }
     }
 }
Esempio n. 5
0
        public MemberPickerVM(IDnSpyFileListOptions options, Language language, ITreeViewNodeFilter filter, IEnumerable <DnSpyFile> assemblies)
        {
            this.Language   = language;
            this.filter     = filter;
            this.origFilter = filter;

            dnSpyFileList = new DnSpyFileList(options, "Member Picker List");
            foreach (var file in assemblies)
            {
                dnSpyFileList.ForceAddFileToList(file, true, false, -1, false);
            }

            this.dnSpyFileListTreeNode             = new DnSpyFileListTreeNode(dnSpyFileList);
            this.dnSpyFileListTreeNode.DisableDrop = true;
            if (dnSpyFileListTreeNode.Children.Count > 0)
            {
                SelectedItem = dnSpyFileListTreeNode.Children[0];
            }

            // Make sure we don't hook this event before the assembly list node because we depend
            // on the new asm node being present when we restart the search.
            dnSpyFileList.CollectionChanged += (s, e) => RestartSearch();

            CreateNewFilterSettings();
        }
Esempio n. 6
0
 static XElement SaveAsXml(DnSpyFileList list)
 {
     return(new XElement(
                LIST_SECTION_NAME,
                new XAttribute("name", SessionSettings.Escape(list.Name)),
                list.GetDnSpyFiles().Where(file => !file.IsAutoLoaded && file.CanBeSavedToSettingsFile && !string.IsNullOrWhiteSpace(file.Filename)).Select(asm => new XElement(FILE_SECTION_NAME, SessionSettings.Escape(asm.Filename)))
                ));
 }
Esempio n. 7
0
        static void DumpNetModule(ProjectInfo info, List <ProjectInfo> projectFiles)
        {
            var fileName = info.AssemblyFileName;

            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception(".NET module filename is empty or null");
            }

            var listOpts = new DnSpyFileListOptionsImpl();

            listOpts.UseGAC            = !noGac;
            listOpts.UseDebugSymbols   = true;
            listOpts.UseMemoryMappedIO = true;
            var fileList = new DnSpyFileList(listOpts, string.Empty);

            fileList.AssemblyResolver.AddSearchPath(Path.GetDirectoryName(fileName));
            foreach (var path in asmPaths)
            {
                fileList.AssemblyResolver.AddSearchPath(path);
            }
            var file = fileList.OpenFile(fileName);
            var opts = new DecompilationOptions {
                FullDecompilation = true,
                CancellationToken = new CancellationToken(),
            };

            TextWriter writer = null;

            try {
                var lang = GetLanguage();

                if (useStdout)
                {
                    writer = System.Console.Out;
                }
                else
                {
                    var baseDir = GetProjectDir(lang, fileName);
                    Directory.CreateDirectory(baseDir);
                    writer = new StreamWriter(info.ProjectFileName, false, Encoding.UTF8);
                    opts.SaveAsProjectDirectory             = baseDir;
                    opts.DontReferenceStdLib                = noCorlibRef;
                    opts.ProjectFiles                       = projectFiles;
                    opts.ProjectGuid                        = info.ProjectGuid;
                    opts.DontShowCreateMethodBodyExceptions = dontMaskErr;
                    Console.WriteLine("Saving {0} to {1}", fileName, baseDir);
                }

                lang.DecompileAssembly(fileList, file, new PlainTextOutput(writer), opts);
            }
            finally {
                if (!useStdout && writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Esempio n. 8
0
 public DnSpyFileListTreeNode(DnSpyFileList dnspyFileList)
 {
     if (dnspyFileList == null)
     {
         throw new ArgumentNullException("dnspyFileList");
     }
     this.dnspyFileList = dnspyFileList;
     BindToObservableCollection();
 }
Esempio n. 9
0
        /// <summary>
        /// Loads an assembly list from the ILSpySettings.
        /// If no list with the specified name is found, the default list is loaded instead.
        /// </summary>
        public DnSpyFileList LoadList(DNSpySettings spySettings, string listName)
        {
            DnSpyFileList list = DoLoadList(spySettings, listName);

            if (!FileLists.Contains(list.Name))
            {
                FileLists.Add(list.Name);
            }
            return(list);
        }
Esempio n. 10
0
        private void AddToList(DnSpyFileList list, string FullName)
        {
            AssemblyNameInfo reference = new AssemblyNameInfo(FullName);
            string           file      = GacInterop.FindAssemblyInNetGac(reference);

            if (file != null)
            {
                list.OpenFile(file);
            }
        }
Esempio n. 11
0
 public bool CreateList(DnSpyFileList list)
 {
     if (!FileLists.Contains(list.Name))
     {
         FileLists.Add(list.Name);
         Initialize(list);
         SaveList(list);
         return(true);
     }
     return(false);
 }
Esempio n. 12
0
        public override void DecompileAssembly(DnSpyFileList dnSpyFileList, DnSpyFile file, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
        {
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                var files = WriteCodeFilesInProject(dnSpyFileList, file.ModuleDef, options, directories).ToList();
                files.AddRange(WriteResourceFilesInProject(file, options, directories));
                WriteProjectFile(dnSpyFileList, new TextOutputWriter(output), files, file, options);
            }
            else
            {
                bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
                bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;
                base.DecompileAssembly(dnSpyFileList, file, output, options, flags);
                output.WriteLine();
                ModuleDef mainModule = file.ModuleDef;
                if (decompileMod && mainModule.Types.Count > 0)
                {
                    output.Write("' Global type: ", TextTokenType.Comment);
                    output.WriteReference(IdentifierEscaper.Escape(mainModule.GlobalType.FullName), mainModule.GlobalType, TextTokenType.Comment);
                    output.WriteLine();
                }
                if (decompileMod || decompileAsm)
                {
                    PrintEntryPoint(file, output);
                }
                if (decompileMod)
                {
                    WriteCommentLine(output, "Architecture: " + CSharpLanguage.GetPlatformDisplayName(mainModule));
                    if (!mainModule.IsILOnly)
                    {
                        WriteCommentLine(output, "This assembly contains unmanaged code.");
                    }
                    string runtimeName = ICSharpCode.ILSpy.CSharpLanguage.GetRuntimeDisplayName(mainModule);
                    if (runtimeName != null)
                    {
                        WriteCommentLine(output, "Runtime: " + runtimeName);
                    }
                }
                if (decompileMod || decompileAsm)
                {
                    output.WriteLine();
                }

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                using (options.FullDecompilation ? null : dnSpyFileList.DisableAssemblyLoad()) {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: file.ModuleDef);
                    codeDomBuilder.AddAssembly(file.ModuleDef, !options.FullDecompilation, decompileAsm, decompileMod);
                    RunTransformsAndGenerateCode(codeDomBuilder, output, options, file.ModuleDef);
                }
            }
        }
Esempio n. 13
0
        DnSpyFile LoadDynamic(DnModule dnModule, bool canLoadDynFile)
        {
            var file = FindDynamic(dnModule);

            if (file != null)
            {
                return(file);
            }

            if (DebugManager.Instance.ProcessState != DebuggerProcessState.Stopped)
            {
                return(null);
            }
            if (!canLoadDynFile)
            {
                return(null);
            }

            var manifestDnModule = dnModule.Assembly.Modules[0];
            var manifestKey      = CorModuleDefFile.CreateKey(manifestDnModule);
            var manMod           = FindAssemblyByKey(manifestKey);

            Debug.Assert(manMod == null);
            if (manMod != null)
            {
                return(null);
            }

            manMod = FindDynamic(manifestDnModule);
            Debug.Assert(manMod == null);
            if (manMod != null)
            {
                return(null);
            }

            var modules = manifestDnModule.Assembly.Modules;
            var dict    = new Dictionary <ModuleDef, CorModuleDefFile>(modules.Length);

            foreach (var module in modules)
            {
                UpdateResolver(module.GetOrCreateCorModuleDef());
                dict.Add(module.GetOrCreateCorModuleDef(), new CorModuleDefFile(dict, module, UseDebugSymbols));
            }
            Initialize(dict.Select(a => a.Value.DnModule.CorModuleDef));

            manMod = dict[manifestDnModule.CorModuleDef];
            DnSpyFileList.AddFile(manMod, true, true, false);

            return(dict[dnModule.CorModuleDef]);
        }
Esempio n. 14
0
 internal void RefreshSave(DnSpyFileList list)
 {
     if (!list.IsDirty)
     {
         list.IsDirty = true;
         App.Current.Dispatcher.BeginInvoke(
             DispatcherPriority.Background,
             new Action(
                 delegate {
             list.IsDirty = false;
             SaveList(list);
         })
             );
     }
 }
Esempio n. 15
0
        DnSpyFileList Create(XElement listElement)
        {
            var name  = SessionSettings.Unescape((string)listElement.Attribute("name"));
            var list  = new DnSpyFileList(options, name);
            var elems = listElement.Elements(FILE_SECTION_NAME).ToList();

            elems.AddRange(listElement.Elements(FILE_SECTION_NAME_OLD));
            foreach (var asm in elems)
            {
                try {
                    list.OpenFile(SessionSettings.Unescape((string)asm));
                }
                catch {
                }
            }
            list.IsDirty = false;
            return(list);
        }
Esempio n. 16
0
        IEnumerable <Tuple <string, string> > WriteAssemblyInfo(DnSpyFileList dnSpyFileList, ModuleDef module, DecompilationOptions options, HashSet <string> directories)
        {
            // don't automatically load additional assemblies when an assembly node is selected in the tree view
            using (dnSpyFileList.DisableAssemblyLoad()) {
                AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
                codeDomBuilder.AddAssembly(module, true, true, true);
                codeDomBuilder.RunTransformations(transformAbortCondition);

                string prop = "Properties";
                if (directories.Add("Properties"))
                {
                    Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, prop));
                }
                string assemblyInfo = Path.Combine(prop, "AssemblyInfo" + this.FileExtension);
                using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, assemblyInfo)))
                    codeDomBuilder.GenerateCode(new PlainTextOutput(w));
                return(new Tuple <string, string>[] { Tuple.Create("Compile", assemblyInfo) });
            }
        }
Esempio n. 17
0
 void Save(DnSpyFileList list)
 {
     if (!list.IsDirty)
     {
         list.IsDirty = true;
         App.Current.Dispatcher.BeginInvoke(
             DispatcherPriority.Background,
             new Action(
                 delegate {
             bool callGc = true;                            //TODO:
             if (callGc)
             {
                 GC.Collect();
                 GC.WaitForPendingFinalizers();
             }
             list.IsDirty = false;
             SaveList(list);
         })
             );
     }
 }
Esempio n. 18
0
        IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(DnSpyFileList dnSpyFileList, ModuleDef module, DecompilationOptions options, HashSet <string> directories)
        {
            var files = module.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
                delegate(TypeDef type) {
                string file = TextView.DecompilerTextView.CleanUpName(type.Name) + this.FileExtension;
                if (string.IsNullOrEmpty(type.Namespace))
                {
                    return(file);
                }
                else
                {
                    string dir = TextView.DecompilerTextView.CleanUpName(type.Namespace);
                    if (directories.Add(dir))
                    {
                        Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dir));
                    }
                    return(Path.Combine(dir, file));
                }
            }, StringComparer.OrdinalIgnoreCase).ToList();

            AstMethodBodyBuilder.ClearUnhandledOpcodes();
            Parallel.ForEach(
                files,
                new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount
            },
                delegate(IGrouping <string, TypeDef> file) {
                using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
                    foreach (TypeDef type in file)
                    {
                        codeDomBuilder.AddType(type);
                    }
                    RunTransformsAndGenerateCode(codeDomBuilder, new PlainTextOutput(w), options, module);
                }
            });
            AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes();
            return(files.Select(f => Tuple.Create("Compile", f.Key)).Concat(WriteAssemblyInfo(dnSpyFileList, module, options, directories)));
        }
Esempio n. 19
0
        public virtual void DecompileAssembly(DnSpyFileList dnSpyFileList, DnSpyFile file, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
        {
            bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
            bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;

            WriteCommentLine(output, file.Filename);
            if (decompileAsm && file.AssemblyDef != null)
            {
                if (file.AssemblyDef.IsContentTypeWindowsRuntime)
                {
                    WriteCommentLine(output, file.AssemblyDef.Name + " [WinRT]");
                }
                else
                {
                    WriteCommentLine(output, file.AssemblyDef.FullName);
                }
            }
            else if (decompileMod)
            {
                WriteCommentLine(output, file.ModuleDef.Name);
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Saves the specifies assembly list into the config file.
 /// </summary>
 public static void SaveList(DnSpyFileList list)
 {
     DNSpySettings.Update((root) => {
         var doc = root.Element(FILELISTS_SECTION_NAME) ?? root.Element(FILELISTS_SECTION_NAME_OLD);
         if (doc != null)
         {
             doc.Name = FILELISTS_SECTION_NAME;
         }
         if (doc == null)
         {
             doc = new XElement(FILELISTS_SECTION_NAME);
             root.Add(doc);
         }
         XElement listElement = doc.Elements(LIST_SECTION_NAME).FirstOrDefault(e => SessionSettings.Unescape((string)e.Attribute("name")) == list.Name);
         if (listElement != null)
         {
             listElement.ReplaceWith(SaveAsXml(list));
         }
         else
         {
             doc.Add(SaveAsXml(list));
         }
     });
 }
Esempio n. 21
0
 DnSpyFileList Initialize(DnSpyFileList list)
 {
     list.CollectionChanged += (s, e) => Save(list);
     return(list);
 }
Esempio n. 22
0
 DnSpyFile FindAssemblyByKey(IDnSpyFilenameKey key)
 {
     return(DnSpyFileList.FindByKey(key));
 }
Esempio n. 23
0
        DnSpyFile LoadFromMemory(DnModule dnModule, bool canLoadDynFile)
        {
            Debug.Assert(!dnModule.IsDynamic);
            if (dnModule.Address == 0)
            {
                return(null);
            }

            var file = FindMemory(dnModule);

            if (file != null)
            {
                return(file);
            }

            var manifestDnModule = dnModule.Assembly.Modules[0];
            var manifestKey      = MemoryModuleDefFile.CreateKey(manifestDnModule.Process, manifestDnModule.Address);
            var manMod           = FindAssemblyByKey(manifestKey);

            Debug.Assert(manMod == null);
            if (manMod != null)
            {
                return(null);
            }

            manMod = FindMemory(manifestDnModule);
            Debug.Assert(manMod == null);
            if (manMod != null)
            {
                return(null);
            }

            var modules = manifestDnModule.Assembly.Modules;
            var dict    = new Dictionary <ModuleDef, MemoryModuleDefFile>(modules.Length);
            var files   = new List <MemoryModuleDefFile>(modules.Length);
            MemoryModuleDefFile result = null;

            foreach (var module in modules)
            {
                MemoryModuleDefFile mfile;
                try {
                    mfile = MemoryModuleDefFile.Create(dict, module, UseDebugSymbols);
                    UpdateResolver(mfile.ModuleDef);
                    if (module == dnModule)
                    {
                        result = mfile;
                    }
                }
                catch {
                    // The PE headers and/or .NET headers are probably corrupt
                    return(LoadDynamic(dnModule, canLoadDynFile));
                }
                files.Add(mfile);
                dict.Add(mfile.ModuleDef, mfile);
            }
            Debug.Assert(result != null);
            if (files.Count == 0)
            {
                return(null);
            }
            var asm = files[0].AssemblyDef;

            if (asm == null)
            {
                if (files.Count > 1)
                {
                    asm = files[0].ModuleDef.UpdateRowId(new AssemblyDefUser("???"));
                    asm.Modules.Add(files[0].ModuleDef);
                }
            }
            asm.Modules.Clear();
            for (int i = 0; i < files.Count; i++)
            {
                asm.Modules.Add(files[i].ModuleDef);
            }

            DnSpyFileList.AddFile(files[0], true, true, false);

            return(result);
        }
Esempio n. 24
0
 public void DeleteCore(bool canDispose)
 {
     DnSpyFileList.Remove(dnSpyFile, canDispose);
 }
Esempio n. 25
0
        private void CreateDefaultAssemblyLists()
        {
            if (!manager.FileLists.Contains(DotNet4List))
            {
                var dotnet4 = new DnSpyFileList(manager.DnSpyFileListOptions, DotNet4List);
                AddToList(dotnet4, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet4, "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(dotnet4, "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(dotnet4, "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(dotnet4, "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

                if (dotnet4.GetDnSpyFiles().Length > 0)
                {
                    manager.CreateList(dotnet4);
                }
            }

            if (!manager.FileLists.Contains(DotNet35List))
            {
                var dotnet35 = new DnSpyFileList(manager.DnSpyFileListOptions, DotNet35List);
                AddToList(dotnet35, "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(dotnet35, "PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(dotnet35, "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(dotnet35, "WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

                if (dotnet35.GetDnSpyFiles().Length > 0)
                {
                    manager.CreateList(dotnet35);
                }
            }

            if (!manager.FileLists.Contains(ASPDotNetMVC3List))
            {
                var mvc = new DnSpyFileList(manager.DnSpyFileListOptions, ASPDotNetMVC3List);
                AddToList(mvc, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(mvc, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(mvc, "System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(mvc, "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(mvc, "System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                AddToList(mvc, "System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
                AddToList(mvc, "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                AddToList(mvc, "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

                if (mvc.GetDnSpyFiles().Length > 0)
                {
                    manager.CreateList(mvc);
                }
            }
        }
Esempio n. 26
0
        void WriteProjectFile(DnSpyFileList dnSpyFileList, TextWriter writer, IEnumerable <Tuple <string, string> > files, DnSpyFile assembly, DecompilationOptions options)
        {
            var          module       = assembly.ModuleDef;
            const string ns           = "http://schemas.microsoft.com/developer/msbuild/2003";
            string       platformName = CSharpLanguage.GetPlatformName(module);
            Guid         guid         = (App.CommandLineArguments == null ? null : App.CommandLineArguments.FixedGuid) ?? Guid.NewGuid();

            using (XmlTextWriter w = new XmlTextWriter(writer)) {
                var asmRefs = CSharpLanguage.GetAssemblyRefs(dnSpyFileList, options, assembly);

                w.Formatting = Formatting.Indented;
                w.WriteStartDocument();
                w.WriteStartElement("Project", ns);
                w.WriteAttributeString("ToolsVersion", "4.0");
                w.WriteAttributeString("DefaultTargets", "Build");

                w.WriteStartElement("PropertyGroup");
                w.WriteElementString("ProjectGuid", (options.ProjectGuid ?? guid).ToString("B").ToUpperInvariant());

                w.WriteStartElement("Configuration");
                w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
                w.WriteValue("Debug");
                w.WriteEndElement();                 // </Configuration>

                w.WriteStartElement("Platform");
                w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
                w.WriteValue(platformName);
                w.WriteEndElement();                 // </Platform>

                switch (module.Kind)
                {
                case ModuleKind.Windows:
                    w.WriteElementString("OutputType", "WinExe");
                    break;

                case ModuleKind.Console:
                    w.WriteElementString("OutputType", "Exe");
                    break;

                default:
                    w.WriteElementString("OutputType", "Library");
                    break;
                }

                if (module.Assembly != null)
                {
                    w.WriteElementString("AssemblyName", IdentifierEscaper.Escape(module.Assembly.Name));
                }
                bool useTargetFrameworkAttribute = false;
                var  targetFrameworkAttribute    = module.Assembly == null ? null : module.Assembly.CustomAttributes.FirstOrDefault(a => a.TypeFullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
                if (targetFrameworkAttribute != null && targetFrameworkAttribute.ConstructorArguments.Any())
                {
                    string   frameworkName    = (targetFrameworkAttribute.ConstructorArguments[0].Value as UTF8String) ?? string.Empty;
                    string[] frameworkParts   = frameworkName.Split(',');
                    string   frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith("Version="));
                    if (frameworkVersion != null)
                    {
                        w.WriteElementString("TargetFrameworkVersion", frameworkVersion.Substring("Version=".Length));
                        useTargetFrameworkAttribute = true;
                    }
                    string frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith("Profile="));
                    if (frameworkProfile != null)
                    {
                        w.WriteElementString("TargetFrameworkProfile", frameworkProfile.Substring("Profile=".Length));
                    }
                }
                if (!useTargetFrameworkAttribute)
                {
                    if (module.IsClr10)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v1.0");
                    }
                    else if (module.IsClr11)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v1.1");
                    }
                    else if (module.IsClr20)
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v2.0");
                        // TODO: Detect when .NET 3.0/3.5 is required
                    }
                    else
                    {
                        w.WriteElementString("TargetFrameworkVersion", "v4.0");
                    }
                }
                w.WriteElementString("WarningLevel", "4");

                w.WriteEndElement();                  // </PropertyGroup>

                w.WriteStartElement("PropertyGroup"); // platform-specific
                w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
                w.WriteElementString("PlatformTarget", platformName);
                w.WriteEndElement();                  // </PropertyGroup> (platform-specific)

                w.WriteStartElement("PropertyGroup"); // Debug
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
                w.WriteElementString("OutputPath", "bin\\Debug\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "full");
                w.WriteElementString("Optimize", "false");
                if (options.DontReferenceStdLib)
                {
                    w.WriteStartElement("NoStdLib");
                    w.WriteString("true");
                    w.WriteEndElement();
                }
                w.WriteEndElement();                  // </PropertyGroup> (Debug)

                w.WriteStartElement("PropertyGroup"); // Release
                w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
                w.WriteElementString("OutputPath", "bin\\Release\\");
                w.WriteElementString("DebugSymbols", "true");
                w.WriteElementString("DebugType", "pdbonly");
                w.WriteElementString("Optimize", "true");
                if (options.DontReferenceStdLib)
                {
                    w.WriteStartElement("NoStdLib");
                    w.WriteString("true");
                    w.WriteEndElement();
                }
                w.WriteEndElement();                 // </PropertyGroup> (Release)


                w.WriteStartElement("ItemGroup");                 // References
                foreach (var r in asmRefs)
                {
                    if (r.Name != "mscorlib")
                    {
                        var asm = dnSpyFileList.AssemblyResolver.Resolve(r, module);
                        if (asm != null && CSharpLanguage.ExistsInProject(options, asm.Filename))
                        {
                            continue;
                        }
                        w.WriteStartElement("Reference");
                        w.WriteAttributeString("Include", IdentifierEscaper.Escape(r.Name));
                        var hintPath = CSharpLanguage.GetHintPath(options, asm);
                        if (hintPath != null)
                        {
                            w.WriteStartElement("HintPath");
                            w.WriteString(hintPath);
                            w.WriteEndElement();
                        }
                        w.WriteEndElement();
                    }
                }
                w.WriteEndElement();                 // </ItemGroup> (References)

                foreach (IGrouping <string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g))
                {
                    w.WriteStartElement("ItemGroup");
                    foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
                    {
                        w.WriteStartElement(gr.Key);
                        w.WriteAttributeString("Include", file);
                        w.WriteEndElement();
                    }
                    w.WriteEndElement();
                }

                w.WriteStartElement("ItemGroup");                 // ProjectReference
                foreach (var r in asmRefs)
                {
                    var asm = dnSpyFileList.AssemblyResolver.Resolve(r, module);
                    if (asm == null)
                    {
                        continue;
                    }
                    var otherProj = CSharpLanguage.FindOtherProject(options, asm.Filename);
                    if (otherProj != null)
                    {
                        var relPath = CSharpLanguage.GetRelativePath(options.SaveAsProjectDirectory, otherProj.ProjectFileName);
                        w.WriteStartElement("ProjectReference");
                        w.WriteAttributeString("Include", relPath);
                        w.WriteStartElement("Project");
                        w.WriteString(otherProj.ProjectGuid.ToString("B").ToUpperInvariant());
                        w.WriteEndElement();
                        w.WriteStartElement("Name");
                        w.WriteString(IdentifierEscaper.Escape(otherProj.AssemblySimpleName));
                        w.WriteEndElement();
                        w.WriteEndElement();
                    }
                }
                w.WriteEndElement();                 // </ItemGroup> (ProjectReference)

                w.WriteStartElement("ItemGroup");    // Imports
                foreach (var import in projectImports.OrderBy(x => x))
                {
                    w.WriteStartElement("Import");
                    w.WriteAttributeString("Include", import);
                    w.WriteEndElement();
                }
                w.WriteEndElement();                 // </ItemGroup> (Imports)

                w.WriteStartElement("Import");
                w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.VisualBasic.targets");
                w.WriteEndElement();

                w.WriteEndDocument();
            }
        }