diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d69a8be..9cc2d4f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ Release notes on GitHub are taken from the matching section here. ## [Unreleased] +### Fixed + +- Crash reports are complete more often. When two threads crash at once, the second waits for the first + report instead of cutting it off, and a stack overflow on one of Roblox's threads now leaves a report. +- A closed pipe or socket, such as the session-log writer exiting, no longer closes Nightcap with no + crash report; the write fails and Nightcap carries on. +- Nightcap no longer quits when it can't start a helper thread, such as under a Flatpak or systemd + thread limit. It logs the failure and carries on. + ## [0.5.7] - 2026-12-02 ### Added diff --git a/include/compat/crash_reporter.h b/include/compat/crash_reporter.h index 9034ab3d..0abd45dc 100644 --- a/include/compat/crash_reporter.h +++ b/include/compat/crash_reporter.h @@ -9,6 +9,14 @@ bool InstallCrashReporter(); bool CrashReporterOwns(int signal_number); +// Makes writes to a closed pipe or socket fail with EPIPE instead of killing +// the process. Unlike SIG_IGN, exec'd programs get the default action back. +bool IgnoreBrokenPipes(); + +// Without its own signal stack, a thread that overflows its stack dies with no +// crash report. The 64 KiB stack is freed when the thread exits. +void InstallThreadCrashStack(); + int SetGuestCrashAction(int signal_number, const struct sigaction* action, struct sigaction* old_action); diff --git a/include/runtime/owned_pthread.h b/include/runtime/owned_pthread.h index a4d9b4bc..ff8973a2 100644 --- a/include/runtime/owned_pthread.h +++ b/include/runtime/owned_pthread.h @@ -4,6 +4,7 @@ #include #include +#include namespace mocktail { namespace runtime { @@ -62,6 +63,11 @@ class OwnedPthread final { const char* OwnedPthreadWaitStatusName(OwnedPthreadWaitStatus status); +// Runs `work` on a new detached thread. Returns false when the thread cannot +// be created; std::thread aborts instead, since this builds without +// exceptions. +bool StartDetachedThread(std::function work); + } // namespace runtime } // namespace mocktail diff --git a/src/compat/bionic_pthread_create_runtime.cc b/src/compat/bionic_pthread_create_runtime.cc index a4fb7afc..a6c0f0ca 100644 --- a/src/compat/bionic_pthread_create_runtime.cc +++ b/src/compat/bionic_pthread_create_runtime.cc @@ -1,6 +1,7 @@ #include "compat/bionic_pthread_create_runtime.h" #include "compat/bionic_abi_exports.h" +#include "compat/crash_reporter.h" #include #include @@ -176,6 +177,7 @@ void* RunGuestThread(void* raw_context) noexcept { const ThreadStartContext values = *context; delete context; + InstallThreadCrashStack(); // Bionic gives every thread one, too. if (values.initializer != nullptr) { values.initializer(); } diff --git a/src/compat/crash_reporter.cc b/src/compat/crash_reporter.cc index a99584c3..b89fde56 100644 --- a/src/compat/crash_reporter.cc +++ b/src/compat/crash_reporter.cc @@ -1,6 +1,7 @@ #include "compat/crash_reporter.h" #include +#include #include #include #include @@ -12,6 +13,7 @@ #include #include #include +#include namespace mocktail::compat { namespace { @@ -34,6 +36,8 @@ struct Mapping { std::atomic g_installed{false}; std::atomic g_reported{false}; +std::atomic g_report_done{false}; +std::atomic g_reporter_tid{0}; std::atomic g_guest_calls{0}; struct sigaction g_guest[kSignalSlots]; std::atomic g_guest_set[kSignalSlots]; @@ -333,10 +337,26 @@ void ResetAndResend(int signal_number, const siginfo_t* info) { } } +// A second crashing thread would otherwise kill the process mid-report. +void WaitForReport() { + constexpr timespec kStep{0, 10'000'000}; + for (int step = 0; step < 200; ++step) { + if (g_report_done.load(std::memory_order_acquire)) { + return; + } + nanosleep(&kStep, nullptr); + } +} + void HandleCrash(int signal_number, siginfo_t* info, void* context) { const int saved_errno = errno; + const long tid = static_cast(syscall(SYS_gettid)); if (!g_reported.exchange(true, std::memory_order_acq_rel)) { + g_reporter_tid.store(tid, std::memory_order_release); Report(signal_number, info, context); + g_report_done.store(true, std::memory_order_release); + } else if (g_reporter_tid.load(std::memory_order_acquire) != tid) { + WaitForReport(); } if (signal_number > 0 && signal_number < kSignalSlots && g_guest_set[signal_number].load(std::memory_order_acquire) && @@ -440,4 +460,67 @@ bool InstallCrashReporter() { return true; } +namespace { + +void IgnoreSignal(int) {} + +constexpr std::size_t kThreadAltStackSize = 64 * 1024; + +class ThreadAltStack { + public: + ThreadAltStack() { + stack_t current{}; + if (sigaltstack(nullptr, ¤t) != 0 || + (current.ss_flags & SS_DISABLE) == 0) { + return; + } + void* const memory = + mmap(nullptr, kThreadAltStackSize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); + if (memory == MAP_FAILED) { + return; + } + stack_t stack{}; + stack.ss_sp = memory; + stack.ss_size = kThreadAltStackSize; + if (sigaltstack(&stack, nullptr) != 0) { + munmap(memory, kThreadAltStackSize); + return; + } + memory_ = memory; + } + + ~ThreadAltStack() { + if (memory_ == nullptr) { + return; + } + stack_t off{}; + off.ss_flags = SS_DISABLE; + sigaltstack(&off, nullptr); + munmap(memory_, kThreadAltStackSize); + } + + ThreadAltStack(const ThreadAltStack&) = delete; + ThreadAltStack& operator=(const ThreadAltStack&) = delete; + + private: + void* memory_ = nullptr; +}; + +} + +void InstallThreadCrashStack() { + // Freed at thread exit, by return or pthread_exit alike. + thread_local ThreadAltStack stack; + (void)stack; +} + +bool IgnoreBrokenPipes() { + struct sigaction action {}; + action.sa_handler = IgnoreSignal; // execve resets a handler; not SIG_IGN. + action.sa_flags = SA_RESTART; + sigemptyset(&action.sa_mask); + return sigaction(SIGPIPE, &action, nullptr) == 0; +} + } diff --git a/src/main.cc b/src/main.cc index 58af613a..7d56ec5c 100644 --- a/src/main.cc +++ b/src/main.cc @@ -45,6 +45,7 @@ #include "runtime/graphics_launch_policy.h" #include "runtime/luau_codegen_switch.h" #include "runtime/memory_limit.h" +#include "runtime/owned_pthread.h" #include "runtime/payload_update_preflight.h" #include "runtime/performance_policy.h" #include "runtime/platform_cache_migration.h" @@ -199,7 +200,8 @@ void RequestAccountSwitchRestart(void* vm, bool signed_in) { if (signed_in) { const auto since = std::filesystem::file_time_type::clock::now() - std::chrono::seconds(2); - std::thread([app_storage = g_app_storage_file, since] { + const bool started = mocktail::runtime::StartDetachedThread( + [app_storage = g_app_storage_file, since] { const mocktail::runtime::SavedAccountBlob result = mocktail::runtime::WaitForSavedRobloxAccountBlob( app_storage, since, std::chrono::seconds(5)); @@ -210,7 +212,14 @@ void RequestAccountSwitchRestart(void* vm, bool signed_in) { << std::flush; g_account_switch_restart = true; kill(getpid(), SIGTERM); - }).detach(); + }); + if (!started) { + std::cout << " [auth] account switched; restarting without waiting " + "for the account blob\n" + << std::flush; + g_account_switch_restart = true; + kill(getpid(), SIGTERM); + } return; } g_account_switch_restart = true; @@ -919,6 +928,10 @@ int main(int argc, char* argv[]) { if (!mocktail::compat::InstallCrashReporter()) { std::cerr << " [crash] reporter unavailable\n"; } + if (!mocktail::compat::IgnoreBrokenPipes()) { + std::cerr << " [crash] cannot ignore SIGPIPE; a closed pipe will " + "kill the process\n"; + } mocktail::runtime::InstallCpuLimitDiagnostics(); mocktail::runtime::LogProcessDiagnostics( mocktail::runtime::ProcessDiagnosticStage::kStartup); diff --git a/src/runtime/desktop_notification.cc b/src/runtime/desktop_notification.cc index 30a64be6..d12b9ac3 100644 --- a/src/runtime/desktop_notification.cc +++ b/src/runtime/desktop_notification.cc @@ -1,5 +1,7 @@ #include "runtime/desktop_notification.h" +#include "runtime/owned_pthread.h" + #include #include @@ -48,7 +50,8 @@ DesktopNotificationCall BuildDesktopNotificationCall(bool sandboxed, } void ShowDesktopNotification(std::string title, std::string body) { - std::thread([title = std::move(title), body = std::move(body)] { + const bool started = StartDetachedThread([title = std::move(title), + body = std::move(body)] { DesktopNotificationCall call = BuildDesktopNotificationCall( std::getenv("FLATPAK_ID") != nullptr, title, body); GError* error = nullptr; @@ -70,7 +73,10 @@ void ShowDesktopNotification(std::string title, std::string body) { g_clear_error(&error); } g_variant_unref(call.parameters); - }).detach(); + }); + if (!started) { + std::cerr << " [notify] cannot start the notification thread\n"; + } } void NotifyWebRobuxPurchase(bool browser_opened) { diff --git a/src/runtime/owned_pthread.cc b/src/runtime/owned_pthread.cc index ae802233..d6b8131e 100644 --- a/src/runtime/owned_pthread.cc +++ b/src/runtime/owned_pthread.cc @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include namespace mocktail { @@ -121,5 +123,34 @@ const char* OwnedPthreadWaitStatusName(OwnedPthreadWaitStatus status) { return "Unknown"; } +bool StartDetachedThread(std::function work) { + auto* owned = new (std::nothrow) std::function(std::move(work)); + if (owned == nullptr) { + return false; + } + pthread_attr_t attributes; + if (pthread_attr_init(&attributes) != 0) { + delete owned; + return false; + } + pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); + pthread_t thread; + const int result = pthread_create( + &thread, &attributes, + [](void* context) -> void* { + std::unique_ptr> run( + static_cast*>(context)); + (*run)(); + return nullptr; + }, + owned); + pthread_attr_destroy(&attributes); + if (result != 0) { + delete owned; + return false; + } + return true; +} + } // namespace runtime } // namespace mocktail diff --git a/src/runtime/roblox_store_purchase.cc b/src/runtime/roblox_store_purchase.cc index c745b00a..bb507dd1 100644 --- a/src/runtime/roblox_store_purchase.cc +++ b/src/runtime/roblox_store_purchase.cc @@ -10,6 +10,7 @@ #include #include "runtime/desktop_notification.h" +#include "runtime/owned_pthread.h" namespace mocktail { namespace runtime { @@ -69,13 +70,17 @@ void HandOffRobuxPurchaseToBrowser() { std::cerr << " [store] repeated Robux purchase ignored\n"; return; } - std::thread([] { + const bool started = StartDetachedThread([] { const bool opened = OpenUrlInDefaultBrowser(kWebRobuxPurchaseUrl); std::cerr << (opened ? " [store] opened the Robux page in the browser\n" : " [store] could not open the Robux page in the " "browser\n"); NotifyWebRobuxPurchase(opened); - }).detach(); + }); + if (!started) { + std::cerr << " [store] could not open the Robux page in the browser\n"; + NotifyWebRobuxPurchase(false); + } } std::vector BrowserEnvironmentChanges( diff --git a/src/window/window.cc b/src/window/window.cc index 6f9bd8bd..e29c1208 100644 --- a/src/window/window.cc +++ b/src/window/window.cc @@ -27,6 +27,7 @@ #include "mocktail/platform/sdl_event_converter.h" #include "mocktail/platform/sdl_window_icon.h" #include "runtime/memory_limit.h" +#include "runtime/owned_pthread.h" #include "window/host_surface_commit_gate.h" #include "window/input_pump_pacer.h" #include "window/main_thread_command_gate.h" @@ -1597,7 +1598,8 @@ void MaybeLogProcessSample(std::uint64_t now_ns) { due, now_ns + kProcessSampleIntervalNs, std::memory_order_relaxed)) { return; } - std::thread([] { + // Skipped, not retried, when the thread can't start; the next one is 60 s out. + (void)runtime::StartDetachedThread([] { const runtime::ProcessMemoryUsage usage = runtime::ReadCurrentProcessMemory(); if (!usage.valid) { @@ -1609,7 +1611,7 @@ void MaybeLogProcessSample(std::uint64_t now_ns) { static_cast(usage.swap_bytes >> 20), static_cast(usage.threads), runtime::CountOpenFileDescriptors()); - }).detach(); + }); } } // namespace diff --git a/tests/crash_reporter_test.cc b/tests/crash_reporter_test.cc index 26f3ce5c..d9284d89 100644 --- a/tests/crash_reporter_test.cc +++ b/tests/crash_reporter_test.cc @@ -1,11 +1,16 @@ #include "compat/crash_reporter.h" #include +#include #include #include +#include +#include +#include #include +#include "compat/bionic_pthread_create_runtime.h" #include "compat/bionic_signal_runtime.h" namespace mocktail::compat { @@ -22,6 +27,30 @@ __attribute__((noinline)) void WriteThrough(volatile int* pointer) { void GuestExit(int, siginfo_t*, void*) { _exit(42); } +__attribute__((noinline)) int Recurse(int depth) { + volatile char frame[4096]; + frame[0] = static_cast(depth); + if (depth < 0) { + return 0; + } + return Recurse(depth + 1) + frame[0]; +} + +void* Overflow(void*) { + return reinterpret_cast(static_cast(Recurse(0))); +} + +std::atomic g_waiting{0}; +constexpr int kCrashingThreads = 8; + +void* CrashTogether(void*) { + g_waiting.fetch_add(1); + while (g_waiting.load() < kCrashingThreads) { + } + WriteThrough(nullptr); + return nullptr; +} + TEST(CrashReporterDeathTest, ReportsAFaultAndStillDiesFromIt) { EXPECT_EXIT( { @@ -62,5 +91,63 @@ TEST(CrashReporterDeathTest, GuestHandlerRunsAfterTheReport) { testing::ExitedWithCode(42), "\\[crash\\] SIGSEGV "); } +TEST(CrashReporterDeathTest, GuestThreadStackOverflowIsReported) { + EXPECT_EXIT( + { + NoCoreDump(); + ASSERT_TRUE(InstallCrashReporter()); + pthread_t thread; + ASSERT_EQ(mocktail_bionic_pthread_create(&thread, nullptr, Overflow, + nullptr), + 0); + pthread_join(thread, nullptr); + }, + testing::KilledBySignal(SIGSEGV), "\\[crash\\] SIGSEGV "); +} + +TEST(CrashReporterDeathTest, SimultaneousCrashesStillFinishOneReport) { + EXPECT_EXIT( + { + NoCoreDump(); + ASSERT_TRUE(InstallCrashReporter()); + pthread_t threads[kCrashingThreads]; + for (pthread_t& thread : threads) { + ASSERT_EQ(pthread_create(&thread, nullptr, CrashTogether, nullptr), + 0); + } + for (pthread_t& thread : threads) { + pthread_join(thread, nullptr); + } + }, + testing::KilledBySignal(SIGSEGV), + "\\[crash\\] SIGSEGV [^\n]*\n\\[crash\\] pc [^\n]*\n" + "(\\[crash\\] #[0-9]+ [^\n]*\n)+"); +} + +TEST(BrokenPipeDeathTest, WriteToAClosedPipeFailsInsteadOfKilling) { + EXPECT_EXIT( + { + ASSERT_TRUE(IgnoreBrokenPipes()); + int ends[2]; + ASSERT_EQ(pipe(ends), 0); + close(ends[0]); + const char byte = 'x'; + const bool epipe = write(ends[1], &byte, 1) == -1 && errno == EPIPE; + _exit(epipe ? 0 : 1); + }, + testing::ExitedWithCode(0), ""); +} + +TEST(BrokenPipeDeathTest, ExecedProgramsKeepTheDefaultAction) { + EXPECT_EXIT( + { + ASSERT_TRUE(IgnoreBrokenPipes()); + execl("/bin/sh", "sh", "-c", "kill -PIPE $$; exit 0", + static_cast(nullptr)); + _exit(127); + }, + testing::KilledBySignal(SIGPIPE), ""); +} + } } diff --git a/tests/owned_pthread_test.cc b/tests/owned_pthread_test.cc index 5d2295a5..00cf9186 100644 --- a/tests/owned_pthread_test.cc +++ b/tests/owned_pthread_test.cc @@ -1,6 +1,8 @@ #include "runtime/owned_pthread.h" #include +#include +#include #include #include @@ -122,6 +124,30 @@ TEST(OwnedPthreadTest, DeferredCancellationNeverConvertsToDetach) { EXPECT_TRUE(worker.WaitFor(1000, 1).joined()); } +TEST(DetachedThreadTest, RunsTheWork) { + std::atomic ran{false}; + ASSERT_TRUE(StartDetachedThread([&ran] { ran.store(true); })); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!ran.load() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_TRUE(ran.load()); +} + +TEST(DetachedThreadDeathTest, ReportsAFailedStartInsteadOfAborting) { + if (geteuid() == 0) { + GTEST_SKIP() << "RLIMIT_NPROC does not limit root"; + } + EXPECT_EXIT( + { + const rlimit none{}; + setrlimit(RLIMIT_NPROC, &none); + _exit(StartDetachedThread([] {}) ? 1 : 0); + }, + testing::ExitedWithCode(0), ""); +} + TEST(OwnedPthreadTest, WaitStatusNamesAreStable) { EXPECT_STREQ(OwnedPthreadWaitStatusName(OwnedPthreadWaitStatus::kJoined), "Joined");