@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,299 @@
1
+ # Output and input/output
2
+
3
+ For simplicity, and because Javascript only has value semantics for primitive types, Koffi can marshal out (or in/out) multiple types of parameters:
4
+
5
+ - [Structs](composites#structs) (to/from JS objects)
6
+ - [Unions](composites#unions)
7
+ - [Opaque types](composites#opaque-types)
8
+ - String buffers
9
+
10
+ In order to change an argument from input-only to output or input/output, use the following functions:
11
+
12
+ - `koffi.out()` on a pointer, e.g. `koffi.out(koffi.pointer(timeval))` (where timeval is a struct type)
13
+ - `koffi.inout()` for dual input/output parameters
14
+
15
+ The same can be done when declaring a function with a C-like prototype string, with the MSDN-like type qualifiers:
16
+
17
+ - `_Out_` for output parameters
18
+ - `_Inout_` for dual input/output parameters
19
+
20
+ > [!TIP]
21
+ > The Win32 API provides many functions that take a pointer to an empty struct for output, except that the first member of the struct (often named `cbSize`) must be set to the size of the struct before calling the function. An example of such a function is `GetLastInputInfo()`.
22
+ >
23
+ > In order to use these functions in Koffi, you must define the parameter as `_Inout_`: the value must be copied in (to provide `cbSize` to the function) and then the filled struct must be copied out to JS.
24
+ >
25
+ > Look at the [Win32 example](#win32-struct-example) below for more information.
26
+
27
+ ## Primitive value
28
+
29
+ This Windows example enumerate all Chrome windows along with their PID and their title. The `GetWindowThreadProcessId()` function illustrates how to get a primitive value from an output argument.
30
+
31
+ ```js
32
+ import koffi from 'koffi';
33
+ // CJS: const koffi = require('koffi');
34
+
35
+ const user32 = koffi.load('user32.dll');
36
+
37
+ const DWORD = koffi.alias('DWORD', 'uint32_t');
38
+ const HANDLE = koffi.pointer('HANDLE', koffi.opaque());
39
+ const HWND = koffi.alias('HWND', HANDLE);
40
+
41
+ const FindWindowEx = user32.func('HWND __stdcall FindWindowExW(HWND hWndParent, HWND hWndChildAfter, const char16_t *lpszClass, const char16_t *lpszWindow)');
42
+ const GetWindowThreadProcessId = user32.func('DWORD __stdcall GetWindowThreadProcessId(HWND hWnd, _Out_ DWORD *lpdwProcessId)');
43
+ const GetWindowText = user32.func('int __stdcall GetWindowTextA(HWND hWnd, _Out_ uint8_t *lpString, int nMaxCount)');
44
+
45
+ for (let hwnd = null;;) {
46
+ hwnd = FindWindowEx(0, hwnd, 'Chrome_WidgetWin_1', null);
47
+
48
+ if (!hwnd)
49
+ break;
50
+
51
+ // Get PID
52
+ let pid;
53
+ {
54
+ let ptr = [null];
55
+ let tid = GetWindowThreadProcessId(hwnd, ptr);
56
+
57
+ if (!tid) {
58
+ // Maybe the process ended in-between?
59
+ continue;
60
+ }
61
+
62
+ pid = ptr[0];
63
+ }
64
+
65
+ // Get window title
66
+ let title;
67
+ {
68
+ let buf = Buffer.allocUnsafe(1024);
69
+ let length = GetWindowText(hwnd, buf, buf.length);
70
+
71
+ if (!length) {
72
+ // Maybe the process ended in-between?
73
+ continue;
74
+ }
75
+
76
+ title = koffi.decode(buf, 'char', length);
77
+ }
78
+
79
+ console.log({ PID: pid, Title: title });
80
+ }
81
+ ```
82
+
83
+ ## Struct examples
84
+
85
+ ### POSIX struct example
86
+
87
+ This example calls the POSIX function `gettimeofday()`, and uses the prototype-like syntax.
88
+
89
+ ```js
90
+ import koffi from 'koffi';
91
+ // CJS: const koffi = require('koffi');
92
+
93
+ const lib = koffi.load('libc.so.6');
94
+
95
+ const timeval = koffi.struct('timeval', {
96
+ tv_sec: 'unsigned int',
97
+ tv_usec: 'unsigned int'
98
+ });
99
+ const timezone = koffi.struct('timezone', {
100
+ tz_minuteswest: 'int',
101
+ tz_dsttime: 'int'
102
+ });
103
+
104
+ // The _Out_ qualifiers instruct Koffi to marshal out the values
105
+ const gettimeofday = lib.func('int gettimeofday(_Out_ timeval *tv, _Out_ timezone *tz)');
106
+
107
+ let tv = {};
108
+ gettimeofday(tv, null);
109
+
110
+ console.log(tv);
111
+ ```
112
+
113
+ ### Win32 struct example
114
+
115
+ Many Win32 functions that use struct outputs require you to set a size member (often named `cbSize`). These functions won't work with `_Out_` because the size value must be copied from JS to C, use `_Inout_` in this case.
116
+
117
+ ```js
118
+ import koffi from 'koffi';
119
+ // CJS: const koffi = require('koffi');
120
+
121
+ const user32 = koffi.load('user32.dll');
122
+
123
+ const LASTINPUTINFO = koffi.struct('LASTINPUTINFO', {
124
+ cbSize: 'uint',
125
+ dwTime: 'uint32'
126
+ });
127
+ const GetLastInputInfo = user32.func('bool __stdcall GetLastInputInfo(_Inout_ LASTINPUTINFO *plii)');
128
+
129
+ let info = { cbSize: koffi.sizeof(LASTINPUTINFO) };
130
+ let success = GetLastInputInfo(info);
131
+
132
+ console.log(success, info);
133
+ ```
134
+
135
+ ## Opaque type example
136
+
137
+ This example opens an in-memory SQLite database, and uses the node-ffi-style function declaration syntax.
138
+
139
+ ```js
140
+ import koffi from 'koffi';
141
+ // CJS: const koffi = require('koffi');
142
+
143
+ const lib = koffi.load('sqlite3.so');
144
+
145
+ const sqlite3 = koffi.opaque('sqlite3');
146
+
147
+ // Use koffi.out() on a double pointer to copy out (from C to JS) after the call
148
+ const sqlite3_open_v2 = lib.func('sqlite3_open_v2', 'int', ['str', koffi.out(koffi.pointer(sqlite3, 2)), 'int', 'str']);
149
+ const sqlite3_close_v2 = lib.func('sqlite3_close_v2', 'int', [koffi.pointer(sqlite3)]);
150
+
151
+ const SQLITE_OPEN_READWRITE = 0x2;
152
+ const SQLITE_OPEN_CREATE = 0x4;
153
+
154
+ let out = [null];
155
+ if (sqlite3_open_v2(':memory:', out, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, null) != 0)
156
+ throw new Error('Failed to open database');
157
+ let db = out[0];
158
+
159
+ sqlite3_close_v2(db);
160
+ ```
161
+
162
+ ## String buffer example
163
+
164
+ This example calls a C function to concatenate two strings to a pre-allocated string buffer. Since JS strings are immutable, you must pass an array with a single string instead.
165
+
166
+ ```c
167
+ void ConcatToBuffer(const char *str1, const char *str2, char *out)
168
+ {
169
+ size_t len = 0;
170
+
171
+ for (size_t i = 0; str1[i]; i++) {
172
+ out[len++] = str1[i];
173
+ }
174
+ for (size_t i = 0; str2[i]; i++) {
175
+ out[len++] = str2[i];
176
+ }
177
+
178
+ out[len] = 0;
179
+ }
180
+ ```
181
+
182
+ ```js
183
+ const ConcatToBuffer = lib.func('void ConcatToBuffer(const char *str1, const char *str2, _Out_ char *out)');
184
+
185
+ let str1 = 'Hello ';
186
+ let str2 = 'Friends!';
187
+
188
+ // We need to reserve space for the output buffer! Including the NUL terminator
189
+ // because ConcatToBuffer() expects so, but Koffi can convert back to a JS string
190
+ // without it (if we reserve the right size).
191
+ let out = ['\0'.repeat(str1.length + str2.length + 1)];
192
+
193
+ ConcatToBuffer(str1, str2, out);
194
+
195
+ console.log(out[0]);
196
+ ```
197
+
198
+ # Output buffers
199
+
200
+ In most cases, you can use buffers and typed arrays to provide output buffers. This works as long as the buffer only gets used while the native C function is being called. See [transient pointers](#transient-pointers) below for an example.
201
+
202
+ > [!WARNING]
203
+ > It is unsafe to keep the pointer around in the native code, or to change the contents outside of the function call where it is provided.
204
+ >
205
+ > If you need to provide a pointer that will be kept around, allocate memory with [koffi.alloc()](#stable-pointers) instead.
206
+
207
+ ## Transient pointers
208
+
209
+ You can use buffers and typed arrays for output (and input/output) pointer parameters. Simply pass the buffer as an argument and the native function will receive a pointer to its contents.
210
+
211
+ Once the native function returns, you can decode the content with `koffi.decode(value, type)` as in the following example:
212
+
213
+ ```js
214
+ import koffi from 'koffi';
215
+ // CJS: const koffi = require('koffi');
216
+
217
+ const lib = koffi.load('libc.so.6');
218
+
219
+ const Vec3 = koffi.struct('Vec3', {
220
+ x: 'float32',
221
+ y: 'float32',
222
+ z: 'float32'
223
+ })
224
+
225
+ const memcpy = lib.func('void *memcpy(_Out_ void *dest, const void *src, size_t size)');
226
+
227
+ let vec1 = { x: 1, y: 2, z: 3 };
228
+ let vec2 = null;
229
+
230
+ // Copy the vector in a convoluted way through memcpy
231
+ {
232
+ let src = koffi.as(vec1, 'Vec3 *');
233
+ let dest = Buffer.allocUnsafe(koffi.sizeof(Vec3));
234
+
235
+ memcpy(dest, src, koffi.sizeof(Vec3));
236
+
237
+ vec2 = koffi.decode(dest, Vec3);
238
+ }
239
+
240
+ // CHange vector1, leaving copy alone
241
+ [vec1.x, vec1.y, vec1.z] = [vec1.z, vec1.y, vec1.x];
242
+
243
+ console.log(vec1); // { x: 3, y: 2, z: 1 }
244
+ console.log(vec2); // { x: 1, y: 2, z: 3 }
245
+ ```
246
+
247
+ See [decoding variables](values#decode-to-js-values) for more information about the decode function.
248
+
249
+ ## Stable pointers
250
+
251
+ In some cases, the native code may need to change the output buffer at a later time, maybe during a later call or from another thread.
252
+
253
+ In this case, it is **not safe to use buffers or typed arrays**!
254
+
255
+ However, you can use `koffi.alloc(type, len)` to allocate memory and get a pointer that won't move, and can be safely used at any time by the native code. Use [koffi.decode()](values#decode-to-js-values) to read data from the pointer when needed.
256
+
257
+ The example below sets up some memory to be used as an output buffer where a concatenation function appends a string on each call.
258
+
259
+ ```c
260
+ #include <assert.h>
261
+ #include <stddef.h>
262
+
263
+ static char *buf_ptr;
264
+ static size_t buf_len;
265
+ static size_t buf_size;
266
+
267
+ void reset_buffer(char *buf, size_t size)
268
+ {
269
+ assert(size > 1);
270
+
271
+ buf_ptr = buf;
272
+ buf_len = 0;
273
+ buf_size = size - 1; // Keep space for trailing NUL
274
+
275
+ buf_ptr[0] = 0;
276
+ }
277
+
278
+ void append_str(const char *str)
279
+ {
280
+ for (size_t i = 0; str[i] && buf_len < buf_size; i++, buf_len++) {
281
+ buf_ptr[buf_len] = str[i];
282
+ }
283
+ buf_ptr[buf_len] = 0;
284
+ }
285
+ ```
286
+
287
+ ```js
288
+ const reset_buffer = lib.func('void reset_buffer(char *buf, size_t size)');
289
+ const append_str = lib.func('void append_str(const char *str)');
290
+
291
+ let output = koffi.alloc('char', 64);
292
+ reset_buffer(output, 64);
293
+
294
+ append_str('Hello');
295
+ console.log(koffi.decode(output, 'char', -1)); // Prints Hello
296
+
297
+ append_str(' World!');
298
+ console.log(koffi.decode(output, 'char', -1)); // Prints Hello World!
299
+ ```
@@ -0,0 +1,385 @@
1
+ # How pointers are used
2
+
3
+ In C, pointer arguments are used for differenty purposes. It is important to distinguish these use cases because Koffi provides different ways to deal with each of them:
4
+
5
+ - **Struct pointers**: Use of struct pointers by C libraries fall in two cases: avoid (potentially) expensive copies, and to let the function change struct contents (output or input/output arguments).
6
+ - **Opaque pointers**: the library does not expose the contents of the structs, and only provides you with a pointer to it (e.g. `FILE *`). Only the functions provided by the library can do something with this pointer, in Koffi we call this an opaque type. This is usually done for ABI-stability reason, and to prevent library users from messing directly with library internals.
7
+ - **Pointers to primitive types**: This is more rare, and generally used for output or input/output arguments. The Win32 API has a lot of these.
8
+ - **Arrays**: in C, dynamically-sized arrays are usually passed to functions with pointers, either NULL-terminated (or any other sentinel value) or with an additional length argument.
9
+
10
+ Koffi uses BigInt numbers to represent pointers.
11
+
12
+ # Data pointers
13
+
14
+ ## Struct pointers
15
+
16
+ The following Win32 example uses `GetCursorPos()` (with an [output parameter](output)) to retrieve and show the current cursor position.
17
+
18
+ ```js
19
+ import koffi from 'koffi';
20
+ // CJS: const koffi = require('koffi');
21
+
22
+ const lib = koffi.load('user32.dll');
23
+
24
+ // Type declarations
25
+ const POINT = koffi.struct('POINT', {
26
+ x: 'long',
27
+ y: 'long'
28
+ });
29
+
30
+ // Functions declarations
31
+ const GetCursorPos = lib.func('int __stdcall GetCursorPos(_Out_ POINT *pos)');
32
+
33
+ // Get and show cursor position
34
+ let pos = {};
35
+ if (!GetCursorPos(pos))
36
+ throw new Error('Failed to get cursor position');
37
+ console.log(pos);
38
+ ```
39
+
40
+ ## Opaque pointers
41
+
42
+ Some C libraries use handles, which behave as pointers to opaque structs. An example of this is the HANDLE type in the Win32 API. If you want to reproduce this behavior, you can define a **named pointer type** to an opaque type, like so:
43
+
44
+ ```js
45
+ const HANDLE = koffi.pointer('HANDLE', koffi.opaque());
46
+
47
+ // And now you get to use it this way:
48
+ const GetHandleInformation = lib.func('bool __stdcall GetHandleInformation(HANDLE h, _Out_ uint32_t *flags)');
49
+ const CloseHandle = lib.func('bool __stdcall CloseHandle(HANDLE h)');
50
+ ```
51
+
52
+ ## Pointer to primitive types
53
+
54
+ In Javascript, it is not possible to pass a primitive value by reference to another function. This means that you cannot call a function and expect it to modify the value of one of its number or string parameter.
55
+
56
+ However, arrays and objects (among others) are reference type values. Assigning an array or an object from one variable to another does not invole any copy. Instead, as the following example illustrates, the new variable references the same array as the first:
57
+
58
+ ```js
59
+ let list1 = [1, 2];
60
+ let list2 = list1;
61
+
62
+ list2[1] = 42;
63
+
64
+ console.log(list1); // Prints [1, 42]
65
+ ```
66
+
67
+ All of this means that C functions that are expected to modify their primitive output values (such as an `int *` parameter) cannot be used directly. However, thanks to Koffi's transparent array support, you can use Javascript arrays to approximate reference semantics with single-element arrays.
68
+
69
+ Below, you can find an example of an addition function where the result is stored in an `int *` [input/output parameter](output) and how to use this function from Koffi.
70
+
71
+ ```c
72
+ void AddInt(int *dest, int add)
73
+ {
74
+ *dest += add;
75
+ }
76
+ ```
77
+
78
+ You can simply pass a single-element array as the first argument:
79
+
80
+ ```js
81
+ const AddInt = lib.func('void AddInt(_Inout_ int *dest, int add)');
82
+
83
+ let sum = [36];
84
+ AddInt(sum, 6);
85
+
86
+ console.log(sum[0]); // Prints 42
87
+ ```
88
+
89
+ ## Dynamic arrays
90
+
91
+ In C, dynamically-sized arrays are usually passed around as pointers. The length is either passed as an additional argument, or inferred from the array content itself, for example with a terminating sentinel value (such as a NULL pointers in the case of an array of strings).
92
+
93
+ Koffi can translate JS arrays and TypedArrays to pointer arguments. However, because C does not have a proper notion of dynamically-sized arrays (fat pointers), you need to provide the length or the sentinel value yourself depending on the API.
94
+
95
+ Here is a simple example of a C function taking a NULL-terminated list of strings as input, to calculate the total length of all strings.
96
+
97
+ ```c
98
+ // Build with: clang -fPIC -o length.so -shared length.c -Wall -O2
99
+
100
+ #include <stdlib.h>
101
+ #include <stdint.h>
102
+ #include <string.h>
103
+
104
+ int64_t ComputeTotalLength(const char **strings)
105
+ {
106
+ int64_t total = 0;
107
+
108
+ for (const char **ptr = strings; *ptr; ptr++) {
109
+ const char *str = *ptr;
110
+ total += strlen(str);
111
+ }
112
+
113
+ return total;
114
+ }
115
+ ```
116
+
117
+ ```js
118
+ import koffi from 'koffi';
119
+ // CJS: const koffi = require('koffi');
120
+
121
+ const lib = koffi.load('./length.so');
122
+
123
+ const ComputeTotalLength = lib.func('int64_t ComputeTotalLength(const char **strings)');
124
+
125
+ let strings = ['Get', 'Total', 'Length', null];
126
+ let total = ComputeTotalLength(strings);
127
+
128
+ console.log(total); // Prints 14
129
+ ```
130
+
131
+ By default, just like for objects, array arguments are copied from JS to C but not vice-versa. You can however change the direction as documented in the section on [output parameters](output).
132
+
133
+ # Function pointers
134
+
135
+ You can call a function pointer in two ways:
136
+
137
+ - Directly call the function pointer with `koffi.call(ptr, type, ...)`
138
+ - Decode the function pointer to an actual function with `koffi.decode(ptr, type)`
139
+
140
+ The example below shows how to call an `int (*)(int, int)` C function pointer both ways, based on the following native C library:
141
+
142
+ ```c
143
+ typedef int BinaryIntFunc(int a, int b);
144
+
145
+ static int AddInt(int a, int b) { return a + b; }
146
+ static int SubstractInt(int a, int b) { return a - b; }
147
+
148
+ BinaryIntFunc *GetBinaryIntFunction(const char *type)
149
+ {
150
+ if (!strcmp(type, "add")) {
151
+ return AddInt;
152
+ } else if (!strcmp(type, "substract")) {
153
+ return SubstractInt;
154
+ } else {
155
+ return NULL;
156
+ }
157
+ }
158
+ ```
159
+
160
+ ## Call pointer directly
161
+
162
+ Use `koffi.call(ptr, type, ...)` to call a function pointer. The first two arguments are the pointer itself and the type of the function you are trying to call (declared with `koffi.proto()` as shown below), and the remaining arguments are used for the call.
163
+
164
+ ```js
165
+ // Declare function type
166
+ const BinaryIntFunc = koffi.proto('int BinaryIntFunc(int a, int b)');
167
+
168
+ const GetBinaryIntFunction = lib.func('BinaryIntFunc *GetBinaryIntFunction(const char *name)');
169
+
170
+ const add_ptr = GetBinaryIntFunction('add');
171
+ const substract_ptr = GetBinaryIntFunction('substract');
172
+
173
+ let sum = koffi.call(add_ptr, BinaryIntFunc, 4, 5);
174
+ let delta = koffi.call(substract_ptr, BinaryIntFunc, 100, 58);
175
+
176
+ console.log(sum, delta); // Prints 9 and 42
177
+ ```
178
+
179
+ ## Decode pointer to function
180
+
181
+ Use `koffi.decode(ptr, type)` to get back a JS function, which you can then use like any other Koffi function.
182
+
183
+ ```js
184
+ // Declare function type
185
+ const BinaryIntFunc = koffi.proto('int BinaryIntFunc(int a, int b)');
186
+
187
+ const GetBinaryIntFunction = lib.func('BinaryIntFunc *GetBinaryIntFunction(const char *name)');
188
+
189
+ const add = koffi.decode(GetBinaryIntFunction('add'), BinaryIntFunc);
190
+ const substract = koffi.decode(GetBinaryIntFunction('substract'), BinaryIntFunc);
191
+
192
+ let sum = add(4, 5);
193
+ let delta = substract(100, 58);
194
+
195
+ console.log(sum, delta); // Prints 9 and 42
196
+ ```
197
+
198
+ This method also allows you to perform an [asynchronous call](load#asynchronous-calls) with the async member of the decoded function.
199
+
200
+ # Handling void pointers
201
+
202
+ Many C functions use `void *` parameters in order to pass polymorphic objects and arrays, meaning that the data format changes can change depending on one other argument, or on some kind of struct tag member.
203
+
204
+ Koffi provides two features to deal with this:
205
+
206
+ - You can use `koffi.as(value, type)` to tell Koffi what kind of type is actually expected, as shown in the example below.
207
+ - Buffers and typed JS arrays can be used as values in place everywhere a pointer is expected. See [dynamic arrays](#dynamic-arrays) for more information, for input or output.
208
+
209
+ The example below shows the use of `koffi.as()` to read the header of a PNG file with `fread()` directly to a JS object. It also uses [endian-sensitive integers](primitives#endian-sensitive-integers) to decode PNG header values:
210
+
211
+ ```js
212
+ import koffi from 'koffi';
213
+ // CJS: const koffi = require('koffi');
214
+
215
+ const lib = koffi.load('libc.so.6');
216
+
217
+ const FILE = koffi.opaque('FILE');
218
+
219
+ const PngHeader = koffi.pack('PngHeader', {
220
+ signature: koffi.array('uint8_t', 8),
221
+ ihdr: koffi.pack({
222
+ length: 'uint32_be_t',
223
+ chunk: koffi.array('char', 4),
224
+ width: 'uint32_be_t',
225
+ height: 'uint32_be_t',
226
+ depth: 'uint8_t',
227
+ color: 'uint8_t',
228
+ compression: 'uint8_t',
229
+ filter: 'uint8_t',
230
+ interlace: 'uint8_t',
231
+ crc: 'uint32_be_t'
232
+ })
233
+ });
234
+
235
+ const fopen = lib.func('FILE *fopen(const char *path, const char *mode)');
236
+ const fclose = lib.func('int fclose(FILE *fp)');
237
+ const fread = lib.func('size_t fread(_Out_ void *ptr, size_t size, size_t nmemb, FILE *fp)');
238
+
239
+ let filename = process.argv[2];
240
+ if (filename == null)
241
+ throw new Error('Usage: node png.js <image.png>');
242
+
243
+ let hdr = {};
244
+ {
245
+ let fp = fopen(filename, 'rb');
246
+ if (!fp)
247
+ throw new Error(`Failed to open '${filename}'`);
248
+
249
+ try {
250
+ let len = fread(koffi.as(hdr, 'PngHeader *'), 1, koffi.sizeof(PngHeader), fp);
251
+ if (len < koffi.sizeof(PngHeader))
252
+ throw new Error('Failed to read PNG header');
253
+ } finally {
254
+ fclose(fp);
255
+ }
256
+ }
257
+
258
+ console.log('PNG header:', hdr);
259
+ ```
260
+
261
+ # Disposable types
262
+
263
+ Disposable types allow you to register a function that will automatically called after each C to JS conversion performed by Koffi. This can be used to avoid leaking heap-allocated strings, for example.
264
+
265
+ Some C functions return heap-allocated values directly or through output parameters. While Koffi automatically converts values from C to JS (to a string or an object), it does not know when something needs to be freed, or how.
266
+
267
+ For opaque types, such as FILE, this does not matter because you will explicitly call `fclose()` on them. But some values (such as strings) get implicitly converted by Koffi, and you lose access to the original pointer. This creates a leak if the string is heap-allocated.
268
+
269
+ To avoid this, you can instruct Koffi to call a function on the original pointer once the conversion is done, by creating a **disposable type** with `koffi.dispose(name, type, func)`. This creates a type derived from another type, the only difference being that *func* gets called with the original pointer once the value has been converted and is not needed anymore.
270
+
271
+ The *name* can be omitted to create an anonymous disposable type. If *func* is omitted or is null, Koffi will use `koffi.free(ptr)` (which calls the standard C library *free* function under the hood).
272
+
273
+ ```js
274
+ const AnonHeapStr = koffi.disposable('str'); // Anonymous type (cannot be used in function prototypes)
275
+ const NamedHeapStr = koffi.disposable('HeapStr', 'str'); // Same thing, but named so usable in function prototypes
276
+ const ExplicitFree = koffi.disposable('HeapStr16', 'str16', koffi.free); // You can specify any other JS function
277
+ ```
278
+
279
+ The following example illustrates the use of a disposable type derived from *str*.
280
+
281
+ ```js
282
+ import koffi from 'koffi';
283
+ // CJS: const koffi = require('koffi');
284
+
285
+ const lib = koffi.load('libc.so.6');
286
+
287
+ const HeapStr = koffi.disposable('str');
288
+ const strdup = lib.cdecl('strdup', HeapStr, ['str']);
289
+
290
+ let copy = strdup('Hello!');
291
+ console.log(copy); // Prints Hello!
292
+ ```
293
+
294
+ When you declare functions with the [prototype-like syntax](load#definition-syntax), you can either use named disposable types or use the '!' shortcut qualifier with compatibles types, as shown in the example below. This qualifier creates an anonymous disposable type that calls `koffi.free(ptr)`.
295
+
296
+ ```js
297
+ import koffi from 'koffi';
298
+ // CJS: const koffi = require('koffi');
299
+
300
+ const lib = koffi.load('libc.so.6');
301
+
302
+ // You can also use: const strdup = lib.func('const char *! strdup(const char *str)')
303
+ const strdup = lib.func('str! strdup(const char *str)');
304
+
305
+ let copy = strdup('World!');
306
+ console.log(copy); // Prints World!
307
+ ```
308
+
309
+ Disposable types can only be created from pointer or string types.
310
+
311
+ > [!WARNING]
312
+ > Be careful on Windows: if your shared library uses a different CRT (such as msvcrt), the memory could have been allocated by a different malloc/free implementation or heap, resulting in undefined behavior if you use `koffi.free()`.
313
+
314
+ # External buffers (views)
315
+
316
+ You can access unmanaged memory with `koffi.view(ptr, len)`. This function takes a pointer and a length, and creates an ArrayBuffer through which you can access the underlying memory without copy.
317
+
318
+ > [!NOTE]
319
+ > Some runtimes (such as Electron) forbid the use of external buffers. In this case, trying to create a view will trigger an exception.
320
+
321
+ The following Linux example writes the string "Hello World!" to a file named "hello.txt" through mmaped memory, to demontrate the use of `koffi.view()`:
322
+
323
+ ```js
324
+ import koffi from 'koffi';
325
+ // CJS: const koffi = require('koffi');
326
+
327
+ const libc = koffi.load('libc.so.6');
328
+
329
+ const mode_t = koffi.alias('mode_t', 'uint32_t');
330
+ const off_t = koffi.alias('off_t', 'int64_t');
331
+
332
+ // These values are used on Linux and may differ on other systems
333
+ const O_RDONLY = 00000000;
334
+ const O_WRONLY = 00000001;
335
+ const O_RDWR = 00000002;
336
+ const O_CREAT = 00000100;
337
+ const O_EXCL = 00000200;
338
+ const O_CLOEXEC = 02000000;
339
+
340
+ // These values are used on Linux and may differ on other systems
341
+ const PROT_READ = 0x01;
342
+ const PROT_WRITE = 0x02;
343
+ const PROT_EXEC = 0x04;
344
+ const MAP_SHARED = 0x01;
345
+ const MAP_PRIVATE = 0x02;
346
+
347
+ const open = libc.func('int open(const char *path, int flags, uint32_t mode)');
348
+ const close = libc.func('int close(int fd)');
349
+ const ftruncate = libc.func('int ftruncate(int fd, off_t length)');
350
+ const mmap = libc.func('void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)');
351
+ const munmap = libc.func('int munmap(void *addr, size_t length)');
352
+ const strerror = libc.func('const char *strerror(int errnum)');
353
+
354
+ write('hello.txt', 'Hello World!');
355
+
356
+ function write(filename, str) {
357
+ let fd = -1;
358
+ let ptr = null;
359
+
360
+ // Work with encoded string
361
+ str = Buffer.from(str);
362
+
363
+ try {
364
+ fd = open(filename, O_CREAT | O_EXCL | O_RDWR | O_CLOEXEC, 0644);
365
+ if (fd < 0)
366
+ throw new Error(`Failed to create '${filename}': ` + strerror(koffi.errno()));
367
+
368
+ if (ftruncate(fd, str.length) < 0)
369
+ throw new Error(`Failed to resize '${filename}': ` + strerror(koffi.errno()));
370
+
371
+ ptr = mmap(null, str.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
372
+ if (ptr == null)
373
+ throw new Error(`Failed to map '${filename}' to memory: ` + strerror(koffi.errno()));
374
+
375
+ let ab = koffi.view(ptr, str.length);
376
+ let view = new Uint8Array(ab);
377
+
378
+ str.copy(view);
379
+ } finally {
380
+ if (ptr != null)
381
+ munmap(ptr, str.length);
382
+ close(fd);
383
+ }
384
+ }
385
+ ```