zshrs 0.11.1

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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! `zsh/attr` module — port of `Src/Modules/attr.c`.
//!
//! Top-level declaration order matches C source line-by-line:
//!   - `xgetxattr(path, name, value, size, symlink)`  c:36
//!   - `xlistxattr(path, list, size, symlink)`        c:51
//!   - `xsetxattr(path, name, value, size, flags, symlink)` c:66
//!   - `xremovexattr(path, name, symlink)`            c:82
//!   - `bin_getattr(nam, argv, ops, func)`            c:97
//!   - `bin_setattr(nam, argv, ops, func)`            c:132
//!   - `bin_delattr(nam, argv, ops, func)`            c:149
//!   - `bin_listattr(nam, argv, ops, func)`           c:168
//!   - `static struct builtin bintab[]`               c:219
//!   - `static struct features module_features`       c:226
//!   - `setup_(m)` / `features_(m, features)` /
//!     `enables_(m, enables)` / `boot_(m)` /
//!     `cleanup_(m)` / `finish_(m)`                   c:235-275

#![allow(non_camel_case_types)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]

use std::ffi::CString;

use crate::ported::utils::{metafy, unmetafy, zwarnnam};
use crate::ported::zsh_h::{module, options, OPT_ISSET};

#[cfg(target_os = "macos")]
const XATTR_NOFOLLOW: i32 = 0x0001;

// =====================================================================
// xgetxattr(const char *path, const char *name, void *value, size_t size, int symlink)  c:36
// =====================================================================

/// Port of `xgetxattr(const char *path, const char *name, void *value, size_t size, int symlink)` from `Src/Modules/attr.c:37`.
///
/// Caller passes a `&mut [u8]` slot for `value` and the buffer length
/// for `size`. Empty slice queries required size — same as C
/// `value=NULL, size=0` (attr.c:107).
#[cfg(any(target_os = "macos", target_os = "linux"))]
/// WARNING: param names don't match C — Rust=(path, name, value, symlink) vs C=(path, name, value, size, symlink)
pub fn xgetxattr(path: &str, name: &str, value: &mut [u8], symlink: i32) -> isize { // c:37
    let path_c = match CString::new(path) { Ok(c) => c, Err(_) => return -1 };
    let name_c = match CString::new(name) { Ok(c) => c, Err(_) => return -1 };
    let val_ptr = if value.is_empty() {
        std::ptr::null_mut()
    } else {
        value.as_mut_ptr() as *mut libc::c_void
    };
    #[cfg(target_os = "macos")]
    {
        // c:40 — `return getxattr(path, name, value, size, 0, symlink ? XATTR_NOFOLLOW: 0);`
        unsafe {
            libc::getxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len(), 0,
                           if symlink != 0 { XATTR_NOFOLLOW } else { 0 })
        }
    }
    #[cfg(target_os = "linux")]
    {
        // c:37-47 — switch (symlink) { case 0: getxattr; default: lgetxattr; }
        match symlink {
            0 => unsafe { libc::getxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len()) },
            _ => unsafe { libc::lgetxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len()) },
        }
    }
}

/// Port of `xgetxattr(const char *path, const char *name, void *value, size_t size, int symlink)` from `Src/Modules/attr.c:37`.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
/// WARNING: param names don't match C — Rust=(_path, _name, _value, _symlink) vs C=(path, name, value, size, symlink)
pub fn xgetxattr(_path: &str, _name: &str, _value: &mut [u8], _symlink: i32) -> isize { -1 }

// =====================================================================
// xlistxattr(const char *path, char *list, size_t size, int symlink)  c:51
// =====================================================================

/// Port of `xlistxattr(const char *path, char *list, size_t size, int symlink)` from `Src/Modules/attr.c:52`.
#[cfg(any(target_os = "macos", target_os = "linux"))]
/// WARNING: param names don't match C — Rust=(path, list, symlink) vs C=(path, list, size, symlink)
pub fn xlistxattr(path: &str, list: &mut [u8], symlink: i32) -> isize {      // c:52
    let path_c = match CString::new(path) { Ok(c) => c, Err(_) => return -1 };
    let list_ptr = if list.is_empty() {
        std::ptr::null_mut()
    } else {
        list.as_mut_ptr() as *mut libc::c_char
    };
    #[cfg(target_os = "macos")]
    {
        // c:55 — return listxattr(path, list, size, symlink ? XATTR_NOFOLLOW : 0);
        unsafe {
            libc::listxattr(path_c.as_ptr(), list_ptr, list.len(),
                            if symlink != 0 { XATTR_NOFOLLOW } else { 0 })
        }
    }
    #[cfg(target_os = "linux")]
    {
        // c:52-62 — switch (symlink) { case 0: listxattr; default: llistxattr; }
        match symlink {
            0 => unsafe { libc::listxattr(path_c.as_ptr(), list_ptr, list.len()) },
            _ => unsafe { libc::llistxattr(path_c.as_ptr(), list_ptr, list.len()) },
        }
    }
}

/// Port of `xlistxattr(const char *path, char *list, size_t size, int symlink)` from `Src/Modules/attr.c:52`.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
/// WARNING: param names don't match C — Rust=(_path, _list, _symlink) vs C=(path, list, size, symlink)
pub fn xlistxattr(_path: &str, _list: &mut [u8], _symlink: i32) -> isize { -1 }

// =====================================================================
// xsetxattr(const char *path, const char *name, const void *value,
//           size_t size, int flags, int symlink)                       c:66
// =====================================================================

/// Port of `xsetxattr(const char *path, const char *name, const void *value, size_t size, int flags, int symlink)` from `Src/Modules/attr.c:67`.
#[cfg(any(target_os = "macos", target_os = "linux"))]
/// WARNING: param names don't match C — Rust=(path, name, value, flags, symlink) vs C=(path, name, value, size, flags, symlink)
pub fn xsetxattr(path: &str, name: &str, value: &[u8], flags: i32, symlink: i32) -> i32 { // c:67
    let path_c = match CString::new(path) { Ok(c) => c, Err(_) => return -1 };
    let name_c = match CString::new(name) { Ok(c) => c, Err(_) => return -1 };
    let val_ptr = value.as_ptr() as *const libc::c_void;
    #[cfg(target_os = "macos")]
    {
        // c:71 — `return setxattr(path, name, value, size, 0, flags | symlink ? XATTR_NOFOLLOW : 0);`
        // The C operator-precedence quirk: `(flags | symlink) ? ... : 0`.
        let combined = if (flags | symlink) != 0 { XATTR_NOFOLLOW } else { 0 };
        unsafe {
            libc::setxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len(), 0, combined)
        }
    }
    #[cfg(target_os = "linux")]
    {
        // c:67-78 — switch (symlink) { case 0: setxattr; default: lsetxattr; }
        match symlink {
            0 => unsafe { libc::setxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len(), flags) },
            _ => unsafe { libc::lsetxattr(path_c.as_ptr(), name_c.as_ptr(), val_ptr, value.len(), flags) },
        }
    }
}

/// Port of `xsetxattr(const char *path, const char *name, const void *value, size_t size, int flags, int symlink)` from `Src/Modules/attr.c:67`.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
/// WARNING: param names don't match C — Rust=(_path, _name, _value, _flags, _symlink) vs C=(path, name, value, size, flags, symlink)
pub fn xsetxattr(_path: &str, _name: &str, _value: &[u8], _flags: i32, _symlink: i32) -> i32 { -1 }

// =====================================================================
// xremovexattr(const char *path, const char *name, int symlink)       c:82
// =====================================================================

/// Port of `xremovexattr(const char *path, const char *name, int symlink)` from `Src/Modules/attr.c:83`.
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn xremovexattr(path: &str, name: &str, symlink: i32) -> i32 {           // c:83
    let path_c = match CString::new(path) { Ok(c) => c, Err(_) => return -1 };
    let name_c = match CString::new(name) { Ok(c) => c, Err(_) => return -1 };
    #[cfg(target_os = "macos")]
    {
        // c:86 — `return removexattr(path, name, symlink ? XATTR_NOFOLLOW : 0);`
        unsafe { libc::removexattr(path_c.as_ptr(), name_c.as_ptr(),
                                   if symlink != 0 { XATTR_NOFOLLOW } else { 0 }) }
    }
    #[cfg(target_os = "linux")]
    {
        // c:83-93 — switch (symlink) { case 0: removexattr; default: lremovexattr; }
        match symlink {
            0 => unsafe { libc::removexattr(path_c.as_ptr(), name_c.as_ptr()) },
            _ => unsafe { libc::lremovexattr(path_c.as_ptr(), name_c.as_ptr()) },
        }
    }
}

/// Port of `xremovexattr(const char *path, const char *name, int symlink)` from `Src/Modules/attr.c:83`.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
#[allow(unused_variables)]
pub fn xremovexattr(path: &str, name: &str, symlink: i32) -> i32 { -1 }

// =====================================================================
// bin_getattr(char *nam, char **argv, Options ops, UNUSED(int func))  c:97
// =====================================================================

/// Port of `bin_getattr(char *nam, char **argv, Options ops, UNUSED(int func))` from `Src/Modules/attr.c:98`.
#[allow(unused_variables)]
pub fn bin_getattr(nam: &str, argv: &[String], ops: &options, func: i32) -> i32 { // c:98
    // c:98 — `int ret = 0;`
    let mut ret: i32 = 0;
    // c:101 — `int val_len = 0, attr_len = 0, slen;`
    let mut val_len: isize = 0;
    let mut attr_len: isize = 0;
    let _slen: usize;
    // c:102 — `char *value, *file = argv[0], *attr = argv[1], *param = argv[2];`
    let file_arg = argv.get(0).map(|s| s.as_str()).unwrap_or("");
    let attr_arg = argv.get(1).map(|s| s.as_str()).unwrap_or("");
    let param: Option<&str> = argv.get(2).map(|s| s.as_str());
    // c:103 — `int symlink = OPT_ISSET(ops, 'h');`
    let symlink: i32 = if OPT_ISSET(ops, b'h') { 1 } else { 0 };

    // c:105 — `unmetafy(file, &slen);`
    let mut file_bytes = file_arg.as_bytes().to_vec();
    _slen = unmetafy(&mut file_bytes);
    // c:106 — `unmetafy(attr, NULL);`
    let mut attr_bytes = attr_arg.as_bytes().to_vec();
    unmetafy(&mut attr_bytes);
    let file = std::str::from_utf8(&file_bytes).unwrap_or(file_arg);
    let attr = std::str::from_utf8(&attr_bytes).unwrap_or(attr_arg);

    // c:107 — `val_len = xgetxattr(file, attr, NULL, 0, symlink);`
    val_len = xgetxattr(file, attr, &mut [], symlink);
    if val_len == 0 {                                                    // c:108
        if let Some(p) = param {                                         // c:109
            unsetparam(p);                                                // c:110
        }
        return 0;                                                         // c:111
    }
    if val_len > 0 {                                                     // c:113
        // c:114 — value = (char *)zalloc(val_len+1);
        let mut value: Vec<u8> = vec![0u8; (val_len + 1) as usize];
        // c:115 — attr_len = xgetxattr(file, attr, value, val_len, symlink);
        attr_len = xgetxattr(file, attr, &mut value[..val_len as usize], symlink);
        if attr_len > 0 && attr_len <= val_len {                         // c:116
            value[attr_len as usize] = b'\0';                            // c:117
            let val_plain = String::from_utf8_lossy(&value[..attr_len as usize]).into_owned();
            if let Some(p) = param {                                     // c:118
                // c:119 — setsparam(param, metafy(value, attr_len, META_DUP));
                setsparam(p, &metafy(&val_plain));
            } else {
                println!("{}", val_plain);                                // c:121
            }
        }
        // c:123 — zfree(value, val_len+1); (Vec drop reclaims)
    }
    if val_len < 0 || attr_len < 0 || attr_len > val_len {               // c:125
        // c:126 — zwarnnam(nam, "%s: %e", metafy(file, slen, META_NOALLOC), errno);
        zwarnnam(nam, &format!("{}: {}", metafy(file), std::io::Error::last_os_error()));
        // c:133 — ret = 1 + ((val_len > 0 && attr_len > val_len) || attr_len < 0);
        ret = 1 + i32::from((val_len > 0 && attr_len > val_len) || attr_len < 0);
    }
    ret                                                                   // c:133
}

// =====================================================================
// bin_setattr(char *nam, char **argv, Options ops, UNUSED(int func))  c:132
// =====================================================================

/// Port of `bin_setattr(char *nam, char **argv, Options ops, UNUSED(int func))` from `Src/Modules/attr.c:133`.
#[allow(unused_variables)]
pub fn bin_setattr(nam: &str, argv: &[String], ops: &options, func: i32) -> i32 { // c:133
    // c:133 — `int ret = 0, slen, vlen;`
    let _slen: usize;
    let vlen: usize;
    // c:136 — `int symlink = OPT_ISSET(ops, 'h');`
    let symlink: i32 = if OPT_ISSET(ops, b'h') { 1 } else { 0 };
    // c:137 — `char *file = argv[0], *attr = argv[1], *value = argv[2];`
    let file_arg = argv.get(0).map(|s| s.as_str()).unwrap_or("");
    let attr_arg = argv.get(1).map(|s| s.as_str()).unwrap_or("");
    let value_arg = argv.get(2).map(|s| s.as_str()).unwrap_or("");

    // c:139-141 — unmetafy each.
    let mut file_bytes = file_arg.as_bytes().to_vec();
    _slen = unmetafy(&mut file_bytes);
    let mut attr_bytes = attr_arg.as_bytes().to_vec();
    unmetafy(&mut attr_bytes);
    let mut value_bytes = value_arg.as_bytes().to_vec();
    vlen = unmetafy(&mut value_bytes);
    let file = std::str::from_utf8(&file_bytes).unwrap_or(file_arg);
    let attr = std::str::from_utf8(&attr_bytes).unwrap_or(attr_arg);

    // c:142 — `if (xsetxattr(file, attr, value, vlen, 0, symlink))`
    if xsetxattr(file, attr, &value_bytes[..vlen], 0, symlink) != 0 {
        // c:143 — zwarnnam(nam, "%s: %e", metafy(file, slen, META_NOALLOC), errno);
        zwarnnam(nam, &format!("{}: {}", metafy(file), std::io::Error::last_os_error()));
        return 1;                                                         // c:150 ret = 1;
    }
    0                                                                     // c:150
}

// =====================================================================
// bin_delattr(char *nam, char **argv, Options ops, UNUSED(int func))  c:149
// =====================================================================

/// Port of `bin_delattr(char *nam, char **argv, Options ops, UNUSED(int func))` from `Src/Modules/attr.c:150`.
#[allow(unused_variables)]
pub fn bin_delattr(nam: &str, argv: &[String], ops: &options, func: i32) -> i32 {
    // c:150 — `int ret = 0, slen;`
    let _slen: usize;
    // c:153 — `int symlink = OPT_ISSET(ops, 'h');`
    let symlink: i32 = if OPT_ISSET(ops, b'h') { 1 } else { 0 };
    // c:154 — `char *file = argv[0], **attr = argv;`
    let file_arg = argv.get(0).map(|s| s.as_str()).unwrap_or("");

    // c:156 — `unmetafy(file, &slen);`
    let mut file_bytes = file_arg.as_bytes().to_vec();
    _slen = unmetafy(&mut file_bytes);
    let file = std::str::from_utf8(&file_bytes)
        .map(|s| s.to_string())
        .unwrap_or_else(|_| file_arg.to_string());

    // c:157 — `while (*++attr)` — iterate argv[1..]
    for attr_arg in &argv[1..] {
        // c:158 — `unmetafy(*attr, NULL);`
        let mut attr_bytes = attr_arg.as_bytes().to_vec();
        unmetafy(&mut attr_bytes);
        let attr = std::str::from_utf8(&attr_bytes).unwrap_or(attr_arg);
        if xremovexattr(&file, attr, symlink) != 0 {                     // c:159
            // c:160 — zwarnnam(nam, "%s: %e", metafy(file, slen, META_NOALLOC), errno);
            zwarnnam(nam, &format!("{}: {}", metafy(&file), std::io::Error::last_os_error()));
            return 1;                                                     // c:169-162 ret=1; break;
        }
    }
    0                                                                     // c:169
}

// =====================================================================
// bin_listattr(char *nam, char **argv, Options ops, UNUSED(int func))  c:168
// =====================================================================

/// Port of `bin_listattr(char *nam, char **argv, Options ops, UNUSED(int func))` from `Src/Modules/attr.c:169`.
#[allow(unused_variables)]
pub fn bin_listattr(nam: &str, argv: &[String], ops: &options, func: i32) -> i32 {
    // c:169 — `int ret = 0;`
    let mut ret: i32 = 0;
    // c:172 — `int val_len, list_len = 0, slen;`
    let val_len: isize;
    let mut list_len: isize = 0;
    let _slen: usize;
    // c:173 — `char *value, *file = argv[0], *param = argv[1];`
    let file_arg = argv.get(0).map(|s| s.as_str()).unwrap_or("");
    let param: Option<&str> = argv.get(1).map(|s| s.as_str());
    // c:174 — `int symlink = OPT_ISSET(ops, 'h');`
    let symlink: i32 = if OPT_ISSET(ops, b'h') { 1 } else { 0 };

    // c:176 — `unmetafy(file, &slen);`
    let mut file_bytes = file_arg.as_bytes().to_vec();
    _slen = unmetafy(&mut file_bytes);
    let file_owned = std::str::from_utf8(&file_bytes)
        .map(|s| s.to_string())
        .unwrap_or_else(|_| file_arg.to_string());
    let file = file_owned.as_str();

    // c:177 — `val_len = xlistxattr(file, NULL, 0, symlink);`
    val_len = xlistxattr(file, &mut [], symlink);
    if val_len == 0 {                                                    // c:178
        if let Some(p) = param {                                         // c:179
            unsetparam(p);                                                // c:180
        }
        return 0;                                                         // c:181
    }
    if val_len > 0 {                                                     // c:183
        // c:184 — value = (char *)zalloc(val_len+1);
        let mut value: Vec<u8> = vec![0u8; (val_len + 1) as usize];
        // c:185 — list_len = xlistxattr(file, value, val_len, symlink);
        list_len = xlistxattr(file, &mut value[..val_len as usize], symlink);
        if list_len > 0 && list_len <= val_len {                         // c:186
            // c:187 — `char *p = value;` — walk the NUL-separated names list.
            let names_bytes = &value[..list_len as usize];
            let raw_names: Vec<&[u8]> = names_bytes
                .split(|&b| b == 0)
                .filter(|s| !s.is_empty())
                .collect();
            if let Some(p) = param {                                     // c:188
                // c:189-202 — build metafied char-array, setaparam(param, array)
                let metafied_names: Vec<String> = raw_names
                    .iter()
                    .map(|n| metafy(&String::from_utf8_lossy(n)))
                    .collect();
                setaparam(p, metafied_names);                            // c:202
            } else {
                // c:203-206 — printf("%s\n", p) per name.
                for n in &raw_names {
                    println!("{}", String::from_utf8_lossy(n));         // c:204
                }
            }
        }
    }
    if val_len < 0 || list_len < 0 || list_len > val_len {               // c:210
        // c:211 — zwarnnam(nam, "%s: %e", metafy(file, slen, META_NOALLOC), errno);
        zwarnnam(nam, &format!("{}: {}", metafy(file), std::io::Error::last_os_error()));
        // c:212 — ret = 1 + (list_len > val_len || list_len < 0);
        ret = 1 + i32::from(list_len > val_len || list_len < 0);
    }
    ret                                                                   // c:214
}

// =====================================================================
// /* module paraphernalia */                                          c:217
// static struct builtin bintab[]                                     c:219
// static struct features module_features                             c:226
//
// Static dispatch tables consumed by C module loader. Static-link
// path: dispatcher in `src/extensions/` invokes bin_* directly.
// Tables omitted from Rust port pending module-loader.
// =====================================================================

// =====================================================================
// setup_(UNUSED(Module m))                                           c:235
// =====================================================================

// =====================================================================
// External fns + tables. `static struct features module_features` from
// attr.c:226. Dispatch through canonical `module::featuresarray`.
// =====================================================================


// `bintab` — port of `static struct builtin bintab[]` (attr.c).


// `module_features` — port of `static struct features module_features`
// from attr.c:226.



/// Port of `setup_(UNUSED(Module m))` from `Src/Modules/attr.c:236`.
#[allow(unused_variables)]
pub fn setup_(m: *const module) -> i32 {                                    // c:236
    // C body c:238-239 — `return 0`. Faithful empty-body port.
    0
}

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

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

/// Port of `boot_(UNUSED(Module m))` from `Src/Modules/attr.c:258`.
#[allow(unused_variables)]
pub fn boot_(m: *const module) -> i32 {                                     // c:258
    // C body c:260-261 — `return 0`. Faithful empty-body port; the
    //                    zgetattr/zsetattr/zdelattr/zlistattr builtins
    //                    register via the bn_list feature dispatch.
    0
}

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

/// Port of `finish_(UNUSED(Module m))` from `Src/Modules/attr.c:272`.
#[allow(unused_variables)]
pub fn finish_(m: *const module) -> i32 {                                   // c:272
    // C body c:274-275 — `return 0`. Faithful empty-body port; the
    //                    builtins unregister via cleanup_'s setfeatureenables.
    0
}

// =====================================================================
// External fns from other Src/*.c files — routed through the canonical
// 2-arg variants that match the C signatures.
// =====================================================================

/// Port of `setsparam(char *s, char *val)` from `Src/params.c:3350` — delegates to
/// `ksh93::setsparam(name, val)` which provides the env-var-shim
/// implementation matching the C signature.
/// WARNING: param names don't match C — Rust=(name, value) vs C=(PM_HASHED)
fn setsparam(name: &str, value: &str) {
    crate::ported::params::setsparam(name, value);
}

/// Port of `setaparam(char *s, char **aval)` from `Src/params.c:3595` — delegates to
/// `ksh93::setsparam` with the value colon-joined (PATH-style array
/// shape that the env-var bridge unpacks at read time).
/// WARNING: param names don't match C — Rust=(name, value) vs C=(s, val, flags)
fn setaparam(name: &str, value: Vec<String>) {
    crate::ported::params::setsparam(name, &value.join(":"));
}

/// Port of `unsetparam(char *s)` from `Src/params.c:3819` — env::remove_var
/// is the static-link equivalent of paramtab->removenode +
/// freeparamnode for scalar params.
fn unsetparam(v: &str) {
    std::env::remove_var(v);
}

// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ported::zsh_h::MAX_OPS;

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

    #[test]
    fn xgetxattr_nonexistent_returns_negative() {
        let mut buf = [0u8; 0];
        let r = xgetxattr("/nonexistent/path", "user.test", &mut buf, 0);
        assert!(r < 0);
    }

    #[test]
    fn xsetxattr_nonexistent_returns_negative() {
        let r = xsetxattr("/nonexistent/path", "user.test", b"value", 0, 0);
        assert!(r < 0);
    }

    #[test]
    fn xlistxattr_nonexistent_returns_negative() {
        let mut buf = [0u8; 0];
        let r = xlistxattr("/nonexistent/path", &mut buf, 0);
        assert!(r < 0);
    }

    #[test]
    fn xremovexattr_nonexistent_returns_negative() {
        let r = xremovexattr("/nonexistent/path", "user.test", 0);
        assert!(r < 0);
    }

    #[test]
    fn bin_getattr_nonexistent_path_returns_nonzero() {
        let ops = empty_ops();
        let argv: Vec<String> = vec!["/nonexistent/path".into(), "user.test".into()];
        let rc = bin_getattr("zgetattr", &argv, &ops, 0);
        assert_ne!(rc, 0);
    }

    #[test]
    fn bin_setattr_nonexistent_path_returns_one() {
        let ops = empty_ops();
        let argv: Vec<String> = vec!["/nonexistent/path".into(), "user.test".into(), "value".into()];
        let rc = bin_setattr("zsetattr", &argv, &ops, 0);
        assert_eq!(rc, 1);
    }

    #[test]
    fn module_loaders_return_zero() {
        let m: *const module = std::ptr::null();
        let mut features: Vec<String> = Vec::new();
        let mut enables: Option<Vec<i32>> = None;
        assert_eq!(setup_(m), 0);
        assert_eq!(features_(m, &mut features), 0);
        assert_eq!(features.len(), 4);
        assert_eq!(enables_(m, &mut enables), 0);
        assert_eq!(boot_(m), 0);
        assert_eq!(cleanup_(m), 0);
        assert_eq!(finish_(m), 0);
    }
}

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

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

// WARNING: NOT IN ATTR.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: 4,
        cd_list: None,
        cd_size: 0,
        mf_list: None,
        mf_size: 0,
        pd_list: None,
        pd_size: 0,
        n_abstract: 0,
    }))
}

// 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 ATTR.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:zgetattr".to_string(), "b:zsetattr".to_string(), "b:zdelattr".to_string(), "b:zlistattr".to_string()]
}

// WARNING: NOT IN ATTR.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; 4]);
    }
    0
}

// WARNING: NOT IN ATTR.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
}