HotPatchService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 synchronize = true;
  51. #if UNITY_EDITOR
  52. synchronize = settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl);
  53. #endif
  54. HotPatchLocalResources local = null;
  55. if (synchronize)
  56. {
  57. var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null);
  58. local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri,
  59. Path.Combine(Application.temporaryCachePath, "HotUpdate"), assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName);
  60. progress?.Invoke(new HotPatchProgress("Loading resources", .82f));
  61. var aotBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.BundledManifest.aotBundle), "aot", cancellationToken);
  62. try
  63. {
  64. foreach (var aot in local.BundledManifest.aotMetadata)
  65. {
  66. var bytes = await HotPatchBundleLoader.ReadDllAsync(aotBundle, aot.name, cancellationToken, aot);
  67. #if !UNITY_EDITOR
  68. if (loadedMetadata.Contains(aot.name)) continue;
  69. HotPatchLog.Info($"aot_load_start name={aot.name} bytes={bytes.Length}");
  70. var result = RuntimeApi.LoadMetadataForAOTAssembly(bytes, HomologousImageMode.SuperSet);
  71. HotPatchLog.Info($"aot_load_result name={aot.name} result={result}");
  72. if (result != LoadImageErrorCode.OK)
  73. throw new InvalidOperationException("Failed to load AOT metadata: " + aot.name + " / " + result);
  74. loadedMetadata.Add(aot.name);
  75. #endif
  76. }
  77. }
  78. finally { aotBundle.Unload(true); }
  79. progress?.Invoke(new HotPatchProgress("Loading resources", .87f));
  80. var dllBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.AssemblyResource), "assembly", cancellationToken);
  81. try
  82. {
  83. var bytes = await HotPatchBundleLoader.ReadDllAsync(dllBundle, assemblyName + ".dll", cancellationToken);
  84. #if !UNITY_EDITOR
  85. if (AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == assemblyName))
  86. throw new InvalidOperationException("The hot patch assembly was loaded prematurely. Rebuild the host application.");
  87. RequiresRestart = true;
  88. HotPatchLog.Info($"assembly_load_start name={assemblyName} version={local.Manifest.version} bundleSha256={local.Manifest.AssemblyResource.sha256}");
  89. LoadedAssembly = Assembly.Load(bytes);
  90. if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidDataException("The DLL assembly name inside the bundle is incorrect.");
  91. LoadedVersion = local.Manifest.version;
  92. HotPatchLog.Info($"assembly_load_complete name={assemblyName} version={LoadedVersion}");
  93. #else
  94. HotPatchLog.Info("editor_bundle_verified version=" + local.Manifest.version + " execution=editor-local");
  95. #endif
  96. }
  97. finally { dllBundle.Unload(true); }
  98. }
  99. #if UNITY_EDITOR
  100. LoadedAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName)
  101. ?? throw new InvalidOperationException("Sync sources and wait for compilation to finish first.");
  102. LoadedVersion = "editor-local";
  103. #endif
  104. RequiresRestart = true;
  105. #if !UNITY_EDITOR
  106. progress?.Invoke(new HotPatchProgress("Loading resources", .91f));
  107. InvokeInitialization(LoadedAssembly);
  108. #endif
  109. if (local != null)
  110. {
  111. progress?.Invoke(new HotPatchProgress("Loading resources", .93f));
  112. sceneBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.SceneResource), "scene", cancellationToken);
  113. var paths = sceneBundle.GetAllScenePaths();
  114. LoadedScenePath = paths.SingleOrDefault(p => string.Equals(p, local.Manifest.gameScenePath, StringComparison.OrdinalIgnoreCase))
  115. ?? throw new InvalidDataException("The scene bundle does not contain the game scene specified in the manifest: " + local.Manifest.gameScenePath);
  116. HotPatchLog.Info("scene_bundle_ready path=" + LoadedScenePath);
  117. }
  118. #if UNITY_EDITOR
  119. else
  120. {
  121. var paths = UnityEditor.AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(UnityEditor.AssetDatabase.GUIDToAssetPath)
  122. .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray();
  123. if (paths.Length != 1) throw new InvalidOperationException("The local game scene is missing or its name is not unique: " + sceneName);
  124. LoadedScenePath = paths[0];
  125. HotPatchLog.Info("editor_local_scene path=" + LoadedScenePath);
  126. }
  127. #endif
  128. initialized = true;
  129. RequiresRestart = false;
  130. progress?.Invoke(new HotPatchProgress("Loading resources", .95f));
  131. HotPatchLog.Info("load_complete assembly=" + assemblyName + " version=" + LoadedVersion);
  132. return LoadedAssembly;
  133. }
  134. catch (Exception e)
  135. {
  136. if (sceneBundle != null) sceneBundle.Unload(false);
  137. sceneBundle = null; LoadedScenePath = null;
  138. HotPatchLog.Warning($"load_failed assembly={assemblyName} requiresRestart={RequiresRestart} type={e.GetType().Name} reason={e.Message}");
  139. throw;
  140. }
  141. finally { busy = false; }
  142. }
  143. public static void InvokeInitialization(Assembly assembly)
  144. {
  145. if (assembly == null) throw new ArgumentNullException(nameof(assembly));
  146. var methods = assembly.GetTypes()
  147. .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
  148. .Select(m => new { Method = m, Attribute = m.GetCustomAttribute<HotPatchInitializerAttribute>(false) })
  149. .Where(m => m.Attribute != null)
  150. .OrderBy(m => m.Attribute.Order)
  151. .ThenBy(m => m.Method.DeclaringType.FullName, StringComparer.Ordinal)
  152. .ThenBy(m => m.Method.Name, StringComparer.Ordinal).ToArray();
  153. foreach (var item in methods)
  154. {
  155. var method = item.Method;
  156. if (!method.IsStatic || method.ContainsGenericParameters || method.ReturnType != typeof(void) ||
  157. method.GetParameters().Length != 0 || method.IsAbstract ||
  158. (method.Attributes & MethodAttributes.PinvokeImpl) != 0 ||
  159. method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false))
  160. throw new InvalidOperationException("[HotPatchInitializer] must be a non-generic, parameterless, non-async static void method: " + method.DeclaringType.FullName + "." + method.Name);
  161. }
  162. foreach (var item in methods)
  163. {
  164. try
  165. {
  166. HotPatchLog.Info("initializer_start method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
  167. item.Method.Invoke(null, null);
  168. HotPatchLog.Info("initializer_complete method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name);
  169. }
  170. catch (TargetInvocationException e)
  171. { throw new InvalidOperationException("Hot patch initialization failed: " + item.Method.DeclaringType.FullName + "." + item.Method.Name, e.InnerException ?? e); }
  172. }
  173. }
  174. public static void MarkEntryFailed() => RequiresRestart = true;
  175. static string CurrentPlatform()
  176. {
  177. #if UNITY_EDITOR
  178. return UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString();
  179. #else
  180. switch (Application.platform)
  181. {
  182. case RuntimePlatform.WindowsPlayer: return "StandaloneWindows64";
  183. case RuntimePlatform.Android: return "Android";
  184. case RuntimePlatform.IPhonePlayer: return "iOS";
  185. case RuntimePlatform.OSXPlayer: return "StandaloneOSX";
  186. case RuntimePlatform.LinuxPlayer: return "StandaloneLinux64";
  187. default: throw new PlatformNotSupportedException("Hot patches are not configured for this platform.");
  188. }
  189. #endif
  190. }
  191. }
  192. }