Skip to main content

nros/
task_census.rs

1//! The boot task census of a Linux process: every thread with its scheduling
2//! policy and real-time priority, as the RTOS runners print theirs (FreeRTOS,
3//! NuttX, ThreadX):
4//!
5//! ```text
6//! nros: task census name=`<comm>` prio=<rt_priority> policy=<FIFO|RR|OTHER|...>
7//! nros: task census done tasks=<n>
8//! ```
9//!
10//! Read from `/proc/self/task/<tid>/{comm,stat}`, through the C library and
11//! not `std`, for the reason [`mod@crate::env`] gives: the edge is "a C library is
12//! linked", which on this tree is `target_os = "linux"`. ONE reader serves both
13//! Linux runners, the Rust board's (`nros-board-linux`) and the C/C++ one
14//! (`nros-cpp`), which do not share a board crate.
15//!
16//! `prio` is the real-time priority (`stat` field 40). A thread on a
17//! non-real-time policy has 0 there and sits outside every band of the
18//! priority plan by construction. The Linux plan states
19//! `reserved.foreign = []`, and this is what a test checks it against.
20
21use core::{
22    ffi::{c_char, c_int, c_void},
23    fmt,
24};
25
26/// glibc's `struct dirent64`, the same on every glibc Linux architecture.
27#[repr(C)]
28struct Dirent64 {
29    d_ino: u64,
30    d_off: i64,
31    d_reclen: u16,
32    d_type: u8,
33    d_name: [c_char; 256],
34}
35
36unsafe extern "C" {
37    fn opendir(name: *const c_char) -> *mut c_void;
38    fn readdir64(dir: *mut c_void) -> *mut Dirent64;
39    fn closedir(dir: *mut c_void) -> c_int;
40    fn open(path: *const c_char, flags: c_int, ...) -> c_int;
41    fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
42    fn close(fd: c_int) -> c_int;
43}
44
45const O_RDONLY: c_int = 0;
46// `man 5 proc`, /proc/[pid]/stat: field (39) processor, (40) rt_priority,
47// (41) policy. Both
48// follow `comm`, which may hold spaces and parentheses, so the fields are
49// counted after the LAST ')'; the first one after it is field 3.
50const RT_PRIORITY_FIELD: usize = 40;
51/// The most threads reported; a census of a nano-ros image is a handful.
52const MAX_THREADS: usize = 64;
53
54/// A fixed buffer that formats a NUL-terminated path.
55struct PathBuf {
56    buf: [u8; 64],
57    len: usize,
58}
59
60impl fmt::Write for PathBuf {
61    fn write_str(&mut self, s: &str) -> fmt::Result {
62        let b = s.as_bytes();
63        // Keep one byte for the NUL.
64        if self.len + b.len() >= self.buf.len() {
65            return Err(fmt::Error);
66        }
67        self.buf[self.len..self.len + b.len()].copy_from_slice(b);
68        self.len += b.len();
69        Ok(())
70    }
71}
72
73fn path(args: fmt::Arguments<'_>) -> Option<PathBuf> {
74    let mut p = PathBuf {
75        buf: [0; 64],
76        len: 0,
77    };
78    fmt::write(&mut p, args).ok()?;
79    p.buf[p.len] = 0;
80    Some(p)
81}
82
83/// Read a small file whole into `buf`; the bytes read.
84fn read_file<'a>(p: &PathBuf, buf: &'a mut [u8]) -> Option<&'a [u8]> {
85    // SAFETY: `p.buf` is NUL-terminated by `path`.
86    let fd = unsafe { open(p.buf.as_ptr() as *const c_char, O_RDONLY) };
87    if fd < 0 {
88        return None;
89    }
90    let mut len = 0usize;
91    while len < buf.len() {
92        // SAFETY: `buf[len..]` is writable for its length.
93        let n = unsafe { read(fd, buf[len..].as_mut_ptr() as *mut c_void, buf.len() - len) };
94        if n <= 0 {
95            break;
96        }
97        len += n as usize;
98    }
99    // SAFETY: `fd` was opened above.
100    unsafe { close(fd) };
101    Some(&buf[..len])
102}
103
104fn parse_u32(s: &[u8]) -> Option<u32> {
105    core::str::from_utf8(s).ok()?.parse().ok()
106}
107
108fn policy_name(policy: u32) -> &'static str {
109    match policy {
110        0 => "OTHER",
111        1 => "FIFO",
112        2 => "RR",
113        3 => "BATCH",
114        5 => "IDLE",
115        6 => "DEADLINE",
116        _ => "?",
117    }
118}
119
120/// Print the census through `println`, one call per line, ending with the
121/// `done` line. A thread that exits between the listing and the read is
122/// skipped; past `MAX_THREADS` (64) the rest are not reported.
123pub fn report(mut println: impl FnMut(fmt::Arguments<'_>)) {
124    let mut tids = [0u32; MAX_THREADS];
125    let mut n = 0usize;
126    // SAFETY: a NUL-terminated literal.
127    let dir = unsafe { opendir(c"/proc/self/task".as_ptr()) };
128    if dir.is_null() {
129        println(format_args!(
130            "nros: task census unavailable: /proc/self/task is not readable"
131        ));
132        return;
133    }
134    loop {
135        // SAFETY: `dir` is open; the entry lives until the next call.
136        let ent = unsafe { readdir64(dir) };
137        if ent.is_null() {
138            break;
139        }
140        // SAFETY: `d_name` is NUL-terminated by the C library.
141        let name = unsafe { core::ffi::CStr::from_ptr((*ent).d_name.as_ptr()) };
142        if let Some(tid) = parse_u32(name.to_bytes())
143            && n < MAX_THREADS
144        {
145            tids[n] = tid;
146            n += 1;
147        }
148    }
149    // SAFETY: opened above.
150    unsafe { closedir(dir) };
151    tids[..n].sort_unstable();
152
153    let mut count = 0usize;
154    for &tid in &tids[..n] {
155        let (Some(stat_path), Some(comm_path)) = (
156            path(format_args!("/proc/self/task/{tid}/stat")),
157            path(format_args!("/proc/self/task/{tid}/comm")),
158        ) else {
159            continue;
160        };
161        let mut stat_buf = [0u8; 1024];
162        let mut comm_buf = [0u8; 32];
163        let (Some(stat), Some(comm)) = (
164            read_file(&stat_path, &mut stat_buf),
165            read_file(&comm_path, &mut comm_buf),
166        ) else {
167            continue;
168        };
169        let Some(close_paren) = stat.iter().rposition(|&b| b == b')') else {
170            continue;
171        };
172        let mut fields = stat[close_paren + 1..]
173            .split(|b| b.is_ascii_whitespace())
174            .filter(|f| !f.is_empty());
175        // Field 3 is the first; advance to 40, and the policy (41) follows.
176        let prio = fields.nth(RT_PRIORITY_FIELD - 3).and_then(parse_u32);
177        let policy = fields.next().and_then(parse_u32);
178        let (Some(prio), Some(policy)) = (prio, policy) else {
179            continue;
180        };
181        let comm = core::str::from_utf8(comm).unwrap_or("?").trim_end();
182        println(format_args!(
183            "nros: task census name=`{comm}` prio={prio} policy={}",
184            policy_name(policy)
185        ));
186        count += 1;
187    }
188    println(format_args!("nros: task census done tasks={count}"));
189}