GetAssemblies() public method

Gets the loaded assemblies. This method is thread-safe.
public GetAssemblies ( ) : ICSharpCode.ILSpy.LoadedAssembly[]
return ICSharpCode.ILSpy.LoadedAssembly[]
Beispiel #1
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ILSpySettings spySettings = this.spySettings;

            this.spySettings = null;

            // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
            // This makes the UI come up a bit faster.
            this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);

            HandleCommandLineArguments(App.CommandLineArguments);

            if (assemblyList.GetAssemblies().Length == 0 &&
                assemblyList.ListName == AssemblyListManager.DefaultListName)
            {
                LoadInitialAssemblies();
            }

            ShowAssemblyList(this.assemblyList);

            if (sessionSettings.ActiveAutoLoadedAssembly != null)
            {
                this.assemblyList.Open(sessionSettings.ActiveAutoLoadedAssembly, true);
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => OpenAssemblies(spySettings)));
#if DEBUG
            this.Title = $"ILSpy {RevisionClass.FullVersion}";
#endif
        }
        LoadedAssembly LookupReferencedAssemblyInternal(string fullName)
        {
            foreach (LoadedAssembly asm in assemblyList.GetAssemblies())
            {
                if (asm.AssemblyDefinition != null && fullName.Equals(asm.AssemblyDefinition.FullName, StringComparison.OrdinalIgnoreCase))
                {
                    return(asm);
                }
            }
            if (assemblyLoadDisableCount > 0)
            {
                return(null);
            }

#if !CORE
            if (!App.Current.Dispatcher.CheckAccess())
            {
                // Call this method on the GUI thread.
                return((LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func <string, LoadedAssembly>(LookupReferencedAssembly), fullName));
            }
#endif

            var    name = AssemblyNameReference.Parse(fullName);
            string file = GacInterop.FindAssemblyInNetGac(name);
            if (file == null)
            {
                string dir = Path.GetDirectoryName(this.fileName);
                if (File.Exists(Path.Combine(dir, name.Name + ".dll")))
                {
                    file = Path.Combine(dir, name.Name + ".dll");
                }
                else if (File.Exists(Path.Combine(dir, name.Name + ".exe")))
                {
                    file = Path.Combine(dir, name.Name + ".exe");
                }
            }
            if (file != null)
            {
                return(assemblyList.OpenAssembly(file));
            }
            else
            {
                return(null);
            }
        }
Beispiel #3
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ILSpySettings spySettings = this.spySettings;

            this.spySettings = null;

            // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
            // This makes the UI come up a bit faster.
            this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);

            HandleCommandLineArguments(App.CommandLineArguments);

            if (assemblyList.GetAssemblies().Length == 0 &&
                assemblyList.ListName == AssemblyListManager.DefaultListName)
            {
                LoadInitialAssemblies();
            }

            ShowAssemblyList(this.assemblyList);

            HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
            if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1)
            {
                SharpTreeNode node = null;
                if (sessionSettings.ActiveTreeViewPath != null)
                {
                    node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
                    if (node == this.assemblyListTreeNode && sessionSettings.ActiveAutoLoadedAssembly != null)
                    {
                        this.assemblyList.Open(sessionSettings.ActiveAutoLoadedAssembly, true);
                        node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
                    }
                }
                if (node != null)
                {
                    SelectNode(node);

                    // only if not showing the about page, perform the update check:
                    ShowMessageIfUpdatesAvailableAsync(spySettings);
                }
                else
                {
                    AboutPage.Display(decompilerTextView);
                }
            }

            AvalonEditTextOutput output = new AvalonEditTextOutput();

            if (FormatExceptions(App.StartupExceptions.ToArray(), output))
            {
                decompilerTextView.ShowText(output);
            }
        }
Beispiel #4
0
        LoadedAssembly LookupReferencedAssemblyInternal(string fullName)
        {
            foreach (LoadedAssembly asm in assemblyList.GetAssemblies())
            {
                var asmDef = asm.GetAssemblyDefinitionAsync().Result;
                if (asmDef != null && fullName.Equals(asmDef.FullName, StringComparison.OrdinalIgnoreCase))
                {
                    return(asm);
                }
            }
            if (assemblyLoadDisableCount > 0)
            {
                return(null);
            }

            if (!App.Current.Dispatcher.CheckAccess())
            {
                // Call this method on the GUI thread.
                return((LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func <string, LoadedAssembly>(LookupReferencedAssembly), fullName));
            }

            var resolver = new MyUniversalResolver(this)
            {
                TargetFramework = GetTargetFrameworkIdAsync().Result
            };
            var name = AssemblyNameReference.Parse(fullName);
            var file = resolver.Resolve(name);

            if (file != null)
            {
                loadedAssemblyReferences.AddMessage(fullName, MessageKind.Info, "Success - Loading from: " + file.MainModule.FileName);
                return(assemblyList.OpenAssembly(file.MainModule.FileName, true));
            }
            else
            {
                loadedAssemblyReferences.AddMessage(fullName, MessageKind.Error, "Could not find reference: " + fullName);
                return(null);
            }
        }
Beispiel #5
0
            public MyAssemblyResolver(LoadedAssembly parent, bool loadOnDemand)
            {
                this.parent       = parent;
                this.loadOnDemand = loadOnDemand;

                this.providedAssemblyResolver = parent.providedAssemblyResolver;
                this.assemblyList             = parent.assemblyList;
                // Note: we cache a copy of the assembly list in the constructor, so that the
                // resolve calls only search-by-asm-name in the assemblies that were already loaded
                // at the time of the GetResolver() call.
                this.alreadyLoadedAssemblies = assemblyList.GetAssemblies();
                // If we didn't do this, we'd also search in the assemblies that we just started to load
                // in previous Resolve() calls; but we don't want to wait for those to be loaded.
                this.tfmTask           = parent.GetTargetFrameworkIdAsync();
                this.referenceLoadInfo = parent.LoadedAssemblyReferencesInfo;
            }
Beispiel #6
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            DockWorkspace.Instance.Documents.Add(new DecompiledDocumentModel()
            {
                Language        = CurrentLanguage,
                LanguageVersion = CurrentLanguageVersion
            });
            DockWorkspace.Instance.ActiveDocument = DockWorkspace.Instance.Documents.First();

            ILSpySettings spySettings = this.spySettingsForMainWindow_Loaded;

            this.spySettingsForMainWindow_Loaded = null;
            var loadPreviousAssemblies = Options.MiscSettingsPanel.CurrentMiscSettings.LoadPreviousAssemblies;

            if (loadPreviousAssemblies)
            {
                // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
                // This makes the UI come up a bit faster.
                this.assemblyList = assemblyListManager.LoadList(sessionSettings.ActiveAssemblyList);
            }
            else
            {
                this.assemblyList = new AssemblyList(AssemblyListManager.DefaultListName);
                assemblyListManager.ClearAll();
            }

            HandleCommandLineArguments(App.CommandLineArguments);

            if (assemblyList.GetAssemblies().Length == 0 &&
                assemblyList.ListName == AssemblyListManager.DefaultListName &&
                loadPreviousAssemblies)
            {
                LoadInitialAssemblies();
            }

            ShowAssemblyList(this.assemblyList);

            if (sessionSettings.ActiveAutoLoadedAssembly != null)
            {
                this.assemblyList.Open(sessionSettings.ActiveAutoLoadedAssembly, true);
            }

            Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => OpenAssemblies(spySettings)));
        }
Beispiel #7
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ILSpySettings spySettings = this.spySettings;

            this.spySettings = null;

            // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
            // This makes the UI come up a bit faster.
            this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);

            HandleCommandLineArguments(App.CommandLineArguments);

            if (assemblyList.GetAssemblies().Length == 0 &&
                assemblyList.ListName == AssemblyListManager.DefaultListName)
            {
                LoadInitialAssemblies();
            }

            ShowAssemblyList(this.assemblyList);

            HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);

            if (App.CommandLineArguments.NavigateTo == null)
            {
                SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
                if (node != null)
                {
                    SelectNode(node);

                    // only if not showing the about page, perform the update check:
                    ShowMessageIfUpdatesAvailableAsync(spySettings);
                }
                else
                {
                    AboutPage.Display(decompilerTextView);
                }
            }

            //Fires the OnLoaded notification to the plugins
            foreach (var x in applicationLifeCycleInterceptors)
            {
                x.Value.OnLoaded();
            }
        }
Beispiel #8
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ILSpySettings spySettings = this.spySettings;

            this.spySettings = null;

            // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
            // This makes the UI come up a bit faster.
            this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);

            ShowAssemblyList(this.assemblyList);

            string[] args = Environment.GetCommandLineArgs();
            for (int i = 1; i < args.Length; i++)
            {
                assemblyList.OpenAssembly(args[i]);
            }
            if (assemblyList.GetAssemblies().Length == 0)
            {
                LoadInitialAssemblies();
            }

            SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);

            if (node != null)
            {
                SelectNode(node);

                // only if not showing the about page, perform the update check:
                ShowMessageIfUpdatesAvailableAsync(spySettings);
            }
            else
            {
                AboutPage.Display(decompilerTextView);
            }
        }
Beispiel #9
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);
        }
Beispiel #10
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ILSpySettings spySettings = this.spySettings;
            this.spySettings = null;

            // Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
            // This makes the UI come up a bit faster.
            this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);

            ShowAssemblyList(this.assemblyList);

            string[] args = Environment.GetCommandLineArgs();
            for (int i = 1; i < args.Length; i++) {
                assemblyList.OpenAssembly(args[i]);
            }
            if (assemblyList.GetAssemblies().Length == 0)
                LoadInitialAssemblies();

            SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
            if (node != null) {
                SelectNode(node);

                // only if not showing the about page, perform the update check:
                ShowMessageIfUpdatesAvailableAsync(spySettings);
            } else {
                AboutPage.Display(decompilerTextView);
            }
        }
Beispiel #11
0
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
		    this.Opacity = 0;

			ILSpySettings spySettings = this.spySettings;
			this.spySettings = null;
			
			// Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
			// This makes the UI come up a bit faster.
			this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
			
			HandleCommandLineArguments(App.CommandLineArguments);
			
			if (assemblyList.GetAssemblies().Length == 0
			    && assemblyList.ListName == AssemblyListManager.DefaultListName)
			{
				LoadInitialAssemblies();
			}
			
			ShowAssemblyList(this.assemblyList);
			
			HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
			
			if (App.CommandLineArguments.NavigateTo == null) {
				SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
				if (node != null) {
					SelectNode(node);
					
					// only if not showing the about page, perform the update check:
					ShowMessageIfUpdatesAvailableAsync(spySettings);
				} else {
					AboutPage.Display(decompilerTextView);
				}
			}

		    searchBox.DataContext = SearchPane.Instance;

            // setting the opacity to 0 and then using this code to set it back to 1 is kind of a hack to get 
            // around a problem where the window doesn't render properly when using the shell integration library
            // but it works, and it looks nice
		    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.Opacity = 1));
		}
Beispiel #12
0
        async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSpySettings spySettings, List <LoadedAssembly> relevantAssemblies)
        {
            var initialSelection = treeView.SelectedItem;

            if (navigateTo != null)
            {
                bool found = false;
                if (navigateTo.StartsWith("N:", StringComparison.Ordinal))
                {
                    string namespaceName = navigateTo.Substring(2);
                    foreach (LoadedAssembly asm in relevantAssemblies)
                    {
                        AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
                        if (asmNode != null)
                        {
                            // FindNamespaceNode() blocks the UI if the assembly is not yet loaded,
                            // so use an async wait instead.
                            await asm.GetPEFileAsync().Catch <Exception>(ex => { });

                            NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
                            if (nsNode != null)
                            {
                                found = true;
                                if (treeView.SelectedItem == initialSelection)
                                {
                                    SelectNode(nsNode);
                                }
                                break;
                            }
                        }
                    }
                }
                else if (navigateTo == "none")
                {
                    // Don't navigate anywhere; start empty.
                    // Used by ILSpy VS addin, it'll send us the real location to navigate to via IPC.
                    found = true;
                }
                else
                {
                    IEntity mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies));

                    if (mr != null && mr.ParentModule.PEFile != null)
                    {
                        found = true;
                        if (treeView.SelectedItem == initialSelection)
                        {
                            JumpToReference(mr);
                        }
                    }
                }
                if (!found && treeView.SelectedItem == initialSelection)
                {
                    AvalonEditTextOutput output = new AvalonEditTextOutput();
                    output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", navigateTo));
                    decompilerTextView.ShowText(output);
                }
            }
            else if (relevantAssemblies.Count == 1)
            {
                // NavigateTo == null and an assembly was given on the command-line:
                // Select the newly loaded assembly
                AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]);
                if (asmNode != null && treeView.SelectedItem == initialSelection)
                {
                    SelectNode(asmNode);
                }
            }
            else if (spySettings != null)
            {
                SharpTreeNode node = null;
                if (activeTreeViewPath?.Length > 0)
                {
                    foreach (var asm in assemblyList.GetAssemblies())
                    {
                        if (asm.FileName == activeTreeViewPath[0])
                        {
                            // FindNodeByPath() blocks the UI if the assembly is not yet loaded,
                            // so use an async wait instead.
                            await asm.GetPEFileAsync().Catch <Exception>(ex => { });
                        }
                    }
                    node = FindNodeByPath(activeTreeViewPath, true);
                }
                if (treeView.SelectedItem == initialSelection)
                {
                    if (node != null)
                    {
                        SelectNode(node);

                        // only if not showing the about page, perform the update check:
                        await ShowMessageIfUpdatesAvailableAsync(spySettings);
                    }
                    else
                    {
                        AboutPage.Display(decompilerTextView);
                    }
                }
            }
        }
Beispiel #13
0
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			ILSpySettings spySettings = this.spySettings;
			this.spySettings = null;
			
			// Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
			// This makes the UI come up a bit faster.
			this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
			
			HandleCommandLineArguments(App.CommandLineArguments);
			
			if (assemblyList.GetAssemblies().Length == 0
			    && assemblyList.ListName == AssemblyListManager.DefaultListName)
			{
				LoadInitialAssemblies();
			}
			
			ShowAssemblyList(this.assemblyList);
			
			HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
			
			if (App.CommandLineArguments.NavigateTo == null) {
				SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
				if (node != null) {
					SelectNode(node);
					
					// only if not showing the about page, perform the update check:
					ShowMessageIfUpdatesAvailableAsync(spySettings);
				} else {
					AboutPage.Display(decompilerTextView);
				}
			}

            //Fires the OnLoaded notification to the plugins
            foreach (var x in applicationLifeCycleInterceptors)
                x.Value.OnLoaded();
		}
Beispiel #14
0
        void LoadingHandler(int i)
        {
            switch (i) {
            case 0:
                this.CommandBindings.Add(new CommandBinding(ILSpyTreeNode.TreeNodeActivatedEvent, TreeNodeActivatedExecuted));

                ContextMenuProvider.Add(treeView);

                ILSpySettings spySettings = this.spySettings;
                this.spySettings = null;

                this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
                break;

            case 1:
                HandleCommandLineArguments(App.CommandLineArguments);

                if (assemblyList.GetAssemblies().Length == 0
                    && assemblyList.ListName == AssemblyListManager.DefaultListName) {
                    LoadInitialAssemblies();
                }

                ShowAssemblyListDontAskUser(this.assemblyList);
                break;

            case 2:
                HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
                if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1) {
                    if (ICSharpCode.ILSpy.Options.DisplaySettingsPanel.CurrentDisplaySettings.RestoreTabsAtStartup) {
                        RestoreTabGroups(sessionSettings.SavedTabGroupsState);
                        if (!sessionSettings.TabsFound)
                            AboutPage.Display(SafeActiveTextView);
                    }
                    else {
                        AboutPage.Display(SafeActiveTextView);
                    }
                }
                break;

            case 3:
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                if (FormatExceptions(App.StartupExceptions.ToArray(), output))
                    SafeActiveTextView.ShowText(output);

                if (topPane.Content == null) {
                    var pane = GetPane(topPane, sessionSettings.TopPaneSettings.Name);
                    if (pane != null)
                        ShowInTopPane(pane.PaneTitle, pane);
                }
                if (bottomPane.Content == null) {
                    var pane = GetPane(bottomPane, sessionSettings.BottomPaneSettings.Name);
                    if (pane != null)
                        ShowInBottomPane(pane.PaneTitle, pane);
                }
                break;

            case 4:
                foreach (var plugin in plugins)
                    plugin.OnLoaded();

                var list = callWhenLoaded;
                callWhenLoaded = null;
                foreach (var func in list)
                    func();

                break;

            case 5:
                this.IsEnabled = true;

                // Make sure that when no tabs are created that we have focus. If we don't do this we
                // can't press Ctrl+K and open the asm search.
                this.Focus();

                // Sometimes we get keyboard focus when it's better that the text editor gets the focus instead
                this.GotKeyboardFocus += MainWindow_GotKeyboardFocus;

                loadingControl.Visibility = Visibility.Collapsed;
                mainGrid.Visibility = Visibility.Visible;

                // In case a plugin has added their own bindings
                UninstallTabCommandBindings(ActiveTabState);
                InstallTabCommandBindings(ActiveTabState);

                // Flickering workaround fix. Could reproduce it when using VMWare + WinXP
                loadingProgressBar.IsIndeterminate = false;
                return;
            default:
                return;
            }
            StartLoadingHandler(i + 1);
        }
Beispiel #15
0
		public static void Main (string[] args)
		{

			string appPath = null;
			string slnName = null;
			string libPath = null;
			string expOpt = null;
			string outLanguageType = LAN_TYPE_CSHARP;
			DecompilerSettings ds = new DecompilerSettings ();
			ds.AnonymousMethods = true;
			ds.AsyncAwait = true;
			ds.YieldReturn = true;
			string onlyDecomileClassName = null;

			List<string> onlyDecompilingFileNameList = new List<string> ();
			//parsing args
			foreach (string x in args) {

				if (x.StartsWith ("-")) {
					switch (x) {
					case "-n":
					case "-l":
					case "-t":
					case "-C":
					case "-D":
						expOpt = x;
						continue;
					
					default:

						if (x.StartsWith ("-")) {

							if (x.Length < 2) {
								Console.WriteLine (" Unexpected options " + x);
								showUsage ();
								return;
							}

							for (int i = 0; i < x.Length; i++) {
								if (!praseDecompileSetting (x [i], ds)) {
									Console.WriteLine (" Unexpected options " + x);
									showUsage ();
									return;
								}

							}
							continue;
						} 

						break;
					}

				} else if (expOpt != null) {

					switch (expOpt) {
					case "-n":
						slnName = x;
						expOpt = null;
						break;
					case "-l":
						libPath = x;
						expOpt = null;
						break;
					case "-t":
						if (x != LAN_TYPE_CSHARP && x != LAN_TYPE_IL) {
							Console.WriteLine (" Unexpected Output language type: " + x);
							showUsage ();
							return;
						}
						outLanguageType = x;
						expOpt = null;
						break;
					case "-C":
						onlyDecomileClassName = x;
						expOpt = null;
						break;
					case "-D":
						onlyDecompilingFileNameList.Add (x);
						break;
					default:
						showUsage ();
						expOpt = null;
						return;
					
					}


				} else {
					if (appPath == null) {
						appPath = x;
						continue;
					} else {
						Console.WriteLine (" Unexpected options " + x);
						showUsage ();
						return;
					}
				}
					
			}


			if (appPath == null) {
			
				Console.WriteLine ("directory/to/all/your/dll missing");
				showUsage ();
				return;
			}

			if (slnName == null && outLanguageType==LAN_TYPE_CSHARP) {

				Console.WriteLine ("Solution Name missing");
				showUsage ();
				return;
			}


			Console.WriteLine ("Decompiling all dll in  " + appPath);
			Console.WriteLine ("Please wait...");

			DirectoryInfo di = new DirectoryInfo(appPath);
			appPath = di.FullName;
			FileInfo[] dllFileInfoList = di.GetFiles("*.dll");
			FileInfo[] exeFileInfoList = di.GetFiles ("*.exe");


			AssemblyList asmlist = new AssemblyList ("mylistname");

			foreach (var dllfile in dllFileInfoList)
			{
				bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList);
				asmlist.OpenAssembly (dllfile.FullName,!bDecompile);
			}

			foreach (var dllfile in exeFileInfoList)
			{
				bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList);

				asmlist.OpenAssembly (dllfile.FullName,!bDecompile);
			}


			if (libPath != null) {
				di = new DirectoryInfo(libPath);
				libPath = di.FullName;
				dllFileInfoList = di.GetFiles("*.dll");
				foreach (var dllfile in dllFileInfoList) {
					asmlist.OpenAssembly (dllfile.FullName,true);
				}
			}
			


			StringBuilder projSln = new StringBuilder ();
			projSln.Append ("Microsoft Visual Studio Solution File, Format Version 11.00\n# Visual Studio 2010\n");

			StringBuilder globSec = new StringBuilder ();
			Guid slnProjGuid =  Guid.NewGuid();

			int num = 0;
			LoadedAssembly [] ls = asmlist.GetAssemblies ();
			var decompilationOptions = new DecompilationOptions ();
			decompilationOptions.FullDecompilation = true;
			decompilationOptions.assenmlyList = asmlist;
			decompilationOptions.DecompilerSettings = ds;
			decompilationOptions.IncludedClassName = onlyDecomileClassName;

			if(outLanguageType==LAN_TYPE_CSHARP)
			{
				foreach (LoadedAssembly asm in ls) {
					if (asm.IsAutoLoaded)
						continue;




					string projectPath = appPath + "/"+ asm.ShortName;
					if(!Directory.Exists(projectPath))
					{
						Directory.CreateDirectory (projectPath);
					}
					string projectFileName = projectPath + "/" + asm.ShortName + ".csproj";
					asm.ProjectGuid = Guid.NewGuid();
					asm.ProjectFileName = projectFileName;
				}
			}



			foreach (LoadedAssembly asm in ls) {
				num++;
				Console.WriteLine(asm.FileName + " " + num+"/"+ls.Length);
				if (asm.IsAutoLoaded)
					continue;

				if(outLanguageType==LAN_TYPE_CSHARP)
				{
					var csharpLanguage = new CSharpLanguage ();
					var textOutput = new PlainTextOutput ();
					decompilationOptions.SaveAsProjectDirectory =  appPath + "/"+ asm.ShortName;

					csharpLanguage.DecompileAssembly (asm, textOutput, decompilationOptions);
					File.WriteAllText (asm.ProjectFileName, textOutput.ToString ());

					
					Guid createdProjGuid = asm.ProjectGuid;
					
					projSln.Append("   Project(\"{");
					projSln.Append (slnProjGuid.ToString());
					projSln.Append ("}\") = \"");
					projSln.Append (asm.ShortName);
					projSln.Append ("\", \"");
					projSln.Append (asm.ShortName+"/"+ asm.ShortName + ".csproj");
					projSln.Append ("\", \"{");
					projSln.Append (createdProjGuid.ToString());
					projSln.Append ("}\"\n");
					projSln.Append("EndProject\n");

					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Debug|Any CPU.Build.0 = Debug|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Release|Any CPU.ActiveCfg = Release|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Release|Any CPU.Build.0 = Release|Any CPU\n");
				}
				else
				{
					var ilLanguage = new ILLanguage(true);
					var textOutput = new PlainTextOutput ();
					ilLanguage.DecompileAssembly (asm, textOutput, decompilationOptions);
					string ilFileName = appPath + "/"+ asm.ShortName+".il";
					File.WriteAllText(ilFileName,textOutput.ToString());
				}

			}

			if (outLanguageType == LAN_TYPE_CSHARP) {
				projSln.Append ("Global\n");
				projSln.Append ("GlobalSection(SolutionConfigurationPlatforms) = preSolution\n");
				projSln.Append ("\t\t\t\tDebug|Any CPU = Debug|Any CPU\n");
				projSln.Append ("\t\t\t\tRelease|Any CPU = Release|Any CPU\n");
				projSln.Append ("EndGlobalSection\n");

				projSln.Append ("GlobalSection(ProjectConfigurationPlatforms) = postSolution\n");
				projSln.Append (globSec.ToString ());
				projSln.Append ("EndGlobalSection\n");

				projSln.Append ("GlobalSection(MonoDevelopProperties) = preSolution\n");
				projSln.Append ("\nEndGlobalSection\n");
				projSln.Append ("EndGlobal\n\t\t");

				string slnFileName = appPath + "/" + slnName + ".sln";
				File.WriteAllText (slnFileName, projSln.ToString ());
			}
		

		}
Beispiel #16
0
        private LoadedAssembly LookupReferencedAssemblyInternal(AssemblyNameReference fullName, bool isWinRT)
        {
            string GetName(AssemblyNameReference name) => isWinRT ? name.Name : name.FullName;

            string         file;
            LoadedAssembly asm;

            lock (loadingAssemblies) {
                foreach (LoadedAssembly loaded in assemblyList.GetAssemblies())
                {
                    var asmDef = loaded.GetAssemblyDefinitionOrNull();
                    if (asmDef != null && GetName(fullName).Equals(GetName(asmDef.Name), StringComparison.OrdinalIgnoreCase))
                    {
                        LoadedAssemblyReferencesInfo.AddMessageOnce(fullName.ToString(), MessageKind.Info, "Success - Found in Assembly List");
                        return(loaded);
                    }
                }

                if (isWinRT)
                {
                    file = Path.Combine(Environment.SystemDirectory, "WinMetadata", fullName.Name + ".winmd");
                }
                else
                {
                    var resolver = new MyUniversalResolver(this)
                    {
                        TargetFramework = GetTargetFrameworkIdAsync().Result
                    };
                    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);
        }
Beispiel #17
0
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			ILSpySettings spySettings = this.spySettings;
			this.spySettings = null;
			
			// Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
			// This makes the UI come up a bit faster.
			this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
			
			HandleCommandLineArguments(App.CommandLineArguments);
			
			if (assemblyList.GetAssemblies().Length == 0
				&& assemblyList.ListName == AssemblyListManager.DefaultListName)
			{
				LoadInitialAssemblies();
			}
			
			ShowAssemblyList(this.assemblyList);
			
			HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
			if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1) {
				SharpTreeNode node = null;
				if (sessionSettings.ActiveTreeViewPath != null) {
					node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
					if (node == this.assemblyListTreeNode & sessionSettings.ActiveAutoLoadedAssembly != null) {
						this.assemblyList.OpenAssembly(sessionSettings.ActiveAutoLoadedAssembly, true);
						node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
					}
				}
				if (node != null) {
					SelectNode(node);
					
					// only if not showing the about page, perform the update check:
					ShowMessageIfUpdatesAvailableAsync(spySettings);
				} else {
					AboutPage.Display(decompilerTextView);
				}
			}
			
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			if (FormatExceptions(App.StartupExceptions.ToArray(), output))
				decompilerTextView.ShowText(output);
		}
Beispiel #18
0
        LoadedAssembly LookupReferencedAssemblyInternal(string fullName)
        {
            foreach (LoadedAssembly asm in assemblyList.GetAssemblies())
            {
                if (asm.AssemblyDefinition != null && fullName.Equals(asm.AssemblyDefinition.FullName, StringComparison.OrdinalIgnoreCase))
                {
                    return(asm);
                }
            }
            if (assemblyLoadDisableCount > 0)
            {
                return(null);
            }

            if (!App.Current.Dispatcher.CheckAccess())
            {
                // Call this method on the GUI thread.
                return((LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func <string, LoadedAssembly>(LookupReferencedAssembly), fullName));
            }

            var    targetFramework = TargetFrameworkId.Split(new[] { ",Version=v" }, StringSplitOptions.None);
            var    name            = AssemblyNameReference.Parse(fullName);
            string file            = null;

            switch (targetFramework[0])
            {
            case ".NETCoreApp":
            case ".NETStandard":
                if (targetFramework.Length != 2)
                {
                    break;
                }
                if (dotNetCorePathFinder == null)
                {
                    var version = targetFramework[1].Length == 3 ? targetFramework[1] + ".0" : targetFramework[1];
                    dotNetCorePathFinder = new DotNetCorePathFinder(fileName, TargetFrameworkId, version, this.loadedAssemblyReferences);
                }
                file = dotNetCorePathFinder.TryResolveDotNetCore(name);
                break;

            default:
                file = GacInterop.FindAssemblyInNetGac(name);
                break;
            }
            if (file == null)
            {
                string dir = Path.GetDirectoryName(this.fileName);
                if (File.Exists(Path.Combine(dir, name.Name + ".dll")))
                {
                    file = Path.Combine(dir, name.Name + ".dll");
                }
                else if (File.Exists(Path.Combine(dir, name.Name + ".exe")))
                {
                    file = Path.Combine(dir, name.Name + ".exe");
                }
            }
            if (file != null)
            {
                loadedAssemblyReferences.AddMessage(fullName, MessageKind.Info, "Success - Loading from: " + file);
                return(assemblyList.OpenAssembly(file, true));
            }
            else
            {
                loadedAssemblyReferences.AddMessage(fullName, MessageKind.Error, "Could not find reference: " + fullName);
                return(null);
            }
        }
Beispiel #19
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);
        }
Beispiel #20
0
		void ShowAssemblyList(AssemblyList assemblyList)
		{
			history.Clear();
			this.assemblyList = assemblyList;

			if (assemblyList.GetAssemblies().Length == 0
			    && assemblyList.ListName == AssemblyListManager.DefaultListName)
			{
				LoadInitialAssemblies();
			}

			assemblyList.assemblies.CollectionChanged += assemblyList_Assemblies_CollectionChanged;
			
			assemblyListTreeNode = new AssemblyListTreeNode(assemblyList);
			assemblyListTreeNode.FilterSettings = sessionSettings.FilterSettings.Clone();
			assemblyListTreeNode.Select = SelectNode;
			treeView.Root = assemblyListTreeNode;
			
			if (assemblyList.ListName == AssemblyListManager.DefaultListName)
				this.Title = "ILSpy";
			else
				this.Title = "ILSpy - " + assemblyList.ListName;
		}