blob: 8b40c766b5b2496abf50857967135af0ad9e527c [file] [edit]
// Copyright 2026 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <algorithm>
#include "process_tree.h"
#include "scoped_handle.h"
namespace {
/// Read the content of a file using non-blocking I/O.
/// Returns true on success, false on error or if the read would block.
bool ReadFileNonBlocking(const std::string& path, char* buffer,
size_t buffer_size, ssize_t* bytes_read) {
int fd_val;
do {
fd_val = open(path.c_str(), O_RDONLY | O_NONBLOCK);
} while (fd_val == -1 && errno == EINTR);
ScopedHandle fd(fd_val);
if (!fd)
return false;
std::string error;
*bytes_read = fd.Read(buffer, buffer_size, &error);
return *bytes_read > 0;
}
/// Read and split /proc/[pid]/cmdline into a vector of strings.
/// The arguments in this file are separated by NUL bytes.
std::vector<std::string> ReadCommandLine(ProcessTree::Pid pid) {
std::vector<std::string> args;
std::string path = "/proc/" + std::to_string(pid) + "/cmdline";
char buffer[4096];
ssize_t n = 0;
if (!ReadFileNonBlocking(path, buffer, sizeof(buffer), &n))
return args;
const char* p = buffer;
const char* end = buffer + n;
while (p < end) {
size_t len = strnlen(p, end - p);
if (len > 0) {
args.emplace_back(p, len);
}
p += len + 1;
}
return args;
}
} // namespace
// static
std::vector<ProcessTree::ProcessInfo> ProcessTree::GetSystemProcesses() {
std::vector<ProcessInfo> processes;
// On Linux, /proc is a virtual filesystem that provides information about
// running processes. Each process has a directory named after its PID.
DIR* dir = opendir("/proc");
if (!dir)
return processes;
struct dirent* ent;
while ((ent = readdir(dir)) != nullptr) {
// Only interested in directories that represent a PID (numeric names).
Pid pid = atoi(ent->d_name);
if (pid <= 0)
continue;
// Read the 'stat' file for this process to get its name and parent PID.
// Use non-blocking read to avoid hanging on D-state processes.
std::string path = "/proc/" + std::to_string(pid) + "/stat";
char buffer[4096];
ssize_t n = 0;
if (!ReadFileNonBlocking(path, buffer, sizeof(buffer), &n))
continue;
// The format of /proc/[pid]/stat starts with:
// pid (comm) state ppid ...
// Note that 'comm' (the executable name) can contain spaces and
// parentheses, which can confuse simple whitespace parsing.
// However, the kernel guarantees that 'comm' is enclosed in parentheses
// and followed by a space.
const char* last_paren = nullptr;
for (ssize_t i = n - 1; i >= 0; --i) {
if (buffer[i] == ')') {
last_paren = &buffer[i];
break;
}
}
if (!last_paren || last_paren + 2 >= buffer + n)
continue;
const char* first_paren = strchr(buffer, '(');
if (!first_paren || first_paren >= last_paren)
continue;
// Extract the executable name between the first and last parentheses.
std::string comm(first_paren + 1, last_paren - first_paren - 1);
// The next two fields are state (a single char) and then the parent PID.
char state;
Pid ppid;
if (sscanf(last_paren + 2, "%c %d", &state, &ppid) != 2)
continue;
processes.push_back({ pid, ppid, comm, {} });
}
closedir(dir);
return processes;
}
// static
void ProcessTree::GetSystemProcessDetails(Pid pid, ProcessDetails* details) {
// Best-effort: try to get the full command line from /proc/pid/cmdline.
details->command_line = ReadCommandLine(pid);
details->collected = true;
}