OpenAssembly() public method

Opens an assembly from disk. Returns the existing assembly node if it is already loaded.
public OpenAssembly ( string file, bool isAutoLoaded = false ) : LoadedAssembly
file string
isAutoLoaded bool
return LoadedAssembly
示例#1
0
 void LoadInitialAssemblies()
 {
     // Called when loading an empty assembly list; so that
     // the user can see something initially.
     System.Reflection.Assembly[] initialAssemblies =
     {
         typeof(object).Assembly,
         typeof(Uri).Assembly,
         typeof(System.Linq.Enumerable).Assembly,
         typeof(System.Xml.XmlDocument).Assembly,
         typeof(System.Windows.Markup.MarkupExtension).Assembly,
         typeof(System.Windows.Rect).Assembly,
         typeof(System.Windows.UIElement).Assembly,
         typeof(System.Windows.FrameworkElement).Assembly,
         typeof(ICSharpCode.TreeView.SharpTreeView).Assembly,
         typeof(Mono.Cecil.AssemblyDefinition).Assembly,
         typeof(ICSharpCode.AvalonEdit.TextEditor).Assembly,
         typeof(ICSharpCode.Decompiler.Ast.AstBuilder).Assembly,
         typeof(MainWindow).Assembly
     };
     foreach (System.Reflection.Assembly asm in initialAssemblies)
     {
         assemblyList.OpenAssembly(asm.Location);
     }
 }
示例#2
0
 bool HandleCommandLineArguments(CommandLineArguments args)
 {
     foreach (string file in args.AssembliesToLoad)
     {
         commandLineLoadedAssemblies.Add(assemblyList.OpenAssembly(file));
     }
     if (args.Language != null)
     {
         sessionSettings.FilterSettings.Language = Languages.GetLanguage(args.Language);
     }
     return(true);
 }
示例#3
0
 private void AddToList(AssemblyList list, string FullName)
 {
     AssemblyNameInfo reference = new AssemblyNameInfo(FullName);
     string file = GacInterop.FindAssemblyInNetGac(reference);
     if (file != null)
         list.OpenAssembly(file);
 }
示例#4
0
 void LoadInitialAssemblies()
 {
     // Called when loading an empty assembly list; so that
     // the user can see something initially.
     System.Reflection.Assembly[] initialAssemblies =
     {
         typeof(object).Assembly,
         typeof(Uri).Assembly,
         typeof(System.Linq.Enumerable).Assembly,
         typeof(System.Xml.XmlDocument).Assembly,
     };
     foreach (System.Reflection.Assembly asm in initialAssemblies)
     {
         assemblyList.OpenAssembly(asm.Location);
     }
 }
示例#5
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 !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);
            }
        }
示例#6
0
        private void AddToList(AssemblyList list, string FullName)
        {
            AssemblyNameInfo reference = new AssemblyNameInfo(FullName);
            string           file      = GacInterop.FindAssemblyInNetGac(reference);

            if (file != null)
            {
                list.OpenAssembly(file);
            }
        }
        private void AddToList(AssemblyList list, string name)
        {
            //AssemblyNameReference reference = AssemblyNameReference.Parse(FullName);
            string file = typeof(string).Assembly.Location;

            if (file != null)
            {
                list.OpenAssembly(file);
            }
        }
示例#8
0
 private void LoadInitialAssemblies()
 {
     // Called when loading an empty assembly list; so that
     // the user can see something initially.
     System.Reflection.Assembly[] initialAssemblies =
     {
         typeof(object).Assembly,
         typeof(Uri).Assembly,
         typeof(System.Linq.Enumerable).Assembly,
         typeof(System.Xml.XmlDocument).Assembly,
         typeof(System.Windows.Markup.MarkupExtension).Assembly,
         typeof(System.Windows.Rect).Assembly,
         typeof(System.Windows.UIElement).Assembly,
         typeof(System.Windows.FrameworkElement).Assembly
     };
     foreach (System.Reflection.Assembly asm in initialAssemblies)
     {
         assemblyList.OpenAssembly(asm.Location);
     }
 }
示例#9
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);
            }
        }
示例#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);
            }
        }
示例#11
0
            public async Task <PEFile?> ResolveAsync(IAssemblyReference reference)
            {
                PEFile?module;

                // 0) if we're inside a package, look for filename.dll in parent directories
                if (providedAssemblyResolver != null)
                {
                    module = await providedAssemblyResolver.ResolveAsync(reference).ConfigureAwait(false);

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

                string tfm = await tfmTask.ConfigureAwait(false);

                bool   isWinRT = reference.IsWindowsRuntime;
                string key     = tfm + ";" + (isWinRT ? reference.Name : reference.FullName);

                // 1) try to find exact match by tfm + full asm name in loaded assemblies
                var lookup = LazyInit.VolatileRead(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName);

                if (lookup == null)
                {
                    lookup = await CreateLoadedAssemblyLookupAsync(shortNames : isWinRT).ConfigureAwait(false);

                    lookup = LazyInit.GetOrSet(ref isWinRT ? ref asmLookupByShortName : ref asmLookupByFullName, lookup);
                }
                if (lookup.TryGetValue(key, out module))
                {
                    referenceLoadInfo.AddMessageOnce(reference.FullName, MessageKind.Info, "Success - Found in Assembly List");
                    return(module);
                }

                string?file = parent.GetUniversalResolver().FindAssemblyFile(reference);

                if (file != null)
                {
                    // Load assembly from disk
                    LoadedAssembly?asm;
                    if (loadOnDemand)
                    {
                        asm = assemblyList.OpenAssembly(file, isAutoLoaded: true);
                    }
                    else
                    {
                        asm = assemblyList.FindAssembly(file);
                    }
                    if (asm != null)
                    {
                        referenceLoadInfo.AddMessage(reference.ToString(), MessageKind.Info, "Success - Loading from: " + file);
                        return(await asm.GetPEFileOrNullAsync().ConfigureAwait(false));
                    }
                    return(null);
                }
                else
                {
                    // Assembly not found; try to find a similar-enough already-loaded assembly
                    var candidates = new List <(LoadedAssembly assembly, Version version)>();

                    foreach (LoadedAssembly loaded in alreadyLoadedAssemblies)
                    {
                        module = await loaded.GetPEFileOrNullAsync().ConfigureAwait(false);

                        var reader = module?.Metadata;
                        if (reader == null || !reader.IsAssembly)
                        {
                            continue;
                        }
                        var asmDef     = reader.GetAssemblyDefinition();
                        var asmDefName = reader.GetString(asmDef.Name);
                        if (reference.Name.Equals(asmDefName, StringComparison.OrdinalIgnoreCase))
                        {
                            candidates.Add((loaded, asmDef.Version));
                        }
                    }

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

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

                    var bestCandidate = candidates.FirstOrDefault(c => c.version >= reference.Version).assembly ?? candidates.Last().assembly;
                    referenceLoadInfo.AddMessageOnce(reference.ToString(), MessageKind.Info, "Success - Found in Assembly List with different TFM or version: " + bestCandidate.fileName);
                    return(await bestCandidate.GetPEFileOrNullAsync().ConfigureAwait(false));
                }
            }
示例#12
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);
            }
        }
示例#13
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);
            }
        }
示例#14
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 ());
			}
		

		}
示例#15
0
		private void AddToList(AssemblyList list, string FullName)
		{
			AssemblyNameReference reference = AssemblyNameReference.Parse(FullName);
			string file = GacInterop.FindAssemblyInNetGacOrWinMetadata(reference);
			if (file != null)
				list.OpenAssembly(file);
		}