Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/wasm/common/whwasmutil.c-pp.js # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / wasm / common / whwasmutil.c-pp.js` 2734 lines ยท 108343 bytes Raw Blame History 1 /** 2 2022-07-08 3 4 The author disclaims copyright to this source code. In place of a 5 legal notice, here is a blessing: 6 7 * May you do good and not evil. 8 * May you find forgiveness for yourself and forgive others. 9 * May you share freely, never taking more than you give. 10 11 *********************************************************************** 12 13 This code is developed in conjunction with the Jaccwabyt project: 14 15 https://fossil.wanderinghorse.net/r/jaccwabyt 16 17 More specifically: 18 19 https://fossil.wanderinghorse.net/r/jaccwabyt/dir/wasmutil 20 21 and SQLite: 22 23 https://sqlite.org/src/dir/ext/wasm/common 24 25 This file is kept in sync between both of those trees. 26 27 This build was generated using: 28 29 //#@ push policy error delimiter "@" "@" 30 @c-pp::argv@ 31 32 by libcmpp @cmpp::version@ 33 */ 34 //#savepoint begin 35 //#define ? esm 0 36 //#define ? no-export 0 37 //#define ? lexical-scoped 0 38 //#if defined canonical-sqlite3 39 //# // The sqlite3 wasm build. 40 //# define no-export 1 41 //# define lexical-scoped 1 42 //# if defined target:es6-module 43 //# define esm 1 44 //# /if 45 //# define omit-yawl 46 //#/if 47 //#if esm 48 //# define lexical-scoped 1 49 //#/if 50 /** 51 The primary goal of this function is to provide JS/WASM utility 52 code similar to some of that provided by Emscripten-generated 53 builds, the difference being that this one can be used in arbitrary 54 WASM environments built with toolchains other than Emscripten. To 55 that end, it populates the given object with various WASM-specific 56 APIs. These APIs work with both 32- and 64-bit WASM builds. 57 58 This function is intended to be called after a WASM module has been 59 loaded, passed some of that module's state as described in the 60 following docs. Its arugment is both a configuration object and 61 a target which gets filled out with many new members. 62 63 Forewarning: this API explicitly targets only browser environments. 64 If a given non-browser environment has the capabilities needed for 65 a given feature (e.g. TextEncoder), great, but it does not go out 66 of its way to account for them and does not provide compatibility 67 crutches for them. That said: no specific incompatibilities with, 68 e.g., node.js are known (whereas it is known that some folks use 69 this with node.js via the sqlite3.org JS/WASM bindings). 70 71 Intended usage: 72 73 ``` 74 const target = { ...see config options below... }; 75 //#if esm 76 import {default as whw} from "./whwasmutil.mjs"; 77 whw(target); 78 //#else 79 globalThis.WhWasmUtilInstaller(target); 80 delete globalThis.WhWasmUtilInstaller; 81 //#/if 82 ``` 83 84 The `target` object then holds the APIs. The caller may set certain 85 properties on it, before calling this, to configure it, as 86 documented below. 87 88 //#if not esm 89 The global-scope symbol for this function is intended only to 90 provide an easy way to make it available to 3rd-party scripts and 91 "should" be deleted after calling it. That symbol is _not_ used 92 within the library. 93 //#/if 94 95 It currently offers alternatives to the following 96 Emscripten-generated APIs: 97 98 - OPTIONALLY memory allocation, but how this gets imported is 99 environment-specific. Most of the following features only work 100 if allocation is available. 101 102 - WASM-exported "indirect function table" access and 103 manipulation. e.g. creating new WASM-side functions using JS 104 functions, analog to Emscripten's addFunction() and 105 uninstallFunction() but slightly different and with more useful 106 lifetime semantics. 107 108 - Get/set specific heap memory values, analog to Emscripten's 109 getValue() and setValue(). 110 111 - String length counting in UTF-8 bytes (C-style and JS strings). 112 113 - JS string to C-string conversion and vice versa, analog to 114 Emscripten's stringToUTF8Array() and friends, but with slighter 115 different interfaces. 116 117 - JS string to Uint8Array conversion, noting that browsers actually 118 already have this built in via TextEncoder. 119 120 - "Scoped" allocation, such that allocations made inside of a given 121 explicit scope will be automatically cleaned up when the scope is 122 closed. This is fundamentally similar to Emscripten's 123 stackAlloc() and friends but uses the heap instead of the stack 124 because access to the stack requires C code. 125 126 - Create JS wrappers for WASM functions, analog to Emscripten's 127 ccall() and cwrap() functions, except that the automatic 128 conversions for function arguments and return values can be 129 easily customized by the client by assigning custom function 130 signature type names to conversion functions. Essentially, 131 it's ccall() and cwrap() on steroids. 132 133 How to install... 134 135 Passing an object to this function both pulls the configuration 136 from that object and installs this library's functionality into 137 that object. It returns its argument. It throws for various error 138 conditions, such as missing required config info (see below). 139 140 //#if not esm 141 After installation, client code "should" delete this function's 142 global symbol (if any). 143 //#/if 144 145 This code requires that the target object have the following 146 properties, though they needn't be available until the first time 147 one of the installed APIs is used (as opposed to when this function 148 is called) except where explicitly noted: 149 150 - `exports` must be a property of the target object OR a property 151 of `target.instance` (a WebAssembly.Module instance) and it must 152 contain the symbols exported by the WASM module associated with 153 this code. In an Enscripten environment it must be set to 154 `Module['asm']` (versions <=3.1.43) or `wasmExports` (versions 155 >=3.1.44). For WASI-SDK (or similar) builds, assigning 156 (target.instance=X.instance) suffices, where X is the result of 157 WebAssembly.instantiate(). The exports object must contain a 158 minimum of the following symbols: 159 160 - `memory`: a WebAssembly.Memory object representing the WASM 161 memory. _Alternately_, the `memory` property can be set as 162 `target.memory`, in particular if the WASM heap memory is 163 initialized in JS an _imported_ into WASM, as opposed to being 164 initialized in WASM and exported to JS. 165 166 - `__indirect_function_table`: the WebAssembly.Table object which 167 holds WASM-exported functions. This API does not strictly 168 require that the table be able to grow but it will throw if its 169 `installFunction()` is called and the table cannot grow. 170 171 - `functionTable`: WebAssembly.Table object holding the indirect 172 function call table or a function which must return one. If not 173 set then `exports.__indirect_function_table` is assumed (and must 174 be set). If it is set and is not a function, it is replaced by a 175 function with the same name, and which returns that object, 176 because this API used that name before this config option was 177 added. If it is set to a function then it MUST return a 178 WebAssembly.Table object and MUST return the same instance on 179 each call (but it may defer any fetching/initialization until its 180 first call and may throw on error). 181 182 In order to simplify downstream usage, if `target.exports` is not 183 set when this is called then a property access interceptor 184 (read-only, configurable, enumerable) gets installed as `exports` 185 which resolves to `target.instance.exports`, noting that the latter 186 property need not exist until the first time `target.exports` is 187 accessed. 188 189 Some APIs _optionally_ make use of the `bigIntEnabled` property of 190 the target object. It "should" be set to true if the WASM 191 environment is compiled with BigInt support, else it must be 192 false. If it is false, certain BigInt-related features will trigger 193 an exception if invoked. This property, if not set when this is 194 called, will get a default value of true only if the BigInt64Array 195 constructor is available, else it will default to false. Having 196 the BigInt type is not sufficient for full int64 integration with 197 WASM: the target WASM file must also have been built with that 198 support. In Emscripten that's done using the `-sWASM_BIGINT` flag. 199 On WASI-SDK use --target-wasm64-wasi. 200 201 Some optional APIs require that the target have the following 202 methods: 203 204 - 'alloc()` must behave like C's `malloc()`, allocating N bytes of 205 memory and returning its pointer. In Emscripten this is 206 conventionally made available via `Module['_malloc']`. This API 207 requires that the alloc routine throw on allocation error, as 208 opposed to returning null or 0. 209 210 - 'dealloc()` must behave like C's `free()`, accepting either a 211 pointer returned from its allocation counterpart or the values 212 null/0 (for which it must be a no-op). In Emscripten this is 213 conventionally made available via `Module['_free']`. 214 215 These are commonly injected by exporting the C library's malloc() 216 and free(). With WASI-SDK that's (--export=malloc --export=free) and 217 in Emscripten it's -SEXPORTED_FUNCTIONS=_malloc,_free. However, 218 any compliant allocators will do. 219 220 APIs which require allocation routines are explicitly documented as 221 such and/or have "alloc" in their names. 222 223 Optional configuration values which may be set on target before 224 calling this: 225 226 - `pointerIR`: an IR-format string for the WASM environment's 227 pointer size. If set it must be either 'i32' or 'i64'. If not 228 set, it gets set to whatever this code thinks the pointer size 229 is. Modifying it after this call has no effect. A reliable 230 way to get this value is (typeof X()), where X is a function 231 from target.exports which returns an innocuous const pointer. 232 The typeof will be 'number' on 32-bit builds and 'bigint' 233 on 64-bit. 234 235 - `pointerSize`: if set, it must be one of 4 or 8 and must 236 correspond to the value of `pointerIR`. If not set, it gets set 237 to whatever this code thinks the pointer size is (4 unless 238 `pointerIR` is 'i64'). If `pointerSize` is set but `pointerIR` 239 is not, `pointerIR` gets set appropriately, and vice versa. 240 241 - `logger`: optional object with `debug`, `warn`, and/or `error` 242 properties which behave like their same-named counterparts in 243 the global console object. The default uses the console API 244 with a file-local prefix on each message. 245 246 When building with Emscripten's --target=wasm64, `pointerIR` must 247 be set to 'i64' and/or `pointerSize` must be set to 8. 248 249 After calling this, the pointerIR and pointerSize properties are 250 replaced with a read-only Object member named target.ptr. It 251 contains the following read-only helper methods and properties to 252 assist in using WASM pointers without having to know what type they 253 are: 254 255 - `size` = pointerSize 256 257 - `ir` = pointerIR 258 259 - `null` = a "null" pointer of type Number or BigInt. Equivalent to 260 one of Number(0) or BigInt(0). This value compares === to 261 WASM NULL pointers. 262 263 - `coerce(arg)` = equivalent to one of Number(arg) or BigInt(arg||0). 264 265 - `add(...args)` = performs "pointer arithmetic" (`wasmPtr+offset` 266 does not work in 64-bit builds unless all operands are of type 267 BigInt). Adds up all of its arguments, accounting for whether 268 each is a Number of BigInt, and returns either a value of the 269 same type as `this.null`. 270 271 - `addn(...args)` = like `add()` but always returns its result as a 272 Number. Equivalent to Number(add(...)). 273 274 ------------------------------------------------------------ 275 Design notes: 276 277 - This function should probably take a config object and return the 278 newly-created (or config-provided) target. The current approach 279 seemed better at the time. 280 */ 281 const WhWasmUtilInstaller = function WhWasmUtilInstaller(target){ 282 //#if not esm 283 'use strict'; 284 //#/if 285 if(undefined===target.bigIntEnabled){ 286 target.bigIntEnabled = !!globalThis['BigInt64Array']; 287 } 288 const LOGPREFIX = "@__FILE__@:"; 289 290 /** Throws a new Error, the message of which is the concatenation of 291 a file-local prefix and all args with a space between each. */ 292 const toss = (...args)=>{ 293 throw new Error(LOGPREFIX+" "+args.join(' ')) 294 }; 295 296 const warn = target.logger?.warn 297 || ((...args)=>console.warn(LOGPREFIX,...args)); 298 const debug = target.logger?.debug 299 || ((...args)=>console.debug(LOGPREFIX,...args)); 300 301 if( !target.pointerSize && !target.pointerIR 302 && target.alloc && target.dealloc ){ 303 /* Try to determine the pointer size by allocating. */ 304 const ptr = target.alloc(1); 305 target.pointerSize = ('bigint'===typeof ptr ? 8 : 4); 306 target.dealloc(ptr); 307 } 308 309 /** 310 As of 2025-09-21, this library works with 64-bit WASM modules 311 built with Emscripten's -sMEMORY64=1. 312 */ 313 if( target.pointerSize && !target.pointerIR ){ 314 target.pointerIR = (4===target.pointerSize ? 'i32' : 'i64'); 315 } 316 const __ptrIR = (target.pointerIR ??= 'i32'); 317 const __ptrSize = (target.pointerSize ??= 318 ('i32'===__ptrIR ? 4 : ('i64'===__ptrIR ? 8 : 0))); 319 delete target.pointerSize; 320 delete target.pointerIR; 321 322 if( 'i32'!==__ptrIR && 'i64'!==__ptrIR ){ 323 toss("Invalid pointerIR:",__ptrIR); 324 }else if( 8!==__ptrSize && 4!==__ptrSize ){ 325 toss("Invalid pointerSize:",__ptrSize); 326 } 327 328 /** Either BigInt or, if !target.bigIntEnabled, a function which 329 throws complaining that BigInt is not enabled. */ 330 const __BigInt = target.bigIntEnabled 331 ? (v)=>BigInt(v || 0) 332 : toss("BigInt support is disabled in this build."); 333 334 const __Number = (v)=>Number(v||0)/*treat undefined the same as null*/; 335 336 /** 337 If target.ptr.ir==='i32' then this is equivalent to 338 Number(v||0) else it's equivalent to BigInt(v||0), throwing 339 if BigInt support is disabled. 340 341 Why? Because Number(null)===0, but BigInt(null) throws. We 342 perform the same for Number to allow the undefined value to be 343 treated as a NULL WASM pointer, primarily to reduce friction in 344 many SQLite3 bindings which have long relied on that. 345 */ 346 const __asPtrType = (4===__ptrSize) ? __Number : __BigInt; 347 348 /** 349 The number 0 as either type Number or BigInt, depending on 350 target.ptr.ir. 351 */ 352 const __NullPtr = __asPtrType(0); 353 354 /** 355 Expects any number of numeric arguments, each one of either type 356 Number or BigInt. It sums them up (from an implicit starting 357 point of 0 or 0n) and returns them as a number of the same type 358 which target.ptr.coerce() uses. 359 360 This is a workaround for not being able to mix Number/BigInt in 361 addition/subtraction expressions (which we frequently need for 362 calculating pointer offsets). 363 */ 364 const __ptrAdd = (4 === __ptrSize) 365 ? function(a, b){ 366 if(2 === arguments.length) return (Number(a || 0) + Number(b || 0)) | 0; 367 let rc = 0; 368 for(let i = 0; i < arguments.length; ++i) rc += Number(arguments[i] || 0); 369 return rc | 0; 370 } 371 : function(a, b){ 372 if(2 === arguments.length) return BigInt(a || 0) + BigInt(b || 0); 373 let rc = 0n; 374 for(let i = 0; i < arguments.length; ++i) rc += BigInt(arguments[i] || 0); 375 return rc; 376 }; 377 378 const nu = (...args)=>Object.assign(Object.create(null),...args); 379 380 /** Set up target.ptr... */ 381 { 382 const __ptr = Object.create(null); 383 Object.defineProperty(target, 'ptr', { 384 enumerable: true, 385 get: ()=>__ptr, 386 set: ()=>toss("The ptr property is read-only.") 387 }); 388 (function f(name, val){ 389 Object.defineProperty(__ptr, name, { 390 enumerable: true, 391 get: ()=>val, 392 set: ()=>toss("ptr["+name+"] is read-only.") 393 }); 394 return f; 395 }) 396 ('null', __NullPtr) 397 ('size', __ptrSize) 398 ('ir', __ptrIR) 399 ('coerce', __asPtrType) 400 ('add', __ptrAdd) 401 ('addn', (4===__ptrIR) ? __ptrAdd : (...args)=>Number(__ptrAdd(...args))); 402 } 403 404 if(!target.exports){ 405 Object.defineProperty(target, 'exports', { 406 enumerable: true, configurable: true, 407 get: ()=>(target.instance?.exports) 408 }); 409 } 410 411 /** Stores various cached state. */ 412 const cache = Object.create(null); 413 /** WebAssembly.Memory object extracted from target.memory or 414 target.exports.memory the first time __HEAPx() is called is used 415 (see __HEAP8, __HEAP32, etc.). */ 416 cache.memory = null; 417 /** uninstallFunction() puts table indexes in here for reuse and 418 installFunction() extracts them. */ 419 cache.freeFuncIndexes = []; 420 /** 421 List-of-lists used by scopedAlloc() and friends. 422 */ 423 cache.scopedAlloc = []; 424 425 /** Push the non-function pointer ptr to the current 426 cache.scopedAlloc list (which must already exist) and return 427 ptr. */ 428 cache.scopedAlloc.pushPtr = (ptr) => { 429 const top = cache.scopedAlloc[cache.scopedAlloc.length - 1]; 430 if( top ) top.ptr.push(ptr); 431 return ptr; 432 }; 433 434 /** Push the given indirect function table pointer to the current 435 cache.scopedAlloc object (which must already exist) and return 436 it. */ 437 cache.scopedAlloc.pushFuncPtr = (indirectFuncPtr) => { 438 const top = cache.scopedAlloc[cache.scopedAlloc.length - 1]; 439 if( top ) top.func.push(indirectFuncPtr); 440 return indirectFuncPtr; 441 }; 442 cache.utf8Decoder = new TextDecoder(); 443 cache.utf8Encoder = new TextEncoder(); 444 445 /** 446 For the given IR-like string in the set ('i8', 'i16', 'i32', 447 'f32', 'float', 'i64', 'f64', 'double', '*'), or any string value 448 ending in '*', returns the sizeof for that value 449 (target.ptr.size in the latter case). For any other value, it 450 returns the undefined value. 451 */ 452 target.sizeofIR = (n)=>{ 453 switch(n){ 454 case 'i8': return 1; 455 case 'i16': return 2; 456 case 'i32': case 'f32': case 'float': return 4; 457 case 'i64': case 'f64': case 'double': return 8; 458 case '*': return __ptrSize; 459 default: 460 return (''+n).endsWith('*') ? __ptrSize : undefined; 461 } 462 }; 463 464 /** 465 The first time this is invoked, it sets up cache.memory, throwing 466 if neither target.memory nor target.exports.memory are a 467 WebAssembly.Memory object. It replaces itself with a function 468 which simply returns cache.memory then returns cache.memory. 469 470 i.e. throws on the first call (only) if no Memory is available, 471 else returns that Memory object. 472 */ 473 let __Memory = ()=>{ 474 if( !cache.memory ){ 475 cache.memory = (target.memory instanceof WebAssembly.Memory) 476 ? target.memory : target.exports.memory; 477 if( !(cache.memory instanceof WebAssembly.Memory) ){ 478 toss("Missing target.memory or target.exports.memory", 479 "WebAssembly.Memory object."); 480 } 481 } 482 //warn("cache.memory =",cache.memory); 483 __Memory = ()=>cache.memory; 484 return cache.memory; 485 } 486 487 /* True if TypedArray view needs to be created or reinitialized. */ 488 const memoryViewNeedsUpdate = (view)=> 489 view?.byteLength !== __Memory().buffer.byteLength; 490 491 /* 492 __HEAPx each return a TypeArray view of cache.memory. These 493 lazily initialize both cache.memory and cache._viewX, and update 494 the view if cache.memory grows. Don't use these in a loop: get a 495 handle before the loop. 496 497 __HEAPx.shift is the number of bits which pointers must be 498 right-shifted when using them as an index for this heap. 499 */ 500 const __HEAP8 = ()=>(memoryViewNeedsUpdate(cache._view8) 501 ? (cache._view8=new Int8Array(cache.memory.buffer)) 502 : cache._view8); 503 const __HEAP8U = ()=>(memoryViewNeedsUpdate(cache._view8u) 504 ? (cache._view8u=new Uint8Array(cache.memory.buffer)) 505 : cache._view8u); 506 __HEAP8.shift = __HEAP8U.shift = 0; 507 508 const __HEAP16 = ()=>(memoryViewNeedsUpdate(cache._view16) 509 ? (cache._view16=new Int16Array(cache.memory.buffer)) 510 : cache._view16); 511 const __HEAP16U = ()=>(memoryViewNeedsUpdate(cache._view16u) 512 ? (cache._view16u=new Uint16Array(cache.memory.buffer)) 513 : cache._view16u); 514 __HEAP16.shift = __HEAP16U.shift = 1; 515 516 const __HEAP32 = ()=>(memoryViewNeedsUpdate(cache._view32) 517 ? (cache._view32=new Int32Array(cache.memory.buffer)) 518 : cache._view32); 519 const __HEAP32U = ()=>(memoryViewNeedsUpdate(cache._view32u) 520 ? (cache._view32u=new Uint32Array(cache.memory.buffer)) 521 : cache._view32u); 522 __HEAP32.shift = __HEAP32U.shift = 2; 523 524 const __HEAP64 = (target.bigIntEnabled && ('undefined'!==typeof BigInt64Array)) 525 ? ()=>(memoryViewNeedsUpdate(cache._view64) 526 ? (cache._view64=new BigInt64Array(cache.memory.buffer)) 527 : cache._view64) 528 : ()=>toss("BigInt64Array is not available.") 529 const __HEAP64U = (target.bigIntEnabled && ('undefined'!==typeof BigUint64Array)) 530 ? ()=>(memoryViewNeedsUpdate(cache._view64u) 531 ? (cache._view64u=new BigUint64Array(cache.memory.buffer)) 532 : cache._view64u) 533 : ()=>toss("BigUint64Array is not available."); 534 __HEAP64.shift = __HEAP64U.shift = 3; 535 536 const __HEAP32F = ()=>(memoryViewNeedsUpdate(cache._view32f) 537 ? (cache._view32f=new Float32Array(cache.memory.buffer)) 538 : cache._view32f); 539 __HEAP32F.shift = 2; 540 const __HEAP64F = ('undefined'!==typeof Float64Array) 541 ? ()=>(memoryViewNeedsUpdate(cache._view64f) 542 ? (cache._view64f=new Float64Array(cache.memory.buffer)) 543 : cache._view64f) 544 : ()=>toss("Float64Array is not available."); 545 __HEAP64F.shift = 3; 546 547 /* Map of IR (and internal pseudo-IR) values to __HEAPx funcs. */ 548 const __typeToHeap = function(type){ 549 return this[type] || toss("Unknown type ID:",type); 550 }.bind(Object.freeze(Object.seal( 551 nu({ 552 i1: __HEAP8, i8: __HEAP8, 553 //i1u: __HEAP8, u8: __HEAP8U, 554 i16: __HEAP16, //u16: __HEAP16U, 555 i32: __HEAP32, //u32: __HEAP32U, 556 i64: __HEAP64, //u64: __HEAP64U, 557 f32: __HEAP32F, 558 f64: __HEAP64F, 559 double: __HEAP64F 560 }) 561 ))); 562 563 /** Convenience (and faster) equivalent of this.heapForSize(8,false). */ 564 target.heap8 = __HEAP8; 565 /** Convenience (and faster) equivalent of this.heapForSize(8,true). */ 566 target.heap8u = __HEAP8U; 567 /** Convenience (and faster) equivalent of this.heapForSize(16,false). */ 568 target.heap16 = __HEAP16; 569 /** Convenience (and faster) equivalent of this.heapForSize(16,true). */ 570 target.heap16u = __HEAP16U; 571 /** Convenience (and faster) equivalent of this.heapForSize(32,false). */ 572 target.heap32 = __HEAP32; 573 /** Convenience (and faster) equivalent of this.heapForSize(32,true). */ 574 target.heap32u = __HEAP32U; 575 /** Convenience (and faster) equivalent of this.heapForSize(64,false). 576 Throws if BigInt support is not enabled. */ 577 target.heap64 = __HEAP64; 578 /** Convenience (and faster) equivalent of this.heapForSize(64,true). 579 Throws if BigInt support is not enabled. */ 580 target.heap64u = __HEAP64U; 581 /** Convenience (and faster) equivalent of 582 * this.heapForSize(Float32Array). */ 583 target.heap32f = __HEAP32F; 584 /** Convenience (and faster) equivalent of 585 * this.heapForSize(Float64Array). */ 586 target.heap64f = __HEAP64F; 587 588 /** 589 Requires n to be one of: 590 591 - integer 8, 16, or 32. 592 - A integer-type TypedArray constructor: Int8Array, Int16Array, 593 Int32Array, or their Uint counterparts. 594 595 If this.bigIntEnabled is true, it also accepts the value 64 or a 596 BigInt64Array/BigUint64Array, else it throws if passed 64 or one 597 of those constructors. 598 599 Returns an integer-based TypedArray view of the WASM heap memory 600 buffer associated with the given block size. If passed an integer 601 as the first argument and unsigned is truthy then the "U" 602 (unsigned) variant of that view is returned, else the signed 603 variant is returned. If passed a TypedArray value, the 2nd 604 argument is ignored. Float32Array and Float64Array views are not 605 supported by this function. 606 607 Growth of the heap will invalidate any references to this heap, 608 so do not hold a reference longer than needed and do not use a 609 reference after any operation which may allocate. Instead, 610 re-fetch the reference by calling this function again. 611 612 Throws if passed an invalid n. 613 */ 614 target.heapForSize = function(n,unsigned = true){ 615 switch(n){ 616 case 8: return unsigned ? __HEAP8U() : __HEAP8(); 617 case 16: return unsigned ? __HEAP16U() : __HEAP16(); 618 case 32: return unsigned ? __HEAP32U() : __HEAP32(); 619 case 64: return unsigned ? __HEAP64U() : __HEAP64(); 620 case Int8Array: return __HEAP8(); 621 case Uint8Array: return __HEAP8U(); 622 case Int16Array: return __HEAP16(); 623 case Uint16Array: return __HEAP16U(); 624 case Int32Array: return __HEAP32(); 625 case Uint32Array: return __HEAP32U(); 626 default: 627 if(n===globalThis['BigUint64Array']) return __HEAP64U(); 628 else if(n===globalThis['BigInt64Array']) return __HEAP64(); 629 else if(n===globalThis['Float32Array']) return __HEAP32F(); 630 else if(n===globalThis['Float64Array']) return __HEAP64F(); 631 toss("Invalid heapForSize() size: expecting 8, 16, 32,", 632 "or (if BigInt is enabled) 64, or a TypedArray constructor."); 633 } 634 }; 635 636 /** 637 Returns the WASM-exported "indirect function table". 638 */ 639 if( !(target.functionTable instanceof Function) ){ 640 target.functionTable = target.functionTable 641 ? ((origFuncTable)=>{return ()=>origFuncTable})(target.functionTable) 642 : ()=>target.exports.__indirect_function_table 643 /** -----------------^^^^^ "seems" to be a standardized export name. 644 From Emscripten release notes from 2020-09-10: 645 - Use `__indirect_function_table` as the import name for the 646 table, which is what LLVM does. 647 648 We must delay access to target.exports until after the library 649 is bootstrapped. 650 */; 651 } 652 653 /** 654 Given a function pointer, returns the WASM function table entry 655 if found, else returns a falsy value: undefined if fptr is out of 656 range or null if it's in range but the table entry is empty. 657 */ 658 target.functionEntry = function(fptr){ 659 const ft = target.functionTable(); 660 //debug("functionEntry(",arguments,")", __asPtrType(fptr)); 661 //-sMEMORY64=1: we get a BigInt fptr and ft.get() wants a BigInt. 662 //-sMEMORY64=2: we get a Number fptr and ft.get() wants a Number. 663 return fptr < ft.length ? ft.get(__asPtrType(fptr)) : undefined; 664 }; 665 666 /** 667 Creates a WASM function which wraps the given JS function and 668 returns the JS binding of that WASM function. The signature 669 string must be the Jaccwabyt-format or Emscripten 670 addFunction()-format function signature string. In short: in may 671 have one of the following formats: 672 673 - Emscripten: `"x..."`, where the first x is a letter representing 674 the result type and subsequent letters represent the argument 675 types. Functions with no arguments have only a single 676 letter. 677 678 - Jaccwabyt: `"x(...)"` where `x` is the letter representing the 679 result type and letters in the parens (if any) represent the 680 argument types. Functions with no arguments use `x()`. 681 682 Supported letters: 683 684 - `i` = int32 685 - `p` = int32 or int64 ("pointer"), depending on target.ptr.size 686 - `j` = int64 687 - `f` = float32 688 - `d` = float64 689 - `v` = void, only legal for use as the result type 690 691 It throws if an invalid signature letter is used. 692 693 Jaccwabyt-format signatures support some additional letters which 694 have no special meaning here but (in this context) act as aliases 695 for other letters: 696 697 - `s`, `P`: same as `p` 698 699 Sidebar: this code is developed together with Jaccwabyt, thus the 700 support for its signature format. 701 702 The arguments may be supplied in either order: (func,sig) or 703 (sig,func). 704 */ 705 target.jsFuncToWasm = function f(func, sig){ 706 /** Attribution: adapted up from Emscripten-generated glue code, 707 refactored primarily for efficiency's sake, eliminating 708 call-local functions and superfluous temporary arrays. */ 709 if(!f._){/*static init...*/ 710 f._ = { 711 /* Map of signature letters to type IR values */ 712 sigTypes: Object.assign(Object.create(null),{ 713 i: 'i32', p: __ptrIR, P: __ptrIR, s: __ptrIR, 714 j: 'i64', f: 'f32', d: 'f64' 715 }), 716 717 /* Map of type IR values to WASM type code values */ 718 typeCodes: Object.assign(Object.create(null),{ 719 f64: 0x7c, f32: 0x7d, i64: 0x7e, i32: 0x7f 720 }), 721 722 /** Encodes n, which must be <2^14 (16384), into target array 723 tgt, as a little-endian value, using the given method 724 ('push' or 'unshift'). */ 725 uleb128Encode: (tgt, method, n)=>{ 726 if(n<128) tgt[method](n); 727 else tgt[method]( (n % 128) | 128, n>>7); 728 }, 729 730 /** Intentionally-lax pattern for Jaccwabyt-format function 731 pointer signatures, the intent of which is simply to 732 distinguish them from Emscripten-format signatures. The 733 downstream checks are less lax. */ 734 rxJSig: /^(\w)\((\w*)\)$/, 735 736 /** Returns the parameter-value part of the given signature 737 string. */ 738 sigParams: (sig)=>{ 739 const m = f._.rxJSig.exec(sig); 740 return m ? m[2] : sig.substr(1); 741 }, 742 743 /** Returns the IR value for the given letter or throws 744 if the letter is invalid. */ 745 letterType: (x)=>f._.sigTypes[x] || toss("Invalid signature letter:",x), 746 747 /** Pushes the WASM data type code for the given signature 748 letter to the given target array. Throws if letter is 749 invalid. */ 750 pushSigType: (dest, letter)=>dest.push(f._.typeCodes[f._.letterType(letter)]) 751 752 /** Returns an object describing the result type and parameter 753 type(s) of the given function signature, or throws if the 754 signature is invalid. */ 755 /******** // only valid for use with the WebAssembly.Function ctor, which 756 // is not yet documented on MDN. 757 sigToWasm: function(sig){ 758 const rc = {parameters:[], results: []}; 759 if('v'!==sig[0]) rc.results.push(f.sigTypes(sig[0])); 760 for(const x of f._.sigParams(sig)){ 761 rc.parameters.push(f._.typeCodes(x)); 762 } 763 return rc; 764 },************/ 765 }; 766 }/*static init*/ 767 if('string'===typeof func){ 768 const x = sig; 769 sig = func; 770 func = x; 771 } 772 const _ = f._; 773 const sigParams = _.sigParams(sig); 774 const wasmCode = [0x01/*count: 1*/, 0x60/*function*/]; 775 _.uleb128Encode(wasmCode, 'push', sigParams.length); 776 for(const x of sigParams) _.pushSigType(wasmCode, x); 777 if('v'===sig[0]) wasmCode.push(0); 778 else{ 779 wasmCode.push(1); 780 _.pushSigType(wasmCode, sig[0]); 781 } 782 _.uleb128Encode(wasmCode, 'unshift', wasmCode.length)/* type section length */; 783 wasmCode.unshift( 784 0x00, 0x61, 0x73, 0x6d, /* magic: "\0asm" */ 785 0x01, 0x00, 0x00, 0x00, /* version: 1 */ 786 0x01 /* type section code */ 787 ); 788 wasmCode.push( 789 /* import section: */ 0x02, 0x07, 790 /* (import "e" "f" (func 0 (type 0))): */ 791 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00, 792 /* export section: */ 0x07, 0x05, 793 /* (export "f" (func 0 (type 0))): */ 794 0x01, 0x01, 0x66, 0x00, 0x00 795 ); 796 return (new WebAssembly.Instance( 797 new WebAssembly.Module(new Uint8Array(wasmCode)), { 798 e: { f: func } 799 })).exports['f']; 800 }/*jsFuncToWasm()*/; 801 802 /** 803 Documented as target.installFunction() except for the 3rd 804 argument: if truthy, the newly-created function pointer 805 is stashed in the current scoped-alloc scope and will be 806 cleaned up at the matching scopedAllocPop(), else it 807 is not stashed there. 808 */ 809 const __installFunction = function f(func, sig, scoped){ 810 if(scoped && !cache.scopedAlloc.length){ 811 toss("No scopedAllocPush() scope is active."); 812 } 813 if('string'===typeof func){ 814 const x = sig; 815 sig = func; 816 func = x; 817 } 818 if('string'!==typeof sig || !(func instanceof Function)){ 819 toss("Invalid arguments: expecting (function,signature) "+ 820 "or (signature,function)."); 821 } 822 const ft = target.functionTable(); 823 const oldLen = __asPtrType(ft.length); 824 let ptr; 825 while( (ptr = cache.freeFuncIndexes.pop()) ){ 826 if(ft.get(ptr)){ 827 /* freeFuncIndexes's entry is stale. Table was modified via a 828 different API */ 829 ptr = null; 830 continue; 831 }else{ 832 /* This index is free. We'll re-use it. */ 833 break; 834 } 835 } 836 if(!ptr){ 837 ptr = __asPtrType(oldLen); 838 ft.grow(__asPtrType(1)); 839 } 840 try{ 841 /*this will only work if func is a WASM-exported function*/ 842 ft.set(ptr, func); 843 if(scoped){ 844 cache.scopedAlloc.pushFuncPtr(ptr); 845 } 846 return ptr; 847 }catch(e){ 848 if(!(e instanceof TypeError)){ 849 if(ptr===oldLen) cache.freeFuncIndexes.push(oldLen); 850 throw e; 851 } 852 } 853 // It's not a WASM-exported function, so compile one... 854 try { 855 const fptr = target.jsFuncToWasm(func, sig); 856 ft.set(ptr, fptr); 857 if(scoped){ 858 cache.scopedAlloc.pushFuncPtr(ptr); 859 } 860 }catch(e){ 861 if(ptr===oldLen) cache.freeFuncIndexes.push(oldLen); 862 throw e; 863 } 864 return ptr; 865 }; 866 867 /** 868 Expects a JS function and signature, exactly as for 869 this.jsFuncToWasm(). It uses that function to create a 870 WASM-exported function, installs that function to the next 871 available slot of this.functionTable(), and returns the 872 function's index in that table (which acts as a pointer to that 873 function). The returned pointer can be passed to 874 uninstallFunction() to uninstall it and free up the table slot 875 for reuse. 876 877 If passed (string,function) arguments then it treats the first 878 argument as the signature and second as the function. 879 880 As a special case, if the passed-in function is a WASM-exported 881 function then the signature argument is ignored and func is 882 installed as-is, without requiring re-compilation/re-wrapping. 883 884 This function will propagate an exception if 885 WebAssembly.Table.grow() throws or this.jsFuncToWasm() throws. 886 The former case can happen in an Emscripten-compiled environment 887 when building without Emscripten's `-sALLOW_TABLE_GROWTH` flag. 888 889 Sidebar: this function differs from Emscripten's addFunction() 890 _primarily_ in that it does not share that function's 891 undocumented behavior of reusing a function if it's passed to 892 addFunction() more than once, which leads to uninstallFunction() 893 breaking clients which do not take care to avoid that case: 894 895 https://github.com/emscripten-core/emscripten/issues/17323 896 */ 897 target.installFunction = (func, sig)=>__installFunction(func, sig, false); 898 899 /** 900 Works exactly like installFunction() but requires that a 901 scopedAllocPush() is active and uninstalls the given function 902 when that alloc scope is popped via scopedAllocPop(). 903 This is used for implementing JS/WASM function bindings which 904 should only persist for the life of a call into a single 905 C-side function. 906 */ 907 target.scopedInstallFunction = (func, sig)=>__installFunction(func, sig, true); 908 909 /** 910 Requires a pointer value previously returned from 911 this.installFunction(). Removes that function from the WASM 912 function table, marks its table slot as free for re-use, and 913 returns that function. It is illegal to call this before 914 installFunction() has been called and results are undefined if 915 ptr was not returned by that function. The returned function 916 may be passed back to installFunction() to reinstall it. 917 918 To simplify certain use cases, if passed a falsy non-0 value 919 (noting that 0 is a valid function table index), this function 920 has no side effects and returns undefined. 921 */ 922 target.uninstallFunction = function(ptr){ 923 if(!ptr && __NullPtr!==ptr) return undefined; 924 925 const ft = target.functionTable(); 926 cache.freeFuncIndexes.push(ptr); 927 const rc = ft.get(ptr); 928 ft.set(ptr, null); 929 return rc; 930 }; 931 932 /** 933 Given a WASM heap memory address and a data type name in the form 934 (i8, i16, i32, i64, float (or f32), double (or f64)), this 935 fetches the numeric value from that address and returns it as a 936 number or, for the case of type='i64', a BigInt (with the caveat 937 BigInt will trigger an exception if this.bigIntEnabled is 938 falsy). Throws if given an invalid type. 939 940 If the first argument is an array, it is treated as an array of 941 addresses and the result is an array of the values from each of 942 those address, using the same 2nd argument for determining the 943 value type to fetch. 944 945 As a special case, if type ends with a `*`, it is considered to 946 be a pointer type and is treated as the WASM numeric type 947 appropriate for the pointer size (==this.ptr.ir). 948 949 While possibly not obvious, this routine and its poke() 950 counterpart are how pointer-to-value _output_ parameters in 951 WASM-compiled C code can be interacted with: 952 953 ``` 954 const ptr = alloc(4); 955 poke32(ptr, 0); // clear the ptr's value 956 aCFuncWithOutputPtrToInt32Arg(ptr); // e.g. void foo(int *x); 957 const result = peek32(ptr); // fetch ptr's value 958 dealloc(ptr); 959 ``` 960 961 scopedAlloc() and friends can be used to make handling of 962 `ptr` safe against leaks in the case of an exception: 963 964 ``` 965 let result; 966 const scope = scopedAllocPush(); 967 try{ 968 const ptr = scopedAlloc(4); 969 poke32(ptr, 0); 970 aCFuncWithOutputPtrArg(ptr); 971 result = peek32(ptr); 972 }finally{ 973 scopedAllocPop(scope); 974 } 975 ``` 976 977 As a rule poke() must be called to set (typically zero out) the 978 pointer's value, else it will contain an essentially random 979 value. 980 981 ACHTUNG: calling this often, e.g. in a loop, can have a noticably 982 painful impact on performance. Rather than doing so, use 983 heapForSize() to fetch the heap object and read directly from it. 984 985 ACHTUNG #2: ptr may be a BigInt (and generally will be in 64-bit 986 builds) but this function must coerce it into a Number in order 987 to access the heap's contents. Ergo: BitInts outside of the 988 (extrardinarily generous) address range exposed to browser-side 989 WASM may cause misbehavior. 990 991 See also: poke() 992 */ 993 target.peek = function(ptr, type = 'i8') { 994 if( type.endsWith('*') ) type = __ptrIR; 995 const heaper = __typeToHeap(type), heap = heaper(); 996 if( Array.isArray(ptr) ){ 997 const res = new Array(ptr.length); 998 for (let i = 0; i < ptr.length; ++i) { 999 const p = Number(ptr[i]); 1000 res[i] = (__HEAP64===heaper) 1001 ? __BigInt(heap[p >> heaper.shift]) 1002 : Number(heap[p >> heaper.shift]); 1003 } 1004 return res; 1005 } 1006 return (__HEAP64===heaper) 1007 ? __BigInt(heap[Number(ptr) >> heaper.shift]) 1008 : Number(heap[Number(ptr) >> heaper.shift]); 1009 }; 1010 1011 /** 1012 The counterpart of peek(), this sets a numeric value at the given 1013 WASM heap address, using the 3rd argument to define how many 1014 bytes are written. Throws if given an invalid type. See peek() 1015 for details about the `type` argument. If the 3rd argument ends 1016 with `*` then it is treated as a pointer type and this function 1017 behaves as if the 3rd argument were this.ptr.ir. 1018 1019 If the first argument is an array, it is treated like a list 1020 of pointers and the given value is written to each one. 1021 1022 Returns `this`. (Prior to 2022-12-09 it returned this function.) 1023 1024 ACHTUNG #1: see peek()'s ACHTUNG #1. 1025 1026 ACHTUNG #2: see peek()'s ACHTUNG #2. 1027 */ 1028 target.poke = function(ptr, value, type='i8'){ 1029 if (type.endsWith('*')) type = __ptrIR; 1030 const heaper = __typeToHeap(type), heap = heaper(); 1031 if( __HEAP64===heaper && 'bigint'!==typeof value ) value = __BigInt(value); 1032 if( Array.isArray(ptr) ){ 1033 for(const p of (Array.isArray(ptr) ? ptr : [ptr])){ 1034 heap[Number(ptr/*tag:64bit*/) >> heaper.shift] = value; 1035 } 1036 }else{ 1037 heap[Number(ptr) >> heaper.shift] = value; 1038 } 1039 return this; 1040 }; 1041 1042 /** 1043 Convenience form of peek() intended for fetching 1044 pointer-to-pointer values. If passed a single non-array argument 1045 it returns the value of that one pointer address. If passed 1046 multiple arguments, or a single array of arguments, it returns an 1047 array of their values. 1048 */ 1049 target.peekPtr = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), __ptrIR ); 1050 1051 /** 1052 A variant of poke() intended for setting pointer-to-pointer 1053 values. Its differences from poke() are that (1) it defaults to a 1054 value of 0 and (2) it always writes to the pointer-sized heap 1055 view. 1056 */ 1057 target.pokePtr = (ptr, value=0)=>target.poke(ptr, value, __ptrIR); 1058 1059 /** 1060 Convenience form of peek() intended for fetching i8 values. If 1061 passed a single non-array argument it returns the value of that 1062 one pointer address. If passed multiple arguments, or a single 1063 array of arguments, it returns an array of their values. 1064 */ 1065 target.peek8 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i8' ); 1066 /** 1067 Convenience form of poke() intended for setting individual bytes. 1068 Its difference from poke() is that it always writes to the 1069 i8-sized heap view. 1070 */ 1071 target.poke8 = (ptr, value)=>target.poke(ptr, value, 'i8'); 1072 /** i16 variant of peek8(). */ 1073 target.peek16 = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i16' ); 1074 /** i16 variant of poke8(). */ 1075 target.poke16 = (ptr, value)=>target.poke(ptr, value, 'i16'); 1076 /** i32 variant of peek8(). */ 1077 target.peek32 = function(ptr){ 1078 if( 'number' === typeof ptr && 1 === arguments.length ) { 1079 /* Fast-path common case. */ 1080 return __HEAP32()[ptr >> 2]; 1081 } 1082 return target.peek(1 === arguments.length 1083 ? ptr 1084 : Array.from(arguments), 'i32'); 1085 }; 1086 /** i32 variant of poke8(). */ 1087 target.poke32 = (ptr, value)=>{ 1088 /* Fast-path common case. */ 1089 if( 'number' === typeof ptr ){ 1090 __HEAP32()[ptr >> 2] = value; 1091 return target; 1092 } 1093 return target.poke(ptr, value, 'i32'); 1094 }; 1095 /** i64 variant of peek8(). Will throw if this build is not 1096 configured for BigInt support. */ 1097 target.peek64 = (ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'i64' ); 1098 1099 /** i64 variant of poke8(). Will throw if this build is not 1100 configured for BigInt support. Note that this returns 1101 a BigInt-type value, not a Number-type value. */ 1102 target.poke64 = (ptr, value)=>target.poke(ptr, value, 'i64'); 1103 1104 /** f32 variant of peek8(). */ 1105 target.peek32f = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'f32' ); 1106 /** f32 variant of poke8(). */ 1107 target.poke32f = (ptr, value)=>target.poke(ptr, value, 'f32'); 1108 /** f64 variant of peek8(). */ 1109 target.peek64f = (...ptr)=>target.peek( (1===ptr.length ? ptr[0] : ptr), 'f64' ); 1110 /** f64 variant of poke8(). */ 1111 target.poke64f = (ptr, value)=>target.poke(ptr, value, 'f64'); 1112 1113 /** Deprecated alias for getMemValue() */ 1114 target.getMemValue = target.peek; 1115 /** Deprecated alias for peekPtr() */ 1116 target.getPtrValue = target.peekPtr; 1117 /** Deprecated alias for poke() */ 1118 target.setMemValue = target.poke; 1119 /** Deprecated alias for pokePtr() */ 1120 target.setPtrValue = target.pokePtr; 1121 1122 /** 1123 Returns true if the given value appears to be legal for use as a 1124 WASM pointer value. Its _range_ of values is not (cannot be) 1125 validated except to ensure that it is a 32-bit integer with a 1126 value of 0 or greater. Likewise, it cannot verify whether the 1127 value actually refers to allocated memory in the WASM heap. 1128 1129 Whether or not null or undefined are legal are context-dependent. 1130 They generally are legal but this function does not treat them as 1131 such because they're not strictly legal for passing as-is as WASM 1132 integer arguments. 1133 */ 1134 target.isPtr32 = (ptr)=>( 1135 'number'===typeof ptr && ptr===(ptr>>>0) 1136 ); 1137 1138 /** 64-bit counterpart of isPtr32() and falls back to that function 1139 if ptr is not a BigInt. */ 1140 target.isPtr64 = (ptr)=>( 1141 ('bigint'===typeof ptr) ? ptr >= 0 : target.isPtr32(ptr) 1142 ); 1143 1144 /** 1145 isPtr() is an alias for isPtr32() or isPtr64(), depending on the 1146 value of target.ptr.size. 1147 */ 1148 target.isPtr = (4===__ptrSize) ? target.isPtr32 : target.isPtr64; 1149 1150 /** 1151 Expects ptr to be a pointer into the WASM heap memory which 1152 refers to a NUL-terminated C-style string encoded as UTF-8. 1153 Returns the length, in bytes, of the string, as for `strlen(3)`. 1154 As a special case, if !ptr or if it's not a pointer then it 1155 returns `null`. Results are undefined if no NUL is found. Throws 1156 if ptr is out of range for target.heap8u(). 1157 */ 1158 target.cstrlen = function(ptr){ 1159 if(!ptr || !target.isPtr(ptr)) return null; 1160 ptr = Number(ptr); 1161 const end = __HEAP8U().indexOf(0, ptr); 1162 return end < 0 ? null : end - ptr; 1163 }; 1164 1165 /** Internal helper to use in operations which need to distinguish 1166 between TypedArrays which are backed by a SharedArrayBuffer 1167 from those which are not. */ 1168 const __SAB = ('undefined'===typeof SharedArrayBuffer) 1169 ? function(){/*dummy class*/} : SharedArrayBuffer; 1170 /** Returns true if the given TypedArray object is backed by a 1171 SharedArrayBuffer, else false. */ 1172 const isSharedTypedArray = (aTypedArray)=>(aTypedArray.buffer instanceof __SAB); 1173 1174 target.isSharedTypedArray = isSharedTypedArray; 1175 1176 /** 1177 Returns either aTypedArray.slice(begin,end) (if 1178 aTypedArray.buffer is a SharedArrayBuffer) or 1179 aTypedArray.subarray(begin,end) (if it's not). 1180 1181 This distinction is important for APIs which don't like to 1182 work on SABs, e.g. TextDecoder, and possibly for our 1183 own APIs which work on memory ranges which "might" be 1184 modified by other threads while they're working. 1185 1186 begin and end may be of type Number or (in 64-bit builds) BigInt 1187 (which get coerced to Numbers). 1188 */ 1189 const typedArrayPart = (aTypedArray, begin, end)=>{ 1190 if( 8===__ptrSize ){ 1191 // slice() and subarray() do not like BigInt args. 1192 if( 'bigint'===typeof begin ) begin = Number(begin); 1193 if( 'bigint'===typeof end ) end = Number(end); 1194 } 1195 return isSharedTypedArray(aTypedArray) 1196 ? aTypedArray.slice(begin, end) 1197 : aTypedArray.subarray(begin, end); 1198 }; 1199 1200 target.typedArrayPart = typedArrayPart; 1201 1202 /** 1203 Uses TextDecoder to decode the given half-open range of the given 1204 TypedArray to a string. This differs from a simple call to 1205 TextDecoder in that it accounts for whether the first argument is 1206 backed by a SharedArrayBuffer or not, and can work more 1207 efficiently if it's not (TextDecoder refuses to act upon an SAB). 1208 1209 If begin/end are not provided or are falsy then each defaults to 1210 the start/end of the array. 1211 */ 1212 const typedArrayToString = (typedArray, begin, end)=> 1213 cache.utf8Decoder.decode( 1214 typedArrayPart(typedArray, begin, end) 1215 ); 1216 1217 target.typedArrayToString = typedArrayToString; 1218 1219 /** 1220 Expects ptr to be a pointer into the WASM heap memory which 1221 refers to a NUL-terminated C-style string encoded as UTF-8. This 1222 function counts its byte length using cstrlen() then returns a 1223 JS-format string representing its contents. As a special case, if 1224 ptr is falsy or not a pointer, `null` is returned. 1225 */ 1226 target.cstrToJs = function(ptr){ 1227 const n = target.cstrlen(ptr); 1228 return n 1229 ? typedArrayToString(__HEAP8U(), Number(ptr), Number(ptr)+n) 1230 : (null===n ? n : ""); 1231 }; 1232 1233 /** 1234 Given a JS string, this function returns its UTF-8 length in 1235 bytes. Returns null if str is not a string. 1236 */ 1237 target.jstrlen = function(str){ 1238 /** Attribution: derived from Emscripten's lengthBytesUTF8() */ 1239 if('string'!==typeof str) return null; 1240 const n = str.length; 1241 let len = 0; 1242 for(let i = 0; i < n; ++i){ 1243 let u = str.charCodeAt(i); 1244 if(u>=0xd800 && u<=0xdfff){ 1245 u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF); 1246 } 1247 if(u<=0x7f) ++len; 1248 else if(u<=0x7ff) len += 2; 1249 else if(u<=0xffff) len += 3; 1250 else len += 4; 1251 } 1252 return len; 1253 }; 1254 1255 /** 1256 Encodes the given JS string as UTF8 into the given TypedArray 1257 tgt, starting at the given offset and writing, at most, maxBytes 1258 bytes (including the NUL terminator if addNul is true, else no 1259 NUL is added). If it writes any bytes at all and addNul is true, 1260 it always NUL-terminates the output, even if doing so means that 1261 the NUL byte is all that it writes. 1262 1263 If maxBytes is negative (the default) then it is treated as the 1264 remaining length of tgt, starting at the given offset. 1265 1266 If writing the last character would surpass the maxBytes count 1267 because the character is multi-byte, that character will not be 1268 written (as opposed to writing a truncated multi-byte character). 1269 This can lead to it writing as many as 3 fewer bytes than 1270 maxBytes specifies. 1271 1272 Returns the number of bytes written to the target, _including_ 1273 the NUL terminator (if any). If it returns 0, it wrote nothing at 1274 all, which can happen if: 1275 1276 - str is empty and addNul is false. 1277 - offset < 0. 1278 - maxBytes == 0. 1279 - maxBytes is less than the byte length of a multi-byte str[0]. 1280 1281 Throws if tgt is not an Int8Array or Uint8Array. 1282 1283 Design notes: 1284 1285 - In C's strcpy(), the destination pointer is the first 1286 argument. That is not the case here primarily because the 3rd+ 1287 arguments are all referring to the destination, so it seems to 1288 make sense to have them grouped with it. 1289 1290 - Emscripten's counterpart of this function (stringToUTF8Array()) 1291 returns the number of bytes written sans NUL terminator. That 1292 is, however, ambiguous: str.length===0 or maxBytes===(0 or 1) 1293 all cause 0 to be returned. 1294 */ 1295 target.jstrcpy = function(jstr, tgt, offset = 0, maxBytes = -1, addNul = true){ 1296 /** Attribution: the encoding bits are taken from Emscripten's 1297 stringToUTF8Array(). */ 1298 if(!tgt || (!(tgt instanceof Int8Array) && !(tgt instanceof Uint8Array))){ 1299 toss("jstrcpy() target must be an Int8Array or Uint8Array."); 1300 } 1301 maxBytes = Number(maxBytes)/*tag:64bit*/; 1302 offset = Number(offset)/*tag:64bit*/; 1303 if(maxBytes<0) maxBytes = tgt.length - offset; 1304 if(!(maxBytes>0) || !(offset>=0)) return 0; 1305 let i = 0, max = jstr.length; 1306 const begin = offset, end = offset + maxBytes - (addNul ? 1 : 0); 1307 for(; i < max && offset < end; ++i){ 1308 let u = jstr.charCodeAt(i); 1309 if(u>=0xd800 && u<=0xdfff){ 1310 u = 0x10000 + ((u & 0x3FF) << 10) | (jstr.charCodeAt(++i) & 0x3FF); 1311 } 1312 if(u<=0x7f){ 1313 if(offset >= end) break; 1314 tgt[offset++] = u; 1315 }else if(u<=0x7ff){ 1316 if(offset + 1 >= end) break; 1317 tgt[offset++] = 0xC0 | (u >> 6); 1318 tgt[offset++] = 0x80 | (u & 0x3f); 1319 }else if(u<=0xffff){ 1320 if(offset + 2 >= end) break; 1321 tgt[offset++] = 0xe0 | (u >> 12); 1322 tgt[offset++] = 0x80 | ((u >> 6) & 0x3f); 1323 tgt[offset++] = 0x80 | (u & 0x3f); 1324 }else{ 1325 if(offset + 3 >= end) break; 1326 tgt[offset++] = 0xf0 | (u >> 18); 1327 tgt[offset++] = 0x80 | ((u >> 12) & 0x3f); 1328 tgt[offset++] = 0x80 | ((u >> 6) & 0x3f); 1329 tgt[offset++] = 0x80 | (u & 0x3f); 1330 } 1331 } 1332 if(addNul) tgt[offset++] = 0; 1333 return offset - begin; 1334 }; 1335 1336 /** 1337 Works similarly to C's strncpy(), copying, at most, n bytes (not 1338 characters) from srcPtr to tgtPtr. It copies until n bytes have 1339 been copied or a 0 byte is reached in src. _Unlike_ strncpy(), it 1340 returns the number of bytes it assigns in tgtPtr, _including_ the 1341 NUL byte (if any). If n is reached before a NUL byte in srcPtr, 1342 tgtPtr will _not_ be NULL-terminated. If a NUL byte is reached 1343 before n bytes are copied, tgtPtr will be NUL-terminated. 1344 1345 If n is negative, cstrlen(srcPtr)+1 is used to calculate it, the 1346 +1 being for the NUL byte. 1347 1348 Throws if tgtPtr or srcPtr are falsy. Results are undefined if: 1349 1350 - either is not a pointer into the WASM heap or 1351 1352 - srcPtr is not NUL-terminated AND n is less than srcPtr's 1353 logical length. 1354 1355 ACHTUNG: it is possible to copy partial multi-byte characters 1356 this way, and converting such strings back to JS strings will 1357 have undefined results. 1358 */ 1359 target.cstrncpy = function(tgtPtr, srcPtr, n){ 1360 if(!tgtPtr || !srcPtr) toss("cstrncpy() does not accept NULL strings."); 1361 if(n<0) n = target.cstrlen(strPtr)+1; 1362 else if(!(n>0)) return 0; 1363 const heap = __HEAP8U(); 1364 let i = 0, ch; 1365 const tgtNumber = Number(tgtPtr), srcNumber = Number(srcPtr)/*tag:64bit*/; 1366 for(; i < n && (ch = heap[srcNumber+i]); ++i){ 1367 heap[tgtNumber+i] = ch; 1368 } 1369 if(i{ 1379 return cache.utf8Encoder.encode(addNul ? (str+"\0") : str); 1380 }; 1381 1382 const __affirmAlloc = (obj,funcName)=>{ 1383 if(!(obj.alloc instanceof Function) || 1384 !(obj.dealloc instanceof Function)){ 1385 toss("Object is missing alloc() and/or dealloc() function(s)", 1386 "required by",funcName+"()."); 1387 } 1388 }; 1389 1390 const __allocCStr = function(jstr, returnWithLength, allocator, funcName){ 1391 __affirmAlloc(target, funcName); 1392 if('string'!==typeof jstr) return null; 1393 const u = cache.utf8Encoder.encode(jstr), 1394 ptr = allocator(u.length+1); 1395 let toFree = ptr; 1396 try{ 1397 const heap = __HEAP8U(); 1398 heap.set(u, Number(ptr)); 1399 heap[__ptrAdd(ptr, u.length)] = 0; 1400 toFree = __NullPtr; 1401 return returnWithLength ? [ptr, u.length] : ptr; 1402 }finally{ 1403 if( toFree ) target.dealloc(toFree); 1404 } 1405 }; 1406 1407 /** 1408 Uses target.alloc() to allocate enough memory for jstrlen(jstr)+1 1409 bytes of memory, copies jstr to that memory using jstrcpy(), 1410 NUL-terminates it, and returns the pointer to that C-string. 1411 Ownership of the pointer is transfered to the caller, who must 1412 eventually pass the pointer to dealloc() to free it. 1413 1414 If passed a truthy 2nd argument then its return semantics change: 1415 it returns [ptr,n], where ptr is the C-string's pointer and n is 1416 its cstrlen(). 1417 1418 Throws if `target.alloc` or `target.dealloc` are not functions. 1419 */ 1420 target.allocCString = 1421 (jstr, returnWithLength=false)=>__allocCStr(jstr, returnWithLength, 1422 target.alloc, 'allocCString()'); 1423 1424 /** 1425 Starts an "allocation scope." All allocations made using 1426 scopedAlloc() are recorded in this scope and are freed when the 1427 value returned from this function is passed to 1428 scopedAllocPop(). 1429 1430 This family of functions requires that the API's object have both 1431 `alloc()` and `dealloc()` methods, else this function will throw. 1432 1433 Intended usage: 1434 1435 ``` 1436 const scope = scopedAllocPush(); 1437 try { 1438 const ptr1 = scopedAlloc(100); 1439 const ptr2 = scopedAlloc(200); 1440 const ptr3 = scopedAlloc(300); 1441 ... 1442 // Note that only allocations made via scopedAlloc() 1443 // are managed by this allocation scope. 1444 }finally{ 1445 scopedAllocPop(scope); 1446 } 1447 ``` 1448 1449 The value returned by this function must be treated as opaque by 1450 the caller, suitable _only_ for passing to scopedAllocPop(). 1451 Its type and value are not part of this function's API and may 1452 change in any given version of this code. 1453 1454 `scopedAlloc.level` can be used to determine how many scoped 1455 alloc levels are currently active. 1456 */ 1457 target.scopedAllocPush = function(){ 1458 __affirmAlloc(target, 'scopedAllocPush'); 1459 const a = nu({ptr:[], func:[]}); 1460 cache.scopedAlloc.push(a); 1461 return a; 1462 }; 1463 1464 /** 1465 Cleans up all allocations made using scopedAlloc() in the context 1466 of the given opaque state object, which must be a value returned 1467 by scopedAllocPush(). See that function for an example of how to 1468 use this function. It also uninstalls any WASM functions 1469 installed with scopedInstallFunction(). 1470 1471 Though scoped allocations are managed like a stack, this API 1472 behaves properly if allocation scopes are popped in an order 1473 other than the order they were pushed. The intent is that it 1474 _always_ be used in a stack-like manner. 1475 1476 If called with no arguments, it pops the most recent 1477 scopedAllocPush() result: 1478 1479 ``` 1480 scopedAllocPush(); 1481 try{ ... } finally { scopedAllocPop(); } 1482 ``` 1483 1484 It's generally recommended that it be passed an explicit argument 1485 to help ensure that push/push are used in matching pairs, but in 1486 trivial code that may be a non-issue. 1487 */ 1488 target.scopedAllocPop = function(state){ 1489 __affirmAlloc(target, 'scopedAllocPop'); 1490 const n = arguments.length 1491 ? cache.scopedAlloc.indexOf(state) 1492 : cache.scopedAlloc.length-1; 1493 if(n<0) toss('Invalid state object for scopedAllocPop().'); 1494 if(0 === arguments.length) state = cache.scopedAlloc[n]; 1495 cache.scopedAlloc.splice(n, 1); 1496 let li = state.func; 1497 while( li.length ){ 1498 try{target.uninstallFunction(li.pop())} 1499 catch(e){/*ignored*/} 1500 } 1501 li = state.ptr; 1502 while( li.length ) target.dealloc(li.pop()); 1503 state.ptr = state.func = null; 1504 }; 1505 1506 /** 1507 Allocates n bytes of memory using this.alloc() and records that 1508 fact in the state for the most recent call of scopedAllocPush(). 1509 Ownership of the memory is given to scopedAllocPop(), which 1510 will clean it up when it is called. The memory _must not_ be 1511 passed to this.dealloc(). Throws if this API object is missing 1512 the required `alloc()` or `dealloc()` functions or no scoped 1513 alloc is active. 1514 1515 See scopedAllocPush() for an example of how to use this function. 1516 1517 The `level` property of this function can be queried to query how 1518 many scoped allocation levels are currently active. 1519 1520 See also: scopedAllocPtr(), scopedAllocCString() 1521 */ 1522 target.scopedAlloc = function(n){ 1523 if(!cache.scopedAlloc.length){ 1524 toss("No scopedAllocPush() scope is active."); 1525 } 1526 const p = __asPtrType(target.alloc(n)); 1527 return cache.scopedAlloc.pushPtr(p); 1528 }; 1529 1530 Object.defineProperty(target.scopedAlloc, 'level', { 1531 configurable: false, enumerable: false, 1532 get: ()=>cache.scopedAlloc.length, 1533 set: ()=>toss("The 'active' property is read-only.") 1534 }); 1535 1536 /** 1537 Works identically to allocCString() except that it allocates the 1538 memory using scopedAlloc(). 1539 1540 Will throw if no scopedAllocPush() call is active. 1541 */ 1542 target.scopedAllocCString = 1543 (jstr, returnWithLength=false)=>__allocCStr(jstr, returnWithLength, 1544 target.scopedAlloc, 1545 'scopedAllocCString()'); 1546 1547 // impl for allocMainArgv() and scopedAllocMainArgv(). 1548 const __allocMainArgv = function(isScoped, list){ 1549 const pList = target[ 1550 isScoped ? 'scopedAlloc' : 'alloc' 1551 ]((list.length + 1) * target.ptr.size); 1552 let i = 0; 1553 list.forEach((e)=>{ 1554 target.pokePtr(__ptrAdd(pList, target.ptr.size * i++), 1555 target[ 1556 isScoped ? 'scopedAllocCString' : 'allocCString' 1557 ](""+e)); 1558 }); 1559 target.pokePtr(__ptrAdd(pList, target.ptr.size * i), 0); 1560 return pList; 1561 }; 1562 1563 /** 1564 Creates an array, using scopedAlloc(), suitable for passing to a 1565 C-level main() routine. The input is a collection with a length 1566 property and a forEach() method. A block of memory 1567 (list.length+1) entries long is allocated and each pointer-sized 1568 block of that memory is populated with a scopedAllocCString() 1569 conversion of the (""+value) of each element, with the exception 1570 that the final entry is a NULL pointer. Returns a pointer to the 1571 start of the list, suitable for passing as the 2nd argument to a 1572 C-style main() function. 1573 1574 Throws if scopedAllocPush() is not active. 1575 1576 Design note: the returned array is allocated with an extra NULL 1577 pointer entry to accommodate certain APIs, but client code which 1578 does not need that functionality should treat the returned array 1579 as list.length entries long. 1580 */ 1581 target.scopedAllocMainArgv = (list)=>__allocMainArgv(true, list); 1582 1583 /** 1584 Identical to scopedAllocMainArgv() but uses alloc() instead of 1585 scopedAlloc(). 1586 */ 1587 target.allocMainArgv = (list)=>__allocMainArgv(false, list); 1588 1589 /** 1590 Expects to be given a C-style string array and its length. It 1591 returns a JS array of strings and/or nulls: any entry in the 1592 pArgv array which is NULL results in a null entry in the result 1593 array. If argc is 0 then an empty array is returned. 1594 1595 Results are undefined if any entry in the first argc entries of 1596 pArgv are neither 0 (NULL) nor legal UTF-format C strings. 1597 1598 To be clear, the expected C-style arguments to be passed to this 1599 function are `(int, char **)` (optionally const-qualified). 1600 */ 1601 target.cArgvToJs = (argc, pArgv)=>{ 1602 const list = []; 1603 for(let i = 0; i < argc; ++i){ 1604 const arg = target.peekPtr(__ptrAdd(pArgv, target.ptr.size * i)); 1605 list.push( arg ? target.cstrToJs(arg) : null ); 1606 } 1607 return list; 1608 }; 1609 1610 /** 1611 Wraps function call func() in a scopedAllocPush() and 1612 scopedAllocPop() block, such that all calls to scopedAlloc() and 1613 friends from within that call will have their memory freed 1614 automatically when func() returns. If func throws or propagates 1615 an exception, the scope is still popped, otherwise it returns the 1616 result of calling func(). 1617 */ 1618 target.scopedAllocCall = function(func){ 1619 target.scopedAllocPush(); 1620 try{ return func() } finally{ target.scopedAllocPop() } 1621 }; 1622 1623 /** Internal impl for allocPtr() and scopedAllocPtr(). */ 1624 const __allocPtr = function(howMany, safePtrSize, method){ 1625 __affirmAlloc(target, method); 1626 const pIr = safePtrSize ? 'i64' : __ptrIR; 1627 let m = target[method](howMany * (safePtrSize ? 8 : __ptrSize)); 1628 target.poke(m, 0, pIr) 1629 if(1===howMany){ 1630 return m; 1631 } 1632 const a = [m]; 1633 for(let i = 1; i < howMany; ++i){ 1634 m = __ptrAdd(m, (safePtrSize ? 8 : __ptrSize)); 1635 a[i] = m; 1636 target.poke(m, 0, pIr); 1637 } 1638 return a; 1639 }; 1640 1641 /** 1642 Allocates one or more pointers as a single chunk of memory and 1643 zeroes them out. 1644 1645 The first argument is the number of pointers to allocate. The 1646 second specifies whether they should use a "safe" pointer size (8 1647 bytes) or whether they may use the default pointer size 1648 (typically 4 but also possibly 8). 1649 1650 How the result is returned depends on its first argument: if 1651 passed 1, it returns the allocated memory address. If passed more 1652 than one then an array of pointer addresses is returned, which 1653 can optionally be used with "destructuring assignment" like this: 1654 1655 ``` 1656 const [p1, p2, p3] = allocPtr(3); 1657 ``` 1658 1659 ACHTUNG: when freeing the memory, pass only the _first_ result 1660 value to dealloc(). The others are part of the same memory chunk 1661 and must not be freed separately. 1662 1663 The reason for the 2nd argument is... 1664 1665 When one of the returned pointers will refer to a 64-bit value, 1666 e.g. a double or int64, and that value must be written or fetched, 1667 e.g. using poke() or peek(), it is important that 1668 the pointer in question be aligned to an 8-byte boundary or else 1669 it will not be fetched or written properly and will corrupt or 1670 read neighboring memory. It is only safe to pass false when the 1671 client code is certain that it will only get/fetch 4-byte values 1672 (or smaller). 1673 */ 1674 target.allocPtr = 1675 (howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'alloc'); 1676 1677 /** 1678 Identical to allocPtr() except that it allocates using scopedAlloc() 1679 instead of alloc(). 1680 */ 1681 target.scopedAllocPtr = 1682 (howMany=1, safePtrSize=true)=>__allocPtr(howMany, safePtrSize, 'scopedAlloc'); 1683 1684 /** 1685 If target.exports[name] exists, it is returned, else an 1686 exception is thrown. 1687 */ 1688 target.xGet = function(name){ 1689 return target.exports[name] || toss("Cannot find exported symbol:",name); 1690 }; 1691 1692 const __argcMismatch = 1693 (f,n)=>toss(f+"() requires",n,"argument(s)."); 1694 1695 /** 1696 Looks up a WASM-exported function named fname from 1697 target.exports. If found, it is called, passed all remaining 1698 arguments, and its return value is returned to xCall's caller. If 1699 not found, an exception is thrown. This function does no 1700 conversion of argument or return types, but see xWrap() and 1701 xCallWrapped() for variants which do. 1702 1703 If the first argument is a function is is assumed to be 1704 a WASM-bound function and is used as-is instead of looking up 1705 the function via xGet(). 1706 1707 As a special case, if passed only 1 argument after the name and 1708 that argument in an Array, that array's entries become the 1709 function arguments. (This is not an ambiguous case because it's 1710 not legal to pass an Array object to a WASM function.) 1711 */ 1712 target.xCall = function(fname, ...args){ 1713 const f = (fname instanceof Function) ? fname : target.xGet(fname); 1714 if(!(f instanceof Function)) toss("Exported symbol",fname,"is not a function."); 1715 if(f.length!==args.length){ 1716 __argcMismatch(((f===fname) ? f.name : fname),f.length) 1717 /* This is arguably over-pedantic but we want to help clients keep 1718 from shooting themselves in the foot when calling C APIs. */; 1719 } 1720 return (2===arguments.length && Array.isArray(arguments[1])) 1721 ? f.apply(null, arguments[1]) 1722 : f.apply(null, args); 1723 }; 1724 1725 /** 1726 State for use with xWrap(). 1727 */ 1728 cache.xWrap = Object.create(null); 1729 cache.xWrap.convert = Object.create(null); 1730 /** Map of type names to argument conversion functions. */ 1731 cache.xWrap.convert.arg = new Map; 1732 /** Map of type names to return result conversion functions. */ 1733 cache.xWrap.convert.result = new Map; 1734 /** Scope-local convenience aliases. */ 1735 const xArg = cache.xWrap.convert.arg, xResult = cache.xWrap.convert.result; 1736 1737 const __xArgPtr = __asPtrType; 1738 xArg 1739 .set('i64', __BigInt) 1740 .set('i32', (i)=>i|0) 1741 .set('i16', (i)=>((i | 0) & 0xFFFF)) 1742 .set('i8', (i)=>((i | 0) & 0xFF)) 1743 .set('f32', (i)=>Number(i).valueOf()) 1744 .set('float', xArg.get('f32')) 1745 .set('f64', xArg.get('f32')) 1746 .set('double', xArg.get('f64')) 1747 .set('int', xArg.get('i32')) 1748 .set('null', (i)=>i) 1749 .set(null, xArg.get('null')) 1750 .set('**', __xArgPtr) 1751 .set('*', __xArgPtr) 1752 ; 1753 xResult.set('*', __xArgPtr) 1754 .set('pointer', __xArgPtr) 1755 .set('number', (v)=>Number(v)) 1756 .set('void', (v)=>undefined) 1757 .set(undefined, xResult.get('void')) 1758 .set('null', (v)=>v) 1759 .set(null, xResult.get('null')) 1760 ; 1761 1762 /* Copy xArg[...] handlers to xResult[...] for cases which have 1763 identical semantics. Also add pointer-style variants of those 1764 xArg entries to both xArg and xResult. */ 1765 for(const t of [ 1766 'i8', 'i16', 'i32', 'i64', 'int', 1767 'f32', 'float', 'f64', 'double' 1768 ]){ 1769 xArg.set(t+'*', __xArgPtr); 1770 xResult.set(t+'*', __xArgPtr); 1771 xResult.set( 1772 t, xArg.get(t) 1773 || toss("Maintenance required: missing arg converter for",t) 1774 ); 1775 } 1776 1777 /** 1778 In order for args of type string to work in various contexts in 1779 the sqlite3 API, we need to pass them on as, variably, a C-string 1780 or a pointer value. Thus for ARGs of type 'string' and 1781 '*'/'pointer' we behave differently depending on whether the 1782 argument is a string or not: 1783 1784 - If v is a string, scopeAlloc() a new C-string from it and return 1785 that temp string's pointer. 1786 1787 - Else return the value from the arg adapter defined for 1788 target.ptr.ir. 1789 1790 TODO? Permit an Int8Array/Uint8Array and convert it to a string? 1791 Would that be too much magic concentrated in one place, ready to 1792 backfire? We handle that at the client level in sqlite3 with a 1793 custom argument converter. 1794 */ 1795 const __xArgString = (v)=>{ 1796 return ('string'===typeof v) 1797 ? target.scopedAllocCString(v) 1798 : __asPtrType(v); 1799 }; 1800 1801 xArg.set('string', __xArgString) 1802 .set('utf8', __xArgString) 1803 // (much later: why did we do this?) .set('pointer', __xArgString) 1804 ; 1805 1806 xResult 1807 .set('string', (i)=>target.cstrToJs(i)) 1808 .set('utf8', xResult.get('string')) 1809 .set('string:dealloc', (i)=>{ 1810 try { return i ? target.cstrToJs(i) : null } 1811 finally{ target.dealloc(i) } 1812 }) 1813 .set('utf8:dealloc', xResult.get('string:dealloc')) 1814 .set('json', (i)=>JSON.parse(target.cstrToJs(i))) 1815 .set('json:dealloc', (i)=>{ 1816 try{ return i ? JSON.parse(target.cstrToJs(i)) : null } 1817 finally{ target.dealloc(i) } 1818 }); 1819 1820 /** 1821 Internal-use-only base class for FuncPtrAdapter and potentially 1822 additional stateful argument adapter classes. 1823 1824 By "internal" we mean "within the sqlite project" (where this 1825 code originated and where it continues to serve). That is: this 1826 API exists to suit that project's internal needs, with no 1827 consideration for its use elsewhere. Client-level code must not 1828 rely on this interface. 1829 1830 Its main interface (convertArg()) is strictly internal, not to be 1831 exposed to client code, as it may still need re-shaping. Only the 1832 constructors of concrete subclasses should be exposed to clients, 1833 and those in such a way that does not hinder internal redesign of 1834 the convertArg() interface. 1835 */ 1836 const AbstractArgAdapter = class { 1837 constructor(opt){ 1838 this.name = opt.name || 'unnamed adapter'; 1839 } 1840 /** 1841 Gets called via xWrap() to "convert" v to whatever type 1842 this specific class supports. 1843 1844 argIndex is the argv index of _this_ argument in the 1845 being-xWrap()'d call. argv is the current argument list 1846 undergoing xWrap() argument conversion. argv entries to the 1847 left of argIndex will have already undergone transformation and 1848 those to the right will not have (they will have the values the 1849 client-level code passed in, awaiting conversion). The RHS 1850 indexes must never be relied upon for anything because their 1851 types are indeterminate, whereas the LHS values will be 1852 WASM-compatible values by the time this is called. 1853 1854 The reason for the argv and argIndex arguments is that we 1855 frequently need more context than v for a specific conversion, 1856 and that context invariably lies in the LHS arguments of v. 1857 Examples of how this is useful can be found in FuncPtrAdapter. 1858 */ 1859 convertArg(/*v,argv,argIndex*/){ 1860 toss("AbstractArgAdapter must be subclassed."); 1861 } 1862 }; 1863 1864 /** 1865 This type is recognized by xWrap() as a proxy for converting a JS 1866 function to a C-side function, either permanently, for the 1867 duration of a single call into the C layer, or semi-contextual, 1868 where it may keep track of a single binding for a given context 1869 and uninstall the binding if it's replaced. 1870 1871 The constructor requires an options object with these properties: 1872 1873 - name (optional): string describing the function binding. This 1874 is solely for debugging and error-reporting purposes. If not 1875 provided, an empty string is assumed. 1876 1877 - signature: a function signature string compatible with 1878 jsFuncToWasm(). 1879 1880 - bindScope (string): one of ('transient', 'context', 1881 'singleton', 'permanent'). Bind scopes are: 1882 1883 - 'transient': it will convert JS functions to WASM only for 1884 the duration of the xWrap()'d function call, using 1885 scopedInstallFunction(). Before that call returns, the 1886 WASM-side binding will be uninstalled. 1887 1888 - 'singleton': holds one function-pointer binding for this 1889 instance. If it's called with a different function pointer, 1890 it uninstalls the previous one after converting the new 1891 value. This is only useful for use with "global" functions 1892 which do not rely on any state other than this function 1893 pointer. If the being-converted function pointer is intended 1894 to be mapped to some sort of state object (e.g. an 1895 `sqlite3*`) then "context" (see below) is the proper mode. 1896 1897 - 'context': similar to singleton mode but for a given 1898 "context", where the context is a key provided by the user 1899 and possibly dependent on a small amount of call-time 1900 context. This mode is the default if bindScope is _not_ set 1901 but a property named contextKey (described below) is. 1902 1903 - 'permanent': the function is installed and left there 1904 forever. There is no way to recover its pointer address 1905 later on for cleanup purposes. i.e. it effectively leaks. 1906 1907 - callProxy (function): if set, this must be a function which 1908 will act as a proxy for any "converted" JS function. It is 1909 passed the being-converted function value and must return 1910 either that function or a function which acts on its 1911 behalf. The returned function will be the one which gets 1912 installed into the WASM function table. The proxy must perform 1913 any required argument conversion (it will be called from C 1914 code, so will receive C-format arguments) before passing them 1915 on to the being-converted function. Whether or not the proxy 1916 itself must return a value depends on the context. If it does, 1917 it must be a WASM-friendly value, as it will be returning from 1918 a call made from WASM code. 1919 1920 - contextKey (function): is only used if bindScope is 'context' 1921 or if bindScope is not set and this function is, in which case 1922 a bindScope of 'context' is assumed. This function gets bound 1923 to this object, so its "this" is this object. It gets passed 1924 (argv,argIndex), where argIndex is the index of _this_ function 1925 in its _wrapping_ function's arguments, and argv is the 1926 _current_ still-being-xWrap()-processed args array. (Got all 1927 that?) When thisFunc(argv,argIndex) is called by xWrap(), all 1928 arguments in argv to the left of argIndex will have been 1929 processed by xWrap() by the time this is called. argv[argIndex] 1930 will be the value the user passed in to the xWrap()'d function 1931 for the argument this FuncPtrAdapter is mapped to. Arguments to 1932 the right of argv[argIndex] will not yet have been converted 1933 before this is called. The function must return a key which 1934 uniquely identifies this function mapping context for _this_ 1935 FuncPtrAdapter instance (other instances are not considered), 1936 taking into account that C functions often take some sort of 1937 state object as one or more of their arguments. As an example, 1938 if the xWrap()'d function takes `(int,T*,functionPtr,X*)` then 1939 this FuncPtrAdapter instance is argv[2], and contextKey(argv,2) 1940 might return 'T@'+argv[1], or even just argv[1]. Note, 1941 however, that the (`X*`) argument will not yet have been 1942 processed by the time this is called and should not be used as 1943 part of that key because its pre-conversion data type might be 1944 unpredictable. Similarly, care must be taken with C-string-type 1945 arguments: those to the left in argv will, when this is called, 1946 be WASM pointers, whereas those to the right might (and likely 1947 do) have another data type. When using C-strings in keys, never 1948 use their pointers in the key because most C-strings in this 1949 constellation are transient. Conversely, the pointer address 1950 makes an ideal key for longer-lived native pointer types. 1951 1952 Yes, that ^^^ is quite awkward, but it's what we have. In 1953 context, as it were, it actually makes some sense, but one must 1954 look under its hook a bit to understand why it's shaped the 1955 way it is. 1956 1957 The constructor only saves the above state for later, and does 1958 not actually bind any functions. The conversion, if any, is 1959 performed when its convertArg() method is called via xWrap(). 1960 1961 Shortcomings: 1962 1963 - These "reverse" bindings, i.e. calling into a JS-defined 1964 function from a WASM-defined function (the generated proxy 1965 wrapper), lack all type conversion support. That means, for 1966 example, that... 1967 1968 - Function pointers which include C-string arguments may still 1969 need a level of hand-written wrappers around them, depending on 1970 how they're used, in order to provide the client with JS 1971 strings. Alternately, clients will need to perform such 1972 conversions on their own, e.g. using cstrToJs(). The purpose of 1973 the callProxy() method is to account for such cases. 1974 */ 1975 xArg.FuncPtrAdapter = class FuncPtrAdapter extends AbstractArgAdapter { 1976 constructor(opt) { 1977 super(opt); 1978 if(xArg.FuncPtrAdapter.warnOnUse){ 1979 warn('xArg.FuncPtrAdapter is an internal-only API', 1980 'and is not intended to be invoked from', 1981 'client-level code. It was invoked with:',opt); 1982 } 1983 this.name = opt.name || "unnamed"; 1984 this.signature = opt.signature; 1985 if(opt.contextKey instanceof Function){ 1986 this.contextKey = opt.contextKey; 1987 if(!opt.bindScope) opt.bindScope = 'context'; 1988 } 1989 this.bindScope = opt.bindScope 1990 || toss("FuncPtrAdapter options requires a bindScope (explicit or implied)."); 1991 if(FuncPtrAdapter.bindScopes.indexOf(opt.bindScope)<0){ 1992 toss("Invalid options.bindScope ("+opt.bindMod+") for FuncPtrAdapter. "+ 1993 "Expecting one of: ("+FuncPtrAdapter.bindScopes.join(', ')+')'); 1994 } 1995 this.isTransient = 'transient'===this.bindScope; 1996 this.isContext = 'context'===this.bindScope; 1997 this.isPermanent = 'permanent'===this.bindScope; 1998 this.singleton = ('singleton'===this.bindScope) ? [] : undefined; 1999 //warn("FuncPtrAdapter()",opt,this); 2000 this.callProxy = (opt.callProxy instanceof Function) 2001 ? opt.callProxy : undefined; 2002 } 2003 2004 /** 2005 The static class members are defined outside of the class to 2006 work around an emcc toolchain build problem: one of the tools 2007 in emsdk v3.1.42 does not support the static keyword. 2008 */ 2009 2010 /* Dummy impl. Overwritten per-instance as needed. */ 2011 contextKey(/*argv,argIndex*/){ 2012 return this; 2013 } 2014 2015 /** 2016 Returns this object's mapping for the given context key, in the 2017 form of an an array, creating the mapping if needed. The key 2018 may be anything suitable for use in a Map. 2019 2020 The returned array is intended to be used as a pair of 2021 [JSValue, WasmFuncPtr], where the first element is one passed 2022 to this.convertArg() and the second is its WASM form. 2023 */ 2024 contextMap(key){ 2025 const cm = (this.__cmap || (this.__cmap = new Map)); 2026 let rc = cm.get(key); 2027 if(undefined===rc) cm.set(key, (rc = [])); 2028 return rc; 2029 } 2030 2031 /** 2032 Gets called via xWrap() to "convert" v to a WASM-bound function 2033 pointer. If v is one of (a WASM pointer, null, undefined) then 2034 (v||0) is returned and any earlier function installed by this 2035 mapping _might_, depending on how it's bound, be uninstalled. 2036 If v is not one of those types, it must be a Function, for 2037 which this method creates (if needed) a WASM function binding 2038 and returns the WASM pointer to that binding. 2039 2040 If this instance is not in 'transient' mode, it will remember 2041 the binding for at least the next call, to avoid recreating the 2042 function binding unnecessarily. 2043 2044 If it's passed a pointer(ish) value for v, it assumes it's a 2045 WASM function pointer and does _not_ perform any function 2046 binding, so this object's bindMode is irrelevant/ignored for 2047 such cases. 2048 2049 See the parent class's convertArg() docs for details on what 2050 exactly the 2nd and 3rd arguments are. 2051 */ 2052 convertArg(v,argv,argIndex){ 2053 let pair = this.singleton; 2054 if(!pair && this.isContext){ 2055 pair = this.contextMap(this.contextKey(argv,argIndex)); 2056 //FuncPtrAdapter.debugOut(this.name, this.signature, "contextKey() =",this.contextKey(argv,argIndex), pair); 2057 } 2058 if( 0 ){ 2059 FuncPtrAdapter.debugOut("FuncPtrAdapter.convertArg()",this.name, 2060 'signature =',this.signature, 2061 'transient ?=',this.transient, 2062 'pair =',pair, 2063 'v =',v); 2064 } 2065 if(pair && 2===pair.length && pair[0]===v){ 2066 /* We have already handled this function. */ 2067 return pair[1]; 2068 } 2069 if(v instanceof Function){ 2070 /* Install a WASM binding and return its pointer. */ 2071 //FuncPtrAdapter.debugOut("FuncPtrAdapter.convertArg()",this.name,this.signature,this.transient,v,pair); 2072 if(this.callProxy){ 2073 v = this.callProxy(v); 2074 } 2075 const fp = __installFunction(v, this.signature, this.isTransient); 2076 if(FuncPtrAdapter.debugFuncInstall){ 2077 FuncPtrAdapter.debugOut("FuncPtrAdapter installed", this, 2078 this.contextKey(argv,argIndex), '@'+fp, v); 2079 } 2080 if(pair){ 2081 /* Replace existing stashed mapping */ 2082 if(pair[1]){ 2083 if(FuncPtrAdapter.debugFuncInstall){ 2084 FuncPtrAdapter.debugOut("FuncPtrAdapter uninstalling", this, 2085 this.contextKey(argv,argIndex), '@'+pair[1], v); 2086 } 2087 try{ 2088 /* Because the pending native call might rely on the 2089 pointer we're replacing, e.g. as is normally the case 2090 with sqlite3's xDestroy() methods, we don't 2091 immediately uninstall but instead add its pointer to 2092 the scopedAlloc stack, which will be cleared when the 2093 xWrap() mechanism is done calling the native 2094 function. We're relying very much here on xWrap() 2095 having pushed an alloc scope. 2096 */ 2097 cache.scopedAlloc.pushFuncPtr(pair[1]); 2098 } 2099 catch(e){/*ignored*/} 2100 } 2101 pair[0] = arguments[0] || __NullPtr/*the original v*/; 2102 pair[1] = fp; 2103 } 2104 return fp; 2105 }else if(target.isPtr(v) || null===v || undefined===v){ 2106 if(pair && pair[1] && pair[1]!==v){ 2107 /* uninstall stashed mapping and replace stashed mapping with v. */ 2108 if(FuncPtrAdapter.debugFuncInstall){ 2109 FuncPtrAdapter.debugOut("FuncPtrAdapter uninstalling", this, 2110 this.contextKey(argv,argIndex), '@'+pair[1], v); 2111 } 2112 try{cache.scopedAlloc.pushFuncPtr(pair[1]);/*see notes above*/} 2113 catch(e){/*ignored*/} 2114 pair[0] = pair[1] = (v || __NullPtr); 2115 } 2116 return v || __NullPtr; 2117 }else{ 2118 throw new TypeError("Invalid FuncPtrAdapter argument type. "+ 2119 "Expecting a function pointer or a "+ 2120 (this.name ? this.name+' ' : '')+ 2121 "function matching signature "+ 2122 this.signature+"."); 2123 } 2124 }/*convertArg()*/ 2125 }/*FuncPtrAdapter*/; 2126 2127 /** If true, the constructor emits a warning. The intent is that 2128 this be set to true after bootstrapping of the higher-level 2129 client library is complete, to warn downstream clients that 2130 they shouldn't be relying on this implementation detail which 2131 does not have a stable interface. */ 2132 xArg.FuncPtrAdapter.warnOnUse = false; 2133 2134 /** If true, convertArg() will call FuncPtrAdapter.debugOut() when 2135 it (un)installs a function binding to/from WASM. Deinstallation 2136 of bindScope=transient bindings happens via scopedAllocPop() so 2137 will not be output. */ 2138 xArg.FuncPtrAdapter.debugFuncInstall = false; 2139 2140 /** Function used for debug output. */ 2141 xArg.FuncPtrAdapter.debugOut = debug; 2142 2143 /** 2144 List of legal values for the FuncPtrAdapter bindScope config 2145 option. 2146 */ 2147 xArg.FuncPtrAdapter.bindScopes = [ 2148 'transient', 'context', 'singleton', 'permanent' 2149 ]; 2150 2151 /** Throws if xArg.get(t) returns falsy. */ 2152 const __xArgAdapterCheck = 2153 (t)=>xArg.get(t) || toss("Argument adapter not found:",t); 2154 2155 /** Throws if xResult.get(t) returns falsy. */ 2156 const __xResultAdapterCheck = 2157 (t)=>xResult.get(t) || toss("Result adapter not found:",t); 2158 2159 /** 2160 Fetches the xWrap() argument adapter mapped to t, calls it, 2161 passing in all remaining arguments, and returns the result. 2162 Throws if t is not mapped to an argument converter. 2163 */ 2164 cache.xWrap.convertArg = 2165 (t, v, argv, argIndex)=> __xArgAdapterCheck(t)(v, argv, argIndex); 2166 /** 2167 Identical to convertArg() except that it does not perform 2168 an is-defined check on the mapping to t before invoking it. 2169 */ 2170 cache.xWrap.convertArgNoCheck = 2171 (t, v, argv, argIndex)=> xArg.get(t)(v, argv, argIndex); 2172 2173 /* Internal code de-duplifier. True if xWrap type id t is 2174 null or 'null'. */ 2175 const __typeIsNull = (t)=>(null===t || 'null'===t); 2176 2177 /** 2178 Fetches the xWrap() result adapter mapped to t, calls it, passing 2179 it v, and returns the result. Throws if t is not mapped to an 2180 argument converter. 2181 */ 2182 cache.xWrap.convertResult = 2183 (t,v)=>(__typeIsNull(t) ? v : (t ? __xResultAdapterCheck(t)(v) : undefined)); 2184 /** 2185 Identical to convertResult() except that it does not perform an 2186 is-defined check on the mapping to t before invoking it. 2187 */ 2188 cache.xWrap.convertResultNoCheck = 2189 (t,v)=>(__typeIsNull(t) ? v : (t ? xResult.get(t)(v) : undefined)); 2190 2191 /** 2192 Creates a wrapper for another function which converts the arguments 2193 of the wrapper to argument types accepted by the wrapped function, 2194 then converts the wrapped function's result to another form 2195 for the wrapper. 2196 2197 The first argument must be one of: 2198 2199 - A JavaScript function. 2200 - The name of a WASM-exported function. xGet() is used to fetch 2201 the exported function, which throws if it's not found. 2202 - A pointer into the indirect function table. e.g. a pointer 2203 returned from target.installFunction(). 2204 2205 It returns either the passed-in function or a wrapper for that 2206 function which converts the JS-side argument types into WASM-side 2207 types and converts the result type. 2208 2209 The second argument, `resultType`, describes the conversion for 2210 the wrapped functions result. A literal `null` or the string 2211 `'null'` both mean to return the original function's value as-is 2212 (mnemonic: there is "null" conversion going on). Literal 2213 `undefined` or the string `"void"` both mean to ignore the 2214 function's result and return `undefined`. Aside from those two 2215 special cases, the `resultType` value may be one of the values 2216 described below or any mapping installed by the client using 2217 xWrap.resultAdapter(). 2218 2219 If passed 3 arguments and the final one is an array, that array 2220 must contain a list of type names (see below) for adapting the 2221 arguments from JS to WASM. If passed 2 arguments, more than 3, 2222 or the 3rd is not an array, all arguments after the 2nd (if any) 2223 are treated as type names. i.e.: 2224 2225 ``` 2226 xWrap('funcname', 'i32', 'string', 'f64'); 2227 // is equivalent to: 2228 xWrap('funcname', 'i32', ['string', 'f64']); 2229 ``` 2230 2231 This function enforces that the given list of arguments has the 2232 same arity as the being-wrapped function (as defined by its 2233 `length` property) and it will throw if that is not the case. 2234 Similarly, the created wrapper will throw if passed a differing 2235 argument count. The intent of that strictness is to help catch 2236 coding errors in using JS-bound WASM functions earlier rather 2237 than laer. 2238 2239 Type names are symbolic names which map the arguments to an 2240 adapter function to convert, if needed, the value before passing 2241 it on to WASM or to convert a return result from WASM. The list 2242 of pre-defined names: 2243 2244 - `i8`, `i16`, `i32` (args and results): all integer conversions 2245 which convert their argument to an integer and truncate it to 2246 the given bit length. 2247 2248 - `*`, `**`, and `pointer` (args): are assumed to be WASM pointer 2249 values and are returned coerced to an appropriately-sized 2250 pointer value (i32 or i64). Non-numeric values will coerce to 0 2251 and out-of-range values will have undefined results (just as 2252 with any pointer misuse). 2253 2254 - `*` and `pointer` (results): aliases for the current 2255 WASM pointer numeric type. 2256 2257 - `**` (args): is simply a descriptive alias for the WASM pointer 2258 type. It's primarily intended to mark output-pointer arguments, 2259 noting that JS's view of WASM does not distinguish between 2260 pointers and pointers-to-pointers, so all such interpretation 2261 of `**`, as distinct from `*`, necessarily happens at the 2262 client level. 2263 2264 - `NumType*` (args): a type name in this form, where T is 2265 the name of a numeric mapping, e.g. 'int16' or 'double', 2266 is treated like `*`. 2267 2268 - `i64` (args and results): passes the value to BigInt() to 2269 convert it to an int64. This conversion will if bigIntEnabled 2270 is falsy. 2271 2272 - `f32` (`float`), `f64` (`double`) (args and results): pass 2273 their argument to Number(). i.e. the adapter does not currently 2274 distinguish between the two types of floating-point numbers. 2275 2276 - `number` (results): converts the result to a JS Number using 2277 Number(theValue). This is for result conversions only, as it's 2278 not possible to generically know which type of number to 2279 convert arguments to. 2280 2281 Non-numeric conversions include: 2282 2283 - `null` literal or `"null"` string (args and results): perform 2284 no translation and pass the arg on as-is. This is primarily 2285 useful for results but may have a use or two for arguments. 2286 2287 - `string` or `utf8` (args): has two different semantics in order 2288 to accommodate various uses of certain C APIs 2289 (e.g. output-style strings)... 2290 2291 - If the arg is a JS string, it creates a _temporary_ 2292 UTF-8-encoded C-string to pass to the exported function, 2293 cleaning it up before the wrapper returns. If a long-lived 2294 C-string pointer is required, that requires client-side code 2295 to create the string then pass its pointer to the function. 2296 2297 - Else the arg is assumed to be a pointer to a string the 2298 client has already allocated and it's passed on as 2299 a WASM pointer. 2300 2301 - `string` or `utf8` (results): treats the result value as a 2302 const C-string, encoded as UTF-8, copies it to a JS string, 2303 and returns that JS string. 2304 2305 - `string:dealloc` or `utf8:dealloc` (results): treats the result 2306 value as a non-const UTF-8 C-string, ownership of which has 2307 just been transfered to the caller. It copies the C-string to a 2308 JS string, frees the C-string using dealloc(), and returns the 2309 JS string. If such a result value is NULL, the JS result is 2310 `null`. Achtung: when using an API which returns results from a 2311 specific allocator, e.g. `my_malloc()`, this conversion _is not 2312 legal_. Instead, an equivalent conversion which uses the 2313 appropriate deallocator is required. For example: 2314 2315 ```js 2316 target.xWrap.resultAdapter('string:my_free',(i)=>{ 2317 try { return i ? target.cstrToJs(i) : null; } 2318 finally{ target.exports.my_free(i); } 2319 }; 2320 ``` 2321 2322 - `json` (results): treats the result as a const C-string and 2323 returns the result of passing the converted-to-JS string to 2324 JSON.parse(). Returns `null` if the C-string is a NULL pointer. 2325 2326 - `json:dealloc` (results): works exactly like `string:dealloc` but 2327 returns the same thing as the `json` adapter. Note the 2328 warning in `string:dealloc` regarding matching allocators and 2329 deallocators. 2330 2331 The type names for results and arguments are validated when 2332 xWrap() is called and any unknown names will trigger an 2333 exception. 2334 2335 Clients may map their own result and argument adapters using 2336 xWrap.resultAdapter() and xWrap.argAdapter(), noting that not all 2337 type conversions are valid for both arguments _and_ result types 2338 as they often have different memory ownership requirements. 2339 2340 Design note: the ability to pass in a JS function as the first 2341 argument is of relatively limited use, primarily for testing 2342 argument and result converters. JS functions, by and large, will 2343 not want to deal with C-type arguments. 2344 2345 TODOs: 2346 2347 - Figure out how/whether we can (semi-)transparently handle 2348 pointer-type _output_ arguments. Those currently require 2349 explicit handling by allocating pointers, assigning them before 2350 the call using poke(), and fetching them with 2351 peek() after the call. We may be able to automate some 2352 or all of that. 2353 2354 - Figure out whether it makes sense to extend the arg adapter 2355 interface such that each arg adapter gets an array containing 2356 the results of the previous arguments in the current call. That 2357 might allow some interesting type-conversion feature. Use case: 2358 handling of the final argument to sqlite3_prepare_v2() depends 2359 on the type (pointer vs JS string) of its 2nd 2360 argument. Currently that distinction requires hand-writing a 2361 wrapper for that function. That case is unusual enough that 2362 abstracting it into this API (and taking on the associated 2363 costs) may well not make good sense. 2364 */ 2365 target.xWrap = function callee(fArg, resultType, ...argTypes){ 2366 if(3===arguments.length && Array.isArray(arguments[2])){ 2367 argTypes = arguments[2]; 2368 } 2369 if(target.isPtr(fArg)){ 2370 fArg = target.functionEntry(fArg) 2371 || toss("Function pointer not found in WASM function table."); 2372 } 2373 const fIsFunc = (fArg instanceof Function); 2374 const xf = fIsFunc ? fArg : target.xGet(fArg); 2375 if(fIsFunc) fArg = xf.name || 'unnamed function'; 2376 if(argTypes.length!==xf.length){ 2377 __argcMismatch(fArg, xf.length) /* throws */; 2378 } 2379 if( 0===xf.length && __typeIsNull(resultType) ){ 2380 /* Func taking no args with an as-is return. We don't need a wrapper. */ 2381 return xf; 2382 } 2383 /*Verify the arg type conversions are valid...*/; 2384 __xResultAdapterCheck(resultType); 2385 for(const t of argTypes){ 2386 if(t instanceof AbstractArgAdapter){ 2387 xArg.set(t, (v, argv, argIndex)=> t.convertArg(v, argv, argIndex)); 2388 } 2389 else __xArgAdapterCheck(t); 2390 } 2391 const cxw = cache.xWrap; 2392 if(0===xf.length){ 2393 // No args to convert, so we can create a simpler wrapper... 2394 return (...args)=>(args.length 2395 ? __argcMismatch(fArg, xf.length) 2396 : cxw.convertResult(resultType, xf.call(null))); 2397 } 2398 const resConverter = 2399 /* Result conversion: null/'null'==> do nothing, 2400 undefined==>void, else do the installed conversion */ 2401 __typeIsNull(resultType) 2402 ? null 2403 : (resultType 2404 ? __xResultAdapterCheck(resultType) 2405 : undefined); 2406 2407 return function(...args) { 2408 if( args.length !== xf.length ) __argcMismatch(fArg, xf.length); 2409 const scope = target.scopedAllocPush(); 2410 try { 2411 /* 2412 Maintenance reminder re. arguments passed to convertArg(): 2413 The public interface of argument adapters is that they take 2414 ONE argument and return a (possibly) converted result for 2415 it. The passing-on of arguments after the first is an 2416 internal implementation detail for the sake of 2417 AbstractArgAdapter, and not to be relied on or documented 2418 for other cases. The fact that this is how 2419 AbstractArgAdapter.convertArgs() gets its 2nd+ arguments, 2420 and how FuncPtrAdapter.contextKey() gets its args, is also 2421 an implementation detail and subject to change. i.e. the 2422 public interface of 1 argument is stable. The fact that any 2423 arguments may be passed in after that one, and what those 2424 arguments are, is _not_ part of the public interface and is 2425 _not_ stable. 2426 2427 Maintenance reminder: the Ember framework modifies the core 2428 Array type, breaking for-in loops: 2429 2430 https://sqlite.org/forum/forumpost/`b549992634b55104` 2431 */ 2432 let i = 0; 2433 if( callee.debug ){ 2434 debug('xWrap() preparing: resultType ', resultType, 2435 'xf', xf, 2436 'argTypes', argTypes, 'args', args); 2437 } 2438 for(; i < args.length; ++i){ 2439 args[i] = cxw.convertArgNoCheck(argTypes[i], args[i], args, i); 2440 } 2441 if( callee.debug ){ 2442 debug('xWrap() calling: resultType ', resultType, 2443 'xf', xf,'argTypes', argTypes, 'args', args); 2444 } 2445 const rawRes = xf.apply(null, args); 2446 return resConverter ? resConverter(rawRes) : rawRes; 2447 }finally{ 2448 target.scopedAllocPop(scope); 2449 } 2450 }; 2451 }/*xWrap()*/; 2452 2453 /** 2454 Internal impl for xWrap.resultAdapter() and argAdapter(). 2455 2456 func = one of xWrap.resultAdapter or xWrap.argAdapter. 2457 2458 argc = the number of args in the wrapping call to this 2459 function. 2460 2461 typeName = the first arg to the wrapping function. 2462 2463 adapter = the second arg to the wrapping function. 2464 2465 modeName = a descriptive name of the wrapping function for 2466 error-reporting purposes. 2467 2468 xcvPart = one of xResult or xArg. 2469 2470 This acts as either a getter (if 1===argc) or setter (if 2471 2===argc) for the given adapter. Returns func on success or 2472 throws if (A) called with 2 args but adapter is-not-a Function or 2473 (B) typeName is not a string or (C) argc is not one of (1, 2). 2474 */ 2475 const __xAdapter = function(func, argc, typeName, adapter, modeName, xcvPart){ 2476 if('string'===typeof typeName){ 2477 if(1===argc) return xcvPart.get(typeName); 2478 else if(2===argc){ 2479 if(!adapter){ 2480 xcvPart.delete(typeName); 2481 return func; 2482 }else if(!(adapter instanceof Function)){ 2483 toss(modeName,"requires a function argument."); 2484 } 2485 xcvPart.set(typeName, adapter); 2486 return func; 2487 } 2488 } 2489 toss("Invalid arguments to",modeName); 2490 }; 2491 2492 /** 2493 Gets, sets, or removes a result value adapter for use with 2494 xWrap(). If passed only 1 argument, the adapter function for the 2495 given type name is returned. If the second argument is explicit 2496 falsy (as opposed to defaulted), the adapter named by the first 2497 argument is removed. If the 2nd argument is not falsy, it must be 2498 a function which takes one value and returns a value appropriate 2499 for the given type name. The adapter may throw if its argument is 2500 not of a type it can work with. This function throws for invalid 2501 arguments. 2502 2503 Example: 2504 2505 ``` 2506 xWrap.resultAdapter('twice',(v)=>v+v); 2507 ``` 2508 2509 Result adapters MUST NOT use the scopedAlloc() family of APIs to 2510 allocate a result value. xWrap()-generated wrappers run in the 2511 context of scopedAllocPush() so that argument adapters can easily 2512 convert, e.g., to C-strings, and have them cleaned up 2513 automatically before the wrapper returns to the caller. Likewise, 2514 if a _result_ adapter uses scoped allocation, the result will be 2515 freed before the wrapper returns, leading to chaos and undefined 2516 behavior. 2517 2518 When called as a setter, this function returns itself. 2519 */ 2520 target.xWrap.resultAdapter = function f(typeName, adapter){ 2521 return __xAdapter(f, arguments.length, typeName, adapter, 2522 'resultAdapter()', xResult); 2523 }; 2524 2525 /** 2526 Functions identically to xWrap.resultAdapter() but applies to 2527 call argument conversions instead of result value conversions. 2528 2529 xWrap()-generated wrappers perform argument conversion in the 2530 context of a scopedAllocPush(), so any memory allocation 2531 performed by argument adapters really, really, really should be 2532 made using the scopedAlloc() family of functions unless 2533 specifically necessary. For example: 2534 2535 ``` 2536 xWrap.argAdapter('my-string', function(v){ 2537 return ('string'===typeof v) 2538 ? myWasmObj.scopedAllocCString(v) : null; 2539 }; 2540 ``` 2541 2542 Contrariwise, _result_ adapters _must not_ use scopedAlloc() to 2543 allocate results because they would be freed before the 2544 xWrap()-created wrapper returns. 2545 2546 It is perfectly legitimate to use these adapters to perform 2547 argument validation, as opposed (or in addition) to conversion. 2548 When used that way, they should throw for invalid arguments. 2549 */ 2550 target.xWrap.argAdapter = function f(typeName, adapter){ 2551 return __xAdapter(f, arguments.length, typeName, adapter, 2552 'argAdapter()', xArg); 2553 }; 2554 2555 target.xWrap.FuncPtrAdapter = xArg.FuncPtrAdapter; 2556 2557 /** 2558 Functions like xCall() but performs argument and result type 2559 conversions as for xWrap(). The first, second, and third 2560 arguments are as documented for xWrap(), except that the 3rd 2561 argument may be either a falsy value or empty array to represent 2562 nullary functions. The 4th+ arguments are arguments for the call, 2563 with the special case that if the 4th argument is an array, it is 2564 used as the arguments for the call. Returns the converted result 2565 of the call. 2566 2567 This is just a thin wrapper around xWrap(). If the given function 2568 is to be called more than once, it's more efficient to use 2569 xWrap() to create a wrapper, then to call that wrapper as many 2570 times as needed. For one-shot calls, however, this variant is 2571 simpler. 2572 */ 2573 target.xCallWrapped = function(fArg, resultType, argTypes, ...args){ 2574 if(Array.isArray(arguments[3])) args = arguments[3]; 2575 return target.xWrap(fArg, resultType, argTypes||[]).apply(null, args||[]); 2576 }; 2577 2578 /** 2579 This function is ONLY exposed in the public API to facilitate 2580 testing. It should not be used in application-level code, only 2581 in test code. 2582 2583 Expects to be given (typeName, value) and returns a conversion 2584 of that value as has been registered using argAdapter(). 2585 It throws if no adapter is found. 2586 2587 ACHTUNG: the adapter may require that a scopedAllocPush() is 2588 active and it may allocate memory within that scope. It may also 2589 require additional arguments, depending on the type of 2590 conversion. 2591 */ 2592 target.xWrap.testConvertArg = cache.xWrap.convertArg; 2593 2594 /** 2595 This function is ONLY exposed in the public API to facilitate 2596 testing. It should not be used in application-level code, only 2597 in test code. 2598 2599 Expects to be given (typeName, value) and returns a conversion 2600 of that value as has been registered using resultAdapter(). 2601 It throws if no adapter is found. 2602 2603 ACHTUNG: the adapter may allocate memory which the caller may need 2604 to know how to free. 2605 */ 2606 target.xWrap.testConvertResult = cache.xWrap.convertResult; 2607 2608 return target; 2609 }; 2610 2611 //#if not defined omit-yawl 2612 /** 2613 yawl (Yet Another Wasm Loader) provides very basic wasm loader. 2614 It requires a config object: 2615 2616 - `uri`: required URI of the WASM file to load. 2617 2618 - `fetchOpt`: Optional object to pass as the second argument to 2619 `fetch(config.uri,X)`. This function always includes 2620 `{credentials:'same-origin'}` unless the caller provides a 2621 different credentials value. 2622 2623 - `onload(loadResult)`: optional on-success callback. Its argument 2624 is an object described in more detail below. 2625 2626 - `imports`: optional imports object for 2627 WebAssembly.instantiate[Streaming](). The default is an empty 2628 set of imports. If the module requires any imports, this object 2629 must include them. 2630 2631 - `wasmUtilTarget`: optional object suitable for passing to 2632 WhWasmUtilInstaller(). If set, it gets passed to that function 2633 before the returned promise resolves. This function sets several 2634 properties on it before passing it on to that function (which 2635 sets many more): 2636 2637 - `module`, `instance`: the properties from the 2638 instantiate[Streaming]() result. 2639 2640 - If `instance.exports.memory` is _not_ set then it requires that 2641 `config.imports.env.memory` be set (else it throws), and 2642 assigns that to `wasmUtilTarget.memory`. 2643 2644 - If `wasmUtilTarget.alloc` is not set and 2645 `instance.exports.malloc` is, it installs 2646 `wasmUtilTarget.alloc()` and `wasmUtilTarget.dealloc()` 2647 wrappers for the exports' `malloc` and `free` functions 2648 if exports.malloc exists. 2649 2650 It returns a function which, when called, initiates loading of the 2651 module and returns a Promise. When that Promise resolves, it calls 2652 the `config.onload` callback (if set) and passes it `(loadResult)`, 2653 where `loadResult` is derived from the result of 2654 WebAssembly.instantiate[Streaming](), an object in the form: 2655 2656 ``` 2657 { 2658 module: a WebAssembly.Module, 2659 instance: a WebAssembly.Instance, 2660 config: the config arg to this function 2661 } 2662 ``` 2663 2664 The resulting Promise resolves to that same value. 2665 2666 Error handling for the returned function is up to the caller, who 2667 may attach a `catch()` call to its returned Promise. 2668 */ 2669 WhWasmUtilInstaller.yawl = function yawl(config){ 2670 //#if not esm 2671 'use strict'; 2672 //#/if 2673 const wfetch = ()=>fetch( 2674 config.uri, Object.assign(Object.create(null),{ 2675 credentials: 'same-origin' 2676 }, config.fetchOpt) 2677 ); 2678 const wui = this; 2679 const finalThen = function(arg){ 2680 //log("finalThen()",arg); 2681 if(config.wasmUtilTarget){ 2682 const toss = (...args)=>{throw new Error(args.join(' '))}; 2683 const tgt = config.wasmUtilTarget; 2684 tgt.module = arg.module; 2685 tgt.instance = arg.instance; 2686 //tgt.exports = tgt.instance.exports; 2687 if(!tgt.instance.exports.memory){ 2688 /** 2689 WhWasmUtilInstaller requires either tgt.exports.memory 2690 (exported from WASM) or tgt.memory (JS-provided memory 2691 imported into WASM). 2692 */ 2693 tgt.memory = config?.imports?.env?.memory 2694 || toss("Missing 'memory' object!"); 2695 } 2696 if(!tgt.alloc && arg.instance.exports.malloc){ 2697 const exports = arg.instance.exports; 2698 tgt.alloc = function(n){ 2699 return exports.malloc(n) || toss("Allocation of",n,"bytes failed."); 2700 }; 2701 tgt.dealloc = function(m){m && exports.free(m)}; 2702 } 2703 wui(tgt); 2704 } 2705 arg.config = config; 2706 if(config.onload instanceof Function) config.onload(arg); 2707 return arg /* for any then() handler attached to 2708 yetAnotherWasmLoader()'s return value */; 2709 }; 2710 const loadWasm = WebAssembly.instantiateStreaming 2711 ? ()=>WebAssembly 2712 .instantiateStreaming(wfetch(), config.imports||{}) 2713 .then(finalThen) 2714 : ()=> wfetch()// Safari < v15 2715 .then(response => response.arrayBuffer()) 2716 .then(bytes => WebAssembly.instantiate(bytes, config.imports||{})) 2717 .then(finalThen) 2718 ; 2719 return loadWasm; 2720 }.bind(WhWasmUtilInstaller)/*yawl()*/; 2721 //#/if not defined omit-yawl 2722 //#if esm 2723 //# if not no-export 2724 //# if amalgamation 2725 export {WhWasmUtilInstaller}; 2726 //# elif not defined no-export-default 2727 export default WhWasmUtilInstaller; 2728 //# /if 2729 //# /if 2730 //#else if not lexical-scoped 2731 globalThis.WhWasmUtilInstaller = WhWasmUtilInstaller; 2732 //#/if 2733 //#savepoint rollback 2734 //#@ pop policy delimiter