HotPatchService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading;
  7. using Cysharp.Threading.Tasks;
  8. using HybridCLR;
  9. using UnityEngine;
  10. namespace HotPatch
  11. {
  12. public static class HotPatchService
  13. {
  14. public static Assembly LoadedAssembly { get; private set; }
  15. public static bool RequiresRestart { get; private set; }
  16. public static string LoadedVersion { get; private set; }
  17. public static string LoadedScenePath { get; private set; }
  18. static AssetBundle sceneBundle;
  19. static bool busy, initialized;
  20. static readonly HashSet<string> loadedMetadata = new HashSet<string>();
  21. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  22. static void ResetEditorSession()
  23. {
  24. if (sceneBundle != null) sceneBundle.Unload(false);
  25. sceneBundle = null; LoadedScenePath = null;
  26. LoadedAssembly = null; LoadedVersion = null;
  27. RequiresRestart = busy = initialized = false;
  28. loadedMetadata.Clear();
  29. }
  30. public static UniTask<Assembly> LoadAndInitializeAsync(Action<HotPatchProgress> progress, CancellationToken cancellationToken)
  31. => LoadAndInitializeAsync(AppSettings.RequireHotPatchAssemblyName(), progress, cancellationToken);
  32. public static async UniTask<Assembly> LoadAndInitializeAsync(string assemblyName,
  33. Action<HotPatchProgress> progress, CancellationToken cancellationToken)
  34. {
  35. if (busy) throw new InvalidOperationException("A hot patch is already loading.");
  36. if (RequiresRestart) throw new InvalidOperationException("The assembly has already been loaded. Restart the app before retrying.");
  37. if (initialized)
  38. {
  39. if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidOperationException("A different hot patch assembly is already loaded in this process.");
  40. HotPatchLog.Info("assembly_reuse name=" + assemblyName + " version=" + LoadedVersion);
  41. return LoadedAssembly;
  42. }
  43. busy = true;
  44. try
  45. {
  46. await UniTask.SwitchToMainThread(cancellationToken);
  47. HotPatchLog.Info($"load_start assembly={assemblyName} platform={CurrentPlatform()} appVersion={Application.version} unity={Application.unityVersion}");
  48. var settings = Resources.Load<AppSettings>("AppSettings");
  49. var sceneName = AppSettings.RequireGameSceneName();
  50. bool localOnly = settings != null && settings.UseLocalHotPatchResources;
  51. bool synchronize = true;
  52. #if UNITY_EDITOR
  53. synchronize = localOnly || settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl);
  54. #endif
  55. HotPatchLocalResources local = null;
  56. if (synchronize)
  57. {
  58. var cache = Path.Combine(Application.temporaryCachePath, "HotUpdate");
  59. if (localOnly)
  60. {
  61. HotPatchLog.Info("local_test_start source=StreamingAssets remote_updates=disabled");
  62. local = await HotPatchResourceStore.LoadBundledAsync(HotPatchResourceStore.StreamingManifestUri(), cache,
  63. assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
  64. }
  65. else
  66. {
  67. var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null);
  68. local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri,
  69. cache, assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
  70. }
  71. progress?.Invoke(new HotPatchProgress("Loading resources", .82f));
  72. var aotBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.BundledManifest.aotBundle), "aot", cancellationToken);
  73. try
  74. {
  75. foreach (var aot in local.BundledManifest.aotMetadata)
  76. {
  77. var bytes = await HotPatchBundleLoader.ReadDllAsync(aotBundle, aot.name, cancellationToken, aot);
  78. #if !UNITY_EDITOR
  79. if (loadedMetadata.Contains(aot.name)) continue;
  80. HotPatchLog.Info($"aot_load_start name={aot.name} bytes={bytes.Length}");
  81. var result = RuntimeApi.LoadMetadataForAOTAssembly(bytes, HomologousImageMode.SuperSet);
  82. HotPatchLog.Info($"aot_load_result name={aot.name} result={result}");
  83. if (result != LoadImageErrorCode.OK)
  84. throw new InvalidOperationException("Failed to load AOT metadata: " + aot.name + " / " + result);
  85. loadedMetadata.Add(aot.name);
  86. #endif
  87. }
  88. }
  89. finally { aotBundle.Unload(true); }
  90. progress?.Invoke(new HotPatchProgress("Loading resources", .87f));
  91. var dllBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.AssemblyResource), "assembly", cancellationToken);
  92. try
  93. {
  94. var bytes = await HotPatchBundleLoader.ReadDllAsync(dllBundle, assemblyName + ".dll", cancellationToken);
  95. #if !UNITY_EDITOR
  96. if (AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == assemblyName))
  97. throw new InvalidOperationException("The hot patch assembly was loaded prematurely. Rebuild the host application.");
  98. RequiresRestart = true;
  99. HotPatchLog.Info($"assembly_load_start name={assemblyName} version={local.Manifest.version} bundleSha256={local.Manifest.AssemblyResource.sha256}");
  100. LoadedAssembly = Assembly.Load(bytes);
  101. if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidDataException("The DLL assembly name inside the bundle is incorrect.");
  102. LoadedVersion = local.Manifest.version;
  103. HotPatchLog.Info($"assembly_load_complete name={assemblyName} version={LoadedVersion}");
  104. #else
  105. HotPatchLog.Info("editor_bundle_verified version=" + local.Manifest.version + " execution=editor-local");
  106. #endif
  107. }
  108. finally { dllBundle.Unload(true); }
  109. }
  110. #if UNITY_EDITOR
  111. LoadedAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName)
  112. ?? throw new InvalidOperationException("Sync sources and wait for compilation to finish first.");
  113. LoadedVersion = "editor-local";
  114. #endif
  115. RequiresRestart = true;
  116. #if !UNITY_EDITOR
  117. progress?.Invoke(new HotPatchProgress("Loading resources", .91f));
  118. InvokeInitialization(LoadedAssembly);
  119. #endif
  120. if (local != null)
  121. {
  122. progress?.Invoke(new HotPatchProgress("Loading resources", .93f));
  123. sceneBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.SceneResource), "scene", cancellationToken);
  124. var paths = sceneBundle.GetAllScenePaths();
  125. LoadedScenePath = paths.SingleOrDefault(p => string.Equals(p, local.Manifest.gameScenePath, StringComparison.OrdinalIgnoreCase))
  126. ?? throw new InvalidDataException("The scene bundle does not contain the game scene specified in the manifest: " + local.Manifest.gameScenePath);
  127. HotPatchLog.Info("scene_bundle_ready path=" + LoadedScenePath);
  128. }
  129. #if UNITY_EDITOR
  130. else
  131. {
  132. var paths = UnityEditor.AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(UnityEditor.AssetDatabase.GUIDToAssetPath)
  133. .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray();
  134. if (paths.Length != 1) throw new InvalidOperationException("The local game scene is missing or its name is not unique: " + sceneName);
  135. LoadedScenePath = paths[0];
  136. HotPatchLog.Info("editor_local_scene path=" + LoadedScenePath);
  137. }
  138. #endif
  139. initialized = true;
  140. RequiresRestart = false;
  141. progress?.Invoke(new HotPatchProgress("Loading resources", .95f));
  142. HotPatchLog.Info("load_complete assembly=" + assemblyName + " version=" + LoadedVersion);
  143. return LoadedAssembly;
  144. }
  145. catch (Exception e)
  146. {
  147. if (sceneBundle != null) sceneBundle.Unload(false);
  148. sceneBundle = null; LoadedScenePath = null;
  149. HotPatchLog.Warning($"load_failed assembly={assemblyName} requiresRestart={RequiresRestart} type={e.GetType().Name} reason={e.Message}");
  150. throw;
  151. }
  152. finally { busy = false; }
  153. }
  154. public static void InvokeInitialization(Assembly assembly)
  155. {
  156. if (assembly == null) throw new ArgumentNullException(nameof(assembly));
  157. var methods = assembly.GetTypes()
  158. .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
  159. .Select(m => new { Method = m, Attribute = m.GetCustomAttribute<HotPatchInitializerAttribute>(false) })
  160. .Where(m => m.Attribute != null)
  161. .OrderBy(m => m.Attribute.Order)
  162. .ThenBy(m => m.Method.DeclaringType.FullName, StringComparer.Ordinal)
  163. .ThenBy(m => m.Method.Name, StringComparer.Ordinal).ToArray();
  164. foreach (var item in methods)
  165. {
  166. var method = item.Method;
  167. if (!method.IsStatic || method.ContainsGenericParameters || method.ReturnType != typeof(void) ||
  168. method.GetParameters().Length != 0 || method.IsAbstract ||
  169. (method.Attributes & MethodAttributes.PinvokeImpl) != 0 ||
  170. method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false))
  171. throw new InvalidOperationException("[HotPatchInitializer] must be a non-generic, parameterless, non-async static void method: " + method.DeclaringType.FullName + "." + method.Name);
  172. }
  173. foreach (var item in methods)
  174. {
  175. try
  176. {
  177. HotPatchLog.Info("initializer_start method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
  178. item.Method.Invoke(null, null);
  179. HotPatchLog.Info("initializer_complete method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
  180. }
  181. catch (TargetInvocationException e)
  182. { throw new InvalidOperationException("Hot patch initialization failed: " + item.Method.DeclaringType.FullName + "." + item.Method.Name, e.InnerException ?? e); }
  183. }
  184. }
  185. public static void MarkEntryFailed() => RequiresRestart = true;
  186. static string CurrentPlatform()
  187. {
  188. #if UNITY_EDITOR
  189. return UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString();
  190. #else
  191. switch (Application.platform)
  192. {
  193. case RuntimePlatform.WindowsPlayer: return "StandaloneWindows64";
  194. case RuntimePlatform.Android: return "Android";
  195. case RuntimePlatform.IPhonePlayer: return "iOS";
  196. case RuntimePlatform.OSXPlayer: return "StandaloneOSX";
  197. case RuntimePlatform.LinuxPlayer: return "StandaloneLinux64";
  198. default: throw new PlatformNotSupportedException("Hot patches are not configured for this platform.");
  199. }
  200. #endif
  201. }
  202. }
  203. }