using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Cysharp.Threading.Tasks; using HybridCLR; using UnityEngine; namespace HotPatch { public static class HotPatchService { public static Assembly LoadedAssembly { get; private set; } public static bool RequiresRestart { get; private set; } public static string LoadedVersion { get; private set; } public static string LoadedScenePath { get; private set; } static AssetBundle sceneBundle; static bool busy, initialized; static readonly HashSet loadedMetadata = new HashSet(); [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void ResetEditorSession() { if (sceneBundle != null) sceneBundle.Unload(false); sceneBundle = null; LoadedScenePath = null; LoadedAssembly = null; LoadedVersion = null; RequiresRestart = busy = initialized = false; loadedMetadata.Clear(); } public static UniTask LoadAndInitializeAsync(Action progress, CancellationToken cancellationToken) => LoadAndInitializeAsync(AppSettings.RequireHotPatchAssemblyName(), progress, cancellationToken); public static async UniTask LoadAndInitializeAsync(string assemblyName, Action progress, CancellationToken cancellationToken) { if (busy) throw new InvalidOperationException("A hot patch is already loading."); if (RequiresRestart) throw new InvalidOperationException("The assembly has already been loaded. Restart the app before retrying."); if (initialized) { if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidOperationException("A different hot patch assembly is already loaded in this process."); HotPatchLog.Info("assembly_reuse name=" + assemblyName + " version=" + LoadedVersion); return LoadedAssembly; } busy = true; try { await UniTask.SwitchToMainThread(cancellationToken); HotPatchLog.Info($"load_start assembly={assemblyName} platform={CurrentPlatform()} appVersion={Application.version} unity={Application.unityVersion}"); var settings = Resources.Load("AppSettings"); var sceneName = AppSettings.RequireGameSceneName(); bool localOnly = settings != null && settings.UseLocalHotPatchResources; bool synchronize = true; #if UNITY_EDITOR synchronize = localOnly || settings != null && !string.IsNullOrWhiteSpace(settings.DownloadUrl); #endif HotPatchLocalResources local = null; if (synchronize) { var cache = Path.Combine(Application.temporaryCachePath, "HotUpdate"); if (localOnly) { HotPatchLog.Info("local_test_start source=StreamingAssets remote_updates=disabled"); local = await HotPatchResourceStore.LoadBundledAsync(HotPatchResourceStore.StreamingManifestUri(), cache, assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName); } else { var manifestUri = HotPatchResourceStore.RemoteManifestUri(settings != null ? settings.DownloadUrl : null); local = await HotPatchResourceStore.SynchronizeAsync(HotPatchResourceStore.StreamingManifestUri(), manifestUri, cache, assemblyName, CurrentPlatform(), progress, cancellationToken, sceneName); } progress?.Invoke(new HotPatchProgress("Loading resources", .82f)); var aotBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.BundledManifest.aotBundle), "aot", cancellationToken); try { foreach (var aot in local.BundledManifest.aotMetadata) { var bytes = await HotPatchBundleLoader.ReadDllAsync(aotBundle, aot.name, cancellationToken, aot); #if !UNITY_EDITOR if (loadedMetadata.Contains(aot.name)) continue; HotPatchLog.Info($"aot_load_start name={aot.name} bytes={bytes.Length}"); var result = RuntimeApi.LoadMetadataForAOTAssembly(bytes, HomologousImageMode.SuperSet); HotPatchLog.Info($"aot_load_result name={aot.name} result={result}"); if (result != LoadImageErrorCode.OK) throw new InvalidOperationException("Failed to load AOT metadata: " + aot.name + " / " + result); loadedMetadata.Add(aot.name); #endif } } finally { aotBundle.Unload(true); } progress?.Invoke(new HotPatchProgress("Loading resources", .87f)); var dllBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.AssemblyResource), "assembly", cancellationToken); try { var bytes = await HotPatchBundleLoader.ReadDllAsync(dllBundle, assemblyName + ".dll", cancellationToken); #if !UNITY_EDITOR if (AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == assemblyName)) throw new InvalidOperationException("The hot patch assembly was loaded prematurely. Rebuild the host application."); RequiresRestart = true; HotPatchLog.Info($"assembly_load_start name={assemblyName} version={local.Manifest.version} bundleSha256={local.Manifest.AssemblyResource.sha256}"); LoadedAssembly = Assembly.Load(bytes); if (LoadedAssembly.GetName().Name != assemblyName) throw new InvalidDataException("The DLL assembly name inside the bundle is incorrect."); LoadedVersion = local.Manifest.version; HotPatchLog.Info($"assembly_load_complete name={assemblyName} version={LoadedVersion}"); #else HotPatchLog.Info("editor_bundle_verified version=" + local.Manifest.version + " execution=editor-local"); #endif } finally { dllBundle.Unload(true); } } #if UNITY_EDITOR LoadedAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(a => a.GetName().Name == assemblyName) ?? throw new InvalidOperationException("Sync sources and wait for compilation to finish first."); LoadedVersion = "editor-local"; #endif RequiresRestart = true; #if !UNITY_EDITOR progress?.Invoke(new HotPatchProgress("Loading resources", .91f)); InvokeInitialization(LoadedAssembly); #endif if (local != null) { progress?.Invoke(new HotPatchProgress("Loading resources", .93f)); sceneBundle = await HotPatchBundleLoader.LoadAsync(local.GetPath(local.Manifest.SceneResource), "scene", cancellationToken); var paths = sceneBundle.GetAllScenePaths(); LoadedScenePath = paths.SingleOrDefault(p => string.Equals(p, local.Manifest.gameScenePath, StringComparison.OrdinalIgnoreCase)) ?? throw new InvalidDataException("The scene bundle does not contain the game scene specified in the manifest: " + local.Manifest.gameScenePath); HotPatchLog.Info("scene_bundle_ready path=" + LoadedScenePath); } #if UNITY_EDITOR else { var paths = UnityEditor.AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }).Select(UnityEditor.AssetDatabase.GUIDToAssetPath) .Where(p => Path.GetFileNameWithoutExtension(p) == sceneName).ToArray(); if (paths.Length != 1) throw new InvalidOperationException("The local game scene is missing or its name is not unique: " + sceneName); LoadedScenePath = paths[0]; HotPatchLog.Info("editor_local_scene path=" + LoadedScenePath); } #endif initialized = true; RequiresRestart = false; progress?.Invoke(new HotPatchProgress("Loading resources", .95f)); HotPatchLog.Info("load_complete assembly=" + assemblyName + " version=" + LoadedVersion); return LoadedAssembly; } catch (Exception e) { if (sceneBundle != null) sceneBundle.Unload(false); sceneBundle = null; LoadedScenePath = null; HotPatchLog.Warning($"load_failed assembly={assemblyName} requiresRestart={RequiresRestart} type={e.GetType().Name} reason={e.Message}"); throw; } finally { busy = false; } } public static void InvokeInitialization(Assembly assembly) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); var methods = assembly.GetTypes() .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly)) .Select(m => new { Method = m, Attribute = m.GetCustomAttribute(false) }) .Where(m => m.Attribute != null) .OrderBy(m => m.Attribute.Order) .ThenBy(m => m.Method.DeclaringType.FullName, StringComparer.Ordinal) .ThenBy(m => m.Method.Name, StringComparer.Ordinal).ToArray(); foreach (var item in methods) { var method = item.Method; if (!method.IsStatic || method.ContainsGenericParameters || method.ReturnType != typeof(void) || method.GetParameters().Length != 0 || method.IsAbstract || (method.Attributes & MethodAttributes.PinvokeImpl) != 0 || method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute), false)) throw new InvalidOperationException("[HotPatchInitializer] must be a non-generic, parameterless, non-async static void method: " + method.DeclaringType.FullName + "." + method.Name); } foreach (var item in methods) { try { HotPatchLog.Info("initializer_start method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name); item.Method.Invoke(null, null); HotPatchLog.Info("initializer_complete method=" + item.Method.DeclaringType.FullName + "." + item.Method.Name); } catch (TargetInvocationException e) { throw new InvalidOperationException("Hot patch initialization failed: " + item.Method.DeclaringType.FullName + "." + item.Method.Name, e.InnerException ?? e); } } } public static void MarkEntryFailed() => RequiresRestart = true; static string CurrentPlatform() { #if UNITY_EDITOR return UnityEditor.EditorUserBuildSettings.activeBuildTarget.ToString(); #else switch (Application.platform) { case RuntimePlatform.WindowsPlayer: return "StandaloneWindows64"; case RuntimePlatform.Android: return "Android"; case RuntimePlatform.IPhonePlayer: return "iOS"; case RuntimePlatform.OSXPlayer: return "StandaloneOSX"; case RuntimePlatform.LinuxPlayer: return "StandaloneLinux64"; default: throw new PlatformNotSupportedException("Hot patches are not configured for this platform."); } #endif } } }