LoadedAssembly.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System;
  19. using System.IO;
  20. using System.Threading.Tasks;
  21. //using System.Windows.Threading;
  22. //using ICSharpCode.ILSpy.Options;
  23. using Mono.Cecil;
  24. namespace ICSharpCode.ILSpy
  25. {
  26. /// <summary>
  27. /// Represents an assembly loaded into ILSpy.
  28. /// </summary>
  29. public sealed class LoadedAssembly
  30. {
  31. readonly Task<ModuleDefinition> assemblyTask;
  32. readonly AssemblyList assemblyList;
  33. readonly string fileName;
  34. readonly string shortName;
  35. public Guid ProjectGuid{ get; set;}
  36. public string ProjectFileName{ get; set; }
  37. public LoadedAssembly(AssemblyList assemblyList, string fileName, Stream stream = null)
  38. {
  39. if (assemblyList == null)
  40. throw new ArgumentNullException("assemblyList");
  41. if (fileName == null)
  42. throw new ArgumentNullException("fileName");
  43. this.assemblyList = assemblyList;
  44. this.fileName = fileName;
  45. this.assemblyTask = Task.Factory.StartNew<ModuleDefinition>(LoadAssembly, stream); // requires that this.fileName is set
  46. this.shortName = Path.GetFileNameWithoutExtension(fileName);
  47. }
  48. /// <summary>
  49. /// Gets the Cecil ModuleDefinition.
  50. /// Can be null when there was a load error.
  51. /// </summary>
  52. public ModuleDefinition ModuleDefinition {
  53. get {
  54. try {
  55. return assemblyTask.Result;
  56. } catch (AggregateException) {
  57. return null;
  58. }
  59. }
  60. }
  61. /// <summary>
  62. /// Gets the Cecil AssemblyDefinition.
  63. /// Is null when there was a load error; or when opening a netmodule.
  64. /// </summary>
  65. public AssemblyDefinition AssemblyDefinition {
  66. get {
  67. var module = this.ModuleDefinition;
  68. return module != null ? module.Assembly : null;
  69. }
  70. }
  71. public AssemblyList AssemblyList {
  72. get { return assemblyList; }
  73. }
  74. public string FileName {
  75. get { return fileName; }
  76. }
  77. public string ShortName {
  78. get { return shortName; }
  79. }
  80. public string Text {
  81. get {
  82. if (AssemblyDefinition != null) {
  83. return String.Format("{0} ({1})", ShortName, AssemblyDefinition.Name.Version);
  84. } else {
  85. return ShortName;
  86. }
  87. }
  88. }
  89. public bool IsLoaded {
  90. get { return assemblyTask.IsCompleted; }
  91. }
  92. public bool HasLoadError {
  93. get { return assemblyTask.IsFaulted; }
  94. }
  95. public bool IsAutoLoaded { get; set; }
  96. ModuleDefinition LoadAssembly(object state)
  97. {
  98. var stream = state as Stream;
  99. ModuleDefinition module;
  100. // runs on background thread
  101. ReaderParameters p = new ReaderParameters();
  102. p.AssemblyResolver = new MyAssemblyResolver(this);
  103. if (stream != null)
  104. {
  105. // Read the module from a precrafted stream
  106. module = ModuleDefinition.ReadModule(stream, p);
  107. }
  108. else
  109. {
  110. // Read the module from disk (by default)
  111. module = ModuleDefinition.ReadModule(fileName, p);
  112. }
  113. //if (DecompilerSettingsPanel.CurrentDecompilerSettings.UseDebugSymbols) {
  114. // try {
  115. // LoadSymbols(module);
  116. // } catch (IOException) {
  117. // } catch (UnauthorizedAccessException) {
  118. // } catch (InvalidOperationException) {
  119. // // ignore any errors during symbol loading
  120. // }
  121. //}
  122. return module;
  123. }
  124. // private void LoadSymbols(ModuleDefinition module)
  125. // {
  126. // // search for pdb in same directory as dll
  127. // string pdbName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".pdb");
  128. // if (File.Exists(pdbName)) {
  129. // using (Stream s = File.OpenRead(pdbName)) {
  130. // module.ReadSymbols(new Mono.Cecil.Pdb.PdbReaderProvider().GetSymbolReader(module, s));
  131. // }
  132. // return;
  133. // }
  134. //
  135. // // TODO: use symbol cache, get symbols from microsoft
  136. // }
  137. [ThreadStatic]
  138. static int assemblyLoadDisableCount;
  139. public static IDisposable DisableAssemblyLoad()
  140. {
  141. assemblyLoadDisableCount++;
  142. return new DecrementAssemblyLoadDisableCount();
  143. }
  144. sealed class DecrementAssemblyLoadDisableCount : IDisposable
  145. {
  146. bool disposed;
  147. public void Dispose()
  148. {
  149. if (!disposed) {
  150. disposed = true;
  151. assemblyLoadDisableCount--;
  152. // clear the lookup cache since we might have stored the lookups failed due to DisableAssemblyLoad()
  153. //MainWindow.Instance.CurrentAssemblyList.ClearCache();
  154. }
  155. }
  156. }
  157. sealed class MyAssemblyResolver : IAssemblyResolver
  158. {
  159. readonly LoadedAssembly parent;
  160. public MyAssemblyResolver(LoadedAssembly parent)
  161. {
  162. this.parent = parent;
  163. }
  164. public AssemblyDefinition Resolve(AssemblyNameReference name)
  165. {
  166. var node = parent.LookupReferencedAssembly(name);
  167. return node != null ? node.AssemblyDefinition : null;
  168. }
  169. public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
  170. {
  171. var node = parent.LookupReferencedAssembly(name);
  172. return node != null ? node.AssemblyDefinition : null;
  173. }
  174. public AssemblyDefinition Resolve(string fullName)
  175. {
  176. var node = parent.LookupReferencedAssembly(fullName);
  177. return node != null ? node.AssemblyDefinition : null;
  178. }
  179. public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
  180. {
  181. var node = parent.LookupReferencedAssembly(fullName);
  182. return node != null ? node.AssemblyDefinition : null;
  183. }
  184. }
  185. public IAssemblyResolver GetAssemblyResolver()
  186. {
  187. return new MyAssemblyResolver(this);
  188. }
  189. public LoadedAssembly LookupReferencedAssembly(AssemblyNameReference name)
  190. {
  191. if (name == null)
  192. throw new ArgumentNullException("name");
  193. if (name.IsWindowsRuntime) {
  194. return assemblyList.winRTMetadataLookupCache.GetOrAdd(name.Name, LookupWinRTMetadata);
  195. } else {
  196. return assemblyList.assemblyLookupCache.GetOrAdd(name.FullName, LookupReferencedAssemblyInternal);
  197. }
  198. }
  199. public LoadedAssembly LookupReferencedAssembly(string fullName)
  200. {
  201. return assemblyList.assemblyLookupCache.GetOrAdd(fullName, LookupReferencedAssemblyInternal);
  202. }
  203. LoadedAssembly LookupReferencedAssemblyInternal(string fullName)
  204. {
  205. foreach (LoadedAssembly asm in assemblyList.GetAssemblies()) {
  206. if (asm.AssemblyDefinition != null && fullName.Equals(asm.AssemblyDefinition.FullName, StringComparison.OrdinalIgnoreCase))
  207. return asm;
  208. }
  209. if (assemblyLoadDisableCount > 0)
  210. return null;
  211. // if (!App.Current.Dispatcher.CheckAccess()) {
  212. // // Call this method on the GUI thread.
  213. // return (LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func<string, LoadedAssembly>(LookupReferencedAssembly), fullName);
  214. // }
  215. var name = AssemblyNameReference.Parse(fullName);
  216. string file = null; // GacInterop.FindAssemblyInNetGac(name);
  217. if (file == null) {
  218. string dir = Path.GetDirectoryName(this.fileName);
  219. if (File.Exists(Path.Combine(dir, name.Name + ".dll")))
  220. file = Path.Combine(dir, name.Name + ".dll");
  221. else if (File.Exists(Path.Combine(dir, name.Name + ".exe")))
  222. file = Path.Combine(dir, name.Name + ".exe");
  223. }
  224. if (file != null) {
  225. var loaded = assemblyList.OpenAssembly(file, true);
  226. return loaded;
  227. } else {
  228. return null;
  229. }
  230. }
  231. LoadedAssembly LookupWinRTMetadata(string name)
  232. {
  233. foreach (LoadedAssembly asm in assemblyList.GetAssemblies()) {
  234. if (asm.AssemblyDefinition != null && name.Equals(asm.AssemblyDefinition.Name.Name, StringComparison.OrdinalIgnoreCase))
  235. return asm;
  236. }
  237. if (assemblyLoadDisableCount > 0)
  238. return null;
  239. // if (!App.Current.Dispatcher.CheckAccess()) {
  240. // // Call this method on the GUI thread.
  241. // return (LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func<string, LoadedAssembly>(LookupWinRTMetadata), name);
  242. // }
  243. string file = Path.Combine(Environment.SystemDirectory, "WinMetadata", name + ".winmd");
  244. if (File.Exists(file)) {
  245. return assemblyList.OpenAssembly(file, true);
  246. } else {
  247. return null;
  248. }
  249. }
  250. public Task ContinueWhenLoaded(Action<Task<ModuleDefinition>> onAssemblyLoaded, TaskScheduler taskScheduler)
  251. {
  252. return this.assemblyTask.ContinueWith(onAssemblyLoaded, taskScheduler);
  253. }
  254. /// <summary>
  255. /// Wait until the assembly is loaded.
  256. /// Throws an AggregateException when loading the assembly fails.
  257. /// </summary>
  258. public void WaitUntilLoaded()
  259. {
  260. assemblyTask.Wait();
  261. }
  262. }
  263. }