procfs2 0.2.1

A modern, zero-copy, strongly-typed Rust library for reading Linux /proc and /sys
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
mod auxv;
mod cgroup;
mod fd;
mod io;
mod limits;
mod maps;
mod mountinfo;
mod ns;
mod pagemap;
mod stat;
mod statm;
mod status;
mod syscall;
mod threads;

pub use auxv::{Auxv, AuxvEntry, auxv_type};
pub use cgroup::CgroupEntry;
pub use fd::{Fd, FdTarget};
pub use io::ProcessIo;
pub use limits::{Limit, LimitUnit, ProcessLimits};
pub use maps::{MapPathname, MapPermissions, MemoryMap, MemoryMapDetail, SmapsRollup};
pub use mountinfo::MountInfo;
pub use ns::Namespaces;
pub use pagemap::PageMapEntry;
pub use stat::ProcessStat;
pub use statm::Statm;
pub use status::{Gids, ProcessState, ProcessStatus, Uids};
pub use syscall::{ProcessSyscall, SyscallState};

use crate::{
    error::{Error, KernelVersion, Result},
    util::parse,
};
use std::{
    os::unix::ffi::OsStrExt,
    path::{Path, PathBuf},
};

/// A handle to a running process, identified by its PID.
///
/// This struct is the entry point for all per-process information
/// available under `/proc/PID/`. It does not hold any open file
/// descriptors — each method performs a fresh read.
///
/// # Process lifetime
///
/// A `Process` may become stale between creation and use if the
/// target process exits. Methods return [`Error::ProcessGone`] in
/// that case.
#[derive(Debug)]
pub struct Process {
    /// Process ID.
    pub pid: u32,
}

impl Process {
    /// Creates a `Process` handle for the given PID.
    ///
    /// Verifies that `/proc/<pid>` exists as a directory. Returns
    /// [`Error::ProcessGone`] if the directory is absent, which
    /// means either the PID is invalid or the process has already
    /// terminated.
    pub fn new(pid: u32) -> Result<Self> {
        let path = format!("/proc/{}", pid);
        if Path::new(&path).is_dir() {
            Ok(Process { pid })
        } else {
            Err(Error::ProcessGone(pid))
        }
    }

    /// Returns a `Process` handle for the calling process.
    ///
    /// Resolves `/proc/self` to determine the caller's PID. This is
    /// preferred over `Process::new(std::process::id())` because it
    /// works correctly inside containers and PID namespaces where
    /// the kernel-visible PID may differ from the host PID.
    pub fn current() -> Result<Self> {
        let path = "/proc/self";
        let target = std::fs::read_link(path).map_err(|e| Error::Io {
            path: Some(PathBuf::from(path)),
            error: e,
        })?;
        let pid_str = target
            .file_name()
            .ok_or_else(|| Error::Parse {
                path: PathBuf::from(path),
                line: 0,
                msg: "invalid /proc/self symlink",
            })?
            .to_str()
            .ok_or_else(|| Error::Parse {
                path: PathBuf::from(path),
                line: 0,
                msg: "non-utf8 pid in /proc/self",
            })?;

        let pid = pid_str.parse::<u32>().map_err(|_| Error::Parse {
            path: PathBuf::from(path),
            line: 0,
            msg: "invalid pid in /proc/self",
        })?;

        Ok(Process { pid })
    }

    /// Iterates over all currently visible processes.
    ///
    /// Scans `/proc` for numeric directory entries. The snapshot is
    /// taken at call time; processes spawned or terminated after the
    /// call are not reflected. Returns an error for any directory
    /// that cannot be read, but continues iterating over the rest.
    pub fn all() -> impl Iterator<Item = Result<Self>> {
        let entries = match std::fs::read_dir("/proc") {
            Ok(iter) => iter,
            Err(e) => {
                return vec![Err(Error::Io {
                    path: Some(PathBuf::from("/proc")),
                    error: e,
                })]
                .into_iter();
            }
        };

        entries
            .filter_map(|entry| match entry {
                Ok(e) => {
                    let name = e.file_name();
                    let name_str = name.to_string_lossy();
                    if name_str.chars().all(|c| c.is_ascii_digit()) {
                        let pid = name_str.parse::<u32>().ok()?;
                        Some(Ok(Process { pid }))
                    } else {
                        None
                    }
                }
                Err(e) => Some(Err(Error::Io {
                    path: Some(PathBuf::from("/proc")),
                    error: e,
                })),
            })
            .collect::<Vec<_>>()
            .into_iter()
    }

    /// Reads `/proc/PID/stat` and returns [`ProcessStat`].
    ///
    /// Contains scheduling information, memory usage, and timing
    /// data. The `comm` field is limited to 15 characters by the
    /// kernel and may be truncated.
    pub fn stat(&self) -> Result<ProcessStat> {
        let path = format!("/proc/{}/stat", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        ProcessStat::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/status` and returns [`ProcessStatus`].
    ///
    /// A human-readable key-value format with more detail than
    /// `/proc/PID/stat`, including UIDs, GIDs, voluntary context
    /// switches, and optional memory peaks.
    pub fn status(&self) -> Result<ProcessStatus> {
        let path = format!("/proc/{}/status", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        ProcessStatus::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/cmdline` and returns the argument vector.
    ///
    /// Arguments are null-delimited in the kernel file. Returns an
    /// empty vector for kernel threads, which have no cmdline.
    pub fn cmdline(&self) -> Result<Vec<std::ffi::OsString>> {
        let path = format!("/proc/{}/cmdline", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;

        if bytes.is_empty() {
            return Ok(Vec::new());
        }

        let args = bytes
            .split(|&b| b == b'\0')
            .filter(|s| !s.is_empty())
            .map(|s| std::ffi::OsStr::from_bytes(s).to_os_string())
            .collect();

        Ok(args)
    }

    /// Reads `/proc/PID/environ` and returns the environment map.
    ///
    /// Entries are null-delimited `KEY=VALUE` pairs. Returns an
    /// empty map for kernel threads. Reading another user's
    /// environment typically yields [`Error::PermissionDenied`].
    pub fn environ(
        &self,
    ) -> Result<std::collections::HashMap<std::ffi::OsString, std::ffi::OsString>> {
        let path = format!("/proc/{}/environ", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;

        let mut map = std::collections::HashMap::new();

        for entry in bytes.split(|&b| b == b'\0').filter(|s| !s.is_empty()) {
            if let Some(eq_pos) = entry.iter().position(|&b| b == b'=') {
                let key = std::ffi::OsStr::from_bytes(&entry[..eq_pos]).to_os_string();
                let value = std::ffi::OsStr::from_bytes(&entry[eq_pos + 1..]).to_os_string();
                map.insert(key, value);
            }
        }

        Ok(map)
    }

    /// Reads the `/proc/PID/exe` symlink to get the executable path.
    ///
    /// Returns [`Error::PermissionDenied`] if the process is owned
    /// by another user and the caller lacks `CAP_SYS_PTRACE`.
    pub fn exe(&self) -> Result<std::path::PathBuf> {
        let path = format!("/proc/{}/exe", self.pid);
        std::fs::read_link(&path).map_err(|e| {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                Error::PermissionDenied(PathBuf::from(&path))
            } else {
                Error::Io {
                    path: Some(PathBuf::from(&path)),
                    error: e,
                }
            }
        })
    }

    /// Reads the `/proc/PID/cwd` symlink to get the working directory.
    ///
    /// Returns [`Error::PermissionDenied`] under the same conditions
    /// as [`Process::exe`].
    pub fn cwd(&self) -> Result<std::path::PathBuf> {
        let path = format!("/proc/{}/cwd", self.pid);
        std::fs::read_link(&path).map_err(|e| {
            if e.kind() == std::io::ErrorKind::PermissionDenied {
                Error::PermissionDenied(PathBuf::from(&path))
            } else {
                Error::Io {
                    path: Some(PathBuf::from(&path)),
                    error: e,
                }
            }
        })
    }

    /// Reads `/proc/PID/maps` and returns the memory map entries.
    ///
    /// Each entry describes a virtual memory region: address range,
    /// permissions (read/write/exec/shared/private), offset, device,
    /// inode, and optional backing pathname.
    pub fn maps(&self) -> Result<Vec<MemoryMap>> {
        let path = format!("/proc/{}/maps", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        MemoryMap::parse_all(&bytes)
    }

    /// Reads `/proc/PID/smaps` and returns detailed memory stats.
    ///
    /// Extends `/proc/PID/maps` with per-region RSS, PSS, shared/
    /// private clean/dirty, referenced, anonymous, and swap counts.
    /// This is significantly larger than `maps` and slower to parse.
    pub fn smaps(&self) -> Result<Vec<MemoryMapDetail>> {
        let path = format!("/proc/{}/smaps", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        MemoryMapDetail::parse_all(&bytes)
    }

    /// Reads `/proc/PID/smaps_rollup` and returns a [`SmapsRollup`].
    ///
    /// A single aggregate memory summary (RSS, PSS, shared/private,
    /// swap, ...). Much smaller and faster to parse than the full
    /// `/proc/PID/smaps`, at the cost of losing per-region details.
    ///
    /// Requires kernel 4.14 or newer; on older kernels this returns
    /// [`Error::UnsupportedKernel`].
    pub fn smaps_rollup(&self) -> Result<SmapsRollup> {
        KernelVersion::current()?.require(4, 14)?;
        let path = format!("/proc/{}/smaps_rollup", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        SmapsRollup::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/fd/` and returns open file descriptors.
    ///
    /// Iterates the directory, reads each symlink, and classifies
    /// the target as a file, socket, pipe, anon-inode, or other.
    pub fn fds(&self) -> Result<Vec<Fd>> {
        fd::read_fds(self.pid)
    }

    /// Reads `/proc/PID/io` and returns I/O counters.
    ///
    /// Reports bytes read/written at the syscall level (`rchar`/
    /// `wchar`) and at the storage layer (`read_bytes`/
    /// `write_bytes`). The difference between the two pairs reveals
    /// page cache activity.
    pub fn io(&self) -> Result<ProcessIo> {
        let path = format!("/proc/{}/io", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        ProcessIo::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/limits` and returns resource limits.
    ///
    /// Parses the table-format file into typed [`Limit`] structs
    /// with soft/hard values and units. `unlimited` is represented
    /// as `None`.
    pub fn limits(&self) -> Result<ProcessLimits> {
        let path = format!("/proc/{}/limits", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        ProcessLimits::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/syscall` and returns the current system call.
    ///
    /// Exposes the system call number and argument registers for the
    /// system call currently being executed by the process, followed
    /// by the stack pointer and instruction pointer.
    ///
    /// Returns [`SyscallState::Running`] if the process is not blocked.
    /// Returns [`SyscallState::BlockedNotInSyscall`] if blocked but
    /// not in a syscall (syscall number -1). Returns
    /// [`SyscallState::InSyscall`] with the syscall number and
    /// arguments if currently in a syscall.
    ///
    /// Requires kernel 2.6.27+ with `CONFIG_HAVE_ARCH_TRACEHOOK`.
    /// Returns [`Error::PermissionDenied`] if the caller lacks
    /// `PTRACE_MODE_ATTACH_FSCREDS` permission.
    pub fn syscall(&self) -> Result<ProcessSyscall> {
        let path = format!("/proc/{}/syscall", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        ProcessSyscall::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/mountinfo` and returns mount entries.
    ///
    /// A richer format than `/proc/mounts` with mount IDs, parent
    /// IDs, optional fields, and separate superblock options.
    pub fn mountinfo(&self) -> Result<Vec<MountInfo>> {
        let path = format!("/proc/{}/mountinfo", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        MountInfo::parse_all(&bytes)
    }

    /// Reads `/proc/PID/cgroup` and returns cgroup memberships.
    ///
    /// Each entry lists the hierarchy ID, controller list, and
    /// cgroup path. Empty controller lists indicate the process is
    /// in the root cgroup for that hierarchy.
    pub fn cgroup(&self) -> Result<Vec<CgroupEntry>> {
        let path = format!("/proc/{}/cgroup", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        CgroupEntry::parse_all(&bytes)
    }

    /// Reads `/proc/PID/ns/` and returns namespace inode numbers.
    ///
    /// Each namespace symlink (`mnt`, `pid`, `net`, etc.) is read
    /// and its target inode is extracted. Missing namespaces (e.g.
    /// `time` on older kernels) are returned as `None`.
    pub fn namespaces(&self) -> Result<Namespaces> {
        let path = format!("/proc/{}/ns", self.pid);
        Namespaces::from_dir(&path)
    }

    /// Iterates over the threads of this process.
    ///
    /// Scans `/proc/PID/task/` for numeric entries. Each thread is
    /// returned as a `Process` with its TID as the `pid` field,
    /// allowing all `Process` methods to be called on individual
    /// threads.
    pub fn threads(&self) -> impl Iterator<Item = Result<Self>> {
        threads::read_threads(self.pid)
    }

    /// Reads `/proc/PID/auxv` and returns the auxiliary vector.
    ///
    /// The auxiliary vector carries startup information the kernel
    /// passes to the dynamic linker, including the page size, ELF
    /// header pointers, and random bytes.
    pub fn auxv(&self) -> Result<Auxv> {
        let path = format!("/proc/{}/auxv", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        Auxv::from_bytes(&bytes)
    }

    /// Reads `/proc/PID/pagemap` for a virtual address range.
    ///
    /// Returns one [`PageMapEntry`] per page intersecting `start..end`
    /// (start inclusive, end exclusive). The pagemap covers the whole
    /// address space, including unmapped holes, so it is read a range
    /// at a time; use [`Process::maps`] to find the regions worth
    /// querying.
    ///
    /// The page size comes from the process's auxiliary vector
    /// (`AT_PAGESZ`), so this also reads `/proc/PID/auxv`.
    ///
    /// Reading another process's pagemap requires `CAP_SYS_PTRACE`.
    /// Without it the page frame numbers read back as zero, though
    /// the present and soft-dirty bits remain visible.
    ///
    /// Ranges that extend past the end of the address space (such as
    /// the `[vsyscall]` mapping on x86_64) yield only the entries the
    /// kernel can report.
    pub fn pagemap(&self, start: u64, end: u64) -> Result<Vec<PageMapEntry>> {
        pagemap::read(self.pid, start, end)
    }

    /// Reads `/proc/PID/statm` and returns the memory summary.
    ///
    /// Seven page counts covering total size, resident set, shared
    /// (file-backed), text, libraries, data, and dirty pages. All
    /// values are in pages, not bytes.
    pub fn statm(&self) -> Result<Statm> {
        let path = format!("/proc/{}/statm", self.pid);
        let bytes = parse::read_file(Path::new(&path))?;
        Statm::from_bytes(&bytes)
    }
}