← All reports

Make Style::Calculation::ValueMap thread-safe

HighWebCore Style value system (Race

CVE: CVE-2026-112686 · Safari 27.2 · Released October 26, 2026 Impact: Processing maliciously crafted web content may lead to an unexpected process termination Apple's description: A race condition was addressed with improved locking. Credit: an anonymous researcher

Severity: High | Component: WebCore Style value system (Style::ValueHandleMap) | 669e3f1 | Bugzilla 323986

High, with a crash-only floor. Four workers and a calc()-valued canvas font are enough to make one process-global hash table rehash under another thread's feet. Going past a renderer crash needs a won race plus control over what reclaims the freed table or value. Neither is established here.

WebKit's CSS engine keeps resolved style values compact by storing small integer handles. Each handle points into a process-wide side table that owns the real out-of-line object, such as the tree for a calc() or min() expression. That table, Style::ValueHandleMap, was built on the assumption that style values are created and released on one thread only. OffscreenCanvas running inside Web Workers quietly broke that assumption.

The angle: A page that starts a few workers and keeps assigning calc()-style fonts to offscreen canvases can make those threads corrupt the shared handle table mid-resize. The reliable result is a renderer crash, and the corruption could become a heap-corruption foothold if the race and the reclaim are both won.

Source/WebCore/style/values/primitives/StyleValueHandleMap.h

@@ -26,6 +26,7 @@
#pragma once
 
#include <wtf/HashMap.h>
+#include <wtf/Lock.h>
#include <wtf/NeverDestroyed.h>
 
namespace WebCore {
@@ -62,15 +63,16 @@ template<typename ValueType> class ValueHandleMap {
}
};
 
- unsigned m_nextAvailableHandle { 1 };
- HashMap<unsigned, Entry> m_map;
+ mutable Lock m_lock;
+ unsigned m_nextAvailableHandle WTF_GUARDED_BY_LOCK(m_lock) { 1 };
+ HashMap<unsigned, Entry> m_map WTF_GUARDED_BY_LOCK(m_lock);
};
 
template<typename ValueType> unsigned ValueHandleMap<ValueType>::insert(Ref<ValueType>&& value)
{
- ASSERT(m_nextAvailableHandle);
-
Entry entry(WTF::move(value));
+ Locker locker { m_lock };
+ ASSERT(m_nextAvailableHandle);
 
// FIXME: This monotonically increasing handle generation scheme is potentially wasteful
// of the handle space. Consider reusing empty handles. https://bugs.webkit.org/show_bug.cgi?id=80489
@@ -83,14 +85,15 @@ template<typename ValueType> unsigned ValueHandleMap<ValueType>::insert(Ref<Valu
// HashMap lookups are not modeled by NoDeleteChecker but cannot destroy anything.
template<typename ValueType> NODELETE SUPPRESS_NODELETE ValueType& ValueHandleMap<ValueType>::get(unsigned handle) const
{
+ Locker locker { m_lock };
auto entry = m_map.find(handle);
ASSERT(entry != m_map.end());
-
return *entry->value.value;
}
 
template<typename ValueType> void ValueHandleMap<ValueType>::ref(unsigned handle)
{
+ Locker locker { m_lock };
ASSERT(m_map.contains(handle));
 
++m_map.find(handle)->value.referenceCountMinusOne;
@@ -98,6 +101,7 @@ template<typename ValueType> void ValueHandleMap<ValueType>::ref(unsigned handle
 
template<typename ValueType> void ValueHandleMap<ValueType>::deref(unsigned handle)
{
+ Locker locker { m_lock };
ASSERT(m_map.contains(handle));
 
auto it = m_map.find(handle);
@@ -106,7 +110,11 @@ template<typename ValueType> void ValueHandleMap<ValueType>::deref(unsigned hand
return;
}
 
+ RefPtr<ValueType> valueHold = WTF::move(it->value.value);
m_map.remove(it);
+ locker.unlockEarly();
+ // Destroying Calculation::Value can run arbitrary `Calculation::Tree` teardown,
+ // so drop the last reference (valueHold) after unlocking.
}

LayoutTests/sar3/fast/canvas/offscreen-canvas-worker-calc-font-race-crash.html

@@ -0,0 +1,33 @@
+// Setting `font` to a calc() that keeps a calc() root — e.g. `simplifyForMinMax`
+// refuses to merge percentages in a <length-percentage> context — registers a
+// `Style::Calculation::Value` in a process-global map. Doing that from several
+// workers can collide due to rehashing during insertion.
+const workerSource = `
+const context = new OffscreenCanvas(1, 1).getContext('2d');
+for (let i = 0; i < 100; ++i)
+ context.font = 'min(' + (i % 90 + 1.5) + '%, ' + (i % 70 + 2.5) + '%) serif';
+self.postMessage('done');
+`;
+
+const workerURL = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));
+const workerCount = 4;
+let finishedCount = 0;
+
+for (let i = 0; i < workerCount; ++i) {
+ const worker = new Worker(workerURL);
+ ...
+}

The whole fix is one header. It changes the generic class template Style::ValueHandleMap<ValueType>, not a calc-specific file. The commit message refers to StyleCalculationValueMap.h and Calculation::ValueMap, but the diff touches StyleValueHandleMap.h, of which Calculation::ValueMap is presumably an instantiation. That matters for auditing: every instantiation of the template inherits the lock, not only the calc one.

The structural change is a mutable Lock m_lock member. The two pieces of mutable state, the handle counter m_nextAvailableHandle and the HashMap<unsigned, Entry> m_map, are now annotated WTF_GUARDED_BY_LOCK(m_lock). With those annotations, Clang's thread-safety analysis rejects any future access to either member that does not hold the lock. The invariant is now enforced at build time, not just documented.

All four entry points take a Locker:

Before the patch, removing the entry was also what released the map's owning RefPtr<ValueType>. That could destroy the Calculation::Value and run its Calculation::Tree teardown. Doing that inside the new critical section is unsafe, because WTF::Lock is not recursive. The patch moves the RefPtr out of the entry into a stack local, valueHold, removes the now-empty entry, and calls locker.unlockEarly(). When valueHold leaves scope at the closing brace, the teardown runs with the lock released.

unlockEarly() is required here, not stylistic. valueHold is declared after locker, and C++ destroys locals in reverse declaration order, so without the explicit unlock valueHold would be destroyed while locker still held the lock:

  Naive locked deref()                     As landed
  ───────────────────────────────          ───────────────────────────────────
  decl 1: Locker locker{m_lock}            decl 1: Locker locker{m_lock}
          m_map.remove(it)                 decl 2: RefPtr valueHold = move(value)
            └─ ~RefPtr → ~Value                    m_map.remove(it)   // RefPtr empty
                 └─ Tree teardown                  locker.unlockEarly()  // lock free
                      └─ deref() → lock ✗  scope exit (reverse order):
                         (non-recursive)     ~valueHold → Tree teardown, unlocked
                                             ~locker   → no-op

The new layout test starts four dedicated workers. Each creates a 1×1 OffscreenCanvas and assigns context.font 100 times, each time a different min(<pct>%, <pct>%) serif value. Every assignment that keeps a calc() root registers a fresh Calculation::Value in the shared map, so four threads hammer insert() together and the map keeps growing. The test passes if the process survives.

Workers and OffscreenCanvas. A dedicated Web Worker runs JavaScript on its own OS thread inside the same renderer (WebContent) process as the page. OffscreenCanvas lets a worker own a canvas 2D context. Setting that context's font property parses and resolves CSS font syntax on the worker's thread, not on the main thread.

CSS math values. CSS math functions like calc(), min() and max() usually fold to a single number at resolution time. When they cannot, WebCore keeps the expression as a Style::Calculation::Value wrapping a Calculation::Tree, its internal expression tree. One case where they cannot fold is mixing percentages in a <length-percentage> context, where the percentage basis is not yet known. Destroying a Calculation::Value tears down that tree, which is ordinary but non-trivial destructor work.

Handle-backed style values. Style PrimitiveData stays small by storing an integer handle rather than a pointer for out-of-line values. Style::ValueHandleMap<ValueType> is the per-type side table behind those handles. It maps each handle to an Entry that owns the value through a RefPtr<ValueType> (WebKit's intrusive refcounting smart pointer) and keeps its own per-handle count, referenceCountMinusOne. Copying a PrimitiveData calls ref(handle), destroying one calls deref(handle), and reading the value calls get(handle). New handles come from a monotonically increasing m_nextAvailableHandle. The handle's lifetime is tracked by the table's counter, and the object's lifetime by the RefPtr inside the table.

Process-wide singletons. ValueHandleMap::singleton() returns a function-local static NeverDestroyed<ValueHandleMap>. NeverDestroyed<T> is WebKit's idiom for an object constructed once on first use and never destructed. Every thread in the process that reaches singleton() gets the same instance.

HashMap growth. WTF::HashMap is an open-addressing hash table: all entries live in one contiguous bucket array. When an insertion pushes the load factor past its threshold, the map rehashes. It allocates a larger bucket array, re-inserts every entry, and frees the old array. Removals can likewise shrink the table. HashMap has no internal synchronization, so a map shared across threads needs an external lock.

Locks and annotations. WTF::Lock is a small, non-recursive mutex. A thread that tries to acquire a lock it already holds deadlocks. Locker is its RAII guard: it acquires in its constructor and releases in its destructor. Locker::unlockEarly() releases before the guard leaves scope. WTF_GUARDED_BY_LOCK(lock) is a Clang thread-safety attribute that makes the compiler warn when the annotated member is accessed without the named lock held.

This is a data race on a process-global, non-thread-safe hash table and its manual refcounts. It leads to heap corruption and use-after-free of the table's backing store.

  Worker A (context.font = min(1.5%,2.5%))   Worker B (context.font = min(2.5%,3.5%))
  ─────────────────────────────────────────  ─────────────────────────────────────────
  insert(): h = m_nextAvailableHandle (=7)   insert(): h = m_nextAvailableHandle (=7)
            m_nextAvailableHandle = 8                  m_nextAvailableHandle = 8
  m_map.add(7, entryA)                       m_map.add(7, entryB)   // duplicate handle
    load factor exceeded → rehash              probing bucket array T0 ...
    alloc T1, move entries into T1
    free(T0) ──────────────────────────────►   write entryB into bucket of T0  ◄── freed
  m_map now = T1 (entryB lost)               returns handle 7 → points at entryA's value

In the diagram above, both threads run insert() on the same singleton with no lock. The left column's m_map.add crosses the load-factor threshold. HashMap allocates T1, migrates the entries and frees T0. The right column is still probing or writing buckets in T0, so that write lands in freed memory. This is the "collide due to rehashing during insertion" that the regression test's comment names. Depending on interleaving, the result is lost entries, duplicated or corrupted buckets, or writes into a freed allocation sized to the map's bucket array. The top row shows a second, independent race: m_nextAvailableHandle++ is an unsynchronized read-modify-write, so two threads can receive the same handle or skip one.

The underlying invariant is that a ValueHandleMap is only ever touched by one thread. The original design was correct under that assumption, since style resolution was main-thread work. Workers broke it. Per the test comment, assigning an OffscreenCanvas 2D font to min(%, %) in a length-percentage context keeps a calc() root, and that root goes through insert() into the global Calculation::Value map. The renderer now has several JavaScript-driven threads reaching the same NeverDestroyed instance, and nothing serialized them.

Triggering it needs nothing beyond ordinary web content, and the test is effectively the PoC:

  1. The page builds a Blob URL for a worker script and spawns four dedicated workers.
  2. Each worker creates new OffscreenCanvas(1, 1).getContext('2d').
  3. Each worker assigns context.font = 'min(X%, Y%) serif' 100 times, varying X and Y so every value is distinct and must be registered fresh.
  4. Each assignment parses the font on the worker's thread. The percentages cannot be merged, so a Calculation::Value is created and ValueHandleMap::insert() runs.
  5. Four threads drive the shared map through repeated growth, and any rehash that overlaps another thread's insert hits the race in the diagram.

The insert-vs-insert rehash is the shape the test exercises, but the refcount path is the more interesting one for lifetime bugs. ref() and deref() do a plain ++/-- on referenceCountMinusOne inside a table entry. Two threads adjusting the same handle can lose an update. A lost increment means a later deref() sees what it believes is the last reference and removes the entry. The RefPtr in that entry then drops its reference and the Calculation::Value can be freed, while a live PrimitiveData elsewhere still carries the handle. That holder's next get() returns a reference into a freed or reused slot. Separately, ref/deref on one handle can overlap with an insert or remove on another handle that rehashes or shrinks the table, which puts the find() result in the same freed-backing-store window as the insert race. A duplicate handle from the racy counter has the same downstream effect: two logically distinct values sharing one handle, so the wrong value can be returned or freed.

The fix restores the single-writer invariant by making it explicit. Every access to m_map and m_nextAvailableHandle now happens under m_lock, and the compiler enforces it. Rehashes become atomic with respect to other operations, handle allocation is serialized, and refcount updates can no longer lose writes. Adding the lock introduced its own hazard, which the deref() restructuring handles. With a non-recursive WTF::Lock, destroying a Calculation::Value inside the critical section could let Calculation::Tree teardown re-enter deref() on the same singleton, for example for nested handle-backed values. That would deadlock in release builds or assert in debug builds. Moving the last RefPtr into valueHold and calling unlockEarly() before scope exit keeps the container mutation inside the lock and the destructor work outside it.

The security impact sits entirely inside the WebContent process, where both the main thread and worker threads run. The reliable outcome is a crash from corrupted HashMap internals during a concurrent rehash, which matches Apple's "unexpected process termination". Beyond that, the primitives are a write into a freed bucket-array allocation and a lifetime violation on Calculation::Value. If an attacker could win the rehash race repeatedly and control what reoccupies the freed table or the freed Calculation::Value, either could give renderer-plane heap corruption or a UAF on a style value object. Without that control, the ceiling is an attacker-triggerable crash. The bug does not cross the sandbox boundary by itself; reaching beyond the renderer would still need a separate escape.

A process-global handle table built for one thread became reachable from every worker that sets a canvas font, so concurrent inserts can rehash the table out from under each other.

This is a recurring hazard: a subsystem written for the main thread gets exposed to workers. OffscreenCanvas pulls CSS font parsing and style-value resolution, historically main-thread code, onto worker threads. Every process-global cache on that path, such as interning tables, value pools and NeverDestroyed handle maps, silently becomes shared mutable state, even though nothing in its own file changed. These bugs are not regressions in the cache. They come from a new caller far away, so a diff review of the cache would never catch them. That is why the WTF_GUARDED_BY_LOCK annotations are the durable part of the fix: they turn the next unlocked access into a compile error, not another race.