zshrs 0.11.5

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Port of `Src/hashnameddir.c` — named-directory hash table.
//!
//! C: `mod_export HashTable nameddirtab;` plus a file-static
//! `int allusersadded;` and seven hash-table callbacks
//! (`createnameddirtable` / `emptynameddirtable` / `fillnameddirtable` /
//! `addnameddirnode` / `removenameddirnode` / `freenameddirnode` /
//! `printnameddirnode`).
//!
//! The Rust port keeps the `nameddir` struct definition canonical
//! (it lives in `zsh_h.rs`) and stores entries in a global
//! `OnceLock<Mutex<HashMap<String, nameddir>>>`, since the full
//! `HashTable` substrate (vtable callbacks, intrusive `next` chain)
//! is not yet wired. Names match C 1:1.

use std::collections::HashMap;
use std::io::Write;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Mutex, OnceLock};

use crate::ported::zsh_h::{nameddir, ND_USERNAME, PRINT_LIST, PRINT_NAMEONLY};

// != 0 if all the usernames have already been *
// added to the named directory hash table.    *                           // c:59-51
#[allow(non_upper_case_globals)]
pub static allusersadded: AtomicI32 = AtomicI32::new(0);                   // c:59

/* Create new hash table for named directories */                          // c:59

/// Port of `createnameddirtable()` from `Src/hashnameddir.c:59`.
/// C builds a `HashTable`, wires 12 callbacks, then resets
/// `allusersadded` and clears the `finddir()` cache.
pub fn createnameddirtable() {                                             // c:59
    // c:59 — `nameddirtab = newhashtable(201, "nameddirtab", NULL);`
    // OnceLock-backed HashMap is initialised lazily; touch it here so
    // first-access timing matches the eager C allocation.
    let _ = nameddirtab();
    // c:63-74 — assign 12 callback slots. Static-link path: callbacks
    // are the free fns in this module; no vtable to populate.
    allusersadded.store(0, Ordering::Relaxed);                             // c:84
    // c:84 — `finddir(NULL);` clear the finddir cache. The Rust
    // `finddir` port has no cache, so the call is a no-op here.
}

/* Empty the named directories table */                                    // c:84

/// Port of `emptynameddirtable(HashTable ht)` from `Src/hashnameddir.c:84`.
/// WARNING: param names don't match C — Rust=() vs C=(ht)
pub fn emptynameddirtable() {                                              // c:84
    if let Ok(mut t) = nameddirtab().lock() {                              // c:84
        t.clear();                                                         // c:86 emptyhashtable
    }
    allusersadded.store(0, Ordering::Relaxed);                             // c:96
    // c:96 — `finddir(NULL);` clear the finddir cache (no-op).
}

/* Add all the usernames in the password file/database *
 * to the named directories table.                     */                  // c:96-92

/// Port of `fillnameddirtable(UNUSED(HashTable ht))` from `Src/hashnameddir.c:96`.
/// C signature is `static void fillnameddirtable(UNUSED(HashTable ht))`;
/// Rust drops the unused parameter since `nameddirtab` is the only
/// table this is wired to.
/// WARNING: param names don't match C — Rust=() vs C=(ht)
pub fn fillnameddirtable() {                                               // c:96
    if allusersadded.load(Ordering::Relaxed) != 0 {                        // c:96
        return;
    }
    // c:99-110 — `#ifdef USE_GETPWENT` block.
    #[cfg(unix)]
    unsafe {
        libc::setpwent();                                                  // c:102
        // c:106 — `while ((pw = getpwent()) && !errflag)`
        loop {
            let pw = libc::getpwent();
            if pw.is_null() {
                break;
            }
            if crate::ported::utils::errflag.load(Ordering::Relaxed) != 0 {
                break;
            }
            let name = std::ffi::CStr::from_ptr((*pw).pw_name)
                .to_string_lossy()
                .into_owned();
            let dir = std::ffi::CStr::from_ptr((*pw).pw_dir)
                .to_string_lossy()
                .into_owned();
            // c:107 — `adduserdir(pw->pw_name, pw->pw_dir, ND_USERNAME, 1);`
            crate::ported::utils::adduserdir(&name, &dir, ND_USERNAME, true);
        }
        libc::endpwent();                                                  // c:109
    }
    allusersadded.store(1, Ordering::Relaxed);                             // c:111
}

/* Add an entry to the named directory hash *
 * table, clearing the finddir() cache and  *
 * initialising the `diff' member.          */                             // c:121-117

/// Port of `addnameddirnode(HashTable ht, char *nam, void *nodeptr)` from `Src/hashnameddir.c:121`.
/// C: `static void addnameddirnode(HashTable ht, char *nam, void *nodeptr)`.
/// Caller constructs the `nameddir` (with `dir` + `flags` already
/// set); this fn computes `diff`, clears the finddir cache, then
/// installs the entry. Rust drops the unused `HashTable ht` since
/// `nameddirtab` is the only target.
/// WARNING: param names don't match C — Rust=(nam, nd) vs C=(ht, nam, nodeptr)
pub fn addnameddirnode(nam: &str, mut nd: nameddir) {                      // c:121
    // c:121 — `nd->diff = strlen(nd->dir) - strlen(nam);`
    nd.diff = nd.dir.len() as i32 - nam.len() as i32;
    // c:126 — `finddir(NULL);` clear cache (no-op in Rust port).
    // c:127 — `addhashnode(ht, nam, nodeptr);`
    if let Ok(mut t) = nameddirtab().lock() {
        nd.node.nam = nam.to_string();
        t.insert(nam.to_string(), nd);
    }
}

/* Remove an entry from the named directory  *
 * hash table, clearing the finddir() cache. */                            // c:135-131

/// Port of `removenameddirnode(HashTable ht, const char *nam)` from `Src/hashnameddir.c:135`.
/// C: `static HashNode removenameddirnode(HashTable ht, const char *nam)`.
/// WARNING: param names don't match C — Rust=(nam) vs C=(ht, nam)
pub fn removenameddirnode(nam: &str) -> Option<nameddir> {                 // c:135
    // c:135 — `HashNode hn = removehashnode(ht, nam);`
    let removed = nameddirtab().lock().ok().and_then(|mut t| t.remove(nam));
    if removed.is_some() {                                                 // c:148
        // c:148 — `finddir(NULL);` clear cache (no-op in Rust port).
    }
    removed                                                                // c:148
}

/* Free up the memory used by a named directory hash node. */              // c:148

/// Port of `freenameddirnode(HashNode hn)` from `Src/hashnameddir.c:148`.
/// C frees the two embedded `char*`s plus the struct; in Rust the
/// `Drop` impl for `nameddir` (which owns its `String`s) covers
/// the same teardown.
pub fn freenameddirnode(hn: nameddir) {                                   // c:148
    // c:161-154 — `zsfree(nd->node.nam); zsfree(nd->dir); zfree(nd, …);`
    // Rust drop covers all three.
}

/* Print a named directory */                                              // c:161

/// Port of `printnameddirnode(HashNode hn, int printflags)` from `Src/hashnameddir.c:161`.
pub fn printnameddirnode(hn: &nameddir, printflags: i32) {                 // c:161
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    if (printflags & PRINT_NAMEONLY) != 0 {                                // c:165
        let _ = writeln!(out, "{}", hn.node.nam);                          // c:166-168
        return;
    }
    if (printflags & PRINT_LIST) != 0 {                                    // c:171
        let _ = write!(out, "hash -d ");                                   // c:172
        if hn.node.nam.starts_with('-') {                                  // c:174
            let _ = write!(out, "-- ");                                    // c:175
        }
    }
    let _ = write!(
        out,
        "{}={}",
        crate::ported::utils::quotedzputs(&hn.node.nam),                   // c:178
        crate::ported::utils::quotedzputs(&hn.dir),                        // c:180
    );
    let _ = writeln!(out);                                                 // c:181
}

/****************************************/
/* Named Directory Hash Table Functions */
/****************************************/

// hash table containing named directories                                 // c:45
//
// C: `mod_export HashTable nameddirtab;` (c:48). Rust port stores the
// table as a `Mutex<HashMap<String, nameddir>>` keyed on `node.nam`.
static NAMEDDIRTAB_INNER: OnceLock<Mutex<HashMap<String, nameddir>>> = OnceLock::new();

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── RUST-ONLY ACCESSORS ───
//
// Singleton accessor fns for `OnceLock<Mutex<T>>` / `OnceLock<
// RwLock<T>>` globals declared above. C zsh uses direct global
// access; Rust needs these wrappers because `OnceLock::get_or_init`
// is the only way to lazily construct shared state. These fns sit
// here so the body of this file reads in C source order without
// the accessor wrappers interleaved between real port fns.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

/// Accessor for the global `nameddirtab`. Mirrors the C global
/// dereference (`nameddirtab->...`) by returning the underlying
/// mutex; callers `.lock()` and operate on the map directly.
#[allow(non_snake_case)]
pub fn nameddirtab() -> &'static Mutex<HashMap<String, nameddir>> {        // c:48
    NAMEDDIRTAB_INNER.get_or_init(|| Mutex::new(HashMap::new()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ported::zsh_h::{hashnode, nameddir};

    /// Process-wide lock serialising tests that mutate the global
    /// `nameddirtab`. Without this, parallel `cargo test` invocations
    /// race on the shared HashMap — `fresh_table()` from one test
    /// can clear an entry another just inserted, producing flaky
    /// "entry inserted" assertion failures. No C counterpart.
    static NAMEDDIR_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn fresh_table() {
        if let Ok(mut t) = nameddirtab().lock() {
            t.clear();
        }
        allusersadded.store(0, Ordering::Relaxed);
    }

    fn make_nd(name: &str, dir: &str, flags: i32) -> nameddir {
        nameddir {
            node: hashnode {
                next: None,
                nam: name.to_string(),
                flags,
            },
            dir: dir.to_string(),
            diff: 0,
        }
    }

    #[test]
    fn addnameddirnode_sets_diff_and_inserts() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // c:125 — `nd->diff = strlen(nd->dir) - strlen(nam);`
        fresh_table();
        addnameddirnode("p", make_nd("p", "/home/user/projects", 0));
        let t = nameddirtab().lock().unwrap();
        let nd = t.get("p").expect("entry inserted");
        assert_eq!(nd.dir, "/home/user/projects");
        // strlen("/home/user/projects") - strlen("p") == 19 - 1 == 18.
        assert_eq!(nd.diff, 18);
        assert_eq!(nd.node.nam, "p");
    }

    #[test]
    fn removenameddirnode_returns_node_and_clears_entry() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // c:137-141 — removehashnode + finddir(NULL).
        fresh_table();
        addnameddirnode("k", make_nd("k", "/tmp/k", 0));
        assert!(nameddirtab().lock().unwrap().contains_key("k"));
        let dropped = removenameddirnode("k");
        assert!(dropped.is_some());
        assert_eq!(dropped.unwrap().dir, "/tmp/k");
        assert!(!nameddirtab().lock().unwrap().contains_key("k"));
    }

    #[test]
    fn removenameddirnode_missing_returns_none() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // c:139 — `if(hn) finddir(NULL);` only fires when a node
        // was actually present; the function still returns NULL
        // when it wasn't.
        fresh_table();
        assert!(removenameddirnode("absent").is_none());
    }

    #[test]
    fn emptynameddirtable_clears_and_resets_allusersadded() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // c:86-87 — emptyhashtable + allusersadded = 0.
        fresh_table();
        addnameddirnode("a", make_nd("a", "/a", 0));
        addnameddirnode("b", make_nd("b", "/b", 0));
        allusersadded.store(1, Ordering::Relaxed);
        emptynameddirtable();
        assert!(nameddirtab().lock().unwrap().is_empty());
        assert_eq!(allusersadded.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn createnameddirtable_resets_allusersadded() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // c:76 — `allusersadded = 0;`
        allusersadded.store(1, Ordering::Relaxed);
        createnameddirtable();
        assert_eq!(allusersadded.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn nd_username_value_matches_zsh_h() {
        // Src/zsh.h:2157 — `#define ND_USERNAME (1<<1)`.
        assert_eq!(ND_USERNAME, 1 << 1);
    }

    /// `Src/hashnameddir.c:98` — `if (!allusersadded) { … allusersadded = 1; }`.
    /// Once the passwd database has been walked, subsequent calls must
    /// early-exit. Regression dropping this guard would re-walk
    /// `getpwent()` on every `~<TAB>` completion attempt — silently
    /// quadratic on systems with thousands of LDAP users. We can't
    /// observe the no-op via the table (other parallel tests may
    /// mutate it) — instead we pin the visible side-effect:
    /// `allusersadded` stays exactly 1, since the c:111 `= 1` only
    /// runs inside the c:98 conditional.
    #[test]
    fn fillnameddirtable_short_circuits_when_allusersadded_set() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        allusersadded.store(1, Ordering::Relaxed);
        fillnameddirtable();
        assert_eq!(allusersadded.load(Ordering::Relaxed), 1,
            "c:98 conditional must early-exit; flag remains 1 unchanged");
    }

    /// `Src/hashnameddir.c:125` — `nd->diff = strlen(nd->dir) - strlen(nam);`.
    /// `Src/zsh.h:2152` — `int diff;` (signed int field). Regression
    /// using unsigned subtraction (or assuming `dir.len() >= name.len()`)
    /// would underflow on a `hash -d short=/x` style entry.
    #[test]
    fn addnameddirnode_diff_can_be_negative() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // name "longname" (8) longer than dir "/x" (2) → diff = -6.
        fresh_table();
        addnameddirnode("longname", make_nd("longname", "/x", 0));
        let t = nameddirtab().lock().unwrap();
        let nd = t.get("longname").expect("entry inserted");
        assert_eq!(nd.diff, -6, "c:125 — signed subtraction may underflow zero");
    }

    /// `Src/hashnameddir.c:121-128` — `addnameddirnode` calls
    /// `addhashnode(ht, nam, nodeptr)` at c:127. `addhashnode` in C
    /// replaces an existing node with the same key (Src/hashtable.c
    /// `addhashnode2` removes the prior entry before insert).
    /// Regression that accumulates duplicate keys would mis-print
    /// `~name`-prefixed paths after `hash -d` reuse and leak the
    /// stale `diff` field.
    #[test]
    fn addnameddirnode_overwrites_existing_entry() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        addnameddirnode("p", make_nd("p", "/old", 0));
        addnameddirnode("p", make_nd("p", "/new/longer/path", 0));
        let t = nameddirtab().lock().unwrap();
        let nd = t.get("p").expect("entry present");
        assert_eq!(nd.dir, "/new/longer/path", "c:127 — addhashnode replaces");
        // c:125 — diff recomputed for the new dir+name pair.
        assert_eq!(nd.diff, "/new/longer/path".len() as i32 - 1);
        assert_eq!(t.len(), 1, "must not accumulate duplicate keys");
    }

    /// c:125 — `nd->diff = strlen(nd->dir) - strlen(nam)`. When
    /// dir and name have equal length, diff is exactly 0. Pin the
    /// zero-edge so a regen that adds a +1/-1 fudge factor breaks
    /// `~name` prefix matching for this case.
    #[test]
    fn addnameddirnode_diff_zero_when_lengths_equal() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        addnameddirnode("abcde", make_nd("abcde", "/etc/", 0));
        let t = nameddirtab().lock().unwrap();
        let nd = t.get("abcde").expect("entry inserted");
        assert_eq!(nd.diff, 0,
            "len(\"/etc/\") == len(\"abcde\") == 5 → diff = 0");
    }

    /// c:84 — `emptynameddirtable` empties the table and resets
    /// `allusersadded`. Pin the full reset because callers depend
    /// on the flag returning to 0 so `fillnameddirtable` will
    /// re-scan on next access.
    #[test]
    fn emptynameddirtable_resets_table_and_flag() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        addnameddirnode("a", make_nd("a", "/x", 0));
        addnameddirnode("b", make_nd("b", "/y", 0));
        allusersadded.store(1, Ordering::Relaxed);
        emptynameddirtable();
        assert!(nameddirtab().lock().unwrap().is_empty(),
            "emptynameddirtable must clear the table");
        assert_eq!(allusersadded.load(Ordering::Relaxed), 0,
            "emptynameddirtable must reset allusersadded to 0");
    }

    /// c:135 — `removenameddirnode` returns the removed entry's data
    /// (Some), or None for an absent name. Pin both branches.
    #[test]
    fn removenameddirnode_returns_some_for_present_and_none_for_absent() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        addnameddirnode("here", make_nd("here", "/tmp/here", 0));
        let removed = removenameddirnode("here");
        assert!(removed.is_some(), "present entry must return Some");
        assert_eq!(removed.unwrap().dir, "/tmp/here");
        // Now it's gone
        assert!(removenameddirnode("here").is_none(),
            "second remove must return None");
        // Unknown name is also None
        assert!(removenameddirnode("never_was").is_none());
    }

    /// c:135 — `removenameddirnode` of a present entry removes it
    /// from the table (followup state check).
    #[test]
    fn removenameddirnode_actually_removes_from_table() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        addnameddirnode("a", make_nd("a", "/a", 0));
        addnameddirnode("b", make_nd("b", "/b", 0));
        assert_eq!(nameddirtab().lock().unwrap().len(), 2);
        removenameddirnode("a");
        let t = nameddirtab().lock().unwrap();
        assert_eq!(t.len(), 1);
        assert!(!t.contains_key("a"));
        assert!(t.contains_key("b"), "removing 'a' must NOT touch 'b'");
    }

    /// c:59 — `createnameddirtable` is idempotent: calling it twice
    /// must not double-init or wipe existing entries. Pin re-entry
    /// safety since `init_misc` and `fillnameddirtable` both call it.
    #[test]
    fn createnameddirtable_is_idempotent() {
        let _g = NAMEDDIR_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        fresh_table();
        createnameddirtable();
        addnameddirnode("preserved", make_nd("preserved", "/x", 0));
        createnameddirtable();  // second call
        let t = nameddirtab().lock().unwrap();
        assert!(t.contains_key("preserved"),
            "second createnameddirtable must NOT wipe existing entries");
    }

    /// c:148 — `freenameddirnode` accepts any nameddir and consumes
    /// it (drops the String fields). Smoke test for the destructor.
    #[test]
    fn freenameddirnode_consumes_node() {
        let nd = make_nd("doomed", "/tmp", 0);
        freenameddirnode(nd);
        // No panic = pass. Caller's `nd` is moved.
    }
}