interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / wasm / jaccwabyt / jaccwabyt.md

1259 lines · 44731 bytes Raw Blame History Source

Jaccwabyt 🐇

Jaccwabyt: _JavaScript ⇄ C Struct Communication via WASM Byte Arrays_^the-name

Forewarning: if this is not being read from its canonical home then some of the markdown formatting and links will not work.

the result was worth it.

<a id='overview'></a> Table of Contents ====================


Welcome to Jaccwabyt, a JavaScript API which creates bindings for WASM-compiled C structs, permitting two-way interchange of WASM-hosted struct state with very little client-side friction.

(If that means nothing to you, neither will the rest of this page!)

To the best of its creator's fallible knowledge, Jaccwabyt is the only library of its kind (as of 2025-11). It is a core component of the SQLite project's JS/WASM bindings, where it is binds JS-side virtual filesystems and virtual database tables to WASM, and is known to work reliably.

Formalities:


<a id='demo'></a> Brief Usage Overview =============================

Client-side, Jaccwabyt looks like...

// 1. Initialize for the current WASM environment. Needed once
//    per app session.
const StructBinder = StructBinderFactory({ 
  memberPrefix: "$",
  ... config info from the WASM environment
});

// 2. Convert a JSON-friendly struct descriptor into
//    a JS constructor. Needed once per struct type.
const StructCtor = StructBinder( structDescriptorObject );

// 3. Instiate an instance which wraps a WASM-hosted instance.
const s = new StructCtor( funcReturningAWasmPointer() );

// 4. Access the C-side members...
s.$x = 3;                 // Write to WASM-side Struct::x
console.debug(s.$y);      // Read from WASM-side Struct::y
console.debug(s.pointer); // WASM pointer value

// 5. Clean up (important!)
s.dispose(); // Memory ownership is configurable.
             // s.pointer is now falsy

<a id='arch'></a> Architecture and Mental Model =============================

Jaccwabyt is made up of several layers:

In graphics, it looks something like:

BSBF: box "StructBinderFactory" fit fill lightblue
BSB: box same "StructBinder" fit at 0.75 e of 0.9 s of BSBF.c
BSM: box rad 0.4*boxht "JSON-format C Structs" fit fill lightblue at 1.5s of BSBF
BST: box same "StructType<T>" fit at 1.5 e of BSBF
BSC: box same "Struct<T>" "Ctor" fit at 1.75 s of BST
BSI: box same "Struct<T>" "Instances" fit at 1.25 right of BSB.e
BC: box same at 0.25 right of 1.6 e of BST "C Structs" fit fill lightgrey

arrow -> from BSM.n to BSB.sw "Input" aligned above dotted
arrow -> from BSBF.s to BSB.nw "Generates" aligned above
arrow -> from BSB.n to BST.sw "Generates" aligned above
arrow -> from BSB.s to BSC.nw "Generates" aligned below
arrow -> from BSC.ne to BSI.s "Constructs" aligned below
arrow <-> from BSI.e to BC.s dotted "WASM heap" aligned below
arrow -> from BST.e to BC.w dotted "Mirrors Struct" aligned above "Model From" aligned below
arrow -> from BST.s to BSC.n "Prototype of" aligned above

<a id='descriptors'></a> Struct Descriptors ====================

Before making use of Jaccwabyt we need so-called descriptors for C structs, JSON-friendly objects which describe their memory layout. Jaccwabyt converts these into codecs for reading and writing WASM-side representations of instances of those structs.

For example, given this C struct:

// C-side:
struct MyStruct {
  int member1;
  void * member2;
  int64_t member3;
};

Its JSON-format description might (depending on the build environment and target) look like:

{
  "name": "MyStruct",
  "sizeof": 16,
  "members": {
    "member1": {"offset": 0, "sizeof": 4, "signature": "i"},
    "member2": {"offset": 4, "sizeof": 4, "signature": "p"},
    "member3": {"offset": 8, "sizeof": 8, "signature": "j"}
  }
}

Forewarning: these data must match up with the C-side definition of the struct (if any), noting that padding and members not exposed to Jaccwabyt must be accounted for in the offsets. See for one way to easily generate these from C code.

Every struct must have a sizeof^sizeof. The name is required as well but it may optionally be passed as the first argument to StructBinder(structName,structDescriptor). The name property represents the member's symbolic name, typically (but not necessarily) its native name.

members, we don't. Actually, we do, then we throw an exception if
the values don't match up.

Abstractly speaking, a struct descriptor in an object with the properties sizeof, offset, and either signature or members. offset is optional only in the top-most object of a struct description. Every sub-object (a.k.a. member descriptor object) requires the offset property.

<a id="member-descr"></a> Member descriptor objects are those in the members property:

"members": {"memberName": {...member descriptor...}, ...}

A struct descriptor which has a members object represents a nested struct, the interior of which follows the same struct descriptor format as a top-level struct except that nested structs require an offset property.

Each entry in a struct/member descriptor object maps the member's name to its low-level layout and other metadata:

The order of the members entries is not important: their memory layout is determined by their offset and sizeof members. The name property is technically optional, but one of the steps in the binding process requires that either it be passed an explicit name or there be one in the struct descriptor. The names of the members entries need not match their C counterparts. Project conventions may call for giving them different names in the JS side and the StructBinderFactory can be configured to automatically add a prefix and/or suffix to their names.

<a id='type-signatures'></a> Type Signatures


Struct descriptor member signature describes the data type of each member, and uses an extended variant of the format used by Emscripten's addFunction(). A signature for a non-function-pointer member, or function pointer member which is to be modelled as an opaque pointer, is a single letter. A signature for a function pointer may also be modelled as a series of letters describing the call signature.

Signatures in the form x(...) denote function-pointer members and the form x denotes non-function members. Functions with no arguments use the form x().

The supported signature letters are:

Noting that:

<a id='type-s'></a>

Type "s" (C-string)

Type ID "s" is a special case of "p". In some limited contexts, described below, the library will treat them as C-strings, with the caveat that that such algorithms must, for lack of information to the contrary, assume that the encoding is UTF-8 and that the pointer's member is NUL-terminated. If that is not the case for a given string member, do not use "s", use "p" instead and do any string handling yourself.

The following APIs handle "s" specially:

StructType.memberIsString() returns true if a given member is legal for those methods, and those methods both throw if memberIsString() is false.

<a id='type-p'></a>

Type "p" (pointer) vs "P" (pointer plus)

The signature letter p means "pointer", which, in WASM, means either int32 or [int64][64bit]. A capital P changes the semantics of plain member pointers (but not, as of this writing, function pointer members) as follows:

When a P-type member is set via myStruct.x=y, if (y instanceof StructType) then the value of y.pointer is stored in myStruct.x. If y is neither a pointer nor a StructType, an exception is triggered regardless of whether p or P is used. P has no further effect when fetching a property, only when setting.

<a id='adaptors'></a> Property Access Adaptors


Adaptors, an optional part of a struct descriptor, provide a way to customize the result of reading and writing WASM-side struct properties. This enables transparent installation of custom "JS-to-WASM" and "WASM-to-JS" conversions for struct properties.

The following optional struct descriptor properties may be used on [Object-type entries of the members property](#member-descr):

Getter and setter implementations MUST NOT try to look up that struct property using Jaccwabyt's property interceptor or they will cause endless recursion and a stack overflow.

A rather contrived example...

First, map getter/setter names to functions for use in the JSON descriptors:

MyStructBinder.adaptGetter('truncateFloat',(k,v)=>v | 0);
MyStructBinder.adaptSetter('parseFloat',(k,v)=>{
  v = parseFloat(v);
  return isNaN(v) ? 0 : v;
});

Sidebar: most implementations will not need the key but it is provided for cases which want to share an implementation across keys and dispatch on their name. The key should arguably be the second argument, allowing it to be elided from most implementations, but experimentation with that caused more confusion than it solved.

With that in place, we can map those to members using something like:

const MyStruct = MyStructBinder({
  ...
  memberPrefix: "$",
  members: {
    foo: {
      ...
      signature: "d", // => double
      getter: "truncateFloat",
      setter: "parseFloat"
    }
  }
});

Then fetching x.$foo will always return a 32-bit-truncated int and assigning x.$foo will coerce its arguments to a number, making x.$foo="3" both legal and well-behaved ("feature or bug?" is for the implementor to decide).

Sidebar: the test app demonstrates a struct member adaptor, for installing proxies for nested structs, but is not yet part of the public API. It also demonstrates how to plug adaptors into the struct descriptor "inline", but that's also not yet part of the public API.


<a id='api'></a> Classes and APIs ====================

<a id='StructBinderFactory'></a> StructBinderFactory


The top-most function of the API, from which all other functions and types are generated. It accepts a configuration object to customize it for a given WASM environment and returns a StructBinder factory function.

Signature:

Configuration Options:


<a id='StructBinder'></a> StructBinder


Factories created by StructBinderFactory which convert [struct descriptions](#descriptors) into StructType constructors.

See also:

Signature:

Members & APIs:

Quirks:


<a id='StructType'></a> StructType


The base class from which all generated struct instances inherit. Accessible via StructBinder.StructType.

Static Members

Prototype / Instance APIs

<a id='StructCtor'></a>

Struct Constructors (StructCtor)

See also:

API overview:

Instantiation Signatures:

Static Members:

<a id='StructCtor.prototype'></a>

Struct Prototypes

Specific instances of StructType serving as the prototype for generated struct constructors.

Properties:

<a id='StructInstance'></a>

Struct Instances

See also:

Concrete JS objects representing individual bound struct instances created via new MyStruct(...).

Inherits all methods and properties directly from StructType.prototype and its struct prototype.

All properties from the underlying C struct are accessible via their configured named. e.g. myObj.$x = 3 will convert 3 to the type configured for $x and set that value at the appropriate memory offset in the corresponding C struct, depending on [the configured member name prefix and/or suffix](#member-prefix).


<a id='using'></a> Using the Various Classes =========================

<a id='using-StructBinder'></a> Using StructBinder


StructBinder is called one time per distinct struct and has a trivial interface:

const MyStruct = MyStructBinder(structDefinition);
// or:
const MyStruct = MyStructBinder('MyStruct', structDefinition);

Where structDefinition is as documented in .

The result of those calls is a constructor function for instances of that struct, as described in the following section.

<a id='using-StructCtor'></a> Using StructCtor


Jaccwabyt structs have two constructor signatures:

And three modes of operation with regard to ownership:

The options object accepts:

Extra Trailing Bytes

The extraBytes constructor option pads the struct object with extra memory. A pointer to the tail of the struct memory can be obtained by adding theInstance.structInfo.sizeof to theInstance.pointer. Doing so portably, however, requires care. See for details and an example.

The API does not currently expose a way to get the number of extra bytes - it is assumed that the caller knows that, or attached it as a property of the instance after construction.

<a id='using-StructInstance'></a> Using StructType Instances


Once constructed, the C-side properties of StructType instances are accessed via normal property access, accounting for any configured property name prefix and/or suffix. e.g. C-side member x might be accessed via myStruct.$x.

Most use cases typically do not need to use any of [the inherited members]StructType beyond dispose(), which they are required to use as described in the following section.

<a id='lifecycle'></a><a id='dispose'></a>

Lifecycle and Memory Management (dispose() and ondispose)

It cannot be overstated that WASM heap memory must be a first-class consideration for Jaccwabyt client code. It is critical that heap memory one owns be released when one is done with it, and it's critical that we do not use stale pointers to heap memory.

It is also critical that memory from WASM heaps other than the one which a given StructBinderFactory is configured with are never, ever passed into Jaccwabyt. Differing heaps have different contents at the same addresses, and Jaccwabyt always reads and writes its configured heap, so passing addresses from different heaps will corrupt memory.

When a client is done with a struct instance, they must free all associated resources by calling theInstance.dispose(). That will, if the struct instance owns its memory, free it, otherwise it will simply disassociate the object from it.

It is important to call dispose() even for non-memory-owning instances so that Jaccwabyt-internal mappings of pointers to objects remain up-to-date.

Struct instances may optionally have an ondispose member. If set, it must be an array. During disposal, the array is walked as follows:

The inherited addOnDispose() method creates the ondispose property, if needed, and then appends its arguments to it, making it a convenient way to incrementally add on-dispose state to a struct instance.

The try/finally construct is ideal for managing short-lived instances:

const x = new MyStruct;
try{
 ...
}finally{
  x.dispose();
}

Alas, longer-lived instances must be managed more closely by the client.


<a id='nested-structs'></a> Nested Structs ===============================

Experimental and Subject to Change.

The feature exists but is not yet well documented. The [test app]test-app is currently the authority but the API is also still subject to change.

This feature supports structs shaped like:

struct X {
  int i;
  struct {int x; int y;} pos;
}

It is not tested with the semantically equivalent:

struct XPos {int x; int y;};
struct X {int i; struct XPos pos;};

(But nor should that impact how the descriptor is defined.)

It does this by treating inner structs (recursively) almost exactly like any an outer struct.

Fetching a property of inner struct X::pos then becomes anX.$pos.$x, where the anX.$pos property accessor returns an instance of a StructType representation of X::pos. That proxy instance has the following quirks:


<a id='64bit'></a> 64-bit WASM ===============================

Jaccwabyt supports both 32- and 64-bit WASM builds, but 64-bit WASM has portability caveats unrelated to Jaccwabyt which affect how it is used.

Specifically: mixed-number-type math is illegal, triggering a TypeError exception. Ergo, on 64-bit builds the following will fail:

const offset = myStruct.pointer + 8;

Because myStruct.pointer is of type Number in 32-bit builds and BigInt in 64-bit builds.

The ptrAdd() method was added to several places in the API as an aid for portably adding and subtracting pointers:

const offset = MyStructBinder.ptrAdd(myStruct.pointer, 8);
// Or:
const offset = MyStructCtor.ptrAdd(myStruct.pointer, 8);
// Or, more simply:
const offset = myStruct.ptrAdd(8);

The return type of each of those calls is Number in 32-bit builds and BigInt in 64-bit builds.


Appendices

<a id='appendix-b'></a> Appendix B: Building


In order to support both vanilla JS and ESM (ES6 module) builds from a single source, this project uses a preprocessor, which requires only a C compiler:

$ make

The makefile requires GNU make, not BSD or POSIX make.

This tree includes all of the requisite sources and requires no out-of-tree dependencies beyond the system's libc.

The resulting files are in the js/ subdirectory, in both "vanilla" JS and ESM formats and they have no dependencies.

<a id='appendix-d'></a> Appendix D: Debug Info


The StructBinderFactory, StructBinder, and StructType classes all have the following "unsupported" method intended primarily to assist in their own development, as opposed to being for use in client code:

<a id='appendix-g'></a> Appendix G: Generating Struct Descriptors


Struct definitions really, really must be generated from WASM-compiled C, as opposed to simply guessing the sizeofs and offsets, so that the sizeof and offset information can be collected using C's sizeof() and offsetof() features. Struct padding and members which are not exposed to Jaccwabyt may impact offsets in ways which might not be immediately obvious, so writing them by hand is most certainly not recommended. (WASM retains the shape of C structs, including their padding, unless the compiler is specifically directed otherwise.)

How exactly the desciption is generated is necessarily project-dependent. It's tempting say, "oh, that's easy! We'll just write it by hand!" but that would be folly. The struct sizes and byte offsets into the struct must be precisely how C-side code sees the struct or the runtime results are completely undefined.

Disregarding the previous two paragraphs' suggestion will eventually lead to WASM memory corruption, a notoriously difficult thing to debug browser-side.

The approach used in developing and testing this software is...

Below is a complete copy/pastable example of how we can use a small set of macros to generate struct descriptors from C99 or later into static string memory. Simply add such a file to your WASM build, arrange for its function to be exported^export-func, and call it from JS (noting that it requires environment-specific JS glue to convert the returned pointer to a JS-side string). Use JSON.parse() to process it, then feed the included struct descriptors into the binder factory at your leisure.


#include <string.h> /* memset() */
#include <stddef.h> /* offsetof() */
#include <stdio.h>  /* snprintf() */
#include <stdint.h> /* int64_t */
#include <assert.h>

struct ExampleStruct {
  int v4;
  void * ppV;
  int64_t v8;
  void (*xFunc)(void*);
};
typedef struct ExampleStruct ExampleStruct;

const char * wasm__ctype_json(void){
  static char strBuf[512 * 8] = {0}
    /* Static buffer which must be sized large enough for
       our JSON. The string-generation macros try very
       hard to assert() if this buffer is too small. */;
  int n = 0, structCount = 0 /* counters for the macros */;
  char * pos = &strBuf[1]
    /* Write-position cursor. Skip the first byte for now to help
       protect against a small race condition. */;
  char const * const zEnd = pos + sizeof(strBuf)
    /* one-past-the-end cursor (virtual EOF) */;
  if(strBuf[0]) return strBuf; // Was set up in a previous call.

  //////////////////////////////
  // First we need to build up our macro framework...

  //////////////////////////////
  // Core output-generating macros...
#define lenCheck assert(pos < zEnd - 100)
#define outf(format,...) \
  pos += snprintf(pos, ((size_t)(zEnd - pos)), format, __VA_ARGS__); \
  lenCheck
#define out(TXT) outf("%s",TXT)
#define CloseBrace(LEVEL) \
  assert(LEVEL<5); memset(pos, '}', LEVEL); pos+=LEVEL; lenCheck

  //////////////////////////////
  // Macros for emitting StructBinders...
#define StructBinder__(TYPE)                 \
  n = 0;                                     \
  outf("%s{", (structCount++ ? ", " : ""));  \
  out("\"name\": \"" # TYPE "\",");          \
  outf("\"sizeof\": %d", (int)sizeof(TYPE)); \
  out(",\"members\": {");
#define StructBinder_(T) StructBinder__(T)
// ^^^ extra indirection needed to expand CurrentStruct
#define StructBinder StructBinder_(CurrentStruct)
#define _StructBinder CloseBrace(2)
#define M(MEMBER,SIG)                                         \
  outf("%s\"%s\": "                                           \
       "{\"offset\":%d,\"sizeof\": %d,\"signature\":\"%s\"}", \
       (n++ ? ", " : ""), #MEMBER,                            \
       (int)offsetof(CurrentStruct,MEMBER),                   \
       (int)sizeof(((CurrentStruct*)0)->MEMBER),              \
       SIG)
  // End of macros.
  //////////////////////////////

  //////////////////////////////
  // With that out of the way, we can do what we came here to do.
  out("\"structs\": ["); {

// For each struct descriptor, do...
#define CurrentStruct ExampleStruct
    StructBinder {
      M(v4,"i");
      M(ppV,"p");
      M(v8,"j");
      M(xFunc,"v(p)");
    } _StructBinder;
#undef CurrentStruct

  } out( "]"/*structs*/);
  //////////////////////////////
  // Done! Finalize the output...
  out("}"/*top-level wrapper*/);
  *pos = 0;
  strBuf[0] = '{'/*end of the race-condition workaround*/;
  return strBuf;

// If this file will ever be concatenated or #included with others,
// it's good hygiene to clean up our macros:
#undef StructBinder
#undef StructBinder_
#undef StructBinder__
#undef M
#undef _StructBinder
#undef CloseBrace
#undef out
#undef outf
#undef lenCheck
}

A much richer example of that, spanning many C structs and non-struct data, can be found at:

<a id='appendix-l'></a> Appendix L: License


Jaccwabyt, including its documentation and test code, are released under the terms of the SQLite Blessing:

  2022-06-30

  The author disclaims copyright to this source code.  In place of a
  legal notice, here is a blessing:

  *   May you do good and not evil.
  *   May you find forgiveness for yourself and forgive others.
  *   May you share freely, never taking more than you give.

<nowiki><style> /* Reminder: greater-than gets mangled to HTML */ div.content {} div.content h1, div.content h2, div.content h3 { border-radius: 0.25em; border-bottom: 1px solid #70707070; } div.content h1 {} div.content { margin-right: 0.5em; } div.content h2 {} div.content h3 {border-left-width: 2.5em} div.content code { border: 1px dotted; border-radius: 0.25em; padding: 0 0.1em; } div.content pre code { border: unset; padding: unset; } </style></nowiki>

project's EXPORT_FUNCTIONS list. Exports can also be declared from C, as demonstrated in .