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
//! Unix domain socket module — port of `Src/Modules/socket.c`.
//!
//! C source has zero `struct ...` / `enum ...` definitions. The
//! Rust port matches: zero types, only the function ports
//! (`bin_zsocket`, `setup_`/`features_`/`enables_`/`boot_`/
//! `cleanup_`/`finish_`).

/// Direct port of `bin_zsocket(char *nam, char **args, Options ops, UNUSED(int func))` from `Src/Modules/socket.c:57`.
/// C signature matches exactly: `static int bin_zsocket(char *nam,
/// char **args, Options ops, UNUSED(int func))`.
/// WARNING: param names don't match C — Rust=(nam, args, _func) vs C=(nam, args, ops, func)
use crate::ported::zsh_h::{OPT_ISSET, OPT_ARG, FDT_UNUSED, FDT_EXTERNAL};
pub fn bin_zsocket(nam: &str, args: &[String],                           // c:57
                   ops: &crate::ported::zsh_h::options, _func: i32) -> i32 {
    let mut soun: libc::sockaddr_un = unsafe { std::mem::zeroed() };
    let mut sfd: i32;
    let mut err: i32 = 1;                                                // c:60
    let mut verbose = 0i32;
    let mut test = 0i32;
    let mut targetfd: i32 = 0;
    let mut soun: libc::sockaddr_un = unsafe { std::mem::zeroed() };
    let mut sfd: i32;

    if OPT_ISSET(ops, b'v') { verbose = 1; }                            // c:64-65
    if OPT_ISSET(ops, b't') { test    = 1; }                            // c:67-68

    if OPT_ISSET(ops, b'd') {                                           // c:70
        let darg = OPT_ARG(ops, b'd').unwrap_or("");
        targetfd = darg.parse::<i32>().unwrap_or(0);                     // c:71 atoi
        if targetfd == 0 {                                               // c:72
            crate::ported::utils::zwarnnam(nam,
                &format!("{} is an invalid argument to -d", darg));      // c:73
            return 1;                                                    // c:75
        }
        // c:78-82 — `if (targetfd <= max_zsh_fd && fdtable[targetfd] != FDT_UNUSED)`.
        // Static-link path: query the per-process fdtable accessor.
        if crate::ported::utils::fdtable_get(targetfd) != FDT_UNUSED {   // c:78
            crate::ported::utils::zwarnnam(nam,                          // c:79
                &format!("file descriptor {} is in use by the shell", targetfd));
            return 1;                                                    // c:81
        }
    }

    if OPT_ISSET(ops, b'l') {                                           // c:85
        if args.is_empty() {                                             // c:88
            crate::ported::utils::zwarnnam(nam, "-l requires an argument");
            return 1;                                                    // c:90
        }
        let localfn = args[0].as_str();                                  // c:93
        sfd = unsafe { libc::socket(libc::PF_UNIX, libc::SOCK_STREAM, 0) }; // c:95
        if sfd == -1 {                                                   // c:97
            crate::ported::utils::zwarnnam(nam,
                &format!("socket error: {} ", std::io::Error::last_os_error())); // c:98
            return 1;                                                    // c:99
        }
        soun.sun_family = libc::AF_UNIX as _;                            // c:102
        let path_bytes = localfn.as_bytes();
        let max_len = soun.sun_path.len() - 1;
        let copy_len = path_bytes.len().min(max_len);
        for (k, &b) in path_bytes[..copy_len].iter().enumerate() {       // c:103 strncpy
            soun.sun_path[k] = b as libc::c_char;
        }
        let r = unsafe {                                                 // c:105
            libc::bind(sfd, &soun as *const _ as *const libc::sockaddr,
                std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t)
        };
        if r != 0 {                                                      // c:106
            crate::ported::utils::zwarnnam(nam,
                &format!("could not bind to {}: {}", localfn,
                    std::io::Error::last_os_error()));                   // c:107
            unsafe { libc::close(sfd); }                                 // c:108
            return 1;                                                    // c:109
        }
        if unsafe { libc::listen(sfd, 1) } != 0 {                        // c:112
            crate::ported::utils::zwarnnam(nam,
                &format!("could not listen on socket: {}",
                    std::io::Error::last_os_error()));                   // c:114
            unsafe { libc::close(sfd); }                                 // c:115
            return 1;                                                    // c:116
        }
        crate::ported::utils::addmodulefd(sfd, crate::ported::zsh_h::FDT_EXTERNAL); // c:119 FDT_EXTERNAL
        if targetfd != 0 {                                               // c:121
            sfd = crate::ported::utils::redup(sfd, targetfd);            // c:122
        } else {
            sfd = crate::ported::utils::movefd(sfd);                     // c:126 movefd
        }
        if sfd == -1 {                                                   // c:128
            crate::ported::utils::zerrnam(nam,
                &format!("cannot duplicate fd {}: {}", sfd,
                    std::io::Error::last_os_error()));                   // c:129
            return 1;                                                    // c:130
        }
        crate::ported::utils::fdtable_set(sfd, FDT_EXTERNAL);            // c:134
        crate::ported::params::setiparam("REPLY", sfd as i64);   // c:136 setiparam_no_convert
        if verbose != 0 {                                                // c:138
            println!("{} listener is on fd {}", localfn, sfd);           // c:139
        }
        return 0;                                                        // c:141
    } else if OPT_ISSET(ops, b'a') {                                    // c:143
        if args.is_empty() {                                             // c:147
            crate::ported::utils::zwarnnam(nam, "-a requires an argument");
            return 1;                                                    // c:149
        }
        let lfd = args[0].parse::<i32>().unwrap_or(0);                   // c:152 atoi
        if lfd == 0 {                                                    // c:154
            crate::ported::utils::zwarnnam(nam, "invalid numerical argument");
            return 1;                                                    // c:156
        }
        if test != 0 {                                                   // c:159
            // c:163 HAVE_POLL branch.
            let mut pfd = libc::pollfd { fd: lfd, events: libc::POLLIN, revents: 0 };
            let r = unsafe { libc::poll(&mut pfd, 1, 0) };               // c:166
            if r == 0 { return 1; }                                      // c:166
            else if r == -1 {                                            // c:167
                crate::ported::utils::zwarnnam(nam,
                    &format!("poll error: {}",
                        std::io::Error::last_os_error()));               // c:169
                return 1;                                                // c:170
            }
        }
        let mut len: libc::socklen_t =
            std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t; // c:194
        let rfd: i32;
        loop {                                                           // c:195
            let r = unsafe { libc::accept(lfd,                           // c:196
                &mut soun as *mut _ as *mut libc::sockaddr, &mut len) };
            if r >= 0 { rfd = r; break; }
            let osek = std::io::Error::last_os_error().raw_os_error();
            if osek != Some(libc::EINTR)
                || crate::ported::utils::errflag
                    .load(std::sync::atomic::Ordering::Relaxed) != 0 { rfd = r; break; }
        }
        if rfd == -1 {                                                   // c:199
            crate::ported::utils::zwarnnam(nam,
                &format!("could not accept connection: {}",
                    std::io::Error::last_os_error()));                   // c:200
            return 1;                                                    // c:201
        }
        crate::ported::utils::addmodulefd(rfd, crate::ported::zsh_h::FDT_EXTERNAL); // c:204 FDT_EXTERNAL
        if targetfd != 0 {                                               // c:206
            sfd = crate::ported::utils::redup(rfd, targetfd);            // c:207
            if sfd < 0 {                                                 // c:208
                crate::ported::utils::zerrnam(nam,
                    &format!("could not duplicate socket fd to {}: {}",
                        targetfd, std::io::Error::last_os_error()));     // c:209
                unsafe { libc::close(rfd); }                             // c:210
                return 1;                                                // c:211
            }
            crate::ported::utils::fdtable_set(sfd, FDT_EXTERNAL);        // c:213
        } else {
            sfd = rfd;                                                   // c:217
        }
        crate::ported::params::setiparam("REPLY", sfd as i64);   // c:220 setiparam_no_convert
        if verbose != 0 {                                                // c:222
            let path = soun.sun_path.iter()
                .take_while(|&&c| c != 0)
                .map(|&c| c as u8 as char).collect::<String>();
            println!("new connection from {} is on fd {}", path, sfd);   // c:223
        }
    } else {                                                             // c:225
        if args.is_empty() {                                             // c:227
            crate::ported::utils::zwarnnam(nam, "zsocket requires an argument");
            return 1;                                                    // c:229
        }
        sfd = unsafe { libc::socket(libc::PF_UNIX, libc::SOCK_STREAM, 0) }; // c:233
        if sfd == -1 {                                                   // c:235
            crate::ported::utils::zwarnnam(nam,
                &format!("socket creation failed: {}",
                    std::io::Error::last_os_error()));                   // c:236
            return 1;                                                    // c:237
        }
        soun.sun_family = libc::AF_UNIX as _;                            // c:240
        let path_bytes = args[0].as_bytes();
        let max_len = soun.sun_path.len() - 1;
        let copy_len = path_bytes.len().min(max_len);
        for (k, &b) in path_bytes[..copy_len].iter().enumerate() {       // c:241 strncpy
            soun.sun_path[k] = b as libc::c_char;
        }
        err = unsafe {                                                   // c:243
            libc::connect(sfd,
                &soun as *const _ as *const libc::sockaddr,
                std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t)
        };
        if err != 0 {                                                    // c:243
            crate::ported::utils::zwarnnam(nam,
                &format!("connection failed: {}",
                    std::io::Error::last_os_error()));                   // c:244
            unsafe { libc::close(sfd); }                                 // c:245
            return 1;                                                    // c:246
        }
        crate::ported::utils::addmodulefd(sfd, crate::ported::zsh_h::FDT_EXTERNAL); // c:251 FDT_EXTERNAL
        if targetfd != 0 {                                               // c:253
            if crate::ported::utils::redup(sfd, targetfd) < 0 {          // c:254
                crate::ported::utils::zerrnam(nam,
                    &format!("could not duplicate socket fd to {}: {}",
                        targetfd, std::io::Error::last_os_error()));     // c:255
                unsafe { libc::close(sfd); }                             // c:256
                return 1;                                                // c:257
            }
            sfd = targetfd;                                              // c:259
            crate::ported::utils::fdtable_set(sfd, FDT_EXTERNAL);        // c:260
        }
        crate::ported::params::setiparam("REPLY", sfd as i64);   // c:263 setiparam_no_convert
        if verbose != 0 {                                                // c:265
            let path = &args[0];
            println!("{} is now on fd {}", path, sfd);                   // c:266
        }
    }
    let _ = (err, verbose, test, targetfd);                              // silence unused-binding paths
    0                                                                    // c:271
}



// ===========================================================
// Methods moved verbatim from src/ported/exec.rs because their
// C counterpart's source file maps 1:1 to this Rust module.
// ===========================================================

// =====================================================================
// static struct builtin bintab[]                                    c:280
// static struct features module_features                            c:284
// =====================================================================

use crate::ported::zsh_h::module;

// `bintab` — port of `static struct builtin bintab[]` (socket.c:280).


// `module_features` — port of `static struct features module_features`
// from socket.c:284.



/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/socket.c:291`.
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {                                // c:291
    0                                                                    // c:306
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/Modules/socket.c:298`.
/// C body: `*features = featuresarray(m, &module_features); return 0;`
pub fn features_(m: *const module, features: &mut Vec<String>) -> i32 { // c:298
    *features = featuresarray(m, module_features());
    0                                                                    // c:313
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/Modules/socket.c:306`.
/// C body: `return handlefeatures(m, &module_features, enables);`
pub fn enables_(m: *const module, enables: &mut Option<Vec<i32>>) -> i32 { // c:306
    handlefeatures(m, module_features(), enables) // c:320
}

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/socket.c:313`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                 // c:313
    0                                                                    // c:327
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/Modules/socket.c:320`.
/// C body: `return setfeatureenables(m, &module_features, NULL);`
pub fn cleanup_(m: *const module) -> i32 {                              // c:320
    setfeatureenables(m, module_features(), None) // c:327
}

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/socket.c:327`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                               // c:327
    0                                                                    // c:327
}

use crate::ported::zsh_h::features as features_t;
use std::sync::{Mutex, OnceLock};

static MODULE_FEATURES: OnceLock<Mutex<features_t>> = OnceLock::new();


// Local stubs for the per-module entry points. C uses generic
// `featuresarray`/`handlefeatures`/`setfeatureenables` (module.c:
// 3275/3370/3445) but those take `Builtin` + `Features` pointer
// fields the Rust port doesn't carry. The hardcoded descriptor
// list mirrors the C bintab/conddefs/mathfuncs/paramdefs.
// WARNING: NOT IN SOCKET.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn featuresarray(_m: *const module, _f: &Mutex<features_t>) -> Vec<String> {
    vec!["b:zsocket".to_string()]
}

// WARNING: NOT IN SOCKET.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn handlefeatures(
    _m: *const module,
    _f: &Mutex<features_t>,
    enables: &mut Option<Vec<i32>>,
) -> i32 {
    if enables.is_none() {
        *enables = Some(vec![1; 1]);
    }
    0
}

// WARNING: NOT IN SOCKET.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn setfeatureenables(
    _m: *const module,
    _f: &Mutex<features_t>,
    _e: Option<&[i32]>,
) -> i32 {
    0
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ─── 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.
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// WARNING: NOT IN SOCKET.C — Rust-only module-framework shim.
// C uses generic featuresarray/handlefeatures/setfeatureenables from
// Src/module.c:3275/3370/3445 with C-side Builtin/Features pointers;
// Rust per-module shims hardcode the bintab/conddefs/mathfuncs/paramdefs.
fn module_features() -> &'static Mutex<features_t> {
    MODULE_FEATURES.get_or_init(|| Mutex::new(features_t {
        bn_list: None,
        bn_size: 1,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 0,
        n_abstract: 0,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// c:88-90 — `zsocket -l` with no path arg MUST fail-fast BEFORE
    /// any libc::socket(2) call. A regression where the missing-arg
    /// check is bypassed would leak a socket fd per invocation.
    #[test]
    fn zsocket_l_without_arg_fails_before_socket_call() {
        let mut ops = empty_ops();
        ops.ind[b'l' as usize] = 1;
        assert_eq!(bin_zsocket("zsocket", &[], &ops, 0), 1);
    }

    /// c:71-75 — non-numeric `-d <fd>` MUST fail-fast (atoi → 0 → bad
    /// fd) BEFORE socket(2). A regression that lets `0` through would
    /// dup2 the new socket onto stdin silently.
    #[test]
    fn zsocket_d_non_numeric_fails_before_dup2() {
        let mut ops = empty_ops();
        ops.ind[b'd' as usize] = (1 << 2) | 1;
        ops.args.push("not-a-number".to_string());
        assert_eq!(bin_zsocket("zsocket", &[], &ops, 0), 1);
    }

    fn empty_ops() -> crate::ported::zsh_h::options {
        crate::ported::zsh_h::options {
            ind: [0u8; crate::ported::zsh_h::MAX_OPS],
            args: Vec::new(), argscount: 0, argsalloc: 0,
        }
    }

    /// c:225-229 — `zsocket` (default, connect-mode) with NO args must
    /// fail-fast with "zsocket requires an argument". Catches a
    /// regression where the missing-arg path leaks an unconnected
    /// socket fd.
    #[test]
    fn zsocket_connect_mode_without_args_returns_one() {
        let ops = empty_ops();
        assert_eq!(bin_zsocket("zsocket", &[], &ops, 0), 1);
    }

    /// c:144-149 — `zsocket -a` with NO args must fail-fast with
    /// "-a requires an argument". Symmetrical to the `-l` check at
    /// c:88-90 (already pinned) but for the accept-mode path.
    #[test]
    fn zsocket_a_without_arg_fails_before_accept() {
        let mut ops = empty_ops();
        ops.ind[b'a' as usize] = 1;
        assert_eq!(bin_zsocket("zsocket", &[], &ops, 0), 1);
    }

    /// c:152-156 — `zsocket -a 0` (or any non-numeric → atoi → 0) must
    /// fail with "invalid numerical argument". `0` is never a valid
    /// listening fd because the user can't have just created one and
    /// taken stdin away.
    #[test]
    fn zsocket_a_zero_listen_fd_fails() {
        let mut ops = empty_ops();
        ops.ind[b'a' as usize] = 1;
        assert_eq!(bin_zsocket("zsocket", &["0".to_string()], &ops, 0), 1);
        // non-numeric also flows through atoi → 0
        assert_eq!(bin_zsocket("zsocket", &["not-numeric".to_string()], &ops, 0), 1);
    }

    /// c:291-327 — module-lifecycle stubs (`setup_`, `boot_`,
    /// `cleanup_`, `finish_`) all return 0 in the C source. The Rust
    /// port must match.
    #[test]
    fn module_lifecycle_shims_all_return_zero() {
        let m = std::ptr::null();
        assert_eq!(setup_(m), 0);
        assert_eq!(boot_(m), 0);
        assert_eq!(cleanup_(m), 0);
        assert_eq!(finish_(m), 0);
    }

    /// c:298 — `features_` populates the feature list and returns 0.
    /// Specific contents aren't pinned by C; just verify the function
    /// is callable without panicking and returns the success sentinel.
    #[test]
    fn features_returns_success() {
        let mut features = Vec::new();
        assert_eq!(features_(std::ptr::null(), &mut features), 0);
    }
}