Skip to content
CefSwift
Esc
↑↓navigate↵open⌘Jpreview
On this page

Where bookmarks, history and settings live

Chromium's data directory, each profile's files, and the settings, task and certificate stores.

print(CefProfile.default.storageDirectory?.path ?? "not loaded")
// ~/Library/Application Support/<bundle ID>/CefSwift/Default

Data paths

What crosses between Chromium and Swift, and what is copied on the way. Fixed-size values pass as raw values or as structs both sides read in place; only strings and collections are encoded.

Strings. CEF’s strings are UTF-16, Swift’s UTF-8, so each crossing transcodes once. A string going into CEF is transcoded into a stack buffer (up to 1 KB, else one allocation) that CEF reads for the call; CEF copies what it keeps. A string coming out is decoded straight from CEF’s buffer. Names CefSwift sends again and again, such as process message names, are CefStaticStrings, transcoded once for the process, and received message names are compared with them without making Swift strings.

Page-scripting messages. Bridge calls, replies, events and evaluations carry one payload each: a cef_binary_value_t as the message’s first argument, or, above 64 KB, a shared memory region (cef_shared_process_message_builder_t). The payload starts with a 24-byte header of six Int32s that both processes read in place (CefWireHeader: the target document or request, the call, whether it succeeded, a line and a column), followed by values:

Tag Value Body
0, 1, 2 null, false, true none
3 integer Int32
4 number Float64
5 string UInt32 length, UTF-8
6 array UInt32 byte length, UInt32 count, values
7 object UInt32 byte length, UInt32 count, then UInt32 key length, UTF-8 key and value for each member
8 bytes UInt32 length, bytes

Numbers are little-endian. A container’s byte length counts what follows its own nine bytes, so a reader skips any value without reading it.

Malformed payloads. A renderer may be compromised, so the browser process treats every payload as untrusted, and the renderer does the same for the page’s as a matter of robustness. Before building anything from a value, a reader checks its whole structure (CefWireReader.validateValue(), which recurses no deeper than the depth limit): every tag known; every run, key and element inside the payload and inside its container; each container’s count at most its byte length divided by the smallest element (1 byte; 5 for an object member), and its elements exactly filling its byte length. readContainer() refuses a count larger than the byte length even unchecked, so no reader reserves room for more elements than the payload holds. A malformed value is a thrown error: a DecodingError for a handler’s argument (the call is rejected) or an evaluation’s value (evaluateJavaScript throws), and null in the renderer.

Both processes keep to the same limits (CefWireLimits), which writers enforce and readers check, so every value one side writes, the other reads:

Limit Value Writer beyond it Reader beyond it
Nesting of arrays and objects 64 The renderer writes null, as for a cycle; CefWireEncoder throws EncodingError Error
Payload size, header included 1 GiB The renderer rejects the call or fails the evaluation; CefWireEncoder throws Error, before reading
Values in a payload (containers, elements, members) 16 Mi Same Error

The value limit bounds what decoding allocates: a value on the wire takes at least a byte, and decoded at most a few dozen (a CefJSON case, a dictionary slot), so a reader allocates at most a few hundred MB for a payload at the limits, never the gigabytes a forged count asks for.

Process messages without a wire payload (configure, sync) are read through CefProcessMessage, whose accessors return nil for a missing argument, another type, or a .double that is not exactly an integer. Each handler checks the arity and types it expects and drops anything else: a sync must be exactly one .int.

Message Header Values
cefswift.page.call document, call bridge, method, origin, argument (the calling frame is the message’s frame)
cefswift.page.reply document, call, succeeded bridge, result or error message
cefswift.page.emit none bridge, event, payload
cefswift.page.evaluate request script
cefswift.page.evaluated request, succeeded, line, column value or error message

The renderer writes a V8 value into a payload through the V8 C API as it walks it (V8Wire), transcoding strings from V8’s UTF-16 into the payload, and builds V8 values straight from one. The browser process decodes a call’s argument into the handler’s Decodable type in place (CefWireDecoder) and encodes the result straight into the reply (CefWireEncoder); evaluateJavaScript(_:as:) decodes into T the same way, and evaluateJavaScript(_:) builds its CefJSON from the payload. Primitives cost no allocation; Codable costs one container per struct, array or dictionary.

What the renderer writes is what JSON.stringify would: an object’s own enumerable string-keyed properties, listed by the document’s Object.keys (CEF’s get_keys also lists enumerable properties of the prototype chain, and aborts the renderer when a Proxy trap throws, so it is not used); undefined and functions left out of objects and null in arrays; Dates as ISO strings; null for a cycle or past the depth limit; an ArrayBuffer as bytes. Reading a property can run page code (getters, Proxy traps, a replaced Object.keys), and when that code throws, or CEF reports an exception (has_exception) or a value it cannot read, the whole value fails: a bridge call’s promise rejects with the exception’s message and an evaluation throws CefJavaScriptError, rather than sending what was read so far.

Bytes (ArrayBuffer in the page, Data in Swift) are copied as few times as the processes allow:

Direction Copies
ArrayBuffer argument → Swift Data One when nothing is read after it: from the ArrayBuffer into shared memory as the message is built. The handler’s Data is the mapping itself. Two otherwise (see below).
Swift Data result → page ArrayBuffer Two: into shared memory as the reply is built, then into a V8 backing store the ArrayBuffer owns.

CEF’s pointer to an ArrayBuffer’s bytes is valid while its cef_v8_value_t lives, and page code can detach the buffer (transfer, postMessage with a transfer list) and free the memory. So a deferred run holds a reference to the value, and before the walk next reads a property or an element, anything that can run page code, it copies every deferred run into the payload buffer (CefWireBuffer.materializeDeferred()). The single copy holds for an ArrayBuffer that is the argument, or the last thing read ({ data: buffer }, [x, buffer]); one followed by any other property or element ({ data: buffer, name: "x" }) costs a second copy.

V8 cannot use the shared memory itself: Chromium enables V8’s sandbox, under which an ArrayBuffer must live in the sandbox’s memory (cef_v8_value_create_array_buffer over other memory returns NULL). Bytes under 64 KB are copied into the payload and travel with it.

Who unmaps shared memory. A received payload (CefWirePayload) holds the region, or the binary value and the message that own its bytes, and releases them when its last reference goes. In the browser process, a call’s payload lives until its argument is decoded, unless a Data of at least 64 KB was decoded from it: that Data holds the payload, and the region is unmapped when the Data and its copies are gone, on whatever thread that happens. In the renderer, a reply’s payload lives until the promise is settled, inside the message handler; if the document went away first, no value is made and the region is unmapped as the handler returns. A sending process unmaps its side once CEF has sent the message.

Scheme handler bodies. A .data body is copied from the Data into CEF’s buffer, once per read. A .file body is read with pread(2) into CEF’s buffer, with no copy in between. A .stream body’s chunks are copied into CEF’s buffer once, and the producer waits while more than 1 MB is buffered.

The app’s requests. CefProfile.data(for:) and bytes(for:) turn a URLRequest into a cef_request_t (URLRequestPlan, tested without Chromium) and start a cef_urlrequest_t on the profile’s request context from the IO thread. on_download_data hands over a pointer into Chromium’s buffer, valid for the call. For data(for:) it is appended to one Data, reserved from Content-Length, so each byte is copied once. For bytes(for:) each chunk becomes its own Data (one copy) in a URLRequestStreamBuffer, a lock-protected state machine tested without Chromium. cef_urlrequest_t has no way to pause a body, and blocking the IO thread until the reader catches up is not allowed; real back pressure would need a cef_thread_t per stream to block in on_download_data, and a cef_thread_t must be stopped and released on the thread that created it, which a stream that ends at quit cannot promise. So the buffer never refuses a chunk for being slow to read: it keeps up to streamMemoryLimit (16 MB) in memory, hands a chunk straight to a reader that waits, and past the limit queues each chunk, as it is, for a serial queue that appends the queued chunks to a spill file in batches of up to 64 (pwritev). Once anything has spilled, later chunks are queued too, until the reader has caught up; the file is then truncated and chunks stay in memory again, so order holds whatever the interleaving. The reader takes memory first, then written bytes in 1 MB reads on the same queue, then a queued chunk directly when nothing written is left before it, so a reader that keeps up never waits for the disk. Queued chunks are memory until they are written: while the network outruns the disk (a local server can deliver 64 MB in the 30–50 ms the disk needs to take it) they pile up, by as much as 40 MB of a 64 MB body in SelfTest, and are released as the disk catches up. A .spillToDisk(limit:) cap bounds that too. The end of the body, or the request’s error, is the reader’s after every byte before it. The file is opened on the first spill, in the profile’s directory or, for an incognito profile, the temporary directory, and unlinked at once, so a crash leaves nothing; cancelling, leaving the loop, dropping the body, a quit and the end of the body close it. .spillToDisk(limit:) caps the file and .fail keeps the body off disk; past either the request fails with ERR_INSUFFICIENT_RESOURCES. download(for:to:) does not use the buffer: each chunk goes to a queue that writes it into the destination. A 64 MB body read off the main actor arrives in about 800 chunks, usually with under 2.5 MB in memory; a reader that waits 1 ms per chunk takes all of it through the spill file, with 1 MB in memory and the footprint a few MB higher once written. The client struct owns the loader; the loader holds the cef_urlrequest_t until the request completes, which breaks the cycle through CEF’s reference to the client. Each loader is registered from the moment it takes a request-context reference. Quitting closes the registry, cancels every registered loader on the IO thread and waits, suspended on the main actor while Chromium’s message loop keeps running, until each has cancelled its cef_urlrequest_t and released its CEF references there, and has closed its spill file or removed its partial download; only then does shutdown begin. Their callers get CefError.shutDown. A drain that has not finished after five seconds is abandoned with a log line, and what is left is cancelled without waiting, so a stuck IO thread cannot stop the app from quitting.

DevTools messages. CEF splits each message into a method and its parameters as UTF-8. An event’s parameters are parsed, without a copy, only when something listens for the method; a method result is copied once, for the call waiting on it.

Settings, tasks and certificates

Preference and site-setting streams each hold a cef_registration_t through CefObserverRegistration; the observation ends when the stream’s consumer stops, on the main actor, or at shutdown. Chromium measures CPU and memory only while a task manager object is alive, so CefTaskManager holds one for two refresh intervals after each read and lets go when nothing reads; its API names no process, so tasks are grouped by Chromium’s ordering and identical figures, an estimate the public API says it is. Camera and microphone requests reach on_request_media_access_permission before Chromium reads the content settings, so the client answers them from the settings and asks the delegate only about the rest; desktop audio and video capture in the same callback are .systemAudioCapture and .screenCapture, which no setting answers and nothing stores, and a device grant never sets their bits in the mask. Prompt-based permissions are answered and stored by Chromium itself. Connection security is read from the visible navigation entry’s cef_sslstatus_t on each address and loading-state change.

Was this page helpful?