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/jaccwabyt/jaccwabyt.md
# 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 / jaccwabyt / jaccwabyt.md`
1259 lines ยท 44731 bytes Raw Blame History Rendered
1 Jaccwabyt ๐
2 ====================
3
4 **Jaccwabyt**: _JavaScript โ C Struct Communication via WASM Byte
5 Arrays_[^the-name]
6
7 Forewarning: if this is not being read from [its canonical home][src]
8 then some of the markdown formatting and links will not work.
9
10 [src]: https://fossil.wanderinghorse.net/r/c-pp
11 [^the-name]: Getting that name to work required some acrobatics, but
12 the result was worth it.
13
14
15 Table of Contents
16 ====================
17
18 - [Brief Demo](#demo)
19 - [Architecture and Mental Model](#arch)
20 - [Struct Descriptors](#descriptors)
21 - [Type signatures](#type-signatures)
22 - [Type "s"](#type-s)
23 - [Type "p" vs. "P"](#type-p)
24 - [Property Access Adaptors](#adaptors)
25 - Class APIs
26 - [StructBinderFactory][]: Environment Configuration
27 - [StructBinder][]: Struct Codec Generator
28 - [StructType][]: Struct Codec
29 - [Constructor][StructCtor]
30 - [Struct Instances][StructInstance]
31 - Using the Classes
32 - [StructBinder](#using-StructBinder)
33 - [StructCtor](#using-StructCtor)
34 - [StructType Instances](#using-StructInstance)
35 - [Lifecycle and Memory Management](#lifecycle)
36 - [Nested Structs](#nested-structs)
37 - [64-bit WASM](#64bit)
38 - Appendices
39 - [A: Limitations, TODOs, etc.](#appendix-a)
40 - [B: Build](#appendix-b)
41 - [D: Debug Info](#appendix-d)
42 - [G: Generating Struct Descriptors](#appendix-g)
43 - [L: License](#appendix-l)
44
45 -----
46
47 Welcome to Jaccwabyt, a JavaScript API which creates bindings for
48 WASM-compiled C structs, permitting two-way interchange of WASM-hosted
49 struct state with very little client-side friction.
50
51 (If that means nothing to you, neither will the rest of this page!)
52
53 To the best of its creator's fallible knowledge, Jaccwabyt is the only
54 library of its kind (as of 2025-11). It is a core component of the
55 [SQLite project's JS/WASM bindings](https://sqlite.org/wasm), where it
56 is binds JS-side virtual filesystems and virtual database tables to
57 WASM, and is known to work reliably.
58
59 Formalities:
60
61 - Canonical source code home: [][src]
62 - License: [SQLite Blessing](#appendix-l)
63 - Maintainer: [Stephan Beal](https://wanderinghorse.net)
64
65 -----
66
67 Brief Usage Overview
68 =============================
69
70 Client-side, Jaccwabyt looks like...
71
72 >
73 ```js
74 // 1. Initialize for the current WASM environment. Needed once
75 // per app session.
76 const StructBinder = StructBinderFactory({
77 memberPrefix: "$",
78 ... config info from the WASM environment
79 });
80
81 // 2. Convert a JSON-friendly struct descriptor into
82 // a JS constructor. Needed once per struct type.
83 const StructCtor = StructBinder( structDescriptorObject );
84
85 // 3. Instiate an instance which wraps a WASM-hosted instance.
86 const s = new StructCtor( funcReturningAWasmPointer() );
87
88 // 4. Access the C-side members...
89 s.$x = 3; // Write to WASM-side Struct::x
90 console.debug(s.$y); // Read from WASM-side Struct::y
91 console.debug(s.pointer); // WASM pointer value
92
93 // 5. Clean up (important!)
94 s.dispose(); // Memory ownership is configurable.
95 // s.pointer is now falsy
96 ```
97
98 -----
99
100 Architecture and Mental Model
101 =============================
102
103 Jaccwabyt is made up of several layers:
104
105 - [StructBinderFactory][] takes a configuration describing the current
106 WASM environment, e.g. Emscripten or WASI-SDK. Its result is...
107 - [StructBinder][] converts JSON-format struct descriptors into...
108 - [StructType][] are constructors for...
109 - [StructInstance][] is a colloquial term for StructType-derived
110 objects.
111
112 In graphics, it looks something like:
113
114 ```pikchr center
115 BSBF: box "StructBinderFactory" fit fill lightblue
116 BSB: box same "StructBinder" fit at 0.75 e of 0.9 s of BSBF.c
117 BSM: box rad 0.4*boxht "JSON-format C Structs" fit fill lightblue at 1.5s of BSBF
118 BST: box same "StructType" fit at 1.5 e of BSBF
119 BSC: box same "Struct" "Ctor" fit at 1.75 s of BST
120 BSI: box same "Struct" "Instances" fit at 1.25 right of BSB.e
121 BC: box same at 0.25 right of 1.6 e of BST "C Structs" fit fill lightgrey
122
123 arrow -> from BSM.n to BSB.sw "Input" aligned above dotted
124 arrow -> from BSBF.s to BSB.nw "Generates" aligned above
125 arrow -> from BSB.n to BST.sw "Generates" aligned above
126 arrow -> from BSB.s to BSC.nw "Generates" aligned below
127 arrow -> from BSC.ne to BSI.s "Constructs" aligned below
128 arrow <-> from BSI.e to BC.s dotted "WASM heap" aligned below
129 arrow -> from BST.e to BC.w dotted "Mirrors Struct" aligned above "Model From" aligned below
130 arrow -> from BST.s to BSC.n "Prototype of" aligned above
131 ```
132
133
134 -----
135
136
137 Struct Descriptors
138 ====================
139
140 Before making use of Jaccwabyt we need so-called descriptors for C
141 structs, JSON-friendly objects which describe their memory layout.
142 Jaccwabyt converts these into codecs for reading and writing WASM-side
143 representations of instances of those structs.
144
145 For example, given this C struct:
146
147 >
148 ```c
149 // C-side:
150 struct MyStruct {
151 int member1;
152 void * member2;
153 int64_t member3;
154 };
155 ```
156
157 Its JSON-format description might (depending on the build environment
158 and target) look like:
159
160 >
161 ```json
162 {
163 "name": "MyStruct",
164 "sizeof": 16,
165 "members": {
166 "member1": {"offset": 0, "sizeof": 4, "signature": "i"},
167 "member2": {"offset": 4, "sizeof": 4, "signature": "p"},
168 "member3": {"offset": 8, "sizeof": 8, "signature": "j"}
169 }
170 }
171 ```
172
173 Forewarning: these data _must_ match up with the C-side definition of
174 the struct (if any), noting that padding and members not exposed to
175 Jaccwabyt must be accounted for in the offsets. See [](#appendix-g)
176 for one way to easily generate these from C code.
177
178 Every struct must have a `sizeof`[^sizeof]. The `name` is
179 required as well but it may optionally be passed as the first argument
180 to `StructBinder(structName,structDescriptor)`. The `name` property
181 represents the member's symbolic name, typically (but not necessarily)
182 its native name.
183
184 [^sizeof]: Though we _could_ calculate the sizeof based on the list of
185 members, we don't. Actually, we do, then we throw an exception if
186 the values don't match up.
187
188 Abstractly speaking, a struct descriptor in an object with the
189 properties `sizeof`, `offset`, and either `signature` _or_
190 `members`. `offset` is optional only in the top-most object of a struct
191 description. Every sub-object (a.k.a. member descriptor object)
192 requires the `offset` property.
193
194
195 Member descriptor objects are those in the `members` property:
196
197 `"members": {"memberName": {...member descriptor...}, ...}`
198
199 A struct descriptor which has a `members` object represents a nested
200 struct, the interior of which follows the same struct descriptor
201 format as a top-level struct except that nested structs require an
202 `offset` property.
203
204 Each entry in a struct/member descriptor object maps the member's
205 name to its low-level layout and other metadata:
206
207 - `offset` (Number)
208 The byte offset from the start of the struct, as reported by C's
209 `offsetof()` feature. For nested structs' members, this value is
210 relative to the nested struct, not the parent struct.
211 - `sizeof` (Number)
212 As reported by C's `sizeof()`.
213 - `signature` (String)
214 A type-id signature for this member. See [](#type-signatures).
215 - `readOnly` (bool=false)
216 Optional boolean. If set to truthy, the binding layer will throw if
217 JS code tries to set that property.
218 - `zeroOnDispose` (bool=false)
219 If truthy, then the library will zero out the memory of instances of
220 this struct when their `dispose()` method is called. Because
221 `StructType.dispose()` does not free instances which wrap
222 externally-provided memory, those instances are not wiped when
223 disposed (doing so would likely interfere with other users of that
224 memory). (There is no need for a `zeroOnAlloc` counterpart because
225 newly-allocated instances are always zero-filled for sanity's sake.)
226 This option has no effect on [nested structs](#nested-structs)
227 because they are implemented as non-owning pointers to an offset
228 within their containing struct's memory. Disposing an outer struct
229 with this flag will _de facto_ also wipe the sub-structs.
230 - `members` (Object)
231 This object describes the individual struct members, mapping their
232 names to a member descriptor object. `members` gets processed
233 recursively and `signature` is illegal if `members` is set. Any
234 member with its own `members` property is a
235 [nested-struct](#nested-structs) - see that section for details.
236 - `name`
237 Is usually optional, and is always optional in `members` entries
238 because their names are conveniently derived from their containing
239 object. `name` must be provided only for the top-most struct. The
240 intent is that `name` maps to the member's property name and that
241 `structName` optionally be set for nested structs (it will be
242 derived from the name if it's not set).
243 - `structName`
244 Optional descriptive name, possibly distinct from the `name`,
245 primarily used for nested structs. The intent is that this be some
246 form of the struct type's name, optionally fully-qualified with
247 the containing structs' names.
248 - `autoCalcSizeOffset` (bool=false)
249 A "very nearly undocumented back door" which tells Jaccwabyt to
250 automatically calculate member sizeofs and offsets for this struct
251 and its sub-structs. This is provided _soley_ as a convenience to
252 Jaccwabyt's own developer in testing using ad hoc JS structs which
253 have no genuine C counterparts. This _must not_ be used with genuine
254 C structs because it cannot account for padding or native members
255 which are not exposed via the struct descriptor. It _is_ safe (and
256 terribly convenient) to use when there is no native counterpart, but
257 genuine use cases for such a thing are probably limited to
258 Jaccwabyt's own testing.
259
260 The order of the `members` entries is not important: their memory
261 layout is determined by their `offset` and `sizeof` members. The
262 `name` property is technically optional, but one of the steps in the
263 binding process requires that either it be passed an explicit name or
264 there be one in the struct descriptor. The names of the `members`
265 entries need not match their C counterparts. Project conventions may
266 call for giving them different names in the JS side and the
267 [StructBinderFactory][] can be configured to automatically add a
268 prefix and/or suffix to their names.
269
270
271 Type Signatures
272 --------------------
273
274 Struct descriptor member `signature` describes the data type of each
275 member, and uses an extended variant of the format used by
276 Emscripten's `addFunction()`. A signature for a non-function-pointer
277 member, or function pointer member which is to be modelled as an
278 opaque pointer, is a single letter. A signature for a function pointer
279 may also be modelled as a series of letters describing the call
280 signature.
281
282 Signatures in the form `x(...)` denote function-pointer members and
283 the form `x` denotes non-function members. Functions with no arguments
284 use the form `x()`.
285
286 The supported signature letters are:
287
288 - **`v`** = `void` (only used as return type for function pointer members)
289 - **`i`** = `int32` (4 bytes)
290 - **`j`** = `int64` (8 bytes) is only really usable if this code is built
291 with BigInt support (e.g. using the Emscripten `-sWASM_BIGINT` build
292 flag). Without that, this API may throw when encountering the `j`
293 signature entry.
294 - **`f`** = `float` (4 bytes)
295 - **`d`** = `double` (8 bytes)
296 - **`c`** = `int8` (1 byte) char - see notes below!
297 - **`C`** = `uint8` (1 byte) unsigned char - see notes below!
298 - **`p`** = `int32` (4 bytes) or `int64` (8 bytes). [Described
299 below](#type-p).
300 - **`P`** = Like `p` but with extra handling for [StructType][]
301 pointers. [Described below](#type-p).
302 - **`s`** = like `p` but is a _hint_ that it's a pointer to a string.
303 [Described below](#type-s).
304
305 Noting that:
306
307 - **All of these types are numeric**. Attempting to set any
308 struct-bound property to a non-numeric value will trigger an
309 exception except in cases explicitly noted otherwise.
310 - **"Char" types**: WASM does not define an `int8` type, nor does its
311 JS representation distinguish between signed and unsigned. This API
312 treats `c` as `int8` and `C` as `uint8` for purposes of getting and
313 setting values when using the `DataView` class. It is _not_
314 recommended that client code use these types in new WASM-capable
315 code, but they were added for the sake of binding some immutable
316 legacy code to WASM.
317
318
319
320 ### Type `"s"` (C-string)
321
322 Type ID "s" is a special case of ["p"](#type-p). In some limited
323 contexts, described below, the library will treat them as C-strings,
324 with the caveat that that such algorithms must, for lack of
325 information to the contrary, assume that the encoding is UTF-8 and
326 that the pointer's member is NUL-terminated. If that is _not_ the case
327 for a given string member, do not use "s", use "p" instead and do any
328 string handling yourself.
329
330 The following APIs handle "s" specially:
331
332 - [StructType][].`setMemberCString()`
333 - [StructType][].`memberToJsString()`
334
335 [StructType][].`memberIsString()` returns true if a given member is
336 legal for those methods, and those methods both throw if
337 `memberIsString()` is false.
338
339
340
341 ### Type `"p"` (pointer) vs `"P"` (pointer plus)
342
343 The signature letter `p` means "pointer", which, in WASM, means either
344 int32 or [int64][64bit]. A capital `P` changes the semantics of plain
345 member pointers (but not, as of this writing, function pointer
346 members) as follows:
347
348 When a `P`-type member is set via `myStruct.x=y`, if
349 [`(y instanceof StructType)`][StructType] then the value of
350 `y.pointer` is stored in `myStruct.x`. If `y` is neither a pointer nor a
351 [StructType][], an exception is triggered regardless of whether `p` or
352 `P` is used. `P` has no further effect when fetching a property, only
353 when setting.
354
355
356
357 Property Access Adaptors
358 -------------------------------
359
360 Adaptors, an optional part of a [struct descriptor](#descriptors),
361 provide a way to customize the result of reading and writing WASM-side
362 struct properties. This enables transparent installation of custom
363 "JS-to-WASM" and "WASM-to-JS" conversions for struct properties.
364
365 The following optional [struct descriptor](#descriptors) properties
366 may be used on [Object-type entries of the `members`
367 property](#member-descr):
368
369 - `getter` (Function)
370 When fetching this struct member, this getter is passed `(K,V)`,
371 where `K` is the struct member's name, _without_ any
372 [prefix/suffix](#member-prefix), and `V` is the _native_
373 value. `get()`'s return value becomes the value of the property
374 access operation, enabling custom "native-to-JS" conversions. In the
375 context of the getter call, "this" is the object upon which the get
376 is being performed.
377 If the member is a [nested struct](#nested-structs), the value
378 passed to the getter is a proxy object which provides access to that
379 struct's own members, a subset of the parent object's memory.
380
381 - `getter` (String)
382 The JSON-friendly form of `getter`, this maps a client-provided key
383 to a getter function. For this to work, the key used here must have
384 been registered with [StructBinder][].`adaptGetter('getterKey',func)`
385 before the struct descriptor is processed. The key used there is
386 independent of any struct property names.
387
388 - `setter` (Function)
389 When setting this struct member, this setter is passed `(K,V)`,
390 where `K` is the struct member's name, _without_ any
391 [prefix/suffix](#member-prefix), and `V` is the _JS_ value the
392 property is being assigned to. `set()`'s return value gets assigned
393 to the _native_ struct member. Thus `set()` _must_ return an
394 appropriate numeric value and may perform arbitrary "JS-to-native"
395 conversions. In the context of the setter call, "this" is the
396 object upon which the set is being performed.
397 `setter` is not currently legal for writing to a [nested
398 struct](#nested-structs) member.
399
400 - `setter` (String)
401 The JSON-friendly form of `setter`, this works the same as the
402 string form of `getter` except that the registration function is
403 [StructBinder][].`adaptSetter('setterKey',func)`.
404
405
406 Getter and setter implementations ***MUST NOT*** try to look up that
407 struct property using Jaccwabyt's property interceptor or they will
408 cause endless recursion and a stack overflow.
409
410 A rather contrived example...
411
412 First, map getter/setter names to functions for use in the JSON
413 descriptors:
414
415 >
416 ```js
417 MyStructBinder.adaptGetter('truncateFloat',(k,v)=>v | 0);
418 MyStructBinder.adaptSetter('parseFloat',(k,v)=>{
419 v = parseFloat(v);
420 return isNaN(v) ? 0 : v;
421 });
422 ```
423
424 > Sidebar: most implementations will not need the key but it is
425 provided for cases which want to share an implementation across keys
426 and dispatch on their name. The key should arguably be the second
427 argument, allowing it to be elided from most implementations, but
428 experimentation with that caused more confusion than it solved.
429
430 With that in place, we can map those to members using something
431 like:
432
433 >
434 ```js
435 const MyStruct = MyStructBinder({
436 ...
437 memberPrefix: "$",
438 members: {
439 foo: {
440 ...
441 signature: "d", // => double
442 getter: "truncateFloat",
443 setter: "parseFloat"
444 }
445 }
446 });
447 ```
448
449 Then fetching `x.$foo` will always return a 32-bit-truncated int and
450 assigning `x.$foo` will coerce its arguments to a number, making
451 `x.$foo="3"` both legal and well-behaved ("feature or bug?" is for the
452 implementor to decide).
453
454 > Sidebar: the test app demonstrates a struct member adaptor, for
455 installing proxies for [nested structs](#nested-structs), but is not
456 yet part of the public API. It also demonstrates how to plug
457 adaptors into the struct descriptor "inline", but that's also not
458 yet part of the public API.
459
460 -----
461
462 Classes and APIs
463 ====================
464
465
466 StructBinderFactory
467 -------------------
468
469 The top-most function of the API, from which all other functions and
470 types are generated. It accepts a configuration object to customize it
471 for a given WASM environment and returns a [StructBinder][] factory
472 function.
473
474 **Signature:**
475
476 * `Function StructBinderFactory(object configOptions)`
477
478 **Configuration Options:**
479
480 - `pointerSize` (integer)
481 Specify the WASM pointer size as `4` (32-bit) or `8` (64-bit). Any
482 other truthy value triggers an exception. If omitted, it guesses the
483 size by allocating 1 byte, checking the result type, and
484 deallocating it.
485
486 - `heap` (WebAssembly.Memory | Function)
487 Must be either a `WebAssembly.Memory` instance representing the WASM
488 heap OR a function returning an `Int8Array` or `Uint8Array` view of
489 the WASM heap.
490
491 - `alloc` (Function)
492 Function semantically compatible with C's `malloc(3)`. Passed the
493 number of bytes to allocate and returns a pointer. On failure,
494 returns `0` (32-bit) or `0n` (64-bit) or throws an exception. Must
495 use the same heap as `heap`.
496
497 - `dealloc` (Function)
498 Function semantically compatible with C's `free(3)`. Takes a pointer
499 returned from `alloc()` and releases memory. Must accept
500 `0`/`0n`/`null` as a no-op and must never throw.
501
502 - `bigIntEnabled` (boolean, optional)
503 Defaults to `true` if `BigInt64Array` is available, otherwise
504 `false`. If true, WASM build must support int64.
505
506 - `memberPrefix` and `memberSuffix` (string, optional)
507 String prefix/suffix applied when binding
508 struct properties to JS. e.g. the member `X` may be made accessible
509 to JS as `$X` with a `memberPrefix` of `"$"`. A prefix is
510 ***strongly recommended*** because symbol names may otherwise
511 collide with other JS-side symbols, inherited or
512 instance-specific. `"$"` is a good choice because it's a legal (but
513 seldom-used) identifier character in JS, and `"$$"` would be even
514 more explicit about the property being unusual in some way.
515
516 * `log` (Function, optional)
517 Logging function used for debugging output (defaults to
518 `console.debug`). This name is deprecated in favor of:
519
520 * `logger` (Object)
521 Optional object to control certain output generated by the library:
522 the `debug`, `warn`, and `error` properties, if set, are expected
523 to be functions which work like their same-named counterparts in
524 the global `console` object. By default it uses the `console`
525 object's methods.
526
527 -----
528
529
530 StructBinder
531 --------------------
532
533 Factories created by [StructBinderFactory][] which convert [struct
534 descriptions](#descriptors) into [StructType][] constructors.
535
536 See also: [](#using-StructBinder)
537
538 **Signature:**
539
540 - `Function StructBinder([string structName,] object structDescriptor)`
541
542 **Members & APIs:**
543
544 - `allocCString(str)`
545 Allocates a new UTF-8-encoded, NUL-terminated copy of the given JS
546 string and returns its address relative to `config.heap()`. Throws
547 if allocation fails. Ownership transfers to the caller, who must
548 eventually deallocate it via `config.dealloc()`.
549
550 - `config` (Object)
551 The configuration object passed to [StructBinderFactory][].
552
553 - `adaptGetter(key [,func])`
554 Gets or sets a "getter adaptor" function by name. When called as a
555 getter, returns a function if one is found or a falsy value if no
556 such getter is mapped. Getters mapped this way can be used by any
557 structs generated by this `StructBinder`: see [](#adaptors).
558
559 - `adaptSetter(key [,func])`
560 Gets or sets a "setter adaptor" function by name.
561 When called as a getter, returns a falsy value if no such setter
562 is mapped. Setters mapped this way can be used by any structs
563 generated by this `StructBinder`: see [](#adaptors).
564
565 - `ptrAdd(...)`
566 Coerces all arguments to the WASM pointer type, adds them together,
567 and returns the resulting sum as the WASM pointer type.
568
569
570 Quirks:
571
572 - It may modify `structDescriptor` its input object, recursively and
573 perhaps extensively. Clients which do not want that should pass a
574 JSON-serialized copy.
575
576 - When called with two arguments, if `structDescriptor.name` is not
577 set, then it gets set to the first argument.
578
579 -----
580
581
582 StructType
583 --------------------
584
585 The base class from which all generated struct instances
586 inherit. Accessible via [StructBinder][].StructType.
587
588 ### Static Members
589
590 - `allocCString(str)`
591 As documented for [StructBinder][].allocCString.
592
593 - `isA(value)`
594 Returns `true` if the argument is a [StructType][] instance from the
595 same [StructBinder][].
596
597 - `memberKey(string)`
598 Returns the given string wrapped in the configured `memberPrefix`
599 and `memberSuffix` values.
600
601
602 ### Prototype / Instance APIs
603
604 - `addOnDispose(...value)`
605 Creates or appends to an [`ondispose` handler](#dispose) array on the
606 object. Returns `this`.
607
608 - `dispose()`
609 Frees WASM-allocated heap memory owned by the object and executes
610 registered `ondispose` cleanup handlers. See [](#dispose) for details.
611
612 - `extraBytes` (integer, read-only)
613 Extra bytes allocated along with this instance, or `0`/`0n`.
614
615 - `lookupMember(memberName [, throwIfNotFound=true])`
616 Returns the member descriptor object. If not found, it throws if
617 `throwIfNotFound` is truthy, else it returns
618 `undefined`. `memberName` may be in either the name from its [struct
619 descriptor](#descriptors) or its JS property name, as modified by
620 [the memberPrefix/memberSuffix options](#member-prefix). That is: if
621 the prefix is `"$"` and the member name is `X` then this function
622 accepts either `X` or `$X`.
623
624 - `memberToJsString(memberName)`
625 Decodes a NUL-terminated, UTF-8-encoded string at the address stored
626 in a member with signature "s", and throws for any unknown or
627 non-"s" member. `memberName` is interpreted as for `lookupMember()`.
628 See [](#type-s).
629
630 - `memberIsString(memberName [, throwIfNotFound=true])`
631 Returns the member descriptor object if signature is "s", else
632 `false`. Both arguments are interpreted as for `lookupMember()`.
633
634 - `memberKey(string)`
635 As documented for [StructType][] static / [StructBinder][].`memberKey()`.
636
637 - `memberKeys()`
638 Returns an array of property names mapped to C struct members, without
639 their [configured prefix/suffix](#member-prefix).
640
641 - `memberSignature(memberName [,throwIfNotFound=true])`
642 Returns the signature for the given member. Both arguments are
643 interpreted as for `lookupMember()`.
644
645 - `memoryDump()`
646 Returns a `Uint8Array` snapshot of the object's raw memory buffer,
647 including any `extraBytes` memory requested via the constructor.
648
649 - `ownsOwnMemory()`
650 Returns `true` if `this.pointer` owns its WASM-side memory.
651
652 - `pointer` (Number \| BigInt, read-only)
653 Numeric WASM heap address allocated for the object, or `undefined`
654 after disposal. This is of type `Number` in in 32-bit builds and
655 `BigInt` in [64-bit](#64bit).
656
657 - `ptrAdd(args...)`
658 Adds the instance's `pointer` value to the arguments via
659 `StructBinder.ptrAdd(this.pointer, args...)`.
660
661 - `setMemberCString(memberName, str)`
662 Allocates a C-string, assigns its address to the member, and
663 registers that C-string with this object's [`ondispose`](#dispose)
664 for cleanup (which means the client _must not free
665 it_). `memberName` is interpreted as for `lookupMember()`. Throws if
666 the given member does not have signature type "s". This does not
667 free any memory pointed to by that member, so may leak when
668 overwriting. See [](#type-s).
669
670 - `zeroOnDispose` (boolean, read-only)
671 `true` if configured to zero out memory upon calling `dispose()`.
672
673
674
675 ### Struct Constructors (`StructCtor`)
676
677 See also: [](#using-StructCtor)
678
679 API overview:
680
681 **Instantiation Signatures:**
682
683 - `new MyStruct()`
684 Allocates new WASM heap memory for the struct.
685
686 - `new MyStruct(pointer)`
687 Wraps existing WASM memory at `pointer` without taking ownership.
688
689 - `new MyStruct({ wrap, takeOwnership, zeroOnDispose, extraBytes, ondispose })`
690 Instantiates wrapping `wrap` pointer or newly allocated heap memory
691 with options for ownership, tail padding, zero-on-dispose, and
692 disposal callbacks.
693
694 **Static Members:**
695
696 - `isA(value)`
697 Returns `true` if argument was created by this constructor.
698
699 - `memberKey(string)`
700 as documented for [StructType][] static.
701
702 - `memberKeys()`
703 as documented for [StructType][] prototype.
704
705 - `ptrAdd(args...)`
706 as documented for [StructBinder][].ptrAdd.
707
708 - `structInfo` (Object, read-only)
709 The struct descriptor metadata object passed when generating the
710 constructor. (Design note: this should have been named
711 `structDescriptor`. Too late.)
712
713 - `structName` (string, read-only)
714 The structure name passed when generating the constructor.
715
716
717 ### Struct Prototypes
718
719 Specific instances of [StructType][] serving as the prototype for
720 generated struct constructors.
721
722 **Properties:**
723
724 - `structInfo`
725 As documented for [StructCtor][].structInfo.
726
727 * `structName`
728 As documented for [StructCtor][].structName.
729
730
731
732 ### Struct Instances
733
734 See also: [](#using-StructInstance)
735
736 Concrete JS objects representing individual bound struct instances
737 created via `new MyStruct(...)`.
738
739 Inherits all methods and properties directly from
740 [StructType.prototype][] and its struct prototype.
741
742 All properties from the underlying C struct are accessible via their
743 configured named. e.g. `myObj.$x = 3` will convert `3` to the type
744 configured for `$x` and set that value at the appropriate memory
745 offset in the corresponding C struct, depending on [the configured
746 member name prefix and/or suffix](#member-prefix).
747
748
749 -----
750
751
752 Using the Various Classes
753 =========================
754
755
756 Using StructBinder
757 --------------------
758
759 [StructBinder][] is called one time per distinct struct and has a
760 trivial interface:
761
762 ```
763 const MyStruct = MyStructBinder(structDefinition);
764 // or:
765 const MyStruct = MyStructBinder('MyStruct', structDefinition);
766 ```
767
768 Where `structDefinition` is as documented in [](#descriptors).
769
770 The result of those calls is a constructor function for instances of
771 that struct, as described in the following section.
772
773
774 Using StructCtor
775 --------------------
776
777 Jaccwabyt structs have two [constructor][StructCtor] signatures:
778
779 - `new Struct(pointer=null)`
780 - `new Struct(optionsObject)`
781
782 And three modes of operation with regard to ownership:
783
784 - `new Struct()`
785 Allocates WASM heap memory owned by this object.
786 - `new Struct({wrap: ptr})` and `new Struct(ptr)`
787 Uses the WASM memory provided via `ptr`, which must outlive
788 the struct object.
789 - `new Struct({wrap: ptr, takeOwnership:true})`
790 Uses the WASM memory provided via `ptr` and takes over its
791 ownership.
792
793 The options object accepts:
794
795 - If `wrap` is set then (A) it must be at least
796 `MyStruct.structInfo.sizeof` of memory owned by the caller, (B) it
797 _must_ have been allocated using the same allocator as Jaccwabyt is
798 configured for, and (C) ownership is transfered (or not) as
799 specified by `takeOwnership` (see below). `zeroOnDispose` and
800 `extraBytes` are disregarded if `wrap` is set. A falsy `wrap` value
801 is equivalent to not providing one, in which case this instance will
802 allocate one from the WASM heap and take over ownership of it. A
803 non-integer value, or a number less than 0, triggers an error.
804
805 - If `takeOwnership` is truthy then this object takes over ownership
806 of the `wrap` pointer (if any). This flag is otherwise ignored.
807 This flag is implicitly true when this object allocates the memory,
808 so has no effect if passed a falsy `wrap` value.
809
810 - `extraBytes` specifies a number of bytes to allocate along with the
811 instance, as part of the same memory block. This setting is exposed
812 as the instance-level `extraBytes` property. Explained in more
813 detail below.
814
815 - `zeroOnDispose` causes the `dispose()` method to zero out this
816 object's memory, but _only_ if it owns the WASM pointer. This
817 setting is later exposed as the instance-level `zeroOnDispose`
818 property.
819
820 - `ondispose`: if set it is passed to the new object's inherited
821 `addOnDispose()` before the constructor returns, so may have any
822 value legal for that method. Results are undefined if `ondispose`
823 and `wrap` have the same pointer value (because `wrap` will already
824 be cleaned up via `dispose()`, as if it had been passed to
825 `addOnDispose()`).
826
827 ### Extra Trailing Bytes
828
829 The `extraBytes` constructor option pads the struct object with extra
830 memory. A pointer to the tail of the struct memory can be obtained by
831 adding `theInstance.structInfo.sizeof` to `theInstance.pointer`.
832 Doing so portably, however, requires care. See [](#64bit) for details
833 and an example.
834
835 The API does not currently expose a way to get the _number_ of extra
836 bytes - it is assumed that the caller knows that, or attached it as
837 a property of the instance after construction.
838
839
840
841 Using StructType Instances
842 --------------------------
843
844 Once [constructed][StructCtor], the C-side properties of [StructType][] instances
845 are accessed via normal property access, accounting for any configured
846 property name prefix and/or suffix. e.g. C-side member `x` might be
847 accessed via `myStruct.$x`.
848
849 Most use cases typically do not need to use any of [the inherited
850 members][StructType] beyond `dispose()`, which they are required to use as
851 described in the following section.
852
853
854 ### Lifecycle and Memory Management (`dispose()` and `ondispose`)
855
856 It cannot be overstated that WASM heap memory must be a first-class
857 consideration for Jaccwabyt client code. It is critical that heap
858 memory one owns be released when one is done with it, and it's
859 critical that we do not use stale pointers to heap memory.
860
861 It is also critical that memory from WASM heaps other than the one
862 which a given [StructBinderFactory][] is configured with are never,
863 ever passed into Jaccwabyt. Differing heaps have different contents at
864 the same addresses, and Jaccwabyt always reads and writes its
865 configured heap, so passing addresses from different heaps _will_
866 corrupt memory.
867
868 When a client is done with a struct instance, they must free all
869 associated resources by calling **`theInstance.dispose()`**. That will, if
870 the struct instance owns its memory, free it, otherwise it will simply
871 disassociate the object from it.
872
873 It is important to call `dispose()` even for non-memory-owning
874 instances so that Jaccwabyt-internal mappings of pointers to objects
875 remain up-to-date.
876
877 Struct instances may optionally have an `ondispose` member. If set, it
878 must be an array. During disposal, the array is walked as follows:
879
880 - Each Function-type entry is called with no arguments. Its `this`
881 is the struct instance being disposed of.
882 - Each [StructType][] value's `dispose()` method is called.
883 - Each pointer-looking value is assumed to be a WASM heap pointer and
884 is passed to the `dealloc()` method provided to the
885 [StructBinderFactory][].
886 - All other types are ignored. It is sometimes useful to annotate
887 entries in the list by adding a string-type entry before or after
888 them, describing the value. e.g. `["memory from X", xPtr]`.
889
890 The inherited `addOnDispose()` method creates the `ondispose`
891 property, if needed, and then appends its arguments to it, making it a
892 convenient way to incrementally add on-dispose state to a struct
893 instance.
894
895 The try/finally construct is ideal for managing short-lived instances:
896
897 >
898 ```js
899 const x = new MyStruct;
900 try{
901 ...
902 }finally{
903 x.dispose();
904 }
905 ```
906
907 Alas, longer-lived instances must be managed more closely by the client.
908
909 -----
910
911 Nested Structs
912 ===============================
913
914 _Experimental and Subject to Change_.
915
916 The feature exists but is not yet well documented. The [test
917 app][test-app] is currently the authority but the API is also still
918 subject to change.
919
920 This feature supports structs shaped like:
921
922 >
923 ```c
924 struct X {
925 int i;
926 struct {int x; int y;} pos;
927 }
928 ```
929
930 It is not tested with the semantically equivalent:
931
932 >
933 ```
934 struct XPos {int x; int y;};
935 struct X {int i; struct XPos pos;};
936 ```
937
938 (But nor should that impact how the descriptor is defined.)
939
940 It does this by treating inner structs (recursively) _almost_ exactly
941 like any an outer struct.
942
943 Fetching a property of inner struct `X::pos` then becomes
944 `anX.$pos.$x`, where the `anX.$pos` property accessor returns an
945 instance of a [StructType][] representation of `X::pos`. That proxy
946 instance has the following quirks:
947
948 - `anX.$pos = X` triggers an exception. These members cannot be
949 overwritten.
950
951 - `anX.$pos.pointer` points to memory inside the parent object (or one
952 of its ancestors, if `anX` is itself a nested struct instances),
953 which the sub-object owns in the sense of read/writing, but not in
954 the sense of memory lifetime.
955
956 - Because the proxy does not control its memory's lifetime,
957 [](#zeroOnDispose) is ignored for sub-structs.
958 [dispose()](#dispose)ing the outermost parent will, _if_ that parent
959 has the `zeroOnDispose` flag, inherently also zero the inner
960 objects.
961
962 - Accessing `anX.$pos` repeatedly will return the same proxy object
963 instance unless...
964
965 - Calling the proxy's [dispose()](#dispose) method will (A) disconnect
966 it but not free the memory (which is owned by someone else further
967 up its chain of command) and (B) the next getter access to
968 `anX.$pos` will create a new proxy instance which points to the same
969 memory as the old one, after which `anX.$pos` will continue to
970 return _that_ proxy instance until it's again `dispose()`d.
971
972 - All such proxies are disposed automatically when their containing
973 struct is disposed.
974
975 -----
976
977 64-bit WASM
978 ===============================
979
980 Jaccwabyt supports both 32- and 64-bit WASM builds, but 64-bit WASM
981 has portability caveats unrelated to Jaccwabyt which affect how it is
982 used.
983
984 Specifically: mixed-number-type math is illegal, triggering a
985 `TypeError` exception. Ergo, on 64-bit builds the following will fail:
986
987 >
988 ```js
989 const offset = myStruct.pointer + 8;
990 ```
991
992 Because `myStruct.pointer` is of type `Number` in 32-bit builds
993 and `BigInt` in 64-bit builds.
994
995 The `ptrAdd()` method was added to several places in the API as an aid
996 for portably adding and subtracting pointers:
997
998 >
999 ```js
1000 const offset = MyStructBinder.ptrAdd(myStruct.pointer, 8);
1001 // Or:
1002 const offset = MyStructCtor.ptrAdd(myStruct.pointer, 8);
1003 // Or, more simply:
1004 const offset = myStruct.ptrAdd(8);
1005 ```
1006
1007 The return type of each of those calls is `Number` in 32-bit builds
1008 and `BigInt` in 64-bit builds.
1009
1010 ------
1011
1012 Appendices
1013 ====================
1014
1015
1016 Appendix B: Building
1017 --------------------
1018
1019 In order to support both vanilla JS and ESM (ES6 module) builds from a
1020 single source, this project uses [a preprocessor][c-pp], which requires
1021 only a C compiler:
1022
1023 > $ make
1024
1025 The makefile requires GNU make, not BSD or POSIX make.
1026
1027 This tree [includes all of the requisite sources](/dir/tool) and
1028 requires no out-of-tree dependencies beyond the system's libc.
1029
1030 The resulting files are in the `js/` subdirectory, in both "vanilla"
1031 JS and ESM formats and they have no dependencies.
1032
1033
1034
1035 Appendix D: Debug Info
1036 --------------------
1037
1038 The [StructBinderFactory][], [StructBinder][], and [StructType][] classes
1039 all have the following "unsupported" method intended primarily
1040 to assist in their own development, as opposed to being for use in
1041 client code:
1042
1043 - `debugFlags(flags)` (integer)
1044 An "unsupported" debugging option which may change or be removed at
1045 any time. Its argument is a set of flags to enable/disable certain
1046 debug/tracing output for property accessors: 0x01 for getters, 0x02
1047 for setters, 0x04 for allocations, 0x08 for deallocations. Pass 0 to
1048 disable all flags and pass a negative value to _completely_ clear
1049 all flags. The latter has the side effect of telling the flags to be
1050 inherited from the next-higher-up class in the hierarchy, with
1051 [StructBinderFactory][] being top-most, followed by [StructBinder][], then
1052 [StructType][].
1053
1054
1055
1056
1057 Appendix G: Generating Struct Descriptors
1058 --------------------
1059
1060 Struct definitions _really, really must_ be generated from
1061 WASM-compiled C, as opposed to simply guessing the sizeofs and
1062 offsets, so that the sizeof and offset information can be collected
1063 using C's `sizeof()` and `offsetof()` features. Struct padding and
1064 members which are not exposed to Jaccwabyt may impact offsets in ways
1065 which might not be immediately obvious, so writing them by hand is
1066 _most certainly not recommended_. (WASM retains the shape of C
1067 structs, including their padding, unless the compiler is specifically
1068 directed otherwise.)
1069
1070 How exactly the desciption is generated is necessarily
1071 project-dependent. It's tempting say, "oh, that's easy! We'll just
1072 write it by hand!" but that would be folly. The struct sizes and byte
1073 offsets into the struct _must_ be _precisely_ how C-side code sees the
1074 struct or the runtime results are completely undefined.
1075
1076 Disregarding the previous two paragraphs' suggestion will eventually
1077 lead to WASM memory corruption, a notoriously difficult thing to debug
1078 browser-side.
1079
1080 The approach used in developing and testing _this_ software is...
1081
1082 Below is a complete copy/pastable example of how we can use a small
1083 set of macros to generate struct descriptors from C99 or later into
1084 static string memory. Simply add such a file to your WASM build,
1085 arrange for its function to be exported[^export-func], and call it
1086 from JS (noting that it requires environment-specific JS glue to
1087 convert the returned pointer to a JS-side string). Use `JSON.parse()`
1088 to process it, then feed the included struct descriptors into the
1089 binder factory at your leisure.
1090
1091 ------------------------------------------------------------
1092
1093 ```c
1094 #include /* memset() */
1095 #include /* offsetof() */
1096 #include /* snprintf() */
1097 #include /* int64_t */
1098 #include
1099
1100 struct ExampleStruct {
1101 int v4;
1102 void * ppV;
1103 int64_t v8;
1104 void (*xFunc)(void*);
1105 };
1106 typedef struct ExampleStruct ExampleStruct;
1107
1108 const char * wasm__ctype_json(void){
1109 static char strBuf[512 * 8] = {0}
1110 /* Static buffer which must be sized large enough for
1111 our JSON. The string-generation macros try very
1112 hard to assert() if this buffer is too small. */;
1113 int n = 0, structCount = 0 /* counters for the macros */;
1114 char * pos = &strBuf[1]
1115 /* Write-position cursor. Skip the first byte for now to help
1116 protect against a small race condition. */;
1117 char const * const zEnd = pos + sizeof(strBuf)
1118 /* one-past-the-end cursor (virtual EOF) */;
1119 if(strBuf[0]) return strBuf; // Was set up in a previous call.
1120
1121 //////////////////////////////
1122 // First we need to build up our macro framework...
1123
1124 //////////////////////////////
1125 // Core output-generating macros...
1126 #define lenCheck assert(pos < zEnd - 100)
1127 #define outf(format,...) \
1128 pos += snprintf(pos, ((size_t)(zEnd - pos)), format, __VA_ARGS__); \
1129 lenCheck
1130 #define out(TXT) outf("%s",TXT)
1131 #define CloseBrace(LEVEL) \
1132 assert(LEVEL<5); memset(pos, '}', LEVEL); pos+=LEVEL; lenCheck
1133
1134 //////////////////////////////
1135 // Macros for emitting StructBinders...
1136 #define StructBinder__(TYPE) \
1137 n = 0; \
1138 outf("%s{", (structCount++ ? ", " : "")); \
1139 out("\"name\": \"" # TYPE "\","); \
1140 outf("\"sizeof\": %d", (int)sizeof(TYPE)); \
1141 out(",\"members\": {");
1142 #define StructBinder_(T) StructBinder__(T)
1143 // ^^^ extra indirection needed to expand CurrentStruct
1144 #define StructBinder StructBinder_(CurrentStruct)
1145 #define _StructBinder CloseBrace(2)
1146 #define M(MEMBER,SIG) \
1147 outf("%s\"%s\": " \
1148 "{\"offset\":%d,\"sizeof\": %d,\"signature\":\"%s\"}", \
1149 (n++ ? ", " : ""), #MEMBER, \
1150 (int)offsetof(CurrentStruct,MEMBER), \
1151 (int)sizeof(((CurrentStruct*)0)->MEMBER), \
1152 SIG)
1153 // End of macros.
1154 //////////////////////////////
1155
1156 //////////////////////////////
1157 // With that out of the way, we can do what we came here to do.
1158 out("\"structs\": ["); {
1159
1160 // For each struct descriptor, do...
1161 #define CurrentStruct ExampleStruct
1162 StructBinder {
1163 M(v4,"i");
1164 M(ppV,"p");
1165 M(v8,"j");
1166 M(xFunc,"v(p)");
1167 } _StructBinder;
1168 #undef CurrentStruct
1169
1170 } out( "]"/*structs*/);
1171 //////////////////////////////
1172 // Done! Finalize the output...
1173 out("}"/*top-level wrapper*/);
1174 *pos = 0;
1175 strBuf[0] = '{'/*end of the race-condition workaround*/;
1176 return strBuf;
1177
1178 // If this file will ever be concatenated or #included with others,
1179 // it's good hygiene to clean up our macros:
1180 #undef StructBinder
1181 #undef StructBinder_
1182 #undef StructBinder__
1183 #undef M
1184 #undef _StructBinder
1185 #undef CloseBrace
1186 #undef out
1187 #undef outf
1188 #undef lenCheck
1189 }
1190 ```
1191
1192 A much richer example of that, spanning many C structs and non-struct
1193 data, can be found at:
1194
1195 -
1196 in the function `sqlite3__wasm_enum_json()`.
1197
1198
1199
1200 Appendix L: License
1201 --------------------
1202
1203 Jaccwabyt, including its documentation and test code, are released
1204 under the terms of [the SQLite Blessing][blessing]:
1205
1206 >
1207 ```
1208 2022-06-30
1209
1210 The author disclaims copyright to this source code. In place of a
1211 legal notice, here is a blessing:
1212
1213 * May you do good and not evil.
1214 * May you find forgiveness for yourself and forgive others.
1215 * May you share freely, never taking more than you give.
1216 ```
1217
1218
1219
1220
1243
1244 [appendix-g]: #appendix-g
1245 [blessing]: https://spdx.org/licenses/blessing.html
1246 [BigInt64Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array
1247 [c-pp]: https://fossil.wanderinghorse.net/r/c-pp
1248 [Emscripten]: https://emscripten.org
1249 [StructBinder]: #StructBinder
1250 [StructBinderFactory]: #StructBinderFactory
1251 [StructCtor]: #StructCtor
1252 [StructInstance]: #StructInstance
1253 [StructType.prototype]: #StructType.prototype
1254 [StructType]: #StructType
1255 [test-app]: /file/test/tester.c-pp.js
1256
1257 [^export-func]: In Emscripten, add its name, prefixed with `_`, to the
1258 project's `EXPORT_FUNCTIONS` list. Exports can also be declared from
1259 C, as demonstrated in [](/file/jaccwabyt/jaccwabyt_test.c).