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
//! rm - remove files or directories
//!
//! POSIX.1-2017 compliant implementation.
//! Reference: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/rm.html

use crate::io;
use crate::sys;
use crate::applets::{get_arg, has_opt};

/// rm - remove files or directories
///
/// # Synopsis
/// ```text
/// rm [-fiRr] file...
/// ```
///
/// # Description
/// Removes (unlinks) files. With -r, removes directories recursively.
///
/// # Options
/// - `-f`: Force - ignore nonexistent files, never prompt
/// - `-i`: Interactive - prompt before every removal (not implemented)
/// - `-R`, `-r`: Recursive - remove directories and their contents
///
/// # Exit Status
/// - 0: All files removed successfully
/// - >0: An error occurred
pub fn rm(argc: i32, argv: *const *const u8) -> i32 {
    let mut recursive = false;
    let mut force = false;
    let mut _interactive = false;
    let mut files_start = 1;
    let mut has_files = false;

    // Parse options and find files
    for i in 1..argc {
        if let Some(arg) = unsafe { get_arg(argv, i) } {
            if arg.len() > 0 && arg[0] == b'-' && !has_files {
                // Handle -- to stop option processing
                if arg == b"--" {
                    files_start = i + 1;
                    break;
                }
                if has_opt(arg, b'r') || has_opt(arg, b'R') { recursive = true; }
                if has_opt(arg, b'f') { force = true; }
                if has_opt(arg, b'i') { _interactive = true; }
                files_start = i + 1;
            } else {
                has_files = true;
                break;
            }
        }
    }

    // Check if we have files to remove
    if files_start >= argc {
        if !force {
            io::write_str(2, b"rm: missing operand\n");
            return 1;
        }
        return 0;  // -f with no files is OK
    }

    let mut exit_code = 0;

    // Process each file
    for i in files_start..argc {
        if let Some(path) = unsafe { get_arg(argv, i) } {
            let result = if recursive {
                remove_recursive(path, force)
            } else {
                remove_file(path, force)
            };

            if result != 0 {
                exit_code = 1;
            }
        }
    }

    exit_code
}

/// Remove a single file (non-directory)
fn remove_file(path: &[u8], force: bool) -> i32 {
    // Check if it's a directory
    let mut st: libc::stat = unsafe { core::mem::zeroed() };
    if io::lstat(path, &mut st) == 0 {
        if (st.st_mode & libc::S_IFMT) == libc::S_IFDIR {
            if !force {
                io::write_str(2, b"rm: cannot remove '");
                io::write_all(2, path);
                io::write_str(2, b"': Is a directory\n");
            }
            return if force { 0 } else { 1 };
        }
    } else {
        // File doesn't exist
        if !force {
            sys::perror(path);
        }
        return if force { 0 } else { 1 };
    }

    if io::unlink(path) < 0 {
        if !force {
            sys::perror(path);
        }
        return if force { 0 } else { 1 };
    }

    0
}

/// Remove a file or directory recursively
fn remove_recursive(path: &[u8], force: bool) -> i32 {
    let mut st: libc::stat = unsafe { core::mem::zeroed() };

    // Use lstat to not follow symlinks
    if io::lstat(path, &mut st) < 0 {
        if !force {
            sys::perror(path);
        }
        return if force { 0 } else { 1 };
    }

    // If it's a symlink or regular file, just unlink it
    if (st.st_mode & libc::S_IFMT) != libc::S_IFDIR {
        if io::unlink(path) < 0 {
            if !force {
                sys::perror(path);
            }
            return if force { 0 } else { 1 };
        }
        return 0;
    }

    // It's a directory - recurse into it
    let fd = io::open(path, libc::O_RDONLY | libc::O_DIRECTORY, 0);
    if fd < 0 {
        if !force {
            sys::perror(path);
        }
        return if force { 0 } else { 1 };
    }

    let mut exit_code = 0;
    let mut buf = [0u8; 4096];

    loop {
        let n = unsafe { libc::syscall(libc::SYS_getdents64, fd, buf.as_mut_ptr(), buf.len()) };
        if n <= 0 { break; }

        let mut offset = 0;
        while offset < n as usize {
            let dirent = unsafe { &*(buf.as_ptr().add(offset) as *const libc::dirent64) };
            let name = unsafe { io::cstr_to_slice(dirent.d_name.as_ptr() as *const u8) };

            if name != b"." && name != b".." {
                // Build full path
                let mut full_path = [0u8; 4096];
                let mut len = 0;
                for &c in path {
                    if len < full_path.len() - 1 {
                        full_path[len] = c;
                        len += 1;
                    }
                }
                if len < full_path.len() - 1 {
                    full_path[len] = b'/';
                    len += 1;
                }
                for &c in name {
                    if len < full_path.len() - 1 {
                        full_path[len] = c;
                        len += 1;
                    }
                }

                if remove_recursive(&full_path[..len], force) != 0 {
                    exit_code = 1;
                }
            }

            offset += dirent.d_reclen as usize;
        }
    }

    io::close(fd);

    // Now remove the empty directory
    if io::rmdir(path) < 0 {
        if !force {
            sys::perror(path);
        }
        return if force { 0 } else { 1 };
    }

    exit_code
}

#[cfg(test)]
mod tests {
    //! Unit tests for rm utility

    extern crate std;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEST_COUNTER: AtomicUsize = AtomicUsize::new(0);
    use std::process::Command;
    use std::fs;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let release = PathBuf::from("target/release/armybox");
        if release.exists() { return release; }
        PathBuf::from("target/debug/armybox")
    }

    fn setup() -> PathBuf {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!("armybox_rm_test_{}_{}",  std::process::id(), counter));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn cleanup(dir: &std::path::Path) {
        let _ = fs::remove_dir_all(dir);
    }

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

        let dir = setup();
        fs::write(dir.join("file.txt"), "content").unwrap();

        let output = Command::new(&armybox)
            .args(["rm", dir.join("file.txt").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("file.txt").exists());
        cleanup(&dir);
    }

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

        let dir = setup();
        fs::write(dir.join("file1.txt"), "content1").unwrap();
        fs::write(dir.join("file2.txt"), "content2").unwrap();

        let output = Command::new(&armybox)
            .args(["rm",
                dir.join("file1.txt").to_str().unwrap(),
                dir.join("file2.txt").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("file1.txt").exists());
        assert!(!dir.join("file2.txt").exists());
        cleanup(&dir);
    }

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

        let output = Command::new(&armybox)
            .args(["rm", "/nonexistent/file"])
            .output()
            .unwrap();

        assert_ne!(output.status.code(), Some(0));
    }

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

        let output = Command::new(&armybox)
            .args(["rm", "-f", "/nonexistent/file"])
            .output()
            .unwrap();

        // -f should not fail on nonexistent files
        assert_eq!(output.status.code(), Some(0));
    }

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

        let dir = setup();
        fs::create_dir(dir.join("subdir")).unwrap();

        let output = Command::new(&armybox)
            .args(["rm", dir.join("subdir").to_str().unwrap()])
            .output()
            .unwrap();

        // Should fail - can't remove directory without -r
        assert_ne!(output.status.code(), Some(0));
        assert!(dir.join("subdir").exists());
        cleanup(&dir);
    }

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

        let dir = setup();
        fs::create_dir_all(dir.join("subdir/nested")).unwrap();
        fs::write(dir.join("subdir/file.txt"), "content").unwrap();
        fs::write(dir.join("subdir/nested/deep.txt"), "deep").unwrap();

        let output = Command::new(&armybox)
            .args(["rm", "-r", dir.join("subdir").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("subdir").exists());
        cleanup(&dir);
    }

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

        let dir = setup();
        fs::create_dir(dir.join("subdir")).unwrap();
        fs::write(dir.join("subdir/file.txt"), "content").unwrap();

        let output = Command::new(&armybox)
            .args(["rm", "-R", dir.join("subdir").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("subdir").exists());
        cleanup(&dir);
    }

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

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

        assert_ne!(output.status.code(), Some(0));
        assert!(std::string::String::from_utf8_lossy(&output.stderr).contains("missing operand"));
    }

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

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

        // -f with no operands should succeed silently
        assert_eq!(output.status.code(), Some(0));
    }

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

        let dir = setup();
        fs::write(dir.join("target.txt"), "content").unwrap();

        // Create symlink
        Command::new("ln")
            .args(["-s",
                dir.join("target.txt").to_str().unwrap(),
                dir.join("link").to_str().unwrap()])
            .output()
            .unwrap();

        let output = Command::new(&armybox)
            .args(["rm", dir.join("link").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("link").exists());
        // Target should still exist
        assert!(dir.join("target.txt").exists());
        cleanup(&dir);
    }

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

        let dir = setup();
        fs::create_dir(dir.join("subdir")).unwrap();
        fs::write(dir.join("subdir/file.txt"), "content").unwrap();

        let output = Command::new(&armybox)
            .args(["rm", "-rf", dir.join("subdir").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        assert!(!dir.join("subdir").exists());
        cleanup(&dir);
    }
}