From 6d060fffa35b667000b7ac2b92c6b28bd17cbd10 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sat, 14 Nov 2026 12:54:30 -0800 Subject: [PATCH 1/5] Use a Unix domain socketpair for TriggerFd on non-Linux POSIX TriggerFd used a pipe on every platform without eventfd. On QNX, pipes are served by the single-threaded pipe resource manager, which makes them slow under load. A socketpair is pollable, nonblocking, and can be passed over SCM_RIGHTS, so it is a drop-in replacement for the pipe on macOS, QNX, and other POSIX systems. Linux keeps using eventfd. Add triggerfd_test covering create, trigger/clear, repeated triggers, non-blocking behaviour when the buffer is full, and move semantics. --- README.md | 2 +- toolbelt/BUILD.bazel | 12 +++++++ toolbelt/triggerfd.cc | 38 ++++++++++++---------- toolbelt/triggerfd.h | 2 +- toolbelt/triggerfd_test.cc | 66 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 19 deletions(-) create mode 100644 toolbelt/triggerfd_test.cc diff --git a/README.md b/README.md index 7254b91..9fbe136 100644 --- a/README.md +++ b/README.md @@ -913,7 +913,7 @@ int value = resizable->VectorGet(&vec_hdr, 0); // Returns 42 ### TriggerFd -A file descriptor that can be used to trigger events. Implemented as an `eventfd` on Linux or a pipe on other systems. +A file descriptor that can be used to trigger events. Implemented as an `eventfd` on Linux and a Unix domain `socketpair` on other POSIX systems, including macOS and QNX. **Header:** `toolbelt/triggerfd.h` diff --git a/toolbelt/BUILD.bazel b/toolbelt/BUILD.bazel index 0c9da20..f4786a9 100644 --- a/toolbelt/BUILD.bazel +++ b/toolbelt/BUILD.bazel @@ -81,6 +81,18 @@ cc_test( "@googletest//:gtest_main", ], ) +cc_test( + name = "triggerfd_test", + size = "small", + srcs = ["triggerfd_test.cc"], + deps = [ + ":toolbelt", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:statusor", + "@googletest//:gtest_main", + ], +) + cc_test( name = "pipe_test", size = "medium", diff --git a/toolbelt/triggerfd.cc b/toolbelt/triggerfd.cc index fd9a835..034a788 100644 --- a/toolbelt/triggerfd.cc +++ b/toolbelt/triggerfd.cc @@ -5,11 +5,17 @@ #include "toolbelt/triggerfd.h" #include "absl/strings/str_format.h" +// Linux has eventfd, which is the cheapest pollable trigger. Everywhere else +// (macOS, QNX, other POSIX) use a Unix domain socketpair. Pipes are a poor +// fit: on QNX they go through a single-threaded pipe service, and a socketpair +// is pollable, nonblocking, and passable over SCM_RIGHTS on every POSIX system +// we care about. +#include #if defined(__linux__) #include #else -#include -#include +#include +#include #endif namespace toolbelt { @@ -41,22 +47,20 @@ absl::Status TriggerFd::Open() { poll_fd_.SetFd(fd); trigger_fd_ = poll_fd_; #else - int pipes[2]; - if (pipe(pipes) == -1) { + int fds[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) { return absl::InternalError(absl::StrFormat( - "Unable to create trigger fd pipe: %s", strerror(errno))); + "Unable to create trigger fd socketpair: %s", strerror(errno))); } - // Both ends of the pipe are nonblocking. - if (fcntl(pipes[0], F_SETFL, (fcntl(pipes[0], F_GETFL) | O_NONBLOCK)) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to set non-blocking on read pipe: %s", strerror(errno))); + // Owned immediately so both ends are closed if setting nonblocking fails. + poll_fd_.SetFd(fds[0]); + trigger_fd_.SetFd(fds[1]); + if (absl::Status status = poll_fd_.SetNonBlocking(); !status.ok()) { + return status; } - if (fcntl(pipes[1], F_SETFL, (fcntl(pipes[1], F_GETFL) | O_NONBLOCK)) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to set non-blocking on write pipe: %s", strerror(errno))); + if (absl::Status status = trigger_fd_.SetNonBlocking(); !status.ok()) { + return status; } - poll_fd_.SetFd(pipes[0]); // Read end - trigger_fd_.SetFd(pipes[1]); // Write end. #endif return absl::OkStatus(); } @@ -67,7 +71,7 @@ void TriggerFd::Trigger() { int64_t val = 1; (void)::write(trigger_fd_.Fd(), &val, 8); #else - // Pipe. Write a single byte to it. + // Unix domain socket. Write a single byte to it. char val = 'x'; (void)::write(trigger_fd_.Fd(), &val, 1); #endif @@ -81,8 +85,8 @@ bool TriggerFd::Clear() { ssize_t n = ::read(poll_fd_.Fd(), &val, 8); return (n > 0); #else - // Pipe. Read all bytes from the pipe. The pipe is nonblocking so we will - // get an EAGAIN when we've cleared it. + // Unix domain socket. Read all pending bytes. The socket is nonblocking + // so we get EAGAIN once it has been drained. bool was_triggered = false; for (;;) { char buffer[256]; diff --git a/toolbelt/triggerfd.h b/toolbelt/triggerfd.h index b248e7d..d99a111 100644 --- a/toolbelt/triggerfd.h +++ b/toolbelt/triggerfd.h @@ -13,7 +13,7 @@ namespace toolbelt { // A TriggerFd is a file descriptor that can be used to trigger // an event. If the facility is available, it is implemented -// as an eventfd, otherwise it's a pipe. +// as an eventfd on Linux, otherwise a Unix domain socketpair. class TriggerFd { public: TriggerFd() = default; diff --git a/toolbelt/triggerfd_test.cc b/toolbelt/triggerfd_test.cc new file mode 100644 index 0000000..95f3d90 --- /dev/null +++ b/toolbelt/triggerfd_test.cc @@ -0,0 +1,66 @@ +// Copyright 2023 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "toolbelt/triggerfd.h" +#include +#include + +namespace { + +bool Readable(toolbelt::TriggerFd &t) { + struct pollfd pfd = t.GetPollFd().GetPollFd(); + return ::poll(&pfd, 1, 0) == 1 && (pfd.revents & POLLIN) != 0; +} + +TEST(TriggerFdTest, CreateAndClearUntriggered) { + auto t = toolbelt::TriggerFd::Create(); + ASSERT_TRUE(t.ok()); + ASSERT_TRUE(t->GetPollFd().Valid()); + ASSERT_TRUE(t->GetTriggerFd().Valid()); + ASSERT_FALSE(Readable(*t)); + ASSERT_FALSE(t->Clear()); +} + +TEST(TriggerFdTest, TriggerThenClear) { + auto t = toolbelt::TriggerFd::Create(); + ASSERT_TRUE(t.ok()); + t->Trigger(); + ASSERT_TRUE(Readable(*t)); + ASSERT_TRUE(t->Clear()); + ASSERT_FALSE(Readable(*t)); + ASSERT_FALSE(t->Clear()); +} + +TEST(TriggerFdTest, MultipleTriggersClearedAtOnce) { + auto t = toolbelt::TriggerFd::Create(); + ASSERT_TRUE(t.ok()); + for (int i = 0; i < 10; i++) { + t->Trigger(); + } + ASSERT_TRUE(t->Clear()); + ASSERT_FALSE(Readable(*t)); +} + +TEST(TriggerFdTest, TriggerNeverBlocksWhenFull) { + auto t = toolbelt::TriggerFd::Create(); + ASSERT_TRUE(t.ok()); + // Far more triggers than any pipe/socket buffer can hold. The trigger fd is + // nonblocking so this must not hang. + for (int i = 0; i < 1000000; i++) { + t->Trigger(); + } + ASSERT_TRUE(t->Clear()); + ASSERT_FALSE(Readable(*t)); +} + +TEST(TriggerFdTest, Move) { + auto t = toolbelt::TriggerFd::Create(); + ASSERT_TRUE(t.ok()); + toolbelt::TriggerFd moved = std::move(*t); + ASSERT_FALSE(t->GetPollFd().Valid()); + moved.Trigger(); + ASSERT_TRUE(moved.Clear()); +} + +} // namespace From 10e2b042cb0e4602b8362d50612abf3c8b681ecc Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sat, 14 Nov 2026 23:16:26 -0800 Subject: [PATCH 2/5] Use a socketpair for TriggerFd only on QNX. QNX pipes go through a single-threaded pipe service. On macOS a socketpair was slower than a pipe, especially when a publish wakes another thread, and its read end always reports POLLOUT. Linux stays on eventfd and other POSIX systems stay on a pipe. --- README.md | 2 +- toolbelt/triggerfd.cc | 38 ++++++++++++++++++++++++++++---------- toolbelt/triggerfd.h | 3 ++- 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 9fbe136..1b3d7ee 100644 --- a/README.md +++ b/README.md @@ -913,7 +913,7 @@ int value = resizable->VectorGet(&vec_hdr, 0); // Returns 42 ### TriggerFd -A file descriptor that can be used to trigger events. Implemented as an `eventfd` on Linux and a Unix domain `socketpair` on other POSIX systems, including macOS and QNX. +A file descriptor that can be used to trigger events. Implemented as an `eventfd` on Linux, a Unix domain `socketpair` on QNX, and a pipe on other POSIX systems, including macOS. QNX pipes go through a single-threaded pipe service, and a socketpair is slower than a pipe on macOS. **Header:** `toolbelt/triggerfd.h` diff --git a/toolbelt/triggerfd.cc b/toolbelt/triggerfd.cc index 034a788..4150551 100644 --- a/toolbelt/triggerfd.cc +++ b/toolbelt/triggerfd.cc @@ -5,17 +5,18 @@ #include "toolbelt/triggerfd.h" #include "absl/strings/str_format.h" -// Linux has eventfd, which is the cheapest pollable trigger. Everywhere else -// (macOS, QNX, other POSIX) use a Unix domain socketpair. Pipes are a poor -// fit: on QNX they go through a single-threaded pipe service, and a socketpair -// is pollable, nonblocking, and passable over SCM_RIGHTS on every POSIX system -// we care about. +// Linux has eventfd, which is the cheapest pollable trigger. QNX pipes go +// through a single-threaded pipe service, so QNX uses a Unix domain socketpair. +// Every other POSIX system, including macOS, keeps the pipe. A socketpair is +// slower there, and its read end always reports POLLOUT. #include #if defined(__linux__) #include -#else +#elif defined(__QNX__) || defined(__QNXNTO__) #include #include +#else +#include #endif namespace toolbelt { @@ -46,7 +47,7 @@ absl::Status TriggerFd::Open() { } poll_fd_.SetFd(fd); trigger_fd_ = poll_fd_; -#else +#elif defined(__QNX__) || defined(__QNXNTO__) int fds[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) { return absl::InternalError(absl::StrFormat( @@ -61,6 +62,23 @@ absl::Status TriggerFd::Open() { if (absl::Status status = trigger_fd_.SetNonBlocking(); !status.ok()) { return status; } +#else + int pipes[2]; + if (pipe(pipes) == -1) { + return absl::InternalError(absl::StrFormat( + "Unable to create trigger fd pipe: %s", strerror(errno))); + } + // Both ends of the pipe are nonblocking. + if (fcntl(pipes[0], F_SETFL, (fcntl(pipes[0], F_GETFL) | O_NONBLOCK)) == -1) { + return absl::InternalError(absl::StrFormat( + "Unable to set non-blocking on read pipe: %s", strerror(errno))); + } + if (fcntl(pipes[1], F_SETFL, (fcntl(pipes[1], F_GETFL) | O_NONBLOCK)) == -1) { + return absl::InternalError(absl::StrFormat( + "Unable to set non-blocking on write pipe: %s", strerror(errno))); + } + poll_fd_.SetFd(pipes[0]); // Read end + trigger_fd_.SetFd(pipes[1]); // Write end. #endif return absl::OkStatus(); } @@ -71,7 +89,7 @@ void TriggerFd::Trigger() { int64_t val = 1; (void)::write(trigger_fd_.Fd(), &val, 8); #else - // Unix domain socket. Write a single byte to it. + // Pipe, or a socketpair on QNX. Write a single byte to it. char val = 'x'; (void)::write(trigger_fd_.Fd(), &val, 1); #endif @@ -85,8 +103,8 @@ bool TriggerFd::Clear() { ssize_t n = ::read(poll_fd_.Fd(), &val, 8); return (n > 0); #else - // Unix domain socket. Read all pending bytes. The socket is nonblocking - // so we get EAGAIN once it has been drained. + // Pipe, or a socketpair on QNX. Read all pending bytes. The fd is + // nonblocking, so we get EAGAIN once it has been drained. bool was_triggered = false; for (;;) { char buffer[256]; diff --git a/toolbelt/triggerfd.h b/toolbelt/triggerfd.h index d99a111..aefced1 100644 --- a/toolbelt/triggerfd.h +++ b/toolbelt/triggerfd.h @@ -13,7 +13,8 @@ namespace toolbelt { // A TriggerFd is a file descriptor that can be used to trigger // an event. If the facility is available, it is implemented -// as an eventfd on Linux, otherwise a Unix domain socketpair. +// as an eventfd on Linux, a Unix domain socketpair on QNX, and a pipe +// everywhere else. class TriggerFd { public: TriggerFd() = default; From 425aa5096ea4680347d6969a61091d1164f48fb8 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 15 Nov 2026 09:50:51 -0800 Subject: [PATCH 3/5] Triggerfd signal config macro --- MODULE.bazel.lock | 36 ++++----------- README.md | 2 +- toolbelt/triggerfd.cc | 101 ++++++++++++++++++++++++------------------ toolbelt/triggerfd.h | 32 +++++++++++-- 4 files changed, 96 insertions(+), 75 deletions(-) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index e3f6375..fabf7a4 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1,5 +1,5 @@ { - "lockFileVersion": 26, + "lockFileVersion": 28, "registryFileHashes": { "https://bcr.bazel.build/bazel_registry.json": "8a28e4aff06ee60aed2a8c281907fb8bcbf3b753c91fb5a5c57da3215d5b3497", "https://bcr.bazel.build/modules/abseil-cpp/20210324.2/MODULE.bazel": "7cd0312e064fde87c8d1cd79ba06c876bd23630c83466e9500321be55c96ace2", @@ -19,8 +19,8 @@ "https://bcr.bazel.build/modules/apple_support/1.21.0/MODULE.bazel": "ac1824ed5edf17dee2fdd4927ada30c9f8c3b520be1b5fd02a5da15bc10bff3e", "https://bcr.bazel.build/modules/apple_support/1.21.1/MODULE.bazel": "5809fa3efab15d1f3c3c635af6974044bac8a4919c62238cce06acee8a8c11f1", "https://bcr.bazel.build/modules/apple_support/1.22.1/MODULE.bazel": "90bd1a660590f3ceffbdf524e37483094b29352d85317060b2327fff8f3f4458", - "https://bcr.bazel.build/modules/apple_support/1.24.2/MODULE.bazel": "0e62471818affb9f0b26f128831d5c40b074d32e6dda5a0d3852847215a41ca4", - "https://bcr.bazel.build/modules/apple_support/1.24.2/source.json": "2c22c9827093250406c5568da6c54e6fdf0ef06238def3d99c71b12feb057a8d", + "https://bcr.bazel.build/modules/apple_support/2.5.2/MODULE.bazel": "bb1b7081e390a8d3885f642cb0073dfcf8e7a36525e079fa8f5835af7079c0fe", + "https://bcr.bazel.build/modules/apple_support/2.5.2/source.json": "dd51ee925a550e92b55eb41c4c809a967da311a2d2520241252a238a48b39c4c", "https://bcr.bazel.build/modules/bazel_features/1.1.1/MODULE.bazel": "27b8c79ef57efe08efccbd9dd6ef70d61b4798320b8d3c134fd571f78963dbcd", "https://bcr.bazel.build/modules/bazel_features/1.10.0/MODULE.bazel": "f75e8807570484a99be90abcd52b5e1f390362c258bcb73106f4544957a48101", "https://bcr.bazel.build/modules/bazel_features/1.11.0/MODULE.bazel": "f9382337dd5a474c3b7d334c2f83e50b6eaedc284253334cf823044a26de03e8", @@ -121,6 +121,7 @@ "https://bcr.bazel.build/modules/rules_cc/0.1.5/MODULE.bazel": "88dfc9361e8b5ae1008ac38f7cdfd45ad738e4fa676a3ad67d19204f045a1fd8", "https://bcr.bazel.build/modules/rules_cc/0.2.0/MODULE.bazel": "b5c17f90458caae90d2ccd114c81970062946f49f355610ed89bebf954f5783c", "https://bcr.bazel.build/modules/rules_cc/0.2.13/MODULE.bazel": "eecdd666eda6be16a8d9dc15e44b5c75133405e820f620a234acc4b1fdc5aa37", + "https://bcr.bazel.build/modules/rules_cc/0.2.15/MODULE.bazel": "6a0a4a75a57aa6dc888300d848053a58c6b12a29f89d4304e1c41448514ec6e8", "https://bcr.bazel.build/modules/rules_cc/0.2.17/MODULE.bazel": "1849602c86cb60da8613d2de887f9566a6d354a6df6d7009f9d04a14402f9a84", "https://bcr.bazel.build/modules/rules_cc/0.2.17/source.json": "3832f45d145354049137c0090df04629d9c2b5493dc5c2bf46f1834040133a07", "https://bcr.bazel.build/modules/rules_cc/0.2.8/MODULE.bazel": "f1df20f0bf22c28192a794f29b501ee2018fa37a3862a1a2132ae2940a23a642", @@ -200,29 +201,9 @@ }, "selectedYankedVersions": {}, "moduleExtensions": { - "@@pybind11_bazel+//:internal_configure.bzl%internal_configure_extension": { - "general": { - "bzlTransitiveDigest": "Ilz4hu4VWEbx3OM4ZIpgYmYXuPq6ewOVgzv5F0ziWS8=", - "usagesDigest": "tVQNvLoXMWAbiK39am3yovKGpwINdftfn7RpDyN+JZc=", - "recordedInputs": [ - "REPO_MAPPING:pybind11_bazel+,bazel_tools bazel_tools" - ], - "generatedRepoSpecs": { - "pybind11": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "build_file": "@@pybind11_bazel+//:pybind11-BUILD.bazel", - "strip_prefix": "pybind11-2.13.6", - "url": "https://github.com/pybind/pybind11/archive/refs/tags/v2.13.6.tar.gz", - "integrity": "sha256-4Iy4f0dz2pf6e18DXeh2OrxlbYfVdz5i9toFh9Hw7CA=" - } - } - } - } - }, "@@rules_kotlin+//src/main/starlark/core/repositories:bzlmod_setup.bzl%rules_kotlin_extensions": { "general": { - "bzlTransitiveDigest": "Ga4z8lQy1YQ5rAMy+dOl0dqcCEBnYNCXku8x3YQmDZI=", + "bzlTransitiveDigest": "WDuVCwqV73DvcHB5Of+02lhUZgPxr9MqtpvMRyUi0eQ=", "usagesDigest": "QI2z8ZUR+mqtbwsf2fLqYdJAkPOHdOV+tF2yVAUgRzw=", "recordedInputs": [ "REPO_MAPPING:rules_kotlin+,bazel_tools bazel_tools" @@ -279,7 +260,7 @@ }, "@@rules_python+//python/extensions:config.bzl%config": { "general": { - "bzlTransitiveDigest": "iibnRYgg8LpcfmH7EAnVwYePC3jsVaJ6Id8XxUjSZps=", + "bzlTransitiveDigest": "L+2ZCpb7GIJqvWaXpzkfk/80d916sIFVmSPzrSm6of8=", "usagesDigest": "ZVSXMAGpD+xzVNPuvF1IoLBkty7TROO0+akMapt1pAg=", "recordedInputs": [ "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", @@ -447,7 +428,7 @@ }, "@@rules_python+//python/uv:uv.bzl%uv": { "general": { - "bzlTransitiveDigest": "ijW9KS7qsIY+yBVvJ+Nr1mzwQox09j13DnE3iIwaeTM=", + "bzlTransitiveDigest": "IgkgxNrtlAec7OnaFrWoCC5NQhHcY/aIz4jsqcNMm8Y=", "usagesDigest": "H8dQoNZcoqP+Mu0tHZTi4KHATzvNkM5ePuEqoQdklIU=", "recordedInputs": [ "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", @@ -476,5 +457,6 @@ } } }, - "facts": {} + "facts": {}, + "factsVersions": {} } diff --git a/README.md b/README.md index 1b3d7ee..2436f77 100644 --- a/README.md +++ b/README.md @@ -913,7 +913,7 @@ int value = resizable->VectorGet(&vec_hdr, 0); // Returns 42 ### TriggerFd -A file descriptor that can be used to trigger events. Implemented as an `eventfd` on Linux, a Unix domain `socketpair` on QNX, and a pipe on other POSIX systems, including macOS. QNX pipes go through a single-threaded pipe service, and a socketpair is slower than a pipe on macOS. +A file descriptor that can be used to trigger events. The mechanism is `TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM`: `TOOLBELT_TRIGGERFD_EVENTFD`, `TOOLBELT_TRIGGERFD_PIPE`, or `TOOLBELT_TRIGGERFD_SOCKETPAIR`. The default is an `eventfd` on Linux, a Unix domain `socketpair` on QNX, and a pipe on other POSIX systems, including macOS. QNX pipes go through a single-threaded pipe service, and a socketpair is slower than a pipe on macOS. Override the default with `-DTOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=...`. **Header:** `toolbelt/triggerfd.h` diff --git a/toolbelt/triggerfd.cc b/toolbelt/triggerfd.cc index 4150551..eadd8c8 100644 --- a/toolbelt/triggerfd.cc +++ b/toolbelt/triggerfd.cc @@ -5,22 +5,62 @@ #include "toolbelt/triggerfd.h" #include "absl/strings/str_format.h" -// Linux has eventfd, which is the cheapest pollable trigger. QNX pipes go -// through a single-threaded pipe service, so QNX uses a Unix domain socketpair. -// Every other POSIX system, including macOS, keeps the pipe. A socketpair is -// slower there, and its read end always reports POLLOUT. #include -#if defined(__linux__) +#if TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_EVENTFD && \ + defined(__linux__) +#define TOOLBELT_TRIGGERFD_USE_EVENTFD 1 #include -#elif defined(__QNX__) || defined(__QNXNTO__) +#elif TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_EVENTFD +#define TOOLBELT_TRIGGERFD_USE_EVENTFD 0 +#error TOOLBELT_TRIGGERFD_EVENTFD is only available on Linux +#elif TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_SOCKETPAIR +#define TOOLBELT_TRIGGERFD_USE_EVENTFD 0 #include #include +#elif TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_PIPE +#define TOOLBELT_TRIGGERFD_USE_EVENTFD 0 +// pipe() is declared in unistd.h. #else -#include +#define TOOLBELT_TRIGGERFD_USE_EVENTFD 0 +#error TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM must be TOOLBELT_TRIGGERFD_EVENTFD, TOOLBELT_TRIGGERFD_PIPE, or TOOLBELT_TRIGGERFD_SOCKETPAIR #endif namespace toolbelt { +#if !TOOLBELT_TRIGGERFD_USE_EVENTFD +// Opens a nonblocking pipe or socketpair. Both ends are owned by the +// FileDescriptors before either is set nonblocking, so a failure cannot leak +// a descriptor. +static absl::Status OpenByteStream(FileDescriptor &poll_fd, + FileDescriptor &trigger_fd) { + int fds[2]; +#if TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_SOCKETPAIR + if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) { + return absl::InternalError(absl::StrFormat( + "Unable to create trigger fd socketpair: %s", strerror(errno))); + } +#else + if (pipe(fds) == -1) { + return absl::InternalError(absl::StrFormat( + "Unable to create trigger fd pipe: %s", strerror(errno))); + } +#endif + poll_fd.SetFd(fds[0]); + trigger_fd.SetFd(fds[1]); + if (absl::Status status = poll_fd.SetNonBlocking(); !status.ok()) { + poll_fd.Close(); + trigger_fd.Close(); + return status; + } + if (absl::Status status = trigger_fd.SetNonBlocking(); !status.ok()) { + poll_fd.Close(); + trigger_fd.Close(); + return status; + } + return absl::OkStatus(); +} +#endif + absl::StatusOr TriggerFd::Create() { TriggerFd t; if (absl::Status status = t.Open(); !status.ok()) { @@ -39,7 +79,7 @@ absl::StatusOr TriggerFd::Create(const FileDescriptor &poll_fd, } absl::Status TriggerFd::Open() { -#if defined(__linux__) +#if TOOLBELT_TRIGGERFD_USE_EVENTFD int fd = eventfd(0, EFD_NONBLOCK); if (fd == -1) { return absl::InternalError(absl::StrFormat( @@ -47,64 +87,37 @@ absl::Status TriggerFd::Open() { } poll_fd_.SetFd(fd); trigger_fd_ = poll_fd_; -#elif defined(__QNX__) || defined(__QNXNTO__) - int fds[2]; - if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to create trigger fd socketpair: %s", strerror(errno))); - } - // Owned immediately so both ends are closed if setting nonblocking fails. - poll_fd_.SetFd(fds[0]); - trigger_fd_.SetFd(fds[1]); - if (absl::Status status = poll_fd_.SetNonBlocking(); !status.ok()) { - return status; - } - if (absl::Status status = trigger_fd_.SetNonBlocking(); !status.ok()) { - return status; - } #else - int pipes[2]; - if (pipe(pipes) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to create trigger fd pipe: %s", strerror(errno))); - } - // Both ends of the pipe are nonblocking. - if (fcntl(pipes[0], F_SETFL, (fcntl(pipes[0], F_GETFL) | O_NONBLOCK)) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to set non-blocking on read pipe: %s", strerror(errno))); - } - if (fcntl(pipes[1], F_SETFL, (fcntl(pipes[1], F_GETFL) | O_NONBLOCK)) == -1) { - return absl::InternalError(absl::StrFormat( - "Unable to set non-blocking on write pipe: %s", strerror(errno))); + if (absl::Status status = OpenByteStream(poll_fd_, trigger_fd_); + !status.ok()) { + return status; } - poll_fd_.SetFd(pipes[0]); // Read end - trigger_fd_.SetFd(pipes[1]); // Write end. #endif return absl::OkStatus(); } void TriggerFd::Trigger() { -#if defined(__linux__) +#if TOOLBELT_TRIGGERFD_USE_EVENTFD // Linux eventfd. Write an 8 byte value to trigger it. int64_t val = 1; (void)::write(trigger_fd_.Fd(), &val, 8); #else - // Pipe, or a socketpair on QNX. Write a single byte to it. + // Pipe or socketpair. Write a single byte to it. char val = 'x'; (void)::write(trigger_fd_.Fd(), &val, 1); #endif } bool TriggerFd::Clear() { -#if defined(__linux__) +#if TOOLBELT_TRIGGERFD_USE_EVENTFD // Linux eventfd, read a single 8 byte value. This will clear the // eventfd. int64_t val; ssize_t n = ::read(poll_fd_.Fd(), &val, 8); return (n > 0); #else - // Pipe, or a socketpair on QNX. Read all pending bytes. The fd is - // nonblocking, so we get EAGAIN once it has been drained. + // Pipe or socketpair. Read all pending bytes. The fd is nonblocking, so + // we get EAGAIN once it has been drained. bool was_triggered = false; for (;;) { char buffer[256]; @@ -119,3 +132,5 @@ bool TriggerFd::Clear() { } } // namespace toolbelt + +#undef TOOLBELT_TRIGGERFD_USE_EVENTFD diff --git a/toolbelt/triggerfd.h b/toolbelt/triggerfd.h index aefced1..49d6384 100644 --- a/toolbelt/triggerfd.h +++ b/toolbelt/triggerfd.h @@ -9,12 +9,36 @@ #include "absl/status/statusor.h" #include "toolbelt/fd.h" +// How a TriggerFd is signaled. +// +// TOOLBELT_TRIGGERFD_EVENTFD Linux eventfd. Linux only. +// TOOLBELT_TRIGGERFD_PIPE Anonymous pipe. +// TOOLBELT_TRIGGERFD_SOCKETPAIR Unix-domain socketpair. +// +// The default is eventfd on Linux, a socketpair on QNX, and a pipe everywhere +// else. QNX pipes go through a single-threaded pipe service. A socketpair is +// slower than a pipe on macOS, and its read end always reports POLLOUT. +// +// Override the default from the build, for example: +// -DTOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=TOOLBELT_TRIGGERFD_SOCKETPAIR +#define TOOLBELT_TRIGGERFD_EVENTFD 1 +#define TOOLBELT_TRIGGERFD_PIPE 2 +#define TOOLBELT_TRIGGERFD_SOCKETPAIR 3 + +#ifndef TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM +#if defined(__linux__) +#define TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM TOOLBELT_TRIGGERFD_EVENTFD +#elif defined(__QNX__) || defined(__QNXNTO__) +#define TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM TOOLBELT_TRIGGERFD_SOCKETPAIR +#else +#define TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM TOOLBELT_TRIGGERFD_PIPE +#endif +#endif + namespace toolbelt { -// A TriggerFd is a file descriptor that can be used to trigger -// an event. If the facility is available, it is implemented -// as an eventfd on Linux, a Unix domain socketpair on QNX, and a pipe -// everywhere else. +// A TriggerFd is a file descriptor that can be used to trigger an event. +// The signaling mechanism is TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM. class TriggerFd { public: TriggerFd() = default; From eaa23f0594f29e7a50bd35de9896ad55af8c89a1 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 15 Nov 2026 10:01:30 -0800 Subject: [PATCH 4/5] Add a trigger_mechanism build setting for TriggerFd. The platform default stays eventfd on Linux, a socketpair on QNX, and a pipe elsewhere. --//toolbelt:trigger_mechanism selects eventfd, pipe, or socketpair when a build needs a different way to wake a waiting subscriber. --- README.md | 2 +- toolbelt/BUILD.bazel | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2436f77..d047234 100644 --- a/README.md +++ b/README.md @@ -913,7 +913,7 @@ int value = resizable->VectorGet(&vec_hdr, 0); // Returns 42 ### TriggerFd -A file descriptor that can be used to trigger events. The mechanism is `TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM`: `TOOLBELT_TRIGGERFD_EVENTFD`, `TOOLBELT_TRIGGERFD_PIPE`, or `TOOLBELT_TRIGGERFD_SOCKETPAIR`. The default is an `eventfd` on Linux, a Unix domain `socketpair` on QNX, and a pipe on other POSIX systems, including macOS. QNX pipes go through a single-threaded pipe service, and a socketpair is slower than a pipe on macOS. Override the default with `-DTOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=...`. +A file descriptor that can be used to trigger events. The mechanism is `TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM`: `TOOLBELT_TRIGGERFD_EVENTFD`, `TOOLBELT_TRIGGERFD_PIPE`, or `TOOLBELT_TRIGGERFD_SOCKETPAIR`. The default is an `eventfd` on Linux, a Unix domain `socketpair` on QNX, and a pipe on other POSIX systems, including macOS. QNX pipes go through a single-threaded pipe service, and a socketpair is slower than a pipe on macOS. Override the default with `-DTOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=TOOLBELT_TRIGGERFD_PIPE` (or `EVENTFD` or `SOCKETPAIR`). With Bazel, `--//toolbelt:trigger_mechanism=pipe`. **Header:** `toolbelt/triggerfd.h` diff --git a/toolbelt/BUILD.bazel b/toolbelt/BUILD.bazel index f4786a9..7021612 100644 --- a/toolbelt/BUILD.bazel +++ b/toolbelt/BUILD.bazel @@ -1,7 +1,39 @@ package(default_visibility = ["//visibility:public"]) +load("@bazel_skylib//rules:common_settings.bzl", "string_flag") load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") +# How a publisher wakes a waiting subscriber. "default" keeps the platform +# choice in triggerfd.h: eventfd on Linux, a socketpair on QNX, and a pipe +# elsewhere. +# +# bazel build --//toolbelt:trigger_mechanism=socketpair //toolbelt:triggerfd_test +string_flag( + name = "trigger_mechanism", + build_setting_default = "default", + values = [ + "default", + "eventfd", + "pipe", + "socketpair", + ], +) + +config_setting( + name = "trigger_mechanism_eventfd", + flag_values = {":trigger_mechanism": "eventfd"}, +) + +config_setting( + name = "trigger_mechanism_pipe", + flag_values = {":trigger_mechanism": "pipe"}, +) + +config_setting( + name = "trigger_mechanism_socketpair", + flag_values = {":trigger_mechanism": "socketpair"}, +) + cc_library( name = "toolbelt", srcs = [ @@ -33,6 +65,12 @@ cc_library( "triggerfd.h", "stacktrace.h", ], + local_defines = select({ + ":trigger_mechanism_eventfd": ["TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=TOOLBELT_TRIGGERFD_EVENTFD"], + ":trigger_mechanism_pipe": ["TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=TOOLBELT_TRIGGERFD_PIPE"], + ":trigger_mechanism_socketpair": ["TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM=TOOLBELT_TRIGGERFD_SOCKETPAIR"], + "//conditions:default": [], + }), deps = [ "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", From a5b1cb994ec301db6023e98cfda71a7262d66bf9 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 15 Nov 2026 13:31:43 -0800 Subject: [PATCH 5/5] Patch coroutines so TSan survives a stack switch on GCC 15 Ubuntu 26.04's GCC still emits TSan function entry and exit hooks in functions that switch coroutine stacks. The hook then writes off the shadow stack and pipe_test and sockets_test die in gtest teardown. Apply the dallison/co fix from c2cbd0f onto the pinned 3.4.1 commit. --- MODULE.bazel | 5 +++ third_party/BUILD.bazel | 1 + third_party/coroutines_tsan.patch | 70 +++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 third_party/BUILD.bazel create mode 100644 third_party/coroutines_tsan.patch diff --git a/MODULE.bazel b/MODULE.bazel index 8cb6e49..a7da97c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -19,5 +19,10 @@ git_override( module_name = "coroutines", commit = "f4bcdffa67315d9aefaed6a802731263c0e0c19b", remote = "https://github.com/dallison/co.git", + # GCC 15 still emits TSan function entry/exit hooks around a stack switch, + # which corrupts the shadow stack (Ubuntu 26.04 CI). This is the fix from + # dallison/co c2cbd0f, applied onto the pinned 3.4.1 commit. + patches = ["//third_party:coroutines_tsan.patch"], + patch_strip = 1, ) diff --git a/third_party/BUILD.bazel b/third_party/BUILD.bazel new file mode 100644 index 0000000..847a060 --- /dev/null +++ b/third_party/BUILD.bazel @@ -0,0 +1 @@ +exports_files(["coroutines_tsan.patch"]) diff --git a/third_party/coroutines_tsan.patch b/third_party/coroutines_tsan.patch new file mode 100644 index 0000000..0fb2330 --- /dev/null +++ b/third_party/coroutines_tsan.patch @@ -0,0 +1,70 @@ +diff --git a/co/detect_sanitizers.h b/co/detect_sanitizers.h +--- a/co/detect_sanitizers.h ++++ b/co/detect_sanitizers.h +@@ -54,7 +54,19 @@ + + #ifdef CO_THREAD_SANITIZER + #ifndef CO_DISABLE_THREAD_SANITIZER ++#if defined(__has_attribute) ++#if __has_attribute(disable_sanitizer_instrumentation) ++// Clang's no_sanitize("thread") still emits TSan function entry/exit hooks. ++// Those hooks cannot span a stack switch, so suppress all sanitizer ++// instrumentation in functions that perform one. ++#define CO_DISABLE_THREAD_SANITIZER \ ++ __attribute__((disable_sanitizer_instrumentation)) ++#else + #define CO_DISABLE_THREAD_SANITIZER __attribute__((no_sanitize("thread"))) ++#endif ++#else ++#define CO_DISABLE_THREAD_SANITIZER __attribute__((no_sanitize("thread"))) ++#endif + #endif // CO_DISABLE_THREAD_SANITIZER + #else + #define CO_DISABLE_THREAD_SANITIZER +diff --git a/co/coroutine.cc b/co/coroutine.cc +--- a/co/coroutine.cc ++++ b/co/coroutine.cc +@@ -509,6 +509,7 @@ + state_ = state; + } + ++CO_DISABLE_THREAD_SANITIZER + void Coroutine::Exit() const { + // Tell TSan we are leaving the coroutine fiber and returning to the + // scheduler before we actually switch stacks. +@@ -897,6 +898,7 @@ + } + } + ++CO_DISABLE_THREAD_SANITIZER + void Coroutine::InvokeFunction() { + try { + function_(*this); +@@ -907,15 +909,10 @@ + __sanitizer_finish_switch_fiber(nullptr, nullptr, nullptr); + #endif + // The coroutine body has returned; the assembly trampoline (or the +- // ucontext uc_link/getcontext+setcontext path) is about to longjmp/setcontext +- // back to the scheduler. Tell TSan we are switching fibers before that +- // happens. We use the no-sync flag because there is nothing the scheduler +- // can synchronize with on a dying coroutine. +-#if defined(CO_THREAD_SANITIZER) +- if (scheduler_.tsan_fiber_ != nullptr) { +- __tsan_switch_to_fiber(scheduler_.tsan_fiber_, 0); +- } +-#endif ++ // ucontext uc_link/getcontext+setcontext path) is about to switch back to ++ // the scheduler. This function and __co_Invoke must not have TSan ++ // entry/exit hooks because they return after changing fibers. ++ CO_TSAN_SWITCH_TO_FIBER(scheduler_.tsan_fiber_); + } + + // We use an intermediate function to do the invocation of +@@ -924,6 +921,7 @@ + // the Resume function. A new compiler might change the + // name mangling rules and that would break the build. + extern "C" { ++CO_DISABLE_THREAD_SANITIZER + void __co_Invoke(Coroutine *c) { c->InvokeFunction(); } + } +