Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

36 changes: 9 additions & 27 deletions MODULE.bazel.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ int value = resizable->VectorGet<int>(&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. 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`

Expand Down
1 change: 1 addition & 0 deletions third_party/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports_files(["coroutines_tsan.patch"])
70 changes: 70 additions & 0 deletions third_party/coroutines_tsan.patch
Original file line number Diff line number Diff line change
@@ -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(); }
}

50 changes: 50 additions & 0 deletions toolbelt/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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 = [
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -81,6 +119,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",
Expand Down
85 changes: 61 additions & 24 deletions toolbelt/triggerfd.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,62 @@
#include "toolbelt/triggerfd.h"
#include "absl/strings/str_format.h"

#if defined(__linux__)
#include <unistd.h>
#if TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_EVENTFD && \
defined(__linux__)
#define TOOLBELT_TRIGGERFD_USE_EVENTFD 1
#include <sys/eventfd.h>
#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 <sys/socket.h>
#include <sys/types.h>
#elif TOOLBELT_TRIGGERFD_SIGNAL_MECHANISM == TOOLBELT_TRIGGERFD_PIPE
#define TOOLBELT_TRIGGERFD_USE_EVENTFD 0
// pipe() is declared in unistd.h.
#else
#include <fcntl.h>
#include <unistd.h>
#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> TriggerFd::Create() {
TriggerFd t;
if (absl::Status status = t.Open(); !status.ok()) {
Expand All @@ -32,7 +79,7 @@ absl::StatusOr<TriggerFd> 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(
Expand All @@ -41,48 +88,36 @@ absl::Status TriggerFd::Open() {
poll_fd_.SetFd(fd);
trigger_fd_ = poll_fd_;
#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. 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. Read all bytes from the pipe. The pipe is nonblocking so we will
// get an EAGAIN when we've cleared it.
// 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];
Expand All @@ -97,3 +132,5 @@ bool TriggerFd::Clear() {
}

} // namespace toolbelt

#undef TOOLBELT_TRIGGERFD_USE_EVENTFD
Loading
Loading