Skip to content

Commit efdf7b4

Browse files
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 #502
1 parent 35cede7 commit efdf7b4

14 files changed

Lines changed: 119 additions & 8 deletions

File tree

‎Changes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ libhxcpp 6.0.3 (unreleased)
1414
* 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 <file>" now, and for a directory "certificates or files", as mbedTLS also counts a file that holds none (HaxeFoundation/hxcpp@45adede6)
1515
* 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)
1616
* 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)
17+
* 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)
1718

1819
libhxcpp 6.0.2
1920
------------------------------------------------------------

‎src/hx/Profiler.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <mutex>
66
#include <thread>
77
#include <chrono>
8+
#include "thread/Detach.hpp"
89

910

1011
#ifdef HX_WINRT
@@ -51,7 +52,7 @@ class Profiler
5152

5253
if (gThreadRefCount == 1) {
5354
std::thread thread(ProfileMainLoop);
54-
thread.detach();
55+
hx::DetachThread(thread);
5556
}
5657
}
5758

‎src/hx/Telemetry.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <mutex>
1111
#include <thread>
1212
#include <chrono>
13+
#include "thread/Detach.hpp"
1314

1415
namespace hx
1516
{
@@ -70,7 +71,7 @@ class Telemetry
7071
if (gThreadRefCount == 1) {
7172
std::thread thread(ProfileMainLoop);
7273

73-
thread.detach();
74+
hx::DetachThread(thread);
7475
}
7576
}
7677

‎src/hx/gc/Immix.cpp‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <hx/thread/Thread.hpp>
77
#include "../Hash.h"
88
#include "../FastMutex.h"
9+
#include "../thread/Detach.hpp"
910
#include "GcRegCapture.h"
1011
#include <unordered_set>
1112
#include <unordered_map>
@@ -4316,7 +4317,7 @@ class GlobalAllocator
43164317
try
43174318
{
43184319
std::thread thread(SReleaseLoop, this);
4319-
thread.detach();
4320+
hx::DetachThread(thread);
43204321
mReleaseStarted = true;
43214322
}
43224323
catch(...)
@@ -5739,7 +5740,7 @@ class GlobalAllocator
57395740

57405741
std::thread thread(SThreadLoop, info);
57415742

5742-
thread.detach();
5743+
hx::DetachThread(thread);
57435744
#endif
57445745
}
57455746

‎src/hx/libs/std/File.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <thread>
88
#include <mutex>
99
#include <condition_variable>
10+
#include "../../thread/Detach.hpp"
1011
#endif
1112

1213
#include <hx/OS.h>
@@ -109,7 +110,8 @@ struct LateCloser
109110
{
110111
try
111112
{
112-
std::thread([this]() { run(); }).detach();
113+
std::thread thread([this]() { run(); });
114+
hx::DetachThread(thread);
113115
}
114116
catch(...)
115117
{

‎src/hx/libs/std/Process.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
#if !defined(HX_WINRT) && !defined(EPPC) && !defined(NEKO_WINDOWS) && !defined(__EMSCRIPTEN__) && !defined(HXCPP_SINGLE_THREADED_APP)
3838
#define HX_PROCESS_REAPER
3939
#include <thread>
40+
#include "../../thread/Detach.hpp"
4041
#include <mutex>
4142
#include <chrono>
4243
#endif
@@ -174,7 +175,8 @@ namespace
174175
{
175176
try
176177
{
177-
std::thread(reaperLoop).detach();
178+
std::thread thread(reaperLoop);
179+
hx::DetachThread(thread);
178180
sReaper.running = true;
179181
}
180182
catch(...)

‎src/hx/thread/Detach.hpp‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#pragma once
2+
3+
#include <thread>
4+
#include <atomic>
5+
#include <exception>
6+
#include <utility>
7+
#include <stdio.h>
8+
9+
namespace hx
10+
{
11+
// Detaches a std::thread the runtime will never join. Where the platform
12+
// cannot detach, as devkitA64's newlib on Switch, whose pthread_detach
13+
// returns ENOSYS, std::thread::detach throws, and the joinable std::thread
14+
// then ended the process with std::terminate when it was destroyed, even
15+
// inside a catch. The thread is kept instead: it runs to its end as it
16+
// would detached, and what the platform holds for it is not reclaimed.
17+
inline void DetachThread(std::thread &ioThread)
18+
{
19+
try
20+
{
21+
ioThread.detach();
22+
}
23+
catch (const std::exception &e)
24+
{
25+
static std::atomic<bool> sReported(false);
26+
if (!sReported.exchange(true))
27+
fprintf(stderr, "Could not detach a thread (%s): finished threads will not be reclaimed\n", e.what());
28+
// Never destroyed, as destroying a joinable std::thread terminates
29+
new std::thread(std::move(ioThread));
30+
}
31+
}
32+
}

‎src/hx/thread/ThreadImpl.cpp‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <system_error>
77
#include <hx/thread/CountingSemaphore.hpp>
88
#include "ThreadImpl.hpp"
9+
#include "Detach.hpp"
910

1011
namespace
1112
{
@@ -206,7 +207,7 @@ hx::thread::ThreadImpl_obj::Native::Native(Thread_obj::CreateFunction _job, Thre
206207
// This does feel like a bit of a bodge and something which will actually need to be addressed to add name setting on Linux.
207208

208209
#ifndef HX_WINDOWS
209-
thread.detach();
210+
hx::DetachThread(thread);
210211
#endif
211212
}
212213

@@ -269,7 +270,7 @@ void hx::thread::ThreadImpl_obj::finalise(hx::Object* obj)
269270

270271
if (native->thread.joinable())
271272
{
272-
native->thread.detach();
273+
hx::DetachThread(native->thread);
273274
}
274275
}
275276

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import sys.thread.Lock;
2+
import sys.thread.Thread;
3+
4+
// Threads where the platform cannot detach one. devkitA64's newlib on Switch
5+
// has no pthread_detach hook, so it returns ENOSYS, std::thread::detach
6+
// throws, and the joinable std::thread being destroyed ended the process
7+
// with std::terminate at the first Thread.create, or when the collector
8+
// started a worker. On glibc this program replaces pthread_detach with one
9+
// that does the same. Elsewhere it cannot, and prints what is expected.
10+
@:cppFileCode('
11+
#if defined(__linux__)
12+
#include <pthread.h>
13+
#include <errno.h>
14+
#endif
15+
#include <atomic>
16+
17+
#if defined(__linux__) && defined(__GLIBC__)
18+
static std::atomic<int> refusedDetaches(0);
19+
20+
extern "C" __attribute__((visibility("default"))) int pthread_detach(pthread_t) __THROW
21+
{
22+
refusedDetaches++;
23+
return ENOSYS;
24+
}
25+
26+
static bool detachRefused() { return refusedDetaches > 0; }
27+
#else
28+
static bool detachRefused() { return true; }
29+
#endif
30+
')
31+
class Main {
32+
static function main() {
33+
final count = 32;
34+
final done = new Lock();
35+
var ran = 0;
36+
final mutex = new sys.thread.Mutex();
37+
for (i in 0...count) {
38+
Thread.create(() -> {
39+
// Allocates enough for collections to run while threads come and go
40+
var keep = [];
41+
for (j in 0...2000) {
42+
keep.push([j, i]);
43+
}
44+
cpp.vm.Gc.run(false);
45+
mutex.acquire();
46+
ran++;
47+
mutex.release();
48+
done.release();
49+
});
50+
}
51+
var all = true;
52+
for (i in 0...count) {
53+
if (!done.wait(30)) {
54+
all = false;
55+
break;
56+
}
57+
}
58+
cpp.vm.Gc.run(true);
59+
final refused:Bool = untyped __cpp__("detachRefused()");
60+
Sys.println("threads created after a refused detach run to their end: " + (all && ran == count));
61+
Sys.println("the platform refused to detach them: " + refused);
62+
}
63+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-m Main
2+
--cpp bin

0 commit comments

Comments
 (0)