Skip to content

Commit 2751477

Browse files
antonismeta-codesync[bot]
authored andcommitted
Fix sampling profiler race when registered thread exits (#1995)
Summary: Fix a crash in the sampling profiler where `pthread_kill` is invoked on a thread that has exited but whose corresponding `SamplingProfiler` is still registered. On Android bionic this aborts the process with `invalid pthread_t 0x... passed to pthread_kill`. On other POSIX platforms `pthread_kill` either signals whichever thread now has that ID or delivers nothing. In the second case the sampler thread waits forever for the signal handler while holding `profilerLock_`, which hangs `SamplingProfiler::disable()` and the next GC of every profiled runtime. Root cause: thread termination was never synchronized with the sampling path. If a JS thread exited while a host held the Runtime alive, the sampler would still attempt to sample it. Fix: register each profiler with a thread-local `ThreadDeathGuard` backed by `pthread_key_create`. Its destructor, which runs before the `pthread_t` is reaped, invalidates the registered thread under the existing `runtimeDataLock_`. A `shared_ptr`-based `ProfilerHandle` keeps the synchronization state alive across either-end destruction, so there is no UAF if the profiler is destroyed on a different thread than the one that registered it. The sampler now skips any profiler whose registered thread has exited, and also returns cleanly on a non-fatal `ESRCH` from `pthread_kill` on platforms where that window is observable. Related: #1853 and getsentry/sentry-react-native#5441. Pull Request resolved: #1995 Test Plan: - New unit tests `SamplingProfilerTest.SamplingAfterRegisteredThreadExitDoesNotCrash` and `SamplingProfilerTest.SamplingSkipsExitedThreadButSamplesOthers` reproduce the scenario deterministically on all POSIX platforms. The first joins the worker thread that last registered the profiler, samples for 50 ms, and expects no samples. The second expects a profiler on a live thread to keep collecting samples while the exited thread's profiler is skipped. - Existing `SamplingProfilerTest` suite continues to pass. - Local build and test run on macOS arm64 (Xcode 16.4, ninja) against `static_h`, before `SamplingSkipsExitedThreadButSamplesOthers` was added: ``` $ ninja -C build HermesVMRuntimeTests [484/484] Linking CXX executable unittests/VMRuntime/HermesVMRuntimeTests $ ./build/unittests/VMRuntime/HermesVMRuntimeTests --gtest_filter='SamplingProfilerTest.*' [==========] Running 4 tests from 1 test case. [----------] 4 tests from SamplingProfilerTest [ RUN ] SamplingProfilerTest.Invariants [ OK ] SamplingProfilerTest.Invariants (96 ms) [ RUN ] SamplingProfilerTest.RegisterDifferentThread [ OK ] SamplingProfilerTest.RegisterDifferentThread (29 ms) [ RUN ] SamplingProfilerTest.RegisterIdenticalThread [ OK ] SamplingProfilerTest.RegisterIdenticalThread (30 ms) [ RUN ] SamplingProfilerTest.SamplingAfterRegisteredThreadExitDoesNotCrash [ OK ] SamplingProfilerTest.SamplingAfterRegisteredThreadExitDoesNotCrash (85 ms) [==========] 4 tests from 1 test case ran. (240 ms total) [ PASSED ] 4 tests. $ ./build/unittests/VMRuntime/HermesVMRuntimeTests [==========] 351 tests from 79 test cases ran. [ PASSED ] 351 tests. ``` - Re-run on this diff (macOS arm64, CMake ASan Debug build with `-O1`): `SamplingProfilerTest.*` runs 5 tests, all passing. Without the fix, both new tests fail because the exited thread's profiler collects samples. The full `HermesVMRuntimeTests` suite passes (405 tests). Reviewed By: avp Differential Revision: D120366165 Pulled By: lavenzg fbshipit-source-id: 09c7af450055dfda1c05d3f4e28c8f05620a603c
1 parent c319a1a commit 2751477

5 files changed

Lines changed: 368 additions & 24 deletions

File tree

‎lib/VM/Profiler/SamplingProfilerPosix.cpp‎

Lines changed: 180 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#if defined(HERMESVM_SAMPLING_PROFILER_POSIX)
1111

12+
#include "hermes/Support/ErrorHandling.h"
1213
#include "hermes/Support/Semaphore.h"
1314
#include "hermes/VM/Callable.h"
1415
#include "hermes/VM/HostModel.h"
@@ -24,12 +25,21 @@
2425
#include <fcntl.h>
2526
#include <pthread.h>
2627
#include <unistd.h>
28+
#include <algorithm>
2729
#include <cassert>
2830
#include <chrono>
2931
#include <cmath>
3032
#include <csignal>
33+
#include <memory>
34+
#include <mutex>
3135
#include <random>
3236
#include <thread>
37+
#include <vector>
38+
39+
#if !defined(__APPLE__)
40+
/// Optional LSan hook for builds that link it without ASan instrumentation.
41+
extern "C" void __lsan_ignore_object(const void *) LLVM_ATTRIBUTE_WEAK;
42+
#endif
3343

3444
namespace hermes {
3545
namespace vm {
@@ -39,14 +49,32 @@ namespace {
3949
/// Name of the semaphore.
4050
constexpr char kSamplingDoneSemaphoreName[] = "/samplingDoneSem";
4151

52+
struct SamplingProfilerPosix;
53+
54+
/// Shared state between a SamplingProfilerPosix and any per-thread guards
55+
/// that reference it. Outlives whichever of the two is destroyed first, so
56+
/// thread-death handlers can safely observe "profiler is gone" without a
57+
/// use-after-free.
58+
struct ProfilerHandle {
59+
std::mutex mu;
60+
/// Back-pointer to the owning profiler. Cleared by the profiler's
61+
/// destructor, at which point thread-death handlers skip this entry.
62+
SamplingProfilerPosix *profiler{nullptr};
63+
};
64+
4265
struct SamplingProfilerPosix : SamplingProfiler {
4366
SamplingProfilerPosix(Runtime &rt);
4467
~SamplingProfilerPosix() override;
4568

46-
/// Thread that this profiler instance represents. This can be updated as the
47-
/// runtime is invoked on different threads. Must only be accessed while
48-
/// holding the runtimeDataLock_.
69+
/// Thread that this profiler instance represents. A value of 0 means the
70+
/// registered thread has exited or no thread is currently registered.
71+
/// Must only be accessed while holding the runtimeDataLock_.
4972
pthread_t currentThread_;
73+
74+
/// Shared state with per-thread death guards referencing this profiler.
75+
/// Set once at construction, never reassigned. The underlying object
76+
/// outlives this profiler if any thread guard still references it.
77+
std::shared_ptr<ProfilerHandle> handle_;
5078
};
5179

5280
struct SamplerPosix : Sampler {
@@ -78,10 +106,101 @@ struct SamplerPosix : Sampler {
78106
/// Signal handler to walk the stack frames.
79107
static void profilingSignalHandler(int signo);
80108
};
109+
110+
/// Per-thread set of profiler handles registered to this thread. On thread
111+
/// exit, destroyThreadDeathGuard iterates the handles and invalidates each
112+
/// profiler's registered thread identity (if it still matches) before the
113+
/// pthread_t becomes invalid and bionic's pthread_kill would abort.
114+
struct ThreadDeathGuard {
115+
std::vector<std::shared_ptr<ProfilerHandle>> handles;
116+
};
117+
118+
/// Pthread key holding the thread-local ThreadDeathGuard. Initialized
119+
/// lazily via std::call_once; never deleted (process-lifetime, matching
120+
/// the SamplerPosix singleton).
121+
pthread_key_t g_threadDeathGuardKey;
122+
std::once_flag g_threadDeathGuardKeyInit;
123+
124+
void destroyThreadDeathGuard(void *ptr) {
125+
std::unique_ptr<ThreadDeathGuard> guard{static_cast<ThreadDeathGuard *>(ptr)};
126+
// For each handle, take handle->mu first (serializes with profiler
127+
// destruction), then invoke the Sampler-internal hook which takes
128+
// runtimeDataLock_. Lock order handle->mu -> runtimeDataLock_ does not
129+
// overlap with the sampler path (profilerLock_ -> runtimeDataLock_), so
130+
// there is no deadlock risk.
131+
for (auto &h : guard->handles) {
132+
std::lock_guard<std::mutex> lock(h->mu);
133+
if (h->profiler) {
134+
Sampler::onRegisteredThreadExit(h->profiler);
135+
}
136+
}
137+
}
138+
139+
void ensureThreadDeathGuardKey() {
140+
std::call_once(g_threadDeathGuardKeyInit, [] {
141+
int ret =
142+
pthread_key_create(&g_threadDeathGuardKey, destroyThreadDeathGuard);
143+
if (ret != 0) {
144+
hermes_fatal("pthread_key_create failed for sampling profiler");
145+
}
146+
});
147+
}
148+
149+
/// Attach \p handle to the calling thread's death guard. Must be called on
150+
/// the thread that will host the profiler.
151+
void attachHandleToCurrentThread(std::shared_ptr<ProfilerHandle> handle) {
152+
ensureThreadDeathGuardKey();
153+
auto *guard = static_cast<ThreadDeathGuard *>(
154+
pthread_getspecific(g_threadDeathGuardKey));
155+
if (!guard) {
156+
guard = new ThreadDeathGuard();
157+
if (pthread_setspecific(g_threadDeathGuardKey, guard) != 0) {
158+
delete guard;
159+
hermes_fatal("pthread_setspecific failed for sampling profiler");
160+
}
161+
#if !defined(__APPLE__)
162+
// The main thread's pthread TLS destructor does not run on normal exit.
163+
if (__lsan_ignore_object) {
164+
__lsan_ignore_object(guard);
165+
}
166+
#endif
167+
}
168+
// Before adding the new handle, drop entries this thread's death guard no
169+
// longer needs to keep around:
170+
// - handles whose profiler has been destroyed (its back-pointer was
171+
// cleared under handle->mu by ~SamplingProfilerPosix), and
172+
// - an existing entry for the same profiler, which happens when a profiler
173+
// is moved back onto this thread via setRuntimeThread().
174+
// Without this, a thread that hosts many profilers over its lifetime -- or
175+
// a single profiler that repeatedly moves onto it -- would accumulate
176+
// entries until the thread exits.
177+
auto &handles = guard->handles;
178+
ProfilerHandle *incoming = handle.get();
179+
handles.erase(
180+
std::remove_if(
181+
handles.begin(),
182+
handles.end(),
183+
[incoming](const std::shared_ptr<ProfilerHandle> &h) {
184+
if (h.get() == incoming) {
185+
return true;
186+
}
187+
std::lock_guard<std::mutex> lock(h->mu);
188+
return h->profiler == nullptr;
189+
}),
190+
handles.end());
191+
handles.push_back(std::move(handle));
192+
}
81193
} // namespace
82194

83195
SamplingProfilerPosix::SamplingProfilerPosix(Runtime &rt)
84-
: SamplingProfiler(rt), currentThread_{pthread_self()} {
196+
: SamplingProfiler(rt),
197+
currentThread_{pthread_self()},
198+
handle_{std::make_shared<ProfilerHandle>()} {
199+
// Set the back-pointer before publishing to any other thread. No lock
200+
// needed: this profiler is not reachable from any other thread yet.
201+
handle_->profiler = this;
202+
attachHandleToCurrentThread(handle_);
203+
85204
// Note that we cannot register this in the base class constructor, because
86205
// all fields must be initialized before we register with the profiling
87206
// thread.
@@ -92,6 +211,12 @@ SamplingProfilerPosix::~SamplingProfilerPosix() {
92211
// TODO(T125910634): re-introduce the requirement for destroying the sampling
93212
// profiler on the same thread in which it was created.
94213
Sampler::get()->unregisterRuntime(this);
214+
// After unregisterRuntime returns, profilerLock_ has been taken and
215+
// released, which guarantees no sampler iteration is in-flight for this
216+
// profiler. Clear the back-pointer so any thread-death handler still
217+
// holding a shared_ptr to handle_ observes profiler==nullptr and skips.
218+
std::lock_guard<std::mutex> lock(handle_->mu);
219+
handle_->profiler = nullptr;
95220
}
96221

97222
std::atomic<SamplerPosix *> SamplerPosix::instance_{nullptr};
@@ -210,30 +335,51 @@ void Sampler::platformUnregisterRuntime(SamplingProfiler *profiler) {}
210335

211336
void Sampler::platformPostSampleStack(SamplingProfiler *localProfiler) {}
212337

213-
bool Sampler::platformSuspendVMAndWalkStack(SamplingProfiler *profiler) {
338+
SampleResult Sampler::platformSuspendVMAndWalkStack(
339+
SamplingProfiler *profiler) {
214340
auto *self = static_cast<SamplerPosix *>(this);
215341
auto *posixProfiler = static_cast<SamplingProfilerPosix *>(profiler);
342+
343+
// If the registered thread has exited, skip this sample. The caller
344+
// holds runtimeDataLock_, which serializes with the thread-death handler
345+
// (see Sampler::onRegisteredThreadExit), so currentThread_ will not be
346+
// concurrently invalidated between this check and the pthread_kill
347+
// below. This prevents bionic's pthread_kill from aborting on a recycled
348+
// pthread_t after a registered JS thread has exited.
349+
if (posixProfiler->currentThread_ == 0) {
350+
return SampleResult::ThreadExited;
351+
}
352+
216353
// Guarantee that the runtime thread will not proceed until it has
217354
// acquired the updates to domains_.
218355
self->profilerForSig_.store(profiler, std::memory_order_release);
219356

220357
// Signal target runtime thread to sample stack. The runtimeDataLock is
221358
// held by the caller, ensuring the runtime won't start to be used on
222359
// another thread before sampling begins.
223-
pthread_kill(posixProfiler->currentThread_, SIGPROF);
360+
int result = pthread_kill(posixProfiler->currentThread_, SIGPROF);
361+
if (result != 0) {
362+
// On non-Android POSIX, pthread_kill may return ESRCH if the target
363+
// terminated in the narrow window where its pthread_t is still in the
364+
// thread list but the thread has exited. Treat it as a thread-exit skip
365+
// rather than a fatal error so the timer loop keeps sampling the other
366+
// registered profilers.
367+
self->profilerForSig_.store(nullptr, std::memory_order_release);
368+
return SampleResult::ThreadExited;
369+
}
224370

225371
// Threading: samplingDoneSem_ will synchronise this thread with the
226372
// signal handler, so that we only have one active signal at a time.
227373
if (!self->samplingDoneSem_.wait()) {
228-
return false;
374+
return SampleResult::Failed;
229375
}
230376

231377
// Guarantee that this thread will observe all changes made to data
232378
// structures in the signal handler.
233379
while (self->profilerForSig_.load(std::memory_order_acquire) != nullptr) {
234380
}
235381

236-
return true;
382+
return SampleResult::Success;
237383
}
238384

239385
} // namespace sampling_profiler
@@ -250,12 +396,34 @@ bool SamplingProfiler::belongsToCurrentThread() {
250396

251397
void SamplingProfiler::setRuntimeThread() {
252398
auto profiler = static_cast<sampling_profiler::SamplingProfilerPosix *>(this);
253-
std::lock_guard<std::mutex> lock(profiler->runtimeDataLock_);
254-
profiler->currentThread_ = pthread_self();
255-
threadID_ = oscompat::global_thread_id();
256-
threadNames_[threadID_] = oscompat::thread_name();
399+
{
400+
std::lock_guard<std::mutex> lock(profiler->runtimeDataLock_);
401+
profiler->currentThread_ = pthread_self();
402+
threadID_ = oscompat::global_thread_id();
403+
threadNames_[threadID_] = oscompat::thread_name();
404+
}
405+
// Register with the new thread's death guard. If an older thread's guard
406+
// still references handle_, it will find currentThread_ no longer matches
407+
// itself and skip on exit.
408+
sampling_profiler::attachHandleToCurrentThread(profiler->handle_);
257409
}
258410

411+
namespace sampling_profiler {
412+
void Sampler::onRegisteredThreadExit(SamplingProfiler *profiler) {
413+
auto *posix = static_cast<SamplingProfilerPosix *>(profiler);
414+
std::lock_guard<std::mutex> lock(posix->runtimeDataLock_);
415+
// Only invalidate if currentThread_ still points at the caller. This
416+
// correctly handles the setRuntimeThread() case where the profiler has
417+
// moved to a different thread before the original thread exits. The
418+
// explicit zero check avoids invoking pthread_equal with an invalid
419+
// thread ID, which POSIX leaves implementation-defined.
420+
if (posix->currentThread_ != 0 &&
421+
pthread_equal(posix->currentThread_, pthread_self())) {
422+
posix->currentThread_ = 0;
423+
}
424+
}
425+
} // namespace sampling_profiler
426+
259427
} // namespace vm
260428
} // namespace hermes
261429

‎lib/VM/Profiler/SamplingProfilerSampler.cpp‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,22 @@ void Sampler::unregisterRuntime(SamplingProfiler *profiler) {
6464
bool Sampler::sampleStacks() {
6565
for (SamplingProfiler *localProfiler : profilers_) {
6666
std::lock_guard<std::mutex> lk(localProfiler->runtimeDataLock_);
67-
if (!sampleStack(localProfiler)) {
68-
return false;
67+
switch (sampleStack(localProfiler)) {
68+
case SampleResult::Success:
69+
platformPostSampleStack(localProfiler);
70+
break;
71+
case SampleResult::ThreadExited:
72+
// The registered thread is gone; skip this profiler but keep
73+
// sampling the others.
74+
continue;
75+
case SampleResult::Failed:
76+
return false;
6977
}
70-
platformPostSampleStack(localProfiler);
7178
}
7279
return true;
7380
}
7481

75-
bool Sampler::sampleStack(SamplingProfiler *localProfiler) {
82+
SampleResult Sampler::sampleStack(SamplingProfiler *localProfiler) {
7683
if (localProfiler->suspendCount_ > 0) {
7784
// Sampling profiler is suspended. Copy pre-captured stack instead without
7885
// interrupting the VM thread.
@@ -97,8 +104,12 @@ bool Sampler::sampleStack(SamplingProfiler *localProfiler) {
97104
localProfiler->nativeFunctions_.capacity();
98105
(void)nativeFunctionsCapacityBefore;
99106

100-
if (!platformSuspendVMAndWalkStack(localProfiler)) {
101-
return false;
107+
SampleResult result = platformSuspendVMAndWalkStack(localProfiler);
108+
if (result != SampleResult::Success) {
109+
// Either the registered thread has exited (skip this profiler) or an
110+
// unrecoverable error occurred (stop the loop). Nothing was walked, so
111+
// there is no sample to record; propagate the outcome to the caller.
112+
return result;
102113
}
103114

104115
// The stack trace was truncated due to insufficient pre-allocated size in
@@ -125,7 +136,7 @@ bool Sampler::sampleStack(SamplingProfiler *localProfiler) {
125136

126137
sampleStorage_.stack.clear();
127138
numSkippedFrames_ = 0;
128-
return true;
139+
return SampleResult::Success;
129140
}
130141

131142
void Sampler::walkRuntimeStack(

‎lib/VM/Profiler/SamplingProfilerSampler.h‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,20 @@
2020
namespace hermes {
2121
namespace vm {
2222
namespace sampling_profiler {
23+
24+
/// Outcome of attempting to sample a single profiler's stack. Distinguishes a
25+
/// per-profiler skip (which should not stop the sampling thread) from a fatal
26+
/// error (which should).
27+
enum class SampleResult {
28+
/// The stack was walked successfully; the caller should record the sample.
29+
Success,
30+
/// The profiler's registered thread has exited, so it could not be sampled.
31+
/// The caller should skip this profiler but keep sampling the others.
32+
ThreadExited,
33+
/// An unrecoverable error occurred; the timer loop thread should stop.
34+
Failed,
35+
};
36+
2337
/// Sampler manages the SamplingProfiler's sampling thread, and abstracts
2438
/// away platform-specific code for suspending the VM thread and performing the
2539
/// JS stack walk.
@@ -116,6 +130,20 @@ struct Sampler {
116130
/// \return the singleton profiler instance.
117131
static Sampler *get();
118132

133+
/// Called by the platform's thread-death infrastructure (e.g. a pthread
134+
/// TLS destructor on POSIX) when a thread that registered \p profiler is
135+
/// exiting. If \p profiler is still registered to the calling thread,
136+
/// invalidates the registered thread so subsequent sample attempts skip
137+
/// \p profiler instead of signalling a dead thread. No-op on platforms
138+
/// where no thread-death synchronization is required (e.g. Windows).
139+
///
140+
/// Caller contract: must be invoked on the dying thread itself. The
141+
/// implementation uses pthread_self() (or the platform equivalent) to
142+
/// identify which registration to invalidate, so calling from any other
143+
/// thread would either be a no-op (wrong identity) or unsafe (if the
144+
/// dying thread is no longer in the thread list).
145+
static void onRegisteredThreadExit(SamplingProfiler *profiler);
146+
119147
protected:
120148
Sampler();
121149

@@ -125,7 +153,11 @@ struct Sampler {
125153

126154
private:
127155
/// Sample stack for a profiler.
128-
bool sampleStack(SamplingProfiler *localProfiler);
156+
/// \return SampleResult::ThreadExited if \p localProfiler's registered thread
157+
/// has exited (skip it but keep sampling others), SampleResult::Failed on an
158+
/// unrecoverable error (stop the timer loop), and SampleResult::Success
159+
/// otherwise.
160+
SampleResult sampleStack(SamplingProfiler *localProfiler);
129161

130162
// Platform-specific hooks.
131163

@@ -158,7 +190,11 @@ struct Sampler {
158190
/// Platform-specific hook invoked to suspend the VM thread and perform stack
159191
/// sampling. Note that this method is invoked with both this->profilerLock_
160192
/// and \p profiler->runtimeDataLock_ locks held.
161-
bool platformSuspendVMAndWalkStack(SamplingProfiler *profiler);
193+
/// \return SampleResult::ThreadExited if the profiler's registered thread has
194+
/// exited (the platform should skip it), SampleResult::Failed on an
195+
/// unrecoverable error, and SampleResult::Success once the stack has been
196+
/// walked.
197+
SampleResult platformSuspendVMAndWalkStack(SamplingProfiler *profiler);
162198
};
163199
} // namespace sampling_profiler
164200
} // namespace vm

0 commit comments

Comments
 (0)