strawberry/include/strawberry/proc_read.hpp
trvon 6628ea9aea
Harden against crashes and I/O faults
Fix for the 2026-10-25 host freeze (an uncaught iostream exception on a
/proc read aborted the daemon; its core dump deadlocked with the exec
guard): non-throwing /proc reads, crash handlers that release fanotify
permission fds, guarded thread entries, from_chars parsing.

Adds the io fault-injection seam with property tests, source invariant
checks (R1-R6) with self-test fixtures, libFuzzer targets and seeds
(including I/O-fault fuzzing), the fold changed-files scan scripts and
the agent workflow docs (CLAUDE.md, prompts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:17:17 -06:00

57 lines
1.9 KiB
C++

#ifndef STRAWBERRY_PROC_READ_HPP
#define STRAWBERRY_PROC_READ_HPP
// Non-throwing, bounded reads of small text files (/proc, /sys, config).
//
// Never read /proc with iostreams: when the process exits mid-read the read
// fails with ESRCH and libstdc++ throws std::ios_base::failure from the stream
// buffer (std::istreambuf_iterator does not catch it). On 2026-10-25 that
// uncaught exception aborted the daemon, and the core dump then deadlocked
// with the exec guard and froze the host.
#include <cerrno>
#include <cstddef>
#include <optional>
#include <string>
#include "strawberry/sys_io.hpp"
namespace strawberry {
/// Whole file up to `max_bytes` (truncated beyond). nullopt if it cannot be
/// opened or a read fails (e.g. the process exited: ESRCH).
inline std::optional<std::string> read_small_file(const std::string& path, std::size_t max_bytes = 1u << 20) {
const int fd = io::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOCTTY);
if (fd < 0) {
return std::nullopt;
}
std::string out;
char buffer[8192];
int interrupted = 0;
while (out.size() < max_bytes) {
const ssize_t n = io::read(fd, buffer, sizeof(buffer));
if (n < 0) {
if (errno == EINTR && ++interrupted < io::kMaxEintrRetries) {
continue;
}
io::close(fd);
return std::nullopt;
}
if (n == 0) {
break;
}
out.append(buffer, static_cast<std::size_t>(n) < max_bytes - out.size() ? static_cast<std::size_t>(n)
: max_bytes - out.size());
}
io::close(fd);
return out;
}
/// Same, empty string on any failure.
inline std::string read_small_file_or_empty(const std::string& path, std::size_t max_bytes = 1u << 20) {
return read_small_file(path, max_bytes).value_or(std::string{});
}
} // namespace strawberry
#endif // STRAWBERRY_PROC_READ_HPP