forked from duckdb/duckdb-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathduckdb.patch
291 lines (287 loc) · 10.8 KB
/
duckdb.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ea74d55f86..db27a653b3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -83,6 +83,13 @@ if (EXTENSION_STATIC_BUILD AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
endif()
option(DISABLE_UNITY "Disable unity builds." FALSE)
+option(USE_WASM_THREADS "Should threads be used" FALSE)
+if (${USE_WASM_THREADS})
+ set(WASM_THREAD_FLAGS
+ -pthread
+ -sSHARED_MEMORY=1
+ )
+endif()
option(FORCE_COLORED_OUTPUT
"Always produce ANSI-colored output (GNU/Clang only)." FALSE)
@@ -762,7 +769,6 @@ function(build_loadable_extension_directory NAME OUTPUT_DIRECTORY PARAMETERS)
${TARGET_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE
"${CMAKE_BINARY_DIR}/${OUTPUT_DIRECTORY}")
endif()
-
if(EMSCRIPTEN)
# Copy file.duckdb_extension.wasm to file.duckdb_extension.wasm.lib
add_custom_command(
@@ -774,7 +780,7 @@ function(build_loadable_extension_directory NAME OUTPUT_DIRECTORY PARAMETERS)
add_custom_command(
TARGET ${TARGET_NAME}
POST_BUILD
- COMMAND emcc $<TARGET_FILE:${TARGET_NAME}>.lib -o $<TARGET_FILE:${TARGET_NAME}> -sSIDE_MODULE=1 -O3
+ COMMAND emcc $<TARGET_FILE:${TARGET_NAME}>.lib -o $<TARGET_FILE:${TARGET_NAME}> -O3 -sSIDE_MODULE=2 -sEXPORTED_FUNCTIONS="_${NAME}_init,_${NAME}_version" ${WASM_THREAD_FLAGS}
)
endif()
endfunction()
diff --git a/src/main/extension/extension_install.cpp b/src/main/extension/extension_install.cpp
index 418a298db3..e7943a95e5 100644
--- a/src/main/extension/extension_install.cpp
+++ b/src/main/extension/extension_install.cpp
@@ -171,7 +171,7 @@ string ExtensionHelper::ExtensionUrlTemplate(optional_ptr<const DBConfig> db_con
string versioned_path = "/${REVISION}/${PLATFORM}/${NAME}.duckdb_extension";
#ifdef WASM_LOADABLE_EXTENSIONS
string default_endpoint = "https://extensions.duckdb.org";
- versioned_path = "/duckdb-wasm" + versioned_path + ".wasm";
+ versioned_path = versioned_path + ".wasm";
#else
string default_endpoint = "http://extensions.duckdb.org";
versioned_path = versioned_path + ".gz";
diff --git a/src/main/extension/extension_load.cpp b/src/main/extension/extension_load.cpp
index a001f2b997..c532db1b2d 100644
--- a/src/main/extension/extension_load.cpp
+++ b/src/main/extension/extension_load.cpp
@@ -110,6 +110,7 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
} else {
filename = fs.ExpandPath(filename);
}
+#ifndef WASM_LOADABLE_EXTENSIONS
if (!fs.FileExists(filename)) {
string message;
bool exact_match = ExtensionHelper::CreateSuggestions(extension, message);
@@ -119,6 +120,181 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
error = StringUtil::Format("Extension \"%s\" not found.\n%s", filename, message);
return false;
}
+#endif
+#ifdef WASM_LOADABLE_EXTENSIONS
+ auto basename = fs.ExtractBaseName(filename);
+ char *exe = NULL;
+ exe = (char *)EM_ASM_PTR(
+ {
+ // Next few lines should argubly in separate JavaScript-land function call
+ // TODO: move them out / have them configurable
+
+var url =(UTF8ToString($0));
+
+ if (typeof XMLHttpRequest === "undefined" ) {
+ const os = require('os');
+ const path = require('path');
+ const fs = require('fs');
+
+ var array = url.split("/");
+ var l = array.length;
+
+ var folder = path.join(os.homedir(), ".duckdb/extensions/" + array[l - 4] + "/" + array[l - 3] + "/" + array[l - 2] + "/");
+ var filePath = path.join(folder, array[l - 1]);
+
+ try {
+ if (!fs.existsSync(folder)) {
+ fs.mkdirSync(folder, {
+ recursive: true
+ });
+ }
+
+ if (!fs.existsSync(filePath)) {
+ const int32 = new Int32Array(new SharedArrayBuffer(8));
+var Worker = require('node:worker_threads').Worker;
+ var worker = new Worker("const {Worker,isMainThread,parentPort,workerData,} = require('node:worker_threads');var times = 0;var SAB = 23;var Z = 0;async function ZZZ(e) {var x = await fetch(e);var res = await x.arrayBuffer();Atomics.store(SAB, 1, res.byteLength);Atomics.store(SAB, 0, 1);Atomics.notify(SAB, 1);Atomics.notify(SAB, 0);Z = res;};parentPort.on('message', function(event) {if (times == 0) {times++;SAB = event;} else if (times == 1) {times++;ZZZ(event);} else {const a = new Uint8Array(Z);const b = new Uint8Array(event.buffer);var K = Z.byteLength;for (var i = 0; i < K; i++) {b[i] = a[i];}Atomics.notify(event, 0);Atomics.store(SAB, 0, 2);Atomics.notify(SAB, 0);}});", {
+ eval: true
+ });
+ var uInt8Array;
+
+ int32[0] = 0;
+ int32[2] = 4;
+ worker.postMessage(int32);
+
+ worker.postMessage(url);
+ Atomics.wait(int32, 0, 0);
+
+ const int32_2 = new Int32Array(new SharedArrayBuffer(int32[1] + 3 - ((int32[1] + 3) % 4)));
+ worker.postMessage(int32_2);
+
+ Atomics.wait(int32, 0, 1);
+
+ var x = new Uint8Array(int32_2.buffer, 0, int32[1]);
+ uInt8Array = x;
+ worker.terminate();
+ fs.writeFileSync(filePath, uInt8Array);
+
+ } else {
+ uInt8Array = fs.readFileSync(filePath);
+ }
+ } catch (e) {
+ console.log("Error fetching module", e);
+ return 0;
+ }
+ } else {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.responseType = "arraybuffer";
+ xhr.send(null);
+ if (xhr.status != 200)
+ return 0;
+ uInt8Array = xhr.response;
+ }
+
+ var valid = WebAssembly.validate(uInt8Array);
+ var len = uInt8Array.byteLength;
+ var fileOnWasmHeap = _malloc(len + 4);
+
+ var properArray = new Uint8Array(uInt8Array);
+
+ for (var iii = 0; iii < len; iii++) {
+ Module.HEAPU8[iii + fileOnWasmHeap + 4] = properArray[iii];
+ }
+ var LEN123 = new Uint8Array(4);
+ LEN123[0] = len % 256;
+ len -= LEN123[0];
+ len /= 256;
+ LEN123[1] = len % 256;
+ len -= LEN123[1];
+ len /= 256;
+ LEN123[2] = len % 256;
+ len -= LEN123[2];
+ len /= 256;
+ LEN123[3] = len % 256;
+ len -= LEN123[3];
+ len /= 256;
+ Module.HEAPU8.set(LEN123, fileOnWasmHeap);
+ //FIXME: found how to expose those to the logger interface
+ //console.log(LEN123);
+ //console.log(properArray);
+ //console.log(new Uint8Array(Module.HEAPU8, fileOnWasmHeap, len+4));
+ // console.log('Loading extension ', UTF8ToString($1));
+
+ // Here we add the uInt8Array to Emscripten's filesystem, for it to be found by dlopen
+ FS.writeFile(UTF8ToString($1), new Uint8Array(uInt8Array));
+ return fileOnWasmHeap;
+ },
+ filename.c_str(), basename.c_str());
+ if (!exe) {
+ throw IOException("Extension %s is not available", filename);
+ }
+
+ auto dopen_from = basename;
+ if (!config.options.allow_unsigned_extensions) {
+ // signature is the last 256 bytes of the file
+
+ string signature;
+ signature.resize(256);
+
+ D_ASSERT(exe);
+ uint64_t LEN = 0;
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[3];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[2];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[1];
+ LEN *= 256;
+ LEN += ((uint8_t *)exe)[0];
+ auto signature_offset = LEN - signature.size();
+
+ const idx_t maxLenChunks = 1024ULL * 1024ULL;
+ const idx_t numChunks = (signature_offset + maxLenChunks - 1) / maxLenChunks;
+ std::vector<std::string> hash_chunks(numChunks);
+ std::vector<idx_t> splits(numChunks + 1);
+
+ for (idx_t i = 0; i < numChunks; i++) {
+ splits[i] = maxLenChunks * i;
+ }
+ splits.back() = signature_offset;
+
+ for (idx_t i = 0; i < numChunks; i++) {
+ string x;
+ x.resize(splits[i + 1] - splits[i]);
+ for (idx_t j = 0; j < x.size(); j++) {
+ x[j] = ((uint8_t *)exe)[j + 4 + splits[i]];
+ }
+ ComputeSHA256String(x, &hash_chunks[i]);
+ }
+
+ string hash_concatenation;
+ hash_concatenation.reserve(32 * numChunks); // 256 bits -> 32 bytes per chunk
+
+ for (auto &hash_chunk : hash_chunks) {
+ hash_concatenation += hash_chunk;
+ }
+
+ string two_level_hash;
+ ComputeSHA256String(hash_concatenation, &two_level_hash);
+
+ for (idx_t j = 0; j < signature.size(); j++) {
+ signature[j] = ((uint8_t *)exe)[4 + signature_offset + j];
+ }
+ bool any_valid = false;
+ for (auto &key : ExtensionHelper::GetPublicKeys()) {
+ if (duckdb_mbedtls::MbedTlsWrapper::IsValidSha256Signature(key, signature, two_level_hash)) {
+ any_valid = true;
+ break;
+ }
+ }
+ if (!any_valid) {
+ throw IOException(config.error_manager->FormatException(ErrorType::UNSIGNED_EXTENSION, filename));
+ }
+ }
+ if (exe) {
+ free(exe);
+ }
+#else
if (!config.options.allow_unsigned_extensions) {
auto handle = fs.OpenFile(filename, FileFlags::FILE_FLAGS_READ);
@@ -179,26 +355,9 @@ bool ExtensionHelper::TryInitialLoad(DBConfig &config, FileSystem &fs, const str
throw IOException(config.error_manager->FormatException(ErrorType::UNSIGNED_EXTENSION, filename));
}
}
+#endif
auto filebase = fs.ExtractBaseName(filename);
-
#ifdef WASM_LOADABLE_EXTENSIONS
- EM_ASM(
- {
- // Next few lines should argubly in separate JavaScript-land function call
- // TODO: move them out / have them configurable
- const xhr = new XMLHttpRequest();
- xhr.open("GET", UTF8ToString($0), false);
- xhr.responseType = "arraybuffer";
- xhr.send(null);
- var uInt8Array = xhr.response;
- WebAssembly.validate(uInt8Array);
- console.log('Loading extension ', UTF8ToString($1));
-
- // Here we add the uInt8Array to Emscripten's filesystem, for it to be found by dlopen
- FS.writeFile(UTF8ToString($1), new Uint8Array(uInt8Array));
- },
- filename.c_str(), filebase.c_str());
- auto dopen_from = filebase;
#else
auto dopen_from = filename;
#endif
diff --git a/src/parallel/task_scheduler.cpp b/src/parallel/task_scheduler.cpp
index aad0a13360..613c856230 100644
--- a/src/parallel/task_scheduler.cpp
+++ b/src/parallel/task_scheduler.cpp
@@ -242,13 +242,13 @@ void TaskScheduler::SetThreads(idx_t total_threads, idx_t external_threads) {
if (total_threads < external_threads) {
throw SyntaxException("Number of threads can't be smaller than number of external threads!");
}
- thread_count = total_threads - external_threads;
#else
- if (threads.size() != external_threads) {
+ if (total_threads != external_threads) {
throw NotImplementedException(
- "DuckDB was compiled without threads! Setting threads != external_threads is not allowed.");
+ "DuckDB was compiled without threads! Setting total_threads != external_threads is not allowed.");
}
#endif
+ thread_count = total_threads - external_threads;
}
void TaskScheduler::SetAllocatorFlushTreshold(idx_t threshold) {