HotPatchBundleLoader.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using Cysharp.Threading.Tasks;
  6. using UnityEngine;
  7. namespace HotPatch
  8. {
  9. public static class HotPatchBundleLoader
  10. {
  11. public static readonly IReadOnlyList<string> AotAssemblyNames = Array.AsReadOnly(new[]
  12. { "mscorlib.dll", "Newtonsoft.Json.dll", "System.Core.dll", "UniTask.dll" });
  13. public static async UniTask<AssetBundle> LoadAsync(string path, string kind, CancellationToken ct)
  14. {
  15. ct.ThrowIfCancellationRequested();
  16. HotPatchLog.Info("bundle_load_start kind=" + kind + " path=" + path);
  17. var bundle = await AssetBundle.LoadFromFileAsync(path).ToUniTask();
  18. if (ct.IsCancellationRequested)
  19. {
  20. if (bundle != null) bundle.Unload(true);
  21. ct.ThrowIfCancellationRequested();
  22. }
  23. if (bundle == null) throw new InvalidDataException("Failed to load AssetBundle: " + path);
  24. HotPatchLog.Info("bundle_load_complete kind=" + kind + " name=" + bundle.name);
  25. return bundle;
  26. }
  27. public static async UniTask<byte[]> ReadDllAsync(AssetBundle bundle, string dllName, CancellationToken ct,
  28. HotPatchResource expected = null)
  29. {
  30. ct.ThrowIfCancellationRequested();
  31. var assetName = dllName + ".bytes";
  32. var asset = await bundle.LoadAssetAsync<TextAsset>(assetName).ToUniTask() as TextAsset;
  33. ct.ThrowIfCancellationRequested();
  34. if (asset == null) throw new InvalidDataException("DLL missing from bundle: " + assetName);
  35. var bytes = asset.bytes;
  36. if (expected != null && (bytes.LongLength != expected.size ||
  37. !string.Equals(HotPatchHash.Of(bytes), expected.sha256, StringComparison.OrdinalIgnoreCase)))
  38. throw new InvalidDataException("DLL verification failed inside bundle: " + dllName);
  39. HotPatchLog.Info("bundle_dll_read name=" + dllName + " bytes=" + bytes.Length);
  40. return bytes;
  41. }
  42. }
  43. }