koffi 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CMakeLists.txt +94 -0
  2. package/README.md +153 -0
  3. package/build/ALL_BUILD.vcxproj +190 -0
  4. package/build/ALL_BUILD.vcxproj.filters +8 -0
  5. package/build/CMakeCache.txt +429 -0
  6. package/build/CMakeFiles/3.23.0-rc1/CMakeASMCompiler.cmake +20 -0
  7. package/build/CMakeFiles/3.23.0-rc1/CMakeASM_MASMCompiler.cmake +20 -0
  8. package/build/CMakeFiles/3.23.0-rc1/CMakeCCompiler.cmake +72 -0
  9. package/build/CMakeFiles/3.23.0-rc1/CMakeCXXCompiler.cmake +83 -0
  10. package/build/CMakeFiles/3.23.0-rc1/CMakeDetermineCompilerABI_C.bin +0 -0
  11. package/build/CMakeFiles/3.23.0-rc1/CMakeDetermineCompilerABI_CXX.bin +0 -0
  12. package/build/CMakeFiles/3.23.0-rc1/CMakeRCCompiler.cmake +6 -0
  13. package/build/CMakeFiles/3.23.0-rc1/CMakeSystem.cmake +15 -0
  14. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/CMakeCCompilerId.c +828 -0
  15. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/CompilerIdC.exe +0 -0
  16. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/CompilerIdC.vcxproj +71 -0
  17. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CMakeCCompilerId.obj +0 -0
  18. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.exe.recipe +11 -0
  19. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/CL.command.1.tlog +0 -0
  20. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/CL.read.1.tlog +0 -0
  21. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/CL.write.1.tlog +0 -0
  22. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/CompilerIdC.lastbuildstate +2 -0
  23. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/link.command.1.tlog +0 -0
  24. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/link.read.1.tlog +0 -0
  25. package/build/CMakeFiles/3.23.0-rc1/CompilerIdC/Debug/CompilerIdC.tlog/link.write.1.tlog +0 -0
  26. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/CMakeCXXCompilerId.cpp +816 -0
  27. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/CompilerIdCXX.exe +0 -0
  28. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/CompilerIdCXX.vcxproj +71 -0
  29. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CMakeCXXCompilerId.obj +0 -0
  30. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.exe.recipe +11 -0
  31. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/CL.command.1.tlog +0 -0
  32. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/CL.read.1.tlog +0 -0
  33. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/CL.write.1.tlog +0 -0
  34. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/CompilerIdCXX.lastbuildstate +2 -0
  35. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/link.command.1.tlog +0 -0
  36. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/link.read.1.tlog +0 -0
  37. package/build/CMakeFiles/3.23.0-rc1/CompilerIdCXX/Debug/CompilerIdCXX.tlog/link.write.1.tlog +0 -0
  38. package/build/CMakeFiles/3.23.0-rc1/VCTargetsPath.txt +1 -0
  39. package/build/CMakeFiles/3.23.0-rc1/VCTargetsPath.vcxproj +31 -0
  40. package/build/CMakeFiles/3.23.0-rc1/x64/Debug/VCTargetsPath.recipe +11 -0
  41. package/build/CMakeFiles/3.23.0-rc1/x64/Debug/VCTargetsPath.tlog/VCTargetsPath.lastbuildstate +2 -0
  42. package/build/CMakeFiles/41bcd16856091d4a38fd1f71fbe2f202/generate.stamp.rule +1 -0
  43. package/build/CMakeFiles/CMakeError.log +108 -0
  44. package/build/CMakeFiles/CMakeOutput.log +413 -0
  45. package/build/CMakeFiles/TargetDirectories.txt +4 -0
  46. package/build/CMakeFiles/cmake.check_cache +1 -0
  47. package/build/CMakeFiles/generate.stamp +1 -0
  48. package/build/CMakeFiles/generate.stamp.depend +28 -0
  49. package/build/CMakeFiles/generate.stamp.list +1 -0
  50. package/build/Raylib.dir/Release/Raylib.dll.recipe +14 -0
  51. package/build/Raylib.dir/Release/Raylib.tlog/CL.command.1.tlog +0 -0
  52. package/build/Raylib.dir/Release/Raylib.tlog/CL.read.1.tlog +0 -0
  53. package/build/Raylib.dir/Release/Raylib.tlog/CL.write.1.tlog +0 -0
  54. package/build/Raylib.dir/Release/Raylib.tlog/CustomBuild.command.1.tlog +10 -0
  55. package/build/Raylib.dir/Release/Raylib.tlog/CustomBuild.read.1.tlog +27 -0
  56. package/build/Raylib.dir/Release/Raylib.tlog/CustomBuild.write.1.tlog +2 -0
  57. package/build/Raylib.dir/Release/Raylib.tlog/Raylib.lastbuildstate +2 -0
  58. package/build/Raylib.dir/Release/Raylib.tlog/Raylib.write.1u.tlog +0 -0
  59. package/build/Raylib.dir/Release/Raylib.tlog/link.command.1.tlog +0 -0
  60. package/build/Raylib.dir/Release/Raylib.tlog/link.read.1.tlog +0 -0
  61. package/build/Raylib.dir/Release/Raylib.tlog/link.write.1.tlog +0 -0
  62. package/build/Raylib.dir/Release/raudio.obj +0 -0
  63. package/build/Raylib.dir/Release/rcore.obj +0 -0
  64. package/build/Raylib.dir/Release/rglfw.obj +0 -0
  65. package/build/Raylib.dir/Release/rmodels.obj +0 -0
  66. package/build/Raylib.dir/Release/rshapes.obj +0 -0
  67. package/build/Raylib.dir/Release/rtext.obj +0 -0
  68. package/build/Raylib.dir/Release/rtextures.obj +0 -0
  69. package/build/Raylib.dir/Release/utils.obj +0 -0
  70. package/build/Raylib.vcxproj +358 -0
  71. package/build/Raylib.vcxproj.filters +37 -0
  72. package/build/Release/Raylib.dll +0 -0
  73. package/build/Release/Raylib.exp +0 -0
  74. package/build/Release/Raylib.lib +0 -0
  75. package/build/Release/koffi.exp +0 -0
  76. package/build/Release/koffi.lib +0 -0
  77. package/build/Release/koffi.node +0 -0
  78. package/build/ZERO_CHECK.vcxproj +176 -0
  79. package/build/ZERO_CHECK.vcxproj.filters +13 -0
  80. package/build/cmake_install.cmake +44 -0
  81. package/build/koffi.dir/Release/call_arm64.obj +0 -0
  82. package/build/koffi.dir/Release/call_x64_sysv.obj +0 -0
  83. package/build/koffi.dir/Release/call_x64_win.obj +0 -0
  84. package/build/koffi.dir/Release/call_x64_win_fwd.obj +0 -0
  85. package/build/koffi.dir/Release/call_x86.obj +0 -0
  86. package/build/koffi.dir/Release/ffi.obj +0 -0
  87. package/build/koffi.dir/Release/koffi.node.recipe +14 -0
  88. package/build/koffi.dir/Release/koffi.tlog/CL.command.1.tlog +0 -0
  89. package/build/koffi.dir/Release/koffi.tlog/CL.read.1.tlog +0 -0
  90. package/build/koffi.dir/Release/koffi.tlog/CL.write.1.tlog +0 -0
  91. package/build/koffi.dir/Release/koffi.tlog/CustomBuild.command.1.tlog +10 -0
  92. package/build/koffi.dir/Release/koffi.tlog/CustomBuild.read.1.tlog +27 -0
  93. package/build/koffi.dir/Release/koffi.tlog/CustomBuild.write.1.tlog +2 -0
  94. package/build/koffi.dir/Release/koffi.tlog/Masm.read.1u.tlog +0 -0
  95. package/build/koffi.dir/Release/koffi.tlog/Masm.write.1u.tlog +0 -0
  96. package/build/koffi.dir/Release/koffi.tlog/koffi.lastbuildstate +2 -0
  97. package/build/koffi.dir/Release/koffi.tlog/koffi.write.1u.tlog +0 -0
  98. package/build/koffi.dir/Release/koffi.tlog/link.command.1.tlog +0 -0
  99. package/build/koffi.dir/Release/koffi.tlog/link.read.1.tlog +0 -0
  100. package/build/koffi.dir/Release/koffi.tlog/link.write.1.tlog +0 -0
  101. package/build/koffi.dir/Release/libcc.obj +0 -0
  102. package/build/koffi.dir/Release/util.obj +0 -0
  103. package/build/koffi.dir/Release/win_delay_load_hook.obj +0 -0
  104. package/build/koffi.sln +67 -0
  105. package/build/koffi.vcxproj +363 -0
  106. package/build/koffi.vcxproj.filters +40 -0
  107. package/build/x64/Release/ALL_BUILD/ALL_BUILD.recipe +20 -0
  108. package/build/x64/Release/ALL_BUILD/ALL_BUILD.tlog/ALL_BUILD.lastbuildstate +2 -0
  109. package/build/x64/Release/ALL_BUILD/ALL_BUILD.tlog/CustomBuild.command.1.tlog +10 -0
  110. package/build/x64/Release/ALL_BUILD/ALL_BUILD.tlog/CustomBuild.read.1.tlog +27 -0
  111. package/build/x64/Release/ALL_BUILD/ALL_BUILD.tlog/CustomBuild.write.1.tlog +2 -0
  112. package/build/x64/Release/ZERO_CHECK/ZERO_CHECK.recipe +11 -0
  113. package/build/x64/Release/ZERO_CHECK/ZERO_CHECK.tlog/CustomBuild.command.1.tlog +10 -0
  114. package/build/x64/Release/ZERO_CHECK/ZERO_CHECK.tlog/CustomBuild.read.1.tlog +28 -0
  115. package/build/x64/Release/ZERO_CHECK/ZERO_CHECK.tlog/CustomBuild.write.1.tlog +2 -0
  116. package/build/x64/Release/ZERO_CHECK/ZERO_CHECK.tlog/ZERO_CHECK.lastbuildstate +2 -0
  117. package/package.json +14 -0
  118. package/src/call.hh +27 -0
  119. package/src/call_arm64.cc +482 -0
  120. package/src/call_arm64_fwd.S +115 -0
  121. package/src/call_x64_sysv.cc +477 -0
  122. package/src/call_x64_sysv_fwd.S +131 -0
  123. package/src/call_x64_win.cc +243 -0
  124. package/src/call_x64_win_fwd.asm +105 -0
  125. package/src/call_x86.cc +259 -0
  126. package/src/call_x86_fwd.S +48 -0
  127. package/src/call_x86_fwd.asm +50 -0
  128. package/src/ffi.cc +504 -0
  129. package/src/ffi.hh +135 -0
  130. package/src/util.cc +296 -0
  131. package/src/util.hh +80 -0
@@ -0,0 +1,50 @@
1
+ ; This program is free software: you can redistribute it and/or modify
2
+ ; it under the terms of the GNU Affero General Public License as published by
3
+ ; the Free Software Foundation, either version 3 of the License, or
4
+ ; (at your option) any later version.
5
+ ;
6
+ ; This program is distributed in the hope that it will be useful,
7
+ ; but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ ; GNU Affero General Public License for more details.
10
+ ;
11
+ ; You should have received a copy of the GNU Affero General Public License
12
+ ; along with this program. If not, see https://www.gnu.org/licenses/.
13
+
14
+ public ForwardCallG
15
+ public ForwardCallF
16
+ public ForwardCallD
17
+
18
+ .model flat, C
19
+ .code
20
+
21
+ ; Copy function pointer to EAX, in order to save it through argument forwarding.
22
+ ; Save ESP in EBX (non-volatile), and use carefully assembled stack provided by caller.
23
+ ; Call native function.
24
+ ; Once done, restore normal stack pointer and return.
25
+ ; The return value is passed back untouched.
26
+ forward macro
27
+ endbr32
28
+ push ebx
29
+ mov ebx, esp
30
+ mov eax, dword ptr [esp+8]
31
+ mov esp, dword ptr [esp+12]
32
+ call eax
33
+ mov esp, ebx
34
+ pop ebx
35
+ ret
36
+ endm
37
+
38
+ ForwardCallG proc
39
+ forward
40
+ ForwardCallG endp
41
+
42
+ ForwardCallF proc
43
+ forward
44
+ ForwardCallF endp
45
+
46
+ ForwardCallD proc
47
+ forward
48
+ ForwardCallD endp
49
+
50
+ end
package/src/ffi.cc ADDED
@@ -0,0 +1,504 @@
1
+ // This program is free software: you can redistribute it and/or modify
2
+ // it under the terms of the GNU Affero General Public License as published by
3
+ // the Free Software Foundation, either version 3 of the License, or
4
+ // (at your option) any later version.
5
+ //
6
+ // This program is distributed in the hope that it will be useful,
7
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ // GNU Affero General Public License for more details.
10
+ //
11
+ // You should have received a copy of the GNU Affero General Public License
12
+ // along with this program. If not, see https://www.gnu.org/licenses/.
13
+
14
+ #include "vendor/libcc/libcc.hh"
15
+ #include "ffi.hh"
16
+ #include "call.hh"
17
+ #include "util.hh"
18
+
19
+ #ifdef _WIN32
20
+ #ifndef NOMINMAX
21
+ #define NOMINMAX
22
+ #endif
23
+ #ifndef WIN32_LEAN_AND_MEAN
24
+ #define WIN32_LEAN_AND_MEAN
25
+ #endif
26
+ #include <windows.h>
27
+ #include <ntsecapi.h>
28
+ #else
29
+ #include <dlfcn.h>
30
+ #include <unistd.h>
31
+ #endif
32
+
33
+ #include <napi.h>
34
+ #if NODE_WANT_INTERNALS
35
+ #include <env-inl.h>
36
+ #include <js_native_api_v8.h>
37
+ #endif
38
+
39
+ namespace RG {
40
+
41
+ // Value does not matter, the tag system uses memory addresses
42
+ static const int TypeInfoMarker = 0xdeadbeef;
43
+
44
+ static const TypeInfo *ResolveType(const InstanceData *instance, Napi::Value value)
45
+ {
46
+ if (value.IsString()) {
47
+ std::string str = value.As<Napi::String>();
48
+
49
+ const TypeInfo *type = instance->types_map.FindValue(str.c_str(), nullptr);
50
+
51
+ if (!type) {
52
+ ThrowError<Napi::TypeError>(value.Env(), "Unknown type string '%1'", str.c_str());
53
+ return nullptr;
54
+ }
55
+
56
+ return type;
57
+ } else if (CheckValueTag(instance, value, &TypeInfoMarker)) {
58
+ Napi::External<TypeInfo> external = value.As<Napi::External<TypeInfo>>();
59
+
60
+ const TypeInfo *type = external.Data();
61
+ RG_ASSERT(type);
62
+
63
+ return type;
64
+ } else {
65
+ ThrowError<Napi::TypeError>(value.Env(), "Unexpected %1 value as type specifier, expected string or type", GetValueType(instance, value));
66
+ return nullptr;
67
+ }
68
+ }
69
+
70
+ static Napi::Value CreateStructType(const Napi::CallbackInfo &info)
71
+ {
72
+ Napi::Env env = info.Env();
73
+ InstanceData *instance = env.GetInstanceData<InstanceData>();
74
+
75
+ if (info.Length() < 2) {
76
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, got %1", info.Length());
77
+ return env.Null();
78
+ }
79
+ if (!info[0].IsString()) {
80
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for name, expected string", GetValueType(instance, info[0]));
81
+ return env.Null();
82
+ }
83
+ if (!info[1].IsObject()) {
84
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for members, expected object", GetValueType(instance, info[1]));
85
+ return env.Null();
86
+ }
87
+
88
+ TypeInfo *type = instance->types.AppendDefault();
89
+ RG_DEFER_N(err_guard) { instance->types.RemoveLast(1); };
90
+
91
+ std::string name = info[0].As<Napi::String>();
92
+ Napi::Object obj = info[1].As<Napi::Object>();
93
+ Napi::Array keys = obj.GetPropertyNames();
94
+
95
+ type->name = DuplicateString(name.c_str(), &instance->str_alloc).ptr;
96
+
97
+ type->primitive = PrimitiveKind::Record;
98
+ type->align = 1;
99
+
100
+ for (uint32_t i = 0; i < keys.Length(); i++) {
101
+ RecordMember member = {};
102
+
103
+ std::string key = ((Napi::Value)keys[i]).As<Napi::String>();
104
+ Napi::Value value = obj[key];
105
+
106
+ member.name = DuplicateString(key.c_str(), &instance->str_alloc).ptr;
107
+ member.type = ResolveType(instance, value);
108
+ if (!member.type)
109
+ return env.Null();
110
+
111
+ type->size += member.type->size;
112
+ type->align = std::max(type->align, member.type->align);
113
+
114
+ type->members.Append(member);
115
+ }
116
+
117
+ type->size = (int16_t)AlignLen(type->size, type->align);
118
+
119
+ // If the insert succeeds, we cannot fail anymore
120
+ if (!instance->types_map.TrySet(type).second) {
121
+ ThrowError<Napi::Error>(env, "Duplicate type name '%1'", type->name);
122
+ return env.Null();
123
+ }
124
+ err_guard.Disable();
125
+
126
+ Napi::External<TypeInfo> external = Napi::External<TypeInfo>::New(env, type);
127
+ SetValueTag(instance, external, &TypeInfoMarker);
128
+
129
+ return external;
130
+ }
131
+
132
+ static Napi::Value CreatePointerType(const Napi::CallbackInfo &info)
133
+ {
134
+ Napi::Env env = info.Env();
135
+ InstanceData *instance = env.GetInstanceData<InstanceData>();
136
+
137
+ if (info.Length() < 1) {
138
+ ThrowError<Napi::TypeError>(env, "Expected 1 argument, got %1", info.Length());
139
+ return env.Null();
140
+ }
141
+
142
+ const TypeInfo *ref = ResolveType(instance, info[0]);
143
+ if (!ref)
144
+ return env.Null();
145
+
146
+ char name_buf[256];
147
+ Fmt(name_buf, "%1%2*", ref->name, ref->primitive == PrimitiveKind::Pointer ? "" : " ");
148
+
149
+ TypeInfo *type = instance->types_map.FindValue(name_buf, nullptr);
150
+
151
+ if (!type) {
152
+ type = instance->types.AppendDefault();
153
+
154
+ type->name = DuplicateString(name_buf, &instance->str_alloc).ptr;
155
+
156
+ type->primitive = PrimitiveKind::Pointer;
157
+ type->size = sizeof(void *);
158
+ type->align = sizeof(void *);
159
+ type->ref = ref;
160
+ }
161
+
162
+ Napi::External<TypeInfo> external = Napi::External<TypeInfo>::New(env, type);
163
+ SetValueTag(instance, external, &TypeInfoMarker);
164
+
165
+ return external;
166
+ }
167
+
168
+ static Napi::Value LoadSharedLibrary(const Napi::CallbackInfo &info)
169
+ {
170
+ Napi::Env env = info.Env();
171
+ InstanceData *instance = env.GetInstanceData<InstanceData>();
172
+
173
+ if (info.Length() < 2) {
174
+ ThrowError<Napi::TypeError>(env, "Expected 2 arguments, not %1", info.Length());
175
+ return env.Null();
176
+ }
177
+ if (!info[0].IsString() && !info[0].IsNull()) {
178
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for filename, expected string or null", GetValueType(instance, info[0]));
179
+ return env.Null();
180
+ }
181
+ if (!info[1].IsObject()) {
182
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for functions, expected object", GetValueType(instance, info[1]));
183
+ return env.Null();
184
+ }
185
+
186
+ std::shared_ptr<LibraryData> lib = std::make_shared<LibraryData>();
187
+
188
+ Napi::Object obj = Napi::Object::New(env);
189
+
190
+ // Load shared library
191
+ #ifdef _WIN32
192
+ if (info[0].IsString()) {
193
+ std::u16string filename = info[0].As<Napi::String>();
194
+ lib->module = LoadLibraryW((LPCWSTR)filename.c_str());
195
+
196
+ if (!lib->module) {
197
+ ThrowError<Napi::Error>(env, "Failed to load shared library: %1", GetWin32ErrorString());
198
+ return env.Null();
199
+ }
200
+ } else {
201
+ lib->module = GetModuleHandle(nullptr);
202
+ RG_ASSERT(lib->module);
203
+ }
204
+ #else
205
+ if (info[0].IsString()) {
206
+ std::string filename = info[0].As<Napi::String>();
207
+ lib->module = dlopen(filename.c_str(), RTLD_NOW);
208
+
209
+ if (!lib->module) {
210
+ const char *msg = dlerror();
211
+
212
+ if (StartsWith(msg, filename.c_str())) {
213
+ msg += filename.length();
214
+ }
215
+ while (strchr(": ", msg[0])) {
216
+ msg++;
217
+ }
218
+
219
+ ThrowError<Napi::Error>(env, "Failed to load shared library: %1", msg);
220
+ return env.Null();
221
+ }
222
+ } else {
223
+ lib->module = RTLD_DEFAULT;
224
+ }
225
+ #endif
226
+
227
+ Napi::Object functions = info[1].As<Napi::Array>();
228
+ Napi::Array keys = functions.GetPropertyNames();
229
+ Size extra_size = 0;
230
+
231
+ for (uint32_t i = 0; i < keys.Length(); i++) {
232
+ FunctionInfo *func = new FunctionInfo();
233
+ RG_DEFER_N(func_guard) { delete func; };
234
+
235
+ std::string key = ((Napi::Value)keys[i]).As<Napi::String>();
236
+ Napi::Array value = ((Napi::Value)functions[key]).As<Napi::Array>();
237
+
238
+ func->name = DuplicateString(key.c_str(), &lib->str_alloc).ptr;
239
+ func->decorated_name = func->name;
240
+ func->lib = lib;
241
+
242
+ if (!value.IsArray()) {
243
+ ThrowError<Napi::TypeError>(env, "Unexpexted %1 value for signature of '%2', expected an array", GetValueType(instance, value), func->name);
244
+ return env.Null();
245
+ }
246
+ if (value.Length() < 2 || value.Length() > 3) {
247
+ ThrowError<Napi::TypeError>(env, "Unexpected array of length %1 for '%2', expected 2 or 3 elements", value.Length(), func->name);
248
+ return env.Null();
249
+ }
250
+
251
+ Napi::Array parameters;
252
+
253
+ if (((Napi::Value)value[1u]).IsString()) {
254
+ std::string conv = ((Napi::Value)value[1u]).As<Napi::String>();
255
+
256
+ if (conv == "cdecl" || conv == "__cdecl") {
257
+ func->convention = CallConvention::Default;
258
+ } else if (conv == "stdcall" || conv == "__stdcall") {
259
+ func->convention = CallConvention::Stdcall;
260
+ } else {
261
+ ThrowError<Napi::Error>(env, "Unknown calling convention '%1'", conv.c_str());
262
+ return env.Null();
263
+ }
264
+
265
+ if (!((Napi::Value)value[2u]).IsArray()) {
266
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for parameters of '%2', expected an array", GetValueType(instance, (Napi::Value)value[1u]), func->name);
267
+ return env.Null();
268
+ }
269
+
270
+ parameters = ((Napi::Value)value[2u]).As<Napi::Array>();
271
+ } else {
272
+ if (!((Napi::Value)value[1u]).IsArray()) {
273
+ ThrowError<Napi::TypeError>(env, "Unexpected %1 value for parameters of '%2', expected an array", GetValueType(instance, (Napi::Value)value[1u]), func->name);
274
+ return env.Null();
275
+ }
276
+
277
+ parameters = ((Napi::Value)value[1u]).As<Napi::Array>();
278
+ }
279
+
280
+ func->ret.type = ResolveType(instance, value[0u]);
281
+ if (!func->ret.type)
282
+ return env.Null();
283
+ func->scratch_size = AlignLen(func->ret.type->size, 16);
284
+
285
+ for (uint32_t j = 0; j < parameters.Length(); j++) {
286
+ ParameterInfo param = {};
287
+
288
+ param.type = ResolveType(instance, parameters[j]);
289
+ if (!param.type)
290
+ return env.Null();
291
+ if (param.type->primitive == PrimitiveKind::Void) {
292
+ ThrowError<Napi::TypeError>(env, "Type void cannot be used as a parameter");
293
+ return env.Null();
294
+ }
295
+ func->parameters.Append(param);
296
+
297
+ func->scratch_size += AlignLen(param.type->size, 16);
298
+ }
299
+
300
+ // That's enough extra space for pretty much every ABI supported, with 16 bytes of
301
+ // bonus for each in case we need to put pointers and exta-align them.
302
+ extra_size = std::max(extra_size, func->scratch_size +
303
+ AlignLen(8 * (func->parameters.len + 1), 16));
304
+
305
+ if (!AnalyseFunction(func))
306
+ return env.Null();
307
+
308
+ #ifdef _WIN32
309
+ func->func = (void *)GetProcAddress((HMODULE)lib->module, func->decorated_name);
310
+ #else
311
+ func->func = dlsym(lib->module, func->decorated_name);
312
+ #endif
313
+ if (!func->func) {
314
+ ThrowError<Napi::Error>(env, "Cannot find function '%1' in shared library", key.c_str());
315
+ return env.Null();
316
+ }
317
+
318
+ Napi::Function wrapper = Napi::Function::New(env, TranslateCall, key.c_str(), (void *)func);
319
+ wrapper.AddFinalizer([](Napi::Env, FunctionInfo *func) { delete func; }, func);
320
+ func_guard.Disable();
321
+
322
+ obj.Set(key, wrapper);
323
+ }
324
+
325
+ lib->stack.AppendDefault(Mebibytes(1) + extra_size);
326
+
327
+ return obj;
328
+ }
329
+
330
+ LibraryData::~LibraryData()
331
+ {
332
+ #ifdef _WIN32
333
+ if (module && module != GetModuleHandle(nullptr)) {
334
+ FreeLibrary((HMODULE)module);
335
+ }
336
+ #else
337
+ if (module && module != RTLD_DEFAULT) {
338
+ dlclose(module);
339
+ }
340
+ #endif
341
+ }
342
+
343
+ static void RegisterPrimitiveType(InstanceData *instance, const char *name, PrimitiveKind primitive, int16_t size)
344
+ {
345
+ TypeInfo *type = instance->types.AppendDefault();
346
+
347
+ type->name = name;
348
+
349
+ type->primitive = primitive;
350
+ type->size = size;
351
+ type->align = size;
352
+
353
+ RG_ASSERT(!instance->types_map.Find(name));
354
+ instance->types_map.Set(type);
355
+ }
356
+
357
+ static Napi::Object InitBaseTypes(Napi::Env env)
358
+ {
359
+ InstanceData *instance = env.GetInstanceData<InstanceData>();
360
+
361
+ RG_ASSERT(!instance->types.len);
362
+
363
+ RegisterPrimitiveType(instance, "void", PrimitiveKind::Void, 0);
364
+ RegisterPrimitiveType(instance, "bool", PrimitiveKind::Bool, 1);
365
+ RegisterPrimitiveType(instance, "int8", PrimitiveKind::Int8, 1);
366
+ RegisterPrimitiveType(instance, "int8_t", PrimitiveKind::Int8, 1);
367
+ RegisterPrimitiveType(instance, "uint8", PrimitiveKind::UInt8, 1);
368
+ RegisterPrimitiveType(instance, "uint8_t", PrimitiveKind::UInt8, 1);
369
+ RegisterPrimitiveType(instance, "char", PrimitiveKind::Int8, 1);
370
+ RegisterPrimitiveType(instance, "uchar", PrimitiveKind::UInt8, 1);
371
+ RegisterPrimitiveType(instance, "unsigned char", PrimitiveKind::UInt8, 1);
372
+ RegisterPrimitiveType(instance, "int16", PrimitiveKind::Int16, 2);
373
+ RegisterPrimitiveType(instance, "int16_t", PrimitiveKind::Int16, 2);
374
+ RegisterPrimitiveType(instance, "uint16", PrimitiveKind::UInt16, 2);
375
+ RegisterPrimitiveType(instance, "uint16_t", PrimitiveKind::UInt16, 2);
376
+ RegisterPrimitiveType(instance, "short", PrimitiveKind::Int16, 2);
377
+ RegisterPrimitiveType(instance, "ushort", PrimitiveKind::UInt16, 2);
378
+ RegisterPrimitiveType(instance, "unsigned short", PrimitiveKind::UInt16, 2);
379
+ RegisterPrimitiveType(instance, "int32", PrimitiveKind::Int32, 4);
380
+ RegisterPrimitiveType(instance, "int32_t", PrimitiveKind::Int32, 4);
381
+ RegisterPrimitiveType(instance, "uint32", PrimitiveKind::UInt32, 4);
382
+ RegisterPrimitiveType(instance, "uint32_t", PrimitiveKind::UInt32, 4);
383
+ RegisterPrimitiveType(instance, "int", PrimitiveKind::Int32, 4);
384
+ RegisterPrimitiveType(instance, "uint", PrimitiveKind::UInt32, 4);
385
+ RegisterPrimitiveType(instance, "unsigned int", PrimitiveKind::UInt32, 4);
386
+ RegisterPrimitiveType(instance, "int64", PrimitiveKind::Int64, 8);
387
+ RegisterPrimitiveType(instance, "int64_t", PrimitiveKind::Int64, 8);
388
+ RegisterPrimitiveType(instance, "uint64", PrimitiveKind::UInt64, 8);
389
+ RegisterPrimitiveType(instance, "uint64_t", PrimitiveKind::UInt64, 8);
390
+ #if ULONG_MAX == UINT64_MAX
391
+ RegisterPrimitiveType(instance, "long", PrimitiveKind::Int64, 8);
392
+ RegisterPrimitiveType(instance, "ulong", PrimitiveKind::UInt64, 8);
393
+ RegisterPrimitiveType(instance, "unsigned long", PrimitiveKind::UInt64, 8);
394
+ #else
395
+ RegisterPrimitiveType(instance, "long", PrimitiveKind::Int32, 4);
396
+ RegisterPrimitiveType(instance, "ulong", PrimitiveKind::UInt32, 4);
397
+ RegisterPrimitiveType(instance, "unsigned long", PrimitiveKind::UInt64, 4);
398
+ #endif
399
+ RegisterPrimitiveType(instance, "longlong", PrimitiveKind::Int64, 8);
400
+ RegisterPrimitiveType(instance, "long long", PrimitiveKind::Int64, 8);
401
+ RegisterPrimitiveType(instance, "ulonglong", PrimitiveKind::UInt64, 8);
402
+ RegisterPrimitiveType(instance, "unsigned long long", PrimitiveKind::UInt64, 8);
403
+ RegisterPrimitiveType(instance, "float32", PrimitiveKind::Float32, 4);
404
+ RegisterPrimitiveType(instance, "float64", PrimitiveKind::Float64, 8);
405
+ RegisterPrimitiveType(instance, "float", PrimitiveKind::Float32, 4);
406
+ RegisterPrimitiveType(instance, "double", PrimitiveKind::Float64, 8);
407
+ RegisterPrimitiveType(instance, "string", PrimitiveKind::String, sizeof(void *));
408
+
409
+ Napi::Object types = Napi::Object::New(env);
410
+ for (TypeInfo &type: instance->types) {
411
+ Napi::External<TypeInfo> external = Napi::External<TypeInfo>::New(env, &type);
412
+ SetValueTag(instance, external, &TypeInfoMarker);
413
+
414
+ types.Set(type.name, external);
415
+
416
+ if (strchr(type.name, ' ')) {
417
+ char name_buf[64] = {};
418
+ for (Size i = 0; type.name[i]; i++) {
419
+ RG_ASSERT(i < RG_SIZE(name_buf) - 1);
420
+ name_buf[i] = type.name[i] != ' ' ? type.name[i] : '_';
421
+ }
422
+ types.Set(name_buf, external);
423
+ }
424
+ }
425
+ types.Freeze();
426
+
427
+ return types;
428
+ }
429
+
430
+ }
431
+
432
+ #if NODE_WANT_INTERNALS
433
+
434
+ static void SetValue(node::Environment *env, v8::Local<v8::Object> target,
435
+ const char *name, Napi::Value value)
436
+ {
437
+ v8::Isolate *isolate = env->isolate();
438
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
439
+
440
+ v8::NewStringType str_type = v8::NewStringType::kInternalized;
441
+ v8::Local<v8::String> str = v8::String::NewFromUtf8(isolate, name, str_type).ToLocalChecked();
442
+
443
+ target->Set(context, str, v8impl::V8LocalValueFromJsValue(value)).Check();
444
+ }
445
+
446
+ static void InitInternal(v8::Local<v8::Object> target, v8::Local<v8::Value>,
447
+ v8::Local<v8::Context> context, void *)
448
+ {
449
+ using namespace RG;
450
+
451
+ node::Environment *env = node::Environment::GetCurrent(context);
452
+
453
+ // Not very clean but I don't know enough about Node and V8 to do better...
454
+ // ... and it seems to work okay.
455
+ napi_env env_napi = new napi_env__(context);
456
+ Napi::Env env_cxx(env_napi);
457
+ env->AtExit([](void *udata) {
458
+ napi_env env_napi = (napi_env)udata;
459
+ delete env_napi;
460
+ }, env_napi);
461
+
462
+ InstanceData *instance = new InstanceData();
463
+ env_cxx.SetInstanceData(instance);
464
+
465
+ FillRandomSafe(&instance->tag_lower, RG_SIZE(instance->tag_lower));
466
+
467
+ SetValue(env, target, "struct", Napi::Function::New(env_napi, CreateStructType));
468
+ SetValue(env, target, "pointer", Napi::Function::New(env_napi, CreatePointerType));
469
+ SetValue(env, target, "load", Napi::Function::New(env_napi, LoadSharedLibrary));
470
+ SetValue(env, target, "internal", Napi::Boolean::New(env_napi, true));
471
+
472
+ Napi::Object types = InitBaseTypes(env_cxx);
473
+ SetValue(env, target, "types", types);
474
+ }
475
+
476
+ #else
477
+
478
+ static Napi::Object InitModule(Napi::Env env, Napi::Object exports)
479
+ {
480
+ using namespace RG;
481
+
482
+ InstanceData *instance = new InstanceData();
483
+ env.SetInstanceData(instance);
484
+
485
+ FillRandomSafe(&instance->tag_lower, RG_SIZE(instance->tag_lower));
486
+
487
+ exports.Set("struct", Napi::Function::New(env, CreateStructType));
488
+ exports.Set("pointer", Napi::Function::New(env, CreatePointerType));
489
+ exports.Set("load", Napi::Function::New(env, LoadSharedLibrary));
490
+ exports.Set("internal", Napi::Boolean::New(env, false));
491
+
492
+ Napi::Object types = InitBaseTypes(env);
493
+ exports.Set("types", types);
494
+
495
+ return exports;
496
+ }
497
+
498
+ #endif
499
+
500
+ #if NODE_WANT_INTERNALS
501
+ NODE_MODULE_CONTEXT_AWARE_INTERNAL(koffi, InitInternal);
502
+ #else
503
+ NODE_API_MODULE(koffi, InitModule);
504
+ #endif
package/src/ffi.hh ADDED
@@ -0,0 +1,135 @@
1
+ // This program is free software: you can redistribute it and/or modify
2
+ // it under the terms of the GNU Affero General Public License as published by
3
+ // the Free Software Foundation, either version 3 of the License, or
4
+ // (at your option) any later version.
5
+ //
6
+ // This program is distributed in the hope that it will be useful,
7
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ // GNU Affero General Public License for more details.
10
+ //
11
+ // You should have received a copy of the GNU Affero General Public License
12
+ // along with this program. If not, see https://www.gnu.org/licenses/.
13
+
14
+ #pragma once
15
+
16
+ #include "vendor/libcc/libcc.hh"
17
+
18
+ #include <napi.h>
19
+
20
+ namespace RG {
21
+
22
+ enum class PrimitiveKind {
23
+ Void,
24
+
25
+ Bool,
26
+ Int8,
27
+ UInt8,
28
+ Int16,
29
+ UInt16,
30
+ Int32,
31
+ UInt32,
32
+ Int64,
33
+ UInt64,
34
+ Float32,
35
+ Float64,
36
+ String,
37
+ Pointer,
38
+
39
+ Record
40
+ };
41
+
42
+ static inline bool IsIntegral(PrimitiveKind primitive)
43
+ {
44
+ bool integral = ((int)primitive <= (int)PrimitiveKind::Pointer);
45
+ return integral;
46
+ }
47
+
48
+ struct TypeInfo;
49
+ struct RecordMember;
50
+
51
+ struct TypeInfo {
52
+ const char *name;
53
+ napi_type_tag tag;
54
+
55
+ PrimitiveKind primitive;
56
+ int16_t size;
57
+ int16_t align;
58
+
59
+ HeapArray<RecordMember> members; // Record only
60
+ const TypeInfo *ref; // Pointer only
61
+
62
+ RG_HASHTABLE_HANDLER(TypeInfo, name);
63
+ };
64
+
65
+ struct RecordMember {
66
+ const char *name;
67
+ const TypeInfo *type;
68
+ };
69
+
70
+ class LibraryData {
71
+ public:
72
+ ~LibraryData();
73
+
74
+ void *module = nullptr; // HMODULE on Windows
75
+
76
+ BlockAllocator tmp_alloc;
77
+ HeapArray<uint8_t> stack;
78
+
79
+ BlockAllocator str_alloc;
80
+ };
81
+
82
+ enum class CallConvention {
83
+ Default,
84
+ Stdcall
85
+ };
86
+
87
+ struct ParameterInfo {
88
+ const TypeInfo *type;
89
+
90
+ // ABI-specific part
91
+
92
+ #if defined(_WIN64)
93
+ bool regular;
94
+ #elif defined(__x86_64__)
95
+ bool use_memory;
96
+ int8_t gpr_count;
97
+ int8_t xmm_count;
98
+ bool gpr_first;
99
+ #elif defined(__aarch64__)
100
+ int8_t gpr_count;
101
+ int8_t vec_count;
102
+ #elif defined(__i386__) || defined(_M_IX86)
103
+ bool trivial; // Only matters for return value
104
+ #endif
105
+ };
106
+
107
+ struct FunctionInfo {
108
+ const char *name;
109
+ const char *decorated_name;
110
+ std::shared_ptr<LibraryData> lib;
111
+
112
+ void *func;
113
+ CallConvention convention;
114
+
115
+ ParameterInfo ret;
116
+ HeapArray<ParameterInfo> parameters;
117
+ Size scratch_size; // Total size needed if all arguments were copied together (with align = 16)
118
+
119
+ // ABI-specific part
120
+
121
+ #if defined(__aarch64__) || defined(__x86_64__) || defined(_WIN64)
122
+ bool forward_fp;
123
+ #endif
124
+ };
125
+
126
+ struct InstanceData {
127
+ BucketArray<TypeInfo> types;
128
+ HashTable<const char *, TypeInfo *> types_map;
129
+
130
+ uint64_t tag_lower;
131
+
132
+ BlockAllocator str_alloc;
133
+ };
134
+
135
+ }