ILPostProcessorAssemblyResolver.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. // based on paul's resolver from
  2. // https://github.com/MirageNet/Mirage/commit/def64cd1db525398738f057b3d1eb1fe8afc540c?branch=def64cd1db525398738f057b3d1eb1fe8afc540c&diff=split
  3. //
  4. // an assembly resolver's job is to open an assembly in case we want to resolve
  5. // a type from it.
  6. //
  7. // for example, while weaving MyGame.dll: if we want to resolve ArraySegment<T>,
  8. // then we need to open and resolve from another assembly (CoreLib).
  9. //
  10. // using DefaultAssemblyResolver with ILPostProcessor throws Exceptions in
  11. // WeaverTypes.cs when resolving anything, for example:
  12. // ArraySegment<T> in Mirror.Tests.Dll.
  13. //
  14. // we need a custom resolver for ILPostProcessor.
  15. #if UNITY_2020_3_OR_NEWER
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading;
  21. using Mono.CecilX;
  22. using Unity.CompilationPipeline.Common.ILPostProcessing;
  23. namespace Mirror.Weaver
  24. {
  25. class ILPostProcessorAssemblyResolver : IAssemblyResolver
  26. {
  27. readonly string[] assemblyReferences;
  28. readonly Dictionary<string, AssemblyDefinition> assemblyCache =
  29. new Dictionary<string, AssemblyDefinition>();
  30. readonly ICompiledAssembly compiledAssembly;
  31. AssemblyDefinition selfAssembly;
  32. Logger Log;
  33. public ILPostProcessorAssemblyResolver(ICompiledAssembly compiledAssembly, Logger Log)
  34. {
  35. this.compiledAssembly = compiledAssembly;
  36. assemblyReferences = compiledAssembly.References;
  37. this.Log = Log;
  38. }
  39. public void Dispose()
  40. {
  41. Dispose(true);
  42. GC.SuppressFinalize(this);
  43. }
  44. protected virtual void Dispose(bool disposing)
  45. {
  46. // Cleanup
  47. }
  48. public AssemblyDefinition Resolve(AssemblyNameReference name) =>
  49. Resolve(name, new ReaderParameters(ReadingMode.Deferred));
  50. public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
  51. {
  52. lock (assemblyCache)
  53. {
  54. if (name.Name == compiledAssembly.Name)
  55. return selfAssembly;
  56. string fileName = FindFile(name);
  57. if (fileName == null)
  58. {
  59. // returning null will throw exceptions in our weaver where.
  60. // let's make it obvious why we returned null for easier debugging.
  61. // NOTE: if this fails for "System.Private.CoreLib":
  62. // ILPostProcessorReflectionImporter fixes it!
  63. Log.Warning($"ILPostProcessorAssemblyResolver.Resolve: Failed to find file for {name}");
  64. return null;
  65. }
  66. DateTime lastWriteTime = File.GetLastWriteTime(fileName);
  67. string cacheKey = fileName + lastWriteTime;
  68. if (assemblyCache.TryGetValue(cacheKey, out AssemblyDefinition result))
  69. return result;
  70. parameters.AssemblyResolver = this;
  71. MemoryStream ms = MemoryStreamFor(fileName);
  72. string pdb = fileName + ".pdb";
  73. if (File.Exists(pdb))
  74. parameters.SymbolStream = MemoryStreamFor(pdb);
  75. AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(ms, parameters);
  76. assemblyCache.Add(cacheKey, assemblyDefinition);
  77. return assemblyDefinition;
  78. }
  79. }
  80. // find assemblyname in assembly's references
  81. string FindFile(AssemblyNameReference name)
  82. {
  83. string fileName = assemblyReferences.FirstOrDefault(r => Path.GetFileName(r) == name.Name + ".dll");
  84. if (fileName != null)
  85. return fileName;
  86. // perhaps the type comes from an exe instead
  87. fileName = assemblyReferences.FirstOrDefault(r => Path.GetFileName(r) == name.Name + ".exe");
  88. if (fileName != null)
  89. return fileName;
  90. // Unfortunately the current ICompiledAssembly API only provides direct references.
  91. // It is very much possible that a postprocessor ends up investigating a type in a directly
  92. // referenced assembly, that contains a field that is not in a directly referenced assembly.
  93. // if we don't do anything special for that situation, it will fail to resolve. We should fix this
  94. // in the ILPostProcessing API. As a workaround, we rely on the fact here that the indirect references
  95. // are always located next to direct references, so we search in all directories of direct references we
  96. // got passed, and if we find the file in there, we resolve to it.
  97. foreach (string parentDir in assemblyReferences.Select(Path.GetDirectoryName).Distinct())
  98. {
  99. string candidate = Path.Combine(parentDir, name.Name + ".dll");
  100. if (File.Exists(candidate))
  101. return candidate;
  102. }
  103. return null;
  104. }
  105. // open file as MemoryStream
  106. // attempts multiple times, not sure why..
  107. static MemoryStream MemoryStreamFor(string fileName)
  108. {
  109. return Retry(10, TimeSpan.FromSeconds(1), () =>
  110. {
  111. byte[] byteArray;
  112. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  113. {
  114. byteArray = new byte[fs.Length];
  115. int readLength = fs.Read(byteArray, 0, (int)fs.Length);
  116. if (readLength != fs.Length)
  117. throw new InvalidOperationException("File read length is not full length of file.");
  118. }
  119. return new MemoryStream(byteArray);
  120. });
  121. }
  122. static MemoryStream Retry(int retryCount, TimeSpan waitTime, Func<MemoryStream> func)
  123. {
  124. try
  125. {
  126. return func();
  127. }
  128. catch (IOException)
  129. {
  130. if (retryCount == 0)
  131. throw;
  132. Console.WriteLine($"Caught IO Exception, trying {retryCount} more times");
  133. Thread.Sleep(waitTime);
  134. return Retry(retryCount - 1, waitTime, func);
  135. }
  136. }
  137. // if the CompiledAssembly's AssemblyDefinition is known, we can add it
  138. public void SetAssemblyDefinitionForCompiledAssembly(AssemblyDefinition assemblyDefinition)
  139. {
  140. selfAssembly = assemblyDefinition;
  141. }
  142. }
  143. }
  144. #endif