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