diff --git a/text/0030-c-api.md b/text/0030-c-api.md new file mode 100644 index 0000000..327a2fc --- /dev/null +++ b/text/0030-c-api.md @@ -0,0 +1,214 @@ +# Electron C APIs + +- Start Date: 2026-10-07 +- RFC PR: [electron/rfcs#0000](https://github.com/electron/rfcs/pull/0000) +- Electron Issues: [electron/electron#0000](https://github.com/electron/electron/issues/0000) +- Reference Implementation: [electron/electron#0000](https://github.com/electron/electron/pull/0000) +- Status: **Proposed** + +## Summary + +Electron should expose a small, versioned **C ABI for native addons**: one exported +symbol, `electron_get_api()`, which fills a size-negotiated core table. Feature sets are +reached as function-pointer tables through a generic getter on that table, so adding a +feature never adds an exported symbol and never changes the core layout. + +## Motivation + +Some of Electron's native surface cannot be an addon: reaching an object that Electron or +Chromium owns requires cooperation from inside the process. Two cases are concrete today. + +1. **Wayland window management.** A Wayland protocol object belongs to the `wl_display` + that created it, so an addon with its own connection cannot act on Electron's windows. + Layer-shell panels, `xdg_popup` parenting, and toplevel control all need requests on + *Chromium's* connection, on the thread that owns it. No complete JavaScript API is + possible here: the protocol set is open-ended, compositor-specific, and versioned + independently of Electron. What is missing is access, not a feature. +2. **Native handles.** Electron's own native-addon fixtures reinterpret the bytes of + `window.getNativeWindowHandle()` as a platform pointer, and the documentation states no + lifetime contract for it. The idiom works and is unsupported. + +The expected outcome is a documented ABI that addons can target on Windows, macOS, and +Linux, and a mechanism under which feature sets — Wayland first — can be proposed, +reviewed, and shipped one at a time. + +## Guide-level explanation + +An addon author writes C or C++, includes ``, and asks for what it needs: + +```c +#include + +electron_api_t api = {0}; +api.struct_size = sizeof(api); +if (electron_get_api(ELECTRON_API_VERSION, &api) != ELECTRON_RESULT_OK) return -1; + +/* A feature's header declares its table type; discovery itself is by name. */ +electron_wayland_connection_api_t wl = {0}; +wl.struct_size = sizeof(wl); + +electron_result_t r = api.get_feature("wayland_connection", 1, &wl); +if (r == ELECTRON_RESULT_UNSUPPORTED) { /* not this build, or not this session */ } +else if (r != ELECTRON_RESULT_OK) return -1; + +wl.create(&opts, &connection); /* call through the table */ +``` + +What this changes for addon authors: instead of `dlsym`-ing private symbols, an addon +targets a documented version and degrades when a feature set is absent, or when the host +filled fewer table fields than the addon was compiled against. + +What it does not change: the JavaScript API, existing addons, and platform support. An +addon that never calls `electron_get_api()` behaves exactly as it does today. + +Headers ship in the existing headers tarball that `@electron/rebuild` already fetches, +under the include path `node-gyp` already searches. Feature absence is a compile-time +signal (a define) and, for callers that opt out of the compile-time error, a runtime +`ELECTRON_RESULT_UNSUPPORTED`. + +## Reference-level explanation + +1. **One exported symbol.** `electron_result_t electron_get_api(uint32_t abi_version, + electron_api_t* out)`, defined in `electron_lib` with C linkage, using the + attribute-based export mechanism Electron already has. No export list, version script, + or `.def` entry is required. +2. **Tables and options structs negotiate with one in/out `struct_size`.** The caller sets + it to its own `sizeof`; the host overwrites it with the size it actually filled. Fields + are append-only. **Layout growth does not bump a version** — that is what `struct_size` + is for — and a version changes only when an existing member changes meaning. Truncation + is not an error here: the host writes what fits, and the caller detects a newer host by + comparing the returned size with its own `sizeof`. +3. **Array-returning calls take capacity in and required out.** The host fills what fits, + writes the number of entries that exist, and returns `ELECTRON_RESULT_BUFFER_TOO_SMALL` + when a supplied buffer was too small; a null output with zero capacity is a size query + that succeeds. The split is used here and not for tables: an array's capacity is a + runtime choice that no compile-time `sizeof` recovers, and retrying with a larger buffer + is a real path, whereas a table's caller cannot obtain members its own header does not + declare. `BUFFER_TOO_SMALL` is kept so that success continues to mean the output is + complete. +4. **Discovery is generic.** The core table carries `abi_version` and + `get_feature(name, version, out_table)`, where the table's own `struct_size` carries the + caller's capacity. Feature headers add typed inline wrappers over that lookup. The core + table therefore contains no feature names: adding a feature set changes neither its + layout nor the exported surface. +5. **Result codes.** Every call returns a 32-bit status. Zero is success; every non-zero + value is a failure, including values an addon does not recognise. Absent features and + unsupported environments are distinct codes. +6. **Scope.** Browser process only, UI thread only, and the API enforces it. This is a + deliberate limitation: it keeps both the surface and the concurrency story small. +7. **Stability.** The core mechanism is stable from the start and append-only. Feature sets + are experimental until individually promoted, with their status recorded in + `docs/experimental.md` beside the existing experimental tag. +8. **Enforcement.** A CI conformance test compiles a fixture addon against the previously + released headers and fails on a non-append-only table change, a removed or reordered + enum or result-code value, or any change to the exported symbol. It should also assert + that `BUFFER_TOO_SMALL` is returned exactly when an array output buffer was too small. This + is CEF's API-hash mechanism, and it is what makes the stability policy checkable rather + than aspirational. + +## Drawbacks + +- **A second public surface to support.** Compiled consumers cannot be shimmed or + feature-detected the way JavaScript callers can. +- **The export is permanent.** Even one symbol is part of the binary interface and needs + per-platform export configuration. +- **Compiled addons can crash the browser.** The crash report points at Electron, and the + cause is harder to diagnose than a JavaScript bug. +- **It weakens the argument for built-in APIs.** "Make it an addon" becomes the default + answer to feature requests, which shifts work onto app developers and can fragment the + ecosystem. +- **Distribution.** Addons now depend on an Electron version range, so prebuilt binaries + must be published per ABI or users compile from source. + +## Rationale and alternatives + +**Why one anchor plus function tables.** A table can grow without new exported symbols, and +`struct_size` lets already-built addons keep working while it does. One symbol per function +or per feature set makes the exported surface grow with every addition and makes each +addition touch per-platform export configuration. + +**Why the capacity/required split is used for arrays but not for tables.** An array's length +is known only at run time and retrying with a larger buffer is a normal path, so keeping the +caller's capacity separate means it never has to keep its own copy. A table's capacity is +the compile-time `sizeof` of the caller's own header, and the members a caller lacks are +ones its own translation unit does not declare — a separate required size would carry no +information and would add a second size that can disagree with the table's own +`struct_size`. + +**Why a generic lookup rather than a typed getter per feature set.** A typed +`get_wayland_connection` field would put a feature name into the stable core layout, so +adding a feature set would change the core table. A generic `get_feature` keeps it free of +feature names. The costs are a string lookup at setup and weaker typing, which feature +headers recover with inline wrappers. + +**Why not expose Chromium's own headers and C++ types.** Chromium's C++ components change +constantly, and its headers are gated by GN visibility that an out-of-tree `node-gyp` +build cannot satisfy. Electron would become responsible for vendoring a moving target. +A feature set may still hand out borrowed opaque handles to objects defined by an external +C library that Chromium owns (Wayland's `wl_*`): the addon includes that library's headers, +not Chromium's, and the operations on those objects are that library's. + +**Why not extend Node-API.** Its versioning belongs to Node, and its abstractions are +JavaScript values; neither matches native objects with platform-specific lifetimes. + +**Why not mediated operations only.** A mediated API (`create_layer_panel(...)`) is safer +but open-ended: every new protocol or capability would need an Electron change, +reintroducing the built-in-API growth this RFC exists to avoid. Mediated helpers are a +useful complement, not a substitute. + +**Impact of not doing this.** The byte-cast idiom remains the undocumented supported way to +reach native handles, and every app that needs native access builds its own private, +unreviewed ABI. + +## Prior art + +- **Node-API** — the model for an addon C ABI: status codes, opaque handles, append-only + enums, an opt-in versioned surface. Its accumulated compatibility machinery is the + cautionary half. +- **CEF's C API** — a stable embedder ABI across years of Chromium rolls, with + `size`-prefixed append-only structs and build-time API-hash verification. +- **Mojo C System API** — Chromium's own C ABI, and the source of the leading `struct_size` + and tolerant result-code conventions used here. +- **RFC 0017, "Import Shared Texture"** — Electron's existing precedent for moving native + handles across its boundary with documented ownership and a `subtle` tier. +- **NPAPI** — the cautionary tale: the last cross-browser plugin ABI, retired in 2013. An + ABI that third parties compile against is a long-lived commitment. + +## Unresolved questions + +- **Process scope.** Browser process only, or also utility and renderer processes? This + changes the surface and the thread rules; browser-only is proposed. +- **Contract version or Electron version.** Should the ABI carry its own version, bumped + only when an existing member changes meaning, or track Electron's release version? A + dedicated counter lets CI require a bump alongside a non-append-only change and keeps + prebuilt artifacts on a stable key; the release version is more familiar to addon + authors, but Electron's majors move on a release train unrelated to ABI changes, so + compatibility becomes a maintained range. A third option is to carry both: a contract + version for negotiation and the release version for identification only. +- **Backward compatibility across Electron majors.** Must the ABI survive from `43-x-y` + to `44-x-y` and beyond, or is it scoped to one major, as `NODE_MODULE_VERSION` is? + Scoped per major, the append-only rule still holds between minors, but a major may + renumber feature identifiers, reorder or remove table members, and drop deprecated + stubs, and prebuilt addons are keyed per major exactly as they already are for V8-based + native addons. If it must survive majors, members can never be removed or reordered, + a deprecated member has to be kept as a failing stub, and the stability item's + append-only rule applies forever rather than within a major. This also decides the + question above: a per-major ABI makes `abi_version == electron_major` coherent, while + cross-major stability requires an independent contract counter. +- **Version namespaces.** Does each feature set need its own version series, or is one + integer per feature set enough? +- **Promotion criteria.** What must a feature set demonstrate before it is marked stable? +- **Export strategy.** Should each API function be its own exported C symbol for direct + linking or `dlsym`, or should functions remain reachable only through `electron_get_api()` + and `get_feature()` returning function-pointer tables? The RFC chooses the latter; + this remains open for discussion. + +## Future possibilities + +- **The first feature set: the Wayland connection feature set**, specified separately over + this mechanism. It motivates this RFC, is not proposed here, and will serve as its + testing ground. +- **More feature sets**, each with its own header, table, and version. +- **Mediated operations** as a complement for the common cases. +- **Retiring the byte-cast idiom** once window identity and native handles are expressible + through this ABI.