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 extern "C" fn fts_cmp_trampoline(
163    a: *const c_void,
164    b: *const c_void,
165    arg: *mut c_void,
166) -> c_int {
167    let cmp: unsafe extern "C" fn(*const *const FtsEnt, *const *const FtsEnt) -> c_int =
168        core::mem::transmute(arg);
169    cmp(a as *const *const FtsEnt, b as *const *const FtsEnt)
170}
171
172unsafe fn fts_sort_entries(fts: *mut Fts, arr: *mut *mut FtsEnt, count: usize) {
173    let cmp = match (*fts).compar { Some(c) => c, None => return };
174    if count > 1 {
175        crate::qsort_r(
176            arr as *mut c_void,
177            count,
178            core::mem::size_of::<*mut FtsEnt>(),
179            fts_cmp_trampoline,
180            cmp as *mut c_void,
181        );
182    }
183}
184
185unsafe fn fts_fill_info(ent: *mut FtsEnt, st: *mut Stat) -> u16 {
186    if (*ent).fts_errno != 0 { return FTS_NS_V; }
187    let mode = (*st).st_mode;
188    if fts_is_dir(mode) { FTS_D_V }
189    else if fts_is_link(mode) { FTS_SL_V }
190    else if mode & 0o170000 == 0o100000 { FTS_F_V }
191    else { FTS_DEFAULT_V }
192}
193
194unsafe fn fts_walk(fts: *mut Fts, ent: *mut FtsEnt) {
195    if !fts_push(fts, ent) {
196        fts_free_ent(ent);
197        return;
198    }
199    if (*ent).fts_level >= 64 || (*ent).fts_info != FTS_D_V { return; }
200    let mut p = (*ent).fts_parent;
201    while !p.is_null() {
202        if (*p).fts_info == FTS_D_V && (*p).fts_dev == (*ent).fts_dev && (*p).fts_ino == (*ent).fts_ino {
203            (*ent).fts_info = FTS_DC_V;
204            return;
205        }
206        p = (*p).fts_parent;
207    }
208
209    let (names, count) = crate::list_dir_names((*ent).fts_path);
210    if !names.is_null() {
211        let ptrsz = core::mem::size_of::<*mut c_char>();
212        let kids = crate::malloc((count + 1) * ptrsz) as *mut *mut FtsEnt;
213        if !kids.is_null() {
214            let mut nkids = 0usize;
215            for i in 0..count {
216                let name = *names.add(i);
217                if ((*fts).options & FTS_SEEDOT_V) == 0 {
218                    if crate::strcmp(name as *const u8, b".\0".as_ptr()) == 0 { continue; }
219                    if crate::strcmp(name as *const u8, b"..\0".as_ptr()) == 0 { continue; }
220                }
221                let full = fts_join((*ent).fts_path, name);
222                if full.is_null() { continue; }
223                let child = fts_ent_alloc(full, name, (*ent).fts_level + 1, ent);
224                crate::free(full as *mut c_void);
225                if child.is_null() { continue; }
226                let mut st: Stat = core::mem::zeroed();
227                let follow = (*fts).options & FTS_LOGICAL_V != 0;
228                let mut rc = fts_stat_path((*child).fts_path, follow, &mut st);
229                if rc != 0 && !follow {
230                    rc = fts_stat_path((*child).fts_path, true, &mut st);
231                }
232                if rc != 0 {
233                    (*child).fts_errno = ERRNO!();
234                    (*child).fts_info = FTS_NS_V;
235                } else {
236                    core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*child).fts_statp as *mut u8, core::mem::size_of::<Stat>());
237                    (*child).fts_ino = st.st_ino;
238                    (*child).fts_dev = st.st_dev;
239                    (*child).fts_nlink = st.st_nlink as u64;
240                    (*child).fts_info = fts_fill_info(child, &mut st);
241                }
242                *kids.add(nkids) = child;
243                nkids += 1;
244            }
245            fts_sort_entries(fts, kids, nkids);
246            for i in 0..nkids { fts_walk(fts, *kids.add(i)); }
247            crate::free(kids as *mut c_void);
248        }
249        crate::free_names(names, count);
250    }
251
252    let dp = fts_ent_alloc((*ent).fts_path, fts_name_ptr(ent), (*ent).fts_level, (*ent).fts_parent);
253    if !dp.is_null() {
254        (*dp).fts_info = FTS_DP_V;
255        (*dp).fts_dev = (*ent).fts_dev;
256        (*dp).fts_ino = (*ent).fts_ino;
257        if !fts_push(fts, dp) {
258            fts_free_ent(dp);
259        }
260    }
261}
262
263unsafe fn fts_build(fts: *mut Fts) {
264    (*fts).built = true;
265    for i in 0..(*fts).nroots {
266        let root = *(*fts).roots.add(i);
267        if root.is_null() { continue; }
268        let mut st: Stat = core::mem::zeroed();
269        let follow = (*fts).options & (FTS_LOGICAL_V | FTS_COMFOLLOW_V) != 0;
270        let rc = fts_stat_path(root, follow, &mut st);
271        let ent = fts_ent_alloc(root, fts_name_of(root), 0, core::ptr::null_mut());
272        if ent.is_null() { continue; }
273        if rc != 0 {
274            (*ent).fts_errno = ERRNO!();
275            (*ent).fts_info = FTS_NS_V;
276            if !fts_push(fts, ent) {
277                fts_free_ent(ent);
278            }
279            continue;
280        }
281        core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*ent).fts_statp as *mut u8, core::mem::size_of::<Stat>());
282        (*ent).fts_ino = st.st_ino;
283        (*ent).fts_dev = st.st_dev;
284        (*ent).fts_nlink = st.st_nlink as u64;
285        (*ent).fts_info = fts_fill_info(ent, &mut st);
286        fts_walk(fts, ent);
287    }
288}
289
290#[no_mangle]
291pub unsafe extern "C" fn fts_open(
292    path_argv: *mut *mut c_char,
293    options: c_int,
294    compar: Option<unsafe extern "C" fn(*const *const FtsEnt, *const *const FtsEnt) -> c_int>,
295) -> *mut Fts {
296    if path_argv.is_null() || (*path_argv).is_null() {
297        ERRNO!() = EINVAL;
298        return core::ptr::null_mut();
299    }
300    let fts = crate::calloc(1, core::mem::size_of::<Fts>()) as *mut Fts;
301    if fts.is_null() { ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
302    let mut n = 0usize;
303    while !(*path_argv.add(n)).is_null() { n += 1; }
304    let roots = crate::malloc((n + 1) * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
305    if roots.is_null() { crate::free(fts as *mut c_void); ERRNO!() = ENOMEM; return core::ptr::null_mut(); }
306    for i in 0..n {
307        let s = *path_argv.add(i);
308        let l = crate::strlen(s);
309        let copy = crate::malloc(l + 1) as *mut c_char;
310        if copy.is_null() {
311            for j in 0..i {
312                crate::free(*roots.add(j) as *mut c_void);
313            }
314            ERRNO!() = ENOMEM;
315            crate::free(roots as *mut c_void);
316            crate::free(fts as *mut c_void);
317            return core::ptr::null_mut();
318        }
319        core::ptr::copy_nonoverlapping(s, copy, l + 1);
320        *roots.add(i) = copy;
321    }
322    *roots.add(n) = core::ptr::null_mut();
323    (*fts).roots = roots;
324    (*fts).nroots = n;
325    (*fts).options = options;
326    (*fts).compar = compar;
327    (*fts).ents = core::ptr::null_mut();
328    (*fts).nents = 0;
329    (*fts).ents_cap = 0;
330    (*fts).idx = 0;
331    (*fts).built = false;
332    fts
333}
334
335#[no_mangle]
336pub unsafe extern "C" fn fts_read(fts: *mut Fts) -> *mut FtsEnt {
337    if fts.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
338    if !(*fts).built { fts_build(fts); }
339    if (*fts).idx < (*fts).nents {
340        let e = *(*fts).ents.add((*fts).idx);
341        (*fts).idx += 1;
342        return e;
343    }
344    core::ptr::null_mut()
345}
346
347#[no_mangle]
348pub unsafe extern "C" fn fts_set(fts: *mut Fts, ent: *mut FtsEnt, instr: c_int) -> c_int {
349    if fts.is_null() || ent.is_null() { ERRNO!() = EINVAL; return -1; }
350    match instr {
351        FTS_SKIP_V => {
352            (*ent).fts_instr = FTS_SKIP_V as u16;
353            if (*ent).fts_info == FTS_D_V {
354                let lvl = (*ent).fts_level;
355                while (*fts).idx < (*fts).nents {
356                    let e = *(*fts).ents.add((*fts).idx);
357                    if (*e).fts_level < lvl { break; }
358                    (*fts).idx += 1;
359                    if (*e).fts_level == lvl && (*e).fts_info == FTS_DP_V { break; }
360                }
361                (*ent).fts_instr = FTS_SKIP_V as u16;
362            }
363        }
364        FTS_FOLLOW_V => {
365            (*ent).fts_instr = FTS_FOLLOW_V as u16;
366            if (*ent).fts_info == FTS_SL_V || (*ent).fts_info == FTS_SLNONE_V {
367                let mut st: Stat = core::mem::zeroed();
368                if crate::stat((*ent).fts_path, &mut st) == 0 {
369                    core::ptr::copy_nonoverlapping(&st as *const Stat as *const u8, (*ent).fts_statp as *mut u8, core::mem::size_of::<Stat>());
370                    (*ent).fts_ino = st.st_ino;
371                    (*ent).fts_dev = st.st_dev;
372                    (*ent).fts_nlink = st.st_nlink as u64;
373                    (*ent).fts_info = fts_fill_info(ent, &mut st);
374                }
375            }
376        }
377        FTS_NOINSTR_V => { (*ent).fts_instr = FTS_NOINSTR_V as u16; }
378        _ => { ERRNO!() = EINVAL; return -1; }
379    }
380    0
381}
382
383#[no_mangle]
384pub unsafe extern "C" fn fts_children(fts: *mut Fts, _instr: c_int) -> *mut FtsEnt {
385    if fts.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
386    if !(*fts).built { fts_build(fts); }
387    if (*fts).idx == 0 { return core::ptr::null_mut(); }
388    let parent = *(*fts).ents.add((*fts).idx - 1);
389    if (*parent).fts_info != FTS_D_V { return core::ptr::null_mut(); }
390    let level = (*parent).fts_level + 1;
391    let mut head: *mut FtsEnt = core::ptr::null_mut();
392    let mut tail: *mut FtsEnt = core::ptr::null_mut();
393    let mut i = (*fts).idx;
394    while i < (*fts).nents {
395        let q = *(*fts).ents.add(i);
396        if (*q).fts_level < level { break; }
397        if (*q).fts_level == level && (*q).fts_info != FTS_DP_V {
398            (*q).fts_link = core::ptr::null_mut();
399            if head.is_null() { head = q; } else { (*tail).fts_link = q; }
400            tail = q;
401        }
402        i += 1;
403    }
404    head
405}
406
407#[no_mangle]
408pub unsafe extern "C" fn fts_close(fts: *mut Fts) -> c_int {
409    if fts.is_null() { ERRNO!() = EINVAL; return -1; }
410    for i in 0..(*fts).nents {
411        fts_free_ent(*(*fts).ents.add(i));
412    }
413    if !(*fts).ents.is_null() { crate::free((*fts).ents as *mut c_void); }
414    for i in 0..(*fts).nroots {
415        if !(*(*fts).roots.add(i)).is_null() { crate::free(*(*fts).roots.add(i) as *mut c_void); }
416    }
417    crate::free((*fts).roots as *mut c_void);
418    crate::free(fts as *mut c_void);
419    0
420}