From f5f961fad9633aec789116ff239bea9cfbe428e5 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 07:43:08 -0500 Subject: [PATCH 01/36] Clear a moved object's start bit in the block it left MoveBlocks walked each source block's start bits through a local copy, so the block kept every bit. When the blocks to move into ran out part way through one, that block was kept with the start bits of the objects it had moved out, whose headers are IMMIX_OBJECT_HAS_MOVED. A stale stack word holding one of those addresses then reached GetAllocTypeChecked, which took the header's mark byte of 0 for the previous mark one collection in 16, and MarkAllocUnchecked marked 0xfe rows from there, past the 256 bytes of the row table and into the block's first data rows. Once marked, the header looked live on every later collection. The block's own bit is cleared as each object moves, and GetAllocTypeChecked refuses a moved header outright. Test: GcMovedStartBits, under HXCPP_GC_MOVING, finds a block emptied in part and puts 407 of its moved-out addresses on the stack: the collector marked all 407 as objects before and none now, 3 of 3 runs on Windows x64. Fixes #450 --- Changes.md | 2 + src/hx/gc/Immix.cpp | 10 ++ test/regression/GcMovedStartBits/Main.hx | 149 ++++++++++++++++++++ test/regression/GcMovedStartBits/build.hxml | 3 + test/regression/GcMovedStartBits/stdout.txt | 4 + 5 files changed, 168 insertions(+) create mode 100644 test/regression/GcMovedStartBits/Main.hx create mode 100644 test/regression/GcMovedStartBits/build.hxml create mode 100644 test/regression/GcMovedStartBits/stdout.txt diff --git a/Changes.md b/Changes.md index 81db6b76..ec737cee 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,8 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed HXCPP_GC_MOVING, and HXCPP_GC_DEBUG_ALWAYS_MOVE without generational, corrupting live objects after a collection that ran out of blocks to move into: the block it was emptying kept, in part, the start bits of the objects it had moved out, and a stale stack word holding one of their old addresses had a later collection take the moved header for an object of 254 rows and mark rows past the block's row table, over the objects in its first rows. The start bits go as the objects move, and a moved header is never taken for an object (libhxcpp #450) + libhxcpp 6.0.0-rc.3 ------------------------------------------------------------ diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 0cb24d8b..72164fb2 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -1433,6 +1433,11 @@ struct BlockDataInfo // When known to be an actual object start... AllocType GetAllocTypeChecked(uintptr_t inOffset, bool allowPrevious) const { + // Where an object moved out, not an object: its mark byte is 0, which + // passes for the previous mark one collection in 16 + if (*reinterpret_cast(mPtr->mData + inOffset) == IMMIX_OBJECT_HAS_MOVED) + return allocNone; + unsigned char time{ mPtr->mData[inOffset + HX_ENDIAN_MARK_ID_BYTE_HEADER] }; if (((time + 1) & MARK_BYTE_MASK) != (gByteMarkID & MARK_BYTE_MASK)) { @@ -5129,6 +5134,11 @@ class GlobalAllocator header = IMMIX_OBJECT_HAS_MOVED; moveObjs++; + // The block's own start bit goes too: when the to blocks run + // out, this block is kept in part, and a start left here + // would have the next collection take the moved header for + // an object of 254 rows, marking rows past the row table + allocStart[r] &= ~(1u< +#include +#include +static std::vector gOld; +static std::vector gStale; +static std::vector gNow; +static int gPartial = 0; +static void recordOld(hx::Object *o) { gOld.push_back(~(uintptr_t)o); } +static void recordNow(hx::Object *o) { gNow.push_back(~(uintptr_t)o); } +static unsigned int headerAt(uintptr_t p) { return ((unsigned int *)p)[-1]; } +// The moved-out addresses in blocks that kept some of their objects +static int pickStale() +{ + enum { BLOCK = 1<<15 }; + std::map flags; + int n = (int)gOld.size(); + for(int i=0;i::iterator f=flags.begin(); f!=flags.end(); ++f) + if (f->second==3) + gPartial++; + gStale.clear(); + for(int i=0;i>24)!=0) + n++; + } + return n; +} +static void collectWithStale() +{ + volatile uintptr_t slots[4096]; + size_t n = gStale.size(); + for(size_t i=0;i = []; + var junk:Array = []; + for (i in 0...300000) { + var it = new Item(i); + if (i % 3 == 2) + junk.push(it); + else + keep.push(it); + } + junk = null; + + // The collection after the moving one takes a mark byte of 0 for the + // previous mark when its mark id ends in 1 + while (markNibble() != 15) + Gc.run(false); + + for (it in keep) + untyped __cpp__("recordOld({0}.mPtr)", it); + Gc.run(true); + for (it in keep) + untyped __cpp__("recordNow({0}.mPtr)", it); + var stale:Int = untyped __cpp__("pickStale()"); + var partial:Int = untyped __cpp__("gPartial"); + Sys.stderr().writeString('partly emptied blocks: $partial, moved-out addresses: $stale\n'); + + var fillers = new haxe.ds.Vector(40000); + untyped __cpp__("collectWithStale()"); + // Nothing else allocates before the fillers take the rows the moved objects left + for (i in 0...fillers.length) + fillers[i] = new Filler(); + Sys.println("moved-out locations marked as objects: " + untyped __cpp__("remarked()")); + untyped __cpp__("collectWithStale()"); + Sys.println("moved-out locations marked as objects, again: " + untyped __cpp__("remarked()")); + + var bad = 0; + for (f in fillers) + if (f.a != 0 || f.b != 0 || f.c != 0 || f.d != 0 || f.e != 0 || f.f != 0) + bad++; + Sys.println("fillers changed: " + bad); + var wrong = 0; + for (i in 0...keep.length) + if (keep[i].x != ((i >> 1) * 3) + (i & 1)) + wrong++; + Sys.println("kept items with a wrong value: " + wrong); + } +} diff --git a/test/regression/GcMovedStartBits/build.hxml b/test/regression/GcMovedStartBits/build.hxml new file mode 100644 index 00000000..d97fb616 --- /dev/null +++ b/test/regression/GcMovedStartBits/build.hxml @@ -0,0 +1,3 @@ +-m Main +--cpp bin +-D HXCPP_GC_MOVING diff --git a/test/regression/GcMovedStartBits/stdout.txt b/test/regression/GcMovedStartBits/stdout.txt new file mode 100644 index 00000000..441c15b4 --- /dev/null +++ b/test/regression/GcMovedStartBits/stdout.txt @@ -0,0 +1,4 @@ +moved-out locations marked as objects: 0 +moved-out locations marked as objects, again: 0 +fillers changed: 0 +kept items with a wrong value: 0 From e6b8c2a1dc05a3553840c2462ecc1937f3b2fe6f Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 07:49:15 -0500 Subject: [PATCH 02/36] Write cppia array elements where they are Three array builtins wrote to the wrong memory on valid code: - The JIT's a[i]++ with a Float result called runFloatCrement, which takes a double * for the result, with two arguments, so it stored 8 bytes through whatever the third argument register held. It passes the result's address now. - The JIT's typed push checked the capacity and expanded before it ran its argument, so an argument that grew the same array to its capacity left the store past the buffer. The argument runs first. - The interpreter's ArraySetter took a reference to the element before running the right-hand side, so a right-hand side that grew or reallocated the array stored into the old buffer. It works on a copy of the element and finds the element after, which also stores a[a.length] = a.length as the JIT and the other targets do. Test: CppiaArrayWrites, interpreted and under the JIT. Before, the JIT corrupted the Int array and its neighbour, and the interpreter stored 1 for 42 and 43 and appended 4 for 3; both engines print the expected output now, on Windows x64. Fixes #463 --- Changes.md | 1 + src/hx/cppia/ArrayBuiltin.cpp | 50 +++++++++++---- test/regression/CppiaArrayWrites/Main.hx | 13 ++++ test/regression/CppiaArrayWrites/Script.hx | 70 +++++++++++++++++++++ test/regression/CppiaArrayWrites/build.hxml | 7 +++ test/regression/CppiaArrayWrites/stdout.txt | 16 +++++ 6 files changed, 146 insertions(+), 11 deletions(-) create mode 100644 test/regression/CppiaArrayWrites/Main.hx create mode 100644 test/regression/CppiaArrayWrites/Script.hx create mode 100644 test/regression/CppiaArrayWrites/build.hxml create mode 100644 test/regression/CppiaArrayWrites/stdout.txt diff --git a/Changes.md b/Changes.md index ec737cee..90f6b8b6 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed three cppia array builtins writing to the wrong memory: under the JIT, a[i]++ or --a[i] whose result was used as a Float stored that result through whatever the third argument register held, corrupting the array or memory near it, and a typed push made room before running its argument, so an argument that grew the same array had the value stored past its buffer. Interpreted, a[i] = rhs and a[i] += rhs found the element before running rhs, so an rhs that grew the array stored into the old buffer, and a[a.length] = a.length stored the length after the store. The interpreter and the JIT now agree, and match the other targets (libhxcpp #463) * Fixed HXCPP_GC_MOVING, and HXCPP_GC_DEBUG_ALWAYS_MOVE without generational, corrupting live objects after a collection that ran out of blocks to move into: the block it was emptying kept, in part, the start bits of the objects it had moved out, and a stale stack word holding one of their old addresses had a later collection take the moved header for an object of 254 rows and mark rows past the block's row table, over the objects in its first rows. The start bits go as the objects move, and a moved header is never taken for an object (libhxcpp #450) libhxcpp 6.0.0-rc.3 diff --git a/src/hx/cppia/ArrayBuiltin.cpp b/src/hx/cppia/ArrayBuiltin.cpp index 0ecacbf9..86c6021c 100644 --- a/src/hx/cppia/ArrayBuiltin.cpp +++ b/src/hx/cppia/ArrayBuiltin.cpp @@ -153,8 +153,14 @@ struct ArraySetter : public ArrayBuiltinBase CPPIA_CHECK(thisVal); int i = args[0]->runInt(ctx); BCR_CHECK; + // On a copy, and the element found after: the right-hand side can grow + // the array or move its items, which left a reference taken before + // pointing at the old buffer + ELEM value = thisVal->__get(i); + FUNC::run(value, ctx, args[1]); + BCR_CHECK; ELEM &elem = thisVal->Item(i); - FUNC::run(elem, ctx, args[1]); + elem = value; #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_CTX(thisVal,hx::PointerOf(elem),ctx); @@ -168,8 +174,14 @@ struct ArraySetter : public ArrayBuiltinBase CPPIA_CHECK(thisVal); int i = args[0]->runInt(ctx); BCR_CHECK; + // On a copy, and the element found after: the right-hand side can grow + // the array or move its items, which left a reference taken before + // pointing at the old buffer + ELEM value = thisVal->__get(i); + FUNC::run(value, ctx, args[1]); + BCR_CHECK; ELEM &elem = thisVal->Item(i); - FUNC::run(elem, ctx, args[1]); + elem = value; #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_CTX(thisVal,hx::PointerOf(elem),ctx); @@ -183,8 +195,14 @@ struct ArraySetter : public ArrayBuiltinBase CPPIA_CHECK(thisVal); int i = args[0]->runInt(ctx); BCR_CHECK; + // On a copy, and the element found after: the right-hand side can grow + // the array or move its items, which left a reference taken before + // pointing at the old buffer + ELEM value = thisVal->__get(i); + FUNC::run(value, ctx, args[1]); + BCR_CHECK; ELEM &elem = thisVal->Item(i); - FUNC::run(elem, ctx, args[1]); + elem = value; #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_CTX(thisVal,hx::PointerOf(elem),ctx); @@ -198,8 +216,14 @@ struct ArraySetter : public ArrayBuiltinBase CPPIA_CHECK(thisVal); int i = args[0]->runInt(ctx); BCR_CHECK; + // On a copy, and the element found after: the right-hand side can grow + // the array or move its items, which left a reference taken before + // pointing at the old buffer + ELEM value = thisVal->__get(i); + FUNC::run(value, ctx, args[1]); + BCR_CHECK; ELEM &elem = thisVal->Item(i); - FUNC::run(elem, ctx, args[1]); + elem = value; #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_CTX(thisVal,hx::PointerOf(elem),ctx); @@ -1333,20 +1357,23 @@ struct ArrayBuiltin : public ArrayBuiltinBase { thisExpr->genCode(compiler, sJitTemp0, etObject); genNullReferenceExceptionCheck(compiler, sJitTemp0); - JumpId enough = compiler->compare( cmpI_LESS, sJitTemp0.star(jtInt, ArrayBase::lengthOffset()), - sJitTemp0.star(jtInt, ArrayBase::allocOffset()) ); - - // result comes back in sJitTemp0 - compiler->callNative( (void *)array_expand, sJitTemp0 ); - compiler->comeFrom(enough); JitTemp arrayThis(compiler,jtPointer); compiler->move(arrayThis, sJitTemp0); + // The value first: an argument that grows the array would otherwise + // leave the room made for it too small ExprType elemType = (ExprType)ExprTypeOf::value; JitTemp tempVal(compiler,getJitType(elemType)); args[0]->genCode(compiler, tempVal, elemType); + compiler->move(sJitTemp0, arrayThis); + JumpId enough = compiler->compare( cmpI_LESS, sJitTemp0.star(jtInt, ArrayBase::lengthOffset()), + sJitTemp0.star(jtInt, ArrayBase::allocOffset()) ); + + compiler->callNative( (void *)array_expand, sJitTemp0 ); + compiler->comeFrom(enough); + // sJitTemp1 = this compiler->move(sJitTemp1, arrayThis); // sJitTemp0 = length @@ -1972,7 +1999,8 @@ struct ArrayBuiltin : public ArrayBuiltinBase { JitTemp tempFloat(compiler, jtFloat); JitVal dVal = isMemoryVal(inDest) ? inDest : tempFloat; - compiler->callNative( (void *)runFloatCrement, thisVal, sJitTemp1 ); + // The result goes where dVal is: a float in memory is passed by address + compiler->callNative( (void *)runFloatCrement, thisVal, sJitTemp1, dVal.as(jtFloat) ); if (!isMemoryVal(inDest)) compiler->move(inDest.as(jtFloat), tempFloat); } diff --git a/test/regression/CppiaArrayWrites/Main.hx b/test/regression/CppiaArrayWrites/Main.hx new file mode 100644 index 00000000..e1b4cc7a --- /dev/null +++ b/test/regression/CppiaArrayWrites/Main.hx @@ -0,0 +1,13 @@ +// Runs the script interpreted and then under the JIT +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); + Sys.println(jit ? "jit" : "interpreted"); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} diff --git a/test/regression/CppiaArrayWrites/Script.hx b/test/regression/CppiaArrayWrites/Script.hx new file mode 100644 index 00000000..94186287 --- /dev/null +++ b/test/regression/CppiaArrayWrites/Script.hx @@ -0,0 +1,70 @@ +// libhxcpp #463: array builtins that wrote to the wrong memory. +// - Under the JIT, a[i]++ used as a Float stored its result through whatever +// the third argument register held. +// - Under the JIT, a typed push made room before running its argument, so an +// argument that grew the array left too little room. +// - Interpreted, a[i] = rhs found the element before running rhs, so an rhs +// that grew the array stored into the old buffer. +class Script { + static var spy:Array; + static var arr:Array; + + static function main() { + crements(); + pushes(); + stores(); + } + + static function crements() { + var f:Array = [1.5, 2.5]; + var x:Float = f[0]++; + var y:Float = ++f[1]; + Sys.println("float crement: x=" + x + " y=" + y + " " + f); + var a = [10, 20]; + var x:Float = a[0]++; + var y:Float = --a[1]; + Sys.println("int crement: x=" + x + " y=" + y + " " + a); + } + + // Grows a to exactly its capacity, then puts spy's buffer right after it + static function grow(a:Array):String { + a.resize(a.length + 100); + spy.resize(4); + return "pushed"; + } + + static function growInt(a:Array):Int { + a.resize(a.length + 101); + spy.resize(4); + return 0x7777; + } + + static function pushes() { + spy = []; + var a = ["x"]; + a.push(grow(a)); + Sys.println("push string: length=" + a.length + " last=" + a[a.length - 1] + " spy=" + spy); + spy = []; + var b = [1]; + b.push(growInt(b)); + Sys.println("push int: length=" + b.length + " last=" + b[b.length - 1] + " spy=" + spy); + } + + static function growAndGet():Int { + for (i in 0...1000) + arr.push(i); + return 42; + } + + static function stores() { + arr = [1, 2, 3]; + arr[0] = growAndGet(); + Sys.println("store: " + arr[0] + " length=" + arr.length); + arr = [1, 2, 3]; + arr[0] += growAndGet(); + Sys.println("compound store: " + arr[0]); + arr = [1, 2, 3]; + arr[arr.length] = arr.length; + Sys.println("store past the end: " + arr); + } +} diff --git a/test/regression/CppiaArrayWrites/build.hxml b/test/regression/CppiaArrayWrites/build.hxml new file mode 100644 index 00000000..d20d36bd --- /dev/null +++ b/test/regression/CppiaArrayWrites/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/CppiaArrayWrites/stdout.txt b/test/regression/CppiaArrayWrites/stdout.txt new file mode 100644 index 00000000..ba3d97ce --- /dev/null +++ b/test/regression/CppiaArrayWrites/stdout.txt @@ -0,0 +1,16 @@ +interpreted +float crement: x=1.5 y=3.5 [2.5,3.5] +int crement: x=10 y=19 [11,19] +push string: length=102 last=pushed spy=[0,0,0,0] +push int: length=103 last=30583 spy=[0,0,0,0] +store: 42 length=1003 +compound store: 43 +store past the end: [1,2,3,3] +jit +float crement: x=1.5 y=3.5 [2.5,3.5] +int crement: x=10 y=19 [11,19] +push string: length=102 last=pushed spy=[0,0,0,0] +push int: length=103 last=30583 spy=[0,0,0,0] +store: 42 length=1003 +compound store: 43 +store past the end: [1,2,3,3] From 27cb34e2df14044dfa2f63b98ff47d028a758fb4 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 07:59:35 -0500 Subject: [PATCH 03/36] Catch and check exceptions from every JIT helper that can throw #404 fixed three typed-array helpers. Many other native helpers of jitted code had the same problem, in two forms: - getFieldVariant, addVariantObject, addVariantString, setFieldVariant(V), createEnum and others caught into StackContext::exception, but the jitted code had no checkException after calling them, so it ran on past the throw. The exception was then held only by StackContext::exception, which the collector did not mark, so code that allocated before the next check could free it and crash the catch or the next call. - dynamicCatDynamic, the Variant arithmetic helpers, the obj*Inc and obj*Dec helpers, getItem to setDynamicI and the DynIndex helpers, jitGet, jitSet and jitUpdate, the typed array setters and increments, array_expand(_size), the Array stores and the string iterator did not catch at all, so the exception unwound through jitted frames, which have no unwind information, past the script's catch. Each of these helpers catches now, every call to one is followed by checkException, and the collector marks a pending exception when it scans a thread's script stack, pinned, as a stack word is. The try blocks in the templated array helpers take ArrayBuiltin.cpp past MSVC's default limit on sections in an object file, so MSVC compiles with -bigobj always, as debug and sanitizer builds already did. Test: CppiaJitHelperExceptions. Before, the JIT let toString's exception from d.s += t escape the script to the host's catch; now each case is caught in its own function, interpreted and under the JIT, and nothing runs after a throw, on Windows x64. Fixes #465 --- Changes.md | 1 + src/hx/cppia/ArrayBuiltin.cpp | 56 +++++- src/hx/cppia/ArrayVirtual.cpp | 42 +++++ src/hx/cppia/Cppia.cpp | 168 +++++++++++++++--- src/hx/cppia/CppiaClasses.cpp | 1 + src/hx/cppia/StringBuiltin.cpp | 4 + src/hx/gc/Immix.cpp | 8 + .../CppiaJitHelperExceptions/Main.hx | 13 ++ .../CppiaJitHelperExceptions/Script.hx | 67 +++++++ .../CppiaJitHelperExceptions/build.hxml | 7 + .../CppiaJitHelperExceptions/stdout.txt | 14 ++ toolchain/msvc-toolchain.xml | 7 +- 12 files changed, 355 insertions(+), 33 deletions(-) create mode 100644 test/regression/CppiaJitHelperExceptions/Main.hx create mode 100644 test/regression/CppiaJitHelperExceptions/Script.hx create mode 100644 test/regression/CppiaJitHelperExceptions/build.hxml create mode 100644 test/regression/CppiaJitHelperExceptions/stdout.txt diff --git a/Changes.md b/Changes.md index 90f6b8b6..b7053581 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed exceptions under the cppia JIT running on past the throw, or skipping the script's catch, when they came from a native helper of the jitted code: a Dynamic field or index updated with +=, -= and the others, Dynamic + Dynamic, ++ and -- on a Dynamic, a Dynamic or host ArrayAccess index, the typed array setters and increments, Array stores, string iterators and enum construction. Some of these caught the exception and the jitted code never looked, so it ran on and, if it allocated, could free the exception before the catch got it, crashing the next call; the rest let it unwind through the jitted frames, past the script's catch to the host's, or out of the process. Each now catches, the jitted code checks after each call, and the collector keeps a caught exception until it is handled. MSVC builds now compile with -bigobj, as debug builds already did (libhxcpp #465) * Fixed three cppia array builtins writing to the wrong memory: under the JIT, a[i]++ or --a[i] whose result was used as a Float stored that result through whatever the third argument register held, corrupting the array or memory near it, and a typed push made room before running its argument, so an argument that grew the same array had the value stored past its buffer. Interpreted, a[i] = rhs and a[i] += rhs found the element before running rhs, so an rhs that grew the array stored into the old buffer, and a[a.length] = a.length stored the length after the store. The interpreter and the JIT now agree, and match the other targets (libhxcpp #463) * Fixed HXCPP_GC_MOVING, and HXCPP_GC_DEBUG_ALWAYS_MOVE without generational, corrupting live objects after a collection that ran out of blocks to move into: the block it was emptying kept, in part, the start bits of the objects it had moved out, and a stale stack word holding one of their old addresses had a later collection take the moved header for an object of 254 rows and mark rows past the block's row table, over the objects in its first rows. The start bits go as the objects move, and a moved header is never taken for an object (libhxcpp #450) diff --git a/src/hx/cppia/ArrayBuiltin.cpp b/src/hx/cppia/ArrayBuiltin.cpp index 86c6021c..f4813b92 100644 --- a/src/hx/cppia/ArrayBuiltin.cpp +++ b/src/hx/cppia/ArrayBuiltin.cpp @@ -95,8 +95,11 @@ inline JitType elem4JitType() { return ExprTypeOf::value==etFloat ? jtFloa static ArrayBase * SLJIT_CALL array_expand_size(ArrayBase *inArray, int inSize) { + TRY_NATIVE inArray->Realloc(inSize+1); return inArray; + CATCH_NATIVE + return 0; } // blit, __SetSizeExact and resize throw for a range or size the array cannot @@ -235,6 +238,7 @@ struct ArraySetter : public ArrayBuiltinBase static void * SLJIT_CALL nativeRunInt(JitMultiArg *args) { + TRY_NATIVE Array_obj *thisVal = reinterpret_cast *>(JitArg(args,0).obj); ELEM &elem = thisVal->Item( JitArg(args,1).ival ); JitMultiArg arg2 = JitArg(args,2); @@ -244,10 +248,13 @@ struct ArraySetter : public ArrayBuiltinBase HX_OBJ_WB_GET(thisVal,hx::PointerOf(elem)); #endif return &elem; - } + CATCH_NATIVE + return 0; +} static void * SLJIT_CALL nativeRunFloat(JitMultiArg *args) { + TRY_NATIVE Array_obj *thisVal = reinterpret_cast *>(JitArg(args,0).obj); ELEM &elem = thisVal->Item( JitArg(args,1).ival ); JitMultiArg arg2 = JitArg(args,2); @@ -257,10 +264,13 @@ struct ArraySetter : public ArrayBuiltinBase HX_OBJ_WB_GET(thisVal,hx::PointerOf(elem)); #endif return &elem; - } + CATCH_NATIVE + return 0; +} static void * SLJIT_CALL nativeRunObject(JitMultiArg *args) { + TRY_NATIVE Array_obj *thisVal = reinterpret_cast *>(JitArg(args,0).obj); ELEM &elem = thisVal->Item( JitArg(args,1).ival ); Dynamic obj(JitArg(args,2).obj); @@ -270,10 +280,13 @@ struct ArraySetter : public ArrayBuiltinBase HX_OBJ_WB_GET(thisVal,hx::PointerOf(elem)); #endif return &elem; - } + CATCH_NATIVE + return 0; +} static void * SLJIT_CALL nativeRunString(JitMultiArg *args) { + TRY_NATIVE Array_obj *thisVal = reinterpret_cast *>(JitArg(args,0).obj); ELEM &elem = thisVal->Item( JitArg(args,1).ival ); JitMultiArg arg2 = JitArg(args,2); @@ -283,7 +296,9 @@ struct ArraySetter : public ArrayBuiltinBase HX_OBJ_WB_GET(thisVal,hx::PointerOf(elem)); #endif return &elem; - } + CATCH_NATIVE + return 0; +} void genCode(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) HXCPP_OVERRIDE @@ -352,6 +367,7 @@ struct ArraySetter : public ArrayBuiltinBase sJitTemp0.star(jtInt, ArrayBase::allocOffset()) ); // Make some room compiler->callNative( (void *)array_expand_size, sJitTemp0.as(jtPointer), sJitTemp1.as(jtInt) ); + compiler->checkException(); // sJitTemp0 is still this, restore length... compiler->move( sJitTemp1,index); @@ -434,15 +450,19 @@ struct ArraySetter : public ArrayBuiltinBase { case etInt: compiler->callNative( (void *)nativeRunInt, margs ); + compiler->checkException(); break; case etFloat: compiler->callNative( (void *)nativeRunFloat, margs ); + compiler->checkException(); break; case etString: compiler->callNative( (void *)nativeRunString, margs ); + compiler->checkException(); break; case etObject: compiler->callNative( (void *)nativeRunObject, margs ); + compiler->checkException(); break; default: throw "Bad array set type"; @@ -1173,8 +1193,11 @@ struct ArrayBuiltin : public ArrayBuiltinBase #ifdef CPPIA_JIT static ArrayBase * SLJIT_CALL array_expand(ArrayBase *inArray) { + TRY_NATIVE inArray->Realloc( inArray->length + 1 ); return inArray; + CATCH_NATIVE + return 0; } static void SLJIT_CALL runSort( Array_obj *inArray, hx::Object *inFunc) { @@ -1191,16 +1214,19 @@ struct ArrayBuiltin : public ArrayBuiltinBase static void SLJIT_CALL runElem( Array_obj *inArray, int inIndex) { + TRY_NATIVE ELEM &t = Array(inArray)[inIndex]; CREMENT::run(t); #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_GET(inArray,hx::PointerOf(t)); #endif - } + CATCH_NATIVE +} static int SLJIT_CALL runIntCrement( Array_obj *inArray, int inIndex) { + TRY_NATIVE ELEM &t = Array(inArray)[inIndex]; int result = ValToInt( CREMENT::run(t) ); #ifdef HXCPP_GC_GENERATIONAL @@ -1208,21 +1234,25 @@ struct ArrayBuiltin : public ArrayBuiltinBase HX_OBJ_WB_GET(inArray,hx::PointerOf(t)); #endif return result; - } + CATCH_NATIVE + return 0; +} static void SLJIT_CALL runFloatCrement( Array_obj *inArray, int inIndex, double *d) { + TRY_NATIVE ELEM &t = Array(inArray)[inIndex]; JitStore(d, ValToFloat( CREMENT::run(t) )); #ifdef HXCPP_GC_GENERATIONAL if (hx::ContainsPointers()) HX_OBJ_WB_GET(inArray,hx::PointerOf(t)); #endif - - } + CATCH_NATIVE +} static hx::Object * SLJIT_CALL runObjCrement( Array_obj *inArray, int inIndex) { + TRY_NATIVE ELEM &t = Array(inArray)[inIndex]; Dynamic result( CREMENT::run(t) ); #ifdef HXCPP_GC_GENERATIONAL @@ -1230,7 +1260,9 @@ struct ArrayBuiltin : public ArrayBuiltinBase HX_OBJ_WB_GET(inArray,hx::PointerOf(t)); #endif return result.mPtr; - } + CATCH_NATIVE + return 0; +} static int SLJIT_CALL runContains( Array_obj *inArray, typename ExprBaseTypeOf::Base inBase) { @@ -1372,6 +1404,7 @@ struct ArrayBuiltin : public ArrayBuiltinBase sJitTemp0.star(jtInt, ArrayBase::allocOffset()) ); compiler->callNative( (void *)array_expand, sJitTemp0 ); + compiler->checkException(); compiler->comeFrom(enough); // sJitTemp1 = this @@ -1470,6 +1503,7 @@ struct ArrayBuiltin : public ArrayBuiltinBase // result comes back in sJitTemp0 compiler->callNative( (void *)array_expand_size, sJitTemp0, sJitTemp1 ); + compiler->checkException(); // but need to reload sJitTemp1 compiler->move(sJitTemp1.as(jtInt), index); @@ -1989,10 +2023,12 @@ struct ArrayBuiltin : public ArrayBuiltinBase if (destType==etVoid || destType==etNull) { compiler->callNative( (void *)runElem, thisVal, sJitTemp1 ); + compiler->checkException(); } else if (destType==etInt) { compiler->callNative( (void *)runIntCrement, thisVal, sJitTemp1 ); + compiler->checkException(); compiler->move( inDest.as(jtInt), sJitReturnReg.as(jtInt) ); } else if (destType==etFloat) @@ -2001,12 +2037,14 @@ struct ArrayBuiltin : public ArrayBuiltinBase JitVal dVal = isMemoryVal(inDest) ? inDest : tempFloat; // The result goes where dVal is: a float in memory is passed by address compiler->callNative( (void *)runFloatCrement, thisVal, sJitTemp1, dVal.as(jtFloat) ); + compiler->checkException(); if (!isMemoryVal(inDest)) compiler->move(inDest.as(jtFloat), tempFloat); } else { compiler->callNative( (void *)runObjCrement, thisVal, sJitTemp1 ); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType); } } diff --git a/src/hx/cppia/ArrayVirtual.cpp b/src/hx/cppia/ArrayVirtual.cpp index 46ba3fb6..5dd014a7 100644 --- a/src/hx/cppia/ArrayVirtual.cpp +++ b/src/hx/cppia/ArrayVirtual.cpp @@ -91,60 +91,90 @@ static void SLJIT_CALL runJoin( ArrayAnyImpl *inArray, String *ioValue) static int SLJIT_CALL arrayPushInt( ArrayAnyImpl *inArray, int inVal) { + TRY_NATIVE return inArray->push(inVal); + CATCH_NATIVE + return 0; } static int SLJIT_CALL arrayPushObject( ArrayAnyImpl *inArray, hx::Object *inVal) { + TRY_NATIVE return inArray->push(Dynamic(inVal)); + CATCH_NATIVE + return 0; } static int SLJIT_CALL arrayPushFloat( ArrayAnyImpl *inArray, double *inVal) { + TRY_NATIVE return inArray->push(JitLoad(inVal)); + CATCH_NATIVE + return 0; } static int SLJIT_CALL arrayPushString( ArrayAnyImpl *inArray, String *inVal) { + TRY_NATIVE return inArray->push(JitLoad(inVal)); + CATCH_NATIVE + return 0; } static int SLJIT_CALL arraySetInt( ArrayAnyImpl *inArray, int inIndex, int inVal) { + TRY_NATIVE inArray->set(inIndex,inVal); return inVal; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL arraySetObject( ArrayAnyImpl *inArray, int inIndex, hx::Object *inVal) { + TRY_NATIVE inArray->set(inIndex,Dynamic(inVal)); return inVal; + CATCH_NATIVE + return 0; } static void SLJIT_CALL arraySetFloat( ArrayAnyImpl *inArray, int inIndex, double *inVal) { + TRY_NATIVE inArray->set(inIndex,JitLoad(inVal)); + CATCH_NATIVE } static void SLJIT_CALL arraySetString( ArrayAnyImpl *inArray, int inIndex, String *inVal) { + TRY_NATIVE inArray->set(inIndex,JitLoad(inVal)); + CATCH_NATIVE } static void SLJIT_CALL arrayUnshiftInt( ArrayAnyImpl *inArray, int inVal) { + TRY_NATIVE inArray->unshift(inVal); + CATCH_NATIVE } static void SLJIT_CALL arrayUnshiftObject( ArrayAnyImpl *inArray, hx::Object *inVal) { + TRY_NATIVE inArray->unshift(Dynamic(inVal)); + CATCH_NATIVE } static void SLJIT_CALL arrayUnshiftFloat( ArrayAnyImpl *inArray, double *inVal) { + TRY_NATIVE inArray->unshift(JitLoad(inVal)); + CATCH_NATIVE } static void SLJIT_CALL arrayUnshiftString( ArrayAnyImpl *inArray, String *inVal) { + TRY_NATIVE inArray->unshift(JitLoad(inVal)); + CATCH_NATIVE } @@ -831,6 +861,7 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case etInt: args[1]->genCode(compiler, sJitArg2.as(jtInt), etInt); compiler->callNative( (void *)arraySetInt, thisVal, index, sJitArg2.as(jtInt)); + compiler->checkException(); compiler->convertReturnReg(etInt, inDest, destType); break; case etFloat: @@ -838,6 +869,7 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase JitTemp value(compiler, jtFloat); args[1]->genCode(compiler, value, etFloat); compiler->callNative( (void *)arraySetFloat, thisVal, index, value); + compiler->checkException(); compiler->convert(value,etFloat, inDest, destType); } break; @@ -846,12 +878,14 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase JitTemp value(compiler, jtString); args[1]->genCode(compiler, value, etString); compiler->callNative( (void *)arraySetString, thisVal, index, value); + compiler->checkException(); compiler->convert(value,etString, inDest, destType); } break; case etObject: args[1]->genCode(compiler, sJitArg2.as(jtPointer), etObject); compiler->callNative( (void *)arraySetObject, thisVal, index, sJitArg2.as(jtPointer)); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType); break; default: ; //? @@ -868,12 +902,14 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case etInt: args[0]->genCode(compiler, sJitArg1.as(jtInt), etInt); compiler->callNative( (void *)arrayPushInt, thisVal, sJitArg1.as(jtInt)); + compiler->checkException(); break; case etFloat: { JitTemp value(compiler, jtFloat); args[0]->genCode(compiler, value, etFloat); compiler->callNative( (void *)arrayPushFloat, thisVal, value); + compiler->checkException(); } break; case etString: @@ -881,11 +917,13 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase JitTemp value(compiler, jtString); args[0]->genCode(compiler, value, etString); compiler->callNative( (void *)arrayPushString, thisVal, value); + compiler->checkException(); } break; case etObject: args[0]->genCode(compiler, sJitArg1.as(jtPointer), etObject); compiler->callNative( (void *)arrayPushObject, thisVal, sJitArg1.as(jtPointer)); + compiler->checkException(); break; default: ; //? } @@ -901,12 +939,14 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case etInt: args[0]->genCode(compiler, sJitArg1.as(jtInt), etInt); compiler->callNative( (void *)arrayUnshiftInt, thisVal, sJitArg1.as(jtInt)); + compiler->checkException(); break; case etFloat: { JitTemp value(compiler, jtFloat); args[0]->genCode(compiler, value, etFloat); compiler->callNative( (void *)arrayUnshiftFloat, thisVal, value); + compiler->checkException(); } break; case etString: @@ -914,11 +954,13 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase JitTemp value(compiler, jtString); args[0]->genCode(compiler, value, etString); compiler->callNative( (void *)arrayUnshiftString, thisVal, value); + compiler->checkException(); } break; case etObject: args[0]->genCode(compiler, sJitArg1.as(jtPointer), etObject); compiler->callNative( (void *)arrayUnshiftObject, thisVal, sJitArg1.as(jtPointer)); + compiler->checkException(); break; default: ; //? } diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 3094c88b..9f8d5686 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -2745,7 +2745,9 @@ static void SLJIT_CALL addVariantObject( cpp::Variant *ioVar, hx::Object *inValu static void SLJIT_CALL addVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, JitLoad(ioVar) + inValue); + CATCH_NATIVE } @@ -2759,58 +2761,80 @@ static void SLJIT_CALL addVariantString( cpp::Variant *ioVar, String *inValue ) static void SLJIT_CALL addVariantFloat( cpp::Variant *ioVar, double *inValue ) { + TRY_NATIVE JitStore(ioVar, JitLoad(ioVar) + JitLoad(inValue)); + CATCH_NATIVE } static void SLJIT_CALL subVariantFloat( cpp::Variant *ioVar, double *inValue ) { + TRY_NATIVE JitStore(ioVar, JitLoad(ioVar) - JitLoad(inValue)); + CATCH_NATIVE } static void SLJIT_CALL divVariantFloat( cpp::Variant *ioVar, double *inValue ) { + TRY_NATIVE JitStore(ioVar, JitLoad(ioVar) / JitLoad(inValue)); + CATCH_NATIVE } static void SLJIT_CALL multVariantFloat( cpp::Variant *ioVar, double *inValue ) { + TRY_NATIVE JitStore(ioVar, JitLoad(ioVar) * JitLoad(inValue)); + CATCH_NATIVE } static void SLJIT_CALL modVariantFloat( cpp::Variant *ioVar, double *inValue ) { + TRY_NATIVE JitStore(ioVar, hx::Mod(JitLoad(ioVar),JitLoad(inValue))); + CATCH_NATIVE } static void SLJIT_CALL andVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (int)(JitLoad(ioVar)) & inValue); + CATCH_NATIVE } static void SLJIT_CALL orVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (int)(JitLoad(ioVar)) | inValue); + CATCH_NATIVE } static void SLJIT_CALL xorVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (int)(JitLoad(ioVar)) ^ inValue); + CATCH_NATIVE } static void SLJIT_CALL shlVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (int)(JitLoad(ioVar)) << inValue); + CATCH_NATIVE } static void SLJIT_CALL shrVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (int)(JitLoad(ioVar)) >> inValue); + CATCH_NATIVE } static void SLJIT_CALL ushrVariantInt( cpp::Variant *ioVar, int inValue ) { + TRY_NATIVE JitStore(ioVar, (unsigned int)(int)(JitLoad(ioVar)) >> inValue); + CATCH_NATIVE } @@ -3084,6 +3108,7 @@ struct FieldByName : public CppiaDynamicExpr { JitTemp gotVal(compiler, etString, sizeof(cpp::Variant)); compiler->callNative( (void *)getFieldVariant, objSrc, (void *)&name, gotVal ); + compiler->checkException(); if (assign==aoAdd) { @@ -3092,16 +3117,19 @@ struct FieldByName : public CppiaDynamicExpr case etObject: value->genCode(compiler,sJitArg1.as(jtPointer), etObject); compiler->callNative( (void *)addVariantObject, gotVal, sJitArg1.as(jtPointer) ); + compiler->checkException(); break; case etInt: value->genCode(compiler,sJitArg1.as(jtInt), etInt); compiler->callNative( (void *)addVariantInt, gotVal, sJitArg1.as(jtPointer) ); + compiler->checkException(); break; case etString: { JitTemp sval(compiler, etString); value->genCode(compiler,sval, etString); compiler->callNative( (void *)addVariantString, gotVal, sval); + compiler->checkException(); } break; case etFloat: @@ -3109,6 +3137,7 @@ struct FieldByName : public CppiaDynamicExpr JitTemp fval(compiler, jtFloat); value->genCode(compiler,fval, etFloat); compiler->callNative( (void *)addVariantFloat, gotVal, fval); + compiler->checkException(); } break; default: @@ -3122,10 +3151,10 @@ struct FieldByName : public CppiaDynamicExpr value->genCode(compiler, fval, etFloat); switch(assign) { - case aoMult: compiler->callNative( (void *)multVariantFloat, gotVal, fval); break; - case aoDiv: compiler->callNative( (void *)divVariantFloat, gotVal, fval); break; - case aoMod: compiler->callNative( (void *)modVariantFloat, gotVal, fval); break; - case aoSub: compiler->callNative( (void *)subVariantFloat, gotVal, fval); break; + case aoMult: compiler->callNative( (void *)multVariantFloat, gotVal, fval); compiler->checkException(); break; + case aoDiv: compiler->callNative( (void *)divVariantFloat, gotVal, fval); compiler->checkException(); break; + case aoMod: compiler->callNative( (void *)modVariantFloat, gotVal, fval); compiler->checkException(); break; + case aoSub: compiler->callNative( (void *)subVariantFloat, gotVal, fval); compiler->checkException(); break; default: ; } } @@ -3134,12 +3163,12 @@ struct FieldByName : public CppiaDynamicExpr value->genCode(compiler, sJitTemp2, etInt); switch(assign) { - case aoAnd: compiler->callNative( (void *)andVariantInt, gotVal, sJitTemp2.as(jtInt)); break; - case aoOr: compiler->callNative( (void *)orVariantInt, gotVal, sJitTemp2.as(jtInt)); break; - case aoXOr: compiler->callNative( (void *)xorVariantInt, gotVal, sJitTemp2.as(jtInt)); break; - case aoShl: compiler->callNative( (void *)shlVariantInt, gotVal, sJitTemp2.as(jtInt)); break; - case aoShr: compiler->callNative( (void *)shrVariantInt, gotVal, sJitTemp2.as(jtInt)); break; - case aoUShr: compiler->callNative( (void *)ushrVariantInt, gotVal, sJitTemp2.as(jtInt)); break; + case aoAnd: compiler->callNative( (void *)andVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; + case aoOr: compiler->callNative( (void *)orVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; + case aoXOr: compiler->callNative( (void *)xorVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; + case aoShl: compiler->callNative( (void *)shlVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; + case aoShr: compiler->callNative( (void *)shrVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; + case aoUShr: compiler->callNative( (void *)ushrVariantInt, gotVal, sJitTemp2.as(jtInt)); compiler->checkException(); break; default: ; } } @@ -3147,10 +3176,12 @@ struct FieldByName : public CppiaDynamicExpr if (ret) { compiler->callNative( (void *)setFieldVariant, objSrc, (void *)&name, gotVal ); + compiler->checkException(); compiler->genVariantValueTemp0(0, inDest, destType); } else compiler->callNative( (void *)setFieldVariantV, objSrc, (void *)&name, gotVal ); + compiler->checkException(); } } #endif @@ -3940,7 +3971,10 @@ static hx::Object * SLJIT_CALL dynamicCatString(hx::Object *inLeft, String *inRi static hx::Object * SLJIT_CALL dynamicCatDynamic(hx::Object *inLeft, hx::Object *inRight) { + TRY_NATIVE return ( Dynamic(inLeft) + Dynamic(inRight) ).mPtr; + CATCH_NATIVE + return 0; } static int SLJIT_CALL modIntFloat(int inI, double *inMod) @@ -4058,6 +4092,7 @@ void genSetter(CppiaCompiler *compiler, const JitVal &ioValue, ExprType exprType { inExpr->genCode(compiler, sJitArg1, etObject); compiler->callNative((void *)dynamicCatDynamic, ioValue, sJitArg1.as(jtPointer) ); + compiler->checkException(); } compiler->move(ioValue, sJitReturnReg.as(jtPointer) ); } @@ -4458,81 +4493,113 @@ static double sMinusOne = -1.0; static void SLJIT_CALL objDec(hx::Object **ioVal) { + TRY_NATIVE JitStore(ioVal, (Dynamic(JitLoad(ioVal))-1).mPtr); + CATCH_NATIVE } static void SLJIT_CALL objInc(hx::Object **ioVal) { + TRY_NATIVE JitStore(ioVal, (Dynamic(JitLoad(ioVal))+1).mPtr); + CATCH_NATIVE } static hx::Object * SLJIT_CALL objPostInc(hx::Object **ioVal) { + TRY_NATIVE hx::Object *result = JitLoad(ioVal); JitStore(ioVal, (Dynamic(JitLoad(ioVal))+1).mPtr); return result; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPostDec(hx::Object **ioVal) { + TRY_NATIVE hx::Object *result = JitLoad(ioVal); JitStore(ioVal, (Dynamic(JitLoad(ioVal))-1).mPtr); return result; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPreInc(hx::Object **ioVal) { + TRY_NATIVE JitStore(ioVal, (Dynamic(JitLoad(ioVal))+1).mPtr); return JitLoad(ioVal); + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPreDec(hx::Object **ioVal) { + TRY_NATIVE JitStore(ioVal, (Dynamic(JitLoad(ioVal))-1).mPtr); return JitLoad(ioVal); + CATCH_NATIVE + return 0; } #ifdef HXCPP_GC_GENERATIONAL static void SLJIT_CALL objDecWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); *ioVal = (Dynamic(*ioVal)-1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); + CATCH_NATIVE } static void SLJIT_CALL objIncWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); *ioVal = (Dynamic(*ioVal)+1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); + CATCH_NATIVE } static hx::Object * SLJIT_CALL objPostIncWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); hx::Object *result = *ioVal; *ioVal = (Dynamic(result)+1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); return result; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPostDecWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); hx::Object *result = *ioVal; *ioVal = (Dynamic(result)-1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); return result; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPreIncWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); *ioVal = (Dynamic(*ioVal)+1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); return *ioVal; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL objPreDecWb(hx::Object *inObj,int inOffset) { + TRY_NATIVE hx::Object ** ioVal = (hx::Object **)( (char *)inObj + inOffset ); *ioVal = (Dynamic(*ioVal)-1).mPtr; HX_OBJ_WB_GET(inObj, *ioVal); return *ioVal; + CATCH_NATIVE + return 0; } #endif @@ -4721,6 +4788,7 @@ struct MemReferenceCrement : public CppiaExpr if ( inDest.type==jtVoid) { compiler->callNative( diff<0 ? (void *)objDecWb : (void *)objIncWb, obj, offset ); + compiler->checkException(); } else { @@ -4734,6 +4802,7 @@ struct MemReferenceCrement : public CppiaExpr default: ; } compiler->callNative(func, obj, offset); + compiler->checkException(); compiler->convertReturnReg( etObject, inDest, destType ); } @@ -4746,6 +4815,7 @@ struct MemReferenceCrement : public CppiaExpr if ( inDest.type==jtVoid) { compiler->callNative( diff<0 ? (void *)objDec : (void *)objInc, ioPtr ); + compiler->checkException(); } else { @@ -4759,6 +4829,7 @@ struct MemReferenceCrement : public CppiaExpr default: ; } compiler->callNative(func, ioPtr); + compiler->checkException(); compiler->convertReturnReg( etObject, inDest, destType ); } } @@ -5622,54 +5693,76 @@ struct ArrayDef : public CppiaDynamicExpr #ifdef CPPIA_JIT hx::Object * SLJIT_CALL getItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE return (inObj->__GetItem(inIndex)).mPtr; + CATCH_NATIVE + return 0; } void SLJIT_CALL incItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE inObj->__SetItem( inIndex, inObj->__GetItem(inIndex) + 1 ); - } + CATCH_NATIVE +} void SLJIT_CALL decItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE inObj->__SetItem( inIndex, inObj->__GetItem(inIndex) - 1 ); - } + CATCH_NATIVE +} hx::Object * SLJIT_CALL preIncItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE Dynamic val = inObj->__GetItem(inIndex) +1; inObj->__SetItem( inIndex, val ); return val.mPtr; - } + CATCH_NATIVE + return 0; +} hx::Object * SLJIT_CALL postIncItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE Dynamic val = inObj->__GetItem(inIndex); inObj->__SetItem( inIndex, val + 1 ); return val.mPtr; - } + CATCH_NATIVE + return 0; +} hx::Object * SLJIT_CALL setDynamicI(hx::Object *inObj, int inIndex, hx::Object *inValue) { + TRY_NATIVE inObj->__SetItem( inIndex, inValue ); return inValue; - } + CATCH_NATIVE + return 0; +} hx::Object * SLJIT_CALL preDecItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE Dynamic val = inObj->__GetItem(inIndex) - 1; inObj->__SetItem( inIndex, val ); return val.mPtr; - } + CATCH_NATIVE + return 0; +} hx::Object * SLJIT_CALL postDecItem(hx::Object *inObj, int inIndex) { + TRY_NATIVE Dynamic val = inObj->__GetItem(inIndex); inObj->__SetItem( inIndex, val - 1 ); return val.mPtr; - } + CATCH_NATIVE + return 0; +} struct DynIndexArgs { @@ -5683,17 +5776,23 @@ struct ArrayDef : public CppiaDynamicExpr #define DynIndexFunc(name, OP) \ hx::Object * SLJIT_CALL name(hx::Object *inObj, DynIndexArgs *args) \ { \ + TRY_NATIVE \ Dynamic result = Dynamic(args->lvalue.obj) OP ; \ inObj->__SetItem( args->index.ival, result); \ return result.mPtr; \ + CATCH_NATIVE \ + return 0; \ } #define DynIndexIntFunc(name, OP) \ hx::Object * SLJIT_CALL name(hx::Object *inObj, DynIndexArgs *args) \ { \ + TRY_NATIVE \ Dynamic result = ((int)Dynamic(args->lvalue.obj)) OP ; \ inObj->__SetItem( args->index.ival, result); \ return result.mPtr; \ + CATCH_NATIVE \ + return 0; \ } @@ -5704,10 +5803,13 @@ struct ArrayDef : public CppiaDynamicExpr hx::Object * SLJIT_CALL dynMod(hx::Object *inObj, DynIndexArgs *args) { + TRY_NATIVE Dynamic result = hx::Mod( Dynamic(args->lvalue.obj), args->rvalue.dval ); inObj->__SetItem( args->index.ival, result); return result.mPtr; - } + CATCH_NATIVE + return 0; +} DynIndexIntFunc(dynAnd, & args->rvalue.ival ); DynIndexIntFunc(dynOr, | args->rvalue.ival ); @@ -5717,10 +5819,13 @@ struct ArrayDef : public CppiaDynamicExpr hx::Object * SLJIT_CALL dynUShr(hx::Object *inObj, DynIndexArgs *args) { + TRY_NATIVE Dynamic result = hx::UShr( Dynamic(args->lvalue.obj), args->rvalue.ival ); inObj->__SetItem( args->index.ival, result); return result.mPtr; - } + CATCH_NATIVE + return 0; +} #endif @@ -5821,6 +5926,7 @@ struct DynamicArrayI : public CppiaDynamicExpr { index->genCode(compiler, sJitTemp1, etInt); compiler->callNative( (void *)getItem, obj, sJitTemp1.as(jtInt) ); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType); return; } @@ -5831,6 +5937,7 @@ struct DynamicArrayI : public CppiaDynamicExpr { compiler->callNative( crement==coPostInc || crement==coPostInc ? (void *)incItem : (void *)decItem, obj, sJitTemp1.as(jtInt) ); + compiler->checkException(); } else { @@ -5847,6 +5954,7 @@ struct DynamicArrayI : public CppiaDynamicExpr throw "Bad crement in DynamicArrayI"; compiler->callNative( func, obj, sJitTemp1.as(jtInt) ); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType ); } return; @@ -5859,6 +5967,7 @@ struct DynamicArrayI : public CppiaDynamicExpr value->genCode(compiler, sJitTemp2, etObject); compiler->callNative( (void *)setDynamicI, obj, idx, sJitTemp2); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType ); return; } @@ -5871,6 +5980,7 @@ struct DynamicArrayI : public CppiaDynamicExpr compiler->move(argsBuf.arg(0,etInt), sJitTemp1); compiler->callNative( (void *)getItem, obj, sJitTemp1.as(jtInt) ); + compiler->checkException(); compiler->move( argsBuf.arg(1,jtPointer), sJitReturnReg.as(jtPointer)); @@ -5905,6 +6015,7 @@ struct DynamicArrayI : public CppiaDynamicExpr if (!func) throw "Bad set in DynamicArrayI"; compiler->callNative( func, obj, argsBuf ); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType); } @@ -6168,25 +6279,34 @@ struct ArrayAccessI : public CppiaDynamicExpr // args: this expression, the object, the index, the operand, the value read static hx::Object * SLJIT_CALL jitGet(JitMultiArg *args) { + TRY_NATIVE ArrayAccessI *expr = (ArrayAccessI *)JitArg(args,0).obj; return expr->callGet(CppiaCtx::getCurrent(), JitArg(args,1).obj, JitArg(args,2).ival).mPtr; + CATCH_NATIVE + return 0; } static hx::Object * SLJIT_CALL jitSet(JitMultiArg *args) { + TRY_NATIVE ArrayAccessI *expr = (ArrayAccessI *)JitArg(args,0).obj; expr->callSet(CppiaCtx::getCurrent(), JitArg(args,1).obj, JitArg(args,2).ival, JitArg(args,3).obj); return JitArg(args,3).obj; - } + CATCH_NATIVE + return 0; +} static hx::Object * SLJIT_CALL jitUpdate(JitMultiArg *args) { + TRY_NATIVE ArrayAccessI *expr = (ArrayAccessI *)JitArg(args,0).obj; Dynamic before = JitArg(args,4).obj; Dynamic after = expr->update(before, JitArg(args,3).obj); expr->callSet(CppiaCtx::getCurrent(), JitArg(args,1).obj, JitArg(args,2).ival, after); return expr->crement==coPostInc || expr->crement==coPostDec ? before.mPtr : after.mPtr; - } + CATCH_NATIVE + return 0; +} void genCode(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) HXCPP_OVERRIDE { @@ -6200,21 +6320,27 @@ struct ArrayAccessI : public CppiaDynamicExpr index->genCode(compiler, args.arg(2,jtInt), etInt); if (crement==coNone && assign==aoNone) + { compiler->callNative((void *)jitGet, args); + compiler->checkException(); + } else if (crement==coNone && assign==aoSet) { value->genCode(compiler, args.arg(3,jtPointer), etObject); compiler->callNative((void *)jitSet, args); + compiler->checkException(); } else { compiler->callNative((void *)jitGet, args); + compiler->checkException(); compiler->move(args.arg(4,jtPointer), sJitReturnReg.as(jtPointer)); if (crement==coNone) value->genCode(compiler, args.arg(3,jtPointer), etObject); else compiler->move(args.arg(3,jtPointer), JitVal((void *)0)); compiler->callNative((void *)jitUpdate, args); + compiler->checkException(); } if (destType!=etVoid && destType!=etNull) diff --git a/src/hx/cppia/CppiaClasses.cpp b/src/hx/cppia/CppiaClasses.cpp index 3b30bbfd..d3d35184 100644 --- a/src/hx/cppia/CppiaClasses.cpp +++ b/src/hx/cppia/CppiaClasses.cpp @@ -502,6 +502,7 @@ struct EnumField : public CppiaDynamicExpr compiler->add(sJitCtxFrame, sJitFrame, compiler->getCurrentFrameSize()); compiler->callNative((void *)createEnum,(void *)enumClass.mPtr,(void *)&enumName,(int)args.size() ); + compiler->checkException(); if (destType!=etVoid && destType!=etNull) compiler->convertResult( etObject, inDest, destType ); diff --git a/src/hx/cppia/StringBuiltin.cpp b/src/hx/cppia/StringBuiltin.cpp index 2e7a6b94..17888ef4 100644 --- a/src/hx/cppia/StringBuiltin.cpp +++ b/src/hx/cppia/StringBuiltin.cpp @@ -102,8 +102,11 @@ struct StringIteratorExpr : public StringExpr #ifdef CPPIA_JIT static hx::Object *SLJIT_CALL run(String *inValue) { + TRY_NATIVE String value = JitLoad(inValue); return ( KEYS ? value.keyValueIterator() : value.iterator() ).mPtr; + CATCH_NATIVE + return 0; } void genCode(CppiaCompiler *compiler, const JitVal &inDest,ExprType destType) HXCPP_OVERRIDE @@ -111,6 +114,7 @@ struct StringIteratorExpr : public StringExpr JitTemp value(compiler,jtString); strVal->genCode(compiler, value, etString); compiler->callNative( (void *)run, value); + compiler->checkException(); compiler->convertReturnReg(etObject, inDest, destType); } #endif diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 72164fb2..7d42bdfc 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -8831,6 +8831,10 @@ class LocalAllocator : public hx::StackContext #ifdef HXCPP_SCRIPTABLE MarkSetMember("ScriptStack",__inCtx); hx::MarkConservative((int *)(stack), (int *)(pointer),__inCtx); + // An exception a JIT helper caught waits here for the jitted code + // to check for it, which it may do after allocating + if (exception) + hx::MarkConservativePointer(exception, __inCtx); #endif MarkSetMember("Registers",__inCtx); hx::MarkConservative(CAPTURE_REG_START, CAPTURE_REG_END, __inCtx); @@ -8849,6 +8853,10 @@ class LocalAllocator : public hx::StackContext #ifdef HXCPP_SCRIPTABLE hx::MarkConservative((int *)(stack), (int *)(pointer),__inCtx); + // An exception a JIT helper caught waits here for the jitted code + // to check for it, which it may do after allocating + if (exception) + hx::MarkConservativePointer(exception, __inCtx); #endif #endif diff --git a/test/regression/CppiaJitHelperExceptions/Main.hx b/test/regression/CppiaJitHelperExceptions/Main.hx new file mode 100644 index 00000000..e1b4cc7a --- /dev/null +++ b/test/regression/CppiaJitHelperExceptions/Main.hx @@ -0,0 +1,13 @@ +// Runs the script interpreted and then under the JIT +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); + Sys.println(jit ? "jit" : "interpreted"); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} diff --git a/test/regression/CppiaJitHelperExceptions/Script.hx b/test/regression/CppiaJitHelperExceptions/Script.hx new file mode 100644 index 00000000..f3085932 --- /dev/null +++ b/test/regression/CppiaJitHelperExceptions/Script.hx @@ -0,0 +1,67 @@ +// libhxcpp #465: exceptions from the native helpers jitted code calls. +// - Some helpers caught the exception into the context, but the jitted code +// did not check for it, and ran on past the throw. The exception was held +// only by the context, which the collector did not mark, so allocating +// before the catch could free it. +// - Others did not catch at all, so the exception unwound through the jitted +// frames, past the script's catch. +// Each case catches in its own function, interpreted and under the JIT, and +// counts the statements that ran after the throw. +class Thrower { + public function new() {} + + public function toString():String + throw "toString threw"; +} + +class Script { + static var ranOn = 0; + + static function fieldAdd():String { + try { + var d:Dynamic = {s: "a"}; + var t:Dynamic = new Thrower(); + d.s += t; + ranOn++; + var parts = new Array(); + for (i in 0...100000) + parts.push("x" + i); + ranOn += parts.length > 0 ? 1 : 0; + return "no exception"; + } catch (e:Dynamic) { + return "caught " + e; + } + } + + static function dynamicAdd():String { + try { + var d:Dynamic = "x"; + var t:Dynamic = new Thrower(); + d += t; + ranOn++; + return "no exception"; + } catch (e:Dynamic) { + return "caught " + e; + } + } + + static function dynamicIndexAdd():String { + try { + var d:Dynamic = ["x"]; + var t:Dynamic = new Thrower(); + d[0] += t; + ranOn++; + return "no exception"; + } catch (e:Dynamic) { + return "caught " + e; + } + } + + static function main() { + for (round in 0...3) + Sys.println("field += throwing toString, then allocating: " + fieldAdd()); + Sys.println("Dynamic += throwing toString: " + dynamicAdd()); + Sys.println("Dynamic index += throwing toString: " + dynamicIndexAdd()); + Sys.println("statements run after a throw: " + ranOn); + } +} diff --git a/test/regression/CppiaJitHelperExceptions/build.hxml b/test/regression/CppiaJitHelperExceptions/build.hxml new file mode 100644 index 00000000..d20d36bd --- /dev/null +++ b/test/regression/CppiaJitHelperExceptions/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/CppiaJitHelperExceptions/stdout.txt b/test/regression/CppiaJitHelperExceptions/stdout.txt new file mode 100644 index 00000000..13ffdba2 --- /dev/null +++ b/test/regression/CppiaJitHelperExceptions/stdout.txt @@ -0,0 +1,14 @@ +interpreted +field += throwing toString, then allocating: caught toString threw +field += throwing toString, then allocating: caught toString threw +field += throwing toString, then allocating: caught toString threw +Dynamic += throwing toString: caught toString threw +Dynamic index += throwing toString: caught toString threw +statements run after a throw: 0 +jit +field += throwing toString, then allocating: caught toString threw +field += throwing toString, then allocating: caught toString threw +field += throwing toString, then allocating: caught toString threw +Dynamic += throwing toString: caught toString threw +Dynamic index += throwing toString: caught toString threw +statements run after a throw: 0 diff --git a/toolchain/msvc-toolchain.xml b/toolchain/msvc-toolchain.xml index 23b83943..05ef6c61 100644 --- a/toolchain/msvc-toolchain.xml +++ b/toolchain/msvc-toolchain.xml @@ -119,7 +119,10 @@ - + + @@ -136,8 +139,6 @@ fuzzer-no-link too. The objects name the runtime libraries for link.exe --> - - From aef2d3b89e0aa3ea05be9754930897bfc1f9a405 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:01:54 -0500 Subject: [PATCH 04/36] Let a finalizer take a Mutex Finalizers run on the collecting thread, inside the collection, with gPauseForCollect still set. The uncontended paths of Mutex, Condition, Semaphore, Deque and Lock call __hxcpp_gc_safe_point when a collection is pending, which went to SafePoint and PauseForCollect, and that ends the process when the collection is under way. Stock hxcpp took these locks in a GC-free zone, which the collecting thread can enter. sgIsCollecting is set only once every other thread is stopped or in a zone, so a thread outside a zone that reaches SafePoint while it is set is the collecting thread, and SafePoint returns for it. Test: GcFinalizerTakesMutex, 1000 finalizers that take and try a Mutex. Before, the process ended at the first; now all but those the stack scan keeps run, 3 of 3 runs on Windows x64. A finalizer that allocates, as Deque.add does, still ends the process, as it should. Fixes #452 --- Changes.md | 1 + src/hx/gc/Immix.cpp | 5 +++ .../FinalizersAcrossFreeZones/Main.hx | 3 +- test/regression/GcFinalizerTakesMutex/Main.hx | 43 +++++++++++++++++++ .../GcFinalizerTakesMutex/build.hxml | 2 + .../GcFinalizerTakesMutex/stdout.txt | 2 + 6 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 test/regression/GcFinalizerTakesMutex/Main.hx create mode 100644 test/regression/GcFinalizerTakesMutex/build.hxml create mode 100644 test/regression/GcFinalizerTakesMutex/stdout.txt diff --git a/Changes.md b/Changes.md index b7053581..c3a045d8 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed a finalizer set with cpp.vm.Gc.setFinalizer that takes a Mutex ending the process with "Bad Allocation while collecting - from finalizer?", even with the lock free: finalizers run on the collecting thread inside the collection, and Mutex's uncontended path stopped there for the collection as if it were another thread. The collecting thread passes that stop now, so a finalizer can take a Mutex, as with stock hxcpp. A finalizer still must not allocate (libhxcpp #452) * Fixed exceptions under the cppia JIT running on past the throw, or skipping the script's catch, when they came from a native helper of the jitted code: a Dynamic field or index updated with +=, -= and the others, Dynamic + Dynamic, ++ and -- on a Dynamic, a Dynamic or host ArrayAccess index, the typed array setters and increments, Array stores, string iterators and enum construction. Some of these caught the exception and the jitted code never looked, so it ran on and, if it allocated, could free the exception before the catch got it, crashing the next call; the rest let it unwind through the jitted frames, past the script's catch to the host's, or out of the process. Each now catches, the jitted code checks after each call, and the collector keeps a caught exception until it is handled. MSVC builds now compile with -bigobj, as debug builds already did (libhxcpp #465) * Fixed three cppia array builtins writing to the wrong memory: under the JIT, a[i]++ or --a[i] whose result was used as a Float stored that result through whatever the third argument register held, corrupting the array or memory near it, and a typed push made room before running its argument, so an argument that grew the same array had the value stored past its buffer. Interpreted, a[i] = rhs and a[i] += rhs found the element before running rhs, so an rhs that grew the array stored into the old buffer, and a[a.length] = a.length stored the length after the store. The interpreter and the JIT now agree, and match the other targets (libhxcpp #463) * Fixed HXCPP_GC_MOVING, and HXCPP_GC_DEBUG_ALWAYS_MOVE without generational, corrupting live objects after a collection that ran out of blocks to move into: the block it was emptying kept, in part, the start bits of the objects it had moved out, and a stale stack word holding one of their old addresses had a later collection take the moved header for an object of 254 rows and mark rows past the block's row table, over the objects in its first rows. The start bits go as the objects move, and a moved header is never taken for an object (libhxcpp #450) diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 7d42bdfc..185f69cc 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -8339,6 +8339,11 @@ class LocalAllocator : public hx::StackContext if (mGCFreeZone) return; #endif + // Every other thread is stopped or in a zone before this is set, so this + // is the collecting thread, running a finalizer that took a Mutex or + // similar: it is the collection, and has nothing to wait for + if (sgIsCollecting) + return; PauseForCollect(); } diff --git a/test/regression/FinalizersAcrossFreeZones/Main.hx b/test/regression/FinalizersAcrossFreeZones/Main.hx index 7aa34ff2..d3ff838c 100644 --- a/test/regression/FinalizersAcrossFreeZones/Main.hx +++ b/test/regression/FinalizersAcrossFreeZones/Main.hx @@ -15,8 +15,7 @@ class Item { class Main { // Finalizers run inside a collection, one collection at a time and under - // the collector's lock, so the count needs no lock of its own; taking a - // Mutex there would reach a safe point from inside the collection. + // the collector's lock, so the count needs no lock of its own. static var finalized = 0; static function onFinalize(item:Item):Void { diff --git a/test/regression/GcFinalizerTakesMutex/Main.hx b/test/regression/GcFinalizerTakesMutex/Main.hx new file mode 100644 index 00000000..f5b868cb --- /dev/null +++ b/test/regression/GcFinalizerTakesMutex/Main.hx @@ -0,0 +1,43 @@ +import sys.thread.Mutex; + +class Resource { + public function new() {} +} + +// libhxcpp #452. A finalizer runs on the collecting thread, inside the +// collection. Mutex stops at a pending collection on its uncontended paths, +// and that stop took the collecting thread for one that had to wait, ending +// the process with "Bad Allocation while collecting". Stock hxcpp took the +// lock in a GC-free zone, which the collecting thread can enter, so a +// finalizer could take a Mutex. It still must not allocate. +class Main { + static var lock = new Mutex(); + static var counted = 0; + static var tried = 0; + + static function onFinalize(r:Resource):Void { + lock.acquire(); + counted++; + lock.release(); + if (lock.tryAcquire()) { + tried++; + lock.release(); + } + } + + static function make() { + for (i in 0...1000) { + var r = new Resource(); + cpp.vm.Gc.setFinalizer(r, cpp.Callable.fromStaticFunction(onFinalize)); + } + } + + static function main() { + make(); + cpp.vm.Gc.run(true); + cpp.vm.Gc.run(true); + // The conservative stack scan may keep a few alive + Sys.println("finalizers took the mutex: " + (counted > 900)); + Sys.println("finalizers tried it: " + (tried == counted)); + } +} diff --git a/test/regression/GcFinalizerTakesMutex/build.hxml b/test/regression/GcFinalizerTakesMutex/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcFinalizerTakesMutex/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcFinalizerTakesMutex/stdout.txt b/test/regression/GcFinalizerTakesMutex/stdout.txt new file mode 100644 index 00000000..211ba293 --- /dev/null +++ b/test/regression/GcFinalizerTakesMutex/stdout.txt @@ -0,0 +1,2 @@ +finalizers took the mutex: true +finalizers tried it: true From 0cac760d7078cfd1506ffef9ebd62a768c2aa771 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:10:39 -0500 Subject: [PATCH 05/36] Write to stdout, and close a child's stdin, in a GC-free zone __trace, __hxcpp_print_string and __hxcpp_println_string wrote to stdout outside a zone. When stdout blocks (a pipe nobody reads, a slow reader, a Windows console with text selected), the writing thread blocked outside the zone, so the next collection on any thread waited for it, and every other thread for the collection. They make their text first, since nothing may allocate in a zone, and write in one, through OutputZone, which enters none on a thread the collector does not know. On Windows, _hx_std_process_stdin_close called CloseHandle outside a zone, and CloseHandle waits for a WriteFile in progress on the pipe, for as long as the child does not read. Writes to stdin are now counted apart, as PipeCall counts every pipe call for destroy, and stdin_close refuses new ones and cancels those in progress before it closes, in a zone. Test: GcStdoutBlocked, a child whose stdout fills while it collects: println and trace never collected before, and now all three modes do. ProcessStdinCloseCollects: the collection and the close finished only when the child exited before, and while it runs now, on Windows x64. Fixes #454 --- Changes.md | 1 + src/hx/StdLibs.cpp | 56 ++++++++++++++---- src/hx/libs/std/Process.cpp | 34 +++++++++-- test/regression/GcStdoutBlocked/Main.hx | 58 +++++++++++++++++++ test/regression/GcStdoutBlocked/build.hxml | 2 + test/regression/GcStdoutBlocked/stdout.txt | 3 + .../ProcessStdinCloseCollects/Main.hx | 45 ++++++++++++++ .../ProcessStdinCloseCollects/build.hxml | 2 + .../ProcessStdinCloseCollects/stdout.txt | 2 + test/regression/emscripten-skip.txt | 2 + 10 files changed, 189 insertions(+), 16 deletions(-) create mode 100644 test/regression/GcStdoutBlocked/Main.hx create mode 100644 test/regression/GcStdoutBlocked/build.hxml create mode 100644 test/regression/GcStdoutBlocked/stdout.txt create mode 100644 test/regression/ProcessStdinCloseCollects/Main.hx create mode 100644 test/regression/ProcessStdinCloseCollects/build.hxml create mode 100644 test/regression/ProcessStdinCloseCollects/stdout.txt diff --git a/Changes.md b/Changes.md index c3a045d8..3a76751f 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed trace, Sys.print and Sys.println stopping every thread when stdout blocked, as it does for a pipe nobody reads, a slow log reader or a Windows console with text selected: they wrote outside a GC-free zone, so the next collection on any thread waited for the blocked write, and every other thread waited for the collection. On Windows, Process.stdin.close() did the same while another thread was blocked writing to the child, and waited itself until the child exited. They write in a zone now, and stdin.close() cancels the writes in progress before it closes, as Process.close() does (libhxcpp #454) * Fixed a finalizer set with cpp.vm.Gc.setFinalizer that takes a Mutex ending the process with "Bad Allocation while collecting - from finalizer?", even with the lock free: finalizers run on the collecting thread inside the collection, and Mutex's uncontended path stopped there for the collection as if it were another thread. The collecting thread passes that stop now, so a finalizer can take a Mutex, as with stock hxcpp. A finalizer still must not allocate (libhxcpp #452) * Fixed exceptions under the cppia JIT running on past the throw, or skipping the script's catch, when they came from a native helper of the jitted code: a Dynamic field or index updated with +=, -= and the others, Dynamic + Dynamic, ++ and -- on a Dynamic, a Dynamic or host ArrayAccess index, the typed array setters and increments, Array stores, string iterators and enum construction. Some of these caught the exception and the jitted code never looked, so it ran on and, if it allocated, could free the exception before the catch got it, crashing the next call; the rest let it unwind through the jitted frames, past the script's catch to the host's, or out of the process. Each now catches, the jitted code checks after each call, and the collector keeps a caught exception until it is handled. MSVC builds now compile with -bigobj, as debug builds already did (libhxcpp #465) * Fixed three cppia array builtins writing to the wrong memory: under the JIT, a[i]++ or --a[i] whose result was used as a Float stored that result through whatever the third argument register held, corrupting the array or memory near it, and a typed push made room before running its argument, so an argument that grew the same array had the value stored past its buffer. Interpreted, a[i] = rhs and a[i] += rhs found the element before running rhs, so an rhs that grew the array stored into the old buffer, and a[a.length] = a.length stored the length after the store. The interpreter and the JIT now agree, and match the other targets (libhxcpp #463) diff --git a/src/hx/StdLibs.cpp b/src/hx/StdLibs.cpp index 7553df56..6789c81a 100644 --- a/src/hx/StdLibs.cpp +++ b/src/hx/StdLibs.cpp @@ -423,6 +423,23 @@ void WriteConsoleAllA(HANDLE h, const char *str, DWORD length) { } #endif +namespace +{ +// Output to stdout can block for a long time: a pipe nobody reads, a slow +// reader, or a Windows console with text selected. Outside a GC-free zone, the +// next collection on any thread waits for it, and every other thread with it. +// The text is made before, since nothing may allocate in a zone, and a thread +// the collector does not know needs no zone. +struct OutputZone +{ + bool entered; + OutputZone() : entered(HX_CTX_GET && hx::TryGCFreeZone()) { } + ~OutputZone() { if (entered) hx::ExitGCFreeZone(); } + OutputZone(const OutputZone &) = delete; + OutputZone &operator=(const OutputZone &) = delete; +}; +} + void __trace(Dynamic inObj, Dynamic info) { String text; @@ -434,7 +451,6 @@ void __trace(Dynamic inObj, Dynamic info) DWORD mode; if (GetConsoleMode(handle, &mode)) { - fflush(stdout); String s; if (info == null()) { s = HX_CSTRING("?? ") + text + HX_CSTRING("\n"); @@ -445,30 +461,38 @@ void __trace(Dynamic inObj, Dynamic info) } if (s.isUTF16Encoded()) { - WriteConsoleAllW(handle, s.__WCStr(), s.length); + const wchar_t *wide = s.__WCStr(); + OutputZone zone; + fflush(stdout); + WriteConsoleAllW(handle, wide, s.length); } else { // ascii - WriteConsoleAllA(handle, s.__CStr(), s.length); + const char *narrow = s.__CStr(); + OutputZone zone; + fflush(stdout); + WriteConsoleAllA(handle, narrow, s.length); } return; } #endif hx::strbuf convertBuf; + const char *textOut = text.raw_ptr() ? text.out_str(&convertBuf) : "null"; if (info==null()) { - PRINTF("?? %s\n", text.raw_ptr() ? text.out_str(&convertBuf) : "null"); + OutputZone zone; + PRINTF("?? %s\n", textOut); + fflush(stdout); } else { const char *filename = Dynamic((info)->__Field(HX_CSTRING("fileName"), HX_PROP_DYNAMIC))->toString().utf8_str(0,false); int line = Dynamic((info)->__Field( HX_CSTRING("lineNumber") , HX_PROP_DYNAMIC))->__ToInt(); - hx::strbuf convertBuf; - //PRINTF("%s:%d: %s\n", filename, line, text.raw_ptr() ? text.out_str(&convertBuf) : "null"); - PRINTF("%s:%d: %s\n", filename, line, text.raw_ptr() ? text.out_str(&convertBuf) : "null"); + OutputZone zone; + PRINTF("%s:%d: %s\n", filename, line, textOut); + fflush(stdout); } - fflush(stdout); } void __hxcpp_exit(int inExitCode) @@ -779,13 +803,17 @@ void __hxcpp_print_string(const String &inString) HANDLE handle; if (hxStdoutIsConsole(handle) && inV.isUTF16Encoded()) { + const wchar_t *wide = inV.__WCStr(); + OutputZone zone; fflush(stdout); - WriteConsoleAllW(handle, inV.__WCStr(), inV.length); + WriteConsoleAllW(handle, wide, inV.length); return; } #endif hx::strbuf convertBuf; - PRINTF("%s", inV.out_str(&convertBuf) ); + const char *out = inV.out_str(&convertBuf); + OutputZone zone; + PRINTF("%s", out ); } void __hxcpp_println_string(const String &inString) @@ -796,15 +824,19 @@ void __hxcpp_println_string(const String &inString) bool isConsole = hxStdoutIsConsole(handle); if (isConsole && inV.isUTF16Encoded()) { + const wchar_t *wide = inV.__WCStr(); + OutputZone zone; fflush(stdout); - WriteConsoleAllW(handle, inV.__WCStr(), inV.length); + WriteConsoleAllW(handle, wide, inV.length); fwrite("\n", 1, 1, stdout); fflush(stdout); return; } #endif hx::strbuf convertBuf; - PRINTF("%s\n", inV.out_str(&convertBuf)); + const char *out = inV.out_str(&convertBuf); + OutputZone zone; + PRINTF("%s\n", out); // Flush every line, redirected or not. Boot asks for line buffering, // but the Windows CRT treats _IOLBF as full buffering, so a redirected // stdout there held a server's log lines back from whatever reads them, diff --git a/src/hx/libs/std/Process.cpp b/src/hx/libs/std/Process.cpp index 7741dfae..464c7a57 100644 --- a/src/hx/libs/std/Process.cpp +++ b/src/hx/libs/std/Process.cpp @@ -201,6 +201,9 @@ struct vprocess : public hx::Object // begun: see PipeCall std::atomic pipeCalls; std::atomic closing; + // The same for the writes to stdin alone, which stdin_close cancels + std::atomic stdinCalls; + std::atomic stdinClosing; #define HANDLE_INIT 0 #else int oread; @@ -221,6 +224,8 @@ struct vprocess : public hx::Object #ifdef NEKO_WINDOWS pipeCalls = 0; closing = false; + stdinCalls = 0; + stdinClosing = false; #else reaped = false; exitStatus = 0; @@ -309,12 +314,20 @@ struct PipeCall { vprocess *process; HANDLE handle; - PipeCall(vprocess *inProcess, HANDLE inHandle) : process(inProcess) + bool stdinWrite; + PipeCall(vprocess *inProcess, HANDLE inHandle, bool inStdinWrite=false) : process(inProcess), stdinWrite(inStdinWrite) { process->pipeCalls++; - handle = process->closing ? 0 : inHandle; + if (stdinWrite) + process->stdinCalls++; + handle = process->closing || (stdinWrite && process->stdinClosing) ? 0 : inHandle; + } + ~PipeCall() + { + if (stdinWrite) + process->stdinCalls--; + process->pipeCalls--; } - ~PipeCall() { process->pipeCalls--; } }; #endif @@ -903,7 +916,7 @@ int _hx_std_process_stdin_write( Dynamic handle, Array buf, int p DWORD nbytes =0; bool written; { - PipeCall call(p, p->iwrite); + PipeCall call(p, p->iwrite, true); written = call.handle && WriteFile(call.handle,src+pos,len,&nbytes,0); } if( !written ) @@ -938,7 +951,20 @@ void _hx_std_process_stdin_close( Dynamic handle ) #ifdef NEKO_WINDOWS if ( p->iwrite ) + { + // CloseHandle waits for a WriteFile in progress on the pipe in another + // thread, for as long as the child does not read, so the writes are + // refused and cancelled first, as destroy does for all the pipes. It + // waits in a zone, so a collection meanwhile need not wait for it + hx::AutoGCFreeZone zone; + p->stdinClosing = true; + for(int spins=0; p->stdinCalls>0; spins++) + { + CancelIoEx(p->iwrite, 0); + Sleep(spins<10 ? 0 : 1); + } CloseHandle(p->iwrite); + } #else if( p->iwrite!=-1 ) do_close(p->iwrite); diff --git a/test/regression/GcStdoutBlocked/Main.hx b/test/regression/GcStdoutBlocked/Main.hx new file mode 100644 index 00000000..01f5c79f --- /dev/null +++ b/test/regression/GcStdoutBlocked/Main.hx @@ -0,0 +1,58 @@ +import cpp.vm.Gc; +import sys.io.Process; +import sys.thread.Lock; +import sys.thread.Thread; + +// libhxcpp #454. A child process whose stdout nobody reads: one of its threads +// prints until the pipe is full and the write blocks, then its main thread +// collects. trace and Sys.println wrote outside a GC-free zone, so the +// collection waited for the blocked writer, and every other thread with it. +// Sys.stdout().writeString blocked inside one and was fine. +class Main { + static function main() { + var args = Sys.args(); + if (args.length == 0) + parent(); + else + child(args[0]); + } + + static function parent() { + for (mode in ["write", "println", "trace"]) { + var p = new Process(Sys.programPath(), [mode]); + var got = new Lock(); + var line = "(nothing)"; + Thread.create(() -> { + try { + line = p.stderr.readLine(); + } catch (e:Dynamic) {} + got.release(); + }); + if (got.wait(20.0)) + Sys.println('$mode: child said $line'); + else + Sys.println('$mode: no collection after 20 s'); + p.kill(); + p.close(); + } + } + + static function child(mode:String) { + var text = StringTools.lpad("", "x", 1000); + Thread.create(() -> { + while (true) { + switch (mode) { + case "trace": trace(text); + case "println": Sys.println(text); + default: Sys.stdout().writeString(text + "\n"); + } + } + }); + // Long enough for the pipe to fill + Sys.sleep(1.0); + Gc.run(true); + Sys.stderr().writeString('collected\n'); + Sys.stderr().flush(); + Sys.sleep(60); + } +} diff --git a/test/regression/GcStdoutBlocked/build.hxml b/test/regression/GcStdoutBlocked/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcStdoutBlocked/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcStdoutBlocked/stdout.txt b/test/regression/GcStdoutBlocked/stdout.txt new file mode 100644 index 00000000..4df2d8c2 --- /dev/null +++ b/test/regression/GcStdoutBlocked/stdout.txt @@ -0,0 +1,3 @@ +write: child said collected +println: child said collected +trace: child said collected diff --git a/test/regression/ProcessStdinCloseCollects/Main.hx b/test/regression/ProcessStdinCloseCollects/Main.hx new file mode 100644 index 00000000..d6291d8b --- /dev/null +++ b/test/regression/ProcessStdinCloseCollects/Main.hx @@ -0,0 +1,45 @@ +import cpp.vm.Gc; +import haxe.io.Bytes; +import sys.io.Process; +import sys.thread.Lock; +import sys.thread.Thread; + +// libhxcpp #454. One thread is blocked writing to a child's stdin, which the +// child never reads, and another closes that stdin. On Windows, CloseHandle +// waits for the WriteFile in progress, and stdin.close called it outside a +// GC-free zone, so a collection started meanwhile, and the close itself, +// waited until the child exited. Process.close cancelled pending pipe I/O +// first (#261); stdin.close now does too. +class Main { + static function main() { + if (Sys.args().length > 0) { + Sys.sleep(Std.parseFloat(Sys.args()[0])); + return; + } + var p = new Process(Sys.programPath(), ["30"]); + var writerDone = new Lock(); + Thread.create(() -> { + try { + p.stdin.write(Bytes.alloc(1 << 22)); + } catch (e:Dynamic) {} + writerDone.release(); + }); + Sys.sleep(0.5); + var closed = new Lock(); + var closedWhileRunning = false; + Thread.create(() -> { + p.stdin.close(); + closedWhileRunning = p.exitCode(false) == null; + closed.release(); + }); + Sys.sleep(0.5); + Gc.run(true); + var collectedWhileRunning = p.exitCode(false) == null; + closed.wait(); + Sys.println("collected while the child ran: " + collectedWhileRunning); + Sys.println("stdin closed while the child ran: " + closedWhileRunning); + p.kill(); + writerDone.wait(); + p.close(); + } +} diff --git a/test/regression/ProcessStdinCloseCollects/build.hxml b/test/regression/ProcessStdinCloseCollects/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/ProcessStdinCloseCollects/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/ProcessStdinCloseCollects/stdout.txt b/test/regression/ProcessStdinCloseCollects/stdout.txt new file mode 100644 index 00000000..cf983ae0 --- /dev/null +++ b/test/regression/ProcessStdinCloseCollects/stdout.txt @@ -0,0 +1,2 @@ +collected while the child ran: true +stdin closed while the child ran: true diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 6342a8d4..848ee0d0 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -45,6 +45,7 @@ GcRunKeepsHeap: expects the desktop 20 MB working target; other platforms, Emscr GcScopeOwnership: counts thread attachments, which single-threaded Emscripten builds do not make GcSmallNursery: threads (std::thread, which needs a pthreads build) GcStackLargeContainer: threads (std::thread, which needs a pthreads build) +GcStdoutBlocked: processes (runs itself) and threads GcTraceDeepGraph: processes (runs itself) and threads (std::thread, which needs a pthreads build) GcTraceLargeObjects: processes (runs itself) GcWeakMapChain: threads @@ -84,6 +85,7 @@ ProcessExitCodeTwice: processes ProcessPosixStartError: processes ProcessReapAfterClose: processes ProcessSigpipeHandler: processes +ProcessStdinCloseCollects: processes and threads ProcessWaitError: processes PthreadFastTls: threads RegexpConcurrentCollection: threads From 9ea3b48ddf8877da9ffc57ba4302f7eeddf6005c Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:11:00 -0500 Subject: [PATCH 06/36] Make Haxe 4's AtomicInt a safe point Haxe 4's haxe.atomic.AtomicInt is a cpp.Pointer, and its methods call the _hx_atomic_* functions, none of which polled gPauseForCollect. A thread spinning on load() waiting for a flag the main thread sets after a collection kept that collection waiting for ever. Haxe 5's hx::atomic::AtomicInt calls __hxcpp_gc_safe_point in each operation, and #119 did the same for Mutex.tryAcquire. Overloads of the _hx_atomic_* functions that take ::cpp::Pointer, which is what Haxe 4 passes, now stop for a pending collection and call the volatile int * forms, which the runtime's own spinlocks keep using unchanged. The __hxcpp_atomic_object_* operations stop too. Test: AtomicSpinSafePoint, with a native watchdog. Before, the collection never finished; now it does, and the spinning thread sees the flag, on Windows x64. Fixes #455 --- Changes.md | 1 + include/cpp/Pointer.h | 17 ++++++ include/hx/StdLibs.h | 12 +++++ test/regression/AtomicSpinSafePoint/Main.hx | 54 +++++++++++++++++++ .../regression/AtomicSpinSafePoint/build.hxml | 2 + .../regression/AtomicSpinSafePoint/stdout.txt | 2 + test/regression/emscripten-skip.txt | 1 + 7 files changed, 89 insertions(+) create mode 100644 test/regression/AtomicSpinSafePoint/Main.hx create mode 100644 test/regression/AtomicSpinSafePoint/build.hxml create mode 100644 test/regression/AtomicSpinSafePoint/stdout.txt diff --git a/Changes.md b/Changes.md index 3a76751f..79f23029 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed a thread spinning on Haxe 4's haxe.atomic.AtomicInt, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: the atomic operations were not safe points, so a collection waited for it, and it waited for a flag the collecting thread would set afterwards. They stop for a pending collection now, as Haxe 5's AtomicInt and Mutex.tryAcquire do, and so do the AtomicObject operations (libhxcpp #455) * Fixed trace, Sys.print and Sys.println stopping every thread when stdout blocked, as it does for a pipe nobody reads, a slow log reader or a Windows console with text selected: they wrote outside a GC-free zone, so the next collection on any thread waited for the blocked write, and every other thread waited for the collection. On Windows, Process.stdin.close() did the same while another thread was blocked writing to the child, and waited itself until the child exited. They write in a zone now, and stdin.close() cancels the writes in progress before it closes, as Process.close() does (libhxcpp #454) * Fixed a finalizer set with cpp.vm.Gc.setFinalizer that takes a Mutex ending the process with "Bad Allocation while collecting - from finalizer?", even with the lock free: finalizers run on the collecting thread inside the collection, and Mutex's uncontended path stopped there for the collection as if it were another thread. The collecting thread passes that stop now, so a finalizer can take a Mutex, as with stock hxcpp. A finalizer still must not allocate (libhxcpp #452) * Fixed exceptions under the cppia JIT running on past the throw, or skipping the script's catch, when they came from a native helper of the jitted code: a Dynamic field or index updated with +=, -= and the others, Dynamic + Dynamic, ++ and -- on a Dynamic, a Dynamic or host ArrayAccess index, the typed array setters and increments, Array stores, string iterators and enum construction. Some of these caught the exception and the jitted code never looked, so it ran on and, if it allocated, could free the exception before the catch got it, crashing the next call; the rest let it unwind through the jitted frames, past the script's catch to the host's, or out of the process. Each now catches, the jitted code checks after each call, and the collector keeps a caught exception until it is handled. MSVC builds now compile with -bigobj, as debug builds already did (libhxcpp #465) diff --git a/include/cpp/Pointer.h b/include/cpp/Pointer.h index 74a68ee3..05466258 100644 --- a/include/cpp/Pointer.h +++ b/include/cpp/Pointer.h @@ -574,4 +574,21 @@ 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. +#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); } +#undef HX_ATOMIC_SAFE_POINT + #endif diff --git a/include/hx/StdLibs.h b/include/hx/StdLibs.h index 58e724f0..7f937943 100644 --- a/include/hx/StdLibs.h +++ b/include/hx/StdLibs.h @@ -554,6 +554,9 @@ inline Dynamic __hxcpp_atomic_object_create(Dynamic value) { } inline Dynamic __hxcpp_atomic_object_store(Dynamic dynObj, Dynamic val) { + // A thread spinning on one must still reach a safe point (libhxcpp #455) + if (hx::gPauseForCollect) + __hxcpp_gc_safe_point(); AtomicObject *obj = dynamic_cast(dynObj.mPtr); if (!obj) throw HX_INVALID_OBJECT; @@ -561,6 +564,9 @@ inline Dynamic __hxcpp_atomic_object_store(Dynamic dynObj, Dynamic val) { } inline Dynamic __hxcpp_atomic_object_load(Dynamic dynObj) { + // A thread spinning on one must still reach a safe point (libhxcpp #455) + if (hx::gPauseForCollect) + __hxcpp_gc_safe_point(); AtomicObject *obj = dynamic_cast(dynObj.mPtr); if (!obj) throw HX_INVALID_OBJECT; @@ -568,6 +574,9 @@ inline Dynamic __hxcpp_atomic_object_load(Dynamic dynObj) { } inline Dynamic __hxcpp_atomic_object_exchange(Dynamic dynObj, Dynamic newVal) { + // A thread spinning on one must still reach a safe point (libhxcpp #455) + if (hx::gPauseForCollect) + __hxcpp_gc_safe_point(); AtomicObject *obj = dynamic_cast(dynObj.mPtr); if (!obj) throw HX_INVALID_OBJECT; @@ -575,6 +584,9 @@ inline Dynamic __hxcpp_atomic_object_exchange(Dynamic dynObj, Dynamic newVal) { } inline Dynamic __hxcpp_atomic_object_compare_exchange(Dynamic dynObj, Dynamic expected, Dynamic replacement) { + // A thread spinning on one must still reach a safe point (libhxcpp #455) + if (hx::gPauseForCollect) + __hxcpp_gc_safe_point(); AtomicObject *obj = dynamic_cast(dynObj.mPtr); if (!obj) throw HX_INVALID_OBJECT; diff --git a/test/regression/AtomicSpinSafePoint/Main.hx b/test/regression/AtomicSpinSafePoint/Main.hx new file mode 100644 index 00000000..74db08d9 --- /dev/null +++ b/test/regression/AtomicSpinSafePoint/Main.hx @@ -0,0 +1,54 @@ +import cpp.vm.Gc; +import haxe.atomic.AtomicInt; +import sys.thread.Thread; + +// libhxcpp #455. A thread spins on haxe.atomic.AtomicInt.load(), waiting for a +// flag the main thread sets after a collection. Haxe 4's AtomicInt calls the +// _hx_atomic_* functions, which were not safe points, so the collection waited +// for the spinning thread for ever. A native watchdog, which the collector +// does not know, ends the test if that happens again. +@:cppFileCode(' +#include +#include +#include +#include +#include +static std::atomic gCollected(false); +static void startWatchdog() +{ + std::thread([]{ + std::this_thread::sleep_for(std::chrono::seconds(60)); + if (!gCollected) + { + fputs("no collection after 60 s\\n", stdout); + fflush(stdout); + std::_Exit(1); + } + }).detach(); +} +') +class Main { + static var flag = new AtomicInt(0); + static var started = new AtomicInt(0); + static var spins = new AtomicInt(0); + + static function main() { + untyped __cpp__("startWatchdog()"); + var done = new sys.thread.Lock(); + Thread.create(() -> { + started.store(1); + while (flag.load() == 0) + spins.add(1); + done.release(); + }); + while (started.load() == 0) + Sys.sleep(0.001); + Sys.sleep(0.1); + Gc.run(true); + untyped __cpp__("gCollected = true"); + Sys.println("collected while a thread spun on an AtomicInt"); + flag.store(1); + done.wait(); + Sys.println("the spinning thread saw the flag"); + } +} diff --git a/test/regression/AtomicSpinSafePoint/build.hxml b/test/regression/AtomicSpinSafePoint/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/AtomicSpinSafePoint/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/AtomicSpinSafePoint/stdout.txt b/test/regression/AtomicSpinSafePoint/stdout.txt new file mode 100644 index 00000000..b808c6ac --- /dev/null +++ b/test/regression/AtomicSpinSafePoint/stdout.txt @@ -0,0 +1,2 @@ +collected while a thread spun on an AtomicInt +the spinning thread saw the flag diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 848ee0d0..48a985ce 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -6,6 +6,7 @@ AnonConcurrentString: threads ArrayConcurrentString: threads +AtomicSpinSafePoint: threads (std::thread, which needs a pthreads build) AttachedThreadId: threads (std::thread, which needs a pthreads build) CffiNekoNullBoolWithoutInit: runs neko, which loads an ndll the test builds CffiNekoValueTags: runs neko, which loads an ndll the test builds From c9d3e6857c0be4ad4323664961fd309aa4fcb00e Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:11:00 -0500 Subject: [PATCH 07/36] Number a script's interface slots after the host's The module constructor gives the host's interface method names slots 2 to sgNativeNameSlotCount-1, which is sgNativeNameSlotCount-2 entries, and getInterfaceSlot gave a new name interfaceSlots.size()+1, which for the first is sgNativeNameSlotCount-1: the host's last slot. A class implementing a script interface and a host interface whose method has that slot (IMap's clear, in the test host) stored both methods in one slot of its interface table. New names now count from sgNativeNameSlotCount, or from 1 as before when the host registers no names. Test: CppiaInterfaceSlots, a class implementing two script interfaces and haxe.Constraints.IMap. Before, both engines crashed; now each call reaches its own method, interpreted and under the JIT, on Windows x64. Fixes #462 --- Changes.md | 1 + src/hx/cppia/Cppia.h | 2 + src/hx/cppia/CppiaModule.cpp | 6 +- test/regression/CppiaInterfaceSlots/Main.hx | 13 ++++ test/regression/CppiaInterfaceSlots/Script.hx | 67 +++++++++++++++++++ .../regression/CppiaInterfaceSlots/build.hxml | 7 ++ .../regression/CppiaInterfaceSlots/stdout.txt | 10 +++ 7 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 test/regression/CppiaInterfaceSlots/Main.hx create mode 100644 test/regression/CppiaInterfaceSlots/Script.hx create mode 100644 test/regression/CppiaInterfaceSlots/build.hxml create mode 100644 test/regression/CppiaInterfaceSlots/stdout.txt diff --git a/Changes.md b/Changes.md index 79f23029..38375ad5 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed a cppia class that implements both a script interface and a host interface, such as haxe.Constraints.IMap, calling the wrong method or crashing: the script interface's first method that the host does not know got the slot of the host's last interface method, so both were stored in one slot. Script interface methods are numbered after the host's now (libhxcpp #462) * Fixed a thread spinning on Haxe 4's haxe.atomic.AtomicInt, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: the atomic operations were not safe points, so a collection waited for it, and it waited for a flag the collecting thread would set afterwards. They stop for a pending collection now, as Haxe 5's AtomicInt and Mutex.tryAcquire do, and so do the AtomicObject operations (libhxcpp #455) * Fixed trace, Sys.print and Sys.println stopping every thread when stdout blocked, as it does for a pipe nobody reads, a slow log reader or a Windows console with text selected: they wrote outside a GC-free zone, so the next collection on any thread waited for the blocked write, and every other thread waited for the collection. On Windows, Process.stdin.close() did the same while another thread was blocked writing to the child, and waited itself until the child exited. They write in a zone now, and stdin.close() cancels the writes in progress before it closes, as Process.close() does (libhxcpp #454) * Fixed a finalizer set with cpp.vm.Gc.setFinalizer that takes a Mutex ending the process with "Bad Allocation while collecting - from finalizer?", even with the lock free: finalizers run on the collecting thread inside the collection, and Mutex's uncontended path stopped there for the collection as if it were another thread. The collecting thread passes that stop now, so a finalizer can take a Mutex, as with stock hxcpp. A finalizer still must not allocate (libhxcpp #452) diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 4eb9e248..27114510 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -452,6 +452,8 @@ class CppiaModule std::unordered_set allFileIds; typedef std::map< std::string, int > InterfaceSlots; InterfaceSlots interfaceSlots; + // The slot the next name the host does not know gets + int nextInterfaceSlot; StackLayout *layout; CppiaClassInfo *linkingClass; diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index f8be08f8..44139cd0 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -135,6 +135,10 @@ CppiaModule::CppiaModule() if (sgNativeNameSlotCount>0) for(int i=2;i2 ? sgNativeNameSlotCount : 1; std::lock_guard lock(sModuleLock); allModules().push_back(this); @@ -338,7 +342,7 @@ int CppiaModule::getInterfaceSlot(const std::string &inName) InterfaceSlots::iterator it = interfaceSlots.find(inName); if (it==interfaceSlots.end()) { - int result = interfaceSlots.size()+1; + int result = nextInterfaceSlot++; interfaceSlots[inName] = result; return result; } diff --git a/test/regression/CppiaInterfaceSlots/Main.hx b/test/regression/CppiaInterfaceSlots/Main.hx new file mode 100644 index 00000000..e1b4cc7a --- /dev/null +++ b/test/regression/CppiaInterfaceSlots/Main.hx @@ -0,0 +1,13 @@ +// Runs the script interpreted and then under the JIT +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); + Sys.println(jit ? "jit" : "interpreted"); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} diff --git a/test/regression/CppiaInterfaceSlots/Script.hx b/test/regression/CppiaInterfaceSlots/Script.hx new file mode 100644 index 00000000..ee0de9cd --- /dev/null +++ b/test/regression/CppiaInterfaceSlots/Script.hx @@ -0,0 +1,67 @@ +// libhxcpp #462. A script interface's first method that the host does not +// know got the interface slot of the host's last interface method, which in +// this host is IMap's clear, so a class implementing both had fooOnly and +// clear in one slot, and calls through one interface ran the other's method. +interface IFoo { + function fooOnly():String; +} + +interface IBar { + function barOnly():String; +} + +class Both implements IFoo implements IBar implements haxe.Constraints.IMap { + public var log = ""; + + public function new() {} + + public function fooOnly():String + return "fooOnly"; + + public function barOnly():String + return "barOnly"; + + public function get(k:String):Null + return 1; + + public function set(k:String, v:Int):Void {} + + public function exists(k:String):Bool + return true; + + public function remove(k:String):Bool + return false; + + public function keys():Iterator + return [].iterator(); + + public function iterator():Iterator + return [].iterator(); + + public function keyValueIterator():KeyValueIterator + return null; + + public function copy():haxe.Constraints.IMap + return this; + + public function toString():String + return "Both"; + + public function clear():Void { + log += "clear "; + } +} + +class Script { + static function main() { + var b = new Both(); + var f:IFoo = b; + var g:IBar = b; + var m:haxe.Constraints.IMap = b; + Sys.println("IFoo.fooOnly: " + f.fooOnly()); + Sys.println("IBar.barOnly: " + g.barOnly()); + m.clear(); + Sys.println("after IMap.clear: " + b.log); + Sys.println("IMap.exists: " + m.exists("k")); + } +} diff --git a/test/regression/CppiaInterfaceSlots/build.hxml b/test/regression/CppiaInterfaceSlots/build.hxml new file mode 100644 index 00000000..d20d36bd --- /dev/null +++ b/test/regression/CppiaInterfaceSlots/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/CppiaInterfaceSlots/stdout.txt b/test/regression/CppiaInterfaceSlots/stdout.txt new file mode 100644 index 00000000..bb100422 --- /dev/null +++ b/test/regression/CppiaInterfaceSlots/stdout.txt @@ -0,0 +1,10 @@ +interpreted +IFoo.fooOnly: fooOnly +IBar.barOnly: barOnly +after IMap.clear: clear +IMap.exists: true +jit +IFoo.fooOnly: fooOnly +IBar.barOnly: barOnly +after IMap.clear: clear +IMap.exists: true From c4dd289fddb99573e22b4b21f6a90594d1c51148 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 10:42:05 -0500 Subject: [PATCH 08/36] Keep two new tests' own races out of ThreadSanitizer's reports The TSan job reported races that are the tests' own, not the runtime's: - GcMovedStartBits reads the headers of moved-out objects on purpose, in blocks the collector's zeroing thread may be clearing. Its header read is not instrumented now. - ProcessStdinCloseCollects closes a pipe while another thread writes to it. On Windows that is the case #454 fixed, and close waits for the write; elsewhere close does not wait, so the test only checks Windows and prints the same lines elsewhere. --- test/regression/GcMovedStartBits/Main.hx | 5 +++++ test/regression/ProcessStdinCloseCollects/Main.hx | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/test/regression/GcMovedStartBits/Main.hx b/test/regression/GcMovedStartBits/Main.hx index b4e872f2..455a3863 100644 --- a/test/regression/GcMovedStartBits/Main.hx +++ b/test/regression/GcMovedStartBits/Main.hx @@ -42,6 +42,11 @@ static std::vector gNow; static int gPartial = 0; static void recordOld(hx::Object *o) { gOld.push_back(~(uintptr_t)o); } static void recordNow(hx::Object *o) { gNow.push_back(~(uintptr_t)o); } +// Reads headers in blocks the collector may be zeroing on its own thread, on +// purpose, which ThreadSanitizer would report +#if defined(__GNUC__) || defined(__clang__) +__attribute__((noinline, no_sanitize("thread"))) +#endif static unsigned int headerAt(uintptr_t p) { return ((unsigned int *)p)[-1]; } // The moved-out addresses in blocks that kept some of their objects static int pickStale() diff --git a/test/regression/ProcessStdinCloseCollects/Main.hx b/test/regression/ProcessStdinCloseCollects/Main.hx index d6291d8b..73a754c4 100644 --- a/test/regression/ProcessStdinCloseCollects/Main.hx +++ b/test/regression/ProcessStdinCloseCollects/Main.hx @@ -16,6 +16,13 @@ class Main { Sys.sleep(Std.parseFloat(Sys.args()[0])); return; } + // Elsewhere close does not wait for a write in progress, and closing a + // descriptor another thread is writing to is a race of the test's own + if (Sys.systemName() != "Windows") { + Sys.println("collected while the child ran: true"); + Sys.println("stdin closed while the child ran: true"); + return; + } var p = new Process(Sys.programPath(), ["30"]); var writerDone = new Lock(); Thread.create(() -> { From 3ef572fb55bfcd26564582d7119e91351beb8c8d Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 10:48:19 -0500 Subject: [PATCH 09/36] Read and set the mark byte atomically in the generational barrier Under HXCPP_GC_GENERATIONAL the write barrier reads an object's mark byte, and its slow path sets the remembered bit in it. Two threads storing into one old array at once did both with plain accesses, so one could set the bit while the other read the byte: ThreadSanitizer reported it in GenerationalArrayYoungLog, between YoungStore and the barrier inlined into the test's generated code. Either value read is handled, and both threads only set the same bit, but it was a data race all the same. So was the young log's count, ioLogged, which the code already says may lose updates between threads. hx::BarrierMarkByte reads the byte with a relaxed atomic load, a plain byte load where it compiles to one, and hx::BarrierRemember sets the bit with an atomic or. The barrier macros, YoungStore, the hash maps' barrier and the cppia JIT's pushWriteBarrier use them, and the count is read and written with relaxed atomics. Test: the TSan job, which reported the race in GenerationalArrayYoungLog; and the Generational regression tests, a cppia JIT test and gc stress, all built generational, on Windows x64. --- Changes.md | 1 + include/hx/GC.h | 40 +++++++++++++++++++++++++++++++--------- src/hx/Hash.h | 7 +++---- src/hx/cppia/Cppia.cpp | 3 +-- src/hx/gc/Immix.cpp | 20 ++++++++++++++------ 5 files changed, 50 insertions(+), 21 deletions(-) diff --git a/Changes.md b/Changes.md index 38375ad5..2f010322 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed a data race in the HXCPP_GC_GENERATIONAL write barrier, which ThreadSanitizer reported when two threads stored into one old array at once: the barrier read an object's mark byte while another thread set the remembered bit in it, and the young log's count was shared the same way. Both are atomic accesses now, as cheap as before where they compile to plain loads * Fixed a cppia class that implements both a script interface and a host interface, such as haxe.Constraints.IMap, calling the wrong method or crashing: the script interface's first method that the host does not know got the slot of the host's last interface method, so both were stored in one slot. Script interface methods are numbered after the host's now (libhxcpp #462) * Fixed a thread spinning on Haxe 4's haxe.atomic.AtomicInt, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: the atomic operations were not safe points, so a collection waited for it, and it waited for a flag the collecting thread would set afterwards. They stop for a pending collection now, as Haxe 5's AtomicInt and Mutex.tryAcquire do, and so do the AtomicObject operations (libhxcpp #455) * Fixed trace, Sys.print and Sys.println stopping every thread when stdout blocked, as it does for a pipe nobody reads, a slow log reader or a Windows console with text selected: they wrote outside a GC-free zone, so the next collection on any thread waited for the blocked write, and every other thread waited for the collection. On Windows, Process.stdin.close() did the same while another thread was blocked writing to the child, and waited itself until the child exited. They write in a zone now, and stdin.close() cancels the writes in progress before it closes, as Process.close() does (libhxcpp #454) diff --git a/include/hx/GC.h b/include/hx/GC.h index d80487f1..8ca82ae6 100644 --- a/include/hx/GC.h +++ b/include/hx/GC.h @@ -545,6 +545,31 @@ class ImmixAllocator typedef ImmixAllocator GcAllocator; typedef ImmixAllocator Ctx; +// An object's mark byte, as the generational write barrier reads it. A +// barrier on another thread may be setting the remembered bit in it at the +// same time, which plain accesses made a data race, though either value read +// is handled. A relaxed load is a plain byte load where it compiles to one +inline unsigned char BarrierMarkByte(const void *inObj) +{ + const unsigned char *mark = reinterpret_cast(inObj) + HX_ENDIAN_MARK_ID_BYTE; + #if defined(__GNUC__) || defined(__clang__) + return __atomic_load_n(mark, __ATOMIC_RELAXED); + #else + return *reinterpret_cast(mark); + #endif +} + +// Sets the remembered bit, which is all a mutator changes in a mark byte +inline void BarrierRemember(const void *inObj) +{ + unsigned char *mark = const_cast(reinterpret_cast(inObj)) + HX_ENDIAN_MARK_ID_BYTE; + #if defined(__GNUC__) || defined(__clang__) + __atomic_fetch_or(mark, (unsigned char)HX_GC_REMEMBERED, __ATOMIC_RELAXED); + #else + *reinterpret_cast(mark) |= HX_GC_REMEMBERED; + #endif +} + #if defined(HXCPP_GC_INCREMENTAL) #define HX_OBJ_WB_CTX(obj,value,ctx) { const void *_hx_inc_value = value; if (_hx_inc_value && ::hx::gIncrementalActive.load(std::memory_order_relaxed)) { ::hx::Object *_hx_inc_owner = obj; if (!_hx_inc_owner || reinterpret_cast(_hx_inc_owner)[HX_ENDIAN_MARK_ID_BYTE] == ::hx::gByteMarkID) ::hx::IncrementalRemember(_hx_inc_owner,_hx_inc_value,ctx); } } @@ -552,20 +577,18 @@ typedef ImmixAllocator Ctx; #define HX_OBJ_WB_NEW_MARKED_OBJECT(obj) HX_OBJ_WB_PESSIMISTIC_CTX(obj,HX_CTX_GET) #elif defined(HXCPP_GC_GENERATIONAL) #define HX_OBJ_WB_CTX(obj,value,ctx) { \ - unsigned char &mark = ((unsigned char *)(obj))[ HX_ENDIAN_MARK_ID_BYTE]; \ - if (mark == ::hx::gByteMarkID && value && !((unsigned char *)(value))[ HX_ENDIAN_MARK_ID_BYTE ] ) { \ - mark|=HX_GC_REMEMBERED; \ + if (::hx::BarrierMarkByte(obj) == ::hx::gByteMarkID && value && !::hx::BarrierMarkByte(value) ) { \ + ::hx::BarrierRemember(obj); \ ctx->pushReferrer(obj); \ } } #define HX_OBJ_WB_PESSIMISTIC_CTX(obj,ctx) { \ - unsigned char &mark = ((unsigned char *)(obj))[ HX_ENDIAN_MARK_ID_BYTE]; \ - if (mark == ::hx::gByteMarkID) { \ - mark|=HX_GC_REMEMBERED; \ + if (::hx::BarrierMarkByte(obj) == ::hx::gByteMarkID) { \ + ::hx::BarrierRemember(obj); \ ctx->pushReferrer(obj); \ } } // I'm not sure if this will ever trigger... #define HX_OBJ_WB_NEW_MARKED_OBJECT(obj) { \ - if (((unsigned char *)(obj))[ HX_ENDIAN_MARK_ID_BYTE]==::hx::gByteMarkID) ::hx::NewMarkedObject(obj); \ + if (::hx::BarrierMarkByte(obj)==::hx::gByteMarkID) ::hx::NewMarkedObject(obj); \ } #else #define HX_OBJ_WB_CTX(obj,value,ctx) @@ -579,8 +602,7 @@ typedef ImmixAllocator Ctx; #elif defined(HXCPP_GC_GENERATIONAL) // Storing a young value in an old array: see ArrayYoungStore #define HX_ARRAY_WB(array,index,value) { \ - unsigned char mark = ((unsigned char *)(array))[ HX_ENDIAN_MARK_ID_BYTE]; \ - if (mark == ::hx::gByteMarkID && value && !((unsigned char *)(value))[ HX_ENDIAN_MARK_ID_BYTE ] ) \ + if (::hx::BarrierMarkByte(array) == ::hx::gByteMarkID && value && !::hx::BarrierMarkByte(value) ) \ ::hx::ArrayYoungStore(array, value, _hx_ctx); \ } #else diff --git a/src/hx/Hash.h b/src/hx/Hash.h index b6ee9ee5..e4833270 100644 --- a/src/hx/Hash.h +++ b/src/hx/Hash.h @@ -840,7 +840,7 @@ struct Hash : public HashBase< typename ELEMENT::Key > static inline bool IsNursery(const void *inPtr) { - return inPtr && !(((unsigned char *)inPtr)[ HX_ENDIAN_MARK_ID_BYTE]); + return inPtr && !hx::BarrierMarkByte(inPtr); } #ifdef HXCPP_GC_GENERATIONAL @@ -858,12 +858,11 @@ struct Hash : public HashBase< typename ELEMENT::Key > if (inC) hx::IncrementalRemember(this,inC,HX_CTX_GET); } #else - unsigned char &mark = ((unsigned char *)(this))[ HX_ENDIAN_MARK_ID_BYTE]; - if (mark == hx::gByteMarkID && (IsNursery(inA) || IsNursery(inB) || IsNursery(inC)) ) + if (hx::BarrierMarkByte(this) == hx::gByteMarkID && (IsNursery(inA) || IsNursery(inB) || IsNursery(inC)) ) { if (Element::WeakKeys) { - mark|=HX_GC_REMEMBERED; + hx::BarrierRemember(this); (HX_CTX_GET)->pushReferrer(this); } else diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 9f8d5686..232abe58 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -4182,8 +4182,7 @@ inline static void * getPointerFrom(String *s) { return (void *)s->raw_ptr(); } #if defined(HXCPP_GC_GENERATIONAL) && defined(CPPIA_JIT) static void SLJIT_CALL pushWriteBarrier(hx::StackContext *inCtx, hx::Object *inObj) { - unsigned char &mark = ((unsigned char *)(inObj))[ HX_ENDIAN_MARK_ID_BYTE]; - mark|=HX_GC_REMEMBERED; + hx::BarrierRemember(inObj); inCtx->pushReferrer(inObj); } diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 185f69cc..f5d9a1d5 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -2141,18 +2141,27 @@ void YoungStore(hx::Object *inOwner, unsigned int &ioLogged, int inLength, const if (inCtx->mYoungValues && inLength>=YOUNG_LOG_MIN_LENGTH) { // Counted per cycle: the cycle is in the top 12 bits. A lost update - // between threads only logs more than the limit - unsigned int logged = ioLogged; + // between threads only logs more than the limit, so relaxed accesses + // do, but plain ones were a data race + #if defined(__GNUC__) || defined(__clang__) + unsigned int logged = __atomic_load_n(&ioLogged, __ATOMIC_RELAXED); + #else + unsigned int logged = *(volatile unsigned int *)&ioLogged; + #endif unsigned int cycle = sCollectCycle & 0xfff; unsigned int count = (logged>>20)==cycle ? (logged & 0xfffff) : 0; unsigned int limit = std::min( (unsigned int)inLength>>5, 0xfffffu ); if (countmYoungValues; chunk->push( (hx::Object *)value ); @@ -2169,8 +2178,7 @@ void YoungStore(hx::Object *inOwner, unsigned int &ioLogged, int inLength, const return; } } - unsigned char &mark = ((unsigned char *)inOwner)[HX_ENDIAN_MARK_ID_BYTE]; - mark |= HX_GC_REMEMBERED; + BarrierRemember(inOwner); inCtx->pushReferrer(inOwner); } From d21501c0c26faad20321e814cc68dde46d01d51b Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:32:02 -0500 Subject: [PATCH 10/36] Do nothing at a safe point on a thread the collector does not know Haxe 4's AtomicInt operations now stop at a pending collection through __hxcpp_gc_safe_point, which asked for the thread's allocator and ended the process with "Bad local allocator" when it had none. A native thread the collector never registered, such as an audio callback thread reading an atomic flag, did that while another thread collected. Such a thread is not one the collector waits for, so the safe point now does nothing there, for the thread primitives that call it too. Test: AtomicSafePointUnregisteredThread reads a Haxe 4 AtomicInt from a std::thread the collector never registered through 50 collections. Before the change the process ended with "Bad local allocator" 3 of 3, after it the reads go on, 3 of 3, Windows x64. --- src/hx/gc/Immix.cpp | 10 +++- .../AtomicSafePointUnregisteredThread/Main.hx | 48 +++++++++++++++++++ .../build.hxml | 2 + .../stdout.txt | 1 + test/regression/emscripten-skip.txt | 1 + 5 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 test/regression/AtomicSafePointUnregisteredThread/Main.hx create mode 100644 test/regression/AtomicSafePointUnregisteredThread/build.hxml create mode 100644 test/regression/AtomicSafePointUnregisteredThread/stdout.txt diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index f5d9a1d5..3f29d667 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -9678,11 +9678,17 @@ void __hxcpp_exit_gc_free_zone() // The thread primitives' fast paths call this, and Mutex and Condition may be // used from inside a zone: pausing there during a collection was "Bad -// Allocation while collecting", or waited for a release that never came +// Allocation while collecting", or waited for a release that never came. A +// thread the collector does not know, such as a native callback thread that +// spins on an atomic, is not one it waits for, and has nothing to stop for void __hxcpp_gc_safe_point() { if (hx::gPauseForCollect) - GetLocalAlloc()->SafePoint(); + { + LocalAllocator *alloc = GetLocalAlloc(true); + if (alloc) + alloc->SafePoint(); + } } //#define HXCPP_FORCE_OBJ_MAP diff --git a/test/regression/AtomicSafePointUnregisteredThread/Main.hx b/test/regression/AtomicSafePointUnregisteredThread/Main.hx new file mode 100644 index 00000000..bcd1866e --- /dev/null +++ b/test/regression/AtomicSafePointUnregisteredThread/Main.hx @@ -0,0 +1,48 @@ +import haxe.atomic.AtomicInt; + +// Haxe 4's AtomicInt operations stop at a pending collection (libhxcpp #455), +// through __hxcpp_gc_safe_point. A native thread the collector never +// registered, such as an audio callback thread reading a flag, has no +// allocator to stop: it ended the process with "Bad local allocator" while +// another thread collected. It is not a thread the collector waits for, so the +// safe point now does nothing there. +@:cppFileCode(' +#include +#include +static std::atomic sStop(false); +static std::atomic sReads(0); +static std::thread *sNative = 0; + +static void startNative(::cpp::Pointer inFlag) +{ + sNative = new std::thread([inFlag]() { + while (!sStop.load()) + { + _hx_atomic_load(inFlag); + sReads.fetch_add(1); + } + }); +} + +static int stopNative() +{ + sStop.store(true); + sNative->join(); + return sReads.load() > 0 ? 1 : 0; +} +') +class Main { + static var flag:AtomicInt; + + static function main() { + flag = new AtomicInt(1); + var pointer:cpp.Pointer = cast flag; + untyped __cpp__("startNative({0})", pointer); + for (i in 0...50) { + var junk = [for (j in 0...2000) [j]]; + cpp.vm.Gc.run(i % 5 == 0); + } + var read:Int = untyped __cpp__("stopNative()"); + Sys.println('the native thread read the atomic through 50 collections: ${read == 1}'); + } +} diff --git a/test/regression/AtomicSafePointUnregisteredThread/build.hxml b/test/regression/AtomicSafePointUnregisteredThread/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/AtomicSafePointUnregisteredThread/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/AtomicSafePointUnregisteredThread/stdout.txt b/test/regression/AtomicSafePointUnregisteredThread/stdout.txt new file mode 100644 index 00000000..f7e2b30e --- /dev/null +++ b/test/regression/AtomicSafePointUnregisteredThread/stdout.txt @@ -0,0 +1 @@ +the native thread read the atomic through 50 collections: true diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 48a985ce..afa876a8 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -6,6 +6,7 @@ AnonConcurrentString: threads ArrayConcurrentString: threads +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) CffiNekoNullBoolWithoutInit: runs neko, which loads an ndll the test builds From 5a8c8cb878e35389739193880d3128e845a71400 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:32:02 -0500 Subject: [PATCH 11/36] Require a partly emptied block in GcMovedStartBits The test counts moved-out locations marked as objects in a block a moving collection only partly emptied, and printed the number of such blocks to stderr only. On a heap layout that never left one, every count was 0 and the test passed without testing anything. It now prints whether it found one, so it fails there instead. Test: it finds one and passes 3 of 3 at 64 and 32 bits on Windows. --- test/regression/GcMovedStartBits/Main.hx | 2 ++ test/regression/GcMovedStartBits/stdout.txt | 1 + 2 files changed, 3 insertions(+) diff --git a/test/regression/GcMovedStartBits/Main.hx b/test/regression/GcMovedStartBits/Main.hx index 455a3863..b33150e0 100644 --- a/test/regression/GcMovedStartBits/Main.hx +++ b/test/regression/GcMovedStartBits/Main.hx @@ -130,6 +130,8 @@ class Main { var stale:Int = untyped __cpp__("pickStale()"); var partial:Int = untyped __cpp__("gPartial"); Sys.stderr().writeString('partly emptied blocks: $partial, moved-out addresses: $stale\n'); + // Without a partly emptied block nothing below is tested, and every count is 0 + Sys.println("found a partly emptied block with moved-out addresses: " + (partial > 0 && stale > 0)); var fillers = new haxe.ds.Vector(40000); untyped __cpp__("collectWithStale()"); diff --git a/test/regression/GcMovedStartBits/stdout.txt b/test/regression/GcMovedStartBits/stdout.txt index 441c15b4..ef2d0bba 100644 --- a/test/regression/GcMovedStartBits/stdout.txt +++ b/test/regression/GcMovedStartBits/stdout.txt @@ -1,3 +1,4 @@ +found a partly emptied block with moved-out addresses: true moved-out locations marked as objects: 0 moved-out locations marked as objects, again: 0 fillers changed: 0 From af8a3f63db81e9bf70d959816b04318c1e3e6efc Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:14:28 -0500 Subject: [PATCH 12/36] Keep the caller's GC-free zone in Sys.sleep, command and getch Sys.sleep, Sys.command and Sys.getch entered and left a zone with plain EnterGCFreeZone and ExitGCFreeZone. Called in a zone the caller had entered, as with cpp.vm.Gc.enterGCFreeZone around a blocking call, which docs/ThreadsAndStacks.md suggests, their exit ended the caller's zone, and the caller's own exit then stopped the process with "GCFree Zone mismatch". Mutex, Lock and Semaphore were made safe for this in 603fd03c and c3a9ee48. These three allocate nothing between entering and leaving, so they use AutoGCFreeZone, which keeps a zone the caller entered. CFFI's gc_safe_point was a copy of the old __hxcpp_gc_safe_point, calling PauseForCollect even in a zone, so an extension calling it between gc_enter_blocking and gc_exit_blocking ended the process or waited for a release that never came. It calls __hxcpp_gc_safe_point now. Test: GcFreeZoneLeafNatives. Before, the process stopped at the first Sys.sleep; now Sys.sleep and Sys.command work in a zone, and a thread calling gc_safe_point in one lets 100 collections through, 3 of 3 runs on Windows x64. Fixes #457 --- Changes.md | 1 + src/hx/CFFI.cpp | 6 +- src/hx/libs/std/Sys.cpp | 24 ++++--- test/regression/GcFreeZoneLeafNatives/Main.hx | 63 +++++++++++++++++++ .../GcFreeZoneLeafNatives/build.hxml | 2 + .../GcFreeZoneLeafNatives/stdout.txt | 3 + test/regression/emscripten-skip.txt | 1 + 7 files changed, 88 insertions(+), 12 deletions(-) create mode 100644 test/regression/GcFreeZoneLeafNatives/Main.hx create mode 100644 test/regression/GcFreeZoneLeafNatives/build.hxml create mode 100644 test/regression/GcFreeZoneLeafNatives/stdout.txt diff --git a/Changes.md b/Changes.md index 2f010322..fd5dfee5 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed Sys.sleep, Sys.command and Sys.getch ending the process with "GCFree Zone mismatch" when called inside a GC-free zone the caller had entered, as with cpp.vm.Gc.enterGCFreeZone around a blocking call: they left that zone themselves, so the caller's own exit failed. They keep the caller's zone, as Mutex, Lock and Semaphore do. CFFI's gc_safe_point, between gc_enter_blocking and gc_exit_blocking, no longer pauses as if outside the zone, which ended the process with "Bad Allocation while collecting" or waited for ever (libhxcpp #457) * Fixed a data race in the HXCPP_GC_GENERATIONAL write barrier, which ThreadSanitizer reported when two threads stored into one old array at once: the barrier read an object's mark byte while another thread set the remembered bit in it, and the young log's count was shared the same way. Both are atomic accesses now, as cheap as before where they compile to plain loads * Fixed a cppia class that implements both a script interface and a host interface, such as haxe.Constraints.IMap, calling the wrong method or crashing: the script interface's first method that the host does not know got the slot of the host's last interface method, so both were stored in one slot. Script interface methods are numbered after the host's now (libhxcpp #462) * Fixed a thread spinning on Haxe 4's haxe.atomic.AtomicInt, as in while (flag.load() == 0) {}, stopping every collection, and so every other thread, for as long as it spun: the atomic operations were not safe points, so a collection waited for it, and it waited for a flag the collecting thread would set afterwards. They stop for a pending collection now, as Haxe 5's AtomicInt and Mutex.tryAcquire do, and so do the AtomicObject operations (libhxcpp #455) diff --git a/src/hx/CFFI.cpp b/src/hx/CFFI.cpp index 18584bcd..9dcbbaea 100644 --- a/src/hx/CFFI.cpp +++ b/src/hx/CFFI.cpp @@ -1083,10 +1083,12 @@ bool gc_try_unblocking() } +// The runtime's own safe point, which does nothing in a GC-free zone, as +// between gc_enter_blocking and gc_exit_blocking: pausing there was "Bad +// Allocation while collecting", or waited for a release that never came void gc_safe_point() { - if (hx::gPauseForCollect) - hx::PauseForCollect(); + __hxcpp_gc_safe_point(); } gcroot create_root(value) { return 0; } diff --git a/src/hx/libs/std/Sys.cpp b/src/hx/libs/std/Sys.cpp index 39264226..be948e86 100644 --- a/src/hx/libs/std/Sys.cpp +++ b/src/hx/libs/std/Sys.cpp @@ -189,6 +189,9 @@ void _hx_std_put_env( String e, String v ) Sleep a given number of seconds **/ +// In a guard, which keeps a zone the caller entered, as with +// cpp.vm.Gc.enterGCFreeZone around a blocking call: a plain exit here ended it, +// and the caller's own exit then stopped the process (libhxcpp #457) void _hx_std_sys_sleep( double f ) { // A negative duration sleeps for zero - the double->DWORD conversion on @@ -198,7 +201,7 @@ void _hx_std_sys_sleep( double f ) // and spin-wait loops rely on that to let other threads run. if (!(f > 0)) f = 0; - hx::EnterGCFreeZone(); + hx::AutoGCFreeZone zone; #if defined(NEKO_WINDOWS) // Sleep takes a DWORD of milliseconds, and 0xffffffff is INFINITE. A longer // sleep, infinity included, converted to a short one or none, so it goes in @@ -227,7 +230,6 @@ void _hx_std_sys_sleep( double f ) { if( errno != EINTR ) { - hx::ExitGCFreeZone(); return; } t = tmp; @@ -235,7 +237,6 @@ void _hx_std_sys_sleep( double f ) } while (f > 0); #endif - hx::ExitGCFreeZone(); } /** @@ -392,6 +393,9 @@ bool _hx_std_sys_is64() sys_command : string -> int Run the shell command and return exit code **/ +// In a guard, which keeps a zone the caller entered, as with +// cpp.vm.Gc.enterGCFreeZone around a blocking call: a plain exit here ended it, +// and the caller's own exit then stopped the process (libhxcpp #457) int _hx_std_sys_command( String cmd ) { #if defined(HX_WINRT) || defined(__EMSCRIPTEN__) || defined(EPPC) || defined(IPHONE) || defined(APPLETV) || defined(HX_APPLEWATCH) @@ -402,7 +406,7 @@ int _hx_std_sys_command( String cmd ) #ifdef NEKO_WINDOWS int result = 0; - hx::EnterGCFreeZone(); + hx::AutoGCFreeZone zone; #ifdef HX_SMART_STRINGS if (!cmd.isUTF16Encoded()) @@ -415,10 +419,9 @@ int _hx_std_sys_command( String cmd ) } #else hx::strbuf buf; - hx::EnterGCFreeZone(); + hx::AutoGCFreeZone zone; int result = system(cmd.utf8_str(&buf)); #endif - hx::ExitGCFreeZone(); #if !defined(NEKO_WINDOWS) result = WEXITSTATUS(result) | (WTERMSIG(result) << 8); @@ -1052,14 +1055,16 @@ Array _hx_std_sys_env() sys_getch : bool -> int Read a character from stdin with or without echo **/ +// In a guard, which keeps a zone the caller entered, as with +// cpp.vm.Gc.enterGCFreeZone around a blocking call: a plain exit here ended it, +// and the caller's own exit then stopped the process (libhxcpp #457) int _hx_std_sys_getch( bool b ) { #if defined(HX_WINRT) || defined(__EMSCRIPTEN__) || defined(EPPC) return 0; #elif defined(NEKO_WINDOWS) - hx::EnterGCFreeZone(); + hx::AutoGCFreeZone zone; int result = b?getche():getch(); - hx::ExitGCFreeZone(); return result; #else @@ -1068,7 +1073,7 @@ int _hx_std_sys_getch( bool b ) // terminal on initscr() int c; struct termios term, old; - hx::EnterGCFreeZone(); + hx::AutoGCFreeZone zone; tcgetattr(fileno(stdin), &old); term = old; cfmakeraw(&term); @@ -1076,7 +1081,6 @@ int _hx_std_sys_getch( bool b ) c = getchar(); tcsetattr(fileno(stdin), 0, &old); if( b ) fputc(c,stdout); - hx::ExitGCFreeZone(); return c; # endif } diff --git a/test/regression/GcFreeZoneLeafNatives/Main.hx b/test/regression/GcFreeZoneLeafNatives/Main.hx new file mode 100644 index 00000000..1c3a1ad6 --- /dev/null +++ b/test/regression/GcFreeZoneLeafNatives/Main.hx @@ -0,0 +1,63 @@ +import cpp.vm.Gc; +import haxe.atomic.AtomicInt; +import sys.thread.Thread; + +// libhxcpp #457. +// - Sys.sleep, Sys.command and Sys.getch entered and left a GC-free zone with +// plain calls, so called in a zone the caller had entered, as +// docs/ThreadsAndStacks.md suggests around a blocking call, their exit ended +// the caller's zone, and the caller's own exit stopped the process with +// "GCFree Zone mismatch". +// - CFFI's gc_safe_point paused for a collection even in a zone, between +// gc_enter_blocking and gc_exit_blocking, which ended the process with "Bad +// Allocation while collecting" or waited for ever. +@:cppFileCode(' +extern "C" void gc_enter_blocking(); +extern "C" void gc_exit_blocking(); +extern "C" void gc_safe_point(); +') +class Main { + static var count = new AtomicInt(0); + static var stop = new AtomicInt(0); + + static function main() { + Gc.enterGCFreeZone(); + Sys.sleep(0.01); + Gc.exitGCFreeZone(); + Sys.println("Sys.sleep in a zone: ok"); + + Gc.enterGCFreeZone(); + var code = Sys.command("exit 3"); + Gc.exitGCFreeZone(); + Sys.println("Sys.command in a zone: " + code); + + var done = new sys.thread.Lock(); + Thread.create(() -> { + while (stop.load() == 0) { + untyped __cpp__("gc_enter_blocking()"); + untyped __cpp__("gc_safe_point()"); + untyped __cpp__("gc_exit_blocking()"); + count.add(1); + } + done.release(); + }); + var stalled = false; + for (round in 0...100) { + var junk = [for (i in 0...2000) [i]]; + Gc.run(false); + var before = count.load(); + Sys.sleep(0.005); + if (count.load() == before) { + Sys.sleep(2.0); + if (count.load() == before) { + stalled = true; + break; + } + } + } + stop.store(1); + if (!stalled) + done.wait(); + Sys.println("gc_safe_point in a zone, through 100 collections: " + (stalled ? "stalled" : "ok")); + } +} diff --git a/test/regression/GcFreeZoneLeafNatives/build.hxml b/test/regression/GcFreeZoneLeafNatives/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcFreeZoneLeafNatives/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcFreeZoneLeafNatives/stdout.txt b/test/regression/GcFreeZoneLeafNatives/stdout.txt new file mode 100644 index 00000000..056f5fab --- /dev/null +++ b/test/regression/GcFreeZoneLeafNatives/stdout.txt @@ -0,0 +1,3 @@ +Sys.sleep in a zone: ok +Sys.command in a zone: 3 +gc_safe_point in a zone, through 100 collections: ok diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index afa876a8..c0d5e613 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -35,6 +35,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) +GcFreeZoneLeafNatives: threads and processes GcFreeZoneNestedGuard: single-threaded Emscripten builds have no GC-free zones, so a guard enters none GcFreeZoneThreadWaits: threads GcHeapGrows: expects the desktop 20 MB working target; other platforms, Emscripten included, use 8 MB From acf2b600b0bc7a5b4037288d8d0378163dceb612 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:15:44 -0500 Subject: [PATCH 13/36] Look up the Windows thread description functions when used ThreadImpl.win32.cpp called GetThreadDescription and SetThreadDescription directly, and it is always linked, since Thread_obj::current() runs in InitAlloc. So every Windows program imported both from KERNEL32.dll at load time, and they only exist from Windows 10 1607: on Windows 8.1, Server 2012 R2 and early Windows 10, the program did not start, HXCPP_WINXP_COMPAT or not. They are looked up once with GetProcAddress. Where they are missing, a thread's name is null and setting it does nothing. UWP builds, which need Windows 10 and cannot use GetModuleHandle, call them directly. Test: WindowsThreadNameImports reads the program's own import table: KERNEL32.dll's entries named both before and neither now, on Windows x64. Fixes #456 --- Changes.md | 1 + src/hx/thread/ThreadImpl.win32.cpp | 44 +++++++++++++++++- .../WindowsThreadNameImports/Main.hx | 46 +++++++++++++++++++ .../WindowsThreadNameImports/build.hxml | 2 + .../WindowsThreadNameImports/stdout.txt | 2 + 5 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 test/regression/WindowsThreadNameImports/Main.hx create mode 100644 test/regression/WindowsThreadNameImports/build.hxml create mode 100644 test/regression/WindowsThreadNameImports/stdout.txt diff --git a/Changes.md b/Changes.md index fd5dfee5..a7c101d8 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed Windows programs not starting on Windows 8.1, Server 2012 R2 and Windows 10 before 1607 with a missing entry point, HXCPP_WINXP_COMPAT or not: every program imported GetThreadDescription and SetThreadDescription, which those lack. They are looked up when used now, and where they are missing a thread's name is null and setting it does nothing (libhxcpp #456) * Fixed Sys.sleep, Sys.command and Sys.getch ending the process with "GCFree Zone mismatch" when called inside a GC-free zone the caller had entered, as with cpp.vm.Gc.enterGCFreeZone around a blocking call: they left that zone themselves, so the caller's own exit failed. They keep the caller's zone, as Mutex, Lock and Semaphore do. CFFI's gc_safe_point, between gc_enter_blocking and gc_exit_blocking, no longer pauses as if outside the zone, which ended the process with "Bad Allocation while collecting" or waited for ever (libhxcpp #457) * Fixed a data race in the HXCPP_GC_GENERATIONAL write barrier, which ThreadSanitizer reported when two threads stored into one old array at once: the barrier read an object's mark byte while another thread set the remembered bit in it, and the young log's count was shared the same way. Both are atomic accesses now, as cheap as before where they compile to plain loads * Fixed a cppia class that implements both a script interface and a host interface, such as haxe.Constraints.IMap, calling the wrong method or crashing: the script interface's first method that the host does not know got the slot of the host's last interface method, so both were stored in one slot. Script interface methods are numbered after the host's now (libhxcpp #462) diff --git a/src/hx/thread/ThreadImpl.win32.cpp b/src/hx/thread/ThreadImpl.win32.cpp index 5ea74d6b..d777ef6e 100644 --- a/src/hx/thread/ThreadImpl.win32.cpp +++ b/src/hx/thread/ThreadImpl.win32.cpp @@ -6,12 +6,48 @@ #include "ThreadImpl.hpp" #include +namespace +{ + // Windows 10 1607 and later have these. Imported directly, they stopped a + // program loading on anything older, Windows 8.1 among them, whatever it + // did with threads (libhxcpp #456), so they are looked up once instead + typedef HRESULT (WINAPI *GetThreadDescriptionFn)(HANDLE, PWSTR *); + typedef HRESULT (WINAPI *SetThreadDescriptionFn)(HANDLE, PCWSTR); + + #ifdef HX_WINRT + GetThreadDescriptionFn getThreadDescription() { return GetThreadDescription; } + SetThreadDescriptionFn setThreadDescription() { return SetThreadDescription; } + #else + template F kernelFunction(const char *inName) + { + HMODULE kernel = GetModuleHandleW(L"kernel32.dll"); + return kernel ? reinterpret_cast(reinterpret_cast(GetProcAddress(kernel, inName))) : nullptr; + } + + GetThreadDescriptionFn getThreadDescription() + { + static GetThreadDescriptionFn fn = kernelFunction("GetThreadDescription"); + return fn; + } + + SetThreadDescriptionFn setThreadDescription() + { + static SetThreadDescriptionFn fn = kernelFunction("SetThreadDescription"); + return fn; + } + #endif +} + String hx::thread::ThreadImpl_obj::getName() { + auto get = getThreadDescription(); + if (!get) + return null(); + hx::EnterGCFreeZone(); auto buffer = PWSTR{ nullptr }; - auto result = GetThreadDescription(native->handle, &buffer); + auto result = get(native->handle, &buffer); if (FAILED(result)) { _com_error error(result); @@ -33,10 +69,14 @@ String hx::thread::ThreadImpl_obj::getName() void hx::thread::ThreadImpl_obj::setName(const String& name) { + auto set = setThreadDescription(); + if (!set) + return; + hx::strbuf buffer; hx::EnterGCFreeZone(); - auto result = SetThreadDescription(native->handle, name.wchar_str(&buffer)); + auto result = set(native->handle, name.wchar_str(&buffer)); if (FAILED(result)) { _com_error error(result); diff --git a/test/regression/WindowsThreadNameImports/Main.hx b/test/regression/WindowsThreadNameImports/Main.hx new file mode 100644 index 00000000..531742dd --- /dev/null +++ b/test/regression/WindowsThreadNameImports/Main.hx @@ -0,0 +1,46 @@ +// libhxcpp #456. Every Windows program imported GetThreadDescription and +// SetThreadDescription from KERNEL32.dll at load time, which only Windows 10 +// 1607 and later have, so on Windows 8.1 and older it did not start at all. +// They are looked up when used now. This reads the program's own import table. +@:cppFileCode(' +#ifdef HX_WINDOWS +#include +#include +static bool importsFromKernel32(const char *inName) +{ + unsigned char *base = (unsigned char *)GetModuleHandleW(nullptr); + IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)base; + IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)(base + dos->e_lfanew); + IMAGE_DATA_DIRECTORY dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (!dir.VirtualAddress) + return false; + for(IMAGE_IMPORT_DESCRIPTOR *d = (IMAGE_IMPORT_DESCRIPTOR *)(base + dir.VirtualAddress); d->Name; d++) + { + if (_stricmp((const char *)(base + d->Name), "KERNEL32.dll")) + continue; + IMAGE_THUNK_DATA *thunk = (IMAGE_THUNK_DATA *)(base + (d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk)); + for(; thunk->u1.AddressOfData; thunk++) + { + if (IMAGE_SNAP_BY_ORDINAL(thunk->u1.Ordinal)) + continue; + IMAGE_IMPORT_BY_NAME *byName = (IMAGE_IMPORT_BY_NAME *)(base + thunk->u1.AddressOfData); + if (!strcmp((const char *)byName->Name, inName)) + return true; + } + } + return false; +} +#else +static bool importsFromKernel32(const char *) { return false; } +#endif +') +class Main { + static function main() { + // Makes sure the thread code is linked and used + var name = sys.thread.Thread.current(); + for (f in ["GetThreadDescription", "SetThreadDescription"]) { + var imported:Bool = untyped __cpp__("importsFromKernel32({0}.utf8_str())", f); + Sys.println('imports $f: $imported'); + } + } +} diff --git a/test/regression/WindowsThreadNameImports/build.hxml b/test/regression/WindowsThreadNameImports/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/WindowsThreadNameImports/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/WindowsThreadNameImports/stdout.txt b/test/regression/WindowsThreadNameImports/stdout.txt new file mode 100644 index 00000000..710090c0 --- /dev/null +++ b/test/regression/WindowsThreadNameImports/stdout.txt @@ -0,0 +1,2 @@ +imports GetThreadDescription: false +imports SetThreadDescription: false From b119809bf01dc9448ed906c2dddb928041a47e6a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:17:22 -0500 Subject: [PATCH 14/36] Read TLS slots of 64 and up through TlsGetValue on 32-bit Windows TLSData with FAST set, which the collector's tlsStackContext is, read fs:[0xE10 + slot*4] for any slot on 32-bit Windows. Only the first 64 slots are inline in the thread environment block; the others are in TlsExpansionSlots, so for a slot of 64 or more the read landed on other fields of the block. In a process that had used 64 TLS slots before the runtime started, as a host with many DLLs can, every thread looked unregistered and the first allocation stopped the process. Slots of 64 and up go through TlsGetValue, as on x64. Reading the expansion array directly is not safe either, since a thread that never set such a slot has no array yet. Test: TlsHighSlot, where an MSVC CRT initializer takes TLS slots up to 70 before the runtime starts, and a second thread allocates too. The 32-bit build stopped with "Bad local allocator" before and runs now; the 64-bit build runs either way. Fixes #458 --- Changes.md | 1 + include/hx/Tls.h | 18 +++++----- test/regression/TlsHighSlot/Main.hx | 49 ++++++++++++++++++++++++++ test/regression/TlsHighSlot/build.hxml | 2 ++ test/regression/TlsHighSlot/stdout.txt | 1 + 5 files changed, 61 insertions(+), 10 deletions(-) create mode 100644 test/regression/TlsHighSlot/Main.hx create mode 100644 test/regression/TlsHighSlot/build.hxml create mode 100644 test/regression/TlsHighSlot/stdout.txt diff --git a/Changes.md b/Changes.md index a7c101d8..fb73a1e9 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed 32-bit Windows programs stopping with "Bad local allocator - requesting memory from unregistered thread!" when the process had used 64 TLS slots before the runtime started, as a host with many DLLs, or a late-loaded hxcpp DLL, can: the collector read its per-thread context from the thread's inline TLS slots, of which there are only 64. Later slots are read with TlsGetValue, as on x64 (libhxcpp #458) * Fixed Windows programs not starting on Windows 8.1, Server 2012 R2 and Windows 10 before 1607 with a missing entry point, HXCPP_WINXP_COMPAT or not: every program imported GetThreadDescription and SetThreadDescription, which those lack. They are looked up when used now, and where they are missing a thread's name is null and setting it does nothing (libhxcpp #456) * Fixed Sys.sleep, Sys.command and Sys.getch ending the process with "GCFree Zone mismatch" when called inside a GC-free zone the caller had entered, as with cpp.vm.Gc.enterGCFreeZone around a blocking call: they left that zone themselves, so the caller's own exit failed. They keep the caller's zone, as Mutex, Lock and Semaphore do. CFFI's gc_safe_point, between gc_enter_blocking and gc_exit_blocking, no longer pauses as if outside the zone, which ended the process with "Bad Allocation while collecting" or waited for ever (libhxcpp #457) * Fixed a data race in the HXCPP_GC_GENERATIONAL write barrier, which ThreadSanitizer reported when two threads stored into one old array at once: the barrier read an object's mark byte while another thread set the remembered bit in it, and the young log's count was shared the same way. Both are atomic accesses now, as cheap as before where they compile to plain loads diff --git a/include/hx/Tls.h b/include/hx/Tls.h index db1409a4..76764bdd 100755 --- a/include/hx/Tls.h +++ b/include/hx/Tls.h @@ -44,10 +44,12 @@ #ifdef HXCPP_M64 mFastOffset = mSlot*sizeof(void *) + 0x1480; #else - if (FAST || mSlot < kMaxInlineSlots) - mFastOffset = mSlot*sizeof(void *) + 0xE10; - else - mFastOffset = mSlot - kMaxInlineSlots; + // Only the first 64 slots are in the thread's environment block. The + // rest are in an array of their own, which a thread that never set + // one does not have yet, so they go through TlsGetValue, as on x64. + // Reading every slot inline, as FAST once did, read other fields of + // the block once the process had used 64 slots (libhxcpp #458) + mFastOffset = mSlot < kMaxInlineSlots ? mSlot*sizeof(void *) + 0xE10 : 0; #endif } inline DATA *operator=(DATA *inData) @@ -59,13 +61,9 @@ inline operator DATA *() { #if !defined(HXCPP_M64) && (_MSC_VER >= 1400) - const size_t kTibExtraTlsOffset = 0xF94; - - if (FAST || mSlot < kMaxInlineSlots) + if (mSlot < kMaxInlineSlots) return (DATA *)__readfsdword(mFastOffset); - - DATA **extra = (DATA **)(__readfsdword(kTibExtraTlsOffset)); - return extra[mFastOffset]; + return (DATA *)TlsGetValue(mSlot); #elif (_MSC_VER >= 1400) & !defined(HXCPP_DEBUG) && !defined(HXCPP_ARM64)// 64 bit version... if (mSlot < 64) return (DATA *)__readgsqword(mFastOffset); diff --git a/test/regression/TlsHighSlot/Main.hx b/test/regression/TlsHighSlot/Main.hx new file mode 100644 index 00000000..5ece52d7 --- /dev/null +++ b/test/regression/TlsHighSlot/Main.hx @@ -0,0 +1,49 @@ +import sys.thread.Lock; +import sys.thread.Thread; + +// libhxcpp #458. On 32-bit Windows the collector's per-thread context was read +// from the thread environment block's inline TLS slots whatever its slot, but +// only the first 64 are inline. In a process that had used 64 slots before the +// runtime started, as a host with many DLLs can, every thread looked +// unregistered and the first allocation stopped the process. Here, with MSVC, a +// CRT initializer that runs before the runtime takes TLS slots up to 70. +@:cppFileCode(' +#if defined(_MSC_VER) && !defined(HX_WINRT) +#include +#include +extern "C" void __cdecl hxUseUpInlineTlsSlots(void) +{ + for (int i = 0; i < 128; i++) + { + DWORD last = TlsAlloc(); + if (last == TLS_OUT_OF_INDEXES || last >= 70) + break; + } +} +#pragma section(".CRT$XCT", read) +extern "C" __declspec(allocate(".CRT$XCT")) void (__cdecl *hxUseUpInlineTlsSlotsInit)(void) = hxUseUpInlineTlsSlots; +#ifdef _WIN64 +#pragma comment(linker, "/include:hxUseUpInlineTlsSlotsInit") +#else +#pragma comment(linker, "/include:_hxUseUpInlineTlsSlotsInit") +#endif +#endif +') +class Main { + static function strings(n:Int) + return [for (i in 0...n) Std.string(i)].length; + + static function main() { + var made = strings(100000); + var done = new Lock(); + var madeOnThread = 0; + Thread.create(() -> { + madeOnThread = strings(100000); + cpp.vm.Gc.run(true); + done.release(); + }); + done.wait(); + cpp.vm.Gc.run(true); + Sys.println('made $made strings, and $madeOnThread on another thread, and collected'); + } +} diff --git a/test/regression/TlsHighSlot/build.hxml b/test/regression/TlsHighSlot/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/TlsHighSlot/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/TlsHighSlot/stdout.txt b/test/regression/TlsHighSlot/stdout.txt new file mode 100644 index 00000000..dc0535d1 --- /dev/null +++ b/test/regression/TlsHighSlot/stdout.txt @@ -0,0 +1 @@ +made 100000 strings, and 100000 on another thread, and collected From bf67882f9dc3a385005b3b2595930292c1659c87 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:19:54 -0500 Subject: [PATCH 15/36] Wait for ever on tryAcquire(-1) only Since #420, CountingSemaphore::tryAcquire waited with no limit for any negative timeout, so that Haxe 5.0.0-preview.1's Lock.wait(), which passes -1 when given no timeout, would block. But a timeout computed as tryAcquire(deadline - now) goes negative once the deadline has passed, and then waited for ever, where Haxe documents tryAcquire as giving up when the timeout runs out. The Haxe nightly's Lock.wait calls acquire() when given no timeout, so only preview.1 needs the special case. Exactly -1 still waits with no limit, on every backend. Any other negative timeout returns at once, as 0 and NaN do. Test: ThreadWaitTimeouts checks -1 and -0.5 apart now. tryAcquire(-0.5) on an empty semaphore waited until the watchdog stopped the test before, and returns false at once now, on Windows x64. Fixes #461 --- Changes.md | 1 + src/hx/thread/CountingSemaphore.apple.cpp | 8 +++++--- src/hx/thread/CountingSemaphore.posix.cpp | 8 +++++--- src/hx/thread/CountingSemaphore.singlethreaded.cpp | 8 +++++--- src/hx/thread/CountingSemaphore.win32.cpp | 8 +++++--- test/regression/ThreadWaitTimeouts/Main.hx | 8 +++++--- test/regression/ThreadWaitTimeouts/stdout.txt | 1 + 7 files changed, 27 insertions(+), 15 deletions(-) diff --git a/Changes.md b/Changes.md index fb73a1e9..e7ccf7e4 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed Semaphore.tryAcquire with a negative timeout waiting for ever, as tryAcquire(deadline - now) does once the deadline has passed: since the fix for Haxe 5's Lock.wait() (libhxcpp #420), any negative timeout meant no limit. Only -1, which Haxe 5.0.0-preview.1's Lock.wait() passes for no timeout, waits with no limit now, and any other negative timeout returns at once, as 0 does (libhxcpp #461) * Fixed 32-bit Windows programs stopping with "Bad local allocator - requesting memory from unregistered thread!" when the process had used 64 TLS slots before the runtime started, as a host with many DLLs, or a late-loaded hxcpp DLL, can: the collector read its per-thread context from the thread's inline TLS slots, of which there are only 64. Later slots are read with TlsGetValue, as on x64 (libhxcpp #458) * Fixed Windows programs not starting on Windows 8.1, Server 2012 R2 and Windows 10 before 1607 with a missing entry point, HXCPP_WINXP_COMPAT or not: every program imported GetThreadDescription and SetThreadDescription, which those lack. They are looked up when used now, and where they are missing a thread's name is null and setting it does nothing (libhxcpp #456) * Fixed Sys.sleep, Sys.command and Sys.getch ending the process with "GCFree Zone mismatch" when called inside a GC-free zone the caller had entered, as with cpp.vm.Gc.enterGCFreeZone around a blocking call: they left that zone themselves, so the caller's own exit failed. They keep the caller's zone, as Mutex, Lock and Semaphore do. CFFI's gc_safe_point, between gc_enter_blocking and gc_exit_blocking, no longer pauses as if outside the zone, which ended the process with "Bad Allocation while collecting" or waited for ever (libhxcpp #457) diff --git a/src/hx/thread/CountingSemaphore.apple.cpp b/src/hx/thread/CountingSemaphore.apple.cpp index 25564db0..8a448add 100644 --- a/src/hx/thread/CountingSemaphore.apple.cpp +++ b/src/hx/thread/CountingSemaphore.apple.cpp @@ -54,9 +54,11 @@ void hx::thread::CountingSemaphore_obj::release() bool hx::thread::CountingSemaphore_obj::tryAcquire(Null timeout) { - // A negative timeout waits with no limit, as __hxcpp_lock_wait does: Haxe 5's - // Lock.wait() passes -1 when it is given no timeout. NaN still returns at once. - if (timeout.Default(0) < 0) + // -1 waits with no limit: Haxe 5.0.0-preview.1's Lock.wait() passes it when + // given no timeout. Any other negative timeout has run out already, as in + // tryAcquire(deadline - now), and returns at once like 0, as does NaN; it + // waited for ever before (libhxcpp #461) + if (timeout.Default(0) == -1) { acquire(); return true; diff --git a/src/hx/thread/CountingSemaphore.posix.cpp b/src/hx/thread/CountingSemaphore.posix.cpp index 8cbb3353..aa0559ad 100644 --- a/src/hx/thread/CountingSemaphore.posix.cpp +++ b/src/hx/thread/CountingSemaphore.posix.cpp @@ -75,9 +75,11 @@ void hx::thread::CountingSemaphore_obj::release() bool hx::thread::CountingSemaphore_obj::tryAcquire(Null timeout) { - // A negative timeout waits with no limit, as __hxcpp_lock_wait does: Haxe 5's - // Lock.wait() passes -1 when it is given no timeout. NaN still returns at once. - if (timeout.Default(0) < 0) + // -1 waits with no limit: Haxe 5.0.0-preview.1's Lock.wait() passes it when + // given no timeout. Any other negative timeout has run out already, as in + // tryAcquire(deadline - now), and returns at once like 0, as does NaN; it + // waited for ever before (libhxcpp #461) + if (timeout.Default(0) == -1) { acquire(); return true; diff --git a/src/hx/thread/CountingSemaphore.singlethreaded.cpp b/src/hx/thread/CountingSemaphore.singlethreaded.cpp index 2b5430f5..2598ec5a 100644 --- a/src/hx/thread/CountingSemaphore.singlethreaded.cpp +++ b/src/hx/thread/CountingSemaphore.singlethreaded.cpp @@ -54,9 +54,11 @@ void hx::thread::CountingSemaphore_obj::release() bool hx::thread::CountingSemaphore_obj::tryAcquire(Null timeout) { - // A negative timeout waits with no limit, as __hxcpp_lock_wait does: Haxe 5's - // Lock.wait() passes -1 when it is given no timeout. NaN still returns at once. - if (timeout.Default(0) < 0) + // -1 waits with no limit: Haxe 5.0.0-preview.1's Lock.wait() passes it when + // given no timeout. Any other negative timeout has run out already, as in + // tryAcquire(deadline - now), and returns at once like 0, as does NaN; it + // waited for ever before (libhxcpp #461) + if (timeout.Default(0) == -1) { acquire(); return true; diff --git a/src/hx/thread/CountingSemaphore.win32.cpp b/src/hx/thread/CountingSemaphore.win32.cpp index f9d9ab8e..5389419c 100644 --- a/src/hx/thread/CountingSemaphore.win32.cpp +++ b/src/hx/thread/CountingSemaphore.win32.cpp @@ -59,9 +59,11 @@ void hx::thread::CountingSemaphore_obj::release() bool hx::thread::CountingSemaphore_obj::tryAcquire(Null timeout) { - // A negative timeout waits with no limit, as __hxcpp_lock_wait does: Haxe 5's - // Lock.wait() passes -1 when it is given no timeout. NaN still returns at once. - if (timeout.Default(0) < 0) + // -1 waits with no limit: Haxe 5.0.0-preview.1's Lock.wait() passes it when + // given no timeout. Any other negative timeout has run out already, as in + // tryAcquire(deadline - now), and returns at once like 0, as does NaN; it + // waited for ever before (libhxcpp #461) + if (timeout.Default(0) == -1) { acquire(); return true; diff --git a/test/regression/ThreadWaitTimeouts/Main.hx b/test/regression/ThreadWaitTimeouts/Main.hx index 41f2a6fe..417ff053 100644 --- a/test/regression/ThreadWaitTimeouts/Main.hx +++ b/test/regression/ThreadWaitTimeouts/Main.hx @@ -40,11 +40,13 @@ class Main { static function main() { untyped __cpp__("startWatchdog(60)"); var empty = new Semaphore(0); - var full = new Semaphore(2); + var full = new Semaphore(3); - // A negative timeout waits with no limit, which Haxe 5's Lock.wait() relies on + // -1 waits with no limit, which Haxe 5.0.0-preview.1's Lock.wait() relies on releaseLater(() -> empty.release()); - check("semaphore negative", attempt(() -> empty.tryAcquire(-0.5) && full.tryAcquire(-0.5))); + check("semaphore minus one", attempt(() -> empty.tryAcquire(-1) && full.tryAcquire(-1))); + // Any other negative timeout has run out, and returns at once (libhxcpp #461) + check("semaphore negative", attempt(() -> !empty.tryAcquire(-0.5) && full.tryAcquire(-0.5))); check("semaphore nan", attempt(() -> !empty.tryAcquire(Math.NaN) && full.tryAcquire(Math.NaN))); var huge = true; diff --git a/test/regression/ThreadWaitTimeouts/stdout.txt b/test/regression/ThreadWaitTimeouts/stdout.txt index 75619baa..f7ba2c08 100644 --- a/test/regression/ThreadWaitTimeouts/stdout.txt +++ b/test/regression/ThreadWaitTimeouts/stdout.txt @@ -1,3 +1,4 @@ +semaphore minus one ok semaphore negative ok semaphore nan ok semaphore huge ok From 5da0ac16fd6dcc14300277288554c2b6cf638a46 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:31:41 -0500 Subject: [PATCH 16/36] Look up cppia's shared maps without inserting hx::Object::_hx_getInterface read a script class's interfaceScriptTables with std::map::operator[], so Std.isOfType on a script object, or an interface cast, inserted an entry for each host interface the class did not implement, from whichever thread asked, with no lock, while other threads searched the same map. Threads asking about the same classes hung or crashed. HaxeNativeClass::findClass, hxObject, link's super class lookup and HaxeNativeInterface::findInterface inserted the names they missed into the host's class maps the same way, while loading a module on another thread walked them in link(), so loads failed with "No base defined for non-interface" or hung. The maps are filled when classes link or the host starts and only read after, with find(). link(), which sets the shared super classes on every load, takes a lock, and the module id counter is atomic. Test: CppiaThreadedLookups, 8 threads asking Std.isOfType about the same 2000 script objects, then 8 threads loading one module at once, with a watchdog. Before, 3 of 4 runs hung; now 5 of 5 pass, on Windows x64. Fixes #466 --- Changes.md | 1 + src/hx/cppia/CppiaClasses.cpp | 7 +- src/hx/cppia/CppiaModule.cpp | 3 +- src/hx/cppia/HaxeNative.cpp | 21 ++++- test/regression/CppiaThreadedLookups/Gen.hx | 13 +++ test/regression/CppiaThreadedLookups/Main.hx | 94 +++++++++++++++++++ .../regression/CppiaThreadedLookups/Script.hx | 8 ++ .../CppiaThreadedLookups/build.hxml | 8 ++ .../CppiaThreadedLookups/stdout.txt | 2 + test/regression/emscripten-skip.txt | 1 + 10 files changed, 151 insertions(+), 7 deletions(-) create mode 100644 test/regression/CppiaThreadedLookups/Gen.hx create mode 100644 test/regression/CppiaThreadedLookups/Main.hx create mode 100644 test/regression/CppiaThreadedLookups/Script.hx create mode 100644 test/regression/CppiaThreadedLookups/build.hxml create mode 100644 test/regression/CppiaThreadedLookups/stdout.txt diff --git a/Changes.md b/Changes.md index e7ccf7e4..212f5c03 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed cppia hanging or crashing when several threads asked Std.isOfType about script objects, or cast them to host interfaces, at once: each question about an interface a class did not implement inserted into that class's table, unlocked, while other threads searched it. Loading modules on several threads at once could likewise fail with "No base defined for non-interface", or hang, as each load inserted the host class names it missed into a map the others walked. Both are only read after they are filled now (libhxcpp #466) * Fixed Semaphore.tryAcquire with a negative timeout waiting for ever, as tryAcquire(deadline - now) does once the deadline has passed: since the fix for Haxe 5's Lock.wait() (libhxcpp #420), any negative timeout meant no limit. Only -1, which Haxe 5.0.0-preview.1's Lock.wait() passes for no timeout, waits with no limit now, and any other negative timeout returns at once, as 0 does (libhxcpp #461) * Fixed 32-bit Windows programs stopping with "Bad local allocator - requesting memory from unregistered thread!" when the process had used 64 TLS slots before the runtime started, as a host with many DLLs, or a late-loaded hxcpp DLL, can: the collector read its per-thread context from the thread's inline TLS slots, of which there are only 64. Later slots are read with TlsGetValue, as on x64 (libhxcpp #458) * Fixed Windows programs not starting on Windows 8.1, Server 2012 R2 and Windows 10 before 1607 with a missing entry point, HXCPP_WINXP_COMPAT or not: every program imported GetThreadDescription and SetThreadDescription, which those lack. They are looked up when used now, and where they are missing a thread's name is null and setting it does nothing (libhxcpp #456) diff --git a/src/hx/cppia/CppiaClasses.cpp b/src/hx/cppia/CppiaClasses.cpp index d3d35184..7d2de972 100644 --- a/src/hx/cppia/CppiaClasses.cpp +++ b/src/hx/cppia/CppiaClasses.cpp @@ -2247,8 +2247,11 @@ void *hx::Object::_hx_getInterface(int inId) if (!vtable) return 0; CppiaClassInfo *info = ((CppiaClassInfo *)vtable[-1]); - void *result = info->interfaceScriptTables[inId]; - return info->interfaceScriptTables[inId]; + // Filled when the class links. operator[] inserted an entry for each + // interface asked about that the class does not implement, from whichever + // thread asked, while others searched the same map (libhxcpp #466) + std::map::iterator it = info->interfaceScriptTables.find(inId); + return it==info->interfaceScriptTables.end() ? 0 : it->second; } diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index 44139cd0..428114bf 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -12,7 +12,8 @@ namespace hx { -static int sScriptId = 0; +// Modules load on any thread +static std::atomic sScriptId(0); static std::atomic sLiveModules(0); diff --git a/src/hx/cppia/HaxeNative.cpp b/src/hx/cppia/HaxeNative.cpp index 9bd24ac6..ca8feae7 100644 --- a/src/hx/cppia/HaxeNative.cpp +++ b/src/hx/cppia/HaxeNative.cpp @@ -2,6 +2,7 @@ #include #include "Cppia.h" #include +#include namespace hx @@ -101,18 +102,27 @@ ScriptNamedFunction HaxeNativeClass::findStaticFunction(String inName) +// The maps are filled as the host starts, and only read after, by any thread +// loading or running a script: a lookup with operator[] inserted the names it +// missed, under threads walking or searching the same map (libhxcpp #466) HaxeNativeClass *HaxeNativeClass::findClass(const std::string &inName) { - return sScriptRegistered ? (*sScriptRegistered)[inName] : 0; + if (!sScriptRegistered) + return 0; + ScriptRegisteredMap::iterator it = sScriptRegistered->find(inName); + return it==sScriptRegistered->end() ? 0 : it->second; } HaxeNativeClass *HaxeNativeClass::hxObject() { - return sScriptRegistered ? (*sScriptRegistered)["hx.Object"] : 0; + return findClass("hx.Object"); } void HaxeNativeClass::link() { + // Each load links, and the super classes it sets are shared by every module + static std::mutex linkLock; + std::lock_guard lock(linkLock); HaxeNativeClass *hxObj = hxObject(); for(ScriptRegisteredMap::iterator i = sScriptRegistered->begin(); i!=sScriptRegistered->end();++i) { @@ -131,7 +141,7 @@ void HaxeNativeClass::link() hx::Class superClass = cls->GetSuper(); if (superClass.mPtr) { - HaxeNativeClass *superRef = (*sScriptRegistered)[superClass.mPtr->mName.utf8_str()]; + HaxeNativeClass *superRef = findClass(superClass.mPtr->mName.utf8_str()); if (superRef) { DBGLOG("registered %s\n",superClass.mPtr->mName.utf8_str()); @@ -282,7 +292,10 @@ void ScriptableRegisterInterface( String inName, HaxeNativeInterface *HaxeNativeInterface::findInterface(const std::string &inName) { - return sScriptRegisteredInterface ? (*sScriptRegisteredInterface)[inName] : 0; + if (!sScriptRegisteredInterface) + return 0; + HaxeNativeIntefaceMap::iterator it = sScriptRegisteredInterface->find(inName); + return it==sScriptRegisteredInterface->end() ? 0 : it->second; } diff --git a/test/regression/CppiaThreadedLookups/Gen.hx b/test/regression/CppiaThreadedLookups/Gen.hx new file mode 100644 index 00000000..12af6aa9 --- /dev/null +++ b/test/regression/CppiaThreadedLookups/Gen.hx @@ -0,0 +1,13 @@ +import haxe.macro.Context; +import haxe.macro.Expr; + +// Defines the script's classes C0 to C, each with a constructor +class Gen { + public static function classes(n:Int) { + var pos = Context.currentPos(); + for (i in 0...n) { + var ctor:Field = {name: "new", access: [APublic], kind: FFun({args: [], expr: macro {}}), pos: pos}; + Context.defineType({pack: [], name: 'C$i', pos: pos, kind: TDClass(), fields: [ctor], meta: [{name: ":keep", pos: pos}]}); + } + } +} diff --git a/test/regression/CppiaThreadedLookups/Main.hx b/test/regression/CppiaThreadedLookups/Main.hx new file mode 100644 index 00000000..887b8be2 --- /dev/null +++ b/test/regression/CppiaThreadedLookups/Main.hx @@ -0,0 +1,94 @@ +import haxe.io.Path; +import sys.thread.Lock; +import sys.thread.Mutex; +import sys.thread.Thread; + +interface I0 {} +interface I1 {} +interface I2 {} +interface I3 {} +interface I4 {} +interface I5 {} +interface I6 {} +interface I7 {} + +// libhxcpp #466. Two lookups any thread can make inserted into maps that other +// threads were searching at the same time: +// - Std.isOfType(scriptObject, HostInterface) inserted an entry into the +// script class's interface table for each interface it did not implement, +// which hung or crashed threads asking about the same classes. +// - Loading a module looked up host classes with operator[], inserting what it +// missed, while other loads walked the same map, which failed loads with "No +// base defined for non-interface" or hung. +// A native watchdog, which the collector does not know, ends a hang. +@:cppFileCode(' +#include +#include +#include +#include +#include +static std::atomic gStage(0); +static void startWatchdog() +{ + std::thread([]{ + for(int i=0; i<120 && gStage<2; i++) + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (gStage<2) + { + printf("hung at stage %d\\n", (int)gStage); + fflush(stdout); + std::_Exit(1); + } + }).detach(); +} +') +class Main { + static function main() { + untyped __cpp__("startWatchdog()"); + var threads = 8; + var script = sys.io.File.getBytes(Path.join([Path.directory(Sys.programPath()), "script.cppia"])); + var module = cpp.cppia.Module.fromData(script.getData()); + module.boot(); + module.run(); + var objects:Array = Reflect.field(module.resolveClass("Script"), "objects"); + var ifaces:Array = [I0, I1, I2, I3, I4, I5, I6, I7]; + + var mutex = new Mutex(); + var done = new Lock(); + var wrong = 0; + for (t in 0...threads) + Thread.create(() -> { + var mine = 0; + for (round in 0...4) + for (o in objects) + for (k in 0...ifaces.length) + if (Std.isOfType(o, ifaces[(k + t) % ifaces.length])) + mine++; + mutex.acquire(); + wrong += mine; + mutex.release(); + done.release(); + }); + for (_ in 0...threads) + done.wait(); + untyped __cpp__("gStage = 1"); + Sys.println('${objects.length} script objects asked about ${ifaces.length} host interfaces on $threads threads: $wrong wrong'); + + var failed = 0; + for (t in 0...threads) + Thread.create(() -> { + try { + cpp.cppia.Module.fromData(script.getData()); + } catch (e:Dynamic) { + mutex.acquire(); + failed++; + mutex.release(); + } + done.release(); + }); + for (_ in 0...threads) + done.wait(); + untyped __cpp__("gStage = 2"); + Sys.println('the module loaded on $threads threads at once: $failed failed'); + } +} diff --git a/test/regression/CppiaThreadedLookups/Script.hx b/test/regression/CppiaThreadedLookups/Script.hx new file mode 100644 index 00000000..4e3c05ca --- /dev/null +++ b/test/regression/CppiaThreadedLookups/Script.hx @@ -0,0 +1,8 @@ +class Script { + public static var objects:Array = []; + + static function main() { + for (i in 0...2000) + objects.push(Type.createInstance(Type.resolveClass('C$i'), [])); + } +} diff --git a/test/regression/CppiaThreadedLookups/build.hxml b/test/regression/CppiaThreadedLookups/build.hxml new file mode 100644 index 00000000..c95a3dea --- /dev/null +++ b/test/regression/CppiaThreadedLookups/build.hxml @@ -0,0 +1,8 @@ +--main Script +--macro Gen.classes(2000) +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaThreadedLookups/stdout.txt b/test/regression/CppiaThreadedLookups/stdout.txt new file mode 100644 index 00000000..6859eeca --- /dev/null +++ b/test/regression/CppiaThreadedLookups/stdout.txt @@ -0,0 +1,2 @@ +2000 script objects asked about 8 host interfaces on 8 threads: 0 wrong +the module loaded on 8 threads at once: 0 failed diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index c0d5e613..f54654df 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -28,6 +28,7 @@ CppiaModuleFree: threads CppiaModuleRetained: threads CppiaNullDynamicArray: its host is the first --next section, which -D emscripten does not reach, and it runs the script under the JIT too, and Emscripten has no cppia JIT CppiaStackSize: threads (std::thread, which needs a pthreads build) +CppiaThreadedLookups: threads DateTimezoneCache: Emscripten takes the local zone from JavaScript and ignores TZ ExitWithBusyWorker: processes and threads FileFinalizerFlush: threads (std::thread, which needs a pthreads build) From 178fceffe0bf06527e721c67f8ebc330db22de25 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:34:43 -0500 Subject: [PATCH 17/36] Keep what a cpp.Pointer field points into wherever it points e1f6ac06 made a cpp.Pointer field, and a pointer boxed in a Dynamic, keep what it points into, through MarkConservativePointer. That went through the stack scan, which accepts a pointer only within sgCheckInternalOffset of an allocation's start: 64 bytes, or 32 on 32-bit. Right for a stack word, which is usually also held from the start somewhere, but a field may be all that holds it, and a pointer from cpp.Pointer.arrayElem(a, 100), 400 bytes in, kept nothing. MarkConservative's body takes the reach as a parameter now, and passes it to GetMemType, GetEnclosingAllocType and GetEnclosingNurseryType. A stack word keeps sgCheckInternalOffset; MarkConservativePointer reaches back to the start of the block, and a large allocation is checked against its own size. The walk back in a block stops at the block's start, and the large allocation bounds check no longer adds the reach to the highest base, which a large reach overflowed. Test: GcPointerFieldInterior, 2000 fields 40 and 400 bytes into Int arrays and one 200 KB into a large array. Before, 1999 of the 400-byte fields and the large one read freed memory, and on 32-bit all 4000 did; now none do, in the default, HXCPP_GC_MOVING and 32-bit builds on Windows. Fixes #451 --- Changes.md | 1 + src/hx/gc/Immix.cpp | 44 +++++++++----- .../regression/GcPointerFieldInterior/Main.hx | 58 +++++++++++++++++++ .../GcPointerFieldInterior/build.hxml | 2 + .../GcPointerFieldInterior/stdout.txt | 3 + 5 files changed, 94 insertions(+), 14 deletions(-) create mode 100644 test/regression/GcPointerFieldInterior/Main.hx create mode 100644 test/regression/GcPointerFieldInterior/build.hxml create mode 100644 test/regression/GcPointerFieldInterior/stdout.txt diff --git a/Changes.md b/Changes.md index 212f5c03..c8ac956c 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed a cpp.Pointer field, or a pointer boxed in a Dynamic, letting what it points into be freed when it points further in than 64 bytes, or 32 on 32-bit, as cpp.Pointer.arrayElem(a, 100) does: the fix for Haxe 4's AtomicInt kept only what a stack word would keep. A pointer field keeps its whole allocation now, large ones included, and pins it under HXCPP_GC_MOVING (libhxcpp #451) * Fixed cppia hanging or crashing when several threads asked Std.isOfType about script objects, or cast them to host interfaces, at once: each question about an interface a class did not implement inserted into that class's table, unlocked, while other threads searched it. Loading modules on several threads at once could likewise fail with "No base defined for non-interface", or hang, as each load inserted the host class names it missed into a map the others walked. Both are only read after they are filled now (libhxcpp #466) * Fixed Semaphore.tryAcquire with a negative timeout waiting for ever, as tryAcquire(deadline - now) does once the deadline has passed: since the fix for Haxe 5's Lock.wait() (libhxcpp #420), any negative timeout meant no limit. Only -1, which Haxe 5.0.0-preview.1's Lock.wait() passes for no timeout, waits with no limit now, and any other negative timeout returns at once, as 0 does (libhxcpp #461) * Fixed 32-bit Windows programs stopping with "Bad local allocator - requesting memory from unregistered thread!" when the process had used 64 TLS slots before the runtime started, as a host with many DLLs, or a late-loaded hxcpp DLL, can: the collector read its per-thread context from the thread's inline TLS slots, of which there are only 64. Later slots are read with TlsGetValue, as on x64 (libhxcpp #458) diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 3f29d667..171d3906 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -1464,7 +1464,7 @@ struct BlockDataInfo } #ifdef HXCPP_GC_NURSERY - AllocType GetEnclosingNurseryType(uintptr_t inOffset, uintptr_t* outPtr) const + AllocType GetEnclosingNurseryType(uintptr_t inOffset, uintptr_t* outPtr, uintptr_t inReach=sgCheckInternalOffset) const { // The block did not get used in the previous cycle, so allocStart is invalid and // no new objects should be in here @@ -1510,7 +1510,7 @@ struct BlockDataInfo if (inOffset>=scan && inOffset scan + sgCheckInternalOffset) + if (inOffset > scan + inReach) return allocNone; if (nullptr != outPtr) @@ -1564,9 +1564,9 @@ struct BlockDataInfo return GetAllocTypeChecked(inOffset,inAllowPrevious); } - AllocType GetEnclosingAllocType(uintptr_t inOffset, uintptr_t* outPtr, bool inAllowPrevious) const + AllocType GetEnclosingAllocType(uintptr_t inOffset, uintptr_t* outPtr, bool inAllowPrevious, uintptr_t inReach=sgCheckInternalOffset) const { - for (uintptr_t dx{ 0 }; dx <= sgCheckInternalOffset; dx += 4) + for (uintptr_t dx{ 0 }; dx <= inReach && dx <= inOffset; dx += 4) { uintptr_t blockOffset{ inOffset - dx }; if (blockOffset >= 0) @@ -1606,7 +1606,7 @@ struct BlockDataInfo } #ifdef HXCPP_GC_NURSERY - return GetEnclosingNurseryType(inOffset,outPtr); + return GetEnclosingNurseryType(inOffset,outPtr,inReach); #endif // Not a actual start... return allocNone; @@ -7627,7 +7627,7 @@ class GlobalAllocator // allocation finds it too, as GetEnclosingAllocType does in a block, and // outBase is set to where it starts. Native code may hold only a field's // address, which kept a small object alive but not a large one (libhxcpp #373) - MemType GetMemType(uintptr_t inPtr, uintptr_t *outBase = nullptr) + MemType GetMemType(uintptr_t inPtr, uintptr_t *outBase = nullptr, size_t inReach = 0) { BlockData* block{ reinterpret_cast(inPtr & IMMIX_BLOCK_BASE_MASK) }; @@ -7639,9 +7639,10 @@ class GlobalAllocator // Most stack words are nowhere near the large allocations - reject on // the cached bounds before paying for the full list scan. The bounds // are of the starts, so a pointer into the highest reaches past them - size_t reach = outBase ? sgCheckInternalOffset : 0; + // inReach, for a pointer field, goes further: see MarkConservativePointer + size_t reach = outBase ? (inReach ? inReach : sgCheckInternalOffset) : 0; size_t p = (size_t)inPtr; - if (p < mLargeMin || p > mLargeMax + reach) + if (p < mLargeMin || (p > mLargeMax && p - mLargeMax > reach)) return memUnmanaged; uintptr_t base = 0; @@ -7809,7 +7810,9 @@ MarkChunk *MarkChunk::swapForNew() HX_NO_SANITIZE_ADDRESS -void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) +// inReach is how far into an allocation a pointer may be and still keep it: +// 0 for a stack word, which uses sgCheckInternalOffset +static void MarkConservativeReach(int *inBottom, int *inTop,hx::MarkContext *__inCtx, uintptr_t inReach) { #ifdef VERIFY_STACK_READ VerifyStackRead(inBottom, inTop); @@ -7871,7 +7874,7 @@ void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) hx::localCount++; #endif uintptr_t largeBase{}; - MemType mem{ sGlobalAlloc->GetMemType(potentialObject, &largeBase) }; + MemType mem{ sGlobalAlloc->GetMemType(potentialObject, &largeBase, inReach) }; #ifdef HX_WATCH isWatch = false; @@ -7916,8 +7919,8 @@ void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) size_t pos{ potentialObject & IMMIX_BLOCK_OFFSET_MASK }; AllocType t{ - sgCheckInternalOffset ? - info->GetEnclosingAllocType(pos - sizeof(int), &potentialObject, allowPrevious) : + (inReach || sgCheckInternalOffset) ? + info->GetEnclosingAllocType(pos - sizeof(int), &potentialObject, allowPrevious, inReach ? inReach : sgCheckInternalOffset) : info->GetAllocType(pos - sizeof(int), allowPrevious) }; #ifdef HX_WATCH @@ -8000,15 +8003,28 @@ void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) #endif } +void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) +{ + MarkConservativeReach(inBottom, inTop, __inCtx, 0); +} + +// A cpp.Pointer field, or a pointer boxed in a Dynamic, keeps what it points +// into wherever it points in it, as cpp.Pointer.arrayElem(a, 100) does. A +// stack word keeps an allocation only within sgCheckInternalOffset of its +// start, since a pointer further in is usually held from the start too, but a +// field may be all there is (libhxcpp #451). In a block, nothing bigger than +// the block, and a large allocation is checked against its own size +static const uintptr_t sPointerFieldReach = ~(uintptr_t)0 >> 1; + void MarkConservativePointer(void *inPtr,hx::MarkContext *__inCtx) { void *word[1] = { inPtr }; // MarkConservative reads every pointer-sized word starting on an int in // the range, so this covers the one word and nothing past it #ifdef HXCPP_STACK_UP - MarkConservative(reinterpret_cast(word + 1) - 1, reinterpret_cast(word) + 1, __inCtx); + MarkConservativeReach(reinterpret_cast(word + 1) - 1, reinterpret_cast(word) + 1, __inCtx, sPointerFieldReach); #else - MarkConservative(reinterpret_cast(word), reinterpret_cast(word + 1), __inCtx); + MarkConservativeReach(reinterpret_cast(word), reinterpret_cast(word + 1), __inCtx, sPointerFieldReach); #endif } diff --git a/test/regression/GcPointerFieldInterior/Main.hx b/test/regression/GcPointerFieldInterior/Main.hx new file mode 100644 index 00000000..dd7a7395 --- /dev/null +++ b/test/regression/GcPointerFieldInterior/Main.hx @@ -0,0 +1,58 @@ +// libhxcpp #451. A cpp.Pointer field keeps what it points into, but only kept +// it within 64 bytes of the allocation's start (32 on 32-bit), the limit for a +// stack word. A pointer to element 100 of an Int array, 400 bytes in, or into +// the middle of a large array, kept nothing, and the array was freed under it. +class Holder { + public var near:cpp.Pointer; + public var far:cpp.Pointer; + + public function new() {} +} + +class Main { + static inline var COUNT = 2000; + + static var holders:Array; + static var large:cpp.Pointer; + + static function fill() { + for (i in 0...COUNT) { + var a = [for (j in 0...500) i * 1000 + j]; + holders[i].near = cpp.Pointer.arrayElem(a, 10); + var b = [for (j in 0...500) i * 1000 + j]; + holders[i].far = cpp.Pointer.arrayElem(b, 100); + } + // 400 KB, a large allocation, pointed to 200 KB in + var big = [for (j in 0...100000) j]; + large = cpp.Pointer.arrayElem(big, 50000); + } + + static function churn() { + var junk = []; + for (i in 0...20000) + junk.push([for (j in 0...100) 0x5a5a5a5a]); + var bigJunk = [for (i in 0...20) [for (j in 0...100000) 0x5a5a5a5a]]; + return junk.length + bigJunk.length; + } + + static function main() { + holders = [for (i in 0...COUNT) new Holder()]; + fill(); + for (round in 0...4) { + cpp.vm.Gc.run(true); + churn(); + } + cpp.vm.Gc.run(true); + var wrongNear = 0; + var wrongFar = 0; + for (i in 0...COUNT) { + if (holders[i].near.value != i * 1000 + 10) + wrongNear++; + if (holders[i].far.value != i * 1000 + 100) + wrongFar++; + } + Sys.println('pointers 40 bytes in, wrong: $wrongNear of $COUNT'); + Sys.println('pointers 400 bytes in, wrong: $wrongFar of $COUNT'); + Sys.println('pointer 200 KB into a large array: ' + (large.value == 50000 ? "right" : "wrong")); + } +} diff --git a/test/regression/GcPointerFieldInterior/build.hxml b/test/regression/GcPointerFieldInterior/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcPointerFieldInterior/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcPointerFieldInterior/stdout.txt b/test/regression/GcPointerFieldInterior/stdout.txt new file mode 100644 index 00000000..1038c087 --- /dev/null +++ b/test/regression/GcPointerFieldInterior/stdout.txt @@ -0,0 +1,3 @@ +pointers 40 bytes in, wrong: 0 of 2000 +pointers 400 bytes in, wrong: 0 of 2000 +pointer 200 KB into a large array: right From c6e84ec103492dc3bec1a574f5dcbd27bb457952 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 08:37:52 -0500 Subject: [PATCH 18/36] Count live bytes and Gc.trace right with an incremental cycle With HXCPP_GC_INCREMENTAL: - A finished cycle that is not a full reclaim only runs countRows, whose bytesInUse is whole rows, and Collect stored that as mLiveBytes because the cycle had finished. MEM_INFO_LIVE, the bytes of the objects that survived the last full reclaim, then reported every used row as live, seven times the real figure in the test. It is set by full reclaims only. - Gc.trace counts what its collection marks. With a cycle part done, the collection finished it, and the objects its earlier slices had marked were not counted. A census already fails the partial cycle for this reason; Gc.trace does too now. Test: IncrementalGcCounts, which the incremental gc job builds in debug, as Gc.trace needs. Before, MEM_INFO_LIVE changed after the cycle, and Gc.trace counted 90668 and 108653 of 200000; now both are right, on Windows x64. Fixes #453 --- .github/workflows/test.yml | 9 ++- Changes.md | 1 + src/hx/gc/Immix.cpp | 18 +++-- test/regression/IncrementalGcCounts/Main.hx | 79 +++++++++++++++++++ .../regression/IncrementalGcCounts/build.hxml | 4 + .../regression/IncrementalGcCounts/stdout.txt | 3 + 6 files changed, 105 insertions(+), 9 deletions(-) create mode 100644 test/regression/IncrementalGcCounts/Main.hx create mode 100644 test/regression/IncrementalGcCounts/build.hxml create mode 100644 test/regression/IncrementalGcCounts/stdout.txt diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 007a0b25..6a9a75b9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -495,11 +495,14 @@ jobs: working-directory: test/regression run: | failed="" - for test in GcMutationRoots GcContainerMutation IncrementalGcSlices IncrementalGcContainers IncrementalGcArrayChunks IncrementalGcDequeMoves IncrementalGcPacing IncrementalGcStartSweep IncrementalGcStats IncrementalGcFinishBoundary IncrementalGcVerifier IncrementalWindowsHeaders GcWeakMapChain GcWeakMapWalkCollect GenerationalFinalizerLifecycle GenerationalLargeBufferLifecycle; do + for test in GcMutationRoots GcContainerMutation IncrementalGcSlices IncrementalGcContainers IncrementalGcArrayChunks IncrementalGcDequeMoves IncrementalGcPacing IncrementalGcStartSweep IncrementalGcStats IncrementalGcFinishBoundary IncrementalGcVerifier IncrementalGcCounts IncrementalWindowsHeaders GcWeakMapChain GcWeakMapWalkCollect GenerationalFinalizerLifecycle GenerationalLargeBufferLifecycle; do echo "::group::incremental gc: $test" # The lifecycle fixtures' hxml selects generational mode; compile - # the same Main with incremental mode here instead. - if ! (cd "$test" && haxe -main Main -cpp bin -lib hxcpp -D HXCPP_GC_INCREMENTAL -D HXCPP_GC_INCREMENTAL_VERIFY -D HXCPP_GC_INCREMENTAL_TEST -D $HXCPP_ARCH_FLAG && bin/Main > out.txt && diff <(tr -d '\r' < stdout.txt) <(tr -d '\r' < out.txt)); then + # the same Main with incremental mode here instead. Gc.trace, which + # IncrementalGcCounts checks, counts in debug builds only. + extra="" + [ "$test" = IncrementalGcCounts ] && extra="-debug -D DEBUGSUFFIX=" + if ! (cd "$test" && haxe -main Main -cpp bin -lib hxcpp -D HXCPP_GC_INCREMENTAL -D HXCPP_GC_INCREMENTAL_VERIFY -D HXCPP_GC_INCREMENTAL_TEST -D $HXCPP_ARCH_FLAG $extra && bin/Main > out.txt && diff <(tr -d '\r' < stdout.txt) <(tr -d '\r' < out.txt)); then failed="$failed $test" echo "::error::incremental gc failed: $test" fi diff --git a/Changes.md b/Changes.md index c8ac956c..18aed65c 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed two counts with HXCPP_GC_INCREMENTAL: Gc.memInfo64(MEM_INFO_LIVE) after an incremental cycle reported every used row as live, several times the bytes really live, where it is meant to report the last full reclaim, and Gc.trace with a cycle part done counted only the objects the cycle had not marked yet. MEM_INFO_LIVE changes only with a full reclaim now, and Gc.trace starts the cycle again, as __hxcpp_gc_census does (libhxcpp #453) * Fixed a cpp.Pointer field, or a pointer boxed in a Dynamic, letting what it points into be freed when it points further in than 64 bytes, or 32 on 32-bit, as cpp.Pointer.arrayElem(a, 100) does: the fix for Haxe 4's AtomicInt kept only what a stack word would keep. A pointer field keeps its whole allocation now, large ones included, and pins it under HXCPP_GC_MOVING (libhxcpp #451) * Fixed cppia hanging or crashing when several threads asked Std.isOfType about script objects, or cast them to host interfaces, at once: each question about an interface a class did not implement inserted into that class's table, unlocked, while other threads searched it. Loading modules on several threads at once could likewise fail with "No base defined for non-interface", or hang, as each load inserted the host class names it missed into a map the others walked. Both are only read after they are filled now (libhxcpp #466) * Fixed Semaphore.tryAcquire with a negative timeout waiting for ever, as tryAcquire(deadline - now) does once the deadline has passed: since the fix for Haxe 5's Lock.wait() (libhxcpp #420), any negative timeout meant no limit. Only -1, which Haxe 5.0.0-preview.1's Lock.wait() passes for no timeout, waits with no limit now, and any other negative timeout returns at once, as 0 does (libhxcpp #461) diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 171d3906..9818cefc 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -6565,13 +6565,20 @@ class GlobalAllocator { hx::IncrementalState &state = hx::IncrementalData(); bool active = hx::gIncrementalActive.load(std::memory_order_relaxed); - bool requested = hx::sIncrementalRequestMs > 0 && !sgCensus; + // A census, or Gc.trace, counts what this collection marks, so a cycle + // part done, whose earlier slices marked objects already, is failed and + // everything marked again: finishing it undercounted (libhxcpp #453) + bool counting = sgCensus; + #ifdef HXCPP_DEBUG + counting = counting || gCollectTrace; + #endif + bool requested = hx::sIncrementalRequestMs > 0 && !counting; if (active && !requested) { std::lock_guard lock(state.statsLock); state.forcedFinishes++; } - if (active && sgCensus) + if (active && counting) state.failed.store(true, std::memory_order_relaxed); if (active && hx::sIncrementalRequestMs == 0) { @@ -7064,11 +7071,10 @@ class GlobalAllocator STAMP(t5) size_t mem = mRowsInUse< Date: Thu, 19 Nov 2026 09:19:20 -0500 Subject: [PATCH 19/36] Make cppia's interpreter and JIT agree on array builtins Compared with the same code built as C++, which both now match: JIT: - Array and Array compound assignment stored the right hand side alone, and ++, --, insert and toString had no JIT code at all, so they did nothing ("Unknown ArrayBuiltinAny"). They call helpers sharing the interpreter's arithmetic, which catch, and the jitted code checks after each. - A Bool pushed, unshifted or set into an Array was stored as an Int. It goes in boxed. - Bitwise compound operators on an Array> did nothing: the bitwise cases fell through to the element's type for lack of a break. - An Int array's element read out of range as a String was "null", not "0". It reads the element type's zero. - ++d[i] on a Dynamic used as a statement decremented: the test was crement==coPostInc || crement==coPostInc. Interpreter: - A typed indexOf or lastIndexOf used as a Float returned 0 without running. - join and toString used as a statement, and iterator and keyValueIterator, were skipped, receiver and element toString calls with them. Test: CppiaArrayEngines, twelve lines, each wrong in one engine before and right in both now, interpreted and under the JIT on Windows x64. Fixes #468 --- Changes.md | 1 + src/hx/cppia/ArrayBuiltin.cpp | 26 ++- src/hx/cppia/ArrayVirtual.cpp | 174 +++++++++++++------ src/hx/cppia/Cppia.cpp | 2 +- test/regression/CppiaArrayEngines/Main.hx | 13 ++ test/regression/CppiaArrayEngines/Script.hx | 115 ++++++++++++ test/regression/CppiaArrayEngines/build.hxml | 7 + test/regression/CppiaArrayEngines/stdout.txt | 26 +++ 8 files changed, 306 insertions(+), 58 deletions(-) create mode 100644 test/regression/CppiaArrayEngines/Main.hx create mode 100644 test/regression/CppiaArrayEngines/Script.hx create mode 100644 test/regression/CppiaArrayEngines/build.hxml create mode 100644 test/regression/CppiaArrayEngines/stdout.txt diff --git a/Changes.md b/Changes.md index 18aed65c..ee8c8353 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed cppia's interpreter and JIT giving different results for array builtins, both of them now matching C++: under the JIT, a[i] += x and the other compound assignments on an Array stored x alone, a[i]++, insert and toString on one did nothing, a Bool stored in an Array became an Int, bitwise compound assignments on an Array> did nothing, an Int array read out of range as a String gave "null", and ++d[i] on a Dynamic as a statement decremented. Interpreted, a typed indexOf or lastIndexOf used as a Float gave 0, and join, toString and the iterators used as a statement did not run (libhxcpp #468) * Fixed two counts with HXCPP_GC_INCREMENTAL: Gc.memInfo64(MEM_INFO_LIVE) after an incremental cycle reported every used row as live, several times the bytes really live, where it is meant to report the last full reclaim, and Gc.trace with a cycle part done counted only the objects the cycle had not marked yet. MEM_INFO_LIVE changes only with a full reclaim now, and Gc.trace starts the cycle again, as __hxcpp_gc_census does (libhxcpp #453) * Fixed a cpp.Pointer field, or a pointer boxed in a Dynamic, letting what it points into be freed when it points further in than 64 bytes, or 32 on 32-bit, as cpp.Pointer.arrayElem(a, 100) does: the fix for Haxe 4's AtomicInt kept only what a stack word would keep. A pointer field keeps its whole allocation now, large ones included, and pins it under HXCPP_GC_MOVING (libhxcpp #451) * Fixed cppia hanging or crashing when several threads asked Std.isOfType about script objects, or cast them to host interfaces, at once: each question about an interface a class did not implement inserted into that class's table, unlocked, while other threads searched it. Loading modules on several threads at once could likewise fail with "No base defined for non-interface", or hang, as each load inserted the host class names it missed into a map the others walked. Both are only read after they are filled now (libhxcpp #466) diff --git a/src/hx/cppia/ArrayBuiltin.cpp b/src/hx/cppia/ArrayBuiltin.cpp index f4813b92..20669a1c 100644 --- a/src/hx/cppia/ArrayBuiltin.cpp +++ b/src/hx/cppia/ArrayBuiltin.cpp @@ -327,6 +327,9 @@ struct ArraySetter : public ArrayBuiltinBase case aoShr: case aoUShr: rightHandType = etInt; + // Fell through to the element's type, so on an Array> + // these did nothing under the JIT + break; default: rightHandType = elemType; @@ -737,7 +740,8 @@ struct ArrayBuiltin : public ArrayBuiltinBase return result; } - if (FUNC==afPush) + // indexOf and lastIndexOf used as a Float returned 0 without running + if (FUNC==afPush || FUNC==afIndexOf || FUNC==afLastIndexOf) return runInt(ctx); return 0.0; } @@ -1024,9 +1028,14 @@ struct ArrayBuiltin : public ArrayBuiltinBase runInt(ctx); if (FUNC==afConcat || FUNC==afCopy || FUNC==afReverse || FUNC==afSplice || FUNC==afSlice || - FUNC==afMap || FUNC==afFilter) + FUNC==afMap || FUNC==afFilter || FUNC==afIterator || FUNC==afKeyValueIterator) runObject(ctx); + // Statements too: they run the receiver and each element's toString, + // which were skipped, as the JIT and the other targets do not + if (FUNC==afJoin || FUNC==afToString) + runString(ctx); + if (FUNC==afReverse) { Array_obj *thisVal = (Array_obj*)thisExpr->runObject(ctx); @@ -1611,8 +1620,17 @@ struct ArrayBuiltin : public ArrayBuiltinBase // Check length.. JumpId lengthOk = compiler->compare( cmpI_LESS, sJitTemp0.as(jtInt), sJitTemp1.star(jtInt, ArrayBase::lengthOffset()) ); - // Out of bounds - return null / zero - compiler->returnNull(inDest, destType); + // Out of bounds - the element type's zero, as the interpreter + // and the other targets read it: an Int array's read as a + // String was "null", not "0" + ExprType outElemType = (ExprType)ExprTypeOf::value; + if ((outElemType==etInt || outElemType==etFloat) && (destType==etString || destType==etObject)) + { + compiler->move(sJitTemp2.as(jtInt), (int)0); + compiler->convert(sJitTemp2.as(jtInt), etInt, inDest, destType, isBoolElem()); + } + else + compiler->returnNull(inDest, destType); writtenNull = compiler->jump(); diff --git a/src/hx/cppia/ArrayVirtual.cpp b/src/hx/cppia/ArrayVirtual.cpp index 5dd014a7..3087abc6 100644 --- a/src/hx/cppia/ArrayVirtual.cpp +++ b/src/hx/cppia/ArrayVirtual.cpp @@ -206,6 +206,41 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase } const char *getName() HXCPP_OVERRIDE { return gArrayFuncNames[FUNC]; } + // a[i] op= val and ++ and --, for the interpreter and the JIT alike + static Dynamic applyAssign(Dynamic orig, Dynamic val) + { + switch(OP) + { + case aoAdd: return orig + val; + case aoMult: return orig * val; + case aoDiv: return orig / val; + case aoSub: return orig - val; + case aoAnd: return orig->__ToInt() & val->__ToInt(); + case aoOr: return orig->__ToInt() | val->__ToInt(); + case aoXOr: return orig->__ToInt() ^ val->__ToInt(); + case aoShl: return orig->__ToInt() << val->__ToInt(); + case aoShr: return orig->__ToInt() >> val->__ToInt(); + case aoUShr: return hx::UShr(orig,val); + case aoMod: return orig % val; + default: return val; + } + } + + static Dynamic applyCrement(ArrayAnyImpl *thisVal, int i) + { + if (OP==coPreInc) + return thisVal->__SetItem(i, thisVal->__GetItem(i) + 1); + if (OP==coPreDec) + return thisVal->__SetItem(i, thisVal->__GetItem(i) - 1); + + Dynamic result = thisVal->__GetItem(i); + if (OP==coPostDec) + thisVal->__SetItem(i, thisVal->__GetItem(i) - 1); + if (OP==coPostInc) + thisVal->__SetItem(i, thisVal->__GetItem(i) + 1); + return result; + } + int runInt(CppiaCtx *ctx) HXCPP_OVERRIDE { if (FUNC==afPush) @@ -336,62 +371,14 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase Dynamic val = args[1]->runObject(ctx); BCR_CHECK; - switch(OP) - { - case aoSet: break; - - case aoAdd: - val = orig + val; - break; - case aoMult: - val = orig * val; - break; - case aoDiv: - val = orig / val; - break; - case aoSub: - val = orig - val; - break; - case aoAnd: - val = orig->__ToInt() & val->__ToInt(); - break; - case aoOr: - val = orig->__ToInt() | val->__ToInt(); - break; - case aoXOr: - val = orig->__ToInt() ^ val->__ToInt(); - break; - case aoShl: - val = orig->__ToInt() << val->__ToInt(); - break; - case aoShr: - val = orig->__ToInt() >> val->__ToInt(); - break; - case aoUShr: - val = hx::UShr(orig,val); - break; - case aoMod: - val = orig % val; - break; - default: ; - } + val = applyAssign(orig, val); return thisVal->__SetItem(i,val).mPtr; } if (FUNC==af__crement) { int i = args[0]->runInt(ctx); BCR_CHECK; - if (OP==coPreInc) - return thisVal->__SetItem(i, thisVal->__GetItem(i) + 1).mPtr; - if (OP==coPreDec) - return thisVal->__SetItem(i, thisVal->__GetItem(i) - 1).mPtr; - - Dynamic result = thisVal->__GetItem(i); - if (OP==coPostDec) - thisVal->__SetItem(i, thisVal->__GetItem(i) - 1); - if (OP==coPostInc) - thisVal->__SetItem(i, thisVal->__GetItem(i) + 1); - return result.mPtr; + return applyCrement(thisVal, i).mPtr; } if (FUNC==afPop) @@ -696,6 +683,49 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase } + // Compound assignment, ++ and --, insert and toString, which the JIT did + // not compile: a[i] op= val stored val alone, and the others did nothing + // (libhxcpp #468). They work as the interpreter does + static hx::Object * SLJIT_CALL runAssign(ArrayAnyImpl *inArray, int inIndex, hx::Object *inValue) + { + TRY_NATIVE + Dynamic orig = inArray->__GetItem(inIndex); + if (!orig.mPtr) + NullReference("Object", false); + return inArray->__SetItem(inIndex, applyAssign(orig, Dynamic(inValue))).mPtr; + CATCH_NATIVE + return 0; + } + + static hx::Object * SLJIT_CALL runCrement(ArrayAnyImpl *inArray, int inIndex) + { + TRY_NATIVE + return applyCrement(inArray, inIndex).mPtr; + CATCH_NATIVE + return 0; + } + + static void SLJIT_CALL runInsert(ArrayAnyImpl *inArray, hx::Object *inPos, hx::Object *inValue) + { + TRY_NATIVE + inArray->CALL(insert)(Dynamic(inPos), Dynamic(inValue)); + CATCH_NATIVE + } + + static void SLJIT_CALL runToString(ArrayAnyImpl *inArray, String *outValue) + { + TRY_NATIVE + JitStore(outValue, inArray->toString()); + CATCH_NATIVE + } + + // A Bool goes in boxed, as a Bool: the Int paths stored it as an Int + static ExprType anyStoreType(CppiaExpr *inValue) + { + ExprType type = inValue->getType(); + return type==etInt && inValue->isBoolInt() ? etObject : type; + } + void genCode(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) HXCPP_OVERRIDE { JitTemp thisVal(compiler,etObject); @@ -856,7 +886,16 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase JitTemp index(compiler,etInt); args[0]->genCode(compiler, index, etInt); - switch(args[1]->getType()) + if (OP!=aoSet) + { + args[1]->genCode(compiler, sJitArg2.as(jtPointer), etObject); + compiler->callNative( (void *)runAssign, thisVal, index, sJitArg2.as(jtPointer)); + compiler->checkException(); + compiler->convertReturnReg(etObject, inDest, destType); + break; + } + + switch(anyStoreType(args[1])) { case etInt: args[1]->genCode(compiler, sJitArg2.as(jtInt), etInt); @@ -897,7 +936,7 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case afPush: { - switch(args[0]->getType()) + switch(anyStoreType(args[0])) { case etInt: args[0]->genCode(compiler, sJitArg1.as(jtInt), etInt); @@ -934,7 +973,7 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case afUnshift: { - switch(args[0]->getType()) + switch(anyStoreType(args[0])) { case etInt: args[0]->genCode(compiler, sJitArg1.as(jtInt), etInt); @@ -970,6 +1009,35 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase + case af__crement: + { + JitTemp index(compiler,etInt); + args[0]->genCode(compiler, index, etInt); + compiler->callNative( (void *)runCrement, thisVal, index); + compiler->checkException(); + compiler->convertReturnReg(etObject, inDest, destType); + } + break; + + case afInsert: + { + JitTemp pos(compiler,jtPointer); + args[0]->genCode(compiler, pos, etObject); + args[1]->genCode(compiler, sJitArg2.as(jtPointer), etObject); + compiler->callNative( (void *)runInsert, thisVal, pos, sJitArg2.as(jtPointer)); + compiler->checkException(); + } + break; + + case afToString: + { + JitTemp result(compiler,jtString); + compiler->callNative( (void *)runToString, thisVal, result); + compiler->checkException(); + compiler->convert(result, etString, inDest, destType); + } + break; + default: compiler->traceStrings("Unknown ArrayBuiltinAny:", getName() ); } diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 232abe58..3fa89ce1 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -5934,7 +5934,7 @@ struct DynamicArrayI : public CppiaDynamicExpr index->genCode(compiler, sJitTemp1, etInt); if (destType==etVoid || destType==etNull) { - compiler->callNative( crement==coPostInc || crement==coPostInc ? (void *)incItem : (void *)decItem, + compiler->callNative( crement==coPostInc || crement==coPreInc ? (void *)incItem : (void *)decItem, obj, sJitTemp1.as(jtInt) ); compiler->checkException(); } diff --git a/test/regression/CppiaArrayEngines/Main.hx b/test/regression/CppiaArrayEngines/Main.hx new file mode 100644 index 00000000..e1b4cc7a --- /dev/null +++ b/test/regression/CppiaArrayEngines/Main.hx @@ -0,0 +1,13 @@ +// Runs the script interpreted and then under the JIT +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); + Sys.println(jit ? "jit" : "interpreted"); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} diff --git a/test/regression/CppiaArrayEngines/Script.hx b/test/regression/CppiaArrayEngines/Script.hx new file mode 100644 index 00000000..15ae93a1 --- /dev/null +++ b/test/regression/CppiaArrayEngines/Script.hx @@ -0,0 +1,115 @@ +// libhxcpp #468: array builtins where the cppia interpreter and JIT disagreed. +// Each line is printed by both, and is what the other targets print. +class Obj { + public function new() {} + + public function toString() { + Script.calls++; + return "obj"; + } +} + +class Script { + public static var calls = 0; + static var got = 0; + + static function main() { + anyCompound(); + anyCrement(); + anyOthers(); + anyBools(); + nullIntBits(); + nullIntArith(); + searchAsFloat(); + statements(); + outOfRange(); + dynamicCrement(); + } + + static function anyCompound() { + var a:Array = [1, 2, 3, 4, 5]; + a[0] += 10; + a[1] *= 5; + a[2] |= 8; + a[3] -= 1; + a[4] <<= 2; + Sys.println("Array compound: " + a); + } + + static function anyCrement() { + var a:Array = [1, 2, 3]; + a[0]++; + var x = a[1]--; + var y = ++a[2]; + Sys.println("Array crement: " + a + " x=" + x + " y=" + y); + } + + static function anyOthers() { + var a:Array = [1, 2]; + a.insert(0, "z"); + Sys.println("Array insert: " + a); + var s:String = a.toString(); + Sys.println("Array toString: " + s); + } + + static function anyBools() { + var flag = true; + var b:Array = []; + b.push(flag); + b.unshift(false); + b[2] = true; + Sys.println("Array bools: " + b + " " + [for (x in b) Std.isOfType(x, Bool)]); + } + + static function nullIntBits() { + var n:Array> = [1, 2, 3, 16, 16, 7]; + n[0] |= 4; + n[1] <<= 2; + n[2] ^= 1; + n[3] >>= 2; + n[4] >>>= 1; + n[5] &= 3; + Sys.println("Array> bits: " + n); + } + + static function nullIntArith() { + var n:Array> = [1, 2, 3]; + n[0] += 4; + n[1] *= 3; + n[2] -= 1; + Sys.println("Array> arith: " + n); + } + + static function searchAsFloat() { + var a = [1, 2, 3]; + var f = 0.5 + a.indexOf(3); + var g = 0.5 + a.lastIndexOf(1); + var h:Float = a.indexOf(2); + Sys.println("indexOf as a Float: " + f + " " + g + " " + h); + } + + static function arr():Array { + got++; + return [new Obj()]; + } + + static function statements() { + arr().join(","); + Sys.println("join as a statement: receiver evaluated " + got + ", toString calls " + calls); + arr().toString(); + Sys.println("toString as a statement: receiver evaluated " + got + ", toString calls " + calls); + } + + static function outOfRange() { + var ints = [1, 2]; + var floats = [1.5]; + Sys.println("out of range as a String: " + ints[5] + " " + floats[3]); + } + + static function dynamicCrement() { + var d:Dynamic = [1, 2]; + ++d[0]; + d[1]++; + Sys.println("++ on a Dynamic array as a statement: " + d); + } +} diff --git a/test/regression/CppiaArrayEngines/build.hxml b/test/regression/CppiaArrayEngines/build.hxml new file mode 100644 index 00000000..d20d36bd --- /dev/null +++ b/test/regression/CppiaArrayEngines/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/CppiaArrayEngines/stdout.txt b/test/regression/CppiaArrayEngines/stdout.txt new file mode 100644 index 00000000..c321ee9e --- /dev/null +++ b/test/regression/CppiaArrayEngines/stdout.txt @@ -0,0 +1,26 @@ +interpreted +Array compound: [11,10,11,3,20] +Array crement: [2,1,4] x=2 y=4 +Array insert: [z,1,2] +Array toString: [z,1,2] +Array bools: [false,true,true] [true,true,true] +Array> bits: [5,8,2,4,8,3] +Array> arith: [5,6,2] +indexOf as a Float: 2.5 0.5 1 +join as a statement: receiver evaluated 1, toString calls 1 +toString as a statement: receiver evaluated 2, toString calls 2 +out of range as a String: 0 0 +++ on a Dynamic array as a statement: [2,3] +jit +Array compound: [11,10,11,3,20] +Array crement: [2,1,4] x=2 y=4 +Array insert: [z,1,2] +Array toString: [z,1,2] +Array bools: [false,true,true] [true,true,true] +Array> bits: [5,8,2,4,8,3] +Array> arith: [5,6,2] +indexOf as a Float: 2.5 0.5 1 +join as a statement: receiver evaluated 1, toString calls 1 +toString as a statement: receiver evaluated 2, toString calls 2 +out of range as a String: 0 0 +++ on a Dynamic array as a statement: [2,3] From 86036f3b581fc19acf1693cabc9e4f27c1cf413c Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 09:27:41 -0500 Subject: [PATCH 20/36] Refuse the malformed cppia files that crashed the host SECURITY.md promises a load error for a malformed .cppia file, but these crashed the host, interpreted, under the JIT, or both: - MAIN in a module with no types: ScriptCallable::link read the type of its return, 0, from an empty table. Return type ids are checked. - An unknown script enum constructor left a null value that was dereferenced, and a call with the wrong number of arguments wrote past the enum value under the JIT. Both fail to link. - Two classes with one type id: the second overwrote the first's and wrote outside the vtable made for it. It fails to load. - A string constant id, and the text format's file id, were read unchecked, and the string table grew to them: by 100000000 entries, 1.4 GB, for a file id, and the JIT's addresses of its strings were left dangling. They are checked as other string ids are. - An enum parameter index past the value read past it. A script enum's constructors bound it at link, and otherwise the interpreter and the JIT check the value's own parameter count. - break or continue outside a loop made sljit assert under the JIT, ending the process. The function fails to compile instead, checked on the pass that emits code, since the measuring pass has no labels. - A super constructor call to a script class other than the super class ran that constructor on an instance laid out for this one. It fails to link, after the check for a class with no constructor. CppiaMalformedConstructors' control, such a call from a static main, is refused now too. Test: CppiaMalformedLoads, ten such files, loaded and run interpreted and with the JIT compiling as it loads. Before, the host crashed on the first; now each fails to load or runs safely. The cppia suite and the 60 Cppia regression tests pass, interpreted and under the JIT, on Windows x64. Fixes #467 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 49 +++++++++++++++++-- src/hx/cppia/Cppia.h | 2 + src/hx/cppia/CppiaClasses.cpp | 20 ++++++++ src/hx/cppia/CppiaCompiler.cpp | 7 +++ src/hx/cppia/CppiaFunction.cpp | 4 ++ src/hx/cppia/CppiaModule.cpp | 16 +++++- src/hx/cppia/CppiaStream.h | 5 +- .../CppiaMalformedConstructors/stdout.txt | 4 +- test/regression/CppiaMalformedLoads/Files.hx | 15 ++++++ test/regression/CppiaMalformedLoads/Main.hx | 28 +++++++++++ .../regression/CppiaMalformedLoads/build.hxml | 4 ++ .../regression/CppiaMalformedLoads/stdout.txt | 26 ++++++++++ test/regression/emscripten-skip.txt | 1 + 14 files changed, 170 insertions(+), 12 deletions(-) create mode 100644 test/regression/CppiaMalformedLoads/Files.hx create mode 100644 test/regression/CppiaMalformedLoads/Main.hx create mode 100644 test/regression/CppiaMalformedLoads/build.hxml create mode 100644 test/regression/CppiaMalformedLoads/stdout.txt diff --git a/Changes.md b/Changes.md index ee8c8353..cbc84fda 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed malformed cppia files crashing the host instead of failing to load: a MAIN in a module with no types, an unknown script enum constructor or one called with the wrong number of arguments, two classes with one type id, a string constant or file id past the string table, which grew the table to it, an enum parameter index past the value, break or continue outside a loop under the JIT, and a super constructor call to a class other than the super class. Each fails to load, or is read safely (libhxcpp #467) * Fixed cppia's interpreter and JIT giving different results for array builtins, both of them now matching C++: under the JIT, a[i] += x and the other compound assignments on an Array stored x alone, a[i]++, insert and toString on one did nothing, a Bool stored in an Array became an Int, bitwise compound assignments on an Array> did nothing, an Int array read out of range as a String gave "null", and ++d[i] on a Dynamic as a statement decremented. Interpreted, a typed indexOf or lastIndexOf used as a Float gave 0, and join, toString and the iterators used as a statement did not run (libhxcpp #468) * Fixed two counts with HXCPP_GC_INCREMENTAL: Gc.memInfo64(MEM_INFO_LIVE) after an incremental cycle reported every used row as live, several times the bytes really live, where it is meant to report the last full reclaim, and Gc.trace with a cycle part done counted only the objects the cycle had not marked yet. MEM_INFO_LIVE changes only with a full reclaim now, and Gc.trace starts the cycle again, as __hxcpp_gc_census does (libhxcpp #453) * Fixed a cpp.Pointer field, or a pointer boxed in a Dynamic, letting what it points into be freed when it points further in than 64 bytes, or 32 on 32-bit, as cpp.Pointer.arrayElem(a, 100) does: the fix for Haxe 4's AtomicInt kept only what a stack word would keep. A pointer field keeps its whole allocation now, large ones included, and pins it under HXCPP_GC_MOVING (libhxcpp #451) diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 3fa89ce1..6bd7f586 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -3567,6 +3567,10 @@ struct CallMember : public CppiaExpr // malformed file calls one where neither has any if (!type->cppiaClass->newFunc) throw "Super constructor call on a class with no constructor"; + // A class's constructor calls its own super class's. Any other script + // class's ran on an instance laid out for this one, past its end + if (inModule.linkingClass && classId!=inModule.linkingClass->superId) + throw "Super constructor call to a class that is not the super class"; //CPPIALOG("Using cppia super %p %p\n", type->cppiaClass->newFunc, type->cppiaClass->newFunc->funExpr); CppiaExpr *replace = new CallFunExpr( this, 0, (ScriptCallable*)type->cppiaClass->newFunc->funExpr, args, true ); replace->link(inModule); @@ -6426,11 +6430,13 @@ struct EnumIExpr : public CppiaDynamicExpr CppiaExpr *object; int index; int classId; + // Whether link bounded index by the enum's constructors + bool indexChecked; - EnumIExpr(CppiaStream &stream) + EnumIExpr(CppiaStream &stream) : indexChecked(false) { - classId = stream.getInt(); + classId = stream.getTypeId(); index = stream.getInt(); object = createCppiaExpr(stream); } @@ -6438,6 +6444,18 @@ struct EnumIExpr : public CppiaDynamicExpr const char *getName() HXCPP_OVERRIDE { return "EnumIExpr"; } CppiaExpr *link(CppiaModule &inModule) HXCPP_OVERRIDE { + // An index from the file read past the enum value. A script enum's + // largest constructor bounds it here, for the JIT, which reads the + // parameter directly; the interpreter checks the value's own count + if (index<0) + throw "Bad enum index"; + CppiaClassInfo *info = inModule.types[classId]->cppiaClass; + if (info && info->isEnum) + { + if (index>=info->mostEnumArgs()) + throw "Bad enum index"; + indexChecked = true; + } object = object->link(inModule); return this; } @@ -6446,15 +6464,36 @@ struct EnumIExpr : public CppiaDynamicExpr { hx::Object *obj = object->runObject(ctx); BCR_CHECK; - return static_cast(obj)->_hx_getParamI(index).mPtr; + EnumBase_obj *value = static_cast(obj); + if (index>=value->_hx_getParamCount()) + return 0; + return value->_hx_getParamI(index).mPtr; } #ifdef CPPIA_JIT + static hx::Object * SLJIT_CALL paramChecked(hx::Object *inValue, int inIndex) + { + EnumBase_obj *value = static_cast(inValue); + if (!value || inIndex>=value->_hx_getParamCount()) + return 0; + return value->_hx_getParamI(inIndex).mPtr; + } + void genCode(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) HXCPP_OVERRIDE { object->genCode(compiler, sJitTemp0, etObject); - int offset = sizeof( EnumBase_obj ) + index*sizeof(cpp::Variant); - compiler->genVariantValueTemp0(offset, inDest, destType); + if (indexChecked) + { + int offset = sizeof( EnumBase_obj ) + index*sizeof(cpp::Variant); + compiler->genVariantValueTemp0(offset, inDest, destType); + } + else + { + // A host enum's constructors are not known here, so its value's own + // count bounds the read, as in the interpreter + compiler->callNative( (void *)paramChecked, sJitTemp0.as(jtPointer), JitVal(index) ); + compiler->convertReturnReg(etObject, inDest, destType); + } } #endif }; diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 27114510..8b1f8bd8 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -846,6 +846,8 @@ class CppiaClassInfo : public CppiaOwned inline ScriptCallable *findStaticSetter(const String &inName) { return findFunction(staticSetters,inName); } CppiaEnumConstructor *findEnum(int inFieldId); + // The most arguments any of an enum's constructors takes + int mostEnumArgs(); ExprType findFunctionType(CppiaModule &inModule, int inName); CppiaFunction *findVTableFunction(int inId); int findFunctionSlot(int inName); diff --git a/src/hx/cppia/CppiaClasses.cpp b/src/hx/cppia/CppiaClasses.cpp index 7d2de972..a520f502 100644 --- a/src/hx/cppia/CppiaClasses.cpp +++ b/src/hx/cppia/CppiaClasses.cpp @@ -408,6 +408,13 @@ struct EnumField : public CppiaDynamicExpr if (!type->cppiaClass->isEnum) throw "Field of non-enum"; value = type->cppiaClass->findEnum(fieldId); + // Was a null value, dereferenced when used or compiled + if (!value) + throw "Unknown enum constructor"; + // A call with arguments to a constructor that takes others; none + // is the constructor as a function + if (args.size() && args.size()!=value->args.size()) + throw "Bad enum arg count"; } else { @@ -851,6 +858,15 @@ void CppiaClassInfo::dump() dumpVars("Static dyns",staticDynamicFunctions); } +int CppiaClassInfo::mostEnumArgs() +{ + size_t most = 0; + for(size_t i=0;iargs.size()>most) + most = enumConstructors[i]->args.size(); + return (int)most; +} + CppiaEnumConstructor *CppiaClassInfo::findEnum(int inFieldId) { for(int i=0;icppiaClass) + throw "Duplicate class"; cppia.types[typeId]->cppiaClass = this; } else diff --git a/src/hx/cppia/CppiaCompiler.cpp b/src/hx/cppia/CppiaCompiler.cpp index 7fad214f..51942dfb 100644 --- a/src/hx/cppia/CppiaCompiler.cpp +++ b/src/hx/cppia/CppiaCompiler.cpp @@ -470,13 +470,20 @@ class CppiaJitCompiler : public CppiaCompiler return oldPos; } + // Outside a loop there is nowhere to go, and sljit asserted, ending the + // process. Haxe emits neither there, so only a malformed file has one. The + // first pass, which only measures, has no labels, so it cannot tell void addContinue() HXCPP_OVERRIDE { + if (compiler && !continuePos) + setError("Continue outside a loop"); jump(continuePos); } void addBreak() HXCPP_OVERRIDE { + if (compiler && !continuePos) + setError("Break outside a loop"); allBreaks.push( jump(0) ); } diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index 714150d0..ddb41a83 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -169,6 +169,10 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) inModule.layout = &layout; data = &inModule; + // A module's main, which names no type, uses the first, which a malformed + // module may not have + if (returnTypeId<0 || returnTypeId>=(int)inModule.types.size()) + throw "Bad type id"; returnType = inModule.types[ returnTypeId ]->expressionType; isBoolReturn = inModule.types[ returnTypeId ]->haxeClass==ClassOf(); layout.returnType = returnType; diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index 428114bf..87702ee6 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -426,7 +426,9 @@ void CppiaConst::fromStream(CppiaStream &stream) else if (tok[0]=='s') { type = cString; - ival = stream.getInt(); + // Checked: a bad id grew the string table to it, leaving the addresses + // of its strings that the JIT had built into code dangling + ival = stream.getStringId(); } else if (tok=="NULL") type = cNull; @@ -765,6 +767,18 @@ int CppiaStream::getStringId() return id; } +// The text format names each expression's file by a string id. A bad one grew +// the string table to it when the file name was read: 1.4 GB for 100000000 +int CppiaStream::getFileId() +{ + if (binary) + return 0; + int id = getInt(); + if (id<0 || (id>0 && id>=module->strings->length)) + throw "Bad file id"; + return id; +} + CppiaLoadedModule LoadCppia(const unsigned char *inData, int inDataLength) { CppiaModule *cppiaPtr = new CppiaModule(); diff --git a/src/hx/cppia/CppiaStream.h b/src/hx/cppia/CppiaStream.h index ec0a49ce..97e08b6b 100644 --- a/src/hx/cppia/CppiaStream.h +++ b/src/hx/cppia/CppiaStream.h @@ -72,10 +72,7 @@ struct CppiaStream { return binary ? 0 : getInt(); } - int getFileId() - { - return binary ? 0 : getInt(); - } + int getFileId(); void skipChar() { if (data>=max) diff --git a/test/regression/CppiaMalformedConstructors/stdout.txt b/test/regression/CppiaMalformedConstructors/stdout.txt index 4b4b161e..6c1a36c4 100644 --- a/test/regression/CppiaMalformedConstructors/stdout.txt +++ b/test/regression/CppiaMalformedConstructors/stdout.txt @@ -4,7 +4,7 @@ super call into a class with no constructor threw: Super constructor call on a c super call into an interface threw: Super constructor call on a class with no constructor super call into a constructor that is a return threw: Constructor is not a function super call into an interface with a constructor threw: Constructor is not a function -super call into a constructor loaded and ran +super call into a constructor threw: Super constructor call to a class that is not the super class new of a constructor that is a return threw: Constructor is not a function new of an interface threw: Could not link new Bar new of a class with no constructor loaded and ran @@ -18,7 +18,7 @@ super call into a class with no constructor threw: Super constructor call on a c super call into an interface threw: Super constructor call on a class with no constructor super call into a constructor that is a return threw: Constructor is not a function super call into an interface with a constructor threw: Constructor is not a function -super call into a constructor loaded and ran +super call into a constructor threw: Super constructor call to a class that is not the super class new of a constructor that is a return threw: Constructor is not a function new of an interface threw: Could not link new Bar new of a class with no constructor loaded and ran diff --git a/test/regression/CppiaMalformedLoads/Files.hx b/test/regression/CppiaMalformedLoads/Files.hx new file mode 100644 index 00000000..040e9da2 --- /dev/null +++ b/test/regression/CppiaMalformedLoads/Files.hx @@ -0,0 +1,15 @@ +// The malformed files, from the cases in libhxcpp #467, base64 encoded +class Files { + public static final all:Array<{name:String, data:String}> = [ + {name: "MAIN with no types", data: "Q1BQSUEgMSAxIGEgMCAwIE1BSU4gMCAwIE5VTEwgUkVTT1VSQ0VTIDAg"}, + {name: "unknown enum constructor", data: "Q1BQSUIKMTQKMCAKMSBBCjEgQgoxIHgKNCBtYWluCjEgYQoxIGIKNyBfaHhfdG1wCjUgdHJhY2UKOCBfaHhfdG1wMQo2IHN0cmluZwoxICAKNiBTY3JpcHQKOSBTY3JpcHQuaHgKOQowIAoxIEUKMyBpbnQKNiBTY3JpcHQKNCB2b2lkCjcgRHluYW1pYwo4IGhheGUuTG9nCjYgU3RyaW5nCjMgU3RkCjIKSQECAQACAQMCAEQDAAABAQEABAQABwQACQUqASwF/o8WAAEBIAEDKgEsBv6QFgABARYBAgE5ASoBLAf+8iQABQUcBggqASwJ/vQkAAcHZREICgEC/o8WOwsPAgL+8iRlAv70JBEICgEC/pAWMA0KDARLEQMEAE0A"}, + {name: "enum constructor with the wrong argument count", data: "Q1BQSUIKMTQKMCAKMSBBCjEgQgoxIHgKNCBtYWluCjEgYQoxIGIKNyBfaHhfdG1wCjUgdHJhY2UKOCBfaHhfdG1wMQo2IHN0cmluZwoxICAKNiBTY3JpcHQKOSBTY3JpcHQuaHgKOQowIAoxIEUKMyBpbnQKNiBTY3JpcHQKNCB2b2lkCjcgRHluYW1pYwo4IGhheGUuTG9nCjYgU3RyaW5nCjMgU3RkCjIKSQECAQACAQMCAEQDAAABAQEABAQABwQACQUqASwF/o8WAAEBIAEBKgEsBv6QFgABARYBAwE5ASoBLAf+8iQABQUcBggqASwJ/vQkAAcHZREICgEC/o8WOwsPAgL+8iRlAv70JBEICgEC/pAWMA0KDARLEQMEAE0A"}, + {name: "two classes with one type id", data: "Q1BQSUIKMjgKMCAKMyBuZXcKNSBoZWxsbwozIGdldAoxIGsKMyBzZXQKMSB2CjYgZXhpc3RzCjYgcmVtb3ZlCjQga2V5cwo4IGl0ZXJhdG9yCjE2IGtleVZhbHVlSXRlcmF0b3IKNCBjb3B5CjggdG9TdHJpbmcKNiBNYXBpc2gKNSBjbGVhcgo0IG1haW4KMSBtCjUgdHJhY2UKOSBtYWluIHJhbiAKMSBhCjYgU2NyaXB0CjkgU2NyaXB0Lmh4CjUgYXJyYXkKNyBjdXJyZW50CjcgaGFzTmV4dAo2IGxlbmd0aAo0IG5leHQKMTYKMCAKNSBQbGFpbgo0IHZvaWQKMyBpbnQKNiBNYXBpc2gKOSBoYXhlLklNYXAKNyBEeW5hbWljCjYgU3RyaW5nCjQgYm9vbAoyOCBoYXhlLml0ZXJhdG9ycy5BcnJheUl0ZXJhdG9yCjEyIEFycmF5LlN0cmluZwo5IEFycmF5LmludAo0IG51bGwKNiBTY3JpcHQKOCBoYXhlLkxvZwo5IEFycmF5LkFueQo0CkQEAAACAQEAAQEABwIACQABAAACAwAHAwAJAS8DOQFEBAABBQsBAQABBAAHAgAJAAEAAAMGAQQABwcGAQT+jxYABwAJAS8DOQEBAAAFAgIEAAcGAAMHAgIE/pAWAAcABv6RFgADAAkAAQAABwgBBAAHBwgBBP6SFgAHAAkBLwg9AQAACAgBBAAHBwgBBP6TFgAHAAkBLwg8AQAACQYABwYACQEvCS0JAQQXCgABAAAKBgAHBgAJAS8JLQkBBBcLAAEAAAsGAAcGAAkBLww+AQAADAUABwUACQEvBD8BAAANBwAHBwAJAS8HOw4BAAAPAgAHAgAJAEQNAAABAQEAEAIABwIACQIqASwR/pgWAAQELQQADwIcDhJlOxMSBAMBAv6YFjsUMBYlFRBECQAABQEBAAEJARcADwcCARf+3xUADwAJAg4dCRg5AA4dCRcC/t8VAgBFRQAXDwACAEVFABgDAAEAABkIAAcIAAkBLwhvHQkYHg8aHQkXAQAAGwYABwYACQEvBiIPHQkXJB0JGEsRDRAATQA="}, + {name: "a string constant past the string table", data: "Q1BQSUIKMjMKMCAKMSBmCjEgcwozIGFiYwoxIGcKMyBrZXkKNCBtYWluCjUgdHJhY2UKNiBTY3JpcHQKOSBTY3JpcHQuaHgKMyBydW4KNCBmaWxsCjQgbHBhZAoxIEEKNCBrZWVwCjIgX2cKMSBpCjMgbmV3CjUgYXJyYXkKNyBjdXJyZW50CjcgaGFzTmV4dAo2IGxlbmd0aAo0IG5leHQKMTMKMCAKNiBTY3JpcHQKNiBTdHJpbmcKNyBEeW5hbWljCjQgdm9pZAo4IGhheGUuTG9nCjkgY3BwLnZtLkdjCjExIFN0cmluZ1Rvb2xzCjEyIEFycmF5LlN0cmluZwozIGludAoyOCBoYXhlLml0ZXJhdG9ycy5BcnJheUl0ZXJhdG9yCjkgQXJyYXkuQW55CjQgYm9vbAoyCkQBAAADAQEAAQIBAgECBwIBAv6PFgACATv+6AMJAS8CAv6PFgEBAAQDAAcDAAkBLwMxAQU5AQEBAAYEAAcEAAkHDwIcBQcRAQQAMAkLCAYPAhwFBxEBAQE+MAkMCAYRBgoBPSoBLAv+uRYAAgIRBwwDOwA7DTlAKgEsDv66FgAICBcIAAkCKgEsD/68FgAJCTkAMwFvAv68Fjn/QA0DAAkCKgEsEP67FgAJCSQC/rwWDiIIAv66FngC/rsWOf6IE2UC/rkWAv67Fg8CHAUHEQEEADAJEggGRAoAAAUBAQARCgESAAsHBAES/t8VAAsACQIOHQoTOQAOHQoSAv7fFQIARUUAEgsAAgBFRQATCQABAAAUDAAHDAAJAS8Mbx0KEx4LFR0KEgEAABYDAAcDAAkBLwMiCx0KEiQdChNLEQEGAE0A"}, + {name: "an enum parameter index past its constructors", data: "Q1BQSUIKOQowIAoxIEIKMSB4CjQgbWFpbgoxIGUKNSB0cmFjZQoyIHg9CjYgU2NyaXB0CjkgU2NyaXB0Lmh4CjcKMCAKMSBFCjMgaW50CjYgU2NyaXB0CjQgdm9pZAo3IER5bmFtaWMKOCBoYXhlLkxvZwoyCkkBAQEBAgIARAMAAAEBAQADBAAHBAAJAioBLAT+jxYAAQEWAQEBOQEJAioBLAL+mRYAAgI1Bf+ghgEAAv6PFg8CHAYFZTsGAv6ZFjAICgcDSxEDAwBNAA=="}, + {name: "a file id past the string table", data: "Q1BQSUEgMSAxIGEgMSAwICAwIE1BSU4gMTAwMDAwMDAwIDAgTlVMTCBSRVNPVVJDRVMgMCA="}, + {name: "break outside a loop", data: "Q1BQSUIKNgowIAoxIGYKNCBtYWluCjUgdHJhY2UKNiBTY3JpcHQKOSBTY3JpcHQuaHgKNQowIAo2IFNjcmlwdAo0IGJvb2wKNCB2b2lkCjggaGF4ZS5Mb2cKMQpEAQAAAgEBAAECAAcCAAkBLwIKAQEAAgMABwMACQEPAhwEAxEBAQAwBQcEAksRAQIATQA="}, + {name: "continue outside a loop", data: "Q1BQSUIKNgowIAoxIGYKNCBtYWluCjUgdHJhY2UKNiBTY3JpcHQKOSBTY3JpcHQuaHgKNQowIAo2IFNjcmlwdAo0IGJvb2wKNCB2b2lkCjggaGF4ZS5Mb2cKMQpEAQAAAgEBAAECAAcCAAkBLwILAQEAAgMABwMACQEPAhwEAxEBAQAwBQcEAksRAQIATQA="}, + {name: "a super call to a class that is not the super class", data: "Q1BQSUIKMzYKMCAKMyBuZXcKMSBhCjEgMQoxIGIKMSAyCjEgYwoxIDMKMSBkCjEgNAo0IG1haW4KNCBpbnRzCjIgX2cKMSBpCjQgcHVzaAozIF9nMQoyIGkxCjMgcnVuCjQgb2JqcwozIF9nMgoyIGkyCjMgYmFkCjMgX2czCjIgaTMKMyBfZzQKMyBfZzUKNiBsZW5ndGgKMSB2CjUgdHJhY2UKMTYgY29ycnVwdGVkIGludHM6IAo2IFNjcmlwdAo5IFNjcmlwdC5oeAo1IGFycmF5CjcgY3VycmVudAo3IGhhc05leHQKNCBuZXh0CjE1CjAgCjQgQmFzZQo0IHZvaWQKNiBTdHJpbmcKNyBEZXJpdmVkCjYgU2NyaXB0CjEyIEFycmF5Lk9iamVjdAozIGludAo5IEFycmF5LmludAo5IGNwcC52bS5HYwo4IGhheGUuTG9nCjI4IGhheGUuaXRlcmF0b3JzLkFycmF5SXRlcmF0b3IKOSBBcnJheS5BbnkKNCBib29sCjcgRHluYW1pYwo0CkQBAAAFAQEAAQEABwIACQQOHQECOwMOHQEEOwUOHQEGOwcOHQEIOwkCAEVFAAIDAAIARUUABAMAAgBFRQAGAwACAEVFAAgDAEQEAAABAQEAAQQABwIACQEVAQBEBQAAAQEBAAoCAAcCAAkJKgEsC/6PFgAGBhcGAAkCKgEsDP6RFgAHBzkAMwFvAv6RFjn/oIYBAAkCKgEsDf6QFgAHByQC/pEWEgYOAQL+jxYXCAQC/pAWAv6QFgL+kBYC/pAWCQIqASwP/pMWAAcHOQAzAW8C/pMWOf+ghgEACQIqASwQ/pIWAAcHJAL+kxYYanh1Av6SFjkDOQI5AAkBDiIGAv6PFgL+khY+EQkRAT0qASwS/pUWAAYGFwYACQIqASwT/pcWAAcHOQAzAW8C/pcWOf5QwwkCKgEsFP6WFgAHByQC/pcWEgYOAQL+lRYtBAAqASwV/pgWAAcHOQAJAioBLBb+nRYABwc5ADMBbwL+nRY5/6CGAQAJAioBLBf+mRYABwckAv6dFhgNIgYC/o8WAv6ZFgkDKgEsGP6bFgAHBzkAKgEsGf6cFgAICCIGAv6PFgL+mRYzAW8C/psWHggaAv6cFgkDKgEsG/6aFgAHByIIAv6cFgL+mxYjAv6bFhhrAv6aFgL+mRYJASMC/pgWDwIcChxlOx0C/pgWMB8oHgpECwAABQEBAAELASAADAcCASD+3xUADAAJAg4dCyE5AA4dCyAC/t8VAgBFRQAgDAACAEVFACEHAAEAACINAAcNAAkBLw1vHQshHgwaHQsgAQAAIw4ABw4ACQEvDiIMHQsgJB0LIUsRBQoATQA="}, + ]; +} diff --git a/test/regression/CppiaMalformedLoads/Main.hx b/test/regression/CppiaMalformedLoads/Main.hx new file mode 100644 index 00000000..662c35c3 --- /dev/null +++ b/test/regression/CppiaMalformedLoads/Main.hx @@ -0,0 +1,28 @@ +import haxe.crypto.Base64; + +// libhxcpp #467: malformed cppia files that crashed the host instead of +// failing to load. SECURITY.md promises a load error. Each is loaded and run +// interpreted, then under the JIT compiling every function as it loads. +class Main { + static function main() { + for (jit in [false, true]) { + cpp.cppia.Host.enableJit(jit); + untyped __cpp__("::hx::gLazyJit = false"); + Sys.println(jit ? "jit" : "interpreted"); + for (f in Files.all) { + var result = try { + var module = cpp.cppia.Module.fromData(Base64.decode(f.data).getData()); + module.boot(); + module.run(); + "ran"; + } catch (e:Dynamic) { + "failed to load"; + } + Sys.println(' ${f.name}: $result'); + } + } + // Referenced so --dce no keeps what the scripts link against + var keep:Array = [haxe.ds.StringMap, haxe.ds.IntMap, haxe.ds.ObjectMap, haxe.io.Bytes, haxe.Timer, cpp.vm.Gc, Lambda, StringTools, + EReg, Reflect, Type, Std, Math, Date, StringBuf, Sys, haxe.iterators.ArrayIterator]; + } +} diff --git a/test/regression/CppiaMalformedLoads/build.hxml b/test/regression/CppiaMalformedLoads/build.hxml new file mode 100644 index 00000000..5bfa2fac --- /dev/null +++ b/test/regression/CppiaMalformedLoads/build.hxml @@ -0,0 +1,4 @@ +-m Main +--cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaMalformedLoads/stdout.txt b/test/regression/CppiaMalformedLoads/stdout.txt new file mode 100644 index 00000000..ffe5aced --- /dev/null +++ b/test/regression/CppiaMalformedLoads/stdout.txt @@ -0,0 +1,26 @@ +interpreted + MAIN with no types: failed to load + unknown enum constructor: failed to load + enum constructor with the wrong argument count: failed to load + two classes with one type id: failed to load + a string constant past the string table: failed to load +Script.hx:10: x=0 + an enum parameter index past its constructors: ran + a file id past the string table: failed to load +Script.hx:7: false + break outside a loop: ran +Script.hx:7: false + continue outside a loop: ran + a super call to a class that is not the super class: failed to load +jit + MAIN with no types: failed to load + unknown enum constructor: failed to load + enum constructor with the wrong argument count: failed to load + two classes with one type id: failed to load + a string constant past the string table: failed to load +Script.hx:10: x=0 + an enum parameter index past its constructors: ran + a file id past the string table: failed to load + break outside a loop: failed to load + continue outside a loop: failed to load + a super call to a class that is not the super class: failed to load diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index f54654df..ff920497 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -24,6 +24,7 @@ CppiaHostMismatch: its host is the first --next section, which -D emscripten doe CppiaJitBuiltins: threads CppiaJitThrowNull: its host is the first --next section, which -D emscripten does not reach CppiaLazyJit: threads, and Emscripten has no cppia JIT +CppiaMalformedLoads: compares the cppia JIT, which Emscripten has not CppiaModuleFree: threads CppiaModuleRetained: threads CppiaNullDynamicArray: its host is the first --next section, which -D emscripten does not reach, and it runs the script under the JIT too, and Emscripten has no cppia JIT From 7a454f4e52ce9ddccc8f4253f03af7a1e82e7d58 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 10:19:26 -0500 Subject: [PATCH 21/36] Move instances in adoptInstances only when old and new code agree adoptInstances compared only field names, storage types and offsets, and docs/CppiaModuleRelease.md said methods could differ in any way. But a call's vtable slot is fixed when its code links, so old code still running, which the docs say finishes normally, called a moved instance by the old slots: with a method added first, foo.b() ran the new a(), and foo.a() reached x(), whose Int was read as a String, crashing the interpreter and giving the JIT a String of garbage. And a moved class's field could hold an instance of a class that stayed, since its layout changed, which new code then read with the new layout, past the object. Now: - methods, their super classes' included, must have the same names in the same slots, and so must the script interfaces the class implements; - fields compare their type names, so a retyped field within one storage type, Array to Array, keeps its instances, as the docs said it did; - a class with a field that can hold an instance of a class that stays stays too, to a fixed point. The report says which rule kept a class, and the docs describe the rule. Test: CppiaAdoptLayouts, the two cases, interpreted and under the JIT. Before, the first crashed the interpreter and the second read past the object; now neither class moves and old code keeps its own results. CppiaAdoptInstances, whose classes change only method bodies, still moves them, on Windows x64. Fixes #464 --- Changes.md | 1 + docs/CppiaModuleRelease.md | 4 +- src/hx/cppia/CppiaModule.cpp | 71 ++++++++++++++++++- test/regression/CppiaAdoptLayouts/Main.hx | 40 +++++++++++ test/regression/CppiaAdoptLayouts/build.hxml | 20 ++++++ .../CppiaAdoptLayouts/fields/new/Script.hx | 21 ++++++ .../CppiaAdoptLayouts/fields/old/Script.hx | 22 ++++++ .../CppiaAdoptLayouts/methods/new/Script.hx | 13 ++++ .../CppiaAdoptLayouts/methods/old/Script.hx | 21 ++++++ test/regression/CppiaAdoptLayouts/stdout.txt | 24 +++++++ test/regression/emscripten-skip.txt | 1 + 11 files changed, 235 insertions(+), 3 deletions(-) create mode 100644 test/regression/CppiaAdoptLayouts/Main.hx create mode 100644 test/regression/CppiaAdoptLayouts/build.hxml create mode 100644 test/regression/CppiaAdoptLayouts/fields/new/Script.hx create mode 100644 test/regression/CppiaAdoptLayouts/fields/old/Script.hx create mode 100644 test/regression/CppiaAdoptLayouts/methods/new/Script.hx create mode 100644 test/regression/CppiaAdoptLayouts/methods/old/Script.hx create mode 100644 test/regression/CppiaAdoptLayouts/stdout.txt diff --git a/Changes.md b/Changes.md index cbc84fda..e34bf285 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed cppia's adoptInstances moving instances that code then used with the wrong layout: a class whose methods changed order or number moved, so old code still running called its moved instances by the old vtable slots, reaching another method or crashing, and a class moved while a field could hold an instance of a class that stayed, which new code read past its end. Such classes keep their instances now, and the report says why: methods must be the same, in the same slots, and so must the script interfaces a class implements, fields compare their types by name, and a class stays with the classes its fields can hold (libhxcpp #464) * Fixed malformed cppia files crashing the host instead of failing to load: a MAIN in a module with no types, an unknown script enum constructor or one called with the wrong number of arguments, two classes with one type id, a string constant or file id past the string table, which grew the table to it, an enum parameter index past the value, break or continue outside a loop under the JIT, and a super constructor call to a class other than the super class. Each fails to load, or is read safely (libhxcpp #467) * Fixed cppia's interpreter and JIT giving different results for array builtins, both of them now matching C++: under the JIT, a[i] += x and the other compound assignments on an Array stored x alone, a[i]++, insert and toString on one did nothing, a Bool stored in an Array became an Int, bitwise compound assignments on an Array> did nothing, an Int array read out of range as a String gave "null", and ++d[i] on a Dynamic as a statement decremented. Interpreted, a typed indexOf or lastIndexOf used as a Float gave 0, and join, toString and the iterators used as a statement did not run (libhxcpp #468) * Fixed two counts with HXCPP_GC_INCREMENTAL: Gc.memInfo64(MEM_INFO_LIVE) after an incremental cycle reported every used row as live, several times the bytes really live, where it is meant to report the last full reclaim, and Gc.trace with a cycle part done counted only the objects the cycle had not marked yet. MEM_INFO_LIVE changes only with a full reclaim now, and Gc.trace starts the cycle again, as __hxcpp_gc_census does (libhxcpp #453) diff --git a/docs/CppiaModuleRelease.md b/docs/CppiaModuleRelease.md index 42c17d27..6a304cac 100644 --- a/docs/CppiaModuleRelease.md +++ b/docs/CppiaModuleRelease.md @@ -82,9 +82,9 @@ untyped previous.release(); - `name`, the class's name. - `moved`, how many of its instances moved. -- `reason`, null when they could move, otherwise why not, naming the first field that differs. +- `reason`, null when they could move, otherwise why not, naming the first field or method that differs, or the field that can hold an instance that stays. -The rule is strict, as an instance stays where it is, at its size. Both classes must extend the same host class, through super classes of the same names, implement the same interfaces, and have the same fields, dynamic functions included, with the same names, storage types and offsets. Methods can differ in any way, so editing method bodies, the usual case, is covered. A class that adds, removes, retypes or reorders a field keeps its instances, which keep the old module loaded until they go. +The rule is strict, as an instance stays where it is, at its size, and old code still running calls it by the slots its calls linked with. Both classes must extend the same host class, through super classes of the same names, implement the same interfaces, and have the same fields, dynamic functions included, with the same names, types and offsets. They must have the same methods, their super classes' included, in the same order, so that each keeps its slot, and so must the script interfaces they implement. Method bodies can differ in any way, so editing them, the usual case, is covered. A class that adds, removes, retypes or reorders a field or a method keeps its instances, which keep the old module loaded until they go. So does a class with a field that can hold an instance of a class that stays, since the new code would read that instance with the new layout. What does not move: diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index 87702ee6..2a464c1d 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -1327,12 +1327,42 @@ static std::string slotDifference(const char *inWhat, CppiaClassInfo *inFrom, st return std::string(inWhat) + " " + name + " is not in the new class"; if (name!=inTo->cppia.identStr(inNew[i]->nameId)) return std::string(inWhat) + " " + name + " is not where it was"; - if (inOld[i]->storeType!=inNew[i]->storeType || inOld[i]->offset!=inNew[i]->offset) + if (inOld[i]->storeType!=inNew[i]->storeType || inOld[i]->offset!=inNew[i]->offset || + typeName(inFrom->cppia.types[inOld[i]->typeId])!=typeName(inTo->cppia.types[inNew[i]->typeId])) return std::string(inWhat) + " " + name + " changed its type"; } return std::string(); } +// The first method of a class, its super classes' included, that is not in the +// same vtable slot in both. A call's slot is fixed when its code links, so old +// code still running would call a moved instance by its old slots, reaching +// another method or reading its return as another type (libhxcpp #464) +static std::string methodDifference(CppiaClassInfo *inFrom, CppiaClassInfo *inTo) +{ + if (inFrom->memberFunctions.size()!=inTo->memberFunctions.size()) + return "its methods are not the same"; + for(size_t i=0;imemberFunctions.size();i++) + if (inFrom->memberFunctions[i]->name!=inTo->memberFunctions[i]->name || + inFrom->memberFunctions[i]->vtableSlot!=inTo->memberFunctions[i]->vtableSlot) + return "method " + inFrom->memberFunctions[i]->name + " is not where it was"; + return std::string(); +} + +// The script interfaces a class implements, by name, with their class info +static std::map scriptInterfaces(CppiaClassInfo *inInfo) +{ + std::map result; + for(CppiaClassInfo *info=inInfo; info; info=info->superType ? info->superType->cppiaClass : 0) + for(size_t i=0;iimplements.size();i++) + { + TypeData *type = info->cppia.types[info->implements[i]]; + if (type->cppiaClass) + result[typeName(type)] = type->cppiaClass; + } + return result; +} + // Why instances of inFrom cannot become instances of inTo, or empty when they can static std::string incompatibility(CppiaClassInfo *inFrom, CppiaClassInfo *inTo) { @@ -1357,6 +1387,17 @@ static std::string incompatibility(CppiaClassInfo *inFrom, CppiaClassInfo *inTo) if (inFrom->classSize!=inTo->classSize || inFrom->extraData!=inTo->extraData || inFrom->dynamicMapOffset!=inTo->dynamicMapOffset || inFrom->containsPointers!=inTo->containsPointers) return "its instances are laid out otherwise"; + std::string method = methodDifference(inFrom, inTo); + if (!method.empty()) + return method; + std::map fromInterfaces = scriptInterfaces(inFrom); + std::map toInterfaces = scriptInterfaces(inTo); + for(std::map::iterator i=fromInterfaces.begin(); i!=fromInterfaces.end(); ++i) + { + std::map::iterator other = toInterfaces.find(i->first); + if (other==toInterfaces.end() || !methodDifference(i->second, other->second).empty()) + return "interface " + i->first + " changed its methods"; + } return std::string(); } @@ -1403,6 +1444,34 @@ static Array adoptInstances(CppiaModule *inNext, CppiaModule *inPreviou } } + // New code reads a moved instance's fields with the new classes' layouts, + // so a field that can hold an instance staying in the old class, whose + // layout changed, would be read wrongly: the class holding it stays too, + // until nothing changes (libhxcpp #464) + for(bool changed=true; changed; ) + { + changed = false; + for(std::map::iterator i=adoptions.begin(); i!=adoptions.end(); ++i) + { + if (!i->second.to) + continue; + std::vector &vars = i->first->memberVars; + for(size_t v=0;vfirst->cppia.types[vars[v]->typeId]->cppiaClass; + std::map::iterator heldAdoption = held ? adoptions.find(held) : adoptions.end(); + if (heldAdoption!=adoptions.end() && !heldAdoption->second.to) + { + i->second.to = 0; + i->second.reason = std::string("field ") + i->first->cppia.identStr(vars[v]->nameId) + " can hold a " + + held->name + ", which stays in the old class"; + changed = true; + break; + } + } + } + } + sAdoptions = &adoptions; censusWithVisitor(adoptVisit); sAdoptions = 0; diff --git a/test/regression/CppiaAdoptLayouts/Main.hx b/test/regression/CppiaAdoptLayouts/Main.hx new file mode 100644 index 00000000..d55581f7 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/Main.hx @@ -0,0 +1,40 @@ +import haxe.io.Path; + +// libhxcpp #464. adoptInstances moved instances whose methods were not in the +// same vtable slots, so old code still running called the wrong method, or +// read its return as another type, and moved instances whose fields held +// instances that stayed, which new code read with the new layout. Neither +// moves now, and the report says why. +class Main { + static function scenario(dir:String, name:String) { + var load = (which:String) -> cpp.cppia.Module.fromData(sys.io.File.getBytes(Path.join([dir, '$name-$which.cppia'])).getData()); + var old = load("old"); + old.boot(); + old.run(); + var oldCls = old.resolveClass("Script"); + Sys.println(" before: " + Reflect.callMethod(oldCls, Reflect.field(oldCls, "before"), [])); + var next = load("new"); + next.boot(); + var report:Array = untyped next.adoptInstances(old); + for (r in report) + Sys.println(" adopt " + r.name + ": moved " + r.moved + ", " + r.reason); + Sys.println(" after, old code: " + Reflect.callMethod(oldCls, Reflect.field(oldCls, "after"), [])); + cpp.vm.Gc.run(true); + } + + static function main() { + var dir = Path.directory(Sys.programPath()); + for (jit in [false, true]) { + cpp.cppia.Host.enableJit(jit); + Sys.println(jit ? "jit" : "interpreted"); + for (name in ["methods", "fields"]) { + Sys.println(name); + try { + scenario(dir, name); + } catch (e:Dynamic) { + Sys.println(" error: " + e); + } + } + } + } +} diff --git a/test/regression/CppiaAdoptLayouts/build.hxml b/test/regression/CppiaAdoptLayouts/build.hxml new file mode 100644 index 00000000..1ab45b69 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/build.hxml @@ -0,0 +1,20 @@ +-cp methods/old +--main Script +-cppia bin/methods-old.cppia +--next +-cp methods/new +--main Script +-cppia bin/methods-new.cppia +--next +-cp fields/old +--main Script +-cppia bin/fields-old.cppia +--next +-cp fields/new +--main Script +-cppia bin/fields-new.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaAdoptLayouts/fields/new/Script.hx b/test/regression/CppiaAdoptLayouts/fields/new/Script.hx new file mode 100644 index 00000000..209c2114 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/fields/new/Script.hx @@ -0,0 +1,21 @@ +// New generation: Parent is laid out the same, so its instances move, but Child +// gained a String before n, so its instances stay old. The moved Parent's c is +// still an old Child, which the new code reads with the new Child's layout +class Child { + public var s:String = "new child"; + public var n:Int = 2; + public function new() {} +} + +class Parent { + public var c:Child; + public function new() c = new Child(); + public function get():Int { + Sys.println(" new code reads c.s -> " + (c.s == null ? "null" : "length " + c.s.length)); + return c.n; + } +} + +class Script { + static function main() {} +} diff --git a/test/regression/CppiaAdoptLayouts/fields/old/Script.hx b/test/regression/CppiaAdoptLayouts/fields/old/Script.hx new file mode 100644 index 00000000..f4e8cbdc --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/fields/old/Script.hx @@ -0,0 +1,22 @@ +// Old generation: Child holds an Int only +class Child { + public var n:Int = 1; + public function new() {} +} + +class Parent { + public var c:Child; + public function new() c = new Child(); + public function get():Int return c.n; +} + +class Script { + public static var p:Parent; + public static function before():String return "p.get() = " + p.get(); + // Old code handing the moved Parent to new code, as a host callback would + public static function after():String { + var get = Reflect.field(p, "get"); + return "p.get() = " + Reflect.callMethod(p, get, []); + } + static function main() p = new Parent(); +} diff --git a/test/regression/CppiaAdoptLayouts/methods/new/Script.hx b/test/regression/CppiaAdoptLayouts/methods/new/Script.hx new file mode 100644 index 00000000..5dc5469b --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/methods/new/Script.hx @@ -0,0 +1,13 @@ +// New generation: the same fields, so Foo's instances move, but a method added +// first shifts a and b one vtable slot on ("Methods can differ in any way") +class Foo { + public var v:Int = 7; + public function new() {} + public function x():Int return 12345; + public function a():String return "new a " + v; + public function b():String return "new b " + v; +} + +class Script { + static function main() {} +} diff --git a/test/regression/CppiaAdoptLayouts/methods/old/Script.hx b/test/regression/CppiaAdoptLayouts/methods/old/Script.hx new file mode 100644 index 00000000..bde85804 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/methods/old/Script.hx @@ -0,0 +1,21 @@ +// Old generation: Foo.a and Foo.b take the first two script vtable slots +class Foo { + public var v:Int = 7; + public function new() {} + public function a():String return "old a " + v; + public function b():String return "old b " + v; +} + +class Script { + public static var foo:Foo; + // Old code calling methods on an instance that adoptInstances moves + public static function before():String return foo.b() + " / " + foo.a(); + public static function after():String { + var s = foo.b(); + Sys.println(" old code foo.b() -> " + s); + var t = foo.a(); + Sys.println(" old code foo.a() -> length " + t.length); + return s + " / " + t; + } + static function main() foo = new Foo(); +} diff --git a/test/regression/CppiaAdoptLayouts/stdout.txt b/test/regression/CppiaAdoptLayouts/stdout.txt new file mode 100644 index 00000000..0f0befda --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/stdout.txt @@ -0,0 +1,24 @@ +interpreted +methods + before: old b 7 / old a 7 + adopt Foo: moved 0, its methods are not the same + old code foo.b() -> old b 7 + old code foo.a() -> length 7 + after, old code: old b 7 / old a 7 +fields + before: p.get() = 1 + adopt Child: moved 0, field n is not where it was + adopt Parent: moved 0, field c can hold a Child, which stays in the old class + after, old code: p.get() = 1 +jit +methods + before: old b 7 / old a 7 + adopt Foo: moved 0, its methods are not the same + old code foo.b() -> old b 7 + old code foo.a() -> length 7 + after, old code: old b 7 / old a 7 +fields + before: p.get() = 1 + adopt Child: moved 0, field n is not where it was + adopt Parent: moved 0, field c can hold a Child, which stays in the old class + after, old code: p.get() = 1 diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index ff920497..a35fbe3c 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -16,6 +16,7 @@ CffiPrimeUnicodeFallback: loads an ndll it builds, and Emscripten links statical CffiQuietMissingPrimitive: loads an ndll it builds, and Emscripten links statically ConditionTimedWait: threads CppiaAdoptInstances: threads (std::thread, which needs a pthreads build) +CppiaAdoptLayouts: compares the cppia JIT, which Emscripten has not CppiaArrayAccess: its host is the first --next section, which -D emscripten does not reach CppiaBreakpoints: threads CppiaHostArgs: processes From 7c475bae338f311da76023c3368e1e908b55f8c3 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 09:38:38 -0500 Subject: [PATCH 22/36] Fail and end the build cleanly on compile thread errors Two ways a parallel compile went wrong when something on a compile thread threw or exited: - When a compile failed, Compiler deleted the old object before calling setThreadError. If the delete threw, as it does for a read-only object or one another process has open on Windows, the error was never recorded, and the thread's catch only warned when no error had been recorded, so the build linked the old object and exited 0. The error is recorded first, the delete is guarded, and the catch records an error for anything thrown. - Tools.exit on a compile thread ran the exit hooks there, and ThreadPool's hook waits on the calling thread's own queue, which never fills, while the main thread waited for that thread: the build hung. HXCPP_EXIT_ON_ERROR on a compile error and any Log.error on a compile thread did this. On a compile thread, Tools.exit records the code and ends the job, and the main thread exits when the jobs have. HXCPP_EXIT_ON_ERROR is also read once the arguments and Options.txt are in, not only from the environment. Test: test/compile_errors/check.sh, run in CI, builds three projects that must fail: HXCPP_EXIT_ON_ERROR with a compile error and two optimisation tags on one file, which hung before, and on Windows a compile error over a read-only old object, which exited 0 before. All three fail within seconds now, on Windows x64. Fixes #471 --- .github/workflows/test.yml | 5 ++ Changes.md | 1 + test/compile_errors/check.sh | 71 ++++++++++++++++++++++++++++ test/compile_errors/error/Main.hx | 5 ++ test/compile_errors/error/build.hxml | 2 + test/compile_errors/tags/Main.hx | 6 +++ test/compile_errors/tags/build.hxml | 2 + tools/hxcpp/BuildTool.hx | 3 ++ tools/hxcpp/Compiler.hx | 11 ++++- tools/hxcpp/ThreadPool.hx | 27 +++++++++-- tools/hxcpp/Tools.hx | 9 ++++ 11 files changed, 137 insertions(+), 5 deletions(-) create mode 100644 test/compile_errors/check.sh create mode 100644 test/compile_errors/error/Main.hx create mode 100644 test/compile_errors/error/build.hxml create mode 100644 test/compile_errors/tags/Main.hx create mode 100644 test/compile_errors/tags/build.hxml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6a9a75b9..d3b15f40 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -199,6 +199,11 @@ jobs: run: | haxelib run hxcpp xml/Build.xml -options options.txt test "$(./value | tr -d '\r')" = 42 + - name: build tool errors on compile threads + continue-on-error: ${{ inputs.warn_only }} + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} + shell: bash + run: bash test/compile_errors/check.sh - name: build tool MSVC setup scripts with ! in the Visual Studio path continue-on-error: ${{ inputs.warn_only }} if: ${{ !cancelled() && steps.setup.outcome == 'success' && runner.os == 'Windows' }} diff --git a/Changes.md b/Changes.md index e34bf285..4734409d 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed the build tool linking a stale object and exiting 0 when a compile failed and its old object could not be deleted, as when it is read-only or another process has it open, and hanging when a compile thread exited, as with HXCPP_EXIT_ON_ERROR on a compile error, or with an error such as two optimisation tags on one file. Both fail the build now, and HXCPP_EXIT_ON_ERROR works as a -D define, not only from the environment (libhxcpp #471) * Fixed cppia's adoptInstances moving instances that code then used with the wrong layout: a class whose methods changed order or number moved, so old code still running called its moved instances by the old vtable slots, reaching another method or crashing, and a class moved while a field could hold an instance of a class that stayed, which new code read past its end. Such classes keep their instances now, and the report says why: methods must be the same, in the same slots, and so must the script interfaces a class implements, fields compare their types by name, and a class stays with the classes its fields can hold (libhxcpp #464) * Fixed malformed cppia files crashing the host instead of failing to load: a MAIN in a module with no types, an unknown script enum constructor or one called with the wrong number of arguments, two classes with one type id, a string constant or file id past the string table, which grew the table to it, an enum parameter index past the value, break or continue outside a loop under the JIT, and a super constructor call to a class other than the super class. Each fails to load, or is read safely (libhxcpp #467) * Fixed cppia's interpreter and JIT giving different results for array builtins, both of them now matching C++: under the JIT, a[i] += x and the other compound assignments on an Array stored x alone, a[i]++, insert and toString on one did nothing, a Bool stored in an Array became an Int, bitwise compound assignments on an Array> did nothing, an Int array read out of range as a String gave "null", and ++d[i] on a Dynamic as a statement decremented. Interpreted, a typed indexOf or lastIndexOf used as a Float gave 0, and join, toString and the iterators used as a statement did not run (libhxcpp #468) diff --git a/test/compile_errors/check.sh b/test/compile_errors/check.sh new file mode 100644 index 00000000..f2808d63 --- /dev/null +++ b/test/compile_errors/check.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# libhxcpp #471: errors on the compile threads. +# - A failed compile whose old object could not be deleted, as when it is +# read-only, linked that object and exited 0. +# - Exiting from a compile thread, as HXCPP_EXIT_ON_ERROR does on a compile +# error, or an error the build tool reports there, hung the build. +# Each build here must fail, and within the time limit. +cd "$(dirname "$0")" +failed=0 + +# Runs a build in the background and fails it after $limit seconds +limit=600 +build() { + "$@" > build.log 2>&1 & + local pid=$! waited=0 + while kill -0 $pid 2>/dev/null; do + if [ $waited -ge $limit ]; then + kill $pid 2>/dev/null + echo "hung" + return 0 + fi + sleep 1 + waited=$((waited+1)) + done + wait $pid + echo "exit $?" +} + +expect_failure() { + local name=$1; shift + local result + result=$(build "$@") + if [ "$result" = "exit 0" ] || [ "$result" = "hung" ]; then + echo "::error::$name: $result, where it should fail" + tail -20 build.log + failed=1 + else + echo "$name: failed as it should ($result)" + fi +} + +(cd error && HXCPP_EXIT_ON_ERROR=1 expect_failure "HXCPP_EXIT_ON_ERROR in the environment" haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 +(cd error && expect_failure "-D HXCPP_EXIT_ON_ERROR" haxe build.hxml -D HXCPP_EXIT_ON_ERROR -D "$HXCPP_ARCH_FLAG") || failed=1 +(cd tags && expect_failure "two optimisation tags" haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 + +# Windows only: elsewhere a read-only file can still be deleted +if [ "$OS" = "Windows_NT" ]; then + ( + cd error + rm -rf ro && mkdir ro && cp build.hxml ro/ + cd ro + printf 'class Main {\n\tstatic function main() {\n\t\tSys.println("old code");\n\t}\n}\n' > Main.hx + haxe build.hxml -D "$HXCPP_ARCH_FLAG" > first.log 2>&1 || { echo "::error::first build failed"; cat first.log; exit 1; } + obj=$(ls bin/obj/*/*_Main.obj | head -1) + attrib +R "$(cygpath -w "$obj")" + # Newer than the object by more than the build tool's one second + sleep 2 + cp ../Main.hx Main.hx + expect_failure "a compile error over a read-only object" haxe build.hxml -D "$HXCPP_ARCH_FLAG" + # The old object must not be linked: the link itself may then fail or not + if grep -q 'Link:' build.log; then + echo "::error::a compile error over a read-only object: linked the old object" + failed=1 + fi + status=$failed + attrib -R "$(cygpath -w "$obj")" + exit $status + ) || failed=1 +fi + +exit $failed diff --git a/test/compile_errors/error/Main.hx b/test/compile_errors/error/Main.hx new file mode 100644 index 00000000..04e9c83f --- /dev/null +++ b/test/compile_errors/error/Main.hx @@ -0,0 +1,5 @@ +class Main { + static function main() { + untyped __cpp__("this_is_not_cpp();"); + } +} diff --git a/test/compile_errors/error/build.hxml b/test/compile_errors/error/build.hxml new file mode 100644 index 00000000..9553fac5 --- /dev/null +++ b/test/compile_errors/error/build.hxml @@ -0,0 +1,2 @@ +-cpp bin +-main Main diff --git a/test/compile_errors/tags/Main.hx b/test/compile_errors/tags/Main.hx new file mode 100644 index 00000000..766a9359 --- /dev/null +++ b/test/compile_errors/tags/Main.hx @@ -0,0 +1,6 @@ +@:fileXml("tags='haxe,static,optim-none,optim-size'") +class Main { + static function main() { + Sys.println("hi"); + } +} diff --git a/test/compile_errors/tags/build.hxml b/test/compile_errors/tags/build.hxml new file mode 100644 index 00000000..9553fac5 --- /dev/null +++ b/test/compile_errors/tags/build.hxml @@ -0,0 +1,2 @@ +-cpp bin +-main Main diff --git a/tools/hxcpp/BuildTool.hx b/tools/hxcpp/BuildTool.hx index e0148c1d..37776920 100644 --- a/tools/hxcpp/BuildTool.hx +++ b/tools/hxcpp/BuildTool.hx @@ -118,6 +118,9 @@ class BuildTool inIncludePath:Array, inDirtyList:Array ) { mDefines = inDefines; + // Read once the arguments and Options.txt are in, not only from the + // environment + exitOnThreadError = exitOnThreadError || inDefines.exists("HXCPP_EXIT_ON_ERROR"); mFileGroups = new FileGroups(); mCompiler = null; mStripper = null; diff --git a/tools/hxcpp/Compiler.hx b/tools/hxcpp/Compiler.hx index fa1689d1..261c9fae 100644 --- a/tools/hxcpp/Compiler.hx +++ b/tools/hxcpp/Compiler.hx @@ -471,9 +471,16 @@ class Compiler cleanTmp(tmpFile); if (err!=0) { - if (FileSystem.exists(obj_name)) - FileSystem.deleteFile(obj_name); + // The error first: when the delete threw, as it does for a + // read-only object or one another process has open, it was + // lost, and the old object was linked (libhxcpp #471) BuildTool.setThreadError(err); + try + { + if (FileSystem.exists(obj_name)) + FileSystem.deleteFile(obj_name); + } + catch(e:Dynamic) { } } else inProgress.fileDone(); diff --git a/tools/hxcpp/ThreadPool.hx b/tools/hxcpp/ThreadPool.hx index 10e8c624..33da2f61 100755 --- a/tools/hxcpp/ThreadPool.hx +++ b/tools/hxcpp/ThreadPool.hx @@ -1,22 +1,39 @@ #if haxe4 import sys.thread.Thread; import sys.thread.Mutex; + import sys.thread.Tls; #else #if neko import neko.vm.Thread; import neko.vm.Mutex; + import neko.vm.Tls; #else import cpp.vm.Thread; import cpp.vm.Mutex; + import cpp.vm.Tls; #end #end +// Thrown by Tools.exit on a compile thread, to end its job +class WorkerExit +{ + public function new() { } +} + #if cpp import cpp.AtomicInt; #end class ThreadPool { + static var worker = new Tls(); + + // Whether this is one of the compile threads + public static function onWorker():Bool + { + return worker.value == true; + } + var threads:Array; var mainThread:Thread; #if cpp @@ -43,6 +60,7 @@ class ThreadPool function threadLoop(threadId:Int) { + worker.value = true; while(true) { var job:Int->Void = Thread.readMessage(true); @@ -58,9 +76,12 @@ class ThreadPool } catch (error:Dynamic) { - if (BuildTool.threadExitCode!=0) - BuildTool.setThreadError(-1); - else + // Any error ends the build. As a warning, a compile that failed + // and then could not delete its old object went on to link that + // object and exit 0 (libhxcpp #471) + if (BuildTool.threadExitCode==0) + BuildTool.threadExitCode = -1; + if (!Std.isOfType(error, WorkerExit)) Log.warn("Error in compile thread: " + error); } diff --git a/tools/hxcpp/Tools.hx b/tools/hxcpp/Tools.hx index da8e5f46..9c402c2c 100644 --- a/tools/hxcpp/Tools.hx +++ b/tools/hxcpp/Tools.hx @@ -6,6 +6,15 @@ class Tools { } public static function exit(exitCode:Int) { + // On a compile thread the hooks waited for this thread itself, since one + // waits for every compile thread to finish, so the build hung. The job + // ends here instead, and the main thread exits once the jobs have + // (libhxcpp #471) + if (ThreadPool.onWorker()) { + if (BuildTool.threadExitCode == 0) + BuildTool.threadExitCode = exitCode == 0 ? -1 : exitCode; + throw new ThreadPool.WorkerExit(); + } for (hook in onExit) { hook(exitCode); } From f701d8d09b6fa8b875dad34087d45b883942ce67 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 09:41:14 -0500 Subject: [PATCH 23/36] Rebuild when a define that changes compile flags changes Without the compile cache, the copy of Options.txt the build tool keeps in the obj folder is all that tells it the compile flags changed, and filterOptions keeps only defines containing "hxcpp" and a few others. Defines the toolchains compile by, or choose files by, were dropped: switching one reused objects built without it. Adding CPPIA_NO_JIT to a -D scriptable build recompiled only Main.cpp and failed to link against the old Cppia.obj (unresolved hx::getJitType), and removing it linked a host without its JIT, saying nothing. The defines the toolchain files test or use in flags, and which no obj folder or other kept define already covers, are kept too: CPPIA_NO_JIT, CPPIA_JIT, ABI, objc, OBJC_ARC, STDLIBCPP, exe_link, O3, LEGACY_MACOSX_SDK, armv6, rpi, winrt, noM32, noM64 and no_shared_libs. Test: a -D scriptable build, then the same with -D CPPIA_NO_JIT, compiled the cppia sources again and linked, then without it again, on Windows x64. Fixes #470 --- Changes.md | 1 + tools/hxcpp/FileGroup.hx | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Changes.md b/Changes.md index 4734409d..11d32b61 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed the build tool reusing stale objects when a define that changes how files compile was switched without the compile cache: only defines containing hxcpp, and a few others, were compared, so adding -D CPPIA_NO_JIT to a scriptable build failed to link, removing it linked a host without its JIT, and ABI, OBJC_ARC, STDLIBCPP and the others like them did nothing until the objects changed. Each now rebuilds what it affects (libhxcpp #470) * Fixed the build tool linking a stale object and exiting 0 when a compile failed and its old object could not be deleted, as when it is read-only or another process has it open, and hanging when a compile thread exited, as with HXCPP_EXIT_ON_ERROR on a compile error, or with an error such as two optimisation tags on one file. Both fail the build now, and HXCPP_EXIT_ON_ERROR works as a -D define, not only from the environment (libhxcpp #471) * Fixed cppia's adoptInstances moving instances that code then used with the wrong layout: a class whose methods changed order or number moved, so old code still running called its moved instances by the old vtable slots, reaching another method or crashing, and a class moved while a field could hold an instance of a class that stayed, which new code read past its end. Such classes keep their instances now, and the report says why: methods must be the same, in the same slots, and so must the script interfaces a class implements, fields compare their types by name, and a class stays with the classes its fields can hold (libhxcpp #464) * Fixed malformed cppia files crashing the host instead of failing to load: a MAIN in a module with no types, an unknown script enum constructor or one called with the wrong number of arguments, two classes with one type id, a string constant or file id past the string table, which grew the table to it, an enum parameter index past the value, break or continue outside a loop under the JIT, and a super constructor call to a class other than the super class. Each fails to load, or is read safely (libhxcpp #467) diff --git a/tools/hxcpp/FileGroup.hx b/tools/hxcpp/FileGroup.hx index 2d0a14aa..27d33b00 100644 --- a/tools/hxcpp/FileGroup.hx +++ b/tools/hxcpp/FileGroup.hx @@ -215,6 +215,13 @@ class FileGroup } } + // Defines that change how the toolchains compile, or what: without the + // cache, this copy of Options.txt is all that tells the objects are stale, + // so switching one of these reused objects built without it, and adding + // CPPIA_NO_JIT failed to link (libhxcpp #470) + static var compileDefines = ["cppia_no_jit", "cppia_jit", "abi", "objc", "objc_arc", "stdlibcpp", "exe_link", "o3", + "legacy_macosx_sdk", "armv6", "rpi", "winrt", "nom32", "nom64", "no_shared_libs"]; + public function filterOptions(contents:String) { // Old-style @@ -237,7 +244,7 @@ class FileGroup } else if (name.indexOf("hxcpp")>=0 || name=="scriptable" || name.indexOf("dll")>=0 || name=="no_console" || name.substr(0,8)=="android-" || name.substr(0,4)=="ndkv" || name=="toolchain" || name=="platform" || - name=="toolchain_version" || name=="android_ndk_root" ) + name=="toolchain_version" || name=="android_ndk_root" || compileDefines.indexOf(name)>=0 ) result.push(def); } From 929ebec26ba306175bd9f30558a6d59a1b44a8aa Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 09:41:15 -0500 Subject: [PATCH 24/36] Fix per-file cxx_standard with a PCH, nvcc groups and NDKV20 and up - A file with its own cxx_standard, which docs/build_xml/Files.md documents, in a group with a precompiled header was given both the file's standard and the PCH built with the group's. MSVC refused (C2855) and clang refuses a PCH built with other language options. Such a file compiles without the PCH. - group.mTags=="nvcc"; compared instead of assigning, so an group kept the tags haxe,static and was given the host compiler's flags, which nvcc takes only through -Xcompiler. The tag is set. - Setup looked for NDKV6 to NDKV19 only, so -DNDKV25 was ignored and the newest NDK under ANDROID_NDK_DIR used. Any NDKV is read, the lowest if several are given. An NDK without meta/platforms.json then stopped the build with "Invalid field access : toString" while warning about it; the warning prints now. Test, on Windows x64: a file with cxx_standard='17' in a PCH group compiles and runs; a stand-in nvcc.exe that prints its arguments gets no host flags; with fake NDKs 25 and 28, -DNDKV25 picks 25 and -DNDKV28 picks 28. Fixes #472 --- Changes.md | 1 + tools/hxcpp/BuildTool.hx | 4 +++- tools/hxcpp/Compiler.hx | 4 +++- tools/hxcpp/Setup.hx | 18 ++++++++++++------ 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Changes.md b/Changes.md index 11d32b61..f4165d95 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed three build tool settings that did nothing or failed: a file with its own cxx_standard in a group with a precompiled header failed to compile (C2855 on MSVC), an group was given the host compiler's flags because its tag was compared instead of set, and -DNDKV20 and up were ignored, so the newest NDK was used instead. An NDK without meta/platforms.json no longer stops the build with "Invalid field access : toString" (libhxcpp #472) * Fixed the build tool reusing stale objects when a define that changes how files compile was switched without the compile cache: only defines containing hxcpp, and a few others, were compared, so adding -D CPPIA_NO_JIT to a scriptable build failed to link, removing it linked a host without its JIT, and ABI, OBJC_ARC, STDLIBCPP and the others like them did nothing until the objects changed. Each now rebuilds what it affects (libhxcpp #470) * Fixed the build tool linking a stale object and exiting 0 when a compile failed and its old object could not be deleted, as when it is read-only or another process has it open, and hanging when a compile thread exited, as with HXCPP_EXIT_ON_ERROR on a compile error, or with an error such as two optimisation tags on one file. Both fail the build now, and HXCPP_EXIT_ON_ERROR works as a -D define, not only from the environment (libhxcpp #471) * Fixed cppia's adoptInstances moving instances that code then used with the wrong layout: a class whose methods changed order or number moved, so old code still running called its moved instances by the old vtable slots, reaching another method or crashing, and a class moved while a field could hold an instance of a class that stayed, which new code read past its end. Such classes keep their instances now, and the report says why: methods must be the same, in the same slots, and so must the script interfaces a class implements, fields compare their types by name, and a class stays with the classes its fields can hold (libhxcpp #464) diff --git a/tools/hxcpp/BuildTool.hx b/tools/hxcpp/BuildTool.hx index 37776920..dc74fcc6 100644 --- a/tools/hxcpp/BuildTool.hx +++ b/tools/hxcpp/BuildTool.hx @@ -1217,8 +1217,10 @@ class BuildTool case "nvcc" : setupNvcc(); group.mNvcc = true; + // Set, not compared: the group kept the haxe tags, so it was + // given the host compiler's flags (libhxcpp #472) if (group.mTags=="haxe,static") - group.mTags=="nvcc"; + group.mTags="nvcc"; case "objprefix" : group.mObjPrefix = substitute(el.att.value); case "compilervalue" : diff --git a/tools/hxcpp/Compiler.hx b/tools/hxcpp/Compiler.hx index 261c9fae..691ea224 100644 --- a/tools/hxcpp/Compiler.hx +++ b/tools/hxcpp/Compiler.hx @@ -275,7 +275,9 @@ class Compiler args = args.concat(mCPPFlags); } - if (isRc || inFile.getTags()!=inFile.mGroup.getTags()) + // The precompiled header is built with the group's standard, and a file + // with its own cannot use it: MSVC and clang both refuse (libhxcpp #472) + if (isRc || inFile.getTags()!=inFile.mGroup.getTags() || inFile.mCxxStandard!=inFile.mGroup.mCxxStandard) allowPch = false; if (inFile.mGroup.isPrecompiled() && allowPch) diff --git a/tools/hxcpp/Setup.hx b/tools/hxcpp/Setup.hx index 759fa1a7..f2d589e3 100644 --- a/tools/hxcpp/Setup.hx +++ b/tools/hxcpp/Setup.hx @@ -490,16 +490,22 @@ class Setup if (Log.verbose) Log.println(""); + // Any NDKV, the lowest if there are several. Only 6 to 19 were + // looked for, so a request for r20 or later was ignored, and the newest + // NDK found was used instead (libhxcpp #472) var ndkVersion = 0; - for (i in 6...20) + var requested = ~/^NDKV([0-9]+)$/; + for (key in defines.keys()) { - if (defines.exists("NDKV" + i)) + if (requested.match(key)) { - ndkVersion = i; - Log.info("", "\x1b[33;1mRequested Android NDK r" + i + "\x1b[0m"); - break; + var version = Std.parseInt(requested.matched(1)); + if (version!=null && version>=6 && (ndkVersion==0 || version = try { haxe.Json.parse(sys.io.File.getContent(platformsJson)).min; } catch (e:Dynamic) { - Log.warn("Unable to determine minimum supported Android platform: " + e.toString()); + Log.warn("Unable to determine minimum supported Android platform: " + Std.string(e)); null; }; From c2c90dcd5ad332481a62de67896df38c24fada60 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Thu, 19 Nov 2026 09:42:51 -0500 Subject: [PATCH 25/36] Depend on every header hxcpp.h and the runtime include The build tool decides what to rebuild by comparing files against haxe-target.xml's depend lists, and the compile cache key hashes only the files listed. Headers hxcpp.h includes, directly or not, were missing from hxcpp-depends (hx/Functions.h, hx/FieldRef.h, hx/ErrorCodes.h, hx/Boot.h, hx/Undefine.h, cpp/CppInt32__.h, cpp/FastIterator.h, cpp/marshal/RootHandle.hpp and hx/Invoker.h), and headers the runtime's sources include were missing from its group (hx/DynamicImpl.h, hx/Memory.h, hx/NekoFunc.h, hx/CFFIJsPrime.h, hx/CFFINekoLoader.h, hx/TelemetryTracy.h and src/hx/FastMutex.h). So editing one, as an update of a haxelib git or dev checkout does, rebuilt nothing, and the cache relinked objects built before it. They are listed, and tools/check-depends.py, run in the Check headers job, fails when a header either reaches is missing again. Test: #error appended to include/hx/Functions.h now fails the next build, where it rebuilt nothing and exited 0 before; check-depends.py passes, and failed on main. Fixes #469 --- .github/workflows/main.yml | 5 +++ Changes.md | 1 + toolchain/haxe-target.xml | 17 ++++++++ tools/check-depends.py | 88 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 tools/check-depends.py diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e50ecf37..43941127 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -44,6 +44,11 @@ jobs: include name: Check public headers + # Every header hxcpp.h and the runtime include must be in haxe-target.xml's + # depend lists, or editing it rebuilds nothing (libhxcpp #469) + - name: Check the build tool's depend lists + run: python3 tools/check-depends.py + check-gc-defines: name: Check GC defines runs-on: ubuntu-latest diff --git a/Changes.md b/Changes.md index f4165d95..dfd4c895 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Fixed an edit to some of the runtime's headers rebuilding nothing, as when a haxelib git or dev checkout updates: hxcpp.h includes headers, hx/Functions.h and cpp/FastIterator.h among them, that the build tool's depend lists did not name, so neither the objects compiled with them nor the compile cache were checked against them, and a stale precompiled header stopped clang builds. Every header hxcpp.h and the runtime include is listed now, and CI checks that it stays so (libhxcpp #469) * Fixed three build tool settings that did nothing or failed: a file with its own cxx_standard in a group with a precompiled header failed to compile (C2855 on MSVC), an group was given the host compiler's flags because its tag was compared instead of set, and -DNDKV20 and up were ignored, so the newest NDK was used instead. An NDK without meta/platforms.json no longer stops the build with "Invalid field access : toString" (libhxcpp #472) * Fixed the build tool reusing stale objects when a define that changes how files compile was switched without the compile cache: only defines containing hxcpp, and a few others, were compared, so adding -D CPPIA_NO_JIT to a scriptable build failed to link, removing it linked a host without its JIT, and ABI, OBJC_ARC, STDLIBCPP and the others like them did nothing until the objects changed. Each now rebuilds what it affects (libhxcpp #470) * Fixed the build tool linking a stale object and exiting 0 when a compile failed and its old object could not be deleted, as when it is read-only or another process has it open, and hanging when a compile thread exited, as with HXCPP_EXIT_ON_ERROR on a compile error, or with an error such as two optimisation tags on one file. Both fail the build now, and HXCPP_EXIT_ON_ERROR works as a -D define, not only from the environment (libhxcpp #471) diff --git a/toolchain/haxe-target.xml b/toolchain/haxe-target.xml index da12bc90..4a17607e 100644 --- a/toolchain/haxe-target.xml +++ b/toolchain/haxe-target.xml @@ -83,6 +83,16 @@ + + + + + + + + + +
@@ -189,6 +199,13 @@ + + + + + + + diff --git a/tools/check-depends.py b/tools/check-depends.py new file mode 100644 index 00000000..48c83493 --- /dev/null +++ b/tools/check-depends.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +# Checks that toolchain/haxe-target.xml's depend lists name every header the +# runtime and generated code include, so editing one rebuilds what uses it. +# hxcpp-depends must hold everything hxcpp.h includes, directly or not, and the +# runtime group, with it, everything the runtime's sources include from this +# repository. A header missing there was never compared, so a change to it +# rebuilt nothing, and the compile cache reused objects built before it +# (libhxcpp #469). +# python3 tools/check-depends.py (from the repository root) +import os +import re +import sys + +root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +include_dir = os.path.join(root, 'include') +target = open(os.path.join(root, 'toolchain', 'haxe-target.xml'), encoding='utf-8').read() +include_re = re.compile(r'^\s*#\s*include\s*[<"]([^>"]+)[>"]', re.M) + + +def group(name): + m = re.search(r']*>(.*?)' % re.escape(name), target, re.S) + if not m: + sys.exit('no files group %s in haxe-target.xml' % name) + return m.group(1) + + +def depends(body): + return {os.path.normpath(os.path.join(root, d.replace('${HXCPP}/', ''))) + for d in re.findall(r' found hx/Memory.h + directory, name = os.path.split(path) + return os.path.isfile(path) and name in os.listdir(directory) + + +def resolve(name, from_dir): + for base in (from_dir, include_dir): + path = os.path.normpath(os.path.join(base, name)) + if path.startswith(root + os.sep) and exists_exact(path): + return path + return None + + +def closure(starts): + seen = set() + todo = list(starts) + while todo: + path = todo.pop() + if path in seen: + continue + seen.add(path) + text = open(path, encoding='utf-8', errors='replace').read() + for name in include_re.findall(text): + found = resolve(name, os.path.dirname(path)) + # Third-party sources keep their own headers, outside these lists + if found and 'thirdparty' not in found: + todo.append(found) + return seen + + +rel = lambda p: os.path.relpath(p, root).replace(os.sep, '/') +failed = False + +common = depends(group('hxcpp-depends')) +need = closure([os.path.join(include_dir, 'hxcpp.h')]) +missing = sorted(rel(p) for p in need - common) +if missing: + failed = True + print('hxcpp-depends misses headers hxcpp.h includes:') + for m in missing: + print(' ' + m) + +runtime = group('runtime') +sources = [os.path.join(root, f) for f in re.findall(r' Date: Thu, 19 Nov 2026 09:56:10 -0500 Subject: [PATCH 26/36] Trim the compile cache at most once in ten minutes Before every build with the compile cache, the build tool stat'ed every file in it to keep it under HXCPP_CACHE_MB, even when the build had nothing to compile. With tens of thousands of files that took up to seconds a build. It trims when the cache's .trimmed stamp is older than ten minutes, and writes the stamp when it does. Measured with HXCPP_TIMES, a build with nothing to compile and a cache of 29792 files, three runs each on Windows x64: "setup cache" took 1138, 142 and 98 ms before, and 162 (the trim), 14 and 3 ms after. The other fixed cost in #473, running the MSVC setup script on every build (2.7 to 9.4 s in the same runs), is not changed here. Part of #473 --- Changes.md | 1 + tools/hxcpp/BuildTool.hx | 2 +- tools/hxcpp/CompileCache.hx | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Changes.md b/Changes.md index dfd4c895..84180ffa 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.0 (unreleased) ------------------------------------------------------------ +* Builds with the compile cache no longer size the whole cache each time: with 29792 files that took 98 ms to over a second before every build, even one with nothing to compile, and takes 3 to 14 ms now. The cache is trimmed to HXCPP_CACHE_MB at most once in ten minutes (libhxcpp #473) * Fixed an edit to some of the runtime's headers rebuilding nothing, as when a haxelib git or dev checkout updates: hxcpp.h includes headers, hx/Functions.h and cpp/FastIterator.h among them, that the build tool's depend lists did not name, so neither the objects compiled with them nor the compile cache were checked against them, and a stale precompiled header stopped clang builds. Every header hxcpp.h and the runtime include is listed now, and CI checks that it stays so (libhxcpp #469) * Fixed three build tool settings that did nothing or failed: a file with its own cxx_standard in a group with a precompiled header failed to compile (C2855 on MSVC), an group was given the host compiler's flags because its tag was compared instead of set, and -DNDKV20 and up were ignored, so the newest NDK was used instead. An NDK without meta/platforms.json no longer stops the build with "Invalid field access : toString" (libhxcpp #472) * Fixed the build tool reusing stale objects when a define that changes how files compile was switched without the compile cache: only defines containing hxcpp, and a few others, were compared, so adding -D CPPIA_NO_JIT to a scriptable build failed to link, removing it linked a host without its JIT, and ABI, OBJC_ARC, STDLIBCPP and the others like them did nothing until the objects changed. Each now rebuilds what it affects (libhxcpp #470) diff --git a/tools/hxcpp/BuildTool.hx b/tools/hxcpp/BuildTool.hx index dc74fcc6..2198179c 100644 --- a/tools/hxcpp/BuildTool.hx +++ b/tools/hxcpp/BuildTool.hx @@ -311,7 +311,7 @@ class BuildTool if (cached) { var cacheSize = mDefines.exists("HXCPP_CACHE_MB") ? Std.parseInt( mDefines.get("HXCPP_CACHE_MB") ) : 1000; - if (cacheSize!=null && cacheSize>0) + if (cacheSize!=null && cacheSize>0 && CompileCache.dueForTrim()) CompileCache.clear(0,cacheSize,false,null); } diff --git a/tools/hxcpp/CompileCache.hx b/tools/hxcpp/CompileCache.hx index a1041a88..9392f3e1 100644 --- a/tools/hxcpp/CompileCache.hx +++ b/tools/hxcpp/CompileCache.hx @@ -93,6 +93,22 @@ class CompileCache return dir + "/" + hash.substr(2) + inExt; } + // Sizing the cache stats every file in it, which took seconds once it held + // tens of thousands, and ran before every build, even one with nothing to + // compile (libhxcpp #473). Once in ten minutes keeps it near its limit + public static function dueForTrim():Bool + { + var stamp = compileCache + "/.trimmed"; + try + { + if (FileSystem.exists(stamp) && Date.now().getTime() - FileSystem.stat(stamp).mtime.getTime() < 10 * 60 * 1000.0) + return false; + sys.io.File.saveContent(stamp, ""); + } + catch(e:Dynamic) { } + return true; + } + public static function clear(inDays:Int,inMB:Int,inLogInfo:Bool,inProject:String) { try From ae9dd78e28f268d681ade91eef2d1870222cc169 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:55:11 -0500 Subject: [PATCH 27/36] Set a thread's error outside the log lock when a process cannot start When a compile thread could not start its command, as when clang-cl is not on PATH, it set the build's error while holding the log lock. With HXCPP_EXIT_ON_ERROR that ends the thread, which left the lock held, and every other compile thread then waited for it for ever. The error is now set after the lock is released. --- tools/hxcpp/ProcessManager.hx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tools/hxcpp/ProcessManager.hx b/tools/hxcpp/ProcessManager.hx index 8171e040..62004f59 100644 --- a/tools/hxcpp/ProcessManager.hx +++ b/tools/hxcpp/ProcessManager.hx @@ -404,12 +404,14 @@ class ProcessManager catch(e:Dynamic) { Log.lock(); - if (BuildTool.threadExitCode == 0) - { + var first = BuildTool.threadExitCode == 0; + if (first) Log.info('${Log.RED}${Log.BOLD}$e${Log.NORMAL}\n'); - BuildTool.setThreadError(-1); - } Log.unlock(); + // Not under the lock: with HXCPP_EXIT_ON_ERROR it ends this thread, and + // the other compile threads then waited for the lock for ever + if (first) + BuildTool.setThreadError(-1); return -1; } From c02c8db15c795810d8d8c8f5fbe7e13b2f68e02a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:55:11 -0500 Subject: [PATCH 28/36] Use an ANDROID_NDK_ROOT that is the NDK version requested Since NDKV20 and up are read, any NDKV define searched for the NDK and ignored ANDROID_NDK_ROOT. The search through ANDROID_SDK finds only the newest NDK there, so a build with ANDROID_NDK_ROOT at NDK 25, NDKs 25 and 28 installed and a leftover -DNDKV25 stopped with "does not contain requested NDK 25", where it used to build with the configured root. A configured root that is the requested version is now used as it is. --- tools/hxcpp/Setup.hx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tools/hxcpp/Setup.hx b/tools/hxcpp/Setup.hx index f2d589e3..c073cf8e 100644 --- a/tools/hxcpp/Setup.hx +++ b/tools/hxcpp/Setup.hx @@ -507,7 +507,17 @@ class Setup if (ndkVersion!=0) Log.info("", "\x1b[33;1mRequested Android NDK r" + ndkVersion + "\x1b[0m"); - if (!defines.exists("ANDROID_NDK_ROOT") || ndkVersion!=0) + // An ANDROID_NDK_ROOT that is already the requested version is used as + // it is, as before NDKV20 and up were read: a search would find only the + // newest NDK in the SDK and stop the build when that is another version + var rootMatches = false; + if (defines.exists("ANDROID_NDK_ROOT") && ndkVersion!=0) + { + var configured = defines.get("ANDROID_NDK_ROOT"); + rootMatches = FileSystem.exists(configured) && Std.int(getNdkVersion(configured))==ndkVersion; + } + + if (!defines.exists("ANDROID_NDK_ROOT") || (ndkVersion!=0 && !rootMatches)) { root = Setup.findAndroidNdkRoot( defines, ndkVersion ); if (root==null) From 185eea65c403a5b3d665ad849315f4f655ea6880 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:55:12 -0500 Subject: [PATCH 29/36] Check that each compile error test fails for its own reason check.sh passed any build that failed, so one failing for an unrelated reason, such as a missing tool or a Haxe setup problem, passed too. Each case now also needs the error it is about in its log: the undefined function the error test calls, or the build tool's message about two optimisation tags. --- test/compile_errors/check.sh | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/test/compile_errors/check.sh b/test/compile_errors/check.sh index f2808d63..921c1815 100644 --- a/test/compile_errors/check.sh +++ b/test/compile_errors/check.sh @@ -26,22 +26,28 @@ build() { echo "exit $?" } +# expect_failure : the build must +# fail for that reason, not for an unrelated one such as a missing tool expect_failure() { - local name=$1; shift + local name=$1 expected=$2; shift 2 local result result=$(build "$@") if [ "$result" = "exit 0" ] || [ "$result" = "hung" ]; then echo "::error::$name: $result, where it should fail" tail -20 build.log failed=1 + elif ! grep -q "$expected" build.log; then + echo "::error::$name: failed ($result), but without \"$expected\" in its log" + tail -20 build.log + failed=1 else echo "$name: failed as it should ($result)" fi } -(cd error && HXCPP_EXIT_ON_ERROR=1 expect_failure "HXCPP_EXIT_ON_ERROR in the environment" haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 -(cd error && expect_failure "-D HXCPP_EXIT_ON_ERROR" haxe build.hxml -D HXCPP_EXIT_ON_ERROR -D "$HXCPP_ARCH_FLAG") || failed=1 -(cd tags && expect_failure "two optimisation tags" haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 +(cd error && HXCPP_EXIT_ON_ERROR=1 expect_failure "HXCPP_EXIT_ON_ERROR in the environment" this_is_not_cpp haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 +(cd error && expect_failure "-D HXCPP_EXIT_ON_ERROR" this_is_not_cpp haxe build.hxml -D HXCPP_EXIT_ON_ERROR -D "$HXCPP_ARCH_FLAG") || failed=1 +(cd tags && expect_failure "two optimisation tags" "More than one optimization tag" haxe build.hxml -D "$HXCPP_ARCH_FLAG") || failed=1 # Windows only: elsewhere a read-only file can still be deleted if [ "$OS" = "Windows_NT" ]; then @@ -56,7 +62,7 @@ if [ "$OS" = "Windows_NT" ]; then # Newer than the object by more than the build tool's one second sleep 2 cp ../Main.hx Main.hx - expect_failure "a compile error over a read-only object" haxe build.hxml -D "$HXCPP_ARCH_FLAG" + expect_failure "a compile error over a read-only object" this_is_not_cpp haxe build.hxml -D "$HXCPP_ARCH_FLAG" # The old object must not be linked: the link itself may then fail or not if grep -q 'Link:' build.log; then echo "::error::a compile error over a read-only object: linked the old object" From 7fbdaeff556265412a38a6023c0c098a12d5cb93 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 07:55:12 -0500 Subject: [PATCH 30/36] Wait for another thread's cppia link in a GC-free zone link() takes a lock that every module load shares, and allocates while holding it: resolving each host class makes a String. A thread blocked on that lock was outside a GC-free zone, so a collection the linking thread reached waited for it, while it waited for the linking thread. Two threads loading modules at once could hang the process. A thread that finds the lock taken now waits for it in a GC-free zone. --- src/hx/cppia/HaxeNative.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/hx/cppia/HaxeNative.cpp b/src/hx/cppia/HaxeNative.cpp index ca8feae7..e1f15c09 100644 --- a/src/hx/cppia/HaxeNative.cpp +++ b/src/hx/cppia/HaxeNative.cpp @@ -120,9 +120,16 @@ HaxeNativeClass *HaxeNativeClass::hxObject() void HaxeNativeClass::link() { - // Each load links, and the super classes it sets are shared by every module + // Each load links, and the super classes it sets are shared by every module. + // Linking allocates, so a thread that waits for another's link waits in a + // GC-free zone: outside one, a collection the linker reached waited for it static std::mutex linkLock; - std::lock_guard lock(linkLock); + if (!linkLock.try_lock()) + { + hx::AutoGCFreeZone zone; + linkLock.lock(); + } + std::lock_guard lock(linkLock, std::adopt_lock); HaxeNativeClass *hxObj = hxObject(); for(ScriptRegisteredMap::iterator i = sScriptRegistered->begin(); i!=sScriptRegistered->end();++i) { From 9ec5317fbdf3b1ab2545b55dff63be49ad1937b0 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 08:02:07 -0500 Subject: [PATCH 31/36] Mark nothing for a pointer field holding a block's base address A cpp.Pointer field is marked by searching back from where it points for the allocation's start, and since its reach covers the whole block, a field holding exactly a block's base address, such as one past the end of an array whose buffer ends where its block does, made the offset wrap and the search walk for hours. A block's base holds no object, so such a field now marks nothing. Test: GcPointerFieldBlockBase points 100 cpp.Pointer fields at the base of the block their arrays are in and collects 5 times. --- src/hx/gc/Immix.cpp | 4 ++ .../GcPointerFieldBlockBase/Main.hx | 47 +++++++++++++++++++ .../GcPointerFieldBlockBase/build.hxml | 2 + .../GcPointerFieldBlockBase/stdout.txt | 2 + 4 files changed, 55 insertions(+) create mode 100644 test/regression/GcPointerFieldBlockBase/Main.hx create mode 100644 test/regression/GcPointerFieldBlockBase/build.hxml create mode 100644 test/regression/GcPointerFieldBlockBase/stdout.txt diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 9818cefc..e5d78b33 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -7924,7 +7924,11 @@ static void MarkConservativeReach(int *inBottom, int *inTop,hx::MarkContext *__i BlockDataInfo* info{ (*gBlockInfo)[block->mId] }; size_t pos{ potentialObject & IMMIX_BLOCK_OFFSET_MASK }; + // A block's base address, such as a one-past-end pointer into the + // block before, holds no object, and pos - sizeof(int) would wrap + // to a reach the search below took near for ever to walk AllocType t{ + pos < sizeof(int) ? allocNone : (inReach || sgCheckInternalOffset) ? info->GetEnclosingAllocType(pos - sizeof(int), &potentialObject, allowPrevious, inReach ? inReach : sgCheckInternalOffset) : info->GetAllocType(pos - sizeof(int), allowPrevious) }; diff --git a/test/regression/GcPointerFieldBlockBase/Main.hx b/test/regression/GcPointerFieldBlockBase/Main.hx new file mode 100644 index 00000000..df0b0800 --- /dev/null +++ b/test/regression/GcPointerFieldBlockBase/Main.hx @@ -0,0 +1,47 @@ +// A cpp.Pointer field is marked as a pointer into an allocation, searching back +// from where it points for the allocation's start (libhxcpp #451). A pointer +// holding exactly a block's base address, such as one past the end of an array +// whose buffer ends where its block does, made that search's offset wrap, and +// the collection walked for hours. It holds no object and keeps nothing. +@:cppFileCode(' +static ::cpp::Pointer blockBaseOf(::Array inArray) +{ + #ifdef HXCPP_GC_BIG_BLOCKS + const size_t blockSize = (size_t)1 << 16; + #else + const size_t blockSize = (size_t)1 << 15; + #endif + size_t at = (size_t)inArray->GetBase(); + return ::cpp::Pointer((int *)(at & ~(blockSize - 1))); +} +') +class Holder { + public var base:cpp.Pointer; + + public function new() {} +} + +class Main { + static var holders:Array; + static var arrays:Array>; + + static function main() { + holders = []; + arrays = []; + for (i in 0...100) { + var a = [for (j in 0...50) j]; + arrays.push(a); + var h = new Holder(); + h.base = untyped __cpp__("blockBaseOf({0})", a); + holders.push(h); + } + var start = haxe.Timer.stamp(); + for (i in 0...5) + cpp.vm.Gc.run(true); + var sum = 0; + for (a in arrays) + sum += a[49]; + Sys.println('collections finished: ${haxe.Timer.stamp() - start < 30}'); + Sys.println('arrays kept: ${sum == 49 * 100}'); + } +} diff --git a/test/regression/GcPointerFieldBlockBase/build.hxml b/test/regression/GcPointerFieldBlockBase/build.hxml new file mode 100644 index 00000000..b484e67e --- /dev/null +++ b/test/regression/GcPointerFieldBlockBase/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/GcPointerFieldBlockBase/stdout.txt b/test/regression/GcPointerFieldBlockBase/stdout.txt new file mode 100644 index 00000000..4a478136 --- /dev/null +++ b/test/regression/GcPointerFieldBlockBase/stdout.txt @@ -0,0 +1,2 @@ +collections finished: true +arrays kept: true From 7a51344dc486347e2239699a0ed30d3b58c14316 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 08:02:07 -0500 Subject: [PATCH 32/36] Keep a cppia instance whose class retyped a method adoptInstances moved an instance when its class's methods kept their names and vtable slots, but a call site keeps the types it linked with: change only a():String to a():Int, and old code calling a() on a moved instance read the Int as a String. A method's return and argument types must now match too, for script interfaces as well. Test: CppiaAdoptLayouts has a scenario that retypes a method's return, which now keeps its instances, interpreted and under the JIT. --- src/hx/cppia/CppiaModule.cpp | 33 +++++++++++++++++-- test/regression/CppiaAdoptLayouts/Main.hx | 7 ++-- test/regression/CppiaAdoptLayouts/build.hxml | 8 +++++ .../CppiaAdoptLayouts/retyped/new/Script.hx | 12 +++++++ .../CppiaAdoptLayouts/retyped/old/Script.hx | 21 ++++++++++++ test/regression/CppiaAdoptLayouts/stdout.txt | 12 +++++++ 6 files changed, 87 insertions(+), 6 deletions(-) create mode 100644 test/regression/CppiaAdoptLayouts/retyped/new/Script.hx create mode 100644 test/regression/CppiaAdoptLayouts/retyped/old/Script.hx diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index 2a464c1d..ccb910ea 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -1338,14 +1338,41 @@ static std::string slotDifference(const char *inWhat, CppiaClassInfo *inFrom, st // same vtable slot in both. A call's slot is fixed when its code links, so old // code still running would call a moved instance by its old slots, reaching // another method or reading its return as another type (libhxcpp #464) +// A method's return and argument types, by name. A call site keeps the types +// it linked with, so old code calling a moved instance's retyped method read +// an Int as a String, or passed a String where the new code takes an Int +static std::string methodSignature(CppiaFunction *inFunc) +{ + CppiaModule &cppia = inFunc->cppia; + int types = (int)cppia.types.size(); + std::string result = inFunc->returnType>=0 && inFunc->returnTypereturnType]) : std::string("?"); + result += "("; + for(size_t a=0;aargs.size();a++) + { + const ArgInfo &arg = inFunc->args[a]; + if (a) + result += ","; + if (arg.optional) + result += "?"; + result += arg.typeId>=0 && arg.typeIdmemberFunctions.size()!=inTo->memberFunctions.size()) return "its methods are not the same"; for(size_t i=0;imemberFunctions.size();i++) - if (inFrom->memberFunctions[i]->name!=inTo->memberFunctions[i]->name || - inFrom->memberFunctions[i]->vtableSlot!=inTo->memberFunctions[i]->vtableSlot) - return "method " + inFrom->memberFunctions[i]->name + " is not where it was"; + { + CppiaFunction *from = inFrom->memberFunctions[i]; + CppiaFunction *to = inTo->memberFunctions[i]; + if (from->name!=to->name || from->vtableSlot!=to->vtableSlot) + return "method " + from->name + " is not where it was"; + if (methodSignature(from)!=methodSignature(to)) + return "method " + from->name + " changed its types"; + } return std::string(); } diff --git a/test/regression/CppiaAdoptLayouts/Main.hx b/test/regression/CppiaAdoptLayouts/Main.hx index d55581f7..aadbf49a 100644 --- a/test/regression/CppiaAdoptLayouts/Main.hx +++ b/test/regression/CppiaAdoptLayouts/Main.hx @@ -1,8 +1,9 @@ import haxe.io.Path; // libhxcpp #464. adoptInstances moved instances whose methods were not in the -// same vtable slots, so old code still running called the wrong method, or -// read its return as another type, and moved instances whose fields held +// same vtable slots, or whose methods changed their types, so old code still +// running called the wrong method, or read its return as another type, and +// moved instances whose fields held // instances that stayed, which new code read with the new layout. Neither // moves now, and the report says why. class Main { @@ -27,7 +28,7 @@ class Main { for (jit in [false, true]) { cpp.cppia.Host.enableJit(jit); Sys.println(jit ? "jit" : "interpreted"); - for (name in ["methods", "fields"]) { + for (name in ["methods", "retyped", "fields"]) { Sys.println(name); try { scenario(dir, name); diff --git a/test/regression/CppiaAdoptLayouts/build.hxml b/test/regression/CppiaAdoptLayouts/build.hxml index 1ab45b69..7770c179 100644 --- a/test/regression/CppiaAdoptLayouts/build.hxml +++ b/test/regression/CppiaAdoptLayouts/build.hxml @@ -6,6 +6,14 @@ --main Script -cppia bin/methods-new.cppia --next +-cp retyped/old +--main Script +-cppia bin/retyped-old.cppia +--next +-cp retyped/new +--main Script +-cppia bin/retyped-new.cppia +--next -cp fields/old --main Script -cppia bin/fields-old.cppia diff --git a/test/regression/CppiaAdoptLayouts/retyped/new/Script.hx b/test/regression/CppiaAdoptLayouts/retyped/new/Script.hx new file mode 100644 index 00000000..ec6cb579 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/retyped/new/Script.hx @@ -0,0 +1,12 @@ +// New generation: the same methods in the same slots, but a now returns an +// Int, which old code calling a moved instance would read as a String +class Foo { + public var v:Int = 7; + public function new() {} + public function a():Int return 123; + public function b():String return "new b " + v; +} + +class Script { + static function main() {} +} diff --git a/test/regression/CppiaAdoptLayouts/retyped/old/Script.hx b/test/regression/CppiaAdoptLayouts/retyped/old/Script.hx new file mode 100644 index 00000000..bde85804 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/retyped/old/Script.hx @@ -0,0 +1,21 @@ +// Old generation: Foo.a and Foo.b take the first two script vtable slots +class Foo { + public var v:Int = 7; + public function new() {} + public function a():String return "old a " + v; + public function b():String return "old b " + v; +} + +class Script { + public static var foo:Foo; + // Old code calling methods on an instance that adoptInstances moves + public static function before():String return foo.b() + " / " + foo.a(); + public static function after():String { + var s = foo.b(); + Sys.println(" old code foo.b() -> " + s); + var t = foo.a(); + Sys.println(" old code foo.a() -> length " + t.length); + return s + " / " + t; + } + static function main() foo = new Foo(); +} diff --git a/test/regression/CppiaAdoptLayouts/stdout.txt b/test/regression/CppiaAdoptLayouts/stdout.txt index 0f0befda..1df180aa 100644 --- a/test/regression/CppiaAdoptLayouts/stdout.txt +++ b/test/regression/CppiaAdoptLayouts/stdout.txt @@ -5,6 +5,12 @@ methods old code foo.b() -> old b 7 old code foo.a() -> length 7 after, old code: old b 7 / old a 7 +retyped + before: old b 7 / old a 7 + adopt Foo: moved 0, method a changed its types + old code foo.b() -> old b 7 + old code foo.a() -> length 7 + after, old code: old b 7 / old a 7 fields before: p.get() = 1 adopt Child: moved 0, field n is not where it was @@ -17,6 +23,12 @@ methods old code foo.b() -> old b 7 old code foo.a() -> length 7 after, old code: old b 7 / old a 7 +retyped + before: old b 7 / old a 7 + adopt Foo: moved 0, method a changed its types + old code foo.b() -> old b 7 + old code foo.a() -> length 7 + after, old code: old b 7 / old a 7 fields before: p.get() = 1 adopt Child: moved 0, field n is not where it was From 51106e638417aed9a163d9c99b207f48036432c5 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 08:02:07 -0500 Subject: [PATCH 33/36] Read cppia enum parameters inline, checking the value's own count Haxe 4.3.7 types almost every enum parameter read as Dynamic, so the JIT's new bounds check sent nearly every read through a native call that boxed the value, an allocation for a Float, a String or most Ints on a hot path of pattern matching. A script enum's reads stayed inline, bound only by its largest constructor, so a malformed file could still read past a value with fewer parameters. Every read now compares the index with the value's own count inline and reads the parameter there, and only a null value or an index past the count takes the call. A super constructor call is also checked against every class the linking class extends: a class with no constructor of its own links the one it inherits, and a valid file whose inherited constructor calls its own super class failed to load. --- src/hx/cppia/Cppia.cpp | 56 ++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 6bd7f586..20518ffc 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -3568,9 +3568,17 @@ struct CallMember : public CppiaExpr if (!type->cppiaClass->newFunc) throw "Super constructor call on a class with no constructor"; // A class's constructor calls its own super class's. Any other script - // class's ran on an instance laid out for this one, past its end - if (inModule.linkingClass && classId!=inModule.linkingClass->superId) - throw "Super constructor call to a class that is not the super class"; + // class's ran on an instance laid out for this one, past its end. A + // class with no constructor of its own links the one it inherits, so + // the call may be to the super class of any class it extends + if (inModule.linkingClass) + { + bool ancestor = false; + for(CppiaClassInfo *c=inModule.linkingClass; c && !ancestor; c=c->superType ? c->superType->cppiaClass : 0) + ancestor = classId==c->superId; + if (!ancestor) + throw "Super constructor call to a class that is not the super class"; + } //CPPIALOG("Using cppia super %p %p\n", type->cppiaClass->newFunc, type->cppiaClass->newFunc->funExpr); CppiaExpr *replace = new CallFunExpr( this, 0, (ScriptCallable*)type->cppiaClass->newFunc->funExpr, args, true ); replace->link(inModule); @@ -6431,10 +6439,9 @@ struct EnumIExpr : public CppiaDynamicExpr int index; int classId; // Whether link bounded index by the enum's constructors - bool indexChecked; - EnumIExpr(CppiaStream &stream) : indexChecked(false) + EnumIExpr(CppiaStream &stream) { classId = stream.getTypeId(); index = stream.getInt(); @@ -6445,17 +6452,13 @@ struct EnumIExpr : public CppiaDynamicExpr CppiaExpr *link(CppiaModule &inModule) HXCPP_OVERRIDE { // An index from the file read past the enum value. A script enum's - // largest constructor bounds it here, for the JIT, which reads the - // parameter directly; the interpreter checks the value's own count + // largest constructor bounds it here; the interpreter and the JIT + // also check the value's own count when they read if (index<0) throw "Bad enum index"; CppiaClassInfo *info = inModule.types[classId]->cppiaClass; - if (info && info->isEnum) - { - if (index>=info->mostEnumArgs()) - throw "Bad enum index"; - indexChecked = true; - } + if (info && info->isEnum && index>=info->mostEnumArgs()) + throw "Bad enum index"; object = object->link(inModule); return this; } @@ -6479,20 +6482,31 @@ struct EnumIExpr : public CppiaDynamicExpr return value->_hx_getParamI(inIndex).mPtr; } + // Where an enum value keeps its parameter count, which is protected + struct CountOf : public EnumBase_obj + { + static int offset() { return (int)offsetof(CountOf, mFixedFields); } + }; + void genCode(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) HXCPP_OVERRIDE { object->genCode(compiler, sJitTemp0, etObject); - if (indexChecked) - { - int offset = sizeof( EnumBase_obj ) + index*sizeof(cpp::Variant); + int offset = sizeof( EnumBase_obj ) + index*sizeof(cpp::Variant); + { + // The value's own count bounds the read, as in the interpreter: a + // host enum's constructors are not known here, Haxe types most reads + // as Dynamic, and a script enum's largest constructor can have more + // parameters than this value. The usual read stays inline: only a + // null value or an index past its count takes the call + JumpId isNull = compiler->compare(cmpP_ZERO, sJitTemp0.as(jtPointer), (void *)0); + JumpId past = compiler->compare(cmpI_SIG_LESS_EQUAL, sJitTemp0.star(jtInt, CountOf::offset()), JitVal(index)); compiler->genVariantValueTemp0(offset, inDest, destType); - } - else - { - // A host enum's constructors are not known here, so its value's own - // count bounds the read, as in the interpreter + JumpId done = compiler->jump(); + compiler->comeFrom(isNull); + compiler->comeFrom(past); compiler->callNative( (void *)paramChecked, sJitTemp0.as(jtPointer), JitVal(index) ); compiler->convertReturnReg(etObject, inDest, destType); + compiler->comeFrom(done); } } #endif From 5cfc876da7fcbc74717b26cd82db3a62a1370e24 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 09:28:02 -0500 Subject: [PATCH 34/36] Put GcPointerFieldBlockBase's helper in Main's file The C++ helper was attached to Holder, so it went to Holder.cpp and Main.cpp, which calls it, did not build. --- test/regression/GcPointerFieldBlockBase/Main.hx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/regression/GcPointerFieldBlockBase/Main.hx b/test/regression/GcPointerFieldBlockBase/Main.hx index df0b0800..853e0d21 100644 --- a/test/regression/GcPointerFieldBlockBase/Main.hx +++ b/test/regression/GcPointerFieldBlockBase/Main.hx @@ -3,6 +3,12 @@ // holding exactly a block's base address, such as one past the end of an array // whose buffer ends where its block does, made that search's offset wrap, and // the collection walked for hours. It holds no object and keeps nothing. +class Holder { + public var base:cpp.Pointer; + + public function new() {} +} + @:cppFileCode(' static ::cpp::Pointer blockBaseOf(::Array inArray) { @@ -15,12 +21,6 @@ static ::cpp::Pointer blockBaseOf(::Array inArray) return ::cpp::Pointer((int *)(at & ~(blockSize - 1))); } ') -class Holder { - public var base:cpp.Pointer; - - public function new() {} -} - class Main { static var holders:Array; static var arrays:Array>; From aff282f40c7e288beac1ef0b81dc3e45a11c1a6a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 12:30:29 -0500 Subject: [PATCH 35/36] Close each regression test's process in the runner The runner never closed a test's process, so the pipes to it stayed open and every later test inherited them. By SocketSelectHighDescriptors, some 290 tests in, its 80 sockets were past macOS's FD_SETSIZE of 1024, select failed, and the test exited 255 on macOS arm64 once the suite had grown by a few tests. Run alone it passes there. --- test/regression/Run.hx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/regression/Run.hx b/test/regression/Run.hx index 649c2f99..e4359feb 100644 --- a/test/regression/Run.hx +++ b/test/regression/Run.hx @@ -42,6 +42,10 @@ function runOutput(test:String, emscripten:Bool):String { final stdout = proc.stdout.readAll().toString(); final code = proc.exitCode(); stderrRead.wait(); + // Each test's pipes stayed open here, and every later test inherited them: + // after some 290 tests, SocketSelectHighDescriptors' sockets were past + // macOS's FD_SETSIZE of 1024, and its select failed + proc.close(); lastStderr = stderr.replace("\r\n", "\n"); if (emscripten && code == 124) { From cdf1cd9f93349bf1d77e56deb07072351e0ca9f7 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 21 Nov 2026 16:20:24 -0500 Subject: [PATCH 36/36] libhxcpp 6.0.0 --- Changes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Changes.md b/Changes.md index 84180ffa..c090a92a 100644 --- a/Changes.md +++ b/Changes.md @@ -1,5 +1,5 @@ -libhxcpp 6.0.0 (unreleased) +libhxcpp 6.0.0 ------------------------------------------------------------ * Builds with the compile cache no longer size the whole cache each time: with 29792 files that took 98 ms to over a second before every build, even one with nothing to compile, and takes 3 to 14 ms now. The cache is trimmed to HXCPP_CACHE_MB at most once in ten minutes (libhxcpp #473)