@finogeeks2026/finshield-opencode 0.0.0-stage → 0.11.50

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 (143) hide show
  1. package/DESIGN.md +593 -0
  2. package/LICENSE.rtf +28 -0
  3. package/README.md +132 -2
  4. package/THIRD-PARTY-NOTICES.md +3131 -0
  5. package/bin/node.exe +4 -0
  6. package/dist/gui-experimental.cjs +96 -0
  7. package/dist/updater/server.js +1046 -0
  8. package/install/download-source.json +3 -0
  9. package/install/runtime.js +60 -0
  10. package/node_modules/@finogeeks2026/finsafe-sdk/LICENSE.rtf +28 -0
  11. package/node_modules/@finogeeks2026/finsafe-sdk/README.md +116 -0
  12. package/node_modules/@finogeeks2026/finsafe-sdk/bin/finsafe_native.dll +0 -0
  13. package/node_modules/@finogeeks2026/finsafe-sdk/native-build.json +5 -0
  14. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/@koromix/koffi-win32-x64/README.md +6 -0
  15. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/@koromix/koffi-win32-x64/index.js +12 -0
  16. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/@koromix/koffi-win32-x64/package.json +24 -0
  17. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/@koromix/koffi-win32-x64/win32_x64/koffi.lib +0 -0
  18. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/@koromix/koffi-win32-x64/win32_x64/koffi.node +0 -0
  19. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/CHANGELOG.md +1183 -0
  20. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/LICENSE.txt +22 -0
  21. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/README.md +42 -0
  22. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/cnoke.cjs +816 -0
  23. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/benchmarks.md +80 -0
  24. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/callbacks.md +182 -0
  25. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/composites.md +549 -0
  26. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/contribute.md +163 -0
  27. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/index.md +46 -0
  28. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/load.md +191 -0
  29. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/migration.md +256 -0
  30. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/misc.md +76 -0
  31. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/output.md +299 -0
  32. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/pointers.md +385 -0
  33. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/primitives.md +151 -0
  34. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/start.md +110 -0
  35. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/types.md +88 -0
  36. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/unions.md +0 -0
  37. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/doc/values.md +134 -0
  38. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/index.cjs +1 -0
  39. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/index.d.ts +389 -0
  40. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/index.js +2 -0
  41. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/indirect.cjs +1 -0
  42. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/indirect.js +2 -0
  43. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/lib/native/base/base.cc +11064 -0
  44. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/lib/native/base/base.hh +5951 -0
  45. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/lib/native/base/unicode.inc +408 -0
  46. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/package.json +68 -0
  47. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/CMakeLists.txt +249 -0
  48. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/index.cjs +296 -0
  49. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/index.js +281 -0
  50. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/indirect.cjs +295 -0
  51. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/indirect.js +280 -0
  52. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/arm64.cc +1408 -0
  53. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/arm64_asm.S +216 -0
  54. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/arm64_asm.asm +181 -0
  55. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/loong64.cc +5 -0
  56. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/loong64_asm.S +200 -0
  57. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/riscv64.cc +1345 -0
  58. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/riscv64_asm.S +200 -0
  59. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x64sysv.cc +1434 -0
  60. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x64sysv_asm.S +224 -0
  61. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x64win.cc +1086 -0
  62. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x64win_asm.S +162 -0
  63. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x64win_asm.asm +189 -0
  64. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x86.cc +1185 -0
  65. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x86_asm.S +217 -0
  66. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/abi/x86_asm.asm +174 -0
  67. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/call.cc +2094 -0
  68. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/call.hh +179 -0
  69. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/errno.inc +462 -0
  70. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/ffi.cc +3009 -0
  71. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/ffi.hh +461 -0
  72. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/parser.cc +218 -0
  73. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/parser.hh +54 -0
  74. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/primitives.inc +36 -0
  75. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/static.cjs +130 -0
  76. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/static.js +133 -0
  77. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/trampolines.cjs +77 -0
  78. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/type.cc +725 -0
  79. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/type.hh +71 -0
  80. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/util.cc +1040 -0
  81. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/util.hh +493 -0
  82. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/uv.cc +214 -0
  83. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/uv.def +11 -0
  84. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/uv.hh +112 -0
  85. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/win32.cc +198 -0
  86. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/src/koffi/src/win32.hh +148 -0
  87. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-addon-api/LICENSE.md +9 -0
  88. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-addon-api/README.md +95 -0
  89. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-addon-api/napi-inl.deprecated.h +186 -0
  90. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-addon-api/napi-inl.h +7211 -0
  91. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-addon-api/napi.h +3421 -0
  92. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/LICENSE +21 -0
  93. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/README.md +95 -0
  94. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/def/js_native_api.def +125 -0
  95. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/def/node_api.def +157 -0
  96. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/include/js_native_api.h +591 -0
  97. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/include/js_native_api_types.h +210 -0
  98. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/include/node_api.h +265 -0
  99. package/node_modules/@finogeeks2026/finsafe-sdk/node_modules/koffi/vendor/node-api-headers/include/node_api_types.h +58 -0
  100. package/node_modules/@finogeeks2026/finsafe-sdk/package.json +36 -0
  101. package/node_modules/@finogeeks2026/finsafe-sdk/release.json +4 -0
  102. package/node_modules/@finogeeks2026/finsafe-sdk/src/native.js +85 -0
  103. package/node_modules/@finogeeks2026/finsafe-sdk/src/shell.js +20 -0
  104. package/node_modules/@finogeeks2026/finsafe-sdk/src/status.js +57 -0
  105. package/package.json +47 -4
  106. package/policy/candidate.yaml +347 -0
  107. package/release.json +4 -0
  108. package/src/activation.js +2 -0
  109. package/src/attachment.js +34 -0
  110. package/src/connector.js +91 -0
  111. package/src/contract.js +8 -0
  112. package/src/desktop-contract.js +4 -0
  113. package/src/desktop.js +25 -0
  114. package/src/gui.tsx +58 -0
  115. package/src/host.js +38 -0
  116. package/src/index.js +12 -0
  117. package/src/instance-settings.js +27 -0
  118. package/src/known-folders.js +22 -0
  119. package/src/management.js +17 -0
  120. package/src/preparation.js +18 -0
  121. package/src/presentation.js +153 -0
  122. package/src/settings.js +18 -0
  123. package/ui/feedback.cjs +45 -0
  124. package/ui/page.cjs +225 -0
  125. package/ui/state.cjs +44 -0
  126. package/updater/bootstrap.js +41 -0
  127. package/updater/common/activation.js +81 -0
  128. package/updater/common/coordinator.js +329 -0
  129. package/updater/common/download.js +57 -0
  130. package/updater/common/index.js +12 -0
  131. package/updater/common/package.js +53 -0
  132. package/updater/common/protocol.js +38 -0
  133. package/updater/common/transport.js +65 -0
  134. package/updater/coordinator.js +2 -0
  135. package/updater/launch.js +40 -0
  136. package/updater/management.js +9 -0
  137. package/updater/native.js +18 -0
  138. package/updater/operations.js +45 -0
  139. package/updater/protocol.js +1 -0
  140. package/updater/server.js +100 -0
  141. package/updater/transport.js +10 -0
  142. package/updater/windows-launch-reader.js +40 -0
  143. package/updater/windows-launch.js +96 -0
@@ -0,0 +1,2094 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // SPDX-FileCopyrightText: 2026 Niels Martignène <niels.martignene@protonmail.com>
3
+
4
+ #include "lib/native/base/base.hh"
5
+ #include "call.hh"
6
+ #include "ffi.hh"
7
+ #include "type.hh"
8
+ #include "util.hh"
9
+ #if defined(_WIN32)
10
+ #include "win32.hh"
11
+ #endif
12
+
13
+ #include <napi.h>
14
+
15
+ namespace K {
16
+
17
+ struct RelayContext {
18
+ CallData *call;
19
+
20
+ Size idx;
21
+ uint8_t *sp;
22
+
23
+ std::mutex mutex = {};
24
+ std::condition_variable cv = {};
25
+ bool done = false;
26
+ };
27
+
28
+ extern "C" napi_value SwitchAndRelay(CallData *call, Size idx, uint8_t *sp, uint8_t *saved_sp, MemoryRange<uint8_t> *new_stack);
29
+
30
+ #if defined(_WIN32)
31
+
32
+ extern "C" void *FindTrampolineStart();
33
+ extern "C" void *FindTrampolineEnd();
34
+
35
+ static const uint8_t *TrampolineStart = (const uint8_t *)FindTrampolineStart();
36
+ static const Size TrampolineSize = ((const uint8_t *)FindTrampolineEnd() - TrampolineStart) / MaxTrampolines;
37
+
38
+ #else
39
+
40
+ extern "C" uint8_t Trampoline0;
41
+ extern "C" uint8_t TrampolineEnd;
42
+
43
+ static const uint8_t *TrampolineStart = (const uint8_t *)&Trampoline0;
44
+ static const Size TrampolineSize = ((const uint8_t *)&TrampolineEnd - TrampolineStart) / MaxTrampolines;
45
+
46
+ #endif
47
+
48
+ static napi_value (*translate_zero_call)(napi_env env, napi_callback_info info);
49
+
50
+ #if defined(K_DEBUG)
51
+ CallData::~CallData()
52
+ {
53
+ K_ASSERT(mem->stack.end == prev_stack);
54
+ K_ASSERT(mem->heap.ptr == prev_heap);
55
+ K_ASSERT(!out_arguments.len);
56
+ K_ASSERT(!used_trampolines.len);
57
+ }
58
+ #endif
59
+
60
+ void CallData::Finalize()
61
+ {
62
+ FinalizeFast();
63
+
64
+ if (out_arguments.len) {
65
+ if (!env.IsExceptionPending()) {
66
+ for (const OutArgument &out: out_arguments) {
67
+ napi_value value = GetReferenceValue(env, out.ref);
68
+
69
+ switch (out.kind) {
70
+ case OutArgument::Kind::Array: {
71
+ K_ASSERT(IsArray(env, value));
72
+
73
+ uint32_t len = GetArrayLength(env, value);
74
+ DecodeElements(instance, value, out.ptr, out.type, len);
75
+ } break;
76
+
77
+ case OutArgument::Kind::String: {
78
+ K_ASSERT(IsArray(env, value));
79
+ K_ASSERT(GetArrayLength(env, value) == 1);
80
+
81
+ Size len = strnlen((const char *)out.ptr, out.max_len);
82
+ napi_value str = NewString(env, (const char *)out.ptr, len);
83
+
84
+ napi_set_element(env, value, 0, str);
85
+ } break;
86
+
87
+ case OutArgument::Kind::String16: {
88
+ K_ASSERT(IsArray(env, value));
89
+ K_ASSERT(GetArrayLength(env, value) == 1);
90
+
91
+ Size len = NullTerminatedLength((const char16_t *)out.ptr, out.max_len);
92
+ napi_value str = NewString(env, (const char16_t *)out.ptr, len);
93
+
94
+ napi_set_element(env, value, 0, str);
95
+ } break;
96
+
97
+ case OutArgument::Kind::String32: {
98
+ K_ASSERT(IsArray(env, value));
99
+ K_ASSERT(GetArrayLength(env, value) == 1);
100
+
101
+ Size len = NullTerminatedLength((const char32_t *)out.ptr, out.max_len);
102
+ napi_value str = NewString(env, (const char32_t *)out.ptr, len);
103
+
104
+ napi_set_element(env, value, 0, str);
105
+ } break;
106
+
107
+ case OutArgument::Kind::Object: {
108
+ if (CheckValueTag(env, value, &UnionValueMarker)) {
109
+ UnionValue *u = nullptr;
110
+ NAPI_OK(napi_unwrap(env, value, (void **)&u));
111
+
112
+ u->SetRaw(out.ptr);
113
+ } else {
114
+ DecodeObject(instance, value, out.ptr, out.type->ref.type);
115
+ }
116
+ } break;
117
+ }
118
+ }
119
+ }
120
+
121
+ for (const OutArgument &out: out_arguments) {
122
+ node_api_delete_reference(env, out.ref);
123
+ }
124
+ }
125
+
126
+ if (used_trampolines.len) {
127
+ std::lock_guard<std::mutex> lock(shared.mutex);
128
+
129
+ for (Size i = used_trampolines.len - 1; i >= 0; i--) {
130
+ int16_t idx = used_trampolines[i];
131
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
132
+
133
+ K_ASSERT(trampoline->instance == instance);
134
+ K_ASSERT(trampoline->func);
135
+
136
+ trampoline->state = 0;
137
+ node_api_delete_reference(env, trampoline->func);
138
+ trampoline->func = nullptr;
139
+
140
+ shared.available.Append(idx);
141
+ }
142
+ }
143
+
144
+ #if defined(K_DEBUG)
145
+ out_arguments.len = 0;
146
+ used_trampolines.len = 0;
147
+ #endif
148
+ }
149
+
150
+ void CallData::FinalizeFast()
151
+ {
152
+ #if defined(K_DEBUG)
153
+ K_ASSERT(!finalized);
154
+ K_DEFER { finalized = true; };
155
+ #endif
156
+
157
+ mem->stack.end = prev_stack;
158
+ mem->heap.ptr = prev_heap;
159
+
160
+ if (release_alloc) {
161
+ // We could check for prev_stack == mem->stack.len and call ReleaseAll() if true, but
162
+ // it is a virtual method. Which means it could be slow (unless devirtualized), and
163
+ // most of the time there's nothing to release.
164
+ // So instead, take note of the need to call ReleaseAll() when big chunks are allocated.
165
+ mem->allocator.ReleaseAll();
166
+ }
167
+ }
168
+
169
+ void CallData::RelayAsync(Size idx, uint8_t *sp)
170
+ {
171
+ // JS/V8 is single-threaded, and runs on main_thread_id. Forward the call
172
+ // to the JS event loop.
173
+
174
+ RelayContext ctx = {
175
+ .call = this,
176
+ .idx = idx,
177
+ .sp = sp
178
+ };
179
+
180
+ NAPI_OK(napi_call_threadsafe_function(instance->broker, &ctx, napi_tsfn_blocking));
181
+
182
+ // Wait until it executes
183
+ std::unique_lock<std::mutex> lock(ctx.mutex);
184
+ while (!ctx.done) {
185
+ ctx.cv.wait(lock);
186
+ }
187
+ }
188
+
189
+ napi_value CallData::CallCallback(const TrampolineInfo *trampoline, const napi_value *args, Size count)
190
+ {
191
+ napi_value recv;
192
+ napi_value func;
193
+ napi_value value;
194
+
195
+ NAPI_OK(napi_get_undefined(env, &recv));
196
+ NAPI_OK(napi_get_reference_value(env, trampoline->func, &func));
197
+
198
+ napi_status status = napi_call_function(env, recv, func, (size_t)count, args, &value);
199
+ if (status == napi_pending_exception) [[unlikely]]
200
+ return nullptr;
201
+ K_ASSERT(status == napi_ok);
202
+
203
+ return value;
204
+ }
205
+
206
+ bool CallData::PushString(napi_value value, int directions, const char **out_str)
207
+ {
208
+ // Fast path
209
+ if (PushStringValue(value, out_str) >= 0) {
210
+ if (directions & 2) [[unlikely]] {
211
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected [string]", GetValueType(instance, value));
212
+ return false;
213
+ }
214
+
215
+ return true;
216
+ }
217
+
218
+ return PushPointer(value, instance->str_type, directions, (void **)out_str);
219
+ }
220
+
221
+ bool CallData::PushString16(napi_value value, int directions, const char16_t **out_str16)
222
+ {
223
+ // Fast path
224
+ if (PushString16Value(value, out_str16) >= 0) {
225
+ if (directions & 2) [[unlikely]] {
226
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected [string]", GetValueType(instance, value));
227
+ return false;
228
+ }
229
+
230
+ return true;
231
+ }
232
+
233
+ return PushPointer(value, instance->str16_type, directions, (void **)out_str16);
234
+ }
235
+
236
+ bool CallData::PushString32(napi_value value, int directions, const char32_t **out_str32)
237
+ {
238
+ // Fast path
239
+ if (PushString32Value(value, out_str32) >= 0) {
240
+ if (directions & 2) [[unlikely]] {
241
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected [string]", GetValueType(instance, value));
242
+ return false;
243
+ }
244
+
245
+ return true;
246
+ }
247
+
248
+ return PushPointer(value, instance->str32_type, directions, (void **)out_str32);
249
+ }
250
+
251
+ Size CallData::PushStringValue(napi_value value, const char **out_str)
252
+ {
253
+ size_t len;
254
+
255
+ size_t available = (size_t)(mem->heap.end - mem->heap.ptr);
256
+ char *ptr = (char *)mem->heap.ptr;
257
+
258
+ // Fast path for small strings
259
+ if (available >= 4096) [[likely]] {
260
+ napi_status status = napi_get_value_string_utf8(env, value, ptr, 4096, &len);
261
+ if (status == napi_string_expected)
262
+ return -1;
263
+ K_ASSERT(status == napi_ok);
264
+
265
+ len++;
266
+
267
+ // UTF-8 can take up to 4 bytes for a codepoint, so truncation may
268
+ // result in a value that is several bytes less than the buffer size.
269
+ // So len < 4096 - 4 should be enough, but exagerate a bit "just in case" :)
270
+
271
+ if ((Size)len < 4096 - 8) {
272
+ mem->heap.ptr += (Size)AlignLen(len, 16);
273
+
274
+ *out_str = ptr;
275
+ return (Size)len;
276
+ }
277
+ }
278
+
279
+ NAPI_OK(napi_get_value_string_utf8(env, value, nullptr, 0, &len));
280
+
281
+ len++;
282
+
283
+ if (len <= available) {
284
+ NAPI_OK(napi_get_value_string_utf8(env, value, ptr, len, nullptr));
285
+
286
+ mem->heap.ptr += (Size)AlignLen(len, 16);
287
+
288
+ *out_str = ptr;
289
+ return (Size)len;
290
+ } else {
291
+ Span<char> buf = AllocateSpan<char>(&mem->allocator, (Size)len);
292
+ release_alloc |= (prev_stack == mem->stack.end);
293
+
294
+ NAPI_OK(napi_get_value_string_utf8(env, value, buf.ptr, len, nullptr));
295
+
296
+ *out_str = buf.ptr;
297
+ return (Size)len;
298
+ }
299
+ }
300
+
301
+ Size CallData::PushString16Value(napi_value value, const char16_t **out_str16)
302
+ {
303
+ size_t len = 0;
304
+ Span<char16_t> buf;
305
+
306
+ napi_status status = napi_get_value_string_utf16(env, value, nullptr, 0, &len);
307
+ if (status == napi_string_expected)
308
+ return -1;
309
+ K_ASSERT(status == napi_ok);
310
+
311
+ len++;
312
+
313
+ buf.ptr = (char16_t *)mem->heap.ptr;
314
+ buf.len = (mem->heap.end - mem->heap.ptr) / 2;
315
+
316
+ if (len <= (size_t)buf.len) {
317
+ NAPI_OK(napi_get_value_string_utf16(env, value, buf.ptr, len, nullptr));
318
+
319
+ mem->heap.ptr += (Size)AlignLen(len * 2, 16);
320
+ } else {
321
+ buf = AllocateSpan<char16_t>(&mem->allocator, (Size)len);
322
+ release_alloc |= (prev_stack == mem->stack.end);
323
+
324
+ NAPI_OK(napi_get_value_string_utf16(env, value, buf.ptr, len, nullptr));
325
+ }
326
+
327
+ *out_str16 = buf.ptr;
328
+ return (Size)len;
329
+ }
330
+
331
+ Size CallData::PushString32Value(napi_value value, const char32_t **out_str32)
332
+ {
333
+ static const char32_t ReplacementChar = 0x0000FFFD;
334
+
335
+ Span<char32_t> buf;
336
+
337
+ Span<const char16_t> buf16;
338
+ buf16.len = PushString16Value(value, &buf16.ptr);
339
+ if (buf16.len < 0) [[unlikely]]
340
+ return -1;
341
+
342
+ buf.ptr = (char32_t *)mem->heap.ptr;
343
+ buf.len = (mem->heap.end - mem->heap.ptr) / 4;
344
+
345
+ if (buf16.len < buf.len) [[likely]] {
346
+ mem->heap.ptr += AlignLen(buf16.len * 4, 16);
347
+ } else {
348
+ buf = AllocateSpan<char32_t>(&mem->allocator, buf16.len);
349
+ release_alloc |= (prev_stack == mem->stack.end);
350
+ }
351
+
352
+ Size j = 0;
353
+ for (Size i = 0; i < buf16.len; i++) {
354
+ char32_t uc = buf16[i];
355
+
356
+ if (uc >= 0xD800 && uc <= 0xDBFF) {
357
+ if (++i < buf16.len) {
358
+ char16_t uc2 = buf16.ptr[i];
359
+
360
+ if (uc2 >= 0xDC00 && uc2 <= 0xDFFF) [[likely]] {
361
+ uc = ((uc - 0xD800) << 10) + (uc2 - 0xDC00) + 0x10000u;
362
+ } else {
363
+ uc = ReplacementChar;
364
+ }
365
+ } else {
366
+ uc = ReplacementChar;
367
+ }
368
+ } else if (uc >= 0xDC00 && uc <= 0xDFFF) [[unlikely]] {
369
+ uc = ReplacementChar;
370
+ }
371
+
372
+ buf[j++] = uc;
373
+ }
374
+
375
+ *out_str32 = buf.ptr;
376
+ return j;
377
+ }
378
+
379
+ static FORCE_INLINE napi_value GetMemberValue(napi_env env, napi_value obj, const RecordMember &member)
380
+ {
381
+ napi_value value;
382
+
383
+ if (member.key) {
384
+ napi_value key;
385
+ NAPI_OK(napi_get_reference_value(env, member.key, &key));
386
+ NAPI_OK(napi_get_property(env, obj, key, &value));
387
+ } else {
388
+ NAPI_OK(napi_get_named_property(env, obj, member.name, &value));
389
+ }
390
+
391
+ return value;
392
+ }
393
+
394
+ bool CallData::PushObject(napi_value obj, const TypeInfo *type, uint8_t *origin)
395
+ {
396
+ K_ASSERT(type->primitive == PrimitiveKind::Record ||
397
+ type->primitive == PrimitiveKind::Union);
398
+
399
+ if (GetKindOf(env, obj) != napi_object) [[unlikely]] {
400
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected object", GetValueType(instance, obj));
401
+ return false;
402
+ }
403
+
404
+ Span<const RecordMember> members = type->members;
405
+
406
+ if (type->primitive == PrimitiveKind::Union) {
407
+ if (CheckValueTag(env, obj, &UnionValueMarker)) {
408
+ UnionValue *u = nullptr;
409
+ napi_unwrap(env, obj, (void **)&u);
410
+
411
+ const uint8_t *raw = u->GetRaw();
412
+
413
+ if (u->GetType() != type) [[unlikely]] {
414
+ ThrowError<Napi::TypeError>(env, "Expected union type %1, got %2", type->name, u->GetType()->name);
415
+ return false;
416
+ }
417
+
418
+ // Fast path: encoded value already exists, just copy!
419
+ if (raw) {
420
+ memcpy(origin, raw, type->size);
421
+ return true;
422
+ }
423
+
424
+ members.ptr = u->GetMember();
425
+ members.len = 1;
426
+
427
+ if (!members.ptr) [[unlikely]] {
428
+ ThrowError<Napi::Error>(env, "Cannot use ambiguous empty union");
429
+ return false;
430
+ }
431
+ } else {
432
+ Napi::Array properties = GetOwnPropertyNames(env, obj);
433
+
434
+ if (properties.Length() != 1 || !properties.Get(0u).IsString()) [[unlikely]] {
435
+ ThrowError<Napi::Error>(env, "Expected object with single property name for union");
436
+ return false;
437
+ }
438
+
439
+ std::string property = properties.Get(0u).As<Napi::String>();
440
+
441
+ const RecordMember *member = std::find_if(members.begin(), members.end(),
442
+ [&](const RecordMember &member) { return TestStr(property.c_str(), member.name); });
443
+
444
+ if (member == members.end()) [[unlikely]] {
445
+ ThrowError<Napi::Error>(env, "Unknown member %1 in union type %2", property.c_str(), type->name);
446
+ return false;
447
+ }
448
+
449
+ members.ptr = member;
450
+ members.len = 1;
451
+ }
452
+ }
453
+
454
+ int fill = (type->flags & (int)TypeFlag::FillWithOnes) ? 0xFF : 0;
455
+ MemSet(origin, fill, type->size);
456
+
457
+ #define PUSH_INTEGER(CType) \
458
+ do { \
459
+ CType v; \
460
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
461
+ abort(); \
462
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
463
+ return false; \
464
+ } \
465
+ \
466
+ *(CType *)dest = v; \
467
+ } while (false)
468
+ #define PUSH_INTEGER_SWAP(CType) \
469
+ do { \
470
+ CType v; \
471
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
472
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
473
+ return false; \
474
+ } \
475
+ \
476
+ *(CType *)dest = ReverseBytes(v); \
477
+ } while (false)
478
+
479
+ for (Size i = 0; i < members.len; i++) {
480
+ const RecordMember &member = members[i];
481
+ napi_value value = GetMemberValue(env, obj, member);
482
+
483
+ if (GetKindOf(env, value) == napi_undefined)
484
+ continue;
485
+
486
+ if (member.countedby >= 0) {
487
+ const char *countedby = members[member.countedby].name;
488
+
489
+ if (!CheckDynamicLength(obj, member.type->ref.type->size, countedby, value)) [[unlikely]]
490
+ return false;
491
+ }
492
+
493
+ uint8_t *dest = origin + member.offset;
494
+
495
+ switch (member.type->primitive) {
496
+ case PrimitiveKind::Void: { K_UNREACHABLE(); } break;
497
+
498
+ case PrimitiveKind::Bool: {
499
+ bool b;
500
+ napi_status status = napi_get_value_bool(env, value, &b);
501
+
502
+ if (status != napi_ok) [[unlikely]] {
503
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected boolean", GetValueType(instance, value));
504
+ return false;
505
+ }
506
+
507
+ *(bool *)dest = b;
508
+ } break;
509
+ case PrimitiveKind::Int8: { PUSH_INTEGER(int8_t); } break;
510
+ case PrimitiveKind::UInt8: { PUSH_INTEGER(uint8_t); } break;
511
+ case PrimitiveKind::Int16: { PUSH_INTEGER(int16_t); } break;
512
+ case PrimitiveKind::Int16S: { PUSH_INTEGER_SWAP(int16_t); } break;
513
+ case PrimitiveKind::UInt16: { PUSH_INTEGER(uint16_t); } break;
514
+ case PrimitiveKind::UInt16S: { PUSH_INTEGER_SWAP(uint16_t); } break;
515
+ case PrimitiveKind::Int32: { PUSH_INTEGER(int32_t); } break;
516
+ case PrimitiveKind::Int32S: { PUSH_INTEGER_SWAP(int32_t); } break;
517
+ case PrimitiveKind::UInt32: { PUSH_INTEGER(uint32_t); } break;
518
+ case PrimitiveKind::UInt32S: { PUSH_INTEGER_SWAP(uint32_t); } break;
519
+ case PrimitiveKind::Int64: { PUSH_INTEGER(int64_t); } break;
520
+ case PrimitiveKind::Int64S: { PUSH_INTEGER_SWAP(int64_t); } break;
521
+ case PrimitiveKind::UInt64: { PUSH_INTEGER(uint64_t); } break;
522
+ case PrimitiveKind::UInt64S: { PUSH_INTEGER_SWAP(uint64_t); } break;
523
+ case PrimitiveKind::String: {
524
+ const char *str;
525
+ if (!PushString(value, 1, &str)) [[unlikely]]
526
+ return false;
527
+
528
+ *(const char **)dest = str;
529
+ } break;
530
+ case PrimitiveKind::String16: {
531
+ const char16_t *str16;
532
+ if (!PushString16(value, 1, &str16)) [[unlikely]]
533
+ return false;
534
+
535
+ *(const char16_t **)dest = str16;
536
+ } break;
537
+ case PrimitiveKind::String32: {
538
+ const char32_t *str32;
539
+ if (!PushString32(value, 1, &str32)) [[unlikely]]
540
+ return false;
541
+
542
+ *(const char32_t **)dest = str32;
543
+ } break;
544
+ case PrimitiveKind::Pointer: {
545
+ void *ptr;
546
+ if (!PushPointer(value, member.type, 1, &ptr)) [[unlikely]]
547
+ return false;
548
+
549
+ *(void **)dest = ptr;
550
+ } break;
551
+ case PrimitiveKind::Record:
552
+ case PrimitiveKind::Union: {
553
+ if (!PushObject(value, member.type, dest)) [[unlikely]]
554
+ return false;
555
+ } break;
556
+ case PrimitiveKind::Array: {
557
+ if (IsArray(env, value)) {
558
+ Napi::Array array = Napi::Array(env, value);
559
+ if (!PushNormalArray(array, member.type, member.type->size, dest))
560
+ return false;
561
+ } else if (Span<uint8_t> buffer = {}; TryBuffer(env, value, &buffer)) {
562
+ PushBuffer(buffer, member.type, dest);
563
+ } else if (GetKindOf(env, value) == napi_string) {
564
+ if (!PushStringArray(value, member.type, dest))
565
+ return false;
566
+ } else {
567
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected array", GetValueType(instance, value));
568
+ return false;
569
+ }
570
+ } break;
571
+ case PrimitiveKind::Float32: {
572
+ float f;
573
+ if (!TryNumber(env, value, &f)) [[unlikely]] {
574
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
575
+ return false;
576
+ }
577
+
578
+ memcpy(dest, &f, 4);
579
+ } break;
580
+ case PrimitiveKind::Float64: {
581
+ double d;
582
+ if (!TryNumber(env, value, &d)) [[unlikely]] {
583
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
584
+ return false;
585
+ }
586
+
587
+ memcpy(dest, &d, 8);
588
+ } break;
589
+ case PrimitiveKind::Callback: {
590
+ void *ptr;
591
+ if (!PushCallback(value, member.type, &ptr))
592
+ return false;
593
+
594
+ *(void **)dest = ptr;
595
+ } break;
596
+
597
+ case PrimitiveKind::Prototype: { K_UNREACHABLE(); } break;
598
+ }
599
+ }
600
+
601
+ #undef PUSH_INTEGER_SWAP
602
+ #undef PUSH_INTEGER
603
+
604
+ return true;
605
+ }
606
+
607
+ bool CallData::PushNormalArray(Napi::Array array, const TypeInfo *type, Size size, uint8_t *origin)
608
+ {
609
+ K_ASSERT(array.IsArray());
610
+
611
+ const TypeInfo *ref = type->ref.type;
612
+ int32_t stride = type->ref.stride;
613
+
614
+ // We can't rely on type->size because type might be a pointer
615
+ Size len = (Size)array.Length();
616
+ Size available = len * stride;
617
+
618
+ if (available > size) {
619
+ len = size / stride;
620
+
621
+ if (stride != ref->size) {
622
+ int fill = (type->flags & (int)TypeFlag::FillWithOnes) ? 0xFF : 0;
623
+ MemSet(origin, fill, size);
624
+ }
625
+ } else if (stride == ref->size) {
626
+ int fill = (type->flags & (int)TypeFlag::FillWithOnes) ? 0xFF : 0;
627
+ MemSet(origin + available, fill, size - available);
628
+ } else {
629
+ int fill = (type->flags & (int)TypeFlag::FillWithOnes) ? 0xFF : 0;
630
+ MemSet(origin, fill, size);
631
+ }
632
+
633
+ Size offset = 0;
634
+
635
+ #define PUSH_ARRAY(SetCode) \
636
+ do { \
637
+ for (Size i = 0; i < len; i++) { \
638
+ napi_value value = array[(uint32_t)i].AsValue(); \
639
+ \
640
+ uint8_t *dest = origin + offset; \
641
+ SetCode \
642
+ offset += stride; \
643
+ } \
644
+ } while (false)
645
+ #define PUSH_INTEGERS(CType) \
646
+ PUSH_ARRAY({ \
647
+ CType v; \
648
+ \
649
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
650
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
651
+ return false; \
652
+ } \
653
+ \
654
+ *(CType *)dest = v; \
655
+ })
656
+ #define PUSH_INTEGERS_SWAP(CType) \
657
+ PUSH_ARRAY({ \
658
+ CType v; \
659
+ \
660
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
661
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
662
+ return false; \
663
+ } \
664
+ \
665
+ *(CType *)dest = ReverseBytes(v); \
666
+ })
667
+
668
+ switch (ref->primitive) {
669
+ case PrimitiveKind::Void: {
670
+ ThrowError<Napi::TypeError>(env, "Ambigous parameter type %1, use koffi.as(value, type)", type->name); \
671
+ return false;
672
+ } break;
673
+
674
+ case PrimitiveKind::Bool: {
675
+ PUSH_ARRAY({
676
+ bool b;
677
+ napi_status status = napi_get_value_bool(env, value, &b);
678
+
679
+ if (status != napi_ok) [[unlikely]] {
680
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected boolean", GetValueType(instance, value));
681
+ return false;
682
+ }
683
+
684
+ *(bool *)dest = b;
685
+ });
686
+ } break;
687
+ case PrimitiveKind::Int8: { PUSH_INTEGERS(int8_t); } break;
688
+ case PrimitiveKind::UInt8: { PUSH_INTEGERS(uint8_t); } break;
689
+ case PrimitiveKind::Int16: { PUSH_INTEGERS(int16_t); } break;
690
+ case PrimitiveKind::Int16S: { PUSH_INTEGERS_SWAP(int16_t); } break;
691
+ case PrimitiveKind::UInt16: { PUSH_INTEGERS(uint16_t); } break;
692
+ case PrimitiveKind::UInt16S: { PUSH_INTEGERS_SWAP(uint16_t); } break;
693
+ case PrimitiveKind::Int32: { PUSH_INTEGERS(int32_t); } break;
694
+ case PrimitiveKind::Int32S: { PUSH_INTEGERS_SWAP(int32_t); } break;
695
+ case PrimitiveKind::UInt32: { PUSH_INTEGERS(uint32_t); } break;
696
+ case PrimitiveKind::UInt32S: { PUSH_INTEGERS_SWAP(uint32_t); } break;
697
+ case PrimitiveKind::Int64: { PUSH_INTEGERS(int64_t); } break;
698
+ case PrimitiveKind::Int64S: { PUSH_INTEGERS_SWAP(int64_t); } break;
699
+ case PrimitiveKind::UInt64: { PUSH_INTEGERS(uint64_t); } break;
700
+ case PrimitiveKind::UInt64S: { PUSH_INTEGERS_SWAP(uint64_t); } break;
701
+ case PrimitiveKind::String: {
702
+ PUSH_ARRAY({
703
+ const char *str;
704
+ if (!PushString(value, 1, &str)) [[unlikely]]
705
+ return false;
706
+
707
+ *(const char **)dest = str;
708
+ });
709
+ } break;
710
+ case PrimitiveKind::String16: {
711
+ PUSH_ARRAY({
712
+ const char16_t *str16;
713
+ if (!PushString16(value, 1, &str16)) [[unlikely]]
714
+ return false;
715
+
716
+ *(const char16_t **)dest = str16;
717
+ });
718
+ } break;
719
+ case PrimitiveKind::String32: {
720
+ PUSH_ARRAY({
721
+ const char32_t *str32;
722
+ if (!PushString32(value, 1, &str32)) [[unlikely]]
723
+ return false;
724
+
725
+ *(const char32_t **)dest = str32;
726
+ });
727
+ } break;
728
+ case PrimitiveKind::Pointer: {
729
+ PUSH_ARRAY({
730
+ void *ptr;
731
+ if (!PushPointer(value, ref, 1, &ptr)) [[unlikely]]
732
+ return false;
733
+
734
+ *(const void **)dest = ptr;
735
+ });
736
+ } break;
737
+ case PrimitiveKind::Record:
738
+ case PrimitiveKind::Union: {
739
+ PUSH_ARRAY({
740
+ if (!PushObject(value, ref, dest)) [[unlikely]]
741
+ return false;
742
+ });
743
+ } break;
744
+ case PrimitiveKind::Array: {
745
+ for (Size i = 0; i < len; i++) {
746
+ napi_value value = array[(uint32_t)i].AsValue();
747
+
748
+ uint8_t *dest = origin + offset;
749
+
750
+ if (IsArray(env, value)) {
751
+ Napi::Array array = Napi::Array(env, value);
752
+ if (!PushNormalArray(array, ref, (Size)ref->size, dest))
753
+ return false;
754
+ } else if (Span<uint8_t> buffer = {}; TryBuffer(env, value, &buffer)) {
755
+ PushBuffer(buffer, ref, dest);
756
+ } else if (GetKindOf(env, value) == napi_string) {
757
+ if (!PushStringArray(value, ref, dest))
758
+ return false;
759
+ } else {
760
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected array", GetValueType(instance, value));
761
+ return false;
762
+ }
763
+
764
+ offset += stride;
765
+ }
766
+ } break;
767
+ case PrimitiveKind::Float32: {
768
+ PUSH_ARRAY({
769
+ float f;
770
+ if (!TryNumber(env, value, &f)) [[unlikely]] {
771
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
772
+ return false;
773
+ }
774
+
775
+ memcpy(dest, &f, 4);
776
+ });
777
+ } break;
778
+ case PrimitiveKind::Float64: {
779
+ PUSH_ARRAY({
780
+ double d;
781
+ if (!TryNumber(env, value, &d)) [[unlikely]] {
782
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
783
+ return false;
784
+ }
785
+
786
+ memcpy(dest, &d, 8);
787
+ });
788
+ } break;
789
+ case PrimitiveKind::Callback: {
790
+ PUSH_ARRAY({
791
+ void *ptr;
792
+ if (!PushCallback(value, ref, &ptr))
793
+ return false;
794
+
795
+ *(const void **)dest = ptr;
796
+ });
797
+ } break;
798
+
799
+ case PrimitiveKind::Prototype: { K_UNREACHABLE(); } break;
800
+ }
801
+
802
+ #undef PUSH_INTEGERS_SWAP
803
+ #undef PUSH_INTEGERS
804
+ #undef PUSH_ARRAY
805
+
806
+ return true;
807
+ }
808
+
809
+ void CallData::PushBuffer(Span<const uint8_t> buffer, const TypeInfo *type, uint8_t *origin)
810
+ {
811
+ buffer.len = std::min(buffer.len, (Size)type->size);
812
+
813
+ const TypeInfo *ref = type->ref.type;
814
+ int32_t stride = type->ref.stride;
815
+
816
+ // Go fast if possible brrrrrrr :)
817
+ if (stride == ref->size) {
818
+ MemCpy(origin, buffer.ptr, buffer.len);
819
+ MemSet(origin + buffer.len, 0, (Size)type->size - buffer.len);
820
+ } else {
821
+ Size len = buffer.len / ref->size;
822
+
823
+ for (Size i = 0; i < len; i++) {
824
+ const uint8_t *src = buffer.ptr + i * ref->size;
825
+ uint8_t *dest = origin + i * stride;
826
+
827
+ memcpy(dest, src, ref->size);
828
+ }
829
+ }
830
+
831
+ #define SWAP(CType) \
832
+ do { \
833
+ Size len = buffer.len / K_SIZE(CType); \
834
+ \
835
+ for (Size i = 0; i < len; i++) { \
836
+ CType *ptr = (CType *)(origin + i * stride); \
837
+ *ptr = ReverseBytes(*ptr); \
838
+ } \
839
+ } while (false)
840
+
841
+ if (type->primitive == PrimitiveKind::Array || type->primitive == PrimitiveKind::Pointer) {
842
+ if (ref->primitive == PrimitiveKind::Int16S || ref->primitive == PrimitiveKind::UInt16S) {
843
+ SWAP(uint16_t);
844
+ } else if (ref->primitive == PrimitiveKind::Int32S || ref->primitive == PrimitiveKind::UInt32S) {
845
+ SWAP(uint32_t);
846
+ } else if (ref->primitive == PrimitiveKind::Int64S || ref->primitive == PrimitiveKind::UInt64S) {
847
+ SWAP(uint64_t);
848
+ }
849
+ }
850
+
851
+ #undef SWAP
852
+ }
853
+
854
+ bool CallData::PushStringArray(napi_value value, const TypeInfo *type, uint8_t *origin)
855
+ {
856
+ K_ASSERT(GetKindOf(env, value) == napi_string);
857
+ K_ASSERT(type->primitive == PrimitiveKind::Array);
858
+ K_ASSERT(type->ref.stride == type->ref.type->size);
859
+
860
+ size_t encoded = 0;
861
+
862
+ switch (type->ref.type->primitive) {
863
+ case PrimitiveKind::Int8: { NAPI_OK(napi_get_value_string_utf8(env, value, (char *)origin, type->size, &encoded)); } break;
864
+ case PrimitiveKind::Int16: {
865
+ NAPI_OK(napi_get_value_string_utf16(env, value, (char16_t *)origin, type->size / 2, &encoded));
866
+ encoded *= 2;
867
+ } break;
868
+
869
+ default: {
870
+ ThrowError<Napi::TypeError>(env, "Strings cannot be converted to %1 array", type->ref.type->name);
871
+ return false;
872
+ } break;
873
+ }
874
+
875
+ MemSet(origin + encoded, 0, type->size - encoded);
876
+
877
+ return true;
878
+ }
879
+
880
+ bool CallData::PushPointer(napi_value value, const TypeInfo *type, int directions, void **out_ptr)
881
+ {
882
+ // In the past we were naively using napi_typeof() and a switch to "reduce" branching,
883
+ // but it did not match the common types very well (so there was still various if tests),
884
+ // and it turns out that napi_typeof() is made of successive type tests anyway so it
885
+ // just made things worse. Oh, well.
886
+
887
+ void *ptr = nullptr;
888
+ napi_valuetype kind = napi_undefined;
889
+
890
+ restart:
891
+
892
+ if (TryPointer(env, value, &ptr, &kind)) {
893
+ #if defined(EXTERNAL_POINTERS)
894
+ if (kind == napi_external && CheckValueTag(env, value, &CastMarker)) {
895
+ Napi::External<ValueCast> external = Napi::External<ValueCast>(env, value);
896
+ ValueCast *cast = external.Data();
897
+
898
+ NAPI_OK(napi_get_reference_value(env, cast->ref, &value));
899
+ type = cast->type;
900
+
901
+ goto restart;
902
+ }
903
+ #endif
904
+
905
+ *out_ptr = ptr;
906
+ return true;
907
+ }
908
+
909
+ #if !defined(EXTERNAL_POINTERS)
910
+ if (kind == napi_external && CheckValueTag(env, value, &CastMarker)) {
911
+ Napi::External<ValueCast> external = Napi::External<ValueCast>(env, value);
912
+ ValueCast *cast = external.Data();
913
+
914
+ napi_get_reference_value(env, cast->ref, &value);
915
+ type = cast->type;
916
+
917
+ goto restart;
918
+ }
919
+ #endif
920
+
921
+ return PushPointerSlow(value, kind, type, directions, out_ptr);
922
+ }
923
+
924
+ bool CallData::PushPointerSlow(napi_value value, napi_valuetype kind, const TypeInfo *type, int directions, void **out_ptr)
925
+ {
926
+ const TypeInfo *ref = type->ref.type;
927
+
928
+ void *ptr = nullptr;
929
+
930
+ if (kind == napi_string) {
931
+ K_ASSERT(type->primitive == PrimitiveKind::Pointer);
932
+
933
+ if (directions & 2) [[unlikely]]
934
+ goto unexpected;
935
+
936
+ if (ref == instance->void_type) {
937
+ PushStringValue(value, (const char **)out_ptr);
938
+ return true;
939
+ } else if (ref->primitive == PrimitiveKind::Int8) {
940
+ PushStringValue(value, (const char **)out_ptr);
941
+ return true;
942
+ } else if (ref->primitive == PrimitiveKind::Int16) {
943
+ PushString16Value(value, (const char16_t **)out_ptr);
944
+ return true;
945
+ } else if (ref->primitive == PrimitiveKind::Int32) {
946
+ PushString32Value(value, (const char32_t **)out_ptr);
947
+ return true;
948
+ } else {
949
+ goto unexpected;
950
+ }
951
+ } else if (IsArray(env, value)) {
952
+ Napi::Array array = Napi::Array(env, value);
953
+ Size len = PushIndirectString(array, ref, &ptr);
954
+
955
+ OutArgument::Kind out_kind;
956
+ Size out_max_len = -1;
957
+
958
+ if (len >= 0) {
959
+ if (!ref->size && ref != instance->void_type) [[unlikely]] {
960
+ ThrowError<Napi::TypeError>(env, "Cannot pass [string] value to %1", type->name);
961
+ return false;
962
+ }
963
+
964
+ switch (ref->size) {
965
+ default: { out_kind = OutArgument::Kind::String; } break;
966
+ case 2: { out_kind = OutArgument::Kind::String16; } break;
967
+ case 4: { out_kind = OutArgument::Kind::String32; } break;
968
+ }
969
+ out_max_len = len;
970
+ } else {
971
+ Size size = (Size)array.Length() * ref->size;
972
+
973
+ if (!ref->size) [[unlikely]] {
974
+ ThrowError<Napi::TypeError>(env, "Cannot pass %1 value to %2, use koffi.as()",
975
+ ref != instance->void_type ? "opaque" : "ambiguous", type->name);
976
+ return false;
977
+ }
978
+
979
+ ptr = AllocHeap(size);
980
+
981
+ if (directions & 1) {
982
+ if (!PushNormalArray(array, type, size, (uint8_t *)ptr))
983
+ return false;
984
+ } else {
985
+ MemSet(ptr, 0, size);
986
+ }
987
+
988
+ out_kind = OutArgument::Kind::Array;
989
+ }
990
+
991
+ if (directions & 2) {
992
+ OutArgument *out = out_arguments.AppendDefault();
993
+
994
+ NAPI_OK(napi_create_reference(env, value, 1, &out->ref));
995
+
996
+ out->kind = out_kind;
997
+ out->ptr = (const uint8_t *)ptr;
998
+ out->type = type;
999
+ out->max_len = out_max_len;
1000
+ }
1001
+
1002
+ *out_ptr = ptr;
1003
+ return true;
1004
+ } else if (ref->primitive == PrimitiveKind::Record ||
1005
+ ref->primitive == PrimitiveKind::Union) [[likely]] {
1006
+ ptr = (void *)AllocHeap(ref->size);
1007
+
1008
+ if (ref->primitive == PrimitiveKind::Union &&
1009
+ (directions & 2) && !CheckValueTag(env, value, &UnionValueMarker)) [[unlikely]] {
1010
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected union value", GetValueType(instance, value));
1011
+ return false;
1012
+ }
1013
+
1014
+ if (directions & 1) {
1015
+ if (!PushObject(value, ref, (uint8_t *)ptr)) [[unlikely]]
1016
+ return false;
1017
+ } else {
1018
+ if (kind != napi_object) [[unlikely]]
1019
+ return false;
1020
+
1021
+ MemSet(ptr, 0, ref->size);
1022
+ }
1023
+
1024
+ if (directions & 2) {
1025
+ OutArgument *out = out_arguments.AppendDefault();
1026
+
1027
+ NAPI_OK(napi_create_reference(env, value, 1, &out->ref));
1028
+
1029
+ out->kind = OutArgument::Kind::Object;
1030
+ out->ptr = (const uint8_t *)ptr;
1031
+ out->type = type;
1032
+ out->max_len = -1;
1033
+ }
1034
+
1035
+ *out_ptr = ptr;
1036
+ return true;
1037
+ } else if (kind == napi_function) {
1038
+ if (type->primitive != PrimitiveKind::Callback) [[unlikely]] {
1039
+ ThrowError<Napi::TypeError>(env, "Cannot pass function to type %1", type->name);
1040
+ return false;
1041
+ }
1042
+
1043
+ Napi::Function func = Napi::Function(env, value);
1044
+
1045
+ ptr = ReserveTrampoline(type->proto, func);
1046
+ if (!ptr) [[unlikely]]
1047
+ return false;
1048
+
1049
+ *out_ptr = (void *)ptr;
1050
+ return true;
1051
+ }
1052
+
1053
+ unexpected:
1054
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected %2", GetValueType(instance, value), type->name);
1055
+ return false;
1056
+ }
1057
+
1058
+ bool CallData::PushCallback(napi_value value, const TypeInfo *type, void **out_ptr)
1059
+ {
1060
+ void *ptr = nullptr;
1061
+ napi_valuetype kind = napi_undefined;
1062
+
1063
+ restart:
1064
+
1065
+ if (TryPointer(env, value, &ptr, &kind)) {
1066
+ #if defined(EXTERNAL_POINTERS)
1067
+ if (kind == napi_external && CheckValueTag(env, value, &CastMarker)) {
1068
+ Napi::External<ValueCast> external = Napi::External<ValueCast>(env, value);
1069
+ ValueCast *cast = external.Data();
1070
+
1071
+ NAPI_OK(napi_get_reference_value(env, cast->ref, &value));
1072
+ type = cast->type;
1073
+
1074
+ goto restart;
1075
+ }
1076
+ #endif
1077
+
1078
+ *out_ptr = ptr;
1079
+ return true;
1080
+ }
1081
+
1082
+ if (kind == napi_function) {
1083
+ Napi::Function func = Napi::Function(env, value);
1084
+
1085
+ ptr = ReserveTrampoline(type->proto, func);
1086
+ if (!ptr) [[unlikely]]
1087
+ return false;
1088
+
1089
+ *out_ptr = ptr;
1090
+ return true;
1091
+ #if !defined(EXTERNAL_POINTERS)
1092
+ } else if (kind == napi_external && CheckValueTag(env, value, &CastMarker)) {
1093
+ Napi::External<ValueCast> external = Napi::External<ValueCast>(env, value);
1094
+ ValueCast *cast = external.Data();
1095
+
1096
+ NAPI_OK(napi_get_reference_value(env, cast->ref, &value));
1097
+ type = cast->type;
1098
+
1099
+ goto restart;
1100
+ #endif
1101
+ }
1102
+
1103
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected %2", GetValueType(instance, value), type->name);
1104
+ return false;
1105
+ }
1106
+
1107
+ Size CallData::PushIndirectString(Napi::Array array, const TypeInfo *ref, void **out_ptr)
1108
+ {
1109
+ if (array.Length() != 1)
1110
+ return -1;
1111
+
1112
+ napi_value value = array[0u].AsValue();
1113
+
1114
+ if (ref == instance->void_type) {
1115
+ return PushStringValue(value, (const char **)out_ptr);
1116
+ } else if (ref->primitive == PrimitiveKind::Int8) {
1117
+ return PushStringValue(value, (const char **)out_ptr);
1118
+ } else if (ref->primitive == PrimitiveKind::Int16) {
1119
+ return PushString16Value(value, (const char16_t **)out_ptr);
1120
+ } else if (ref->primitive == PrimitiveKind::Int32) {
1121
+ return PushString32Value(value, (const char32_t **)out_ptr);
1122
+ } else {
1123
+ return -1;
1124
+ }
1125
+ }
1126
+
1127
+ void *CallData::ReserveTrampoline(const FunctionInfo *proto, Napi::Function func)
1128
+ {
1129
+ if (!InitAsyncBroker(env, instance)) [[unlikely]]
1130
+ return nullptr;
1131
+
1132
+ int16_t idx;
1133
+ {
1134
+ std::lock_guard<std::mutex> lock(shared.mutex);
1135
+
1136
+ if (!shared.available.len) [[unlikely]] {
1137
+ ThrowError<Napi::Error>(env, "Too many callbacks are in use (max = %1)", MaxTrampolines);
1138
+ return env.Null();
1139
+ }
1140
+ if (!used_trampolines.Available()) [[unlikely]] {
1141
+ ThrowError<Napi::Error>(env, "This call uses too many temporary callbacks (max = %1)", K_LEN(used_trampolines.data));
1142
+ return env.Null();
1143
+ }
1144
+
1145
+ idx = shared.available.data[--shared.available.len];
1146
+ used_trampolines.Append(idx);
1147
+ }
1148
+
1149
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
1150
+
1151
+ trampoline->state = 1;
1152
+ trampoline->env = env;
1153
+ trampoline->instance = instance;
1154
+ trampoline->stack0 = instance->memories[0]->stack0;
1155
+ trampoline->proto = proto;
1156
+ NAPI_OK(napi_create_reference(env, func, 1, &trampoline->func));
1157
+
1158
+ void *ptr = GetTrampoline(idx);
1159
+
1160
+ return ptr;
1161
+ }
1162
+
1163
+ bool CallData::CheckDynamicLength(napi_value obj, Size element, const char *countedby, napi_value value)
1164
+ {
1165
+ int64_t expected = -1;
1166
+ int64_t size = -1;
1167
+
1168
+ // Get expected size
1169
+ {
1170
+ napi_value by;
1171
+ napi_status status = napi_get_named_property(env, obj, countedby, &by);
1172
+
1173
+ if (status != napi_ok || !TryNumber(env, by, &expected)) [[unlikely]] {
1174
+ ThrowError<Napi::Error>(env, "Unexpected %1 value for dynamic length, expected number", GetValueType(instance, by));
1175
+ return false;
1176
+ }
1177
+
1178
+ // If we get anywhere near overflow there are other problems to worry about.
1179
+ // So let's not worry about that.
1180
+ expected *= element;
1181
+ }
1182
+
1183
+ // Get actual size
1184
+ if (uint32_t len = 0; napi_get_array_length(env, value, &len) == napi_ok) {
1185
+ size = (int64_t)len * element;
1186
+ } else if (size_t len = 0; node_api_get_buffer_info(env, value, nullptr, &len) == napi_ok) {
1187
+ size = (int64_t)len;
1188
+ } else if (size_t len = 0; napi_get_arraybuffer_info(env, value, nullptr, &len) == napi_ok) {
1189
+ size = (int64_t)len;
1190
+ } else if (!IsNullOrUndefined(env, value)) {
1191
+ size = element;
1192
+ } else {
1193
+ size = 0;
1194
+ }
1195
+
1196
+ if (size != expected) {
1197
+ ThrowError<Napi::Error>(env, "Mismatched dynamic length between '%1' and actual array", countedby);
1198
+ return false;
1199
+ }
1200
+
1201
+ return true;
1202
+ }
1203
+
1204
+ #if defined(K_DEBUG)
1205
+
1206
+ static bool IsDebugCallsEnabled()
1207
+ {
1208
+ static bool debug = GetDebugFlag("DEBUG_CALLS");
1209
+ return debug;
1210
+ }
1211
+
1212
+ void CallData::DebugCall(const FunctionInfo *func)
1213
+ {
1214
+ if (!IsDebugCallsEnabled())
1215
+ return;
1216
+
1217
+ PrintLn(StdErr, "%!..+---- %1 (%2) ----%!0", func->name, CallConventionNames[(int)func->convention]);
1218
+
1219
+ if (func->parameters.len) {
1220
+ PrintLn(StdErr, "Parameters:");
1221
+ for (Size i = 0; i < func->parameters.len; i++) {
1222
+ const ParameterInfo &param = func->parameters[i];
1223
+ PrintLn(StdErr, " %1 = %2 (%3)", i, param.type->name, FmtMemSize(param.type->size));
1224
+ }
1225
+ }
1226
+
1227
+ PrintLn(StdErr, "Return: %1 (%2)", func->ret.type->name, FmtMemSize(func->ret.type->size));
1228
+ }
1229
+
1230
+ void CallData::DebugForward()
1231
+ {
1232
+ if (!IsDebugCallsEnabled())
1233
+ return;
1234
+
1235
+ Span<const uint8_t> stack = MakeSpan(mem->stack.end, prev_stack - mem->stack.end);
1236
+ Span<const uint8_t> heap = MakeSpan(prev_heap, mem->heap.ptr - prev_heap);
1237
+
1238
+ DumpMemory("Stack", stack);
1239
+ DumpMemory("Heap", heap);
1240
+ }
1241
+
1242
+ #endif
1243
+
1244
+ static napi_value TranslateZeroCall(napi_env env, napi_callback_info info)
1245
+ {
1246
+ struct CallbackBundle {
1247
+ napi_env env;
1248
+ void *data;
1249
+ };
1250
+
1251
+ CallbackBundle **ptr = (CallbackBundle **)((uint8_t *)info + K_SIZE(void *));
1252
+ FunctionInfo *func = (FunctionInfo *)(*ptr)->data;
1253
+
1254
+ InstanceData *instance = func->instance;
1255
+ InstanceMemory *mem = instance->memories[0];
1256
+ CallData call(env, instance, mem, func->native);
1257
+
1258
+ K_DEFER_C(prev_call = instance->sync_call) { instance->sync_call = prev_call; };
1259
+ instance->sync_call = &call;
1260
+
1261
+ call.DebugCall(func);
1262
+
1263
+ napi_value ret = call.Run(func, nullptr);
1264
+ call.FinalizeFast();
1265
+
1266
+ return ret;
1267
+ }
1268
+
1269
+ napi_value TranslateFastCall(napi_env env, napi_callback_info info)
1270
+ {
1271
+ napi_value args[6];
1272
+ size_t count = 6;
1273
+ FunctionInfo *func;
1274
+
1275
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&func));
1276
+
1277
+ if (count < (size_t)func->required_parameters) [[unlikely]] {
1278
+ ThrowError<Napi::TypeError>(env, "Expected %1 arguments, got %2", func->parameters.len, count);
1279
+ return Napi::Env(env).Null();
1280
+ }
1281
+
1282
+ InstanceData *instance = func->instance;
1283
+ InstanceMemory *mem = instance->memories[0];
1284
+ CallData call(env, instance, mem, func->native);
1285
+
1286
+ K_DEFER_C(prev_call = instance->sync_call) { instance->sync_call = prev_call; };
1287
+ instance->sync_call = &call;
1288
+
1289
+ call.DebugCall(func);
1290
+
1291
+ napi_value ret = call.Run(func, args);
1292
+ call.FinalizeFast();
1293
+
1294
+ return ret;
1295
+ }
1296
+
1297
+ static FORCE_INLINE napi_value TranslateNormalCall(napi_env env, const FunctionInfo *func, void *native, napi_value *args, Size count)
1298
+ {
1299
+ if (count < func->required_parameters) [[unlikely]] {
1300
+ ThrowError<Napi::TypeError>(env, "Expected %1 arguments, got %2", func->parameters.len, count);
1301
+ return Napi::Env(env).Null();
1302
+ }
1303
+
1304
+ InstanceData *instance = func->instance;
1305
+ InstanceMemory *mem = instance->memories[0];
1306
+ CallData call(env, instance, mem, native);
1307
+
1308
+ K_DEFER_C(prev_call = instance->sync_call) { instance->sync_call = prev_call; };
1309
+ instance->sync_call = &call;
1310
+
1311
+ call.DebugCall(func);
1312
+
1313
+ napi_value ret = call.Run(func, args);
1314
+ call.Finalize();
1315
+
1316
+ return ret;
1317
+ }
1318
+
1319
+ static napi_value TranslateNormalCall(napi_env env, napi_callback_info info)
1320
+ {
1321
+ static_assert(MaxParameters >= 8);
1322
+
1323
+ napi_value args[MaxParameters];
1324
+ size_t count = 8;
1325
+ FunctionInfo *func;
1326
+
1327
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&func));
1328
+
1329
+ if (count > 8) {
1330
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, nullptr));
1331
+ count = std::min(count, (size_t)MaxParameters);
1332
+ }
1333
+
1334
+ return TranslateNormalCall(env, func, func->native, args, (Size)count);
1335
+ }
1336
+
1337
+ static FORCE_INLINE napi_value TranslateNormalCallDebugAsync(napi_env env, const FunctionInfo *func, void *native, napi_value *args, Size count)
1338
+ {
1339
+ if (count < func->required_parameters) [[unlikely]] {
1340
+ ThrowError<Napi::TypeError>(env, "Expected %1 arguments, got %2", func->parameters.len, count);
1341
+ return Napi::Env(env).Null();
1342
+ }
1343
+
1344
+ InstanceData *instance = func->instance;
1345
+ InstanceMemory *mem = instance->memories[0];
1346
+ CallData call(env, instance, mem, native);
1347
+
1348
+ K_DEFER_C(prev_call = instance->sync_call) { instance->sync_call = prev_call; };
1349
+ instance->sync_call = &call;
1350
+
1351
+ call.DebugCall(func);
1352
+
1353
+ // The async call code partly works differently, with Yield and Return instructions which do not
1354
+ // get used for normal sync calls. To exercise them, we also run the sync tests using async
1355
+ // instructions, by setting DEBUG_ASYNC=1.
1356
+
1357
+ napi_value ret;
1358
+ if (call.PrepareAsync(func, args)) {
1359
+ call.ExecuteAsync();
1360
+ ret = call.EndAsync();
1361
+ } else {
1362
+ ret = Napi::Env(env).Null();
1363
+ }
1364
+ call.Finalize();
1365
+
1366
+ return ret;
1367
+ }
1368
+
1369
+ static napi_value TranslateNormalCallDebugAsync(napi_env env, napi_callback_info info)
1370
+ {
1371
+ static_assert(MaxParameters >= 8);
1372
+
1373
+ napi_value args[MaxParameters];
1374
+ size_t count = 8;
1375
+ FunctionInfo *func;
1376
+
1377
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&func));
1378
+
1379
+ if (count > 8) {
1380
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, nullptr));
1381
+ count = std::min(count, (size_t)MaxParameters);
1382
+ }
1383
+
1384
+ return TranslateNormalCallDebugAsync(env, func, func->native, args, count);
1385
+ }
1386
+
1387
+ static napi_value TranslateVariadicCall(napi_env env, const FunctionInfo *func, void *native, napi_value *args, Size count)
1388
+ {
1389
+ FunctionInfo *variadic = nullptr;
1390
+ K_DEFER_N(err_guard) { delete variadic; };
1391
+
1392
+ InstanceData *instance = func->instance;
1393
+ InstanceMemory *mem = instance->memories[0];
1394
+ CallData call(env, instance, mem, native);
1395
+
1396
+ // Try cached function
1397
+ {
1398
+ FunctionInfo *prev = instance->variadic_func;
1399
+
1400
+ if (prev && prev->native == native) {
1401
+ Size specified = (count - prev->required_parameters);
1402
+ Size processed = (prev->parameters.len - prev->required_parameters) * 2;
1403
+
1404
+ if (specified == processed) {
1405
+ bool match = true;
1406
+
1407
+ for (Size i = prev->required_parameters, j = prev->required_parameters; i < (Size)count; i += 2, j++) {
1408
+ int directions;
1409
+ const TypeInfo *type = ResolveType(instance, args[i], &directions);
1410
+
1411
+ if (type != prev->parameters[j].type || directions != prev->parameters[j].directions) [[unlikely]] {
1412
+ match = false;
1413
+ break;
1414
+ }
1415
+ }
1416
+
1417
+ if (match) [[likely]] {
1418
+ variadic = prev;
1419
+
1420
+ // If an error happens it'll get destroyed, so don't keep it around
1421
+ instance->variadic_func = nullptr;
1422
+ }
1423
+ }
1424
+ }
1425
+ }
1426
+
1427
+ if (!variadic) {
1428
+ variadic = new FunctionInfo();
1429
+
1430
+ memcpy((void *)variadic, func, K_SIZE(*func));
1431
+ memset((void *)&variadic->parameters, 0, K_SIZE(variadic->parameters));
1432
+ memset((void *)&variadic->sync, 0, K_SIZE(variadic->sync));
1433
+ memset((void *)&variadic->async, 0, K_SIZE(variadic->async));
1434
+
1435
+ variadic->parameters = func->parameters;
1436
+ variadic->lib = nullptr;
1437
+
1438
+ if (count < variadic->required_parameters) [[unlikely]] {
1439
+ ThrowError<Napi::TypeError>(env, "Expected %1 arguments or more, got %2", variadic->parameters.len, count);
1440
+ return Napi::Env(env).Null();
1441
+ }
1442
+ if ((count - variadic->required_parameters) % 2) [[unlikely]] {
1443
+ ThrowError<Napi::Error>(env, "Missing value argument for variadic call");
1444
+ return Napi::Env(env).Null();
1445
+ }
1446
+
1447
+ for (Size i = variadic->required_parameters; i < count; i += 2) {
1448
+ ParameterInfo param = {};
1449
+
1450
+ param.type = ResolveType(instance, args[i], &param.directions);
1451
+
1452
+ if (!param.type) [[unlikely]]
1453
+ return Napi::Env(env).Null();
1454
+ if (!CanPassType(param.type, param.directions)) [[unlikely]] {
1455
+ ThrowError<Napi::TypeError>(env, "Type %1 cannot be used as a parameter", param.type->name);
1456
+ return Napi::Env(env).Null();
1457
+ }
1458
+ if (variadic->parameters.len >= MaxParameters) [[unlikely]] {
1459
+ ThrowError<Napi::TypeError>(env, "Functions cannot have more than %1 parameters", MaxParameters);
1460
+ return Napi::Env(env).Null();
1461
+ }
1462
+
1463
+ param.variadic = true;
1464
+ param.offset = (int8_t)(i + 1);
1465
+
1466
+ variadic->parameters.Append(param);
1467
+ }
1468
+
1469
+ if (!AnalyseFunction(env, instance, variadic)) [[unlikely]]
1470
+ return Napi::Env(env).Null();
1471
+ }
1472
+
1473
+ K_DEFER_C(prev_call = instance->sync_call) { instance->sync_call = prev_call; };
1474
+ instance->sync_call = &call;
1475
+
1476
+ call.DebugCall(func);
1477
+
1478
+ napi_value ret = call.Run(variadic, args);
1479
+ call.Finalize();
1480
+
1481
+ if (variadic != instance->variadic_func) {
1482
+ err_guard.Disable();
1483
+
1484
+ delete instance->variadic_func;
1485
+ instance->variadic_func = variadic;
1486
+ }
1487
+
1488
+ return ret;
1489
+ }
1490
+
1491
+ static napi_value TranslateVariadicCall(napi_env env, napi_callback_info info)
1492
+ {
1493
+ static_assert(MaxParameters >= 8);
1494
+
1495
+ napi_value args[MaxParameters];
1496
+ size_t count = 8;
1497
+ FunctionInfo *func;
1498
+
1499
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&func));
1500
+
1501
+ if (count > 8) {
1502
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, nullptr));
1503
+ count = std::min(count, (size_t)MaxParameters);
1504
+ }
1505
+
1506
+ return TranslateVariadicCall(env, func, func->native, args, (Size)count);
1507
+ }
1508
+
1509
+ class AsyncCall: public Napi::AsyncWorker {
1510
+ Napi::Env env;
1511
+
1512
+ const FunctionInfo *func;
1513
+ NoDestroy<CallData> call;
1514
+
1515
+ bool prepared = false;
1516
+
1517
+ public:
1518
+ AsyncCall(Napi::Env env, InstanceData *instance, InstanceMemory *mem, const FunctionInfo *func, Napi::Function &callback)
1519
+ : Napi::AsyncWorker(callback), env(env), func(func->Ref()), call(env, instance, mem, func->native) {}
1520
+ ~AsyncCall();
1521
+
1522
+ bool Prepare(napi_value *args) {
1523
+ call->DebugCall(func);
1524
+
1525
+ prepared = call->PrepareAsync(func, args);
1526
+
1527
+ if (!prepared) [[unlikely]] {
1528
+ Napi::Error err = env.GetAndClearPendingException();
1529
+ SetError(err.Message());
1530
+ }
1531
+
1532
+ return prepared;
1533
+ }
1534
+
1535
+ void Execute() override;
1536
+ void OnOK() override;
1537
+ void OnError(const Napi::Error& err) override;
1538
+ };
1539
+
1540
+ AsyncCall::~AsyncCall()
1541
+ {
1542
+ #if defined(K_DEBUG)
1543
+ call->~CallData();
1544
+ #endif
1545
+
1546
+ ReleaseMemory(call->instance, call->mem);
1547
+ func->Unref();
1548
+ }
1549
+
1550
+ void AsyncCall::Execute()
1551
+ {
1552
+ if (prepared) [[likely]] {
1553
+ call->ExecuteAsync();
1554
+ }
1555
+ }
1556
+
1557
+ void AsyncCall::OnOK()
1558
+ {
1559
+ K_ASSERT(prepared);
1560
+
1561
+ Napi::FunctionReference &callback = Callback();
1562
+
1563
+ napi_value ret = call->EndAsync();
1564
+ call->Finalize();
1565
+
1566
+ napi_value self = env.Null();
1567
+ napi_value args[] = { env.Null(), ret };
1568
+
1569
+ callback.Call(self, K_LEN(args), args);
1570
+ }
1571
+
1572
+ void AsyncCall::OnError(const Napi::Error& err)
1573
+ {
1574
+ Napi::FunctionReference &callback = Callback();
1575
+
1576
+ call->Finalize();
1577
+
1578
+ napi_value self = env.Null();
1579
+ napi_value args[] = { err.Value(), env.Undefined() };
1580
+
1581
+ callback.Call(self, K_LEN(args), args);
1582
+ }
1583
+
1584
+ static napi_value TranslateAsyncCall(napi_env env, napi_callback_info info)
1585
+ {
1586
+ static_assert(MaxParameters >= 6);
1587
+
1588
+ napi_value args[MaxParameters];
1589
+ size_t count = 6;
1590
+ FunctionInfo *func;
1591
+
1592
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&func));
1593
+
1594
+ if (count > 6) {
1595
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, nullptr));
1596
+ count = std::min(count, (size_t)MaxParameters);
1597
+ }
1598
+
1599
+ InstanceData *instance = func->instance;
1600
+
1601
+ if (count <= (size_t)func->required_parameters) {
1602
+ ThrowError<Napi::TypeError>(env, "Expected %1 arguments, got %2", func->required_parameters + 1, count);
1603
+ return Napi::Env(env).Null();
1604
+ }
1605
+
1606
+ Napi::Function callback = Napi::Value(env, args[func->required_parameters]).As<Napi::Function>();
1607
+
1608
+ if (!callback.IsFunction()) {
1609
+ ThrowError<Napi::TypeError>(env, "Expected callback function as last argument, got %1", GetValueType(instance, callback));
1610
+ return Napi::Env(env).Null();
1611
+ }
1612
+
1613
+ InstanceMemory *mem = AllocateMemory(instance, instance->config.async_stack_size, instance->config.async_heap_size);
1614
+ if (!mem) [[unlikely]] {
1615
+ ThrowError<Napi::Error>(env, "Too many asynchronous calls are running");
1616
+ return Napi::Env(env).Null();
1617
+ }
1618
+ AsyncCall *async = new AsyncCall(env, instance, mem, func, callback);
1619
+
1620
+ async->Prepare(args);
1621
+ async->Queue();
1622
+
1623
+ return Napi::Env(env).Undefined();
1624
+ }
1625
+
1626
+ static bool DetectDeno(Napi::Env env)
1627
+ {
1628
+ Napi::Value ret = env.RunScript("typeof Deno != 'undefined'");
1629
+ Napi::Boolean b = ret.ToBoolean();
1630
+
1631
+ return b.Value();
1632
+ }
1633
+
1634
+ static bool DetectBun(Napi::Env env)
1635
+ {
1636
+ Napi::Value ret = env.RunScript("process.isBun");
1637
+ Napi::Boolean b = ret.ToBoolean();
1638
+
1639
+ return b.Value();
1640
+ }
1641
+
1642
+ void InitTranslateZeroCall(Napi::Env env)
1643
+ {
1644
+ if (DetectDeno(env) || DetectBun(env)) {
1645
+ translate_zero_call = TranslateFastCall;
1646
+ return;
1647
+ }
1648
+
1649
+ Napi::Object self = Napi::Object::New(env);
1650
+
1651
+ napi_value func;
1652
+ napi_value ret;
1653
+
1654
+ auto cb = [](napi_env env, napi_callback_info info) {
1655
+ napi_value self;
1656
+ NAPI_OK(napi_get_cb_info(env, info, nullptr, nullptr, &self, nullptr));
1657
+
1658
+ napi_value *ptr = (napi_value *)info;
1659
+
1660
+ if (ptr[0] != self && ptr[1] != self) {
1661
+ translate_zero_call = TranslateZeroCall;
1662
+ } else {
1663
+ translate_zero_call = TranslateFastCall;
1664
+ }
1665
+
1666
+ return self;
1667
+ };
1668
+
1669
+ NAPI_OK(napi_create_function(env, nullptr, 0, cb, nullptr, &func));
1670
+ NAPI_OK(napi_call_function(env, self, func, 0, nullptr, &ret));
1671
+ }
1672
+
1673
+ napi_value CallPointer(Napi::Env env, const FunctionInfo *proto, void *native, napi_value *args, Size count)
1674
+ {
1675
+ if (proto->variadic) {
1676
+ return TranslateVariadicCall(env, proto, native, args, count);
1677
+ } else {
1678
+ return TranslateNormalCall(env, proto, native, args, count);
1679
+ }
1680
+ }
1681
+
1682
+ static void PerformAsyncRelay(napi_env, napi_value, void *, void *udata)
1683
+ {
1684
+ RelayContext *ctx = (RelayContext *)udata;
1685
+ CallData *call = ctx->call;
1686
+
1687
+ call->Relay(ctx->idx, ctx->sp);
1688
+ call->Finalize();
1689
+
1690
+ // We're done!
1691
+ std::lock_guard<std::mutex> lock(ctx->mutex);
1692
+ ctx->done = true;
1693
+ ctx->cv.notify_one();
1694
+ }
1695
+
1696
+ bool InitAsyncBroker(Napi::Env env, InstanceData *instance)
1697
+ {
1698
+ if (!instance->broker) {
1699
+ if (napi_create_threadsafe_function(env, nullptr, nullptr,
1700
+ NewString(env, "Koffi Async Callback Broker"),
1701
+ 0, 1, nullptr, nullptr, nullptr,
1702
+ PerformAsyncRelay, &instance->broker) != napi_ok) {
1703
+ LogError("Failed to create async callback broker");
1704
+ return false;
1705
+ }
1706
+
1707
+ NAPI_OK(napi_unref_threadsafe_function(env, instance->broker));
1708
+ }
1709
+
1710
+ return true;
1711
+ }
1712
+
1713
+ void *GetTrampoline(int idx)
1714
+ {
1715
+ return (void *)(TrampolineStart + TrampolineSize * idx);
1716
+ }
1717
+
1718
+ static bool CanTypeAcceptCallbacks(const TypeInfo *type)
1719
+ {
1720
+ if (type->primitive == PrimitiveKind::Pointer)
1721
+ return true;
1722
+ if (type->primitive == PrimitiveKind::Callback)
1723
+ return true;
1724
+
1725
+ if (type->primitive == PrimitiveKind::Record ||
1726
+ type->primitive == PrimitiveKind::Union) {
1727
+ for (const RecordMember &member: type->members) {
1728
+ if (CanTypeAcceptCallbacks(member.type))
1729
+ return false;
1730
+ }
1731
+ }
1732
+
1733
+ return true;
1734
+ }
1735
+
1736
+ static bool CanUseFastCall(const FunctionInfo *func)
1737
+ {
1738
+ if (func->parameters.len > 6)
1739
+ return false;
1740
+
1741
+ // Fast calls basically skip CallData::Finalize(), which handles output arguments
1742
+ // and temporary callback trampolines. If the function does not use any
1743
+ // output argument and cannot accept callbacks (so no pointer or callback arguments),
1744
+ // we can skip finalization!
1745
+
1746
+ for (const ParameterInfo &param: func->parameters) {
1747
+ if (param.directions & 2)
1748
+ return false;
1749
+ if (CanTypeAcceptCallbacks(param.type))
1750
+ return false;
1751
+ }
1752
+
1753
+ return true;
1754
+ }
1755
+
1756
+ napi_value DescribeFunction(InstanceData *instance, const FunctionInfo *func)
1757
+ {
1758
+ static const char *const DirectionNames[] = {
1759
+ nullptr,
1760
+ "Input",
1761
+ "Output",
1762
+ "Input/Output"
1763
+ };
1764
+
1765
+ Napi::Env env = instance->env;
1766
+
1767
+ Napi::Object meta = Napi::Object::New(env);
1768
+ Napi::Array arguments = Napi::Array::New(env, func->parameters.len);
1769
+
1770
+ meta.Set("name", NewString(env, func->name));
1771
+ meta.Set("arguments", arguments);
1772
+ meta.Set("result", WrapType(instance, func->ret.type));
1773
+
1774
+ for (Size i = 0; i < func->parameters.len; i++) {
1775
+ const ParameterInfo &param = func->parameters[i];
1776
+ Napi::Object obj = Napi::Object::New(env);
1777
+
1778
+ obj.Set("type", WrapType(instance, param.type));
1779
+ obj.Set("direction", NewString(env, DirectionNames[param.directions]));
1780
+
1781
+ arguments.Set((uint32_t)i, obj);
1782
+ }
1783
+
1784
+ meta.Freeze();
1785
+
1786
+ return meta;
1787
+ }
1788
+
1789
+ static bool IsDebugAsyncEnabled()
1790
+ {
1791
+ static bool debug = GetDebugFlag("DEBUG_ASYNC");
1792
+ return debug;
1793
+ }
1794
+
1795
+ napi_value WrapFunction(InstanceData *instance, const FunctionInfo *func)
1796
+ {
1797
+ Napi::Env env = instance->env;
1798
+
1799
+ Napi::Function wrapper;
1800
+ {
1801
+ napi_value value;
1802
+
1803
+ if (func->variadic) {
1804
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, TranslateVariadicCall, (void *)func->Ref(), &value));
1805
+ } else if (IsDebugAsyncEnabled()) {
1806
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, TranslateNormalCallDebugAsync, (void *)func->Ref(), &value));
1807
+ } else if (!func->parameters.len) {
1808
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, translate_zero_call, (void *)func->Ref(), &value));
1809
+ } else if (CanUseFastCall(func)) {
1810
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, TranslateFastCall, (void *)func->Ref(), &value));
1811
+ } else {
1812
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, TranslateNormalCall, (void *)func->Ref(), &value));
1813
+ }
1814
+
1815
+ wrapper = Napi::Function(env, value);
1816
+ wrapper.AddFinalizer([](Napi::BasicEnv, FunctionInfo *func) { func->Unref(); }, (FunctionInfo *)func);
1817
+ }
1818
+
1819
+ if (!func->variadic) {
1820
+ napi_value value;
1821
+ NAPI_OK(napi_create_function(env, func->name, NAPI_AUTO_LENGTH, TranslateAsyncCall, (void *)func->Ref(), &value));
1822
+
1823
+ Napi::Function async = Napi::Function(env, value);
1824
+ async.AddFinalizer([](Napi::BasicEnv, FunctionInfo *func) { func->Unref(); }, (FunctionInfo *)func);
1825
+
1826
+ wrapper.Set("async", async);
1827
+ }
1828
+
1829
+ napi_value meta = DescribeFunction(instance, func);
1830
+ wrapper.Set("info", meta);
1831
+
1832
+ return wrapper;
1833
+ }
1834
+
1835
+ static FORCE_INLINE bool CheckTrampolineStatus(TrampolineInfo *trampoline)
1836
+ {
1837
+ if (trampoline->state == 1) [[likely]]
1838
+ return true;
1839
+
1840
+ Napi::Env env = trampoline->env;
1841
+
1842
+ if (!trampoline->state) {
1843
+ ThrowError<Napi::Error>(env, "Cannot use non-registered callback beyond FFI call");
1844
+ trampoline->state = -1;
1845
+ }
1846
+
1847
+ // We use trampoline->state < 0 as a signal than an exception has occured, because we want
1848
+ // to avoid calling IsExceptionPending() in the happy path. But trampolines get reused, so
1849
+ // there might not be an exception anymore!
1850
+ if (!env.IsExceptionPending()) {
1851
+ trampoline->state = 1;
1852
+ return true;
1853
+ }
1854
+
1855
+ return false;
1856
+ }
1857
+
1858
+ extern "C" void RelayCallback(Size idx, uint8_t *sp)
1859
+ {
1860
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
1861
+ InstanceData *instance = trampoline->instance;
1862
+
1863
+ // Fast path: main thread and we are running a native call through Koffi.
1864
+ // But this means we are running on the custom Koffi stack, which could trip up
1865
+ // Node and V8, so we need to switch back to the normal/main stack.
1866
+ if (sp >= trampoline->stack0.ptr && sp <= trampoline->stack0.end) [[likely]] {
1867
+ CallData *call = instance->sync_call;
1868
+
1869
+ SwitchAndRelay(call, idx, sp, call->saved_sp, &call->mem->stack);
1870
+ return;
1871
+ }
1872
+
1873
+ if (!CheckTrampolineStatus(trampoline))
1874
+ return;
1875
+
1876
+ // Otherwise, we need to allocate memory to perform the callback.
1877
+ // Since the necessary machinery live in CallData, just use a temporary instance.
1878
+ // In some cases we would reuse the existing call, but it is rare so let's ignore
1879
+ // this for simplicity.
1880
+
1881
+ Napi::Env env = trampoline->env;
1882
+
1883
+ InstanceMemory *mem = AllocateMemory(instance, instance->config.async_stack_size, instance->config.async_heap_size);
1884
+ if (!mem) [[unlikely]] {
1885
+ ThrowError<Napi::Error>(env, "Too many asynchronous calls are running");
1886
+ return;
1887
+ }
1888
+ K_DEFER { ReleaseMemory(instance, mem); };
1889
+
1890
+ if (std::this_thread::get_id() == instance->main_thread_id) {
1891
+ CallData call(env, instance, mem, nullptr);
1892
+ K_DEFER { call.Finalize(); };
1893
+
1894
+ napi_handle_scope scope;
1895
+ NAPI_OK(napi_open_handle_scope(env, &scope));
1896
+ K_DEFER { napi_close_handle_scope(env, scope); };
1897
+
1898
+ call.Relay(idx, sp);
1899
+ } else {
1900
+ CallData call(env, instance, mem, nullptr);
1901
+ call.RelayAsync(idx, sp);
1902
+ }
1903
+ }
1904
+
1905
+ extern "C" void RelayDirect(CallData *call, Size idx, uint8_t *sp)
1906
+ {
1907
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
1908
+
1909
+ #if defined(_WIN32)
1910
+ TEB *teb = GetTEB();
1911
+ InstanceData *instance = trampoline->instance;
1912
+
1913
+ // Restore previous stack limits at the end
1914
+ K_DEFER_C(base = teb->StackBase,
1915
+ limit = teb->StackLimit,
1916
+ dealloc = teb->DeallocationStack) {
1917
+ teb->StackBase = base;
1918
+ teb->StackLimit = limit;
1919
+ teb->DeallocationStack = dealloc;
1920
+ };
1921
+
1922
+ // Adjust stack limits so SEH works correctly
1923
+ teb->StackBase = instance->main_stack_max;
1924
+ teb->StackLimit = instance->main_stack_min;
1925
+ teb->DeallocationStack = instance->main_stack_min;
1926
+ #endif
1927
+
1928
+ if (!CheckTrampolineStatus(trampoline))
1929
+ return;
1930
+
1931
+ // Relay the call
1932
+ {
1933
+ napi_handle_scope scope;
1934
+ NAPI_OK(napi_open_handle_scope(call->env, &scope));
1935
+ K_DEFER { napi_close_handle_scope(call->env, scope); };
1936
+
1937
+ call->Relay(idx, sp);
1938
+ }
1939
+ }
1940
+
1941
+ bool Encode(InstanceData *instance, uint8_t *origin, napi_value value, const TypeInfo *type)
1942
+ {
1943
+ Napi::Env env = instance->env;
1944
+
1945
+ InstanceMemory mem = {};
1946
+ CallData call(env, instance, &mem, nullptr);
1947
+
1948
+ #define PUSH_INTEGER(CType) \
1949
+ do { \
1950
+ CType v; \
1951
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
1952
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
1953
+ return false; \
1954
+ } \
1955
+ \
1956
+ *(CType *)origin = v; \
1957
+ } while (false)
1958
+ #define PUSH_INTEGER_SWAP(CType) \
1959
+ do { \
1960
+ CType v; \
1961
+ if (!TryNumber(env, value, &v)) [[unlikely]] { \
1962
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value)); \
1963
+ return false; \
1964
+ } \
1965
+ \
1966
+ *(CType *)origin = ReverseBytes(v); \
1967
+ } while (false)
1968
+
1969
+ switch (type->primitive) {
1970
+ case PrimitiveKind::Void: { K_UNREACHABLE(); } break;
1971
+
1972
+ case PrimitiveKind::Bool: {
1973
+ bool b;
1974
+ napi_status status = napi_get_value_bool(env, value, &b);
1975
+
1976
+ if (status != napi_ok) [[unlikely]] {
1977
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected boolean", GetValueType(instance, value));
1978
+ return false;
1979
+ }
1980
+
1981
+ *(bool *)origin = b;
1982
+ } break;
1983
+ case PrimitiveKind::Int8: { PUSH_INTEGER(int8_t); } break;
1984
+ case PrimitiveKind::UInt8: { PUSH_INTEGER(uint8_t); } break;
1985
+ case PrimitiveKind::Int16: { PUSH_INTEGER(int16_t); } break;
1986
+ case PrimitiveKind::Int16S: { PUSH_INTEGER_SWAP(int16_t); } break;
1987
+ case PrimitiveKind::UInt16: { PUSH_INTEGER(uint16_t); } break;
1988
+ case PrimitiveKind::UInt16S: { PUSH_INTEGER_SWAP(uint16_t); } break;
1989
+ case PrimitiveKind::Int32: { PUSH_INTEGER(int32_t); } break;
1990
+ case PrimitiveKind::Int32S: { PUSH_INTEGER_SWAP(int32_t); } break;
1991
+ case PrimitiveKind::UInt32: { PUSH_INTEGER(uint32_t); } break;
1992
+ case PrimitiveKind::UInt32S: { PUSH_INTEGER_SWAP(uint32_t); } break;
1993
+ case PrimitiveKind::Int64: { PUSH_INTEGER(int64_t); } break;
1994
+ case PrimitiveKind::Int64S: { PUSH_INTEGER_SWAP(int64_t); } break;
1995
+ case PrimitiveKind::UInt64: { PUSH_INTEGER(uint64_t); } break;
1996
+ case PrimitiveKind::UInt64S: { PUSH_INTEGER_SWAP(uint64_t); } break;
1997
+ case PrimitiveKind::String: {
1998
+ const char *str;
1999
+ if (!call.PushString(value, 1, &str)) [[unlikely]]
2000
+ return false;
2001
+ *(const char **)origin = str;
2002
+ } break;
2003
+ case PrimitiveKind::String16: {
2004
+ const char16_t *str16;
2005
+ if (!call.PushString16(value, 1, &str16)) [[unlikely]]
2006
+ return false;
2007
+ *(const char16_t **)origin = str16;
2008
+ } break;
2009
+ case PrimitiveKind::String32: {
2010
+ const char32_t *str32;
2011
+ if (!call.PushString32(value, 1, &str32)) [[unlikely]]
2012
+ return false;
2013
+ *(const char32_t **)origin = str32;
2014
+ } break;
2015
+ case PrimitiveKind::Pointer: {
2016
+ void *ptr;
2017
+ if (!call.PushPointer(value, type, 1, &ptr)) [[unlikely]]
2018
+ return false;
2019
+ *(void **)origin = ptr;
2020
+ } break;
2021
+ case PrimitiveKind::Record:
2022
+ case PrimitiveKind::Union: {
2023
+ if (!call.PushObject(value, type, origin)) [[unlikely]]
2024
+ return false;
2025
+ } break;
2026
+ case PrimitiveKind::Array: {
2027
+ if (IsArray(env, value)) {
2028
+ Napi::Array array = Napi::Array(env, value);
2029
+ if (!call.PushNormalArray(array, type, type->size, origin))
2030
+ return false;
2031
+ } else if (Span<uint8_t> buffer = {}; TryBuffer(env, value, &buffer)) {
2032
+ call.PushBuffer(buffer, type, origin);
2033
+ } else if (GetKindOf(env, value) == napi_string) {
2034
+ if (!call.PushStringArray(value, type, origin))
2035
+ return false;
2036
+ } else {
2037
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected array", GetValueType(instance, value));
2038
+ return false;
2039
+ }
2040
+ } break;
2041
+ case PrimitiveKind::Float32: {
2042
+ float f;
2043
+ if (!TryNumber(env, value, &f)) [[unlikely]] {
2044
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
2045
+ return false;
2046
+ }
2047
+
2048
+ memcpy(origin, &f, 4);
2049
+ } break;
2050
+ case PrimitiveKind::Float64: {
2051
+ double d;
2052
+ if (!TryNumber(env, value, &d)) [[unlikely]] {
2053
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected number", GetValueType(instance, value));
2054
+ return false;
2055
+ }
2056
+
2057
+ memcpy(origin, &d, 8);
2058
+ } break;
2059
+ case PrimitiveKind::Callback: {
2060
+ void *ptr;
2061
+ if (!TryPointer(env, value, &ptr)) [[unlikely]] {
2062
+ if (GetKindOf(env, value) == napi_function) {
2063
+ ThrowError<Napi::Error>(env, "Cannot encode non-registered callback");
2064
+ } else {
2065
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value, expected %2", GetValueType(instance, value), type->name);
2066
+ }
2067
+ return false;
2068
+ }
2069
+
2070
+ *(void **)origin = ptr;
2071
+ } break;
2072
+
2073
+ case PrimitiveKind::Prototype: { K_UNREACHABLE(); } break;
2074
+ }
2075
+
2076
+ #undef PUSH_INTEGER_SWAP
2077
+ #undef PUSH_INTEGER
2078
+
2079
+ // Keep memory around if any was allocated
2080
+ if (mem.allocator.IsUsed()) {
2081
+ LinkedAllocator *copy = instance->encode_map.FindValue(origin, nullptr);
2082
+
2083
+ if (!copy) {
2084
+ copy = instance->encode_allocators.AppendDefault();
2085
+ instance->encode_map.Set(origin, copy);
2086
+ }
2087
+
2088
+ std::swap(mem.allocator, *copy);
2089
+ }
2090
+
2091
+ return true;
2092
+ }
2093
+
2094
+ }