From efdf7b459f2f77db167a8690f8051eb4139921b6 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 02:39:26 -0500 Subject: [PATCH] Keep a thread the platform cannot detach instead of terminating Where pthread_detach fails, as on Switch with devkitA64, whose newlib returns ENOSYS because libnx installs no __syscall_thread_detach hook, std::thread::detach throws std::system_error. Every place the runtime detached a thread then destroyed a std::thread that was still joinable, which is std::terminate: ThreadImpl's Native and its finaliser, the collector's workers and release thread, the late file closer, the process reaper, and the profiler and telemetry threads. The catch(...) around three of them never ran, as the unwind destroyed the thread first. They all detach through hx::DetachThread, in src/hx/thread/Detach.hpp. When detach throws, it moves the std::thread to the heap and never destroys it, so the thread runs to its end as it would detached, and says once on stderr that finished threads will not be reclaimed. That is left to the platform, which alone can free what it holds for them. ThreadDetachFailure replaces pthread_detach on glibc with one that returns ENOSYS, creates threads that allocate and collect, and checks that they all ran and that the detach was refused. Tests: ThreadDetachFailure Fixes openfl/libhxcpp#502 --- Changes.md | 1 + src/hx/Profiler.cpp | 3 +- src/hx/Telemetry.cpp | 3 +- src/hx/gc/Immix.cpp | 5 +- src/hx/libs/std/File.cpp | 4 +- src/hx/libs/std/Process.cpp | 4 +- src/hx/thread/Detach.hpp | 32 ++++++++++ src/hx/thread/ThreadImpl.cpp | 5 +- test/regression/ThreadDetachFailure/Main.hx | 63 +++++++++++++++++++ .../regression/ThreadDetachFailure/build.hxml | 2 + .../regression/ThreadDetachFailure/stdout.txt | 2 + test/regression/emscripten-skip.txt | 1 + toolchain/haxe-target-threads.xml | 1 + toolchain/haxe-target.xml | 1 + 14 files changed, 119 insertions(+), 8 deletions(-) create mode 100644 src/hx/thread/Detach.hpp create mode 100644 test/regression/ThreadDetachFailure/Main.hx create mode 100644 test/regression/ThreadDetachFailure/build.hxml create mode 100644 test/regression/ThreadDetachFailure/stdout.txt diff --git a/Changes.md b/Changes.md index e1888b737..debab8537 100644 --- a/Changes.md +++ b/Changes.md @@ -14,6 +14,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed sys.ssl.Certificate.loadFile and loadPath reporting certificates that did not parse as an unrelated mbedTLS error: mbedTLS counts them, and the count was read as an error code, so one threw "ERROR - Generic error" and two a BIGNUM file error. They throw "Could not parse 2 certificates in " now, and for a directory "certificates or files", as mbedTLS also counts a file that holds none (HaxeFoundation/hxcpp@45adede6) * Fixed cppia's interpreter running a var statement with no declarations, which a malformed file can hold, from the first element of its empty list: undefined behaviour, on which a standard library that checks indexing stops the program (HaxeFoundation/hxcpp@a8a5724f) * A cppia script reads and writes a host class's static object fields, such as a singleton, a static Array or a static function, directly again below API level 500, which includes Haxe 5.0.0-preview.1, instead of looking each up by name: a loop that reads one host static Array and stores another runs 1.8 times as fast interpreted and 12 times as fast under the JIT. Host statics of other types and object fields already were direct; API level 500 keeps the lookup, which a typed function needs (HaxeFoundation/hxcpp#1365) +* Fixed the process ending with std::terminate where the platform cannot detach a thread, as on Switch with devkitA64, whose pthread_detach returns ENOSYS: std::thread::detach threw and the std::thread, still joinable, was destroyed, at the first Thread.create or when the collector, the file closer, the process reaper, the profiler or telemetry started a thread. The thread is kept and runs to its end as it would detached, and the runtime says once on stderr that finished threads will not be reclaimed, which only the platform can do (libhxcpp #502) libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/Profiler.cpp b/src/hx/Profiler.cpp index 09a2047f0..c1031c93f 100644 --- a/src/hx/Profiler.cpp +++ b/src/hx/Profiler.cpp @@ -5,6 +5,7 @@ #include #include #include +#include "thread/Detach.hpp" #ifdef HX_WINRT @@ -51,7 +52,7 @@ class Profiler if (gThreadRefCount == 1) { std::thread thread(ProfileMainLoop); - thread.detach(); + hx::DetachThread(thread); } } diff --git a/src/hx/Telemetry.cpp b/src/hx/Telemetry.cpp index 6ed3104ff..d69844a6b 100644 --- a/src/hx/Telemetry.cpp +++ b/src/hx/Telemetry.cpp @@ -10,6 +10,7 @@ #include #include #include +#include "thread/Detach.hpp" namespace hx { @@ -70,7 +71,7 @@ class Telemetry if (gThreadRefCount == 1) { std::thread thread(ProfileMainLoop); - thread.detach(); + hx::DetachThread(thread); } } diff --git a/src/hx/gc/Immix.cpp b/src/hx/gc/Immix.cpp index 8e0286bdc..429e4fcd2 100644 --- a/src/hx/gc/Immix.cpp +++ b/src/hx/gc/Immix.cpp @@ -6,6 +6,7 @@ #include #include "../Hash.h" #include "../FastMutex.h" +#include "../thread/Detach.hpp" #include "GcRegCapture.h" #include #include @@ -4316,7 +4317,7 @@ class GlobalAllocator try { std::thread thread(SReleaseLoop, this); - thread.detach(); + hx::DetachThread(thread); mReleaseStarted = true; } catch(...) @@ -5739,7 +5740,7 @@ class GlobalAllocator std::thread thread(SThreadLoop, info); - thread.detach(); + hx::DetachThread(thread); #endif } diff --git a/src/hx/libs/std/File.cpp b/src/hx/libs/std/File.cpp index d877a732c..d3b639a24 100644 --- a/src/hx/libs/std/File.cpp +++ b/src/hx/libs/std/File.cpp @@ -7,6 +7,7 @@ #include #include #include +#include "../../thread/Detach.hpp" #endif #include @@ -109,7 +110,8 @@ struct LateCloser { try { - std::thread([this]() { run(); }).detach(); + std::thread thread([this]() { run(); }); + hx::DetachThread(thread); } catch(...) { diff --git a/src/hx/libs/std/Process.cpp b/src/hx/libs/std/Process.cpp index 464c7a57b..f8a3638c7 100644 --- a/src/hx/libs/std/Process.cpp +++ b/src/hx/libs/std/Process.cpp @@ -37,6 +37,7 @@ #if !defined(HX_WINRT) && !defined(EPPC) && !defined(NEKO_WINDOWS) && !defined(__EMSCRIPTEN__) && !defined(HXCPP_SINGLE_THREADED_APP) #define HX_PROCESS_REAPER #include +#include "../../thread/Detach.hpp" #include #include #endif @@ -174,7 +175,8 @@ namespace { try { - std::thread(reaperLoop).detach(); + std::thread thread(reaperLoop); + hx::DetachThread(thread); sReaper.running = true; } catch(...) diff --git a/src/hx/thread/Detach.hpp b/src/hx/thread/Detach.hpp new file mode 100644 index 000000000..f9d264a63 --- /dev/null +++ b/src/hx/thread/Detach.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace hx +{ + // Detaches a std::thread the runtime will never join. Where the platform + // cannot detach, as devkitA64's newlib on Switch, whose pthread_detach + // returns ENOSYS, std::thread::detach throws, and the joinable std::thread + // then ended the process with std::terminate when it was destroyed, even + // inside a catch. The thread is kept instead: it runs to its end as it + // would detached, and what the platform holds for it is not reclaimed. + inline void DetachThread(std::thread &ioThread) + { + try + { + ioThread.detach(); + } + catch (const std::exception &e) + { + static std::atomic sReported(false); + if (!sReported.exchange(true)) + fprintf(stderr, "Could not detach a thread (%s): finished threads will not be reclaimed\n", e.what()); + // Never destroyed, as destroying a joinable std::thread terminates + new std::thread(std::move(ioThread)); + } + } +} diff --git a/src/hx/thread/ThreadImpl.cpp b/src/hx/thread/ThreadImpl.cpp index c9d8db617..a9de9f5dd 100644 --- a/src/hx/thread/ThreadImpl.cpp +++ b/src/hx/thread/ThreadImpl.cpp @@ -6,6 +6,7 @@ #include #include #include "ThreadImpl.hpp" +#include "Detach.hpp" namespace { @@ -206,7 +207,7 @@ hx::thread::ThreadImpl_obj::Native::Native(Thread_obj::CreateFunction _job, Thre // This does feel like a bit of a bodge and something which will actually need to be addressed to add name setting on Linux. #ifndef HX_WINDOWS - thread.detach(); + hx::DetachThread(thread); #endif } @@ -269,7 +270,7 @@ void hx::thread::ThreadImpl_obj::finalise(hx::Object* obj) if (native->thread.joinable()) { - native->thread.detach(); + hx::DetachThread(native->thread); } } diff --git a/test/regression/ThreadDetachFailure/Main.hx b/test/regression/ThreadDetachFailure/Main.hx new file mode 100644 index 000000000..ef3a6b211 --- /dev/null +++ b/test/regression/ThreadDetachFailure/Main.hx @@ -0,0 +1,63 @@ +import sys.thread.Lock; +import sys.thread.Thread; + +// Threads where the platform cannot detach one. devkitA64's newlib on Switch +// has no pthread_detach hook, so it returns ENOSYS, std::thread::detach +// throws, and the joinable std::thread being destroyed ended the process +// with std::terminate at the first Thread.create, or when the collector +// started a worker. On glibc this program replaces pthread_detach with one +// that does the same. Elsewhere it cannot, and prints what is expected. +@:cppFileCode(' +#if defined(__linux__) +#include +#include +#endif +#include + +#if defined(__linux__) && defined(__GLIBC__) +static std::atomic refusedDetaches(0); + +extern "C" __attribute__((visibility("default"))) int pthread_detach(pthread_t) __THROW +{ + refusedDetaches++; + return ENOSYS; +} + +static bool detachRefused() { return refusedDetaches > 0; } +#else +static bool detachRefused() { return true; } +#endif +') +class Main { + static function main() { + final count = 32; + final done = new Lock(); + var ran = 0; + final mutex = new sys.thread.Mutex(); + for (i in 0...count) { + Thread.create(() -> { + // Allocates enough for collections to run while threads come and go + var keep = []; + for (j in 0...2000) { + keep.push([j, i]); + } + cpp.vm.Gc.run(false); + mutex.acquire(); + ran++; + mutex.release(); + done.release(); + }); + } + var all = true; + for (i in 0...count) { + if (!done.wait(30)) { + all = false; + break; + } + } + cpp.vm.Gc.run(true); + final refused:Bool = untyped __cpp__("detachRefused()"); + Sys.println("threads created after a refused detach run to their end: " + (all && ran == count)); + Sys.println("the platform refused to detach them: " + refused); + } +} diff --git a/test/regression/ThreadDetachFailure/build.hxml b/test/regression/ThreadDetachFailure/build.hxml new file mode 100644 index 000000000..b484e67e7 --- /dev/null +++ b/test/regression/ThreadDetachFailure/build.hxml @@ -0,0 +1,2 @@ +-m Main +--cpp bin diff --git a/test/regression/ThreadDetachFailure/stdout.txt b/test/regression/ThreadDetachFailure/stdout.txt new file mode 100644 index 000000000..8d1ea0346 --- /dev/null +++ b/test/regression/ThreadDetachFailure/stdout.txt @@ -0,0 +1,2 @@ +threads created after a refused detach run to their end: true +the platform refused to detach them: true diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 690431f24..37843dd1a 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -122,6 +122,7 @@ SslNativeMemoryPressure: threads (std::thread, which needs a pthreads build) SslPeerCertificateLifetime: sockets SslSniLifetime: sockets SslSniName: sockets +ThreadDetachFailure: threads ThreadEndsAtExit: threads ThreadEndsAtExitDebugger: threads ThreadEndsWhileCollecting: threads diff --git a/toolchain/haxe-target-threads.xml b/toolchain/haxe-target-threads.xml index f8763716a..0753cab32 100644 --- a/toolchain/haxe-target-threads.xml +++ b/toolchain/haxe-target-threads.xml @@ -1,5 +1,6 @@  + diff --git a/toolchain/haxe-target.xml b/toolchain/haxe-target.xml index e8d0310a4..9d04f1038 100644 --- a/toolchain/haxe-target.xml +++ b/toolchain/haxe-target.xml @@ -208,6 +208,7 @@ +