From 5deadc6eaede3d32ccdd68529f371092d4d218da Mon Sep 17 00:00:00 2001 From: Vitaly Buka Date: Thu, 10 Oct 2024 14:52:50 -0700 Subject: [PATCH] [NFC][sanitizer] Extract `LoadStatus` (#111909) For #111901 --- .../lib/sanitizer_common/sanitizer_linux.cpp | 21 +++++++++++++------ .../lib/sanitizer_common/sanitizer_linux.h | 1 + 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp index e5d6d0a6e716..a4e58133c79f 100644 --- a/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp +++ b/compiler-rt/lib/sanitizer_common/sanitizer_linux.cpp @@ -1042,8 +1042,6 @@ ThreadLister::Result ThreadLister::ListThreads( Result result = Ok; for (bool first_read = true;; first_read = false) { - // Resize to max capacity if it was downsized by IsAlive. - buffer_.resize(buffer_.capacity()); CHECK_GE(buffer_.size(), 4096); uptr read = internal_getdents( descriptor, (struct linux_dirent *)buffer_.data(), buffer_.size()); @@ -1088,14 +1086,25 @@ ThreadLister::Result ThreadLister::ListThreads( } } +const char *ThreadLister::LoadStatus(int tid) { + auto cleanup = at_scope_exit([&] { + // Resize back to capacity if it is downsized by `ReadFileToVector`. + buffer_.resize(buffer_.capacity()); + }); + if (!ReadFileToVector(status_path_.data(), &buffer_) || buffer_.empty()) + return nullptr; + buffer_.push_back('\0'); + return buffer_.data(); +} + bool ThreadLister::IsAlive(int tid) { // /proc/%d/task/%d/status uses same call to detect alive threads as // proc_task_readdir. See task_state implementation in Linux. - if (!ReadFileToVector(status_path_.data(), &buffer_) || buffer_.empty()) - return false; - buffer_.push_back(0); static const char kPrefix[] = "\nPPid:"; - const char *field = internal_strstr(buffer_.data(), kPrefix); + const char *status = LoadStatus(tid); + if (!status) + return false; + const char *field = internal_strstr(status, kPrefix); if (!field) return false; field += internal_strlen(kPrefix); diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_linux.h b/compiler-rt/lib/sanitizer_common/sanitizer_linux.h index 96c617822b5b..07d9528813b3 100644 --- a/compiler-rt/lib/sanitizer_common/sanitizer_linux.h +++ b/compiler-rt/lib/sanitizer_common/sanitizer_linux.h @@ -103,6 +103,7 @@ class ThreadLister { Ok, }; Result ListThreads(InternalMmapVector *threads); + const char *LoadStatus(int tid); private: bool IsAlive(int tid);