krillplayer-plugin 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/LICENSE +2 -1
  2. package/README.md +1 -0
  3. package/dist/cli.js +351 -73
  4. package/dist/crypto.js +37 -11
  5. package/dist/engine/engine.c +6 -3
  6. package/kernel/Sources/CQuickJS/include/kernel_qjs.h +8 -1
  7. package/kernel/Sources/CQuickJS/kernel_internal.h +54 -0
  8. package/kernel/Sources/CQuickJS/kernel_qjs.c +17 -29
  9. package/kernel/Sources/CQuickJS/kernel_wasm.c +1155 -0
  10. package/kernel/Sources/CWAMR/include/kernel_wamr.h +151 -0
  11. package/kernel/Sources/CWAMR/include/kernel_wamr_config.h +66 -0
  12. package/kernel/Sources/CWAMR/vendor/LICENSE +219 -0
  13. package/kernel/Sources/CWAMR/vendor/core/config.h +727 -0
  14. package/kernel/Sources/CWAMR/vendor/core/iwasm/aot/aot_runtime.h +899 -0
  15. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/arch/invokeNative_general.c +123 -0
  16. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_application.c +933 -0
  17. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_blocking_op.c +92 -0
  18. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_c_api.c +5391 -0
  19. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_c_api_internal.h +246 -0
  20. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_exec_env.c +336 -0
  21. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_exec_env.h +328 -0
  22. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_loader_common.c +242 -0
  23. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_loader_common.h +62 -0
  24. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_memory.c +1999 -0
  25. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_memory.h +154 -0
  26. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_native.c +1532 -0
  27. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_native.h +117 -0
  28. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_runtime_common.c +8070 -0
  29. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_runtime_common.h +1396 -0
  30. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_shared_memory.c +477 -0
  31. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_shared_memory.h +63 -0
  32. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_suspend_flags.h +52 -0
  33. package/kernel/Sources/CWAMR/vendor/core/iwasm/compilation/aot.h +366 -0
  34. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/lib_export.h +60 -0
  35. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/wasm_c_api.h +910 -0
  36. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/wasm_export.h +2440 -0
  37. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm.h +1492 -0
  38. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_interp.h +122 -0
  39. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_interp_fast.c +7998 -0
  40. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_loader.c +16909 -0
  41. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_loader.h +80 -0
  42. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_opcode.h +1043 -0
  43. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_runtime.c +5174 -0
  44. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_runtime.h +912 -0
  45. package/kernel/Sources/CWAMR/vendor/core/iwasm/libraries/thread-mgr/thread_manager.c +1569 -0
  46. package/kernel/Sources/CWAMR/vendor/core/iwasm/libraries/thread-mgr/thread_manager.h +256 -0
  47. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_alloc.c +1169 -0
  48. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc.c +497 -0
  49. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc.h +350 -0
  50. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc_internal.h +384 -0
  51. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_hmu.c +95 -0
  52. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_kfc.c +547 -0
  53. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/mem_alloc.c +252 -0
  54. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/mem_alloc.h +96 -0
  55. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/memory/mremap.c +12 -0
  56. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_blocking_op.c +70 -0
  57. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_malloc.c +72 -0
  58. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_memmap.c +302 -0
  59. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_sleep.c +20 -0
  60. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_thread.c +784 -0
  61. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_time.c +28 -0
  62. package/kernel/Sources/CWAMR/vendor/core/shared/platform/darwin/platform_init.c +43 -0
  63. package/kernel/Sources/CWAMR/vendor/core/shared/platform/darwin/platform_internal.h +126 -0
  64. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_api_extension.h +1676 -0
  65. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_api_vmcore.h +192 -0
  66. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_common.h +204 -0
  67. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_wasi_types.h +610 -0
  68. package/kernel/Sources/CWAMR/vendor/core/shared/platform/linux/platform_init.c +43 -0
  69. package/kernel/Sources/CWAMR/vendor/core/shared/platform/linux/platform_internal.h +139 -0
  70. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_assert.c +25 -0
  71. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_assert.h +42 -0
  72. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_atomic.h +300 -0
  73. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_bitmap.c +27 -0
  74. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_bitmap.h +114 -0
  75. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_common.c +217 -0
  76. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_common.h +83 -0
  77. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_hashmap.c +339 -0
  78. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_hashmap.h +168 -0
  79. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_leb128.c +77 -0
  80. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_leb128.h +30 -0
  81. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_list.c +111 -0
  82. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_list.h +109 -0
  83. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_log.c +111 -0
  84. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_log.h +94 -0
  85. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_platform.h +38 -0
  86. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_queue.c +256 -0
  87. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_queue.h +80 -0
  88. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_vector.c +279 -0
  89. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_vector.h +126 -0
  90. package/kernel/Sources/CWAMR/vendor/core/shared/utils/gnuc.h +14 -0
  91. package/kernel/Sources/CWAMR/vendor/core/shared/utils/runtime_timer.c +469 -0
  92. package/kernel/Sources/CWAMR/vendor/core/shared/utils/runtime_timer.h +51 -0
  93. package/kernel/Sources/CWAMR/vendor/core/version.h +24 -0
  94. package/kernel/Sources/CWAMR/wamr_bh_assert.c +98 -0
  95. package/kernel/Sources/CWAMR/wamr_bh_bitmap.c +98 -0
  96. package/kernel/Sources/CWAMR/wamr_bh_common.c +98 -0
  97. package/kernel/Sources/CWAMR/wamr_bh_hashmap.c +98 -0
  98. package/kernel/Sources/CWAMR/wamr_bh_leb128.c +98 -0
  99. package/kernel/Sources/CWAMR/wamr_bh_list.c +98 -0
  100. package/kernel/Sources/CWAMR/wamr_bh_log.c +98 -0
  101. package/kernel/Sources/CWAMR/wamr_bh_queue.c +98 -0
  102. package/kernel/Sources/CWAMR/wamr_bh_vector.c +98 -0
  103. package/kernel/Sources/CWAMR/wamr_ems_alloc.c +98 -0
  104. package/kernel/Sources/CWAMR/wamr_ems_gc.c +98 -0
  105. package/kernel/Sources/CWAMR/wamr_ems_hmu.c +98 -0
  106. package/kernel/Sources/CWAMR/wamr_ems_kfc.c +98 -0
  107. package/kernel/Sources/CWAMR/wamr_invokeNative_general.c +98 -0
  108. package/kernel/Sources/CWAMR/wamr_mem_alloc.c +98 -0
  109. package/kernel/Sources/CWAMR/wamr_mremap.c +98 -0
  110. package/kernel/Sources/CWAMR/wamr_platform_init_darwin.c +100 -0
  111. package/kernel/Sources/CWAMR/wamr_platform_init_linux.c +100 -0
  112. package/kernel/Sources/CWAMR/wamr_posix_blocking_op.c +98 -0
  113. package/kernel/Sources/CWAMR/wamr_posix_malloc.c +98 -0
  114. package/kernel/Sources/CWAMR/wamr_posix_memmap.c +98 -0
  115. package/kernel/Sources/CWAMR/wamr_posix_sleep.c +98 -0
  116. package/kernel/Sources/CWAMR/wamr_posix_thread.c +98 -0
  117. package/kernel/Sources/CWAMR/wamr_posix_time.c +98 -0
  118. package/kernel/Sources/CWAMR/wamr_runtime_timer.c +98 -0
  119. package/kernel/Sources/CWAMR/wamr_thread_manager.c +98 -0
  120. package/kernel/Sources/CWAMR/wamr_wasm_application.c +98 -0
  121. package/kernel/Sources/CWAMR/wamr_wasm_blocking_op.c +98 -0
  122. package/kernel/Sources/CWAMR/wamr_wasm_c_api.c +98 -0
  123. package/kernel/Sources/CWAMR/wamr_wasm_exec_env.c +98 -0
  124. package/kernel/Sources/CWAMR/wamr_wasm_interp_fast.c +98 -0
  125. package/kernel/Sources/CWAMR/wamr_wasm_loader.c +98 -0
  126. package/kernel/Sources/CWAMR/wamr_wasm_loader_common.c +98 -0
  127. package/kernel/Sources/CWAMR/wamr_wasm_memory.c +98 -0
  128. package/kernel/Sources/CWAMR/wamr_wasm_native.c +98 -0
  129. package/kernel/Sources/CWAMR/wamr_wasm_runtime.c +98 -0
  130. package/kernel/Sources/CWAMR/wamr_wasm_runtime_common.c +98 -0
  131. package/kernel/Sources/CWAMR/wamr_wasm_shared_memory.c +98 -0
  132. package/kernel/Sources/Kernel/PluginPrelude.js +5 -2
  133. package/kernel/Tests/KernelTests/CasePins.js +50 -0
  134. package/package.json +2 -2
  135. package/skill/krillplayer-plugin/SKILL.md +2 -0
  136. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-content-rejected.json +8 -4
  137. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-login-expired.json +8 -4
  138. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-muted.json +8 -4
  139. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-other.json +8 -4
  140. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-rate-limited.json +8 -4
  141. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-sent.json +8 -4
  142. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-logged-in.json +39 -0
  143. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-selected-backup-line.json +8 -0
  144. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-selected-line-gone.json +8 -0
  145. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live.json +8 -0
  146. package/skill/krillplayer-plugin/assets/samples/live-video-platform/plugin.ts +26 -9
  147. package/skill/krillplayer-plugin/references/cases.md +19 -1
  148. package/skill/krillplayer-plugin/references/contract.d.ts +104 -11
  149. package/skill/krillplayer-plugin/references/crypto-tools.md +104 -0
  150. package/skill/krillplayer-plugin/references/errors-and-fixes.md +5 -1
@@ -0,0 +1,1155 @@
1
+ /* krillplayer.wasm 的引擎一侧(ADR 0042):WAMR 的快速解释器,形状照 WebAssembly 的 JS 接口。
2
+ * App 内核与试跑器链接同一份,两个宿主跑同一个模块得到同样的字节。
3
+ *
4
+ * 沙箱:
5
+ * - 内存:WAMR 的全部分配(线性内存、表、解释器自己的)都记在这个上下文的计数分配器上,和 JS 合在一起算。
6
+ * 超了上限这次调用就失败,接不住(同 QuickJS 的超内存,内核停用上下文)。线性内存由这里清零:WAMR 按用途分配时不清。
7
+ * - 时间:进模块时登记到看门狗,过了这次调用的期限由看门狗线程调 wasm_runtime_terminate 打断;接不住。
8
+ * - 原生栈:解释器的栈边界设在 QuickJS 的同一条限深线上方一段,JS 与模块互相嵌套过深时是陷阱,不是崩溃。
9
+ * - 字节:只编清单钉住的模块。宿主在装前导脚本之前登记清单 modules 的名字、长度与 SHA-256(kq_declare_module),
10
+ * 这里在编之前按名字核对。字节从宿主到这里要经过前导脚本里的 Map 与 Promise,插件改得了它们,所以核对不能只在宿主一侧。
11
+ * - 宿主函数:只有插件传进来的 JS 函数;缺一个就不实例化,报出名字与签名。
12
+ * - 陷阱变成接得住的 JS 异常(RuntimeError);宿主函数里 JS 抛的原样穿过模块交回调用方。
13
+ * WAMR 在实例化时自己会跑的 start 函数、__wasm_call_ctors 与 __post_instantiate 不在这些管束里:
14
+ * 带 start 段的模块不收,后两个导出在交给 WAMR 的副本里改了名,插件照原名调到它们,什么时候调由插件定(JS 接口也是这样)。
15
+ * 所以载入与实例化(解析、校验、初始化表与数据段)不跑模块的代码,看门狗也打断不了它(还没有实例可停):
16
+ * 它的工作量由钉住的字节(清单的上限 8 MiB)与上下文的内存上限封顶。 */
17
+ #include "kernel_internal.h"
18
+ #include "kernel_wamr.h"
19
+
20
+ #include <math.h>
21
+ #include <pthread.h>
22
+ #include <stdio.h>
23
+ #include <stdlib.h>
24
+ #include <string.h>
25
+
26
+ enum {
27
+ /* 每个实例的操作数栈(WAMR 的 wasm 栈,计在分配器上)。 */
28
+ OPERAND_STACK_BYTES = 128 << 10,
29
+ /* 解释器入口过了栈检查以后,到下一次检查(宿主函数里 QuickJS 自己的)之前要用的原生栈,量过约 1.5 KiB。
30
+ * 线程栈 512 KiB、预算 256 KiB,越过预算线一点不会碰到线程的底。 */
31
+ NATIVE_STACK_GUARD = 4 << 10,
32
+ BLOCK_HEADER = 16,
33
+ };
34
+
35
+ /* ---------- 分配器 ----------
36
+ * 每块前面 16 字节记着它算在哪个上下文的账上与申请的大小,释放时照着退账:WAMR 的块可能在别的调用里、
37
+ * 由 QuickJS 的垃圾回收释放。current_heap 是这条线程此刻在哪个上下文里,进模块与实例化时设。 */
38
+ static _Thread_local KQHeap *current_heap;
39
+ static _Thread_local KQWasmInstance *current_instance;
40
+
41
+ typedef struct {
42
+ KQHeap *heap;
43
+ size_t size;
44
+ } Block;
45
+
46
+ static Block *block_of(void *ptr) { return (Block *)((uint8_t *)ptr - BLOCK_HEADER); }
47
+
48
+ /* 要超上限时,线性内存先让 QuickJS 回收一次再算:插件扔掉的实例(实例对象与导出互相指着,只有循环回收收得掉)还占着
49
+ * 线性内存,QuickJS 按它自己分配的量决定什么时候回收,看不到这些;不回收的话,长住的上下文里每次 play.start 实例化一次,
50
+ * 早晚超内存。只对线性内存这样做:它只在实例化与 memory.grow 时要,那时不在 registry 锁里,回收里放掉别的实例是安全的
51
+ * (正在用的实例有调用的引用,放不掉)。 */
52
+ static void collect_garbage(void);
53
+
54
+ static bool admit(KQHeap *heap, size_t size, bool linear) {
55
+ if (!heap) return true;
56
+ if (linear && heap->limit != 0 && heap->used + size > heap->limit) collect_garbage();
57
+ return kq_heap_allows(heap, size);
58
+ }
59
+
60
+ /* linear:线性内存,清零(WAMR 按用途分配时不清)、要超上限时先回收一次。 */
61
+ static void *block_alloc(size_t size, bool linear) {
62
+ KQHeap *heap = current_heap;
63
+ if (size > SIZE_MAX - BLOCK_HEADER) return NULL;
64
+ if (!admit(heap, size + BLOCK_HEADER, linear)) return NULL;
65
+ Block *block = linear ? calloc(1, size + BLOCK_HEADER) : malloc(size + BLOCK_HEADER);
66
+ if (!block) return NULL;
67
+ block->heap = heap;
68
+ block->size = size;
69
+ if (heap) heap->used += kq_block_size(block);
70
+ return (uint8_t *)block + BLOCK_HEADER;
71
+ }
72
+
73
+ static void block_free(void *ptr) {
74
+ if (!ptr) return;
75
+ Block *block = block_of(ptr);
76
+ if (block->heap) block->heap->used -= kq_block_size(block);
77
+ free(block);
78
+ }
79
+
80
+ static void *block_realloc(void *ptr, size_t size, bool linear) {
81
+ if (!ptr) return block_alloc(size, linear);
82
+ Block *block = block_of(ptr);
83
+ KQHeap *heap = block->heap;
84
+ size_t old = kq_block_size(block), old_size = block->size;
85
+ if (size > SIZE_MAX - BLOCK_HEADER) return NULL;
86
+ if (size + BLOCK_HEADER > old && !admit(heap, size + BLOCK_HEADER - old, linear)) return NULL;
87
+ Block *grown = realloc(block, size + BLOCK_HEADER);
88
+ if (!grown) return NULL;
89
+ grown->size = size;
90
+ if (heap) heap->used = heap->used - old + kq_block_size(grown);
91
+ uint8_t *data = (uint8_t *)grown + BLOCK_HEADER;
92
+ if (linear && size > old_size) memset(data + old_size, 0, size - old_size);
93
+ return data;
94
+ }
95
+
96
+ /* ---------- 实例 ---------- */
97
+
98
+ typedef struct {
99
+ char *module;
100
+ char *name;
101
+ JSValue function;
102
+ uint32_t params;
103
+ wasm_valkind_t param[16];
104
+ uint32_t results;
105
+ wasm_valkind_t result;
106
+ const void *key;
107
+ } Import;
108
+
109
+ typedef struct {
110
+ char *name;
111
+ wasm_function_inst_t function;
112
+ /* 参数占几个 32 位槽;cells 是参数与结果里大的那个,UINT32_MAX 表示有 JS 交不了的类型。 */
113
+ uint32_t param_cells;
114
+ uint32_t cells;
115
+ uint32_t params;
116
+ wasm_valkind_t *param;
117
+ uint32_t results;
118
+ wasm_valkind_t *result;
119
+ } Export;
120
+
121
+ struct KQWasmInstance {
122
+ KQContext *q;
123
+ JSRuntime *rt;
124
+ /* 交给 WAMR 的模块字节(改过名的副本),模块卸载之前一直要在。 */
125
+ uint8_t *bytes;
126
+ wasm_module_t module;
127
+ wasm_module_inst_t instance;
128
+ wasm_exec_env_t env;
129
+ /* 引用:JS 的实例对象一个,正在进行的每次导出调用一个,交出去还指着线性内存的每个 ArrayBuffer 各一个。到 0 才卸载。 */
130
+ int refs;
131
+ /* 被看门狗打断过:之后的调用一律接不住地失败。 */
132
+ bool terminated;
133
+ Import *imports;
134
+ uint32_t import_count;
135
+ Export *exports;
136
+ uint32_t export_count;
137
+ /* 最近交出的 memory.buffer 与它指的那段线性内存;内存变大(wamr_realloc)或挪了就把它分离,下次取时重建。
138
+ * 它不可分离(transfer 抛 TypeError,同 V8),所以指着线性内存的 ArrayBuffer 只有它一个。buffer_object 是它这个对象,
139
+ * 实例对象被回收、放掉 buffer 以后还认得出它;它被分离或回收时(buffer_gone)清空。 */
140
+ JSValue buffer;
141
+ void *buffer_object;
142
+ uint8_t *buffer_base;
143
+ uint64_t buffer_size;
144
+ /* 宿主函数里 JS 抛的异常,模块退出后在导出的调用处原样抛出。 */
145
+ JSValue pending;
146
+ KQWasmInstance *next;
147
+ };
148
+
149
+ static void collect_garbage(void) {
150
+ if (current_instance) JS_RunGC(current_instance->rt);
151
+ }
152
+
153
+ static void *wamr_malloc(mem_alloc_usage_t usage, unsigned int size) {
154
+ return block_alloc(size, usage == Alloc_For_LinearMemory);
155
+ }
156
+
157
+ static void detach_buffer(KQWasmInstance *rec);
158
+
159
+ /* 线性内存变大:先分离交出的 memory.buffer(同 JS 接口,grow 之后旧的 buffer 分离)。它转移不走,分离以后没有
160
+ * 别的 ArrayBuffer 指着旧块,原地 realloc。 */
161
+ static void *wamr_realloc(mem_alloc_usage_t usage, bool full_size_mmaped, void *ptr, unsigned int size) {
162
+ (void)full_size_mmaped;
163
+ bool linear = usage == Alloc_For_LinearMemory;
164
+ if (linear && current_instance) detach_buffer(current_instance);
165
+ return block_realloc(ptr, size, linear);
166
+ }
167
+
168
+ static void wamr_free(mem_alloc_usage_t usage, void *ptr) {
169
+ (void)usage;
170
+ block_free(ptr);
171
+ }
172
+
173
+ /* ---------- WAMR 全局状态 ----------
174
+ * 运行时只初始化一次。注册宿主函数(按模块名与函数名,全进程共用)与解析模块的导入都在 registry 锁里:
175
+ * WAMR 的注册表不是线程安全的。每个被导入过的名字登记一个原始形状的通用宿主函数,调到时按实例找插件给的 JS 函数。 */
176
+ static pthread_once_t runtime_once = PTHREAD_ONCE_INIT;
177
+ static bool runtime_ready;
178
+ static pthread_mutex_t registry = PTHREAD_MUTEX_INITIALIZER;
179
+
180
+ typedef struct Registered {
181
+ char *module;
182
+ char *name;
183
+ NativeSymbol symbol;
184
+ struct Registered *next;
185
+ } Registered;
186
+ static Registered *registered;
187
+
188
+ static void init_runtime(void) {
189
+ RuntimeInitArgs args;
190
+ memset(&args, 0, sizeof args);
191
+ args.mem_alloc_type = Alloc_With_Allocator;
192
+ args.mem_alloc_option.allocator.malloc_func = (void *)wamr_malloc;
193
+ args.mem_alloc_option.allocator.realloc_func = (void *)wamr_realloc;
194
+ args.mem_alloc_option.allocator.free_func = (void *)wamr_free;
195
+ KQHeap *saved = current_heap;
196
+ current_heap = NULL;
197
+ runtime_ready = wasm_runtime_full_init(&args);
198
+ current_heap = saved;
199
+ }
200
+
201
+ /* ---------- 看门狗 ----------
202
+ * 正在模块里的上下文登记在这里,期限取进模块那一刻的。到期就给它所有的实例设终止标志:快速解释器在每个跳转上查,
203
+ * 死循环也停得下。宿主函数里的 JS 由 QuickJS 自己的中断处理按同一个期限停。 */
204
+ typedef struct Watch {
205
+ KQContext *q;
206
+ double deadline;
207
+ struct Watch *next;
208
+ } Watch;
209
+
210
+ static pthread_mutex_t watch_lock = PTHREAD_MUTEX_INITIALIZER;
211
+ static pthread_cond_t watch_wake = PTHREAD_COND_INITIALIZER;
212
+ static Watch *watching;
213
+ static pthread_once_t watchdog_once = PTHREAD_ONCE_INIT;
214
+
215
+ static void terminate_all(KQContext *q) {
216
+ for (KQWasmInstance *rec = q->wasm_instances; rec; rec = rec->next) {
217
+ if (rec->instance) wasm_runtime_terminate(rec->instance);
218
+ }
219
+ }
220
+
221
+ static void *watchdog(void *unused) {
222
+ (void)unused;
223
+ pthread_mutex_lock(&watch_lock);
224
+ for (;;) {
225
+ while (!watching) pthread_cond_wait(&watch_wake, &watch_lock);
226
+ double now = kq_monotonic_seconds();
227
+ for (Watch *w = watching; w; w = w->next) {
228
+ if (w->deadline > 0 && now > w->deadline && !atomic_load(&w->q->wasm_expired)) {
229
+ atomic_store(&w->q->wasm_expired, true);
230
+ terminate_all(w->q);
231
+ }
232
+ }
233
+ /* 测试会拨单调时钟(kq_skip_clock),所以按短间隔重查,不按期限睡。 */
234
+ struct timespec until;
235
+ clock_gettime(CLOCK_REALTIME, &until);
236
+ until.tv_nsec += 5 * 1000 * 1000;
237
+ if (until.tv_nsec >= 1000000000) {
238
+ until.tv_sec += 1;
239
+ until.tv_nsec -= 1000000000;
240
+ }
241
+ pthread_cond_timedwait(&watch_wake, &watch_lock, &until);
242
+ }
243
+ return NULL;
244
+ }
245
+
246
+ static void start_watchdog(void) {
247
+ pthread_attr_t attributes;
248
+ pthread_attr_init(&attributes);
249
+ pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
250
+ pthread_t thread;
251
+ pthread_create(&thread, &attributes, watchdog, NULL);
252
+ pthread_attr_destroy(&attributes);
253
+ }
254
+
255
+ typedef struct {
256
+ KQHeap *heap;
257
+ KQWasmInstance *instance;
258
+ Watch watch;
259
+ } Entry;
260
+
261
+ /* 进模块:这条线程的分配记到这个上下文,最外一层登记看门狗。 */
262
+ static void enter_wasm(KQContext *q, KQWasmInstance *rec, Entry *entry) {
263
+ entry->heap = current_heap;
264
+ entry->instance = current_instance;
265
+ current_heap = &q->heap;
266
+ current_instance = rec;
267
+ if (q->wasm_depth++ == 0 && q->deadline > 0) {
268
+ pthread_once(&watchdog_once, start_watchdog);
269
+ entry->watch.q = q;
270
+ entry->watch.deadline = q->deadline;
271
+ pthread_mutex_lock(&watch_lock);
272
+ entry->watch.next = watching;
273
+ watching = &entry->watch;
274
+ pthread_cond_signal(&watch_wake);
275
+ pthread_mutex_unlock(&watch_lock);
276
+ } else {
277
+ entry->watch.q = NULL;
278
+ }
279
+ }
280
+
281
+ static void leave_wasm(KQContext *q, Entry *entry) {
282
+ q->wasm_depth--;
283
+ if (entry->watch.q) {
284
+ pthread_mutex_lock(&watch_lock);
285
+ for (Watch **w = &watching; *w; w = &(*w)->next) {
286
+ if (*w == &entry->watch) {
287
+ *w = entry->watch.next;
288
+ break;
289
+ }
290
+ }
291
+ pthread_mutex_unlock(&watch_lock);
292
+ }
293
+ current_heap = entry->heap;
294
+ current_instance = entry->instance;
295
+ }
296
+
297
+ /* ---------- 报错 ---------- */
298
+
299
+ static JSValue throw_uncatchable(JSContext *ctx, const char *message) {
300
+ JS_ThrowInternalError(ctx, "%s", message);
301
+ JSValue error = JS_GetException(ctx);
302
+ JS_SetUncatchableError(ctx, error);
303
+ return JS_Throw(ctx, error);
304
+ }
305
+
306
+ /* 超内存与超时接不住(插件的 try 接不到,内核停用上下文);别的都接得住。 */
307
+ __attribute__((noinline)) static JSValue throw_limit(KQContext *q) {
308
+ if (q->heap.exceeded) return throw_uncatchable(q->ctx, "out of memory");
309
+ return throw_uncatchable(q->ctx, "interrupted");
310
+ }
311
+
312
+ static bool over_limit(KQContext *q) { return q->heap.exceeded || atomic_load(&q->wasm_expired); }
313
+
314
+ __attribute__((noinline)) static JSValue throw_runtime_error(JSContext *ctx, const char *format, const char *a, const char *b) {
315
+ char text[512];
316
+ snprintf(text, sizeof text, format, a, b);
317
+ JSValue error = JS_NewError(ctx);
318
+ JS_DefinePropertyValueStr(ctx, error, "name", JS_NewString(ctx, "RuntimeError"), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
319
+ JS_DefinePropertyValueStr(ctx, error, "message", JS_NewString(ctx, text), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);
320
+ return JS_Throw(ctx, error);
321
+ }
322
+
323
+ static const char *kind_name(wasm_valkind_t kind) {
324
+ switch (kind) {
325
+ case WASM_I32: return "i32";
326
+ case WASM_I64: return "i64";
327
+ case WASM_F32: return "f32";
328
+ case WASM_F64: return "f64";
329
+ case WASM_V128: return "v128";
330
+ case WASM_EXTERNREF: return "externref";
331
+ case WASM_FUNCREF: return "funcref";
332
+ default: return "?";
333
+ }
334
+ }
335
+
336
+ static bool number_kind(wasm_valkind_t kind) {
337
+ return kind == WASM_I32 || kind == WASM_I64 || kind == WASM_F32 || kind == WASM_F64;
338
+ }
339
+
340
+ static void describe_signature(char *out, size_t size, wasm_func_type_t type) {
341
+ uint32_t params = wasm_func_type_get_param_count(type), results = wasm_func_type_get_result_count(type);
342
+ size_t n = (size_t)snprintf(out, size, "(");
343
+ for (uint32_t i = 0; i < params && n < size; i++) {
344
+ n += (size_t)snprintf(out + n, size - n, "%s%s", i ? ", " : "", kind_name(wasm_func_type_get_param_valkind(type, i)));
345
+ }
346
+ if (n < size) n += (size_t)snprintf(out + n, size - n, ") -> ");
347
+ if (results == 0 && n < size) snprintf(out + n, size - n, "nothing");
348
+ for (uint32_t i = 0; i < results && n < size; i++) {
349
+ n += (size_t)snprintf(out + n, size - n, "%s%s", i ? ", " : "", kind_name(wasm_func_type_get_result_valkind(type, i)));
350
+ }
351
+ }
352
+
353
+ /* 没开的语言特性用到时 WAMR 报「unsupported opcode <前缀>」,换成作者看得懂的名字。 */
354
+ static const char *feature_of_opcode(const char *error) {
355
+ const char *at = strstr(error, "unsupported opcode ");
356
+ if (!at) return NULL;
357
+ unsigned long opcode = strtoul(at + strlen("unsupported opcode "), NULL, 16);
358
+ switch (opcode) {
359
+ case 0xfd: return "SIMD";
360
+ case 0xfe: return "threads (atomic operations)";
361
+ case 0xfb: return "garbage collection";
362
+ case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x18: case 0x19: case 0x1f: return "exception handling";
363
+ case 0x12: case 0x13: return "tail calls";
364
+ default: return NULL;
365
+ }
366
+ }
367
+
368
+ static JSValue throw_unsupported(JSContext *ctx, const char *feature) {
369
+ return JS_ThrowTypeError(ctx, "krillplayer.wasm: the module uses %s, which KrillPlayer does not support", feature);
370
+ }
371
+
372
+ static JSValue throw_load_error(JSContext *ctx, const char *error) {
373
+ const char *feature = feature_of_opcode(error);
374
+ if (feature) return throw_unsupported(ctx, feature);
375
+ return JS_ThrowTypeError(ctx, "krillplayer.wasm: the module could not be loaded: %s", error);
376
+ }
377
+
378
+ /* ---------- 模块字节的预读 ----------
379
+ * 只读段的边界,不校验(校验是 WAMR 的事),读坏了就当没看到,交给 WAMR 报错。 */
380
+ static bool read_leb(const uint8_t **p, const uint8_t *end, uint32_t *out) {
381
+ uint32_t value = 0;
382
+ for (int shift = 0; shift < 35; shift += 7) {
383
+ if (*p >= end) return false;
384
+ uint8_t byte = *(*p)++;
385
+ value |= (uint32_t)(byte & 0x7f) << shift;
386
+ if (!(byte & 0x80)) {
387
+ *out = value;
388
+ return true;
389
+ }
390
+ }
391
+ return false;
392
+ }
393
+
394
+ static const char *const HIDDEN[] = {"__wasm_call_ctors", "__post_instantiate"};
395
+
396
+ /* 有 start 段返回 true。导出名是 HIDDEN 里的,把副本里的第一个字节换成 0x7f,WAMR 就找不到、不在实例化时自己调。
397
+ * 共享内存、64 位内存与异常的 tag 段 WAMR 只报「invalid limits flags」「invalid section id」,这里先认出来记在 feature。 */
398
+ static bool prepare(uint8_t *bytes, size_t size, bool *renamed, const char **feature) {
399
+ const uint8_t *p = bytes + 8, *end = bytes + size;
400
+ bool start = false;
401
+ if (size < 8) return false;
402
+ while (p < end) {
403
+ uint8_t id = *p++;
404
+ uint32_t length;
405
+ if (!read_leb(&p, end, &length) || length > (size_t)(end - p)) return start;
406
+ const uint8_t *section = p, *section_end = p + length;
407
+ if (id == 8) start = true;
408
+ if (id == 13) *feature = "exception handling";
409
+ if (id == 5) {
410
+ uint32_t count, flags;
411
+ if (read_leb(&section, section_end, &count) && count > 0 && read_leb(&section, section_end, &flags)) {
412
+ if (flags & 0x2) *feature = "threads (shared memory)";
413
+ if (flags & 0x4) *feature = "memory64";
414
+ }
415
+ }
416
+ if (id == 7) {
417
+ uint32_t count;
418
+ if (!read_leb(&section, section_end, &count)) return start;
419
+ for (uint32_t i = 0; i < count; i++) {
420
+ uint32_t name_length, index;
421
+ if (!read_leb(&section, section_end, &name_length) || name_length > (size_t)(section_end - section)) return start;
422
+ uint8_t *name = (uint8_t *)section;
423
+ section += name_length;
424
+ if (section >= section_end) return start;
425
+ section++;
426
+ if (!read_leb(&section, section_end, &index)) return start;
427
+ for (size_t h = 0; h < sizeof HIDDEN / sizeof HIDDEN[0]; h++) {
428
+ if (name_length == strlen(HIDDEN[h]) && !memcmp(name, HIDDEN[h], name_length)) {
429
+ name[0] = 0x7f;
430
+ renamed[h] = true;
431
+ }
432
+ }
433
+ }
434
+ }
435
+ p = section_end;
436
+ }
437
+ return start;
438
+ }
439
+
440
+ /* ---------- 清单钉住的模块 ---------- */
441
+
442
+ struct KQModule {
443
+ char *name;
444
+ size_t size;
445
+ uint8_t sha256[32];
446
+ KQModule *next;
447
+ };
448
+
449
+ int kq_declare_module(KQContext *q, const char *name, size_t size, const uint8_t sha256[32]) {
450
+ KQModule *module = calloc(1, sizeof *module);
451
+ if (!module || !(module->name = strdup(name))) {
452
+ free(module);
453
+ return 1;
454
+ }
455
+ module->size = size;
456
+ memcpy(module->sha256, sha256, 32);
457
+ module->next = q->modules;
458
+ q->modules = module;
459
+ return 0;
460
+ }
461
+
462
+ void kq_wasm_free_modules(KQContext *q) {
463
+ for (KQModule *module = q->modules, *next; module; module = next) {
464
+ next = module->next;
465
+ free(module->name);
466
+ free(module);
467
+ }
468
+ q->modules = NULL;
469
+ }
470
+
471
+ static const KQModule *declared_module(KQContext *q, const char *name) {
472
+ for (const KQModule *module = q->modules; module; module = module->next) {
473
+ if (!strcmp(module->name, name)) return module;
474
+ }
475
+ return NULL;
476
+ }
477
+
478
+ /* SHA-256(FIPS 180-4)。只用来核对模块字节;两个宿主都链接这一份,不依赖平台的密码库。 */
479
+ static const uint32_t SHA256_K[64] = {
480
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
481
+ 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
482
+ 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
483
+ 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
484
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
485
+ 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
486
+ };
487
+
488
+ static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
489
+
490
+ static void sha256_block(uint32_t h[8], const uint8_t block[64]) {
491
+ uint32_t w[64], v[8];
492
+ for (int i = 0; i < 16; i++) {
493
+ w[i] = (uint32_t)block[i * 4] << 24 | (uint32_t)block[i * 4 + 1] << 16 | (uint32_t)block[i * 4 + 2] << 8 | block[i * 4 + 3];
494
+ }
495
+ for (int i = 16; i < 64; i++) {
496
+ uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
497
+ uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
498
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
499
+ }
500
+ memcpy(v, h, sizeof v);
501
+ for (int i = 0; i < 64; i++) {
502
+ uint32_t t1 = v[7] + (rotr(v[4], 6) ^ rotr(v[4], 11) ^ rotr(v[4], 25)) + ((v[4] & v[5]) ^ (~v[4] & v[6])) + SHA256_K[i] + w[i];
503
+ uint32_t t2 = (rotr(v[0], 2) ^ rotr(v[0], 13) ^ rotr(v[0], 22)) + ((v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]));
504
+ memmove(v + 1, v, 7 * sizeof v[0]);
505
+ v[4] += t1;
506
+ v[0] = t1 + t2;
507
+ }
508
+ for (int i = 0; i < 8; i++) h[i] += v[i];
509
+ }
510
+
511
+ static void sha256(const uint8_t *data, size_t size, uint8_t out[32]) {
512
+ uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
513
+ size_t whole = size & ~(size_t)63;
514
+ for (size_t at = 0; at < whole; at += 64) sha256_block(h, data + at);
515
+ uint8_t tail[128] = {0};
516
+ size_t rest = size - whole, padded = rest < 56 ? 64 : 128;
517
+ memcpy(tail, data + whole, rest);
518
+ tail[rest] = 0x80;
519
+ uint64_t bits = (uint64_t)size * 8;
520
+ for (int i = 0; i < 8; i++) tail[padded - 1 - i] = (uint8_t)(bits >> (i * 8));
521
+ for (size_t at = 0; at < padded; at += 64) sha256_block(h, tail + at);
522
+ for (int i = 0; i < 8; i++) {
523
+ for (int b = 0; b < 4; b++) out[i * 4 + b] = (uint8_t)(h[i] >> (24 - b * 8));
524
+ }
525
+ }
526
+
527
+ static bool pinned(const KQModule *module, const uint8_t *bytes, size_t size) {
528
+ if (size != module->size) return false;
529
+ uint8_t digest[32];
530
+ sha256(bytes, size, digest);
531
+ return !memcmp(digest, module->sha256, sizeof digest);
532
+ }
533
+
534
+ /* ---------- 线性内存交给 JS ---------- */
535
+
536
+ static wasm_memory_inst_t memory_of(KQWasmInstance *rec) {
537
+ return rec->instance ? wasm_runtime_get_default_memory(rec->instance) : NULL;
538
+ }
539
+
540
+ static void release(KQWasmInstance *rec);
541
+
542
+ /* 交出去的 ArrayBuffer 被回收(或被分离)时 QuickJS 以长度 0 调它。它不可调整长度:别的长度一律不给。 */
543
+ static void *buffer_gone(JSRuntime *rt, void *opaque, void *ptr, size_t size) {
544
+ (void)rt;
545
+ (void)ptr;
546
+ if (size != 0) return NULL;
547
+ KQWasmInstance *rec = opaque;
548
+ rec->buffer_object = NULL;
549
+ release(rec);
550
+ return NULL;
551
+ }
552
+
553
+ static void detach_buffer(KQWasmInstance *rec) {
554
+ if (JS_IsUndefined(rec->buffer)) return;
555
+ JSValue stale = rec->buffer;
556
+ rec->buffer = JS_UNDEFINED;
557
+ JS_DetachArrayBuffer(rec->q->ctx, stale);
558
+ JS_FreeValue(rec->q->ctx, stale);
559
+ }
560
+
561
+ /* 模块的内存挪了或变大了:先前交出的 buffer 分离,同 JS 接口里 memory.grow 之后的旧 buffer。 */
562
+ static void refresh_buffer(KQWasmInstance *rec) {
563
+ if (JS_IsUndefined(rec->buffer)) return;
564
+ wasm_memory_inst_t memory = memory_of(rec);
565
+ uint8_t *base = memory ? wasm_memory_get_base_address(memory) : NULL;
566
+ uint64_t size = memory ? wasm_memory_get_cur_page_count(memory) * wasm_memory_get_bytes_per_page(memory) : 0;
567
+ if (base != rec->buffer_base || size != rec->buffer_size) detach_buffer(rec);
568
+ }
569
+
570
+ static JSValue memory_buffer(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValueConst *data) {
571
+ (void)this_val;
572
+ (void)argc;
573
+ (void)argv;
574
+ (void)magic;
575
+ KQContext *q = JS_GetContextOpaque(ctx);
576
+ KQWasmInstance *rec = JS_GetOpaque(data[0], q->wasm_class);
577
+ if (!rec) return JS_ThrowTypeError(ctx, "krillplayer.wasm: the instance is gone");
578
+ refresh_buffer(rec);
579
+ if (JS_IsUndefined(rec->buffer)) {
580
+ wasm_memory_inst_t memory = memory_of(rec);
581
+ uint8_t *base = memory ? wasm_memory_get_base_address(memory) : NULL;
582
+ uint64_t size = memory ? wasm_memory_get_cur_page_count(memory) * wasm_memory_get_bytes_per_page(memory) : 0;
583
+ JSValue buffer = JS_NewArrayBuffer(ctx, base, (size_t)size, 0, buffer_gone, rec, false);
584
+ if (JS_IsException(buffer)) return buffer;
585
+ rec->refs++;
586
+ rec->buffer = buffer;
587
+ rec->buffer_object = JS_VALUE_GET_PTR(buffer);
588
+ rec->buffer_base = base;
589
+ rec->buffer_size = size;
590
+ }
591
+ return JS_DupValue(ctx, rec->buffer);
592
+ }
593
+
594
+ /* ---------- 值的换算(照 WebAssembly 的 JS 接口:i64 是 BigInt,别的是 Number) ---------- */
595
+
596
+ static int to_wasm(JSContext *ctx, JSValueConst value, wasm_valkind_t kind, wasm_val_t *out) {
597
+ out->kind = kind;
598
+ switch (kind) {
599
+ case WASM_I32: return JS_ToInt32(ctx, &out->of.i32, value);
600
+ case WASM_I64: return JS_ToBigInt64(ctx, &out->of.i64, value);
601
+ case WASM_F32: {
602
+ double d;
603
+ if (JS_ToFloat64(ctx, &d, value)) return -1;
604
+ out->of.f32 = (float)d;
605
+ return 0;
606
+ }
607
+ case WASM_F64: return JS_ToFloat64(ctx, &out->of.f64, value);
608
+ default: JS_ThrowTypeError(ctx, "krillplayer.wasm: %s values cannot cross between JS and the module", kind_name(kind)); return -1;
609
+ }
610
+ }
611
+
612
+ static JSValue from_wasm(JSContext *ctx, const wasm_val_t *value) {
613
+ switch (value->kind) {
614
+ case WASM_I32: return JS_NewInt32(ctx, value->of.i32);
615
+ case WASM_I64: return JS_NewBigInt64(ctx, value->of.i64);
616
+ case WASM_F32: return JS_NewFloat64(ctx, value->of.f32);
617
+ case WASM_F64: return JS_NewFloat64(ctx, value->of.f64);
618
+ default: return JS_UNDEFINED;
619
+ }
620
+ }
621
+
622
+ /* 原始形状的参数槽:每个参数一个 64 位槽,结果写回第 0 槽。 */
623
+ static JSValue slot_to_js(JSContext *ctx, uint64_t slot, wasm_valkind_t kind) {
624
+ wasm_val_t value = {.kind = kind};
625
+ switch (kind) {
626
+ case WASM_I32: value.of.i32 = (int32_t)(uint32_t)slot; break;
627
+ case WASM_I64: value.of.i64 = (int64_t)slot; break;
628
+ case WASM_F32: memcpy(&value.of.f32, &slot, sizeof(float)); break;
629
+ case WASM_F64: memcpy(&value.of.f64, &slot, sizeof(double)); break;
630
+ default: break;
631
+ }
632
+ return from_wasm(ctx, &value);
633
+ }
634
+
635
+ static int js_to_slot(JSContext *ctx, JSValueConst value, wasm_valkind_t kind, uint64_t *slot) {
636
+ wasm_val_t out;
637
+ if (to_wasm(ctx, value, kind, &out)) return -1;
638
+ switch (kind) {
639
+ case WASM_I32: *(uint32_t *)slot = (uint32_t)out.of.i32; break;
640
+ case WASM_I64: *slot = (uint64_t)out.of.i64; break;
641
+ case WASM_F32: memcpy(slot, &out.of.f32, sizeof(float)); break;
642
+ case WASM_F64: memcpy(slot, &out.of.f64, sizeof(double)); break;
643
+ default: break;
644
+ }
645
+ return 0;
646
+ }
647
+
648
+ /* ---------- 宿主函数:模块调插件的 JS ---------- */
649
+
650
+ static void host_import(wasm_exec_env_t env, uint64_t *slots) {
651
+ wasm_module_inst_t instance = wasm_runtime_get_module_inst(env);
652
+ KQWasmInstance *rec = wasm_runtime_get_custom_data(instance);
653
+ const void *key = wasm_runtime_get_function_attachment(env);
654
+ Import *import = NULL;
655
+ for (uint32_t i = 0; rec && i < rec->import_count; i++) {
656
+ if (rec->imports[i].key == key) import = &rec->imports[i];
657
+ }
658
+ if (!import) {
659
+ wasm_runtime_set_exception(instance, "import called outside its instance");
660
+ return;
661
+ }
662
+ JSContext *ctx = rec->q->ctx;
663
+ refresh_buffer(rec);
664
+ JSValue args[import->params ? import->params : 1];
665
+ for (uint32_t i = 0; i < import->params; i++) args[i] = slot_to_js(ctx, slots[i], import->param[i]);
666
+ JSValue result = JS_Call(ctx, import->function, JS_UNDEFINED, (int)import->params, args);
667
+ for (uint32_t i = 0; i < import->params; i++) JS_FreeValue(ctx, args[i]);
668
+ refresh_buffer(rec);
669
+ if (!JS_IsException(result) && import->results == 1) {
670
+ if (js_to_slot(ctx, result, import->result, slots)) {
671
+ JS_FreeValue(ctx, result);
672
+ result = JS_EXCEPTION;
673
+ }
674
+ }
675
+ if (JS_IsException(result)) {
676
+ JS_FreeValue(ctx, rec->pending);
677
+ rec->pending = JS_GetException(ctx);
678
+ wasm_runtime_set_exception(instance, "the import threw");
679
+ return;
680
+ }
681
+ JS_FreeValue(ctx, result);
682
+ }
683
+
684
+ /* 模块导入的每个名字登记一个通用的宿主函数;只登记模块真的导入的,表不随插件给的对象长。 */
685
+ static const void *registration(const char *module, const char *name) {
686
+ for (Registered *r = registered; r; r = r->next) {
687
+ if (!strcmp(r->module, module) && !strcmp(r->name, name)) return r;
688
+ }
689
+ Registered *r = calloc(1, sizeof *r);
690
+ if (!r) return NULL;
691
+ r->module = strdup(module);
692
+ r->name = strdup(name);
693
+ if (!r->module || !r->name) {
694
+ free(r->module);
695
+ free(r->name);
696
+ free(r);
697
+ return NULL;
698
+ }
699
+ r->symbol.symbol = r->name;
700
+ r->symbol.func_ptr = (void *)host_import;
701
+ r->symbol.signature = NULL;
702
+ r->symbol.attachment = r;
703
+ if (!wasm_runtime_register_natives_raw(r->module, &r->symbol, 1)) {
704
+ free(r->module);
705
+ free(r->name);
706
+ free(r);
707
+ return NULL;
708
+ }
709
+ r->next = registered;
710
+ registered = r;
711
+ return r;
712
+ }
713
+
714
+ /* ---------- 导出:插件调模块 ---------- */
715
+
716
+ /* 不内联:它的报错缓冲区不该算进每一层嵌套的栈帧。 */
717
+ __attribute__((noinline)) static JSValue raise(KQWasmInstance *rec, const char *export_name) {
718
+ KQContext *q = rec->q;
719
+ JSContext *ctx = q->ctx;
720
+ if (!JS_IsUndefined(rec->pending)) {
721
+ JSValue pending = rec->pending;
722
+ rec->pending = JS_UNDEFINED;
723
+ wasm_runtime_clear_exception(rec->instance);
724
+ return JS_Throw(ctx, pending);
725
+ }
726
+ if (over_limit(q) || rec->terminated) {
727
+ rec->terminated = true;
728
+ return throw_limit(q);
729
+ }
730
+ char reason[128];
731
+ const char *exception = wasm_runtime_get_exception(rec->instance);
732
+ snprintf(reason, sizeof reason, "%s", exception ? exception : "trap");
733
+ wasm_runtime_clear_exception(rec->instance);
734
+ const char *text = strncmp(reason, "Exception: ", 11) ? reason : reason + 11;
735
+ return throw_runtime_error(ctx, "krillplayer.wasm: %s trapped: %s", export_name, text);
736
+ }
737
+
738
+ static uint32_t cells_of(wasm_valkind_t kind) { return kind == WASM_I64 || kind == WASM_F64 ? 2 : 1; }
739
+
740
+ /* 调导出走 WAMR 的 32 位槽(wasm_runtime_call_wasm):JS 与模块每嵌套一层都要经过这里,栈帧要小(ADR 0042「原生栈」)。 */
741
+ static JSValue call_export(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValueConst *data) {
742
+ (void)this_val;
743
+ KQContext *q = JS_GetContextOpaque(ctx);
744
+ KQWasmInstance *rec = JS_GetOpaque(data[0], q->wasm_class);
745
+ if (!rec || (uint32_t)magic >= rec->export_count) return JS_ThrowTypeError(ctx, "krillplayer.wasm: the instance is gone");
746
+ if (rec->terminated) return throw_limit(q);
747
+ Export *export = &rec->exports[magic];
748
+ if (export->cells == UINT32_MAX) {
749
+ return JS_ThrowTypeError(ctx, "krillplayer.wasm: %s takes or returns values that cannot cross between JS and the module", export->name);
750
+ }
751
+ uint32_t cells[export->cells ? export->cells : 1];
752
+ for (uint32_t i = 0, at = 0; i < export->params; at += cells_of(export->param[i]), i++) {
753
+ uint64_t slot = 0;
754
+ if (js_to_slot(ctx, i < (uint32_t)argc ? argv[i] : JS_UNDEFINED, export->param[i], &slot)) return JS_EXCEPTION;
755
+ memcpy(&cells[at], &slot, cells_of(export->param[i]) * sizeof(uint32_t));
756
+ }
757
+ rec->refs++;
758
+ wasm_runtime_set_native_stack_boundary(rec->env, q->stack_limit + NATIVE_STACK_GUARD);
759
+ Entry entry;
760
+ enter_wasm(q, rec, &entry);
761
+ bool ok = !over_limit(q) && wasm_runtime_call_wasm(rec->env, export->function, export->param_cells, cells);
762
+ leave_wasm(q, &entry);
763
+ refresh_buffer(rec);
764
+ JSValue value;
765
+ if (!ok || over_limit(q)) {
766
+ value = raise(rec, export->name);
767
+ } else if (export->results == 0) {
768
+ value = JS_UNDEFINED;
769
+ } else if (export->results == 1) {
770
+ uint64_t slot = 0;
771
+ memcpy(&slot, cells, cells_of(export->result[0]) * sizeof(uint32_t));
772
+ value = slot_to_js(ctx, slot, export->result[0]);
773
+ } else {
774
+ value = JS_NewArray(ctx);
775
+ for (uint32_t i = 0, at = 0; i < export->results; at += cells_of(export->result[i]), i++) {
776
+ uint64_t slot = 0;
777
+ memcpy(&slot, &cells[at], cells_of(export->result[i]) * sizeof(uint32_t));
778
+ JS_SetPropertyUint32(ctx, value, i, slot_to_js(ctx, slot, export->result[i]));
779
+ }
780
+ }
781
+ release(rec);
782
+ return value;
783
+ }
784
+
785
+ /* ---------- 实例的生灭 ---------- */
786
+
787
+ /* 记录里的 JS 值(插件给的宿主函数、pending、buffer)归 JS 的实例对象:instance_mark 报给回收器的正是这几个,所以只由
788
+ * instance_finalizer 放掉(同 QuickJS 自己的类:gc_mark 报什么,finalizer 就放什么)。release 只收原生的资源:实例对象被回收以后
789
+ * 记录还可能因拿着的 memory.buffer 活着,到 buffer_gone 才退到 0,那时回收器可能已经把这些 JS 值连同对象一起释放了。 */
790
+ static void free_js_values(JSRuntime *rt, KQWasmInstance *rec) {
791
+ for (uint32_t i = 0; i < rec->import_count; i++) {
792
+ JSValue function = rec->imports[i].function;
793
+ rec->imports[i].function = JS_UNDEFINED;
794
+ JS_FreeValueRT(rt, function);
795
+ }
796
+ JSValue pending = rec->pending;
797
+ rec->pending = JS_UNDEFINED;
798
+ JS_FreeValueRT(rt, pending);
799
+ /* 引用随 ArrayBuffer 本身:它被回收时 buffer_gone 再退。这里只放掉记录手里的这一份。 */
800
+ JSValue buffer = rec->buffer;
801
+ rec->buffer = JS_UNDEFINED;
802
+ JS_FreeValueRT(rt, buffer);
803
+ }
804
+
805
+ static void release(KQWasmInstance *rec) {
806
+ if (--rec->refs > 0) return;
807
+ KQContext *q = rec->q;
808
+ pthread_mutex_lock(&watch_lock);
809
+ for (KQWasmInstance **r = &q->wasm_instances; *r; r = &(*r)->next) {
810
+ if (*r == rec) {
811
+ *r = rec->next;
812
+ break;
813
+ }
814
+ }
815
+ if (rec->env) wasm_runtime_destroy_exec_env(rec->env);
816
+ if (rec->instance) wasm_runtime_deinstantiate(rec->instance);
817
+ pthread_mutex_unlock(&watch_lock);
818
+ if (rec->module) wasm_runtime_unload(rec->module);
819
+ for (uint32_t i = 0; i < rec->import_count; i++) {
820
+ free(rec->imports[i].module);
821
+ free(rec->imports[i].name);
822
+ }
823
+ for (uint32_t i = 0; i < rec->export_count; i++) {
824
+ free(rec->exports[i].name);
825
+ free(rec->exports[i].param);
826
+ free(rec->exports[i].result);
827
+ }
828
+ free(rec->imports);
829
+ free(rec->exports);
830
+ block_free(rec->bytes);
831
+ free(rec);
832
+ }
833
+
834
+ static void instance_finalizer(JSRuntime *rt, JSValueConst value) {
835
+ KQContext *q = JS_GetRuntimeOpaque(rt);
836
+ KQWasmInstance *rec = JS_GetOpaque(value, q->wasm_class);
837
+ if (!rec) return;
838
+ free_js_values(rt, rec);
839
+ release(rec);
840
+ }
841
+
842
+ static void instance_mark(JSRuntime *rt, JSValueConst value, JS_MarkFunc *mark) {
843
+ KQContext *q = JS_GetRuntimeOpaque(rt);
844
+ KQWasmInstance *rec = JS_GetOpaque(value, q->wasm_class);
845
+ if (!rec) return;
846
+ for (uint32_t i = 0; i < rec->import_count; i++) JS_MarkValue(rt, rec->imports[i].function, mark);
847
+ JS_MarkValue(rt, rec->buffer, mark);
848
+ JS_MarkValue(rt, rec->pending, mark);
849
+ }
850
+
851
+ /* memory.buffer 不可分离,同 V8:插件转移走它的话,grow 之后它还指着旧块,要么悬空、要么旧块留到卸载。
852
+ * ArrayBuffer.prototype 上能分离 ArrayBuffer 的只有这几个方法(QuickJS-ng 没有 structuredClone):在插件的代码跑之前
853
+ * 各换成一层,对 memory.buffer 抛接得住的 TypeError,别的 ArrayBuffer 照原样转。原来的函数只在这层里,插件拿不到。 */
854
+ static const char *const TRANSFERS[] = {"transfer", "transferToFixedLength", "transferToImmutable"};
855
+
856
+ static JSValue guarded_transfer(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValueConst *data) {
857
+ (void)magic;
858
+ KQContext *q = JS_GetContextOpaque(ctx);
859
+ if (JS_VALUE_GET_TAG(this_val) == JS_TAG_OBJECT) {
860
+ for (KQWasmInstance *rec = q->wasm_instances; rec; rec = rec->next) {
861
+ if (rec->buffer_object == JS_VALUE_GET_PTR(this_val)) {
862
+ return JS_ThrowTypeError(ctx, "krillplayer.wasm: a module memory's ArrayBuffer is not detachable and cannot be transferred");
863
+ }
864
+ }
865
+ }
866
+ return JS_Call(ctx, data[0], this_val, argc, argv);
867
+ }
868
+
869
+ static int guard_transfers(JSContext *ctx) {
870
+ JSValue global = JS_GetGlobalObject(ctx);
871
+ JSValue constructor = JS_GetPropertyStr(ctx, global, "ArrayBuffer");
872
+ JSValue prototype = JS_GetPropertyStr(ctx, constructor, "prototype");
873
+ int status = JS_IsObject(prototype) ? 0 : -1;
874
+ for (size_t i = 0; status == 0 && i < sizeof TRANSFERS / sizeof *TRANSFERS; i++) {
875
+ JSValue original = JS_GetPropertyStr(ctx, prototype, TRANSFERS[i]);
876
+ if (JS_IsFunction(ctx, original)) {
877
+ JSValue guarded = JS_NewCFunctionData(ctx, guarded_transfer, 0, 0, 1, &original);
878
+ if (JS_IsException(guarded) ||
879
+ JS_DefinePropertyValueStr(ctx, guarded, "name", JS_NewString(ctx, TRANSFERS[i]), JS_PROP_CONFIGURABLE) < 0 ||
880
+ JS_DefinePropertyValueStr(ctx, prototype, TRANSFERS[i], guarded, JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE) < 0) {
881
+ status = -1;
882
+ }
883
+ }
884
+ JS_FreeValue(ctx, original);
885
+ }
886
+ JS_FreeValue(ctx, prototype);
887
+ JS_FreeValue(ctx, constructor);
888
+ JS_FreeValue(ctx, global);
889
+ return status;
890
+ }
891
+
892
+ int kq_wasm_setup(KQContext *q) {
893
+ JSClassDef definition = {"WebAssemblyInstance", .finalizer = instance_finalizer, .gc_mark = instance_mark};
894
+ JS_SetRuntimeOpaque(q->rt, q);
895
+ JS_NewClassID(q->rt, &q->wasm_class);
896
+ if (JS_NewClass(q->rt, q->wasm_class, &definition) < 0) return -1;
897
+ return guard_transfers(q->ctx);
898
+ }
899
+
900
+ static JSValue fail_instantiate(JSContext *ctx, KQWasmInstance *rec, JSValue error) {
901
+ if (rec) {
902
+ /* 还没有实例对象:记录里的 JS 值由这里放。 */
903
+ free_js_values(JS_GetRuntime(ctx), rec);
904
+ rec->refs = 1;
905
+ release(rec);
906
+ }
907
+ return error;
908
+ }
909
+
910
+ /* 导入对象里取 module.name,必须是函数。 */
911
+ static JSValue import_function(JSContext *ctx, JSValueConst imports, const char *module, const char *name) {
912
+ if (!JS_IsObject(imports)) return JS_UNDEFINED;
913
+ JSValue table = JS_GetPropertyStr(ctx, imports, module);
914
+ if (JS_IsException(table)) return table;
915
+ JSValue function = JS_IsObject(table) ? JS_GetPropertyStr(ctx, table, name) : JS_UNDEFINED;
916
+ JS_FreeValue(ctx, table);
917
+ return function;
918
+ }
919
+
920
+ static const char *import_kind_name(wasm_import_export_kind_t kind) {
921
+ switch (kind) {
922
+ case WASM_IMPORT_EXPORT_KIND_MEMORY: return "a memory";
923
+ case WASM_IMPORT_EXPORT_KIND_TABLE: return "a table";
924
+ case WASM_IMPORT_EXPORT_KIND_GLOBAL: return "a global";
925
+ default: return "something other than a function";
926
+ }
927
+ }
928
+
929
+ static int bind_imports(JSContext *ctx, KQWasmInstance *rec, JSValueConst imports) {
930
+ int32_t count = wasm_runtime_get_import_count(rec->module);
931
+ rec->imports = calloc((size_t)(count > 0 ? count : 1), sizeof(Import));
932
+ if (!rec->imports) return JS_ThrowOutOfMemory(ctx), -1;
933
+ for (int32_t i = 0; i < count; i++) {
934
+ wasm_import_t type;
935
+ wasm_runtime_get_import_type(rec->module, i, &type);
936
+ if (type.kind != WASM_IMPORT_EXPORT_KIND_FUNC) {
937
+ JS_ThrowTypeError(ctx, "krillplayer.wasm: the module imports %s.%s, %s; plugins can only give it functions", type.module_name,
938
+ type.name, import_kind_name(type.kind));
939
+ return -1;
940
+ }
941
+ char signature[160];
942
+ describe_signature(signature, sizeof signature, type.u.func_type);
943
+ Import *import = &rec->imports[rec->import_count];
944
+ import->function = JS_UNDEFINED;
945
+ import->params = wasm_func_type_get_param_count(type.u.func_type);
946
+ import->results = wasm_func_type_get_result_count(type.u.func_type);
947
+ bool numbers = import->params <= 16 && import->results <= 1;
948
+ for (uint32_t p = 0; numbers && p < import->params; p++) {
949
+ import->param[p] = wasm_func_type_get_param_valkind(type.u.func_type, p);
950
+ numbers = number_kind(import->param[p]);
951
+ }
952
+ if (numbers && import->results == 1) {
953
+ import->result = wasm_func_type_get_result_valkind(type.u.func_type, 0);
954
+ numbers = number_kind(import->result);
955
+ }
956
+ if (!numbers) {
957
+ JS_ThrowTypeError(ctx, "krillplayer.wasm: the module imports %s.%s %s, which JS functions cannot implement", type.module_name, type.name,
958
+ signature);
959
+ return -1;
960
+ }
961
+ JSValue function = import_function(ctx, imports, type.module_name, type.name);
962
+ if (JS_IsException(function)) return -1;
963
+ if (!JS_IsFunction(ctx, function)) {
964
+ JS_FreeValue(ctx, function);
965
+ JS_ThrowTypeError(ctx, "krillplayer.wasm: missing import %s.%s %s; pass it as a function in the imports object", type.module_name,
966
+ type.name, signature);
967
+ return -1;
968
+ }
969
+ import->function = function;
970
+ import->module = strdup(type.module_name);
971
+ import->name = strdup(type.name);
972
+ rec->import_count++;
973
+ if (!import->module || !import->name) return JS_ThrowOutOfMemory(ctx), -1;
974
+ }
975
+ pthread_mutex_lock(&registry);
976
+ bool registered_all = true;
977
+ for (uint32_t i = 0; i < rec->import_count; i++) {
978
+ rec->imports[i].key = registration(rec->imports[i].module, rec->imports[i].name);
979
+ registered_all = registered_all && rec->imports[i].key;
980
+ }
981
+ bool resolved = registered_all && wasm_runtime_resolve_symbols(rec->module);
982
+ pthread_mutex_unlock(&registry);
983
+ if (!resolved) return JS_ThrowTypeError(ctx, "krillplayer.wasm: could not link the module's imports"), -1;
984
+ return 0;
985
+ }
986
+
987
+ static int bind_exports(JSContext *ctx, KQWasmInstance *rec, const bool *renamed, JSValueConst instance_object, JSValue exports) {
988
+ int32_t count = wasm_runtime_get_export_count(rec->module);
989
+ rec->exports = calloc((size_t)(count > 0 ? count : 1), sizeof(Export));
990
+ if (!rec->exports) return JS_ThrowOutOfMemory(ctx), -1;
991
+ for (int32_t i = 0; i < count; i++) {
992
+ wasm_export_t type;
993
+ wasm_runtime_get_export_type(rec->module, i, &type);
994
+ char name[256];
995
+ snprintf(name, sizeof name, "%s", type.name);
996
+ for (size_t h = 0; h < sizeof HIDDEN / sizeof HIDDEN[0]; h++) {
997
+ if (renamed[h] && (unsigned char)name[0] == 0x7f && !strcmp(name + 1, HIDDEN[h] + 1)) name[0] = HIDDEN[h][0];
998
+ }
999
+ JSValue value;
1000
+ if (type.kind == WASM_IMPORT_EXPORT_KIND_FUNC) {
1001
+ Export *export = &rec->exports[rec->export_count];
1002
+ export->function = wasm_runtime_lookup_function(rec->instance, type.name);
1003
+ export->name = strdup(name);
1004
+ export->params = wasm_func_type_get_param_count(type.u.func_type);
1005
+ export->results = wasm_func_type_get_result_count(type.u.func_type);
1006
+ export->param = calloc(export->params + 1, sizeof(wasm_valkind_t));
1007
+ export->result = calloc(export->results + 1, sizeof(wasm_valkind_t));
1008
+ rec->export_count++;
1009
+ if (!export->function || !export->name || !export->param || !export->result) return JS_ThrowOutOfMemory(ctx), -1;
1010
+ bool numbers = export->params <= 64 && export->results <= 16;
1011
+ uint32_t result_cells = 0;
1012
+ for (uint32_t p = 0; p < export->params; p++) {
1013
+ export->param[p] = wasm_func_type_get_param_valkind(type.u.func_type, p);
1014
+ numbers = numbers && number_kind(export->param[p]);
1015
+ export->param_cells += cells_of(export->param[p]);
1016
+ }
1017
+ for (uint32_t r = 0; r < export->results; r++) {
1018
+ export->result[r] = wasm_func_type_get_result_valkind(type.u.func_type, r);
1019
+ numbers = numbers && number_kind(export->result[r]);
1020
+ result_cells += cells_of(export->result[r]);
1021
+ }
1022
+ export->cells = !numbers ? UINT32_MAX : export->param_cells > result_cells ? export->param_cells : result_cells;
1023
+ value = JS_NewCFunctionData(ctx, call_export, (int)export->params, (int)(rec->export_count - 1), 1, &instance_object);
1024
+ } else if (type.kind == WASM_IMPORT_EXPORT_KIND_MEMORY) {
1025
+ JSValue getter = JS_NewCFunctionData(ctx, memory_buffer, 0, 0, 1, &instance_object);
1026
+ if (JS_IsException(getter)) return -1;
1027
+ value = JS_NewObjectProto(ctx, JS_NULL);
1028
+ if (JS_IsException(value)) {
1029
+ JS_FreeValue(ctx, getter);
1030
+ return -1;
1031
+ }
1032
+ JSAtom atom = JS_NewAtom(ctx, "buffer");
1033
+ JS_DefinePropertyGetSet(ctx, value, atom, getter, JS_UNDEFINED, JS_PROP_ENUMERABLE);
1034
+ JS_FreeAtom(ctx, atom);
1035
+ JS_FreezeObject(ctx, value);
1036
+ } else {
1037
+ /* 表与全局变量不交给插件(契约只有函数与内存)。 */
1038
+ continue;
1039
+ }
1040
+ if (JS_IsException(value)) return -1;
1041
+ if (JS_DefinePropertyValueStr(ctx, exports, name, value, JS_PROP_ENUMERABLE) < 0) return -1;
1042
+ }
1043
+ return 0;
1044
+ }
1045
+
1046
+ /* instantiate(name, bytes, imports):前导脚本向宿主要到了这个名字的模块字节,这里先按登记的清单核对再编。返回 { exports }。
1047
+ * 报错的文字与宿主一侧(PluginModules.swift、host/krillplayer.ts 的 wasmModuleBytes)相同。 */
1048
+ static JSValue js_instantiate(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
1049
+ (void)this_val;
1050
+ KQContext *q = JS_GetContextOpaque(ctx);
1051
+ const char *name = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(ctx, argv[0]) : NULL;
1052
+ if (!name) return JS_ThrowTypeError(ctx, "krillplayer.wasm.instantiate takes a non-empty module name");
1053
+ const KQModule *module = declared_module(q, name);
1054
+ size_t size = 0;
1055
+ uint8_t *source = module && argc > 1 ? JS_GetUint8Array(ctx, &size, argv[1]) : NULL;
1056
+ bool matches = source && pinned(module, source, size);
1057
+ if (!module) {
1058
+ JS_ThrowTypeError(ctx, "krillplayer.wasm: the manifest declares no module named %s", name);
1059
+ } else if (!matches) {
1060
+ JS_ThrowTypeError(ctx, "krillplayer.wasm: module %s does not match the size and SHA-256 in the manifest", name);
1061
+ }
1062
+ JS_FreeCString(ctx, name);
1063
+ if (!matches) return JS_EXCEPTION;
1064
+ JSValueConst imports = argc > 2 ? argv[2] : JS_UNDEFINED;
1065
+ if (!JS_IsUndefined(imports) && !JS_IsNull(imports) && !JS_IsObject(imports)) {
1066
+ return JS_ThrowTypeError(ctx, "krillplayer.wasm: imports must be an object of objects of functions");
1067
+ }
1068
+ pthread_once(&runtime_once, init_runtime);
1069
+ if (!runtime_ready) return JS_ThrowInternalError(ctx, "krillplayer.wasm: the WebAssembly runtime could not start");
1070
+
1071
+ KQWasmInstance *rec = calloc(1, sizeof *rec);
1072
+ if (!rec) return JS_ThrowOutOfMemory(ctx);
1073
+ rec->q = q;
1074
+ rec->rt = q->rt;
1075
+ rec->buffer = JS_UNDEFINED;
1076
+ rec->pending = JS_UNDEFINED;
1077
+ Entry entry;
1078
+ enter_wasm(q, rec, &entry);
1079
+ rec->bytes = block_alloc(size, false);
1080
+ if (rec->bytes) memcpy(rec->bytes, source, size);
1081
+ bool renamed[2] = {false, false};
1082
+ const char *feature = NULL;
1083
+ bool start = rec->bytes && prepare(rec->bytes, size, renamed, &feature);
1084
+ char error[256] = "";
1085
+ if (rec->bytes && !start && !feature) {
1086
+ /* 载入时 WAMR 读宿主函数的注册表,与别的线程的注册互斥。 */
1087
+ pthread_mutex_lock(&registry);
1088
+ rec->module = wasm_runtime_load(rec->bytes, (uint32_t)size, error, sizeof error);
1089
+ pthread_mutex_unlock(&registry);
1090
+ }
1091
+ leave_wasm(q, &entry);
1092
+ if (over_limit(q)) return fail_instantiate(ctx, rec, throw_limit(q));
1093
+ if (!rec->bytes) return fail_instantiate(ctx, rec, JS_ThrowOutOfMemory(ctx));
1094
+ if (feature) return fail_instantiate(ctx, rec, throw_unsupported(ctx, feature));
1095
+ if (start) {
1096
+ return fail_instantiate(ctx, rec, JS_ThrowTypeError(ctx, "krillplayer.wasm: the module has a start function, which KrillPlayer does not "
1097
+ "run; export the initializer and call it from the plugin"));
1098
+ }
1099
+ if (!rec->module) return fail_instantiate(ctx, rec, throw_load_error(ctx, error));
1100
+ if (bind_imports(ctx, rec, imports)) return fail_instantiate(ctx, rec, JS_EXCEPTION);
1101
+
1102
+ enter_wasm(q, rec, &entry);
1103
+ rec->instance = wasm_runtime_instantiate(rec->module, 0, 0, error, sizeof error);
1104
+ if (rec->instance) {
1105
+ wasm_runtime_set_custom_data(rec->instance, rec);
1106
+ rec->env = wasm_runtime_create_exec_env(rec->instance, OPERAND_STACK_BYTES);
1107
+ }
1108
+ leave_wasm(q, &entry);
1109
+ if (over_limit(q)) return fail_instantiate(ctx, rec, throw_limit(q));
1110
+ if (!rec->instance) return fail_instantiate(ctx, rec, throw_load_error(ctx, error));
1111
+ if (!rec->env) return fail_instantiate(ctx, rec, JS_ThrowOutOfMemory(ctx));
1112
+ pthread_mutex_lock(&watch_lock);
1113
+ rec->next = q->wasm_instances;
1114
+ q->wasm_instances = rec;
1115
+ pthread_mutex_unlock(&watch_lock);
1116
+
1117
+ JSValue object = JS_NewObjectClass(ctx, q->wasm_class);
1118
+ if (JS_IsException(object)) return fail_instantiate(ctx, rec, JS_EXCEPTION);
1119
+ rec->refs = 1;
1120
+ JS_SetOpaque(object, rec);
1121
+ JSValue exports = JS_NewObjectProto(ctx, JS_NULL);
1122
+ if (JS_IsException(exports) || bind_exports(ctx, rec, renamed, object, exports)) {
1123
+ JS_FreeValue(ctx, exports);
1124
+ JS_FreeValue(ctx, object);
1125
+ return JS_EXCEPTION;
1126
+ }
1127
+ JS_FreezeObject(ctx, exports);
1128
+ JS_DefinePropertyValueStr(ctx, object, "exports", exports, JS_PROP_ENUMERABLE);
1129
+ JS_FreezeObject(ctx, object);
1130
+ return object;
1131
+ }
1132
+
1133
+ /* 每个包装文件一行「wamr_<名字>.c 名字=值 …」,按 KQ_WAMR_WRAPPERS 的顺序。只拼一次,之后一直用这一份。 */
1134
+ static char *compiled_options;
1135
+ static pthread_once_t compiled_options_once = PTHREAD_ONCE_INIT;
1136
+
1137
+ static void join_compiled_options(void) {
1138
+ size_t size = 1;
1139
+ #define KQ_WAMR_LINE_SIZE(stem) size += strlen("wamr_" #stem ".c \n") + strlen(kq_wamr_options_##stem());
1140
+ KQ_WAMR_WRAPPERS(KQ_WAMR_LINE_SIZE)
1141
+ #undef KQ_WAMR_LINE_SIZE
1142
+ char *text = malloc(size), *at = text;
1143
+ if (!text) return;
1144
+ #define KQ_WAMR_LINE(stem) at += snprintf(at, size - (size_t)(at - text), "wamr_" #stem ".c %s\n", kq_wamr_options_##stem());
1145
+ KQ_WAMR_WRAPPERS(KQ_WAMR_LINE)
1146
+ #undef KQ_WAMR_LINE
1147
+ compiled_options = text;
1148
+ }
1149
+
1150
+ const char *kq_wasm_compiled_options(void) {
1151
+ pthread_once(&compiled_options_once, join_compiled_options);
1152
+ return compiled_options ? compiled_options : "";
1153
+ }
1154
+
1155
+ JSValue kq_wasm_instantiate_function(JSContext *ctx) { return JS_NewCFunction(ctx, js_instantiate, "instantiate", 2); }