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

Process model and helpers

Chromium's processes, the five helper apps, loading the framework, unresponsive pages, quitting and relaunching.

var configuration = CefRuntime.Configuration.embedded
configuration.processPolicy = .minimal   // .automatic, .onDemand or .minimal

Gallery: TaskManagerDemo.

Processes

CefRuntime.shared.taskManager is Chromium’s task manager: an @Observable list of the app’s processes and what runs in them, with CPU and memory, as Chrome’s Task Manager shows them.

struct TaskList: View {
    private let manager = CefRuntime.shared.taskManager

    var body: some View {
        Table(manager.tasks) {
            TableColumn("Task", value: \.title)
            TableColumn("Memory") { task in
                Text(task.memory.map { ByteCountFormatter.string(fromByteCount: $0, countStyle: .memory) } ?? "–")
            }
        }
    }
}

Each CefTaskManager.Task has a kind (.page, .gpu, .renderer, .utility, .serviceWorker, …), Chromium’s title, cpuUsage in percent of one core (up to processorCount × 100), memory and gpuMemory in bytes (nil until Chromium has measured them), and canTerminate. terminate(_:) ends a task’s process, as End Process does; the pages it showed report page(_:renderProcessDidTerminate:). Chromium does not end the app’s own process.

tasks refreshes every refreshInterval (one second) while something reads it: a view showing it, or code that reads it again within two intervals. When nothing does, it stops, and Chromium stops measuring. refresh() takes one snapshot at once.

The figures belong to processes, and several tasks can share one: tabs of one site in one renderer, a page and its workers. Tasks of one process report the same figures and the same process; processes groups them, and CefTaskManager.Process.estimatedTotalMemory(of:) counts each process once. Chromium’s API names no process, so the grouping is an estimate: CefSwift groups the consecutive renderer tasks with identical measured figures, which is what the tasks of one process have. Two separate renderers that report the same figures side by side are grouped as one, which undercounts the total, and tasks not measured yet stay apart. Show the grouping; do not decide anything by it.

taskManager.task(for: page) is the task of the renderer showing a page’s document, and taskManager.pages(in:) lists the pages in the same estimated process, so a page’s memory is that process’s memory shared with those pages.

Unresponsive pages

A page whose renderer has not handled input for 15 seconds, such as one stuck in a loop, is unresponsive: page.isResponsive turns false until it responds again or its process ends. Chrome-style pages show Chromium’s “Page Unresponsive” dialog. Other pages ask the delegate, whose default is a native sheet offering Wait and Force Reload:

func pageIsUnresponsive(_ page: CefPage) async -> CefUnresponsivePageDecision {
    .reload   // .wait asks again later if the page still does not respond; .terminate ends it
}

Set CefPage.Configuration.unresponsivePages to .delegate to have Chrome-style pages ask the delegate too, instead of showing Chromium’s dialog. A page that responds again before you answer withdraws the question: the task is cancelled and the default sheet dismisses itself. So do a navigation, closing the page, and a second notification while the first is still open, which replaces it; an answer to a withdrawn question is ignored. .reload reloads only when the renderer it was asked about ends, never a later one.

Processes

The app is Chromium’s browser process. Renderer, GPU and utility processes run from the helper apps inside the bundle, all the same executable, CefSwift’s cefswift-helper product, which cef bundle or the Xcode build phase builds with the app (bundling), through the cefswift tool both run. It finds the framework dyld loaded with it, checks the API hash, registers the custom URL schemes it receives on its command line (--cefswift-schemes), so every process registers the same list, and calls cef_execute_process; in renderers, with the render process handler described in Page-facing features. With the sandbox on, each helper seals itself before any framework code runs (sandbox).

Loading the framework at launch

The helper links two libraries, in this order:

  1. Contents/Frameworks/libcefswift_helper_startup.dylib, CefSwift’s cefswift_helper_startup product (Sources/CefHelperStartup, a few lines of C). Its initializer opens CEF’s libcef_sandbox.dylib and calls cef_sandbox_initialize unless the helper was started with --no-sandbox. dyld runs a library’s initializers before those of the libraries listed after it, so the sandbox is sealed before the framework’s static initializers run. This part stays C: it must run before the framework’s initializers, which run before any of the executable’s own code, and must not load the Swift runtime.
  2. The CEF framework.

Both tracks link the helper with -needed_library and -needed_framework for these two, in that order (HelperLink.swift), and -dead_strip_dylibs, which drops libraries the helper does not use, such as Foundation, which SwiftPM’s build system links into executables by default. The helper uses the Swift standard library and the C API, not Foundation.

A library that dyld loads at launch is fixed up by the kernel as its pages are read in (page-in linking), so the framework’s __DATA_CONST segment, about 12 MB of pointers, stays clean memory that every process shares. A library loaded with dlopen has the same segment fixed up in the process, which makes all of it private, dirty memory. The app executable gets the same benefit from the weak link cef bundle gives it; an Xcode target’s executable does not link the framework, so its process loads it with dlopen (bundling). With this change and the presets’ process settings, the Minimal example’s idle footprint went from 185 MB in six processes to 88 MB in five, most of it from linking at launch (design notes).

Chrome 157 does the same with its “Aperitif” helpers: separate helper apps (Google Chrome Helper (Aperitif).app and so on) that link libaperitif.dylib, which registers PartitionAlloc’s malloc zone and seals the sandbox in an initializer, and then the framework (content/public/app/aperitif_mac.h). Chromium chooses those helper names when its AperitifHelpers feature is on. CEF 156 does not ship libaperitif.dylib or Aperitif helpers and leaves the feature off; turning it on with --enable-features=AperitifHelpers makes Chromium launch helper apps that the bundle does not contain. CefSwift’s helper keeps CEF’s classic helper names and gets the memory saving without the feature.

Quitting

CefApplication.terminate(_:) asks CefRuntime first. The runtime closes every page, so pages can run beforeunload, and declines the request. As the last page and the last Chromium window are destroyed, it calls terminate(_:) again from the run loop. It then waits for the profile requests in flight to end on the IO thread (see “The app’s requests”), declining once more and calling terminate(_:) again when they have, and shuts Chromium down in a fixed order: the shutdown participants (service hosts, the media router’s registrations), lifecycle observers and the discard policy’s timer, the preference and site-setting observer registrations (CefObserverRegistration, whose streams finish) and the task manager object, every profile’s request context, the message pump, then cef_shutdown() with the thread actors’ jobs waiting it out. CefRuntime.state is .stopping meanwhile and .stopped after; initialize then throws CefError.shutDown, as Chromium cannot start twice in a process. Calling cef_shutdown() earlier, or from inside a CEF callback, crashes, so the shutdown is internal to this path. A page that asks to stay cancels the quit. A page discarded by closing has no Chromium page left and is marked closed at once.

Logging out, restarting and shutting down send the app a quit Apple Event, which AppKit handles with terminate(_:). While the pages close, the runtime suspends that event (NSAppleEventManager.suspendCurrentAppleEvent), as NSApplication.TerminateReply.terminateLater does, and resumes it when they are gone, or with userCanceledErr when a page asks to stay, which stops the logout as an app that cancels it does.

Relaunching

Only one process can use a data directory, so an app runs as a single instance. When it is launched again while running, from the command line or by another app, the new process hands its arguments to the running one and exits. The running app is brought to the front and CefRuntime.shared.onRelaunch receives the new launch’s arguments, without the program path, and its working directory:

CefRuntime.shared.onRelaunch = { arguments, workingDirectory in
    let urls = arguments.compactMap(URL.init(string:)).filter { $0.scheme != nil }
    if urls.isEmpty { openTab(nil) } else { urls.forEach(openTab) }
}

Resolve relative file paths against workingDirectory. Without a handler, a relaunch only brings the app to the front.

Relaunching

Chromium allows one process per data directory. A second launch finds the running one, hands it its command line and working directory, and exits; CefRuntime.initialize(configuration:) throws CefError.anotherInstanceRunning in that process. The running process receives the launch from Chromium, activates the app and calls CefRuntime.onRelaunch on the next run-loop turn, outside Chromium’s callback.

Was this page helpful?