zshrs 0.10.9

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, SQLite 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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! GDBM database bindings for zsh
//!
//! Port of zsh/Src/Modules/db_gdbm.c
//!
//! Provides builtins:
//! - ztie: Tie a parameter to a GDBM database
//! - zuntie: Untie a parameter from a GDBM database
//! - zgdbmpath: Get the path of a tied GDBM database

use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::path::{Path, PathBuf};
use std::ptr;
use std::sync::{Arc, Mutex, RwLock};

use once_cell::sync::Lazy;

const BACKTYPE: &str = "db/gdbm";

/// GDBM open flags
const GDBM_READER: c_int = 0;
const GDBM_WRITER: c_int = 1;
const GDBM_WRCREAT: c_int = 2;
const GDBM_NEWDB: c_int = 3;
const GDBM_SYNC: c_int = 0x20;
const GDBM_REPLACE: c_int = 1;

/// Datum structure for GDBM
#[repr(C)]
struct Datum {
    dptr: *mut c_char,
    dsize: c_int,
}

impl Datum {
    fn null() -> Self {
        Datum {
            dptr: ptr::null_mut(),
            dsize: 0,
        }
    }

    fn from_bytes(data: &[u8]) -> Self {
        let ptr = unsafe { libc::malloc(data.len()) as *mut c_char };
        if !ptr.is_null() {
            unsafe {
                ptr::copy_nonoverlapping(data.as_ptr(), ptr as *mut u8, data.len());
            }
        }
        Datum {
            dptr: ptr,
            dsize: data.len() as c_int,
        }
    }

    fn to_bytes(&self) -> Option<Vec<u8>> {
        if self.dptr.is_null() {
            None
        } else {
            let mut result = vec![0u8; self.dsize as usize];
            unsafe {
                ptr::copy_nonoverlapping(
                    self.dptr as *const u8,
                    result.as_mut_ptr(),
                    self.dsize as usize,
                );
            }
            Some(result)
        }
    }

    fn free(&mut self) {
        if !self.dptr.is_null() {
            unsafe { libc::free(self.dptr as *mut c_void) };
            self.dptr = ptr::null_mut();
            self.dsize = 0;
        }
    }
}

/// Opaque GDBM file handle
type GdbmFile = *mut c_void;

#[cfg(feature = "gdbm")]
#[link(name = "gdbm")]
extern "C" {
    fn gdbm_open(
        name: *const c_char,
        block_size: c_int,
        flags: c_int,
        mode: c_int,
        fatal_func: Option<extern "C" fn(*const c_char)>,
    ) -> GdbmFile;
    fn gdbm_close(dbf: GdbmFile);
    fn gdbm_store(dbf: GdbmFile, key: Datum, content: Datum, flag: c_int) -> c_int;
    fn gdbm_fetch(dbf: GdbmFile, key: Datum) -> Datum;
    fn gdbm_delete(dbf: GdbmFile, key: Datum) -> c_int;
    fn gdbm_exists(dbf: GdbmFile, key: Datum) -> c_int;
    fn gdbm_firstkey(dbf: GdbmFile) -> Datum;
    fn gdbm_nextkey(dbf: GdbmFile, key: Datum) -> Datum;
    fn gdbm_reorganize(dbf: GdbmFile) -> c_int;
    fn gdbm_fdesc(dbf: GdbmFile) -> c_int;
    fn gdbm_strerror(errno: c_int) -> *const c_char;
    static gdbm_errno: c_int;
}

/// GDBM database handle wrapper.
/// Port of the per-tied-param `Db` slot Src/Modules/db_gdbm.c
/// stores in `myfreeparamnode()` (line 45) — the C source threads
/// the live `GDBM_FILE *` through every `gdbmgetfn`/`gdbmsetfn` call
/// (lines 282/347). Same shape on the Rust side.
#[derive(Debug)]
pub struct GdbmDatabase {
    dbf: GdbmFile,
    path: PathBuf,
    readonly: bool,
}

impl GdbmDatabase {
    #[cfg(feature = "gdbm")]
    pub fn open(path: &Path, readonly: bool) -> Result<Self, String> {
        let c_path = CString::new(path.to_string_lossy().as_bytes()).map_err(|_| "Invalid path")?;

        let flags = GDBM_SYNC | if readonly { GDBM_READER } else { GDBM_WRCREAT };

        let dbf = unsafe { gdbm_open(c_path.as_ptr(), 0, flags, 0o666, None) };

        if dbf.is_null() {
            let err = unsafe {
                let err_ptr = gdbm_strerror(gdbm_errno);
                if err_ptr.is_null() {
                    "Unknown error".to_string()
                } else {
                    CStr::from_ptr(err_ptr).to_string_lossy().to_string()
                }
            };
            return Err(format!(
                "error opening database file {} ({})",
                path.display(),
                err
            ));
        }

        Ok(GdbmDatabase {
            dbf,
            path: path.to_path_buf(),
            readonly,
        })
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn open(_path: &Path, _readonly: bool) -> Result<Self, String> {
        Err("GDBM support not compiled in".to_string())
    }

    #[cfg(feature = "gdbm")]
    pub fn get(&self, key: &str) -> Option<String> {
        let key_bytes = key.as_bytes();
        let key_datum = Datum::from_bytes(key_bytes);

        let exists = unsafe {
            gdbm_exists(
                self.dbf,
                Datum {
                    dptr: key_datum.dptr,
                    dsize: key_datum.dsize,
                },
            )
        };

        if exists == 0 {
            unsafe { libc::free(key_datum.dptr as *mut c_void) };
            return None;
        }

        let mut content = unsafe {
            gdbm_fetch(
                self.dbf,
                Datum {
                    dptr: key_datum.dptr,
                    dsize: key_datum.dsize,
                },
            )
        };

        unsafe { libc::free(key_datum.dptr as *mut c_void) };

        let result = content
            .to_bytes()
            .map(|bytes| String::from_utf8_lossy(&bytes).to_string());

        content.free();
        result
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn get(&self, _key: &str) -> Option<String> {
        None
    }

    #[cfg(feature = "gdbm")]
    pub fn set(&self, key: &str, value: &str) -> Result<(), String> {
        if self.readonly {
            return Err("Database is read-only".to_string());
        }

        let key_datum = Datum::from_bytes(key.as_bytes());
        let content_datum = Datum::from_bytes(value.as_bytes());

        let ret = unsafe {
            gdbm_store(
                self.dbf,
                Datum {
                    dptr: key_datum.dptr,
                    dsize: key_datum.dsize,
                },
                Datum {
                    dptr: content_datum.dptr,
                    dsize: content_datum.dsize,
                },
                GDBM_REPLACE,
            )
        };

        unsafe {
            libc::free(key_datum.dptr as *mut c_void);
            libc::free(content_datum.dptr as *mut c_void);
        }

        if ret != 0 {
            Err("Failed to store value".to_string())
        } else {
            Ok(())
        }
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn set(&self, _key: &str, _value: &str) -> Result<(), String> {
        Err("GDBM support not compiled in".to_string())
    }

    #[cfg(feature = "gdbm")]
    pub fn delete(&self, key: &str) -> Result<(), String> {
        if self.readonly {
            return Err("Database is read-only".to_string());
        }

        let key_datum = Datum::from_bytes(key.as_bytes());

        let ret = unsafe {
            gdbm_delete(
                self.dbf,
                Datum {
                    dptr: key_datum.dptr,
                    dsize: key_datum.dsize,
                },
            )
        };

        unsafe { libc::free(key_datum.dptr as *mut c_void) };

        if ret != 0 {
            Err("Key not found".to_string())
        } else {
            Ok(())
        }
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn delete(&self, _key: &str) -> Result<(), String> {
        Err("GDBM support not compiled in".to_string())
    }

    #[cfg(feature = "gdbm")]
    pub fn keys(&self) -> Vec<String> {
        let mut keys = Vec::new();

        let mut key = unsafe { gdbm_firstkey(self.dbf) };

        while !key.dptr.is_null() {
            if let Some(bytes) = key.to_bytes() {
                keys.push(String::from_utf8_lossy(&bytes).to_string());
            }

            let prev_key = key;
            key = unsafe {
                gdbm_nextkey(
                    self.dbf,
                    Datum {
                        dptr: prev_key.dptr,
                        dsize: prev_key.dsize,
                    },
                )
            };
            unsafe { libc::free(prev_key.dptr as *mut c_void) };
        }

        keys
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn keys(&self) -> Vec<String> {
        Vec::new()
    }

    #[cfg(feature = "gdbm")]
    pub fn clear(&self) -> Result<(), String> {
        if self.readonly {
            return Err("Database is read-only".to_string());
        }

        let keys = self.keys();
        for key in keys {
            let _ = self.delete(&key);
        }

        unsafe { gdbm_reorganize(self.dbf) };
        Ok(())
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn clear(&self) -> Result<(), String> {
        Err("GDBM support not compiled in".to_string())
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    #[cfg(feature = "gdbm")]
    pub fn fd(&self) -> i32 {
        unsafe { gdbm_fdesc(self.dbf) }
    }

    #[cfg(not(feature = "gdbm"))]
    pub fn fd(&self) -> i32 {
        -1
    }
}

#[cfg(feature = "gdbm")]
impl Drop for GdbmDatabase {
    fn drop(&mut self) {
        if !self.dbf.is_null() {
            unsafe { gdbm_close(self.dbf) };
            self.dbf = ptr::null_mut();
        }
    }
}

#[cfg(not(feature = "gdbm"))]
impl Drop for GdbmDatabase {
    fn drop(&mut self) {}
}

unsafe impl Send for GdbmDatabase {}
unsafe impl Sync for GdbmDatabase {}

/// A parameter tied to a GDBM database.
/// Port of the `Param` shape Src/Modules/db_gdbm.c installs via
/// `bin_ztie()` (line 109) — the C source builds a special hash
/// `Param` whose `getfn`/`setfn`/`unsetfn` route every read/write
/// through `gdbmgetfn` (line 282) / `gdbmsetfn` (line 347) /
/// `gdbmunsetfn` (line 399). The Rust struct holds the live db
/// handle plus a small per-key cache.
pub struct TiedGdbmParam {
    pub name: String,
    pub db: Arc<GdbmDatabase>,
    pub cache: RwLock<HashMap<String, String>>,
}

impl TiedGdbmParam {
    pub fn new(name: String, db: Arc<GdbmDatabase>) -> Self {
        TiedGdbmParam {
            name,
            db,
            cache: RwLock::new(HashMap::new()),
        }
    }

    pub fn get(&self, key: &str) -> Option<String> {
        if let Ok(cache) = self.cache.read() {
            if let Some(val) = cache.get(key) {
                return Some(val.clone());
            }
        }

        if let Some(val) = self.db.get(key) {
            if let Ok(mut cache) = self.cache.write() {
                cache.insert(key.to_string(), val.clone());
            }
            Some(val)
        } else {
            None
        }
    }

    pub fn set(&self, key: &str, value: &str) -> Result<(), String> {
        self.db.set(key, value)?;
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key.to_string(), value.to_string());
        }
        Ok(())
    }

    pub fn delete(&self, key: &str) -> Result<(), String> {
        self.db.delete(key)?;
        if let Ok(mut cache) = self.cache.write() {
            cache.remove(key);
        }
        Ok(())
    }

    pub fn keys(&self) -> Vec<String> {
        self.db.keys()
    }

    pub fn to_hash(&self) -> HashMap<String, String> {
        let mut result = HashMap::new();
        for key in self.keys() {
            if let Some(val) = self.get(&key) {
                result.insert(key, val);
            }
        }
        result
    }

    pub fn from_hash(&self, hash: &HashMap<String, String>) -> Result<(), String> {
        self.db.clear()?;
        for (key, val) in hash {
            self.db.set(key, val)?;
        }
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
        Ok(())
    }
}

/// Global registry of tied GDBM parameters
static TIED_PARAMS: Lazy<Mutex<HashMap<String, Arc<TiedGdbmParam>>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// List currently-tied GDBM parameter names.
/// Port of the `tied_param_list` enumeration the C source keeps in
/// Src/Modules/db_gdbm.c via `append_tied_name()` /
/// `remove_tied_name()` (lines 42/43) — `${zgdbm_tied}` reads it.
pub fn zgdbm_tied() -> Vec<String> {
    if let Ok(params) = TIED_PARAMS.lock() {
        params.keys().cloned().collect()
    } else {
        Vec::new()
    }
}

/// `ztie` builtin entry point — bind a parameter to a GDBM file.
/// Port of `bin_ztie()` from Src/Modules/db_gdbm.c:109 — the C
/// source opens the GDBM file via `gdbm_open()`, allocates a hash
/// `Param`, wires the per-key getter/setter slots, and inserts
/// the param name into the tied-list.
///
/// Usage: `ztie -d db/gdbm -f /path/to/db.gdbm [-r] PARAM_NAME`
pub fn ztie(
    args: &[String],
    readonly: bool,
    db_type: Option<&str>,
    file_path: Option<&str>,
) -> Result<(), String> {
    let db_type = db_type.ok_or("you must pass `-d db/gdbm'")?;
    let file_path = file_path.ok_or("you must pass `-f' with a filename")?;

    if db_type != BACKTYPE {
        return Err(format!("unsupported backend type `{}'", db_type));
    }

    let param_name = args.first().ok_or("parameter name required")?;

    // Resolve path
    let path = if file_path.starts_with('/') {
        PathBuf::from(file_path)
    } else {
        std::env::current_dir()
            .map_err(|e| e.to_string())?
            .join(file_path)
    };

    // Check if already tied
    {
        let params = TIED_PARAMS.lock().map_err(|_| "lock error")?;
        if params.contains_key(param_name) {
            return Err(format!("parameter {} is already tied", param_name));
        }
    }

    // Open database
    let db = GdbmDatabase::open(&path, readonly)?;
    let db = Arc::new(db);

    // Create tied parameter
    let tied = Arc::new(TiedGdbmParam::new(param_name.clone(), db));

    // Register
    {
        let mut params = TIED_PARAMS.lock().map_err(|_| "lock error")?;
        params.insert(param_name.clone(), tied);
    }

    Ok(())
}

/// `zuntie` builtin entry point — release a tied parameter.
/// Port of `bin_zuntie()` from Src/Modules/db_gdbm.c:201 — the C
/// source's `gdbmuntie()` (line 555) closes the database, frees
/// the hash table, and removes the entry from the tied-list.
///
/// Usage: `zuntie [-u] PARAM_NAME...`
pub fn zuntie(args: &[String], force_unset: bool) -> Result<(), String> {
    let mut errors = Vec::new();

    for param_name in args {
        let mut params = match TIED_PARAMS.lock() {
            Ok(p) => p,
            Err(_) => {
                errors.push(format!("cannot untie {}: lock error", param_name));
                continue;
            }
        };

        if !params.contains_key(param_name) {
            errors.push(format!("cannot untie {}", param_name));
            continue;
        }

        params.remove(param_name);
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors.join("\n"))
    }
}

/// `zgdbmpath` builtin entry point — print a tied parameter's path.
/// Port of `bin_zgdbmpath()` from Src/Modules/db_gdbm.c:236 — the
/// C source writes the result into `$REPLY`. Same convention.
///
/// Usage: `zgdbmpath PARAM_NAME`
pub fn zgdbmpath(param_name: &str) -> Result<String, String> {
    let params = TIED_PARAMS.lock().map_err(|_| "lock error")?;

    let tied = params
        .get(param_name)
        .ok_or_else(|| format!("no such parameter: {}", param_name))?;

    Ok(tied.db.path().to_string_lossy().to_string())
}

/// Is a given parameter currently tied to GDBM?
/// zshrs convenience — equivalent to scanning `tied_param_list`
/// in Src/Modules/db_gdbm.c.
pub fn is_gdbm_tied(param_name: &str) -> bool {
    if let Ok(params) = TIED_PARAMS.lock() {
        params.contains_key(param_name)
    } else {
        false
    }
}

/// Get the live `TiedGdbmParam` for a given name.
/// zshrs convenience — Src/Modules/db_gdbm.c uses
/// `getgdbmnode()` (line 407) for the same lookup at the C level.
pub fn get_tied_param(param_name: &str) -> Option<Arc<TiedGdbmParam>> {
    if let Ok(params) = TIED_PARAMS.lock() {
        params.get(param_name).cloned()
    } else {
        None
    }
}

/// Read a key from a tied parameter.
/// Port of `gdbmgetfn()` from Src/Modules/db_gdbm.c:282 — the
/// `getfn` slot the C source wires for `${db[key]}`.
pub fn gdbm_get(param_name: &str, key: &str) -> Option<String> {
    get_tied_param(param_name).and_then(|p| p.get(key))
}

/// Write a key to a tied parameter.
/// Port of `gdbmsetfn()` from Src/Modules/db_gdbm.c:347.
pub fn gdbm_set(param_name: &str, key: &str, value: &str) -> Result<(), String> {
    let param = get_tied_param(param_name)
        .ok_or_else(|| format!("not a tied gdbm hash: {}", param_name))?;
    param.set(key, value)
}

/// Delete a key from a tied parameter.
/// Port of `gdbmunsetfn()` from Src/Modules/db_gdbm.c:399 — used
/// by `unset 'db[key]'`.
pub fn gdbm_delete(param_name: &str, key: &str) -> Result<(), String> {
    let param = get_tied_param(param_name)
        .ok_or_else(|| format!("not a tied gdbm hash: {}", param_name))?;
    param.delete(key)
}

/// Get every key in a tied parameter.
/// Port of `scangdbmkeys()` from Src/Modules/db_gdbm.c:442 — the
/// `scanfn` slot the C source wires for `${(k)db}`.
pub fn gdbm_keys(param_name: &str) -> Option<Vec<String>> {
    get_tied_param(param_name).map(|p| p.keys())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    #[cfg(feature = "gdbm")]
    fn test_gdbm_basic_operations() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.gdbm");

        // Open database
        let db = GdbmDatabase::open(&db_path, false).unwrap();

        // Set and get
        db.set("key1", "value1").unwrap();
        assert_eq!(db.get("key1"), Some("value1".to_string()));

        // Non-existent key
        assert_eq!(db.get("nonexistent"), None);

        // Delete
        db.delete("key1").unwrap();
        assert_eq!(db.get("key1"), None);

        // Multiple keys
        db.set("a", "1").unwrap();
        db.set("b", "2").unwrap();
        db.set("c", "3").unwrap();

        let keys = db.keys();
        assert_eq!(keys.len(), 3);
        assert!(keys.contains(&"a".to_string()));
        assert!(keys.contains(&"b".to_string()));
        assert!(keys.contains(&"c".to_string()));

        // Clear
        db.clear().unwrap();
        assert_eq!(db.keys().len(), 0);
    }

    #[test]
    #[cfg(feature = "gdbm")]
    fn test_tied_param() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("tied.gdbm");

        let db = Arc::new(GdbmDatabase::open(&db_path, false).unwrap());
        let tied = TiedGdbmParam::new("mydb".to_string(), db);

        tied.set("foo", "bar").unwrap();
        assert_eq!(tied.get("foo"), Some("bar".to_string()));

        let hash = tied.to_hash();
        assert_eq!(hash.get("foo"), Some(&"bar".to_string()));
    }
}