@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,3009 @@
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 "ffi.hh"
6
+ #include "call.hh"
7
+ #include "parser.hh"
8
+ #include "type.hh"
9
+ #include "util.hh"
10
+ #include "uv.hh"
11
+ #if defined(_WIN32)
12
+ #include "win32.hh"
13
+ #endif
14
+ #include "errno.inc"
15
+
16
+ #if defined(_WIN32)
17
+ #if !defined(NOMINMAX)
18
+ #define NOMINMAX
19
+ #endif
20
+ #if !defined(WIN32_LEAN_AND_MEAN)
21
+ #define WIN32_LEAN_AND_MEAN
22
+ #endif
23
+ #include <windows.h>
24
+ #include <ntsecapi.h>
25
+ #else
26
+ #include <dlfcn.h>
27
+ #include <unistd.h>
28
+ #include <sys/mman.h>
29
+ #if !defined(MAP_STACK)
30
+ #define MAP_STACK 0
31
+ #endif
32
+ #endif
33
+ #include <wchar.h>
34
+
35
+ #include <napi.h>
36
+
37
+ namespace K {
38
+
39
+ // Value does not matter, the tag system uses memory addresses
40
+ const napi_type_tag LibraryHandleMarker = { 0xdb9b066e6f700474, 0x0aecd7e4c63fbda9 };
41
+ const napi_type_tag TypeObjectMarker = { 0x1cc449675b294374, 0xbb13a50e97dcb017 };
42
+ const napi_type_tag DirectionMarker = { 0xf9c306238b480580, 0xc2e168524a0823f5 };
43
+ const napi_type_tag UnionValueMarker = { 0x5eaf2245526a4c7d, 0x8c86c9ee2b96ffc8 };
44
+ const napi_type_tag CastMarker = { 0x77f459614a0a412f, 0x80b3dda1341dc8df };
45
+
46
+ SharedData shared;
47
+
48
+ // Some Node-API functions are loaded dynamically to work around bugs or because they are recent
49
+ napi_status (NAPI_CDECL *node_api_delete_reference)(node_api_basic_env env, napi_ref ref);
50
+ napi_status (NAPI_CDECL *node_api_get_buffer_info)(napi_env env, napi_value value, void **data, size_t *length);
51
+ napi_status (NAPI_CDECL *node_api_create_property_key_utf8)(napi_env env, const char* str, size_t length, napi_value* result);
52
+ napi_status (NAPI_CDECL *node_api_post_finalizer)(node_api_basic_env env, napi_finalize finalize_cb, void* finalize_data, void* finalize_hint);
53
+ napi_status (NAPI_CDECL *node_api_create_object_with_properties)(napi_env env, napi_value prototype_or_null, const napi_value *property_names,
54
+ const napi_value *property_values, size_t property_count, napi_value *result);
55
+
56
+ static bool ChangeSize(InstanceData *instance, const char *name, Napi::Value value, Size min_size, Size max_size, Size *out_size)
57
+ {
58
+ Napi::Env env = instance->env;
59
+
60
+ if (!value.IsNumber()) {
61
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for '%2', expected number", GetValueType(instance, value), name);
62
+ return false;
63
+ }
64
+
65
+ int64_t size = value.As<Napi::Number>().Int64Value();
66
+
67
+ if (size < min_size || size > max_size) {
68
+ ThrowError<Napi::Error>(env, "Setting '%1' must be between %2 and %3", name, FmtMemSize(min_size), FmtMemSize(max_size));
69
+ return false;
70
+ }
71
+
72
+ *out_size = (Size)size;
73
+ return true;
74
+ }
75
+
76
+ static bool ChangeMemorySize(InstanceData *instance, const char *name, Napi::Value value, Size *out_size)
77
+ {
78
+ const Size MinSize = Kibibytes(1);
79
+ const Size MaxSize = Mebibytes(16);
80
+
81
+ return ChangeSize(instance, name, value, MinSize, MaxSize, out_size);
82
+ }
83
+
84
+ static bool ChangeAsyncLimit(InstanceData *instance, const char *name, Napi::Value value, int max, int *out_limit)
85
+ {
86
+ Napi::Env env = value.Env();
87
+
88
+ if (!value.IsNumber()) {
89
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for '%2', expected number", GetValueType(instance, value), name);
90
+ return false;
91
+ }
92
+
93
+ int64_t n = value.As<Napi::Number>().Int64Value();
94
+
95
+ if (n < 0 || n > max) {
96
+ ThrowError<Napi::Error>(env, "Setting '%1' must be between 0 and %2", name, max);
97
+ return false;
98
+ }
99
+
100
+ *out_limit = (int)n;
101
+ return true;
102
+ }
103
+
104
+ static Napi::Value GetSetConfig(const Napi::CallbackInfo &info)
105
+ {
106
+ Napi::Env env = info.Env();
107
+ InstanceData *instance = (InstanceData *)info.Data();
108
+
109
+ if (info.Length()) {
110
+ if (instance->memories.len) {
111
+ ThrowError<Napi::Error>(env, "Cannot change Koffi configuration once a library has been loaded");
112
+ return env.Null();
113
+ }
114
+
115
+ if (!IsObject(env, info[0])) {
116
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for config, expected object", GetValueType(instance, info[0]));
117
+ return env.Null();
118
+ }
119
+
120
+ decltype(instance->config) new_config = instance->config;
121
+ int max_async_calls = new_config.resident_async_pools + new_config.max_temporaries;
122
+
123
+ Napi::Object obj = info[0].As<Napi::Object>();
124
+ Napi::Array keys = GetOwnPropertyNames(env, obj);
125
+
126
+ for (uint32_t i = 0; i < keys.Length(); i++) {
127
+ std::string key = keys.Get(i).As<Napi::String>();
128
+ Napi::Value value = obj[key];
129
+
130
+ if (key == "sync_stack_size") {
131
+ if (!ChangeMemorySize(instance, key.c_str(), value, &new_config.sync_stack_size))
132
+ return env.Null();
133
+ } else if (key == "sync_heap_size") {
134
+ if (!ChangeMemorySize(instance, key.c_str(), value, &new_config.sync_heap_size))
135
+ return env.Null();
136
+ } else if (key == "async_stack_size") {
137
+ if (!ChangeMemorySize(instance, key.c_str(), value, &new_config.async_stack_size))
138
+ return env.Null();
139
+ } else if (key == "async_heap_size") {
140
+ if (!ChangeMemorySize(instance, key.c_str(), value, &new_config.async_heap_size))
141
+ return env.Null();
142
+ } else if (key == "resident_async_pools") {
143
+ if (!ChangeAsyncLimit(instance, key.c_str(), value, K_LEN(instance->memories.data) - 1, &new_config.resident_async_pools))
144
+ return env.Null();
145
+ } else if (key == "max_async_calls") {
146
+ if (!ChangeAsyncLimit(instance, key.c_str(), value, MaxAsyncCalls, &max_async_calls))
147
+ return env.Null();
148
+ } else if (key == "max_type_size") {
149
+ if (!ChangeSize(instance, key.c_str(), value, 32, Mebibytes(512), &new_config.max_type_size))
150
+ return env.Null();
151
+ } else {
152
+ ThrowError<Napi::Error>(env, "Unexpected config member '%1'", key.c_str());
153
+ return env.Null();
154
+ }
155
+ }
156
+
157
+ if (max_async_calls < new_config.resident_async_pools) {
158
+ ThrowError<Napi::Error>(env, "Setting max_async_calls must be >= to resident_async_pools");
159
+ return env.Null();
160
+ }
161
+
162
+ new_config.max_temporaries = max_async_calls - new_config.resident_async_pools;
163
+ instance->config = new_config;
164
+ }
165
+
166
+ Napi::Object obj = Napi::Object::New(env);
167
+
168
+ obj.Set("sync_stack_size", instance->config.sync_stack_size);
169
+ obj.Set("sync_heap_size", instance->config.sync_heap_size);
170
+ obj.Set("async_stack_size", instance->config.async_stack_size);
171
+ obj.Set("async_heap_size", instance->config.async_heap_size);
172
+ obj.Set("resident_async_pools", instance->config.resident_async_pools);
173
+ obj.Set("max_async_calls", instance->config.resident_async_pools + instance->config.max_temporaries);
174
+ obj.Set("max_type_size", instance->config.max_type_size);
175
+
176
+ return obj;
177
+ }
178
+
179
+ static Napi::Value GetStats(const Napi::CallbackInfo &info)
180
+ {
181
+ Napi::Env env = info.Env();
182
+ InstanceData *instance = (InstanceData *)info.Data();
183
+
184
+ Napi::Object obj = Napi::Object::New(env);
185
+
186
+ obj.Set("disposed", instance->stats.disposed);
187
+
188
+ return obj;
189
+ }
190
+
191
+ static inline bool CheckAlignment(int64_t align)
192
+ {
193
+ bool valid = (align > 0) && (align <= 8 && !(align & (align - 1)));
194
+ return valid;
195
+ }
196
+
197
+ static bool IsNameValid(const char *name)
198
+ {
199
+ if (!IsXidStart(name[0]))
200
+ return false;
201
+
202
+ for (Size i = 1; name[i]; i++) {
203
+ if (!IsXidContinue(name[i])) [[unlikely]]
204
+ return false;
205
+ }
206
+
207
+ return true;
208
+ }
209
+
210
+ static bool MapType(Napi::Env env, InstanceData *instance, const TypeInfo *type, const char *name)
211
+ {
212
+ if (!IsNameValid(name)) {
213
+ ThrowError<Napi::Error>(env, "Invalid type name '%1'", name);
214
+ return false;
215
+ }
216
+
217
+ bool inserted;
218
+ instance->types_map.InsertOrGet(name, type, &inserted);
219
+
220
+ if (!inserted) {
221
+ ThrowError<Napi::Error>(env, "Duplicate type name '%1'", name);
222
+ return false;
223
+ }
224
+
225
+ return true;
226
+ }
227
+
228
+ static bool FinalizeCompositeType(Napi::Env env, TypeInfo *type, PrimitiveKind primitive, Size size)
229
+ {
230
+ type->primitive = primitive;
231
+
232
+ if (node_api_create_property_key_utf8) {
233
+ for (RecordMember &member: type->members) {
234
+ napi_value key = nullptr;
235
+
236
+ NAPI_OK(node_api_create_property_key_utf8(env, member.name, NAPI_AUTO_LENGTH, &key));
237
+ NAPI_OK(napi_create_reference(env, key, 1, &member.key));
238
+ }
239
+ }
240
+
241
+ size = AlignLen(size, type->align);
242
+ if (!size) {
243
+ ThrowError<Napi::Error>(env, "Empty type '%1' is not allowed in C", type->name);
244
+ return false;
245
+ }
246
+ type->size = (int32_t)size;
247
+
248
+ return true;
249
+ }
250
+
251
+ static Napi::Value CreateStructType(const Napi::CallbackInfo &info, bool pad)
252
+ {
253
+ Napi::Env env = info.Env();
254
+ InstanceData *instance = (InstanceData *)info.Data();
255
+
256
+ if (info.Length() < 1) {
257
+ ThrowError<Napi::TypeError>(env, "Expected 1 or 2 arguments, got %1", info.Length());
258
+ return env.Null();
259
+ }
260
+
261
+ bool skip = (info.Length() > 1);
262
+ bool named = skip && !IsNullOrUndefined(env, info[0]);
263
+ #if defined(EXTERNAL_TYPES)
264
+ bool redefine = named && info[0].IsExternal() && CheckValueTag(env, info[0], &TypeObjectMarker);
265
+ #else
266
+ bool redefine = named && info[0].IsObject() && CheckValueTag(env, info[0], &TypeObjectMarker);
267
+ #endif
268
+
269
+ if (named && !info[0].IsString() && !redefine) {
270
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
271
+ return env.Null();
272
+ }
273
+ if (!IsObject(env, info[skip])) {
274
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for members, expected object", GetValueType(instance, info[1]));
275
+ return env.Null();
276
+ }
277
+
278
+ Napi::String name = info[0].As<Napi::String>();
279
+ Napi::Object obj = info[skip].As<Napi::Object>();
280
+ Napi::Array keys = GetOwnPropertyNames(env, obj);
281
+
282
+ K_DEFER_NC(err_guard, count = instance->types.count) {
283
+ Size start = count + !skip;
284
+
285
+ for (Size i = start; i < instance->types.count; i++) {
286
+ const TypeInfo *it = &instance->types[i];
287
+ const TypeInfo **ptr = instance->types_map.Find(it->name);
288
+
289
+ if (ptr && *ptr == it) {
290
+ instance->types_map.Remove(ptr);
291
+ }
292
+ }
293
+
294
+ instance->types.RemoveFrom(count);
295
+ };
296
+
297
+ TypeInfo *type = instance->types.AppendDefault();
298
+ TypeInfo *replace = nullptr;
299
+
300
+ if (redefine) {
301
+ #if defined(EXTERNAL_TYPES)
302
+ Napi::External<TypeInfo> external = name.As<Napi::External<TypeInfo>>();
303
+ replace = external.Data();
304
+ #else
305
+ TypeObject *defn = nullptr;
306
+ NAPI_OK(napi_unwrap(env, name, (void **)&defn));
307
+
308
+ replace = (TypeInfo *)defn->GetType();
309
+ #endif
310
+
311
+ type->instance = instance;
312
+ type->name = replace->name;
313
+
314
+ if (replace->primitive != PrimitiveKind::Void || replace == instance->void_type) {
315
+ ThrowError<Napi::TypeError>(env, "Cannot redefine non-opaque type %1", replace->name);
316
+ return env.Null();
317
+ }
318
+ } else if (named) {
319
+ type->instance = instance;
320
+ type->name = DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr;
321
+
322
+ if (!MapType(env, instance, type, type->name))
323
+ return env.Null();
324
+ } else {
325
+ type->instance = instance;
326
+ type->name = Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
327
+ }
328
+
329
+ type->primitive = PrimitiveKind::Void;
330
+ type->align = 1;
331
+
332
+ HashSet<const char *> members;
333
+ Size size = 0;
334
+
335
+ for (uint32_t i = 0; i < keys.Length(); i++) {
336
+ RecordMember member = {};
337
+
338
+ std::string key = keys.Get(i).As<Napi::String>();
339
+ Napi::Value value = obj[key];
340
+ int16_t align = 0;
341
+
342
+ member.name = DuplicateString(key.c_str(), &instance->str_alloc).ptr;
343
+
344
+ if (value.IsArray()) {
345
+ Napi::Array array = value.As<Napi::Array>();
346
+
347
+ if (array.Length() != 2 || !array.Get(0u).IsNumber()) {
348
+ ThrowError<Napi::Error>(env, "Member specifier array must contain alignement value and type");
349
+ return env.Null();
350
+ }
351
+
352
+ int64_t align64 = array.Get(0u).As<Napi::Number>().Int64Value();
353
+
354
+ if (!CheckAlignment(align64)) {
355
+ ThrowError<Napi::Error>(env, "Alignment of member '%1' must be 1, 2, 4 or 8", member.name);
356
+ return env.Null();
357
+ }
358
+
359
+ value = array[1u];
360
+ align = (int16_t)align64;
361
+ }
362
+
363
+ member.type = ResolveType(instance, value);
364
+ if (!member.type)
365
+ return env.Null();
366
+ if (!CanStoreType(member.type)) {
367
+ ThrowError<Napi::TypeError>(env, "Type %1 cannot be used as a member (maybe try %1 *)", member.type->name);
368
+ return env.Null();
369
+ }
370
+
371
+ if (!align) {
372
+ align = pad ? member.type->align : 1;
373
+ }
374
+ member.offset = (int32_t)AlignLen(size, align);
375
+
376
+ size = member.offset + member.type->size;
377
+ type->align = std::max(type->align, align);
378
+
379
+ member.countedby = -1;
380
+
381
+ if (size > instance->config.max_type_size) {
382
+ ThrowError<Napi::Error>(env, "Struct '%1' size is too high (max = %2)", type->name, FmtMemSize(size));
383
+ return env.Null();
384
+ }
385
+
386
+ if (TestStr(member.name, "_"))
387
+ continue;
388
+
389
+ if (!IsNameValid(member.name)) {
390
+ ThrowError<Napi::Error>(env, "Invalid member name '%1'", member.name);
391
+ return env.Null();
392
+ }
393
+
394
+ bool inserted;
395
+ members.InsertOrGet(member.name, &inserted);
396
+
397
+ if (!inserted) {
398
+ ThrowError<Napi::Error>(env, "Duplicate member '%1' in struct '%2'", member.name, type->name);
399
+ return env.Null();
400
+ }
401
+
402
+ type->members.Append(member);
403
+ }
404
+
405
+ for (Size i = 0; i < type->members.len; i++) {
406
+ RecordMember *member = &type->members[i];
407
+ const char *countedby = member->type->countedby;
408
+
409
+ if (countedby) {
410
+ const RecordMember *by = std::find_if(type->members.begin(), type->members.end(),
411
+ [&](const RecordMember &member) { return TestStr(member.name, countedby); });
412
+
413
+ if (by == type->members.end()) {
414
+ ThrowError<Napi::Error>(env, "Record type %1 does not have member '%2'", type->name, countedby);
415
+ return env.Null();
416
+ }
417
+ if (!IsInteger(by->type)) {
418
+ ThrowError<Napi::Error>(env, "Dynamic length member %1 is not an integer", countedby);
419
+ return env.Null();
420
+ }
421
+ if (member->type->primitive == PrimitiveKind::Array && i < type->members.len - 1) {
422
+ ThrowError<Napi::Error>(env, "Flexible array '%1' is not the last member of struct", member->name);
423
+ return env.Null();
424
+ }
425
+
426
+ member->countedby = by - type->members.ptr;
427
+ }
428
+ }
429
+
430
+ if (!FinalizeCompositeType(env, type, PrimitiveKind::Record, size))
431
+ return env.Null();
432
+ err_guard.Disable();
433
+
434
+ if (replace) {
435
+ *replace = std::move(*type);
436
+ type = replace;
437
+ }
438
+
439
+ napi_value wrapper = WrapType(instance, type);
440
+ return Napi::Value(env, wrapper);
441
+ }
442
+
443
+ static Napi::Value CreatePaddedStructType(const Napi::CallbackInfo &info)
444
+ {
445
+ return CreateStructType(info, true);
446
+ }
447
+
448
+ static Napi::Value CreatePackedStructType(const Napi::CallbackInfo &info)
449
+ {
450
+ return CreateStructType(info, false);
451
+ }
452
+
453
+ static Napi::Value CreateUnionType(const Napi::CallbackInfo &info)
454
+ {
455
+ Napi::Env env = info.Env();
456
+ InstanceData *instance = (InstanceData *)info.Data();
457
+
458
+ if (info.Length() < 1) {
459
+ ThrowError<Napi::TypeError>(env, "Expected 1 or 2 arguments, got %1", info.Length());
460
+ return env.Null();
461
+ }
462
+
463
+ bool skip = (info.Length() > 1);
464
+ bool named = skip && !IsNullOrUndefined(env, info[0]);
465
+ #if defined(EXTERNAL_TYPES)
466
+ bool redefine = named && info[0].IsExternal() && CheckValueTag(env, info[0], &TypeObjectMarker);
467
+ #else
468
+ bool redefine = named && info[0].IsObject() && CheckValueTag(env, info[0], &TypeObjectMarker);
469
+ #endif
470
+
471
+ if (named && !info[0].IsString() && !redefine) {
472
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
473
+ return env.Null();
474
+ }
475
+ if (!IsObject(env, info[skip])) {
476
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for members, expected object", GetValueType(instance, info[1]));
477
+ return env.Null();
478
+ }
479
+
480
+ Napi::String name = info[0].As<Napi::String>();
481
+ Napi::Object obj = info[skip].As<Napi::Object>();
482
+ Napi::Array keys = GetOwnPropertyNames(env, obj);
483
+
484
+ K_DEFER_NC(err_guard, count = instance->types.count) {
485
+ Size start = count + !skip;
486
+
487
+ for (Size i = start; i < instance->types.count; i++) {
488
+ const TypeInfo *it = &instance->types[i];
489
+ const TypeInfo **ptr = instance->types_map.Find(it->name);
490
+
491
+ if (ptr && *ptr == it) {
492
+ instance->types_map.Remove(ptr);
493
+ }
494
+ }
495
+
496
+ instance->types.RemoveFrom(count);
497
+ };
498
+
499
+ TypeInfo *type = instance->types.AppendDefault();
500
+ TypeInfo *replace = nullptr;
501
+
502
+ if (redefine) {
503
+ #if defined(EXTERNAL_TYPES)
504
+ Napi::External<TypeInfo> external = name.As<Napi::External<TypeInfo>>();
505
+ replace = external.Data();
506
+ #else
507
+ TypeObject *defn = nullptr;
508
+ NAPI_OK(napi_unwrap(env, name, (void **)&defn));
509
+
510
+ replace = (TypeInfo *)defn->GetType();
511
+ #endif
512
+
513
+ type->instance = instance;
514
+ type->name = replace->name;
515
+
516
+ if (replace->primitive != PrimitiveKind::Void || replace == instance->void_type) {
517
+ ThrowError<Napi::TypeError>(env, "Cannot redefine non-opaque type %1", replace->name);
518
+ return env.Null();
519
+ }
520
+ } else if (named) {
521
+ type->instance = instance;
522
+ type->name = DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr;
523
+
524
+ if (!MapType(env, instance, type, type->name))
525
+ return env.Null();
526
+ } else {
527
+ type->instance = instance;
528
+ type->name = Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
529
+ }
530
+
531
+ type->primitive = PrimitiveKind::Void;
532
+ type->align = 1;
533
+
534
+ HashSet<const char *> members;
535
+ int32_t size = 0;
536
+
537
+ for (uint32_t i = 0; i < keys.Length(); i++) {
538
+ RecordMember member = {};
539
+
540
+ std::string key = keys.Get(i).As<Napi::String>();
541
+ Napi::Value value = obj[key];
542
+ int16_t align = 0;
543
+
544
+ member.name = DuplicateString(key.c_str(), &instance->str_alloc).ptr;
545
+
546
+ if (value.IsArray()) {
547
+ Napi::Array array = value.As<Napi::Array>();
548
+
549
+ if (array.Length() != 2 || !array.Get(0u).IsNumber()) {
550
+ ThrowError<Napi::Error>(env, "Member specifier array must contain alignement value and type");
551
+ return env.Null();
552
+ }
553
+
554
+ int64_t align64 = array.Get(0u).As<Napi::Number>().Int64Value();
555
+
556
+ if (!CheckAlignment(align64)) {
557
+ ThrowError<Napi::Error>(env, "Alignment of member '%1' must be 1, 2, 4 or 8", member.name);
558
+ return env.Null();
559
+ }
560
+
561
+ value = array[1u];
562
+ align = (int16_t)align64;
563
+ }
564
+
565
+ member.type = ResolveType(instance, value);
566
+ if (!member.type)
567
+ return env.Null();
568
+ if (!CanStoreType(member.type)) {
569
+ ThrowError<Napi::TypeError>(env, "Type %1 cannot be used as a member (maybe try %1 *)", member.type->name);
570
+ return env.Null();
571
+ }
572
+ if (member.type->countedby) {
573
+ ThrowError<Napi::TypeError>(env, "Cannot use dynamic-length array or pointer inside of union");
574
+ return env.Null();
575
+ }
576
+
577
+ align = align ? align : member.type->align;
578
+ size = std::max(size, member.type->size);
579
+ type->align = std::max(type->align, align);
580
+
581
+ member.countedby = -1;
582
+
583
+ if (TestStr(member.name, "_"))
584
+ continue;
585
+
586
+ if (!IsNameValid(member.name)) {
587
+ ThrowError<Napi::Error>(env, "Invalid member name '%1'", member.name);
588
+ return env.Null();
589
+ }
590
+
591
+ bool inserted;
592
+ members.InsertOrGet(member.name, &inserted);
593
+
594
+ if (!inserted) {
595
+ ThrowError<Napi::Error>(env, "Duplicate member '%1' in union '%2'", member.name, type->name);
596
+ return env.Null();
597
+ }
598
+
599
+ type->members.Append(member);
600
+ }
601
+
602
+ if (!FinalizeCompositeType(env, type, PrimitiveKind::Union, size))
603
+ return env.Null();
604
+ err_guard.Disable();
605
+
606
+ Napi::Object construct = UnionValue::InitClass(instance, type);
607
+ NAPI_OK(napi_create_reference(env, construct, 1, &type->construct));
608
+
609
+ if (replace) {
610
+ *replace = std::move(*type);
611
+ type = replace;
612
+ }
613
+
614
+ napi_value wrapper = WrapType(instance, type);
615
+ return Napi::Value(env, wrapper);
616
+ }
617
+
618
+ Napi::Value InstantiateUnion(const Napi::CallbackInfo &info)
619
+ {
620
+ Napi::Env env = info.Env();
621
+ InstanceData *instance = (InstanceData *)info.Data();
622
+
623
+ if (!info.IsConstructCall()) {
624
+ ThrowError<Napi::TypeError>(env, "This function is a constructor and must be called with new");
625
+ return env.Null();
626
+ }
627
+ if (info.Length() < 1) {
628
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
629
+ return env.Null();
630
+ }
631
+
632
+ const TypeInfo *type = ResolveType(instance, info[0]);
633
+ if (!type)
634
+ return env.Null();
635
+ if (type->primitive != PrimitiveKind::Union) {
636
+ ThrowError<Napi::TypeError>(env, "Expected union type, got %1", PrimitiveKindNames[(int)type->primitive]);
637
+ return env.Null();
638
+ }
639
+
640
+ Napi::Function construct;
641
+ {
642
+ napi_value value;
643
+ NAPI_OK(napi_get_reference_value(env, type->construct, &value));
644
+
645
+ construct = Napi::Function(env, value);
646
+ }
647
+
648
+ Napi::Object wrapper = construct.New({}).As<Napi::Object>();
649
+ SetValueTag(env, wrapper, &UnionValueMarker);
650
+
651
+ return wrapper;
652
+ }
653
+
654
+ static Napi::Value CreateOpaqueType(const Napi::CallbackInfo &info)
655
+ {
656
+ Napi::Env env = info.Env();
657
+ InstanceData *instance = (InstanceData *)info.Data();
658
+
659
+ bool named = (info.Length() >= 1) && !IsNullOrUndefined(env, info[0]);
660
+
661
+ if (named && !info[0].IsString()) {
662
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
663
+ return env.Null();
664
+ }
665
+
666
+ Napi::String name = info[0].As<Napi::String>();
667
+
668
+ TypeInfo *type = instance->types.AppendDefault();
669
+ K_DEFER_N(err_guard) { instance->types.RemoveLast(1); };
670
+
671
+ type->instance = instance;
672
+ type->name = named ? DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr
673
+ : Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
674
+
675
+ type->primitive = PrimitiveKind::Void;
676
+ type->size = 0;
677
+ type->align = 0;
678
+
679
+ // If the insert succeeds, we cannot fail anymore
680
+ if (named && !MapType(env, instance, type, type->name))
681
+ return env.Null();
682
+ err_guard.Disable();
683
+
684
+ napi_value wrapper = WrapType(instance, type);
685
+ return Napi::Value(env, wrapper);
686
+ }
687
+
688
+ static Napi::Value CreatePointerType(const Napi::CallbackInfo &info)
689
+ {
690
+ Napi::Env env = info.Env();
691
+ InstanceData *instance = (InstanceData *)info.Data();
692
+
693
+ if (info.Length() < 1) {
694
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 3 arguments, got %1", info.Length());
695
+ return env.Null();
696
+ }
697
+
698
+ bool skip = (info.Length() > 1) && !info[1].IsNumber();
699
+ bool named = skip && !IsNullOrUndefined(env, info[0]);
700
+
701
+ if (named && !info[0].IsString()) {
702
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
703
+ return env.Null();
704
+ }
705
+
706
+ std::string name = named ? info[0].As<Napi::String>() : std::string();
707
+
708
+ const TypeInfo *ref = ResolveType(instance, info[skip]);
709
+ if (!ref)
710
+ return env.Null();
711
+
712
+ Napi::Value countedby;
713
+ int count = 1;
714
+
715
+ if (info.Length() >= 2u + skip) {
716
+ if (info[1 + skip].IsString()) {
717
+ countedby = info[1 + skip];
718
+ } else if (info[1 + skip].IsNumber()) {
719
+ count = info[1 + skip].As<Napi::Number>();
720
+
721
+ if (count < 1 || count > 4) {
722
+ ThrowError<Napi::TypeError>(env, "Value of count must be between 1 and 4");
723
+ return env.Null();
724
+ }
725
+ } else {
726
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for count, expected number", GetValueType(instance, info[1 + skip]));
727
+ return env.Null();
728
+ }
729
+ }
730
+
731
+ TypeInfo *type = MakePointerType(instance, ref, count);
732
+ K_ASSERT(type);
733
+
734
+ if (named || !countedby.IsEmpty()) {
735
+ TypeInfo *copy = instance->types.AppendDefault();
736
+ K_DEFER_N(err_guard) { instance->types.RemoveLast(1); };
737
+
738
+ memcpy((void *)copy, type, K_SIZE(*type));
739
+ copy->name = named ? DuplicateString(name.c_str(), &instance->str_alloc).ptr : copy->name;
740
+ copy->defn = nullptr;
741
+
742
+ static_assert(!std::is_polymorphic_v<Napi::ObjectReference>);
743
+
744
+ if (!countedby.IsEmpty()) {
745
+ Napi::String str = countedby.As<Napi::String>();
746
+ copy->countedby = DuplicateString(str.Utf8Value().c_str(), &instance->str_alloc).ptr;
747
+ }
748
+
749
+ // If the insert succeeds, we cannot fail anymore
750
+ if (named && !MapType(env, instance, copy, copy->name))
751
+ return env.Null();
752
+ err_guard.Disable();
753
+
754
+ type = copy;
755
+ }
756
+
757
+ napi_value wrapper = WrapType(instance, type);
758
+ return Napi::Value(env, wrapper);
759
+ }
760
+
761
+ static Napi::Value EncodePointerDirection(const Napi::CallbackInfo &info, int directions)
762
+ {
763
+ K_ASSERT(directions >= 1 && directions <= 3);
764
+
765
+ Napi::Env env = info.Env();
766
+ InstanceData *instance = (InstanceData *)info.Data();
767
+
768
+ if (info.Length() < 1) {
769
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
770
+ return env.Null();
771
+ }
772
+
773
+ const TypeInfo *type = ResolveType(instance, info[0]);
774
+ if (!type)
775
+ return env.Null();
776
+
777
+ if (type->primitive != PrimitiveKind::Pointer &&
778
+ type->primitive != PrimitiveKind::String &&
779
+ type->primitive != PrimitiveKind::String16 &&
780
+ type->primitive != PrimitiveKind::String32) {
781
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 type, expected pointer or string type", type->name);
782
+ return env.Null();
783
+ }
784
+
785
+ // Embed direction in unused pointer bits
786
+ const TypeInfo *marked = (const TypeInfo *)((uint8_t *)type + directions - 1);
787
+
788
+ Napi::External<TypeInfo> external = Napi::External<TypeInfo>::New(env, (TypeInfo *)marked);
789
+ SetValueTag(env, external, &DirectionMarker);
790
+
791
+ return external;
792
+ }
793
+
794
+ static Napi::Value MarkIn(const Napi::CallbackInfo &info)
795
+ {
796
+ return EncodePointerDirection(info, 1);
797
+ }
798
+
799
+ static Napi::Value MarkOut(const Napi::CallbackInfo &info)
800
+ {
801
+ return EncodePointerDirection(info, 2);
802
+ }
803
+
804
+ static Napi::Value MarkInOut(const Napi::CallbackInfo &info)
805
+ {
806
+ return EncodePointerDirection(info, 3);
807
+ }
808
+
809
+ static Napi::Value CreateDisposableType(const Napi::CallbackInfo &info)
810
+ {
811
+ Napi::Env env = info.Env();
812
+ InstanceData *instance = (InstanceData *)info.Data();
813
+
814
+ if (info.Length() < 1) {
815
+ ThrowError<Napi::TypeError>(env, "Expected 1 or 2 arguments, got %1", info.Length());
816
+ return env.Null();
817
+ }
818
+
819
+ bool skip = (info.Length() > 1) && !info[1].IsFunction();
820
+ bool named = skip && !IsNullOrUndefined(env, info[0]);
821
+
822
+ if (named && !info[0].IsString()) {
823
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
824
+ return env.Null();
825
+ }
826
+
827
+ Napi::String name = info[0].As<Napi::String>();
828
+
829
+ const TypeInfo *src = ResolveType(instance, info[skip]);
830
+ if (!src)
831
+ return env.Null();
832
+ if (src->primitive != PrimitiveKind::Pointer &&
833
+ src->primitive != PrimitiveKind::String &&
834
+ src->primitive != PrimitiveKind::String16 &&
835
+ src->primitive != PrimitiveKind::String32) {
836
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 type, expected pointer or string type", src->name);
837
+ return env.Null();
838
+ }
839
+ if (src->dispose) {
840
+ ThrowError<Napi::TypeError>(env, "Cannot use disposable type '%1' to create new disposable", src->name);
841
+ return env.Null();
842
+ }
843
+
844
+ DisposeFunc *dispose;
845
+ Napi::Function dispose_func;
846
+ if (info.Length() >= 2u + skip && !IsNullOrUndefined(env, info[1 + skip])) {
847
+ Napi::Function func = info[1 + skip].As<Napi::Function>();
848
+
849
+ if (!func.IsFunction()) {
850
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for func, expected function", GetValueType(instance, func));
851
+ return env.Null();
852
+ }
853
+
854
+ dispose = [](InstanceData *instance, const TypeInfo *type, const void *ptr) {
855
+ Napi::Env env = instance->env;
856
+
857
+ napi_value func;
858
+ NAPI_OK(napi_get_reference_value(env, type->dispose_ref, &func));
859
+
860
+ napi_value self = env.Null();
861
+ napi_value wrapper = WrapPointer(env, type->ref.type, (void *)ptr);
862
+
863
+ NAPI_OK(napi_call_function(env, self, func, 1, &wrapper, nullptr));
864
+ instance->stats.disposed++;
865
+ };
866
+ dispose_func = func;
867
+ } else {
868
+ dispose = [](InstanceData *instance, const TypeInfo *, const void *ptr) {
869
+ free((void *)ptr);
870
+ instance->stats.disposed++;
871
+ };
872
+ }
873
+
874
+ TypeInfo *type = instance->types.AppendDefault();
875
+ K_DEFER_N(err_guard) { instance->types.RemoveLast(1); };
876
+
877
+ memcpy((void *)type, (const void *)src, K_SIZE(*src));
878
+ type->defn = nullptr;
879
+ K_ASSERT(!type->members.len);
880
+
881
+ static_assert(!std::is_polymorphic_v<Napi::ObjectReference>);
882
+
883
+ type->name = named ? DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr
884
+ : Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
885
+
886
+ type->dispose = dispose;
887
+ NAPI_OK(napi_create_reference(env, dispose_func, 1, &type->dispose_ref));
888
+
889
+ // If the insert succeeds, we cannot fail anymore
890
+ if (named) {
891
+ bool inserted;
892
+ instance->types_map.InsertOrGet(type->name, type, &inserted);
893
+
894
+ if (!inserted) {
895
+ ThrowError<Napi::Error>(env, "Duplicate type name '%1'", type->name);
896
+ return env.Null();
897
+ }
898
+ }
899
+ err_guard.Disable();
900
+
901
+ napi_value wrapper = WrapType(instance, type);
902
+ return Napi::Value(env, wrapper);
903
+ }
904
+
905
+ static Napi::Value CallAlloc(const Napi::CallbackInfo &info)
906
+ {
907
+ Napi::Env env = info.Env();
908
+ InstanceData *instance = (InstanceData *)info.Data();
909
+
910
+ if (info.Length() < 2) {
911
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
912
+ return env.Null();
913
+ }
914
+ if (!info[1].IsNumber()) {
915
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for length, expected number", GetValueType(instance, info[1]));
916
+ return env.Null();
917
+ }
918
+
919
+ const TypeInfo *type = ResolveType(instance, info[0]);
920
+ if (!type)
921
+ return env.Null();
922
+
923
+ if (!type->size) [[unlikely]] {
924
+ ThrowError<Napi::TypeError>(env, "Cannot allocate memory for zero-sized type %1", type->name);
925
+ return env.Null();
926
+ }
927
+
928
+ int32_t len = info[1].As<Napi::Number>();
929
+
930
+ if (len <= 0) [[unlikely]] {
931
+ ThrowError<Napi::Error>(env, "Size must be greater than 0");
932
+ return env.Null();
933
+ }
934
+ if (len > INT32_MAX / type->size) [[unlikely]] {
935
+ ThrowError<Napi::Error>(env, "Cannot allocate more than %1 objects of type %2", INT32_MAX / type->size, type->name);
936
+ return env.Null();
937
+ }
938
+
939
+ void *ptr = calloc((size_t)len, (size_t)type->size);
940
+
941
+ if (!ptr) [[unlikely]] {
942
+ Size size = (Size)(len * type->size);
943
+
944
+ ThrowError<Napi::Error>(env, "Failed to allocate %1 of memory", FmtMemSize((Size)size));
945
+ return env.Null();
946
+ }
947
+
948
+ napi_value wrapper = WrapPointer(env, type, ptr);
949
+ return Napi::Value(env, wrapper);
950
+ }
951
+
952
+ static Napi::Value CallFree(const Napi::CallbackInfo &info)
953
+ {
954
+ Napi::Env env = info.Env();
955
+ InstanceData *instance = (InstanceData *)info.Data();
956
+
957
+ if (info.Length() < 1) {
958
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
959
+ return env.Null();
960
+ }
961
+
962
+ void *ptr = nullptr;
963
+ if (!TryPointer(env, info[0], &ptr)) {
964
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, info[0]));
965
+ return env.Null();
966
+ }
967
+
968
+ free(ptr);
969
+
970
+ return env.Undefined();
971
+ }
972
+
973
+ static Napi::Value GetOrSetErrNo(const Napi::CallbackInfo &info)
974
+ {
975
+ Napi::Env env = info.Env();
976
+ InstanceData *instance = (InstanceData *)info.Data();
977
+
978
+ if (info.Length() >= 1) {
979
+ Napi::Number value = info[0].As<Napi::Number>();
980
+
981
+ if (!value.IsNumber()) {
982
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for errno, expected integer", GetValueType(instance, value));
983
+ return env.Null();
984
+ }
985
+
986
+ errno = value;
987
+ }
988
+
989
+ napi_value ret = NewInt(env, (int32_t)errno);
990
+ return Napi::Value(env, ret);
991
+ }
992
+
993
+ static Napi::Value CreateArrayType(const Napi::CallbackInfo &info)
994
+ {
995
+ Napi::Env env = info.Env();
996
+ InstanceData *instance = (InstanceData *)info.Data();
997
+
998
+ if (info.Length() < 2) {
999
+ ThrowError<Napi::TypeError>(env, "Expected 2 to 4 arguments, got %1", info.Length());
1000
+ return env.Null();
1001
+ }
1002
+
1003
+ const TypeInfo *ref = ResolveType(instance, info[0]);
1004
+ if (!ref)
1005
+ return env.Null();
1006
+
1007
+ bool dynamic = (info.Length() >= 3) && info[1].IsString();
1008
+
1009
+ if (dynamic && !info[1].IsString()) {
1010
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for countedBy, expected string", GetValueType(instance, info[1]));
1011
+ return env.Null();
1012
+ }
1013
+ if (!info[1 + dynamic].IsNumber()) {
1014
+ if (info.Length() == 2 && info[1].IsString()) {
1015
+ ThrowError<Napi::TypeError>(env, "Missing maxLen argument");
1016
+ } else {
1017
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for %2, expected integer", GetValueType(instance, info[1]), dynamic ? "maxLen" : "len");
1018
+ }
1019
+ return env.Null();
1020
+ }
1021
+
1022
+ int64_t len = info[1 + dynamic].As<Napi::Number>().Int64Value();
1023
+
1024
+ if (len <= 0) {
1025
+ ThrowError<Napi::TypeError>(env, "Array length must be positive and non-zero");
1026
+ return env.Null();
1027
+ }
1028
+ if (len > instance->config.max_type_size / ref->size) {
1029
+ ThrowError<Napi::TypeError>(env, "Array length is too high (max = %1)", instance->config.max_type_size / ref->size);
1030
+ return env.Null();
1031
+ }
1032
+
1033
+ TypeInfo *type = nullptr;
1034
+
1035
+ if (info.Length() >= 3u + dynamic && !IsNullOrUndefined(env, info[2 + dynamic])) {
1036
+ if (!info[2 + dynamic].IsString()) {
1037
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for hint, expected string", GetValueType(instance, info[2]));
1038
+ return env.Null();
1039
+ }
1040
+
1041
+ std::string str = info[2 + dynamic].As<Napi::String>();
1042
+ ArrayHint hint = {};
1043
+
1044
+ if (str == "Typed" || str == "typed") {
1045
+ if (!(ref->flags & (int)TypeFlag::HasTypedArray)) {
1046
+ ThrowError<Napi::Error>(env, "Array hint 'Typed' cannot be used with type %1", ref->name);
1047
+ return env.Null();
1048
+ }
1049
+
1050
+ hint = ArrayHint::Typed;
1051
+ } else if (str == "Buffer" || str == "buffer") {
1052
+ if (!(ref->flags & (int)TypeFlag::HasTypedArray)) {
1053
+ ThrowError<Napi::Error>(env, "Array hint 'Buffer' cannot be used with type %1", ref->name);
1054
+ return env.Null();
1055
+ }
1056
+
1057
+ hint = ArrayHint::Buffer;
1058
+ } else if (str == "Array" || str == "array") {
1059
+ hint = ArrayHint::Array;
1060
+ } else if (str == "String" || str == "string") {
1061
+ if (ref->primitive != PrimitiveKind::Int8 &&
1062
+ ref->primitive != PrimitiveKind::Int16 &&
1063
+ ref->primitive != PrimitiveKind::Int32) {
1064
+ ThrowError<Napi::Error>(env, "Array hint 'String' can only be used with 8, 16 and 32-bit signed integer types");
1065
+ return env.Null();
1066
+ }
1067
+
1068
+ hint = ArrayHint::String;
1069
+ } else {
1070
+ ThrowError<Napi::Error>(env, "Array conversion hint must be 'Typed', 'Array' or 'String'");
1071
+ return env.Null();
1072
+ }
1073
+
1074
+ type = MakeArrayType(instance, ref, (Size)len, hint);
1075
+ } else {
1076
+ type = MakeArrayType(instance, ref, (Size)len);
1077
+ }
1078
+
1079
+ if (dynamic) {
1080
+ Napi::String str = info[1].As<Napi::String>();
1081
+ type->countedby = DuplicateString(str.Utf8Value().c_str(), &instance->str_alloc).ptr;
1082
+ }
1083
+
1084
+ napi_value wrapper = WrapType(instance, type);
1085
+ return Napi::Value(env, wrapper);
1086
+ }
1087
+
1088
+ static bool ParseClassicFunction(const Napi::CallbackInfo &info, bool concrete, FunctionInfo *out_func)
1089
+ {
1090
+ K_ASSERT(info.Length() >= 2);
1091
+
1092
+ Napi::Env env = info.Env();
1093
+ InstanceData *instance = (InstanceData *)info.Data();
1094
+
1095
+ Napi::String name = info[0u].As<Napi::String>();
1096
+ Napi::Value ret = info[1u];
1097
+ Napi::Array parameters = info[2u].As<Napi::Array>();
1098
+
1099
+ // Detect optional call convention
1100
+ if (name.IsString() && DetectCallConvention(name.Utf8Value().c_str(), &out_func->convention)) {
1101
+ if (info.Length() < 3) {
1102
+ ThrowError<Napi::TypeError>(env, "Expected 3 or 4 arguments, got %1", info.Length());
1103
+ return false;
1104
+ }
1105
+
1106
+ name = info[1u].As<Napi::String>();
1107
+ ret = info[2u];
1108
+ parameters = (info.Length() >= 4 ? info[3u] : env.Null()).As<Napi::Array>();
1109
+ }
1110
+
1111
+ bool named = parameters.IsArray();
1112
+
1113
+ if (named) {
1114
+ #if defined(_WIN32)
1115
+ if (name.IsNumber()) {
1116
+ out_func->ordinal_name = name.As<Napi::Number>().Int32Value();
1117
+ name = name.ToString();
1118
+ }
1119
+ #endif
1120
+ if (!name.IsString()) {
1121
+ if (!concrete && IsNullOrUndefined(env, name)) {
1122
+ named = false;
1123
+ } else {
1124
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string or integer", GetValueType(instance, name));
1125
+ return false;
1126
+ }
1127
+ }
1128
+ } else {
1129
+ parameters = ret.As<Napi::Array>();
1130
+ ret = name;
1131
+ }
1132
+
1133
+ // Leave anonymous naming responsibility to caller
1134
+ out_func->name = named ? DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr : nullptr;
1135
+
1136
+ out_func->ret.type = ResolveType(instance, ret);
1137
+ if (!out_func->ret.type)
1138
+ return false;
1139
+ if (!CanReturnType(out_func->ret.type)) {
1140
+ ThrowError<Napi::TypeError>(env, "You are not allowed to directly return %1 values (maybe try %1 *)", out_func->ret.type->name);
1141
+ return false;
1142
+ }
1143
+
1144
+ if (!parameters.IsArray()) {
1145
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for parameters of '%2', expected an array", GetValueType(instance, parameters), out_func->name);
1146
+ return false;
1147
+ }
1148
+
1149
+ uint32_t parameters_len = parameters.Length();
1150
+
1151
+ if (parameters_len) {
1152
+ Napi::String str = parameters.Get(parameters_len - 1).As<Napi::String>();
1153
+
1154
+ if (str.IsString() && str.Utf8Value() == "...") {
1155
+ out_func->variadic = true;
1156
+ parameters_len--;
1157
+ }
1158
+ }
1159
+
1160
+ for (uint32_t j = 0; j < parameters_len; j++) {
1161
+ ParameterInfo param = {};
1162
+
1163
+ param.type = ResolveType(instance, parameters[j].AsValue(), &param.directions);
1164
+
1165
+ if (!param.type)
1166
+ return false;
1167
+ if (!CanPassType(param.type, param.directions)) {
1168
+ ThrowError<Napi::TypeError>(env, "Type %1 cannot be used as a parameter", param.type->name);
1169
+ return false;
1170
+ }
1171
+ if (out_func->parameters.len >= MaxParameters) {
1172
+ ThrowError<Napi::TypeError>(env, "Functions cannot have more than %1 parameters", MaxParameters);
1173
+ return false;
1174
+ }
1175
+
1176
+ param.offset = (int8_t)j;
1177
+
1178
+ out_func->parameters.Append(param);
1179
+ }
1180
+
1181
+ out_func->required_parameters = (int8_t)out_func->parameters.len;
1182
+
1183
+ return true;
1184
+ }
1185
+
1186
+ static Napi::Value CreateFunctionType(const Napi::CallbackInfo &info)
1187
+ {
1188
+ Napi::Env env = info.Env();
1189
+ InstanceData *instance = (InstanceData *)info.Data();
1190
+
1191
+ FunctionInfo *func = instance->callbacks.AppendDefault();
1192
+ K_DEFER_N(err_guard) { instance->callbacks.RemoveLast(1); };
1193
+
1194
+ func->env = env;
1195
+ func->instance = instance;
1196
+
1197
+ if (info.Length() >= 2) {
1198
+ if (!ParseClassicFunction(info, false, func))
1199
+ return env.Null();
1200
+ } else if (info.Length() >= 1) {
1201
+ if (!info[0].IsString()) {
1202
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for prototype, expected string", GetValueType(instance, info[0]));
1203
+ return env.Null();
1204
+ }
1205
+
1206
+ std::string proto = info[0u].As<Napi::String>();
1207
+ if (!ParsePrototype(instance, proto.c_str(), false, func))
1208
+ return env.Null();
1209
+ } else {
1210
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 4 arguments, got %1", info.Length());
1211
+ return env.Null();
1212
+ }
1213
+
1214
+ bool named = func->name;
1215
+
1216
+ if (!named) {
1217
+ func->name = Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
1218
+ }
1219
+
1220
+ if (!AnalyseFunction(env, instance, func))
1221
+ return env.Null();
1222
+
1223
+ // We cannot fail after this check
1224
+ if (named && instance->types_map.Find(func->name)) {
1225
+ ThrowError<Napi::Error>(env, "Duplicate type name '%1'", func->name);
1226
+ return env.Null();
1227
+ }
1228
+ err_guard.Disable();
1229
+
1230
+ TypeInfo *type = instance->types.AppendDefault();
1231
+
1232
+ type->instance = instance;
1233
+ type->name = func->name;
1234
+
1235
+ type->primitive = PrimitiveKind::Prototype;
1236
+ type->align = alignof(void *);
1237
+ type->size = K_SIZE(void *);
1238
+ type->proto = func;
1239
+
1240
+ instance->types_map.Set(type->name, type);
1241
+
1242
+ napi_value wrapper = WrapType(instance, type);
1243
+ return Napi::Value(env, wrapper);
1244
+ }
1245
+
1246
+ static Napi::Value CreateEnumType(const Napi::CallbackInfo &info)
1247
+ {
1248
+ Napi::Env env = info.Env();
1249
+ InstanceData *instance = (InstanceData *)info.Data();
1250
+
1251
+ if (info.Length() < 1) {
1252
+ ThrowError<Napi::TypeError>(env, "Expected 1 or 2 arguments, got %1", info.Length());
1253
+ return env.Null();
1254
+ }
1255
+
1256
+ bool named = (info.Length() >= 2 && !info[0].IsObject());
1257
+ bool typed = (info.Length() >= 2u + named && !IsNullOrUndefined(env, info[1 + named]));
1258
+
1259
+ if (named && !info[0].IsString()) {
1260
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
1261
+ return env.Null();
1262
+ }
1263
+ if (!IsObject(env, info[named])) {
1264
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for values, expected object", GetValueType(instance, info[1]));
1265
+ return env.Null();
1266
+ }
1267
+
1268
+ Napi::String name = info[0].As<Napi::String>();
1269
+ Napi::Object obj = info[named].As<Napi::Object>();
1270
+ Napi::Array keys = GetOwnPropertyNames(env, obj);
1271
+
1272
+ TypeInfo *type = instance->types.AppendDefault();
1273
+ K_DEFER_N(err_guard) { instance->types.RemoveLast(1); };
1274
+
1275
+ type->instance = instance;
1276
+ type->name = named ? DuplicateString(name.Utf8Value().c_str(), &instance->str_alloc).ptr
1277
+ : Fmt(&instance->str_alloc, "<anonymous_%1>", instance->types.count).ptr;
1278
+
1279
+ Napi::Object values = Napi::Object::New(env);
1280
+
1281
+ // Determine needed storage type
1282
+ if (typed) {
1283
+ const TypeInfo *storage = ResolveType(instance, info[1 + named]);
1284
+ if (!storage)
1285
+ return env.Null();
1286
+
1287
+ if (!IsInteger(storage)) {
1288
+ ThrowError<Napi::TypeError>(env, "Expected integer type for underlying enum storage type");
1289
+ return env.Null();
1290
+ }
1291
+
1292
+ type->primitive = storage->primitive;
1293
+ type->size = storage->size;
1294
+ type->align = storage->align;
1295
+ } else {
1296
+ #if defined(_WIN32)
1297
+ type->primitive = PrimitiveKind::Int32;
1298
+ type->size = 4;
1299
+ type->align = 4;
1300
+
1301
+ for (uint32_t i = 0; i < keys.Length(); i++) {
1302
+ std::string key = keys.Get(i).As<Napi::String>();
1303
+ Napi::Value value = obj[key];
1304
+
1305
+ int64_t i64;
1306
+ bool lossless;
1307
+
1308
+ if (value.IsNumber()) {
1309
+ i64 = value.As<Napi::Number>().Int64Value();
1310
+ lossless = true;
1311
+ } else if (value.IsBigInt()) {
1312
+ Napi::BigInt big = value.As<Napi::BigInt>();
1313
+ i64 = big.Int64Value(&lossless);
1314
+ } else {
1315
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for enumeration value, expected number", GetValueType(instance, info[0]));
1316
+ return env.Null();
1317
+ }
1318
+
1319
+ if (!lossless || i64 < INT_MIN || i64 > INT_MAX) {
1320
+ ThrowError<Napi::Error>(env, "Cannot find storage type wide enough for enum values");
1321
+ return env.Null();
1322
+ }
1323
+
1324
+ values.Set(key, value);
1325
+ }
1326
+ #else
1327
+ bool negative = false;
1328
+ bool negative64 = false;
1329
+ uint64_t max = 0;
1330
+
1331
+ for (uint32_t i = 0; i < keys.Length(); i++) {
1332
+ std::string key = keys.Get(i).As<Napi::String>();
1333
+ Napi::Value value = obj[key];
1334
+
1335
+ if (value.IsNumber()) {
1336
+ int64_t i = value.As<Napi::Number>().Int64Value();
1337
+
1338
+ if (i < 0) {
1339
+ negative = true;
1340
+ negative64 |= (i < INT_MIN);
1341
+ } else {
1342
+ max = std::max(max, (uint64_t)i);
1343
+ }
1344
+ } else if (value.IsBigInt()) {
1345
+ Napi::BigInt big = value.As<Napi::BigInt>();
1346
+
1347
+ bool lossless;
1348
+ int64_t i = big.Int64Value(&lossless);
1349
+
1350
+ if (lossless && i < 0) {
1351
+ negative = true;
1352
+ negative64 |= (i < INT_MIN);
1353
+ } else {
1354
+ uint64_t u = big.Uint64Value(&lossless);
1355
+
1356
+ if (!lossless) {
1357
+ ThrowError<Napi::Error>(env, "Cannot find storage type wide enough for enum values");
1358
+ return env.Null();
1359
+ }
1360
+
1361
+ max = std::max(max, u);
1362
+ }
1363
+ } else {
1364
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for enumeration value, expected number", GetValueType(instance, info[0]));
1365
+ return env.Null();
1366
+ }
1367
+
1368
+ values.Set(key, value);
1369
+ }
1370
+
1371
+ // The rules are implementation-defined, but tend to be the same
1372
+ if (max <= UINT_MAX && !negative) {
1373
+ type->primitive = PrimitiveKind::UInt32;
1374
+ type->size = 4;
1375
+ type->align = 4;
1376
+ } else if (max <= INT_MAX && !negative64) {
1377
+ type->primitive = PrimitiveKind::Int32;
1378
+ type->size = 4;
1379
+ type->align = 4;
1380
+ } else if (!negative) {
1381
+ type->primitive = PrimitiveKind::UInt64;
1382
+ type->size = 8;
1383
+ type->align = alignof(uint64_t);
1384
+ } else if (max <= INT64_MAX) {
1385
+ type->primitive = PrimitiveKind::Int64;
1386
+ type->size = 8;
1387
+ type->align = alignof(int64_t);
1388
+ } else {
1389
+ ThrowError<Napi::Error>(env, "Cannot find storage type wide enough for enum values");
1390
+ return env.Null();
1391
+ }
1392
+ #endif
1393
+ }
1394
+
1395
+ // If the insert succeeds, we cannot fail anymore
1396
+ if (named && !MapType(env, instance, type, type->name))
1397
+ return env.Null();
1398
+ err_guard.Disable();
1399
+
1400
+ napi_value wrapper = WrapType(instance, type, false);
1401
+
1402
+ #if defined(EXTERNAL_TYPES)
1403
+ Napi::Object defn;
1404
+ {
1405
+ napi_value value;
1406
+ NAPI_OK(napi_get_reference_value(env, type->defn, &defn));
1407
+
1408
+ defn = Napi::Object(env, value);
1409
+ }
1410
+ #else
1411
+ Napi::Object defn(env, wrapper);
1412
+ #endif
1413
+
1414
+ defn.Set("values", values);
1415
+ defn.Freeze();
1416
+
1417
+ return Napi::Value(env, wrapper);
1418
+ }
1419
+
1420
+ static Napi::Value CreateTypeAlias(const Napi::CallbackInfo &info)
1421
+ {
1422
+ Napi::Env env = info.Env();
1423
+ InstanceData *instance = (InstanceData *)info.Data();
1424
+
1425
+ if (info.Length() < 2) {
1426
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
1427
+ return env.Null();
1428
+ }
1429
+ if (!info[0].IsString()) {
1430
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
1431
+ return env.Null();
1432
+ }
1433
+
1434
+ std::string name = info[0].As<Napi::String>();
1435
+ const char *alias = DuplicateString(name.c_str(), &instance->str_alloc).ptr;
1436
+
1437
+ const TypeInfo *type = ResolveType(instance, info[1]);
1438
+ if (!type)
1439
+ return env.Null();
1440
+
1441
+ // Alias the type
1442
+ if (!MapType(env, instance, type, alias))
1443
+ return env.Null();
1444
+
1445
+ napi_value wrapper = WrapType(instance, type);
1446
+ return Napi::Value(env, wrapper);
1447
+ }
1448
+
1449
+ static Napi::Value GetResolvedType(const Napi::CallbackInfo &info)
1450
+ {
1451
+ Napi::Env env = info.Env();
1452
+ InstanceData *instance = (InstanceData *)info.Data();
1453
+
1454
+ if (info.Length() < 1) {
1455
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
1456
+ return env.Null();
1457
+ }
1458
+
1459
+ const TypeInfo *type = ResolveType(instance, info[0]);
1460
+ if (!type)
1461
+ return env.Null();
1462
+
1463
+ napi_value wrapper = WrapType(instance, type);
1464
+ return Napi::Value(env, wrapper);
1465
+ }
1466
+
1467
+ #if defined(EXTERNAL_TYPES)
1468
+
1469
+ static Napi::Value GetTypeDefinition(const Napi::CallbackInfo &info)
1470
+ {
1471
+ Napi::Env env = info.Env();
1472
+ InstanceData *instance = (InstanceData *)info.Data();
1473
+
1474
+ if (info.Length() < 1) {
1475
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
1476
+ return env.Null();
1477
+ }
1478
+
1479
+ const TypeInfo *type = ResolveType(instance, info[0]);
1480
+ if (!type)
1481
+ return env.Null();
1482
+
1483
+ // Make sure definition is available
1484
+ WrapType(instance, type);
1485
+
1486
+ napi_value defn;
1487
+ NAPI_OK(napi_get_reference_value(env, instance->defn, &defn));
1488
+
1489
+ return defn;
1490
+ }
1491
+
1492
+ #endif
1493
+
1494
+ InstanceMemory *AllocateMemory(InstanceData *instance, Size stack_size, Size heap_size)
1495
+ {
1496
+ std::lock_guard<std::mutex> lock(instance->mem_mutex);
1497
+
1498
+ for (Size i = 1; i < instance->memories.len; i++) {
1499
+ InstanceMemory *mem = instance->memories[i];
1500
+
1501
+ if (!mem->busy) {
1502
+ mem->busy = true;
1503
+ return mem;
1504
+ }
1505
+ }
1506
+
1507
+ bool temporary = (instance->memories.len > instance->config.resident_async_pools);
1508
+
1509
+ if (temporary && instance->temporaries > instance->config.max_temporaries)
1510
+ return nullptr;
1511
+
1512
+ InstanceMemory *mem = new InstanceMemory();
1513
+ K_DEFER_N(mem_guard) { delete mem; };
1514
+
1515
+ stack_size = AlignLen(stack_size, Kibibytes(64));
1516
+
1517
+ #if defined(_WIN32)
1518
+ // Allocate stack memory
1519
+ mem->stack.ptr = (uint8_t *)VirtualAlloc(nullptr, stack_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
1520
+ mem->stack.end = mem->stack.ptr + stack_size;
1521
+
1522
+ K_CRITICAL(mem->stack.ptr, "Failed to allocate %1 of memory", stack_size);
1523
+ #else
1524
+ mem->stack.ptr = (uint8_t *)mmap(nullptr, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_STACK, -1, 0);
1525
+ mem->stack.end = mem->stack.ptr + stack_size;
1526
+
1527
+ K_CRITICAL(mem->stack.ptr, "Failed to allocate %1 of memory", stack_size);
1528
+ #endif
1529
+
1530
+ #if defined(__OpenBSD__)
1531
+ // Make sure the SP points inside the MAP_STACK area, or (void) functions may crash on OpenBSD i386
1532
+ mem->stack.end -= 16;
1533
+ #endif
1534
+
1535
+ // Keep real stack limits intact, in case we need them
1536
+ mem->stack0 = mem->stack;
1537
+
1538
+ #if defined(_WIN32) && !defined(_WIN64)
1539
+ mem->stack.end -= K_SIZE(SehFrame);
1540
+
1541
+ // Prepare at the top SEH frame record
1542
+ {
1543
+ SehFrame *seh = (SehFrame *)mem->stack.end;
1544
+
1545
+ seh->Next = (void *)-1;
1546
+ seh->Handler = (void *)SehHandler;
1547
+ }
1548
+ #endif
1549
+
1550
+ #if defined(_WIN32)
1551
+ mem->heap.ptr = (uint8_t *)VirtualAlloc(nullptr, heap_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
1552
+ mem->heap.end = mem->heap.ptr + heap_size;
1553
+
1554
+ K_CRITICAL(mem->heap.ptr, "Failed to allocate %1 of memory", heap_size);
1555
+ #else
1556
+ mem->heap.ptr = (uint8_t *)mmap(nullptr, heap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
1557
+ mem->heap.end = mem->heap.ptr + heap_size;
1558
+
1559
+ K_CRITICAL(mem->heap.ptr, "Failed to allocate %1 of memory", heap_size);
1560
+ #endif
1561
+
1562
+ if (temporary) {
1563
+ instance->temporaries++;
1564
+ mem->temporary = true;
1565
+ } else {
1566
+ instance->memories.Append(mem);
1567
+ mem->temporary = false;
1568
+ }
1569
+
1570
+ mem->busy = true;
1571
+
1572
+ mem_guard.Disable();
1573
+ return mem;
1574
+ }
1575
+
1576
+ void ReleaseMemory(InstanceData *instance, InstanceMemory *mem)
1577
+ {
1578
+ std::lock_guard<std::mutex> lock(instance->mem_mutex);
1579
+
1580
+ if (mem->temporary) {
1581
+ instance->temporaries--;
1582
+ delete mem;
1583
+ } else {
1584
+ mem->busy = false;
1585
+ }
1586
+ }
1587
+
1588
+ TypeInfo::~TypeInfo()
1589
+ {
1590
+ if (!instance)
1591
+ return;
1592
+
1593
+ Napi::Env env = instance->env;
1594
+
1595
+ for (RecordMember &member: members) {
1596
+ node_api_delete_reference(env, member.key);
1597
+ member.key = nullptr;
1598
+ }
1599
+
1600
+ node_api_delete_reference(env, dispose_ref);
1601
+ node_api_delete_reference(env, construct);
1602
+ node_api_delete_reference(env, defn);
1603
+ }
1604
+
1605
+ Napi::Function LibraryHandle::InitClass(InstanceData *instance)
1606
+ {
1607
+ Napi::Env env = instance->env;
1608
+
1609
+ // node-addon-api wants std::vector
1610
+ std::vector<Napi::ClassPropertyDescriptor<LibraryHandle>> properties = {
1611
+ InstanceMethod("func", &LibraryHandle::Func, napi_default, instance),
1612
+ InstanceMethod("symbol", &LibraryHandle::Symbol, napi_default, instance),
1613
+ InstanceMethod("unload", &LibraryHandle::Unload, napi_default, instance)
1614
+ };
1615
+
1616
+ if (Napi::Value dispose = env.RunScript("Symbol.dispose"); !IsNullOrUndefined(env, dispose)) {
1617
+ Napi::ClassPropertyDescriptor<LibraryHandle> prop = InstanceMethod(dispose.As<Napi::Symbol>(), &LibraryHandle::Unload);
1618
+ properties.push_back(prop);
1619
+ }
1620
+
1621
+ Napi::Function constructor = DefineClass(env, "LibraryHandle", properties);
1622
+ return constructor;
1623
+ }
1624
+
1625
+ LibraryHandle::LibraryHandle(const Napi::CallbackInfo &info)
1626
+ : Napi::ObjectWrap<LibraryHandle>(info)
1627
+ {
1628
+ Napi::Env env = info.Env();
1629
+
1630
+ if (info.Length() < 1 || !info[0].IsExternal()) [[unlikely]] {
1631
+ ThrowError<Napi::Error>(env, "Library objects cannot be constructed manually");
1632
+ return;
1633
+ }
1634
+
1635
+ Napi::External<void> external = info[0].As<Napi::External<void>>();
1636
+ lib = (LibraryHolder *)external.Data();
1637
+ }
1638
+
1639
+ void LibraryHandle::Finalize(Napi::BasicEnv env)
1640
+ {
1641
+ node_api_delete_reference(env, *this);
1642
+ SuppressDestruct();
1643
+
1644
+ lib->Unref();
1645
+ }
1646
+
1647
+ Napi::Value LibraryHandle::Func(const Napi::CallbackInfo &info)
1648
+ {
1649
+ Napi::Env env = info.Env();
1650
+ InstanceData *instance = (InstanceData *)info.Data();
1651
+
1652
+ FunctionInfo *func = new FunctionInfo();
1653
+ K_DEFER { func->Unref(); };
1654
+
1655
+ func->env = env;
1656
+ func->instance = instance;
1657
+ func->lib = lib->Ref();
1658
+
1659
+ if (info.Length() >= 2) {
1660
+ if (!ParseClassicFunction(info, true, func))
1661
+ return env.Null();
1662
+ } else if (info.Length() >= 1) {
1663
+ if (!info[0].IsString()) {
1664
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for prototype, expected string", GetValueType(instance, info[0]));
1665
+ return env.Null();
1666
+ }
1667
+
1668
+ std::string proto = info[0u].As<Napi::String>();
1669
+ if (!ParsePrototype(instance, proto.c_str(), true, func))
1670
+ return env.Null();
1671
+ } else {
1672
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 4 arguments, got %1", info.Length());
1673
+ return env.Null();
1674
+ }
1675
+
1676
+ if (func->convention != CallConvention::Cdecl && func->variadic) {
1677
+ LogError("Call convention '%1' does not support variadic functions, ignoring",
1678
+ CallConventionNames[(int)func->convention]);
1679
+ func->convention = CallConvention::Cdecl;
1680
+ }
1681
+
1682
+ if (!AnalyseFunction(env, instance, func))
1683
+ return env.Null();
1684
+
1685
+ #if defined(_WIN32)
1686
+ if (func->ordinal_name < 0) {
1687
+ if (func->decorated_name) {
1688
+ func->native = (void *)GetProcAddress((HMODULE)lib->module, func->decorated_name);
1689
+ }
1690
+ if (!func->native) {
1691
+ func->native = (void *)GetProcAddress((HMODULE)lib->module, func->name);
1692
+ }
1693
+ } else {
1694
+ uint16_t ordinal = (uint16_t)func->ordinal_name;
1695
+
1696
+ func->decorated_name = nullptr;
1697
+ func->native = (void *)GetProcAddress((HMODULE)lib->module, (LPCSTR)(size_t)ordinal);
1698
+ }
1699
+ #else
1700
+ if (func->decorated_name) {
1701
+ func->native = dlsym(lib->module, func->decorated_name);
1702
+ }
1703
+ if (!func->native) {
1704
+ func->native = dlsym(lib->module, func->name);
1705
+ }
1706
+ #endif
1707
+ if (!func->native) {
1708
+ ThrowError<Napi::Error>(env, "Cannot find function '%1' in shared library", func->name);
1709
+ return env.Null();
1710
+ }
1711
+
1712
+ napi_value wrapper = WrapFunction(instance, func);
1713
+ return Napi::Value(env, wrapper);
1714
+ }
1715
+
1716
+ Napi::Value LibraryHandle::Symbol(const Napi::CallbackInfo &info)
1717
+ {
1718
+ Napi::Env env = info.Env();
1719
+ InstanceData *instance = (InstanceData *)info.Data();
1720
+
1721
+ #if defined(EXTERNAL_POINTERS)
1722
+ if (info.Length() < 2) {
1723
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
1724
+ return env.Null();
1725
+ }
1726
+ #else
1727
+ if (info.Length() < 1) {
1728
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
1729
+ return env.Null();
1730
+ }
1731
+ #endif
1732
+ if (!info[0].IsString()) {
1733
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
1734
+ return env.Null();
1735
+ }
1736
+
1737
+ std::string name = info[0].As<Napi::String>();
1738
+
1739
+ #if defined(EXTERNAL_POINTERS)
1740
+ const TypeInfo *type = ResolveType(instance, info[1]);
1741
+ if (!type)
1742
+ return env.Null();
1743
+ #else
1744
+ const TypeInfo *type = nullptr;
1745
+ #endif
1746
+
1747
+ #if defined(_WIN32)
1748
+ void *ptr = (void *)GetProcAddress((HMODULE)lib->module, name.c_str());
1749
+ #else
1750
+ void *ptr = (void *)dlsym(lib->module, name.c_str());
1751
+ #endif
1752
+ if (!ptr) {
1753
+ ThrowError<Napi::Error>(env, "Cannot find symbol '%1' in shared library", name.c_str());
1754
+ return env.Null();
1755
+ }
1756
+
1757
+ napi_value wrapper = WrapPointer(env, type, ptr);
1758
+ return Napi::Value(env, wrapper);
1759
+ }
1760
+
1761
+ Napi::Value LibraryHandle::Unload(const Napi::CallbackInfo &info)
1762
+ {
1763
+ Napi::Env env = info.Env();
1764
+
1765
+ lib->Unload();
1766
+
1767
+ return env.Undefined();
1768
+ }
1769
+
1770
+ static Napi::Value LoadSharedLibrary(const Napi::CallbackInfo &info)
1771
+ {
1772
+ Napi::Env env = info.Env();
1773
+ InstanceData *instance = (InstanceData *)info.Data();
1774
+
1775
+ if (info.Length() < 1) {
1776
+ ThrowError<Napi::TypeError>(env, "Expected 1 or 2 arguments, got %1", info.Length());
1777
+ return env.Null();
1778
+ }
1779
+ if (!info[0].IsString() && !IsNullOrUndefined(env, info[0])) {
1780
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for filename, expected string or null", GetValueType(instance, info[0]));
1781
+ return env.Null();
1782
+ }
1783
+ if (info.Length() >= 2 && !IsObject(env, info[1])) {
1784
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for options, expected object", GetValueType(instance, info[1]));
1785
+ return env.Null();
1786
+ }
1787
+
1788
+ #if !defined(_WIN32)
1789
+ int flags = 0;
1790
+
1791
+ if (info.Length() >= 2) {
1792
+ Napi::Object options = info[1].As<Napi::Object>();
1793
+
1794
+ flags |= options.Get("lazy").ToBoolean() ? RTLD_LAZY : RTLD_NOW;
1795
+ flags |= options.Get("global").ToBoolean() ? RTLD_GLOBAL : RTLD_LOCAL;
1796
+ #if defined(RTLD_DEEPBIND)
1797
+ flags |= options.Get("deep").ToBoolean() ? RTLD_DEEPBIND : 0;
1798
+ #endif
1799
+ } else {
1800
+ flags = RTLD_NOW | RTLD_LOCAL;
1801
+ }
1802
+ #endif
1803
+
1804
+ if (!instance->memories.len) {
1805
+ AllocateMemory(instance, instance->config.sync_stack_size, instance->config.sync_heap_size);
1806
+ K_ASSERT(instance->memories.len == 1);
1807
+ }
1808
+
1809
+ // Load shared library
1810
+ void *module = nullptr;
1811
+ #if defined(_WIN32)
1812
+ if (info[0].IsString()) {
1813
+ std::string filename = info[0].As<Napi::String>();
1814
+ module = LoadWindowsLibrary(env, filename.c_str());
1815
+
1816
+ if (!module)
1817
+ return env.Null();
1818
+ } else {
1819
+ module = GetModuleHandle(nullptr);
1820
+ K_ASSERT(module);
1821
+ }
1822
+ #else
1823
+ if (info[0].IsString()) {
1824
+ std::string filename = info[0].As<Napi::String>();
1825
+ module = dlopen(filename.c_str(), flags);
1826
+
1827
+ if (!module) {
1828
+ const char *msg = dlerror();
1829
+
1830
+ if (StartsWith(msg, filename.c_str())) {
1831
+ msg += filename.length();
1832
+
1833
+ while (strchr(": ", msg[0]) && msg[0]) {
1834
+ msg++;
1835
+ }
1836
+ }
1837
+
1838
+ ThrowError<Napi::Error>(env, "Failed to load shared library: %1", msg);
1839
+ return env.Null();
1840
+ }
1841
+ } else {
1842
+ module = RTLD_DEFAULT;
1843
+ }
1844
+ #endif
1845
+
1846
+ LibraryHolder *lib = new LibraryHolder(module);
1847
+
1848
+ Napi::External<void> external = Napi::External<void>::New(env, lib);
1849
+ Napi::Object obj = instance->construct_lib.New({ external }).As<Napi::Object>();
1850
+ SetValueTag(env, obj, &LibraryHandleMarker);
1851
+
1852
+ return obj;
1853
+ }
1854
+
1855
+ static Napi::Value RegisterCallback(const Napi::CallbackInfo &info)
1856
+ {
1857
+ Napi::Env env = info.Env();
1858
+ InstanceData *instance = (InstanceData *)info.Data();
1859
+
1860
+ if (!InitAsyncBroker(env, instance)) [[unlikely]]
1861
+ return env.Null();
1862
+
1863
+ if (info.Length() < 2u) {
1864
+ ThrowError<Napi::TypeError>(env, "Expected 2, got %1", info.Length());
1865
+ return env.Null();
1866
+ }
1867
+ if (!info[0u].IsFunction()) {
1868
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for func, expected function", GetValueType(instance, info[0]));
1869
+ return env.Null();
1870
+ }
1871
+
1872
+ Napi::Function func = info[0].As<Napi::Function>();
1873
+
1874
+ const TypeInfo *type = ResolveType(instance, info[1]);
1875
+ if (!type)
1876
+ return env.Null();
1877
+ if (type->primitive != PrimitiveKind::Callback) {
1878
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 type, expected <callback> * type", type->name);
1879
+ return env.Null();
1880
+ }
1881
+
1882
+ int16_t idx;
1883
+ {
1884
+ std::lock_guard<std::mutex> lock(shared.mutex);
1885
+
1886
+ if (!shared.available.len) [[unlikely]] {
1887
+ ThrowError<Napi::Error>(env, "Too many callbacks are in use (max = %1)", MaxTrampolines);
1888
+ return env.Null();
1889
+ }
1890
+
1891
+ idx = shared.available.data[--shared.available.len];
1892
+ }
1893
+
1894
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
1895
+
1896
+ trampoline->state = 1;
1897
+ trampoline->env = env;
1898
+ trampoline->instance = instance;
1899
+ trampoline->stack0 = instance->memories[0]->stack0;
1900
+ trampoline->proto = type->proto;
1901
+ NAPI_OK(napi_create_reference(env, func, 1, &trampoline->func));
1902
+
1903
+ void *ptr = GetTrampoline(idx);
1904
+
1905
+ // Cache index for fast unregistration
1906
+ instance->trampolines_map.Set(ptr, idx);
1907
+
1908
+ napi_value wrapper = WrapPointer(env, type->ref.type, ptr);
1909
+ return Napi::Value(env, wrapper);
1910
+ }
1911
+
1912
+ static Napi::Value UnregisterCallback(const Napi::CallbackInfo &info)
1913
+ {
1914
+ Napi::Env env = info.Env();
1915
+ InstanceData *instance = (InstanceData *)info.Data();
1916
+
1917
+ if (info.Length() < 1) {
1918
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
1919
+ return env.Null();
1920
+ }
1921
+
1922
+ void *ptr;
1923
+ if (!TryPointer(env, info[0], &ptr)) {
1924
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for id, expected registered callback", GetValueType(instance, info[0]));
1925
+ return env.Null();
1926
+ }
1927
+
1928
+ int16_t idx;
1929
+ {
1930
+ int16_t *it = instance->trampolines_map.Find(ptr);
1931
+
1932
+ if (!it) [[unlikely]] {
1933
+ ThrowError<Napi::Error>(env, "Could not find matching registered callback");
1934
+ return env.Null();
1935
+ }
1936
+
1937
+ idx = *it;
1938
+ instance->trampolines_map.Remove(it);
1939
+ }
1940
+
1941
+ // Release shared trampoline safely
1942
+ {
1943
+ std::lock_guard<std::mutex> lock(shared.mutex);
1944
+
1945
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
1946
+ K_ASSERT(trampoline->func);
1947
+
1948
+ trampoline->state = 0;
1949
+ node_api_delete_reference(env, trampoline->func);
1950
+ trampoline->func = nullptr;
1951
+
1952
+ shared.available.Append(idx);
1953
+ }
1954
+
1955
+ return env.Undefined();
1956
+ }
1957
+
1958
+ static Napi::Value CastValue(const Napi::CallbackInfo &info)
1959
+ {
1960
+ Napi::Env env = info.Env();
1961
+ InstanceData *instance = (InstanceData *)info.Data();
1962
+
1963
+ if (info.Length() < 2) [[unlikely]] {
1964
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
1965
+ return env.Null();
1966
+ }
1967
+
1968
+ Napi::Value value = info[0];
1969
+
1970
+ const TypeInfo *type = ResolveType(instance, info[1]);
1971
+ if (!type) [[unlikely]]
1972
+ return env.Null();
1973
+ if (type->primitive != PrimitiveKind::Pointer &&
1974
+ type->primitive != PrimitiveKind::Callback &&
1975
+ type->primitive != PrimitiveKind::String &&
1976
+ type->primitive != PrimitiveKind::String16 &&
1977
+ type->primitive != PrimitiveKind::String32) [[unlikely]] {
1978
+ ThrowError<Napi::TypeError>(env, "Only pointer or string types can be used for casting");
1979
+ return env.Null();
1980
+ }
1981
+
1982
+ ValueCast *cast = new ValueCast();
1983
+
1984
+ cast->env = env;
1985
+ NAPI_OK(napi_create_reference(env, value, 1, &cast->ref));
1986
+ cast->type = type;
1987
+
1988
+ Napi::External<ValueCast> external = Napi::External<ValueCast>::New(env, cast, [](Napi::BasicEnv, ValueCast *cast) { delete cast; });
1989
+ SetValueTag(env, external, &CastMarker);
1990
+
1991
+ return external;
1992
+ }
1993
+
1994
+ static Napi::Value DecodeValue(const Napi::CallbackInfo &info)
1995
+ {
1996
+ Napi::Env env = info.Env();
1997
+ InstanceData *instance = (InstanceData *)info.Data();
1998
+
1999
+ bool has_offset = (info.Length() >= 2 && info[1].IsNumber());
2000
+ bool has_len = (info.Length() >= 3u + has_offset && info[2 + has_offset].IsNumber());
2001
+
2002
+ if (info.Length() < 2u + has_offset) [[unlikely]] {
2003
+ ThrowError<Napi::TypeError>(env, "Expected %1 to 4 arguments, got %2", 2 + has_offset, info.Length());
2004
+ return env.Null();
2005
+ }
2006
+
2007
+ const TypeInfo *type = ResolveType(instance, info[1u + has_offset]);
2008
+ if (!type) [[unlikely]]
2009
+ return env.Null();
2010
+
2011
+ napi_value ref = info[0];
2012
+ int64_t offset = has_offset ? info[1].As<Napi::Number>().Int64Value() : 0;
2013
+
2014
+ const void *src = nullptr;
2015
+ Size len = 0;
2016
+
2017
+ if (!TryPointer(env, ref, (void **)&src, &len)) {
2018
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for reference, expected pointer", GetValueType(instance, ref));
2019
+ return env.Null();
2020
+ }
2021
+
2022
+ if (len >= 0) {
2023
+ if (offset < 0) [[unlikely]] {
2024
+ ThrowError<Napi::Error>(env, "Offset must be >= 0");
2025
+ return env.Null();
2026
+ }
2027
+ if (len - offset < type->size) [[unlikely]] {
2028
+ ThrowError<Napi::Error>(env, "Expected buffer with size superior or equal to type %1 (%2 bytes)",
2029
+ type->name, type->size + offset);
2030
+ return env.Null();
2031
+ }
2032
+ }
2033
+
2034
+ if (!src) [[unlikely]] {
2035
+ ThrowError<Napi::Error>(env, "Cannot encode data in NULL pointer");
2036
+ return env.Null();
2037
+ }
2038
+
2039
+ src = (const void *)((const uint8_t *)src + offset);
2040
+
2041
+ if (has_len) {
2042
+ Size len = info[2 + has_offset].As<Napi::Number>();
2043
+
2044
+ if (len >= 0) {
2045
+ type = MakeArrayType(instance, type, len);
2046
+ } else {
2047
+ switch (type->primitive) {
2048
+ case PrimitiveKind::Int8:
2049
+ case PrimitiveKind::UInt8: {
2050
+ Size count = strlen((const char *)src);
2051
+ type = MakeArrayType(instance, type, count);
2052
+ } break;
2053
+ case PrimitiveKind::Int16:
2054
+ case PrimitiveKind::UInt16: {
2055
+ Size count = NullTerminatedLength((const char16_t *)src);
2056
+ type = MakeArrayType(instance, type, count);
2057
+ } break;
2058
+ case PrimitiveKind::Int32:
2059
+ case PrimitiveKind::UInt32: {
2060
+ Size count = NullTerminatedLength((const char32_t *)src);
2061
+ type = MakeArrayType(instance, type, count);
2062
+ } break;
2063
+
2064
+ case PrimitiveKind::Pointer: {
2065
+ Size count = NullTerminatedLength((const void **)src);
2066
+ type = MakeArrayType(instance, type, count);
2067
+ } break;
2068
+
2069
+ default: {
2070
+ ThrowError<Napi::TypeError>(env, "Cannot determine null-terminated length for type %1", type->name);
2071
+ return env.Null();
2072
+ } break;
2073
+ }
2074
+ }
2075
+ }
2076
+
2077
+ napi_value ret = Decode(instance, (const uint8_t *)src, type);
2078
+ return Napi::Value(env, ret);
2079
+ }
2080
+
2081
+ template <typename T>
2082
+ static FORCE_INLINE napi_value DecodeInteger(napi_env env, napi_callback_info info)
2083
+ {
2084
+ napi_value arg;
2085
+ size_t count = 1;
2086
+ InstanceData *instance;
2087
+
2088
+ NAPI_OK(napi_get_cb_info(env, info, &count, &arg, nullptr, (void **)&instance));
2089
+
2090
+ if (count < 1) [[unlikely]] {
2091
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", count);
2092
+ return Napi::Env(env).Null();
2093
+ }
2094
+
2095
+ void *ptr = nullptr;
2096
+ if (!TryPointer(env, arg, &ptr)) [[unlikely]] {
2097
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, arg));
2098
+ return Napi::Env(env).Null();
2099
+ }
2100
+
2101
+ T i;
2102
+ memcpy(&i, ptr, K_SIZE(i));
2103
+
2104
+ return NewInt(env, i);
2105
+ }
2106
+
2107
+ template <typename T>
2108
+ static FORCE_INLINE napi_value DecodeIntegerSwap(napi_env env, napi_callback_info info)
2109
+ {
2110
+ napi_value arg;
2111
+ size_t count = 1;
2112
+ InstanceData *instance;
2113
+
2114
+ NAPI_OK(napi_get_cb_info(env, info, &count, &arg, nullptr, (void **)&instance));
2115
+
2116
+ if (count < 1) [[unlikely]] {
2117
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", count);
2118
+ return Napi::Env(env).Null();
2119
+ }
2120
+
2121
+ void *ptr = nullptr;
2122
+ if (!TryPointer(env, arg, &ptr)) [[unlikely]] {
2123
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, arg));
2124
+ return Napi::Env(env).Null();
2125
+ }
2126
+
2127
+ T i;
2128
+ memcpy(&i, ptr, K_SIZE(i));
2129
+
2130
+ return NewInt(env, ReverseBytes(i));
2131
+ }
2132
+
2133
+ #if defined(K_BIG_ENDIAN)
2134
+
2135
+ template <typename T>
2136
+ static FORCE_INLINE napi_value DecodeIntegerLE(napi_env env, napi_callback_info info) { return DecodeIntegerSwap<T>(env, info); }
2137
+ template <typename T>
2138
+ static FORCE_INLINE napi_value DecodeIntegerBE(napi_env env, napi_callback_info info) { return DecodeInteger<T>(env, info); }
2139
+
2140
+ #else
2141
+
2142
+ template <typename T>
2143
+ static FORCE_INLINE napi_value DecodeIntegerLE(napi_env env, napi_callback_info info) { return DecodeInteger<T>(env, info); }
2144
+ template <typename T>
2145
+ static FORCE_INLINE napi_value DecodeIntegerBE(napi_env env, napi_callback_info info) { return DecodeIntegerSwap<T>(env, info); }
2146
+
2147
+ #endif
2148
+
2149
+ static napi_value DecodeFloat(napi_env env, napi_callback_info info)
2150
+ {
2151
+ napi_value arg;
2152
+ size_t count = 1;
2153
+ InstanceData *instance;
2154
+
2155
+ NAPI_OK(napi_get_cb_info(env, info, &count, &arg, nullptr, (void **)&instance));
2156
+
2157
+ if (count < 1) [[unlikely]] {
2158
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", count);
2159
+ return Napi::Env(env).Null();
2160
+ }
2161
+
2162
+ void *ptr = nullptr;
2163
+ if (!TryPointer(env, arg, &ptr)) [[unlikely]] {
2164
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, arg));
2165
+ return Napi::Env(env).Null();
2166
+ }
2167
+
2168
+ float f;
2169
+ memcpy(&f, ptr, K_SIZE(f));
2170
+
2171
+ return NewFloat(env, f);
2172
+ }
2173
+
2174
+ static napi_value DecodeDouble(napi_env env, napi_callback_info info)
2175
+ {
2176
+ napi_value arg;
2177
+ size_t count = 1;
2178
+ InstanceData *instance;
2179
+
2180
+ NAPI_OK(napi_get_cb_info(env, info, &count, &arg, nullptr, (void **)&instance));
2181
+
2182
+ if (count < 1) [[unlikely]] {
2183
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", count);
2184
+ return Napi::Env(env).Null();
2185
+ }
2186
+
2187
+ void *ptr = nullptr;
2188
+ if (!TryPointer(env, arg, &ptr)) [[unlikely]] {
2189
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, arg));
2190
+ return Napi::Env(env).Null();
2191
+ }
2192
+
2193
+ double d;
2194
+ memcpy(&d, ptr, K_SIZE(d));
2195
+
2196
+ return NewFloat(env, d);
2197
+ }
2198
+
2199
+ static napi_value DecodeString(napi_env env, napi_callback_info info)
2200
+ {
2201
+ napi_value args[2];
2202
+ size_t count = 2;
2203
+ InstanceData *instance;
2204
+
2205
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&instance));
2206
+
2207
+ if (count < 1) [[unlikely]] {
2208
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 2 arguments, got %1", count);
2209
+ return Napi::Env(env).Null();
2210
+ }
2211
+
2212
+ void *ptr = nullptr;
2213
+ if (!TryPointer(env, args[0], &ptr)) [[unlikely]] {
2214
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, args[0]));
2215
+ return Napi::Env(env).Null();
2216
+ }
2217
+
2218
+ if (count >= 2) {
2219
+ Size len;
2220
+ if (!TryNumber(env, args[1], &len)) [[unlikely]] {
2221
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for length, expected number", GetValueType(instance, args[1]));
2222
+ return Napi::Env(env).Null();
2223
+ }
2224
+
2225
+ return NewString(env, (const char *)ptr, (size_t)len);
2226
+ } else {
2227
+ return NewString(env, (const char *)ptr);
2228
+ }
2229
+ }
2230
+
2231
+ static napi_value DecodeString16(napi_env env, napi_callback_info info)
2232
+ {
2233
+ napi_value args[2];
2234
+ size_t count = 2;
2235
+ InstanceData *instance;
2236
+
2237
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&instance));
2238
+
2239
+ if (count < 1) [[unlikely]] {
2240
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 2 arguments, got %1", count);
2241
+ return Napi::Env(env).Null();
2242
+ }
2243
+
2244
+ void *ptr = nullptr;
2245
+ if (!TryPointer(env, args[0], &ptr)) [[unlikely]] {
2246
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, args[0]));
2247
+ return Napi::Env(env).Null();
2248
+ }
2249
+
2250
+ if (count >= 2) {
2251
+ Size len;
2252
+ if (!TryNumber(env, args[1], &len)) [[unlikely]] {
2253
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for length, expected number", GetValueType(instance, args[1]));
2254
+ return Napi::Env(env).Null();
2255
+ }
2256
+
2257
+ return NewString(env, (const char16_t *)ptr, (size_t)len);
2258
+ } else {
2259
+ return NewString(env, (const char16_t *)ptr);
2260
+ }
2261
+ }
2262
+
2263
+ static napi_value DecodeString32(napi_env env, napi_callback_info info)
2264
+ {
2265
+ napi_value args[2];
2266
+ size_t count = 2;
2267
+ InstanceData *instance;
2268
+
2269
+ NAPI_OK(napi_get_cb_info(env, info, &count, args, nullptr, (void **)&instance));
2270
+
2271
+ if (count < 1) [[unlikely]] {
2272
+ ThrowError<Napi::TypeError>(env, "Expected 1 to 2 arguments, got %1", count);
2273
+ return Napi::Env(env).Null();
2274
+ }
2275
+
2276
+ void *ptr = nullptr;
2277
+ if (!TryPointer(env, args[0], &ptr)) [[unlikely]] {
2278
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, args[0]));
2279
+ return Napi::Env(env).Null();
2280
+ }
2281
+
2282
+ if (count >= 2) {
2283
+ Size len;
2284
+ if (!TryNumber(env, args[1], &len)) [[unlikely]] {
2285
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for length, expected number", GetValueType(instance, args[1]));
2286
+ return Napi::Env(env).Null();
2287
+ }
2288
+
2289
+ return NewString(env, (const char32_t *)ptr, len);
2290
+ } else {
2291
+ return NewString(env, (const char32_t *)ptr);
2292
+ }
2293
+ }
2294
+
2295
+ static Napi::Value GetPointerAddress(const Napi::CallbackInfo &info)
2296
+ {
2297
+ Napi::Env env = info.Env();
2298
+ InstanceData *instance = (InstanceData *)info.Data();
2299
+
2300
+ if (info.Length() < 1) {
2301
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
2302
+ return env.Null();
2303
+ }
2304
+
2305
+ void *ptr = nullptr;
2306
+ if (!TryPointer(env, info[0], &ptr)) {
2307
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, info[0]));
2308
+ return env.Null();
2309
+ }
2310
+
2311
+ uint64_t ptr64 = (uint64_t)(uintptr_t)ptr;
2312
+ Napi::BigInt bigint = Napi::BigInt::New(env, ptr64);
2313
+
2314
+ return bigint;
2315
+ }
2316
+
2317
+ static Napi::Value CallPointerSync(const Napi::CallbackInfo &info)
2318
+ {
2319
+ Napi::Env env = info.Env();
2320
+ InstanceData *instance = (InstanceData *)info.Data();
2321
+
2322
+ if (info.Length() < 2) [[unlikely]] {
2323
+ ThrowError<Napi::TypeError>(env, "Expected 2 or more arguments, got %1", info.Length());
2324
+ return env.Null();
2325
+ }
2326
+
2327
+ void *ptr = nullptr;
2328
+ if (!TryPointer(env, info[0], &ptr)) {
2329
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, info[0]));
2330
+ return env.Null();
2331
+ }
2332
+
2333
+ const TypeInfo *type = ResolveType(instance, info[1]);
2334
+ if (!type) [[unlikely]]
2335
+ return env.Null();
2336
+ if (type->primitive != PrimitiveKind::Prototype) [[unlikely]] {
2337
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for type, expected function type", GetValueType(instance, info[1]));
2338
+ return env.Null();
2339
+ }
2340
+
2341
+ napi_value ret = CallPointer(env, type->proto, ptr, info.First() + 2, info.Length() - 2);
2342
+ return Napi::Value(env, ret);
2343
+ }
2344
+
2345
+ static Napi::Value EncodeValue(const Napi::CallbackInfo &info)
2346
+ {
2347
+ Napi::Env env = info.Env();
2348
+ InstanceData *instance = (InstanceData *)info.Data();
2349
+
2350
+ bool has_offset = (info.Length() >= 2 && info[1].IsNumber());
2351
+ bool has_len = (info.Length() >= 4u + has_offset && info[3 + has_offset].IsNumber());
2352
+
2353
+ if (info.Length() < 3u + has_offset) [[unlikely]] {
2354
+ ThrowError<Napi::TypeError>(env, "Expected %1 to 5 arguments, got %2", 3 + has_offset, info.Length());
2355
+ return env.Null();
2356
+ }
2357
+
2358
+ const TypeInfo *type = ResolveType(instance, info[1u + has_offset]);
2359
+ if (!type) [[unlikely]]
2360
+ return env.Null();
2361
+
2362
+ Napi::Value ref = info[0];
2363
+ int64_t offset = has_offset ? info[1].As<Napi::Number>().Int64Value() : 0;
2364
+ Napi::Value value = info[2 + has_offset];
2365
+
2366
+ void *dest = nullptr;
2367
+ Size len = 0;
2368
+
2369
+ if (!TryPointer(env, ref, &dest, &len)) {
2370
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for reference, expected pointer", GetValueType(instance, ref));
2371
+ return env.Null();
2372
+ }
2373
+
2374
+ if (len >= 0) {
2375
+ if (offset < 0) [[unlikely]] {
2376
+ ThrowError<Napi::Error>(env, "Offset must be >= 0");
2377
+ return env.Null();
2378
+ }
2379
+ if (len - offset < type->size) [[unlikely]] {
2380
+ ThrowError<Napi::Error>(env, "Expected buffer with size superior or equal to type %1 (%2 bytes)",
2381
+ type->name, type->size + offset);
2382
+ return env.Null();
2383
+ }
2384
+ }
2385
+
2386
+ if (!dest) [[unlikely]] {
2387
+ ThrowError<Napi::Error>(env, "Cannot encode data in NULL pointer");
2388
+ return env.Null();
2389
+ }
2390
+
2391
+ dest = (void *)((uint8_t *)dest + offset);
2392
+
2393
+ if (has_len) {
2394
+ Size len = info[3 + has_offset].As<Napi::Number>();
2395
+
2396
+ if (type->primitive != PrimitiveKind::String &&
2397
+ type->primitive != PrimitiveKind::String16 &&
2398
+ type->primitive != PrimitiveKind::String32 &&
2399
+ type->primitive != PrimitiveKind::Prototype) {
2400
+ if (len < 0) [[unlikely]] {
2401
+ ThrowError<Napi::TypeError>(env, "Automatic (negative) length is only supported when decoding");
2402
+ return env.Null();
2403
+ }
2404
+
2405
+ type = MakeArrayType(instance, type, len);
2406
+ }
2407
+ }
2408
+
2409
+ if (!Encode(instance, (uint8_t *)dest, value, type))
2410
+ return env.Null();
2411
+
2412
+ return env.Undefined();
2413
+ }
2414
+
2415
+ static Napi::Value CreateView(const Napi::CallbackInfo &info)
2416
+ {
2417
+ Napi::Env env = info.Env();
2418
+ InstanceData *instance = (InstanceData *)info.Data();
2419
+
2420
+ if (info.Length() < 1) {
2421
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
2422
+ return env.Null();
2423
+ }
2424
+ if (!info[1].IsNumber()) {
2425
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for length, expected integer", GetValueType(instance, info[1]));
2426
+ return env.Null();
2427
+ }
2428
+
2429
+ void *ptr = nullptr;
2430
+ if (!TryPointer(env, info[0], &ptr)) {
2431
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for ptr, expected pointer", GetValueType(instance, info[0]));
2432
+ return env.Null();
2433
+ }
2434
+
2435
+ Size len = (Size)info[1].As<Napi::Number>().Int64Value();
2436
+
2437
+ if (len) {
2438
+ if (len < 0) [[unlikely]] {
2439
+ ThrowError<Napi::TypeError>(env, "Array length must be positive and non-zero");
2440
+ return env.Null();
2441
+ }
2442
+
2443
+ Napi::ArrayBuffer view = Napi::ArrayBuffer::New(env, ptr, (size_t)len);
2444
+
2445
+ if (!view.ByteLength()) {
2446
+ ThrowError<Napi::Error>(env, "This runtime does not support external buffers");
2447
+ return env.Null();
2448
+ }
2449
+
2450
+ return view;
2451
+ } else {
2452
+ return Napi::ArrayBuffer::New(env, 0);
2453
+ }
2454
+ }
2455
+
2456
+ static Napi::Value ResetKoffi(const Napi::CallbackInfo &info)
2457
+ {
2458
+ Napi::Env env = info.Env();
2459
+ InstanceData *instance = (InstanceData *)info.Data();
2460
+
2461
+ if (instance->broker) {
2462
+ napi_release_threadsafe_function(instance->broker, napi_tsfn_abort);
2463
+ instance->broker = nullptr;
2464
+ }
2465
+
2466
+ instance->types.RemoveFrom(instance->base_types_count);
2467
+
2468
+ {
2469
+ HashSet<const void *> base_types;
2470
+ HashMap<const char *, const TypeInfo *> new_map;
2471
+
2472
+ for (const TypeInfo &type: instance->types) {
2473
+ base_types.Set(&type);
2474
+ }
2475
+
2476
+ for (const auto &bucket: instance->types_map.table) {
2477
+ if (base_types.Find(bucket.value)) {
2478
+ new_map.Set(bucket.key, bucket.value);
2479
+ }
2480
+ }
2481
+
2482
+ std::swap(instance->types_map, new_map);
2483
+ }
2484
+
2485
+ instance->callbacks.Clear();
2486
+
2487
+ for (InstanceMemory *mem: instance->memories) {
2488
+ delete mem;
2489
+ }
2490
+ instance->memories.Clear();
2491
+
2492
+ return env.Undefined();
2493
+ }
2494
+
2495
+ void LibraryHolder::Unload()
2496
+ {
2497
+ #if defined(_WIN32)
2498
+ if (module && module != GetModuleHandle(nullptr)) {
2499
+ FreeLibrary((HMODULE)module);
2500
+ }
2501
+ #else
2502
+ if (module && module != RTLD_DEFAULT) {
2503
+ dlclose(module);
2504
+ }
2505
+ #endif
2506
+
2507
+ module = nullptr;
2508
+ }
2509
+
2510
+ ValueCast::~ValueCast()
2511
+ {
2512
+ node_api_delete_reference(env, ref);
2513
+ }
2514
+
2515
+ FunctionInfo::~FunctionInfo()
2516
+ {
2517
+ if (lib) {
2518
+ lib->Unref();
2519
+ }
2520
+ }
2521
+
2522
+ InstanceMemory::~InstanceMemory()
2523
+ {
2524
+ #if defined(_WIN32)
2525
+ if (stack.ptr) {
2526
+ VirtualFree(stack.ptr, 0, MEM_RELEASE);
2527
+ }
2528
+ if (heap.ptr) {
2529
+ VirtualFree(heap.ptr, 0, MEM_RELEASE);
2530
+ }
2531
+ #else
2532
+ if (stack.ptr) {
2533
+ munmap(stack.ptr, stack.end - stack.ptr);
2534
+ }
2535
+ if (heap.ptr) {
2536
+ munmap(heap.ptr, heap.end - heap.ptr);
2537
+ }
2538
+ #endif
2539
+ }
2540
+
2541
+ static void RegisterPrimitiveType(InstanceData *instance, Napi::Object map, std::initializer_list<const char *> names,
2542
+ PrimitiveKind primitive, int32_t size, int16_t align, const char *ref = nullptr)
2543
+ {
2544
+ K_ASSERT(names.size() > 0);
2545
+ K_ASSERT(align <= size);
2546
+
2547
+ TypeInfo *type = instance->types.AppendDefault();
2548
+
2549
+ type->instance = instance;
2550
+ type->name = *names.begin();
2551
+
2552
+ type->primitive = primitive;
2553
+ type->size = size;
2554
+ type->align = align;
2555
+
2556
+ if (IsInteger(type) || IsFloat(type)) {
2557
+ type->flags |= (int)TypeFlag::HasTypedArray;
2558
+ }
2559
+ if (TestStr(type->name, "char") ||
2560
+ TestStr(type->name, "char16") || TestStr(type->name, "char16_t") ||
2561
+ TestStr(type->name, "char32") || TestStr(type->name, "char32_t") ||
2562
+ TestStr(type->name, "wchar") || TestStr(type->name, "wchar_t")) {
2563
+ type->flags |= (int)TypeFlag::IsCharLike;
2564
+ }
2565
+
2566
+ if (ref) {
2567
+ type->ref.type = instance->types_map.FindValue(ref, nullptr);
2568
+ K_ASSERT(type->ref.type);
2569
+ }
2570
+
2571
+ napi_value wrapper = WrapType(instance, type);
2572
+
2573
+ for (const char *name: names) {
2574
+ bool inserted;
2575
+ instance->types_map.InsertOrGet(name, type, &inserted);
2576
+ K_ASSERT(inserted);
2577
+
2578
+ if (!EndsWith(name, "*")) {
2579
+ map.Set(name, wrapper);
2580
+ }
2581
+ }
2582
+ }
2583
+
2584
+ static inline PrimitiveKind GetSignPrimitive(Size len, bool sign)
2585
+ {
2586
+ switch (len) {
2587
+ case 1: return sign ? PrimitiveKind::Int8 : PrimitiveKind::UInt8;
2588
+ case 2: return sign ? PrimitiveKind::Int16 : PrimitiveKind::UInt16;
2589
+ case 4: return sign ? PrimitiveKind::Int32 : PrimitiveKind::UInt32;
2590
+ case 8: return sign ? PrimitiveKind::Int64 : PrimitiveKind::UInt64;
2591
+ }
2592
+
2593
+ K_UNREACHABLE();
2594
+ }
2595
+
2596
+ static inline PrimitiveKind GetLittleEndianPrimitive(PrimitiveKind kind)
2597
+ {
2598
+ #if defined(K_BIG_ENDIAN)
2599
+ return (PrimitiveKind)((int)kind + 1);
2600
+ #else
2601
+ return kind;
2602
+ #endif
2603
+ }
2604
+
2605
+ static inline PrimitiveKind GetBigEndianPrimitive(PrimitiveKind kind)
2606
+ {
2607
+ #if defined(K_BIG_ENDIAN)
2608
+ return kind;
2609
+ #else
2610
+ return (PrimitiveKind)((int)kind + 1);
2611
+ #endif
2612
+ }
2613
+
2614
+ static bool CanCallNapiGetBufferInfoDirectly(const napi_node_version &node, uint32_t napi)
2615
+ {
2616
+ if (napi >= 10)
2617
+ return true;
2618
+ if (node.major >= 22)
2619
+ return true;
2620
+
2621
+ // Made by looking at the git history of each release branch
2622
+ if (node.major == 21 && node.minor >= 7)
2623
+ return true;
2624
+ if (node.major == 20 && node.minor >= 12)
2625
+ return true;
2626
+
2627
+ return false;
2628
+ }
2629
+
2630
+ static bool CanReferencePrimitiveValues(const napi_node_version &, uint32_t napi)
2631
+ {
2632
+ return napi >= 10;
2633
+ }
2634
+
2635
+ static bool CanDeleteReferenceInFinalizer(const napi_node_version &node, uint32_t)
2636
+ {
2637
+ if (node.major >= 24)
2638
+ return true;
2639
+
2640
+ // Made by looking at the git history of each release branch
2641
+ if (node.major == 23 && node.minor >= 5)
2642
+ return true;
2643
+ if (node.major == 22 && node.minor >= 13)
2644
+ return true;
2645
+ if (node.major == 20 && node.minor >= 19)
2646
+ return true;
2647
+ if (node.major == 20 && node.minor == 18 && node.patch >= 3)
2648
+ return true;
2649
+
2650
+ return false;
2651
+ }
2652
+
2653
+ static napi_value CreateFunction(InstanceData *instance, napi_callback native, const char *name = nullptr)
2654
+ {
2655
+ Napi::Env env = instance->env;
2656
+
2657
+ napi_value func;
2658
+ NAPI_OK(napi_create_function(env, name, NAPI_AUTO_LENGTH, native, instance, &func));
2659
+
2660
+ return func;
2661
+ }
2662
+
2663
+ static Napi::Object InitModule(Napi::Env env, Napi::Object exports)
2664
+ {
2665
+ // Load recent Node-API functions (version >= 9) functions dynamically
2666
+ {
2667
+ static std::once_flag flag;
2668
+
2669
+ std::call_once(flag, [&]() {
2670
+ InitTranslateZeroCall(env);
2671
+
2672
+ #if defined(_WIN32)
2673
+ HMODULE h = GetModuleHandle(nullptr);
2674
+ #define SYMBOL(Symbol) ((decltype(Symbol))GetProcAddress(h, K_STRINGIFY(Symbol)))
2675
+ #else
2676
+ void *h = RTLD_DEFAULT;
2677
+ #define SYMBOL(Symbol) ((decltype(Symbol))dlsym(h, K_STRINGIFY(Symbol)))
2678
+ #endif
2679
+
2680
+ const napi_node_version *node_version = nullptr;
2681
+ uint32_t napi_version = 0;
2682
+ napi_get_node_version(env, &node_version);
2683
+ napi_get_version(env, &napi_version);
2684
+
2685
+ if (CanCallNapiGetBufferInfoDirectly(*node_version, napi_version)) {
2686
+ node_api_get_buffer_info = napi_get_buffer_info;
2687
+ } else {
2688
+ // Before Node 20.12, napi_get_buffer_info() would assert/crash
2689
+ // when used with something it did not support, instead of returning napi_invalid_arg.
2690
+ // So we need to call napi_is_buffer() for old versions before trying napi_get_buffer_info().
2691
+
2692
+ node_api_get_buffer_info = [](napi_env env, napi_value value, void **data, size_t *length) {
2693
+ if (!IsBuffer(env, value))
2694
+ return napi_invalid_arg;
2695
+ return napi_get_buffer_info(env, value, data, length);
2696
+ };
2697
+ }
2698
+
2699
+ if (CanReferencePrimitiveValues(*node_version, napi_version)) {
2700
+ // We can't use optimized property keys in older versions because we need to create
2701
+ // references to them, but napi_create_reference() was not usable with primitive values.
2702
+ node_api_create_property_key_utf8 = SYMBOL(node_api_create_property_key_utf8);
2703
+ }
2704
+
2705
+ if (!CanDeleteReferenceInFinalizer(*node_version, napi_version)) {
2706
+ // napi_delete_reference cannot be safely used in older Node versions because it
2707
+ // errors out (or even asserts) if it gets called in a finalizer. In this case,
2708
+ // use experimental API to try to run it later.
2709
+ node_api_post_finalizer = SYMBOL(node_api_post_finalizer);
2710
+
2711
+ if (node_api_post_finalizer) {
2712
+ node_api_delete_reference = [](node_api_basic_env env, napi_ref ref) {
2713
+ node_api_post_finalizer((napi_env)env, [](napi_env env, void *data, void *) {
2714
+ napi_ref ref = (napi_ref)data;
2715
+ napi_delete_reference(env, ref);
2716
+ }, (void *)ref, nullptr);
2717
+
2718
+ return napi_ok;
2719
+ };
2720
+ } else {
2721
+ node_api_delete_reference = napi_delete_reference;
2722
+ }
2723
+ } else {
2724
+ node_api_delete_reference = napi_delete_reference;
2725
+ }
2726
+
2727
+ node_api_create_object_with_properties = SYMBOL(node_api_create_object_with_properties);
2728
+
2729
+ #undef SYMBOL
2730
+ });
2731
+ }
2732
+
2733
+ InstanceData *instance = new InstanceData();
2734
+ K_CRITICAL(instance, "Failed to initialize Koffi");
2735
+
2736
+ instance->env = env;
2737
+
2738
+ #if defined(__clang__)
2739
+ // First call to napi_create_double() does some weird stuff I can't explain
2740
+ // in clang-cl builds. I don't like this... but this fixes it, somehow ><
2741
+ NewFloat(env, 0.0);
2742
+ #endif
2743
+
2744
+ exports.Set("config", Napi::Function::New(env, GetSetConfig, "config", instance));
2745
+ exports.Set("stats", Napi::Function::New(env, GetStats, "stats", instance));
2746
+
2747
+ exports.Set("struct", Napi::Function::New(env, CreatePaddedStructType, "struct", instance));
2748
+ exports.Set("pack", Napi::Function::New(env, CreatePackedStructType, "pack", instance));
2749
+ exports.Set("union", Napi::Function::New(env, CreateUnionType, "union", instance));
2750
+ exports.Set("Union", Napi::Function::New(env, InstantiateUnion, "Union", instance));
2751
+ exports.Set("opaque", Napi::Function::New(env, CreateOpaqueType, "opaque", instance));
2752
+ exports.Set("pointer", Napi::Function::New(env, CreatePointerType, "pointer", instance));
2753
+ exports.Set("array", Napi::Function::New(env, CreateArrayType, "array", instance));
2754
+ exports.Set("proto", Napi::Function::New(env, CreateFunctionType, "proto", instance));
2755
+ exports.Set("alias", Napi::Function::New(env, CreateTypeAlias, "alias", instance));
2756
+ exports.Set("enumeration", Napi::Function::New(env, CreateEnumType, "enumeration", instance));
2757
+
2758
+ exports.Set("type", Napi::Function::New(env, GetResolvedType, "type", instance));
2759
+ #if defined(EXTERNAL_TYPES)
2760
+ exports.Set("introspect", Napi::Function::New(env, GetTypeDefinition, "introspect", instance));
2761
+ #endif
2762
+
2763
+ exports.Set("load", Napi::Function::New(env, LoadSharedLibrary, "load", instance));
2764
+
2765
+ exports.Set("in", Napi::Function::New(env, MarkIn, "in", instance));
2766
+ exports.Set("out", Napi::Function::New(env, MarkOut, "out", instance));
2767
+ exports.Set("inout", Napi::Function::New(env, MarkInOut, "inout", instance));
2768
+
2769
+ exports.Set("disposable", Napi::Function::New(env, CreateDisposableType, "disposable", instance));
2770
+ exports.Set("alloc", Napi::Function::New(env, CallAlloc, "alloc", instance));
2771
+ exports.Set("free", Napi::Function::New(env, CallFree, "free", instance));
2772
+
2773
+ exports.Set("register", Napi::Function::New(env, RegisterCallback, "register", instance));
2774
+ exports.Set("unregister", Napi::Function::New(env, UnregisterCallback, "unregister", instance));
2775
+
2776
+ exports.Set("as", Napi::Function::New(env, CastValue, "as", instance));
2777
+ exports.Set("address", Napi::Function::New(env, GetPointerAddress, "address", instance));
2778
+ exports.Set("call", Napi::Function::New(env, CallPointerSync, "call", instance));
2779
+ exports.Set("encode", Napi::Function::New(env, EncodeValue, "encode", instance));
2780
+ exports.Set("view", Napi::Function::New(env, CreateView, "view", instance));
2781
+
2782
+ {
2783
+ Napi::Function decode = Napi::Function::New(env, DecodeValue, "decode", instance);
2784
+
2785
+ decode.Set("char", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<char>(env, info); }, "char"));
2786
+ decode.Set("uchar", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<unsigned char>(env, info); }, "uchar"));
2787
+ decode.Set("short", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<short>(env, info); }, "short"));
2788
+ decode.Set("ushort", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<unsigned short>(env, info); }, "ushort"));
2789
+ decode.Set("int", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<int>(env, info); }, "int"));
2790
+ decode.Set("uint", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<unsigned int>(env, info); }, "uint"));
2791
+ decode.Set("long", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<long>(env, info); }, "long"));
2792
+ decode.Set("ulong", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<unsigned long>(env, info); }, "ulong"));
2793
+ decode.Set("longlong", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<long long>(env, info); }, "longlong"));
2794
+ decode.Set("ulonglong", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<unsigned long long>(env, info); }, "ulonglong"));
2795
+ decode.Set("int8", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<int8_t>(env, info); }, "int8"));
2796
+ decode.Set("uint8", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<uint8_t>(env, info); }, "uint8"));
2797
+ decode.Set("int16", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<int16_t>(env, info); }, "int16"));
2798
+ decode.Set("int16le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<int16_t>(env, info); }, "int16le"));
2799
+ decode.Set("int16be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<int16_t>(env, info); }, "int16be"));
2800
+ decode.Set("uint16", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<uint16_t>(env, info); }, "uint16"));
2801
+ decode.Set("uint16le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<uint16_t>(env, info); }, "uint16le"));
2802
+ decode.Set("uint16be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<uint16_t>(env, info); }, "uint16be"));
2803
+ decode.Set("int32", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<int32_t>(env, info); }, "int32"));
2804
+ decode.Set("int32le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<int32_t>(env, info); }, "int32le"));
2805
+ decode.Set("int32be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<int32_t>(env, info); }, "int32be"));
2806
+ decode.Set("uint32", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<uint32_t>(env, info); }, "uint32"));
2807
+ decode.Set("uint32le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<uint32_t>(env, info); }, "uint32le"));
2808
+ decode.Set("uint32be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<uint32_t>(env, info); }, "uint32be"));
2809
+ decode.Set("int64", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<int64_t>(env, info); }, "int64"));
2810
+ decode.Set("int64le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<int64_t>(env, info); }, "int64le"));
2811
+ decode.Set("int64be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<int64_t>(env, info); }, "int64be"));
2812
+ decode.Set("uint64", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeInteger<uint64_t>(env, info); }, "uint64"));
2813
+ decode.Set("uint64le", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerLE<uint64_t>(env, info); }, "uint64le"));
2814
+ decode.Set("uint64be", CreateFunction(instance, [](napi_env env, napi_callback_info info) { return DecodeIntegerBE<uint64_t>(env, info); }, "uint64be"));
2815
+ decode.Set("float", CreateFunction(instance, DecodeFloat, "float"));
2816
+ decode.Set("double", CreateFunction(instance, DecodeDouble, "double"));
2817
+ decode.Set("string", CreateFunction(instance, DecodeString, "string"));
2818
+ decode.Set("string16", CreateFunction(instance, DecodeString16, "string16"));
2819
+ decode.Set("string32", CreateFunction(instance, DecodeString32, "string32"));
2820
+ if constexpr (K_SIZE(wchar_t) == 2) {
2821
+ decode.Set("wstring", CreateFunction(instance, DecodeString16, "wstring"));
2822
+ } else if constexpr (K_SIZE(wchar_t) == 4) {
2823
+ decode.Set("wstring", CreateFunction(instance, DecodeString32, "wstring"));
2824
+ }
2825
+ static_assert(K_SIZE(wchar_t) == 2 || K_SIZE(wchar_t) == 4);
2826
+
2827
+ exports.Set("decode", decode);
2828
+ }
2829
+
2830
+ exports.Set("reset", Napi::Function::New(env, ResetKoffi, "reset", instance));
2831
+
2832
+ exports.Set("errno", Napi::Function::New(env, GetOrSetErrNo, "errno", instance));
2833
+
2834
+ // Export useful OS info
2835
+ {
2836
+ Napi::Object os = Napi::Object::New(env);
2837
+ exports.Set("os", os);
2838
+
2839
+ Napi::Object codes = Napi::Object::New(env);
2840
+
2841
+ for (const ErrnoCodeInfo &info: ErrnoCodes) {
2842
+ codes.Set(info.name, NewInt(env, (int32_t)info.value));
2843
+ }
2844
+
2845
+ os.Set("errno", codes);
2846
+ }
2847
+
2848
+ #if defined(_WIN32)
2849
+ exports.Set("extension", NewString(env, ".dll"));
2850
+ #elif defined(__APPLE__)
2851
+ exports.Set("extension", NewString(env, ".dylib"));
2852
+ #else
2853
+ exports.Set("extension", NewString(env, ".so"));
2854
+ #endif
2855
+
2856
+ // Init object classes and symbols
2857
+ {
2858
+ instance->object_constructor = Napi::Persistent(env.RunScript("Object.prototype").As<Napi::Object>());
2859
+ instance->construct_lib = Napi::Persistent(LibraryHandle::InitClass(instance));
2860
+ #if !defined(EXTERNAL_TYPES)
2861
+ instance->construct_type = Napi::Persistent(TypeObject::InitClass(instance));
2862
+ #endif
2863
+ instance->construct_poll = Napi::Persistent(PollHandle::InitClass(instance));
2864
+ instance->active_symbol = Napi::Persistent(Napi::Symbol::New(env, "active"));
2865
+
2866
+ exports.Set("LibraryHandle", instance->construct_lib.Value());
2867
+ #if !defined(EXTERNAL_TYPES)
2868
+ exports.Set("TypeObject", instance->construct_type.Value());
2869
+ #endif
2870
+ }
2871
+
2872
+ // Init base types
2873
+ {
2874
+ Napi::Object types = Napi::Object::New(env);
2875
+ exports.Set("types", types);
2876
+
2877
+ RegisterPrimitiveType(instance, types, {"void"}, PrimitiveKind::Void, 0, 0);
2878
+ RegisterPrimitiveType(instance, types, {"bool"}, PrimitiveKind::Bool, K_SIZE(bool), alignof(bool));
2879
+ RegisterPrimitiveType(instance, types, {"int8_t", "int8"}, PrimitiveKind::Int8, 1, 1);
2880
+ RegisterPrimitiveType(instance, types, {"uint8_t", "uint8"}, PrimitiveKind::UInt8, 1, 1);
2881
+ RegisterPrimitiveType(instance, types, {"char"}, PrimitiveKind::Int8, 1, 1);
2882
+ RegisterPrimitiveType(instance, types, {"unsigned char", "uchar"}, PrimitiveKind::UInt8, 1, 1);
2883
+ RegisterPrimitiveType(instance, types, {"char16_t", "char16"}, PrimitiveKind::Int16, 2, 2);
2884
+ RegisterPrimitiveType(instance, types, {"char32_t", "char32"}, PrimitiveKind::Int32, 4, 4);
2885
+ if constexpr (K_SIZE(wchar_t) == 2) {
2886
+ RegisterPrimitiveType(instance, types, {"wchar_t", "wchar"}, PrimitiveKind::Int16, 2, 2);
2887
+ } else if constexpr (K_SIZE(wchar_t) == 4) {
2888
+ RegisterPrimitiveType(instance, types, {"wchar_t", "wchar"}, PrimitiveKind::Int32, 4, 4);
2889
+ }
2890
+ RegisterPrimitiveType(instance, types, {"int16_t", "int16"}, PrimitiveKind::Int16, 2, 2);
2891
+ RegisterPrimitiveType(instance, types, {"int16_le_t", "int16_le"}, GetLittleEndianPrimitive(PrimitiveKind::Int16), 2, 2);
2892
+ RegisterPrimitiveType(instance, types, {"int16_be_t", "int16_be"}, GetBigEndianPrimitive(PrimitiveKind::Int16), 2, 2);
2893
+ RegisterPrimitiveType(instance, types, {"uint16_t", "uint16"}, PrimitiveKind::UInt16, 2, 2);
2894
+ RegisterPrimitiveType(instance, types, {"uint16_le_t", "uint16_le"}, GetLittleEndianPrimitive(PrimitiveKind::UInt16), 2, 2);
2895
+ RegisterPrimitiveType(instance, types, {"uint16_be_t", "uint16_be"}, GetBigEndianPrimitive(PrimitiveKind::UInt16), 2, 2);
2896
+ RegisterPrimitiveType(instance, types, {"short"}, PrimitiveKind::Int16, 2, 2);
2897
+ RegisterPrimitiveType(instance, types, {"unsigned short", "ushort"}, PrimitiveKind::UInt16, 2, 2);
2898
+ RegisterPrimitiveType(instance, types, {"int32_t", "int32"}, PrimitiveKind::Int32, 4, 4);
2899
+ RegisterPrimitiveType(instance, types, {"int32_le_t", "int32_le"}, GetLittleEndianPrimitive(PrimitiveKind::Int32), 4, 4);
2900
+ RegisterPrimitiveType(instance, types, {"int32_be_t", "int32_be"}, GetBigEndianPrimitive(PrimitiveKind::Int32), 4, 4);
2901
+ RegisterPrimitiveType(instance, types, {"uint32_t", "uint32"}, PrimitiveKind::UInt32, 4, 4);
2902
+ RegisterPrimitiveType(instance, types, {"uint32_le_t", "uint32_le"}, GetLittleEndianPrimitive(PrimitiveKind::UInt32), 4, 4);
2903
+ RegisterPrimitiveType(instance, types, {"uint32_be_t", "uint32_be"}, GetBigEndianPrimitive(PrimitiveKind::UInt32), 4, 4);
2904
+ RegisterPrimitiveType(instance, types, {"int"}, PrimitiveKind::Int32, 4, 4);
2905
+ RegisterPrimitiveType(instance, types, {"unsigned int", "uint"}, PrimitiveKind::UInt32, 4, 4);
2906
+ RegisterPrimitiveType(instance, types, {"int64_t", "int64"}, PrimitiveKind::Int64, 8, alignof(int64_t));
2907
+ RegisterPrimitiveType(instance, types, {"int64_le_t", "int64_le"}, GetLittleEndianPrimitive(PrimitiveKind::Int64), 8, alignof(int64_t));
2908
+ RegisterPrimitiveType(instance, types, {"int64_be_t", "int64_be"}, GetBigEndianPrimitive(PrimitiveKind::Int64), 8, alignof(int64_t));
2909
+ RegisterPrimitiveType(instance, types, {"uint64_t", "uint64"}, PrimitiveKind::UInt64, 8, alignof(int64_t));
2910
+ RegisterPrimitiveType(instance, types, {"uint64_le_t", "uint64_le"}, GetLittleEndianPrimitive(PrimitiveKind::UInt64), 8, alignof(int64_t));
2911
+ RegisterPrimitiveType(instance, types, {"uint64_be_t", "uint64_be"}, GetBigEndianPrimitive(PrimitiveKind::UInt64), 8, alignof(int64_t));
2912
+ RegisterPrimitiveType(instance, types, {"intptr_t", "intptr"}, GetSignPrimitive(K_SIZE(intptr_t), true), K_SIZE(intptr_t), alignof(intptr_t));
2913
+ RegisterPrimitiveType(instance, types, {"uintptr_t", "uintptr"}, GetSignPrimitive(K_SIZE(intptr_t), false), K_SIZE(intptr_t), alignof(intptr_t));
2914
+ RegisterPrimitiveType(instance, types, {"size_t"}, GetSignPrimitive(K_SIZE(size_t), false), K_SIZE(size_t), alignof(size_t));
2915
+ RegisterPrimitiveType(instance, types, {"long"}, GetSignPrimitive(K_SIZE(long), true), K_SIZE(long), alignof(long));
2916
+ RegisterPrimitiveType(instance, types, {"unsigned long", "ulong"}, GetSignPrimitive(K_SIZE(long), false), K_SIZE(long), alignof(long));
2917
+ RegisterPrimitiveType(instance, types, {"long long", "longlong"}, PrimitiveKind::Int64, K_SIZE(int64_t), alignof(int64_t));
2918
+ RegisterPrimitiveType(instance, types, {"unsigned long long", "ulonglong"}, PrimitiveKind::UInt64, K_SIZE(uint64_t), alignof(uint64_t));
2919
+ RegisterPrimitiveType(instance, types, {"float", "float32"}, PrimitiveKind::Float32, 4, alignof(float));
2920
+ RegisterPrimitiveType(instance, types, {"double", "float64"}, PrimitiveKind::Float64, 8, alignof(double));
2921
+ RegisterPrimitiveType(instance, types, {"char *", "str", "string"}, PrimitiveKind::String, K_SIZE(void *), alignof(void *), "char");
2922
+ RegisterPrimitiveType(instance, types, {"char16_t *", "char16 *", "str16", "string16"}, PrimitiveKind::String16, K_SIZE(void *), alignof(void *), "char16_t");
2923
+ RegisterPrimitiveType(instance, types, {"char32_t *", "char32 *", "str32", "string32"}, PrimitiveKind::String32, K_SIZE(void *), alignof(void *), "char32_t");
2924
+ if constexpr (K_SIZE(wchar_t) == 2) {
2925
+ RegisterPrimitiveType(instance, types, {"wchar_t *", "wchar *", "wstring"}, PrimitiveKind::String16, K_SIZE(void *), alignof(void *), "wchar_t");
2926
+ } else if constexpr (K_SIZE(wchar_t) == 4) {
2927
+ RegisterPrimitiveType(instance, types, {"wchar_t *", "wchar *", "wstring"}, PrimitiveKind::String32, K_SIZE(void *), alignof(void *), "wchar_t");
2928
+ }
2929
+ static_assert(K_SIZE(wchar_t) == 2 || K_SIZE(wchar_t) == 4);
2930
+
2931
+ instance->void_type = instance->types_map.FindValue("void", nullptr);
2932
+ instance->char_type = instance->types_map.FindValue("char", nullptr);
2933
+ instance->char16_type = instance->types_map.FindValue("char16", nullptr);
2934
+ instance->char32_type = instance->types_map.FindValue("char32", nullptr);
2935
+ instance->str_type = instance->types_map.FindValue("char *", nullptr);
2936
+ instance->str16_type = instance->types_map.FindValue("char16_t *", nullptr);
2937
+ instance->str32_type = instance->types_map.FindValue("char32_t *", nullptr);
2938
+
2939
+ instance->base_types_count = instance->types.count;
2940
+ }
2941
+
2942
+ // Expose internal Node stuff
2943
+ {
2944
+ Napi::Object node = Napi::Object::New(env);
2945
+ exports.Set("node", node);
2946
+
2947
+ node.Set("env", WrapPointer(env, instance->void_type, (napi_env)env));
2948
+
2949
+ node.Set("poll", Napi::Function::New(env, &Poll, "poll", instance));
2950
+ node.Set("PollHandle", instance->construct_poll.Value());
2951
+ }
2952
+
2953
+ exports.Set("version", NewString(env, K_STRINGIFY(VERSION)));
2954
+
2955
+ #if defined(_WIN32)
2956
+ {
2957
+ TEB *teb = GetTEB();
2958
+
2959
+ instance->main_stack_max = teb->StackBase;
2960
+ instance->main_stack_min = teb->DeallocationStack;
2961
+ }
2962
+ #endif
2963
+
2964
+ instance->main_thread_id = std::this_thread::get_id();
2965
+
2966
+ napi_add_env_cleanup_hook(env, [](void *udata) {
2967
+ InstanceData *instance = (InstanceData *)udata;
2968
+
2969
+ if (instance->broker) {
2970
+ // This deadlocks if we try to do this when the module is destroyed, when
2971
+ // the InstanceData destructor runs, so run in the env cleanup hook instead,
2972
+ // where it seems to go okay.
2973
+ napi_release_threadsafe_function(instance->broker, napi_tsfn_abort);
2974
+ }
2975
+ }, instance);
2976
+
2977
+ return exports;
2978
+ }
2979
+
2980
+ InstanceData::~InstanceData()
2981
+ {
2982
+ delete variadic_func;
2983
+
2984
+ for (InstanceMemory *mem: memories) {
2985
+ delete mem;
2986
+ }
2987
+
2988
+ // Clean-up leftover trampoline references
2989
+ {
2990
+ std::lock_guard<std::mutex> lock(shared.mutex);
2991
+
2992
+ for (int16_t idx = 0; idx < MaxTrampolines; idx++) {
2993
+ TrampolineInfo *trampoline = &shared.trampolines[idx];
2994
+
2995
+ if (trampoline->instance == this) {
2996
+ trampoline->instance = nullptr;
2997
+ if (trampoline->func) {
2998
+ node_api_delete_reference(env, trampoline->func);
2999
+ trampoline->func = nullptr;
3000
+ }
3001
+ trampoline->state = 0;
3002
+ }
3003
+ }
3004
+ }
3005
+ }
3006
+
3007
+ NODE_API_MODULE(koffi, InitModule);
3008
+
3009
+ }