Skip to main content

c/
path_extra.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// realpath, glob/globfree and nftw/ftw.
5
6const PATH_MAX_V: usize = 4096;
7
8// ============================================================
9// realpath
10// ============================================================
11
12static mut REALPATH_BUF: [c_char; PATH_MAX_V] = [0; PATH_MAX_V];
13
14#[no_mangle]
15pub unsafe extern "C" fn realpath(
16    filename: *const c_char,
17    resolved: *mut c_char,
18) -> *mut c_char {
19    if filename.is_null() { ERRNO!() = EINVAL; return core::ptr::null_mut(); }
20    let flen = crate::strlen(filename);
21    if flen == 0 { ERRNO!() = ENOENT; return core::ptr::null_mut(); }
22    if flen >= PATH_MAX_V { ERRNO!() = ENAMETOOLONG; return core::ptr::null_mut(); }
23
24    let mut out = [0u8; PATH_MAX_V + 1];
25    let mut olen;
26    let mut pend = [0u8; 2 * PATH_MAX_V + 1];
27    core::ptr::copy_nonoverlapping(filename as *const u8, pend.as_mut_ptr(), flen);
28    pend[flen] = 0;
29    let mut pi = 0usize;
30    let absolute = pend[0] == b'/';
31    if absolute {
32        pi = 1;
33        out[0] = b'/';
34        olen = 1;
35    } else {
36        let r = crate::getcwd(out.as_mut_ptr() as *mut c_char, PATH_MAX_V);
37        if r.is_null() { return core::ptr::null_mut(); }
38        olen = crate::strlen(out.as_ptr() as *const c_char);
39        if olen == 0 { out[0] = b'/'; olen = 1; }
40    }
41    let mut symlinks = 0;
42
43    loop {
44        while pend[pi] == b'/' { pi += 1; }
45        if pend[pi] == 0 { break; }
46        let start = pi;
47        while pend[pi] != 0 && pend[pi] != b'/' { pi += 1; }
48        let comp_len = pi - start;
49        let mut q = pi;
50        while pend[q] == b'/' { q += 1; }
51        let is_last = pend[q] == 0;
52        let followed_by_slash = pend[pi] == b'/';
53        let needs_dir = !is_last || followed_by_slash;
54
55        if comp_len == 1 && pend[start] == b'.' {
56            continue;
57        }
58        if comp_len == 2 && pend[start] == b'.' && pend[start + 1] == b'.' {
59            while olen > 0 && out[olen - 1] != b'/' { olen -= 1; }
60            if olen > 0 { olen -= 1; }
61            continue;
62        }
63
64        if olen == 0 {
65            out[0] = b'/';
66            olen = 1;
67        }
68        if olen > 0 && out[olen - 1] != b'/' {
69            if olen + 1 >= PATH_MAX_V { ERRNO!() = ENAMETOOLONG; return core::ptr::null_mut(); }
70            out[olen] = b'/';
71            olen += 1;
72        }
73        if olen + comp_len >= PATH_MAX_V { ERRNO!() = ENAMETOOLONG; return core::ptr::null_mut(); }
74        core::ptr::copy_nonoverlapping(pend.as_ptr().add(start), out.as_mut_ptr().add(olen), comp_len);
75        olen += comp_len;
76        out[olen] = 0;
77
78        let mut st: Stat = core::mem::zeroed();
79        if crate::lstat(out.as_ptr() as *const c_char, &mut st as *mut Stat as *mut c_void) != 0 {
80            return core::ptr::null_mut();
81        }
82        let mode = st.st_mode;
83        if mode & 0o170000 == 0o120000 {
84            symlinks += 1;
85            if symlinks > 40 { ERRNO!() = ELOOP; return core::ptr::null_mut(); }
86            let mut link = [0u8; PATH_MAX_V + 1];
87            let n = crate::readlink(out.as_ptr() as *const c_char, link.as_mut_ptr() as *mut c_char, PATH_MAX_V);
88            if n < 0 { return core::ptr::null_mut(); }
89            let n = n as usize;
90            if n == 0 { ERRNO!() = ENOENT; return core::ptr::null_mut(); }
91            link[n] = 0;
92            // Remove the component we just appended.
93            while olen > 0 && out[olen - 1] != b'/' { olen -= 1; }
94            if olen > 0 { olen -= 1; }
95            let mut next = [0u8; 2 * PATH_MAX_V + 1];
96            let link_abs = link[0] == b'/';
97            let mut nl = n;
98            core::ptr::copy_nonoverlapping(link.as_ptr(), next.as_mut_ptr(), n);
99            let rest = &pend[pi..];
100            let rest_len = crate::strlen(rest.as_ptr() as *const c_char);
101            if rest_len > 0 {
102                if nl > 0 && next[nl - 1] != b'/' {
103                    next[nl] = b'/';
104                    nl += 1;
105                }
106                if nl + rest_len >= next.len() { ERRNO!() = ENAMETOOLONG; return core::ptr::null_mut(); }
107                core::ptr::copy_nonoverlapping(rest.as_ptr(), next.as_mut_ptr().add(nl), rest_len + 1);
108            }
109            if link_abs { olen = 0; }
110            pend = next;
111            pi = 0;
112            continue;
113        }
114        if mode & 0o170000 != 0o040000 && needs_dir {
115            ERRNO!() = ENOTDIR;
116            return core::ptr::null_mut();
117        }
118    }
119
120    if olen == 0 {
121        out[0] = b'/';
122        olen = 1;
123    }
124    // Collapse a trailing slash except for the root.
125    while olen > 1 && out[olen - 1] == b'/' { olen -= 1; }
126    out[olen] = 0;
127    let dst = if resolved.is_null() { REALPATH_BUF.as_mut_ptr() } else { resolved };
128    core::ptr::copy_nonoverlapping(out.as_ptr(), dst as *mut u8, olen + 1);
129    dst
130}
131
132// ============================================================
133// glob
134// ============================================================
135
136#[repr(C)]
137pub struct GlobT {
138    pub gl_pathc: usize,
139    pub gl_pathv: *mut *mut c_char,
140    pub gl_offs: usize,
141    __dummy1: c_int,
142    __dummy2: [*mut c_void; 5],
143}
144
145const GLOB_ERR_V: c_int = 0x01;
146const GLOB_MARK_V: c_int = 0x02;
147const GLOB_NOSORT_V: c_int = 0x04;
148const GLOB_DOOFFS_V: c_int = 0x08;
149const GLOB_NOCHECK_V: c_int = 0x10;
150const GLOB_APPEND_V: c_int = 0x20;
151const GLOB_NOESCAPE_V: c_int = 0x40;
152const GLOB_PERIOD_V: c_int = 0x80;
153const GLOB_TILDE_V: c_int = 0x1000;
154const GLOB_TILDE_CHECK_V: c_int = 0x4000;
155
156const GLOB_NOSPACE_V: c_int = 1;
157const GLOB_ABORTED_V: c_int = 2;
158const GLOB_NOMATCH_V: c_int = 3;
159
160struct GlobList {
161    items: *mut *mut c_char,
162    n: usize,
163    cap: usize,
164}
165
166unsafe fn glob_list_push(list: *mut GlobList, s: *const c_char) {
167    if (*list).n == (*list).cap {
168        let ncap = if (*list).cap == 0 { 32 } else { (*list).cap * 2 };
169        let na = crate::realloc(
170            (*list).items as *mut c_void,
171            ncap * core::mem::size_of::<*mut c_char>(),
172        ) as *mut *mut c_char;
173        if na.is_null() { return; }
174        (*list).items = na;
175        (*list).cap = ncap;
176    }
177    let l = crate::strlen(s);
178    let copy = crate::malloc(l + 1) as *mut c_char;
179    if copy.is_null() { return; }
180    core::ptr::copy_nonoverlapping(s as *const u8, copy as *mut u8, l + 1);
181    *(*list).items.add((*list).n) = copy;
182    (*list).n += 1;
183}
184
185unsafe fn glob_list_push_n(list: *mut GlobList, s: *const u8, len: usize) {
186    if (*list).n == (*list).cap {
187        let ncap = if (*list).cap == 0 { 32 } else { (*list).cap * 2 };
188        let na = crate::realloc(
189            (*list).items as *mut c_void,
190            ncap * core::mem::size_of::<*mut c_char>(),
191        ) as *mut *mut c_char;
192        if na.is_null() { return; }
193        (*list).items = na;
194        (*list).cap = ncap;
195    }
196    let copy = crate::malloc(len + 1) as *mut c_char;
197    if copy.is_null() { return; }
198    core::ptr::copy_nonoverlapping(s, copy as *mut u8, len);
199    *copy.add(len) = 0;
200    *(*list).items.add((*list).n) = copy;
201    (*list).n += 1;
202}
203
204unsafe fn list_dir_names(path: *const c_char) -> (*mut *mut c_char, usize) {
205    let fd = crate::open(path, crate::O_DIRECTORY, 0);
206    if fd < 0 { return (core::ptr::null_mut(), 0); }
207    let mut cap = 32usize;
208    let mut count = 0usize;
209    let mut arr = crate::malloc(cap * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
210    if arr.is_null() { crate::close(fd); return (core::ptr::null_mut(), 0); }
211    #[repr(align(8))]
212    struct Buf([u8; 8192]);
213    let mut buf = Buf([0u8; 8192]);
214    let name_off = core::mem::offset_of!(linux_dirent64, d_name);
215    loop {
216        let n = <Arch as Syscalls>::syscall3(
217            SYS_GETDENTS64,
218            fd as i64,
219            buf.0.as_mut_ptr() as i64,
220            buf.0.len() as i64,
221        ) as isize;
222        if n <= 0 { break; }
223        let mut off = 0usize;
224        while off + name_off < n as usize {
225            let ent = buf.0.as_ptr().add(off) as *const linux_dirent64;
226            let reclen = (*ent).d_reclen as usize;
227            if reclen == 0 { break; }
228            let name = buf.0.as_ptr().add(off + name_off) as *const c_char;
229            let nl = crate::strlen(name);
230            if count + 2 >= cap {
231                cap *= 2;
232                let na = crate::realloc(arr as *mut c_void, cap * core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
233                if na.is_null() { break; }
234                arr = na;
235            }
236            let copy = crate::malloc(nl + 1) as *mut c_char;
237            if copy.is_null() { break; }
238            core::ptr::copy_nonoverlapping(name as *const u8, copy as *mut u8, nl + 1);
239            *arr.add(count) = copy;
240            count += 1;
241            off += reclen;
242        }
243    }
244    crate::close(fd);
245    (arr, count)
246}
247
248unsafe fn free_names(arr: *mut *mut c_char, n: usize) {
249    if arr.is_null() { return; }
250    for i in 0..n {
251        if !(*arr.add(i)).is_null() { crate::free(*arr.add(i) as *mut c_void); }
252    }
253    crate::free(arr as *mut c_void);
254}
255
256fn glob_has_magic(comp: &[u8], noescape: bool) -> bool {
257    let mut i = 0;
258    while i < comp.len() {
259        match comp[i] {
260            b'\\' if !noescape => i += 1,
261            b'*' | b'?' | b'[' => return true,
262            _ => {}
263        }
264        i += 1;
265    }
266    false
267}
268
269unsafe fn glob_unescape(dst: &mut [u8], comp: &[u8], noescape: bool) -> usize {
270    let mut o = 0usize;
271    let mut i = 0usize;
272    while i < comp.len() {
273        if comp[i] == b'\\' && !noescape && i + 1 < comp.len() {
274            i += 1;
275        }
276        if o < dst.len() { dst[o] = comp[i]; o += 1; }
277        i += 1;
278    }
279    o
280}
281
282#[derive(Copy, Clone)]
283struct Comp {
284    start: usize,
285    end: usize,
286}
287
288unsafe fn glob_split(pat: &[u8], noescape: bool, comps: &mut [Comp; 128]) -> (usize, bool) {
289    let mut n = 0usize;
290    let mut i = 0usize;
291    let absolute = !pat.is_empty() && pat[0] == b'/';
292    let mut trailing = false;
293    while i < pat.len() {
294        while i < pat.len() && pat[i] == b'/' { i += 1; }
295        if i >= pat.len() { if i > 0 { trailing = pat[i - 1] == b'/'; } break; }
296        let start = i;
297        while i < pat.len() {
298            if pat[i] == b'\\' && !noescape && i + 1 < pat.len() { i += 2; continue; }
299            if pat[i] == b'/' { break; }
300            i += 1;
301        }
302        if n < comps.len() {
303            comps[n] = Comp { start, end: i };
304            n += 1;
305        }
306    }
307    let _ = trailing;
308    (n, absolute)
309}
310
311unsafe fn glob_walk(
312    base: &mut [u8; PATH_MAX_V + 1],
313    blen: &mut usize,
314    pat: &[u8],
315    comps: &[Comp],
316    ci: usize,
317    trailing: bool,
318    flags: c_int,
319    errfunc: Option<unsafe extern "C" fn(*const c_char, c_int) -> c_int>,
320    list: *mut GlobList,
321) -> c_int {
322    if ci >= comps.len() {
323        glob_list_push_n(list, base.as_ptr(), *blen);
324        return 0;
325    }
326    let comp = &pat[comps[ci].start..comps[ci].end];
327    let last = ci + 1 == comps.len();
328    let noescape = flags & GLOB_NOESCAPE_V != 0;
329
330    if !glob_has_magic(comp, noescape) {
331        let mut name = [0u8; PATH_MAX_V + 1];
332        let nlen = glob_unescape(&mut name, comp, noescape);
333        let mut newlen = *blen;
334        if newlen > 0 && base[newlen - 1] != b'/' {
335            if newlen + 1 >= base.len() { return GLOB_NOSPACE_V; }
336            base[newlen] = b'/';
337            newlen += 1;
338        }
339        if newlen + nlen >= base.len() { return GLOB_NOSPACE_V; }
340        core::ptr::copy_nonoverlapping(name.as_ptr(), base.as_mut_ptr().add(newlen), nlen);
341        newlen += nlen;
342        base[newlen] = 0;
343        let mut st: Stat = core::mem::zeroed();
344        let exists = crate::lstat(base.as_ptr() as *const c_char, &mut st as *mut Stat as *mut c_void) == 0;
345        let is_dir = exists && st.st_mode & 0o170000 == 0o040000;
346        if last {
347            if exists && (!trailing || is_dir) {
348                if flags & GLOB_ONLYDIR_V != 0 && !is_dir {
349                    *blen = newlen;
350                    return 0;
351                }
352                let mut end = newlen;
353                if (flags & GLOB_MARK_V != 0) && is_dir {
354                    if end + 1 < base.len() {
355                        base[end] = b'/';
356                        end += 1;
357                    }
358                }
359                glob_list_push_n(list, base.as_ptr(), end);
360            }
361        } else {
362            if !is_dir {
363                if flags & GLOB_ERR_V != 0 {
364                    *blen = newlen;
365                    return GLOB_ABORTED_V;
366                }
367            } else {
368                let old = *blen;
369                *blen = newlen;
370                let r = glob_walk(base, blen, pat, comps, ci + 1, trailing, flags, errfunc, list);
371                *blen = old;
372                if r != 0 { return r; }
373            }
374        }
375        *blen = newlen;
376        return 0;
377    }
378
379    // Wildcard component: enumerate the base directory.
380    let mut dirc = [0 as c_char; PATH_MAX_V + 1];
381    let dp: *const c_char;
382    if *blen == 0 {
383        dirc[0] = b'.' as c_char;
384        dirc[1] = 0;
385        dp = dirc.as_ptr();
386    } else {
387        core::ptr::copy_nonoverlapping(base.as_ptr(), dirc.as_mut_ptr() as *mut u8, *blen);
388        dirc[*blen] = 0;
389        dp = dirc.as_ptr();
390    }
391    let (names, count) = list_dir_names(dp);
392    if names.is_null() {
393        if flags & GLOB_ERR_V != 0 {
394            if let Some(f) = errfunc { let _ = f(dp, ERRNO!()); }
395            return GLOB_ABORTED_V;
396        }
397        return 0;
398    }
399    let mut patc = [0 as c_char; PATH_MAX_V + 1];
400    core::ptr::copy_nonoverlapping(comp.as_ptr(), patc.as_mut_ptr() as *mut u8, comp.len());
401    patc[comp.len()] = 0;
402    let mut fnm_flags = 0;
403    if noescape { fnm_flags |= FNM_NOESCAPE; }
404    if flags & GLOB_PERIOD_V == 0 { fnm_flags |= FNM_PERIOD; }
405    let old = *blen;
406    for i in 0..count {
407        let name = *names.add(i);
408        if flags & GLOB_PERIOD_V == 0 {
409            // FNM_PERIOD already covers this, but skip "." / ".." here.
410            if *name == b'.' as c_char {
411                let second = *name.add(1);
412                if second == 0 || (second == b'.' as c_char && *name.add(2) == 0) { continue; }
413            }
414        }
415        if crate::fnmatch(patc.as_ptr(), name, fnm_flags) != 0 { continue; }
416        let nlen = crate::strlen(name);
417        let mut newlen = old;
418        if newlen > 0 && base[newlen - 1] != b'/' {
419            if newlen + 1 >= base.len() { free_names(names, count); return GLOB_NOSPACE_V; }
420            base[newlen] = b'/';
421            newlen += 1;
422        }
423        if newlen + nlen >= base.len() { free_names(names, count); return GLOB_NOSPACE_V; }
424        core::ptr::copy_nonoverlapping(name as *const u8, base.as_mut_ptr().add(newlen), nlen);
425        newlen += nlen;
426        base[newlen] = 0;
427        let mut st: Stat = core::mem::zeroed();
428        let exists = crate::lstat(base.as_ptr() as *const c_char, &mut st as *mut Stat as *mut c_void) == 0;
429        let is_dir = exists && st.st_mode & 0o170000 == 0o040000;
430        if last {
431            if flags & GLOB_ONLYDIR_V != 0 && !is_dir { continue; }
432            let mut end = newlen;
433            if (flags & GLOB_MARK_V != 0) && is_dir && end + 1 < base.len() {
434                base[end] = b'/';
435                end += 1;
436            }
437            glob_list_push_n(list, base.as_ptr(), end);
438        } else if is_dir {
439            *blen = newlen;
440            let r = glob_walk(base, blen, pat, comps, ci + 1, trailing, flags, errfunc, list);
441            *blen = old;
442            if r != 0 { free_names(names, count); return r; }
443        }
444    }
445    free_names(names, count);
446    *blen = old;
447    0
448}
449
450const GLOB_ONLYDIR_V: c_int = 0x200; // same value as musl/glibc
451
452unsafe fn glob_expand_tilde(pat: *const c_char, buf: *mut u8, cap: usize) -> Option<usize> {
453    let s = pat as *const u8;
454    if *s != b'~' { return None; }
455    let mut i = 1usize;
456    while *s.add(i) != 0 && *s.add(i) != b'/' { i += 1; }
457    let mut name = [0 as c_char; 256];
458    let nlen = i - 1;
459    if nlen >= name.len() { return None; }
460    core::ptr::copy_nonoverlapping(s.add(1), name.as_mut_ptr() as *mut u8, nlen);
461    name[nlen] = 0;
462    let pw = if nlen == 0 {
463        crate::getpwuid(crate::getuid())
464    } else {
465        crate::getpwnam(name.as_ptr())
466    };
467    if pw.is_null() { return None; }
468    let home = (*pw).pw_dir;
469    let hl = crate::strlen(home);
470    let rest = crate::strlen(s.add(i) as *const c_char);
471    if hl + rest + 1 > cap { return None; }
472    core::ptr::copy_nonoverlapping(home as *const u8, buf, hl);
473    core::ptr::copy_nonoverlapping(s.add(i), buf.add(hl), rest + 1);
474    Some(hl + rest)
475}
476
477#[no_mangle]
478pub unsafe extern "C" fn glob(
479    pattern: *const c_char,
480    flags: c_int,
481    errfunc: Option<unsafe extern "C" fn(*const c_char, c_int) -> c_int>,
482    pglob: *mut GlobT,
483) -> c_int {
484    if pattern.is_null() || pglob.is_null() { ERRNO!() = EINVAL; return GLOB_ABORTED_V; }
485
486    let mut expanded = [0u8; PATH_MAX_V + 1];
487    let mut pat_ptr = pattern as *const u8;
488    let mut pat_len = crate::strlen(pattern);
489    if flags & (GLOB_TILDE_V | GLOB_TILDE_CHECK_V) != 0 {
490        if let Some(n) = glob_expand_tilde(pattern, expanded.as_mut_ptr(), PATH_MAX_V) {
491            pat_ptr = expanded.as_ptr();
492            pat_len = n;
493        } else if flags & GLOB_TILDE_CHECK_V != 0 {
494            return GLOB_NOMATCH_V;
495        }
496    }
497    let pat = &core::slice::from_raw_parts(pat_ptr, pat_len)[..];
498
499    let mut comps = [Comp { start: 0, end: 0 }; 128];
500    let (ncomp, absolute) = glob_split(pat, flags & GLOB_NOESCAPE_V != 0, &mut comps);
501
502    let mut list = GlobList { items: core::ptr::null_mut(), n: 0, cap: 0 };
503    let mut base = [0u8; PATH_MAX_V + 1];
504    let mut blen = 0usize;
505    if absolute {
506        base[0] = b'/';
507        blen = 1;
508    }
509    let trailing = !pat.is_empty() && pat[pat.len() - 1] == b'/';
510    let r = if ncomp == 0 {
511        if absolute {
512            glob_list_push_n(&mut list, b"/".as_ptr(), 1);
513            0
514        } else {
515            GLOB_NOMATCH_V
516        }
517    } else {
518        glob_walk(&mut base, &mut blen, pat, &comps[..ncomp], 0, trailing, flags, errfunc, &mut list)
519    };
520    if r == GLOB_ABORTED_V {
521        for i in 0..list.n { crate::free(*list.items.add(i) as *mut c_void); }
522        crate::free(list.items as *mut c_void);
523        return r;
524    }
525    let mut matches = list.n;
526    if matches == 0 && flags & GLOB_NOCHECK_V != 0 {
527        glob_list_push(&mut list, pattern);
528        matches = list.n;
529    }
530    if matches == 0 && flags & GLOB_APPEND_V == 0 {
531        crate::free(list.items as *mut c_void);
532        return GLOB_NOMATCH_V;
533    }
534    if flags & GLOB_NOSORT_V == 0 && matches > 1 {
535        crate::qsort(
536            list.items as *mut c_void,
537            matches,
538            core::mem::size_of::<*mut c_char>(),
539            glob_cmp,
540        );
541    }
542
543    let old_n = if flags & GLOB_APPEND_V != 0 { (*pglob).gl_pathc } else { 0 };
544    let offs = if flags & GLOB_DOOFFS_V != 0 { (*pglob).gl_offs } else { 0 };
545    if old_n != 0 && !(*pglob).gl_pathv.is_null() && flags & GLOB_APPEND_V == 0 {
546        // Nothing to free; append is off.
547    }
548    // offs is caller-controlled with GLOB_DOOFFS, so bound the vector size
549    // before it wraps (musl: regex: avoid overflow sizing glob result vector).
550    let lim = usize::MAX / core::mem::size_of::<*mut c_char>() / 2;
551    let total = offs
552        .checked_add(old_n)
553        .and_then(|n| n.checked_add(matches))
554        .and_then(|n| n.checked_add(1));
555    if offs >= lim || total.is_none_or(|n| n > lim) {
556        for i in 0..list.n { crate::free(*list.items.add(i) as *mut c_void); }
557        crate::free(list.items as *mut c_void);
558        return GLOB_NOSPACE_V;
559    }
560    let total = total.expect("checked above");
561    let pathv = crate::calloc(total, core::mem::size_of::<*mut c_char>()) as *mut *mut c_char;
562    if pathv.is_null() {
563        for i in 0..list.n { crate::free(*list.items.add(i) as *mut c_void); }
564        crate::free(list.items as *mut c_void);
565        return GLOB_NOSPACE_V;
566    }
567    for i in 0..offs { *pathv.add(i) = core::ptr::null_mut(); }
568    if flags & GLOB_APPEND_V != 0 && old_n != 0 && !(*pglob).gl_pathv.is_null() {
569        for i in 0..old_n {
570            *pathv.add(offs + i) = *(*pglob).gl_pathv.add(offs + i);
571        }
572        crate::free((*pglob).gl_pathv as *mut c_void);
573    }
574    for i in 0..list.n {
575        *pathv.add(offs + old_n + i) = *list.items.add(i);
576    }
577    *pathv.add(offs + old_n + matches) = core::ptr::null_mut();
578    crate::free(list.items as *mut c_void);
579
580    (*pglob).gl_pathc = old_n + matches;
581    (*pglob).gl_pathv = pathv;
582    (*pglob).gl_offs = offs;
583    (*pglob).__dummy1 = 0;
584    0
585}
586
587unsafe extern "C" fn glob_cmp(a: *const c_void, b: *const c_void) -> c_int {
588    let sa = *(a as *const *const c_char);
589    let sb = *(b as *const *const c_char);
590    crate::strcmp(sa as *const u8, sb as *const u8)
591}
592
593#[no_mangle]
594pub unsafe extern "C" fn globfree(pglob: *mut GlobT) {
595    if pglob.is_null() || (*pglob).gl_pathv.is_null() { return; }
596    let offs = (*pglob).gl_offs;
597    for i in 0..(*pglob).gl_pathc {
598        let p = *(*pglob).gl_pathv.add(offs + i);
599        if !p.is_null() { crate::free(p as *mut c_void); }
600    }
601    crate::free((*pglob).gl_pathv as *mut c_void);
602    (*pglob).gl_pathv = core::ptr::null_mut();
603    (*pglob).gl_pathc = 0;
604}
605
606// ============================================================
607// nftw / ftw
608// ============================================================
609
610#[repr(C)]
611pub struct Ftw {
612    pub base: c_int,
613    pub level: c_int,
614}
615
616const FTW_F_V: c_int = 1;
617const FTW_D_V: c_int = 2;
618const FTW_DNR_V: c_int = 3;
619const FTW_NS_V: c_int = 4;
620const FTW_SL_V: c_int = 5;
621const FTW_DP_V: c_int = 6;
622const FTW_SLN_V: c_int = 7;
623
624const FTW_PHYS_V: c_int = 1;
625const FTW_MOUNT_V: c_int = 2;
626const FTW_DEPTH_V: c_int = 8;
627
628struct History {
629    chain: *mut History,
630    dev: u64,
631    ino: u64,
632    base: c_int,
633}
634
635#[derive(Copy, Clone)]
636enum WalkCb {
637    N(Option<unsafe extern "C" fn(*const c_char, *const Stat, c_int, *mut Ftw) -> c_int>),
638    F(Option<unsafe extern "C" fn(*const c_char, *const Stat, c_int) -> c_int>),
639}
640
641unsafe fn walk_call(cb: WalkCb, path: *const c_char, st: *const Stat, type_: c_int, ftw: *mut Ftw) -> c_int {
642    match cb {
643        WalkCb::N(Some(f)) => f(path, st, type_, ftw),
644        WalkCb::F(Some(f)) => f(path, st, type_),
645        _ => 0,
646    }
647}
648
649unsafe fn nftw_do(
650    buf: *mut u8,
651    cap: usize,
652    len: usize,
653    cb: WalkCb,
654    fd_limit: c_int,
655    flags: c_int,
656    h: *mut History,
657    level: c_int,
658) -> c_int {
659    let path = buf as *const c_char;
660    let mut st: Stat = core::mem::zeroed();
661    let phys = flags & FTW_PHYS_V != 0;
662    let mut type_: c_int;
663    let mut stat_ok = true;
664    let rc = if phys { crate::lstat(path, &mut st as *mut Stat as *mut c_void) } else { crate::stat(path, &mut st) };
665    if rc != 0 {
666        if !phys && ERRNO!() == 2 && crate::lstat(path, &mut st as *mut Stat as *mut c_void) == 0 {
667            type_ = FTW_SLN_V;
668        } else if ERRNO!() != 13 {
669            return -1;
670        } else {
671            type_ = FTW_NS_V;
672            st = core::mem::zeroed();
673            stat_ok = false;
674        }
675    } else {
676        let mode = st.st_mode;
677        if mode & 0o170000 == 0o040000 {
678            type_ = if flags & FTW_DEPTH_V != 0 { FTW_DP_V } else { FTW_D_V };
679        } else if mode & 0o170000 == 0o120000 {
680            type_ = if phys { FTW_SL_V } else { FTW_SLN_V };
681        } else {
682            type_ = FTW_F_V;
683        }
684    }
685    if flags & FTW_MOUNT_V != 0 && !h.is_null() && stat_ok && type_ != FTW_NS_V && st.st_dev != (*h).dev {
686        return 0;
687    }
688    let parent_base = if h.is_null() {
689        let mut k = len;
690        while k > 0 && *buf.add(k - 1) == b'/' { k -= 1; }
691        while k > 0 && *buf.add(k - 1) != b'/' { k -= 1; }
692        k as c_int
693    } else {
694        (*h).base
695    };
696    let mut new = History {
697        chain: h,
698        dev: st.st_dev,
699        ino: st.st_ino,
700        base: parent_base,
701    };
702    let mut ftw = Ftw { base: parent_base, level: level };
703
704    let mut dfd: c_int = -1;
705    let mut open_err: c_int = 0;
706    if type_ == FTW_D_V || type_ == FTW_DP_V {
707        dfd = crate::open(path, 0, 0);
708        open_err = ERRNO!();
709        if dfd < 0 && open_err == 13 { type_ = FTW_DNR_V; }
710        if fd_limit == 0 && dfd >= 0 { crate::close(dfd); dfd = -1; }
711    }
712
713    if flags & FTW_DEPTH_V == 0 {
714        let r = walk_call(cb, path, &st, type_, &mut ftw);
715        if r != 0 { return r; }
716    }
717
718    let mut p = h;
719    while !p.is_null() {
720        if (*p).dev == st.st_dev && (*p).ino == st.st_ino { return 0; }
721        p = (*p).chain;
722    }
723
724    if (type_ == FTW_D_V || type_ == FTW_DP_V) && fd_limit > 0 {
725        if dfd < 0 {
726            ERRNO!() = open_err;
727            return -1;
728        }
729        // Enumerate with getdents64 so nested walks are independent.
730        #[repr(align(8))]
731        struct Buf([u8; 8192]);
732        let mut dbuf = Buf([0u8; 8192]);
733        let name_off = core::mem::offset_of!(linux_dirent64, d_name);
734        loop {
735            let n = <Arch as Syscalls>::syscall3(
736                SYS_GETDENTS64,
737                dfd as i64,
738                dbuf.0.as_mut_ptr() as i64,
739                dbuf.0.len() as i64,
740            ) as isize;
741            if n <= 0 { break; }
742            let mut off = 0usize;
743            while off + name_off < n as usize {
744                let ent = dbuf.0.as_ptr().add(off) as *const linux_dirent64;
745                let reclen = (*ent).d_reclen as usize;
746                if reclen == 0 { break; }
747                let name = dbuf.0.as_ptr().add(off + name_off) as *const c_char;
748                off += reclen;
749                if *name == b'.' as c_char {
750                    let s = *name.add(1);
751                    if s == 0 || (s == b'.' as c_char && *name.add(2) == 0) { continue; }
752                }
753                let nl = crate::strlen(name);
754                if len + 1 + nl >= cap {
755                    ERRNO!() = 36;
756                    crate::close(dfd);
757                    return -1;
758                }
759                *buf.add(len) = b'/';
760                core::ptr::copy_nonoverlapping(name as *const u8, buf.add(len + 1), nl + 1);
761                let r = nftw_do(buf, cap, len + 1 + nl, cb, fd_limit - 1, flags, &mut new, level + 1);
762                if r != 0 { crate::close(dfd); return r; }
763            }
764        }
765        crate::close(dfd);
766    } else if dfd >= 0 {
767        crate::close(dfd);
768    }
769    *buf.add(len) = 0;
770
771    if flags & FTW_DEPTH_V != 0 {
772        let mut f2 = Ftw { base: parent_base, level: level };
773        let r = walk_call(cb, path, &st, type_, &mut f2);
774        if r != 0 { return r; }
775    }
776    0
777}
778
779#[no_mangle]
780pub unsafe extern "C" fn nftw(
781    path: *const c_char,
782    f: Option<unsafe extern "C" fn(*const c_char, *const Stat, c_int, *mut Ftw) -> c_int>,
783    fd_limit: c_int,
784    flags: c_int,
785) -> c_int {
786    if path.is_null() || f.is_none() { ERRNO!() = EINVAL; return -1; }
787    if fd_limit <= 0 { return 0; }
788    let l = crate::strlen(path);
789    if l >= PATH_MAX_V { ERRNO!() = 36; return -1; }
790    let mut buf = [0u8; PATH_MAX_V + 1];
791    core::ptr::copy_nonoverlapping(path as *const u8, buf.as_mut_ptr(), l + 1);
792    nftw_do(buf.as_mut_ptr(), buf.len(), l, WalkCb::N(f), fd_limit, flags, core::ptr::null_mut(), 0)
793}
794
795#[no_mangle]
796pub unsafe extern "C" fn ftw(
797    path: *const c_char,
798    f: Option<unsafe extern "C" fn(*const c_char, *const Stat, c_int) -> c_int>,
799    fd_limit: c_int,
800) -> c_int {
801    if path.is_null() || f.is_none() { ERRNO!() = EINVAL; return -1; }
802    if fd_limit <= 0 { return 0; }
803    let l = crate::strlen(path);
804    if l >= PATH_MAX_V { ERRNO!() = 36; return -1; }
805    let mut buf = [0u8; PATH_MAX_V + 1];
806    core::ptr::copy_nonoverlapping(path as *const u8, buf.as_mut_ptr(), l + 1);
807    nftw_do(buf.as_mut_ptr(), buf.len(), l, WalkCb::F(f), fd_limit, FTW_PHYS_V, core::ptr::null_mut(), 0)
808}