| // Copyright 2023 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| #include <dirent.h> | |
| #include <elf.h> | |
| #include <fcntl.h> | |
| #include <grp.h> | |
| #include <lib/fit/defer.h> | |
| #include <sched.h> | |
| #include <sys/epoll.h> | |
| #include <sys/eventfd.h> | |
| #include <sys/fsuid.h> | |
| #include <sys/inotify.h> | |
| #include <sys/mount.h> | |
| #include <sys/prctl.h> | |
| #include <sys/resource.h> | |
| #include <sys/signalfd.h> | |
| #include <sys/socket.h> | |
| #include <sys/stat.h> | |
| #include <sys/syscall.h> | |
| #include <sys/timerfd.h> | |
| #include <sys/wait.h> | |
| #include <unistd.h> | |
| #include <algorithm> | |
| #include <atomic> | |
| #include <cinttypes> | |
| #include <cstdlib> | |
| #include <cstring> | |
| #include <format> | |
| #include <map> | |
| #include <optional> | |
| #include <sstream> | |
| #include <string> | |
| #include <string_view> | |
| #include <thread> | |
| #include <vector> | |
| #include <fbl/unique_fd.h> | |
| #include <gtest/gtest.h> | |
| #include <linux/capability.h> | |
| #include <linux/perf_event.h> | |
| #include "src/lib/files/directory.h" | |
| #include "src/lib/files/file.h" | |
| #include "src/lib/files/path.h" | |
| #include "src/lib/fxl/strings/string_printf.h" | |
| #include "src/starnix/tests/syscalls/cpp/capabilities_helper.h" | |
| #include "src/starnix/tests/syscalls/cpp/proc_test_base.h" | |
| #include "src/starnix/tests/syscalls/cpp/syscall_matchers.h" | |
| #include "src/starnix/tests/syscalls/cpp/test_helper.h" | |
| namespace { | |
| using testing::AnyOf; | |
| using testing::ContainsRegex; | |
| using testing::Eq; | |
| /// Check if the procfs status file shows the correct fsuid number. | |
| void AssertFsuidInProcfsStatus(uid_t fsuid) { | |
| std::string status_string; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/status", &status_string)); | |
| ASSERT_THAT(status_string, | |
| testing::ContainsRegex(std::format("Uid:\t[0-9]+\t[0-9]+\t[0-9]+\t{}\n", fsuid))); | |
| } | |
| std::string GetExecChildBinaryPath() { | |
| return test_helper::GetTestResourcePath("procfs_test_exec_child"); | |
| } | |
| class ProcUptimeTest : public ProcTestBase { | |
| protected: | |
| void SetUp() override { | |
| ProcTestBase::SetUp(); | |
| Open(); | |
| } | |
| void Close() { fd_.reset(); } | |
| void Open() { | |
| std::string path = proc_path() + "/uptime"; | |
| fd_.reset(open(path.c_str(), O_RDONLY)); | |
| ASSERT_TRUE(fd_.is_valid()); | |
| } | |
| double Parse(const char* buf) { | |
| double uptime, idle; | |
| int s = sscanf(buf, "%lf %lf\n", &uptime, &idle); | |
| EXPECT_EQ(s, 2); | |
| // On Linux `idle` value may decrease, i.e. we cannot expect it to | |
| // increase with `uptime` (see https://fxbug.dev/42080772). Ignore it. | |
| return uptime; | |
| } | |
| double Read() { | |
| char buf[100]; | |
| long r = read(fd_.get(), buf, sizeof(buf)); | |
| EXPECT_GT(r, 0); | |
| return Parse(buf); | |
| } | |
| ~ProcUptimeTest() override { Close(); } | |
| fbl::unique_fd fd_; | |
| }; | |
| TEST_F(ProcUptimeTest, UptimeRead) { Read(); } | |
| TEST_F(ProcUptimeTest, UptimeProgressReopen) { | |
| auto v1 = Read(); | |
| Close(); | |
| sleep(1); | |
| Open(); | |
| auto v2 = Read(); | |
| EXPECT_GT(v2, v1); | |
| } | |
| // Verify that the reported value is updated after seeking /proc/uptime to the beginning. | |
| TEST_F(ProcUptimeTest, UptimeProgressSeek) { | |
| auto v1 = Read(); | |
| off_t pos = lseek(fd_.get(), 0, SEEK_SET); | |
| ASSERT_EQ(pos, 0); | |
| sleep(1); | |
| auto v2 = Read(); | |
| EXPECT_GT(v2, v1); | |
| } | |
| // Verify that a valid value is produced even when reading by single char. | |
| TEST_F(ProcUptimeTest, UptimeByChar) { | |
| auto v1 = Read(); | |
| Open(); | |
| std::string buf; | |
| char c; | |
| ssize_t r = read(fd_.get(), &c, 1); | |
| ASSERT_EQ(r, 1); | |
| buf.push_back(c); | |
| // Keep the FD, and then read from a new FD. | |
| fbl::unique_fd old_fd = std::move(fd_); | |
| Open(); | |
| auto v2 = Read(); | |
| // Wait for a bit and then read the old FD to the end. | |
| sleep(1); | |
| while ((r = read(old_fd.get(), &c, 1)) == 1) { | |
| buf.push_back(c); | |
| } | |
| auto v3 = Parse(buf.c_str()); | |
| // `v3` should be between `v1` and `v2`. | |
| EXPECT_LE(v1, v3); | |
| EXPECT_LE(v3, v2); | |
| } | |
| struct Loadavg { | |
| double load1 = 0; | |
| double load5 = 0; | |
| double load15 = 0; | |
| uint64_t runnable = 0; | |
| uint64_t existing = 0; | |
| pid_t last_pid = 0; | |
| }; | |
| class ProcLoadavgTest : public ProcTestBase { | |
| protected: | |
| Loadavg ReadLoadavg() { | |
| std::string contents; | |
| EXPECT_TRUE(files::ReadFileToString(proc_path() + "/loadavg", &contents)) << strerror(errno); | |
| Loadavg result; | |
| int consumed = 0; | |
| EXPECT_EQ(sscanf(contents.c_str(), "%lf %lf %lf %" SCNu64 "/%" SCNu64 " %d\n%n", &result.load1, | |
| &result.load5, &result.load15, &result.runnable, &result.existing, | |
| &result.last_pid, &consumed), | |
| 6) | |
| << contents; | |
| EXPECT_EQ(static_cast<size_t>(consumed), contents.size()) << contents; | |
| EXPECT_GE(result.load1, 0.0); | |
| EXPECT_GE(result.load5, 0.0); | |
| EXPECT_GE(result.load15, 0.0); | |
| EXPECT_GE(result.runnable, 1u); | |
| EXPECT_GE(result.existing, result.runnable); | |
| EXPECT_GT(result.last_pid, 0); | |
| return result; | |
| } | |
| }; | |
| TEST_F(ProcLoadavgTest, ReadFormat) { ReadLoadavg(); } | |
| TEST_F(ProcLoadavgTest, TaskCountTracksProcessesAndThreads) { | |
| if (!test_helper::IsStarnix()) { | |
| GTEST_SKIP() | |
| << "Deterministic /proc/loadavg task accounting requires an isolated Starnix kernel"; | |
| } | |
| constexpr size_t kNumChildren = 3; | |
| constexpr size_t kNumThreads = 3; | |
| const Loadavg before = ReadLoadavg(); | |
| int child_ready_pipe[2]; | |
| int child_exit_pipe[2]; | |
| ASSERT_THAT(pipe2(child_ready_pipe, O_CLOEXEC), SyscallSucceeds()); | |
| ASSERT_THAT(pipe2(child_exit_pipe, O_CLOEXEC), SyscallSucceeds()); | |
| fbl::unique_fd child_ready_read(child_ready_pipe[0]); | |
| fbl::unique_fd child_ready_write(child_ready_pipe[1]); | |
| fbl::unique_fd child_exit_read(child_exit_pipe[0]); | |
| fbl::unique_fd child_exit_write(child_exit_pipe[1]); | |
| std::vector<pid_t> child_pids; | |
| auto cleanup_children = fit::defer([&] { | |
| child_exit_write.reset(); | |
| for (pid_t pid : child_pids) { | |
| kill(pid, SIGKILL); | |
| waitpid(pid, nullptr, 0); | |
| } | |
| }); | |
| for (size_t i = 0; i < kNumChildren; ++i) { | |
| pid_t pid = fork(); | |
| ASSERT_GE(pid, 0) << strerror(errno); | |
| if (pid == 0) { | |
| child_ready_read.reset(); | |
| child_exit_write.reset(); | |
| char byte = 'r'; | |
| if (write(child_ready_write.get(), &byte, 1) != 1) { | |
| _exit(1); | |
| } | |
| child_ready_write.reset(); | |
| if (read(child_exit_read.get(), &byte, 1) < 0) { | |
| _exit(2); | |
| } | |
| _exit(0); | |
| } | |
| child_pids.push_back(pid); | |
| } | |
| child_ready_write.reset(); | |
| child_exit_read.reset(); | |
| for (size_t i = 0; i < kNumChildren; ++i) { | |
| char byte = 0; | |
| ASSERT_EQ(read(child_ready_read.get(), &byte, 1), 1) << strerror(errno); | |
| } | |
| // Each single-threaded child process adds exactly one task (its thread-group leader). | |
| const Loadavg with_children = ReadLoadavg(); | |
| EXPECT_EQ(with_children.existing, before.existing + kNumChildren); | |
| EXPECT_GE(with_children.last_pid, child_pids.back()); | |
| int thread_ready_pipe[2]; | |
| int thread_exit_pipe[2]; | |
| ASSERT_THAT(pipe2(thread_ready_pipe, O_CLOEXEC), SyscallSucceeds()); | |
| ASSERT_THAT(pipe2(thread_exit_pipe, O_CLOEXEC), SyscallSucceeds()); | |
| fbl::unique_fd thread_ready_read(thread_ready_pipe[0]); | |
| fbl::unique_fd thread_ready_write(thread_ready_pipe[1]); | |
| fbl::unique_fd thread_exit_read(thread_exit_pipe[0]); | |
| fbl::unique_fd thread_exit_write(thread_exit_pipe[1]); | |
| std::vector<std::thread> threads; | |
| std::vector<pid_t> thread_tids(kNumThreads, 0); | |
| auto cleanup_threads = fit::defer([&] { | |
| thread_exit_write.reset(); | |
| for (std::thread& t : threads) { | |
| if (t.joinable()) { | |
| t.join(); | |
| } | |
| } | |
| }); | |
| for (size_t i = 0; i < kNumThreads; ++i) { | |
| threads.emplace_back([&, i] { | |
| thread_tids[i] = static_cast<pid_t>(syscall(SYS_gettid)); | |
| char byte = 't'; | |
| SAFE_SYSCALL(write(thread_ready_write.get(), &byte, 1)); | |
| SAFE_SYSCALL(read(thread_exit_read.get(), &byte, 1)); | |
| }); | |
| } | |
| for (size_t i = 0; i < kNumThreads; ++i) { | |
| char byte = 0; | |
| ASSERT_EQ(read(thread_ready_read.get(), &byte, 1), 1) << strerror(errno); | |
| } | |
| const Loadavg with_threads = ReadLoadavg(); | |
| EXPECT_EQ(with_threads.existing, with_children.existing + kNumThreads); | |
| cleanup_threads.call(); | |
| for (pid_t tid : thread_tids) { | |
| std::string tid_dir = fxl::StringPrintf("%s/self/task/%d", proc_path().c_str(), tid); | |
| while (access(tid_dir.c_str(), F_OK) == 0) { | |
| usleep(1000); | |
| } | |
| } | |
| const Loadavg after_threads = ReadLoadavg(); | |
| EXPECT_EQ(after_threads.existing, with_children.existing); | |
| child_exit_write.reset(); | |
| for (pid_t pid : child_pids) { | |
| int status = 0; | |
| ASSERT_THAT(waitpid(pid, &status, 0), SyscallSucceeds()); | |
| EXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0) << status; | |
| } | |
| child_pids.clear(); | |
| cleanup_children.cancel(); | |
| const Loadavg after_children = ReadLoadavg(); | |
| EXPECT_EQ(after_children.existing, before.existing); | |
| } | |
| class ProcSysNetTest : public ProcTestBase, | |
| public ::testing::WithParamInterface<std::tuple<const char*, const char*>> { | |
| protected: | |
| void SetUp() override { | |
| ProcTestBase::SetUp(); | |
| // Required to open the path below for writing. | |
| // TODO(https://fxbug.dev/317285180) don't skip on baseline | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| auto const& [dev, path_fmt] = GetParam(); | |
| char buf[100] = {}; | |
| sprintf(buf, path_fmt, dev); | |
| std::string path = proc_path() + "/sys/net" + buf; | |
| fd_.reset(open(path.c_str(), O_RDWR)); | |
| ASSERT_TRUE(fd_.is_valid()) << "path: " + path + "; " + strerror(errno); | |
| } | |
| fbl::unique_fd fd_; | |
| }; | |
| TEST_P(ProcSysNetTest, Write) { | |
| // Notably does not include a null terminator, which the kernel will reject. | |
| const char kWriteBuf[] = {'1'}; | |
| ssize_t n = write(fd_.get(), kWriteBuf, sizeof(kWriteBuf)); | |
| ASSERT_EQ(n, static_cast<ssize_t>(sizeof(kWriteBuf))) << "Failed to write: " << strerror(errno); | |
| } | |
| INSTANTIATE_TEST_SUITE_P( | |
| ProcSysNetTest, ProcSysNetTest, | |
| ::testing::Combine( | |
| ::testing::Values("all", "default"), | |
| ::testing::Values("/ipv4/neigh/%s/ucast_solicit", "/ipv4/neigh/%s/retrans_time_ms", | |
| "/ipv4/neigh/%s/mcast_resolicit", "/ipv6/conf/%s/accept_ra", | |
| "/ipv6/conf/%s/dad_transmits", "/ipv6/conf/%s/use_tempaddr", | |
| "/ipv6/conf/%s/addr_gen_mode", "/ipv6/conf/%s/stable_secret", | |
| "/ipv6/conf/%s/disable_ipv6", "/ipv6/neigh/%s/ucast_solicit", | |
| "/ipv6/neigh/%s/retrans_time_ms", "/ipv6/neigh/%s/mcast_resolicit"))); | |
| using ProcTest = ProcTestBase; | |
| // Test that after forking without execing, /proc/self/cmdline still works. | |
| TEST_F(ProcTest, CmdlineAfterFork) { | |
| char cmdline[100]; | |
| int cmdline_fd = open("/proc/self/cmdline", O_RDONLY); | |
| ASSERT_GT(cmdline_fd, 0) << strerror(errno); | |
| ssize_t cmdline_len = read(cmdline_fd, cmdline, sizeof(cmdline)); | |
| ASSERT_GT(cmdline_len, 0) << strerror(errno); | |
| close(cmdline_fd); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| char child_cmdline[100]; | |
| int cmdline_fd = open("/proc/self/cmdline", O_RDONLY); | |
| ASSERT_GT(cmdline_fd, 0) << strerror(errno); | |
| ssize_t child_cmdline_len = read(cmdline_fd, child_cmdline, sizeof(child_cmdline)); | |
| ASSERT_GT(child_cmdline_len, 0) << strerror(errno); | |
| close(cmdline_fd); | |
| ASSERT_EQ(cmdline_len, child_cmdline_len); | |
| ASSERT_TRUE(memcmp(cmdline, child_cmdline, cmdline_len) == 0); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| class ProcTaskDirTest : public ProcTestBase { | |
| protected: | |
| void SetUp() override { ProcTestBase::SetUp(); } | |
| }; | |
| bool ends_with(const std::string& haystack, const std::string needle) { | |
| return haystack.rfind(needle) == (haystack.size() - needle.size()); | |
| } | |
| std::string ProcSelfDirName() { | |
| std::string proc_self = fxl::StringPrintf("/proc/%d", getpid()); | |
| struct stat statbuf; | |
| SAFE_SYSCALL(stat(proc_self.c_str(), &statbuf)); | |
| return proc_self; | |
| } | |
| // Ensure that entries in /proc/pid/. have the correct ownership. proc(2) says | |
| // that entries are owned by the effective uid of the task. This doesn't seem to | |
| // be exactly what Linux does - Linux seems to assign most directories to the | |
| // euid, and everything else to the real id - but it's not clear exactly what | |
| // Linux is doing from looking at its behavior, so we hew to the man page. | |
| // | |
| // This test ensures that the proc directories *are* set to be owned by the euid | |
| // of the task. | |
| TEST_F(ProcTaskDirTest, PidDirCorrectUidIsEuid) { | |
| // TODO(https://fxbug.dev/317285180) don't skip on baseline | |
| if (!test_helper::HasSysAdmin() || !test_helper::IsStarnix()) { | |
| GTEST_SKIP() << "PidDirCorrectUid requires root access (to change euid), " | |
| << "and currently only works on Starnix"; | |
| } | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([] { | |
| std::string proc_path = ProcSelfDirName(); | |
| int dirfd; | |
| struct stat pre_stat; | |
| struct stat euid_stat; | |
| // Get the original (presumably real) ownership | |
| ASSERT_NE(-1, dirfd = open(proc_path.c_str(), O_RDONLY)) | |
| << "Error trying to open " << proc_path << ": " << strerror(errno); | |
| SAFE_SYSCALL(fstat(dirfd, &pre_stat)); | |
| SAFE_SYSCALL(close(dirfd)); | |
| // Set the effective uid. | |
| uid_t newuid = geteuid() + 1; | |
| SAFE_SYSCALL(seteuid(newuid)); | |
| // From proc(5): The files inside each /proc/pid directory are normally | |
| // owned by the effective user and effective group ID of the process. | |
| // However, as a security measure, the ownership is made root:root | |
| // if the process's "dumpable" attribute is set to a value other than 1. | |
| SAFE_SYSCALL(prctl(PR_SET_DUMPABLE, 1)); | |
| // Make sure the effective uid appears to own /proc/self. | |
| SAFE_SYSCALL(dirfd = open(proc_path.c_str(), O_RDONLY)); | |
| SAFE_SYSCALL(fstat(dirfd, &euid_stat)); | |
| SAFE_SYSCALL(close(dirfd)); | |
| EXPECT_EQ(euid_stat.st_uid, newuid) | |
| << "owner for " << proc_path << " did not change to correct value"; | |
| std::vector<std::string> dirs; | |
| files::ReadDirContents(proc_path, &dirs); | |
| for (const auto& entry : dirs) { | |
| if ((entry == ".") || (entry == "..")) { | |
| continue; | |
| } | |
| struct stat info; | |
| auto fname = | |
| (entry[0] == '/') ? entry : fxl::StringPrintf("%s/%s", proc_path.c_str(), entry.c_str()); | |
| ASSERT_NE(-1, stat(fname.c_str(), &info)) | |
| << "Error reading " << fname << ": " << strerror(errno); | |
| // Links to other parts of the fs have their original ownership. S_ISLNK does | |
| // not currently work on these files. See https://fxbug.dev/331990255. | |
| if (ends_with(fname, "/cwd") || ends_with(fname, "/root") || ends_with(fname, "/exe")) { | |
| continue; | |
| } | |
| EXPECT_EQ(info.st_uid, euid_stat.st_uid) << "Wrong owner for file " << fname; | |
| } | |
| }); | |
| } | |
| // This test ensures that the proc directories aren't set to be owned by the | |
| // fsuid of the task. This is separate from PidDirCorrectUidIsEuid because | |
| // setting the euid implicitly sets the fsuid. We want to check we're not | |
| // accidentally relying on the fsuid. | |
| TEST_F(ProcTaskDirTest, PidDirSetFsuidDoesntChangeOwnership) { | |
| // TODO(https://fxbug.dev/317285180) don't skip on baseline | |
| if (!test_helper::HasSysAdmin() || !test_helper::IsStarnix()) { | |
| GTEST_SKIP() << "PidDirCorrectUid requires root access (to change euid), " | |
| << "and currently only works on Starnix"; | |
| } | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([] { | |
| std::string proc_path = ProcSelfDirName(); | |
| int dirfd; | |
| struct stat pre_stat; | |
| struct stat fsuid_stat; | |
| uid_t newuid; | |
| // Get the original (presumably real) ownership | |
| ASSERT_NE(-1, dirfd = open(proc_path.c_str(), O_RDONLY)) | |
| << "Error trying to open " << proc_path << ": " << strerror(errno); | |
| SAFE_SYSCALL(fstat(dirfd, &pre_stat)); | |
| SAFE_SYSCALL(close(dirfd)); | |
| // Set the fsuid. | |
| newuid = pre_stat.st_uid + 1; | |
| ASSERT_EQ(static_cast<const int>(pre_stat.st_uid), setfsuid(newuid)) << "Unexpected fsuid"; | |
| // This is how you check to see if a call to setfsuid worked correctly. | |
| ASSERT_EQ(static_cast<const int>(newuid), setfsuid(-1)) << "setfsuid not supported"; | |
| AssertFsuidInProcfsStatus(newuid); | |
| // Make sure that the current owner has *not* changed to the fsuid | |
| SAFE_SYSCALL(dirfd = open(proc_path.c_str(), O_RDONLY)); | |
| SAFE_SYSCALL(fstat(dirfd, &fsuid_stat)); | |
| SAFE_SYSCALL(close(dirfd)); | |
| EXPECT_NE(fsuid_stat.st_uid, newuid) << "fsuid seen to change incorrectly"; | |
| // Revert the fsuid | |
| ASSERT_EQ(static_cast<const int>(newuid), setfsuid(pre_stat.st_uid)); | |
| AssertFsuidInProcfsStatus(pre_stat.st_uid); | |
| }); | |
| } | |
| class ProcPidOwnerTest : public ProcTestBase { | |
| protected: | |
| static constexpr uid_t kRealUid = 1000; | |
| static constexpr gid_t kRealGid = 1001; | |
| static constexpr uid_t kEffectiveUid = 2000; | |
| static constexpr gid_t kEffectiveGid = 2001; | |
| static constexpr uid_t kFsUid = 3000; | |
| static constexpr gid_t kFsGid = 3001; | |
| void SetUp() override { | |
| ProcTestBase::SetUp(); | |
| if (!CanSetDistinctCreds()) { | |
| GTEST_SKIP() << "Requires root with CAP_SETUID, CAP_SETGID, CAP_DAC_OVERRIDE, and " | |
| "CAP_DAC_READ_SEARCH"; | |
| } | |
| } | |
| static bool CanSetDistinctCreds() { | |
| return geteuid() == 0 && getegid() == 0 && test_helper::HasCapability(CAP_SETUID) && | |
| test_helper::HasCapability(CAP_SETGID) && test_helper::HasCapability(CAP_DAC_OVERRIDE) && | |
| test_helper::HasCapability(CAP_DAC_READ_SEARCH); | |
| } | |
| // Gives the calling process distinct real (1000:1001), effective (2000:2001), and filesystem | |
| // (3000:3001) IDs so tests can tell which IDs own /proc/<pid> entries. Retains | |
| // CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH so filesystem ID 3000 can still traverse 0500 fd | |
| // and fdinfo directories owned by effective ID 2000, and marks the process dumpable so proc(5) | |
| // keeps its /proc/<pid> entries owned by the effective IDs rather than root:root. | |
| static void SetDistinctCreds() { | |
| ASSERT_THAT(prctl(PR_SET_KEEPCAPS, 1), SyscallSucceeds()); | |
| ASSERT_THAT(setgroups(0, nullptr), SyscallSucceeds()); | |
| // setresgid/setresuid set real, effective, and saved IDs, and always reset fsgid/fsuid to | |
| // egid/euid. Pass kFsGid/kFsUid as the saved IDs so the unprivileged setfsgid/setfsuid calls | |
| // below are allowed; setfsgid/setfsuid are the only syscalls that can make fsgid != egid and | |
| // fsuid != euid. | |
| ASSERT_THAT(setresgid(kRealGid, kEffectiveGid, kFsGid), SyscallSucceeds()); | |
| ASSERT_THAT(setresuid(kRealUid, kEffectiveUid, kFsUid), SyscallSucceeds()); | |
| ASSERT_EQ(setfsgid(kFsGid), static_cast<int>(kEffectiveGid)); | |
| ASSERT_EQ(setfsgid(-1), static_cast<int>(kFsGid)); | |
| ASSERT_EQ(setfsuid(kFsUid), static_cast<int>(kEffectiveUid)); | |
| ASSERT_EQ(setfsuid(-1), static_cast<int>(kFsUid)); | |
| test_helper::SetCapabilityEffective(CAP_DAC_OVERRIDE); | |
| test_helper::SetCapabilityEffective(CAP_DAC_READ_SEARCH); | |
| ASSERT_THAT(prctl(PR_SET_DUMPABLE, 1), SyscallSucceeds()); | |
| } | |
| test_helper::ForkHelper fork_helper_; | |
| }; | |
| TEST_F(ProcPidOwnerTest, TaskListDirOwnerRefreshesOnStat) { | |
| fork_helper_.RunInForkedProcess([] { | |
| fbl::unique_fd task_dir(open("/proc/self/task", O_RDONLY | O_DIRECTORY)); | |
| ASSERT_THAT(task_dir.get(), SyscallSucceeds()); | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| // Keep `task_dir` open so `/proc/self/task` resolves to the existing directory entry rather | |
| // than creating a new one, and use path-based `stat` because `fstat(task_dir.get(), ...)` does | |
| // not refresh `/proc/<pid>/task`'s owner on Linux. | |
| struct stat st{}; | |
| ASSERT_THAT(stat("/proc/self/task", &st), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, TidDirOwnerRefreshesOnStat) { | |
| fork_helper_.RunInForkedProcess([] { | |
| long tid = syscall(SYS_gettid); | |
| ASSERT_THAT(tid, SyscallSucceeds()); | |
| std::string tid_path = fxl::StringPrintf("/proc/self/task/%ld", tid); | |
| fbl::unique_fd tid_dir(open(tid_path.c_str(), O_RDONLY | O_DIRECTORY)); | |
| ASSERT_THAT(tid_dir.get(), SyscallSucceeds()); | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| struct stat st{}; | |
| ASSERT_THAT(fstat(tid_dir.get(), &st), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, TidDirChildOwnedByCurrentEuid) { | |
| fork_helper_.RunInForkedProcess([] { | |
| long tid = syscall(SYS_gettid); | |
| ASSERT_THAT(tid, SyscallSucceeds()); | |
| std::string tid_path = fxl::StringPrintf("/proc/self/task/%ld", tid); | |
| fbl::unique_fd tid_dir(open(tid_path.c_str(), O_RDONLY | O_DIRECTORY)); | |
| ASSERT_THAT(tid_dir.get(), SyscallSucceeds()); | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| // Stat the child relative to `tid_dir` without statting `tid_dir` itself first. | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(tid_dir.get(), "stat", &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, PidDirOpenNoAtimeFollowsSetuidWithoutStat) { | |
| fork_helper_.RunInForkedProcess([] { | |
| struct stat st{}; | |
| ASSERT_THAT(stat("/proc/self", &st), SyscallSucceeds()); | |
| // Drop privileges without PR_SET_KEEPCAPS so CAP_FOWNER is cleared, then open /proc/self | |
| // with O_NOATIME without statting it first. | |
| ASSERT_THAT(setgroups(0, nullptr), SyscallSucceeds()); | |
| ASSERT_THAT(setgid(kEffectiveGid), SyscallSucceeds()); | |
| ASSERT_THAT(setuid(kEffectiveUid), SyscallSucceeds()); | |
| ASSERT_THAT(prctl(PR_SET_DUMPABLE, 1), SyscallSucceeds()); | |
| ASSERT_FALSE(test_helper::HasCapability(CAP_FOWNER)); | |
| fbl::unique_fd fd(open("/proc/self", O_RDONLY | O_DIRECTORY | O_NOATIME)); | |
| EXPECT_THAT(fd.get(), SyscallSucceeds()); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, FdLinkOwnedByEuid) { | |
| fork_helper_.RunInForkedProcess([] { | |
| test_helper::ScopedPipe pipe; | |
| ASSERT_TRUE(pipe.ReadSide().is_valid()); | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| std::string path = fxl::StringPrintf("/proc/self/fd/%d", pipe.ReadSide().get()); | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(AT_FDCWD, path.c_str(), &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, FdInfoOwnedByEuid) { | |
| fork_helper_.RunInForkedProcess([] { | |
| test_helper::ScopedPipe pipe; | |
| ASSERT_TRUE(pipe.ReadSide().is_valid()); | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| std::string path = fxl::StringPrintf("/proc/self/fdinfo/%d", pipe.ReadSide().get()); | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(AT_FDCWD, path.c_str(), &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, NsLinkOwnedByEuid) { | |
| fork_helper_.RunInForkedProcess([] { | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(AT_FDCWD, "/proc/self/ns/mnt", &st, AT_SYMLINK_NOFOLLOW), | |
| SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, kEffectiveUid); | |
| EXPECT_EQ(st.st_gid, kEffectiveGid); | |
| }); | |
| } | |
| TEST_F(ProcPidOwnerTest, NsTargetOwnedByRoot) { | |
| fork_helper_.RunInForkedProcess([] { | |
| ASSERT_NO_FATAL_FAILURE(SetDistinctCreds()); | |
| struct stat st{}; | |
| ASSERT_THAT(stat("/proc/self/ns/mnt", &st), SyscallSucceeds()); | |
| EXPECT_EQ(st.st_uid, 0u); | |
| EXPECT_EQ(st.st_gid, 0u); | |
| }); | |
| } | |
| TEST_F(ProcTaskDirTest, PidDirCorrectIno) { | |
| const char kProcPath[] = "/proc/self/status"; | |
| int fd; | |
| struct stat pre_stat; | |
| struct stat post_stat; | |
| SAFE_SYSCALL(fd = open(kProcPath, O_RDONLY)); | |
| SAFE_SYSCALL(fstat(fd, &pre_stat)); | |
| SAFE_SYSCALL(close(fd)); | |
| SAFE_SYSCALL(fd = open(kProcPath, O_RDONLY)); | |
| SAFE_SYSCALL(fstat(fd, &post_stat)); | |
| SAFE_SYSCALL(close(fd)); | |
| ASSERT_EQ(pre_stat.st_ino, post_stat.st_ino) << "Inode number incorrectly seen to change"; | |
| } | |
| TEST_F(ProcTaskDirTest, PidDirNotAccessibleAfterExitWithOpenChildFd) { | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(); | |
| test_helper::ForkHelper helper; | |
| pid_t child_pid = helper.RunInForkedProcess( | |
| [holder = std::move(child_exit.holder)]() mutable { holder.hold(); }); | |
| std::string child_dir = fxl::StringPrintf("/proc/%d", child_pid); | |
| std::string child_status = child_dir + "/status"; | |
| fbl::unique_fd status_fd(SAFE_SYSCALL(open(child_status.c_str(), O_RDONLY))); | |
| // Allow the child to exit and reap it while keeping status_fd open. | |
| child_exit.poker.poke(); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| struct stat st; | |
| EXPECT_THAT(stat(child_dir.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(stat(child_status.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| } | |
| TEST_F(ProcTaskDirTest, PidDirFdLookupsFailAfterExit) { | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(); | |
| test_helper::ForkHelper helper; | |
| pid_t child_pid = helper.RunInForkedProcess( | |
| [holder = std::move(child_exit.holder)]() mutable { holder.hold(); }); | |
| std::string child_dir = fxl::StringPrintf("/proc/%d", child_pid); | |
| fbl::unique_fd dirfd(SAFE_SYSCALL(open(child_dir.c_str(), O_RDONLY | O_DIRECTORY))); | |
| fbl::unique_fd status_fd(SAFE_SYSCALL(openat(dirfd.get(), "status", O_RDONLY))); | |
| // Allow the child to exit and reap it while keeping the fds open. | |
| child_exit.poker.poke(); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| // The open fds themselves remain valid. | |
| struct stat st; | |
| EXPECT_THAT(fstat(dirfd.get(), &st), SyscallSucceeds()); | |
| EXPECT_THAT(fstat(status_fd.get(), &st), SyscallSucceeds()); | |
| // Lookups relative to the dead task's directory fail with ESRCH, whether or not the entry has | |
| // been looked up before, and even for names that never existed. | |
| EXPECT_THAT(openat(dirfd.get(), "status", O_RDONLY), SyscallFailsWithErrno(ESRCH)); | |
| EXPECT_THAT(openat(dirfd.get(), "cmdline", O_RDONLY), SyscallFailsWithErrno(ESRCH)); | |
| EXPECT_THAT(fstatat(dirfd.get(), "status", &st, 0), SyscallFailsWithErrno(ESRCH)); | |
| EXPECT_THAT(fstatat(dirfd.get(), "stat", &st, 0), SyscallFailsWithErrno(ESRCH)); | |
| EXPECT_THAT(fstatat(dirfd.get(), "nonexistent", &st, 0), SyscallFailsWithErrno(ESRCH)); | |
| } | |
| TEST_F(ProcTaskDirTest, PidDirFdListingAndReadsFailAfterExit) { | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(); | |
| test_helper::ForkHelper helper; | |
| pid_t child_pid = helper.RunInForkedProcess( | |
| [holder = std::move(child_exit.holder)]() mutable { holder.hold(); }); | |
| std::string child_dir = fxl::StringPrintf("/proc/%d", child_pid); | |
| fbl::unique_fd dirfd(SAFE_SYSCALL(open(child_dir.c_str(), O_RDONLY | O_DIRECTORY))); | |
| fbl::unique_fd status_fd(SAFE_SYSCALL(openat(dirfd.get(), "status", O_RDONLY))); | |
| fbl::unique_fd task_fd(SAFE_SYSCALL(openat(dirfd.get(), "task", O_RDONLY | O_DIRECTORY))); | |
| // Allow the child to exit and reap it while keeping the fds open. | |
| child_exit.poker.poke(); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| // Listing the dead task's directories fails with ENOENT. | |
| char buf[4096]; | |
| EXPECT_THAT(syscall(SYS_getdents64, dirfd.get(), buf, sizeof(buf)), | |
| SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(syscall(SYS_getdents64, task_fd.get(), buf, sizeof(buf)), | |
| SyscallFailsWithErrno(ENOENT)); | |
| // Reading an already-open file of the dead task fails with ESRCH. | |
| EXPECT_THAT(read(status_fd.get(), buf, sizeof(buf)), SyscallFailsWithErrno(ESRCH)); | |
| } | |
| // Opens /proc/<pid>/`dir` of a child process, and returns it once the child has exited and has | |
| // been reaped. | |
| fbl::unique_fd OpenTaskSubdirOfReapedChild(const char* dir) { | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(); | |
| test_helper::ForkHelper helper; | |
| pid_t child_pid = helper.RunInForkedProcess( | |
| [holder = std::move(child_exit.holder)]() mutable { holder.hold(); }); | |
| std::string path = fxl::StringPrintf("/proc/%d/%s", child_pid, dir); | |
| fbl::unique_fd dir_fd(open(path.c_str(), O_RDONLY | O_DIRECTORY)); | |
| EXPECT_TRUE(dir_fd.is_valid()) << path << ": " << strerror(errno); | |
| // Allow the child to exit and reap it while keeping dir_fd open. | |
| child_exit.poker.poke(); | |
| EXPECT_TRUE(helper.WaitForChildren()); | |
| return dir_fd; | |
| } | |
| TEST_F(ProcTaskDirTest, AttrDirLookupFailsWithEnoentAfterExit) { | |
| fbl::unique_fd attr_fd = OpenTaskSubdirOfReapedChild("attr"); | |
| ASSERT_TRUE(attr_fd.is_valid()); | |
| // Unlike lookups relative to the dead task's /proc/<pid> directory, which fail with ESRCH, | |
| // lookups relative to its attr directory fail with ENOENT. | |
| EXPECT_THAT(openat(attr_fd.get(), "current", O_RDONLY), SyscallFailsWithErrno(ENOENT)); | |
| } | |
| TEST_F(ProcTaskDirTest, AttrDirListingFailsWithEnoentAfterExit) { | |
| fbl::unique_fd attr_fd = OpenTaskSubdirOfReapedChild("attr"); | |
| ASSERT_TRUE(attr_fd.is_valid()); | |
| // Like listing the dead task's /proc/<pid> directory, listing its attr directory fails with | |
| // ENOENT. | |
| char buf[4096]; | |
| EXPECT_THAT(syscall(SYS_getdents64, attr_fd.get(), buf, sizeof(buf)), | |
| SyscallFailsWithErrno(ENOENT)); | |
| } | |
| // Returns the d_ino and d_type of each entry of the directory open at `dir_fd`, by name, | |
| // without "." and "..". | |
| std::map<std::string, std::pair<uint64_t, unsigned char>> ListDirEntries(int dir_fd) { | |
| struct linux_dirent64 { | |
| uint64_t d_ino; | |
| int64_t d_off; | |
| unsigned short d_reclen; | |
| unsigned char d_type; | |
| char d_name[]; | |
| }; | |
| std::map<std::string, std::pair<uint64_t, unsigned char>> entries; | |
| std::vector<uint8_t> buffer(4096); | |
| long nread; | |
| while ((nread = syscall(SYS_getdents64, dir_fd, buffer.data(), buffer.size())) > 0) { | |
| for (long pos = 0; pos < nread;) { | |
| auto entry = reinterpret_cast<linux_dirent64*>(buffer.data() + pos); | |
| std::string name(entry->d_name); | |
| if (name != "." && name != "..") { | |
| entries[name] = {entry->d_ino, entry->d_type}; | |
| } | |
| pos += entry->d_reclen; | |
| } | |
| } | |
| EXPECT_EQ(nread, 0) << "getdents64 failed: " << std::strerror(errno); | |
| return entries; | |
| } | |
| TEST_F(ProcTaskDirTest, AttrDirListsAttributeEntries) { | |
| auto entries = test_helper::ListDirectory("/proc/self/attr"); | |
| ASSERT_TRUE(entries.is_ok()) << std::strerror(entries.error_value()); | |
| // Linux may also list directories for specific security modules, so only check that the | |
| // common entries are present. | |
| for (const char* name : {"current", "prev", "exec", "fscreate", "keycreate", "sockcreate"}) { | |
| EXPECT_TRUE(entries->contains(name)) << name; | |
| } | |
| } | |
| TEST_F(ProcTaskDirTest, AttrDirListingMatchesStat) { | |
| fbl::unique_fd attr_fd(SAFE_SYSCALL(open("/proc/self/attr", O_RDONLY | O_DIRECTORY))); | |
| auto entries = ListDirEntries(attr_fd.get()); | |
| ASSERT_FALSE(entries.empty()); | |
| for (const auto& [name, ino_and_type] : entries) { | |
| struct stat st; | |
| ASSERT_THAT(fstatat(attr_fd.get(), name.c_str(), &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()) | |
| << name; | |
| EXPECT_EQ(ino_and_type.first, st.st_ino) << name; | |
| EXPECT_EQ(ino_and_type.second, IFTODT(st.st_mode)) << name; | |
| } | |
| } | |
| TEST_F(ProcTaskDirTest, SelfAuxvIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/auxv", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadAuxvIsEmpty) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/auxv", &contents)); | |
| ASSERT_EQ(contents.size(), 0ul); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfCmdlineIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/cmdline", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadCmdlineIsEmpty) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/cmdline", &contents)); | |
| ASSERT_EQ(contents.size(), 0ul); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfEnvironIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/environ", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadEnvironIsEmpty) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/environ", &contents)); | |
| ASSERT_EQ(contents.size(), 0ul); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfExeSymlinkIsValid) { | |
| char buf[1000]; | |
| ASSERT_THAT(readlink("/proc/self/exe", buf, 1000), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadExeSymlinkIsNotValid) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| char buf[1000]; | |
| ASSERT_EQ(readlink("/proc/2/exe", buf, 1000), -1); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfSmapsIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/smaps", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadSmapsIsEmpty) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/smaps", &contents)); | |
| ASSERT_EQ(contents.size(), 0ul); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfSmapsRollupIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/smaps_rollup", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| EXPECT_THAT(contents, testing::HasSubstr("[rollup]")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nRss:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPss:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPss_Anon:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPss_File:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPss_Shmem:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nShared_Clean:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPrivate_Clean:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPrivate_Dirty:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nAnonymous:")); | |
| } | |
| // Linux 6.6 allows open() without an mm and fails on read() with ESRCH (Linux 6.11+ fails on | |
| // open()). | |
| TEST_F(ProcTaskDirTest, KthreadSmapsRollupReadFails) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| fbl::unique_fd fd(open("/proc/2/smaps_rollup", O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()); | |
| char buf[1024]; | |
| EXPECT_THAT(read(fd.get(), buf, sizeof(buf)), SyscallFailsWithErrno(ESRCH)); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfStatIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| std::optional<std::string> ExtractStatComm(const std::string& stat_contents) { | |
| size_t open_paren = stat_contents.find('('); | |
| size_t close_paren = stat_contents.rfind(')'); | |
| if (open_paren == std::string::npos || close_paren == std::string::npos || | |
| close_paren <= open_paren) { | |
| return std::nullopt; | |
| } | |
| return stat_contents.substr(open_paren + 1, close_paren - open_paren - 1); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfStatCommTruncatedToTaskCommLen) { | |
| constexpr size_t kMaxCommLen = 15; // TASK_COMM_LEN - 1 | |
| std::string stat_contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &stat_contents)); | |
| std::optional<std::string> stat_comm = ExtractStatComm(stat_contents); | |
| ASSERT_TRUE(stat_comm.has_value()) << stat_contents; | |
| EXPECT_LE(stat_comm->size(), kMaxCommLen) << *stat_comm; | |
| std::string comm_contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/comm", &comm_contents)); | |
| if (!comm_contents.empty() && comm_contents.back() == '\n') { | |
| comm_contents.pop_back(); | |
| } | |
| EXPECT_EQ(*stat_comm, comm_contents); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Setting a 16-byte non-null string must truncate the comm field in /proc/self/stat to 15 | |
| // bytes. | |
| ASSERT_THAT(prctl(PR_SET_NAME, "0123456789abcdef"), SyscallSucceeds()); | |
| std::string child_stat; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &child_stat)); | |
| std::optional<std::string> child_comm = ExtractStatComm(child_stat); | |
| ASSERT_TRUE(child_comm.has_value()) << child_stat; | |
| EXPECT_EQ(*child_comm, "0123456789abcde"); | |
| // Setting a multi-byte UTF-8 string whose codepoint straddles the 15-byte boundary must raw- | |
| // truncate to 15 bytes rather than expanding invalid trailing UTF-8 into a 3-byte replacement | |
| // character (\xef\xbf\xbd). | |
| ASSERT_THAT(prctl(PR_SET_NAME, "0123456789abcd\xc3\xa9"), SyscallSucceeds()); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &child_stat)); | |
| child_comm = ExtractStatComm(child_stat); | |
| ASSERT_TRUE(child_comm.has_value()) << child_stat; | |
| EXPECT_EQ(*child_comm, "0123456789abcd\xc3"); | |
| std::string child_comm_file; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/comm", &child_comm_file)); | |
| EXPECT_EQ(child_comm_file, "0123456789abcd\xc3\n"); | |
| // Setting a substring of argv[0] (which triggers TaskCommand::try_embed in Starnix) must still | |
| // report only the comm name in /proc/self/stat rather than the full argv[0] basename. | |
| ASSERT_THAT(prctl(PR_SET_NAME, "procfs_test"), SyscallSucceeds()); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &child_stat)); | |
| child_comm = ExtractStatComm(child_stat); | |
| ASSERT_TRUE(child_comm.has_value()) << child_stat; | |
| EXPECT_EQ(*child_comm, "procfs_test"); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadStatIsNotEmpty) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/stat", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| // Verify that seeking in a pseudo-dynamic file (which uses lazy seek) and subsequently reading from | |
| // it correctly catches up the sequence generator and returns the expected suffix data. | |
| // Uses `/proc/self/cmdline` as it is static during the lifetime of the process. | |
| TEST_F(ProcTaskDirTest, DynamicFileSeek) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/cmdline", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(5)); | |
| fbl::unique_fd fd(open("/proc/self/cmdline", O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()); | |
| off_t offset = lseek(fd.get(), 3, SEEK_SET); | |
| ASSERT_EQ(offset, 3); | |
| std::string seeked_contents; | |
| ASSERT_TRUE(files::ReadFileDescriptorToString(fd.get(), &seeked_contents)); | |
| EXPECT_EQ(seeked_contents, contents.substr(3)); | |
| } | |
| // Verify that seeking past the end of a pseudo-dynamic file succeeds (lazy seek) and only returns | |
| // EOF when actually reading. | |
| // Uses `/proc/self/cmdline` as it is static during the lifetime of the process. | |
| TEST_F(ProcTaskDirTest, DynamicFileSeekPastEnd) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/cmdline", &contents)); | |
| fbl::unique_fd fd(open("/proc/self/cmdline", O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()); | |
| // Seek past the end of the cmdline file. | |
| off_t target_offset = static_cast<off_t>(contents.size()) + 1; | |
| off_t offset = lseek(fd.get(), target_offset, SEEK_SET); | |
| ASSERT_EQ(offset, target_offset); | |
| // The seek succeeded. Attempting to read should return 0 bytes (EOF) rather than failing. | |
| char buf; | |
| EXPECT_THAT(read(fd.get(), &buf, sizeof(buf)), SyscallSucceedsWithValue(0)); | |
| } | |
| // Returns a vector holding the elements of the supplied "/proc/pid/stat" contents, with a zeroeth | |
| // element prepended so that the elements align with the positions documented in the man page. | |
| std::vector<std::string> ProcPidStatElements(const std::string& contents) { | |
| std::istringstream iss(contents); | |
| std::vector<std::string> result(std::istream_iterator<std::string>{iss}, | |
| std::istream_iterator<std::string>{}); | |
| result.insert(result.begin(), std::string()); | |
| return result; | |
| } | |
| TEST_F(ProcTaskDirTest, ParentFieldsZeroedWithoutCapSysPtrace) { | |
| if (!test_helper::HasCapabilityPermitted(CAP_SYS_PTRACE)) { | |
| // Technically any capability is sufficient, so that the parent has greater capabilities than | |
| // the child, so that the child will fail the ptrace read access check. | |
| GTEST_SKIP() << "Needs the CAP_SYS_PTRACE capability."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Ensure that we do not have the effective CAP_SYS_PTRACE capability. | |
| test_helper::DropAllCapabilities(); | |
| std::string path = fxl::StringPrintf("/proc/%d/stat", parent_pid); | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString(path, &contents)); | |
| auto fields = ProcPidStatElements(contents); | |
| // The fields requiring a ptrace read access check will be zeroed when the check fails. | |
| EXPECT_EQ(fields[26], "1") << "startcode(26)"; | |
| EXPECT_EQ(fields[27], "1") << "endcode(27)"; | |
| EXPECT_EQ(fields[28], "0") << "startstack(28)"; | |
| EXPECT_EQ(fields[29], "0") << "kstkesp(29)"; | |
| EXPECT_EQ(fields[30], "0") << "kstkeip(30)"; | |
| EXPECT_EQ(fields[35], "0") << "wchan(35)"; | |
| EXPECT_EQ(fields[45], "0") << "start_data(45)"; | |
| EXPECT_EQ(fields[46], "0") << "end_data(46)"; | |
| EXPECT_EQ(fields[47], "0") << "start_brk(47)"; | |
| EXPECT_EQ(fields[48], "0") << "arg_start(48)"; | |
| EXPECT_EQ(fields[49], "0") << "arg_end(49)"; | |
| EXPECT_EQ(fields[50], "0") << "env_start(50)"; | |
| EXPECT_EQ(fields[51], "0") << "env_end(51)"; | |
| EXPECT_EQ(fields[52], "0") << "exit_code(52)"; | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_F(ProcTaskDirTest, ParentFieldsValidWithCapSysPtrace) { | |
| if (!test_helper::HasCapabilityPermitted(CAP_SYS_PTRACE)) { | |
| GTEST_SKIP() << "Needs the CAP_SYS_PTRACE capability."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // We need to have the effective CAP_SYS_PTRACE capability. | |
| test_helper::SetCapabilityEffective(CAP_SYS_PTRACE); | |
| std::string path = fxl::StringPrintf("/proc/%d/stat", parent_pid); | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString(path, &contents)); | |
| auto fields = ProcPidStatElements(contents); | |
| // The fields requiring a ptrace read access check will be zeroed when the check fails. | |
| EXPECT_NE(fields[26], "1") << "startcode(26)"; | |
| EXPECT_NE(fields[27], "1") << "endcode(27)"; | |
| EXPECT_NE(fields[28], "0") << "startstack(28)"; | |
| // kstkesp(29) and kstkeip(30) are typically zero. | |
| // wchan(35) is zero unless the task is sleeping. | |
| if (!test_helper::IsStarnix()) { | |
| // Starnix doesn't yet implement these fields. | |
| EXPECT_NE(fields[45], "0") << "start_data(45)"; | |
| EXPECT_NE(fields[46], "0") << "end_data(46)"; | |
| EXPECT_NE(fields[47], "0") << "start_brk(47)"; | |
| } | |
| EXPECT_NE(fields[48], "0") << "arg_start(48)"; | |
| EXPECT_NE(fields[49], "0") << "arg_end(49)"; | |
| EXPECT_NE(fields[50], "0") << "env_start(50)"; | |
| EXPECT_NE(fields[51], "0") << "env_end(51)"; | |
| // exit_code(52) will be zero. | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| // Observed on Linux: the initial [stack] VMA always extends exactly 128 KiB below the page holding | |
| // the lowest byte of the strings (argv, envp and AT_EXECFN). The pointer area (argc, argv, envp, | |
| // auxv, AT_RANDOM, AT_PLATFORM) and a random amount of padding are carved out of those 128 KiB; the | |
| // remainder is pre-mapped but unused. The VMA size is therefore not the size of the resolved | |
| // argv/envp/auxv but round_up_to_page(strings + one NULL word) + 128 KiB. | |
| // | |
| // This relationship only holds until the process uses more stack than the initial slack and makes | |
| // the VMA grow, so it is measured on a freshly exec'd child that has executed almost nothing, | |
| // rather than on the long-lived test process. | |
| TEST_F(ProcTest, InitialStackVmaSizeIsStringsPlusFixedSlack) { | |
| constexpr size_t kStackSlackBelowStrings = 128 * 1024; | |
| const size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE)); | |
| test_helper::ForkHelper fork_helper; | |
| test_helper::ScopedPipe child_stdout; | |
| test_helper::ScopedPipe child_stdin; | |
| pid_t child_pid = fork_helper.RunInForkedProcess( | |
| [child_stdout = &child_stdout.WriteSide(), child_stdin = &child_stdin.ReadSide()]() mutable { | |
| // Use the pipes for stdin & stdout. Stderr remains unchanged, to allow error output. | |
| SAFE_SYSCALL(dup2(child_stdin->get(), STDIN_FILENO)); | |
| child_stdin->reset(); | |
| SAFE_SYSCALL(dup2(child_stdout->get(), STDOUT_FILENO)); | |
| child_stdout->reset(); | |
| std::string binary_path = GetExecChildBinaryPath(); | |
| char* const argv[] = {const_cast<char*>(binary_path.c_str()), | |
| const_cast<char*>("some-argument"), nullptr}; | |
| char* const envp[] = {const_cast<char*>("SOME_VARIABLE=some-value"), nullptr}; | |
| SAFE_SYSCALL(execve(binary_path.c_str(), argv, envp)); | |
| _exit(EXIT_FAILURE); | |
| }); | |
| // Wait for the child to indicate that it has exec'd and started. | |
| test_helper::Rendezvous child_ready = test_helper::MakeRendezvous(std::move(child_stdout)); | |
| child_ready.holder.hold(); | |
| // Let the child exit once we are done, whatever the outcome. | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(std::move(child_stdin)); | |
| auto release_child = fit::defer([&] { | |
| child_exit.poker.poke(); | |
| EXPECT_TRUE(fork_helper.WaitForChildren()); | |
| }); | |
| std::string child_dir = fxl::StringPrintf("%s/%d", proc_path().c_str(), child_pid); | |
| std::string maps; | |
| ASSERT_TRUE(files::ReadFileToString(child_dir + "/maps", &maps)); | |
| auto stack = test_helper::find_memory_mapping( | |
| [](const test_helper::MemoryMapping& mapping) { return mapping.pathname == "[stack]"; }, | |
| maps); | |
| ASSERT_TRUE(stack.has_value()) << maps; | |
| std::string stat_contents; | |
| ASSERT_TRUE(files::ReadFileToString(child_dir + "/stat", &stat_contents)); | |
| auto fields = ProcPidStatElements(stat_contents); | |
| ASSERT_GE(fields.size(), 52u) << stat_contents; | |
| // The child has the same word size as this test, so its addresses fit in our uintptr_t. | |
| auto parse_address = [](const std::string& field) -> uintptr_t { | |
| char* end = nullptr; | |
| unsigned long long value = strtoull(field.c_str(), &end, 10); | |
| EXPECT_TRUE(end != field.c_str() && *end == '\0') << "not a number: " << field; | |
| return static_cast<uintptr_t>(value); | |
| }; | |
| uintptr_t arg_start = parse_address(fields[48]); | |
| uintptr_t env_start = parse_address(fields[50]); | |
| // /proc/<pid>/auxv is an array of (type, value) pairs of the child's native word size, which is | |
| // the same as ours since the child is built alongside this test. | |
| std::string auxv_contents; | |
| ASSERT_TRUE(files::ReadFileToString(child_dir + "/auxv", &auxv_contents)); | |
| ASSERT_EQ(auxv_contents.size() % (2 * sizeof(unsigned long)), 0u); | |
| uintptr_t execfn = 0; | |
| for (size_t offset = 0; offset + 2 * sizeof(unsigned long) <= auxv_contents.size(); | |
| offset += 2 * sizeof(unsigned long)) { | |
| unsigned long type, value; | |
| memcpy(&type, auxv_contents.data() + offset, sizeof(type)); | |
| memcpy(&value, auxv_contents.data() + offset + sizeof(type), sizeof(value)); | |
| if (type == AT_EXECFN) { | |
| execfn = value; | |
| break; | |
| } | |
| } | |
| ASSERT_NE(execfn, 0u); | |
| // The strings area consists of the argv strings, the envp strings and the AT_EXECFN string. Only | |
| // its extent matters here, not the order of the three blocks, so take the lowest start. | |
| uintptr_t strings_start = std::min({arg_start, env_start, execfn}); | |
| ASSERT_GE(strings_start, stack->start); | |
| ASSERT_LT(strings_start, stack->end); | |
| // The VMA ends on a page boundary, so this is equivalent to checking that the VMA size is the | |
| // strings rounded up to a page plus the slack. | |
| uintptr_t strings_page = strings_start & ~(page_size - 1); | |
| EXPECT_EQ(strings_page - stack->start, kStackSlackBelowStrings); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfStatPriorityAndNice) { | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([] { | |
| auto read_stat_fields = [] { | |
| std::string contents; | |
| EXPECT_TRUE(files::ReadFileToString("/proc/self/stat", &contents)); | |
| return ProcPidStatElements(contents); | |
| }; | |
| sched_param zero_param = {.sched_priority = 0}; | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_OTHER, &zero_param), SyscallSucceeds()); | |
| if (getpriority(PRIO_PROCESS, 0) < 0) { | |
| ASSERT_THAT(setpriority(PRIO_PROCESS, 0, 0), SyscallSucceeds()); | |
| } | |
| int initial_nice = getpriority(PRIO_PROCESS, 0); | |
| auto fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], std::to_string(20 + initial_nice)) << "priority(18)"; | |
| EXPECT_EQ(fields[19], std::to_string(initial_nice)) << "nice(19)"; | |
| int raised_nice = std::min(19, initial_nice + 5); | |
| ASSERT_THAT(setpriority(PRIO_PROCESS, 0, raised_nice), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], std::to_string(20 + raised_nice)) << "priority(18)"; | |
| EXPECT_EQ(fields[19], std::to_string(raised_nice)) << "nice(19)"; | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_BATCH, &zero_param), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], std::to_string(20 + raised_nice)) << "priority(18)"; | |
| EXPECT_EQ(fields[19], std::to_string(raised_nice)) << "nice(19)"; | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_IDLE, &zero_param), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], std::to_string(20 + raised_nice)) << "priority(18)"; | |
| EXPECT_EQ(fields[19], std::to_string(raised_nice)) << "nice(19)"; | |
| if (test_helper::HasCapabilityEffective(CAP_SYS_NICE)) { | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_OTHER, &zero_param), SyscallSucceeds()); | |
| ASSERT_THAT(setpriority(PRIO_PROCESS, 0, -5), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], "15") << "priority(18)"; | |
| EXPECT_EQ(fields[19], "-5") << "nice(19)"; | |
| sched_param fifo_param = {.sched_priority = 10}; | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_FIFO, &fifo_param), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], "-11") << "priority(18)"; | |
| EXPECT_EQ(fields[19], "-5") << "nice(19)"; | |
| sched_param rr_param = {.sched_priority = 99}; | |
| ASSERT_THAT(sched_setscheduler(0, SCHED_RR, &rr_param), SyscallSucceeds()); | |
| fields = read_stat_fields(); | |
| ASSERT_GT(fields.size(), 19u); | |
| EXPECT_EQ(fields[18], "-100") << "priority(18)"; | |
| EXPECT_EQ(fields[19], "-5") << "nice(19)"; | |
| } | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfStatmIsNotEmpty) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/statm", &contents)); | |
| ASSERT_THAT(contents.size(), testing::Gt(0)); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadStatmIsAllZeroes) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/statm", &contents)); | |
| ASSERT_EQ(contents, "0 0 0 0 0 0 0\n"); | |
| } | |
| TEST_F(ProcTaskDirTest, SelfStatusSensibleOutput) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/status", &contents)); | |
| EXPECT_THAT(contents, testing::HasSubstr("Name:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nUmask:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nSigBlk:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nSigPnd:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nShdPnd:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nState:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nTgid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPPid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nUid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nGid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nGroups:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmSize:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmLck:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmRSS:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nRssAnon:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nRssFile:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nRssShmem:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nRssShmem:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmData:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmStk:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmExe:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmSwap:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nThreads:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nVmHWM:")); | |
| } | |
| TEST_F(ProcTaskDirTest, KthreadStatusSensibleOutput) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/2/status", &contents)); | |
| EXPECT_THAT(contents, testing::HasSubstr("Name:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nUmask:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nSigBlk:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nSigPnd:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nShdPnd:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nState:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nTgid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nPPid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nUid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nGid:")); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nGroups:")); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmSize:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmRSS:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nRssAnon:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nRssFile:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nRssShmem:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nRssShmem:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmData:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmStk:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmExe:"))); | |
| EXPECT_THAT(contents, Not(testing::HasSubstr("\nVmSwap:"))); | |
| EXPECT_THAT(contents, testing::HasSubstr("\nThreads:")); | |
| } | |
| constexpr char kProcSelfFdPath[] = "/proc/self/fd/%d"; | |
| TEST_F(ProcTaskDirTest, FdOpath) { | |
| test_helper::ScopedTempFD temp_file; | |
| ASSERT_TRUE(temp_file); | |
| fbl::unique_fd opath_fd(SAFE_SYSCALL(open(temp_file.name().c_str(), O_RDONLY | O_PATH))); | |
| ASSERT_TRUE(opath_fd.is_valid()); | |
| std::string opath_fd_path = fxl::StringPrintf(kProcSelfFdPath, opath_fd.get()); | |
| fbl::unique_fd regular_fd(SAFE_SYSCALL(open(opath_fd_path.c_str(), O_RDONLY))); | |
| ASSERT_TRUE(regular_fd.is_valid()); | |
| } | |
| TEST_F(ProcTaskDirTest, FdOpathMode) { | |
| test_helper::ScopedTempFD temp_file; | |
| ASSERT_TRUE(temp_file); | |
| constexpr struct { | |
| int open_flags; | |
| mode_t expected_mode; | |
| } kTestCases[] = { | |
| {O_RDONLY, S_IFLNK | 0500}, | |
| {O_WRONLY, S_IFLNK | 0300}, | |
| {O_RDWR, S_IFLNK | 0700}, | |
| {O_RDONLY | O_PATH, S_IFLNK | 0000}, | |
| {O_WRONLY | O_PATH, S_IFLNK | 0000}, | |
| {O_RDWR | O_PATH, S_IFLNK | 0000}, | |
| }; | |
| for (const auto& [open_flags, expected_mode] : kTestCases) { | |
| SCOPED_TRACE(fxl::StringPrintf("open_flags=0x%x", open_flags)); | |
| fbl::unique_fd fd(SAFE_SYSCALL(open(temp_file.name().c_str(), open_flags))); | |
| ASSERT_TRUE(fd.is_valid()); | |
| std::string fd_path = fxl::StringPrintf(kProcSelfFdPath, fd.get()); | |
| struct stat fd_stat = {}; | |
| SAFE_SYSCALL(fstatat(AT_FDCWD, fd_path.c_str(), &fd_stat, AT_SYMLINK_NOFOLLOW)); | |
| EXPECT_EQ(fd_stat.st_mode, expected_mode); | |
| } | |
| } | |
| TEST_F(ProcTaskDirTest, FdOpathSymlink) { | |
| test_helper::ScopedTempFD temp_file; | |
| ASSERT_TRUE(temp_file); | |
| test_helper::ScopedTempSymlink temp_symlink(temp_file.name().c_str()); | |
| ASSERT_TRUE(temp_symlink); | |
| fbl::unique_fd symlink_fd(SAFE_SYSCALL(open(temp_symlink.path().c_str(), O_PATH | O_NOFOLLOW))); | |
| ASSERT_TRUE(symlink_fd.is_valid()); | |
| std::string symlink_fd_path = fxl::StringPrintf(kProcSelfFdPath, symlink_fd.get()); | |
| ASSERT_THAT(open(symlink_fd_path.c_str(), O_RDONLY), SyscallFailsWithErrno(ELOOP)); | |
| } | |
| TEST_F(ProcTaskDirTest, TimerslackNsSelf) { | |
| // We do not need CAP_SYS_NICE to access our own timerslack_ns file. | |
| test_helper::UnsetCapabilityEffective(CAP_SYS_NICE); | |
| std::string initial_contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/timerslack_ns", &initial_contents)); | |
| std::string new_contents = "1" + initial_contents; | |
| fbl::unique_fd fd(open("/proc/self/timerslack_ns", O_RDWR)); | |
| if (!fd.is_valid()) { | |
| if (errno == EROFS) { | |
| GTEST_SKIP() << "/proc is not writable, skipping"; | |
| } else { | |
| ADD_FAILURE() << "Failed to open /proc/self/timerslack_ns for writing: " << strerror(errno); | |
| return; | |
| } | |
| } | |
| ASSERT_NE(write(fd.get(), new_contents.c_str(), new_contents.size()), -1) << errno; | |
| fd.reset(); | |
| std::string read_contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/timerslack_ns", &read_contents)); | |
| EXPECT_EQ(read_contents, new_contents); | |
| // Writing zero resets to the default value. | |
| ASSERT_TRUE(files::WriteFile("/proc/self/timerslack_ns", "0")); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/timerslack_ns", &read_contents)); | |
| EXPECT_EQ(read_contents, initial_contents); | |
| } | |
| TEST_F(ProcTaskDirTest, TimerslackNsOtherNoAccess) { | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Ensure we don't have CAP_SYS_NICE, otherwise we would have access. | |
| test_helper::DropAllCapabilities(); | |
| std::string path = fxl::StringPrintf("/proc/%d/timerslack_ns", parent_pid); | |
| // Open succeeds even though the file will not be readable. | |
| fbl::unique_fd fd(open(path.c_str(), O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()); | |
| // But reading fails. | |
| char buf[256]; | |
| EXPECT_EQ(read(fd.get(), buf, sizeof(buf)), -1); | |
| EXPECT_EQ(errno, EPERM); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_F(ProcTaskDirTest, TimerslackNsOtherAccessWithCap) { | |
| if (!test_helper::HasCapabilityPermitted(CAP_SYS_NICE)) { | |
| GTEST_SKIP() << "Needs the CAP_SYS_NICE capability."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // We need to have the effective CAP_SYS_NICE capability. | |
| test_helper::SetCapabilityEffective(CAP_SYS_NICE); | |
| std::string path = fxl::StringPrintf("/proc/%d/timerslack_ns", parent_pid); | |
| std::string contents; | |
| EXPECT_TRUE(files::ReadFileToString(path, &contents)); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| class ProcfsTest : public ProcTestBase { | |
| protected: | |
| // Verifies whether the input string is a valid UUID in hyphenated format | |
| // Example: | |
| // af0af413-58e1-4210-bb57-bc9a9d3ca44a | |
| // Segment lengths: | |
| // 8 | 4 | 4 | 4 | 12 | |
| void is_valid_uuid(std::string in) { | |
| size_t pos = 0; | |
| std::string token; | |
| std::array<size_t, 5> lengths = {8, 4, 4, 4, 12}; // Lengths of tokens | |
| // Some Linux kernels have a newline character at the end | |
| if (in[in.size() - 1] == '\n') { | |
| in.pop_back(); | |
| } | |
| in.append("-"); | |
| // For each hyphen-delimited token of the UUID string | |
| for (size_t length : lengths) { | |
| // Grab token | |
| ASSERT_TRUE((pos = in.find("-")) != std::string::npos); | |
| token = in.substr(0, pos); | |
| in.erase(0, pos + 1); | |
| ASSERT_TRUE(length == token.size()); | |
| // All characters are hexadecimal digits | |
| ASSERT_TRUE(std::all_of(token.begin(), token.end(), [](char c) { return std::isxdigit(c); })); | |
| } | |
| } | |
| }; | |
| // Verify /proc/sys/kernel/random/boot_id exists and has the boot UUID | |
| TEST_F(ProcfsTest, ProcSysKernelRandomBootIdExists) { | |
| std::string uuid; | |
| EXPECT_EQ(0, access("/proc/sys/kernel/random/boot_id", R_OK)); | |
| EXPECT_TRUE(files::ReadFileToString("/proc/sys/kernel/random/boot_id", &uuid)); | |
| is_valid_uuid(uuid); | |
| } | |
| // Verify that /proc/zoneinfo contains something reasonable. | |
| TEST_F(ProcfsTest, ZoneInfo) { | |
| auto path = "/proc/zoneinfo"; | |
| EXPECT_EQ(0, access(path, R_OK)); | |
| std::string content; | |
| ASSERT_TRUE(files::ReadFileToString(path, &content)); | |
| // Ensures that one node has `nr_inactive_file` and `nr_inactive_file`. | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)Node [0-9]+, zone +[a-zA-Z]+\n" | |
| " per-node stats\n" | |
| "( {6}.*\n)*" | |
| " nr_inactive_file [0-9]+\n" | |
| " nr_active_file [0-9]+\n")); | |
| // Ensures that one node has `free`, `min`, `low`, `high`, `present`, among others. | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)Node [0-9]+, zone +[a-zA-Z]+\n" | |
| "( .*\n)*" | |
| " pages free [0-9]+\n" | |
| "( .*\n)*" | |
| " min [0-9]+\n" | |
| "( .*\n)*" | |
| " low [0-9]+\n" | |
| "( .*\n)*" | |
| " high [0-9]+\n" | |
| "( .*\n)*" | |
| " present [0-9]+\n" | |
| "( .*\n)*" | |
| " pagesets\n")); | |
| // On Linux the `Normal` zone may be empty (e.g. x86_64 with < 4GiB of RAM), so only | |
| // check the watermarks on Starnix, where there is a single `Normal` zone whose | |
| // watermarks are derived from the host kernel's OOM thresholds. | |
| if (!test_helper::IsStarnix()) { | |
| return; | |
| } | |
| std::istringstream iss(content); | |
| std::string line; | |
| bool in_normal_zone = false; | |
| std::optional<uint64_t> min_pages; | |
| std::optional<uint64_t> low_pages; | |
| std::optional<uint64_t> high_pages; | |
| std::optional<uint64_t> present_pages; | |
| while (std::getline(iss, line)) { | |
| if (line.starts_with("Node ")) { | |
| in_normal_zone = (line.find("zone Normal") != std::string::npos); | |
| continue; | |
| } | |
| if (!in_normal_zone) { | |
| continue; | |
| } | |
| std::istringstream line_ss(line); | |
| std::string key; | |
| uint64_t val = 0; | |
| if (line_ss >> key >> val) { | |
| if (key == "min") { | |
| min_pages = val; | |
| } else if (key == "low") { | |
| low_pages = val; | |
| } else if (key == "high") { | |
| high_pages = val; | |
| } else if (key == "present") { | |
| present_pages = val; | |
| } | |
| } | |
| } | |
| ASSERT_TRUE(min_pages.has_value()); | |
| ASSERT_TRUE(low_pages.has_value()); | |
| ASSERT_TRUE(high_pages.has_value()); | |
| ASSERT_TRUE(present_pages.has_value()); | |
| EXPECT_LT(*high_pages, *present_pages); | |
| // The test realm uses the default watermarks from `starnix_kernel.cml`. | |
| const long raw_page_size = sysconf(_SC_PAGESIZE); | |
| ASSERT_GT(raw_page_size, 0); | |
| const uint64_t page_size = static_cast<uint64_t>(raw_page_size); | |
| constexpr uint64_t kBytesPerMb = 1024ULL * 1024ULL; | |
| EXPECT_EQ(*min_pages, (50ULL * kBytesPerMb) / page_size); | |
| EXPECT_EQ(*low_pages, (150ULL * kBytesPerMb) / page_size); | |
| EXPECT_EQ(*high_pages, (300ULL * kBytesPerMb) / page_size); | |
| } | |
| // Verify that /proc/vmstat shape is reasonable. | |
| TEST_F(ProcfsTest, VmStatFile) { | |
| auto path = "/proc/vmstat"; | |
| EXPECT_EQ(0, access(path, R_OK)); | |
| std::string content; | |
| ASSERT_TRUE(files::ReadFileToString(path, &content)); | |
| // Ensures that one node has `nr_inactive_file` and `nr_inactive_file`. | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)workingset_refault_file [0-9]+\n")); | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)nr_inactive_file [0-9]+\n")); | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)nr_active_file [0-9]+\n")); | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)pgscan_direct [0-9]+\n")); | |
| EXPECT_THAT(content, ContainsRegex("(\n|^)pgscan_kswapd [0-9]+\n")); | |
| } | |
| // Verify that /proc/net/dev format is correct. | |
| TEST_F(ProcfsTest, ProcNetDev) { | |
| auto path = "/proc/net/dev"; | |
| EXPECT_EQ(0, access(path, R_OK)); | |
| std::string content; | |
| ASSERT_TRUE(files::ReadFileToString(path, &content)); | |
| std::istringstream iss(content); | |
| std::string line; | |
| // Header 1 | |
| ASSERT_TRUE(std::getline(iss, line)); | |
| EXPECT_THAT(line, testing::HasSubstr("Inter-|")); | |
| // Header 2 | |
| ASSERT_TRUE(std::getline(iss, line)); | |
| EXPECT_THAT(line, testing::HasSubstr(" face |")); | |
| // Interfaces | |
| bool found_lo = false; | |
| while (std::getline(iss, line)) { | |
| // Trim leading spaces | |
| size_t start = line.find_first_not_of(" "); | |
| if (start == std::string::npos) { | |
| continue; // empty line | |
| } | |
| std::string trimmed = line.substr(start); | |
| size_t colon = trimmed.find(':'); | |
| ASSERT_NE(colon, std::string::npos) << "Line: " << line; | |
| std::string iface = trimmed.substr(0, colon); | |
| std::string stats_str = trimmed.substr(colon + 1); | |
| if (iface == "lo") { | |
| found_lo = true; | |
| } | |
| std::istringstream stats_iss(stats_str); | |
| uint64_t val; | |
| int count = 0; | |
| while (stats_iss >> val) { | |
| count++; | |
| } | |
| EXPECT_EQ(count, 16) << "Interface " << iface << " has " << count << " stats instead of 16"; | |
| } | |
| EXPECT_TRUE(found_lo) << "lo interface not found in /proc/net/dev"; | |
| } | |
| // Verify that writing invalid data to a numeric sysctl results in EINVAL. | |
| TEST_F(ProcfsTest, ProcSysNetInvalidWriteReturnsEinval) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Requires CAP_SYS_ADMIN to write to net interfaces, skipping."; | |
| } | |
| // This particular interface is an example of one which requires int-only values. | |
| std::string path = "/proc/sys/net/ipv4/neigh/default/ucast_solicit"; | |
| fbl::unique_fd fd(open(path.c_str(), O_WRONLY)); | |
| ASSERT_TRUE(fd.is_valid()); | |
| // "As she is spoke," the Linux kernel rejects null terminated values. This is true even if the | |
| // data value itself is an integer. The presence of non-numerical data alone causes rejection. | |
| const char kBadBuf[] = {'1', '\0'}; | |
| ssize_t n = write(fd.get(), kBadBuf, sizeof(kBadBuf)); | |
| EXPECT_EQ(n, -1); | |
| EXPECT_EQ(errno, EINVAL) << "Expected EINVAL when writing non-numeric data to " << path | |
| << " but got: " << strerror(errno); | |
| } | |
| // Writes to /proc/sys/kernel/tainted require CAP_SYS_ADMIN; Linux fails them with EPERM, | |
| // before parsing the value. | |
| TEST_F(ProcfsTest, ProcSysKernelTaintedWriteRequiresSysAdmin) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Requires CAP_SYS_ADMIN to open the file for writing, skipping."; | |
| } | |
| constexpr char kPath[] = "/proc/sys/kernel/tainted"; | |
| // Writing 0 adds no taint flags, so this is a no-op on both Linux and Starnix. | |
| { | |
| fbl::unique_fd fd(open(kPath, O_WRONLY)); | |
| ASSERT_THAT(fd.get(), SyscallSucceeds()); | |
| EXPECT_THAT(write(fd.get(), "0", 1), SyscallSucceedsWithValue(1)); | |
| } | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Open before dropping the capability: the file is mode 0644 and owned by root, so | |
| // this isolates the write-time capability check from the open-time DAC check. | |
| fbl::unique_fd fd(open(kPath, O_WRONLY)); | |
| ASSERT_THAT(fd.get(), SyscallSucceeds()); | |
| test_helper::UnsetCapabilityEffective(CAP_SYS_ADMIN); | |
| EXPECT_THAT(write(fd.get(), "0", 1), SyscallFailsWithErrno(EPERM)); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| class ProcSelfFdTest : public ProcTestBase { | |
| protected: | |
| std::string read_fd_link(int fd) { | |
| std::string path = fxl::StringPrintf(kProcSelfFdPath, fd); | |
| std::string links_to(PATH_MAX, 0); | |
| ssize_t result = SAFE_SYSCALL(readlink(path.c_str(), links_to.data(), links_to.capacity())); | |
| if (result < 0) { | |
| return fxl::StringPrintf("readlink() failed: %s", strerror(errno)); | |
| } | |
| links_to.resize(result); | |
| return links_to; | |
| } | |
| std::string expected_name(const char* kind, int fd) { | |
| struct stat stat_buf; | |
| if (SAFE_SYSCALL(fstat(fd, &stat_buf)) != 0) { | |
| return fxl::StringPrintf("fstat() failed: %s", strerror(errno)); | |
| } | |
| return fxl::StringPrintf("%s:[%lu]", kind, stat_buf.st_ino); | |
| } | |
| }; | |
| // Validate naming of anonymous pipes as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, AnonymousPipeFdName) { | |
| int pipes[2]; | |
| ASSERT_EQ(SAFE_SYSCALL(pipe2(pipes, 0)), 0) << "pipe() failed:" << strerror(errno); | |
| fbl::unique_fd pipe_a(pipes[0]); | |
| fbl::unique_fd pipe_b(pipes[1]); | |
| EXPECT_EQ(read_fd_link(pipe_a.get()), expected_name("pipe", pipe_a.get())); | |
| EXPECT_EQ(read_fd_link(pipe_b.get()), expected_name("pipe", pipe_b.get())); | |
| } | |
| // Validate naming of sockets as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, SocketFdName) { | |
| fbl::unique_fd sock(SAFE_SYSCALL(socket(AF_UNIX, SOCK_STREAM, 0))); | |
| ASSERT_TRUE(sock.is_valid()) << "socket() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(sock.get()), expected_name("socket", sock.get())); | |
| } | |
| // Validate naming of memory file descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, MemFdName) { | |
| constexpr char kMemFdName[] = "just_a_test_mem_fd"; | |
| fbl::unique_fd mem_fd(SAFE_SYSCALL(memfd_create(kMemFdName, 0))); | |
| ASSERT_TRUE(mem_fd.is_valid()) << "memfd_create() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(mem_fd.get()), fxl::StringPrintf("/memfd:%s (deleted)", kMemFdName)); | |
| } | |
| // Validate naming of timerfd descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, TimerFdName) { | |
| fbl::unique_fd timer_fd(SAFE_SYSCALL(timerfd_create(CLOCK_MONOTONIC, 0))); | |
| ASSERT_TRUE(timer_fd.is_valid()) << "timerfd_create() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(timer_fd.get()), "anon_inode:[timerfd]"); | |
| } | |
| // Validate naming of signalfd descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, SignalFdName) { | |
| sigset_t mask; | |
| ASSERT_EQ(sigemptyset(&mask), 0); | |
| ASSERT_EQ(sigaddset(&mask, SIGHUP), 0); | |
| fbl::unique_fd signal_fd(SAFE_SYSCALL(signalfd(-1, &mask, 0))); | |
| ASSERT_TRUE(signal_fd.is_valid()) << "signalfd_create() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(signal_fd.get()), "anon_inode:[signalfd]"); | |
| } | |
| // Validate naming of pidfd descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, PidFdName) { | |
| fbl::unique_fd pid_fd(SAFE_SYSCALL(static_cast<int>(syscall(SYS_pidfd_open, getpid(), 0)))); | |
| ASSERT_TRUE(pid_fd.is_valid()) << "syscall(SYS_pidfd_open) failed:" << strerror(errno); | |
| std::string result = read_fd_link(pid_fd.get()); | |
| EXPECT_THAT(result, AnyOf(Eq(expected_name("pidfd", pid_fd.get())), Eq("anon_inode:[pidfd]"))); | |
| } | |
| // Validate naming of inotify descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, InotifyFdName) { | |
| fbl::unique_fd inotify_fd(SAFE_SYSCALL(inotify_init())); | |
| ASSERT_TRUE(inotify_fd.is_valid()) << "inotify_init() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(inotify_fd.get()), "anon_inode:inotify"); | |
| } | |
| // Validate naming of epoll descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, EpollFdName) { | |
| fbl::unique_fd epoll_fd(SAFE_SYSCALL(epoll_create1(0))); | |
| ASSERT_TRUE(epoll_fd.is_valid()) << "epoll_create1() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(epoll_fd.get()), "anon_inode:[eventpoll]"); | |
| } | |
| // Validate naming of eventfd descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, EventFdName) { | |
| fbl::unique_fd event_fd(SAFE_SYSCALL(eventfd(0, 0))); | |
| ASSERT_TRUE(event_fd.is_valid()) << "eventfd() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(event_fd.get()), "anon_inode:[eventfd]"); | |
| } | |
| // Validate naming of normal (still file-system linked) descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, PathFdName) { | |
| constexpr char kTmpPath[] = "/tmp"; | |
| fbl::unique_fd tmp_fd(SAFE_SYSCALL(open(kTmpPath, O_RDONLY))); | |
| ASSERT_TRUE(tmp_fd.is_valid()) << "open(tmp) failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(tmp_fd.get()), kTmpPath); | |
| } | |
| // Validate naming of O_TMPFILE descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, TmpFileFdName) { | |
| constexpr char kTmpPath[] = "/tmp"; | |
| fbl::unique_fd tmpfile_fd(SAFE_SYSCALL(open(kTmpPath, O_RDWR | O_TMPFILE))); | |
| ASSERT_TRUE(tmpfile_fd.is_valid()) << "open(tmpfile) failed:" << strerror(errno); | |
| std::string result = read_fd_link(tmpfile_fd.get()); | |
| EXPECT_TRUE(result.starts_with(kTmpPath)) << " target: " << result; | |
| EXPECT_TRUE(result.ends_with(" (deleted)")) << " target: " << result; | |
| } | |
| // Validate naming of O_TMPFILE descriptors, and the naming of the file that it is linked into. | |
| TEST_F(ProcSelfFdTest, TmpFileLinkIntoAfterFdName) { | |
| // CAP_DAC_READ_SEARCH capability is required to use AT_EMPTY_PATH with linkat | |
| if (!test_helper::HasCapability(CAP_DAC_READ_SEARCH)) { | |
| GTEST_SKIP() << "Not running with CAP_DAC_READ_SEARCH capabilities, skipping."; | |
| } | |
| constexpr char kTmpPath[] = "/tmp"; | |
| fbl::unique_fd tmpfile_fd(SAFE_SYSCALL(open(kTmpPath, O_RDWR | O_TMPFILE))); | |
| ASSERT_TRUE(tmpfile_fd.is_valid()) << "open(tmpfile) failed:" << strerror(errno); | |
| std::string filename("/tmp/procfs_test_file"); | |
| SAFE_SYSCALL(linkat(tmpfile_fd.get(), "", AT_FDCWD, filename.c_str(), AT_EMPTY_PATH)); | |
| fbl::unique_fd linked_file_fd(open(filename.c_str(), O_RDONLY)); | |
| ASSERT_TRUE(linked_file_fd.is_valid()) << "Failed to open file:" << strerror(errno); | |
| std::string result_linked_file = read_fd_link(linked_file_fd.get()); | |
| EXPECT_EQ(result_linked_file, filename); | |
| std::string result_tmp_fd = read_fd_link(tmpfile_fd.get()); | |
| EXPECT_TRUE(result_tmp_fd.starts_with(kTmpPath)) << " target: " << result_tmp_fd; | |
| EXPECT_TRUE(result_tmp_fd.ends_with(" (deleted)")) << " target: " << result_tmp_fd; | |
| SAFE_SYSCALL(unlink(filename.c_str())); | |
| } | |
| // Validate naming of a file that is created, and opened, but then unlinked. | |
| TEST_F(ProcSelfFdTest, OpenedAndUnlinkedFileFdName) { | |
| std::string filename("/tmp/procfs_test_file:XXXXXX"); | |
| fbl::unique_fd fd(SAFE_SYSCALL(mkstemp(filename.data()))); | |
| ASSERT_TRUE(fd.is_valid()) << "mkstemp() failed:" << strerror(errno); | |
| std::string result = read_fd_link(fd.get()); | |
| EXPECT_EQ(result, filename); | |
| ASSERT_EQ(SAFE_SYSCALL(unlink(filename.data())), 0) << "unlink() failed:" << strerror(errno); | |
| result = read_fd_link(fd.get()); | |
| EXPECT_EQ(result, filename + " (deleted)"); | |
| } | |
| // Validate naming of a file that is created, and opened, but then unlinked, and is also | |
| // unreachable. | |
| TEST_F(ProcSelfFdTest, DeletedAndUnreachable) { | |
| if (!test_helper::HasCapability(CAP_SYS_CHROOT)) { | |
| GTEST_SKIP() << "Not running with chroot capability, skipping"; | |
| } | |
| std::string filename("/tmp/procfs_test_file:XXXXXX"); | |
| fbl::unique_fd fd(SAFE_SYSCALL(mkstemp(filename.data()))); | |
| ASSERT_TRUE(fd.is_valid()) << "mkstemp() failed:" << strerror(errno); | |
| unlink(filename.c_str()); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| SAFE_SYSCALL(chroot("/proc/self")); | |
| std::string path = fxl::StringPrintf("/fd/%d", fd.get()); | |
| std::string links_to(PATH_MAX, 0); | |
| ssize_t result = SAFE_SYSCALL(readlink(path.c_str(), links_to.data(), links_to.capacity())); | |
| if (result < 0) { | |
| return; | |
| } | |
| links_to.resize(result); | |
| EXPECT_EQ(links_to, filename + " (deleted)"); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| // Validate naming of perf_event_open descriptors as reported via "/proc/self/fd". | |
| TEST_F(ProcSelfFdTest, PerfEventFdName) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Require CAP_SYS_ADMIN to test perf_event_open(), Skipping."; | |
| } | |
| perf_event_attr attr{}; | |
| attr.type = PERF_TYPE_SOFTWARE; | |
| attr.size = sizeof(attr); | |
| attr.config = PERF_COUNT_SW_CPU_CLOCK; | |
| attr.sample_type = PERF_SAMPLE_IP; | |
| attr.disabled = true; | |
| attr.exclude_kernel = true; | |
| attr.exclude_hv = true; | |
| attr.exclude_idle = true; | |
| fbl::unique_fd perf_event_fd(SAFE_SYSCALL(static_cast<int>( | |
| syscall(SYS_perf_event_open, &attr, /*pid=*/0, /*cpu=*/-1, /*group_fd=*/-1, /*flags=*/0)))); | |
| ASSERT_TRUE(perf_event_fd.is_valid()) << "perf_event_open() failed:" << strerror(errno); | |
| EXPECT_EQ(read_fd_link(perf_event_fd.get()), "anon_inode:[perf_event]"); | |
| } | |
| struct ProcSelfFdEntryParam { | |
| const char* name; | |
| // The task directory that holds `fd` and `fdinfo`. | |
| const char* task_dir; | |
| }; | |
| // Tests for the fd/<N> and fdinfo/<N> entries of the calling task, reached through /proc/self | |
| // (thread group) or /proc/thread-self (which resolves to /proc/<pid>/task/<tid>). | |
| // | |
| // Each test looks an entry up before it changes the descriptor, so that the later lookup finds an | |
| // entry that already exists rather than a new one. | |
| class ProcSelfFdEntryTest : public ProcTestBase, | |
| public ::testing::WithParamInterface<ProcSelfFdEntryParam> { | |
| protected: | |
| static std::string fd_path(int fd) { | |
| return fxl::StringPrintf("%s/fd/%d", GetParam().task_dir, fd); | |
| } | |
| static std::string fdinfo_path(int fd) { | |
| return fxl::StringPrintf("%s/fdinfo/%d", GetParam().task_dir, fd); | |
| } | |
| static std::string read_fd_entry_link(int fd) { | |
| std::string links_to(PATH_MAX, 0); | |
| ssize_t result = readlink(fd_path(fd).c_str(), links_to.data(), links_to.size()); | |
| if (result < 0) { | |
| return fxl::StringPrintf("readlink() failed: %s", strerror(errno)); | |
| } | |
| links_to.resize(result); | |
| return links_to; | |
| } | |
| // Returns the `flags:` field of fdinfo/<N>, without masking. | |
| static std::optional<int> read_fdinfo_flags(int fd) { | |
| std::string contents; | |
| if (!files::ReadFileToString(fdinfo_path(fd), &contents)) { | |
| return std::nullopt; | |
| } | |
| std::istringstream stream(contents); | |
| std::string line; | |
| while (std::getline(stream, line)) { | |
| unsigned int flags = 0; | |
| if (sscanf(line.c_str(), "flags:\t%o", &flags) == 1) { | |
| return static_cast<int>(flags); | |
| } | |
| } | |
| return std::nullopt; | |
| } | |
| // Checks that fd/<N> and fdinfo/<N> describe a descriptor for `target` opened with `open_flags`. | |
| static void ExpectFdEntriesMatch(int fd, const std::string& target, int open_flags, | |
| mode_t expected_mode) { | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(AT_FDCWD, fd_path(fd).c_str(), &st, AT_SYMLINK_NOFOLLOW), | |
| SyscallSucceeds()); | |
| EXPECT_EQ(st.st_mode, expected_mode); | |
| EXPECT_EQ(read_fd_entry_link(fd), target); | |
| std::optional<int> flags = read_fdinfo_flags(fd); | |
| ASSERT_TRUE(flags.has_value()); | |
| EXPECT_EQ(*flags & O_ACCMODE, open_flags & O_ACCMODE); | |
| EXPECT_EQ(*flags & O_PATH, open_flags & O_PATH); | |
| } | |
| }; | |
| // Validate that fd/<N> and fdinfo/<N> report the new mode, target and flags each time dup2() | |
| // replaces the descriptor in slot N. Each step re-reads entries that the previous step read. | |
| TEST_P(ProcSelfFdEntryTest, UpdatedAfterDup2) { | |
| test_helper::ScopedTempFD file_a; | |
| test_helper::ScopedTempFD file_b; | |
| ASSERT_TRUE(file_a); | |
| ASSERT_TRUE(file_b); | |
| fbl::unique_fd slot_fd(open(file_a.name().c_str(), O_RDONLY)); | |
| ASSERT_TRUE(slot_fd.is_valid()) << strerror(errno); | |
| { | |
| SCOPED_TRACE("before dup2()"); | |
| ExpectFdEntriesMatch(slot_fd.get(), file_a.name(), O_RDONLY, S_IFLNK | 0500); | |
| } | |
| const struct { | |
| std::string target; | |
| int open_flags; | |
| mode_t expected_mode; | |
| } steps[] = { | |
| {.target = file_b.name(), .open_flags = O_WRONLY, .expected_mode = S_IFLNK | 0300}, | |
| {.target = file_b.name(), .open_flags = O_RDWR, .expected_mode = S_IFLNK | 0700}, | |
| {.target = file_a.name(), .open_flags = O_PATH, .expected_mode = S_IFLNK | 0000}, | |
| }; | |
| for (const auto& [target, open_flags, expected_mode] : steps) { | |
| SCOPED_TRACE(fxl::StringPrintf("dup2() of open_flags=0%o", open_flags)); | |
| fbl::unique_fd new_fd(open(target.c_str(), open_flags)); | |
| ASSERT_TRUE(new_fd.is_valid()) << strerror(errno); | |
| ASSERT_THAT(dup2(new_fd.get(), slot_fd.get()), SyscallSucceeds()); | |
| ExpectFdEntriesMatch(slot_fd.get(), target, open_flags, expected_mode); | |
| } | |
| } | |
| // Validate that fd/<N> and fdinfo/<N> are gone once N is closed. | |
| TEST_P(ProcSelfFdEntryTest, RemovedAfterClose) { | |
| test_helper::ScopedTempFD file; | |
| ASSERT_TRUE(file); | |
| fbl::unique_fd fd(open(file.name().c_str(), O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()) << strerror(errno); | |
| const int raw_fd = fd.get(); | |
| ASSERT_NO_FATAL_FAILURE(ExpectFdEntriesMatch(raw_fd, file.name(), O_RDONLY, S_IFLNK | 0500)); | |
| ASSERT_THAT(close(fd.release()), SyscallSucceeds()); | |
| struct stat st{}; | |
| EXPECT_THAT(fstatat(AT_FDCWD, fd_path(raw_fd).c_str(), &st, AT_SYMLINK_NOFOLLOW), | |
| SyscallFailsWithErrno(ENOENT)); | |
| char buf[PATH_MAX]; | |
| EXPECT_THAT(readlink(fd_path(raw_fd).c_str(), buf, sizeof(buf)), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(fbl::unique_fd(open(fdinfo_path(raw_fd).c_str(), O_RDONLY)).get(), | |
| SyscallFailsWithErrno(ENOENT)); | |
| } | |
| // Validate that fd/<N> and fdinfo/<N> describe the new descriptor after N is closed and reused. | |
| // Unlike RemovedAfterClose, nothing looks N up between close() and the reopen. | |
| TEST_P(ProcSelfFdEntryTest, UpdatedAfterSlotReuse) { | |
| test_helper::ScopedTempFD file_a; | |
| test_helper::ScopedTempFD file_b; | |
| ASSERT_TRUE(file_a); | |
| ASSERT_TRUE(file_b); | |
| fbl::unique_fd slot_fd(open(file_a.name().c_str(), O_RDONLY)); | |
| ASSERT_TRUE(slot_fd.is_valid()) << strerror(errno); | |
| const int raw_slot_fd = slot_fd.get(); | |
| { | |
| SCOPED_TRACE("before close()"); | |
| ExpectFdEntriesMatch(raw_slot_fd, file_a.name(), O_RDONLY, S_IFLNK | 0500); | |
| } | |
| ASSERT_THAT(close(slot_fd.release()), SyscallSucceeds()); | |
| // open() returns the lowest free descriptor, which is the slot we just closed. | |
| slot_fd.reset(open(file_b.name().c_str(), O_RDWR)); | |
| ASSERT_TRUE(slot_fd.is_valid()) << strerror(errno); | |
| ASSERT_EQ(slot_fd.get(), raw_slot_fd); | |
| { | |
| SCOPED_TRACE("after reopen"); | |
| ExpectFdEntriesMatch(raw_slot_fd, file_b.name(), O_RDWR, S_IFLNK | 0700); | |
| } | |
| } | |
| INSTANTIATE_TEST_SUITE_P( | |
| ProcSelfFdEntryTest, ProcSelfFdEntryTest, | |
| ::testing::Values(ProcSelfFdEntryParam{.name = "Self", .task_dir = "/proc/self"}, | |
| ProcSelfFdEntryParam{.name = "ThreadSelf", .task_dir = "/proc/thread-self"}), | |
| [](const auto& info) { return info.param.name; }); | |
| class ProcMmTest : public ProcTestBase, public ::testing::WithParamInterface<const char*> {}; | |
| TEST_P(ProcMmTest, ReadBeforeAfterExec) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| test_helper::ForkHelper fork_helper; | |
| test_helper::ScopedPipe child_stdout; | |
| test_helper::ScopedPipe child_stdin; | |
| test_helper::Rendezvous fork_ready = test_helper::MakeRendezvous(); | |
| test_helper::Rendezvous exec_ready = test_helper::MakeRendezvous(); | |
| pid_t child_pid = fork_helper.RunInForkedProcess( | |
| [child_stdout = &child_stdout.WriteSide(), child_stdin = &child_stdin.ReadSide(), | |
| fork_ready = std::move(fork_ready.poker), | |
| exec_ready = std::move(exec_ready.holder)]() mutable { | |
| // Inform the test that the fork succeeded. | |
| fork_ready.poke(); | |
| // Use the pipes for stdin & stdout. Stderr remains unchanged, to allow error output. | |
| SAFE_SYSCALL(dup2(child_stdin->get(), STDIN_FILENO)); | |
| child_stdin->reset(); | |
| SAFE_SYSCALL(dup2(child_stdout->get(), STDOUT_FILENO)); | |
| child_stdout->reset(); | |
| // Wait for the test to indicate that it's ready for the child to exec. | |
| exec_ready.hold(); | |
| // exec the test binary. | |
| std::string binary_path = GetExecChildBinaryPath(); | |
| char* const argv[] = {const_cast<char*>(binary_path.c_str()), nullptr}; | |
| SAFE_SYSCALL(execve(binary_path.c_str(), argv, nullptr)); | |
| _exit(EXIT_FAILURE); | |
| }); | |
| // Wait for the child to indicate that it was forked. | |
| fork_ready.holder.hold(); | |
| // Check that file is not empty before exec. | |
| std::string path = fxl::StringPrintf("/proc/%d/%s", child_pid, GetParam()); | |
| std::string initial_contents; | |
| EXPECT_TRUE(files::ReadFileToString(path, &initial_contents)); | |
| EXPECT_THAT(initial_contents.size(), testing::Gt(0)); | |
| // Open the file, keeping it open until after exec. | |
| fbl::unique_fd fd(SAFE_SYSCALL(open(path.c_str(), O_RDONLY))); | |
| ASSERT_TRUE(fd.is_valid()); | |
| // Trigger the exec and wait for the child to indicate that it's ready. | |
| exec_ready.poker.poke(); | |
| test_helper::Rendezvous child_ready = test_helper::MakeRendezvous(std::move(child_stdout)); | |
| child_ready.holder.hold(); | |
| // Check that the existing file descriptor is empty. | |
| char buf[1]; | |
| EXPECT_EQ(read(fd.get(), buf, sizeof buf), 0); | |
| fd.reset(); | |
| // Let the child exit. | |
| test_helper::Rendezvous child_exit = test_helper::MakeRendezvous(std::move(child_stdin)); | |
| child_exit.poker.poke(); | |
| ASSERT_TRUE(fork_helper.WaitForChildren()); | |
| } | |
| INSTANTIATE_TEST_SUITE_P(ProcMmTest, ProcMmTest, ::testing::Values("maps", "smaps"), | |
| [](const auto& info) { return info.param; }); | |
| struct ProcfsAccessParam { | |
| const char* path; | |
| bool requires_ptrace; | |
| }; | |
| class ProcfsAccessTest : public ProcTestBase, | |
| public ::testing::WithParamInterface<ProcfsAccessParam> {}; | |
| // Verify that an unprivileged process cannot read sensitive files of another process. | |
| // This reproduces the bug where Starnix allows access without proper checks. | |
| TEST_P(ProcfsAccessTest, AccessDeniedToNonOwner) { | |
| if (getuid() != 0) { | |
| GTEST_SKIP() << "Not running as root, skipping."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Switch to a different UID so we are not the owner of the parent process. | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| ASSERT_NE(getuid(), 0u); | |
| std::string path = fxl::StringPrintf("/proc/%d/%s", parent_pid, GetParam().path); | |
| // Access to the file should be denied, either via permissions, or lack of CAP_SYS_PTRACE. | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallFailsWithErrno(EACCES)); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_P(ProcfsAccessTest, AccessDeniedToNonOwnerWithoutCapPtrace) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| if (getuid() != 0) { | |
| GTEST_SKIP() << "Not running as root, skipping."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Keep capabilities after setuid to verify access with CAP_SYS_PTRACE. | |
| SAFE_SYSCALL(prctl(PR_SET_KEEPCAPS, 1)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| // On standard Linux, CAP_SYS_PTRACE alone might not be enough to bypass | |
| // file permission checks (DAC) for /proc/<pid>/environ if it's 0400 owned by root. | |
| // We add DAC overrides to ensure we are testing the ptrace check, not DAC. | |
| test_helper::SetCapabilityEffective(CAP_DAC_OVERRIDE); | |
| test_helper::SetCapabilityEffective(CAP_DAC_READ_SEARCH); | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYS_PTRACE)); | |
| ASSERT_NE(getuid(), 0u); | |
| // Without CAP_SYS_PTRACE access should be denied if it requires ptrace. | |
| std::string path = fxl::StringPrintf("/proc/%d/%s", parent_pid, GetParam().path); | |
| if (GetParam().requires_ptrace) { | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallFailsWithErrno(EACCES)); | |
| } else { | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallSucceeds()); | |
| } | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_P(ProcfsAccessTest, AccessGrantedWithCapPtrace) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| if (getuid() != 0) { | |
| GTEST_SKIP() << "Not running as root, skipping."; | |
| } | |
| pid_t parent_pid = getpid(); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| // Keep capabilities after setuid to verify access with CAP_SYS_PTRACE. | |
| SAFE_SYSCALL(prctl(PR_SET_KEEPCAPS, 1)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| // Explicitly set CAP_SYS_PTRACE effective again (if permitted). | |
| test_helper::SetCapabilityEffective(CAP_SYS_PTRACE); | |
| // On standard Linux, CAP_SYS_PTRACE alone might not be enough to bypass | |
| // file permission checks (DAC) for /proc/<pid>/environ if it's 0400 owned by root. | |
| // We add DAC overrides to ensure we are testing the ptrace check, not DAC. | |
| test_helper::SetCapabilityEffective(CAP_DAC_OVERRIDE); | |
| test_helper::SetCapabilityEffective(CAP_DAC_READ_SEARCH); | |
| ASSERT_TRUE(test_helper::HasCapabilityEffective(CAP_SYS_PTRACE)); | |
| ASSERT_NE(getuid(), 0u); | |
| // With CAP_SYS_PTRACE, CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH, access should be granted. | |
| std::string path = fxl::StringPrintf("/proc/%d/%s", parent_pid, GetParam().path); | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallSucceeds()); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| TEST_P(ProcfsAccessTest, AccessGrantedToSelf) { | |
| std::string path = fxl::StringPrintf("/proc/self/%s", GetParam().path); | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallSucceeds()); | |
| } | |
| INSTANTIATE_TEST_SUITE_P( | |
| ProcfsAccessTest, ProcfsAccessTest, | |
| ::testing::Values(ProcfsAccessParam{"auxv", true}, ProcfsAccessParam{"environ", true}, | |
| ProcfsAccessParam{"maps", true}, ProcfsAccessParam{"mem", true}, | |
| ProcfsAccessParam{"pagemap", true}, ProcfsAccessParam{"smaps", true}, | |
| ProcfsAccessParam{"smaps_rollup", true}, ProcfsAccessParam{"fdinfo", true}, | |
| ProcfsAccessParam{"fd", false}), | |
| [](const auto& info) { return info.param.path; }); | |
| TEST(ProcFilesystemsTest, Format) { | |
| std::string contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/filesystems", &contents)); | |
| std::istringstream stream(contents); | |
| std::string line; | |
| bool saw_tmpfs = false; | |
| bool saw_proc = false; | |
| bool saw_sysfs = false; | |
| bool saw_ext4 = false; | |
| while (std::getline(stream, line)) { | |
| if (line.empty()) { | |
| continue; | |
| } | |
| if (line == "nodev\ttmpfs") { | |
| saw_tmpfs = true; | |
| } else if (line == "nodev\tproc") { | |
| saw_proc = true; | |
| } else if (line == "nodev\tsysfs") { | |
| saw_sysfs = true; | |
| } else if (line == "\text4") { | |
| saw_ext4 = true; | |
| } | |
| EXPECT_TRUE(line.starts_with("nodev\t") || line.starts_with("\t")) | |
| << "Unexpected line format: " << line; | |
| } | |
| EXPECT_TRUE(saw_tmpfs); | |
| EXPECT_TRUE(saw_proc); | |
| EXPECT_TRUE(saw_sysfs); | |
| EXPECT_TRUE(saw_ext4); | |
| } | |
| TEST_F(ProcfsTest, ZombieProcessStatusAccessible) { | |
| test_helper::Rendezvous ready = test_helper::MakeRendezvous(); | |
| test_helper::Rendezvous exit_now = test_helper::MakeRendezvous(); | |
| pid_t child_pid = fork(); | |
| ASSERT_GE(child_pid, 0); | |
| if (child_pid == 0) { | |
| ready.poker.poke(); | |
| exit_now.holder.hold(); | |
| _exit(0); | |
| } | |
| auto cleanup_child = fit::defer([child_pid] { | |
| kill(child_pid, SIGKILL); | |
| waitpid(child_pid, nullptr, 0); | |
| }); | |
| ready.holder.hold(); | |
| std::string child_proc_dir = fxl::StringPrintf("/proc/%d", child_pid); | |
| std::string status_path = fxl::StringPrintf("/proc/%d/status", child_pid); | |
| // Wait for the child to exit and become an unreaped zombie before looking up | |
| // /proc/<pid>/status so that uncached zombie lookup in /proc is exercised. | |
| exit_now.poker.poke(); | |
| siginfo_t info{}; | |
| ASSERT_THAT(waitid(P_PID, child_pid, &info, WEXITED | WNOWAIT), SyscallSucceeds()); | |
| std::string status_contents; | |
| ASSERT_TRUE(files::ReadFileToString(status_path, &status_contents)) << strerror(errno); | |
| EXPECT_THAT(status_contents, ContainsRegex("Name:\t")); | |
| EXPECT_THAT(status_contents, ContainsRegex(fxl::StringPrintf("Pid:\t%d", child_pid))); | |
| EXPECT_THAT(status_contents, ContainsRegex("State:\tZ")); | |
| int status = 0; | |
| ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds()); | |
| cleanup_child.cancel(); | |
| struct stat st{}; | |
| EXPECT_THAT(stat(child_proc_dir.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| } | |
| // Forks a child that exits immediately and waits until it is an unreaped zombie. The caller must | |
| // reap `*child_pid` if this succeeds without fatal failure. | |
| void ForkZombie(pid_t* child_pid) { | |
| *child_pid = fork(); | |
| ASSERT_GE(*child_pid, 0); | |
| if (*child_pid == 0) { | |
| _exit(0); | |
| } | |
| auto cleanup_child = fit::defer([pid = *child_pid] { | |
| kill(pid, SIGKILL); | |
| waitpid(pid, nullptr, 0); | |
| }); | |
| siginfo_t info{}; | |
| ASSERT_THAT(waitid(P_PID, *child_pid, &info, WEXITED | WNOWAIT), SyscallSucceeds()); | |
| cleanup_child.cancel(); | |
| } | |
| std::string ReadLink(const std::string& path) { | |
| char buf[256]; | |
| ssize_t len = readlink(path.c_str(), buf, sizeof(buf)); | |
| return len < 0 ? std::string() : std::string(buf, len); | |
| } | |
| TEST_F(ProcfsTest, NsLinkLstatZombieSucceeds) { | |
| pid_t child_pid; | |
| ASSERT_NO_FATAL_FAILURE(ForkZombie(&child_pid)); | |
| auto reap_child = fit::defer([child_pid] { waitpid(child_pid, nullptr, 0); }); | |
| std::string path = fxl::StringPrintf("/proc/%d/ns/mnt", child_pid); | |
| struct stat st{}; | |
| ASSERT_THAT(fstatat(AT_FDCWD, path.c_str(), &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()); | |
| EXPECT_TRUE(S_ISLNK(st.st_mode)); | |
| } | |
| TEST_F(ProcfsTest, NsLinkReadlinkZombieFails) { | |
| pid_t child_pid; | |
| ASSERT_NO_FATAL_FAILURE(ForkZombie(&child_pid)); | |
| auto reap_child = fit::defer([child_pid] { waitpid(child_pid, nullptr, 0); }); | |
| std::string path = fxl::StringPrintf("/proc/%d/ns/mnt", child_pid); | |
| char buf[256]; | |
| EXPECT_THAT(readlink(path.c_str(), buf, sizeof(buf)), SyscallFailsWithErrno(ENOENT)); | |
| } | |
| TEST_F(ProcfsTest, NsPidForChildrenLinksToPidNamespace) { | |
| std::string target = ReadLink("/proc/self/ns/pid_for_children"); | |
| EXPECT_THAT(target, ContainsRegex("^pid:\\[[0-9]+\\]$")); | |
| EXPECT_EQ(target, ReadLink("/proc/self/ns/pid")); | |
| } | |
| TEST_F(ProcfsTest, NsTimeForChildrenLinksToTimeNamespace) { | |
| if (access("/proc/self/ns/time", F_OK) != 0) { | |
| GTEST_SKIP() << "Time namespaces are not supported, skipping."; | |
| } | |
| std::string target = ReadLink("/proc/self/ns/time_for_children"); | |
| EXPECT_THAT(target, ContainsRegex("^time:\\[[0-9]+\\]$")); | |
| EXPECT_EQ(target, ReadLink("/proc/self/ns/time")); | |
| } | |
| // Linux requires ptrace read access to read or follow another process's /proc/<pid>/ns links, but | |
| // not to look up the links themselves. | |
| class ProcNsOtherUserTest : public ProcTestBase { | |
| protected: | |
| void SetUp() override { | |
| ProcTestBase::SetUp(); | |
| if (getuid() != 0) { | |
| GTEST_SKIP() << "Not running as root, skipping."; | |
| } | |
| } | |
| // Runs `fn` with the path of this process's ns/mnt link, in a child process that runs as a | |
| // different, unprivileged user. | |
| void RunAsOtherUser(fit::function<void(const std::string&)> fn) { | |
| std::string path = fxl::StringPrintf("/proc/%d/ns/mnt", getpid()); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| fn(path); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| } | |
| }; | |
| TEST_F(ProcNsOtherUserTest, LstatSucceeds) { | |
| RunAsOtherUser([](const std::string& path) { | |
| struct stat st{}; | |
| EXPECT_THAT(fstatat(AT_FDCWD, path.c_str(), &st, AT_SYMLINK_NOFOLLOW), SyscallSucceeds()); | |
| }); | |
| } | |
| TEST_F(ProcNsOtherUserTest, ReadlinkFails) { | |
| RunAsOtherUser([](const std::string& path) { | |
| char buf[256]; | |
| EXPECT_THAT(readlink(path.c_str(), buf, sizeof(buf)), SyscallFailsWithErrno(EACCES)); | |
| }); | |
| } | |
| TEST_F(ProcNsOtherUserTest, OpenFails) { | |
| RunAsOtherUser([](const std::string& path) { | |
| EXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallFailsWithErrno(EACCES)); | |
| }); | |
| } | |
| TEST_F(ProcfsTest, LeaderlessThreadGroupAccessible) { | |
| int raw_pipe[2]; | |
| ASSERT_THAT(pipe(raw_pipe), SyscallSucceeds()); | |
| fbl::unique_fd tid_pipe_read(raw_pipe[0]); | |
| fbl::unique_fd tid_pipe_write(raw_pipe[1]); | |
| test_helper::Rendezvous exit_worker = test_helper::MakeRendezvous(); | |
| pid_t child_pid = fork(); | |
| ASSERT_GE(child_pid, 0); | |
| if (child_pid == 0) { | |
| tid_pipe_read.reset(); | |
| int write_fd = tid_pipe_write.release(); | |
| test_helper::Rendezvous worker_started = test_helper::MakeRendezvous(); | |
| std::thread worker([write_fd, &worker_started, &exit_worker] { | |
| pid_t worker_tid = static_cast<pid_t>(syscall(SYS_gettid)); | |
| SAFE_SYSCALL(write(write_fd, &worker_tid, sizeof(worker_tid))); | |
| close(write_fd); | |
| worker_started.poker.poke(); | |
| exit_worker.holder.hold(); | |
| _exit(0); | |
| }); | |
| worker.detach(); | |
| worker_started.holder.hold(); | |
| syscall(SYS_exit, 0); | |
| } | |
| auto cleanup_child = fit::defer([child_pid] { | |
| kill(child_pid, SIGKILL); | |
| waitpid(child_pid, nullptr, 0); | |
| }); | |
| tid_pipe_write.reset(); | |
| pid_t worker_tid = 0; | |
| ASSERT_EQ(read(tid_pipe_read.get(), &worker_tid, sizeof(worker_tid)), | |
| static_cast<ssize_t>(sizeof(worker_tid))); | |
| tid_pipe_read.reset(); | |
| // Wait for the thread-group leader to exit. On Linux, the exited group leader remains in | |
| // /proc/<pid>/task/<pid> in State: Z until the entire thread group exits; on Starnix, the | |
| // exited leader's task entry is removed immediately (ENOENT). | |
| std::string leader_status_path = | |
| fxl::StringPrintf("/proc/%d/task/%d/status", child_pid, child_pid); | |
| while (true) { | |
| std::string leader_status; | |
| if (!files::ReadFileToString(leader_status_path, &leader_status)) { | |
| EXPECT_THAT(open(leader_status_path.c_str(), O_RDONLY), SyscallFailsWithErrno(ENOENT)); | |
| break; | |
| } | |
| if (!test_helper::IsStarnix() && leader_status.find("State:\tZ") != std::string::npos) { | |
| break; | |
| } | |
| usleep(1000); | |
| } | |
| std::string status_path = fxl::StringPrintf("/proc/%d/status", child_pid); | |
| std::string status_contents; | |
| ASSERT_TRUE(files::ReadFileToString(status_path, &status_contents)) << strerror(errno); | |
| EXPECT_THAT(status_contents, ContainsRegex(fxl::StringPrintf("Tgid:\t%d", child_pid))); | |
| EXPECT_THAT(status_contents, ContainsRegex(fxl::StringPrintf("Pid:\t%d", child_pid))); | |
| std::string stat_path = fxl::StringPrintf("/proc/%d/stat", child_pid); | |
| std::string stat_contents; | |
| ASSERT_TRUE(files::ReadFileToString(stat_path, &stat_contents)) << strerror(errno); | |
| EXPECT_FALSE(stat_contents.empty()); | |
| std::string limits_path = fxl::StringPrintf("/proc/%d/limits", child_pid); | |
| std::string limits_contents; | |
| ASSERT_TRUE(files::ReadFileToString(limits_path, &limits_contents)) << strerror(errno); | |
| EXPECT_FALSE(limits_contents.empty()); | |
| if (test_helper::IsStarnix()) { | |
| std::string mounts_path = fxl::StringPrintf("/proc/%d/mounts", child_pid); | |
| std::string mounts_contents; | |
| ASSERT_TRUE(files::ReadFileToString(mounts_path, &mounts_contents)) << strerror(errno); | |
| EXPECT_FALSE(mounts_contents.empty()); | |
| std::string mountinfo_path = fxl::StringPrintf("/proc/%d/mountinfo", child_pid); | |
| std::string mountinfo_contents; | |
| ASSERT_TRUE(files::ReadFileToString(mountinfo_path, &mountinfo_contents)) << strerror(errno); | |
| EXPECT_FALSE(mountinfo_contents.empty()); | |
| } | |
| std::string task_list_dir = fxl::StringPrintf("/proc/%d/task", child_pid); | |
| std::vector<std::string> task_entries; | |
| ASSERT_TRUE(files::ReadDirContents(task_list_dir, &task_entries)); | |
| EXPECT_EQ(std::count(task_entries.begin(), task_entries.end(), std::to_string(worker_tid)), 1); | |
| if (test_helper::IsStarnix()) { | |
| EXPECT_EQ(std::count(task_entries.begin(), task_entries.end(), std::to_string(child_pid)), 0); | |
| } | |
| std::string worker_status_path = | |
| fxl::StringPrintf("/proc/%d/task/%d/status", child_pid, worker_tid); | |
| std::string worker_status; | |
| ASSERT_TRUE(files::ReadFileToString(worker_status_path, &worker_status)) << strerror(errno); | |
| EXPECT_THAT(worker_status, ContainsRegex(fxl::StringPrintf("Pid:\t%d", worker_tid))); | |
| exit_worker.poker.poke(); | |
| int status = 0; | |
| ASSERT_THAT(waitpid(child_pid, &status, 0), SyscallSucceeds()); | |
| cleanup_child.cancel(); | |
| } | |
| TEST(ProcHidePidTest, HidePidAndGidMountOptions) { | |
| if (!test_helper::HasSysAdmin()) { | |
| GTEST_SKIP() << "Not running with sysadmin capabilities, skipping."; | |
| } | |
| if (getuid() != 0) { | |
| GTEST_SKIP() << "Not running as root, skipping."; | |
| } | |
| test_helper::ScopedTempDir temp_dir; | |
| ASSERT_THAT(mount("proc", temp_dir.path().c_str(), "proc", 0, "hidepid=2,gid=3009"), | |
| SyscallSucceeds()); | |
| auto cleanup = fit::defer([&] { | |
| mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=0,gid=0"); | |
| umount2(temp_dir.path().c_str(), MNT_DETACH); | |
| }); | |
| std::string mounts_contents; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/mounts", &mounts_contents)); | |
| EXPECT_THAT(mounts_contents, ContainsRegex("gid=3009,hidepid=(2|invisible)")); | |
| pid_t parent_pid = getpid(); | |
| std::string parent_proc_dir = fxl::StringPrintf("%s/%d", temp_dir.path().c_str(), parent_pid); | |
| std::string parent_cmdline = | |
| fxl::StringPrintf("%s/%d/cmdline", temp_dir.path().c_str(), parent_pid); | |
| std::string parent_task_dir = | |
| fxl::StringPrintf("%s/%d/task/%d", temp_dir.path().c_str(), parent_pid, parent_pid); | |
| std::string parent_task_cmdline = | |
| fxl::StringPrintf("%s/%d/task/%d/cmdline", temp_dir.path().c_str(), parent_pid, parent_pid); | |
| // Keep open FDs to parent's /proc/<pid> and /proc/<pid>/task/<tid> so their dentries remain | |
| // pinned in DirEntry::children (which holds Weak<DirEntry>) and cached dentry revalidation | |
| // is exercised for unprivileged callers. | |
| fbl::unique_fd pinned_proc_fd(SAFE_SYSCALL(open(parent_proc_dir.c_str(), O_PATH | O_DIRECTORY))); | |
| fbl::unique_fd pinned_task_fd(SAFE_SYSCALL(open(parent_task_dir.c_str(), O_PATH | O_DIRECTORY))); | |
| struct stat parent_st{}; | |
| ASSERT_THAT(stat(parent_cmdline.c_str(), &parent_st), SyscallSucceeds()); | |
| ASSERT_THAT(stat(parent_task_cmdline.c_str(), &parent_st), SyscallSucceeds()); | |
| // An unprivileged process not in gid 3009 cannot see or stat parent's /proc/<pid> | |
| // or /proc/<pid>/task/<tid>, but can see and stat its own /proc/<pid>. | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| SAFE_SYSCALL(setgroups(0, nullptr)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| struct stat st{}; | |
| EXPECT_THAT(stat(parent_proc_dir.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(open(parent_cmdline.c_str(), O_RDONLY), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(stat(parent_task_dir.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(open(parent_task_cmdline.c_str(), O_RDONLY), SyscallFailsWithErrno(ENOENT)); | |
| struct statx stx{}; | |
| EXPECT_THAT(syscall(SYS_statx, pinned_proc_fd.get(), "", AT_EMPTY_PATH | AT_STATX_DONT_SYNC, | |
| STATX_BASIC_STATS, &stx), | |
| SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(syscall(SYS_statx, pinned_task_fd.get(), "", AT_EMPTY_PATH | AT_STATX_DONT_SYNC, | |
| STATX_BASIC_STATS, &stx), | |
| SyscallFailsWithErrno(ENOENT)); | |
| std::string self_proc_dir = fxl::StringPrintf("%s/%d", temp_dir.path().c_str(), getpid()); | |
| std::string self_task_dir = | |
| fxl::StringPrintf("%s/%d/task/%d", temp_dir.path().c_str(), getpid(), getpid()); | |
| EXPECT_THAT(stat(self_proc_dir.c_str(), &st), SyscallSucceeds()); | |
| EXPECT_THAT(stat(self_task_dir.c_str(), &st), SyscallSucceeds()); | |
| std::vector<std::string> entries; | |
| ASSERT_TRUE(files::ReadDirContents(temp_dir.path(), &entries)); | |
| EXPECT_EQ(std::count(entries.begin(), entries.end(), std::to_string(parent_pid)), 0); | |
| EXPECT_EQ(std::count(entries.begin(), entries.end(), std::to_string(getpid())), 1); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| pinned_proc_fd.reset(); | |
| pinned_task_fd.reset(); | |
| // An unprivileged process in gid 3009 can see and stat parent's /proc/<pid> and | |
| // /proc/<pid>/task/<tid>. | |
| helper.RunInForkedProcess([&] { | |
| gid_t groups[] = {3009}; | |
| SAFE_SYSCALL(setgroups(1, groups)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| struct stat st{}; | |
| EXPECT_THAT(stat(parent_proc_dir.c_str(), &st), SyscallSucceeds()); | |
| EXPECT_THAT(stat(parent_task_dir.c_str(), &st), SyscallSucceeds()); | |
| fbl::unique_fd fd(open(parent_cmdline.c_str(), O_RDONLY)); | |
| EXPECT_TRUE(fd.is_valid()) << strerror(errno); | |
| fbl::unique_fd task_fd(open(parent_task_cmdline.c_str(), O_RDONLY)); | |
| EXPECT_TRUE(task_fd.is_valid()) << strerror(errno); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| // Remount with hidepid=0 (omitting gid) so an unprivileged process can open FDs to parent's | |
| // /proc/<pid> and /proc/<pid>/task, verifying that gid=3009 is preserved across partial remounts, | |
| // then remount with hidepid=noaccess and hidepid=ptraceable while holding those FDs to verify | |
| // dynamic enforcement on fstat, getdents64, openat, and "." / "..". | |
| std::string parent_task_list_dir = | |
| fxl::StringPrintf("%s/%d/task", temp_dir.path().c_str(), parent_pid); | |
| ASSERT_THAT(mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=0"), | |
| SyscallSucceeds()); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/mounts", &mounts_contents)); | |
| EXPECT_THAT(mounts_contents, ContainsRegex("gid=3009")); | |
| fbl::unique_fd held_proc_fd(SAFE_SYSCALL(open(parent_proc_dir.c_str(), O_RDONLY | O_DIRECTORY))); | |
| fbl::unique_fd held_task_list_fd( | |
| SAFE_SYSCALL(open(parent_task_list_dir.c_str(), O_RDONLY | O_DIRECTORY))); | |
| // Remount with hidepid=noaccess (1), omitting gid to verify gid=3009 remains preserved: | |
| // unprivileged process not in gid 3009 can stat parent's /proc/<pid>, but cannot open it, | |
| // open files inside it, or traverse "." / ".." / task/<tid> (EPERM). Reading directory | |
| // entries via an already-open FD continues to succeed while the target process is alive. | |
| ASSERT_THAT(mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=noaccess"), | |
| SyscallSucceeds()); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/mounts", &mounts_contents)); | |
| EXPECT_THAT(mounts_contents, ContainsRegex("gid=3009,hidepid=(1|noaccess)")); | |
| helper.RunInForkedProcess([&] { | |
| SAFE_SYSCALL(setgroups(0, nullptr)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| struct stat st{}; | |
| EXPECT_THAT(stat(parent_proc_dir.c_str(), &st), SyscallSucceeds()); | |
| EXPECT_THAT(fstat(held_proc_fd.get(), &st), SyscallSucceeds()); | |
| EXPECT_THAT(access(parent_proc_dir.c_str(), F_OK), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(access(parent_proc_dir.c_str(), X_OK), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(open(parent_proc_dir.c_str(), O_RDONLY | O_DIRECTORY), | |
| SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(open(parent_cmdline.c_str(), O_RDONLY), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(openat(held_proc_fd.get(), "cmdline", O_RDONLY), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(fstatat(held_proc_fd.get(), ".", &st, 0), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(fstatat(held_proc_fd.get(), "..", &st, 0), SyscallFailsWithErrno(EPERM)); | |
| char dirent_buf[256]; | |
| EXPECT_THAT(syscall(SYS_getdents64, held_proc_fd.get(), dirent_buf, sizeof(dirent_buf)), | |
| SyscallSucceeds()); | |
| EXPECT_THAT(syscall(SYS_getdents64, held_task_list_fd.get(), dirent_buf, sizeof(dirent_buf)), | |
| SyscallSucceeds()); | |
| EXPECT_THAT(stat(parent_task_dir.c_str(), &st), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(open(parent_task_cmdline.c_str(), O_RDONLY), SyscallFailsWithErrno(EPERM)); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| // Remount with hidepid=ptraceable (4), omitting gid: even a process in gid 3009 with a | |
| // different UID cannot see or stat parent's /proc/<pid> (ENOENT), and fstat/openat on a | |
| // held FD fail. | |
| ASSERT_THAT(mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=ptraceable"), | |
| SyscallSucceeds()); | |
| ASSERT_TRUE(files::ReadFileToString("/proc/mounts", &mounts_contents)); | |
| EXPECT_THAT(mounts_contents, ContainsRegex("gid=3009,hidepid=(4|ptraceable)")); | |
| helper.RunInForkedProcess([&] { | |
| gid_t groups[] = {3009}; | |
| SAFE_SYSCALL(setgroups(1, groups)); | |
| SAFE_SYSCALL(setgid(65534)); | |
| SAFE_SYSCALL(setuid(65534)); | |
| struct stat st{}; | |
| EXPECT_THAT(stat(parent_proc_dir.c_str(), &st), SyscallFailsWithErrno(ENOENT)); | |
| EXPECT_THAT(fstat(held_proc_fd.get(), &st), SyscallFailsWithErrno(ENOENT)); | |
| struct statx stx{}; | |
| EXPECT_THAT(syscall(SYS_statx, held_proc_fd.get(), "", AT_EMPTY_PATH | AT_STATX_DONT_SYNC, | |
| STATX_BASIC_STATS, &stx), | |
| SyscallFailsWithErrno(ENOENT)); | |
| // Note: When /proc/<pid> is already cached in the VFS dcache (e.g. pinned by held_proc_fd), | |
| // Linux 6.1's proc_pid_permission returns EPERM under hidepid=ptraceable whereas uncached | |
| // proc_pid_lookup returns ENOENT. | |
| EXPECT_THAT(open(parent_cmdline.c_str(), O_RDONLY), | |
| SyscallFailsWithErrno(testing::AnyOf(ENOENT, EPERM))); | |
| EXPECT_THAT(openat(held_proc_fd.get(), "cmdline", O_RDONLY), | |
| SyscallFailsWithErrno(testing::AnyOf(ENOENT, EPERM))); | |
| EXPECT_THAT(lseek(held_proc_fd.get(), 0, SEEK_SET), SyscallSucceeds()); | |
| EXPECT_THAT(lseek(held_task_list_fd.get(), 0, SEEK_SET), SyscallSucceeds()); | |
| char dirent_buf[256]; | |
| EXPECT_THAT(syscall(SYS_getdents64, held_proc_fd.get(), dirent_buf, sizeof(dirent_buf)), | |
| SyscallSucceeds()); | |
| EXPECT_THAT(syscall(SYS_getdents64, held_task_list_fd.get(), dirent_buf, sizeof(dirent_buf)), | |
| SyscallSucceeds()); | |
| EXPECT_THAT(stat(parent_task_dir.c_str(), &st), | |
| SyscallFailsWithErrno(testing::AnyOf(ENOENT, EPERM))); | |
| EXPECT_THAT(open(parent_task_cmdline.c_str(), O_RDONLY), | |
| SyscallFailsWithErrno(testing::AnyOf(ENOENT, EPERM))); | |
| }); | |
| ASSERT_TRUE(helper.WaitForChildren()); | |
| // Invalid hidepid values are rejected with EINVAL. | |
| EXPECT_THAT(mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=3"), | |
| SyscallFailsWithErrno(EINVAL)); | |
| EXPECT_THAT(mount("proc", temp_dir.path().c_str(), "proc", MS_REMOUNT, "hidepid=invalid"), | |
| SyscallFailsWithErrno(EINVAL)); | |
| } | |
| blksize_t ExpectedProcfsBlksize() { | |
| // Linux's procfs sets s_blocksize = 1024 in proc_fill_super, whereas Starnix sets st_blksize to | |
| // PAGE_SIZE so Bionic stdio buffers size to a full page. | |
| return test_helper::IsStarnix() ? static_cast<blksize_t>(sysconf(_SC_PAGESIZE)) : 1024; | |
| } | |
| TEST(ProcfsBlksizeTest, FileFstatBlksize) { | |
| const blksize_t expected_blksize = ExpectedProcfsBlksize(); | |
| for (const char* path : {"/proc/self/smaps", "/proc/self/maps", "/proc/uptime"}) { | |
| fbl::unique_fd fd(open(path, O_RDONLY)); | |
| ASSERT_TRUE(fd.is_valid()) << "open failed for " << path << ": " << strerror(errno); | |
| struct stat st; | |
| ASSERT_EQ(fstat(fd.get(), &st), 0) << "fstat failed for " << path << ": " << strerror(errno); | |
| EXPECT_EQ(st.st_blksize, expected_blksize) << "path: " << path; | |
| } | |
| } | |
| TEST(ProcfsBlksizeTest, StatBlksize) { | |
| const blksize_t expected_blksize = ExpectedProcfsBlksize(); | |
| for (const char* path : | |
| {"/proc", "/proc/self", "/proc/self/fd", "/proc/sys", "/proc/self/attr", "/proc/kmsg"}) { | |
| struct stat st; | |
| ASSERT_EQ(stat(path, &st), 0) << "stat failed for " << path << ": " << strerror(errno); | |
| EXPECT_EQ(st.st_blksize, expected_blksize) << "path: " << path; | |
| } | |
| } | |
| struct KernelTextBounds { | |
| std::optional<uint64_t> stext; | |
| std::optional<uint64_t> etext; | |
| }; | |
| std::optional<KernelTextBounds> ReadKernelTextBoundsFromFd(int fd) { | |
| std::string contents; | |
| if (!files::ReadFileDescriptorToString(fd, &contents)) { | |
| return std::nullopt; | |
| } | |
| std::istringstream stream(contents); | |
| std::string line; | |
| KernelTextBounds bounds; | |
| while (std::getline(stream, line)) { | |
| uint64_t addr = 0; | |
| char type = 0; | |
| char name[256] = {}; | |
| if (sscanf(line.c_str(), "%" SCNx64 " %c %255s", &addr, &type, name) == 3) { | |
| if (strcmp(name, "_stext") == 0) { | |
| bounds.stext = addr; | |
| } else if (strcmp(name, "_etext") == 0) { | |
| bounds.etext = addr; | |
| } | |
| if (bounds.stext.has_value() && bounds.etext.has_value()) { | |
| break; | |
| } | |
| } | |
| } | |
| return bounds; | |
| } | |
| std::optional<KernelTextBounds> ReadKernelTextBounds() { | |
| fbl::unique_fd fd(open("/proc/kallsyms", O_RDONLY | O_CLOEXEC)); | |
| if (!fd.is_valid()) { | |
| return std::nullopt; | |
| } | |
| return ReadKernelTextBoundsFromFd(fd.get()); | |
| } | |
| TEST(ProcKallsymsTest, TextSectionSymbolsPresent) { | |
| if (access("/proc/kallsyms", R_OK) != 0) { | |
| GTEST_SKIP() << "/proc/kallsyms is not readable: " << strerror(errno); | |
| } | |
| std::string kptr_restrict; | |
| bool has_kptr_restrict = | |
| files::ReadFileToString("/proc/sys/kernel/kptr_restrict", &kptr_restrict); | |
| std::string perf_paranoid_str; | |
| int perf_paranoid = 2; | |
| if (files::ReadFileToString(test_helper::kPerfEventParanoidPath, &perf_paranoid_str)) { | |
| perf_paranoid = atoi(perf_paranoid_str.c_str()); | |
| } | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| if (test_helper::HasCapabilityEffective(CAP_SYSLOG)) { | |
| test_helper::UnsetCapabilityEffective(CAP_SYSLOG); | |
| } | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYSLOG)); | |
| std::optional<KernelTextBounds> bounds = ReadKernelTextBounds(); | |
| ASSERT_TRUE(bounds.has_value()); | |
| ASSERT_TRUE(bounds->stext.has_value()); | |
| ASSERT_TRUE(bounds->etext.has_value()); | |
| if (has_kptr_restrict && (kptr_restrict == "1\n" || kptr_restrict == "2\n")) { | |
| EXPECT_EQ(*bounds->stext, 0u); | |
| EXPECT_EQ(*bounds->etext, 0u); | |
| } else if (has_kptr_restrict && kptr_restrict == "0\n") { | |
| if (test_helper::IsStarnix() || perf_paranoid <= 1) { | |
| EXPECT_NE(*bounds->stext, 0u); | |
| EXPECT_GT(*bounds->etext, *bounds->stext); | |
| } else { | |
| EXPECT_EQ(*bounds->stext, 0u); | |
| EXPECT_EQ(*bounds->etext, 0u); | |
| } | |
| } | |
| }); | |
| } | |
| TEST(ProcKallsymsTest, KptrRestrictControlsKernelSymbolAddresses) { | |
| if (!test_helper::HasSysAdmin() || !test_helper::HasCapabilityEffective(CAP_SYSLOG)) { | |
| GTEST_SKIP() << "Requires CAP_SYS_ADMIN and CAP_SYSLOG"; | |
| } | |
| if (access("/proc/kallsyms", R_OK) != 0 || access("/proc/sys/kernel/kptr_restrict", R_OK) != 0) { | |
| GTEST_SKIP() << "/proc/kallsyms or /proc/sys/kernel/kptr_restrict is not accessible"; | |
| } | |
| constexpr const char* kKptrRestrictPath = "/proc/sys/kernel/kptr_restrict"; | |
| std::string saved_kptr_restrict; | |
| ASSERT_TRUE(files::ReadFileToString(kKptrRestrictPath, &saved_kptr_restrict)); | |
| auto restore_kptr_restrict = | |
| fit::defer([&] { files::WriteFile(kKptrRestrictPath, saved_kptr_restrict); }); | |
| test_helper::ScopedPerfEventParanoid scoped_perf_paranoid(1); | |
| // Reject out-of-range, signed-positive, whitespace-only, non-UTF8, or malformed values with | |
| // EINVAL. | |
| for (const char* invalid : {"-1", "+1", "3", "256", "999999999", " \n", "\xff", "invalid"}) { | |
| fbl::unique_fd fd(open(kKptrRestrictPath, O_WRONLY)); | |
| ASSERT_THAT(fd.get(), SyscallSucceeds()); | |
| EXPECT_THAT(write(fd.get(), invalid, strlen(invalid)), SyscallFailsWithErrno(EINVAL)); | |
| } | |
| // Zero-length write succeeds with 0 bytes written and leaves kptr_restrict unchanged. | |
| { | |
| ASSERT_TRUE(files::WriteFile(kKptrRestrictPath, "2\n")); | |
| fbl::unique_fd fd(open(kKptrRestrictPath, O_WRONLY)); | |
| ASSERT_THAT(fd.get(), SyscallSucceeds()); | |
| EXPECT_EQ(write(fd.get(), "", 0), 0); | |
| std::string read_back; | |
| ASSERT_TRUE(files::ReadFileToString(kKptrRestrictPath, &read_back)); | |
| EXPECT_EQ(read_back, "2\n"); | |
| } | |
| // Reject writes when the writer lacks CAP_SYS_ADMIN (including zero-length writes). | |
| { | |
| fbl::unique_fd fd(open(kKptrRestrictPath, O_WRONLY)); | |
| ASSERT_THAT(fd.get(), SyscallSucceeds()); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| test_helper::UnsetCapabilityEffective(CAP_SYS_ADMIN); | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYS_ADMIN)); | |
| EXPECT_THAT(write(fd.get(), "", 0), SyscallFailsWithErrno(EPERM)); | |
| EXPECT_THAT(write(fd.get(), "1", 1), SyscallFailsWithErrno(EPERM)); | |
| }); | |
| } | |
| // Mode 0 (including newline-terminated sysctl writes): expose non-zero ordered kernel symbol | |
| // addresses to all readers. | |
| ASSERT_TRUE(files::WriteFile(kKptrRestrictPath, "0\n")); | |
| { | |
| std::string read_back; | |
| ASSERT_TRUE(files::ReadFileToString(kKptrRestrictPath, &read_back)); | |
| EXPECT_EQ(read_back, "0\n"); | |
| std::optional<KernelTextBounds> bounds = ReadKernelTextBounds(); | |
| ASSERT_TRUE(bounds.has_value()); | |
| ASSERT_TRUE(bounds->stext.has_value()); | |
| ASSERT_TRUE(bounds->etext.has_value()); | |
| EXPECT_NE(*bounds->stext, 0u); | |
| EXPECT_GT(*bounds->etext, *bounds->stext); | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([] { | |
| test_helper::UnsetCapabilityEffective(CAP_SYSLOG); | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYSLOG)); | |
| std::optional<KernelTextBounds> unpriv_bounds = ReadKernelTextBounds(); | |
| ASSERT_TRUE(unpriv_bounds.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->stext.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->etext.has_value()); | |
| EXPECT_NE(*unpriv_bounds->stext, 0u); | |
| EXPECT_GT(*unpriv_bounds->etext, *unpriv_bounds->stext); | |
| }); | |
| } | |
| // Mode 1 (including leading/trailing whitespace): expose non-zero addresses only to readers | |
| // holding CAP_SYSLOG at open() time; mask to zero otherwise. | |
| ASSERT_TRUE(files::WriteFile(kKptrRestrictPath, " 1 \n")); | |
| { | |
| std::string read_back; | |
| ASSERT_TRUE(files::ReadFileToString(kKptrRestrictPath, &read_back)); | |
| EXPECT_EQ(read_back, "1\n"); | |
| fbl::unique_fd priv_kallsyms_fd(open("/proc/kallsyms", O_RDONLY | O_CLOEXEC)); | |
| ASSERT_THAT(priv_kallsyms_fd.get(), SyscallSucceeds()); | |
| std::optional<KernelTextBounds> bounds = ReadKernelTextBoundsFromFd(priv_kallsyms_fd.get()); | |
| ASSERT_TRUE(bounds.has_value()); | |
| ASSERT_TRUE(bounds->stext.has_value()); | |
| ASSERT_TRUE(bounds->etext.has_value()); | |
| EXPECT_NE(*bounds->stext, 0u); | |
| EXPECT_GT(*bounds->etext, *bounds->stext); | |
| // Verify open-time credential evaluation: a child without CAP_SYSLOG reading from a descriptor | |
| // opened with CAP_SYSLOG still observes non-zero addresses, while opening /proc/kallsyms anew | |
| // without CAP_SYSLOG masks addresses to zero. | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([&] { | |
| test_helper::UnsetCapabilityEffective(CAP_SYSLOG); | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYSLOG)); | |
| ASSERT_THAT(lseek(priv_kallsyms_fd.get(), 0, SEEK_SET), SyscallSucceeds()); | |
| std::optional<KernelTextBounds> inherited_bounds = | |
| ReadKernelTextBoundsFromFd(priv_kallsyms_fd.get()); | |
| ASSERT_TRUE(inherited_bounds.has_value()); | |
| ASSERT_TRUE(inherited_bounds->stext.has_value()); | |
| EXPECT_NE(*inherited_bounds->stext, 0u); | |
| std::optional<KernelTextBounds> unpriv_bounds = ReadKernelTextBounds(); | |
| ASSERT_TRUE(unpriv_bounds.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->stext.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->etext.has_value()); | |
| EXPECT_EQ(*unpriv_bounds->stext, 0u); | |
| EXPECT_EQ(*unpriv_bounds->etext, 0u); | |
| }); | |
| } | |
| // Mode 2: mask kernel symbol addresses to zero for all newly opened readers, including | |
| // CAP_SYSLOG holders. | |
| ASSERT_TRUE(files::WriteFile(kKptrRestrictPath, "2\n")); | |
| { | |
| std::string read_back; | |
| ASSERT_TRUE(files::ReadFileToString(kKptrRestrictPath, &read_back)); | |
| EXPECT_EQ(read_back, "2\n"); | |
| fbl::unique_fd masked_kallsyms_fd(open("/proc/kallsyms", O_RDONLY | O_CLOEXEC)); | |
| ASSERT_THAT(masked_kallsyms_fd.get(), SyscallSucceeds()); | |
| std::optional<KernelTextBounds> bounds = ReadKernelTextBoundsFromFd(masked_kallsyms_fd.get()); | |
| ASSERT_TRUE(bounds.has_value()); | |
| ASSERT_TRUE(bounds->stext.has_value()); | |
| ASSERT_TRUE(bounds->etext.has_value()); | |
| EXPECT_EQ(*bounds->stext, 0u); | |
| EXPECT_EQ(*bounds->etext, 0u); | |
| { | |
| test_helper::ForkHelper helper; | |
| helper.RunInForkedProcess([] { | |
| test_helper::UnsetCapabilityEffective(CAP_SYSLOG); | |
| ASSERT_FALSE(test_helper::HasCapabilityEffective(CAP_SYSLOG)); | |
| std::optional<KernelTextBounds> unpriv_bounds = ReadKernelTextBounds(); | |
| ASSERT_TRUE(unpriv_bounds.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->stext.has_value()); | |
| ASSERT_TRUE(unpriv_bounds->etext.has_value()); | |
| EXPECT_EQ(*unpriv_bounds->stext, 0u); | |
| EXPECT_EQ(*unpriv_bounds->etext, 0u); | |
| }); | |
| } | |
| // Lowering kptr_restrict back to 0 does not retroactively expose addresses on a descriptor | |
| // opened while kptr_restrict was 2, whereas a newly opened descriptor sees non-zero addresses. | |
| ASSERT_TRUE(files::WriteFile(kKptrRestrictPath, "0\n")); | |
| ASSERT_THAT(lseek(masked_kallsyms_fd.get(), 0, SEEK_SET), SyscallSucceeds()); | |
| std::optional<KernelTextBounds> still_masked = | |
| ReadKernelTextBoundsFromFd(masked_kallsyms_fd.get()); | |
| ASSERT_TRUE(still_masked.has_value()); | |
| ASSERT_TRUE(still_masked->stext.has_value()); | |
| EXPECT_EQ(*still_masked->stext, 0u); | |
| std::optional<KernelTextBounds> newly_opened = ReadKernelTextBounds(); | |
| ASSERT_TRUE(newly_opened.has_value()); | |
| ASSERT_TRUE(newly_opened->stext.has_value()); | |
| EXPECT_NE(*newly_opened->stext, 0u); | |
| } | |
| } | |
| // Parses a whole decimal string. Returns std::nullopt if it is not a valid number. | |
| std::optional<uint64_t> ParseUint64(const std::string& value) { | |
| char* end = nullptr; | |
| errno = 0; | |
| const uint64_t result = strtoull(value.c_str(), &end, 10); | |
| if (value.empty() || errno != 0 || *end != '\0') { | |
| return std::nullopt; | |
| } | |
| return result; | |
| } | |
| // Returns the value of `field` in /proc/<pid>/status contents, in kB. | |
| std::optional<uint64_t> StatusFieldKb(const std::string& status, std::string_view field) { | |
| const std::string key = std::format("\n{}:", field); | |
| const size_t pos = status.find(key); | |
| if (pos == std::string::npos) { | |
| return std::nullopt; | |
| } | |
| const char* start = status.c_str() + pos + key.size(); | |
| char* end = nullptr; | |
| errno = 0; | |
| const uint64_t value = strtoull(start, &end, 10); | |
| if (end == start || errno != 0) { | |
| return std::nullopt; | |
| } | |
| return value; | |
| } | |
| // A process that reads the memory stats of another process must see a mapping that the other | |
| // process created after its previous read, even when the two reads are close together. | |
| TEST(ProcfsMemoryStatsTest, StatusOfOtherProcessReflectsNewMapping) { | |
| const size_t page_size = SAFE_SYSCALL(sysconf(_SC_PAGE_SIZE)); | |
| constexpr size_t kPages = 1024; | |
| const uint64_t mapping_kb = kPages * page_size / 1024; | |
| const std::string status_path = std::format("/proc/{}/status", getpid()); | |
| test_helper::ForkHelper helper; | |
| int to_child[2]; | |
| int to_parent[2]; | |
| ASSERT_THAT(pipe2(to_child, O_CLOEXEC), SyscallSucceeds()); | |
| ASSERT_THAT(pipe2(to_parent, O_CLOEXEC), SyscallSucceeds()); | |
| fbl::unique_fd child_reads(to_child[0]); | |
| fbl::unique_fd parent_writes(to_child[1]); | |
| fbl::unique_fd parent_reads(to_parent[0]); | |
| fbl::unique_fd child_writes(to_parent[1]); | |
| helper.RunInForkedProcess([&] { | |
| parent_writes.reset(); | |
| parent_reads.reset(); | |
| std::string before; | |
| ASSERT_TRUE(files::ReadFileToString(status_path, &before)); | |
| std::optional<uint64_t> vm_size_before = StatusFieldKb(before, "VmSize"); | |
| ASSERT_TRUE(vm_size_before.has_value()) << before; | |
| char token = 0; | |
| ASSERT_EQ(write(child_writes.get(), &token, 1), 1); | |
| ASSERT_EQ(read(child_reads.get(), &token, 1), 1); | |
| std::string after; | |
| ASSERT_TRUE(files::ReadFileToString(status_path, &after)); | |
| std::optional<uint64_t> vm_size_after = StatusFieldKb(after, "VmSize"); | |
| ASSERT_TRUE(vm_size_after.has_value()) << after; | |
| EXPECT_GE(*vm_size_after, *vm_size_before + mapping_kb); | |
| }); | |
| child_reads.reset(); | |
| child_writes.reset(); | |
| char token = 0; | |
| ASSERT_EQ(read(parent_reads.get(), &token, 1), 1); | |
| auto mapping = test_helper::ScopedMMap::MMap(nullptr, kPages * page_size, PROT_READ | PROT_WRITE, | |
| MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
| ASSERT_TRUE(mapping.is_ok()); | |
| ASSERT_EQ(write(parent_writes.get(), &token, 1), 1); | |
| EXPECT_TRUE(helper.WaitForChildren()); | |
| } | |
| // /proc/self/status, statm and stat must stay well-formed and consistent while other threads map, | |
| // split and unmap memory. | |
| TEST(ProcfsMemoryStatsTest, MemoryStatsStayConsistentWhileMappingsChange) { | |
| const size_t page_size = SAFE_SYSCALL(sysconf(_SC_PAGE_SIZE)); | |
| constexpr size_t kAnchorPages = 256; | |
| constexpr size_t kChurnPages = 8; | |
| constexpr int kChurnThreads = 2; | |
| constexpr int kReads = 100; | |
| // This mapping stays in place for the whole test, so every read must account for it. | |
| auto anchor = | |
| test_helper::ScopedMMap::MMap(nullptr, kAnchorPages * page_size, PROT_READ | PROT_WRITE, | |
| MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
| ASSERT_TRUE(anchor.is_ok()); | |
| memset(anchor.value().mapping(), 1, kAnchorPages * page_size); | |
| const uint64_t anchor_kb = kAnchorPages * page_size / 1024; | |
| std::atomic<bool> stop = false; | |
| std::atomic<int> churn_failures = 0; | |
| std::vector<std::thread> churn_threads; | |
| churn_threads.reserve(kChurnThreads); | |
| for (int i = 0; i < kChurnThreads; ++i) { | |
| churn_threads.emplace_back([&stop, &churn_failures, page_size] { | |
| const size_t size = kChurnPages * page_size; | |
| while (!stop.load()) { | |
| void* addr = | |
| mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); | |
| if (addr == MAP_FAILED) { | |
| churn_failures++; | |
| continue; | |
| } | |
| memset(addr, 2, size); | |
| // Changing the protection of one page splits the mapping. | |
| if (mprotect(addr, page_size, PROT_READ) != 0) { | |
| churn_failures++; | |
| } | |
| if (munmap(addr, size) != 0) { | |
| churn_failures++; | |
| } | |
| } | |
| }); | |
| } | |
| auto stop_churn = fit::defer([&] { | |
| stop = true; | |
| for (std::thread& thread : churn_threads) { | |
| thread.join(); | |
| } | |
| }); | |
| for (int i = 0; i < kReads; ++i) { | |
| std::string status; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/status", &status)); | |
| std::optional<uint64_t> vm_size = StatusFieldKb(status, "VmSize"); | |
| std::optional<uint64_t> vm_rss = StatusFieldKb(status, "VmRSS"); | |
| ASSERT_TRUE(vm_size.has_value() && vm_rss.has_value()) << status; | |
| EXPECT_GE(*vm_size, anchor_kb); | |
| EXPECT_LE(*vm_rss, *vm_size); | |
| EXPECT_THAT(status, ContainsRegex("\nUid:\t[0-9]+\t[0-9]+\t[0-9]+\t[0-9]+\n")); | |
| EXPECT_THAT(status, ContainsRegex("\nGid:\t[0-9]+\t[0-9]+\t[0-9]+\t[0-9]+\n")); | |
| EXPECT_THAT(status, ContainsRegex("\nGroups:\t[0-9 ]*\n")); | |
| std::string statm; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/statm", &statm)); | |
| char* end = nullptr; | |
| const uint64_t size_pages = strtoull(statm.c_str(), &end, 10); | |
| ASSERT_NE(end, statm.c_str()) << statm; | |
| const char* resident_start = end; | |
| const uint64_t resident_pages = strtoull(resident_start, &end, 10); | |
| ASSERT_NE(end, resident_start) << statm; | |
| EXPECT_GE(size_pages, kAnchorPages); | |
| EXPECT_LE(resident_pages, size_pages); | |
| std::string stat; | |
| ASSERT_TRUE(files::ReadFileToString("/proc/self/stat", &stat)); | |
| // vsize and rss are fields 23 and 24. The fields after the command name start at field 3. | |
| const size_t comm_end = stat.rfind(')'); | |
| ASSERT_NE(comm_end, std::string::npos) << stat; | |
| std::istringstream fields(stat.substr(comm_end + 1)); | |
| std::string field; | |
| std::optional<uint64_t> vsize; | |
| std::optional<uint64_t> rss_pages; | |
| for (int n = 3; n <= 24 && fields >> field; ++n) { | |
| if (n == 23) { | |
| vsize = ParseUint64(field); | |
| } else if (n == 24) { | |
| rss_pages = ParseUint64(field); | |
| } | |
| } | |
| ASSERT_TRUE(vsize.has_value() && rss_pages.has_value()) << stat; | |
| EXPECT_GE(*vsize, kAnchorPages * page_size) << stat; | |
| EXPECT_LE(*rss_pages * page_size, *vsize) << stat; | |
| } | |
| stop_churn.call(); | |
| EXPECT_EQ(churn_failures.load(), 0); | |
| } | |
| } // namespace |