From a0ac5ebe0fbc8ef604058b71dbbd6c06fb26cdb5 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 13:53:54 -0500 Subject: [PATCH 1/8] 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 --- Changes.md | 2 ++ src/hx/gc/Immix.cpp | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Changes.md b/Changes.md index e52f55d4..0cfda5e6 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,8 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ +* Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) + libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index e5d78b33..f5be9bf1 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -4998,12 +4998,15 @@ class GlobalAllocator hx::sMakeZombieSet.insert(inTo); } + // Erased before the insert, as above: the insert can rehash the map, + // which leaves id no iterator to erase through hx::ObjectIdMap::iterator id = hx::sObjectIdMap.find(inFrom); if (id!=hx::sObjectIdMap.end()) { - hx::sIdObjectMap[id->second] = inTo; - hx::sObjectIdMap[inTo] = id->second; + int objectId = id->second; hx::sObjectIdMap.erase(id); + hx::sObjectIdMap[inTo] = objectId; + hx::sIdObjectMap[objectId] = inTo; } // Maybe do something faster with weakmaps From fe159d612bc3c84df5f3f21f284ca05bcf6b8265 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 13:57:05 -0500 Subject: [PATCH 2/8] 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 --- Changes.md | 1 + src/hx/libs/std/Socket.cpp | 30 ++++++++---- .../SocketIpv6AddressLength/Main.hx | 46 +++++++++++++++++++ .../SocketIpv6AddressLength/build.hxml | 2 + .../SocketIpv6AddressLength/stdout.txt | 11 +++++ test/regression/emscripten-skip.txt | 1 + 6 files changed, 83 insertions(+), 8 deletions(-) create mode 100644 test/regression/SocketIpv6AddressLength/Main.hx create mode 100644 test/regression/SocketIpv6AddressLength/build.hxml create mode 100644 test/regression/SocketIpv6AddressLength/stdout.txt diff --git a/Changes.md b/Changes.md index 0cfda5e6..29ed87cc 100644 --- a/Changes.md +++ b/Changes.md @@ -3,6 +3,7 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ * Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) +* Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/libs/std/Socket.cpp b/src/hx/libs/std/Socket.cpp index 11b89ae3..4bbb2106 100644 --- a/src/hx/libs/std/Socket.cpp +++ b/src/hx/libs/std/Socket.cpp @@ -1038,16 +1038,30 @@ static DynamicInetFunc dynamic_inet_ntop = { "inet_ntop" }; #endif +// The 16 bytes of an IPv6 address, copied out of its array, which may move +// once a GC-free zone is entered. False for a null array or one of another +// length, which reading 16 bytes from would run past +static bool ipv6_address( Array inHost, void *outAddr ) +{ + if (!inHost.mPtr || inHost->length!=16) + return false; + memcpy(outAddr, inHost->GetBase(), 16); + return true; +} + String _hx_std_host_to_string_ipv6( Array ip ) { + unsigned char addr[16]; + if (!ipv6_address(ip, addr)) + return String(); char buf[100]; #ifdef DYNAMIC_INET_FUNCS inet_ntop_func ntop = (inet_ntop_func)dynamic_inet_ntop.get(); if (!ntop) return String(); - return String( ntop(AF_INET6, &ip[0], buf, 100) ); + return String( ntop(AF_INET6, addr, buf, 100) ); #else - return String( inet_ntop(AF_INET6, &ip[0], buf, 100) ); + return String( inet_ntop(AF_INET6, addr, buf, 100) ); #endif } @@ -1077,12 +1091,10 @@ String _hx_std_host_reverse( int host ) String _hx_std_host_reverse_ipv6( Array host ) { - if (!host.mPtr || host->length!=16) + unsigned char addr[16]; + if (!ipv6_address(host, addr)) return String(); - // Out of the array first: it may move once the zone is entered - unsigned char addr[16]; - memcpy(addr, host->GetBase(), 16); struct hostent *h = 0; hx::EnterGCFreeZone(); #if defined(NEKO_WINDOWS) || defined(NEKO_MAC) || defined(ANDROID) || defined(BLACKBERRY) || defined(__EMSCRIPTEN__) || defined(NEKO_BSD) @@ -1163,9 +1175,10 @@ void _hx_std_socket_connect_ipv6( Dynamic o, Array host, int port { struct sockaddr_in6 addr; memset(&addr,0,sizeof(addr)); + if (!ipv6_address(host, &addr.sin6_addr)) + hx::Throw(HX_CSTRING("Invalid IPv6 address")); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); - memcpy(&addr.sin6_addr,&host[0],16); SOCKET sock = val_sock(o); hx::EnterGCFreeZone(); @@ -1601,9 +1614,10 @@ void _hx_std_socket_bind_ipv6( Dynamic o, Array host, int port ) struct sockaddr_in6 addr; memset(&addr,0,sizeof(addr)); + if (!ipv6_address(host, &addr.sin6_addr)) + hx::Throw(HX_CSTRING("Invalid IPv6 address")); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); - memcpy(&addr.sin6_addr,&host[0], 16); #ifndef NEKO_WINDOWS if (isStreamSocket(sock)) setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&opt,sizeof(opt)); diff --git a/test/regression/SocketIpv6AddressLength/Main.hx b/test/regression/SocketIpv6AddressLength/Main.hx new file mode 100644 index 00000000..bffeb8a5 --- /dev/null +++ b/test/regression/SocketIpv6AddressLength/Main.hx @@ -0,0 +1,46 @@ +import cpp.NativeSocket; +import haxe.io.Bytes; +import haxe.io.BytesData; + +// cpp.NativeSocket's IPv6 functions take the address as a byte array. Three +// of them read 16 bytes from its start without looking at its length, so a +// shorter array was read past its end: formatted, connected to or bound to as +// whatever followed it in memory, and a null array crashed. Only +// host_reverse_ipv6 checked. The bytes are 0xff, so an over-read shows. +function address(length:Int):BytesData { + final bytes = Bytes.alloc(length); + bytes.fill(0, length, 0xff); + return bytes.getData(); +} + +function show(s:String):String { + return s == null ? "null" : s; +} + +function threw(f:() -> Void):String { + try { + f(); + return "nothing"; + } catch (e:Dynamic) { + return Std.string(e); + } +} + +function main() { + for (length in [0, 4, 15, 17]) + Sys.println('to_string of $length bytes: ${show(NativeSocket.host_to_string_ipv6(address(length)))}'); + Sys.println('to_string of 16 bytes: ${show(NativeSocket.host_to_string_ipv6(address(16)))}'); + Sys.println('reverse of 4 bytes: ${show(NativeSocket.host_reverse_ipv6(address(4)))}'); + + NativeSocket.socket_init(); + final socket = NativeSocket.socket_new_ip(false, true); + // Not blocking, so a connect to an over-read address does not wait + NativeSocket.socket_set_blocking(socket, false); + Sys.println('connect to 4 bytes threw: ${threw(() -> NativeSocket.socket_connect_ipv6(socket, address(4), 80))}'); + Sys.println('bind to 4 bytes threw: ${threw(() -> NativeSocket.socket_bind_ipv6(socket, address(4), 0))}'); + Sys.println('connect to null threw: ${threw(() -> NativeSocket.socket_connect_ipv6(socket, null, 80))}'); + Sys.println('bind to null threw: ${threw(() -> NativeSocket.socket_bind_ipv6(socket, null, 0))}'); + NativeSocket.socket_close(socket); + + Sys.println('to_string of null: ${show(NativeSocket.host_to_string_ipv6(null))}'); +} diff --git a/test/regression/SocketIpv6AddressLength/build.hxml b/test/regression/SocketIpv6AddressLength/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/SocketIpv6AddressLength/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/SocketIpv6AddressLength/stdout.txt b/test/regression/SocketIpv6AddressLength/stdout.txt new file mode 100644 index 00000000..3ce6f946 --- /dev/null +++ b/test/regression/SocketIpv6AddressLength/stdout.txt @@ -0,0 +1,11 @@ +to_string of 0 bytes: null +to_string of 4 bytes: null +to_string of 15 bytes: null +to_string of 17 bytes: null +to_string of 16 bytes: ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff +reverse of 4 bytes: null +connect to 4 bytes threw: Invalid IPv6 address +bind to 4 bytes threw: Invalid IPv6 address +connect to null threw: Invalid IPv6 address +bind to null threw: Invalid IPv6 address +to_string of null: null diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index e2c2c75d..5d58de82 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -105,6 +105,7 @@ SemaphoreLoopCollect: threads SleepLongDuration: threads SocketEmptyBytes: sockets SocketIpv6Accept: sockets +SocketIpv6AddressLength: sockets SocketIpv6ConcurrentFormat: threads (std::thread, which needs a pthreads build) SocketLibraryHandle: sockets SocketReadAhead: sockets From 596a7820def9b9a814e92bb6c30fffcc84fa2b70 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:03:36 -0500 Subject: [PATCH 3/8] 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 8 ++++---- test/regression/CppiaEmptyVars/Main.hx | 25 +++++++++++++++++++++++ test/regression/CppiaEmptyVars/build.hxml | 4 ++++ test/regression/CppiaEmptyVars/stdout.txt | 4 ++++ 5 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 test/regression/CppiaEmptyVars/Main.hx create mode 100644 test/regression/CppiaEmptyVars/build.hxml create mode 100644 test/regression/CppiaEmptyVars/stdout.txt diff --git a/Changes.md b/Changes.md index 29ed87cc..447b4ea6 100644 --- a/Changes.md +++ b/Changes.md @@ -4,6 +4,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) * Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) +* Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index c9f3b101..c1ae20c5 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -6632,12 +6632,12 @@ struct TVars : public CppiaVoidExpr return this; } + // By index: a file can declare no vars, and vars[0] of an empty vector is + // undefined behaviour, which checked library builds trap void runVoid(CppiaCtx *ctx) HXCPP_OVERRIDE { - CppiaExpr **v = &vars[0]; - CppiaExpr **end = v + vars.size(); - for(;vbreakContReturn && !ctx->exception;v++) - (*v)->runVoid(ctx); + for(size_t v=0; vbreakContReturn && !ctx->exception; v++) + vars[v]->runVoid(ctx); } #ifdef CPPIA_JIT diff --git a/test/regression/CppiaEmptyVars/Main.hx b/test/regression/CppiaEmptyVars/Main.hx new file mode 100644 index 00000000..933d0ca4 --- /dev/null +++ b/test/regression/CppiaEmptyVars/Main.hx @@ -0,0 +1,25 @@ +// A var statement in a cppia file lists its declarations with a count, and +// the loader accepts a count of 0. The interpreter then ran the statement +// from &vars[0] of the empty list, which is undefined behaviour, and a +// standard library with checked indexing stops there. Nothing here checks +// indexing, so this passed before too; it keeps both engines running the +// empty statement. +function run(name:String, code:String) { + try { + final module = cpp.cppia.Module.fromString(code); + module.boot(); + module.run(); + Sys.println('$name ran'); + } catch (e:Dynamic) { + Sys.println('$name threw $e'); + } +} + +function main() { + for (jit in [false, true]) { + cpp.cppia.Host.enableJit(jit); + final engine = jit ? "jit" : "interpreter"; + run('$engine: an empty var statement', "CPPIA 0 1 4 void 0 MAIN 0 0 TVARS 0 RESOURCES 0 "); + run('$engine: two in a block', "CPPIA 0 1 4 void 0 MAIN 0 0 BLOCK 2 0 0 TVARS 0 0 0 TVARS 0 RESOURCES 0 "); + } +} diff --git a/test/regression/CppiaEmptyVars/build.hxml b/test/regression/CppiaEmptyVars/build.hxml new file mode 100644 index 00000000..5bfa2fac --- /dev/null +++ b/test/regression/CppiaEmptyVars/build.hxml @@ -0,0 +1,4 @@ +-m Main +--cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaEmptyVars/stdout.txt b/test/regression/CppiaEmptyVars/stdout.txt new file mode 100644 index 00000000..ea73d234 --- /dev/null +++ b/test/regression/CppiaEmptyVars/stdout.txt @@ -0,0 +1,4 @@ +interpreter: an empty var statement ran +interpreter: two in a block ran +jit: an empty var statement ran +jit: two in a block ran From d237cb1f56b3f19f07fa9fa7ed4a184f20f47382 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:09:45 -0500 Subject: [PATCH 4/8] 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 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 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 --- Changes.md | 1 + include/cpp/Pointer.h | 40 ++++++--- include/hx/StdLibs.h | 2 +- .../AtomicFieldSpinSafePoint/Main.hx | 87 +++++++++++++++++++ .../AtomicFieldSpinSafePoint/build.hxml | 2 + .../AtomicFieldSpinSafePoint/stdout.txt | 9 ++ test/regression/emscripten-skip.txt | 1 + 7 files changed, 127 insertions(+), 15 deletions(-) create mode 100644 test/regression/AtomicFieldSpinSafePoint/Main.hx create mode 100644 test/regression/AtomicFieldSpinSafePoint/build.hxml create mode 100644 test/regression/AtomicFieldSpinSafePoint/stdout.txt diff --git a/Changes.md b/Changes.md index 447b4ea6..21403496 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ +* Fixed a thread spinning on Haxe 5.0.0-preview.1's haxe.atomic.AtomicInt or AtomicBool, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: preview.1 passes the address of an Int field to the _hx_atomic_* functions, which took it as a volatile int *, the runtime's form that never stops. An int * stops for a pending collection now, as Haxe 4's cpp.Pointer has since libhxcpp #455, and the runtime's own spinlocks keep the volatile form (HaxeFoundation/hxcpp#1443) * Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) * Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) diff --git a/include/cpp/Pointer.h b/include/cpp/Pointer.h index 05466258..0977c906 100644 --- a/include/cpp/Pointer.h +++ b/include/cpp/Pointer.h @@ -574,21 +574,33 @@ T *StarOf(T &x) { return &x; } } -// Haxe 4's haxe.atomic.AtomicInt is a cpp.Pointer, and its methods call -// these. A thread spinning on one never otherwise reached a safe point, so a -// collection on another thread waited for it for ever, as Haxe 5's -// hx::atomic::AtomicInt does not (libhxcpp #455). The runtime's own spinlocks -// call the volatile int * forms, which do not stop. +// The forms of these that stop for a pending collection, for an int * and a +// cpp::Pointer. Haxe 4's haxe.atomic.AtomicInt is a cpp.Pointer, and +// Haxe 5.0.0-preview.1's keeps an Int field and passes its address, a plain +// int *. A thread spinning on either never otherwise reached a safe point, so +// a collection on another thread waited for it for ever (libhxcpp #455). +// Later Haxe 5's hx::atomic::AtomicInt stops by itself. The runtime's own +// spinlocks call the volatile int * forms in hx/StdLibs.h, which do not stop. #define HX_ATOMIC_SAFE_POINT if (::hx::gPauseForCollect) __hxcpp_gc_safe_point(); -inline int _hx_atomic_add(::cpp::Pointer a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_add((volatile int *)a.ptr, b); } -inline int _hx_atomic_sub(::cpp::Pointer a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_sub((volatile int *)a.ptr, b); } -inline int _hx_atomic_and(::cpp::Pointer a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_and((volatile int *)a.ptr, b); } -inline int _hx_atomic_or(::cpp::Pointer a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_or((volatile int *)a.ptr, b); } -inline int _hx_atomic_xor(::cpp::Pointer a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_xor((int *)a.ptr, b); } -inline int _hx_atomic_compare_exchange(::cpp::Pointer a, int expected, int replacement) { HX_ATOMIC_SAFE_POINT return _hx_atomic_compare_exchange((volatile int *)a.ptr, expected, replacement); } -inline int _hx_atomic_exchange(::cpp::Pointer a, int replacement) { HX_ATOMIC_SAFE_POINT return _hx_atomic_exchange((volatile int *)a.ptr, replacement); } -inline int _hx_atomic_load(::cpp::Pointer a) { HX_ATOMIC_SAFE_POINT return _hx_atomic_load((volatile int *)a.ptr); } -inline int _hx_atomic_store(::cpp::Pointer a, int value) { HX_ATOMIC_SAFE_POINT return _hx_atomic_store((volatile int *)a.ptr, value); } +inline int _hx_atomic_add(int *a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_add((volatile int *)a, b); } +inline int _hx_atomic_sub(int *a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_sub((volatile int *)a, b); } +inline int _hx_atomic_and(int *a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_and((volatile int *)a, b); } +inline int _hx_atomic_or(int *a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_or((volatile int *)a, b); } +inline int _hx_atomic_xor(int *a, int b) { HX_ATOMIC_SAFE_POINT return _hx_atomic_xor((volatile int *)a, b); } +inline int _hx_atomic_compare_exchange(int *a, int expected, int replacement) { HX_ATOMIC_SAFE_POINT return _hx_atomic_compare_exchange((volatile int *)a, expected, replacement); } +inline int _hx_atomic_exchange(int *a, int replacement) { HX_ATOMIC_SAFE_POINT return _hx_atomic_exchange((volatile int *)a, replacement); } +inline int _hx_atomic_load(int *a) { HX_ATOMIC_SAFE_POINT return _hx_atomic_load((volatile int *)a); } +inline int _hx_atomic_store(int *a, int value) { HX_ATOMIC_SAFE_POINT return _hx_atomic_store((volatile int *)a, value); } #undef HX_ATOMIC_SAFE_POINT +inline int _hx_atomic_add(::cpp::Pointer a, int b) { return _hx_atomic_add(a.ptr, b); } +inline int _hx_atomic_sub(::cpp::Pointer a, int b) { return _hx_atomic_sub(a.ptr, b); } +inline int _hx_atomic_and(::cpp::Pointer a, int b) { return _hx_atomic_and(a.ptr, b); } +inline int _hx_atomic_or(::cpp::Pointer a, int b) { return _hx_atomic_or(a.ptr, b); } +inline int _hx_atomic_xor(::cpp::Pointer a, int b) { return _hx_atomic_xor(a.ptr, b); } +inline int _hx_atomic_compare_exchange(::cpp::Pointer a, int expected, int replacement) { return _hx_atomic_compare_exchange(a.ptr, expected, replacement); } +inline int _hx_atomic_exchange(::cpp::Pointer a, int replacement) { return _hx_atomic_exchange(a.ptr, replacement); } +inline int _hx_atomic_load(::cpp::Pointer a) { return _hx_atomic_load(a.ptr); } +inline int _hx_atomic_store(::cpp::Pointer a, int value) { return _hx_atomic_store(a.ptr, value); } + #endif diff --git a/include/hx/StdLibs.h b/include/hx/StdLibs.h index 126a8858..1b4a3c0c 100644 --- a/include/hx/StdLibs.h +++ b/include/hx/StdLibs.h @@ -427,7 +427,7 @@ inline int _hx_atomic_or(volatile int *a, int b) { #endif } -inline int _hx_atomic_xor(int *a, int b) { +inline int _hx_atomic_xor(volatile int *a, int b) { #if defined(HX_GCC_ATOMICS) return __atomic_fetch_xor(a, b, __ATOMIC_SEQ_CST); #elif defined(HX_MSVC_ATOMICS) diff --git a/test/regression/AtomicFieldSpinSafePoint/Main.hx b/test/regression/AtomicFieldSpinSafePoint/Main.hx new file mode 100644 index 00000000..0a97eac6 --- /dev/null +++ b/test/regression/AtomicFieldSpinSafePoint/Main.hx @@ -0,0 +1,87 @@ +import cpp.vm.Gc; +import sys.thread.Lock; +import sys.thread.Thread; + +// Haxe 5.0.0-preview.1's haxe.atomic.AtomicInt keeps its value in an Int field +// and passes the field's address, a plain int *, to the _hx_atomic_* +// functions. That chose the runtime's volatile int * forms, which never stop +// for a collection, so a thread spinning on one held up every collection, as +// Haxe 4's AtomicInt did before libhxcpp #455. This spins on each operation in +// turn, called as preview.1 calls them, while the main thread collects. Only +// the operation under test can stop the thread: it watches a native flag. A +// native watchdog, which the collector does not know, ends the test if a +// collection never finishes. +class Data { + public var value:Int; + + public function new(value:Int) + this.value = value; +} + +@:cppFileCode(' +#include +#include +#include +#include +#include +static std::atomic gStop(false); +static std::atomic gSpinning(false); +static std::atomic gOperation(-1); +static std::atomic gFinished(false); +static const char *gNames[] = { "add", "sub", "and", "or", "xor", "compare_exchange", "exchange", "load", "store" }; +static void startWatchdog() +{ + std::thread([]{ + std::this_thread::sleep_for(std::chrono::seconds(60)); + if (!gFinished) + { + int op = gOperation; + printf("no collection after 60 s while a thread spun on _hx_atomic_%s\\n", op>=0 ? gNames[op] : "?"); + fflush(stdout); + std::_Exit(1); + } + }).detach(); +} +') +class Main { + static final names = ["add", "sub", "and", "or", "xor", "compare_exchange", "exchange", "load", "store"]; + + static function apply(op:Int, data:Data):Int { + return switch op { + case 0: untyped __cpp__("_hx_atomic_add(&{0}, 1)", data.value); + case 1: untyped __cpp__("_hx_atomic_sub(&{0}, 1)", data.value); + case 2: untyped __cpp__("_hx_atomic_and(&{0}, 0xff)", data.value); + case 3: untyped __cpp__("_hx_atomic_or(&{0}, 0x100)", data.value); + case 4: untyped __cpp__("_hx_atomic_xor(&{0}, 1)", data.value); + case 5: untyped __cpp__("_hx_atomic_compare_exchange(&{0}, 0, 1)", data.value); + case 6: untyped __cpp__("_hx_atomic_exchange(&{0}, 2)", data.value); + case 7: untyped __cpp__("_hx_atomic_load(&{0})", data.value); + case _: untyped __cpp__("_hx_atomic_store(&{0}, 3)", data.value); + } + } + + static function main() { + untyped __cpp__("startWatchdog()"); + final data = new Data(0); + for (op in 0...names.length) { + untyped __cpp__("gOperation = {0}", op); + untyped __cpp__("gStop = false"); + untyped __cpp__("gSpinning = false"); + final done = new Lock(); + Thread.create(() -> { + untyped __cpp__("gSpinning = true"); + while (untyped __cpp__("!gStop")) + apply(op, data); + done.release(); + }); + while (untyped __cpp__("!gSpinning")) + Sys.sleep(0.001); + Sys.sleep(0.02); + Gc.run(true); + untyped __cpp__("gStop = true"); + done.wait(); + Sys.println('collected while a thread spun on _hx_atomic_${names[op]}(&field)'); + } + untyped __cpp__("gFinished = true"); + } +} diff --git a/test/regression/AtomicFieldSpinSafePoint/build.hxml b/test/regression/AtomicFieldSpinSafePoint/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/AtomicFieldSpinSafePoint/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/AtomicFieldSpinSafePoint/stdout.txt b/test/regression/AtomicFieldSpinSafePoint/stdout.txt new file mode 100644 index 00000000..857ccf5e --- /dev/null +++ b/test/regression/AtomicFieldSpinSafePoint/stdout.txt @@ -0,0 +1,9 @@ +collected while a thread spun on _hx_atomic_add(&field) +collected while a thread spun on _hx_atomic_sub(&field) +collected while a thread spun on _hx_atomic_and(&field) +collected while a thread spun on _hx_atomic_or(&field) +collected while a thread spun on _hx_atomic_xor(&field) +collected while a thread spun on _hx_atomic_compare_exchange(&field) +collected while a thread spun on _hx_atomic_exchange(&field) +collected while a thread spun on _hx_atomic_load(&field) +collected while a thread spun on _hx_atomic_store(&field) diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 5d58de82..7f38d103 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -6,6 +6,7 @@ AnonConcurrentString: threads ArrayConcurrentString: threads +AtomicFieldSpinSafePoint: threads (std::thread, which needs a pthreads build) AtomicSafePointUnregisteredThread: threads (std::thread, which needs a pthreads build) AtomicSpinSafePoint: threads (std::thread, which needs a pthreads build) AttachedThreadId: threads (std::thread, which needs a pthreads build) From acee25a75477afae7de30fd9e4e1d0c9fe372ac7 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:17:11 -0500 Subject: [PATCH 5/8] 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 --- Changes.md | 1 + include/cpp/Int64.h | 6 ++--- src/Dynamic.cpp | 4 ++- test/regression/Int64IsInt64/Main.hx | 36 +++++++++++++++++++++++++ test/regression/Int64IsInt64/Script.hx | 10 +++++++ test/regression/Int64IsInt64/build.hxml | 7 +++++ test/regression/Int64IsInt64/stdout.txt | 22 +++++++++++++++ 7 files changed, 82 insertions(+), 4 deletions(-) create mode 100644 test/regression/Int64IsInt64/Main.hx create mode 100644 test/regression/Int64IsInt64/Script.hx create mode 100644 test/regression/Int64IsInt64/build.hxml create mode 100644 test/regression/Int64IsInt64/stdout.txt diff --git a/Changes.md b/Changes.md index 21403496..ff5d9218 100644 --- a/Changes.md +++ b/Changes.md @@ -5,6 +5,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed a thread spinning on Haxe 5.0.0-preview.1's haxe.atomic.AtomicInt or AtomicBool, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: preview.1 passes the address of an Int field to the _hx_atomic_* functions, which took it as a volatile int *, the runtime's form that never stops. An int * stops for a pending collection now, as Haxe 4's cpp.Pointer has since libhxcpp #455, and the runtime's own spinlocks keep the volatile form (HaxeFoundation/hxcpp#1443) * Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) * Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) +* haxe.Int64.isInt64 is false for an Int now, as on the other targets, in compiled code and in cppia: isInt64(100) was true, and so was isInt64(1.0), since a whole Float boxes as an Int. This changes what code that used isInt64 to accept any integer sees, and it should test Std.isOfType(value, Int) as well. Std.isOfType(value, cpp.Int64) changed with it, as Haxe 4.3 and later implement isInt64 with it, and cpp.Int64Struct.is, which Haxe 4.2 uses. Std.isOfType(value, Int) is still true for an Int64 that fits (HaxeFoundation/hxcpp#1461) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) libhxcpp 6.0.2 diff --git a/include/cpp/Int64.h b/include/cpp/Int64.h index 2aab289d..a9d39701 100644 --- a/include/cpp/Int64.h +++ b/include/cpp/Int64.h @@ -32,10 +32,10 @@ class Int64Handler } else if (op==dhoIs) { + // Every Int64 boxes as one, small values included, so a boxed Int + // is not one, as on the other targets StructHandlerDynamicParams *params = (StructHandlerDynamicParams *)outResult; - hx::Object *obj = params->inData; - int type = obj->__GetType(); - params->outProcessed = type==vtInt || type==vtInt64; + params->outProcessed = params->inData->__GetType()==vtInt64; } else return DefaultStructHandler::handler(op,ioValue,inSize, outResult); diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index 137c882b..8f01799e 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -636,9 +636,11 @@ static bool IsFloat(hx::Object *inPtr) { return inPtr && (TCanCast(inPtr) || TCanCast(inPtr) || TCanCast(inPtr) ); } +// haxe.Int64.isInt64 asks this from Haxe 4.3 (Int64Handler's dhoIs before). +// Every Int64 boxes as one, small values included, so a boxed Int is not one static bool IsInt64(hx::Object *inPtr) { - return inPtr && (TCanCast(inPtr) || TCanCast(inPtr)); + return TCanCast(inPtr); } static bool IsPointer(hx::Object *inPtr) diff --git a/test/regression/Int64IsInt64/Main.hx b/test/regression/Int64IsInt64/Main.hx new file mode 100644 index 00000000..2258d323 --- /dev/null +++ b/test/regression/Int64IsInt64/Main.hx @@ -0,0 +1,36 @@ +import haxe.Int64; + +// haxe.Int64.isInt64 asks cpp.Int64's handler whether a value is one, and the +// handler said yes to a boxed Int as well, so isInt64(100) was true here and +// false on the other targets. It took Ints because small Int64 values used to +// box as Ints; they have had boxes of their own since 6.0.0, so every Int64 +// boxes as an Int64, and an Int is not one. A cppia script asks the same. +function claim(text:String, value:Bool) + Sys.println('$text: $value'); + +function main() { + final int:Dynamic = 100; + final zero:Dynamic = 0; + final float:Dynamic = 1.0; + claim("isInt64 of the Int 100 is false", !Int64.isInt64(int)); + claim("isInt64 of the Int 0 is false", !Int64.isInt64(zero)); + claim("isInt64 of 1.0 is false", !Int64.isInt64(float)); + claim("isInt64 of null is false", !Int64.isInt64(null)); + claim("isInt64 of a String is false", !Int64.isInt64("1")); + for (value in [Int64.ofInt(100), Int64.ofInt(-1), Int64.ofInt(255), Int64.ofInt(-2), Int64.ofInt(256), Int64.make(1, 0)]) + claim('isInt64 of the Int64 $value is true', Int64.isInt64(value)); + + // isInt64 asks the handler with Haxe 4.2 and cpp.Int64's class from 4.3 + final int64:Dynamic = Int64.ofInt(100); + claim("the handler says the Int 100 is not an Int64", !untyped __cpp__("::cpp::Int64Struct::is({0})", int)); + claim("the handler says the Int64 100 is one", untyped __cpp__("::cpp::Int64Struct::is({0})", int64)); + claim("the class says the Int 100 is not an Int64", !Std.isOfType(int, untyped __cpp__("::hx::ClassOf< ::cpp::Int64 >()"))); + claim("the class says the Int64 100 is one", Std.isOfType(int64, untyped __cpp__("::hx::ClassOf< ::cpp::Int64 >()"))); + claim("the Int64 100 is still an Int", Std.isOfType(int64, Int)); + + final script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + cpp.cppia.Host.enableJit(jit); + cpp.cppia.Host.runFile(script); + } +} diff --git a/test/regression/Int64IsInt64/Script.hx b/test/regression/Int64IsInt64/Script.hx new file mode 100644 index 00000000..9ddc3c2b --- /dev/null +++ b/test/regression/Int64IsInt64/Script.hx @@ -0,0 +1,10 @@ +import haxe.Int64; + +class Script { + static function main() { + final int:Dynamic = 100; + Sys.println('script: isInt64 of the Int 100 is false: ${!Int64.isInt64(int)}'); + Sys.println('script: isInt64 of the Int64 100 is true: ${Int64.isInt64(Int64.ofInt(100))}'); + Sys.println('script: isInt64 of the Int64 2^32 is true: ${Int64.isInt64(Int64.make(1, 0))}'); + } +} diff --git a/test/regression/Int64IsInt64/build.hxml b/test/regression/Int64IsInt64/build.hxml new file mode 100644 index 00000000..d20d36bd --- /dev/null +++ b/test/regression/Int64IsInt64/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/Int64IsInt64/stdout.txt b/test/regression/Int64IsInt64/stdout.txt new file mode 100644 index 00000000..0a6ec8e6 --- /dev/null +++ b/test/regression/Int64IsInt64/stdout.txt @@ -0,0 +1,22 @@ +isInt64 of the Int 100 is false: true +isInt64 of the Int 0 is false: true +isInt64 of 1.0 is false: true +isInt64 of null is false: true +isInt64 of a String is false: true +isInt64 of the Int64 100 is true: true +isInt64 of the Int64 -1 is true: true +isInt64 of the Int64 255 is true: true +isInt64 of the Int64 -2 is true: true +isInt64 of the Int64 256 is true: true +isInt64 of the Int64 4294967296 is true: true +the handler says the Int 100 is not an Int64: true +the handler says the Int64 100 is one: true +the class says the Int 100 is not an Int64: true +the class says the Int64 100 is one: true +the Int64 100 is still an Int: true +script: isInt64 of the Int 100 is false: true +script: isInt64 of the Int64 100 is true: true +script: isInt64 of the Int64 2^32 is true: true +script: isInt64 of the Int 100 is false: true +script: isInt64 of the Int64 100 is true: true +script: isInt64 of the Int64 2^32 is true: true From b3f34d4eebe795f419db0b9220bb66b91a10c3f0 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:24:19 -0500 Subject: [PATCH 6/8] 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 --- Changes.md | 1 + src/hx/gc/Immix.cpp | 7 ++ .../GcFreeZoneAllocationReported/Main.hx | 75 +++++++++++++++++++ .../GcFreeZoneAllocationReported/build.hxml | 2 + .../GcFreeZoneAllocationReported/stdout.txt | 2 + test/regression/emscripten-skip.txt | 1 + 6 files changed, 88 insertions(+) create mode 100644 test/regression/GcFreeZoneAllocationReported/Main.hx create mode 100644 test/regression/GcFreeZoneAllocationReported/build.hxml create mode 100644 test/regression/GcFreeZoneAllocationReported/stdout.txt diff --git a/Changes.md b/Changes.md index ff5d9218..292166ec 100644 --- a/Changes.md +++ b/Changes.md @@ -6,6 +6,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed undefined behaviour in HXCPP_GC_MOVING when a compaction moved an object that has an id, as an ObjectMap key does: the move inserted the new address into the id table, then erased the old entry through an iterator found before the insert, which a rehash during the insert leaves invalid. The old entry is erased first now (HaxeFoundation/hxcpp#1468) * Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) * haxe.Int64.isInt64 is false for an Int now, as on the other targets, in compiled code and in cppia: isInt64(100) was true, and so was isInt64(1.0), since a whole Float boxes as an Int. This changes what code that used isInt64 to accept any integer sees, and it should test Std.isOfType(value, Int) as well. Std.isOfType(value, cpp.Int64) changed with it, as Haxe 4.3 and later implement isInt64 with it, and cpp.Int64Struct.is, which Haxe 4.2 uses. Std.isOfType(value, Int) is still true for an Int64 that fits (HaxeFoundation/hxcpp#1461) +* A thread that allocates or collects inside a GC-free zone while another thread collects, as native code that misses an exit from one can, now ends the program with "Critical Error: Allocating or collecting from a GC-free thread while another thread collects - was ExitGCFreeZone missed?". In a release build it waited for ever, with no message: the collector neither waits for a thread in a zone nor releases it. Debug builds already reported any allocation in a zone (HaxeFoundation/hxcpp#1468) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) libhxcpp 6.0.2 diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index f5be9bf1..8e0286bd 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -8361,6 +8361,13 @@ class LocalAllocator : public hx::StackContext if (sgIsCollecting) CriticalGCError("Bad Allocation while collecting - from finalizer?"); + // The collector neither waits for a thread in a GC-free zone nor + // releases it, so this would wait for ever. Safe points return before + // this in a zone, so only allocating or collecting in one gets here, + // which debug builds report whether a collection is pending or not + if (mGCFreeZone) + CriticalGCError("Allocating or collecting from a GC-free thread while another thread collects - was ExitGCFreeZone missed?"); + mPausedForCollect = true; mReadyForCollect.Set(); mCollectDone.Wait(); diff --git a/test/regression/GcFreeZoneAllocationReported/Main.hx b/test/regression/GcFreeZoneAllocationReported/Main.hx new file mode 100644 index 00000000..463d05e6 --- /dev/null +++ b/test/regression/GcFreeZoneAllocationReported/Main.hx @@ -0,0 +1,75 @@ +import cpp.vm.Gc; +import sys.thread.Lock; +import sys.thread.Thread; + +// A thread that allocates inside a GC-free zone while another thread collects +// stops in PauseForCollect to wait for the collection. The collector neither +// waits for a thread in a zone nor releases it, so in a release build that +// thread waited for ever, silently; only debug builds said why. It is +// reported as a critical error now, which ends the program, so the misuse +// runs in a child process. A third thread that reaches no safe point for half +// a second keeps the collection pending while the zone thread allocates. +@:cppFileCode(' +#include +#include +#ifdef HX_WINDOWS +#include +#endif +static std::atomic gInZone(false); +static bool collectionPending() { return ::hx::gPauseForCollect.load() != 0; } +static void spinFor(int inMilliseconds) +{ + auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(inMilliseconds); + while (std::chrono::steady_clock::now() < end) {} +} +// The report ends the program with a fault, which must not open a dialog +static void quietFaults() +{ + #ifdef HX_WINDOWS + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + #endif +} +') +class Main { + static function child() { + untyped __cpp__("quietFaults()"); + final busyStarted = new Lock(); + Thread.create(() -> { + busyStarted.release(); + untyped __cpp__("spinFor(500)"); + }); + busyStarted.wait(); + + final allocated = new Lock(); + Thread.create(() -> { + Gc.enterGCFreeZone(); + untyped __cpp__("gInZone = true"); + while (!untyped __cpp__("collectionPending()")) {} + // The misuse: an allocation in the zone, with a collection pending + final strings = [for (i in 0...10) Std.string(i)]; + Gc.exitGCFreeZone(); + allocated.release(); + }); + while (!untyped __cpp__("gInZone")) + Sys.sleep(0.001); + Gc.run(true); + Sys.println(allocated.wait(5.0) ? "the allocation in the zone returned" : "the allocation in the zone never returned"); + } + + static function main() { + if (Sys.args().length > 0) { + child(); + return; + } + final process = new sys.io.Process(Sys.programPath(), ["child"]); + final out = process.stdout.readAll().toString(); + final code = process.exitCode(); + process.close(); + Sys.stderr().writeString('child: exit code $code\n$out'); + // A debug build reports any allocation in a zone, with its own message + Sys.println("allocating in a GC-free zone while another thread collects is reported: " + + (out.indexOf("Critical Error: Allocating or collecting from a GC-free thread while another thread collects") >= 0 + || out.indexOf("Critical Error: Allocating from a GC-free thread") >= 0)); + Sys.println("and ends the program: " + (code != 0)); + } +} diff --git a/test/regression/GcFreeZoneAllocationReported/build.hxml b/test/regression/GcFreeZoneAllocationReported/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcFreeZoneAllocationReported/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcFreeZoneAllocationReported/stdout.txt b/test/regression/GcFreeZoneAllocationReported/stdout.txt new file mode 100644 index 00000000..3df26ebe --- /dev/null +++ b/test/regression/GcFreeZoneAllocationReported/stdout.txt @@ -0,0 +1,2 @@ +allocating in a GC-free zone while another thread collects is reported: true +and ends the program: true diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 7f38d103..690431f2 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -39,6 +39,7 @@ FinalizerExceptionState: threads (std::thread, which needs a pthreads build) FinalizersAcrossFreeZones: threads GcConcurrentCensus: threads (std::thread, which needs a pthreads build) GcFinalizerPromotion: threads (std::thread, which needs a pthreads build) +GcFreeZoneAllocationReported: threads and processes GcFreeZoneLeafNatives: threads and processes GcFreeZoneNestedGuard: single-threaded Emscripten builds have no GC-free zones, so a guard enters none GcFreeZoneThreadWaits: threads From ab2309acfc13007c3f0a83cfb74ef1ca91fcee68 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:27:37 -0500 Subject: [PATCH 7/8] 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 ", 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 --- Changes.md | 1 + src/hx/libs/ssl/SSL.cpp | 16 +++++- .../SslCertificateParseCount/Main.hx | 53 +++++++++++++++++++ .../SslCertificateParseCount/build.hxml | 3 ++ .../SslCertificateParseCount/cert.pem | 19 +++++++ .../SslCertificateParseCount/stdout.txt | 5 ++ 6 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 test/regression/SslCertificateParseCount/Main.hx create mode 100644 test/regression/SslCertificateParseCount/build.hxml create mode 100644 test/regression/SslCertificateParseCount/cert.pem create mode 100644 test/regression/SslCertificateParseCount/stdout.txt diff --git a/Changes.md b/Changes.md index 292166ec..71caead5 100644 --- a/Changes.md +++ b/Changes.md @@ -7,6 +7,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed cpp.NativeSocket's host_to_string_ipv6, socket_connect_ipv6 and socket_bind_ipv6 reading 16 bytes from an address array of any length: a shorter one was read past its end, so it formatted, connected to or bound whatever followed it in memory, and a null one crashed. An array that is not 16 bytes long now gives null from host_to_string_ipv6, as it already did from host_reverse_ipv6, and connect and bind throw "Invalid IPv6 address". sys.net.Host always passes 16 bytes (HaxeFoundation/hxcpp@a8a5724f) * haxe.Int64.isInt64 is false for an Int now, as on the other targets, in compiled code and in cppia: isInt64(100) was true, and so was isInt64(1.0), since a whole Float boxes as an Int. This changes what code that used isInt64 to accept any integer sees, and it should test Std.isOfType(value, Int) as well. Std.isOfType(value, cpp.Int64) changed with it, as Haxe 4.3 and later implement isInt64 with it, and cpp.Int64Struct.is, which Haxe 4.2 uses. Std.isOfType(value, Int) is still true for an Int64 that fits (HaxeFoundation/hxcpp#1461) * A thread that allocates or collects inside a GC-free zone while another thread collects, as native code that misses an exit from one can, now ends the program with "Critical Error: Allocating or collecting from a GC-free thread while another thread collects - was ExitGCFreeZone missed?". In a release build it waited for ever, with no message: the collector neither waits for a thread in a zone nor releases it. Debug builds already reported any allocation in a zone (HaxeFoundation/hxcpp#1468) +* Fixed sys.ssl.Certificate.loadFile and loadPath reporting certificates that did not parse as an unrelated mbedTLS error: mbedTLS counts them, and the count was read as an error code, so one threw "ERROR - Generic error" and two a BIGNUM file error. They throw "Could not parse 2 certificates in " now, and for a directory "certificates or files", as mbedTLS also counts a file that holds none (HaxeFoundation/hxcpp@45adede6) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) libhxcpp 6.0.2 diff --git a/src/hx/libs/ssl/SSL.cpp b/src/hx/libs/ssl/SSL.cpp index 08ecaf56..c42dc0e2 100644 --- a/src/hx/libs/ssl/SSL.cpp +++ b/src/hx/libs/ssl/SSL.cpp @@ -1066,6 +1066,18 @@ Dynamic _hx_ssl_cert_load_defaults(){ return null(); } +// mbedtls_x509_crt_parse_file and _path give a negative error code, or a +// positive count of what they could not parse. ssl_error read that count as +// an error code: one certificate gave "ERROR - Generic error", two a BIGNUM +// file error. A directory's count is of certificates, and of files with none +static void cert_parse_error( int r, String inWhere, bool inDirectory ){ + if( r < 0 ) + ssl_error(r); + const char *what = inDirectory ? (r==1 ? " certificate or file in " : " certificates or files in ") + : (r==1 ? " certificate in " : " certificates in "); + hx::Throw( HX_CSTRING("Could not parse ") + String(r) + String(what) + inWhere ); +} + Dynamic _hx_ssl_cert_load_file( String file ){ int r; sslcert *cert = new sslcert(); @@ -1073,7 +1085,7 @@ Dynamic _hx_ssl_cert_load_file( String file ){ hx::strbuf buf; if( (r = mbedtls_x509_crt_parse_file(cert->c, file.utf8_str(&buf))) != 0 ){ cert->destroy(); - ssl_error(r); + cert_parse_error(r, file, false); } return cert; } @@ -1085,7 +1097,7 @@ Dynamic _hx_ssl_cert_load_path( String path ){ hx::strbuf buf; if( (r = mbedtls_x509_crt_parse_path(cert->c, path.utf8_str(&buf))) != 0 ){ cert->destroy(); - ssl_error(r); + cert_parse_error(r, path, true); } return cert; } diff --git a/test/regression/SslCertificateParseCount/Main.hx b/test/regression/SslCertificateParseCount/Main.hx new file mode 100644 index 00000000..3eb4124a --- /dev/null +++ b/test/regression/SslCertificateParseCount/Main.hx @@ -0,0 +1,53 @@ +import haxe.io.Path; +import sys.FileSystem; +import sys.io.File; +import sys.ssl.Certificate; + +// Certificate.loadFile and loadPath throw when a certificate does not parse, +// and mbedTLS reports how many did not as a positive count. That count was +// read as an mbedTLS error code, so one bad certificate threw +// "ERROR - Generic error" and two a BIGNUM file error. They say how many now. +final corrupt = "-----BEGIN CERTIFICATE-----\nMIIBAAAAAAAAAAAA\n-----END CERTIFICATE-----\n"; + +function message(load:() -> Certificate):String { + try { + load(); + return "loaded"; + } catch (e:Dynamic) { + return Std.string(e); + } +} + +function claim(text:String, value:Bool) + Sys.println('$text: $value'); + +function main() { + final good = haxe.Resource.getString("cert"); + final dir = Path.join([Path.directory(Sys.programPath()), "certs"]); + if (!FileSystem.exists(dir)) + FileSystem.createDirectory(dir); + final goodFile = Path.join([dir, "good.pem"]); + final oneBad = Path.join([dir, "one-bad.pem"]); + final twoBad = Path.join([dir, "two-bad.pem"]); + File.saveContent(goodFile, good); + File.saveContent(oneBad, good + corrupt); + File.saveContent(twoBad, corrupt + good + corrupt); + + claim("a file of good certificates loads", message(() -> Certificate.loadFile(goodFile)) == "loaded"); + claim("one bad certificate in a file is counted", + message(() -> Certificate.loadFile(oneBad)) == 'Could not parse 1 certificate in $oneBad'); + claim("two bad certificates in a file are counted", + message(() -> Certificate.loadFile(twoBad)) == 'Could not parse 2 certificates in $twoBad'); + + final mixed = Path.join([dir, "mixed"]); + if (!FileSystem.exists(mixed)) + FileSystem.createDirectory(mixed); + File.saveContent(Path.join([mixed, "good.pem"]), good); + File.saveContent(Path.join([mixed, "notes.txt"]), "not a certificate\n"); + claim("a file with no certificate in a directory is counted", + message(() -> Certificate.loadPath(mixed)) == 'Could not parse 1 certificate or file in $mixed'); + + final missing = Path.join([dir, "missing.pem"]); + final noFile = message(() -> Certificate.loadFile(missing)); + claim("a missing file still gives mbedTLS's error", noFile != "loaded" && noFile.indexOf("Could not parse") < 0); +} diff --git a/test/regression/SslCertificateParseCount/build.hxml b/test/regression/SslCertificateParseCount/build.hxml new file mode 100644 index 00000000..82b679ee --- /dev/null +++ b/test/regression/SslCertificateParseCount/build.hxml @@ -0,0 +1,3 @@ +-m Main +--cpp bin +--resource cert.pem@cert diff --git a/test/regression/SslCertificateParseCount/cert.pem b/test/regression/SslCertificateParseCount/cert.pem new file mode 100644 index 00000000..6014cfd4 --- /dev/null +++ b/test/regression/SslCertificateParseCount/cert.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDGDCCAgCgAwIBAgIUTYjw2op43D9f5sE4+TcYIeXj59cwDQYJKoZIhvcNAQEL +BQAwETEPMA0GA1UEAwwGYS50ZXN0MCAXDTI2MTAxNTA1MjIyN1oYDzIxMjYwOTIx +MDUyMjI3WjARMQ8wDQYDVQQDDAZhLnRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQCg7+y95lC/v3VZLkjnqdGYx8C+zMIHAzB7xatRMlB7W/y5riTH +RR9552p0PyU9+aROu097UD2oEsnSV1H3dVj6Nl4z8NlOXYTNV2p8cnRm5ECFs4MF +sczSxKVxjy2W/T7StrdNTnrZlm9LpmvV4SlHOzC0FFKojYqta4Hfb4qRArIpCmqW +ARf6jzYg3LMrG7QPhhkgMLSR5lWiJWTm/NeW0Xe/MfzTsFzeNPxyuGMSQVQXlpYw +J+zj4lBe0V1f7HM28IuHPXHh/mIWLBYz3r3cl7UC1mfjIW4Wa76jiaBedgUjYxmx +n5msMvRXZS6YCA1PzCPmJ++RCR3hd/i9ivJbAgMBAAGjZjBkMB0GA1UdDgQWBBSm +aZo8fg/8lE3hEk3c1BQAhPOZ6TAfBgNVHSMEGDAWgBSmaZo8fg/8lE3hEk3c1BQA +hPOZ6TAPBgNVHRMBAf8EBTADAQH/MBEGA1UdEQQKMAiCBmEudGVzdDANBgkqhkiG +9w0BAQsFAAOCAQEAcOH/O8GRJU+VeyixkcewmjKxXZygex8j7AUR0bw1+uGWYjd8 +/EqpXg6VgkYsozK6FtDJTgW2rXj0Ptbz1pU9pC1M5cLc8+CSp8dNW1qN+OP1THVJ +K9qvPcbIuRQnG7hcX/EJk0kevks7XD7lNwhEjBmwvwefqW7TWMveByedZrwsdy+9 +mSlOjgNMY/qlUf5yqa8PAK7i/EPHAdYIbRDGkxKvhgOjv7H89qaXZXbCR+uBDLOh +TPkRFIDfBAkzu/PUW/7resii9R5CoO8pNnDuGwPVtq+Ibt23zUyEwiciCRcn1kEo +nB2gkX9tRTaZWDBtLKClylafLMq0y6Cu+dAFFg== +-----END CERTIFICATE----- diff --git a/test/regression/SslCertificateParseCount/stdout.txt b/test/regression/SslCertificateParseCount/stdout.txt new file mode 100644 index 00000000..b441da2f --- /dev/null +++ b/test/regression/SslCertificateParseCount/stdout.txt @@ -0,0 +1,5 @@ +a file of good certificates loads: true +one bad certificate in a file is counted: true +two bad certificates in a file are counted: true +a file with no certificate in a directory is counted: true +a missing file still gives mbedTLS's error: true From c8077d25da18bbb6479ae11652217e265efb7579 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 14:40:57 -0500 Subject: [PATCH 8/8] 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. c653b135 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 --- Changes.md | 1 + bench/cppia/Script.hx | 16 ++++++++++ bench/cppia/shared/CppiaBridge.hx | 3 ++ bench/src/CppiaBenchmarks.hx | 1 + src/hx/cppia/Cppia.cpp | 17 ++++++++--- .../CppiaHostStaticObjects/HostNode.hx | 6 ++++ .../CppiaHostStaticObjects/HostStatics.hx | 11 +++++++ .../regression/CppiaHostStaticObjects/Main.hx | 17 +++++++++++ .../CppiaHostStaticObjects/Script.hx | 29 +++++++++++++++++++ .../CppiaHostStaticObjects/build.hxml | 8 +++++ .../CppiaHostStaticObjects/stdout.txt | 2 ++ 11 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 test/regression/CppiaHostStaticObjects/HostNode.hx create mode 100644 test/regression/CppiaHostStaticObjects/HostStatics.hx create mode 100644 test/regression/CppiaHostStaticObjects/Main.hx create mode 100644 test/regression/CppiaHostStaticObjects/Script.hx create mode 100644 test/regression/CppiaHostStaticObjects/build.hxml create mode 100644 test/regression/CppiaHostStaticObjects/stdout.txt diff --git a/Changes.md b/Changes.md index 71caead5..43c36865 100644 --- a/Changes.md +++ b/Changes.md @@ -9,6 +9,7 @@ libhxcpp 6.0.3 (unreleased) * A thread that allocates or collects inside a GC-free zone while another thread collects, as native code that misses an exit from one can, now ends the program with "Critical Error: Allocating or collecting from a GC-free thread while another thread collects - was ExitGCFreeZone missed?". In a release build it waited for ever, with no message: the collector neither waits for a thread in a zone nor releases it. Debug builds already reported any allocation in a zone (HaxeFoundation/hxcpp#1468) * Fixed sys.ssl.Certificate.loadFile and loadPath reporting certificates that did not parse as an unrelated mbedTLS error: mbedTLS counts them, and the count was read as an error code, so one threw "ERROR - Generic error" and two a BIGNUM file error. They throw "Could not parse 2 certificates in " now, and for a directory "certificates or files", as mbedTLS also counts a file that holds none (HaxeFoundation/hxcpp@45adede6) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) +* A cppia script reads and writes a host class's static object fields, such as a singleton, a static Array or a static function, directly again below API level 500, which includes Haxe 5.0.0-preview.1, instead of looking each up by name: a loop that reads one host static Array and stores another runs 1.8 times as fast interpreted and 12 times as fast under the JIT. Host statics of other types and object fields already were direct; API level 500 keeps the lookup, which a typed function needs (HaxeFoundation/hxcpp#1365) libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index 0c110e15..cc123661 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -11,6 +11,7 @@ class Script { case "closure_call": new ClosureCall(); case "native_call": new NativeCall(); case "native_callback": new NativeCallback(); + case "host_statics": new HostStatics(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -147,3 +148,18 @@ class NativeCallback implements CppiaWorkload { }); } } + +class HostStatics implements CppiaWorkload { + public function new() {} + + public function run():Int { + var sum = 0; + for (i in 0...200000) { + // A read and a write of host static objects each pass + var values = CppiaBridge.values; + sum += values[i & 15]; + CppiaBridge.last = values; + } + return sum; + } +} diff --git a/bench/cppia/shared/CppiaBridge.hx b/bench/cppia/shared/CppiaBridge.hx index aa34843f..c63c708d 100644 --- a/bench/cppia/shared/CppiaBridge.hx +++ b/bench/cppia/shared/CppiaBridge.hx @@ -5,6 +5,9 @@ package; class CppiaBridge { public static var name:String; public static var workload:CppiaWorkload; + /** Read and written by the host_statics workload. **/ + public static var values:Array = [for (i in 0...16) i]; + public static var last:Array; @:noInline public static function step(value:Int):Int { diff --git a/bench/src/CppiaBenchmarks.hx b/bench/src/CppiaBenchmarks.hx index da258883..748c20c4 100644 --- a/bench/src/CppiaBenchmarks.hx +++ b/bench/src/CppiaBenchmarks.hx @@ -23,6 +23,7 @@ class CppiaBenchmarks extends Benchmark { result.push(new CppiaBenchmarks("closure_call", "calls", 200000, 10, jit)); result.push(new CppiaBenchmarks("native_call", "calls", 200000, 50, jit)); result.push(new CppiaBenchmarks("native_callback", "callbacks", 200000, 10, jit)); + result.push(new CppiaBenchmarks("host_statics", "iterations", 200000, 10, jit)); } return result; } diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index c1ae20c5..30ff8cf5 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -3272,11 +3272,20 @@ struct GetFieldByName : public CppiaDynamicExpr return new LinkMissExpr(this); } const StaticInfo *info = staticClass->GetStaticStorage(name); + bool direct = info && info->type!=hx::fsUnknown; + + // A host static can hold a typed function at API level 500, which a + // script closure must be converted to on the way in: stored through + // an hx::Object pointer, it is not callable as one + // (HaxeFoundation/hxcpp#1365). Below that an object static holds the + // object as it is, as an object field does, and statics are roots, + // so a store needs no barrier + #if (HXCPP_API_LEVEL>=500) + if (direct && info->type==fsObject) + direct = false; + #endif - // Do not use a MemReference for static access to objects. - // If the object in question is a hx::Callable_obj, its pointer will be downcasted to a hx::Object* and then updated to a non callable_obj pointer. - // This leads to memory exceptions later when then trying to invoke that callable. - if (info && info->type!=hx::fsUnknown && info->type != fsObject) + if (direct) { CppiaExpr* replace = createStaticAccess(this, info->type, info->address); replace->link(inModule); diff --git a/test/regression/CppiaHostStaticObjects/HostNode.hx b/test/regression/CppiaHostStaticObjects/HostNode.hx new file mode 100644 index 00000000..98373d28 --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/HostNode.hx @@ -0,0 +1,6 @@ +class HostNode { + public var value:Int; + + public function new(value:Int) + this.value = value; +} diff --git a/test/regression/CppiaHostStaticObjects/HostStatics.hx b/test/regression/CppiaHostStaticObjects/HostStatics.hx new file mode 100644 index 00000000..e89ecbde --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/HostStatics.hx @@ -0,0 +1,11 @@ +class HostStatics { + public static var obj:Dynamic; + public static var items:Array = [0]; + public static var fn:Void->Int; + public static var node:HostNode; + public static var count:Int = 0; + + public static function check():Bool { + return (obj : HostNode).value == -15000 && fn() == 15000 && items[1] == 15001 && node.value == 15000 && count == 4; + } +} diff --git a/test/regression/CppiaHostStaticObjects/Main.hx b/test/regression/CppiaHostStaticObjects/Main.hx new file mode 100644 index 00000000..ba28c4b7 --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/Main.hx @@ -0,0 +1,17 @@ +// A cppia script reads and writes a host class's static object fields: an +// object, an Array, a function and a typed object. They were read and written +// by name, through __GetStatic and __SetStatic, on every access in Haxe 4 +// builds; they are direct references now, as an object member is and as a +// host static Int or String already was. The objects stored are young and +// only the statics hold them, through minor and full collections. +function main() { + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} diff --git a/test/regression/CppiaHostStaticObjects/Script.hx b/test/regression/CppiaHostStaticObjects/Script.hx new file mode 100644 index 00000000..ccc24d64 --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/Script.hx @@ -0,0 +1,29 @@ +class Script { + static function main() { + HostStatics.count = 0; + var first = 0; + var sum = 0; + var expected = 0; + for (i in 0...20000) { + // Read through the host statics on every pass + sum += HostStatics.items[0]; + expected += first; + if (i % 5000 == 0) { + // Young objects, stored where only the host's statics hold them + HostStatics.obj = new HostNode(-i); + var captured = i; + HostStatics.fn = () -> captured; + HostStatics.items = [i, i + 1]; + HostStatics.node = new HostNode(i); + HostStatics.count++; + first = i; + cpp.vm.Gc.run(false); + } + } + cpp.vm.Gc.run(false); + cpp.vm.Gc.run(true); + var scriptOk = (HostStatics.obj : HostNode).value == -15000 && HostStatics.fn() == 15000 && HostStatics.items[1] == 15001 + && HostStatics.node.value == 15000 && sum == expected; + Sys.println('script reads its stores: $scriptOk, host reads them: ${HostStatics.check()}'); + } +} diff --git a/test/regression/CppiaHostStaticObjects/build.hxml b/test/regression/CppiaHostStaticObjects/build.hxml new file mode 100644 index 00000000..12343d28 --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/build.hxml @@ -0,0 +1,8 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +-D HXCPP_GC_GENERATIONAL +--dce no diff --git a/test/regression/CppiaHostStaticObjects/stdout.txt b/test/regression/CppiaHostStaticObjects/stdout.txt new file mode 100644 index 00000000..8c934da0 --- /dev/null +++ b/test/regression/CppiaHostStaticObjects/stdout.txt @@ -0,0 +1,2 @@ +script reads its stores: true, host reads them: true +script reads its stores: true, host reads them: true