Skip to main content

c/
fts.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// A real fts(3) implementation. The tree is scanned depth-first on the first
5// fts_read() call into a preorder array; fts_read() then walks that array.
6
7pub const FTS_COMFOLLOW_V: c_int = 0x001;
8pub const FTS_LOGICAL_V: c_int = 0x002;
9pub const FTS_NOCHDIR_V: c_int = 0x004;
10pub const FTS_NOSTAT_V: c_int = 0x008;
11pub const FTS_PHYSICAL_V: c_int = 0x010;
12pub const FTS_SEEDOT_V: c_int = 0x020;
13pub const FTS_XDEV_V: c_int = 0x040;
14
15pub const FTS_D_V: u16 = 1;
16pub const FTS_DC_V: u16 = 2;
17pub const FTS_DEFAULT_V: u16 = 3;
18pub const FTS_DNR_V: u16 = 4;
19pub const FTS_DOT_V: u16 = 5;
20pub const FTS_DP_V: u16 = 6;
21pub const FTS_ERR_V: u16 = 7;
22pub const FTS_F_V: u16 = 8;
23pub const FTS_INIT_V: u16 = 9;
24pub const FTS_NS_V: u16 = 10;
25pub const FTS_NSOK_V: u16 = 11;
26pub const FTS_SL_V: u16 = 12;
27pub const FTS_SLNONE_V: u16 = 13;
28pub const FTS_W_V: u16 = 14;
29
30pub const FTS_SKIP_V: c_int = 1;
31pub const FTS_FOLLOW_V: c_int = 2;
32pub const FTS_NOINSTR_V: c_int = 3;
33
34const FTS_NAME_OFF: usize = core::mem::offset_of!(FtsEnt, fts_name);
35
36#[repr(C)]
37pub struct FtsEnt {
38    pub fts_cycle: *mut FtsEnt,
39    pub fts_parent: *mut FtsEnt,
40    pub fts_link: *mut FtsEnt,
41    pub fts_number: c_long,
42    pub fts_pointer: *mut c_void,
43    pub fts_accpath: *mut c_char,
44    pub fts_path: *mut c_char,
45    pub fts_errno: c_int,
46    pub fts_symfd: c_int,
47    pub fts_pathlen: u16,
48    pub fts_namelen: u16,
49    pub fts_ino: u64,
50    pub fts_dev: u64,
51    pub fts_nlink: u64,
52    pub fts_level: u16,
53    pub fts_info: u16,
54    pub fts_flags: u16,
55    pub fts_instr: u16,
56    pub fts_statp: *mut Stat,
57    pub fts_name: [c_char; 1],
58}
59
60const _: [(); 120] = [(); core::mem::size_of::<FtsEnt>()];
61const _: [(); 112] = [(); FTS_NAME_OFF];
62
63pub struct Fts {
64    roots: *mut *mut c_char,
65    nroots: usize,
66    options: c_int,
67    compar: Option<unsafe extern "C" fn(*const *const FtsEnt, *const *const FtsEnt) -> c_int>,
68    ents: *mut *mut FtsEnt,
69    nents: usize,
70    ents_cap: usize,
71    idx: usize,
72    built: bool,
73}
74
75unsafe fn fts_name_ptr(ent: *mut FtsEnt) -> *mut c_char {
76    (ent as *mut u8).add(FTS_NAME_OFF) as *mut c_char
77}
78
79unsafe fn fts_ent_alloc(
80    path: *const c_char,
81    name: *const c_char,
82    level: u16,
83    parent: *mut FtsEnt,
84) -> *mut FtsEnt {
85    let plen = crate::strlen(path);
86    let nlen = crate::strlen(name);
87    let namelen = nlen + 1;
88    let stat_off = (core::mem::size_of::<FtsEnt>() + namelen + 7) & !7usize;
89    let total = stat_off + core::mem::size_of::<Stat>();
90    let raw = crate::calloc(1, total) as *mut u8;
91    if raw.is_null() { return core::ptr::null_mut(); }
92    let ent = raw as *mut FtsEnt;
93    (*ent).fts_parent = parent;
94    (*ent).fts_level = level;
95    (*ent).fts_pathlen = plen as u16;
96    (*ent).fts_namelen = nlen as u16;
97    let pathbuf = crate::malloc(plen + 1) as *mut c_char;
98    if pathbuf.is_null() { crate::free(raw as *mut c_void); return core::ptr::null_mut(); }
99    core::ptr::copy_nonoverlapping(path, pathbuf, plen + 1);
100    (*ent).fts_path = pathbuf;
101    (*ent).fts_accpath = pathbuf;
102    core::ptr::copy_nonoverlapping(name, fts_name_ptr(ent), namelen);
103    (*ent).fts_statp = raw.add(stat_off) as *mut Stat;
104    ent
105}
106
107unsafe fn fts_push(fts: *mut Fts, ent: *mut FtsEnt) -> bool {
108    if ent.is_null() { return false; }
109    if (*fts).nents == (*fts).ents_cap {
110        let ncap = if (*fts).ents_cap == 0 { 64 } else { (*fts).ents_cap * 2 };
111        let na = crate::realloc(
112            (*fts).ents as *mut c_void,
113            ncap * core::mem::size_of::<*mut FtsEnt>(),
114        ) as *mut *mut FtsEnt;
115        if na.is_null() { ERRNO!() = ENOMEM; return false; }
116        (*fts).ents = na;
117        (*fts).ents_cap = ncap;
118    }
119    *(*fts).ents.add((*fts).nents) = ent;
120    (*fts).nents += 1;
121    (*ent).fts_link = core::ptr::null_mut();
122    true
123}
124
125unsafe fn fts_free_ent(ent: *mut FtsEnt) {
126    if ent.is_null() { return; }
127    if !(*ent).fts_path.is_null() { crate::free((*ent).fts_path as *mut c_void); }
128    crate::free(ent as *mut c_void);
129}
130
131unsafe fn fts_name_of(path: *const c_char) -> *const c_char {
132    let n = crate::strlen(path);
133    let mut i = n;
134    while i > 0 {
135        if *path.add(i - 1) == b'/' as c_char { break; }
136        i -= 1;
137    }
138    path.add(i)
139}
140
141unsafe fn fts_join(dir: *const c_char, name: *const c_char) -> *mut c_char {
142    let dl = crate::strlen(dir);
143    let nl = crate::strlen(name);
144    let need_sep = dl > 0 && *dir.add(dl - 1) != b'/' as c_char;
145    let total = dl + if need_sep { 1 } else { 0 } + nl + 1;
146    let p = crate::malloc(total) as *mut c_char;
147    if p.is_null() { return core::ptr::null_mut(); }
148    core::ptr::copy_nonoverlapping(dir, p, dl);
149    let mut o = dl;
150    if need_sep { *p.add(o) = b'/' as c_char; o += 1; }
151    core::ptr::copy_nonoverlapping(name, p.add(o), nl + 1);
152    p
153}
154
155unsafe fn fts_is_dir(mode: u32) -> bool { mode & 0o170000 == 0o040000 }
156unsafe fn fts_is_link(mode: u32) -> bool { mode & 0o170000 == 0o120000 }
157
158unsafe fn fts_stat_path(path: *const c_char, follow: bool, st: *mut Stat) -> c_int {
159    if follow { crate::stat(path, st) } else { crate::lstat(path, st as *mut c_void) }
160}
161
162unsafe fn fts_collect_names(path: *const c_char) -> (*mut *mut c_char, usize) {
163    let fd = crate::open(path, crate::O_DIRECTORY, 0); // O_RDONLY|O_DIRECTORY
164    if fd < 0 { return (core::ptr::null_mut(), 0); }
165    let mut cap = 16usize;
166    let mut count = 0usize;
167    let mut arr = crate::malloc(cap * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
168    if arr.is_null() { crate::close(fd); return (core::ptr::null_mut(), 0); }
169    let mut buf = [0u8; 4096];
170    loop {
171        let n = <Arch as Syscalls>::syscall3(
172            SYS_GETDENTS64,
173            fd as i64,
174            buf.as_mut_ptr() as i64,
175            buf.len() as i64,
176        ) as isize;
177        if n <= 0 { break; }
178        let mut pos = 0usize;
179        while pos < n as usize {
180            let ent = buf.as_ptr().add(pos) as *const linux_dirent64;
181            let reclen = (*ent).d_reclen as usize;
182            if reclen == 0 { break; }
183            let namep = (ent as *const u8).add(core::mem::offset_of!(linux_dirent64, d_name)) as *const c_char;
184            let nl = crate::strlen(namep);
185            if count + 2 >= cap {
186                cap *= 2;
187                let na = crate::realloc(arr as *mut c_void, cap * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
188                if na.is_null() { break; }
189                arr = na;
190            }
191            let copy = crate::malloc(nl + 1) as *mut c_char;
192            if copy.is_null() { break; }
193            core::ptr::copy_nonoverlapping(namep, copy, nl + 1);
194            *arr.add(count) = copy;
195            count += 1;
196            pos += reclen;
197        }
198    }
199    crate::close(fd);
200    (arr, count)
201}
202
203unsafe fn fts_free_names(arr: *mut *mut c_char, count: usize) {
204    if arr.is_null() { return; }
205    for i in 0..count {
206        if !(*arr.add(i)).is_null() { crate::free(*arr.add(i) as *mut c_void); }
207    }
208    crate::free(arr as *mut c_void);
209}
210
211unsafe extern "C" fn fts_cmp_trampoline(
212    a: *const c_void,
213    b: *const c_void,
214    arg: *mut c_void,
215) -> c_int {
216    let cmp: unsafe extern "C" fn(*const *const FtsEnt, *const *const FtsEnt) -> c_int =
217        core::mem::transmute(arg);
218    cmp(a as *const *const FtsEnt, b as *const *const FtsEnt)
219}
220
221unsafe fn fts_sort_entries(fts: *mut Fts, arr: *mut *mut FtsEnt, count: usize) {
222    let cmp = match (*fts).compar { Some(c) => c, None => return };
223    if count > 1 {
224        crate::qsort_r(
225            arr as *mut c_void,
226            count,
227            core::mem::size_of::<*mut FtsEnt>(),
228            fts_cmp_trampoline,
229            cmp as *mut c_void,
230        );
231    }
232}
233
234unsafe fn fts_fill_info(ent: *mut FtsEnt, st: *mut Stat) -> u16 {
235    if (*ent).fts_errno != 0 { return FTS_NS_V; }
236    let mode = (*st).st_mode;
237    if fts_is_dir(mode) { FTS_D_V }
238    else if fts_is_link(mode) { FTS_SL_V }
239    else if mode & 0o170000 == 0o100000 { FTS_F_V }
240    else { FTS_DEFAULT_V }
241}
242
243unsafe fn fts_walk(fts: *mut Fts, ent: *mut FtsEnt) {
244    if !fts_push(fts, ent) {
245        fts_free_ent(ent);
246        return;
247    }
248    if (*ent).fts_level >= 64 || (*ent).fts_info != FTS_D_V { return; }
249    let mut p = (*ent).fts_parent;
250    while !p.is_null() {
251        if (*p).fts_info == FTS_D_V && (*p).fts_dev == (*ent).fts_dev && (*p).fts_ino == (*ent).fts_ino {
252            (*ent).fts_info = FTS_DC_V;
253            return;
254        }
255        p = (*p).fts_parent;
256    }
257
258    let (names, count) = fts_collect_names((*ent).fts_path);
259    if !names.is_null() {
260        let ptrsz = core::mem::size_of::<*mut c_char>();
261        let kids = crate::malloc((count + 1) * ptrsz) as *mut *mut FtsEnt;
262        if !kids.is_null() {
263            let mut nkids = 0usize;
264            for i in 0..count {
265                let name = *names.add(i);
266                if ((*fts).options & FTS_SEEDOT_V) == 0 {
267                    if crate::strcmp(name as *const u8, b".\0".as_ptr()) == 0 { continue; }
268                    if crate::strcmp(name as *const u8, b"..\0".as_ptr()) == 0 { continue; }
269                }
270                let full = fts_join((*ent).fts_path, name);
271                if full.is_null() { continue; }
272                let child = fts_ent_alloc(full, name, (*ent).fts_level + 1, ent);
273                crate::free(full as *mut c_void);
274                if child.is_null() { continue; }
275                let mut st: Stat = core::mem::zeroed();
276                let follow = (*fts).options & FTS_LOGICAL_V != 0;
277                let mut rc = fts_stat_path((*child).fts_path, follow, &mut st);
278                if rc != 0 && !follow {
279                    rc = fts_stat_path((*child).fts_path, true, &mut st);
280                }
281                if rc != 0 {
282                    (*child).fts_errno = ERRNO!();
283                    (*child).fts_info = FTS_NS_V;
284                } else {
285                    core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*child).fts_statp as *mut u8, core::mem::size_of::<Stat>());
286                    (*child).fts_ino = st.st_ino;
287                    (*child).fts_dev = st.st_dev;
288                    (*child).fts_nlink = st.st_nlink as u64;
289                    (*child).fts_info = fts_fill_info(child, &mut st);
290                }
291                *kids.add(nkids) = child;
292                nkids += 1;
293            }
294            fts_sort_entries(fts, kids, nkids);
295            for i in 0..nkids { fts_walk(fts, *kids.add(i)); }
296            crate::free(kids as *mut c_void);
297        }
298        fts_free_names(names, count);
299    }
300
301    let dp = fts_ent_alloc((*ent).fts_path, fts_name_ptr(ent), (*ent).fts_level, (*ent).fts_parent);
302    if !dp.is_null() {
303        (*dp).fts_info = FTS_DP_V;
304        (*dp).fts_dev = (*ent).fts_dev;
305        (*dp).fts_ino = (*ent).fts_ino;
306        if !fts_push(fts, dp) {
307            fts_free_ent(dp);
308        }
309    }
310}
311
312unsafe fn fts_build(fts: *mut Fts) {
313    (*fts).built = true;
314    for i in 0..(*fts).nroots {
315        let root = *(*fts).roots.add(i);
316        if root.is_null() { continue; }
317        let mut st: Stat = core::mem::zeroed();
318        let follow = (*fts).options & (FTS_LOGICAL_V | FTS_COMFOLLOW_V) != 0;
319        let rc = fts_stat_path(root, follow, &mut st);
320        let ent = fts_ent_alloc(root, fts_name_of(root), 0, core::ptr::null_mut());
321        if ent.is_null() { continue; }
322        if rc != 0 {
323            (*ent).fts_errno = ERRNO!();
324            (*ent).fts_info = FTS_NS_V;
325            if !fts_push(fts, ent) {
326                fts_free_ent(ent);
327            }
328            continue;
329        }
330        core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*ent).fts_statp as *mut u8, core::mem::size_of::<Stat>());
331        (*ent).fts_ino = st.st_ino;
332        (*ent).fts_dev = st.st_dev;
333        (*ent).fts_nlink = st.st_nlink as u64;
334        (*ent).fts_info = fts_fill_info(ent, &mut st);
335        fts_walk(fts, ent);
336    }
337}
338
339#[no_mangle]
340pub unsafe extern "C" fn fts_open(
341    path_argv: *mut *mut c_char,
342    options: c_int,
343    compar: Option<unsafe extern "C" fn(*const *const FtsEnt, *const *const FtsEnt) -> c_int>,
344) -> *mut Fts {
345    if path_argv.is_null() || (*path_argv).is_null() {
346        ERRNO!() = EINVAL;
347        return core::ptr::null_mut();
348    }
349    let fts = crate::calloc(1, core::mem::size_of::<Fts>()) as *mut Fts;
350    if fts.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
351    let mut n = 0usize;
352    while !(*path_argv.add(n)).is_null() { n += 1; }
353    let roots = crate::malloc((n + 1) * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
354    if roots.is_null() { crate::free(fts as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
355    for i in 0..n {
356        let s = *path_argv.add(i);
357        let l = crate::strlen(s);
358        let copy = crate::malloc(l + 1) as *mut c_char;
359        if copy.is_null() {
360            for j in 0..i {
361                crate::free(*roots.add(j) as *mut c_void);
362            }
363            ERRNO!() = ENOMEM;
364            crate::free(roots as *mut c_void);
365            crate::free(fts as *mut c_void);
366            return core::ptr::null_mut();
367        }
368        core::ptr::copy_nonoverlapping(s, copy, l + 1);
369        *roots.add(i) = copy;
370    }
371    *roots.add(n) = core::ptr::null_mut();
372    (*fts).roots = roots;
373    (*fts).nroots = n;
374    (*fts).options = options;
375    (*fts).compar = compar;
376    (*fts).ents = core::ptr::null_mut();
377    (*fts).nents = 0;
378    (*fts).ents_cap = 0;
379    (*fts).idx = 0;
380    (*fts).built = false;
381    fts
382}
383
384#[no_mangle]
385pub unsafe extern "C" fn fts_read(fts: *mut Fts) -> *mut FtsEnt {
386    if fts.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
387    if !(*fts).built { fts_build(fts); }
388    if (*fts).idx < (*fts).nents {
389        let e = *(*fts).ents.add((*fts).idx);
390        (*fts).idx += 1;
391        return e;
392    }
393    core::ptr::null_mut()
394}
395
396#[no_mangle]
397pub unsafe extern "C" fn fts_set(fts: *mut Fts, ent: *mut FtsEnt, instr: c_int) -> c_int {
398    if fts.is_null() || ent.is_null() { ERRNO!() = EINVAL; return -1; }
399    match instr {
400        FTS_SKIP_V => {
401            (*ent).fts_instr = FTS_SKIP_V as u16;
402            if (*ent).fts_info == FTS_D_V {
403                let lvl = (*ent).fts_level;
404                while (*fts).idx < (*fts).nents {
405                    let e = *(*fts).ents.add((*fts).idx);
406                    if (*e).fts_level < lvl { break; }
407                    (*fts).idx += 1;
408                    if (*e).fts_level == lvl && (*e).fts_info == FTS_DP_V { break; }
409                }
410                (*ent).fts_instr = FTS_SKIP_V as u16;
411            }
412        }
413        FTS_FOLLOW_V => {
414            (*ent).fts_instr = FTS_FOLLOW_V as u16;
415            if (*ent).fts_info == FTS_SL_V || (*ent).fts_info == FTS_SLNONE_V {
416                let mut st: Stat = core::mem::zeroed();
417                if crate::stat((*ent).fts_path, &mut st) == 0 {
418                    core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*ent).fts_statp as *mut u8, core::mem::size_of::<Stat>());
419                    (*ent).fts_ino = st.st_ino;
420                    (*ent).fts_dev = st.st_dev;
421                    (*ent).fts_nlink = st.st_nlink as u64;
422                    (*ent).fts_info = fts_fill_info(ent, &mut st);
423                }
424            }
425        }
426        FTS_NOINSTR_V => { (*ent).fts_instr = FTS_NOINSTR_V as u16; }
427        _ => { ERRNO!() = EINVAL; return -1; }
428    }
429    0
430}
431
432#[no_mangle]
433pub unsafe extern "C" fn fts_children(fts: *mut Fts, _instr: c_int) -> *mut FtsEnt {
434    if fts.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
435    if !(*fts).built { fts_build(fts); }
436    if (*fts).idx == 0 { return core::ptr::null_mut(); }
437    let parent = *(*fts).ents.add((*fts).idx - 1);
438    if (*parent).fts_info != FTS_D_V { return core::ptr::null_mut(); }
439    let level = (*parent).fts_level + 1;
440    let mut head: *mut FtsEnt = core::ptr::null_mut();
441    let mut tail: *mut FtsEnt = core::ptr::null_mut();
442    let mut i = (*fts).idx;
443    while i < (*fts).nents {
444        let q = *(*fts).ents.add(i);
445        if (*q).fts_level < level { break; }
446        if (*q).fts_level == level && (*q).fts_info != FTS_DP_V {
447            (*q).fts_link = core::ptr::null_mut();
448            if head.is_null() { head = q; } else { (*tail).fts_link = q; }
449            tail = q;
450        }
451        i += 1;
452    }
453    head
454}
455
456#[no_mangle]
457pub unsafe extern "C" fn fts_close(fts: *mut Fts) -> c_int {
458    if fts.is_null() { ERRNO!() = EINVAL; return -1; }
459    for i in 0..(*fts).nents {
460        fts_free_ent(*(*fts).ents.add(i));
461    }
462    if !(*fts).ents.is_null() { crate::free((*fts).ents as *mut c_void); }
463    for i in 0..(*fts).nroots {
464        if !(*(*fts).roots.add(i)).is_null() { crate::free(*(*fts).roots.add(i) as *mut c_void); }
465    }
466    crate::free((*fts).roots as *mut c_void);
467    crate::free(fts as *mut c_void);
468    0
469}