armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! time - time command execution
//!
//! Run a command and report how long it took including user/sys CPU time.

extern crate alloc;

use alloc::vec::Vec;
use alloc::ffi::CString;
use crate::io;
use crate::sys;
use super::get_arg;

/// rusage structure for getrusage()
#[repr(C)]
struct Rusage {
    ru_utime: Timeval,      // user CPU time
    ru_stime: Timeval,      // system CPU time
    ru_maxrss: libc::c_long,        // max resident set size
    ru_ixrss: libc::c_long,         // integral shared memory size
    ru_idrss: libc::c_long,         // integral unshared data size
    ru_isrss: libc::c_long,         // integral unshared stack size
    ru_minflt: libc::c_long,        // page reclaims (soft page faults)
    ru_majflt: libc::c_long,        // page faults (hard page faults)
    ru_nswap: libc::c_long,         // swaps
    ru_inblock: libc::c_long,       // block input operations
    ru_oublock: libc::c_long,       // block output operations
    ru_msgsnd: libc::c_long,        // IPC messages sent
    ru_msgrcv: libc::c_long,        // IPC messages received
    ru_nsignals: libc::c_long,      // signals received
    ru_nvcsw: libc::c_long,         // voluntary context switches
    ru_nivcsw: libc::c_long,        // involuntary context switches
}

#[repr(C)]
#[derive(Clone, Copy)]
struct Timeval {
    tv_sec: i64,
    tv_usec: libc::suseconds_t,
}

#[repr(C)]
struct Timespec {
    tv_sec: i64,
    tv_nsec: libc::c_long,
}

const CLOCK_MONOTONIC: libc::clockid_t = 1;

unsafe extern "C" {
    fn wait4(pid: libc::pid_t, status: *mut libc::c_int, options: libc::c_int,
             rusage: *mut Rusage) -> libc::pid_t;
    fn clock_gettime(clockid: libc::clockid_t, tp: *mut Timespec) -> libc::c_int;
}

/// time - time command execution
///
/// # Synopsis
/// ```text
/// time [-p] [-v] COMMAND [ARGS...]
/// ```
///
/// # Description
/// Run COMMAND and report timing information including real (wall-clock),
/// user (CPU time in user mode), and system (CPU time in kernel mode) times.
///
/// # Options
/// - `-p`: Use POSIX portable output format
/// - `-v`: Verbose output with memory and I/O statistics
///
/// # Exit Status
/// - Exit status of COMMAND, or 127 if command cannot be found
pub fn time(argc: i32, argv: *const *const u8) -> i32 {
    let mut portable = false;
    let mut verbose = false;
    let mut cmd_start = 1;

    // Parse options
    for i in 1..argc {
        if let Some(arg) = unsafe { get_arg(argv, i) } {
            if arg == b"-p" || arg == b"--portability" {
                portable = true;
                cmd_start = i + 1;
            } else if arg == b"-v" || arg == b"--verbose" {
                verbose = true;
                cmd_start = i + 1;
            } else if arg == b"-h" || arg == b"--help" {
                print_help();
                return 0;
            } else if arg == b"--" {
                cmd_start = i + 1;
                break;
            } else if !arg.starts_with(b"-") {
                cmd_start = i;
                break;
            }
        }
    }

    if cmd_start >= argc {
        io::write_str(2, b"time: missing command\n");
        io::write_str(2, b"Usage: time [-p] [-v] COMMAND [ARGS...]\n");
        return 1;
    }

    // Get start time with high precision
    let mut start_time = Timespec { tv_sec: 0, tv_nsec: 0 };
    unsafe { clock_gettime(CLOCK_MONOTONIC, &mut start_time); }

    // Fork and exec
    let pid = unsafe { libc::fork() };
    if pid < 0 {
        io::write_str(2, b"time: fork failed\n");
        return 1;
    }

    if pid == 0 {
        // Child process - exec the command
        let mut args: Vec<CString> = Vec::new();

        for i in cmd_start..argc {
            if let Some(arg) = unsafe { get_arg(argv, i) } {
                let mut v = Vec::with_capacity(arg.len() + 1);
                v.extend_from_slice(arg);
                v.push(0);
                if let Ok(cs) = CString::from_vec_with_nul(v) {
                    args.push(cs);
                }
            }
        }

        let ptrs: Vec<*const i8> = args.iter()
            .map(|s| s.as_ptr())
            .chain(core::iter::once(core::ptr::null()))
            .collect();

        unsafe { libc::execvp(ptrs[0], ptrs.as_ptr()); }

        // If exec failed
        io::write_str(2, b"time: ");
        if let Some(cmd) = unsafe { get_arg(argv, cmd_start) } {
            io::write_all(2, cmd);
        }
        io::write_str(2, b": command not found\n");
        unsafe { libc::_exit(127); }
    }

    // Parent - wait for child and get resource usage
    let mut status: libc::c_int = 0;
    let mut rusage: Rusage = unsafe { core::mem::zeroed() };

    let ret = unsafe { wait4(pid, &mut status, 0, &mut rusage) };

    // Get end time
    let mut end_time = Timespec { tv_sec: 0, tv_nsec: 0 };
    unsafe { clock_gettime(CLOCK_MONOTONIC, &mut end_time); }

    if ret < 0 {
        io::write_str(2, b"time: wait failed\n");
        return 1;
    }

    // Calculate real time
    let real_sec = end_time.tv_sec - start_time.tv_sec;
    let mut real_nsec = end_time.tv_nsec - start_time.tv_nsec;
    let real_sec = if real_nsec < 0 {
        real_nsec += 1_000_000_000;
        real_sec - 1
    } else {
        real_sec
    };

    // Convert rusage times to seconds and microseconds
    let user_sec = rusage.ru_utime.tv_sec as u64;
    let user_usec = rusage.ru_utime.tv_usec as u64;
    let sys_sec = rusage.ru_stime.tv_sec as u64;
    let sys_usec = rusage.ru_stime.tv_usec as u64;

    io::write_str(2, b"\n");

    if portable {
        // POSIX portable format
        print_portable_time(b"real", real_sec as u64, (real_nsec / 1000) as u64);
        print_portable_time(b"user", user_sec, user_usec);
        print_portable_time(b"sys", sys_sec, sys_usec);
    } else if verbose {
        // Verbose format with all stats
        print_verbose_stats(
            real_sec as u64, (real_nsec / 1000) as u64,
            user_sec, user_usec,
            sys_sec, sys_usec,
            &rusage
        );
    } else {
        // Default bash-like format
        print_default_time(b"real", real_sec as u64, (real_nsec / 1_000_000) as u64);
        print_default_time(b"user", user_sec, user_usec / 1000);
        print_default_time(b"sys", sys_sec, sys_usec / 1000);
    }

    // Return child's exit status
    if libc::WIFEXITED(status) {
        libc::WEXITSTATUS(status)
    } else if libc::WIFSIGNALED(status) {
        128 + libc::WTERMSIG(status)
    } else {
        1
    }
}

/// Print time in POSIX portable format: name Xm Y.YYs
fn print_portable_time(name: &[u8], secs: u64, usecs: u64) {
    io::write_all(2, name);
    io::write_str(2, b" ");

    let minutes = secs / 60;
    let seconds = secs % 60;
    let centisecs = usecs / 10000; // Convert to hundredths

    io::write_num(2, minutes);
    io::write_str(2, b"m");
    io::write_num(2, seconds);
    io::write_str(2, b".");
    if centisecs < 10 {
        io::write_str(2, b"0");
    }
    io::write_num(2, centisecs);
    io::write_str(2, b"s\n");
}

/// Print time in default bash-like format with tab: name\tXmY.YYYs
fn print_default_time(name: &[u8], secs: u64, msecs: u64) {
    io::write_all(2, name);
    io::write_str(2, b"\t");

    let minutes = secs / 60;
    let seconds = secs % 60;

    io::write_num(2, minutes);
    io::write_str(2, b"m");
    io::write_num(2, seconds);
    io::write_str(2, b".");

    // Print milliseconds with leading zeros
    if msecs < 100 {
        io::write_str(2, b"0");
    }
    if msecs < 10 {
        io::write_str(2, b"0");
    }
    io::write_num(2, msecs);
    io::write_str(2, b"s\n");
}

/// Print verbose statistics (like GNU time -v)
fn print_verbose_stats(
    real_sec: u64, real_usec: u64,
    user_sec: u64, user_usec: u64,
    sys_sec: u64, sys_usec: u64,
    rusage: &Rusage
) {
    io::write_str(2, b"\tCommand being timed\n");

    // Time stats
    io::write_str(2, b"\tUser time (seconds): ");
    print_seconds(user_sec, user_usec);
    io::write_str(2, b"\n");

    io::write_str(2, b"\tSystem time (seconds): ");
    print_seconds(sys_sec, sys_usec);
    io::write_str(2, b"\n");

    // Calculate CPU percentage
    let total_cpu_usec = (user_sec * 1_000_000 + user_usec) + (sys_sec * 1_000_000 + sys_usec);
    let real_usec_total = real_sec * 1_000_000 + real_usec;
    let cpu_percent = if real_usec_total > 0 {
        (total_cpu_usec * 100) / real_usec_total
    } else {
        0
    };

    io::write_str(2, b"\tPercent of CPU this job got: ");
    io::write_num(2, cpu_percent);
    io::write_str(2, b"%\n");

    io::write_str(2, b"\tElapsed (wall clock) time: ");
    let minutes = real_sec / 60;
    let seconds = real_sec % 60;
    let hours = minutes / 60;
    let minutes = minutes % 60;
    if hours > 0 {
        io::write_num(2, hours);
        io::write_str(2, b":");
    }
    if minutes < 10 && hours > 0 {
        io::write_str(2, b"0");
    }
    io::write_num(2, minutes);
    io::write_str(2, b":");
    if seconds < 10 {
        io::write_str(2, b"0");
    }
    io::write_num(2, seconds);
    io::write_str(2, b".");
    let centisecs = real_usec / 10000;
    if centisecs < 10 {
        io::write_str(2, b"0");
    }
    io::write_num(2, centisecs);
    io::write_str(2, b"\n");

    // Memory stats
    io::write_str(2, b"\tMaximum resident set size (kbytes): ");
    io::write_num(2, rusage.ru_maxrss as u64);
    io::write_str(2, b"\n");

    // Page fault stats
    io::write_str(2, b"\tMajor (requiring I/O) page faults: ");
    io::write_num(2, rusage.ru_majflt as u64);
    io::write_str(2, b"\n");

    io::write_str(2, b"\tMinor (reclaiming a frame) page faults: ");
    io::write_num(2, rusage.ru_minflt as u64);
    io::write_str(2, b"\n");

    // I/O stats
    io::write_str(2, b"\tVoluntary context switches: ");
    io::write_num(2, rusage.ru_nvcsw as u64);
    io::write_str(2, b"\n");

    io::write_str(2, b"\tInvoluntary context switches: ");
    io::write_num(2, rusage.ru_nivcsw as u64);
    io::write_str(2, b"\n");

    io::write_str(2, b"\tFile system inputs: ");
    io::write_num(2, rusage.ru_inblock as u64);
    io::write_str(2, b"\n");

    io::write_str(2, b"\tFile system outputs: ");
    io::write_num(2, rusage.ru_oublock as u64);
    io::write_str(2, b"\n");
}

/// Print seconds with microsecond precision
fn print_seconds(secs: u64, usecs: u64) {
    io::write_num(2, secs);
    io::write_str(2, b".");

    // Print microseconds with leading zeros
    let mut num_buf = [0u8; 16];
    let usec_str = sys::format_u64(usecs, &mut num_buf);
    // Pad to 6 digits
    for _ in 0..(6 - usec_str.len()) {
        io::write_str(2, b"0");
    }
    io::write_all(2, usec_str);
}

fn print_help() {
    io::write_str(1, b"Usage: time [-p] [-v] COMMAND [ARGS...]\n\n");
    io::write_str(1, b"Run COMMAND and report time statistics.\n\n");
    io::write_str(1, b"Options:\n");
    io::write_str(1, b"  -p, --portability   Use POSIX portable output format\n");
    io::write_str(1, b"  -v, --verbose       Print all resource usage statistics\n");
    io::write_str(1, b"  -h, --help          Display this help\n\n");
    io::write_str(1, b"Output:\n");
    io::write_str(1, b"  real    Wall clock time (elapsed time)\n");
    io::write_str(1, b"  user    CPU time in user mode\n");
    io::write_str(1, b"  sys     CPU time in kernel mode\n");
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::Command;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::current_dir().unwrap());
        let release = manifest_dir.join("target/release/armybox");
        if release.exists() { return release; }
        manifest_dir.join("target/debug/armybox")
    }

    #[test]
    fn test_time_true() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "true"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("real"));
        assert!(stderr.contains("user"));
        assert!(stderr.contains("sys"));
    }

    #[test]
    fn test_time_no_command() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("missing command"));
    }

    #[test]
    fn test_time_portable() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "-p", "true"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        // Portable format uses "real Xm Y.YYs"
        assert!(stderr.contains("real "));
        assert!(stderr.contains("m"));
    }

    #[test]
    fn test_time_verbose() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "-v", "true"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("Maximum resident set size"));
        assert!(stderr.contains("User time"));
    }

    #[test]
    fn test_time_help() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "--help"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("Usage"));
    }

    #[test]
    fn test_time_exit_status() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "false"])
            .output()
            .unwrap();

        // 'false' returns exit code 1
        assert_eq!(output.status.code(), Some(1));
    }

    #[test]
    fn test_time_nonexistent_command() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "nonexistent_command_12345"])
            .output()
            .unwrap();

        // Should return 127 for command not found
        assert_eq!(output.status.code(), Some(127));
    }

    #[test]
    fn test_time_with_args() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["time", "echo", "hello", "world"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("hello world"));
    }
}