public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     EnsureLazyChildren();
     base.Decompile(language, output, options);
     if (stringTableEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     return new ResourceStringTable(stringTableEntries,
                         new System.Windows.Size(MainWindow.Instance.mainPane.ActualWidth - 45,
                                                 MainWindow.Instance.mainPane.ActualHeight));
                 }
             );
         }
         output.WriteLine();
         output.WriteLine();
     }
     if (otherEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     return new ResourceObjectTable(otherEntries,
                         new System.Windows.Size(MainWindow.Instance.mainPane.ActualWidth - 45,
                                                 MainWindow.Instance.mainPane.ActualHeight));
                 }
             );
         }
         output.WriteLine();
     }
 }
		public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
		{
			WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
			AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true);
			codeDomBuilder.AddMethod(method);
			RunTransformsAndGenerateCode(codeDomBuilder, output, options, method.Module);
		}
Example #3
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureChildrenFiltered));
			foreach (ILSpyTreeNode child in this.Children) {
				child.Decompile(language, output, options);
			}
		}
Example #4
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     EnsureChildrenFiltered();
     base.Decompile(language, output, options);
     if (stringTableEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     var textView = options.DecompilerTextView;
                     if (textView != null)
                         return new ResourceStringTable(stringTableEntries, textView) { Cursor = Cursors.Arrow };
                     return new TextBlock { Text = "no active tab!" };
                 }
             );
         }
         output.WriteLine();
         output.WriteLine();
     }
     if (otherEntries.Count != 0) {
         ISmartTextOutput smartOutput = output as ISmartTextOutput;
         if (null != smartOutput) {
             smartOutput.AddUIElement(
                 delegate {
                     var textView = options.DecompilerTextView;
                     if (textView != null)
                         return new ResourceObjectTable(otherEntries, textView) { Cursor = Cursors.Arrow };
                     return new TextBlock { Text = "no active tab!" };
                 }
             );
         }
         output.WriteLine();
     }
 }
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			if (r.IsWindowsRuntime) {
				language.WriteCommentLine(output, r.Name + " [WinRT]");
			} else {
				language.WriteCommentLine(output, r.FullName);
			}
		}
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options) {
			App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureChildrenFiltered));
			// Show metadata order of references
			foreach (var r in module.GetAssemblyRefs())
				new AssemblyReferenceTreeNode(r, parentAssembly, dnSpyFileListTreeNode).Decompile(language, output, options);
			foreach (var r in module.GetModuleRefs())
				language.WriteCommentLine(output, IdentifierEscaper.Escape(r.Name));
		}
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			if ((r.Attributes & (AssemblyAttributes)0x0200) != 0) {
				language.WriteCommentLine(output, r.Name + " [WinRT]");
			} else {
				language.WriteCommentLine(output, r.FullName);
			}
		}
Example #8
0
		public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
		{
			if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {
				HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				var files = WriteCodeFilesInProject(assembly.AssemblyDefinition, options, directories).ToList();
				files.AddRange(WriteResourceFilesInProject(assembly, options, directories));
				WriteProjectFile(new TextOutputWriter(output), files, assembly.AssemblyDefinition.MainModule);
			} else {
				base.DecompileAssembly(assembly, output, options);
				output.WriteLine();
				ModuleDefinition mainModule = assembly.AssemblyDefinition.MainModule;
				if (mainModule.EntryPoint != null) {
					output.Write("' Entry point: ");
					output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
					output.WriteLine();
				}
				switch (mainModule.Architecture) {
					case TargetArchitecture.I386:
						if ((mainModule.Attributes & ModuleAttributes.Required32Bit) == ModuleAttributes.Required32Bit)
							WriteCommentLine(output, "Architecture: x86");
						else
							WriteCommentLine(output, "Architecture: AnyCPU");
						break;
					case TargetArchitecture.AMD64:
						WriteCommentLine(output, "Architecture: x64");
						break;
					case TargetArchitecture.IA64:
						WriteCommentLine(output, "Architecture: Itanium-64");
						break;
				}
				if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) {
					WriteCommentLine(output, "This assembly contains unmanaged code.");
				}
				switch (mainModule.Runtime) {
					case TargetRuntime.Net_1_0:
						WriteCommentLine(output, "Runtime: .NET 1.0");
						break;
					case TargetRuntime.Net_1_1:
						WriteCommentLine(output, "Runtime: .NET 1.1");
						break;
					case TargetRuntime.Net_2_0:
						WriteCommentLine(output, "Runtime: .NET 2.0");
						break;
					case TargetRuntime.Net_4_0:
						WriteCommentLine(output, "Runtime: .NET 4.0");
						break;
				}
				output.WriteLine();
				
				// don't automatically load additional assemblies when an assembly node is selected in the tree view
				using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
					AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.AssemblyDefinition.MainModule);
					codeDomBuilder.AddAssembly(assembly.AssemblyDefinition, onlyAssemblyLevel: !options.FullDecompilation);
					RunTransformsAndGenerateCode(codeDomBuilder, output, options);
				}
			}
			OnDecompilationFinished(null);
		}
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureLazyChildren));
			// Show metadata order of references
			foreach (var r in module.AssemblyReferences)
				new AssemblyReferenceTreeNode(r, parentAssembly).Decompile(language, output, options);
			foreach (var r in module.ModuleReferences)
				language.WriteCommentLine(output, r.Name);
		}
Example #10
0
		public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
		{
			if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {

                //Checks if must create a solution
                if (options.CreateSolution)
                {
                    //Solution directory
                    var solutionDir = options.SaveAsProjectDirectory;

                    //List of the project names and their guid
                    List<Tuple<string, string>> projects = new List<Tuple<string, string>>();

                    //For each module
                    foreach (var module in assembly.AssemblyDefinition.Modules)
                    {
                        //Creates the project and the various files
                        var projectDir = Path.Combine(solutionDir, TextView.DecompilerTextView.CleanUpName(Path.GetFileNameWithoutExtension(module.Name)));
                        Directory.CreateDirectory(projectDir);
                        options.SaveAsProjectDirectory = projectDir;
                        HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                        var files = WriteCodeFilesInProject(module, options, directories).ToList();
                        files.AddRange(WriteResourceFilesInProject(module, options, directories));
                        using (var writer = new StreamWriter(Path.Combine(projectDir, Path.GetFileName(projectDir) + this.ProjectFileExtension), false, System.Text.Encoding.UTF8))
                            projects.Add(Tuple.Create(
                                Path.GetFileName(projectDir),
                                "{" + WriteProjectFile(writer, files, module, options).ToString().ToUpperInvariant() + "}"
                            ));
                    }

                    //Writes the solution
                    WriteSolutionFile(new TextOutputWriter(output), Enumerable.Reverse(projects));
                }
                else
                {
                    HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                    var files = assembly.AssemblyDefinition.Modules.SelectMany(m => WriteCodeFilesInProject(m, options, directories)).ToList();
                    files.AddRange(assembly.AssemblyDefinition.Modules.SelectMany(m => WriteResourceFilesInProject(m, options, directories)));
                    WriteProjectFile(new TextOutputWriter(output), files, assembly.AssemblyDefinition.MainModule, options);
                }

			} else {
				base.DecompileAssembly(assembly, output, options);
				output.WriteLine();
                WriteCommentLine(output, "Main module:");
                WriteModuleAttributes(assembly.AssemblyDefinition.MainModule, output, options);
				output.WriteLine();
				
				// don't automatically load additional assemblies when an assembly node is selected in the tree view
				using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
					AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.AssemblyDefinition.MainModule);
					codeDomBuilder.AddAssembly(assembly.AssemblyDefinition, onlyAssemblyLevel: !options.FullDecompilation);
					RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.AssemblyDefinition.MainModule);
				}
			}
			OnDecompilationFinished(null);
		}
Example #11
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			language.WriteCommentLine(output, string.Format("{0} ({1}, {2})", r.Name, r.ResourceType, r.Attributes));
			
			ISmartTextOutput smartOutput = output as ISmartTextOutput;
			if (smartOutput != null && r is EmbeddedResource) {
				smartOutput.AddButton(Images.Save, "Save", delegate { Save(null); });
				output.WriteLine();
			}
		}
Example #12
0
 public void Decompile(Language language, ITextOutput output, DecompilationOptions options, Action ensureLazyChildren)
 {
     var loadChildrenTask = this.loadChildrenTask;
     if (loadChildrenTask == null) {
         App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, ensureLazyChildren);
         loadChildrenTask = this.loadChildrenTask;
     }
     if (loadChildrenTask != null) {
         foreach (ILSpyTreeNode child in loadChildrenTask.Result.Cast<ILSpyTreeNode>()) {
             child.Decompile(language, output, options);
         }
     }
 }
Example #13
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     var loadChildrenTask = this.loadChildrenTask;
     if (loadChildrenTask == null) {
         App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnsureLazyChildren));
         loadChildrenTask = this.loadChildrenTask;
     }
     if (loadChildrenTask != null) {
         foreach (var child in loadChildrenTask.Result) {
             child.Decompile(language, output, options);
         }
     }
 }
Example #14
0
		public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
		{
			if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {
                var decompiler = new VBProjectDecompiler();
                decompiler.Decompile(this, assembly, output, options);
			} else {
				base.DecompileAssembly(assembly, output, options);
				output.WriteLine();
				ModuleDefinition mainModule = assembly.ModuleDefinition;
				if (mainModule.EntryPoint != null) {
					output.Write("' Entry point: ");
					output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
					output.WriteLine();
				}
				WriteCommentLine(output, "Architecture: " + CSharpLanguage.GetPlatformDisplayName(mainModule));
				if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) {
					WriteCommentLine(output, "This assembly contains unmanaged code.");
				}
				switch (mainModule.Runtime) {
					case TargetRuntime.Net_1_0:
						WriteCommentLine(output, "Runtime: .NET 1.0");
						break;
					case TargetRuntime.Net_1_1:
						WriteCommentLine(output, "Runtime: .NET 1.1");
						break;
					case TargetRuntime.Net_2_0:
						WriteCommentLine(output, "Runtime: .NET 2.0");
						break;
					case TargetRuntime.Net_4_0:
                        if (assembly.IsNet45())
                        {
                            WriteCommentLine(output, "Runtime: .NET 4.5");
                        }
                        else
                        {
                            WriteCommentLine(output, "Runtime: .NET 4.0");
                        }
						break;
				}
				output.WriteLine();
				
				// don't automatically load additional assemblies when an assembly node is selected in the tree view
				using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
					AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition);
					codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation);
					RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.ModuleDefinition);
				}
			}
		}
Example #15
0
		public override void DecompileAssembly(LoadedAssembly assembly, 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(assembly.ModuleDefinition, options, directories).ToList();
				files.AddRange(WriteResourceFilesInProject(assembly, options, directories));
				WriteProjectFile(new TextOutputWriter(output), files, assembly, options);
			} else {
				bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
				bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;
				base.DecompileAssembly(assembly, output, options, flags);
				output.WriteLine();
				ModuleDef mainModule = assembly.ModuleDefinition;
				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(assembly, 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 : LoadedAssembly.DisableAssemblyLoad()) {
					AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition);
					codeDomBuilder.AddAssembly(assembly.ModuleDefinition, !options.FullDecompilation, decompileAsm, decompileMod);
					RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.ModuleDefinition);
				}
			}
		}
Example #16
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     try {
         assembly.WaitUntilLoaded(); // necessary so that load errors are passed on to the caller
     } catch (AggregateException ex) {
         language.WriteCommentLine(output, assembly.FileName);
         if (ex.InnerException is BadImageFormatException || ex.InnerException is IOException) {
             language.WriteCommentLine(output, "This file does not contain a managed assembly.");
             return;
         } else {
             throw;
         }
     }
     var flags = Parent is AssemblyTreeNode ? DecompileAssemblyFlags.Module : DecompileAssemblyFlags.Assembly;
     if (assembly.AssemblyDefinition == null)
         flags = DecompileAssemblyFlags.Module;
     if (options.FullDecompilation)
         flags = DecompileAssemblyFlags.AssemblyAndModule;
     language.DecompileAssembly(assembly, output, options, flags);
 }
Example #17
0
 public override void Decompile(Language language, ICSharpCode.Decompiler.ITextOutput output, DecompilationOptions options)
 {
 }
Example #18
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			language.WriteCommentLine(output, IdentifierEscaper.Escape(r.Name));
		}
Example #19
0
        /// <summary>
        /// Shows the 'save file dialog', prompting the user to save the decompiled nodes to disk.
        /// </summary>
        public void SaveToDisk(ILSpy.Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options)
        {
            if (!treeNodes.Any())
            {
                return;
            }

            SaveFileDialog dlg = new SaveFileDialog();

            dlg.DefaultExt = language.FileExtension;
            dlg.Filter     = language.Name + "|*" + language.FileExtension + "|All Files|*.*";
            dlg.FileName   = CleanUpName(treeNodes.First().ToString()) + language.FileExtension;
            if (dlg.ShowDialog() == true)
            {
                SaveToDisk(new DecompilationContext(language, treeNodes.ToArray(), options), dlg.FileName);
            }
        }
Example #20
0
        /// <summary>
        /// Starts the decompilation of the given nodes.
        /// The result is displayed in the text view.
        /// </summary>
        public void Decompile(ILSpy.Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options)
        {
            // Some actions like loading an assembly list cause several selection changes in the tree view,
            // and each of those will start a decompilation action.
            bool isDecompilationScheduled = this.nextDecompilationRun != null;

            this.nextDecompilationRun = new DecompilationContext(language, treeNodes.ToArray(), options);
            if (!isDecompilationScheduled)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(
                                           delegate {
                    var context = this.nextDecompilationRun;
                    this.nextDecompilationRun = null;
                    if (context != null)
                    {
                        DoDecompile(context, DefaultOutputLengthLimit);
                    }
                }
                                           ));
            }
        }
Example #21
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            PEFile module = assembly.GetPEFileAsync().GetAwaiter().GetResult();
            ReadyToRunReaderCacheEntry cacheEntry = GetReader(assembly, module);

            if (cacheEntry.readyToRunReader == null)
            {
                WriteCommentLine(output, cacheEntry.failureReason);
            }
            else
            {
                ReadyToRunReader reader = cacheEntry.readyToRunReader;
                WriteCommentLine(output, reader.Machine.ToString());
                WriteCommentLine(output, reader.OperatingSystem.ToString());
                WriteCommentLine(output, reader.CompilerIdentifier);
                WriteCommentLine(output, "TODO - display more header information");
            }

            return(base.DecompileAssembly(assembly, output, options));
        }
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, string.Format("{0} = {1}", key, data));
 }
Example #23
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, IdentifierEscaper.Escape(r.Name));
 }
Example #24
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, "MethodImpls");
 }
Example #25
0
        // There are several methods available to override; in this sample, we deal with methods only

        public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
        {
            if (method.Body != null)
            {
                output.WriteLine("Size of method: {0} bytes", method.Body.CodeSize);

                ISmartTextOutput smartOutput = output as ISmartTextOutput;
                if (smartOutput != null)
                {
                    // when writing to the text view (but not when writing to a file), we can even add UI elements such as buttons:
                    smartOutput.AddButton(null, "Click me!", (sender, e) => (sender as Button).Content = "I was clicked!");
                    smartOutput.WriteLine();
                }

                // ICSharpCode.Decompiler.Ast.AstBuilder can be used to decompile to C#
                AstBuilder b = new AstBuilder(new DecompilerContext(method.Module)
                {
                    Settings    = options.DecompilerSettings,
                    CurrentType = method.DeclaringType
                });
                b.AddMethod(method);
                b.RunTransformations();
                output.WriteLine("Decompiled AST has {0} nodes", b.CompilationUnit.DescendantsAndSelf.Count());
            }
        }
Example #26
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileProperty(property, output, options);
 }
Example #27
0
 public void SaveToDisk(ILSpy.Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options, string fileName)
 {
     SaveToDisk(new DecompilationContext(language, treeNodes.ToArray(), options), fileName);
 }
Example #28
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			threading.Decompile(language, output, options, EnsureLazyChildren);
		}
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, "CustomAttributes");
 }
Example #30
0
 public abstract void Decompile(Language language, ITextOutput output, DecompilationOptions options);
Example #31
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileEvent(ev, output, options);
 }
Example #32
0
        IEnumerable <Tuple <string, string> > WriteCodeFilesInProject(ModuleDefinition module, DecompilationOptions options, HashSet <string> directories)
        {
            var files = module.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
                delegate(TypeDefinition 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, TypeDefinition> file) {
                using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
                    foreach (TypeDefinition 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(module, options, directories)));
        }
Example #33
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
 }
Example #34
0
        IEnumerable <Tuple <string, string> > WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options, HashSet <string> directories)
        {
            // don't automatically load additional assemblies when an assembly node is selected in the tree view
            using (LoadedAssembly.DisableAssemblyLoad())
            {
                AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
                codeDomBuilder.AddAssembly(module, onlyAssemblyLevel: 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) });
            }
        }
        /// <summary>
        /// Shows the 'save file dialog', prompting the user to save the decompiled nodes to disk.
        /// </summary>
        public async void SaveToDisk(Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options)
        {
            if (!treeNodes.Any())
            {
                return;
            }

            SaveFileDialog dlg = new SaveFileDialog();

            dlg.DefaultExtension = language.FileExtension;
            dlg.Filters          = new List <FileDialogFilter>()
            {
                new FileDialogFilter()
                {
                    Name = language.Name, Extensions = { language.FileExtension }
                },
                new FileDialogFilter()
                {
                    Name = "All Files", Extensions = { "*" }
                }
            };
            dlg.InitialFileName = CleanUpName(treeNodes.First().ToString()) + language.FileExtension;
            var fileName = await dlg.ShowAsync(App.Current.MainWindow);

            if (fileName != null)
            {
                SaveToDisk(new DecompilationContext(language, treeNodes.ToArray(), options), fileName);
            }
        }
Example #36
0
 public abstract void Decompile(Language language, ITextOutput output, DecompilationOptions options);
Example #37
0
 public DecompilationContext(ILSpy.Language language, ILSpyTreeNode[] treeNodes, DecompilationOptions options)
 {
     this.Language  = language;
     this.TreeNodes = treeNodes;
     this.Options   = options;
 }
Example #38
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileField(field, output, options);
 }
Example #39
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, "List: " + assemblyList.ListName);
     output.WriteLine();
     foreach (AssemblyTreeNode asm in this.Children) {
         language.WriteCommentLine(output, new string('-', 60));
         output.WriteLine();
         asm.Decompile(language, output, options);
     }
 }
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			EnsureLazyChildren();
		}
Example #41
0
		public override bool Save(DecompilerTextView textView)
		{
			Language language = this.Language;
			if (string.IsNullOrEmpty(language.ProjectFileExtension))
				return false;
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.FileName = DecompilerTextView.CleanUpName(assembly.ShortName) + language.ProjectFileExtension;
			dlg.Filter = language.Name + " project|*" + language.ProjectFileExtension + "|" + language.Name + " single file|*" + language.FileExtension + "|All files|*.*";
			if (dlg.ShowDialog() == true) {
				DecompilationOptions options = new DecompilationOptions();
				options.FullDecompilation = true;
				if (dlg.FilterIndex == 1) {
					options.SaveAsProjectDirectory = Path.GetDirectoryName(dlg.FileName);
					foreach (string entry in Directory.GetFileSystemEntries(options.SaveAsProjectDirectory)) {
						if (!string.Equals(entry, dlg.FileName, StringComparison.OrdinalIgnoreCase)) {
							var result = MessageBox.Show(
								"The directory is not empty. File will be overwritten." + Environment.NewLine +
								"Are you sure you want to continue?",
								"Project Directory not empty",
								MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
							if (result == MessageBoxResult.No)
								return true; // don't save, but mark the Save operation as handled
							break;
						}
					}
				}
				textView.SaveToDisk(language, new[] { this }, options, dlg.FileName);
			}
			return true;
		}
Example #42
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			language.WriteCommentLine(output, string.Format("{0} = {1}", key, data));
		}
Example #43
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileMethod(method, output, options);
 }
        /// <summary>
        /// Starts the decompilation of the given nodes.
        /// The result is displayed in the text view.
        /// If any errors occur, the error message is displayed in the text view, and the task returned by this method completes successfully.
        /// If the operation is cancelled (by starting another decompilation action); the returned task is marked as cancelled.
        /// </summary>
        public Task DecompileAsync(ILSpy.Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options)
        {
            // Some actions like loading an assembly list cause several selection changes in the tree view,
            // and each of those will start a decompilation action.

            bool isDecompilationScheduled = this.nextDecompilationRun != null;

            if (this.nextDecompilationRun != null)
            {
                this.nextDecompilationRun.TaskCompletionSource.TrySetCanceled();
            }
            this.nextDecompilationRun = new DecompilationContext(language, treeNodes.ToArray(), options);
            var task = this.nextDecompilationRun.TaskCompletionSource.Task;

            if (!isDecompilationScheduled)
            {
                Dispatcher.UIThread.InvokeAsync(
                    new Action(
                        delegate {
                    var context = this.nextDecompilationRun;
                    this.nextDecompilationRun = null;
                    if (context != null)
                    {
                        DoDecompile(context, DefaultOutputLengthLimit)
                        .ContinueWith(t => context.TaskCompletionSource.SetFromTask(t)).HandleExceptions();
                    }
                }
                        ), DispatcherPriority.Background);
            }
            return(task);
        }
Example #45
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList();
                files.AddRange(WriteResourceFilesInProject(assembly, options, directories));
                WriteProjectFile(new TextOutputWriter(output), files, assembly.ModuleDefinition);
            }
            else
            {
                base.DecompileAssembly(assembly, output, options);
                output.WriteLine();
                ModuleDefinition mainModule = assembly.ModuleDefinition;
                if (mainModule.Types.Count > 0)
                {
                    output.Write("' Global type: ");
                    output.WriteReference(mainModule.Types[0].FullName, mainModule.Types[0]);
                    output.WriteLine();
                }
                if (mainModule.EntryPoint != null)
                {
                    output.Write("' Entry point: ");
                    output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
                    output.WriteLine();
                }
                WriteCommentLine(output, "Architecture: " + CSharpLanguage.GetPlatformDisplayName(mainModule));
                if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0)
                {
                    WriteCommentLine(output, "This assembly contains unmanaged code.");
                }
                switch (mainModule.Runtime)
                {
                case TargetRuntime.Net_1_0:
                    WriteCommentLine(output, "Runtime: .NET 1.0");
                    break;

                case TargetRuntime.Net_1_1:
                    WriteCommentLine(output, "Runtime: .NET 1.1");
                    break;

                case TargetRuntime.Net_2_0:
                    WriteCommentLine(output, "Runtime: .NET 2.0");
                    break;

                case TargetRuntime.Net_4_0:
                    WriteCommentLine(output, "Runtime: .NET 4.0");
                    break;
                }
                output.WriteLine();

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
                    AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition);
                    codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation);
                    RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.ModuleDefinition);
                }
            }
        }
Example #46
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			language.DecompileField(field, output, options);
		}
Example #47
0
        public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
            AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: field.DeclaringType, isSingleMember: true);

            codeDomBuilder.AddField(field);
            RunTransformsAndGenerateCode(codeDomBuilder, output, options, field.Module);
        }
Example #48
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			language.WriteCommentLine(output, language.TypeToString(def, true));
		}
Example #49
0
        public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true));
            AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: property.DeclaringType, isSingleMember: true);

            codeDomBuilder.AddProperty(property);
            RunTransformsAndGenerateCode(codeDomBuilder, output, options, property.Module);
        }
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileType(TypeDefinition, output, options);
 }
Example #51
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, moduleName);
     language.WriteCommentLine(output, containsMetadata ? "contains metadata" : "contains no metadata");
 }
Example #52
0
		public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
		{
			assembly.WaitUntilLoaded(); // necessary so that load errors are passed on to the caller
			language.DecompileAssembly(assembly, output, options);
		}
Example #53
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, language.TypeToString(type, true));
 }
Example #54
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileEvent(ev, output, options);
 }
Example #55
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.WriteCommentLine(output, "Optional Header");
 }
Example #56
0
 public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
 {
     language.DecompileNamespace(name, this.Children.OfType<TypeTreeNode>().Select(t => t.TypeDefinition), output, options);
 }
 public void Decompile(ILSpy.Language language, IEnumerable <ILSpyTreeNode> treeNodes, DecompilationOptions options)
 {
     DecompileAsync(language, treeNodes, options).HandleExceptions();
 }