From 36d22d82aa202bb199967e9512281e9a53db42c9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 21:33:14 +0200 Subject: Adding upstream version 115.7.0esr. Signed-off-by: Daniel Baumann --- dom/docs/fedcm.rst | 67 + dom/docs/index.rst | 17 + dom/docs/ioutils_migration.md | 589 +++++ dom/docs/ipc/Fission-IPC-Diagram.svg | 5 + dom/docs/ipc/Fission-actors-diagram.png | Bin 0 -> 69010 bytes dom/docs/ipc/Fission-framescripts.png | Bin 0 -> 84425 bytes dom/docs/ipc/index.rst | 9 + dom/docs/ipc/jsactors.rst | 547 +++++ dom/docs/ipc/mainthread.rst | 13 + dom/docs/ipc/process_model.rst | 334 +++ dom/docs/navigation/BrowsingContext.rst | 149 ++ dom/docs/navigation/embedding.rst | 92 + dom/docs/navigation/index.rst | 9 + dom/docs/navigation/nav_replace.rst | 119 + dom/docs/push/index.md | 118 + dom/docs/scriptSecurity/images/compartments.png | Bin 0 -> 208057 bytes .../scriptSecurity/images/computing-a-wrapper.png | Bin 0 -> 282979 bytes .../images/cross-compartment-wrapper.png | Bin 0 -> 53671 bytes .../scriptSecurity/images/cross-origin-wrapper.png | Bin 0 -> 56232 bytes dom/docs/scriptSecurity/images/opaque-wrapper.png | Bin 0 -> 55336 bytes .../images/principal-relationships.png | Bin 0 -> 147630 bytes .../scriptSecurity/images/same-origin-wrapper.png | Bin 0 -> 56603 bytes dom/docs/scriptSecurity/images/xray-wrapper.png | Bin 0 -> 55418 bytes dom/docs/scriptSecurity/index.rst | 318 +++ dom/docs/scriptSecurity/xray_vision.rst | 411 ++++ dom/docs/webIdlBindings/index.md | 2427 ++++++++++++++++++++ dom/docs/workersAndStorage/CodeStyle.rst | 354 +++ dom/docs/workersAndStorage/index.rst | 9 + 28 files changed, 5587 insertions(+) create mode 100644 dom/docs/fedcm.rst create mode 100644 dom/docs/index.rst create mode 100644 dom/docs/ioutils_migration.md create mode 100644 dom/docs/ipc/Fission-IPC-Diagram.svg create mode 100644 dom/docs/ipc/Fission-actors-diagram.png create mode 100644 dom/docs/ipc/Fission-framescripts.png create mode 100644 dom/docs/ipc/index.rst create mode 100644 dom/docs/ipc/jsactors.rst create mode 100644 dom/docs/ipc/mainthread.rst create mode 100644 dom/docs/ipc/process_model.rst create mode 100644 dom/docs/navigation/BrowsingContext.rst create mode 100644 dom/docs/navigation/embedding.rst create mode 100644 dom/docs/navigation/index.rst create mode 100644 dom/docs/navigation/nav_replace.rst create mode 100644 dom/docs/push/index.md create mode 100644 dom/docs/scriptSecurity/images/compartments.png create mode 100644 dom/docs/scriptSecurity/images/computing-a-wrapper.png create mode 100644 dom/docs/scriptSecurity/images/cross-compartment-wrapper.png create mode 100644 dom/docs/scriptSecurity/images/cross-origin-wrapper.png create mode 100644 dom/docs/scriptSecurity/images/opaque-wrapper.png create mode 100644 dom/docs/scriptSecurity/images/principal-relationships.png create mode 100644 dom/docs/scriptSecurity/images/same-origin-wrapper.png create mode 100644 dom/docs/scriptSecurity/images/xray-wrapper.png create mode 100644 dom/docs/scriptSecurity/index.rst create mode 100644 dom/docs/scriptSecurity/xray_vision.rst create mode 100644 dom/docs/webIdlBindings/index.md create mode 100644 dom/docs/workersAndStorage/CodeStyle.rst create mode 100644 dom/docs/workersAndStorage/index.rst (limited to 'dom/docs') 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``. +- 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 read(DOMString path, ...); + +Promise readUTF8(DOMString path, ...); + +Promise 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 write(DOMString path, Uint8Array data, ...); + +Promise writeUTF8(DOMString path, DOMString string, ...); + +Promise 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 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 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 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 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 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 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> getChildren(DOMString path); +``` + +#### Example + +**`OS.File`** +```js +for await (const { path } of new OS.FileDirectoryIterator(dirName)) {

+ ... +} +``` + +**`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 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 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 @@ + + +
Browser Process
Browser Process
Content Process
<div>Content Process</div>
Content Process
<div>Content Process</div>
<xul:browser src="a.com"/>
nsFrameLoader
[Not supported by viewer]
PBrowser
[Not supported by viewer]
BrowserParent
BrowserParent
BrowserChild
BrowserChild
nsWebBrowser
nsWebBrowser
<iframe src="b.com"/>
nsFrameLoader
[Not supported by viewer]
PBrowserBridge
PBrowserBridge
BrowserBridgeChild
BrowserBridgeChild
PBrowser
[Not supported by viewer]
BrowserParent
BrowserParent
BrowserChild
BrowserChild
PBrowser
[Not supported by viewer]
BrowserParent
BrowserParent
BrowserChild
BrowserChild
BrowserBridgeParent
BrowserBridgeParent
BrowserBridgeParent
BrowserBridgeParent
nsWebBrowser
nsWebBrowser
nsWebBrowser
nsWebBrowser
<iframe src="a.com"/>
nsFrameLoader
[Not supported by viewer]
PBrowserBridge
PBrowserBridge
BrowserBridgeChild
BrowserBridgeChild

Gecko IPC for Fission

Example:
<xul:browser src="a.com"/>
  <iframe src="b.com"/>
    <iframe src="a.com"/>

[Not supported by viewer]
\ No newline at end of file diff --git a/dom/docs/ipc/Fission-actors-diagram.png b/dom/docs/ipc/Fission-actors-diagram.png new file mode 100644 index 0000000000..d3acce2c5c Binary files /dev/null and b/dom/docs/ipc/Fission-actors-diagram.png differ diff --git a/dom/docs/ipc/Fission-framescripts.png b/dom/docs/ipc/Fission-framescripts.png new file mode 100644 index 0000000000..98748bc965 Binary files /dev/null and b/dom/docs/ipc/Fission-framescripts.png differ 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:: + + + + + + + + + + + + +.. 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 ``_. + + +API Documentation +----------------- + +.. cpp:class:: BrowsingContext + + .. hlist:: + :columns: 3 + + * `header (searchfox) `_ + * `source (searchfox) `_ + * `html spec `_ + + 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 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) `_ + * `source (searchfox) `_ + + 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) `_ + * `source (searchfox) `_ + +.. cpp:class:: WindowGlobalParent : public WindowContext, public WindowGlobalActor, public PWindowGlobalParent + + .. hlist:: + :columns: 3 + + * `header (searchfox) `_ + * `source (searchfox) `_ + +.. cpp:class:: WindowGlobalChild : public WindowGlobalActor, public PWindowGlobalChild + + .. hlist:: + :columns: 3 + + * `header (searchfox) `_ + * `source (searchfox) `_ 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.