diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e50ecf37d..439411273 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/.github/workflows/test.yml b/.github/workflows/test.yml index 007a0b254..d3b15f405 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' }} @@ -495,11 +500,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 81db6b76f..c090a92ab 100644 --- a/Changes.md +++ b/Changes.md @@ -1,7 +1,31 @@ -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) +* 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) +* 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) +* 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) +* 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) +* 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) +* 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/docs/CppiaModuleRelease.md b/docs/CppiaModuleRelease.md index 42c17d271..6a304cac7 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/include/cpp/Pointer.h b/include/cpp/Pointer.h index 74a68ee35..054662584 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/GC.h b/include/hx/GC.h index d80487f15..8ca82ae6a 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/include/hx/StdLibs.h b/include/hx/StdLibs.h index 58e724f0b..7f937943a 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/include/hx/Tls.h b/include/hx/Tls.h index db1409a40..76764bdd3 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/src/hx/CFFI.cpp b/src/hx/CFFI.cpp index 18584bcd0..9dcbbaeaf 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/Hash.h b/src/hx/Hash.h index b6ee9ee52..e48332701 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/StdLibs.cpp b/src/hx/StdLibs.cpp index 7553df56b..6789c81ac 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/cppia/ArrayBuiltin.cpp b/src/hx/cppia/ArrayBuiltin.cpp index 0ecacbf92..20669a1cf 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 @@ -153,8 +156,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 +177,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 +198,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 +219,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); @@ -211,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); @@ -220,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); @@ -233,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); @@ -246,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); @@ -259,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 @@ -288,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; @@ -328,6 +370,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); @@ -410,15 +453,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"; @@ -693,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; } @@ -980,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); @@ -1149,8 +1202,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) { @@ -1167,16 +1223,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 @@ -1184,21 +1243,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 @@ -1206,7 +1269,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) { @@ -1333,20 +1398,24 @@ 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->checkException(); + compiler->comeFrom(enough); + // sJitTemp1 = this compiler->move(sJitTemp1, arrayThis); // sJitTemp0 = length @@ -1443,6 +1512,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); @@ -1550,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(); @@ -1962,23 +2041,28 @@ 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) { 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) ); + 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 46ba3fb6f..3087abc62 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 } @@ -176,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) @@ -306,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) @@ -666,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); @@ -826,11 +886,21 @@ 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); compiler->callNative( (void *)arraySetInt, thisVal, index, sJitArg2.as(jtInt)); + compiler->checkException(); compiler->convertReturnReg(etInt, inDest, destType); break; case etFloat: @@ -838,6 +908,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 +917,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: ; //? @@ -863,17 +936,19 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case afPush: { - switch(args[0]->getType()) + switch(anyStoreType(args[0])) { 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 +956,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: ; //? } @@ -896,17 +973,19 @@ struct ArrayBuiltinAny : public ArrayBuiltinBase case afUnshift: { - switch(args[0]->getType()) + switch(anyStoreType(args[0])) { 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 +993,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: ; //? } @@ -928,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 3094c88b0..20518ffcb 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 @@ -3536,6 +3567,18 @@ 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. 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); @@ -3940,7 +3983,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 +4104,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) ); } @@ -4147,8 +4194,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); } @@ -4458,81 +4504,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 +4799,7 @@ struct MemReferenceCrement : public CppiaExpr if ( inDest.type==jtVoid) { compiler->callNative( diff<0 ? (void *)objDecWb : (void *)objIncWb, obj, offset ); + compiler->checkException(); } else { @@ -4734,6 +4813,7 @@ struct MemReferenceCrement : public CppiaExpr default: ; } compiler->callNative(func, obj, offset); + compiler->checkException(); compiler->convertReturnReg( etObject, inDest, destType ); } @@ -4746,6 +4826,7 @@ struct MemReferenceCrement : public CppiaExpr if ( inDest.type==jtVoid) { compiler->callNative( diff<0 ? (void *)objDec : (void *)objInc, ioPtr ); + compiler->checkException(); } else { @@ -4759,6 +4840,7 @@ struct MemReferenceCrement : public CppiaExpr default: ; } compiler->callNative(func, ioPtr); + compiler->checkException(); compiler->convertReturnReg( etObject, inDest, destType ); } } @@ -5622,54 +5704,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 +5787,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 +5814,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 +5830,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 +5937,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; } @@ -5829,8 +5946,9 @@ 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(); } else { @@ -5847,6 +5965,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 +5978,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 +5991,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 +6026,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 +6290,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 +6331,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) @@ -6301,11 +6438,12 @@ struct EnumIExpr : public CppiaDynamicExpr CppiaExpr *object; int index; int classId; + // Whether link bounded index by the enum's constructors EnumIExpr(CppiaStream &stream) { - classId = stream.getInt(); + classId = stream.getTypeId(); index = stream.getInt(); object = createCppiaExpr(stream); } @@ -6313,6 +6451,14 @@ 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; 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 && index>=info->mostEnumArgs()) + throw "Bad enum index"; object = object->link(inModule); return this; } @@ -6321,15 +6467,47 @@ 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; + } + + // 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); int offset = sizeof( EnumBase_obj ) + index*sizeof(cpp::Variant); - compiler->genVariantValueTemp0(offset, inDest, destType); + { + // 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); + 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 }; diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 4eb9e2483..8b1f8bd81 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; @@ -844,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 3b30bbfdc..a520f5022 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 { @@ -502,6 +509,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 ); @@ -850,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 @@ -2246,8 +2267,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/CppiaCompiler.cpp b/src/hx/cppia/CppiaCompiler.cpp index 7fad214f5..51942dfb0 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 714150d0f..ddb41a830 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 f8be08f8f..ccb910eac 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); @@ -135,6 +136,10 @@ CppiaModule::CppiaModule() if (sgNativeNameSlotCount>0) for(int i=2;i2 ? sgNativeNameSlotCount : 1; std::lock_guard lock(sModuleLock); allModules().push_back(this); @@ -338,7 +343,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; } @@ -421,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; @@ -760,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(); @@ -1308,12 +1327,69 @@ 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) +// 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++) + { + 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(); +} + +// 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) { @@ -1338,6 +1414,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(); } @@ -1384,6 +1471,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/src/hx/cppia/CppiaStream.h b/src/hx/cppia/CppiaStream.h index ec0a49ce4..97e08b6bb 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/src/hx/cppia/HaxeNative.cpp b/src/hx/cppia/HaxeNative.cpp index 9bd24ac66..e1f15c090 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,34 @@ 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. + // 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; + 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) { @@ -131,7 +148,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 +299,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/src/hx/cppia/StringBuiltin.cpp b/src/hx/cppia/StringBuiltin.cpp index 2e7a6b94f..17888ef4b 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 0cb24d8b2..e5d78b332 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)) { @@ -1459,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 @@ -1505,7 +1510,7 @@ struct BlockDataInfo if (inOffset>=scan && inOffset scan + sgCheckInternalOffset) + if (inOffset > scan + inReach) return allocNone; if (nullptr != outPtr) @@ -1559,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) @@ -1601,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; @@ -2136,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 ); @@ -2164,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); } @@ -5129,6 +5142,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< 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) { @@ -7046,11 +7071,10 @@ class GlobalAllocator STAMP(t5) size_t mem = mRowsInUse<(inPtr & IMMIX_BLOCK_BASE_MASK) }; @@ -7621,9 +7645,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; @@ -7791,7 +7816,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); @@ -7853,7 +7880,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; @@ -7897,9 +7924,13 @@ void MarkConservative(int *inBottom, int *inTop,hx::MarkContext *__inCtx) 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{ - sgCheckInternalOffset ? - info->GetEnclosingAllocType(pos - sizeof(int), &potentialObject, allowPrevious) : + pos < sizeof(int) ? allocNone : + (inReach || sgCheckInternalOffset) ? + info->GetEnclosingAllocType(pos - sizeof(int), &potentialObject, allowPrevious, inReach ? inReach : sgCheckInternalOffset) : info->GetAllocType(pos - sizeof(int), allowPrevious) }; #ifdef HX_WATCH @@ -7982,15 +8013,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 } @@ -8329,6 +8373,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(); } @@ -8821,6 +8870,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); @@ -8839,6 +8892,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 @@ -9647,11 +9704,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/src/hx/libs/std/Process.cpp b/src/hx/libs/std/Process.cpp index 7741dfae3..464c7a57b 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/src/hx/libs/std/Sys.cpp b/src/hx/libs/std/Sys.cpp index 392642266..be948e866 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/src/hx/thread/CountingSemaphore.apple.cpp b/src/hx/thread/CountingSemaphore.apple.cpp index 25564db0e..8a448addf 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 8cbb3353d..aa0559ade 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 2b5430f56..2598ec5a6 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 f9d9ab8e3..5389419cc 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/src/hx/thread/ThreadImpl.win32.cpp b/src/hx/thread/ThreadImpl.win32.cpp index 5ea74d6b0..d777ef6e3 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/compile_errors/check.sh b/test/compile_errors/check.sh new file mode 100644 index 000000000..921c18156 --- /dev/null +++ b/test/compile_errors/check.sh @@ -0,0 +1,77 @@ +#!/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 : the build must +# fail for that reason, not for an unrelated one such as a missing tool +expect_failure() { + 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" 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 + ( + 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" 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" + 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 000000000..04e9c83f8 --- /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 000000000..9553fac55 --- /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 000000000..766a93591 --- /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 000000000..9553fac55 --- /dev/null +++ b/test/compile_errors/tags/build.hxml @@ -0,0 +1,2 @@ +-cpp bin +-main Main diff --git a/test/regression/AtomicSafePointUnregisteredThread/Main.hx b/test/regression/AtomicSafePointUnregisteredThread/Main.hx new file mode 100644 index 000000000..bcd1866eb --- /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 000000000..b484e67e7 --- /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 000000000..f7e2b30e5 --- /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/AtomicSpinSafePoint/Main.hx b/test/regression/AtomicSpinSafePoint/Main.hx new file mode 100644 index 000000000..74db08d92 --- /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 000000000..b484e67e7 --- /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 000000000..b808c6ac2 --- /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/CppiaAdoptLayouts/Main.hx b/test/regression/CppiaAdoptLayouts/Main.hx new file mode 100644 index 000000000..aadbf49a6 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/Main.hx @@ -0,0 +1,41 @@ +import haxe.io.Path; + +// libhxcpp #464. adoptInstances moved instances whose methods were not in the +// 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 { + 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", "retyped", "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 000000000..7770c1792 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/build.hxml @@ -0,0 +1,28 @@ +-cp methods/old +--main Script +-cppia bin/methods-old.cppia +--next +-cp methods/new +--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 +--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 000000000..209c21145 --- /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 000000000..f4e8cbdc9 --- /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 000000000..5dc5469b7 --- /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 000000000..bde858046 --- /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/retyped/new/Script.hx b/test/regression/CppiaAdoptLayouts/retyped/new/Script.hx new file mode 100644 index 000000000..ec6cb5799 --- /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 000000000..bde858046 --- /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 new file mode 100644 index 000000000..1df180aa6 --- /dev/null +++ b/test/regression/CppiaAdoptLayouts/stdout.txt @@ -0,0 +1,36 @@ +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 +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 + 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 +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 + 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/CppiaArrayEngines/Main.hx b/test/regression/CppiaArrayEngines/Main.hx new file mode 100644 index 000000000..e1b4cc7a2 --- /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 000000000..15ae93a14 --- /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 000000000..d20d36bd4 --- /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 000000000..c321ee9e7 --- /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] diff --git a/test/regression/CppiaArrayWrites/Main.hx b/test/regression/CppiaArrayWrites/Main.hx new file mode 100644 index 000000000..e1b4cc7a2 --- /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 000000000..941862872 --- /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 000000000..d20d36bd4 --- /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 000000000..ba3d97ced --- /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] diff --git a/test/regression/CppiaInterfaceSlots/Main.hx b/test/regression/CppiaInterfaceSlots/Main.hx new file mode 100644 index 000000000..e1b4cc7a2 --- /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 000000000..ee0de9cde --- /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 000000000..d20d36bd4 --- /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 000000000..bb1004221 --- /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 diff --git a/test/regression/CppiaJitHelperExceptions/Main.hx b/test/regression/CppiaJitHelperExceptions/Main.hx new file mode 100644 index 000000000..e1b4cc7a2 --- /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 000000000..f3085932d --- /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 000000000..d20d36bd4 --- /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 000000000..13ffdba2d --- /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/test/regression/CppiaMalformedConstructors/stdout.txt b/test/regression/CppiaMalformedConstructors/stdout.txt index 4b4b161e4..6c1a36c4f 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 000000000..040e9da2a --- /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 000000000..662c35c33 --- /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 000000000..5bfa2fac9 --- /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 000000000..ffe5aced6 --- /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/CppiaThreadedLookups/Gen.hx b/test/regression/CppiaThreadedLookups/Gen.hx new file mode 100644 index 000000000..12af6aa93 --- /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 000000000..887b8be2e --- /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 000000000..4e3c05ca3 --- /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 000000000..c95a3dea9 --- /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 000000000..6859eeca7 --- /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/FinalizersAcrossFreeZones/Main.hx b/test/regression/FinalizersAcrossFreeZones/Main.hx index 7aa34ff26..d3ff838ce 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 000000000..f5b868cb7 --- /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 000000000..b484e67e7 --- /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 000000000..211ba2930 --- /dev/null +++ b/test/regression/GcFinalizerTakesMutex/stdout.txt @@ -0,0 +1,2 @@ +finalizers took the mutex: true +finalizers tried it: true diff --git a/test/regression/GcFreeZoneLeafNatives/Main.hx b/test/regression/GcFreeZoneLeafNatives/Main.hx new file mode 100644 index 000000000..1c3a1ad6f --- /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 000000000..b484e67e7 --- /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 000000000..056f5fab1 --- /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/GcMovedStartBits/Main.hx b/test/regression/GcMovedStartBits/Main.hx new file mode 100644 index 000000000..b33150e00 --- /dev/null +++ b/test/regression/GcMovedStartBits/Main.hx @@ -0,0 +1,156 @@ +import cpp.vm.Gc; + +class Item { + public var x:Int; + public var y:Int; + public var z:Float; + public var next:Item; + + public function new(i:Int) { + x = i; + } +} + +class Filler { + public var a:Int = 0; + public var b:Int = 0; + public var c:Int = 0; + public var d:Int = 0; + public var e:Int = 0; + public var f:Int = 0; + + public function new() {} +} + +// libhxcpp #450. A moving collection that runs out of blocks to move into +// keeps the block it was emptying, in part. That block kept the start bits of +// the objects it had moved out, whose headers say they moved. A stale word on +// the stack still holding one of those addresses then had the next 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. +// +// Old addresses are kept encoded, so the collector does not see them, and put +// on the stack only for the collections below, as stale slots of a deeper call +// would be on a real stack. +@:cppFileCode(' +#include +#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); } +// 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() +{ + 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'); + // 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()"); + // 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 000000000..d97fb6164 --- /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 000000000..ef2d0bbaf --- /dev/null +++ b/test/regression/GcMovedStartBits/stdout.txt @@ -0,0 +1,5 @@ +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 +kept items with a wrong value: 0 diff --git a/test/regression/GcPointerFieldBlockBase/Main.hx b/test/regression/GcPointerFieldBlockBase/Main.hx new file mode 100644 index 000000000..853e0d21d --- /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. +class Holder { + public var base:cpp.Pointer; + + public function new() {} +} + +@: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 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 000000000..b484e67e7 --- /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 000000000..4a4781366 --- /dev/null +++ b/test/regression/GcPointerFieldBlockBase/stdout.txt @@ -0,0 +1,2 @@ +collections finished: true +arrays kept: true diff --git a/test/regression/GcPointerFieldInterior/Main.hx b/test/regression/GcPointerFieldInterior/Main.hx new file mode 100644 index 000000000..dd7a73957 --- /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 000000000..b484e67e7 --- /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 000000000..1038c087c --- /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 diff --git a/test/regression/GcStdoutBlocked/Main.hx b/test/regression/GcStdoutBlocked/Main.hx new file mode 100644 index 000000000..01f5c79f7 --- /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 000000000..b484e67e7 --- /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 000000000..4df2d8c27 --- /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/IncrementalGcCounts/Main.hx b/test/regression/IncrementalGcCounts/Main.hx new file mode 100644 index 000000000..b4d4dbb5b --- /dev/null +++ b/test/regression/IncrementalGcCounts/Main.hx @@ -0,0 +1,79 @@ +import cpp.vm.Gc; +#if HXCPP_GC_INCREMENTAL +import hxcpp.gc.Incremental; +#end + +class Small { + public var a:Int; + + public function new(a:Int) + this.a = a; +} + +class Counted { + public var next:Counted; + + public function new(n:Counted) + next = n; +} + +// libhxcpp #453, with HXCPP_GC_INCREMENTAL, and Gc.trace in a debug build. +// It prints the same without. +// - MEM_INFO_LIVE is the bytes of the objects that survived the last full +// reclaim. A finished incremental cycle that was not one counted whole rows +// and reported those as live: seven times the real figure here. +// - Gc.trace counts what a collection marks. With a cycle part done, the +// collection finished it, and what its earlier slices marked went uncounted. +class Main { + static function liveBytes() { + #if HXCPP_GC_INCREMENTAL + Gc.enable(false); + var keep = []; + for (i in 0...800000) { + var s = new Small(i); + if (i % 16 == 0) + keep.push(s); + } + Gc.run(true); + var afterFull = Gc.memInfo64(4); + // Garbage between the survivors' rows, then one budgeted cycle to its end + for (i in 0...200000) + new Small(i); + while (Incremental.step(2.0)) {} + var afterCycle = Gc.memInfo64(4); + Sys.println("live bytes after an incremental cycle as after the full collection: " + (afterCycle == afterFull)); + Sys.println("kept " + keep.length); + Gc.enable(true); + #else + Sys.println("live bytes after an incremental cycle as after the full collection: true"); + Sys.println("kept 50000"); + #end + } + + static function traceCount() { + var keep = []; + for (i in 0...20000) { + var head:Counted = null; + for (j in 0...10) + head = new Counted(head); + keep.push(head); + } + // Gc.trace counts in debug builds only + #if (HXCPP_GC_INCREMENTAL && debug) + Gc.enable(false); + Incremental.step(0.05); + var during = Incremental.isActive() ? Gc.trace(Counted, false) : 200000; + Gc.enable(true); + #elseif debug + var during = Gc.trace(Counted, false); + #else + var during = keep.length * 10; + #end + Sys.println("Gc.trace with a cycle part done: " + during + " of " + keep.length * 10); + } + + static function main() { + liveBytes(); + traceCount(); + } +} diff --git a/test/regression/IncrementalGcCounts/build.hxml b/test/regression/IncrementalGcCounts/build.hxml new file mode 100644 index 000000000..5f01ed3da --- /dev/null +++ b/test/regression/IncrementalGcCounts/build.hxml @@ -0,0 +1,4 @@ +-m Main +--cpp bin +-debug +-D DEBUGSUFFIX= diff --git a/test/regression/IncrementalGcCounts/stdout.txt b/test/regression/IncrementalGcCounts/stdout.txt new file mode 100644 index 000000000..b614c3b71 --- /dev/null +++ b/test/regression/IncrementalGcCounts/stdout.txt @@ -0,0 +1,3 @@ +live bytes after an incremental cycle as after the full collection: true +kept 50000 +Gc.trace with a cycle part done: 200000 of 200000 diff --git a/test/regression/ProcessStdinCloseCollects/Main.hx b/test/regression/ProcessStdinCloseCollects/Main.hx new file mode 100644 index 000000000..73a754c4c --- /dev/null +++ b/test/regression/ProcessStdinCloseCollects/Main.hx @@ -0,0 +1,52 @@ +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; + } + // 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(() -> { + 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 000000000..b484e67e7 --- /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 000000000..cf983ae06 --- /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/Run.hx b/test/regression/Run.hx index 649c2f99e..e4359febb 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) { diff --git a/test/regression/ThreadWaitTimeouts/Main.hx b/test/regression/ThreadWaitTimeouts/Main.hx index 41f2a6fee..417ff0535 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 75619baa8..f7ba2c080 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 diff --git a/test/regression/TlsHighSlot/Main.hx b/test/regression/TlsHighSlot/Main.hx new file mode 100644 index 000000000..5ece52d79 --- /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 000000000..b484e67e7 --- /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 000000000..dc0535d1b --- /dev/null +++ b/test/regression/TlsHighSlot/stdout.txt @@ -0,0 +1 @@ +made 100000 strings, and 100000 on another thread, and collected diff --git a/test/regression/WindowsThreadNameImports/Main.hx b/test/regression/WindowsThreadNameImports/Main.hx new file mode 100644 index 000000000..531742dda --- /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 000000000..b484e67e7 --- /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 000000000..710090c05 --- /dev/null +++ b/test/regression/WindowsThreadNameImports/stdout.txt @@ -0,0 +1,2 @@ +imports GetThreadDescription: false +imports SetThreadDescription: false diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 6342a8d49..a35fbe3ce 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -6,6 +6,8 @@ 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 CffiNekoValueTags: runs neko, which loads an ndll the test builds @@ -14,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 @@ -22,10 +25,12 @@ 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 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) @@ -33,6 +38,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 @@ -45,6 +51,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 +91,7 @@ ProcessExitCodeTwice: processes ProcessPosixStartError: processes ProcessReapAfterClose: processes ProcessSigpipeHandler: processes +ProcessStdinCloseCollects: processes and threads ProcessWaitError: processes PthreadFastTls: threads RegexpConcurrentCollection: threads diff --git a/toolchain/haxe-target.xml b/toolchain/haxe-target.xml index da12bc909..4a17607e1 100644 --- a/toolchain/haxe-target.xml +++ b/toolchain/haxe-target.xml @@ -83,6 +83,16 @@ + + + + + + + + + +
@@ -189,6 +199,13 @@ + + + + + + + diff --git a/toolchain/msvc-toolchain.xml b/toolchain/msvc-toolchain.xml index 23b839431..05ef6c61c 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 --> - - diff --git a/tools/check-depends.py b/tools/check-depends.py new file mode 100644 index 000000000..48c834931 --- /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', 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; @@ -308,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); } @@ -1214,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/CompileCache.hx b/tools/hxcpp/CompileCache.hx index a1041a886..9392f3e1b 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 diff --git a/tools/hxcpp/Compiler.hx b/tools/hxcpp/Compiler.hx index fa1689d18..691ea224b 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) @@ -471,9 +473,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/FileGroup.hx b/tools/hxcpp/FileGroup.hx index 2d0a14aae..27d33b003 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); } diff --git a/tools/hxcpp/ProcessManager.hx b/tools/hxcpp/ProcessManager.hx index 8171e040c..62004f590 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; } diff --git a/tools/hxcpp/Setup.hx b/tools/hxcpp/Setup.hx index 759fa1a7b..c073cf8e3 100644 --- a/tools/hxcpp/Setup.hx +++ b/tools/hxcpp/Setup.hx @@ -490,18 +490,34 @@ 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; }; diff --git a/tools/hxcpp/ThreadPool.hx b/tools/hxcpp/ThreadPool.hx index 10e8c6247..33da2f616 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 da8e5f466..9c402c2ca 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); }