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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! xargs - build and execute command lines from standard input
//!
//! GNU coreutils compatible implementation.

extern crate alloc;

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

/// xargs - build and execute command lines from standard input
///
/// # Synopsis
/// ```text
/// xargs [OPTIONS] [COMMAND [INITIAL-ARGS]]
/// ```
///
/// # Description
/// Read items from the standard input and execute a command with
/// those items as arguments.
///
/// # Options
/// - `-0, --null`: Input items are separated by a null character
/// - `-d DELIM`: Input items are separated by DELIM character
/// - `-I REPLSTR`: Replace REPLSTR with input items in arguments
/// - `-n MAXARGS`: Use at most MAXARGS arguments per command line
/// - `-P MAXPROCS`: Run up to MAXPROCS processes at a time
/// - `-r, --no-run-if-empty`: Don't run command if input is empty
/// - `-t, --verbose`: Print command before executing
/// - `-x`: Exit if command line length exceeds limit
///
/// # Exit Status
/// - 0: All commands succeeded
/// - 123: Any command returned 1-125
/// - 124: Command exited with status 255
/// - 125: Command was killed by a signal
/// - 126: Command cannot be run
/// - 127: Command not found
/// - 1: Other error
pub fn xargs(argc: i32, argv: *const *const u8) -> i32 {
    let mut null_delimiter = false;
    let mut delimiter = b'\n';
    let mut replace_str: Option<&[u8]> = None;
    let mut max_args: Option<usize> = None;
    let mut max_procs: usize = 1;
    let mut no_run_if_empty = false;
    let mut verbose = false;
    let mut exit_on_limit = false;
    let mut cmd_start = 1;

    // Parse options
    let mut i = 1;
    while i < argc {
        if let Some(arg) = unsafe { get_arg(argv, i) } {
            if arg == b"-0" || arg == b"--null" {
                null_delimiter = true;
                delimiter = 0;
                cmd_start = i + 1;
            } else if arg == b"-d" {
                i += 1;
                if let Some(d) = unsafe { get_arg(argv, i) } {
                    if !d.is_empty() {
                        delimiter = d[0];
                    }
                }
                cmd_start = i + 1;
            } else if arg == b"-I" || arg == b"-i" {
                i += 1;
                replace_str = unsafe { get_arg(argv, i) };
                cmd_start = i + 1;
            } else if arg.starts_with(b"-I") && arg.len() > 2 {
                // Handle -I{} format (no space)
                replace_str = Some(&arg[2..]);
                cmd_start = i + 1;
            } else if arg == b"-n" {
                i += 1;
                if let Some(n) = unsafe { get_arg(argv, i) } {
                    max_args = sys::parse_u64(n).map(|v| v as usize);
                }
                cmd_start = i + 1;
            } else if arg.starts_with(b"-n") && arg.len() > 2 {
                // Handle -nN format (no space)
                max_args = sys::parse_u64(&arg[2..]).map(|v| v as usize);
                cmd_start = i + 1;
            } else if arg == b"-P" {
                i += 1;
                if let Some(p) = unsafe { get_arg(argv, i) } {
                    max_procs = sys::parse_u64(p).unwrap_or(1) as usize;
                }
                cmd_start = i + 1;
            } else if arg.starts_with(b"-P") && arg.len() > 2 {
                // Handle -PN format (no space)
                max_procs = sys::parse_u64(&arg[2..]).unwrap_or(1) as usize;
                cmd_start = i + 1;
            } else if arg == b"-r" || arg == b"--no-run-if-empty" {
                no_run_if_empty = true;
                cmd_start = i + 1;
            } else if arg == b"-t" || arg == b"--verbose" {
                verbose = true;
                cmd_start = i + 1;
            } else if arg == b"-x" {
                exit_on_limit = 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;
            } else {
                // Check for combined short options like -r0
                let mut valid = true;
                for &c in &arg[1..] {
                    match c {
                        b'0' => {
                            null_delimiter = true;
                            delimiter = 0;
                        }
                        b'r' => no_run_if_empty = true,
                        b't' => verbose = true,
                        b'x' => exit_on_limit = true,
                        _ => {
                            valid = false;
                            break;
                        }
                    }
                }
                if valid {
                    cmd_start = i + 1;
                } else {
                    cmd_start = i;
                    break;
                }
            }
        }
        i += 1;
    }

    // Get command and initial args
    let command = if cmd_start < argc {
        unsafe { get_arg(argv, cmd_start).unwrap_or(b"echo") }
    } else {
        b"echo"
    };

    let mut initial_args: Vec<&[u8]> = Vec::new();
    for j in (cmd_start + 1)..argc {
        if let Some(arg) = unsafe { get_arg(argv, j) } {
            initial_args.push(arg);
        }
    }

    // Read input
    let input = io::read_all(0);

    // Split input into items
    let items: Vec<&[u8]> = if null_delimiter {
        input.split(|&c| c == 0)
            .filter(|s| !s.is_empty())
            .collect()
    } else {
        input.split(|&c| c == delimiter)
            .filter(|s| !s.is_empty())
            .collect()
    };

    // Handle empty input
    if items.is_empty() {
        if no_run_if_empty {
            return 0;
        }
        // With no input and no -r, xargs still runs command once with initial args
        if replace_str.is_none() && max_args.is_none() {
            return run_command(command, &initial_args, verbose);
        }
        return 0;
    }

    // Track exit status
    let mut exit_status = 0;
    let mut running_pids: Vec<libc::pid_t> = Vec::new();

    if let Some(repl) = replace_str {
        // Replace mode: run command once per item, replacing REPLSTR in args
        for item in &items {
            // Wait if we've reached max parallel processes
            while running_pids.len() >= max_procs && max_procs > 0 {
                let status = wait_for_any(&mut running_pids);
                exit_status = update_exit_status(exit_status, status);
            }

            let args = build_replace_args(&initial_args, repl, item);
            let args_refs: Vec<&[u8]> = args.iter().map(|v| v.as_slice()).collect();

            if max_procs > 1 {
                // Run in parallel
                if let Some(pid) = fork_and_run(command, &args_refs, verbose) {
                    running_pids.push(pid);
                }
            } else {
                let status = run_command(command, &args_refs, verbose);
                exit_status = update_exit_status(exit_status, status);
            }
        }
    } else {
        // Normal mode: batch items into command invocations
        let batch_size = max_args.unwrap_or(items.len());

        for chunk in items.chunks(batch_size) {
            // Wait if we've reached max parallel processes
            while running_pids.len() >= max_procs && max_procs > 0 {
                let status = wait_for_any(&mut running_pids);
                exit_status = update_exit_status(exit_status, status);
            }

            let mut args = initial_args.clone();
            args.extend(chunk.iter().copied());

            if max_procs > 1 {
                // Run in parallel
                if let Some(pid) = fork_and_run(command, &args, verbose) {
                    running_pids.push(pid);
                }
            } else {
                let status = run_command(command, &args, verbose);
                exit_status = update_exit_status(exit_status, status);
            }
        }
    }

    // Wait for remaining processes
    while !running_pids.is_empty() {
        let status = wait_for_any(&mut running_pids);
        exit_status = update_exit_status(exit_status, status);
    }

    exit_status
}

/// Build args with replacement
fn build_replace_args(args: &[&[u8]], repl: &[u8], item: &[u8]) -> Vec<Vec<u8>> {
    args.iter().map(|arg| {
        if let Some(pos) = find_subsequence(arg, repl) {
            // Replace REPLSTR with item
            let mut new_arg = Vec::new();
            new_arg.extend_from_slice(&arg[..pos]);
            new_arg.extend_from_slice(item);
            new_arg.extend_from_slice(&arg[pos + repl.len()..]);
            new_arg
        } else {
            arg.to_vec()
        }
    }).collect()
}

/// Find subsequence in slice
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|window| window == needle)
}

/// Run a command synchronously
fn run_command(cmd: &[u8], args: &[&[u8]], verbose: bool) -> i32 {
    if verbose {
        print_command(cmd, args);
    }

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

    if pid == 0 {
        exec_command(cmd, args);
    }

    // Parent - wait for child
    let mut status: libc::c_int = 0;
    unsafe { libc::waitpid(pid, &mut status, 0); }

    get_exit_code(status)
}

/// Fork and run command, returning PID
fn fork_and_run(cmd: &[u8], args: &[&[u8]], verbose: bool) -> Option<libc::pid_t> {
    if verbose {
        print_command(cmd, args);
    }

    let pid = unsafe { libc::fork() };
    if pid < 0 {
        io::write_str(2, b"xargs: fork failed\n");
        return None;
    }

    if pid == 0 {
        exec_command(cmd, args);
    }

    Some(pid)
}

/// Exec a command (in child process)
fn exec_command(cmd: &[u8], args: &[&[u8]]) -> ! {
    let mut cstrings: Vec<CString> = Vec::new();

    // Command
    let mut v = Vec::with_capacity(cmd.len() + 1);
    v.extend_from_slice(cmd);
    v.push(0);
    if let Ok(cs) = CString::from_vec_with_nul(v) {
        cstrings.push(cs);
    }

    // Args
    for arg in args {
        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) {
            cstrings.push(cs);
        }
    }

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

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

    // exec failed
    io::write_str(2, b"xargs: ");
    io::write_all(2, cmd);
    io::write_str(2, b": ");

    let errno = unsafe { *libc::__errno_location() };
    if errno == libc::ENOENT {
        io::write_str(2, b"command not found\n");
        unsafe { libc::_exit(127); }
    } else if errno == libc::EACCES {
        io::write_str(2, b"permission denied\n");
        unsafe { libc::_exit(126); }
    } else {
        io::write_str(2, b"cannot run command\n");
        unsafe { libc::_exit(126); }
    }
}

/// Wait for any child process
fn wait_for_any(pids: &mut Vec<libc::pid_t>) -> i32 {
    let mut status: libc::c_int = 0;
    let pid = unsafe { libc::wait(&mut status) };

    if pid > 0 {
        if let Some(idx) = pids.iter().position(|&p| p == pid) {
            pids.remove(idx);
        }
    }

    get_exit_code(status)
}

/// Get exit code from wait status
fn get_exit_code(status: libc::c_int) -> i32 {
    if libc::WIFEXITED(status) {
        libc::WEXITSTATUS(status)
    } else if libc::WIFSIGNALED(status) {
        125 // killed by signal
    } else {
        1
    }
}

/// Update exit status according to xargs rules
fn update_exit_status(current: i32, new: i32) -> i32 {
    match new {
        0 => current,
        255 => 124,
        126 | 127 => new,
        1..=125 if current == 0 => 123,
        _ => if current == 0 { new } else { current },
    }
}

/// Print command for verbose mode
fn print_command(cmd: &[u8], args: &[&[u8]]) {
    io::write_all(2, cmd);
    for arg in args {
        io::write_str(2, b" ");
        // Quote if contains spaces
        let needs_quote = arg.iter().any(|&c| c == b' ' || c == b'\t');
        if needs_quote {
            io::write_str(2, b"'");
        }
        io::write_all(2, arg);
        if needs_quote {
            io::write_str(2, b"'");
        }
    }
    io::write_str(2, b"\n");
}

fn print_help() {
    io::write_str(1, b"Usage: xargs [OPTIONS] [COMMAND [INITIAL-ARGS]]\n\n");
    io::write_str(1, b"Build and execute command lines from standard input.\n\n");
    io::write_str(1, b"Options:\n");
    io::write_str(1, b"  -0, --null           Items separated by null, not newline\n");
    io::write_str(1, b"  -d DELIM             Items separated by DELIM\n");
    io::write_str(1, b"  -I REPLSTR           Replace REPLSTR in args with input item\n");
    io::write_str(1, b"  -n MAXARGS           Use at most MAXARGS per command line\n");
    io::write_str(1, b"  -P MAXPROCS          Run up to MAXPROCS processes in parallel\n");
    io::write_str(1, b"  -r, --no-run-if-empty  Don't run if input is empty\n");
    io::write_str(1, b"  -t, --verbose        Print command before executing\n");
    io::write_str(1, b"  -x                   Exit if command line too long\n");
    io::write_str(1, b"  -h, --help           Show this help\n\n");
    io::write_str(1, b"Examples:\n");
    io::write_str(1, b"  find . -name '*.txt' | xargs grep 'pattern'\n");
    io::write_str(1, b"  find . -print0 | xargs -0 rm\n");
    io::write_str(1, b"  echo 'a b c' | xargs -n1 echo\n");
    io::write_str(1, b"  ls | xargs -I{} mv {} {}.bak\n");
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::{Command, Stdio};
    use std::io::Write;
    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_xargs_echo() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let mut child = Command::new(&armybox)
            .args(["xargs", "echo"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        {
            let stdin = child.stdin.as_mut().unwrap();
            stdin.write_all(b"hello\nworld\n").unwrap();
        }

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

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

        let mut child = Command::new(&armybox)
            .args(["xargs", "-r", "echo"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        {
            let stdin = child.stdin.as_mut().unwrap();
            stdin.write_all(b"").unwrap();
        }

        let output = child.wait_with_output().unwrap();
        assert_eq!(output.status.code(), Some(0));
        // With -r, no output when input is empty
        assert!(output.stdout.is_empty());
    }

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

        let mut child = Command::new(&armybox)
            .args(["xargs", "-n1", "echo"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        {
            let stdin = child.stdin.as_mut().unwrap();
            stdin.write_all(b"a\nb\nc\n").unwrap();
        }

        let output = child.wait_with_output().unwrap();
        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        // Each item on its own line
        let lines: Vec<&str> = stdout.lines().collect();
        assert_eq!(lines.len(), 3);
    }

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

        let mut child = Command::new(&armybox)
            .args(["xargs", "-0", "echo"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        {
            let stdin = child.stdin.as_mut().unwrap();
            stdin.write_all(b"hello\0world\0").unwrap();
        }

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

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

        let mut child = Command::new(&armybox)
            .args(["xargs", "-I{}", "echo", "item:{}"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();

        {
            let stdin = child.stdin.as_mut().unwrap();
            stdin.write_all(b"foo\nbar\n").unwrap();
        }

        let output = child.wait_with_output().unwrap();
        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("item:foo"));
        assert!(stdout.contains("item:bar"));
    }

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

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

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