Represents an assembly loaded into ILSpy.
Ejemplo n.º 1
0
		public override TreeViewNodeFilterResult GetFilterResult(LoadedAssembly asm, AssemblyFilterType type) {
			if (type == AssemblyFilterType.NonNetFile)
				return new TreeViewNodeFilterResult(FilterResult.Hidden, false);

			if (type == AssemblyFilterType.Assembly) {
				if (assembly == null || asm.AssemblyDefinition != assembly)
					return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
				return new TreeViewNodeFilterResult(FilterResult.Match, false);
			}

			if (type == AssemblyFilterType.NetModule) {
				if (asm.AssemblyDefinition != assembly)
					return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
				if (assembly == null || assembly.ManifestModule != module) {
					if (asm.ModuleDefinition != module)
						return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
					return new TreeViewNodeFilterResult(FilterResult.Match, false);
				}
				else
					return new TreeViewNodeFilterResult(FilterResult.Match, asm.ModuleDefinition != assembly.ManifestModule);
			}

			Debug.Fail("Invalid AssemblyFilterType value");
			return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
		}
Ejemplo n.º 2
0
		public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
		{
			output.WriteLine("// " + assembly.FileName);
			output.WriteLine();
			
			new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).WriteAssemblyHeader(assembly.AssemblyDefinition);
		}
		public override TreeViewNodeFilterResult GetFilterResult(LoadedAssembly asm, AssemblyFilterType type) {
			if (asm.AssemblyDefinition != allowedAsm)
				return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
			if (allowedAsm == null && asm.ModuleDefinition != allowedMod)
				return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
			return base.GetFilterResult(asm, type);
		}
Ejemplo n.º 4
0
        static void Execute(ILSpyTreeNode[] nodes)
        {
            if (!AddNetModuleToAssemblyCommand.CanExecute(nodes))
                return;

            var dialog = new System.Windows.Forms.OpenFileDialog() {
                Filter = ".NET NetModules (*.netmodule)|*.netmodule|All files (*.*)|*.*",
                RestoreDirectory = true,
            };
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;
            if (string.IsNullOrEmpty(dialog.FileName))
                return;

            var asm = new LoadedAssembly(MainWindow.Instance.CurrentAssemblyList, dialog.FileName);
            if (asm.ModuleDefinition == null || asm.AssemblyDefinition != null) {
                MainWindow.Instance.ShowMessageBox(string.Format("{0} is not a NetModule", asm.FileName), System.Windows.MessageBoxButton.OK);
                asm.TheLoadedFile.Dispose();
                return;
            }

            var cmd = new AddExistingNetModuleToAssemblyCommand((AssemblyTreeNode)nodes[0], asm);
            UndoCommandManager.Instance.Add(cmd);
            MainWindow.Instance.JumpToReference(cmd.modNode);
        }
Ejemplo n.º 5
0
		public string WriteResourceToFile(LoadedAssembly assembly, string fileName, Stream stream, DecompilationOptions options)
		{
			var document = BamlResourceEntryNode.LoadIntoDocument(assembly.GetAssemblyResolver(), assembly.AssemblyDefinition, stream);
			fileName = Path.ChangeExtension(fileName, ".xaml");
			document.Save(Path.Combine(options.SaveAsProjectDirectory, fileName));
			return fileName;
		}
Ejemplo n.º 6
0
 public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
 {
     WriteCommentLine(output, assembly.FileName);
     if (assembly.AssemblyDefinition != null) {
         if (assembly.AssemblyDefinition.IsContentTypeWindowsRuntime) {
             WriteCommentLine(output, assembly.AssemblyDefinition.Name + " [WinRT]");
         } else {
             WriteCommentLine(output, assembly.AssemblyDefinition.FullName);
         }
     } else {
         WriteCommentLine(output, assembly.ModuleDefinition.Name);
     }
 }
Ejemplo n.º 7
0
		public override TreeViewNodeFilterResult GetFilterResult(LoadedAssembly asm, AssemblyFilterType type) {
			VisibleMembersFlags thisFlag, visibleFlags;
			switch (type) {
			case AssemblyFilterType.Assembly:
				thisFlag = VisibleMembersFlags.AssemblyDef;
				visibleFlags = thisFlag | VisibleMembersFlags.ModuleDef |
						VisibleMembersFlags.Namespace | VisibleMembersFlags.AnyTypeDef |
						VisibleMembersFlags.FieldDef | VisibleMembersFlags.MethodDef |
						VisibleMembersFlags.InstanceConstructor | VisibleMembersFlags.PropertyDef |
						VisibleMembersFlags.EventDef | VisibleMembersFlags.AssemblyRef |
						VisibleMembersFlags.BaseTypes | VisibleMembersFlags.DerivedTypes |
						VisibleMembersFlags.ModuleRef | VisibleMembersFlags.ResourceList |
						VisibleMembersFlags.MethodBody | VisibleMembersFlags.ParamDefs |
						VisibleMembersFlags.ParamDef | VisibleMembersFlags.Locals |
						VisibleMembersFlags.Local | VisibleMembersFlags.Resource |
						VisibleMembersFlags.ResourceElement | VisibleMembersFlags.PE |
						VisibleMembersFlags.Hex;
				break;

			case AssemblyFilterType.NetModule:
				thisFlag = VisibleMembersFlags.ModuleDef;
				visibleFlags = thisFlag |
						VisibleMembersFlags.Namespace | VisibleMembersFlags.AnyTypeDef |
						VisibleMembersFlags.FieldDef | VisibleMembersFlags.MethodDef |
						VisibleMembersFlags.InstanceConstructor | VisibleMembersFlags.PropertyDef |
						VisibleMembersFlags.EventDef | VisibleMembersFlags.AssemblyRef |
						VisibleMembersFlags.BaseTypes | VisibleMembersFlags.DerivedTypes |
						VisibleMembersFlags.ModuleRef | VisibleMembersFlags.ResourceList |
						VisibleMembersFlags.MethodBody | VisibleMembersFlags.ParamDefs |
						VisibleMembersFlags.ParamDef | VisibleMembersFlags.Locals |
						VisibleMembersFlags.Local | VisibleMembersFlags.Resource |
						VisibleMembersFlags.ResourceElement | VisibleMembersFlags.PE |
						VisibleMembersFlags.Hex;
				break;

			case AssemblyFilterType.NonNetFile:
			default:
				thisFlag = VisibleMembersFlags.NonNetFile;
				visibleFlags = thisFlag | VisibleMembersFlags.PE | VisibleMembersFlags.Hex;
				break;
			}
			bool isMatch = (flags & thisFlag) != 0;
			if ((flags & visibleFlags) == 0)
				return new TreeViewNodeFilterResult(FilterResult.Hidden, isMatch);

			if (isMatch)
				return new TreeViewNodeFilterResult(FilterResult.Match, isMatch);   // Make sure it's not hidden

			return new TreeViewNodeFilterResult(null, isMatch);
		}
Ejemplo n.º 8
0
        public AssemblyCompiler AssemblyCompiler { get { return compiler.AssemblyCompiler; } }
        public MapFileLookup MapFile { get { return compiler.MapFile; }  }


        public static bool GenerateSetNextInstructionCode
        {
            get { return compiler.GenerateSetNextInstructionCode; }
            set { compiler.GenerateSetNextInstructionCode = value; }
        }


        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            compiler.CompileIfRequired(assembly.AssemblyDefinition);
Ejemplo n.º 9
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();

            ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);
            //if (options.FullDecompilation)
            //	rd.WriteAssemblyReferences(assembly.ModuleDefinition);
            if (assembly.AssemblyDefinition != null)
                rd.WriteAssemblyHeader(assembly.AssemblyDefinition);
            output.WriteLine();
            rd.WriteModuleHeader(assembly.ModuleDefinition);
            if (options.FullDecompilation) {
                output.WriteLine();
                output.WriteLine();
                rd.WriteModuleContents(assembly.ModuleDefinition);
            }
        }
Ejemplo n.º 10
0
        void Search(LoadedAssembly ownerModule, TypeDef type, FieldDef field)
        {
            var res = filter.GetFilterResult(field);

            if (res.FilterResult == FilterResult.Hidden)
            {
                return;
            }

            if (res.IsMatch && IsMatch(field.Name, field))
            {
                onMatch(new SearchResult {
                    Language          = language,
                    Object            = field,
                    NameObject        = field,
                    TypeImageInfo     = FieldTreeNode.GetImageInfo(field, BackgroundType.Search),
                    LocationObject    = type,
                    LocationImageInfo = TypeTreeNode.GetImageInfo(type, BackgroundType.Search),
                    LoadedAssembly    = ownerModule,
                });
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Replace the assembly object model from a crafted stream, without disk I/O
        /// Returns null if it is not already loaded.
        /// </summary>
        public LoadedAssembly HotReplaceAssembly(string file, Stream stream)
        {
            App.Current.Dispatcher.VerifyAccess();
            file = Path.GetFullPath(file);

            var target = this.assemblies.FirstOrDefault(asm => file.Equals(asm.FileName, StringComparison.OrdinalIgnoreCase));

            if (target == null)
            {
                return(null);
            }

            var index  = this.assemblies.IndexOf(target);
            var newAsm = new LoadedAssembly(this, file, stream);

            lock (assemblies)
            {
                this.assemblies.Remove(target);
                this.assemblies.Insert(index, newAsm);
            }
            return(newAsm);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Opens an assembly from disk.
        /// Returns the existing assembly node if it is already loaded.
        /// </summary>
        public LoadedAssembly OpenAssembly(string file, bool isAutoLoaded = false)
        {
            App.Current.Dispatcher.VerifyAccess();

            file = Path.GetFullPath(file);

            foreach (LoadedAssembly asm in this.assemblies)
            {
                if (file.Equals(asm.FileName, StringComparison.OrdinalIgnoreCase))
                {
                    return(asm);
                }
            }

            var newAsm = new LoadedAssembly(this, file);

            newAsm.IsAutoLoaded = isAutoLoaded;
            lock (assemblies) {
                this.assemblies.Add(newAsm);
            }
            return(newAsm);
        }
Ejemplo n.º 13
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();

            ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            //if (options.FullDecompilation)
            //	rd.WriteAssemblyReferences(assembly.ModuleDefinition);
            if (assembly.AssemblyDefinition != null)
            {
                rd.WriteAssemblyHeader(assembly.AssemblyDefinition);
            }
            output.WriteLine();
            rd.WriteModuleHeader(assembly.ModuleDefinition);
            if (options.FullDecompilation)
            {
                output.WriteLine();
                output.WriteLine();
                rd.WriteModuleContents(assembly.ModuleDefinition);
            }
        }
Ejemplo n.º 14
0
        public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
        {
            bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
            bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;

            WriteCommentLine(output, assembly.FileName);
            if (decompileAsm && assembly.AssemblyDefinition != null)
            {
                if (assembly.AssemblyDefinition.IsContentTypeWindowsRuntime)
                {
                    WriteCommentLine(output, assembly.AssemblyDefinition.Name + " [WinRT]");
                }
                else
                {
                    WriteCommentLine(output, assembly.AssemblyDefinition.FullName);
                }
            }
            else if (decompileMod)
            {
                WriteCommentLine(output, assembly.ModuleDefinition.Name);
            }
        }
Ejemplo n.º 15
0
        public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, assembly.FileName);
            var asm = assembly.GetAssemblyDefinitionOrNull();

            if (asm != null)
            {
                var name = asm.Name;
                if (name.IsWindowsRuntime)
                {
                    WriteCommentLine(output, name.Name + " [WinRT]");
                }
                else
                {
                    WriteCommentLine(output, name.FullName);
                }
            }
            else
            {
                WriteCommentLine(output, assembly.GetModuleDefinitionAsync().Result.Name);
            }
        }
Ejemplo n.º 16
0
        void Search(LoadedAssembly ownerModule, TypeDef type, EventDef evt)
        {
            var res = filter.GetFilterResult(evt);

            if (res.FilterResult == FilterResult.Hidden)
            {
                return;
            }

            if (res.IsMatch && IsMatch(evt.Name, evt))
            {
                onMatch(new SearchResult {
                    Language          = language,
                    Object            = evt,
                    NameObject        = evt,
                    TypeImageInfo     = EventTreeNode.GetImageInfo(evt, BackgroundType.Search),
                    LocationObject    = type,
                    LocationImageInfo = TypeTreeNode.GetImageInfo(type, BackgroundType.Search),
                    LoadedAssembly    = ownerModule,
                });
            }
        }
Ejemplo n.º 17
0
        void Search(LoadedAssembly ownerModule, TypeDef type, PropertyDef prop)
        {
            var res = filter.GetFilterResult(prop);

            if (res.FilterResult == FilterResult.Hidden)
            {
                return;
            }

            if (res.IsMatch && IsMatch(prop.Name, prop))
            {
                onMatch(new SearchResult {
                    Language          = language,
                    Object            = prop,
                    NameObject        = prop,
                    TypeImageInfo     = PropertyTreeNode.GetImageInfo(prop, BackgroundType.Search),
                    LocationObject    = type,
                    LocationImageInfo = TypeTreeNode.GetImageInfo(type, BackgroundType.Search),
                    LoadedAssembly    = ownerModule,
                });
            }
        }
Ejemplo n.º 18
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();

            ReflectionDisassembler rd = new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken);

            if (options.FullDecompilation)
            {
                rd.WriteAssemblyReferences(assembly.AssemblyDefinition.MainModule);
            }
            rd.WriteAssemblyHeader(assembly.AssemblyDefinition);
            output.WriteLine();
            if (options.FullDecompilation)
            {
                foreach (var m in assembly.AssemblyDefinition.Modules)
                {
                    DecompileModule(m, output, options);
                }
            }
            OnDecompilationFinished(null);
        }
Ejemplo n.º 19
0
 void SearchMembers(LoadedAssembly ownerModule, TypeDef type)
 {
     foreach (var method in type.Methods)
     {
         Search(ownerModule, type, method);
     }
     cancellationToken.ThrowIfCancellationRequested();
     foreach (var field in type.Fields)
     {
         Search(ownerModule, type, field);
     }
     cancellationToken.ThrowIfCancellationRequested();
     foreach (var prop in type.Properties)
     {
         Search(ownerModule, type, prop);
     }
     cancellationToken.ThrowIfCancellationRequested();
     foreach (var evt in type.Events)
     {
         Search(ownerModule, type, evt);
     }
 }
Ejemplo n.º 20
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();
                ModuleDef mainModule = assembly.ModuleDefinition;
                if (mainModule.EntryPoint != null)
                {
                    output.Write("// Entry point: ");
                    output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
                    output.WriteLine();
                }
                output.WriteLine("// Architecture: " + GetPlatformDisplayName(mainModule));
                if (!mainModule.IsILOnly)
                {
                    output.WriteLine("// This assembly contains unmanaged code.");
                }
                output.WriteLine("// Runtime: " + mainModule.RuntimeVersion);
                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);
                    codeDomBuilder.RunTransformations(transformAbortCondition);
                    codeDomBuilder.GenerateCode(output);
                }
            }
        }
Ejemplo n.º 21
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();
            var module   = assembly.GetPEFileOrNull();
            var metadata = module.Metadata;
            var dis      = CreateDisassembler(output, options);

            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                throw new NotSupportedException($"Language '{Name}' does not support exporting assemblies as projects!");
            }

            // don't automatically load additional assemblies when an assembly node is selected in the tree view
            using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad(assembly.AssemblyList))
            {
                dis.AssemblyResolver = module.GetAssemblyResolver();
                dis.DebugInfo        = module.GetDebugInfoOrNull();
                if (options.FullDecompilation)
                {
                    dis.WriteAssemblyReferences(metadata);
                }
                if (metadata.IsAssembly)
                {
                    dis.WriteAssemblyHeader(module);
                }
                output.WriteLine();
                dis.WriteModuleHeader(module);
                if (options.FullDecompilation)
                {
                    output.WriteLine();
                    output.WriteLine();
                    dis.WriteModuleContents(module);
                }
            }
            return(null);
        }
Ejemplo n.º 22
0
        public virtual ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            WriteCommentLine(output, assembly.FileName);
            var asm = assembly.GetPEFileOrNull();

            if (asm == null)
            {
                return(null);
            }
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                throw new NotSupportedException($"Language '{Name}' does not support exporting assemblies as projects!");
            }
            var metadata = asm.Metadata;

            if (metadata.IsAssembly)
            {
                var name = metadata.GetAssemblyDefinition();
                if ((name.Flags & System.Reflection.AssemblyFlags.WindowsRuntime) != 0)
                {
                    WriteCommentLine(output, metadata.GetString(name.Name) + " [WinRT]");
                }
                else if (metadata.TryGetFullAssemblyName(out string assemblyName))
                {
                    WriteCommentLine(output, assemblyName);
                }
                else
                {
                    WriteCommentLine(output, "ERR: Could not read assembly name");
                }
            }
            else
            {
                WriteCommentLine(output, metadata.GetString(metadata.GetModuleDefinition().Name));
            }
            return(null);
        }
Ejemplo n.º 23
0
        LoadedAssembly DelayLoadAssembly(LoadedAssembly newAsm, int index, bool canDispose)
        {
            System.Diagnostics.Debug.Assert(!string.IsNullOrWhiteSpace(newAsm.FileName));
            bool startThread;

            lock (delayLoadedAsms) {
                Tuple <LoadedAssembly, int> info;
                if (delayLoadedAsms.TryGetValue(newAsm.FileName, out info))
                {
                    if (canDispose)
                    {
                        newAsm.TheLoadedFile.Dispose();
                    }
                    return(info.Item1);
                }
                delayLoadedAsms.Add(newAsm.FileName, Tuple.Create(newAsm, index));
                startThread = delayLoadedAsms.Count == 1;
            }
            if (startThread)
            {
                App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => DelayLoadAssemblyMainThread()));
            }
            return(newAsm);
        }
Ejemplo n.º 24
0
        void Search(LoadedAssembly ownerModule, TypeDef type)
        {
            var res = filter.GetFilterResult(type);

            if (res.FilterResult == FilterResult.Hidden)
            {
                return;
            }

            if (res.IsMatch && (IsMatch(type.FullName, type) || IsMatch(type.Name, type)))
            {
                onMatch(new SearchResult {
                    Language          = language,
                    Object            = type,
                    NameObject        = type,
                    TypeImageInfo     = TypeTreeNode.GetImageInfo(type, BackgroundType.Search),
                    LocationObject    = type.DeclaringType,
                    LocationImageInfo = TypeTreeNode.GetImageInfo(type.DeclaringType, BackgroundType.Search),
                    LoadedAssembly    = ownerModule,
                });
            }

            SearchMembers(ownerModule, type);
        }
Ejemplo n.º 25
0
		public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
		{
			bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
			bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;
			output.WriteLine("// " + assembly.FileName, TextTokenType.Comment);
			if (decompileMod || decompileAsm)
				PrintEntryPoint(assembly, output);
			output.WriteLine();
			
			ReflectionDisassembler rd = CreateReflectionDisassembler(output, options, assembly.ModuleDefinition);
			if (decompileMod && options.FullDecompilation)
				rd.WriteAssemblyReferences(assembly.ModuleDefinition as ModuleDefMD);
			if (decompileAsm && assembly.AssemblyDefinition != null)
				rd.WriteAssemblyHeader(assembly.AssemblyDefinition);
			if (decompileMod) {
				output.WriteLine();
				rd.WriteModuleHeader(assembly.ModuleDefinition);
				if (options.FullDecompilation) {
					output.WriteLine();
					output.WriteLine();
					rd.WriteModuleContents(assembly.ModuleDefinition);
				}
			}
		}
Ejemplo n.º 26
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + assembly.FileName);
            output.WriteLine();

            var dis = CreateDisassembler(output, options);

            if (options.FullDecompilation)
            {
                dis.WriteAssemblyReferences(assembly.ModuleDefinition);
            }
            if (assembly.AssemblyDefinition != null)
            {
                dis.WriteAssemblyHeader(assembly.AssemblyDefinition);
            }
            output.WriteLine();
            dis.WriteModuleHeader(assembly.ModuleDefinition);
            if (options.FullDecompilation)
            {
                output.WriteLine();
                output.WriteLine();
                dis.WriteModuleContents(assembly.ModuleDefinition);
            }
        }
Ejemplo n.º 27
0
        void WriteProject(LoadedAssembly loadedAssembly, Language language, string targetDirectory, CancellationToken ct)
        {
            targetDirectory = Path.Combine(targetDirectory, loadedAssembly.ShortName);
            string projectFileName = Path.Combine(targetDirectory, loadedAssembly.ShortName + language.ProjectFileExtension);

            if (!Directory.Exists(targetDirectory))
            {
                try {
                    Directory.CreateDirectory(targetDirectory);
                } catch (Exception e) {
                    statusOutput.Add($"Failed to create a directory '{targetDirectory}':{Environment.NewLine}{e}");
                    return;
                }
            }

            try {
                using (var projectFileWriter = new StreamWriter(projectFileName)) {
                    var projectFileOutput = new PlainTextOutput(projectFileWriter);
                    var options           = new DecompilationOptions()
                    {
                        FullDecompilation      = true,
                        CancellationToken      = ct,
                        SaveAsProjectDirectory = targetDirectory
                    };

                    var projectInfo = language.DecompileAssembly(loadedAssembly, projectFileOutput, options);
                    if (projectInfo != null)
                    {
                        projects.Add(new ProjectItem(projectFileName, projectInfo.PlatformName, projectInfo.Guid, projectInfo.TypeGuid));
                    }
                }
            } catch (Exception e) when(!(e is OperationCanceledException))
            {
                statusOutput.Add($"Failed to decompile the assembly '{loadedAssembly.FileName}':{Environment.NewLine}{e}");
            }
        }
Ejemplo n.º 28
0

        
Ejemplo n.º 29
0
        DebugProcessVM CreateDebugProcessVM(LoadedAssembly asm = null)
        {
            // Re-use the previous one if it's the same file
            if (lastDebugProcessVM != null && asm != null) {
                if (StringComparer.OrdinalIgnoreCase.Equals(lastDebugProcessVM.Filename, asm.FileName))
                    return lastDebugProcessVM.Clone();
            }

            var vm = new DebugProcessVM();
            if (asm != null)
                vm.Filename = asm.FileName;
            vm.BreakProcessType = DebuggerSettings.Instance.BreakProcessType;
            return vm;
        }
Ejemplo n.º 30
0
 public ILSpyWholeProjectDecompiler(LoadedAssembly assembly, DecompilationOptions options)
 {
     this.assembly = assembly;
     this.options  = options;
     base.Settings = options.DecompilerSettings;
 }
Ejemplo n.º 31
0
 public static void NotifyModifiedAssembly(LoadedAssembly asm)
 {
     MainWindow.Instance.ModuleModified(asm);
 }
Ejemplo n.º 32
0
 public LoadedAssembly(LoadedAssembly bundle, string fileName, Task <Stream?>?stream, IAssemblyResolver?assemblyResolver = null)
     : this(bundle.assemblyList, fileName, stream, assemblyResolver)
 {
     this.ParentBundle = bundle;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// 1) try to find exact match by tfm + full asm name in loaded assemblies
        /// 2) try to find match in search paths
        /// 3) if a.deps.json is found: search %USERPROFILE%/.nuget/packages/* as well
        /// 4) look in /dotnet/shared/{runtime-pack}/{closest-version}
        /// 5) if the version is retargetable or all zeros or ones, search C:\Windows\Microsoft.NET\Framework64\v4.0.30319
        /// 6) For "mscorlib.dll" we use the exact same assembly with which ILSpy runs
        /// 7) Search the GAC
        /// 8) search C:\Windows\Microsoft.NET\Framework64\v4.0.30319
        /// 9) try to find match by asm name (no tfm/version) in loaded assemblies
        /// </summary>
        LoadedAssembly LookupReferencedAssemblyInternal(IAssemblyReference fullName, bool isWinRT, string tfm)
        {
            string key = tfm + ";" + (isWinRT ? fullName.Name : fullName.FullName);

            string         file;
            LoadedAssembly asm;

            lock (loadingAssemblies)
            {
                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    var module = loaded.GetPEFileOrNull();
                    var reader = module?.Metadata;
                    if (reader == null || !reader.IsAssembly)
                    {
                        continue;
                    }
                    var asmDef     = reader.GetAssemblyDefinition();
                    var asmDefName = loaded.GetTargetFrameworkIdAsync().Result + ";" + (isWinRT ? reader.GetString(asmDef.Name) : reader.GetFullAssemblyName());
                    if (key.Equals(asmDefName, StringComparison.OrdinalIgnoreCase))
                    {
                        LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.FullName, MessageKind.Info, "Success - Found in Assembly List");
                        return(loaded);
                    }
                }

                if (universalResolver == null)
                {
                    universalResolver = new MyUniversalResolver(this);
                }

                file = universalResolver.FindAssemblyFile(fullName);

                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    if (loaded.FileName.Equals(file, StringComparison.OrdinalIgnoreCase))
                    {
                        return(loaded);
                    }
                }

                if (file != null && loadingAssemblies.TryGetValue(file, out asm))
                {
                    return(asm);
                }

                if (assemblyLoadDisableCount > 0)
                {
                    return(null);
                }

                if (file != null)
                {
                    LoadedAssemblyReferencesInfo.AddMessage(fullName.ToString(), MessageKind.Info, "Success - Loading from: " + file);
                    asm = new LoadedAssembly(assemblyList, file)
                    {
                        IsAutoLoaded = true
                    };
                }
                else
                {
                    var candidates = new List <(LoadedAssembly assembly, Version version)>();

                    foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                    {
                        var module = loaded.GetPEFileOrNull();
                        var reader = module?.Metadata;
                        if (reader == null || !reader.IsAssembly)
                        {
                            continue;
                        }
                        var asmDef     = reader.GetAssemblyDefinition();
                        var asmDefName = reader.GetString(asmDef.Name);
                        if (fullName.Name.Equals(asmDefName, StringComparison.OrdinalIgnoreCase))
                        {
                            candidates.Add((loaded, asmDef.Version));
                        }
                    }

                    if (candidates.Count == 0)
                    {
                        LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.ToString(), MessageKind.Error, "Could not find reference: " + fullName);
                        return(null);
                    }

                    candidates.SortBy(c => c.version);

                    var bestCandidate = candidates.FirstOrDefault(c => c.version >= fullName.Version).assembly ?? candidates.Last().assembly;
                    LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.ToString(), MessageKind.Info, "Success - Found in Assembly List with different TFM or version: " + bestCandidate.fileName);
                    return(bestCandidate);
                }
                loadingAssemblies.Add(file, asm);
            }
            App.Current.Dispatcher.BeginInvoke((Action) delegate() {
                lock (assemblyList.assemblies)
                {
                    assemblyList.assemblies.Add(asm);
                }
                lock (loadingAssemblies)
                {
                    loadingAssemblies.Remove(file);
                }
            }, DispatcherPriority.Normal);
            return(asm);
        }
Ejemplo n.º 34
0
			public MyAssemblyResolver(LoadedAssembly parent)
			{
				this.parent = parent;
			}
Ejemplo n.º 35
0
		public virtual void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
		{
			WriteCommentLine(output, assembly.FileName);
			WriteCommentLine(output, assembly.AssemblyDefinition.FullName);
		}
Ejemplo n.º 36
0
 LoadedAssembly DelayLoadAssembly(LoadedAssembly newAsm, int index, bool canDispose)
 {
     System.Diagnostics.Debug.Assert(!string.IsNullOrWhiteSpace(newAsm.FileName));
     bool startThread;
     lock (delayLoadedAsms) {
         Tuple<LoadedAssembly, int> info;
         if (delayLoadedAsms.TryGetValue(newAsm.FileName, out info)) {
             if (canDispose)
                 newAsm.TheLoadedFile.Dispose();
             return info.Item1;
         }
         delayLoadedAsms.Add(newAsm.FileName, Tuple.Create(newAsm, index));
         startThread = delayLoadedAsms.Count == 1;
     }
     if (startThread)
         App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => DelayLoadAssemblyMainThread()));
     return newAsm;
 }
Ejemplo n.º 37
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            var module = assembly.GetPEFileOrNull();

            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                var decompiler = new ILSpyWholeProjectDecompiler(assembly, options);
                decompiler.DecompileProject(module, options.SaveAsProjectDirectory, new TextOutputWriter(output), options.CancellationToken);
            }
            else
            {
                AddReferenceAssemblyWarningMessage(module, output);
                AddReferenceWarningMessage(module, output);
                output.WriteLine();
                base.DecompileAssembly(assembly, output, options);

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
                    IAssemblyResolver assemblyResolver = assembly.GetAssemblyResolver();
                    var typeSystem = new DecompilerTypeSystem(module, assemblyResolver, options.DecompilerSettings);
                    var globalType = typeSystem.MainModule.TypeDefinitions.FirstOrDefault();
                    if (globalType != null)
                    {
                        output.Write("// Global type: ");
                        output.WriteReference(globalType, globalType.FullName);
                        output.WriteLine();
                    }
                    var metadata         = module.Metadata;
                    var corHeader        = module.Reader.PEHeaders.CorHeader;
                    var entrypointHandle = MetadataTokenHelpers.EntityHandleOrNil(corHeader.EntryPointTokenOrRelativeVirtualAddress);
                    if (!entrypointHandle.IsNil && entrypointHandle.Kind == HandleKind.MethodDefinition)
                    {
                        var entrypoint = typeSystem.MainModule.ResolveMethod(entrypointHandle, new Decompiler.TypeSystem.GenericContext());
                        if (entrypoint != null)
                        {
                            output.Write("// Entry point: ");
                            output.WriteReference(entrypoint, entrypoint.DeclaringType.FullName + "." + entrypoint.Name);
                            output.WriteLine();
                        }
                    }
                    output.WriteLine("// Architecture: " + GetPlatformDisplayName(module));
                    if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.ILOnly) == 0)
                    {
                        output.WriteLine("// This assembly contains unmanaged code.");
                    }
                    string runtimeName = GetRuntimeDisplayName(module);
                    if (runtimeName != null)
                    {
                        output.WriteLine("// Runtime: " + runtimeName);
                    }
                    var debugInfo = assembly.GetDebugInfoOrNull();
                    if (debugInfo != null)
                    {
                        output.WriteLine("// Debug info: " + debugInfo.Description);
                    }
                    output.WriteLine();

                    CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings);
                    decompiler.CancellationToken = options.CancellationToken;
                    SyntaxTree st;
                    if (options.FullDecompilation)
                    {
                        st = decompiler.DecompileWholeModuleAsSingleFile();
                    }
                    else
                    {
                        st = decompiler.DecompileModuleAndAssemblyAttributes();
                    }
                    WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem);
                }
            }
        }
Ejemplo n.º 38
0
        internal LoadedAssembly OpenAssemblyInternal(string file, bool canAdd, bool isAutoLoaded, bool delay)
        {
            file = Path.GetFullPath(file);

            lock (assemblies) {
                var asm = FindAssemblyByFileName_NoLock(file);
                if (asm != null)
                    return asm;

                var newAsm = new LoadedAssembly(this, file);
                newAsm.IsAutoLoaded = isAutoLoaded;
                return ForceAddAssemblyToList(newAsm, canAdd, delay, -1, true);
            }
        }
Ejemplo n.º 39
0
 void AddToList(LoadedAssembly newAsm, int index)
 {
     if (index >= 0 && index < assemblies.Count)
         assemblies.Insert(index, newAsm);
     else
         assemblies.Add(newAsm);
 }
Ejemplo n.º 40
0
 internal void Insert_NoLock(int index, LoadedAssembly asm)
 {
     assemblies.Insert(index, asm);
 }
Ejemplo n.º 41
0
 internal int IndexOf_NoLock(LoadedAssembly asm)
 {
     return assemblies.IndexOf(asm);
 }
Ejemplo n.º 42
0
		/// <summary>
		/// Opens an assembly from disk.
		/// Returns the existing assembly node if it is already loaded.
		/// </summary>
		public LoadedAssembly OpenAssembly(string file)
		{
			App.Current.Dispatcher.VerifyAccess();
			
			file = Path.GetFullPath(file);
			
			foreach (LoadedAssembly asm in this.assemblies) {
				if (file.Equals(asm.FileName, StringComparison.OrdinalIgnoreCase))
					return asm;
			}
			
			var newAsm = new LoadedAssembly(this, file);
			lock (assemblies) {
				this.assemblies.Add(newAsm);
			}
			return newAsm;
		}
Ejemplo n.º 43
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();
				}
				output.WriteLine("// Architecture: " + GetPlatformDisplayName(mainModule));
				if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) {
					output.WriteLine("// This assembly contains unmanaged code.");
				}
				switch (mainModule.Runtime) {
					case TargetRuntime.Net_1_0:
						output.WriteLine("// Runtime: .NET 1.0");
						break;
					case TargetRuntime.Net_1_1:
						output.WriteLine("// Runtime: .NET 1.1");
						break;
					case TargetRuntime.Net_2_0:
						output.WriteLine("// Runtime: .NET 2.0");
						break;
					case TargetRuntime.Net_4_0:
						output.WriteLine("// 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);
					codeDomBuilder.RunTransformations(transformAbortCondition);
					codeDomBuilder.GenerateCode(output);
				}
			}
		}
Ejemplo n.º 44
0
 public ILSpyWholeProjectDecompiler(LoadedAssembly assembly, DecompilationOptions options)
     : base(options.DecompilerSettings, assembly.GetAssemblyResolver(), assembly.GetAssemblyReferenceClassifier(), assembly.GetDebugInfoOrNull())
 {
     this.assembly = assembly;
     this.options  = options;
 }
Ejemplo n.º 45
0
		IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories)
		{
			//AppDomain bamlDecompilerAppDomain = null;
			//try {
				foreach (EmbeddedResource r in assembly.AssemblyDefinition.MainModule.Resources.OfType<EmbeddedResource>()) {
					string fileName;
					Stream s = r.GetResourceStream();
					s.Position = 0;
					if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase)) {
						IEnumerable<DictionaryEntry> rs = null;
						try {
							rs = new ResourceSet(s).Cast<DictionaryEntry>();
						}
						catch (ArgumentException) {
						}
						if (rs != null && rs.All(e => e.Value is Stream)) {
							foreach (var pair in rs) {
								fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => TextView.DecompilerTextView.CleanUpName(p)).ToArray());
								string dirName = Path.GetDirectoryName(fileName);
								if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) {
									Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dirName));
								}
								Stream entryStream = (Stream)pair.Value;
								entryStream.Position = 0;
								if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) {
									MemoryStream ms = new MemoryStream();
									entryStream.CopyTo(ms);
									// TODO implement extension point
//									var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
//									string xaml = null;
//									try {
//										xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
//									}
//									catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
//									if (xaml != null) {
//										File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
//										yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
//										continue;
//									}
								}
								using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
									entryStream.CopyTo(fs);
								}
								yield return Tuple.Create("Resource", fileName);
							}
							continue;
						}
					}
					fileName = GetFileNameForResource(r.Name, directories);
					using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
						s.CopyTo(fs);
					}
					yield return Tuple.Create("EmbeddedResource", fileName);
				}
			//}
			//finally {
			//    if (bamlDecompilerAppDomain != null)
			//        AppDomain.Unload(bamlDecompilerAppDomain);
			//}
		}
Ejemplo n.º 46
0
		public override TreeViewNodeFilterResult GetFilterResult(string ns, LoadedAssembly owner) {
			if (owner.ModuleDefinition != module)
				return new TreeViewNodeFilterResult(FilterResult.Hidden, false);
			return new TreeViewNodeFilterResult(FilterResult.Match, false);
		}
Ejemplo n.º 47
0
        LoadedAssembly LookupReferencedAssemblyInternal(Decompiler.Metadata.IAssemblyReference fullName, bool isWinRT)
        {
            string GetName(Decompiler.Metadata.IAssemblyReference name) => isWinRT ? name.Name : name.FullName;

            string         file;
            LoadedAssembly asm;

            lock (loadingAssemblies) {
                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    var reader = loaded.GetPEFileOrNull()?.Metadata;
                    if (reader == null || !reader.IsAssembly)
                    {
                        continue;
                    }
                    var asmDef     = reader.GetAssemblyDefinition();
                    var asmDefName = isWinRT ? reader.GetString(asmDef.Name) : reader.GetFullAssemblyName();
                    if (GetName(fullName).Equals(asmDefName, StringComparison.OrdinalIgnoreCase))
                    {
                        LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.FullName, MessageKind.Info, "Success - Found in Assembly List");
                        return(loaded);
                    }
                }

                var resolver = new MyUniversalResolver(this);
                file = resolver.FindAssemblyFile(fullName);

                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    if (loaded.FileName.Equals(file, StringComparison.OrdinalIgnoreCase))
                    {
                        return(loaded);
                    }
                }

                if (file != null && loadingAssemblies.TryGetValue(file, out asm))
                {
                    return(asm);
                }

                if (assemblyLoadDisableCount > 0)
                {
                    return(null);
                }

                if (file != null)
                {
                    LoadedAssemblyReferencesInfo.AddMessage(fullName.ToString(), MessageKind.Info, "Success - Loading from: " + file);
                    asm = new LoadedAssembly(assemblyList, file)
                    {
                        IsAutoLoaded = true
                    };
                }
                else
                {
                    LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.ToString(), MessageKind.Error, "Could not find reference: " + fullName);
                    return(null);
                }
                loadingAssemblies.Add(file, asm);
            }
            App.Current.Dispatcher.BeginInvoke((Action) delegate() {
                lock (assemblyList.assemblies) {
                    assemblyList.assemblies.Add(asm);
                }
                lock (loadingAssemblies) {
                    loadingAssemblies.Remove(file);
                }
            });
            return(asm);
        }
Ejemplo n.º 48
0
			public override bool HandleModelUpdated(LoadedAssembly asm)
			{
				this.Children.RemoveAll(
					delegate(SharpTreeNode n) {
						AnalyzerTreeNode an = n as AnalyzerTreeNode;
						return an == null || !an.HandleModelUpdated(asm);
					});
				return true;
			}
Ejemplo n.º 49
0
        public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule)
        {
            bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0;
            bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0;
            output.WriteLine("// " + assembly.FileName, TextTokenType.Comment);
            if (decompileMod || decompileAsm)
                PrintEntryPoint(assembly, output);
            output.WriteLine();

            ReflectionDisassembler rd = CreateReflectionDisassembler(output, options, assembly.ModuleDefinition);
            if (decompileMod && options.FullDecompilation)
                rd.WriteAssemblyReferences(assembly.ModuleDefinition as ModuleDefMD);
            if (decompileAsm && assembly.AssemblyDefinition != null)
                rd.WriteAssemblyHeader(assembly.AssemblyDefinition);
            if (decompileMod) {
                output.WriteLine();
                rd.WriteModuleHeader(assembly.ModuleDefinition);
                if (options.FullDecompilation) {
                    output.WriteLine();
                    output.WriteLine();
                    rd.WriteModuleContents(assembly.ModuleDefinition);
                }
            }
        }
Ejemplo n.º 50
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 asmList = new AssemblyList("dnspc.exe", false);
            asmList.UseGAC = !noGac;
            asmList.AddSearchPath(Path.GetDirectoryName(fileName));
            foreach (var path in asmPaths)
                asmList.AddSearchPath(path);
            var lasm = new LoadedAssembly(asmList, 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(lasm, new PlainTextOutput(writer), opts);
            }
            finally {
                if (!useStdout && writer != null)
                    writer.Dispose();
            }
        }
Ejemplo n.º 51
0
        public override ProjectId DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
        {
            var module = assembly.GetPEFileOrNull();

            if (module == null)
            {
                return(null);
            }
            if (options.FullDecompilation && options.SaveAsProjectDirectory != null)
            {
                if (!WholeProjectDecompiler.CanUseSdkStyleProjectFormat(module))
                {
                    options.DecompilerSettings.UseSdkStyleProjectFormat = false;
                }
                var decompiler = new ILSpyWholeProjectDecompiler(assembly, options);
                return(decompiler.DecompileProject(module, options.SaveAsProjectDirectory, new TextOutputWriter(output), options.CancellationToken));
            }
            else
            {
                AddReferenceAssemblyWarningMessage(module, output);
                AddReferenceWarningMessage(module, output);
                output.WriteLine();
                base.DecompileAssembly(assembly, output, options);

                // don't automatically load additional assemblies when an assembly node is selected in the tree view
                IAssemblyResolver assemblyResolver = assembly.GetAssemblyResolver(loadOnDemand: options.FullDecompilation);
                var typeSystem = new DecompilerTypeSystem(module, assemblyResolver, options.DecompilerSettings);
                var globalType = typeSystem.MainModule.TypeDefinitions.FirstOrDefault();
                if (globalType != null)
                {
                    output.Write("// Global type: ");
                    output.WriteReference(globalType, globalType.FullName);
                    output.WriteLine();
                }
                var metadata         = module.Metadata;
                var corHeader        = module.Reader.PEHeaders.CorHeader;
                var entrypointHandle = MetadataTokenHelpers.EntityHandleOrNil(corHeader.EntryPointTokenOrRelativeVirtualAddress);
                if (!entrypointHandle.IsNil && entrypointHandle.Kind == HandleKind.MethodDefinition)
                {
                    var entrypoint = typeSystem.MainModule.ResolveMethod(entrypointHandle, new Decompiler.TypeSystem.GenericContext());
                    if (entrypoint != null)
                    {
                        output.Write("// Entry point: ");
                        output.WriteReference(entrypoint, entrypoint.DeclaringType.FullName + "." + entrypoint.Name);
                        output.WriteLine();
                    }
                }
                output.WriteLine("// Architecture: " + GetPlatformDisplayName(module));
                if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.ILOnly) == 0)
                {
                    output.WriteLine("// This assembly contains unmanaged code.");
                }
                string runtimeName = GetRuntimeDisplayName(module);
                if (runtimeName != null)
                {
                    output.WriteLine("// Runtime: " + runtimeName);
                }
                if ((corHeader.Flags & System.Reflection.PortableExecutable.CorFlags.StrongNameSigned) != 0)
                {
                    output.WriteLine("// This assembly is signed with a strong name key.");
                }
                if (module.Reader.ReadDebugDirectory().Any(d => d.Type == DebugDirectoryEntryType.Reproducible))
                {
                    output.WriteLine("// This assembly was compiled using the /deterministic option.");
                }
                if (metadata.IsAssembly)
                {
                    var asm = metadata.GetAssemblyDefinition();
                    if (asm.HashAlgorithm != AssemblyHashAlgorithm.None)
                    {
                        output.WriteLine("// Hash algorithm: " + asm.HashAlgorithm.ToString().ToUpper());
                    }
                    if (!asm.PublicKey.IsNil)
                    {
                        output.Write("// Public key: ");
                        var reader = metadata.GetBlobReader(asm.PublicKey);
                        while (reader.RemainingBytes > 0)
                        {
                            output.Write(reader.ReadByte().ToString("x2"));
                        }
                        output.WriteLine();
                    }
                }
                var debugInfo = assembly.GetDebugInfoOrNull();
                if (debugInfo != null)
                {
                    output.WriteLine("// Debug info: " + debugInfo.Description);
                }
                output.WriteLine();

                CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, options.DecompilerSettings);
                decompiler.CancellationToken = options.CancellationToken;
                if (options.EscapeInvalidIdentifiers)
                {
                    decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
                }
                SyntaxTree st;
                if (options.FullDecompilation)
                {
                    st = decompiler.DecompileWholeModuleAsSingleFile();
                }
                else
                {
                    st = decompiler.DecompileModuleAndAssemblyAttributes();
                }
                WriteCode(output, options.DecompilerSettings, st, decompiler.TypeSystem);
                return(null);
            }
        }
Ejemplo n.º 52
0
 public MyAssemblyResolver(LoadedAssembly parent)
 {
     this.parent = parent;
 }
Ejemplo n.º 53
0
        IEnumerable <Tuple <string, string> > WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet <string> directories)
        {
            //AppDomain bamlDecompilerAppDomain = null;
            //try {
            foreach (EmbeddedResource r in assembly.AssemblyDefinition.MainModule.Resources.OfType <EmbeddedResource>())
            {
                string fileName;
                Stream s = r.GetResourceStream();
                s.Position = 0;
                if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase))
                {
                    IEnumerable <DictionaryEntry> rs = null;
                    try {
                        rs = new ResourceSet(s).Cast <DictionaryEntry>();
                    }
                    catch (ArgumentException) {
                    }
                    if (rs != null && rs.All(e => e.Value is Stream))
                    {
                        foreach (var pair in rs)
                        {
                            fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => TextView.DecompilerTextView.CleanUpName(p)).ToArray());
                            string dirName = Path.GetDirectoryName(fileName);
                            if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName))
                            {
                                Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dirName));
                            }
                            Stream entryStream = (Stream)pair.Value;
                            entryStream.Position = 0;
                            if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase))
                            {
//									MemoryStream ms = new MemoryStream();
//									entryStream.CopyTo(ms);
                                // TODO implement extension point
//									var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
//									string xaml = null;
//									try {
//										xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
//									}
//									catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
//									if (xaml != null) {
//										File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
//										yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
//										continue;
//									}
                            }
                            using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
                                entryStream.CopyTo(fs);
                            }
                            yield return(Tuple.Create("Resource", fileName));
                        }
                        continue;
                    }
                }
                fileName = GetFileNameForResource(r.Name, directories);
                using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
                    s.CopyTo(fs);
                }
                yield return(Tuple.Create("EmbeddedResource", fileName));
            }
            //}
            //finally {
            //    if (bamlDecompilerAppDomain != null)
            //        AppDomain.Unload(bamlDecompilerAppDomain);
            //}
        }
Ejemplo n.º 54
0
			public RunningSearch(LoadedAssembly[] assemblies, string searchTerm, int searchMode, Language language)
			{
				this.dispatcher = Dispatcher.CurrentDispatcher;
				this.assemblies = assemblies;
				this.searchTerm = searchTerm.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
				this.language = language;
				this.searchMode = searchMode;
				
				this.Results.Add(new SearchResult { Name = "Searching..." });
			}
Ejemplo n.º 55
0
		public void Unload(LoadedAssembly assembly)
		{
			App.Current.Dispatcher.VerifyAccess();
			lock (assemblies) {
				assemblies.Remove(assembly);
			}
		}
Ejemplo n.º 56
0
 public void Unload(LoadedAssembly assembly)
 {
     if (App.Current != null)
         App.Current.Dispatcher.VerifyAccess();
     lock (assemblies) {
         assemblies.Remove(assembly);
         assembly.Dispose();
     }
     RequestGC();
 }
Ejemplo n.º 57
0
 public MyUniversalResolver(LoadedAssembly assembly)
     : base(assembly.FileName, false, assembly.GetTargetFrameworkIdAsync().Result, PEStreamOptions.PrefetchEntireImage, DecompilerSettingsPanel.CurrentDecompilerSettings.ApplyWindowsRuntimeProjections ? MetadataReaderOptions.ApplyWindowsRuntimeProjections : MetadataReaderOptions.None)
 {
 }
Ejemplo n.º 58
0
        internal LoadedAssembly AddAssembly(LoadedAssembly newAsm, bool canAdd, bool delay, bool canDispose = true)
        {
            lock (assemblies) {
                var asm = FindAssemblyByFileName_NoLock(newAsm.FileName);
                if (asm != null) {
                    if (canDispose)
                        newAsm.TheLoadedFile.Dispose();
                    return asm;
                }

                return ForceAddAssemblyToList(newAsm, canAdd, delay, -1, canDispose);
            }
        }
Ejemplo n.º 59
0
        LoadedAssembly LookupReferencedModuleInternal(PEFile mainModule, string moduleName)
        {
            string         file;
            LoadedAssembly asm;

            lock (loadingAssemblies)
            {
                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    var reader = loaded.GetPEFileOrNull()?.Metadata;
                    if (reader == null || reader.IsAssembly)
                    {
                        continue;
                    }
                    var moduleDef = reader.GetModuleDefinition();
                    if (moduleName.Equals(reader.GetString(moduleDef.Name), StringComparison.OrdinalIgnoreCase))
                    {
                        LoadedAssemblyReferencesInfo.AddMessageOnce(moduleName, MessageKind.Info, "Success - Found in Assembly List");
                        return(loaded);
                    }
                }

                file = Path.Combine(Path.GetDirectoryName(mainModule.FileName), moduleName);
                if (!File.Exists(file))
                {
                    return(null);
                }

                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    if (loaded.FileName.Equals(file, StringComparison.OrdinalIgnoreCase))
                    {
                        return(loaded);
                    }
                }

                if (file != null && loadingAssemblies.TryGetValue(file, out asm))
                {
                    return(asm);
                }

                if (assemblyLoadDisableCount > 0)
                {
                    return(null);
                }

                if (file != null)
                {
                    LoadedAssemblyReferencesInfo.AddMessage(moduleName, MessageKind.Info, "Success - Loading from: " + file);
                    asm = new LoadedAssembly(assemblyList, file)
                    {
                        IsAutoLoaded = true
                    };
                }
                else
                {
                    LoadedAssemblyReferencesInfo.AddMessageOnce(moduleName, MessageKind.Error, "Could not find reference: " + moduleName);
                    return(null);
                }
                loadingAssemblies.Add(file, asm);
            }
            App.Current.Dispatcher.BeginInvoke((Action) delegate() {
                lock (assemblyList.assemblies)
                {
                    assemblyList.assemblies.Add(asm);
                }
                lock (loadingAssemblies)
                {
                    loadingAssemblies.Remove(file);
                }
            });
            return(asm);
        }
Ejemplo n.º 60
0
        internal LoadedAssembly ForceAddAssemblyToList(LoadedAssembly newAsm, bool canAdd, bool delay, int index, bool canDispose)
        {
            if (!canAdd)
                return newAsm;

            // Happens when we start dnSpy (try with many tabs) and try to exit while it's still
            // decompiling and the decompiler resolves a reference.
            if (App.Current == null && MainWindow.Instance != null)
                return newAsm;

            if (App.Current == null)
                delay = false;
            else if (!App.Current.CheckAccess())
                delay = true;

            // Sometimes the treeview will completely mess up if we immediately add the asm.
            // Wait a little while for the treeview to finish its things before we add it.
            if (delay)
                return DelayLoadAssembly(newAsm, index, canDispose);
            AddToList(newAsm, index);
            return newAsm;
        }