diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 19:33:14 +0000 |
commit | 36d22d82aa202bb199967e9512281e9a53db42c9 (patch) | |
tree | 105e8c98ddea1c1e4784a60a5a6410fa416be2de /dom/docs | |
parent | Initial commit. (diff) | |
download | firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.tar.xz firefox-esr-36d22d82aa202bb199967e9512281e9a53db42c9.zip |
Adding upstream version 115.7.0esr.upstream/115.7.0esr
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'dom/docs')
28 files changed, 5587 insertions, 0 deletions
diff --git a/dom/docs/fedcm.rst b/dom/docs/fedcm.rst new file mode 100644 index 0000000000..64f4763d79 --- /dev/null +++ b/dom/docs/fedcm.rst @@ -0,0 +1,67 @@ +=============================== +Federated Credential Management +=============================== + +FedCM, as it is abbreviated, is a platform feature that requires a full-stack implementation. +As such, its code is scattered throughout the codebase and it can be hard to follow the flow of execution. +This documentation aims to make those two points easier. + +Code sites +========== + +Code relevant to it can be found in all of the following places. + +The webidl for this spec lives in ``dom/webidl/IdentityCredential.webidl`` + +Core spec algorithm logic and the implementation of the ``IdentityCredential`` live in ``dom/credentialmanagement/identity/IdentityCredential.{cpp,h}``. The static functions of ``IdentityCredential`` are the spec algorithm logic. Helpers for managing the ``IdentityCredential.webidl`` objects are in the other files in ``dom/credentialmanagement/identity/``. The IPC is defined on the WindowGlobal in ``dom/ipc/PWindowGlobal.ipdl`` and ``dom/ipc/WindowGlobalParent.cpp``, and is a very thin layer. + +The service for managing state associated with IdentityCredentials is ``IdentityCredentialStorageService`` and the service for managing the UI prompts associated with IdentityCredentials is ``IdentityCredentialPromptService``. Both definitions and implementations are in ``toolkit/components/credentialmanagement``. + +The UI panel is spread around a little. The actual DOM elements are in the HTML subtree with root at ``#identity-credential-notification`` in ``browser/base/content/popup-notifications.inc``. But the CSS describing it is spread through ``browser/themes/shared/customizableui/panelUI-shared.css``, ``browser/themes/shared/identity-credential-notification.css``, and ``browser/themes/shared/notification-icons.css``. Generally speaking, search for ``identity-credential`` in those files to find the relevant ids and classes. + +Temporary content strings, which will be moved when included in i18n: ``browser/components/credentialmanager/identityCredentialNotification.ftl``, for now. This will eventually be moved to ``browser/locales/en-US/browser/``. + +All of this is entered from the ``navigator.credentials`` object, implemented in ``dom/credentialmanagement/CredentialsContainer.{cpp,h}``. + +Flow of Execution +================= + +This is the general flow through code relevant to the core spec algorithms, which happens to be the complicated parts imo. + +A few notes: + +- All functions without a class specified are in ``IdentityCredential``. +- Functions in ``IdentityCredentialPromptService`` mutate the Chrome DOM +- FetchT functions send network requests via ``mozilla::dom::FetchJSONStructure<T>``. +- A call to ``IdentityCredentialStorageService`` is made in ``PromptUserWithPolicy`` + +.. graphviz:: + + digraph fedcm { + "RP (visited page) calls ``navigator.credentials.get()``" -> "CredentialsContainer::Get" + "CredentialsContainer::Get" -> "DiscoverFromExternalSource" + "DiscoverFromExternalSource" -> "DiscoverFromExternalSourceInMainProcess" [label="IPC via WindowGlobal's DiscoverIdentityCredentialFromExternalSource"] + "DiscoverFromExternalSourceInMainProcess" -> "anonymous timeout callback" -> "CloseUserInterface" -> "IdentityCredentialPromptService::Close" + "DiscoverFromExternalSourceInMainProcess" -> "CheckRootManifest A" + "CheckRootManifest A" -> "FetchInternalManifest A" [label="via promise chain in DiscoverFromExternalSourceInMainProcess"] + "FetchInternalManifest A" -> "DiscoverFromExternalSourceInMainProcess inline anonymous callback (Promise::All)" + "DiscoverFromExternalSourceInMainProcess" -> "CheckRootManifest N" + "CheckRootManifest N" -> "FetchInternalManifest N" [label="via promise chain in DiscoverFromExternalSourceInMainProcess"] + "FetchInternalManifest N" -> "DiscoverFromExternalSourceInMainProcess inline anonymous callback (Promise::All)" + "DiscoverFromExternalSourceInMainProcess inline anonymous callback (Promise::All)" -> "PromptUserToSelectProvider" + "PromptUserToSelectProvider" -> "IdentityCredentialPromptService::ShowProviderPrompt" + "IdentityCredentialPromptService::ShowProviderPrompt" -> "CreateCredential" [label="via promise chain in DiscoverFromExternalSourceInMainProcess"] + "CreateCredential" -> "FetchAccountList" [label="via promise chain in CreateCredential"] + "FetchAccountList" -> "PromptUserToSelectAccount" [label="via promise chain in CreateCredential"] + "PromptUserToSelectAccount" -> "IdentityCredentialPromptService::ShowAccountListPrompt" + "IdentityCredentialPromptService::ShowAccountListPrompt" -> "PromptUserWithPolicy" [label="via promise chain in CreateCredential"] + "PromptUserWithPolicy" -> "FetchMetadata" + "FetchMetadata" -> "IdentityCredentialPromptService::ShowPolicyPrompt" [label="via promise chain in PromptUserWithPolicy"] + "IdentityCredentialPromptService::ShowPolicyPrompt" -> "FetchToken" [label="via promise chain in CreateCredential"] + "FetchToken" -> "cancel anonymous timeout callback" + "FetchToken" -> "CreateCredential inline anonymous callback" + "CreateCredential inline anonymous callback" -> "DiscoverFromExternalSourceInMainProcess inline anonymous callback" + "DiscoverFromExternalSourceInMainProcess inline anonymous callback" -> "DiscoverFromExternalSource inline anonymous callback" [label="Resolving IPC via WindowGlobal's DiscoverIdentityCredentialFromExternalSource"] + "DiscoverFromExternalSource inline anonymous callback" -> "CredentialsContainer::Get inline anonymous callback" + "CredentialsContainer::Get inline anonymous callback" -> "RP (visited page) gets the credential" + } diff --git a/dom/docs/index.rst b/dom/docs/index.rst new file mode 100644 index 0000000000..e833cba011 --- /dev/null +++ b/dom/docs/index.rst @@ -0,0 +1,17 @@ +DOM +=== + +These linked pages contain design documents for the DOM implementation in Gecko. They live in-tree under the 'dom/docs' directory. + +.. toctree:: + :maxdepth: 1 + + ipc/index + navigation/index + push/index + scriptSecurity/index + scriptSecurity/xray_vision + workersAndStorage/index + webIdlBindings/index + ioutils_migration + fedcm diff --git a/dom/docs/ioutils_migration.md b/dom/docs/ioutils_migration.md new file mode 100644 index 0000000000..c9f959b564 --- /dev/null +++ b/dom/docs/ioutils_migration.md @@ -0,0 +1,589 @@ +# IOUtils Migration Guide + +**Improving performance through a new file API** + +--- + +## What is IOUtils? + +`IOUtils` is a privileged JavaScript API for performing file I/O in the Firefox frontend. +It was developed as a replacement for `OS.File`, addressing +[bug 1231711](https://bugzilla.mozilla.org/show_bug.cgi?id=1231711). +It is *not to be confused* with the unprivileged +[DOM File API](https://developer.mozilla.org/en-US/docs/Web/API/File). + +`IOUtils` provides a minimal API surface to perform common +I/O tasks via a collection of static methods inspired from `OS.File`. +It is implemented in C++, and exposed to JavaScript via WebIDL bindings. + +The most up-to-date API can always be found in +[IOUtils.webidl](https://searchfox.org/mozilla-central/source/dom/chrome-webidl/IOUtils.webidl). + +## Differences from `OS.File` + +`IOUtils` has a similar API to `OS.File`, but one should keep in mind some key differences. + +### No `File` instances (except `SyncReadFile` in workers) + +Most of the `IOUtils` methods only operate on absolute path strings, and don't expose a file handle to the caller. +The exception to this rule is the `openFileForSyncReading` API, which is only available in workers. + +Furthermore, `OS.File` was exposing platform-specific file descriptors through the +[`fd`](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File_for_workers#Attributes) +attribute. `IOUtils` does not expose file descriptors. + +### WebIDL has no `Date` type + +`IOUtils` is written in C++ and exposed to JavaScript through WebIDL. +Many uses of `OS.File` concern themselves with obtaining or manipulating file metadata, +like the last modified time, however the `Date` type does not exist in WebIDL. +Using `IOUtils`, +these values are returned to the caller as the number of milliseconds since +`1970-01-01T00:00:00Z`. +`Date`s can be safely constructed from these values if needed. + +For example, to obtain the last modification time of a file and update it to the current time: + +```js +let { lastModified } = await IOUtils.stat(path); + +let lastModifiedDate = new Date(lastModified); + +let now = new Date(); + +await IOUtils.touch(path, now.valueOf()); +``` + +### Some methods are not implemented + +For various reasons +(complexity, safety, availability of underlying system calls, usefulness, etc.) +the following `OS.File` methods have no analogue in IOUtils. +They also will **not** be implemented. + +- void unixSymlink(in string targetPath, in string createPath) +- string getCurrentDirectory(void) +- void setCurrentDirectory(in string path) +- object open(in string path) +- object openUnique(in string path) + +### Errors are reported as `DOMException`s + +When an `OS.File` method runs into an error, +it will throw/reject with a custom +[`OS.File.Error`](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File.Error). +These objects have custom attributes that can be checked for common error cases. + +`IOUtils` has similar behaviour, however its methods consistently reject with a +[`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) +whose name depends on the failure: + +| Exception Name | Reason for exception | +| -------------- | -------------------- | +| `NotFoundError` | A file at the specified path could not be found on disk. | +| `NotAllowedError` | Access to a file at the specified path was denied by the operating system. | +| `NotReadableError` | A file at the specified path could not be read for some reason. It may have been too big to read, or it was corrupt, or some other reason. The exception message should have more details. | +| `ReadOnlyError` | A file at the specified path is read only and could not be modified. | +| `NoModificationAllowedError` | A file already exists at the specified path and could not be overwritten according to the specified options. The exception message should have more details. | +| `OperationError` | Something went wrong during the I/O operation. E.g. failed to allocate a buffer. The exception message should have more details. | +| `UnknownError` | An unknown error occurred in the implementation. An nsresult error code should be included in the exception message to assist with debugging and improving `IOUtils` internal error handling. | + +### `IOUtils` is mostly async-only + +`OS.File` provided an asynchronous front-end for main-thread consumers, +and a synchronous front-end for workers. +`IOUtils` only provides an asynchronous API for the vast majority of its API surface. +These asynchronous methods can be called from both the main thread and from chrome-privileged worker threads. + +The one exception to this rule is `openFileForSyncReading`, which allows synchronous file reading in workers. + +## `OS.File` vs `IOUtils` + +Some methods and options of `OS.File` keep the same name and underlying behaviour in `IOUtils`, +but others have been renamed. +The following is a detailed comparison with examples of the methods and options in each API. + +### Reading a file + +`IOUtils` provides the following methods to read data from a file. Like +`OS.File`, they accept an `options` dictionary. + +Note: The maximum file size that can be read is `UINT32_MAX` bytes. Attempting +to read a file larger will result in a `NotReadableError`. + +```idl +Promise<Uint8Array> read(DOMString path, ...); + +Promise<DOMString> readUTF8(DOMString path, ...); + +Promise<any> readJSON(DOMString path, ...); + +// Workers only: +SyncReadFile openFileForSyncReading(DOMString path); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| ------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| bytes: number? | maxBytes: number? | If specified, read only up to this number of bytes. Otherwise, read the entire file. Default is null. | +| compression: 'lz4' | decompress: boolean | If true, read the file and return the decompressed LZ4 stream. Otherwise, just read the file byte-for-byte. Default is false. | +| encoding: 'utf-8' | N/A; use `readUTF8` instead. | Interprets the file as UTF-8 encoded text, and returns a string to the caller. | + +#### Examples + +##### Read raw (unsigned) byte values + +**`OS.File`** +```js +let bytes = await OS.File.read(path); // Uint8Array +``` +**`IOUtils`** +```js +let bytes = await IOUtils.read(path); // Uint8Array +``` + +##### Read UTF-8 encoded text + +**`OS.File`** +```js +let utf8 = await OS.File.read(path, { encoding: 'utf-8' }); // string +``` +**`IOUtils`** +```js +let utf8 = await IOUtils.readUTF8(path); // string +``` + +##### Read JSON file + +**`IOUtils`** +```js +let obj = await IOUtils.readJSON(path); // object +``` + +##### Read LZ4 compressed file contents + +**`OS.File`** +```js +// Uint8Array +let bytes = await OS.File.read(path, { compression: 'lz4' }); +// string +let utf8 = await OS.File.read(path, { + encoding: 'utf-8', + compression: 'lz4', +}); +``` +**`IOUtils`** +```js +let bytes = await IOUtils.read(path, { decompress: true }); // Uint8Array +let utf8 = await IOUtils.readUTF8(path, { decompress: true }); // string +``` + +##### Synchronously read a fragment of a file into a buffer, from a worker + +**`OS.File`** +```js +// Read 64 bytes at offset 128, workers only: +let file = OS.File.open(path, { read: true }); +file.setPosition(128); +let bytes = file.read({ bytes: 64 }); // Uint8Array +file.close(); +``` +**`IOUtils`** +```js +// Read 64 bytes at offset 128, workers only: +let file = IOUtils.openFileForSyncReading(path); +let bytes = new Uint8Array(64); +file.readBytesInto(bytes, 128); +file.close(); +``` + +### Writing to a file + +IOUtils provides the following methods to write data to a file. Like +OS.File, they accept an options dictionary. + +```idl +Promise<unsigned long long> write(DOMString path, Uint8Array data, ...); + +Promise<unsigned long long> writeUTF8(DOMString path, DOMString string, ...); + +Promise<unsigned long long> writeJSON(DOMString path, any value, ...); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| -------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| backupTo: string? | backupFile: string? | Identifies the path to backup the target file to before performing the write operation. If unspecified, no backup will be performed. Default is null. | +| tmpPath: string? | tmpPath: string? | Identifies a path to write to first, before performing a move to overwrite the target file. If unspecified, the target file will be written to directly. Default is null. | +| noOverwrite: boolean | mode: 'overwrite' or 'create' | 'create' mode will refuse to overwrite an existing file. Default is 'overwrite'. | +| flush: boolean | flush: boolean | If true, force the OS to flush its internal buffers to disk. Default is false. | +| encoding: 'utf-8' | N/A; use `writeUTF8` instead. | Allows the caller to supply a string to be encoded as utf-8 text on disk. | + +#### Examples +##### Write raw (unsigned) byte values + +**`OS.File`** +```js +let bytes = new Uint8Array(); +await OS.File.writeAtomic(path, bytes); +``` + +**`IOUtils`** +```js +let bytes = new Uint8Array(); +await IOUtils.write(path, bytes); +``` + +##### Write UTF-8 encoded text + +**`OS.File`** +```js +let str = ""; +await OS.File.writeAtomic(path, str, { encoding: 'utf-8' }); +``` + +**`IOUtils`** +```js +let str = ""; +await IOUtils.writeUTF8(path, str); +``` + +##### Write A JSON object + +**`IOUtils`** +```js +let obj = {}; +await IOUtils.writeJSON(path, obj); +``` + +##### Write with LZ4 compression + +**`OS.File`** +```js +let bytes = new Uint8Array(); +await OS.File.writeAtomic(path, bytes, { compression: 'lz4' }); +let str = ""; +await OS.File.writeAtomic(path, str, { + compression: 'lz4', +}); +``` + +**`IOUtils`** +```js +let bytes = new Uint8Array(); +await IOUtils.write(path, bytes, { compress: true }); +let str = ""; +await IOUtils.writeUTF8(path, str, { compress: true }); +``` + +### Move a file + +`IOUtils` provides the following method to move files on disk. +Like `OS.File`, it accepts an options dictionary. + +```idl +Promise<void> move(DOMString sourcePath, DOMString destPath, ...); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| -------------------- | ----------------------------------- | ---------------------------------------------------------------------------- | +| noOverwrite: boolean | noOverwrite: boolean | If true, fail if the destination already exists. Default is false. | +| noCopy: boolean | N/A; will not be implemented | This option is not implemented in `IOUtils`, and will be ignored if provided | + +#### Example + +**`OS.File`** +```js +await OS.File.move(srcPath, destPath); +``` + +**`IOUtils`** +```js +await IOUtils.move(srcPath, destPath); +``` + +### Remove a file + +`IOUtils` provides *one* method to remove files from disk. +`OS.File` provides several methods. + +```idl +Promise<void> remove(DOMString path, ...); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| ---------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------- | +| ignoreAbsent: boolean | ignoreAbsent: boolean | If true, and the destination does not exist, then do not raise an error. Default is true. | +| N/A; `OS.File` has dedicated methods for directory removal | recursive: boolean | If true, and the target is a directory, recursively remove the directory and all its children. Default is false. | + +#### Examples + +##### Remove a file + +**`OS.File`** +```js +await OS.File.remove(path, { ignoreAbsent: true }); +``` + +**`IOUtils`** +```js +await IOUtils.remove(path); +``` + +##### Remove a directory and all its contents + +**`OS.File`** +```js +await OS.File.removeDir(path, { ignoreAbsent: true }); +``` + +**`IOUtils`** +```js +await IOUtils.remove(path, { recursive: true }); +``` + +##### Remove an empty directory + +**`OS.File`** +```js +await OS.File.removeEmptyDir(path); // Will throw an exception if `path` is not empty. +``` + +**`IOUtils`** +```js +await IOUtils.remove(path); // Will throw an exception if `path` is not empty. +``` + +### Make a directory + +`IOUtils` provides the following method to create directories on disk. +Like `OS.File`, it accepts an options dictionary. + +```idl +Promise<void> makeDirectory(DOMString path, ...); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| ----------------------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ignoreExisting: boolean | ignoreExisting: boolean | If true, succeed even if the target directory already exists. Default is true. | +| from: string | createAncestors: boolean | If true, `IOUtils` will create all missing ancestors in a path. Default is true. This option differs from `OS.File`, which requires the caller to specify a root path from which to create missing directories. | +| unixMode: number | permissions: unsigned long | The file mode to create the directory with. Ignored on Windows. Default is 0755. | +| winSecurity | N/A | `IOUtils` does not support setting custom directory security settings on Windows. | + +#### Example + +**`OS.File`** +```js +await OS.File.makeDir(srcPath, destPath); +``` +**`IOUtils`** +```js +await IOUtils.makeDirectory(srcPath, destPath); +``` + +### Update a file's modification time + +`IOUtils` provides the following method to update a file's modification time. + +```idl +Promise<void> setModificationTime(DOMString path, optional long long modification); +``` + +#### Example + +**`OS.File`** +```js +await OS.File.setDates(path, new Date(), new Date()); +``` + +**`IOUtils`** +```js +await IOUtils.setModificationTime(path, new Date().valueOf()); +``` + +### Get file metadata + +`IOUtils` provides the following method to query file metadata. + +```idl +Promise<void> stat(DOMString path); +``` + +#### Example + +**`OS.File`** +```js +let fileInfo = await OS.File.stat(path); +``` + +**`IOUtils`** +```js +let fileInfo = await IOUtils.stat(path); +``` + +### Copy a file + +`IOUtils` provides the following method to copy a file on disk. +Like `OS.File`, it accepts an options dictionary. + +```idl +Promise<void> copy(DOMString path, ...); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| ------------------------------------------------------------------- | -------------------- | -------------------------------------------------------------------| +| noOverwrite: boolean | noOverwrite: boolean | If true, fail if the destination already exists. Default is false. | +| N/A; `OS.File` does not appear to support recursively copying files | recursive: boolean | If true, copy the source recursively. | + +#### Examples + +##### Copy a file + +**`OS.File`** +```js +await OS.File.copy(srcPath, destPath); +``` + +**`IOUtils`** +```js +await IOUtils.copy(srcPath, destPath); +``` + +##### Copy a directory recursively + +**`OS.File`** +```js +// Not easy to do. +``` + +**`IOUtils`** +```js +await IOUtils.copy(srcPath, destPath, { recursive: true }); +``` + +### Iterate a directory + +At the moment, `IOUtils` does not have a way to expose an iterator for directories. +This is blocked by +[bug 1577383](https://bugzilla.mozilla.org/show_bug.cgi?id=1577383). +As a stop-gap for this functionality, +one can get all the children of a directory and iterate through the returned path array using the following method. + +```idl +Promise<sequence<DOMString>> getChildren(DOMString path); +``` + +#### Example + +**`OS.File`** +```js +for await (const { path } of new OS.FileDirectoryIterator(dirName)) {</p> + ... +} +``` + +**`IOUtils`** +```js +for (const path of await IOUtils.getChildren(dirName)) { + ... +} +``` + +### Check if a file exists + +`IOUtils` provides the following method analogous to the `OS.File` method of the same name. + +```idl +Promise<boolean> exists(DOMString path); +``` + +#### Example + +**`OS.File`** +```js +if (await OS.File.exists(path)) { + ... +} +``` + +**`IOUtils`** +```js +if (await IOUtils.exists(path)) { + ... +} +``` + +### Set the permissions of a file + +`IOUtils` provides the following method analogous to the `OS.File` method of the same name. + +```idl +Promise<void> setPermissions(DOMString path, unsigned long permissions, optional boolean honorUmask = true); +``` + +#### Options + +| `OS.File` option | `IOUtils` option | Description | +| ----------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| unixMode: number | permissions: unsigned long | The UNIX file mode representing the permissions. Required in IOUtils. | +| unixHonorUmask: boolean | honorUmask: boolean | If omitted or true, any UNIX file mode is modified by the permissions. Otherwise the exact value of the permissions will be applied. | + +#### Example + +**`OS.File`** +```js +await OS.File.setPermissions(path, { unixMode: 0o600 }); +``` + +**`IOUtils`** +```js +await IOUtils.setPermissions(path, 0o600); +``` + +## FAQs + +**Why should I use `IOUtils` instead of `OS.File`?** + +[Bug 1231711](https://bugzilla.mozilla.org/show_bug.cgi?id=1231711) +provides some good context, but some reasons include: +* reduced cache-contention, +* faster startup, and +* less memory usage. + +Additionally, `IOUtils` benefits from a native implementation, +which assists in performance-related work for +[Project Fission](https://hacks.mozilla.org/2021/05/introducing-firefox-new-site-isolation-security-architecture/). + +We are actively working to migrate old code usages of `OS.File` +to analogous `IOUtils` calls, so new usages of `OS.File` +should not be introduced at this time. + +**Do I need to import anything to use this API?** + +Nope! It's available via the `IOUtils` global in JavaScript (`ChromeOnly` context). + +**Can I use this API from C++ or Rust?** + +Currently usage is geared exclusively towards JavaScript callers, +and all C++ methods are private except for the Web IDL bindings. +However given sufficient interest, +it should be easy to expose ergonomic public methods for C++ and/or Rust. + +**Why isn't `IOUtils` written in Rust?** + +At the time of writing, +support for Web IDL bindings was more mature for C++ oriented tooling than it was for Rust. + +**Is `IOUtils` feature complete? When will it be available?** + +`IOUtils` is considered feature complete as of Firefox 83. diff --git a/dom/docs/ipc/Fission-IPC-Diagram.svg b/dom/docs/ipc/Fission-IPC-Diagram.svg new file mode 100644 index 0000000000..f53d4b65b4 --- /dev/null +++ b/dom/docs/ipc/Fission-IPC-Diagram.svg @@ -0,0 +1,5 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> +<svg xmlns="http://www.w3.org/2000/svg" style="background-color: rgb(255, 255, 255);" version="1.1" width="841px" height="861px" viewBox="-0.5 -0.5 841 861" content="<mxfile modified="2019-04-26T17:33:16.547Z" host="www.draw.io" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0" etag="ryQDoUVJ1oS_b3fguxas" version="10.6.5" type="google"><diagram id="GcJpJ4Eku4OUxVByAJcz" name="Page-1">7Vxbc9o6EP41PDZjyzd4DCSkZ6ZnJnNyZto+dYQtQImxOLZISH/9kWzJNxlsKAY1pQ+ptbp6d7/VrrRmYE1W24cYrpd/kwCFA2AE24F1NwBgZA7ZX054zwiO7WWERYyDjGQWhCf8EwmiIagbHKCk0pASElK8rhJ9EkXIpxUajGPyVm02J2F11jVcIIXw5MNQpX7FAV1m1KFjFPTPCC+WcmbTEDUrKBsLQrKEAXkrkaz7gTWJCaHZ02o7QSHnneRL1m+6ozZfWIwi2qXDN289dbav0x8Pw89T4IHk2f7nkxjlFYYb8cJisfRdciAmmyhAfBBzYI3flpiipzX0ee0bEzmjLekqFNXqouQMKKZoWyKJRT4gskI0fmdNRK0t+CUUxrSNGyejvBUC8FzRalliPpC8h0Loi3zwgi/sQbDmADYB7dlkgyY22cMGNtm9scnSj02O24VPOTfPwydb4dOYWyoUM+JjTHyUJArj2PvSKncSGpMXNCEhiRklIhFrOZ7jMKyRYIgXESv6jItsCmvMuYeZibsVFSscBHyaRnEUAjP48CSiT2JRDRboYPEM62C3G6RjNkkH9CUcp0GJ3ZDzPsCv7HHBHyeMD/ytS/LK2rApS83+TCl6I/PCMnSvMjxUhq6pmxCBo7AeBcw5E0US0yVZkAiG9wW1xqSizRdC1kJaz4jSd+Fpwg0lVVmiLabfeHdmiLLS91LN3VaMnBbeZSFi71vqxIvfy3VFt7Qk+zXqTUJhTG+568o1JYRJgn1JnuKwdW9MyCb20R6+CgecjbdAdE874blznu9VoBiFkOLXqsN8em3w2p2LM6jHVTr7Vr3f4LL/4YpbsrRiu2Ez3M5yxyeJ/bSn+9+Gh0RjeOOTVVHk65P95WiN1lqZNkqmMVyhLwQGfKKsfhbXe7RY/arm9O+4jmqekdfkt5qgwSC7vRnk0U4p892owi8pNl7xKUnRdMsamGC9Lcs0Y/Zj7v7mosgG3CELfXB+rOU/3j4MO9qH0antg+j6SHAqaqnETi2+MnM9lYNkSxX9aiqYL+R4rRwqSim06THjrmZAZvC8OJAt48/YS0cdsSJdX002U9XMCo2eLHEY6KbQduMB3ZkV2lS48uFChZ6xIjHQDhZTK7CYqi2Lkq9olrsUeqHFsTRAy0Ws/cdCi7yLakUL0AstTRc+LYEanvPwqSFCm/Uaoekdj7nyYvNiKLatS6LYLGG4QHQbiisYvvGci8MYdIVxP+EUezf4Xmqw5kFSUhq5Fm05Ru2Q1hqJ3WTasQcL2Ko92EO2ipMGZbZ6ICSD/HGMORPruqueqscowT/hLG3AtUEwh7V2xgPnbnDIeXoIZygcQ/9lkSJAHrkOgDVP/zVq0V7YKZYjz0EQSx6Ur/mbLIpxYw09cVNxbBQupJorsuxC5vME9RJuy5nU6CQTrJYximeMLu91Nd2Ol7bCYw/PznQE12lTvrqRB+4/dtf9x9HLjdyZwaDJoZvlaHjqZv8ueOlf752Oeg/0Opkz1eQQrY7m6mqvxdnc7oSaD3drpCfY3K6bjKcX2NQsHr02GRdouMl4V72vqXP7JqPZibYaO2u1ydTVXodNxv5tLoD6V/uuGQLSiddF7Xde5GcHC5oY/bqLpUNijuX+LtqvbyTeOVfA1Qs1O5MFtEJNfc/QATVA85vjuqXR4up4dLU0v2hp8s8YW91SoJWlyRVYU7jUTYwOcJHfS1zhcjxcQFe4WHrBBShwOT7Tot9ceM0yLepA1iDV4jIn9xKSZgWQN+BEaRO5mSgZibZUjufNai1fG3Il/RVkW11d7pN/69KcK1FXPA8ouezZSym57AfncdS/mGzP46h/KTs8Tx6HGl7onscR4Bj5FBPej4mLW4zOuR3yWvMEuR3G0AEVicnfWjhWSftP7QBqhoKGqR0KSjXI7ZCibtjsl6bcWB+Q/0JYo78e2STGnCkuMKaYGWemqvu+SitGaNjQ77fMDeCiuO3sA1zoM7y8WzRL1mnZOHeeqbqEtnLXJXblUvtnh02LPu6LxeO/U08YfnG0YASnKP2bui381KQZ5YRBeB6mPseSmWsUKT7QCcBf/3EYQwH+0GgAfm4NDkA+KxY/zpOZ2OIXjqz7/wE=</diagram></mxfile>"><defs/><g><rect x="20" y="160.5" width="760" height="200" rx="30" ry="30" fill="#ffffff" stroke="#000000" pointer-events="none"/><rect x="20" y="440.5" width="480" height="400" rx="60" ry="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><rect x="540" y="440.5" width="240" height="400" rx="36" ry="36" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(80.5,168.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="98" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 99px; white-space: nowrap; overflow-wrap: normal; font-weight: bold; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Browser Process</div></div></foreignObject><text x="49" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold">Browser Process</text></switch></g><g transform="translate(82.5,814.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="95" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 96px; white-space: nowrap; overflow-wrap: normal; font-weight: bold; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div>Content Process</div></div></div></foreignObject><text x="48" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold"><div>Content Process</div></text></switch></g><g transform="translate(612.5,814.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="95" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 96px; white-space: nowrap; overflow-wrap: normal; font-weight: bold; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div>Content Process</div></div></div></foreignObject><text x="48" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold"><div>Content Process</div></text></switch></g><path d="M 130 256.87 L 130 271 L 130 261 L 130 274.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 251.62 L 133.5 258.62 L 130 256.87 L 126.5 258.62 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 279.38 L 126.5 272.38 L 130 274.13 L 133.5 272.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="70" y="190.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(71.5,199.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="116" height="41" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 116px; white-space: normal; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div><xul:browser src="a.com"/></div><div>nsFrameLoader<br /></div></div></div></foreignObject><text x="58" y="27" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 130 346.87 L 130 454.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 341.62 L 133.5 348.62 L 130 346.87 L 126.5 348.62 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 459.88 L 126.5 452.88 L 130 454.63 L 133.5 452.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(103.5,394.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="52" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 11px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><font style="font-size: 12px">PBrowser</font></div></div></foreignObject><text x="26" y="12" fill="#000000" text-anchor="middle" font-size="11px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="70" y="280.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(90.5,304.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="79" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 80px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserParent</div></div></foreignObject><text x="40" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserParent</text></switch></g><path d="M 130 526.87 L 130 541 L 130 531 L 130 544.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 521.62 L 133.5 528.62 L 130 526.87 L 126.5 528.62 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 549.38 L 126.5 542.38 L 130 544.13 L 133.5 542.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="70" y="460.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(94.5,484.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="71" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 72px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserChild</div></div></foreignObject><text x="36" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserChild</text></switch></g><path d="M 130 617.37 L 130 631.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 612.12 L 133.5 619.12 L 130 617.37 L 126.5 619.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 636.88 L 126.5 629.88 L 130 631.63 L 133.5 629.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="70" y="550.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(89.5,574.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="81" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 82px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">nsWebBrowser</div></div></foreignObject><text x="41" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">nsWebBrowser</text></switch></g><path d="M 130 704.37 L 130 723.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 699.12 L 133.5 706.12 L 130 704.37 L 126.5 706.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 130 728.88 L 126.5 721.88 L 130 723.63 L 133.5 721.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="70" y="638" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(71.5,647.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="116" height="41" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 116px; white-space: normal; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div><iframe src="b.com"/></div><div>nsFrameLoader</div></div></div></foreignObject><text x="58" y="27" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 196.37 760 L 480 760 L 480 236 L 593.63 236" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 191.12 760 L 198.12 756.5 L 196.37 760 L 198.12 763.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 598.88 236 L 591.88 239.5 L 593.63 236 L 591.88 232.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(436.5,384.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="87" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">PBrowserBridge</div></div></foreignObject><text x="44" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">PBrowserBridge</text></switch></g><rect x="70" y="729.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(76.5,753.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="106" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 107px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserBridgeChild</div></div></foreignObject><text x="53" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserBridgeChild</text></switch></g><path d="M 390 347.37 L 390 454.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 342.12 L 393.5 349.12 L 390 347.37 L 386.5 349.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 459.88 L 386.5 452.88 L 390 454.63 L 393.5 452.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(363.5,394.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="52" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 11px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><div style="font-size: 12px"><font style="font-size: 12px">PBrowser</font></div></div></div></foreignObject><text x="26" y="12" fill="#000000" text-anchor="middle" font-size="11px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="330" y="280.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(350.5,304.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="79" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 80px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserParent</div></div></foreignObject><text x="40" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserParent</text></switch></g><path d="M 390 527.37 L 390 541 L 390 531 L 390 544.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 522.12 L 393.5 529.12 L 390 527.37 L 386.5 529.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 549.38 L 386.5 542.38 L 390 544.13 L 393.5 542.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="330" y="460.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(354.5,484.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="71" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 72px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserChild</div></div></foreignObject><text x="36" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserChild</text></switch></g><path d="M 660 347.37 L 660 454.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 342.12 L 663.5 349.12 L 660 347.37 L 656.5 349.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 459.38 L 656.5 452.38 L 660 454.13 L 663.5 452.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(633.5,394.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="52" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 11px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;"><font style="font-size: 12px">PBrowser</font></div></div></foreignObject><text x="26" y="12" fill="#000000" text-anchor="middle" font-size="11px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><rect x="600" y="280.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(620.5,304.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="79" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 80px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserParent</div></div></foreignObject><text x="40" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserParent</text></switch></g><path d="M 660 527.37 L 660 541 L 660 531 L 660 544.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 522.12 L 663.5 529.12 L 660 527.37 L 656.5 529.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 549.38 L 656.5 542.38 L 660 544.13 L 663.5 542.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="600" y="460.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(624.5,484.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="71" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 72px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserChild</div></div></foreignObject><text x="36" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserChild</text></switch></g><path d="M 390 257.37 L 390 271 L 390 261 L 390 274.13" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 252.12 L 393.5 259.12 L 390 257.37 L 386.5 259.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 390 279.38 L 386.5 272.38 L 390 274.13 L 393.5 272.38 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="330" y="190.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(332.5,214.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="114" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 115px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserBridgeParent</div></div></foreignObject><text x="57" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserBridgeParent</text></switch></g><path d="M 660 257.37 L 660 274.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 252.12 L 663.5 259.12 L 660 257.37 L 656.5 259.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 279.88 L 656.5 272.88 L 660 274.63 L 663.5 272.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="600" y="190.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(602.5,214.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="114" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 115px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserBridgeParent</div></div></foreignObject><text x="57" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserBridgeParent</text></switch></g><rect x="330" y="550.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(349.5,574.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="81" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 82px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">nsWebBrowser</div></div></foreignObject><text x="41" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">nsWebBrowser</text></switch></g><path d="M 660 617.37 L 660 631.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 612.12 L 663.5 619.12 L 660 617.37 L 656.5 619.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 636.88 L 656.5 629.88 L 660 631.63 L 663.5 629.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="600" y="550.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(619.5,574.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="81" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 82px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">nsWebBrowser</div></div></foreignObject><text x="41" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">nsWebBrowser</text></switch></g><path d="M 660 704.37 L 660 723.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 699.12 L 663.5 706.12 L 660 704.37 L 656.5 706.12 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 660 728.88 L 656.5 721.88 L 660 723.63 L 663.5 721.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><rect x="600" y="638" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(601.5,647.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="116" height="41" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 116px; white-space: normal; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><div><iframe src="a.com"/></div><div>nsFrameLoader</div></div></div></foreignObject><text x="58" y="27" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g><path d="M 593.63 760 L 560 760 L 560 239 C 563.9 239 563.9 233 560 233 L 560 233 L 560 206 L 456.37 206" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 598.88 760 L 591.88 763.5 L 593.63 760 L 591.88 756.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><path d="M 451.12 206 L 458.12 202.5 L 456.37 206 L 458.12 209.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(517.5,412.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="87" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;background-color:#ffffff;">PBrowserBridge</div></div></foreignObject><text x="44" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">PBrowserBridge</text></switch></g><rect x="600" y="729.5" width="120" height="60" fill="#ffffff" stroke="#000000" pointer-events="none"/><g transform="translate(606.5,753.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="106" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; width: 107px; white-space: nowrap; overflow-wrap: normal; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">BrowserBridgeChild</div></div></foreignObject><text x="53" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">BrowserBridgeChild</text></switch></g><g transform="translate(24.5,19.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="249" height="130" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 130px; max-width: 790px; width: 250px; white-space: normal; overflow-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;"><h1>Gecko IPC for Fission<br /></h1><div>Example:</div><div><xul:browser src="a.com"/></div><div> <iframe src="b.com"/></div><div> <iframe src="a.com"/><br /></div><div><br /></div></div></div></foreignObject><text x="125" y="71" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">[Not supported by viewer]</text></switch></g></g></svg>
\ No newline at end of file diff --git a/dom/docs/ipc/Fission-actors-diagram.png b/dom/docs/ipc/Fission-actors-diagram.png Binary files differnew file mode 100644 index 0000000000..d3acce2c5c --- /dev/null +++ b/dom/docs/ipc/Fission-actors-diagram.png diff --git a/dom/docs/ipc/Fission-framescripts.png b/dom/docs/ipc/Fission-framescripts.png Binary files differnew file mode 100644 index 0000000000..98748bc965 --- /dev/null +++ b/dom/docs/ipc/Fission-framescripts.png diff --git a/dom/docs/ipc/index.rst b/dom/docs/ipc/index.rst new file mode 100644 index 0000000000..4a044ab906 --- /dev/null +++ b/dom/docs/ipc/index.rst @@ -0,0 +1,9 @@ +DOM IPC +======= + +.. toctree:: + :maxdepth: 1 + + jsactors + mainthread + process_model diff --git a/dom/docs/ipc/jsactors.rst b/dom/docs/ipc/jsactors.rst new file mode 100644 index 0000000000..3cd2d63c79 --- /dev/null +++ b/dom/docs/ipc/jsactors.rst @@ -0,0 +1,547 @@ +JSActors +======== + +In the Fission world, the preferred method of communication between between things-that-may-live-in-a-different-process are JSActors. + +At the time of this writing, Fission offers the following JSActors: + +- `JSProcessActor`, to communicate between a child process and its parent; +- `JSWindowActor`, to communicate between a frame and its parent. + +JSProcessActor +--------------- + +What are JSProcessActors? +~~~~~~~~~~~~~~~~~~~~~~~~~ + +A JSProcess pair (see below) is the preferred method of communication between a child process and its parent process. + +In the Fission world, JSProcessActors are the replacement for e10s-era *process scripts*. + +The life of a JSProcessActor pair +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +JSProcessActors always exist by pair: + +- one instance of `JSProcessActorChild`, which lives in the child process – for instance, `MyActorChild`; +- one instance of `JSProcessActorParent`, which lives in the parent process – for instance, `MyActorParent`. + +The pair is instantiated lazily, upon the first call to `getActor("MyActor")` (see below). Note that if a +parent process has several children, the parent process will typically host several instances of `MyActorParent` +whereas the children will each host a single instance of `MyActorChild`. + +JSProcessActor primitives allow sending and receiving messages *within the pair*. As of this writing, +JSProcessActor does not offer primitives for broadcasting, enumerating, etc. + +The pair dies when the child process dies. + +About actor names +`````````````````` + +Note that the names +`MyActorChild` and `MyActorParent` are meaningful – suffixes `Child` and `Parent` are how `getActor(...)` finds +the correct classes to load within the JS code. + + +JSWindowActor +--------------- + +What are JSWindowActors? +~~~~~~~~~~~~~~~~~~~~~~~~~ + +A JSWindowActor pair (see below) is the preferred method of communication between a frame and its parent, regardless of whether the frame +and parent live in the same process or in distinct processes. + +In the Fission world, JSWindowActors are the replacement for *framescripts*. Framescripts were how we structured code to be aware of the parent (UI) and child (content) separation, including establishing the communication channel between the two (via the Frame Message Manager). + +However, the framescripts had no way to establish further process separation downwards (that is, for out-of-process iframes). JSWindowActors will be the replacement. + +How are they structured? +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A review of the pre-Fission Message Manager mechanism +````````````````````````````````````````````````````` + +.. note:: + There are actually several types of Message Managers: Frame Message Managers, Window Message Managers, Group Message Managers and Process Message Managers. For the purposes of this documentation, it's simplest to refer to all of these mechanisms altogether as the "Message Manager mechanism". Most of the examples in this document will be operating on the assumption that the Message Manager is a Frame Message Manager, which is the most commonly used one. + +Currently, in the post `Electrolysis Project`_ Firefox codebase, we have code living in the parent process (UI) that is in plain JS (.js files) or in JS modules (.jsm files). In the child process (hosting the content), we use framescripts (.js) and also JS modules. The framescripts are instantiated once per top-level frame (or, in simpler terms, once per tab). This code has access to all of the DOM from the web content, including all iframes within it. + +The two processes communicate via the Frame Message Manager (mm) using the ``sendAsyncMessage`` / ``receiveMessage`` API, and any code in the parent can communicate with any code in the child (and vice versa), by just listening to the messages of interest. + +The Frame Message Manager communication mechanism follows a publish / subscribe pattern similar to how Events work in Firefox: + +1. Something exposes a mechanism for subscribing to notifications (``addMessageListener`` for the Frame Message Manager, ``addEventListener`` for Events). +2. The subscriber is responsible for unsubscribing when there's no longer interest in the notifications (``removeMessageListener`` for the Frame Message Manager, ``removeEventListener`` for Events). +3. Any number of subscribers can be attached at any one time. + +.. figure:: Fission-framescripts.png + :width: 320px + :height: 200px + +How JSWindowActors differ from the Frame Message Manager +`````````````````````````````````````````````````````````` + +For Fission, the JSWindowActors replacing framescripts will be structured in pairs. A pair of JSWindowActors will be instantiated lazily: one in the parent and one in the child process, and a direct channel of communication between the two will be established. The JSWindowActor in the parent must extend the global ``JSWindowActorParent`` class, and the JSWindowActor in the child must extend the global ``JSWindowActorChild`` class. + +The JSWindowActor mechanism is similar to how `IPC Actors`_ work in the native layer of Firefox: + +#. Every Actor has one counterpart in another process that they can communicate directly with. +#. Every Actor inherits a common communications API from a parent class. +#. Every Actor has a name that ends in either ``Parent`` or ``Child``. +#. There is no built-in mechanism for subscribing to messages. When one JSWindowActor sends a message, the counterpart JSWindowActor on the other side will receive it without needing to explicitly listen for it. + +Other notable differences between JSWindowActor's and Message Manager / framescripts: + +#. Each JSWindowActor pair is associated with a particular frame. For example, given the following DOM hierarchy:: + + <browser src="https://www.example.com"> + <iframe src="https://www.a.com" /> + <iframe src="https://www.b.com" /> + + A ``JSWindowActorParent`` / ``JSWindowActorChild`` pair instantiated for either of the ``iframe``'s would only be sending messages to and from that ``iframe``. + +#. There's only one pair per actor type, per frame. + + For example, suppose we have a ``ContextMenu`` actor. The parent process can have up to N instances of the ``ContextMenuParent`` actor, where N is the number of frames that are currently loaded. For any individual frame though, there's only ever one `ContextMenuChild` associated with that frame. + +#. We can no longer assume full, synchronous access to the frame tree, even in content processes. + + This is a natural consequence of splitting frames to run out-of-process. + +#. ``JSWindowActorChild``'s live as long as the ``WindowGlobalChild`` they're associated with. + + If in the previously mentioned DOM hierarchy, one of the ``<iframe>``'s unload, any associated JSWindowActor pairs will be torn down. + +.. hint:: + JSWindowActors are "managed" by the WindowGlobal IPC Actors, and are implemented as JS classes (subclasses of ``JSWindowActorParent`` and ``JSWindowActorChild``) instantiated when requested for any particular window. Like the Frame Message Manager, they are ultimately using IPC Actors to communicate under the hood. + +.. figure:: Fission-actors-diagram.png + :width: 233px + :height: 240px + +.. note:: + Like the Message Manager, JSWindowActors are implemented for both in-process and out-of-process frame communication. This means that porting to JSWindowActors can be done immediately without waiting for out-of-process iframes to be enabled. + + +Communication with actors +------------------------- + +Sending messages +~~~~~~~~~~~~~~~~ + +The ``JSActor`` base class exposes two methods for sending messages. Both methods are asynchronous. +There **is no way to send messages synchronously** with ``JSActor``. + + +``sendAsyncMessage`` +```````````````````` + + sendAsyncMessage("SomeMessage", value); + +Where `value` is anything that can be serialized using the structured clone algorithm. Additionally, a ``nsIPrincipal`` can be sent without having to manually serializing and deserializing it. + +.. note:: + Cross Process Object Wrappers (CPOWs) cannot be sent over JSWindowActors. + + +``sendQuery`` +````````````` + + Promise<any> sendQuery("SomeMessage", value); + + +``sendQuery`` improves upon ``sendAsyncMessage`` by returning a ``Promise``. The receiver of the message must then return a ``Promise`` that can eventually resolve into a value - at which time the ``sendQuery`` ``Promise`` resolves with that value. + +The ``sendQuery`` method arguments follow the same conventions as ``sendAsyncMessage``, with the second argument being a structured clone. + +Receiving messages +~~~~~~~~~~~~~~~~~~ + +``receiveMessage`` +`````````````````` + +To receive messages, you need to implement + + receiveMessage(value) + +The method receives a single argument, which is the de-serialized arguments that were sent via either ``sendAsyncMessage`` or ``sendQuery``. + +.. note:: + If `receiveMessage` is responding to a `sendQuery`, it MUST return a ``Promise`` for that message. + +.. hint:: + Using ``sendQuery``, and the ``receiveMessage`` is able to return a value right away? Try using ``Promise.resolve(value);`` to return ``value``, or you could also make your ``receiveMessage`` method an async function, presuming none of the other messages it handles need to get a non-Promise return value. + +Other methods that can be overridden +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``constructor()`` + +If there's something you need to do as soon as the ``JSActor`` is instantiated, the ``constructor`` function is a great place to do that. + +.. note:: + At this point the infrastructure for sending messages is not ready yet and objects such as ``manager`` or ``browsingContext`` are not available. + +``observe(subject, topic, data)`` +````````````````````````````````` + +If you register your Actor to listen for ``nsIObserver`` notifications, implement an ``observe`` method with the above signature to handle the notification. + +``handleEvent(event)`` +`````````````````````` + +If you register your Actor to listen for content events, implement a ``handleEvent`` method with the above signature to handle the event. + +.. note:: + Only JSWindowActors can register to listen for content events. + +``actorCreated`` +```````````````` + +This method is called immediately *after* a child actor is created and initialized. Unlike the actor's constructor, it is possible to do things like access the actor's content window and send messages from this callback. + +``didDestroy`` +`````````````` + +This is another point to clean-up an Actor before it is destroyed, but at this point, no communication is possible with the other side. + +.. note:: + This method cannot be async. + +.. note:: + As a `JSProcessActorChild` is destroyed when its process dies, a `JSProcessActorChild` will never receive this call. + +Other things exposed on a JSWindowActorParent +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``CanonicalBrowsingContext`` +```````````````````````````` + +Getter: ``this.browsingcontext``. + +``WindowGlobalParent`` +`````````````````````` + +TODO + +Other things exposed on a JSWindowActorChild +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``BrowsingContext`` +``````````````````` + +TODO + +``WindowGlobalChild`` +````````````````````` + +TODO + + +Helpful getters +``````````````` + +A number of helpful getters exist on a ``JSWindowActorChild``, including: + +``this.document`` +^^^^^^^^^^^^^^^^^ + +The currently loaded document in the frame associated with this ``JSWindowActorChild``. + +``this.contentWindow`` +^^^^^^^^^^^^^^^^^^^^^^ + +The outer window for the frame associated with this ``JSWindowActorChild``. + +``this.docShell`` +^^^^^^^^^^^^^^^^^ + +The ``nsIDocShell`` for the frame associated with this ``JSWindowActorChild``. + +See `JSWindowActor.webidl`_ for more detail on exactly what is exposed on both ``JSWindowActorParent`` and ``JSWindowActorChild`` implementations. + +How to port from message manager and framescripts to JSWindowActors +------------------------------------------------------------------- + +.. _fission.message-manager-actors: + +Message Manager Actors +~~~~~~~~~~~~~~~~~~~~~~ + +While the JSWindowActor mechanism was being designed and developed, large sections of our framescripts were converted to an "actor style" pattern to make eventual porting to JSWindowActors easier. These Actors use the Message Manager under the hood, but made it much easier to shrink our framescripts, and also allowed us to gain significant memory savings by having the actors be lazily instantiated. + +You can find the list of Message Manager Actors (or "Legacy Actors") in :searchfox:`BrowserGlue.sys.mjs <browser/components/BrowserGlue.sys.mjs>` and :searchfox:`ActorManagerParent.sys.mjs <toolkit/modules/ActorManagerParent.sys.mjs>`, in the ``LEGACY_ACTORS`` lists. + +.. note:: + The split in Message Manager Actors defined between ``BrowserGlue`` and ``ActorManagerParent`` is mainly to keep Firefox Desktop specific Actors separate from Actors that can (in theory) be instantiated for non-Desktop browsers (like Fennec and GeckoView-based browsers). Firefox Desktop-specific Actors should be registered in ``BrowserGlue``. Shared "toolkit" Actors should go into ``ActorManagerParent``. + +"Porting" these Actors often means doing what is necessary in order to move their registration entries from ``LEGACY_ACTORS`` to the ``JSWINDOWACTORS`` list. + +Figuring out the lifetime of a new Actor pair +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In the old model, framescript were loaded and executed as soon as possible by the top-level frame. In the JSWindowActor model, the Actors are much lazier, and only instantiate when: + +1. They're instantiated explicitly by calling ``getActor`` on a ``WindowGlobal``, and passing in the name of the Actor. +2. A message is sent to them. +3. A pre-defined ``nsIObserver`` observer notification fires with the subject of the notification corresponding to an inner or outer window. +4. A pre-defined content Event fires. + +Making the Actors lazy like this saves on processing time to get a frame ready to load web pages, as well as the overhead of loading the Actor into memory. + +When porting a framescript to JSWindowActors, often the first question to ask is: what's the entrypoint? At what point should the Actors instantiate and become active? + +For example, when porting the content area context menu for Firefox, it was noted that the ``contextmenu`` event firing in content was a natural event to wait for to instantiate the Actor pair. Once the ``ContextMenuChild`` instantiated, the ``handleEvent`` method was used to inspect the event and prepare a message to be sent to the ``ContextMenuParent``. This example can be found by looking at the patch for the `Context Menu Fission Port`_. + +.. _fission.registering-a-new-jswindowactor: + +Using ContentDOMReference instead of CPOWs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Despite being outlawed as a way of synchronously accessing the properties of objects in other processes, CPOWs ended up being useful as a way of passing handles for DOM elements between processes. + +CPOW messages, however, cannot be sent over the JSWindowActor communications pipe, so this handy mechanism will no longer work. + +Instead, a new module called :searchfox:`ContentDOMReference.sys.mjs <toolkit/modules/ContentDOMReference.sys.mjs>` has been created which supplies the same capability. See that file for documentation. + +How to start porting parent-process browser code to use JSWindowActors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The :ref:`fission.message-manager-actors` work made it much easier to migrate away from framescripts towards something that is similar to ``JSWindowActors``. It did not, however, substantially change how the parent process interacted with those framescripts. + +So when porting code to work with ``JSWindowActors``, we find that this is often where the time goes - refactoring the parent process browser code to accommodate the new ``JSWindowActor`` model. + +Usually, the first thing to do is to find a reasonable name for your actor pair, and get them registered (see :ref:`fission.registering-a-new-jswindowactor`), even if the actors implementations themselves are nothing but unmodified subclasses of ``JSWindowActorParent`` and ``JSWindowActorChild``. + +Next, it's often helpful to find and note all of the places where ``sendAsyncMessage`` is being used to send messages through the old message manager interface for the component you're porting, and where any messages listeners are defined. + +Let's look at a hypothetical example. Suppose we're porting part of the Page Info dialog, which scans each frame for useful information to display in the dialog. Given a chunk of code like this: + +.. code-block:: javascript + + // This is some hypothetical Page Info dialog code. + + let mm = browser.messageManager; + mm.sendAsyncMessage("PageInfo:getInfoFromAllFrames", { someArgument: 123 }); + + // ... and then later on + + mm.addMessageListener("PageInfo:info", async function onmessage(message) { + // ... + }); + +If a ``PageInfo`` pair of ``JSWindowActor``'s is registered, it might be tempting to simply replace the first part with: + +.. code-block:: javascript + + let actor = browser.browsingContext.currentWindowGlobal.getActor("PageInfo"); + actor.sendAsyncMessage("PageInfo:getInfoFromAllFrames", { someArgument: 123 }); + +However, if any of the frames on the page are running in their own process, they're not going to receive that ``PageInfo:getInfoFromAllFrames`` message. Instead, in this case, we should walk the ``BrowsingContext`` tree, and instantiate a ``PageInfo`` actor for each global, and send one message each to get information for each frame. Perhaps something like this: + +.. code-block:: javascript + + let contextsToVisit = [browser.browsingContext]; + while (contextsToVisit.length) { + let currentContext = contextsToVisit.pop(); + let global = currentContext.currentWindowGlobal; + + if (!global) { + continue; + } + + let actor = global.getActor("PageInfo"); + actor.sendAsyncMessage("PageInfo:getInfoForFrame", { someArgument: 123 }); + + contextsToVisit.push(...currentContext.children); + } + +The original ``"PageInfo:info"`` message listener will need to be updated, too. Any responses from the ``PageInfoChild`` actor will end up being passed to the ``receiveMessage`` method of the ``PageInfoParent`` actor. It will be necessary to pass that information along to the interested party (in this case, the dialog code which is showing the table of interesting Page Info). + +It might be necessary to refactor or rearchitect the original senders and consumers of message manager messages in order to accommodate the ``JSWindowActor`` model. Sometimes it's also helpful to have a singleton management object that manages all ``JSWindowActorParent`` instances and does something with their results. + +Where to store state +~~~~~~~~~~~~~~~~~~~~ + +It's not a good idea to store any state within a ``JSWindowActorChild`` that you want to last beyond the lifetime of its ``BrowsingContext``. An out-of-process ``<iframe>`` can be closed at any time, and if it's the only one for a particular content process, that content process will soon be shut down, and any state you may have stored there will go away. + +Your best bet for storing state is in the parent process. + +.. hint:: + If each individual frame needs state, consider using a ``WeakMap`` in the parent process, mapping ``CanonicalBrowsingContext``'s with that state. That way, if the associates frames ever go away, you don't have to do any cleaning up yourself. + +If you have state that you want multiple ``JSWindowActorParent``'s to have access to, consider having a "manager" of those ``JSWindowActorParent``'s inside of the same .jsm file to hold that state. + +Registering a new actor +----------------------- + +``ChromeUtils`` exposes an API for registering actors, but both ``BrowserGlue`` and ``ActorManagerParent`` are the main entry points where the registration occurs. If you want to register an actor, +you should add it either to ``JSPROCESSACTORS`` or ``JSWINDOWACTORS`` in either of those two files. + +In the ``JS*ACTORS`` objects, each key is the name of the actor pair (example: ``ContextMenu``), and the associated value is an ``Object`` of registration parameters. + +The full list of registration parameters can be found: + +- for JSProcessActor in file `JSProcessActor.webidl`_ as ``WindowActorOptions``, ``ProcessActorSidedOptions`` and ``ProcessActorChildOptions``. +- for JSWindowActor in file `JSWindowActor.webidl`_ as ``WindowActorOptions``, ``WindowActorSidedOptions`` and ``WindowActorChildOptions``. + +Here's an example ``JSWindowActor`` registration pulled from ``BrowserGlue.sys.mjs``: + +.. code-block:: javascript + + Plugin: { + kind: "JSWindowActor", + parent: { + esModuleURI: "resource:///actors/PluginParent.sys.mjs", + }, + child: { + esModuleURI: "resource:///actors/PluginChild.sys.mjs", + events: { + PluginCrashed: { capture: true }, + }, + + observers: ["decoder-doctor-notification"], + }, + + allFrames: true, + }, + +This example is for the JSWindowActor implementation of crash reporting for GMP. + +Let's examine parent registration: + +.. code-block:: javascript + + parent: { + esModuleURI: "resource:///actors/PluginParent.sys.mjs", + }, + +Here, we're declaring that class ``PluginParent`` (here, a subclass of ``JSWindowActorParent``) is defined and exported from module ``PluginParent.sys.mjs``. That's all we have to say for the parent (main process) side of things. + +.. note:: + It's not sufficient to just add a new .jsm file to the actors subdirectories. You also need to update the ``moz.build`` files in the same directory to get the ``resource://`` linkages set up correctly. + +Let's look at the second chunk: + +.. code-block:: javascript + + child: { + esModuleURI: "resource:///actors/PluginChild.sys.mjs", + events: { + PluginCrashed: { capture: true }, + }, + + observers: ["decoder-doctor-notification"], + }, + + allFrames: true, + }, + +We're similarly declaring where the ``PluginChild`` subclassing ``JSWindowActorChild`` can be found. + +Next, we declare the content events which, when fired in a window, will cause the ``JSWindowActorChild`` to instantiate if it doesn't already exist, and then have ``handleEvent`` called on the ``PluginChild`` instance. For each event name, an Object of event listener options can be passed. You can use the same event listener options as accepted by ``addEventListener``. If an event listener has no useful effect when the actor hasn't been created yet, ``createActor: false`` may also be specified to avoid creating the actor when not needed. + +.. note:: + Content events make sense for ``JSWindowActorChild`` (which *have* a content) but are ignored for ``JSProcessActorChild`` (which don't). + +Next, we declare that ``PluginChild`` should observe the ``decoder-doctor-notification`` ``nsIObserver`` notification. When that observer notification fires, the ``PluginChild`` actor will be instantiated for the ``BrowsingContext`` corresponding to the inner or outer window that is the subject argument of the observer notification, and the ``observe`` method on that ``PluginChild`` implementation will be called. If you need this functionality to work with other subjects, please file a bug. + +.. note:: + Unlike ``JSWindowActorChild`` subclasses, observer topics specified for ``JSProcessActorChild`` subclasses will cause those child actor instances to be created and invoke their ``observe`` method no matter what the subject argument of the observer is. + +Finally, we say that the ``PluginChild`` actor should apply to ``allFrames``. This means that the ``PluginChild`` is allowed to be loaded in any subframe. If ``allFrames`` is set to false (the default), the actor will only ever load in the top-level frame. + +Design considerations when adding a new actor +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A few things worth bearing in mind when adding your own actor registration: + +- Any ``child`` or ``parent`` side you register **must** have a ``moduleURI`` property. +- You do not need to have both ``child`` and ``parent`` modules, and should avoid having actor sides that do nothing but send messages. The process without a defined module will still get an actor, and you can send messages from that side, but cannot receive them via ``receiveMessage``. Note that you **can** also use ``sendQuery`` from this side, enabling you to handle a response from the other process despite not having a ``receiveMessage`` method. +- If you are writing a JSWindowActor, consider whether you really need ``allFrames`` - it'll save memory and CPU time if we don't need to instantiate the actor for subframes. +- When copying/moving "Legacy" :ref:`fission.message-manager-actors`, remove their ``messages`` properties. They are no longer necessary. + + +Minimal Example Actors +----------------------- + +Get a JSWindowActor +~~~~~~~~~~~~~~~~~~~~ + +**Define an Actor** + +.. code-block:: javascript + + // resource://testing-common/TestWindowParent.jsm + var EXPORTED_SYMBOLS = ["TestWindowParent"]; + class TestParent extends JSWindowActorParent { + ... + } + +.. code-block:: javascript + + // resource://testing-common/TestWindowChild.jsm + var EXPORTED_SYMBOLS = ["TestWindowChild"]; + class TestChild extends JSWindowActorChild { + ... + } + + +**Get a JS window actor for a specific window** + +.. code-block:: javascript + + // get parent side actor + let parentActor = this.browser.browsingContext.currentWindowGlobal.getActor("TestWindow"); + + // get child side actor + let childActor = content.windowGlobalChild.getActor("TestWindow"); + +Get a JSProcessActor +~~~~~~~~~~~~~~~~~~~~ + +**Define an Actor** + +.. code-block:: javascript + + // resource://testing-common/TestProcessParent.jsm + var EXPORTED_SYMBOLS = ["TestProcessParent"]; + class TestParent extends JSProcessActorParent { + ... + } + +.. code-block:: javascript + + // resource://testing-common/TestProcessChild.jsm + var EXPORTED_SYMBOLS = ["TestProcessChild"]; + class TestChild extends JSProcessActorChild { + ... + } + + +**Get a JS process actor for a specific process** + +.. code-block:: javascript + + // get parent side actor + let parentActor = this.browser + .browsingContext + .currentWindowGlobal + .domProcess + .getActor("TestProcess"); + + // get child side actor + let childActor = ChromeUtils.domProcessChild + .getActor("TestProcess"); + +And more +=========== + + +.. _Electrolysis Project: https://wiki.mozilla.org/Electrolysis +.. _IPC Actors: https://developer.mozilla.org/en-US/docs/Mozilla/IPDL/Tutorial +.. _Context Menu Fission Port: https://hg.mozilla.org/mozilla-central/rev/adc60720b7b8 +.. _JSProcessActor.webidl: https://searchfox.org/mozilla-central/source/dom/chrome-webidl/JSProcessActor.webidl +.. _JSWindowActor.webidl: https://searchfox.org/mozilla-central/source/dom/chrome-webidl/JSWindowActor.webidl +.. _BrowserElementParent.jsm: https://searchfox.org/mozilla-central/rev/ec806131cb7bcd1c26c254d25cd5ab8a61b2aeb6/toolkit/actors/BrowserElementParent.jsm diff --git a/dom/docs/ipc/mainthread.rst b/dom/docs/ipc/mainthread.rst new file mode 100644 index 0000000000..c04e8dc484 --- /dev/null +++ b/dom/docs/ipc/mainthread.rst @@ -0,0 +1,13 @@ +================== +Main Thread Actors +================== + +Actors on the main thread between the parent and content processes are +generally managed by ``PContent``, the primary actor for a content process. + +TODO + +Fission Actor Diagram +===================== + +.. image:: Fission-IPC-Diagram.svg diff --git a/dom/docs/ipc/process_model.rst b/dom/docs/ipc/process_model.rst new file mode 100644 index 0000000000..b405566a1d --- /dev/null +++ b/dom/docs/ipc/process_model.rst @@ -0,0 +1,334 @@ +Process Model +============= + +The complete set of recognized process types is defined in `GeckoProcessTypes <https://searchfox.org/mozilla-central/source/xpcom/geckoprocesstypes_generator/geckoprocesstypes/__init__.py>`_. + +For more details on how process types are added and managed by IPC, see the process creation documentation :ref:`Gecko Processes`. + +Diagram +------- + +.. digraph:: processtypes + :caption: Diagram of processes used by Firefox. All child processes are spawned and managed by the Parent process. + + compound=true; + node [shape=rectangle]; + + launcher [label=<Launcher Process>] + parent [label=<Parent Process>] + + subgraph cluster_child { + color=lightgrey; + label=<Child Processes>; + + subgraph cluster_content { + color=lightgrey; + label=<Content Processes>; + + web [ + color=lightgrey; + label=< + <TABLE BORDER="0" CELLSPACING="5" CELLPADDING="5" COLOR="black"> + <TR><TD BORDER="0" CELLPADDING="0" CELLSPACING="0">Web Content</TD></TR> + <TR><TD BORDER="1">Shared Web Content<BR/>(<FONT FACE="monospace">web</FONT>)</TD></TR> + <TR><TD BORDER="1">Isolated Web Content<BR/>(<FONT FACE="monospace">webIsolated=$SITE</FONT>)</TD></TR> + <TR><TD BORDER="1">COOP+COEP Web Content<BR/>(<FONT FACE="monospace">webCOOP+COEP=$SITE</FONT>)</TD></TR> + <TR><TD BORDER="1">ServiceWorker Web Content<BR/>(<FONT FACE="monospace">webServiceWorker</FONT>)</TD></TR> + </TABLE> + > + ] + + nonweb [ + shape=none; + label=< + <TABLE BORDER="0" CELLSPACING="5" CELLPADDING="5" COLOR="black"> + <TR><TD BORDER="1">Preallocated Content<BR/>(<FONT FACE="monospace">prealloc</FONT>)</TD></TR> + <TR><TD BORDER="1">File Content<BR/>(<FONT FACE="monospace">file</FONT>)</TD></TR> + <TR><TD BORDER="1">WebExtensions<BR/>(<FONT FACE="monospace">extension</FONT>)</TD></TR> + <TR><TD BORDER="1">Privileged Content<BR/>(<FONT FACE="monospace">privilegedabout</FONT>)</TD></TR> + <TR><TD BORDER="1">Privileged Mozilla Content<BR/>(<FONT FACE="monospace">privilegedmozilla</FONT>)</TD></TR> + </TABLE> + > + ] + } + + helper [ + color=lightgrey; + label=< + <TABLE BORDER="0" CELLSPACING="5" CELLPADDING="5" COLOR="black"> + <TR><TD BORDER="0" CELLPADDING="0" CELLSPACING="0">Helper Processes</TD></TR> + <TR><TD BORDER="1">Gecko Media Plugins (GMP) Process</TD></TR> + <TR><TD BORDER="1">GPU Process</TD></TR> + <TR><TD BORDER="1">VR Process</TD></TR> + <TR><TD BORDER="1">Data Decoder (RDD) Process</TD></TR> + <TR><TD BORDER="1">Network (Socket) Process</TD></TR> + <TR><TD BORDER="1">Utility Process</TD></TR> + <TR><TD BORDER="1">Remote Sandbox Broker Process</TD></TR> + <TR><TD BORDER="1">Fork Server</TD></TR> + </TABLE> + > + ] + } + + subgraph { rank=same; launcher -> parent; } + + parent -> web [lhead="cluster_content"]; + parent -> helper; + +.. _parent-process: + +Parent Process +-------------- + +:remoteType: *null* +:other names: UI Process, Main Process, Chrome Process, Browser Process, Default Process, Broker Process +:sandboxed?: no + +The parent process is the primary process which handles the core functionality of Firefox, including its UI, profiles, process selection, navigation, and more. The parent process is responsible for launching all other child processes, and acts as a broker establishing communication between them. + +All primary protocols establish a connection between the parent process and the given child process, which can then be used to establish additional connections to other processes. + +As the parent process can display HTML and JS, such as the browser UI and privileged internal pages such as ``about:preferences`` and ``about:config``, it is often treated as-if it was a content process with a *null* remote type by process selection logic. The parent process has extra protections in place to ensure it cannot load untrusted code when running in multiprocess mode. To this effect, any attempts to load web content in the parent process will lead to a browser crash, and all navigations to and from parent-process documents immediately perform full isolation, to prevent content processes from manipulating them. + +.. _content-process: + +Content Process +--------------- + +:primary protocol: `PContent <https://searchfox.org/mozilla-central/source/dom/ipc/PContent.ipdl>`_ +:other names: Renderer Process +:sandboxed?: yes (content sandbox policy) + +Content processes are used to load web content, and are the only process type (other than the parent process) which can load and execute JS code. These processes are further subdivided into specific "remote types", which specify the type of content loaded within them, their sandboxing behavior, and can gate access to certain privileged IPC methods. + +The specific remote type and isolation behaviour used for a specific resource is currently controlled in 2 major places. When performing a document navigation, the final process to load the document in is selected by the logic in `ProcessIsolation.cpp <https://searchfox.org/mozilla-central/source/dom/ipc/ProcessIsolation.cpp>`_. This will combine information about the specific response, such as the site and headers, with other state to select which process and other isolating actions should be taken. When selecting which process to create the initial process for a new tab in, and when selecting processes for serviceworkers and shared workers, the logic in :searchfox:`E10SUtils.sys.mjs <toolkit/modules/E10SUtils.sys.mjs>`_ is used to select a process. The logic in ``E10SUtils.sys.mjs`` will likely be removed and replaced with ``ProcessIsolation.cpp`` in the future. + +.. note:: + + The "Renderer" alternative name is used by Chromium for its equivalent to content processes, and is occasionally used in Gecko as well, due to the similarity in process architecture. The actual rendering & compositing steps are performed in the GPU or main process. + +Preallocated Content +^^^^^^^^^^^^^^^^^^^^ + +:remoteType: ``prealloc`` +:default count: 3 (``dom.ipc.processPrelaunch.fission.number``, or 1 if Fission is disabled) + +To avoid the need to launch new content processes to host new content when navigating, new content processes are pre-launched and specialized when they are requested. These preallocated content processes will never load content, and must be specialized before they can be used. + +The count of preallocated processes can vary depending on various factors, such as the memory available in the host system. + +The ``prealloc`` process cannot be used to launch ``file`` content processes, due to their weakened OS sandbox. ``extension`` content processes are also currently not supported due to `Bug 1637119 <https://bugzilla.mozilla.org/show_bug.cgi?id=1638119>`_. + +File Content +^^^^^^^^^^^^ + +:remoteType: ``file`` +:default count: 1 (``dom.ipc.processCount.file``) +:capabilities: File System Access + +The File content process is used to load ``file://`` URIs, and is therefore less sandboxed than other content processes. It may also be used to load remote web content if the browser has used a legacy CAPS preference to allow that site to access local resources (see `Bug 995943 <https://bugzilla.mozilla.org/show_bug.cgi?id=995943>`_) + +WebExtensions +^^^^^^^^^^^^^ + +:remoteType: ``extension`` +:default count: 1 (``dom.ipc.processCount.extension``) +:capabilities: Extension APIs, Shared Memory (SharedArrayBuffer) + +The WebExtension content process is used to load background pages and top level WebExtension frames. This process generally has access to elevated permissions due to loading privileged extension pages with access to the full WebExtension API surface. Currently all extensions share a single content process. + +Privileged extensions loaded within the extension process may also be granted access to shared memory using SharedArrayBuffer. + +.. note:: + + ``moz-extension://`` subframes are currently loaded in the same process as the parent document, rather than in the ``extension`` content process, due to existing permissions behaviour granting content scripts the ability to access the content of extension subframes. This may change in the future. + +Privileged Content +^^^^^^^^^^^^^^^^^^ + +:remoteType: ``privilegedabout`` +:default count: 1 (``dom.ipc.processCount.privilegedabout``) +:capabilities: Restricted JSWindowActor APIs + +The ``privilegedabout`` content process is used to load internal pages which have privileged access to internal state. The use of the ``privilegedabout`` content process is requested by including both ``nsIAboutModule::URI_MUST_LOAD_IN_CHILD`` and ``nsIAboutModule::URI_CAN_LOAD_IN_PRIVILEGEDABOUT_PROCESS`` flags in the corresponding ``nsIAboutModule``. + +As of August 11, 2021, the following internal pages load in the privileged content process: ``about:logins``, ``about:loginsimportreport``, ``about:privatebrowsing``, ``about:home``, ``about:newtab``, ``about:welcome``, ``about:protections``, and ``about:certificate``. + +Various ``JSWindowActor`` instances which provide special API access for these internal about pages are restricted to only be available in this content process through the ``remoteTypes`` attribute, which will block attempts to use them from other content processes. + +Privileged Mozilla Content +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:remoteType: ``privilegedmozilla`` +:default count: 1 (``dom.ipc.processCount.privilegedmozilla``) +:domains: ``addons.mozilla.org`` and ``accounts.firefox.com`` (``browser.tabs.remote.separatedMozillaDomains``) +:capabilities: Restricted Addon Manager APIs + +The ``privilegedmozilla`` content process is used to load specific high-value Mozilla-controlled webpages which have been granted access to privileged features. To provide an extra layer of security for these sites, they are loaded in a separate process from other web content even when Fission is disabled. + +This separate remote type is also used to gate access at the IPC boundary to certain high-power web APIs, such as access to the ability to interact with installed extension APIs. + +Web Content Processes +^^^^^^^^^^^^^^^^^^^^^ + +These processes all have remote types beginning with ``web``, and are used to host general untrusted web content. The different variants of web content processes are used at different times, depending on the isolation strategy requested by the page and the browser's configuration. + +Shared Web Content +"""""""""""""""""" + +:remoteType: ``web`` +:default count: 8 (``dom.ipc.processCount``) + +The shared web content process is used to host content which is not isolated into one of the other web content process types. This includes almost all web content with Fission disabled, and web content which cannot be attributed to a specific origin with Fission enabled, such as user-initiated ``data:`` URI loads. + +Isolated Web Content +"""""""""""""""""""" + +:remoteType: ``webIsolated=$SITE`` +:default count: 1 per-site (``dom.ipc.processCount.webIsolated``) + +Isolated web content processes are used to host web content with Fission which can be attributed to a specific site. These processes are allocated when navigating, and will only load content from the named site. When Fission is disabled, isolated web content processes are not used. + +A different ``webIsolated=`` remote type, and therefore a different pool of processes, is used for each site loaded, with separation also being used for different container tabs and private browsing. + +COOP+COEP Web Content +""""""""""""""""""""" + +:remoteType: ``webCOOP+COEP=$SITE`` +:default count: 1 per-site (``dom.ipc.processCount.webCOOP+COEP``) +:capabilities: Shared Memory (SharedArrayBuffer) + +When loading a top level document with both the ``Cross-Origin-Opener-Policy`` and ``Cross-Origin-Embedder-Policy`` headers configured correctly, the document is requesting access to Shared Memory. For security reasons, we only provide this API access to sufficiently-isolated pages, and we load them within special isolated content processes. + +Like Isolated Web Content, these processes are keyed by the site loaded within them, and are also segmented based on container tabs and private browsing. + +.. note:: + + Another name for this process may be "Cross-Origin Isolated Web Content", to correspond with the ``window.crossOriginIsolated`` attribute which is set for documents loaded with these headers set. Unfortunately that may be confused with Fission's "Isolated Web Content" processes, as the attribute was named after the ``webIsolated`` remote type was already in use. + + In ``about:processes``, COOP+COEP Web Content processes will be listed with a "cross-origin isolated" note after the PID, like ``https://example.com (12345, cross-origin isolated)``. + +ServiceWorker Web Content +""""""""""""""""""""""""" + +:remoteType: ``webServiceWorker=$SITE`` +:default count: 1 per-site using ServiceWorkers + +ServiceWorker web content processes are used to host ServiceWorkers on a per-site basis, so that ServiceWorker operations aren't impacted by MainThread event latency whenrunning in the same process as the content for the page. ServiceWorkers are usually transitory, and will disappear if unused for a short period of time. + +.. _gecko-media-plugins-process: + +Gecko Media Plugins (GMP) Process +--------------------------------- + +:primary protocol: `PGMP <https://searchfox.org/mozilla-central/source/dom/media/gmp/PGMP.ipdl>`_ +:sandboxed?: yes (GMP sandbox policy) + +The GMP process is used to sandbox third-party "Content Decryption Module" (CDM) binaries used for media playback in a sandboxed environment. This process is only launched when DRM-enabled content is loaded. + +.. _gpu-process: + +GPU Process +----------- + +:primary protocol: `PGPU <https://searchfox.org/mozilla-central/source/gfx/ipc/PGPU.ipdl>`_ +:other names: Compositor Process +:sandboxed?: no (`bug 1347710 <https://bugzilla.mozilla.org/show_bug.cgi?id=1347710>`_ tracks sandboxing on windows) + +The GPU process performs compositing, and is used to talk to GPU hardware in an isolated process. This helps isolate things like GPU driver crashes from impacting the entire browser, and will allow for this code to be sandboxed in the future. In addition, some components like Windows Media Foundation (WMF) are run in the GPU process when it is available. + +The GPU process is not used on all platforms. Platforms which do not use it, such as macOS and some Linux configurations, will perform compositing on a background thread in the Parent Process. + +.. _vr-process: + +VR Process +---------- + +:primary protocol: `PVR <https://searchfox.org/mozilla-central/source/gfx/vr/ipc/PVR.ipdl>`_ +:sandboxed?: no (`bug 1430043 <https://bugzilla.mozilla.org/show_bug.cgi?id=1430043>`_ tracks sandboxing on windows) + +VR headset libraries require access to specific OS level features and other requirements which we would generally like to block with the sandbox in other processes. In order to allow the GPU process to have tighter sandboxing rules, these VR libraries are loaded into the less-restricted VR process. Like the GPU process, this serves to isolate them from the rest of Firefox and reduce the impact of bugs in these libraries on the rest of the browser. The VR process is launched only after a user visits a site which uses WebVR. + +.. _data-decoder-process: + +Data Decoder (RDD) Process +-------------------------- + +:primary protocol: `PRDD <https://searchfox.org/mozilla-central/source/dom/media/ipc/PRDD.ipdl>`_ +:sandboxed?: yes (RDD sandbox policy) + +This process is used to run media data decoders within their own sandboxed process, allowing the code to be isolated from other code in Gecko. This aims to reduce the severity of potential bugs in media decoder libraries, and improve the security of the browser. + +.. note:: + + This process is in the process of being restructured into a generic "utility" process type for running untrusted code in a maximally secure sandbox. After these changes, the following new process types will exist, replacing the RDD process: + + * ``Utility``: A maximally sandboxed process used to host untrusted code which does not require access to OS resources. This process will be even more sandboxed than RDD today on Windows, where the RDD process has access to Win32k. + * ``UtilityWithWin32k``: A Windows-only process with the same sandboxing as the RDD process today. This will be used to host untrusted sandboxed code which requires access to Win32k to allow decoding directly into GPU surfaces. + * ``GPUFallback``: A Windows-only process using the GPU process' sandboxing policy which will be used to run Windows Media Foundation (WMF) when the GPU process itself is unavailable, allowing ``UtilityWithWin32k`` to re-enable Arbitrary Code Guard (ACG) on Windows. + + For more details about the planned utility process architecture changes, see `the planning document <https://docs.google.com/document/d/1WDEY5fQetK_YE5oxGxXK9BzC1A8kJP3q6F1gAPc2UGE>`_. + +.. _network-socket-process: + +Network (Socket) Process +------------------------ + +:primary protocol: `PSocketProcess <https://searchfox.org/mozilla-central/source/netwerk/ipc/PSocketProcess.ipdl>`_ +:sandboxed?: yes (socket sandbox policy) + +The socket process is used to separate certain networking operations from the parent process, allowing them to be performed more directly in a partially sandboxed process. The eventual goal is to move all TCP/UDP network operations into this dedicated process, and is being tracked in `Bug 1322426 <https://bugzilla.mozilla.org/show_bug.cgi?id=1322426>`_. + +.. _remote-sandbox-process: + +Remote Sandbox Broker Process +----------------------------- + +:platform: Windows on ARM only +:primary protocol: `PRemoteSandboxBroker <https://searchfox.org/mozilla-central/source/security/sandbox/win/src/remotesandboxbroker/PRemoteSandboxBroker.ipdl>`_ +:sandboxed?: no + +In order to run sandboxed x86 plugin processes from Windows-on-ARM, the remote sandbox broker process is launched in x86-mode, and used to launch sandboxed x86 subprocesses. This avoids issues with the sandboxing layer, which unfortunately assumes that pointer width matches between the sandboxer and sandboxing process. To avoid this, the remote sandbox broker is used as an x86 sandboxing process which wraps these plugins. + +.. _fork-server: + +Fork Server +----------- + +:platform: Linux only +:pref: ``dom.ipc.forkserver.enable`` (disabled by default) +:primary protocol: *none* +:sandboxed?: no (processes forked by the fork server are sandboxed) + +The fork server process is used to reduce the memory overhead and improve launch efficiency for new processes. When a new supported process is requested and the feature is enabled, the parent process will ask the fork server to ``fork(2)`` itself, and then begin executing. This avoids the need to re-load ``libxul.so`` and re-perform relocations. + +The fork server must run before having initialized XPCOM or the IPC layer, and therefore uses a custom low-level IPC system called ``MiniTransceiver`` rather than IPDL to communicate. + +.. _launcher-process: + +Launcher Process +---------------- + +:platform: Windows only +:metabug: `Bug 1435780 <https://bugzilla.mozilla.org/show_bug.cgi?id=1435780>`_ +:sandboxed?: no + +The launcher process is used to bootstrap Firefox on Windows before launching the main Firefox process, allowing things like DLL injection blocking to initialize before the main thread even starts running, and improving stability. Unlike the other utility processes, this process is not launched by the parent process, but rather launches it. + +IPDLUnitTest +------------ + +:primary protocol: varies + +This test-only process type is intended for use when writing IPDL unit tests. However, it is currently broken, due to these tests having never been run in CI. The type may be removed or re-used when these unit tests are fixed. + +.. _utility-process: + +Utility Process +--------------- + +:primary protocol: `PUtilityProcess <https://searchfox.org/mozilla-central/source/ipc/glue/PUtilityProcess.ipdl>`_ +:metabug: `Bug 1722051 <https://bugzilla.mozilla.org/show_bug.cgi?id=1722051>`_ +:sandboxed?: yes, customizable + +The utility process is used to provide a simple way to implement IPC actor with some more specific sandboxing properties, in case where you don't need or want to deal with the extra complexity of adding a whole new process type but you just want to apply different sandboxing policies. Details can be found in :ref:`Utility Process`. diff --git a/dom/docs/navigation/BrowsingContext.rst b/dom/docs/navigation/BrowsingContext.rst new file mode 100644 index 0000000000..213b2fcce5 --- /dev/null +++ b/dom/docs/navigation/BrowsingContext.rst @@ -0,0 +1,149 @@ +BrowsingContext and WindowContext +================================= + +The ``BrowsingContext`` is the Gecko representation of the spec-defined +`Browsing Context`_ object. + +.. _Browsing Context: https://html.spec.whatwg.org/multipage/browsers.html#browsing-context + + +The Browsing Context Tree +------------------------- + +``BrowsingContext`` and ``WindowContext`` objects form a tree, corresponding +to the tree of frame elements which was used to construct them. + + +Example +^^^^^^^ + +Loading the HTML documents listed here, would end up creating a set of BrowsingContexts and WindowContexts forming the tree. + +.. code-block:: html + + <!-- http://example.com/top.html --> + <iframe src="frame1.html"></iframe> + <iframe src="http://mozilla.org/"></iframe> + + <!-- http://example.com/frame1.html --> + <iframe src="http://example.com/frame2.html"></iframe> + + <!-- http://mozilla.org --> + <iframe></iframe> + <iframe></iframe> + +.. digraph:: browsingcontext + + node [shape=rectangle] + + "BC1" [label="BrowsingContext A"] + "BC2" [label="BrowsingContext B"] + "BC3" [label="BrowsingContext C"] + "BC4" [label="BrowsingContext D"] + "BC5" [label="BrowsingContext E"] + "BC6" [label="BrowsingContext F"] + + "WC1" [label="WindowContext\n(http://example.com/top.html)"] + "WC2" [label="WindowContext\n(http://example.com/frame1.html)"] + "WC3" [label="WindowContext\n(http://mozilla.org)"] + "WC4" [label="WindowContext\n(http://example.com/frame2.html)"] + "WC5" [label="WindowContext\n(about:blank)"] + "WC6" [label="WindowContext\n(about:blank)"] + + "BC1" -> "WC1"; + "WC1" -> "BC2"; + "WC1" -> "BC3"; + "BC2" -> "WC2"; + "BC3" -> "WC3"; + "WC2" -> "BC4"; + "BC4" -> "WC4"; + "WC3" -> "BC5"; + "BC5" -> "WC5"; + "WC3" -> "BC6"; + "BC6" -> "WC6"; + + +Synced Fields +------------- + +WIP - In-progress documentation at `<https://wiki.mozilla.org/Project_Fission/BrowsingContext>`_. + + +API Documentation +----------------- + +.. cpp:class:: BrowsingContext + + .. hlist:: + :columns: 3 + + * `header (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/BrowsingContext.h>`_ + * `source (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/BrowsingContext.cpp>`_ + * `html spec <https://html.spec.whatwg.org/multipage/browsers.html#browsing-context>`_ + + This is a synced-context type. Instances of it will exist in every + "relevant" content process for the navigation. + + Instances of :cpp:class:`BrowsingContext` created in the parent processes + will be :cpp:class:`CanonicalBrowsingContext`. + + .. cpp:function:: WindowContext* GetParentWindowContext() + + Get the parent ``WindowContext`` embedding this context, or ``nullptr``, + if this is the toplevel context. + + .. cpp:function:: WindowContext* GetTopWindowContext() + + Get the toplevel ``WindowContext`` embedding this context, or ``nullptr`` + if this is the toplevel context. + + This is equivalent to repeatedly calling ``GetParentWindowContext()`` + until it returns nullptr. + + .. cpp:function:: BrowsingContext* GetParent() + + .. cpp:function:: BrowsingContext* Top() + + .. cpp:function:: static already_AddRefed<BrowsingContext> Get(uint64_t aId) + + Look up a specific ``BrowsingContext`` by it's unique ID. Callers should + check if the returned context has already been discarded using + ``IsDiscarded`` before using it. + +.. cpp:class:: CanonicalBrowsingContext : public BrowsingContext + + .. hlist:: + :columns: 3 + + * `header (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/CanonicalBrowsingContext.h>`_ + * `source (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/CanonicalBrowsingContext.cpp>`_ + + When a :cpp:class:`BrowsingContext` is constructed in the parent process, + it is actually an instance of :cpp:class:`CanonicalBrowsingContext`. + + Due to being in the parent process, more information about the context is + available from a ``CanonicalBrowsingContext``. + +.. cpp:class:: WindowContext + + .. hlist:: + :columns: 3 + + * `header (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/WindowContext.h>`_ + * `source (searchfox) <https://searchfox.org/mozilla-central/source/docshell/base/WindowContext.cpp>`_ + +.. cpp:class:: WindowGlobalParent : public WindowContext, public WindowGlobalActor, public PWindowGlobalParent + + .. hlist:: + :columns: 3 + + * `header (searchfox) <https://searchfox.org/mozilla-central/source/dom/ipc/WindowGlobalParent.h>`_ + * `source (searchfox) <https://searchfox.org/mozilla-central/source/dom/ipc/WindowGlobalParent.cpp>`_ + +.. cpp:class:: WindowGlobalChild : public WindowGlobalActor, public PWindowGlobalChild + + .. hlist:: + :columns: 3 + + * `header (searchfox) <https://searchfox.org/mozilla-central/source/dom/ipc/WindowGlobalChild.h>`_ + * `source (searchfox) <https://searchfox.org/mozilla-central/source/dom/ipc/WindowGlobalChild.cpp>`_ diff --git a/dom/docs/navigation/embedding.rst b/dom/docs/navigation/embedding.rst new file mode 100644 index 0000000000..a42aabc6f5 --- /dev/null +++ b/dom/docs/navigation/embedding.rst @@ -0,0 +1,92 @@ +Browsing Context Embedding +========================== + +Embedder Element to nsDocShell +------------------------------ + +In order to render the contents of a ``BrowsingContext``, the embedding +element needs to be able to communicate with the ``nsDocShell`` which is +currently being used to host it's content. This is done in 3 different ways +depending on which combination of processes is in-use. + +- *in-process*: The ``nsFrameLoader`` directly embeds the ``nsDocShell``. +- *remote tab*: The parent process is the embedder, and uses a ``PBrowser``, + via a ``BrowserHost``. The ``BrowserChild`` actor holds the actual + ``nsDocShell`` alive. +- *remote subframe*: A content process is the embedder, and uses a + ``PBrowserBridge``, via a ``BrowserBridgeHost`` to communicate with the + parent process. The parent process then uses a ``BrowserParent``, as in the + *remote tab* case, to communicate with the ``nsDocShell``. + +Diagram +^^^^^^^ + +.. digraph:: embedding + + node [shape=rectangle] + + subgraph cluster_choice { + color=transparent; + node [shape=none]; + + "In-Process"; + "Remote Tab"; + "Remote Subframe"; + } + + "nsFrameLoaderOwner" [label="nsFrameLoaderOwner\ne.g. <iframe>, <xul:browser>, <embed>"] + + "nsFrameLoaderOwner" -> "nsFrameLoader"; + + "nsFrameLoader" -> "In-Process" [dir=none]; + "nsFrameLoader" -> "Remote Tab" [dir=none]; + "nsFrameLoader" -> "Remote Subframe" [dir=none]; + + "In-Process" -> "nsDocShell"; + "Remote Tab" -> "BrowserHost"; + "Remote Subframe" -> "BrowserBridgeHost"; + + "BrowserHost" -> "BrowserParent"; + "BrowserParent" -> "BrowserChild" [label="PBrowser" style=dotted]; + "BrowserChild" -> "nsDocShell"; + + "BrowserBridgeHost" -> "BrowserBridgeChild"; + "BrowserBridgeChild" -> "BrowserBridgeParent" [label="PBrowserBridge", style=dotted]; + "BrowserBridgeParent" -> "BrowserParent"; + +nsDocShell to Document +---------------------- + +Embedding an individual document within a ``nsDocShell`` is done within the +content process, which has that docshell. + + +Diagram +^^^^^^^ + +This diagram shows the objects involved in a content process which is being +used to host a given ``BrowsingContext``, along with rough relationships +between them. Dotted lines represent a "current" relationship, whereas solid +lines are a stronger lifetime relationship. + +.. graph:: document + + node [shape=rectangle] + + "BrowsingContext" -- "nsDocShell" [style=dotted]; + "nsDocShell" -- "nsGlobalWindowOuter"; + "nsGlobalWindowOuter" -- "nsGlobalWindowInner" [style=dotted]; + "nsGlobalWindowInner" -- "Document" [style=dotted]; + + "nsDocShell" -- "nsDocumentViewer" [style=dotted]; + "nsDocumentViewer" -- "Document"; + "nsDocumentViewer" -- "PresShell"; + + "nsGlobalWindowInner" -- "WindowGlobalChild"; + "BrowsingContext" -- "WindowContext" [style=dotted]; + "WindowContext" -- "nsGlobalWindowInner"; + + subgraph cluster_synced { + label = "Synced Contexts"; + "BrowsingContext" "WindowContext"; + } diff --git a/dom/docs/navigation/index.rst b/dom/docs/navigation/index.rst new file mode 100644 index 0000000000..b322855eb6 --- /dev/null +++ b/dom/docs/navigation/index.rst @@ -0,0 +1,9 @@ +DOM Navigation +============== + +.. toctree:: + :maxdepth: 1 + + embedding + BrowsingContext + nav_replace diff --git a/dom/docs/navigation/nav_replace.rst b/dom/docs/navigation/nav_replace.rst new file mode 100644 index 0000000000..6e2c710e28 --- /dev/null +++ b/dom/docs/navigation/nav_replace.rst @@ -0,0 +1,119 @@ +Objects Replaced by Navigations +=============================== + +There are 3 major types of navigations, each of which can cause different +objects to be replaced. The general rules look something like this: + +.. csv-table:: objects replaced or preserved across navigations + :header: "Class/Id", ":ref:`in-process navigations <in-process navigations>`", ":ref:`cross-process navigations <cross-process navigations>`", ":ref:`cross-group navigations <cross-group navigations>`" + + "BrowserId [#bid]_", |preserve|, |preserve|, |preserve| + "BrowsingContextWebProgress", |preserve|, |preserve|, |preserve| + "BrowsingContextGroup", |preserve|, |preserve|, |replace| + "BrowsingContext", |preserve|, |preserve|, |replace| + "nsFrameLoader", |preserve|, |replace|, |replace| + "RemoteBrowser", |preserve|, |replace|, |replace| + "Browser{Parent,Child}", |preserve|, |replace|, |replace| + "nsDocShell", |preserve|, |replace|, |replace| + "nsGlobalWindowOuter", |preserve|, |replace|, |replace| + "nsGlobalWindowInner", "|replace| [#inner]_", |replace|, |replace| + "WindowContext", "|replace| [#inner]_", |replace|, |replace| + "WindowGlobal{Parent,Child}", "|replace| [#inner]_", |replace|, |replace| + "Document", "|replace|", |replace|, |replace| + + +.. |replace| replace:: ❌ replaced +.. |preserve| replace:: ✔️ preserved + +.. [#bid] + + The BrowserId is a unique ID on each ``BrowsingContext`` object, obtained + using ``GetBrowserId``, not a class. This ID will persist even when a + ``BrowsingContext`` is replaced (e.g. due to + ``Cross-Origin-Opener-Policy``). + +.. [#inner] + + When navigating from the initial ``about:blank`` document to a same-origin + document, the same ``nsGlobalWindowInner``, ``WindowContext`` and + ``WindowGlobal{Parent,Child}`` may be used. This initial ``about:blank`` + document is the one created when synchronously accessing a newly-created + pop-up window from ``window.open``, or a newly-created document in an + ``<iframe>``. + +Types of Navigations +-------------------- + +.. _in-process navigations: + +in-process navigations +^^^^^^^^^^^^^^^^^^^^^^ + +An in-process navigation is the traditional type of navigation, and the most +common type of navigation when :ref:`Fission` is not enabled. + +These navigations are used when no process switching or BrowsingContext +replacement is required, which includes most navigations with Fission +disabled, and most same site-origin navigations when Fission is enabled. + +.. _cross-process navigations: + +cross-process navigations +^^^^^^^^^^^^^^^^^^^^^^^^^ + +A cross-process navigation is used when a navigation requires a process +switch to occur, and no BrowsingContext replacement is required. This is a +common type of load when :ref:`Fission` is enabled, though it is also used +for navigations to and from special URLs like ``file://`` URIs when +Fission is disabled. + +These process changes are triggered by ``DocumentLoadListener`` when it +determines that a process switch is required. See that class's documentation +for more details. + +.. _cross-group navigations: + +cross-group navigations +^^^^^^^^^^^^^^^^^^^^^^^ + +A cross-group navigation is used when the navigation's `response requires +a browsing context group switch +<https://html.spec.whatwg.org/multipage/origin.html#browsing-context-group-switches-due-to-cross-origin-opener-policy>`_. + +These types of switches may or may not cause the process to change, but will +finish within a different ``BrowsingContextGroup`` than they started with. +Like :ref:`cross-process navigations`, these navigations are triggered using +the process switching logic in ``DocumentLoadListener``. + +As the parent of a content browsing context cannot change due to a navigation, +only toplevel content browsing contexts can cross-group navigate. Navigations in +chrome browsing contexts [#chromebc]_ or content subframes only experience +either in-process or cross-process navigations. + +As of the time of this writing, we currently trigger a cross-group navigation +in the following circumstances, though this may change in the future: + +- If the `Cross-Origin-Opener-Policy + <https://html.spec.whatwg.org/multipage/origin.html#the-cross-origin-opener-policy-header>`_ + header is specified, and a mismatch is detected. +- When switching processes between the parent process, and a content process. +- When loading an extension document in a toplevel browsing context. +- When navigating away from a preloaded ``about:newtab`` document. +- When putting a ``BrowsingContext`` into BFCache for the session history + in-parent BFCache implementation. This will happen on most toplevel + navigations without opener relationships when the ``fission.bfcacheInParent`` + pref is enabled. + +State which needs to be saved over cross-group navigations on +``BrowsingContext`` instances is copied in the +``CanonicalBrowsingContext::ReplacedBy`` method. + +.. [#chromebc] + + A chrome browsing context does **not** refer to pages with the system + principal loaded in the content area such as ``about:preferences``. + Chrome browsing contexts are generally used as the root context in a chrome + window, such where ``browser.xhtml`` is loaded for a browser window. + + All chrome browsing contexts exclusively load in the parent process and + cannot process switch when navigating. diff --git a/dom/docs/push/index.md b/dom/docs/push/index.md new file mode 100644 index 0000000000..fb9e3db380 --- /dev/null +++ b/dom/docs/push/index.md @@ -0,0 +1,118 @@ +# Push +<div class="note"> +<div class="admonition-title">Note</div> +This document describes how Firefox implements the Web Push standard internally, and is intended for developers working directly on Push. If you are looking for how to consume push, please refer to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Push_API" target="_blank">following MDN document</a> + +</div> + +## High level push architecture +The following sequence diagram describes the high level push architecture as observed by web application. The diagram describes the interactions between a Web application's client code running in the browser, Firefox, [Autopush](https://autopush.readthedocs.io/en/latest/) (Firefox's push server that delivers push notifications) and a third party server that sends the push notifications to Autopush + +The dotted lines are done by the consumer of push. +```{mermaid} +sequenceDiagram + participant TP as Web Application JS + participant F as Firefox + participant A as Autopush + participant TPS as Third party Server + TP->>F: subscribe(scope) + activate TP + activate F + F->>A: subscribe(scope) using web socket + activate A + A->>F: URL + deactivate A + F->>F: Create pub/privKey Encryption pair + F->>F: Persist URL, pubKey, privKey indexed using an id derived from scope + F->>TP: URL + pubKey + deactivate F + TP-->>TPS: URL + pubKey + deactivate TP + TPS-->>TPS: Encrypt payload using pubKey + TPS-->>A: Send encrypted payload using URL + activate A + A->>F: Send encrypted payload using web socket + deactivate A + activate F + F->>F: Decrypt payload using privKey + F->>F: Display Notification + deactivate F +``` + +## Flow diagram for source code + +The source code for push is available under [`dom/push`](https://searchfox.org/mozilla-central/source/dom/push) in mozilla-central. + +The following flow diagram describes how different modules interact with each other to provide the push API to consumers. + +```{mermaid} +flowchart TD + subgraph Public API + + W[Third party Web app]-->|imports| P[PushManager.webidl] + end + subgraph Browser Code + P-->|Implemented by| MM + MM{Main Thread?}-->|Yes| B[Push.sys.mjs] + MM -->|NO| A[PushManager.cpp] + B-->|subscribe,getSubscription| D[PushComponents.sys.mjs] + A-->|subscribe,getSubscription| D + D-->|subscribe,getSubscription| M[PushService.sys.mjs] + M-->|Storage| S[PushDB.sys.mjs] + M-->|Network| N[PushWebSocket.sys.mjs] + F[FxAccountsPush.sys.mjs] -->|uses| D + end + subgraph Server + N-. Send, Receive.-> O[Autopush] + end + subgraph Local Storage + S-->|Read,Write| PP[(IndexedDB)] + end +``` + +## The Push Web Socket +Push in Firefox Desktop communicates with Autopush using a web socket connection. + +The web socket connection is created as the browser initializes and is managed by the following state diagram. + +```{mermaid} +stateDiagram-v2 + state "Shut Down" as SD + state "Waiting for WebSocket to start" as W1 + state "Waiting for server hello" as W2 + state "Ready" as R + [*] --> SD + SD --> W1: beginWSSetup + W1 --> W2: wsOnStart Success + W2 --> R: handleHelloReply + R --> R: send (subscribe) + R --> R: Receive + notify observers + R --> SD: wsOnStop + R --> SD: sendPing Fails + W1 --> SD: wsOnStart fails + W2 --> SD: invalid server hello + R --> [*] +``` + +Once the Push web socket is on the `Ready` state, it is ready to send new subscriptions to Autopush, and receive push notifications from those subscriptions. + +Push uses an observer pattern to notify observers of any incoming push notifications. See the [high level architecture](#high-level-push-architecture) section. + + +## Push Storage +Push uses IndexedDB to store subscriptions for the following reasons: +1. In case the consumer attempts to re-subscribe, storage is used as a cache to serve the URL and the public key +1. In order to persist the private key, so that it can be used to decrypt any incoming push notifications + +The following is what gets persisted: + +```{mermaid} +erDiagram + Subscription { + string channelID "Key, Derived from scope" + string pushEndpoint "Unique endpoint for this subscription" + string scope "Usually the origin, unique value for internal consumers" + Object p256dhPublicKey "Object representing the public key" + Object p256dhPrivateKey "Object representing the private key" + } +``` diff --git a/dom/docs/scriptSecurity/images/compartments.png b/dom/docs/scriptSecurity/images/compartments.png Binary files differnew file mode 100644 index 0000000000..c80ea166ca --- /dev/null +++ b/dom/docs/scriptSecurity/images/compartments.png diff --git a/dom/docs/scriptSecurity/images/computing-a-wrapper.png b/dom/docs/scriptSecurity/images/computing-a-wrapper.png Binary files differnew file mode 100644 index 0000000000..1221ff4a00 --- /dev/null +++ b/dom/docs/scriptSecurity/images/computing-a-wrapper.png diff --git a/dom/docs/scriptSecurity/images/cross-compartment-wrapper.png b/dom/docs/scriptSecurity/images/cross-compartment-wrapper.png Binary files differnew file mode 100644 index 0000000000..ba31355d44 --- /dev/null +++ b/dom/docs/scriptSecurity/images/cross-compartment-wrapper.png diff --git a/dom/docs/scriptSecurity/images/cross-origin-wrapper.png b/dom/docs/scriptSecurity/images/cross-origin-wrapper.png Binary files differnew file mode 100644 index 0000000000..14b7022c3d --- /dev/null +++ b/dom/docs/scriptSecurity/images/cross-origin-wrapper.png diff --git a/dom/docs/scriptSecurity/images/opaque-wrapper.png b/dom/docs/scriptSecurity/images/opaque-wrapper.png Binary files differnew file mode 100644 index 0000000000..67cd87ba5b --- /dev/null +++ b/dom/docs/scriptSecurity/images/opaque-wrapper.png diff --git a/dom/docs/scriptSecurity/images/principal-relationships.png b/dom/docs/scriptSecurity/images/principal-relationships.png Binary files differnew file mode 100644 index 0000000000..0a4e7014f6 --- /dev/null +++ b/dom/docs/scriptSecurity/images/principal-relationships.png diff --git a/dom/docs/scriptSecurity/images/same-origin-wrapper.png b/dom/docs/scriptSecurity/images/same-origin-wrapper.png Binary files differnew file mode 100644 index 0000000000..ec966afa1b --- /dev/null +++ b/dom/docs/scriptSecurity/images/same-origin-wrapper.png diff --git a/dom/docs/scriptSecurity/images/xray-wrapper.png b/dom/docs/scriptSecurity/images/xray-wrapper.png Binary files differnew file mode 100644 index 0000000000..43316d9089 --- /dev/null +++ b/dom/docs/scriptSecurity/images/xray-wrapper.png diff --git a/dom/docs/scriptSecurity/index.rst b/dom/docs/scriptSecurity/index.rst new file mode 100644 index 0000000000..482c5e888c --- /dev/null +++ b/dom/docs/scriptSecurity/index.rst @@ -0,0 +1,318 @@ +Script Security +=============== + +.. container:: summary + + This page provides an overview of the script security architecture in + Gecko. + +Like any web browser, Gecko can load JavaScript from untrusted and +potentially hostile web pages and run it on the user's computer. The +security model for web content is based on the `same-origin policy +<https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy>`__, +in which code +gets full access to objects from its origin but highly restricted access +to objects from a different origin. The rules for determining whether an +object is same-origin with another, and what access is allowed +cross-origin, are now mostly standardized across browsers. + +Gecko has an additional problem, though: while its core is written in +C++, the front-end code is written in JavaScript. This JavaScript code, +which is commonly referred to as c\ *hrome code*, runs with system +privileges. If the code is compromised, the attacker can take over the +user's computer. Legacy SDK extensions also run with chrome privileges. + +Having the browser front end in JavaScript has benefits: it can be much +quicker to develop in JavaScript than in C++, and contributors do not +need to learn C++. However, JavaScript is a highly dynamic, malleable +language, and without help it's difficult to write system-privileged +code that interacts safely with untrusted web content. From the point of +view of chrome code, the script security model in Gecko is intended to +provide that help to make writing secure, system-privileged JavaScript a +realistic expectation. + +.. _Security_policy: + +Security policy +--------------- + +Gecko implements the following security policy: + +- **Objects that are same-origin** are able to access each other + freely. For example, the objects associated with a document served + from *https://example.org/* can access each other, and they can also + access objects served from *https://example.org/foo*. +- **Objects that are cross-origin** get highly restricted access to + each other, according to the same-origin policy. + For example, code served from *https://example.org/* trying to access + objects from *https://somewhere-else.org/* will have restricted + access. +- **Objects in a privileged scope** are allowed complete access to + objects in a less privileged scope, but by default they see a + `restricted view <#privileged-to-unprivileged-code>`__ + of such objects, designed to prevent them from being tricked by the + untrusted code. An example of this scope is chrome-privileged + JavaScript accessing web content. +- **Objects in a less privileged scope** don't get any access to + objects in a more privileged scope, unless the more privileged scope + `explicitly clones those objects <#unprivileged-to-privileged-code>`__. + An example of this scope is web content accessing objects in a + chrome-privileged scope. + +.. _Compartments: + +Compartments +------------ + +Compartments are the foundation for Gecko's script security +architecture. A compartment is a specific, separate area of memory. In +Gecko, there's a separate compartment for every global object. This +means that each global object and the objects associated with it live in +their own region of memory. + +.. image:: images/compartments.png + +Normal content windows are globals, of course, but so are chrome +windows, sandboxes, workers, the ``ContentFrameMessageManager`` in a frame +script, and so on. + +Gecko guarantees that JavaScript code running in a given compartment is +only allowed to access objects in the same compartment. When code from +compartment A tries to access an object in compartment B, Gecko gives it +a *cross-compartment wrapper*. This is a proxy in compartment A for the +real object, which lives in compartment B. + +.. image:: images/cross-compartment-wrapper.png + +Inside the same compartment, all objects share a global and are +therefore same-origin with each other. Therefore there's no need for any +security checks, there are no wrappers, and there is no performance +overhead for the common case of objects in a single window interacting +with each other. + +Whenever cross-compartment access happens, the wrappers enable us to +implement the appropriate security policy. Because the wrapper we choose +is specific to the relationship between the two compartments, the +security policy it implements can be static: when the caller uses the +wrapper, there's no need to check who is making the call or where it is +going. + +.. _Cross-compartment_access: + +Cross-compartment access +------------------------ + +.. _Same-origin: + +Same-origin +~~~~~~~~~~~ + +As we've already seen, the most common scenario for same-origin access +is when objects belonging to the same window object interact. This all +takes place within the same compartment, with no need for security +checks or wrappers. + +When objects share an origin but not a global - for example two web +pages from the same protocol, port, and domain - they belong to two +different compartments, and the caller gets a *transparent wrapper* to +the target object. + +.. image:: images/same-origin-wrapper.png + +Transparent wrappers allow access to all the target's properties: +functionally, it's as if the target is in the caller's compartment. + +.. _Cross-origin: + +Cross-origin +~~~~~~~~~~~~ + +If the two compartments are cross-origin, the caller gets a +*cross-origin wrapper*. + +.. image:: images/cross-origin-wrapper.png + +This denies access to all the object's properties, except for a few +properties of Window and Location objects, as defined by +the `same-origin +policy <https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#cross-origin_script_api_access>`__. + +.. _Privileged_to_unprivileged_code: + +Privileged to unprivileged code +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The most obvious example of this kind of security relation is between +system-privileged chrome code and untrusted web content, but there are +other examples in Gecko. The Add-on SDK runs content scripts in +sandboxes, which are initialized with an `expanded +principal <#expanded-principal>`__, +giving them elevated privileges with respect to the web content they +operate on, but reduced privileges with respect to chrome. + +If the caller has a higher privilege than the target object, the caller +gets an *Xray wrapper* for the object. + +.. image:: images/xray-wrapper.png + +Xrays are designed to prevent untrusted code from confusing trusted code +by redefining objects in unexpected ways. For example, privileged code +using an Xray to a DOM object sees only the original version of the DOM +object. Any expando properties are not visible, and if any native DOM properties have been +redefined, they are not visible in the Xray. + +The privileged code is able to waive Xrays if it wants unfiltered access to the untrusted object. + +See `Xray vision <xray_vision.html>`__ for much more information on Xrays. + +.. _Unprivileged_to_privileged_code: + +Unprivileged to privileged code +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If the caller has lower privileges than the target object, then the +caller gets an *opaque wrapper.* + +.. image:: images/opaque-wrapper.png + +An opaque wrapper denies all access to the target object. + +However, the privileged target is able to copy objects and functions +into the less privileged scope using the ``exportFunction()`` and +``cloneInto()`` functions, and the less privileged scope is then able +to use them. + +.. _Security_checks: + +Security checks +--------------- + +To determine the security relation between two compartments, Gecko uses +two concepts: *security principals* and the act of *subsuming*. To +establish the security relationship between two compartments A and B, +Gecko asks: + +*Does the security principal for compartment A subsume the security +principal for compartment B, and vice versa?* + +.. _Subsumes: + +Subsumes +~~~~~~~~ + ++-----------------------------------+-----------------------------------+ +| *A subsumes B* | A has all of the privileges of B, | +| | and possibly more, and therefore | +| | A is allowed to see and do | +| | anything that B can see and do. | ++-----------------------------------+-----------------------------------+ +| *A Subsumes B &&* *B Subsumes A* | A and B are same-origin. | ++-----------------------------------+-----------------------------------+ +| *A Subsumes B && B !Subsumes A* | A is more privileged than B. | +| | | +| | A gets access to all of B, by | +| | default with Xray vision, which | +| | it may choose to waive. | +| | | +| | B gets no access to A, although A | +| | may choose to export objects to | +| | B. | ++-----------------------------------+-----------------------------------+ +| *A !Subsumes B && B !Subsumes A* | A and B are cross-origin. | ++-----------------------------------+-----------------------------------+ + +.. _Security_principals: + +Security principals +~~~~~~~~~~~~~~~~~~~ + +There are four types of security principal: the system principal, +content principals, expanded principals, and the null principal. + +.. _System_principal: + +System principal +^^^^^^^^^^^^^^^^ + +The system principal passes all security checks. It subsumes itself and +all other principals. Chrome code, by definition, runs with the system +principal, as do frame scripts. + +.. _Content_principal: + +Content principal +^^^^^^^^^^^^^^^^^ + +A content principal is associated with some web content and is defined +by the origin +of the content. For example, a normal DOM window has a content principal +defined by the window's origin. A content principal subsumes only other +content principals with the same origin. It is subsumed by the system +principal, any expanded principals that include its origin, and any +other content principals with the same origin. + +.. _Expanded_principal: + +Expanded principal +^^^^^^^^^^^^^^^^^^ + +An expanded principal is specified as an array of origins: + +.. code:: + + ["http://mozilla.org", "http://moz.org"] + +The expanded principal subsumes every content principal it contains. The +content principals do not subsume the expanded principal, even if the +expanded principal only contains a single content principal. + +Thus ``["http://moz.org"]`` subsumes ``"http://moz.org"`` but not vice +versa. The expanded principal gets full access to the content principals +it contains, with Xray vision by default, and the content principals get +no access to the expanded principal. + +This also enables the script security model to treat compartments that +have expanded principals more like part of the browser than like web +content. This means, for example, that it can run when JavaScript is +disabled for web content. + +Expanded principals are useful when you want to give code extra +privileges, including cross-origin access, but don't want to give the +code full system privileges. For example, expanded principals are used +in the Add-on SDK to give content scripts cross-domain privileges for a predefined set of +domains, +and to protect content scripts from access by untrusted web content, +without having to give content scripts system privileges. + +.. _Null_principal: + +Null principal +^^^^^^^^^^^^^^ + +The null principal fails almost all security checks. It has no +privileges and can't be accessed by anything but itself and chrome. It +subsumes no other principals, even other null principals. (This is what +is used when HTML5 and other specs say "origin is a globally unique +identifier".) + +.. _Principal_relationships: + +Principal relationships +~~~~~~~~~~~~~~~~~~~~~~~ + +The diagram below summarizes the relationships between the different +principals. The arrow connecting principals A and B means "A subsumes +B". (A is the start of the arrow, and B is the end.) + +.. image:: images/principal-relationships.png + +.. _Computing_a_wrapper: + +Computing a wrapper +------------------- + +The following diagram shows the factors that determine the kind of +wrapper that compartment A would get when trying to access an object in +compartment B. + +.. image:: images/computing-a-wrapper.png diff --git a/dom/docs/scriptSecurity/xray_vision.rst b/dom/docs/scriptSecurity/xray_vision.rst new file mode 100644 index 0000000000..8a8a093201 --- /dev/null +++ b/dom/docs/scriptSecurity/xray_vision.rst @@ -0,0 +1,411 @@ +Xray Vision +=========== + +.. container:: summary + + Xray vision helps JavaScript running in a privileged security context + safely access objects created by less privileged code, by showing the + caller only the native version of the objects. + +Gecko runs JavaScript from a variety of different sources and at a +variety of different privilege levels. + +- The JavaScript code that along with the C++ core, implements the + browser itself is called *chrome code* and runs using system + privileges. If chrome-privileged code is compromised, the attacker + can take over the user's computer. +- JavaScript loaded from normal web pages is called *content code*. + Because this code is being loaded from arbitrary web pages, it is + regarded as untrusted and potentially hostile, both to other websites + and to the user. +- As well as these two levels of privilege, chrome code can create + sandboxes. The security principal defined for the sandbox determines + its privilege level. If an + Expanded Principal is used, the sandbox is granted certain privileges + over content code and is protected from direct access by content + code. + +| The security machinery in Gecko ensures that there's asymmetric access + between code at different privilege levels: so for example, content + code can't access objects created by chrome code, but chrome code can + access objects created by content. +| However, even the ability to access content objects can be a security + risk for chrome code. JavaScript's a highly malleable language. + Scripts running in web pages can add extra properties to DOM objects + (also known as expando properties) + and even redefine standard DOM objects to do something unexpected. If + chrome code relies on such modified objects, it can be tricked into + doing things it shouldn't. +| For example: ``window.confirm()`` is a DOM + API that's supposed to ask the user to confirm an action, and return a + boolean depending on whether they clicked "OK" or "Cancel". A web page + could redefine it to return ``true``: + +.. code:: JavaScript + + window.confirm = function() { + return true; + } + +Any privileged code calling this function and expecting its result to +represent user confirmation would be deceived. This would be very naive, +of course, but there are more subtle ways in which accessing content +objects from chrome can cause security problems. + +| This is the problem that Xray vision is designed to solve. When a + script accesses an object using Xray vision it sees only the native + version of the object. Any expandos are invisible, and if any + properties of the object have been redefined, it sees the original + implementation, not the redefined version. +| So in the example above, chrome code calling the content's + ``window.confirm()`` would get the original version of ``confirm()``, + not the redefined version. + +.. note:: + + It's worth emphasizing that even if content tricks chrome into + running some unexpected code, that code does not run with chrome + privileges. So this is not a straightforward privilege escalation + attack, although it might lead to one if the chrome code is + sufficiently confused. + +.. _How_you_get_Xray_vision: + +How you get Xray vision +----------------------- + +Privileged code automatically gets Xray vision whenever it accesses +objects belonging to less-privileged code. So when chrome code accesses +content objects, it sees them with Xray vision: + +.. code:: JavaScript + + // chrome code + var transfer = gBrowser.contentWindow.confirm("Transfer all my money?"); + // calls the native implementation + +.. note:: + + Note that using window.confirm() would be a terrible way to implement + a security policy, and is only shown here to illustrate how Xray + vision works. + +.. _Waiving_Xray_vision: + +Waiving Xray vision +------------------- + +| Xray vision is a kind of security heuristic, designed to make most + common operations on untrusted objects simple and safe. However, there + are some operations for which they are too restrictive: for example, + if you need to see expandos on DOM objects. In cases like this you can + waive Xray protection, but then you can no longer rely on any + properties or functions being, or doing, what you expect. Any of them, + even setters and getters, could have been redefined by untrusted code. +| To waive Xray vision for an object you can use + Components.utils.waiveXrays(object), + or use the object's ``wrappedJSObject`` property: + +.. code:: JavaScript + + // chrome code + var waivedWindow = Components.utils.waiveXrays(gBrowser.contentWindow); + var transfer = waivedWindow.confirm("Transfer all my money?"); + // calls the redefined implementation + +.. code:: JavaScript + + // chrome code + var waivedWindow = gBrowser.contentWindow.wrappedJSObject; + var transfer = waivedWindow.confirm("Transfer all my money?"); + // calls the redefined implementation + +Waivers are transitive: so if you waive Xray vision for an object, then +you automatically waive it for all the object's properties. For example, +``window.wrappedJSObject.document`` gets you the waived version of +``document``. + +To undo the waiver again, call Components.utils.unwaiveXrays(waivedObject): + +.. code:: JavaScript + + var unwaived = Components.utils.unwaiveXrays(waivedWindow); + unwaived.confirm("Transfer all my money?"); + // calls the native implementation + +.. _Xrays_for_DOM_objects: + +Xrays for DOM objects +--------------------- + +The primary use of Xray vision is for DOM objects: that is, the +objects that represent parts of the web page. + +In Gecko, DOM objects have a dual representation: the canonical +representation is in C++, and this is reflected into JavaScript for the +benefit of JavaScript code. Any modifications to these objects, such as +adding expandos or redefining standard properties, stays in the +JavaScript reflection and does not affect the C++ representation. + +The dual representation enables an elegant implementation of Xrays: the +Xray just directly accesses the C++ representation of the original +object, and doesn't go to the content's JavaScript reflection at all. +Instead of filtering out modifications made by content, the Xray +short-circuits the content completely. + +This also makes the semantics of Xrays for DOM objects clear: they are +the same as the DOM specification, since that is defined using the +`WebIDL <http://www.w3.org/TR/WebIDL/>`__, and the WebIDL also defines +the C++ representation. + +.. _Xrays_for_JavaScript_objects: + +Xrays for JavaScript objects +---------------------------- + +Until recently, built-in JavaScript objects that are not part of the +DOM, such as +``Date``, ``Error``, and ``Object``, did not get Xray vision when +accessed by more-privileged code. + +Most of the time this is not a problem: the main concern Xrays solve is +with untrusted web content manipulating objects, and web content is +usually working with DOM objects. For example, if content code creates a +new ``Date`` object, it will usually be created as a property of a DOM +object, and then it will be filtered out by the DOM Xray: + +.. code:: JavaScript + + // content code + + // redefine Date.getFullYear() + Date.prototype.getFullYear = function() {return 1000}; + var date = new Date(); + +.. code:: JavaScript + + // chrome code + + // contentWindow is an Xray, and date is an expando on contentWindow + // so date is filtered out + gBrowser.contentWindow.date.getFullYear() + // -> TypeError: gBrowser.contentWindow.date is undefined + +The chrome code will only even see ``date`` if it waives Xrays, and +then, because waiving is transitive, it should expect to be vulnerable +to redefinition: + +.. code:: JavaScript + + // chrome code + + Components.utils.waiveXrays(gBrowser.contentWindow).date.getFullYear(); + // -> 1000 + +However, there are some situations in which privileged code will access +JavaScript objects that are not themselves DOM objects and are not +properties of DOM objects. For example: + +- the ``detail`` property of a CustomEvent fired by content could be a JavaScript + Object or Date as well as a string or a primitive +- the return value of ``evalInSandbox()`` and any properties attached to the + ``Sandbox`` object may be pure JavaScript objects + +Also, the WebIDL specifications are starting to use JavaScript types +such as ``Date`` and ``Promise``: since WebIDL definition is the basis +of DOM Xrays, not having Xrays for these JavaScript types starts to seem +arbitrary. + +So, in Gecko 31 and 32 we've added Xray support for most JavaScript +built-in objects. + +Like DOM objects, most JavaScript built-in objects have an underlying +C++ state that is separate from their JavaScript representation, so the +Xray implementation can go straight to the C++ state and guarantee that +the object will behave as its specification defines: + +.. code:: JavaScript + + // chrome code + + var sandboxScript = 'Date.prototype.getFullYear = function() {return 1000};' + + 'var date = new Date(); '; + + var sandbox = Components.utils.Sandbox("https://example.org/"); + Components.utils.evalInSandbox(sandboxScript, sandbox); + + // Date objects are Xrayed + console.log(sandbox.date.getFullYear()); + // -> 2014 + + // But you can waive Xray vision + console.log(Components.utils.waiveXrays(sandbox.date).getFullYear()); + // -> 1000 + +.. note:: + + To test out examples like this, you can use the Scratchpad in + browser context + for the code snippet, and the Browser Console to see the expected + output. + + Because code running in Scratchpad's browser context has chrome + privileges, any time you use it to run code, you need to understand + exactly what the code is doing. That includes the code samples in + this article. + +.. _Xray_semantics_for_Object_and_Array: + +Xray semantics for Object and Array +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The exceptions are ``Object`` +and ``Array``: their interesting state is in JavaScript, not C++. This +means that the semantics of their Xrays have to be independently +defined: they can't simply be defined as "the C++ representation". + +The aim of Xray vision is to make most common operations simple and +safe, avoiding the need to access the underlying object except in more +involved cases. So the semantics defined for ``Object`` and ``Array`` +Xrays aim to make it easy for privileged code to treat untrusted objects +like simple dictionaries. + +Any value properties +of the object are visible in the Xray. If the object has properties +which are themselves objects, and these objects are same-origin with the +content, then their value properties are visible as well. + +There are two main sorts of restrictions: + +- First, the chrome code might expect to rely on the prototype's + integrity, so the object's prototype is protected: + + - the Xray has the standard ``Object`` or ``Array`` prototype, + without any modifications that content may have done to that + prototype. The Xray always inherits from this standard prototype, + even if the underlying instance has a different prototype. + - if a script has created a property on an object instance that + shadows a property on the prototype, the shadowing property is not + visible in the Xray + +- Second, we want to prevent the chrome code from running content code, + so functions and accessor properties + of the object are not visible in the Xray. + +These rules are demonstrated in the script below, which evaluates a +script in a sandbox, then examines the object attached to the sandbox. + +.. note:: + + To test out examples like this, you can use the Scratchpad in + browser context for the code snippet, and the Browser Console + to see the expected output. + + Because code running in Scratchpad's browser context has chrome + privileges, any time you use it to run code, you need to understand + exactly what the code is doing. That includes the code samples in + this article. + +.. code:: JavaScript + + /* + The sandbox script: + * redefines Object.prototype.toSource() + * creates a Person() constructor that: + * defines a value property "firstName" using assignment + * defines a value property which shadows "constructor" + * defines a value property "address" which is a simple object + * defines a function fullName() + * using defineProperty, defines a value property on Person "lastName" + * using defineProperty, defines an accessor property on Person "middleName", + which has some unexpected accessor behavior + */ + + var sandboxScript = 'Object.prototype.toSource = function() {'+ + ' return "not what you expected?";' + + '};' + + 'function Person() {' + + ' this.constructor = "not a constructor";' + + ' this.firstName = "Joe";' + + ' this.address = {"street" : "Main Street"};' + + ' this.fullName = function() {' + + ' return this.firstName + " " + this.lastName;'+ + ' };' + + '};' + + 'var me = new Person();' + + 'Object.defineProperty(me, "lastName", {' + + ' enumerable: true,' + + ' configurable: true,' + + ' writable: true,' + + ' value: "Smith"' + + '});' + + 'Object.defineProperty(me, "middleName", {' + + ' enumerable: true,' + + ' configurable: true,' + + ' get: function() { return "wait, is this really a getter?"; }' + + '});'; + + var sandbox = Components.utils.Sandbox("https://example.org/"); + Components.utils.evalInSandbox(sandboxScript, sandbox); + + // 1) trying to access properties in the prototype that have been redefined + // (non-own properties) will show the original 'native' version + // note that functions are not included in the output + console.log("1) Property redefined in the prototype:"); + console.log(sandbox.me.toSource()); + // -> "({firstName:"Joe", address:{street:"Main Street"}, lastName:"Smith"})" + + // 2) trying to access properties on the object that shadow properties + // on the prototype will show the original 'native' version + console.log("2) Property that shadows the prototype:"); + console.log(sandbox.me.constructor); + // -> function() + + // 3) value properties defined by assignment to this are visible: + console.log("3) Value property defined by assignment to this:"); + console.log(sandbox.me.firstName); + // -> "Joe" + + // 4) value properties defined using defineProperty are visible: + console.log("4) Value property defined by defineProperty"); + console.log(sandbox.me.lastName); + // -> "Smith" + + // 5) accessor properties are not visible + console.log("5) Accessor property"); + console.log(sandbox.me.middleName); + // -> undefined + + // 6) accessing a value property of a value-property object is fine + console.log("6) Value property of a value-property object"); + console.log(sandbox.me.address.street); + // -> "Main Street" + + // 7) functions defined on the sandbox-defined object are not visible in the Xray + console.log("7) Call a function defined on the object"); + try { + console.log(sandbox.me.fullName()); + } + catch (e) { + console.error(e); + } + // -> TypeError: sandbox.me.fullName is not a function + + // now with waived Xrays + console.log("Now with waived Xrays"); + + console.log("1) Property redefined in the prototype:"); + console.log(Components.utils.waiveXrays(sandbox.me).toSource()); + // -> "not what you expected?" + + console.log("2) Property that shadows the prototype:"); + console.log(Components.utils.waiveXrays(sandbox.me).constructor); + // -> "not a constructor" + + console.log("3) Accessor property"); + console.log(Components.utils.waiveXrays(sandbox.me).middleName); + // -> "wait, is this really a getter?" + + console.log("4) Call a function defined on the object"); + console.log(Components.utils.waiveXrays(sandbox.me).fullName()); + // -> "Joe Smith" diff --git a/dom/docs/webIdlBindings/index.md b/dom/docs/webIdlBindings/index.md new file mode 100644 index 0000000000..5554123757 --- /dev/null +++ b/dom/docs/webIdlBindings/index.md @@ -0,0 +1,2427 @@ +# Web IDL bindings + +<div class="note"> +<div class="admonition-title">Note</div> + +Need to document the setup for indexed and named +setters/creators/deleters. + +</div> + +The [Web IDL](https://webidl.spec.whatwg.org/) bindings are generated +at build time based on two things: the actual Web IDL file and a +configuration file that lists some metadata about how the Web IDL should +be reflected into Gecko-internal code. + +All Web IDL files should be placed in +[`dom/webidl`](https://searchfox.org/mozilla-central/source/dom/webidl/) +and added to the list in the +[moz.build](https://searchfox.org/mozilla-central/source/dom/webidl/moz.build) +file in that directory. + +Note that if you're adding new interfaces, then the test at +`dom/tests/mochitest/general/test_interfaces.html` will most likely +fail. This is a signal that you need to get a review from a [DOM +peer](https://wiki.mozilla.org/Modules/All#Document_Object_Model). +Resist the urge to just add your interfaces to the +[moz.build](https://searchfox.org/mozilla-central/source/dom/webidl/moz.build) list +without the review; it will just annoy the DOM peers and they'll make +you get the review anyway. + +The configuration file, `dom/bindings/Bindings.conf`, is basically a +Python dict that maps interface names to information about the +interface, called a *descriptor*. There are all sorts of possible +options here that handle various edge cases, but most descriptors can be +very simple. + +All the generated code is placed in the `mozilla::dom` namespace. For +each interface, a namespace whose name is the name of the interface with +`Binding` appended is created, and all the things pertaining to that +interface's binding go in that namespace. + +There are various helper objects and utility methods in +[`dom/bindings`](https://searchfox.org/mozilla-central/source/dom/bindings) +that are also all in the `mozilla::dom` namespace and whose headers +are all exported into `mozilla/dom` (placed in +`$OBJDIR/dist/include` by the build process). + +## Adding Web IDL bindings to a class + +To add a Web IDL binding for interface `MyInterface` to a class +`mozilla::dom::MyInterface` that's supposed to implement that +interface, you need to do the following: + +1. If your interface doesn't inherit from any other interfaces, inherit + from `nsWrapperCache` and hook up the class to the cycle collector + so it will trace the wrapper cache properly. Note that you may not + need to do this if your objects can only be created, never gotten + from other objects. If you also inherit from `nsISupports`, make + sure the `nsISupports` comes before the `nsWrapperCache` in your + list of parent classes. If your interface *does* inherit from another + interface, just inherit from the C++ type that the other interface + corresponds to. + + If you do need to hook up cycle collection, it will look like this in + the common case of also inheriting from nsISupports: + + ``` cpp + // Add strong pointers your class holds here. If you do, change to using + // NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE. + NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(MyClass) + NS_IMPL_CYCLE_COLLECTING_ADDREF(MyClass) + NS_IMPL_CYCLE_COLLECTING_RELEASE(MyClass) + NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(MyClass) + NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY + NS_INTERFACE_MAP_ENTRY(nsISupports) + NS_INTERFACE_MAP_END + ``` + +1. If your class doesn't inherit from a class that implements + `GetParentObject`, then add a function of that name that, for a + given instance of your class, returns the same object every time + (unless you write explicit code that handles your parent object + changing by reparenting JS wrappers, as nodes do). The idea is that + walking the `GetParentObject` chain will eventually get you to a + Window, so that every Web IDL object is associated with a particular + Window. + For example, `nsINode::GetParentObject` returns the node's owner + document. The return type of `GetParentObject` doesn't matter other + than it must either singly-inherit from `nsISupports` or have a + corresponding + [`ToSupports`](https://searchfox.org/mozilla-central/search?q=ToSupports&path=&case=true®exp=false) + method that can produce an `nsISupports` from it. (This allows the + return value to be implicitly converted to a + [`ParentObject`](https://searchfox.org/mozilla-central/search?q=ParentObject&path=&case=true®exp=false) + instance by the compiler via one of that class's non-explicit + constructors.) + If many instances of `MyInterface` are expected to be created + quickly, the return value of `GetParentObject` should itself inherit + from `nsWrapperCache` for optimal performance. Returning null from + `GetParentObject` is allowed in situations in which it's OK to + associate the resulting object with a random global object for + security purposes; this is not usually ok for things that are exposed + to web content. Again, if you do not need wrapper caching you don't + need to do this. The actual type returned from `GetParentObject` + must be defined in a header included from your implementation header, + so that this type's definition is visible to the binding code. + +1. Add the Web IDL for `MyInterface` in `dom/webidl` and to the list + in `dom/webidl/moz.build`. + +1. Add an entry to `dom/bindings/Bindings.conf` that sets some basic + information about the implementation of the interface. If the C++ + type is not `mozilla::dom::MyInterface`, you need to set the + `'nativeType'` to the right type. If the type is not in the header + file one gets by replacing '::' with '/' and appending '`.h`', then + add a corresponding `'headerFile'` annotation (or + [`HeaderFile`](#headerfile-path-to-headerfile-h) annotation to the .webidl file). If + you don't have to set any annotations, then you don't need to add an + entry either and the code generator will simply assume the defaults + here. Note that using a `'headerFile'` annotation is generally not + recommended. If you do use it, you will need to make sure your + header includes all the headers needed for your [`Func`](#func-funcname) + annotations. + +1. Add external interface entries to `Bindings.conf` for whatever + non-Web IDL interfaces your new interface has as arguments or return + values. + +1. Implement a `WrapObject` override on `mozilla::dom::MyInterface` + that just calls through to + `mozilla::dom::MyInterface_Binding::Wrap`. Note that if your C++ + type is implementing multiple distinct Web IDL interfaces, you need + to choose which `mozilla::dom::MyInterface_Binding::Wrap` to call + here. See `AudioContext::WrapObject`, for example. + +1. Expose whatever methods the interface needs on + `mozilla::dom::MyInterface`. These can be inline, virtual, have any + calling convention, and so forth, as long as they have the right + argument types and return types. You can see an example of what the + function declarations should look like by running + `mach webidl-example MyInterface`. This will produce two files in + `dom/bindings` in your objdir: `MyInterface-example.h` and + `MyInterface-example.cpp`, which show a basic implementation of the + interface using a class that inherits from `nsISupports` and has a + wrapper cache. + +See this [sample patch that migrates window.performance.\* to Web IDL +bindings](https://hg.mozilla.org/mozilla-central/rev/dd08c10193c6). + +<div class="note"><div class="admonition-title">Note</div> + +If your object can only be reflected into JS by creating it, not by +retrieving it from somewhere, you can skip steps 1 and 2 above and +instead add `'wrapperCache': False` to your descriptor. You will +need to flag the functions that return your object as +[`[NewObject]`](https://webidl.spec.whatwg.org/#NewObject) in +the Web IDL. If your object is not refcounted then the return value of +functions that return it should return a UniquePtr. + +</div> + +## C++ reflections of Web IDL constructs + +### C++ reflections of Web IDL operations (methods) + +A Web IDL operation is turned into a method call on the underlying C++ +object. The return type and argument types are determined [as described +below](#c-reflections-of-webidl-constructs). In addition to those, all [methods that are +allowed to throw](#throws-getterthrows-setterthrows) will get an `ErrorResult&` argument +appended to their argument list. Non-static methods that use certain +Web IDL types like `any` or `object` will get a `JSContext*` +argument prepended to the argument list. Static methods will be passed a +[`const GlobalObject&`](#globalobject) for the relevant global and +can get a `JSContext*` by calling `Context()` on it. + +The name of the C++ method is simply the name of the Web IDL operation +with the first letter converted to uppercase. + +Web IDL overloads are turned into C++ overloads: they simply call C++ +methods with the same name and different signatures. + +For example, this Web IDL: + +``` webidl +interface MyInterface +{ + undefined doSomething(long number); + double doSomething(MyInterface? otherInstance); + + [Throws] + MyInterface doSomethingElse(optional long maybeNumber); + [Throws] + undefined doSomethingElse(MyInterface otherInstance); + + undefined doTheOther(any something); + + undefined doYetAnotherThing(optional boolean actuallyDoIt = false); + + static undefined staticOperation(any arg); +}; +``` + +will require these method declarations: + +``` cpp +class MyClass +{ + void DoSomething(int32_t a number); + double DoSomething(MyClass* aOtherInstance); + + already_AddRefed<MyInterface> DoSomethingElse(Optional<int32_t> aMaybeNumber, + ErrorResult& rv); + void DoSomethingElse(MyClass& aOtherInstance, ErrorResult& rv); + + void DoTheOther(JSContext* cx, JS::Value aSomething); + + void DoYetAnotherThing(bool aActuallyDoIt); + + static void StaticOperation(const GlobalObject& aGlobal, JS::Value aSomething); +} +``` + +### C++ reflections of Web IDL attributes + +A Web IDL attribute is turned into a pair of method calls for the getter +and setter on the underlying C++ object. A readonly attribute only has a +getter and no setter. + +The getter's name is the name of the attribute with the first letter +converted to uppercase. This has `Get` prepended to it if any of these +conditions hold: + +1. The type of the attribute is nullable. +1. The getter can throw. +1. The return value of the attribute is returned via an out parameter in + the C++. + +The method signature for the getter looks just like an operation with no +arguments and the attribute's type as the return type. + +The setter's name is `Set` followed by the name of the attribute with +the first letter converted to uppercase. The method signature looks just +like an operation with an undefined return value and a single argument +whose type is the attribute's type. + +### C++ reflections of Web IDL constructors + +A Web IDL constructor is turned into a static class method named +`Constructor`. The arguments of this method will be the arguments of +the Web IDL constructor, with a +[`const GlobalObject&`](#globalobject) for the relevant global +prepended. For the non-worker case, the global is typically the inner +window for the DOM Window the constructor function is attached to. If a +`JSContext*` is also needed due to some of the argument types, it will +come after the global. The return value of the constructor for +`MyInterface` is exactly the same as that of a method returning an +instance of `MyInterface`. Constructors are always allowed to throw. + +For example, this IDL: + +``` webidl +interface MyInterface { + constructor(); + constructor(unsigned long someNumber); +}; +``` + +will require the following declarations in `MyClass`: + +``` cpp +class MyClass { + // Various nsISupports stuff or whatnot + static + already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal, + ErrorResult& rv); + static + already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal, + uint32_t aSomeNumber, + ErrorResult& rv); +}; +``` + +### C++ reflections of Web IDL types + +The exact C++ representation for Web IDL types can depend on the precise +way that they're being used (e.g., return values, arguments, and +sequence or dictionary members might all have different +representations). + +Unless stated otherwise, a type only has one representation. Also, +unless stated otherwise, nullable types are represented by wrapping +[`Nullable<>`](#nullable-t) around the base type. + +In all cases, optional arguments which do not have a default value are +represented by wrapping [`const Optional<>&`](#optional-t) around the +representation of the argument type. If the argument type is a C++ +reference, it will also become a [`NonNull<>`](#nonnull-t) around the +actual type of the object in the process. Optional arguments which do +have a default value are just represented by the argument type itself, +set to the default value if the argument was not in fact passed in. + +Variadic Web IDL arguments are treated as a +[`const Sequence<>&`](#sequence-t) around the actual argument type. + +Here's a table, see the specific sections below for more details and +explanations. + +| Web IDL Type | Argument Type | Return Type | Dictionary/Member Type | +| -------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------- | +| any | `JS::Handle<JS::Value>` | `JS::MutableHandle<JS::Value>` | `JS::Value` | +| boolean | `bool` | `bool` | `bool` | +| byte | `int8_t` | `int8_t` | `int8_t` | +| ByteString | `const nsACString&` | `nsCString&` _(outparam)_<br>`nsACString&` _(outparam)_ | `nsCString` | +| Date | | | `mozilla::dom::Date` | +| DOMString | `const nsAString&` | [`mozilla::dom::DOMString&`](#domstring-c) _(outparam)_<br>`nsAString&` _(outparam)_<br>`nsString&` _(outparam)_ | `nsString` | +| UTF8String | `const nsACString&` _(outparam)_ | `nsACString&` | `nsCString` | +| double | `double` | `double` | `double` | +| float | `float` | `float` | `float` | +| interface:<br>non-nullable | `Foo&` | `already_addRefed<Foo>` | [`OwningNonNull<Foo>`](#owningnonnull-t) | +| interface:<br>nullable | `Foo*` | `already_addRefed<Foo>`<br>`Foo*` | `RefPtr<Foo>` | +| long | `int32_t` | `int32_t` | `int32_t` | +| long long | `int64_t` | `int64_t` | `int64_t` | +| object | `JS::Handle<JSObject*>` | `JS::MutableHandle<JSObject*>` | `JSObject*` | +| octet | `uint8_t` | `uint8_t` | `uint8_t` | +| sequence | [`const Sequence<T>&`](#sequence-t) | `nsTArray<T>&` _(outparam)_ | | +| short | `int16_t` | `int16_t` | `int16_t` | +| unrestricted double | `double` | `double` | `double` | +| unrestricted float | `float` | `float` | `float` | +| unsigned long | `uint32_t` | `uint32_t` | `uint32_t` | +| unsigned long long | `uint64_t` | `uint64_t` | `uint64_t` | +| unsigned short | `uint16_t` | `uint16_t` | `uint16_t` | +| USVString | `const nsAString&` | [`mozilla::dom::DOMString&`](#domstring-c) _(outparam)_<br>`nsAString&` _(outparam)_<br>`nsString&` _(outparam)_ | `nsString` | + +#### `any` + +`any` is represented in three different ways, depending on use: + +- `any` arguments become `JS::Handle<JS::Value>`. They will be in + the compartment of the passed-in JSContext. +- `any` return values become a `JS::MutableHandle<JS::Value>` out + param appended to the argument list. This comes after all IDL + arguments, but before the `ErrorResult&`, if any, for the method. + The return value is allowed to be in any compartment; bindings will + wrap it into the context compartment as needed. +- `any` dictionary members and sequence elements become + `JS::Value`. The dictionary members and sequence elements are + guaranteed to be marked by whomever puts the sequence or dictionary + on the stack, using `SequenceRooter` and `DictionaryRooter`. + +Methods using `any` always get a `JSContext*` argument. + +For example, this Web IDL: + +``` webidl +interface Test { + attribute any myAttr; + any myMethod(any arg1, sequence<any> arg2, optional any arg3); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +void MyAttr(JSContext* cx, JS::MutableHandle<JS::Value> retval); +void SetMyAttr(JSContext* cx, JS::Handle<JS::Value> value); +void MyMethod(JSContext* cx, JS::Handle<JS::Value> arg1, + const Sequence<JS::Value>& arg2, + const Optional<JS::Handle<JS::Value>>& arg3, + JS::MutableHandle<JS::Value> retval); +``` + +#### `boolean` + +The `boolean` Web IDL type is represented as a C++ `bool`. + +For example, this Web IDL: + +``` webidl +interface Test { + attribute boolean myAttr; + boolean myMethod(optional boolean arg); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +bool MyAttr(); +void SetMyAttr(bool value); +JS::Value MyMethod(const Optional<bool>& arg); +``` + +#### Integer types + +Integer Web IDL types are mapped to the corresponding C99 stdint types. + +For example, this Web IDL: + +``` webidl +interface Test { + attribute short myAttr; + long long myMethod(unsigned long? arg); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +int16_t MyAttr(); +void SetMyAttr(int16_t value); +int64_t MyMethod(const Nullable<uint32_t>& arg); +``` + +#### Floating point types + +Floating point Web IDL types are mapped to the C++ type of the same +name. So `float` and `unrestricted float` become a C++ `float`, +while `double` and `unrestricted double` become a C++ `double`. + +For example, this Web IDL: + +``` webidl +interface Test { + float myAttr; + double myMethod(unrestricted double? arg); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +float MyAttr(); +void SetMyAttr(float value); +double MyMethod(const Nullable<double>& arg); +``` + +#### `DOMString` + +Strings are reflected in three different ways, depending on use: + +- String arguments become `const nsAString&`. +- String return values become a + [`mozilla::dom::DOMString&`](#domstring-c) out param + appended to the argument list. This comes after all IDL arguments, + but before the `ErrorResult&`, if any, for the method. Note that + this allows callees to declare their methods as taking an + `nsAString&` or `nsString&` if desired. +- Strings in sequences, dictionaries, owning unions, and variadic + arguments become `nsString`. + +Nullable strings are represented by the same types as non-nullable ones, +but the string will return true for `DOMStringIsNull()`. Returning +null as a string value can be done using `SetDOMStringToNull` on the +out param if it's an `nsAString` or calling `SetNull()` on a +`DOMString`. + +For example, this Web IDL: + +``` webidl +interface Test { + DOMString myAttr; + [Throws] + DOMString myMethod(sequence<DOMString> arg1, DOMString? arg2, optional DOMString arg3); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +void GetMyAttr(nsString& retval); +void SetMyAttr(const nsAString& value); +void MyMethod(const Sequence<nsString>& arg1, const nsAString& arg2, + const Optional<nsAString>& arg3, nsString& retval, ErrorResult& rv); +``` + +#### `USVString` + +`USVString` is reflected just like `DOMString`. + +#### `UTF8String` + +`UTF8String` is a string with guaranteed-valid UTF-8 contents. It is +not a standard in the Web IDL spec, but its observables are the same as +those of `USVString`. + +It is a good fit for when the specification allows a `USVString`, but +you want to process the string as UTF-8 rather than UTF-16. + +It is reflected in three different ways, depending on use: + +- Arguments become `const nsACString&`. +- Return values become an `nsACString&` out param appended to the + argument list. This comes after all IDL arguments, but before the + `ErrorResult&`, if any, for the method. +- In sequences, dictionaries owning unions, and variadic arguments it + becomes `nsCString`. + +Nullable `UTF8String`s are represented by the same types as +non-nullable ones, but the string will return true for `IsVoid()`. +Returning null as a string value can be done using `SetIsVoid()` on +the out param. + +#### `ByteString` + +`ByteString` is reflected in three different ways, depending on use: + +- `ByteString` arguments become `const nsACString&`. +- `ByteString` return values become an `nsCString&` out param + appended to the argument list. This comes after all IDL arguments, + but before the `ErrorResult&`, if any, for the method. +- `ByteString` in sequences, dictionaries, owning unions, and + variadic arguments becomes `nsCString`. + +Nullable `ByteString` are represented by the same types as +non-nullable ones, but the string will return true for `IsVoid()`. +Returning null as a string value can be done using `SetIsVoid()` on +the out param. + +#### `object` + +`object` is represented in three different ways, depending on use: + +- `object` arguments become `JS::Handle<JSObject*>`. They will be + in the compartment of the passed-in JSContext. +- `object` return values become a `JS::MutableHandle<JSObject*>` + out param appended to the argument list. This comes after all IDL + arguments, but before the `ErrorResult&`, if any, for the method. + The return value is allowed to be in any compartment; bindings will + wrap it into the context compartment as needed. +- `object` dictionary members and sequence elements become + `JSObject*`. The dictionary members and sequence elements are + guaranteed to be marked by whoever puts the sequence or dictionary on + the stack, using `SequenceRooter` and `DictionaryRooter`. + +Methods using `object` always get a `JSContext*` argument. + +For example, this Web IDL: + +``` webidl +interface Test { + object myAttr; + object myMethod(object arg1, object? arg2, sequence<object> arg3, optional object arg4, + optional object? arg5); +}; +``` + +will correspond to these C++ function declarations: + +``` cpp +void GetMyAttr(JSContext* cx, JS::MutableHandle<JSObject*> retval); +void SetMyAttr(JSContext* cx, JS::Handle<JSObject*> value); +void MyMethod(JSContext* cx, JS::Handle<JSObject*> arg1, JS::Handle<JSObject*> arg2, + const Sequence<JSObject*>& arg3, + const Optional<JS::Handle<JSObject*>>& arg4, + const Optional<JS::Handle<JSObject*>>& arg5, + JS::MutableHandle<JSObject*> retval); +``` + +#### Interface types + +There are four kinds of interface types in the Web IDL bindings. Callback +interfaces are used to represent script objects that browser code can +call into. External interfaces are used to represent objects that have +not been converted to the Web IDL bindings yet. Web IDL interfaces are +used to represent Web IDL binding objects. "SpiderMonkey" interfaces are +used to represent objects that are implemented natively by the +JavaScript engine (e.g., typed arrays). + +##### Callback interfaces + +Callback interfaces are represented in C++ as objects inheriting from +[`mozilla::dom::CallbackInterface`](#callbackinterface), whose +name, in the `mozilla::dom` namespace, matches the name of the +callback interface in the Web IDL. The exact representation depends on +how the type is being used. + +- Nullable arguments become `Foo*`. +- Non-nullable arguments become `Foo&`. +- Return values become `already_AddRefed<Foo>` or `Foo*` as + desired. The pointer form is preferred because it results in faster + code, but it should only be used if the return value was not addrefed + (and so it can only be used if the return value is kept alive by the + callee until at least the binding method has returned). +- Web IDL callback interfaces in sequences, dictionaries, owning unions, + and variadic arguments are represented by `RefPtr<Foo>` if nullable + and [`OwningNonNull<Foo>`](#owningnonnull-t) otherwise. + +If the interface is a single-operation interface, the object exposes two +methods that both invoke the same underlying JS callable. The first of +these methods allows the caller to pass in a `this` object, while the +second defaults to `undefined` as the `this` value. In either case, +the `this` value is only used if the callback interface is implemented +by a JS callable. If it's implemented by an object with a property whose +name matches the operation, the object itself is always used as +`this`. + +If the interface is not a single-operation interface, it just exposes a +single method for every IDL method/getter/setter. + +The signatures of the methods correspond to the signatures for throwing +IDL methods/getters/setters with an additional trailing +`mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling` +argument, defaulting to `eReportExceptions`. +If `aReportExceptions` is set to `eReportExceptions`, the methods +will report JS exceptions before returning. If `aReportExceptions` is +set to `eRethrowExceptions`, JS exceptions will be stashed in the +`ErrorResult` and will be reported when the stack unwinds to wherever +the `ErrorResult` was set up. + +For example, this Web IDL: + +``` webidl +callback interface MyCallback { + attribute long someNumber; + short someMethod(DOMString someString); +}; +callback interface MyOtherCallback { + // single-operation interface + short doSomething(Node someNode); +}; +interface MyInterface { + attribute MyCallback foo; + attribute MyCallback? bar; +}; +``` + +will lead to these C++ class declarations in the `mozilla::dom` +namespace: + +``` cpp +class MyCallback : public CallbackInterface +{ + int32_t GetSomeNumber(ErrorResult& rv, ExceptionHandling aExceptionHandling = eReportExceptions); + void SetSomeNumber(int32_t arg, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); + int16_t SomeMethod(const nsAString& someString, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); +}; + +class MyOtherCallback : public CallbackInterface +{ +public: + int16_t + DoSomething(nsINode& someNode, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); + + template<typename T> + int16_t + DoSomething(const T& thisObj, nsINode& someNode, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); +}; +``` + +and these C++ function declarations on the implementation of +`MyInterface`: + +``` cpp +already_AddRefed<MyCallback> GetFoo(); +void SetFoo(MyCallback&); +already_AddRefed<MyCallback> GetBar(); +void SetBar(MyCallback*); +``` + +A consumer of MyCallback would be able to use it like this: + +``` cpp +void +SomeClass::DoSomethingWithCallback(MyCallback& aCallback) +{ + ErrorResult rv; + int32_t number = aCallback.GetSomeNumber(rv); + if (rv.Failed()) { + // The error has already been reported to the JS console; you can handle + // things however you want here. + return; + } + + // For some reason we want to catch and rethrow exceptions from SetSomeNumber, say. + aCallback.SetSomeNumber(2*number, rv, eRethrowExceptions); + if (rv.Failed()) { + // The exception is now stored on rv. This code MUST report + // it usefully; otherwise it will assert. + } +} +``` + +##### External interfaces + +External interfaces are represented in C++ as objects that XPConnect +knows how to unwrap to. This can mean XPCOM interfaces (whether declared +in XPIDL or not) or it can mean some type that there's a castable native +unwrapping function for. The C++ type to be used should be the +`nativeType` listed for the external interface in the +[`Bindings.conf`](#bindings-conf-details) file. The exact representation +depends on how the type is being used. + +- Arguments become `nsIFoo*`. +- Return values can be `already_AddRefed<nsIFoo>` or `nsIFoo*` as + desired. The pointer form is preferred because it results in faster + code, but it should only be used if the return value was not addrefed + (and so it can only be used if the return value is kept alive by the + callee until at least the binding method has returned). +- External interfaces in sequences, dictionaries, owning unions, and + variadic arguments are represented by `RefPtr<nsIFoo>`. + +##### Web IDL interfaces + +Web IDL interfaces are represented in C++ as C++ classes. The class +involved must either be refcounted or must be explicitly annotated in +`Bindings.conf` as being directly owned by the JS object. If the class +inherits from `nsISupports`, then the canonical `nsISupports` must +be on the primary inheritance chain of the object. If the interface has +a parent interface, the C++ class corresponding to the parent must be on +the primary inheritance chain of the object. This guarantees that a +`void*` can be stored in the JSObject which can then be +`reinterpret_cast` to any of the classes that correspond to interfaces +the object implements. The C++ type to be used should be the +`nativeType` listed for the interface in the +[`Bindings.conf`](#bindings-conf-details) file, or +`mozilla::dom::InterfaceName` if none is listed. The exact +representation depends on how the type is being used. + +- Nullable arguments become `Foo*`. +- Non-nullable arguments become `Foo&`. +- Return values become `already_AddRefed<Foo>` or `Foo*` as + desired. The pointer form is preferred because it results in faster + code, but it should only be used if the return value was not addrefed + (and so it can only be used if the return value is kept alive by the + callee until at least the binding method has returned). +- Web IDL interfaces in sequences, dictionaries, owning unions, and + variadic arguments are represented by `RefPtr<Foo>` if nullable and + [`OwningNonNull<Foo>`](#owningnonnull-t) otherwise. + +For example, this Web IDL: + +``` webidl +interface MyInterface { + attribute MyInterface myAttr; + undefined passNullable(MyInterface? arg); + MyInterface? doSomething(sequence<MyInterface> arg); + MyInterface doTheOther(sequence<MyInterface?> arg); + readonly attribute MyInterface? nullableAttr; + readonly attribute MyInterface someOtherAttr; + readonly attribute MyInterface someYetOtherAttr; +}; +``` + +Would correspond to these C++ function declarations: + +``` cpp +already_AddRefed<MyClass> MyAttr(); +void SetMyAttr(MyClass& value); +void PassNullable(MyClass* arg); +already_AddRefed<MyClass> doSomething(const Sequence<OwningNonNull<MyClass>>& arg); +already_AddRefed<MyClass> doTheOther(const Sequence<RefPtr<MyClass>>& arg); +already_Addrefed<MyClass> GetNullableAttr(); +MyClass* SomeOtherAttr(); +MyClass* SomeYetOtherAttr(); // Don't have to return already_AddRefed! +``` + +##### "SpiderMonkey" interfaces + +Typed array, array buffer, and array buffer view arguments are +represented by the objects in [`TypedArray.h`](#typed-arrays-arraybuffers-array-buffer-views). For +example, this Web IDL: + +``` webidl +interface Test { + undefined passTypedArrayBuffer(ArrayBuffer arg); + undefined passTypedArray(ArrayBufferView arg); + undefined passInt16Array(Int16Array? arg); +} +``` + +will correspond to these C++ function declarations: + +``` cpp +void PassTypedArrayBuffer(const ArrayBuffer& arg); +void PassTypedArray(const ArrayBufferView& arg); +void PassInt16Array(const Nullable<Int16Array>& arg); +``` + +Typed array return values become a `JS::MutableHandle<JSObject*>` out +param appended to the argument list. This comes after all IDL arguments, +but before the `ErrorResult&`, if any, for the method. The return +value is allowed to be in any compartment; bindings will wrap it into +the context compartment as needed. + +Typed arrays store a `JSObject*` and hence need to be rooted +properly. On-stack typed arrays can be declared as +`RootedTypedArray<TypedArrayType>` (e.g. +`RootedTypedArray<Int16Array>`). Typed arrays on the heap need to be +traced. + +#### Dictionary types + +A dictionary argument is represented by a const reference to a struct +whose name is the dictionary name in the `mozilla::dom` namespace. +The struct has one member for each of the dictionary's members with the +same name except the first letter uppercased and prefixed with "m". The +members that are required or have default values have types as described +under the corresponding Web IDL type in this document. The members that +are not required and don't have default values have those types wrapped +in [`Optional<>`](#optional-t). + +Dictionary return values are represented by an out parameter whose type +is a non-const reference to the struct described above, with all the +members that have default values preinitialized to those default values. + +Note that optional dictionary arguments are always forced to have a +default value of an empty dictionary by the IDL parser and code +generator, so dictionary arguments are never wrapped in `Optional<>`. + +If necessary, dictionaries can be directly initialized from a +`JS::Value` in C++ code by invoking their `Init()` method. Consumers +doing this should declare their dictionary as +`RootedDictionary<DictionaryName>`. When this is done, passing in a +null `JSContext*` is allowed if the passed-in `JS::Value` is +`JS::NullValue()`. Likewise, a dictionary struct can be converted to a +`JS::Value` in C++ by calling `ToJSValue` with the dictionary as the +second argument. If `Init()` or `ToJSValue()` returns false, they +will generally set a pending exception on the JSContext; reporting those +is the responsibility of the caller. + +For example, this Web IDL: + +``` webidl +dictionary Dict { + long foo = 5; + DOMString bar; +}; + +interface Test { + undefined initSomething(optional Dict arg = {}); +}; +``` + +will correspond to this C++ function declaration: + +``` cpp +void InitSomething(const Dict& arg); +``` + +and the `Dict` struct will look like this: + +``` cpp +struct Dict { + bool Init(JSContext* aCx, JS::Handle<JS::Value> aVal, const char* aSourceDescription = "value"); + + Optional<nsString> mBar; + int32_t mFoo; +} +``` + +Note that the dictionary members are sorted in the struct in +alphabetical order. + +##### API for working with dictionaries + +There are a few useful methods found on dictionaries and dictionary +members that you can use to quickly determine useful things. + +- **member.WasPassed()** - as the name suggests, was a particular + member passed? + (e.g., `if (arg.foo.WasPassed() { /* do nice things!*/ }`) +- **dictionary.IsAnyMemberPresent()** - great for checking if you need + to do anything. + (e.g., `if (!arg.IsAnyMemberPresent()) return; // nothing to do`) +- **member.Value()** - getting the actual data/value of a member that + was passed. + (e.g., `mBar.Assign(args.mBar.value())`) + +Example implementation using all of the above: + +``` cpp +void +MyInterface::InitSomething(const Dict& aArg){ + if (!aArg.IsAnyMemberPresent()) { + return; // nothing to do! + } + if (aArg.mBar.WasPassed() && !mBar.Equals(aArg.mBar.value())) { + mBar.Assign(aArg.mBar.Value()); + } +} +``` + +#### Enumeration types + +Web IDL enumeration types are represented as C++ enum classes. The values +of the C++ enum are named by taking the strings in the Web IDL +enumeration, replacing all non-alphanumerics with underscores, and +uppercasing the first letter, with a special case for the empty string, +which becomes the value `_empty`. + +For a Web IDL enum named `MyEnum`, the C++ enum is named `MyEnum` and +placed in the `mozilla::dom` namespace, while the values are placed in +the `mozilla::dom::MyEnum` namespace. There is also a +`mozilla::dom::MyEnumValues::strings` which is an array of +`mozilla::dom::EnumEntry` structs that gives access to the string +representations of the values. + +The type of the enum class is automatically selected to be the smallest +unsigned integer type that can hold all the values. In practice, this +is always uint8_t, because Web IDL enums tend to not have more than 255 +values. + +For example, this Web IDL: + +``` webidl +enum MyEnum { + "something", + "something-else", + "", + "another" +}; +``` + +would lead to this C++ enum declaration: + +``` cpp +enum class MyEnum : uint8_t { + Something, + Something_else, + _empty, + Another +}; + +namespace MyEnumValues { +extern const EnumEntry strings[10]; +} // namespace MyEnumValues +``` + +#### Callback function types + +Callback functions are represented as an object, inheriting from +[`mozilla::dom::CallbackFunction`](#callbackfunction), whose name, +in the `mozilla::dom` namespace, matches the name of the callback +function in the Web IDL. If the type is nullable, a pointer is passed in; +otherwise a reference is passed in. + +The object exposes two `Call` methods, which both invoke the +underlying JS callable. The first `Call` method has the same signature +as a throwing method declared just like the callback function, with an +additional trailing `mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling` +argument, defaulting to `eReportExceptions`, +and calling it will invoke the callable with `undefined` as the +`this` value. The second `Call` method allows passing in an explicit +`this` value as the first argument. This second call method is a +template on the type of the first argument, so the `this` value can be +passed in in whatever form is most convenient, as long as it's either a +type that can be wrapped by XPConnect or a Web IDL interface type. + +If `aReportExceptions` is set to `eReportExceptions`, the `Call` +methods will report JS exceptions before returning. If +`aReportExceptions` is set to `eRethrowExceptions`, JS exceptions +will be stashed in the `ErrorResult` and will be reported when the +stack unwinds to wherever the `ErrorResult` was set up. + +For example, this Web IDL: + +``` webidl +callback MyCallback = long (MyInterface arg1, boolean arg2); +interface MyInterface { + attribute MyCallback foo; + attribute MyCallback? bar; +}; +``` + +will lead to this C++ class declaration, in the `mozilla::dom` +namespace: + +``` cpp +class MyCallback : public CallbackFunction +{ +public: + int32_t + Call(MyInterface& arg1, bool arg2, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); + + template<typename T> + int32_t + Call(const T& thisObj, MyInterface& arg1, bool arg2, ErrorResult& rv, + ExceptionHandling aExceptionHandling = eReportExceptions); +}; +``` + +and these C++ function declarations in the `MyInterface` class: + +``` cpp +already_AddRefed<MyCallback> GetFoo(); +void SetFoo(MyCallback&); +already_AddRefed<MyCallback> GetBar(); +void SetBar(MyCallback*); +``` + +A consumer of MyCallback would be able to use it like this: + +``` cpp +void +SomeClass::DoSomethingWithCallback(MyCallback& aCallback, MyInterface& aInterfaceInstance) +{ + ErrorResult rv; + int32_t number = aCallback.Call(aInterfaceInstance, false, rv); + if (rv.Failed()) { + // The error has already been reported to the JS console; you can handle + // things however you want here. + return; + } + + // Now for some reason we want to catch and rethrow exceptions from the callback, + // and use "this" as the this value for the call to JS. + number = aCallback.Call(*this, true, rv, eRethrowExceptions); + if (rv.Failed()) { + // The exception is now stored on rv. This code MUST report + // it usefully; otherwise it will assert. + } +} +``` + +#### Sequences + +Sequence arguments are represented by +[`const Sequence<T>&`](#sequence-t), where `T` depends on the type +of elements in the Web IDL sequence. + +Sequence return values are represented by an `nsTArray<T>` out param +appended to the argument list, where `T` is the return type for the +elements of the Web IDL sequence. This comes after all IDL arguments, but +before the `ErrorResult&`, if any, for the method. + +#### Arrays + +IDL array objects are not supported yet. The spec on these is likely to +change drastically anyway. + +#### Union types + +Union types are reflected as a struct in the `mozilla::dom` namespace. +There are two kinds of union structs: one kind does not keep its members +alive (is "non-owning"), and the other does (is "owning"). Const +references to non-owning unions are used for plain arguments. Owning +unions are used in dictionaries, sequences, and for variadic arguments. +Union return values become a non-const owning union out param. The name +of the struct is the concatenation of the names of the types in the +union, with "Or" inserted between them, and for an owning struct +"Owning" prepended. So for example, this IDL: + +``` webidl +undefined passUnion((object or long) arg); +(object or long) receiveUnion(); +undefined passSequenceOfUnions(sequence<(object or long)> arg); +undefined passOtherUnion((HTMLDivElement or ArrayBuffer or EventInit) arg); +``` + +would correspond to these C++ function declarations: + +``` cpp +void PassUnion(const ObjectOrLong& aArg); +void ReceiveUnion(OwningObjectObjectOrLong& aArg); +void PassSequenceOfUnions(const Sequence<OwningObjectOrLong>& aArg); +void PassOtherUnion(const HTMLDivElementOrArrayBufferOrEventInit& aArg); +``` + +Union structs expose accessors to test whether they're of a given type +and to get hold of the data of that type. They also expose setters that +set the union as being of a particular type and return a reference to +the union's internal storage where that type could be stored. The one +exception is the `object` type, which uses a somewhat different form +of setter where the `JSObject*` is passed in directly. For example, +`ObjectOrLong` would have the following methods: + +``` cpp +bool IsObject() const; +JSObject* GetAsObject() const; +void SetToObject(JSContext*, JSObject*); +bool IsLong() const; +int32_t GetAsLong() const; +int32_t& SetAsLong() +``` + +Owning unions used on the stack should be declared as a +`RootedUnion<UnionType>`, for example, +`RootedUnion<OwningObjectOrLong>`. + +#### `Date` + +Web IDL `Date` types are represented by a `mozilla::dom::Date` +struct. + +### C++ reflections of Web IDL declarations + +Web IDL declarations (maplike/setlike/iterable) are turned into a set of +properties and functions on the interface they are declared on. Each has +a different set of helper functions it comes with. In addition, for +iterable, there are requirements for C++ function implementation by the +interface developer. + +#### Maplike + +Example Interface: + +``` webidl +interface StringToLongMap { + maplike<DOMString, long>; +}; +``` + +The bindings for this interface will generate the storage structure for +the map, as well as helper functions for accessing that structure from +C++. The generated C++ API will look as follows: + +``` cpp +namespace StringToLongMapBinding { +namespace MaplikeHelpers { +void Clear(mozilla::dom::StringToLongMap* self, ErrorResult& aRv); +bool Delete(mozilla::dom::StringToLongMap* self, const nsAString& aKey, ErrorResult& aRv); +bool Has(mozilla::dom::StringToLongMap* self, const nsAString& aKey, ErrorResult& aRv); +void Set(mozilla::dom::StringToLongMap* self, const nsAString& aKey, int32_t aValue, ErrorResult& aRv); +} // namespace MaplikeHelpers +} // namespace StringToLongMapBindings +``` + +#### Setlike + +Example Interface: + +``` webidl +interface StringSet { + setlike<DOMString>; +}; +``` + +The bindings for this interface will generate the storage structure for +the set, as well as helper functions for accessing that structure from +c++. The generated C++ API will look as follows: + +``` cpp +namespace StringSetBinding { +namespace SetlikeHelpers { +void Clear(mozilla::dom::StringSet* self, ErrorResult& aRv); +bool Delete(mozilla::dom::StringSet* self, const nsAString& aKey, ErrorResult& aRv); +bool Has(mozilla::dom::StringSet* self, const nsAString& aKey, ErrorResult& aRv); +void Add(mozilla::dom::StringSet* self, const nsAString& aKey, ErrorResult& aRv); +} // namespace SetlikeHelpers +} +``` + +#### Iterable + +Unlike maplike and setlike, iterable does not have any C++ helpers, as +the structure backing the iterable data for the interface is left up to +the developer. With that in mind, the generated iterable bindings expect +the wrapper object to provide certain methods for the interface to +access. + +Iterable interfaces have different requirements, based on if they are +single or pair value iterators. + +Example Interface for a single value iterator: + +``` webidl +interface LongIterable { + iterable<long>; + getter long(unsigned long index); + readonly attribute unsigned long length; +}; +``` + +For single value iterator interfaces, we treat the interface as an +[indexed getter](#indexed-getters), as required by the spec. See the +[indexed getter implementation section](#indexed-getters) for more +information on building this kind of structure. + +Example Interface for a pair value iterator: + +``` webidl +interface StringAndLongIterable { + iterable<DOMString, long>; +}; +``` + +The bindings for this pair value iterator interface require the +following methods be implemented in the C++ object: + +``` cpp +class StringAndLongIterable { +public: + // Returns the number of items in the iterable storage + size_t GetIterableLength(); + // Returns key of pair at aIndex in iterable storage + nsAString& GetKeyAtIndex(uint32_t aIndex); + // Returns value of pair at aIndex in iterable storage + uint32_t& GetValueAtIndex(uint32_t aIndex); +} +``` + +### Stringifiers + +Named stringifiers operations in Web IDL will just invoke the +corresponding C++ method. + +Anonymous stringifiers in Web IDL will invoke the C++ method called +`Stringify`. So, for example, given this IDL: + +``` webidl +interface FirstInterface { + stringifier; +}; + +interface SecondInterface { + stringifier DOMString getStringRepresentation(); +}; +``` + +the corresponding C++ would be: + +``` cpp +class FirstInterface { +public: + void Stringify(nsAString& aResult); +}; + +class SecondInterface { +public: + void GetStringRepresentation(nsAString& aResult); +}; +``` + +### Legacy Callers + +Only anonymous legacy callers are supported, and will invoke the C++ +method called `LegacyCall`. This will be passed the JS "this" value as +the first argument, then the arguments to the actual operation. A +`JSContext` will be passed if any of the operation arguments need it. +So for example, given this IDL: + +``` webidl +interface InterfaceWithCall { + legacycaller long (float arg); +}; +``` + +the corresponding C++ would be: + +``` cpp +class InterfaceWithCall { +public: + int32_t LegacyCall(JS::Handle<JS::Value> aThisVal, float aArgument); +}; +``` + +### Named getters + +If the interface has a named getter, the binding will expect several +methods on the C++ implementation: + +- A `NamedGetter` method. This takes a property name and returns + whatever type the named getter is declared to return. It also has a + boolean out param for whether a property with that name should exist + at all. +- A `NameIsEnumerable` method. This takes a property name and + returns a boolean that indicates whether the property is enumerable. +- A `GetSupportedNames` method. This takes an unsigned integer which + corresponds to the flags passed to the `iterate` proxy trap and + returns a list of property names. For implementations of this method, + the important flags is `JSITER_HIDDEN`. If that flag is set, the + call needs to return all supported property names. If it's not set, + the call needs to return only the enumerable ones. + +The `NameIsEnumerable` and `GetSupportedNames` methods need to agree +on which names are and are not enumerable. The `NamedGetter` and +`GetSupportedNames` methods need to agree on which names are +supported. + +So for example, given this IDL: + +``` webidl +interface InterfaceWithNamedGetter { + getter long(DOMString arg); +}; +``` + +the corresponding C++ would be: + +``` cpp +class InterfaceWithNamedGetter +{ +public: + int32_t NamedGetter(const nsAString& aName, bool& aFound); + bool NameIsEnumerable(const nsAString& aName); + undefined GetSupportedNames(unsigned aFlags, nsTArray<nsString>& aNames); +}; +``` + +### Indexed getters + +If the interface has a indexed getter, the binding will expect the +following methods on the C++ implementation: + +- A `IndexedGetter` method. This takes an integer index value and + returns whatever type the indexed getter is declared to return. It + also has a boolean out param for whether a property with that index + should exist at all. The implementation must set this out param + correctly. The return value is guaranteed to be ignored if the out + param is set to false. + +So for example, given this IDL: + +``` webidl +interface InterfaceWithIndexedGetter { + getter long(unsigned long index); + readonly attribute unsigned long length; +}; +``` + +the corresponding C++ would be: + +``` cpp +class InterfaceWithIndexedGetter +{ +public: + uint32_t Length() const; + int32_t IndexedGetter(uint32_t aIndex, bool& aFound) const; +}; +``` + +## Throwing exceptions from Web IDL methods, getters, and setters + +Web IDL methods, getters, and setters that are [explicitly marked as +allowed to throw](#throws-getterthrows-setterthrows) have an `ErrorResult&` argument as their +last argument. To throw an exception, simply call `Throw()` on the +`ErrorResult&` and return from your C++ back into the binding code. + +In cases when the specification calls for throwing a `TypeError`, you +should use `ErrorResult::ThrowTypeError()` instead of calling +`Throw()`. + +## Custom extended attributes + +Our Web IDL parser and code generator recognize several extended +attributes that are not present in the Web IDL spec. + +### `[Alias=propName]` + +This extended attribute can be specified on a method and indicates that +another property with the specified name will also appear on the +interface prototype object and will have the same Function object value +as the property for the method. For example: + +``` webidl +interface MyInterface { + [Alias=performSomething] undefined doSomething(); +}; +``` + +`MyInterface.prototype.performSomething` will have the same Function +object value as `MyInterface.prototype.doSomething`. + +Multiple `[Alias]` extended attribute can be used on the one method. +`[Alias]` cannot be used on a static method, nor on methods on a +global interface (such as `Window`). + +Aside from regular property names, the name of an alias can be +[Symbol.iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator). +This is specified by writing `[Alias="@@iterator"]`. + +### `[BindingAlias=propName]` + +This extended attribute can be specified on an attribute and indicates +that another property with the specified name will also appear on the +interface prototype object and will call the same underlying C++ +implementation for the getter and setter. This is more efficient than +using the same `BinaryName` for both attributes, because it shares the +binding glue code between them. The properties still have separate +getter/setter functions in JavaScript, so from the point of view of web +consumers it's as if you actually had two separate attribute +declarations on your interface. For example: + +``` webidl +interface MyInterface { + [BindingAlias=otherAttr] readonly attribute boolean attr; +}; +``` + +`MyInterface.prototype.otherAttr` and `MyInterface.prototype.attr` +will both exist, have separate getter/setter functions, but call the +same binding glue code and implementation function on the objects +implementing `MyInterface`. + +Multiple `[BindingAlias]` extended attributes can be used on a single +attribute. + +### `[ChromeOnly]` + +This extended attribute can be specified on any method, attribute, or +constant on an interface or on an interface as a whole. It can also be +specified on dictionary members. + +Interface members flagged as `[ChromeOnly]` are only exposed in chrome +Windows (and in particular, are not exposed to webpages). From the point +of view of web content, it's as if the interface member were not there +at all. These members *are* exposed to chrome script working with a +content object via Xrays. + +If specified on an interface as a whole, this functions like +[`[Func]`](#func-funcname) except that the binding code will automatically +check whether the caller script has the system principal (is chrome or a +worker started from a chrome page) instead of calling into the C++ +implementation to determine whether to expose the interface object on +the global. This means that accessing a content global via Xrays will +show `[ChromeOnly]` interface objects on it. + +If specified on a dictionary member, then the dictionary member will +only appear to exist in system-privileged code. + +This extended attribute can be specified together with `[Func]`, and +`[Pref]`. If more than one of these is specified, all conditions will +need to test true for the interface or interface member to be exposed. + +### `[Pref=prefname]` + +This extended attribute can be specified on any method, attribute, or +constant on an interface or on an interface as a whole. It can also be +specified on dictionary members. It takes a value, which must be the +name of a boolean preference exposed from `StaticPrefs`. The +`StaticPrefs` function that will be called is calculated from the +value of the extended attribute, with dots replaced by underscores +(`StaticPrefs::my_pref_name()` in the example below). + +If specified on an interface member, the interface member involved is +only exposed if the preference is set to `true`. An example of how +this can be used: + +``` webidl +interface MyInterface { + attribute long alwaysHere; + [Pref="my.pref.name"] attribute long onlyHereIfEnabled; +}; +``` + +If specified on an interface as a whole, this functions like +[`[Func]`](#func-funcname) except that the binding will check the value of +the preference directly without calling into the C++ implementation of +the interface at all. This is useful when the enable check is simple and +it's desirable to keep the prefname with the Web IDL declaration. + +If specified on a dictionary member, the web-observable behavior when +the pref is set to false will be as if the dictionary did not have a +member of that name defined. That means that on the JS side no +observable get of the property will happen. On the C++ side, the +behavior would be as if the passed-in object did not have a property +with the relevant name: the dictionary member would either be +`!Passed()` or have the default value if there is a default value. + +> An example of how this can be used: + +``` webidl +[Pref="my.pref.name"] +interface MyConditionalInterface { +}; +``` + +This extended attribute can be specified together with `[ChromeOnly]`, +and `[Func]`. If more than one of these is specified, all conditions +will need to test true for the interface or interface member to be +exposed. + +### `[Func="funcname"]` + +This extended attribute can be specified on any method, attribute, or +constant on an interface or on an interface as a whole. It can also be +specified on dictionary members. It takes a value, which must be the +name of a static function. + +If specified on an interface member, the interface member involved is +only exposed if the specified function returns `true`. An example of +how this can be used: + +``` webidl +interface MyInterface { + attribute long alwaysHere; + [Func="MyClass::StuffEnabled"] attribute long onlyHereIfEnabled; +}; +``` + +The function is invoked with two arguments: the `JSContext` that the +operation is happening on and the `JSObject` for the global of the +object that the property will be defined on if the function returns +true. In particular, in the Xray case the `JSContext` is in the caller +compartment (typically chrome) but the `JSObject` is in the target +compartment (typically content). This allows the method implementation +to select which compartment it cares about in its checks. + +The above IDL would also require the following C++: + +``` cpp +class MyClass { + static bool StuffEnabled(JSContext* cx, JSObject* obj); +}; +``` + +If specified on an interface as a whole, then lookups for the interface +object for this interface on a DOM Window will only find it if the +specified function returns true. For objects that can only be created +via a constructor, this allows disabling the functionality altogether +and making it look like the feature is not implemented at all. + +If specified on a dictionary member, the web-observable behavior when +the function returns false will be as if the dictionary did not have a +member of that name defined. That means that on the JS side no +observable get of the property will happen. On the C++ side, the +behavior would be as if the passed-in object did not have a property +with the relevant name: the dictionary member would either be +`!Passed()` or have the default value if there is a default value. + +An example of how `[Func]` can be used: + +``` webidl +[Func="MyClass::MyConditionalInterfaceEnabled"] +interface MyConditionalInterface { +}; +``` + +In this case, the C++ function is passed a `JS::Handle<JSObject*>`. So +the C++ in this case would look like this: + +``` cpp +class MyClass { + static bool MyConditionalInterfaceEnabled(JSContext* cx, JS::Handle<JSObject*> obj); +}; +``` + +Just like in the interface member case, the `JSContext` is in the +caller compartment but the `JSObject` is the actual object the +property would be defined on. In the Xray case that means obj is in the +target compartment (typically content) and `cx` is typically chrome. + +This extended attribute can be specified together with `[ChromeOnly]`, +and `[Pref]`. If more than one of these is specified, all conditions +will need to test true for the interface or interface member to be +exposed. + +Binding code will include the headers necessary for a `[Func]`, unless +the interface is using a non-default header file. If a non-default +header file is used, that header file needs to do any header inclusions +necessary for `[Func]` annotations. + +### `[Throws]`, `[GetterThrows]`, `[SetterThrows]` + +Used to flag methods or attributes as allowing the C++ callee to throw. +This causes the binding generator, and in many cases the JIT, to +generate extra code to handle possible exceptions. Possibly-throwing +methods and attributes get an `ErrorResult&` argument. + +`[Throws]` applies to both methods and attributes; for attributes it +means both the getter and the setter can throw. `[GetterThrows]` +applies only to attributes. `[SetterThrows]` applies only to +non-readonly attributes. + +For interfaces flagged with `[JSImplementation]`, all methods and +properties are assumed to be able to throw and do not need to be flagged +as throwing. + +### `[DependsOn]` + +Used for a method or attribute to indicate what the return value depends +on. Possible values are: + +* `Everything` + + This value can't actually be specified explicitly; this is the + default value you get when `[DependsOn]` is not specified. This + means we don't know anything about the return value's dependencies + and hence can't rearrange other code that might change values around + the method or attribute. + +* `DOMState` + + The return value depends on the state of the "DOM", by which we mean + all objects specified via Web IDL. The return value is guaranteed to + not depend on the state of the JS heap or other JS engine data + structures, and is guaranteed to not change unless some function with + [`[Affects=Everything]`](#affects) is executed. + +* `DeviceState` + + The return value depends on the state of the device we're running on + (e.g., the system clock). The return value is guaranteed to not be + affected by any code running inside Gecko itself, but we might get a + new value every time the method or getter is called even if no Gecko + code ran between the calls. + +* `Nothing` + + The return value is a constant that never changes. This value cannot + be used on non-readonly attributes, since having a non-readonly + attribute whose value never changes doesn't make sense. + +Values other than `Everything`, when used in combination with +[`[Affects=Nothing]`](#affects), can used by the JIT to +perform loop-hoisting and common subexpression elimination on the return +values of IDL attributes and methods. + +### `[Affects]` + +Used for a method or attribute getter to indicate what sorts of state +can be affected when the function is called. Attribute setters are, for +now, assumed to affect everything. Possible values are: + +* `Everything` + + This value can't actually be specified explicitly; this is the + default value you get when `[Affects]` is not specified. This means + that calling the method or getter might change any mutable state in + the DOM or JS heap. + +* `Nothing` + + Calling the method or getter will have no side-effects on either the + DOM or the JS heap. + +Methods and attribute getters with `[Affects=Nothing]` are allowed to +throw exceptions, as long as they do so deterministically. In the case +of methods, whether an exception is thrown is allowed to depend on the +arguments, as long as calling the method with the same arguments will +always either throw or not throw. + +The `Nothing` value, when used with `[DependsOn]` values other than +`Everything`, can used by the JIT to perform loop-hoisting and common +subexpression elimination on the return values of IDL attributes and +methods, as well as code motion past DOM methods that might depend on +system state but have no side effects. + +### `[Pure]` + +This is an alias for `[Affects=Nothing, DependsOn=DOMState]`. +Attributes/methods flagged in this way promise that they will keep +returning the same value as long as nothing that has +`[Affects=Everything]` executes. + +### `[Constant]` + +This is an alias for `[Affects=Nothing, DependsOn=Nothing]`. Used to +flag readonly attributes or methods that could have been annotated with +`[Pure]` and also always return the same value. This should only be +used when it's absolutely guaranteed that the return value of the +attribute getter will always be the same from the JS engine's point of +view. + +The spec's `[SameObject]` extended attribute is an alias for +`[Constant]`, but can only be applied to things returning objects, +whereas `[Constant]` can be used for any type of return value. + +### `[NeedResolve]` + +Used to flag interfaces which have a custom resolve hook. This +annotation will cause the `DoResolve` method to be called on the +underlying C++ class when a property lookup happens on the object. The +signature of this method is: +`bool DoResolve(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::Value>)`. +Here the passed-in object is the object the property lookup is happening +on (which may be an Xray for the actual DOM object) and the jsid is the +property name. The value that the property should have is returned in +the `MutableHandle<Value>`, with `UndefinedValue()` indicating that +the property does not exist. + +If this extended attribute is used, then the underlying C++ class must +also implement a method called `GetOwnPropertyNames` with the +signature +`void GetOwnPropertyNames(JSContext* aCx, nsTArray<nsString>& aNames, ErrorResult& aRv)`. +This method will be called by the JS engine's enumerate hook and must +provide a superset of all the property names that `DoResolve` might +resolve. Providing names that `DoResolve` won't actually resolve is +OK. + +### `[HeaderFile="path/to/headerfile.h"]` + +Indicates where the implementation can be found. Similar to the +headerFile annotation in Bindings.conf. Just like headerFile in +Bindings.conf, should be avoided. + +### `[JSImplementation="@mozilla.org/some-contractid;1"]` + +Used on an interface to provide the contractid of the [JavaScript +component implementing the +interface](#implementing-webidl-using-javascript). + +### `[StoreInSlot]` + +Used to flag attributes that can be gotten very quickly from the JS +object by the JIT. Such attributes will have their getter called +immediately when the JS wrapper for the DOM object is created, and the +returned value will be stored directly on the JS object. Later gets of +the attribute will not call the C++ getter and instead use the cached +value. If the value returned by the attribute needs to change, the C++ +code should call the `ClearCachedFooValue` method in the namespace of +the relevant binding, where `foo` is the name of the attribute. This +will immediately call the C++ getter and cache the value it returns, so +it needs a `JSContext` to work on. This extended attribute can only be +used on attributes whose getters are [`[Pure]`](#pure) or +[`[Constant]`](#constant) and which are not +[`[Throws]`](#throws-getterthrows-setterthrows) or [`[GetterThrows]`](#throws-getterthrows-setterthrows). + +So for example, given this IDL: + +``` webidl +interface MyInterface { + [Pure, StoreInSlot] attribute long myAttribute; +}; +``` + +the C++ implementation of MyInterface would clear the cached value by +calling +`mozilla::dom::MyInterface_Binding::ClearCachedMyAttributeValue(cx, this)`. +This function will return false on error and the caller is responsible +for handling any JSAPI exception that is set by the failure. + +If the attribute is not readonly, setting it will automatically clear +the cached value and reget it again before the setter returns. + +### `[Cached]` + +Used to flag attributes that, when their getter is called, will cache +the returned value on the JS object. This can be used to implement +attributes whose value is a sequence or dictionary (which would +otherwise end up returning a new object each time and hence not be +allowed in Web IDL). + +Unlike [`[StoreInSlot]`](#storeinslot) this does *not* cause the +getter to be eagerly called at JS wrapper creation time; the caching is +lazy. `[Cached]` attributes must be [`[Pure]`](#pure) or +[`[Constant]`](#constant), because otherwise not calling the C++ +getter would be observable, but are allowed to have throwing getters. +Their cached value can be cleared by calling the `ClearCachedFooValue` +method in the namespace of the relevant binding, where `foo` is the +name of the attribute. Unlike `[StoreInSlot]` attributes, doing so +will not immediately invoke the getter, so it does not need a +`JSContext`. + +So for example, given this IDL: + +``` webidl +interface MyInterface { + [Pure, StoreInSlot] attribute long myAttribute; +}; +``` + +the C++ implementation of MyInterface would clear the cached value by +calling +`mozilla::dom::MyInterface_Binding::ClearCachedMyAttributeValue(this)`. +JS-implemented Web IDL can clear the cached value by calling +`this.__DOM_IMPL__._clearCachedMyAttributeValue()`. + +If the attribute is not readonly, setting it will automatically clear +the cached value. + +### `[Frozen]` + +Used to flag attributes that, when their getter is called, will call +[`Object.freeze`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) +on the return value before returning it. This extended attribute is only +allowed on attributes that return sequences, dictionaries and +`MozMap`, and corresponds to returning a frozen `Array` (for the +sequence case) or `Object` (for the other two cases). + +### `[BinaryName]` + +`[BinaryName]` can be specified on method or attribute to change the +C++ function name that will be used for the method or attribute. It +takes a single string argument, which is the name you wish the method or +attribute had instead of the one it actually has. + +For example, given this IDL: + +``` webidl +interface InterfaceWithRenamedThings { + [BinaryName="renamedMethod"] + undefined someMethod(); + [BinaryName="renamedAttribute"] + attribute long someAttribute; +}; +``` + +the corresponding C++ would be: + +``` cpp +class InterfaceWithRenamedThings +{ +public: + void RenamedMethod(); + int32_t RenamedAttribute(); + void SetRenamedAttribute(int32_t); +}; +``` + +### `[Deprecated="tag"]` + +When deprecating an interface or method, the `[Deprecated]` annotation +causes the Web IDL compiler to insert code that generates deprecation +warnings. This annotation can be added to interface methods or +interfaces. Adding this to an interface causes a warning to be issued +the first time the object is constructed, or any static method on the +object is invoked. + +The complete list of valid deprecation tags is maintained in +[nsDeprecatedOperationList.h](https://searchfox.org/mozilla-central/source/dom/base/nsDeprecatedOperationList.h). +Each new tag requires that a localized string be defined, containing the +deprecation message to display. + +### `[CrossOriginReadable]` + +Used to flag an attribute that, when read, will not have the same-origin +constraint tested: it can be read from a context with a different +origin. + +### `[CrossOriginWrite]` + +Used to flag an attribute that, when written, will not have the +same-origin constraint tested: it can be written from a context with a +different origin. + +### `[CrossOriginCallable]` + +Used to flag a method that, when called, will not have the same-origin +constraint tested: it can be called from a context with a different +origin. + +### `[SecureContext]` + +We implement the [standard extended +attribute](https://webidl.spec.whatwg.org/#SecureContext) with a few +details specific to Gecko: + +- System principals are considered secure. +- An extension poking at non-secured DOM objects will see APIs marked + with `[SecureContext]`. +- XPConnect sandboxes don't see `[SecureContext]` APIs, except if + they're created with `isSecureContext: true`. + +### `[NeedsSubjectPrincipal]`, `[GetterNeedsSubjectPrincipal]`, `[SetterNeedsSubjectPrincipal]` + +Used to flag a method or an attribute that needs to know the subject +principal. This principal will be passed as argument. If the interface +is not exposed on any worker global, the argument will be a +`nsIPrincipal&` because a subject principal is always available in +mainthread globals. If the interface is exposed on some worker global, +the argument will be a `const Maybe<nsIPrincipal*>&`. This `Maybe<>` +object contains the principal *only* on the main thread; when the method +is called on a {{domxref("Worker")}} thread, the value of the object +will be `Nothing()`. Note that, in workers, it is always possible to +retrieve the correct subject principal from the `WorkerPrivate` +object, though it cannot be used on the worker thread. + +`[NeedsSubjectPrincipal]` applies to both methods and attributes; for +attributes it means both the getter and the setter need a subject +principal. `[GetterNeedsSubjectPrincipal]` applies only to attributes. +`[SetterNeedsSubjectPrincipal]` applies only to non-readonly +attributes. + +### `[NeedsCallerType]` + +Used to flag a method or an attribute that needs to know the caller +type, in the `mozilla::dom::CallerType` sense. This can be safely +used for APIs exposed in workers; there it will indicate whether the +worker involved is a `ChromeWorker` or not. At the moment the only +possible caller types are `System` (representing system-principal +callers) and `NonSystem`. + +## Helper objects + +The C++ side of the bindings uses a number of helper objects. + +### `Nullable<T>` + +`Nullable<>` is a struct declared in +[`Nullable.h`](https://searchfox.org/mozilla-central/source/dom/bindings/Nullable.h) +and exported to `mozilla/dom/Nullable.h` that is used to represent +nullable values of types that don't have a natural way to represent +null. + +`Nullable<T>` has an `IsNull()` getter that returns whether null is +represented and a `Value()` getter that returns a `const T&` and can +be used to get the value when it's not null. + +`Nullable<T>` has a `SetNull()` setter that sets it as representing +null and two setters that can be used to set it to a value: +`void SetValue(T)` (for setting it to a given value) and +`T& SetValue()` for directly modifying the underlying `T&`. + +### `Optional<T>` + +`Optional<>` is a struct declared in +[`BindingDeclarations.h`](https://searchfox.org/mozilla-central/source/dom/bindings/BindingDeclarations.h) +and exported to `mozilla/dom/BindingDeclarations.h` that is used to +represent optional arguments and dictionary members, but only those that +have no default value. + +`Optional<T>` has a `WasPassed()` getter that returns true if a +value is available. In that case, the `Value()` getter can be used to +get a `const T&` for the value. + +### `NonNull<T>` + +`NonNull<T>` is a struct declared in +[`BindingUtils.h`](https://searchfox.org/mozilla-central/source/dom/bindings/BindingUtils.h) +and exported to `mozilla/dom/BindingUtils.h` that is used to represent +non-null C++ objects. It has a conversion operator that produces `T&`. + +### `OwningNonNull<T>` + +`OwningNonNull<T>` is a struct declared in +[`OwningNonNull.h`](https://searchfox.org/mozilla-central/source/xpcom/base/OwningNonNull.h) +and exported to `mozilla/OwningNonNull.h` that is used to represent +non-null C++ objects and holds a strong reference to them. It has a +conversion operator that produces `T&`. + +### Typed arrays, arraybuffers, array buffer views + +`TypedArray.h` is exported to `mozilla/dom/TypedArray.h` and exposes +structs that correspond to the various typed array types, as well as +`ArrayBuffer` and `ArrayBufferView`, all in the `mozilla::dom` +namespace. Each struct has a `Data()` method that returns a pointer to +the relevant type (`uint8_t` for `ArrayBuffer` and +`ArrayBufferView`) and a `Length()` method that returns the length +in units of `*Data()`. So for example, `Int32Array` has a `Data()` +returning `int32_t*` and a `Length()` that returns the number of +32-bit ints in the array. + +### `Sequence<T>` + +`Sequence<>` is a type declared in +[`BindingDeclarations.h`](https://searchfox.org/mozilla-central/source/dom/bindings/BindingDeclarations.h) +and exported to `mozilla/dom/BindingDeclarations.h` that is used to +represent sequence arguments. It's some kind of typed array, but which +exact kind is opaque to consumers. This allows the binding code to +change the exact definition (e.g., to use auto arrays of different sizes +and so forth) without having to update all the callees. + +### `CallbackFunction` + +`CallbackFunction` is a type declared in +[CallbackFunction.h](https://searchfox.org/mozilla-central/source/dom/bindings/CallbackFunction.h) +and exported to `mozilla/dom/CallbackFunction.h` that is used as a +common base class for all the generated callback function +representations. This class inherits from `nsISupports`, and consumers +must make sure to cycle-collect it, since it keeps JS objects alive. + +### `CallbackInterface` + +`CallbackInterface` is a type declared in +[CallbackInterface.h](https://searchfox.org/mozilla-central/source/dom/bindings/CallbackInterface.h) +and exported to `mozilla/dom/CallbackInterface.h` that is used as a +common base class for all the generated callback interface +representations. This class inherits from `nsISupports`, and consumers +must make sure to cycle-collect it, since it keeps JS objects alive. + +### `DOMString` + +`DOMString` is a class declared in +[BindingDeclarations.h](https://searchfox.org/mozilla-central/source/dom/bindings/BindingDeclarations.h) +and exported to `mozilla/dom/BindingDeclarations.h` that is used for +Web IDL `DOMString` return values. It has a conversion operator to +`nsString&` so that it can be passed to methods that take that type or +`nsAString&`, but callees that care about performance, have an +`nsStringBuffer` available, and promise to hold on to the +`nsStringBuffer` at least until the binding code comes off the stack +can also take a `DOMString` directly for their string return value and +call its `SetStringBuffer` method with the `nsStringBuffer` and its +length. This allows the binding code to avoid extra reference-counting +of the string buffer in many cases, and allows it to take a faster +codepath even if it does end up having to addref the `nsStringBuffer`. + +### `GlobalObject` + +`GlobalObject` is a class declared in +[BindingDeclarations.h](https://searchfox.org/mozilla-central/source/dom/bindings/BindingDeclarations.h) +and exported to `mozilla/dom/BindingDeclarations.h` that is used to +represent the global object for static attributes and operations +(including constructors). It has a `Get()` method that returns the +`JSObject*` for the global and a `GetAsSupports()` method that +returns an `nsISupports*` for the global on the main thread, if such +is available. It also has a `Context()` method that returns the +`JSContext*` the call is happening on. A caveat: the compartment of +the `JSContext` may not match the compartment of the global! + +### `Date` + +`Date` is a class declared in +[BindingDeclarations.h](https://searchfox.org/mozilla-central/source/dom/bindings/BindingDeclarations.h) +and exported to `mozilla/dom/BindingDeclarations.h` that is used to +represent Web IDL Dates. It has a `TimeStamp()` method returning a +double which represents a number of milliseconds since the epoch, as +well as `SetTimeStamp()` methods that can be used to initialize it +with a double timestamp or a JS `Date` object. It also has a +`ToDateObject()` method that can be used to create a new JS `Date`. + +### `ErrorResult` + +`ErrorResult` is a class declared in +[ErrorResult.h](https://searchfox.org/mozilla-central/source/dom/bindings/ErrorResult.h) +and exported to `mozilla/ErrorResult.h` that is used to represent +exceptions in Web IDL bindings. This has the following methods: + +- `Throw`: allows throwing an `nsresult`. The `nsresult` must be + a failure code. +- `ThrowTypeError`: allows throwing a `TypeError` with the given + error message. The list of allowed `TypeError`s and corresponding + messages is in + [`dom/bindings/Errors.msg`](https://searchfox.org/mozilla-central/source/dom/bindings/Errors.msg). +- `ThrowJSException`: allows throwing a preexisting JS exception + value. However, the `MightThrowJSException()` method must be called + before any such exceptions are thrown (even if no exception is + thrown). +- `Failed`: checks whether an exception has been thrown on this + `ErrorResult`. +- `ErrorCode`: returns a failure `nsresult` representing (perhaps + incompletely) the state of this `ErrorResult`. +- `operator=`: takes an `nsresult` and acts like `Throw` if the + result is an error code, and like a no-op otherwise (unless an + exception has already been thrown, in which case it asserts). This + should only be used for legacy code that has nsresult everywhere; we + would like to get rid of this operator at some point. + +## Events + +Simple `Event` interfaces can be automatically generated by adding the +interface file to GENERATED_EVENTS_WEBIDL_FILES in the +appropriate dom/webidl/moz.build file. You can also take a simple +generated C++ file pair and use it to build a more complex event (i.e., +one that has methods). + +### Event handler attributes + +A lot of interfaces define event handler attributes, like: + +``` webidl +attribute EventHandler onthingchange; +``` + +If you need to implement an event handler attribute for an interface, in +the definition (header file), you use the handy +"IMPL_EVENT_HANDLER" macro: + +``` cpp +IMPL_EVENT_HANDLER(onthingchange); +``` + +The "onthingchange" needs to be added to the StaticAtoms.py file: + +``` py +Atom("onthingchange", "onthingchange") +``` + +The actual implementation (.cpp) for firing the event would then look +something like: + +``` cpp +nsresult +MyInterface::DispatchThingChangeEvent() +{ + NS_NAMED_LITERAL_STRING(type, "thingchange"); + EventInit init; + init.mBubbles = false; + init.mCancelable = false; + RefPtr<Event> event = Event::Constructor(this, type, init); + event->SetTrusted(true); + ErrorResult rv; + DispatchEvent(*event, rv); + return rv.StealNSResult(); // Assuming the caller cares about the return code. +} +``` + +## `Bindings.conf` details + +Write me. In particular, need to describe at least use of `concrete`, +`prefable`, and `addExternalInterface`. + +### How to get a JSContext passed to a given method + +In some rare cases you may need a `JSContext*` argument to be passed +to a C++ method that wouldn't otherwise get such an argument. To see how +to achieve this, search for `implicitJSContext` in +[dom/bindings/Bindings.conf](#bindings-conf-details). + +## Implementing Web IDL using Javascript + +<div class="warning"><div class="admonition-title">Warning</div> + +Implementing Web IDL using Javascript is deprecated. New interfaces +should always be implemented in C++! + +</div> + +It is possible to implement Web IDL interfaces in JavaScript within Gecko +-- however, **this is limited to interfaces that are not exposed in Web +Workers**. When the binding occurs, two objects are created: + +- *Content-exposed object:* what gets exposed to the web page. +- *Implementation object:* running as a chrome-privileged script. This + allows the implementation object to have various APIs that the + content-exposed object does not. + +Because there are two types of objects, you have to be careful about +which object you are creating. + +### Creating JS-implemented Web IDL objects + +To create a JS-implemented Web IDL object, one must create both the +chrome-side implementation object and the content-side page-exposed +object. There are three ways to do this. + +#### Using the Web IDL constructor + +If the interface has a constructor, a content-side object can be created +by getting that constructor from the relevant content window and +invoking it. For example: + +``` js +var contentObject = new contentWin.RTCPeerConnection(); +``` + +The returned object will be an Xray wrapper for the content-side object. +Creating the object this way will automatically create the chrome-side +object using its contractID. + +This method is limited to the constructor signatures exposed to +webpages. Any additional configuration of the object needs to be done +methods on the interface. + +Creating many objects this way can be slow due to the createInstance +overhead involved. + +#### Using a `_create` method + +A content-side object can be created for a given chrome-side object by +invoking the static `_create` method on the interface. This method +takes two arguments: the content window in which to create the object +and the chrome-side object to use. For example: + +``` js +var contentObject = RTCPeerConnection._create(contentWin, new +MyPeerConnectionImpl()); +``` + +However, if you are in a JS component, you may only be able to get to +the correct interface object via some window object. In this case, the +code would look more like: + +``` js +var contentObject = contentWin.RTCPeerConnection._create(contentWin, +new MyPeerConnectionImpl()); +``` + +Creating the object this way will not invoke its `__init` method or +`init` method. + +#### By returning a chrome-side object from a JS-implemented Web IDL method + +If a JS-implemented Web IDL method is declared as returning a +JS-implemented interface, then a non-Web IDL object returned from that +method will be treated as the chrome-side part of a JS-implemented +WebIdL object and the content-side part will be automatically created. + +Creating the object this way will not invoke its `__init` method or +`init` method. + +### Implementing a Web IDL object in JavaScript + +To implement a Web IDL interface in JavaScript, first add a Web IDL file, +in the same way as you would for a C++-implemented interface. To support +implementation in JS, you must add an extended attribute +`JSImplementation="CONTRACT_ID_STRING"` on your interface, where +CONTRACT_ID_STRING is the XPCOM component contract ID of the JS +implementation -- note ";1" is just a Mozilla convention for versioning +APIs. Here's an example: + +``` webidl +[JSImplementation="@mozilla.org/my-number;1"] +interface MyNumber { + constructor(optional long firstNumber); + attribute long value; + readonly attribute long otherValue; + undefined doNothing(); +}; +``` + +Next, create an XPCOM component that implements this interface. Use +the same contract ID as you specified in the Web IDL file. The class +ID doesn't matter, except that it should be a newly generated one. For +`QueryInterface`, you only need to implement `nsISupports`, not +anything corresponding to the Web IDL interface. The name you use for +the XPCOM component should be distinct from the name of the interface, +to avoid confusing error messages. + +Web IDL attributes are implemented as properties on the JS object or its +prototype chain, whereas Web IDL methods are implemented as methods on +the object or prototype. Note that any other instances of the interface +that you are passed in as arguments are the full web-facing version of +the object, and not the JS implementation, so you currently cannot +access any private data. + +The Web IDL constructor invocation will first create your object. If the +XPCOM component implements `nsIDOMGlobalPropertyInitializer`, then +the object's `init` method will be invoked with a single argument: +the content window the constructor came from. This allows the JS +implementation to know which content window it's associated with. +The `init` method should not return anything. After this, the +content-side object will be created. Then,if there are any constructor +arguments, the object's `__init` method will be invoked, with the +constructor arguments as its arguments. + +### Static Members + +Static attributes and methods are not supported on JS-implemented Web IDL +(see [bug +863952](https://bugzilla.mozilla.org/show_bug.cgi?id=863952)). +However, with the changes in [bug +1172785](https://bugzilla.mozilla.org/show_bug.cgi?id=1172785) you +can route static methods to a C++ implementation on another object using +a `StaticClassOverride` annotation. This annotation includes the +full, namespace-qualified name of the class that contains an +implementation of the named method. The include for that class must be +found in a directory based on its name. + +``` webidl +[JSImplementation="@mozilla.org/dom/foo;1"] +interface Foo { + [StaticClassOverride="mozilla::dom::OtherClass"] + static Promise<undefined> doSomething(); +}; +``` + +Rather than calling into a method on the JS implementation; calling +`Foo.doSomething()` will result in calling +`mozilla::dom::OtherClass::DoSomething()`. + +### Checking for Permissions or Preferences + +With JS-implemented Web IDL, the `init` method should only return +undefined. If any other value, such as `null`, is returned, the +bindings code will assert or crash. In other words, it acts like it has +an "undefined" return type. Preference or permission checking should be +implemented by adding an extended attribute to the Web IDL interface. +This has the advantage that if the check fails, the constructor or +object will not show up at all. + +For preference checking, add an extended attribute +`Pref="myPref.enabled"` where `myPref.enabled` is the preference +that should be checked. `SettingsLock` is an example of this. + +For permissions or other kinds of checking, add an extended attribute +`Func="MyPermissionChecker"` where `MyPermissionChecker` is a +function implemented in C++ that returns true if the interface should be +enabled. This function can do whatever checking is needed. One example +of this is `PushManager`. + +### Example + +Here's an example JS implementation of the above interface. The +`invisibleValue` field will not be accessible to web content, but is +usable by the doNothing() method. + +``` js +function MyNumberInner() { + this.value = 111; + this.invisibleValue = 12345; +} + +MyNumberInner.prototype = { + classDescription: "Get my number XPCOM Component", + contractID: "@mozilla.org/my-number;1", + QueryInterface: ChromeUtils.generateQI([]), + doNothing: function() {}, + get otherValue() { return this.invisibleValue - 4; }, + __init: function(firstNumber) { + if (arguments.length > 0) { + this.value = firstNumber; + } + } +} +``` + +Finally, add a component and a contract and whatever other manifest +stuff you need to implement an XPCOM component. + +### Guarantees provided by bindings + +When implementing a Web IDL interface in JavaScript, certain guarantees +will be provided by the binding implementation. For example, string or +numeric arguments will actually be primitive strings or numbers. +Dictionaries will contain only the properties that they are declared to +have, and they will have the right types. Interface arguments will +actually be objects implementing that interface. + +What the bindings will NOT guarantee is much of anything about +`object` and `any` arguments. They will get cross-compartment +wrappers that make touching them from chrome code not be an immediate +security bug, but otherwise they can have quite surprising behavior if +the page is trying to be malicious. Try to avoid using these types if +possible. + +### Accessing the content object from the implementation + +If the JS implementation of the Web IDL interface needs to access the +content object, it is available as a property called `__DOM_IMPL__` on +the chrome implementation object. This property only appears after the +content-side object has been created. So it is available in `__init` +but not in `init`. + +### Determining the principal of the caller that invoked the Web IDL API + +This can be done by calling +`Component.utils.getWebIDLCallerPrincipal()`. + +### Throwing exceptions from JS-implemented APIs + +There are two reasons a JS implemented API might throw. The first reason +is that some unforeseen condition occurred and the second is that a +specification requires an exception to be thrown. + +When throwing for an unforeseen condition, the exception will be +reported to the console, and a sanitized NS_ERROR_UNEXPECTED exception +will be thrown to the calling content script, with the file/line of the +content code that invoked your API. This will avoid exposing chrome URIs +and other implementation details to the content code. + +When throwing because a specification requires an exception, you need to +create the exception from the window your Web IDL object is associated +with (the one that was passed to your `init` method). The binding code +will then rethrow that exception to the web page. An example of how +this could work: + +``` js +if (!isValid(passedInObject)) { + throw new this.contentWindow.TypeError("Object is invalid"); +} +``` + +or + +``` js +if (!isValid(passedInObject)) { + throw new this.contentWindow.DOMException("Object is invalid", "InvalidStateError"); +} +``` + +depending on which exact exception the specification calls for throwing +in this situation. + +In some cases you may need to perform operations whose exception message +you just want to propagate to the content caller. This can be done like +so: + +``` js +try { + someOperationThatCanThrow(); +} catch (e) { + throw new this.contentWindow.Error(e.message); +} +``` + +### Inheriting from interfaces implemented in C++ + +It's possible to have an interface implemented in JavaScript inherit +from an interface implemented in C++. To do so, simply have one +interface inherit from the other and the bindings code will +auto-generate a C++ object inheriting from the implementation of the +parent interface. The class implementing the parent interface will need +a constructor that takes an `nsPIDOMWindow*` (though it doesn't have +to do anything with that argument). + +If the class implementing the parent interface is abstract and you want +to use a specific concrete class as the implementation to inherit from, +you will need to add a `defaultImpl` annotation to the descriptor for +the parent interface in `Bindings.conf`. The value of the annotation +is the C++ class to use as the parent for JS-implemented descendants; if +`defaultImpl` is not specified, the `nativeType` will be used. + +For example, consider this interface that we wish to implement in +JavaScript: + +``` webidl +[JSImplementation="some-contract"] +interface MyEventTarget : EventTarget { + attribute EventHandler onmyevent; + undefined dispatchTheEvent(); // Sends a "myevent" event to this EventTarget +} +``` + +The implementation would look something like this, ignoring most of the +XPCOM boilerplate: + +``` js +function MyEventTargetImpl() { +} +MyEventTargetImpl.prototype = { + // QI to nsIDOMGlobalPropertyInitializer so we get init() called on us. + QueryInterface: ChromeUtils.generateQI(["nsIDOMGlobalPropertyInitializer"]), + + init: function(contentWindow) { + this.contentWindow = contentWindow; + }, + + get onmyevent() { + return this.__DOM_IMPL__.getEventHandler("onmyevent"); + }, + + set onmyevent(handler) { + this.__DOM_IMPL__.setEventHandler("onmyevent", handler); + }, + + dispatchTheEvent: function() { + var event = new this.contentWindow.Event("myevent"); + this.__DOM_IMPL__.dispatchEvent(event); + }, +}; +``` + +The implementation would automatically support the API exposed on +`EventTarget` (so, for example, `addEventListener`). Calling the +`dispatchTheEvent` method would cause dispatch of an event that +content script can see via listeners it has added. + +Note that in this case the chrome implementation is relying on some +`[ChromeOnly]` methods on EventTarget that were added specifically to +make it possible to easily implement event handlers. Other cases can do +similar things as needed. diff --git a/dom/docs/workersAndStorage/CodeStyle.rst b/dom/docs/workersAndStorage/CodeStyle.rst new file mode 100644 index 0000000000..822779d179 --- /dev/null +++ b/dom/docs/workersAndStorage/CodeStyle.rst @@ -0,0 +1,354 @@ +==================================== +DOM Workers & Storage C++ Code Style +==================================== + +This page describes the code style for the components maintained by the DOM Workers & Storage team. They live in-tree under the 'dom/docs/indexedDB' directory. + +.. contents:: + :depth: 4 + +Introduction +============ + +This code style currently applies to the components living in the following directories: + +* ``dom/file`` +* ``dom/indexedDB`` +* ``dom/localstorage`` +* ``dom/payments`` +* ``dom/quota`` +* ``dom/serviceworkers`` +* ``dom/workers`` + +In the long-term, the code is intended to use the +:ref:`Mozilla Coding Style <Coding style>`, +which references the `Google C++ Coding Style <https://google.github.io/styleguide/cppguide.html>`_. + +However, large parts of the code were written before rules and in particular +the reference to the Google C++ Coding Style were enacted, and due to the +size of the code, this misalignment cannot be fixed in the short term. +To avoid that an arbitrary mixture of old-style and new-style code grows, +this document makes deviations from the "global" code style explicit, and +will be amended to describe migration paths in the future. + +In addition, to achieve higher consistency within the components maintained by +the team and to reduce style discussions during reviews, allowing them to focus +on more substantial issues, more specific rules are described here that go +beyond the global code style. These topics might have been deliberately or +accidentally omitted from the global code style. Depending on wider agreement +and applicability, these specific rules might be migrated into the global code +style in the future. + +Note that this document does not cover pure formatting issues. The code is and +must be kept formatted automatically by clang-format using the supplied +configuration file, and whatever clang-format does takes precedence over any +other stated rules regarding formatting. + +Deviations from the Google C++ Coding Style +=========================================== + +Deviations not documented yet. + +Deviations from the Mozilla C++ Coding Style +============================================ + +.. the table renders impractically, cf. https://github.com/readthedocs/sphinx_rtd_theme/issues/117 + +.. tabularcolumns:: |p{4cm}|p{4cm}|p{2cm}|p{2cm}| + ++--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+-----------------+-------------------------------------------------------------------------------------+ +| Mozilla style | Prevalent WAS style | Deviation scope | Evolution | ++========================================================================================================+============================================================================================+=================+=====================================================================================+ +| We prefer using "static", instead of anonymous C++ namespaces. | Place all symbols that should have internal linkage in a single anonymous | All files | Unclear. The recommendation in the Mozilla code style says this might change in the | +| | namespace block at the top of an implementation file, rather than declarating them static. | | future depending on debugger support, so this deviation might become obsolete. | +| | | | | ++--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+-----------------+-------------------------------------------------------------------------------------+ +| `All parameters passed by lvalue reference must be labeled const. [...] Input parameters may be const | Non-const reference parameters may be used. | All files | Unclear. Maybe at least restrict the use of non-const reference parameters to | +| pointers, but we never allow non-const reference parameters except when required by convention, e.g., | | | cases that are not clearly output parameters (i.e. which are assigned to). | +| swap(). <https://google.github.io/styleguide/cppguide.html#Reference_Arguments>`_ | | | | ++--------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+-----------------+-------------------------------------------------------------------------------------+ + +Additions to the Google/Mozilla C++ Code Style +============================================== + +This section contains style guidelines that do not conflict with the Google or +Mozilla C++ Code Style, but may make guidelines more specific or add guidelines +on topics not covered by those style guides at all. + +Naming +------ + +gtest test names +~~~~~~~~~~~~~~~~ + +gtest constructs a full test name from different fragments. Test names are +constructed somewhat differently for basic and parametrized tests. + +The *prefix* for a test should start with an identifier of the component +and class, based on the name of the source code directory, transformed to +PascalCase and underscores as separators, so e.g. for a class ``Key`` in +``dom/indexedDB``, use ``DOM_IndexedDB_Key`` as a prefix. + +For basic tests constructed with ``TEST(test_case_name, test_name)``: Use +the *prefix* as the ``test_case_name``. Test ``test_name`` should start with +the name of tested method(s), and a . Use underscores as a separator within +the ``test_name``. + +Value-parametrized tests are constructed with +``TEST_P(parametrized_test_case_name, parametrized_test_name)``. They require a +custom test base class, whose name is used as the ``parametrized_test_case_name``. +Start the class name with ``TestWithParam_``, and end it with a transliteration +of the parameter type (e.g. ``String_Int_Pair`` for ``std::pair<nsString, int>``), +and place it in an (anonymous) namespace. + +.. attention:: + It is important to place the class in an (anonymous) namespace, since its + name according to this guideline is not unique within libxul-gtest, and name + clashes are likely, which would lead to ODR violations otherwise. + +A ``parametrized_test_name`` is constructed according to the same rules +described for ``test_name`` above. + +Instances of value-parametrized tests are constructed using +``INSTANTIATE_TEST_CASE_P(prefix, parametrized_test_case_name, generator, ...)``. +As ``prefix``, use the prefix as described above. + +Similar considerations apply to type-parametrized tests. If necessary, specific +rules for type-parametrized tests will be added here. + +Rationale + All gtests (not only from the WAS components) are linked into libxul-gtest, + which requires names to be unique within that large scope. In addition, it + should be clear from the test name (e.g. in the test execution log) in what + source file (or at least which directory) the test code can be found. + Optimally, test names should be structured hierarchically to allow + easy selection of groups of tests for execution. However, gtest has some + restrictions that do not allow that completely. The guidelines try to + accommodate for these as far as possible. Note that gtest recommends not to + use underscores in test names in general, because this may lead to reserved + names and naming conflicts, but the rules stated here should avoid that. + In case of any problems arising, we can evolve the rules to accommodate + for that. + +Specifying types +---------------- + +Use of ``auto`` for declaring variables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The `Google C++ Code Style on auto <https://google.github.io/styleguide/cppguide.html#auto>`_ +allows the use of ``auto`` generally with encouragements for specific cases, which still +leaves a rather wide range for interpretation. + +We extend this by some more encouragements and discouragements: + +* DO use ``auto`` when the type is already present in the + initialization expression (esp. a template argument or similar), + e.g. ``auto c = static_cast<uint16_t>(*(iter++)) << 8;`` or + ``auto x = MakeRefPtr<MediaStreamError>(mWindow, *aError);`` + +* DO use ``auto`` if the spelled out type were complex otherwise, + e.g. a nested typedef or type alias, e.g. ``foo_container::value_type``. + +* DO NOT use ``auto`` if the type were spelled out as a builtin + integer type or one of the types from ``<cstdint>``, e.g. + instead of ``auto foo = funcThatReturnsUint16();`` use + ``uint16_t foo = funcThatReturnsUint16();``. + +.. note:: + Some disadvantages of using ``auto`` relate to the unavailability of type + information outside an appropriate IDE/editor. This may be somewhat remedied + by resolving `Bug 1567464 <https://bugzilla.mozilla.org/show_bug.cgi?id=1567464>`_ + which will make the type information available in searchfox. In consequence, + the guidelines might be amended to promote a more widespread use of ``auto``. + +Pointer types +------------- + +Plain pointers +~~~~~~~~~~~~~~ + +The use of plain pointers is error-prone. Avoid using owning plain pointers. In +particular, avoid using literal, non-placement new. There are various kinds +of smart pointers, not all of which provide appropriate factory functions. +However, where such factory functions exist, do use them (along with auto). +The following is an incomplete list of smart pointer types and corresponding +factory functions: + ++------------------------+-------------------------+------------------------+ +| Type | Factory function | Header file | ++========================+=========================+========================+ +| ``mozilla::RefPtr`` | ``mozilla::MakeRefPtr`` | ``"mfbt/RefPtr.h"`` | ++------------------------+-------------------------+------------------------+ +| ``mozilla::UniquePtr`` | ``mozilla::MakeUnique`` | ``"mfbt/UniquePtr.h"`` | ++------------------------+-------------------------+------------------------+ +| ``std::unique_ptr`` | ``std::make_unique`` | ``<memory>`` | ++------------------------+-------------------------+------------------------+ +| ``std::shared_ptr`` | ``std::make_shared`` | ``<memory>`` | ++------------------------+-------------------------+------------------------+ + +Also, to create an ``already_AddRefed<>`` to pass as a parameter or return from +a function without the need to dereference it, use ``MakeAndAddRef`` instead of +creating a dereferenceable ``RefPtr`` (or similar) first and then using +``.forget()``. + +Smart pointers +~~~~~~~~~~~~~~ + +In function signatures, prefer accepting or returning ``RefPtr`` instead of +``already_AddRefed`` in conjunction with regular ``std::move`` rather than +``.forget()``. This improves readability and code generation. Prevailing +legimitate uses of ``already_AddRefed`` are described in its +`documentation <https://searchfox.org/mozilla-central/rev/4df8821c1b824db5f40f381f48432f219d99ae36/mfbt/AlreadyAddRefed.h#31>`_. + +Prefer using ``mozilla::UniquePtr`` over ``nsAutoPtr``, since the latter is +deprecated (and e.g. has no factory function, see Bug 1600079). + +Use ``nsCOMPtr<T>`` iff ``T`` is an XPCOM interface type +(`more details on MDN <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/nsCOMPtr_versus_RefPtr>`). + +Enums +----- + +Use scoped resp. strongly typed enums (``enum struct``) rather than non-scoped +enums. Use PascalCase for naming the values of scoped enums. + +Evolution Process +================= + +This section explains the process to evolve the coding style described in this +document. For clarity, we will distinguish coding tasks from code style +evolution tasks in this section. + +Managing code style evolution tasks +----------------------------------- + +A code style evolution task is a task that ought to amend or revise the +coding style as described in this document. + +Code style evolution tasks should be managed in Bugzilla, as individual bugs +for each topic. All such tasks +should block the meta-bug +`1586788 <https://bugzilla.mozilla.org/show_bug.cgi?id=1586788>`. + +When you take on to work on a code style evolution task: + +- The task may already include a sketch of a resolution. If no preferred + solution is obvious, discuss options to resolve it via comments on the bug + first. +- When the general idea is ready to be spelled out in this document, amend or + revise it accordingly. +- Submit the changes to this document as a patch to Phabricator, and put it up + for review. Since this will affect a number of people, every change should + be reviewed by at least two people. Ideally, this should include the owner + of this style document and one person with good knowledge of the parts of + the code base this style applies to. +- If there are known violations of the amendment to the coding style, consider + fixing some of them, so that the amendment is tested on actual code. If + the code style evolution task refers to a particular code location from a + review, at least that location should be fixed to comply with the amended + coding style. +- When you have two r+, land the patch. +- Report on the addition in the next team meeting to raise awareness. + +Basis for code style evolution tasks +------------------------------------ + +The desire or necessity to evolve the code style can originate from +different activities, including +- reviews +- reading or writing code locally +- reading the coding style +- general thoughts on coding style + +The code style should not be cluttered with aspects that are rarely +relevant or rarely leads to discussions, as the maintenance of the +code style has a cost as well. The code style should be as comprehensive +as necessary to reduce the overall maintenance costs of the code and +code style combined. + +A particular focus is therefore on aspects that led to some discussion in +a code review, as reducing the number or verbosity of necessary style +discussions in reviews is a major indicator for the effectiveness of the +documented style. + +Evolving code style based on reviews +------------------------------------ + +The goal of the process described here is to take advantage of style-related +discussions that originate from a code review, but to decouple evolution of +the code style from the review process, so that it does not block progress on +the underlying bug. + +The following should be considered when performing a review: + +- Remind yourself of the code style, maybe skim through the document before + starting the review, or have it open side-by-side while doing the review. +- If you find a violation of an existing rule, add an inline comment. +- Have an eye on style-relevant aspects in the code itself or after a + discussions with the author. Consider if this could be generalized into a + style rule, but is not yet covered by the documented global or local style. + This might be something that is in a different style as opposed to other + locations, differs from your personal style, etc. +- In that case, find an acceptable temporary solution for the code fragments + at hand, which is acceptable for an r+ of the patch. Maybe agree with the + code author on adding a comment that this should be revised later, when + a rule is codified. +- Create a code style evolution task in Bugzilla as described above. In the + description of the bug, reference the review comment that gave rise to it. + If you can suggest a resolution, include that in the description, but this + is not a necessary condition for creating the task. + +Improving code style compliance when writing code +------------------------------------------------- + +Periodically look into the code style document, and remind yourself of its +rules, and give particular attention to recent changes. + +When writing code, i.e. adding new code or modify existing code, +remind yourself of checking the code for style compliance. + +Time permitting, resolve existing violations on-the-go as part of other work +in the code area. Submit such changes in dedicated patches. If you identify +major violations that are too complex to resolve on-the-go, consider +creating a bug dedicated to the resolution of that violation, which +then can be scheduled in the planning process. + +Syncing with the global Mozilla C++ Coding Style +------------------------------------------------ + +Several aspects of the coding style described here will be applicable to +the overall code base. However, amendments to the global coding style will +affect a large number of code authors and may require extended discussion. +Deviations from the global coding style should be limited in the long term. +On the other hand, amendments that are not relevant to all parts of the code +base, or where it is difficult to reach a consensus at the global scope, +may make sense to be kept in the local style. + +The details of synchronizing with the global style are subject to discussion +with the owner and peers of the global coding style (see +`Bug 1587810 <https://bugzilla.mozilla.org/show_bug.cgi?id=1587810>`). + +FAQ +--- + +* When someone introduces new code that adheres to the current style, but the + remainder of the function/class/file does not, is it their responsibility + to update that remainder on-the-go? + + The code author is not obliged to update the remainder, but they are + encouraged to do so, time permitting. Whether that is the case depends on a + number of factors, including the number and complexity of existing style + violations, the risk introduced by changing that on the go etc. Judging this + is left to the code author. + At the very least, the function/class/file should not be left in a worse + state than before. + +* Are stylistic inconsistencies introduced by applying the style as defined + here only to new code considered acceptable? + + While this is certainly not optimal, accepting such inconsistencies to + some degree is inevitable to allow making progress towards an improved style. + Personal preferences regarding the degree may differ, but in doubt such + inconsistencies should be considered acceptable. They should not block a bug + from being closed. diff --git a/dom/docs/workersAndStorage/index.rst b/dom/docs/workersAndStorage/index.rst new file mode 100644 index 0000000000..2d2f2a761e --- /dev/null +++ b/dom/docs/workersAndStorage/index.rst @@ -0,0 +1,9 @@ +DOM Workers & Storage +===================== + +These linked pages contain design documents for the Workers & Storage implementations in Gecko. They live in-tree under the 'dom/docs/workerAndStorage' directory. + +.. toctree:: + :maxdepth: 1 + + CodeStyle |