Skip to content

Don't enter GC free zones in atomic operations - #1443

Merged
Simn merged 3 commits into
masterfrom
remove-atomic-gc-free-zones
Oct 30, 2026
Merged

Simn merged 3 commits into
masterfrom
remove-atomic-gc-free-zones

Conversation

@Simn

@Simn Simn commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Since #1441, every AtomicInt and AtomicObject operation enters and leaves a GC free zone. These operations are on std::atomic and never block, so a free zone isn't needed, and it is costly, mostly on Windows. This PR removes the zones. It keeps the one useful side effect: each operation is still a GC safe point.

Cost

On Windows, HxSemaphore is a Win32 event. Entering a zone calls SetEvent, and leaving it calls ResetEvent while holding the global gThreadStateChangeLock. That's two kernel calls and a process-wide lock for every atomic operation.

Measured on Windows (MSVC, release), 1,000,000 operations in a loop:

before after
AtomicInt.load ~670 ns 2–3 ns
AtomicInt.add ~660 ns 8–9 ns
AtomicInt.load, 4 other threads allocating ~1050 ns 2 ns

Before #1441, cpp atomics were inline intrinsics, so this is a regression. In hxcoro, a work-stealing thread pool does a few atomic operations per scheduled event. It slowed down by about 15–25x on Windows, and every thread contended on gThreadStateChangeLock. With this change, a benchmark round went from 3.6 s to 0.23 s.

GC safe points

Entering a free zone also made each atomic operation a GC safe point. A loop that spins on atomics without allocating depends on that (see HaxeFoundation/haxe#13087). Without it, a collection started by another thread waits for the spinning thread forever.

Each operation now starts with __hxcpp_gc_safe_point(), which only reads gPauseForCollect unless a collection is pending. In a test where a thread spins on compareExchange and load while another allocates enough to trigger collections, removing the zones alone hung in the first round, and with the safe points all 200 rounds passed.

Correctness for AtomicObject

A collection can run while a thread is inside a GC free zone, and the GC can move objects. __Visit stores the moved pointer back for this reason. load() read the raw pointer inside the zone and converted it to Dynamic before leaving the zone, so a collection in that window could leave it holding a stale pointer. Without the zone, no collection can run during the operation.

Relation to #1442

#1442 fixes AtomicInt.compareExchange reporting success for exchanges that didn't happen. Faster atomics make that race much easier to hit. With this PR alone, the hxcoro thread pool benchmark crashed in most runs. With #1442 as well, 16 of 16 runs passed. I'd merge #1442 first, or both together.

🤖 Generated with Claude Code

Operations on std::atomic never block, so they don't need to let a
collection run alongside them. Entering and leaving a zone is expensive:
on Windows it costs two kernel calls (SetEvent/ResetEvent) and takes the
global gThreadStateChangeLock, which made each atomic operation take
roughly 650 ns instead of a few.

For AtomicObject, the zone was also unsafe: a collection running while
the thread is in the zone can move the referenced object, while load()
is still handing out the raw pointer it read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread src/hx/atomic/AtomicObject.cpp Resolved
Simn and others added 2 commits October 30, 2026 10:54
The GC free zones also made every atomic operation a GC safe point. A
loop that spins on atomics without allocating relies on that: without
it, a collection started by another thread waits for the spinning
thread forever. Check for a pending collection at the start of each
operation instead, which costs a read of gPauseForCollect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Simn

Simn commented Oct 30, 2026

Copy link
Copy Markdown
Member Author

Our combined intelligence isn't quite sure if we should really be doing this in the atomic functions in the first place, but everyone agrees that it's an improvement over the current state, so I'll merge this.

@Simn
Simn merged commit 24d5416 into master Oct 30, 2026
63 checks passed
@Simn
Simn deleted the remove-atomic-gc-free-zones branch October 30, 2026 14:22
HomuHomu833 pushed a commit to ShadowEngineTeam/libhxcpp that referenced this pull request Nov 2, 2026
Since HaxeFoundation/haxe#13095, Haxe 5's haxe.atomic.AtomicInt and
AtomicObject on C++ are hx::atomic::AtomicInt and AtomicObject from
hx/atomic/AtomicInt.hpp and AtomicObject.hpp, which stock added in
HaxeFoundation/hxcpp#1441. Without them a program using haxe.atomic did
not compile with the current Haxe 5. Haxe 4 and 5.0.0-preview.1 keep using
the atomic intrinsics, which are unchanged.

They take the form stock settled on in HaxeFoundation/hxcpp#1442 and
HaxeFoundation/hxcpp#1443: compareExchange returns the value it found,
which equals expected only when it stored, and each operation is a GC
safe point, not a GC free zone, which was 15 to 25 times slower and let a
collection move an object a load had just read. Unlike stock's, each holds
its std::atomic itself instead of behind an Impl it allocated and never
freed, so no native block leaks per atomic. Both are header only, so no
build file changes, and AtomicInt is allocated as data, since it holds no
pointers.

Tests: HaxeAtomics checks every AtomicInt operation and four threads
adding at once; CppiaHaxeAtomics uses AtomicInt from a script through the
host, interpreted and with the JIT; TestAtomicObject in the native suite
checks AtomicObject's operations, strings comparing by value, and values
only it holds surviving collections. C++ has AtomicObject only from the
Haxe 5 with HaxeFoundation/haxe#13095, so that test runs where the native
suite's other Haxe 5 tests do. openfl#416.
dimensionscape added a commit to openfl/libhxcpp that referenced this pull request Nov 27, 2026
libhxcpp #455 made Haxe 4's haxe.atomic.AtomicInt operations safe
points, through cpp::Pointer<int> overloads of the _hx_atomic_*
functions. Haxe 5.0.0-preview.1's AtomicInt is a class with an Int
field instead, and calls _hx_atomic_add(&{0}, ...) on that field, so it
passes a plain int *. That binds to the runtime's volatile int * forms,
which never stop, so a thread spinning on flag.load() still held up
every collection, and every other thread with it. AtomicBool wraps
AtomicInt and had the same gap. AtomicSpinSafePoint has failed this
way on the preview.1 jobs, where failures are warnings.

The stopping forms take an int * now, and the cpp::Pointer<int> ones
call them. The runtime's own spinlocks pass a volatile int *, so they
keep the forms that do not stop. _hx_atomic_xor was the one runtime
form that took an int *; it takes a volatile int * like the others.

AtomicFieldSpinSafePoint does what preview.1's AtomicInt does on any
Haxe: a thread spins on each of the nine operations in turn, called on
the address of an Int field, while the main thread collects. Before
this, the first collection never finished and its watchdog ended the
test after 60 s; it passes in under a second now, and with
HXCPP_GC_MOVING.

HaxeFoundation/hxcpp#1443

Tests: AtomicFieldSpinSafePoint, AtomicSpinSafePoint
dimensionscape added a commit to openfl/libhxcpp that referenced this pull request Nov 28, 2026
Erase a moved object's old id entry before inserting its new address

When the moving collector moves an object that has an id, MoveSpecial
found its entry in sObjectIdMap, inserted the new address with
operator[], and then erased the old entry through the iterator it had
found. The insert can rehash the unordered_map, and a rehash invalidates
every iterator, so the erase was undefined behaviour. Any id'd object
can be moved, ObjectMap keys among them, since under HXCPP_GC_MOVING
they all take their hash from __hxcpp_obj_id.

The id is now read out, the old entry erased, and the new one inserted,
as the finalizer and zombie maps just above already do.

No test can fail before this: libstdc++, libc++ and MSVC all keep a
node's iterator valid through a rehash, even in their debug modes.
Issue679 moves 20,000 ObjectMap keys through compactions and still
finds every one.

HaxeFoundation/hxcpp#1468

Tests: Issue679

Check the length of an IPv6 address array before reading it

host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 read 16
bytes from &host[0] whatever the array's length. An empty array grew to
one element and was read 15 bytes past it, a shorter one was read past
its end, and a null one crashed. So host_to_string_ipv6 of four 0xff
bytes gave "ffff:ffff::106:8010", and connect and bind went to whatever
address followed the array in memory. host_reverse_ipv6 already checked
for 16 bytes and copied them out first.

The four functions share one helper now, which copies the address out
of the array and refuses a null array or one of any length but 16.
host_to_string_ipv6 gives null for such an array, as host_reverse_ipv6
does, and connect and bind throw "Invalid IPv6 address". sys.net.Host
always passes the 16 bytes host_resolve_ipv6 made, so only direct
cpp.NativeSocket callers could reach this.

HaxeFoundation/hxcpp@a8a5724f, which swapped &a[0] for Pointer() in
these functions, does not check the length either.

Tests: SocketIpv6AddressLength

Run a cppia var statement with no declarations without indexing it

TVars reads its declaration count from the file, and checkCount accepts
0. runVoid then started from &vars[0] on the empty vector, which is
undefined behaviour: a standard library that checks indexing, such as
libstdc++ with _GLIBCXX_ASSERTIONS or MSVC's checked iterators, stops
the program there. The Haxe compiler never writes an empty one, so only
a malformed or hand-made file reaches it. BlockExpr guards the same
pattern with a size check.

runVoid walks the declarations by index now, as genCode already did.

CppiaEmptyVars loads hand-written modules whose main is an empty var
statement, alone and twice in a block, and runs them interpreted and
under the JIT. No build here checks indexing, so it passed before too.

HaxeFoundation/hxcpp@a8a5724f

Tests: CppiaEmptyVars

Stop for a collection in the atomic operations on a plain int *

libhxcpp #455 made Haxe 4's haxe.atomic.AtomicInt operations safe
points, through cpp::Pointer<int> overloads of the _hx_atomic_*
functions. Haxe 5.0.0-preview.1's AtomicInt is a class with an Int
field instead, and calls _hx_atomic_add(&{0}, ...) on that field, so it
passes a plain int *. That binds to the runtime's volatile int * forms,
which never stop, so a thread spinning on flag.load() still held up
every collection, and every other thread with it. AtomicBool wraps
AtomicInt and had the same gap. AtomicSpinSafePoint has failed this
way on the preview.1 jobs, where failures are warnings.

The stopping forms take an int * now, and the cpp::Pointer<int> ones
call them. The runtime's own spinlocks pass a volatile int *, so they
keep the forms that do not stop. _hx_atomic_xor was the one runtime
form that took an int *; it takes a volatile int * like the others.

AtomicFieldSpinSafePoint does what preview.1's AtomicInt does on any
Haxe: a thread spins on each of the nine operations in turn, called on
the address of an Int field, while the main thread collects. Before
this, the first collection never finished and its watchdog ended the
test after 60 s; it passes in under a second now, and with
HXCPP_GC_MOVING.

HaxeFoundation/hxcpp#1443

Tests: AtomicFieldSpinSafePoint, AtomicSpinSafePoint

Say an Int is not an Int64

haxe.Int64.isInt64(100) was true on C++ and false on the other targets,
and so was isInt64(1.0), because a whole Float boxes as an Int. Haxe 4.2
implements isInt64 with cpp::Int64Struct::is, which asks Int64Handler,
and Haxe 4.3 and 5.0.0-preview.1 with Std.isOfType(val, cpp.Int64),
which asks the cpp::Int64 class's IsInt64 in Dynamic.cpp. Both took a
boxed Int as well as a boxed Int64.

They took Ints because small Int64 values, -1 to 255, used to come out
of the boxed Int cache. Since 6.0.0 they have a cache of their own, so
every boxed Int64 is an Int64Data and reports vtInt64, and both checks
now take only that. This changes behaviour for code that used isInt64
to accept any integer. Std.isOfType(int64, Int) stays true for a value
that fits, as for a whole Float.

Int64IsInt64 checks isInt64 on Ints, a whole Float, null, a String and
Int64 values on both sides of the box cache, asks the handler and the
class directly so each is covered whichever Haxe builds it, and asks
again from a cppia script, interpreted and under the JIT. Before this,
the Int, 0 and 1.0 cases were all true.

HaxeFoundation/hxcpp#1461

Tests: Int64IsInt64

Report a thread that allocates in a GC-free zone during a collection

A thread in a GC-free zone that allocates, or collects, while another
thread collects reaches PauseForCollect and waits there for the
collection to finish. The collector neither waits for a thread in a
zone nor releases it at the end, so in a release build that thread
waited for ever, with nothing to say why. Native code that misses an
ExitGCFreeZone is the usual way there. Debug builds report any
allocation or collection in a zone, before it gets that far.

PauseForCollect now ends the program with a critical error that names
the misuse when its thread is in a zone. No correct caller gets there:
safe points return first in a zone, as do the Mutex and Condition fast
paths that call them, and ExitGCFreeZone waits out a collection on the
state lock instead.

GcFreeZoneAllocationReported runs the misuse in a child process: one
thread enters a zone and allocates once a collection is pending, while
another keeps it pending by reaching no safe point for half a second.
Before this the allocation never returned and the child said so after
5 s; now the child prints the error and ends, and a debug build's own
message is accepted too.

HaxeFoundation/hxcpp#1468

Tests: GcFreeZoneAllocationReported

Say how many certificates did not parse instead of a wrong mbedTLS error

mbedtls_x509_crt_parse_file and mbedtls_x509_crt_parse_path return a
negative error code, or, when they parsed something, a positive count
of the certificates they could not parse. cert_load_file and
cert_load_path passed any non-zero result to ssl_error, and
mbedtls_strerror negates a positive value and looks it up: one bad
certificate threw "ERROR - Generic error", two "BIGNUM - An error
occurred while reading from or writing to a file", and so on.

A negative result still goes to ssl_error. A positive one throws "Could
not parse 1 certificate in <file>", or "certificates" for more. For a
directory the message says "certificates or files", because
parse_path also counts each file it could not read a certificate from.
Both still throw, as before; whether a directory or bundle that partly
parsed should be kept instead is left for its own change.

SslCertificateParseCount writes a good certificate, the same with one
corrupt certificate after it, and one between two corrupt ones, loads
each, and loads a directory with a certificate and a text file. Before
this, the three messages were the mbedTLS ones.

HaxeFoundation/hxcpp@45adede6

Tests: SslCertificateParseCount

Link a cppia script's host static object fields directly below API 500

HaxeFoundation/hxcpp#1047, to keep typed callables working at API level
500, stopped cppia linking a host class's static object fields to a
direct reference: a script closure stored through an hx::Object pointer
into a typed function slot is not callable as one. The exclusion had no
API level guard, so in Haxe 4 builds, and Haxe 5.0.0-preview.1 ones,
which build against the 430 runtime, every script read or write of a
host static object, a singleton, a static Array or a static function,
was a __GetStatic or __SetStatic by name, interpreted and jitted.
c653b13 restored direct access for object members the same way and
left statics out.

The exclusion applies at API level 500 only now, as for members, and
below that an object static gets the same MemReference an Int or String
static already had. Statics are roots, marked at the start of every
collection, so the direct store needs no write barrier, as a compiled
store into a static has none.

A new host_statics workload in bench/cppia reads one host static Array
and stores another on each pass. Against f0622380, with --base:

  interpreter  13.2M -> 23.4M iterations/s (14.3M -> 25.8M rerun)
  JIT          31.5M -> 386M  iterations/s (35.6M -> 542M rerun)

native_call, which this cannot reach, read 8% slower under the JIT in
both runs (287M against 312M). Keeping only Script.main's store to
CppiaBridge.workload on the named path brought it to 296M against 301M,
within the spread: the JIT compiles lazily, so main's smaller code moved
every function compiled after it.

CppiaHostStaticObjects has a script store young objects, an Array and
a closure into host statics that alone hold them, through minor and full
collections with HXCPP_GC_GENERATIONAL, then read them back in the
script and in the host, interpreted and under the JIT. It passed before
too, through the named path.

HaxeFoundation/hxcpp#1365

Tests: CppiaHostStaticObjects, CppiaObjectFields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants