RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / user / ls.rs
5302 bytes ยท raw
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
//! ls [-l] [path...] -- list directories (shell alias: dir).
//!
//! On the console the names are printed in columns; into a pipe or file
//! one per line (like the real `ls`, so `ls | wc -l` counts files).
//! -l adds sizes, DOS style: `<DIR>` or the size in bytes. On file systems
//! with Unix permissions (ext2) it also shows them, like `-rw-r--r--`, and
//! where symlinks point: `hello-link -> hello.txt`.
#![no_std]
#![no_main]

extern crate alloc;

#[macro_use]
#[path = "ulib.rs"]
mod ulib;

use alloc::{format, string::String, vec::Vec};
use ulib::*;

struct Entry {
    name: String,
    dir: bool,
    link: bool,
    size: u64,
    mode: u64,           // 0 = no permissions on this file system
    target: String,      // symlinks (with -l): where they point
}

fn main() -> i64 {
    let mut long = false;
    let mut paths = Vec::new();
    for i in 1..argc() {
        match arg(i) {
            Some("-l") => long = true,
            Some(a) => paths.push(a),
            None => {}
        }
    }
    if paths.is_empty() {
        paths.push(".");
    }
    let mut st = Stat::default();
    let columns = !long && fstat(1, &mut st) == 0 && st.kind == KIND_CONSOLE;

    let mut status = 0;
    for (i, path) in paths.iter().enumerate() {
        let r = stat(path, &mut st);
        if r < 0 {
            eprintln!("ls: {}: {}", path, strerror(r));
            status = 1;
            continue;
        }
        if st.kind != KIND_DIR {
            let entry = Entry { name: String::from(*path), dir: false, link: false, size: st.size, mode: st.mode, target: String::new() };
            print_entries(&[entry], long, columns);
            continue;
        }
        if paths.len() > 1 {
            println!("{}{}:", if i > 0 { "\n" } else { "" }, path);
        }
        match read_dir(path, long) {
            Ok(entries) => print_entries(&entries, long, columns),
            Err(e) => {
                eprintln!("ls: {}: {}", path, strerror(e));
                status = 1;
            }
        }
    }
    status
}

/// All entries of a directory, sorted by name.
fn read_dir(path: &str, long: bool) -> Result<Vec<Entry>, i64> {
    let fd = open(path, 0);
    if fd < 0 {
        return Err(fd);
    }
    let mut entries = Vec::new();
    let mut buf = [0u8; 1024];
    loop {
        // Each call returns as many records as fit; 0 = no more.
        let n = getdents64(fd, &mut buf);
        if n <= 0 {
            break;
        }
        for_each_dirent(&buf, n as usize, |name, d_type| {
            if name != "." && name != ".." {
                let (dir, link) = (d_type == 4, d_type == 10); // DT_DIR, DT_LNK
                entries.push(Entry { name: String::from(name), dir, link, size: 0, mode: 0, target: String::new() });
            }
        });
    }
    close(fd);
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    if long {
        let mut st = Stat::default();
        for e in entries.iter_mut() {
            let full = format!("{}/{}", path, e.name);
            if e.link {
                let mut buf = [0u8; 256];
                let n = readlink(&full, &mut buf);
                if n >= 0 {
                    e.target = String::from(core::str::from_utf8(&buf[..n as usize]).unwrap_or("?"));
                }
            } else if stat(&full, &mut st) == 0 {
                e.size = st.size;
                e.mode = st.mode;
            }
        }
    }
    Ok(entries)
}

fn print_entries(entries: &[Entry], long: bool, columns: bool) {
    if long {
        for e in entries {
            // `drwxr-xr-x ` in front if the file system has permissions.
            let perms = if e.mode != 0 || e.link { format!("{} ", mode_string(e)) } else { String::new() };
            if e.dir {
                println!("{}     <DIR>  {}/", perms, e.name);
            } else if e.link {
                println!("{}            {} -> {}", perms, e.name, e.target);
            } else {
                println!("{}{:>10}  {}", perms, e.size, e.name);
            }
        }
        return;
    }
    let shown = |e: &Entry| match (e.dir, e.link) {
        (true, _) => format!("{}/", e.name),
        (_, true) => format!("{}@", e.name), // like `ls -F`
        _ => e.name.clone(),
    };
    if !columns {
        entries.iter().for_each(|e| println!("{}", shown(e)));
        return;
    }
    // Columns across an 80-character screen.
    let width = entries.iter().map(|e| shown(e).len() + 2).max().unwrap_or(1);
    let per_line = (79 / width).max(1);
    for (i, e) in entries.iter().enumerate() {
        let last = i + 1 == entries.len() || (i + 1) % per_line == 0;
        if last {
            println!("{}", shown(e));
        } else {
            print!("{:<w$}", shown(e), w = width);
        }
    }
}

/// `-rw-r--r--` style: type, then rwx for owner, group and others.
fn mode_string(e: &Entry) -> String {
    if e.link {
        return String::from("lrwxrwxrwx"); // symlink permissions are never used
    }
    let mut s = String::from(if e.dir { "d" } else { "-" });
    for shift in [6, 3, 0] {
        let bits = (e.mode >> shift) & 7;
        s.push(if bits & 4 != 0 { 'r' } else { '-' });
        s.push(if bits & 2 != 0 { 'w' } else { '-' });
        s.push(if bits & 1 != 0 { 'x' } else { '-' });
    }
    s
}