wasi_virt_layer-cli 0.5.8

CLI for the wasi_virt_layer crate
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
//! Provides mechanisms to generate unique non-colliding crate identifiers and exports for WASM modules.

use crate::util::WasmName;

/// Represents a unique, non-colliding name element within the generated WASM structure.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum UniqueName<'a, 'b> {
    /// A unique name corresponding to shared global functions.
    SharedGlobalFns(&'a SharedGlobalFnsName),
    /// A unique name corresponding to shared global functions for a specific target.
    SharedGlobalFnsForTarget(&'a SharedGlobalFnsName, &'a str),
    /// A unique name corresponding to WASI P1 ABI function replacements.
    Wasip1ABI(&'a Wasip1ABIName<'b>),
    /// A unique name corresponding to thread spawning logic.
    ThreadsSpawn(&'a ThreadsSpawnName<'b>),
    /// A unique name corresponding to special initialization or reset functions.
    SpecialFunc(&'a SpecialFuncUniqueName<'b>),
    /// A unique name corresponding to memory bridge interactions.
    Memory(&'a MemoryUniqueName<'b>),
}

macro_rules! fmt {
    (
        Wasip1ABI; $($arg:tt)*
    ) => {
        paste::paste! {
            {
                format!(
                    "__wasip1_vfs_{}{}",
                    { $crate::unique_name::UniqueName::WASIP1_ABI },
                    format!($($arg)*)
                )
            }
        }
    };

    (
        $_ty:ty; $($arg:tt)*
    ) => {
        paste::paste! {
            {
                format!(
                    "__wasip1_vfs_{}{}",
                    { $crate::unique_name::UniqueName:: [<$_ty:snake:upper>] },
                    format!($($arg)*)
                )
            }
        }
    };

    (
        $($arg:tt)*
    ) => {
        { format!("__wasip1_vfs_{}", format!($($arg)*)) }
    };
}
#[cfg(test)]
pub(crate) use fmt;
use strum::EnumCount;

#[cfg(test)]
mod tests {
    #[test]
    fn test_unique_name_to_str() {
        let r = "abc";
        let fmt = super::fmt!("{r}def");
        assert_eq!(fmt, format!("{}abcdef", super::UniqueName::PREFIX));
    }

    #[test]
    fn test_unique_name_start_alternative() {
        let fmt = super::fmt!(StartAlternative; "suffix");
        assert_eq!(
            fmt,
            format!("{}start_alt_suffix", super::UniqueName::PREFIX)
        );
    }

    #[test]
    fn test_unique_name_threads_import_anchor_is_prefixed() {
        let t = crate::unique_name::ThreadsSpawnName::ImportAnchor("thread-spawn");
        let s = super::UniqueName::ThreadsSpawn(&t).to_string();
        assert_eq!(s, "__wasip1_vfs_thread-spawn_import_anchor");
    }
}

impl UniqueName<'_, '_> {
    /// The root module namespace for core VFS operations.
    pub const CORE_MODULE_ROOT: &'static str = "wasip1-vfs:host/virtual-file-system-wasip1-core";
    /// The root module namespace for thread imports.
    pub const THREADS_MODULE_ROOT: &'static str =
        "wasip1-vfs:host/virtual-file-system-wasip1-threads-import";
    /// The root module namespace for thread exports.
    pub const THREADS_EXPORT_MODULE_ROOT: &'static str =
        "wasip1-vfs:host/virtual-file-system-wasip1-threads-export#wasi-thread-start";
    /// The module namespace for non-recursive execution of snapshot preview 1.
    pub const CORE_NON_RECURSIVE_MODULE_ROOT: &'static str = "non_recursive_wasi_snapshot_preview1";
    /// The namespace identifier for the virtual file system.
    pub const NAMESPACE: &'static str = "wasip1-vfs";
    /// The crate name for the Wasi Virt Layer library itself.
    pub const CRATE_NAME: &'static str = "wasi_virt_layer";
    /// The typical WASI ABI module string.
    pub const WASIP1_ABI_MODULE: &'static str = "wasi_snapshot_preview1";
    /// An alternative module string for WASI preview 1.
    pub const WASIP1_ABI_MODULE_ALT: &'static str = "wasip1";
    /// The common WASI thread module string.
    pub const WASIP1_THREADS_ABI_MODULE: &'static str = "wasi";
    /// An alternative module string for WASI threads.
    pub const WASIP1_THREADS_ABI_MODULE_ALT: &'static str = "wasip1-threads";

    /// The prefix used for globally distinct Wasm elements generated by this tool.
    pub const PREFIX: &'static str = "__wasip1_vfs_";

    /// Constant representing the start alternative name prefix.
    pub const START_ALTERNATIVE: &'static str = "start_alt_";
    /// Constant representing shared global functions prefix.
    pub const SHARED_GLOBAL_FNS: &'static str = "memory_grow_";
    /// Constant representing the special func prefix identifier.
    /// todo!(); to identified unique names
    pub const SPECIAL_FUNC: &'static str = "";
    /// Constant representing the WASIP1 ABI prefix identifier.
    /// todo!(); to identified unique names
    pub const WASIP1_ABI: &'static str = "";
    /// Constant representing the threads spawn prefix identifier.
    /// todo!(); to identified unique names
    pub const THREADS_SPAWN: &'static str = "";
    /// Constant representing the memory operation prefix identifier.
    /// todo!(); to identified unique names
    pub const MEMORY: &'static str = "";

    fn to_str(&self) -> String {
        match self {
            UniqueName::SharedGlobalFns(func) => {
                let func_name = func.as_ref();
                match func {
                    SharedGlobalFnsName::Locker(n) => {
                        fmt!(SharedGlobalFns; "{func_name}_{n}")
                    }
                    _ => fmt!(SharedGlobalFns; "{func_name}"),
                }
            }
            UniqueName::SharedGlobalFnsForTarget(func, target) => {
                let func_name = func.as_ref();
                let normalized_target = target.replace('-', "_");
                let op = UniqueName::SHARED_GLOBAL_FNS;
                match func {
                    SharedGlobalFnsName::Locker(n) => {
                        fmt!("{normalized_target}_{op}{func_name}_{n}")
                    }
                    _ => fmt!("{normalized_target}_{op}{func_name}"),
                }
            }
            UniqueName::Wasip1ABI(t) => {
                let name = t.as_ref();
                match t {
                    Wasip1ABIName::SelfDefault { import } => fmt!(Wasip1ABI; "{name}_{import}"),
                    Wasip1ABIName::TargetTemporal { wasm, import } => {
                        fmt!(Wasip1ABI; "{wasm}_{import}")
                    }
                }
            }
            UniqueName::ThreadsSpawn(t) => {
                let name = t.as_ref();
                match t {
                    ThreadsSpawnName::ImportAnchor(wasm) => {
                        fmt!(ThreadsSpawn; "{wasm}_{name}")
                    }
                    ThreadsSpawnName::WasiThreadStart(wasm)
                    | ThreadsSpawnName::WasiThreadStartAnchor(wasm) => {
                        fmt!(ThreadsSpawn; "{wasm}_{name}")
                    }
                    ThreadsSpawnName::WasiThreadStartDestination(wasm)
                    | ThreadsSpawnName::WasiThreadSpawn(wasm) => {
                        fmt!(ThreadsSpawn; "{name}_{wasm}")
                    }
                    _ => {
                        fmt!(ThreadsSpawn; "{name}")
                    }
                }
            }
            UniqueName::SpecialFunc(t) => {
                let name = t.as_ref();
                match t {
                    SpecialFuncUniqueName::Resetter(wasm) => {
                        fmt!(SpecialFunc; "{wasm}_{name}")
                    }
                    SpecialFuncUniqueName::Start(wasm) => {
                        fmt!(SpecialFunc; "{wasm}__{name}")
                    }
                    SpecialFuncUniqueName::MainVoid(wasm) => {
                        fmt!(SpecialFunc; "{wasm}___{name}")
                    }
                    SpecialFuncUniqueName::Reset(wasm) => {
                        fmt!(SpecialFunc; "{wasm}_{name}")
                    }
                    _ => {
                        fmt!(SpecialFunc; "{name}")
                    }
                }
            }
            UniqueName::Memory(t) => {
                let name = t.as_ref();
                match t {
                    MemoryUniqueName::MemoryCopyFrom(wasm)
                    | MemoryUniqueName::MemoryCopyTo(wasm)
                    | MemoryUniqueName::MemoryTrap(wasm)
                    | MemoryUniqueName::MemoryTrapAnchor(wasm)
                    | MemoryUniqueName::MemoryDirector(wasm)
                    | MemoryUniqueName::MemoryDirectorAnchor(wasm)
                    | MemoryUniqueName::Memory(wasm) => {
                        fmt!(Memory; "{wasm}_{name}")
                    }
                }
            }
        }
    }
}

/// A marker trait for structured references that can be converted to strings for unique WASM names.
pub trait UniqueNameMarker: ToString + Copy {}

impl UniqueNameMarker for &'_ UniqueName<'_, '_> {}

impl ToString for &'_ UniqueName<'_, '_> {
    fn to_string(&self) -> String {
        self.to_str()
    }
}

impl ToString for UniqueName<'_, '_> {
    fn to_string(&self) -> String {
        self.to_str()
    }
}

impl<'a> From<&'a SharedGlobalFnsName> for UniqueName<'_, 'a> {
    fn from(value: &'a SharedGlobalFnsName) -> Self {
        UniqueName::SharedGlobalFns(value)
    }
}

impl<'a> From<&'a Wasip1ABIName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a Wasip1ABIName<'_>) -> Self {
        UniqueName::Wasip1ABI(value)
    }
}

impl<'a> From<&'a ThreadsSpawnName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a ThreadsSpawnName<'_>) -> Self {
        UniqueName::ThreadsSpawn(value)
    }
}

impl<'a> From<&'a SpecialFuncUniqueName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a SpecialFuncUniqueName<'_>) -> Self {
        UniqueName::SpecialFunc(value)
    }
}

impl<'a> From<&'a MemoryUniqueName<'_>> for UniqueName<'_, 'a> {
    fn from(value: &'a MemoryUniqueName<'_>) -> Self {
        UniqueName::Memory(value)
    }
}

/// To verify whether an identical entry exists
/// in the destination for generating UniqueName, prepare an iterator.
#[allow(dead_code)]
trait UniqueNameIterator<'a>
where
    Self: Sized,
{
    type REQUIRED;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self>;
}

impl<'a> UniqueNameIterator<'a> for WasmName {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![require.clone()];
        assert_eq!(v.len(), 1);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for SharedGlobalFnsName {
    type REQUIRED = usize;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            SharedGlobalFnsName::GlobalAltSet,
            SharedGlobalFnsName::GlobalAltGet,
            SharedGlobalFnsName::GlobalAltGetNoWait,
            SharedGlobalFnsName::GlobalAltInitOnce,
            SharedGlobalFnsName::GlobalAltPos,
            SharedGlobalFnsName::Locker(*require),
            SharedGlobalFnsName::LockerBase,
            SharedGlobalFnsName::MemoryGrowAlt,
            SharedGlobalFnsName::GlobalAltSetWithLock,
        ];
        assert_eq!(v.len(), SharedGlobalFnsName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for Wasip1ABIName<'a> {
    type REQUIRED = (WasmName, &'a str);

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let (wasm, import) = require;
        let v = vec![
            Wasip1ABIName::SelfDefault { import },
            Wasip1ABIName::TargetTemporal { import, wasm },
        ];
        assert_eq!(v.len(), Wasip1ABIName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for ThreadsSpawnName<'a> {
    type REQUIRED = (WasmName, &'a str);

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let (wasm, import) = require;
        let v = vec![
            ThreadsSpawnName::ImportAnchor(import),
            ThreadsSpawnName::IsRootSpawn,
            ThreadsSpawnName::WasiThreadSpawnSelf,
            ThreadsSpawnName::SelfWasiThreadStart,
            ThreadsSpawnName::SelfWasiThreadStartAnchor,
            ThreadsSpawnName::RealThreadSpawnFn,
            ThreadsSpawnName::WasiThreadStartEntry,
            ThreadsSpawnName::WasiThreadSpawn(wasm),
            ThreadsSpawnName::WasiThreadStart(wasm),
            ThreadsSpawnName::WasiThreadStartAnchor(wasm),
            ThreadsSpawnName::WasiThreadStartDestination(wasm),
            ThreadsSpawnName::ThreadInitializer,
            ThreadsSpawnName::OldStart,
        ];
        assert_eq!(v.len(), ThreadsSpawnName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for SpecialFuncUniqueName<'a> {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            SpecialFuncUniqueName::Resetter(require),
            SpecialFuncUniqueName::ResetOnThread,
            SpecialFuncUniqueName::ResetOnThreadOnce,
            SpecialFuncUniqueName::StartInitOld,
            SpecialFuncUniqueName::Start(require),
            SpecialFuncUniqueName::MainVoid(require),
            SpecialFuncUniqueName::Reset(require),
        ];
        assert_eq!(v.len(), SpecialFuncUniqueName::COUNT);
        v
    }
}

impl<'a> UniqueNameIterator<'a> for MemoryUniqueName<'a> {
    type REQUIRED = WasmName;

    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
        let v = vec![
            MemoryUniqueName::MemoryCopyFrom(require),
            MemoryUniqueName::MemoryCopyTo(require),
            MemoryUniqueName::MemoryTrap(require),
            MemoryUniqueName::MemoryTrapAnchor(require),
            MemoryUniqueName::MemoryDirector(require),
            MemoryUniqueName::MemoryDirectorAnchor(require),
            MemoryUniqueName::Memory(require),
        ];
        assert_eq!(v.len(), MemoryUniqueName::COUNT);
        v
    }
}

#[cfg(test)]
mod unique_name_iterator_tests {
    use std::collections::HashSet;

    use crate::util::WasmNameHolder;

    use super::*;

    #[test]
    fn test_unique_name_iterator_start_alternative() {
        let holder = WasmNameHolder::new(vec!["#original_import".into()].into_boxed_slice());
        let require_import = holder.iter().next().unwrap();
        let require_name = "#original_name";
        let require_num = 5;
        let requires = (require_import.clone(), require_name);
        let t3 = SharedGlobalFnsName::iter_unique_names(&require_num);
        let t4 = Wasip1ABIName::iter_unique_names(&requires);
        let t5 = ThreadsSpawnName::iter_unique_names(&requires);
        let t6 = SpecialFuncUniqueName::iter_unique_names(&require_import);
        let t7 = MemoryUniqueName::iter_unique_names(&require_import);
        let t3 = t3.iter().map(Into::into);
        let t4 = t4.iter().map(Into::into);
        let t5 = t5.iter().map(Into::into);
        let t6 = t6.iter().map(Into::into);
        let t7 = t7.iter().map(Into::into);
        let t = t3
            .chain(t4)
            .chain(t5)
            .chain(t6)
            .chain(t7)
            .collect::<Vec<UniqueName>>();

        // Check whether there is the same output destination
        let mut seen = std::collections::HashMap::new();
        let mut duplicates = HashSet::new();
        for t in &t {
            let name = t.to_string();
            if seen.insert(name.clone(), t).is_some() {
                duplicates.insert(t);
                duplicates.insert(seen.get(&name).unwrap());
            }
        }
        assert!(
            duplicates.is_empty(),
            "Found duplicate unique names: {duplicates:?}",
        );
    }
}

#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
#[strum(serialize_all = "snake_case")]
/// Name for Wasip1 ABI.
pub enum Wasip1ABIName<'a> {
    #[strum(serialize = "__self")]
    /// Reference to a self-contained import.
    SelfDefault {
        /// Identifier string representation of the import.
        import: &'a str,
    },
    #[strum(serialize = "")]
    /// Temporarily constructed linking to a specified module during intermediate compilation.
    TargetTemporal {
        /// Specific wasm module binding origin.
        wasm: &'a WasmName,
        /// Specific imported signature target.
        import: &'a str,
    },
}

#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq, strum::VariantNames)]
#[strum(serialize_all = "snake_case")]
/// Name for memory.
pub enum MemoryUniqueName<'a> {
    /// Copies contents from Target Memory to VFS Memory.
    MemoryCopyFrom(&'a WasmName),
    /// Copies contents from VFS Memory to Target Memory.
    MemoryCopyTo(&'a WasmName),
    /// Emplaces a runtime trap to deduce pointer arithmetic limits.
    MemoryTrap(&'a WasmName),
    /// Serves as a linked anchor ensuring `MemoryTrap` preserves its compiled identity.
    MemoryTrapAnchor(&'a WasmName),
    /// Wraps dynamic function dispatch controlling pointers to merged targets.
    MemoryDirector(&'a WasmName),
    /// Serves as a linked anchor preserving the compiled `MemoryDirector` identity.
    MemoryDirectorAnchor(&'a WasmName),
    /// The fundamental reference identifying the exported memory location of the underlying module.
    Memory(&'a WasmName),
}

/// Shared global context.
#[derive(Debug, Default)]
pub struct SharedGlobal {
    #[allow(dead_code)]
    before_globals: Option<usize>,
    #[allow(dead_code)]
    before_memories: Option<usize>,
}

/// Enum containing identifiers for alternative shared global function replacements and locker usages.
#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
#[strum(serialize_all = "snake_case")]
pub enum SharedGlobalFnsName {
    /// Wrapper replacing a global variable assignment internally without locking overhead.
    GlobalAltSet,
    /// Global alt set with lock.
    GlobalAltSetWithLock,
    /// Thread-safe wrapper evaluating and retrieving the global value.
    GlobalAltGet,
    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
    GlobalAltGetNoWait,
    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
    GlobalAltInitOnce,
    /// Utility function yielding the exact offset index memory location storing the global proxy.
    GlobalAltPos,
    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
    Locker(usize),
    #[strum(serialize = "locker")]
    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
    LockerBase,
    #[strum(serialize = "alt")]
    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
    MemoryGrowAlt,
}

#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
#[strum(serialize_all = "snake_case")]
/// Name for special func.
pub enum SpecialFuncUniqueName<'a> {
    /// Function that initializes memory resets.
    Resetter(&'a WasmName),
    /// Function that handles thread resets.
    ResetOnThread,
    /// Function that ensures thread reset occurs precisely once.
    ResetOnThreadOnce,
    /// Preserved original initialization function.
    StartInitOld,
    /// The primary start wrapper routine function.
    Start(&'a WasmName),
    /// Early application termination safe wrapper function.
    MainVoid(&'a WasmName),
    /// State reset function generated for given module.
    Reset(&'a WasmName),
}

#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
#[strum(serialize_all = "snake_case")]
/// Name for threads spawn.
pub enum ThreadsSpawnName<'a> {
    /// Custom spawn anchor injected for bridging definitions.
    ImportAnchor(&'a str),
    /// Flag indicating whether the current instance is the root spawner thread.
    IsRootSpawn,
    #[strum(serialize = "wasi_thread_spawn___self")]
    /// Function identifier for native WASI spawn capability.
    WasiThreadSpawnSelf,
    #[strum(serialize = "__self_wasi_thread_start")]
    /// The starting routine mapping on thread creation execution.
    SelfWasiThreadStart,
    #[strum(serialize = "__self_wasi_thread_start_anchor")]
    /// The underlying static bridge to anchor thread origins.
    SelfWasiThreadStartAnchor,
    /// Low level function signature to actually request system spawn.
    RealThreadSpawnFn,
    /// Entry stub function used when entering newly spawned routines.
    WasiThreadStartEntry,
    /// Specialized start function per WASM module target.
    WasiThreadStart(&'a WasmName),
    #[strum(serialize = "wasi_thread_start")]
    /// Target resolving memory start capabilities per component.
    WasiThreadStartDestination(&'a WasmName),
    /// Wraps dynamic spawn allocations over components.
    WasiThreadSpawn(&'a WasmName),
    /// Cross-linking anchor marking a spawn location.
    WasiThreadStartAnchor(&'a WasmName),
    /// Initializer function for thread memory limits scaling.
    ThreadInitializer,
    /// Reference to the existing deprecated `_start` handling.
    OldStart,
}