Skip to main content

wasi_virt_layer_cli/
unique_name.rs

1//! Provides mechanisms to generate unique non-colliding crate identifiers and exports for WASM modules.
2
3use crate::util::WasmName;
4
5/// Represents a unique, non-colliding name element within the generated WASM structure.
6#[derive(Debug, Eq, PartialEq, Hash)]
7pub enum UniqueName<'a, 'b> {
8    /// A unique name corresponding to shared global functions.
9    SharedGlobalFns(&'a SharedGlobalFnsName),
10    /// A unique name corresponding to shared global functions for a specific target.
11    SharedGlobalFnsForTarget(&'a SharedGlobalFnsName, &'a str),
12    /// A unique name corresponding to WASI P1 ABI function replacements.
13    Wasip1ABI(&'a Wasip1ABIName<'b>),
14    /// A unique name corresponding to thread spawning logic.
15    ThreadsSpawn(&'a ThreadsSpawnName<'b>),
16    /// A unique name corresponding to special initialization or reset functions.
17    SpecialFunc(&'a SpecialFuncUniqueName<'b>),
18    /// A unique name corresponding to memory bridge interactions.
19    Memory(&'a MemoryUniqueName<'b>),
20}
21
22macro_rules! fmt {
23    (
24        Wasip1ABI; $($arg:tt)*
25    ) => {
26        paste::paste! {
27            {
28                format!(
29                    "__wasip1_vfs_{}{}",
30                    { $crate::unique_name::UniqueName::WASIP1_ABI },
31                    format!($($arg)*)
32                )
33            }
34        }
35    };
36
37    (
38        $_ty:ty; $($arg:tt)*
39    ) => {
40        paste::paste! {
41            {
42                format!(
43                    "__wasip1_vfs_{}{}",
44                    { $crate::unique_name::UniqueName:: [<$_ty:snake:upper>] },
45                    format!($($arg)*)
46                )
47            }
48        }
49    };
50
51    (
52        $($arg:tt)*
53    ) => {
54        { format!("__wasip1_vfs_{}", format!($($arg)*)) }
55    };
56}
57pub(crate) use fmt;
58use strum::EnumCount;
59
60#[cfg(test)]
61mod tests {
62    #[test]
63    fn test_unique_name_to_str() {
64        let r = "abc";
65        let fmt = super::fmt!("{r}def");
66        assert_eq!(fmt, format!("{}abcdef", super::UniqueName::PREFIX));
67    }
68
69    #[test]
70    fn test_unique_name_start_alternative() {
71        let fmt = super::fmt!(StartAlternative; "suffix");
72        assert_eq!(
73            fmt,
74            format!("{}start_alt_suffix", super::UniqueName::PREFIX)
75        );
76    }
77
78    #[test]
79    fn test_unique_name_threads_import_anchor_is_prefixed() {
80        let t = crate::unique_name::ThreadsSpawnName::ImportAnchor("thread-spawn");
81        let s = super::UniqueName::ThreadsSpawn(&t).to_string();
82        assert_eq!(s, "__wasip1_vfs_thread-spawn_import_anchor");
83    }
84}
85
86impl UniqueName<'_, '_> {
87    /// The root module namespace for core VFS operations.
88    pub const CORE_MODULE_ROOT: &'static str = "wasip1-vfs:host/virtual-file-system-wasip1-core";
89    /// The root module namespace for thread imports.
90    pub const THREADS_MODULE_ROOT: &'static str =
91        "wasip1-vfs:host/virtual-file-system-wasip1-threads-import";
92    /// The root module namespace for thread exports.
93    pub const THREADS_EXPORT_MODULE_ROOT: &'static str =
94        "wasip1-vfs:host/virtual-file-system-wasip1-threads-export#wasi-thread-start";
95    /// The module namespace for non-recursive execution of snapshot preview 1.
96    pub const CORE_NON_RECURSIVE_MODULE_ROOT: &'static str = "non_recursive_wasi_snapshot_preview1";
97    /// The namespace identifier for the virtual file system.
98    pub const NAMESPACE: &'static str = "wasip1-vfs";
99    /// The crate name for the Wasi Virt Layer library itself.
100    pub const CRATE_NAME: &'static str = "wasi_virt_layer";
101    /// The typical WASI ABI module string.
102    pub const WASIP1_ABI_MODULE: &'static str = "wasi_snapshot_preview1";
103    /// An alternative module string for WASI preview 1.
104    pub const WASIP1_ABI_MODULE_ALT: &'static str = "wasip1";
105    /// The common WASI thread module string.
106    pub const WASIP1_THREADS_ABI_MODULE: &'static str = "wasi";
107    /// An alternative module string for WASI threads.
108    pub const WASIP1_THREADS_ABI_MODULE_ALT: &'static str = "wasip1-threads";
109
110    /// The prefix used for globally distinct Wasm elements generated by this tool.
111    pub const PREFIX: &'static str = "__wasip1_vfs_";
112
113    /// Constant representing the start alternative name prefix.
114    pub const START_ALTERNATIVE: &'static str = "start_alt_";
115    /// Constant representing shared global functions prefix.
116    pub const SHARED_GLOBAL_FNS: &'static str = "memory_grow_";
117    /// Constant representing the special func prefix identifier.
118    /// todo!(); to identified unique names
119    pub const SPECIAL_FUNC: &'static str = "";
120    /// Constant representing the WASIP1 ABI prefix identifier.
121    /// todo!(); to identified unique names
122    pub const WASIP1_ABI: &'static str = "";
123    /// Constant representing the threads spawn prefix identifier.
124    /// todo!(); to identified unique names
125    pub const THREADS_SPAWN: &'static str = "";
126    /// Constant representing the memory operation prefix identifier.
127    /// todo!(); to identified unique names
128    pub const MEMORY: &'static str = "";
129
130    fn to_str(&self) -> String {
131        match self {
132            UniqueName::SharedGlobalFns(func) => {
133                let func_name = func.as_ref();
134                match func {
135                    SharedGlobalFnsName::Locker(n) => {
136                        fmt!(SharedGlobalFns; "{func_name}_{n}")
137                    }
138                    _ => fmt!(SharedGlobalFns; "{func_name}"),
139                }
140            }
141            UniqueName::SharedGlobalFnsForTarget(func, target) => {
142                let func_name = func.as_ref();
143                let normalized_target = target.replace('-', "_");
144                let op = UniqueName::SHARED_GLOBAL_FNS;
145                match func {
146                    SharedGlobalFnsName::Locker(n) => {
147                        fmt!("{normalized_target}_{op}{func_name}_{n}")
148                    }
149                    _ => fmt!("{normalized_target}_{op}{func_name}"),
150                }
151            }
152            UniqueName::Wasip1ABI(t) => {
153                let name = t.as_ref();
154                match t {
155                    Wasip1ABIName::SelfDefault { import } => fmt!(Wasip1ABI; "{name}_{import}"),
156                    Wasip1ABIName::TargetTemporal { wasm, import } => {
157                        fmt!(Wasip1ABI; "{wasm}_{import}")
158                    }
159                }
160            }
161            UniqueName::ThreadsSpawn(t) => {
162                let name = t.as_ref();
163                match t {
164                    ThreadsSpawnName::ImportAnchor(wasm) => {
165                        fmt!(ThreadsSpawn; "{wasm}_{name}")
166                    }
167                    ThreadsSpawnName::WasiThreadStart(wasm)
168                    | ThreadsSpawnName::WasiThreadStartAnchor(wasm) => {
169                        fmt!(ThreadsSpawn; "{wasm}_{name}")
170                    }
171                    ThreadsSpawnName::WasiThreadStartDestination(wasm)
172                    | ThreadsSpawnName::WasiThreadSpawn(wasm) => {
173                        fmt!(ThreadsSpawn; "{name}_{wasm}")
174                    }
175                    _ => {
176                        fmt!(ThreadsSpawn; "{name}")
177                    }
178                }
179            }
180            UniqueName::SpecialFunc(t) => {
181                let name = t.as_ref();
182                match t {
183                    SpecialFuncUniqueName::Resetter(wasm) => {
184                        fmt!(SpecialFunc; "{wasm}_{name}")
185                    }
186                    SpecialFuncUniqueName::Start(wasm) => {
187                        fmt!(SpecialFunc; "{wasm}__{name}")
188                    }
189                    SpecialFuncUniqueName::MainVoid(wasm) => {
190                        fmt!(SpecialFunc; "{wasm}___{name}")
191                    }
192                    SpecialFuncUniqueName::Reset(wasm) => {
193                        fmt!(SpecialFunc; "{wasm}_{name}")
194                    }
195                    _ => {
196                        fmt!(SpecialFunc; "{name}")
197                    }
198                }
199            }
200            UniqueName::Memory(t) => {
201                let name = t.as_ref();
202                match t {
203                    MemoryUniqueName::MemoryCopyFrom(wasm)
204                    | MemoryUniqueName::MemoryCopyTo(wasm)
205                    | MemoryUniqueName::MemoryTrap(wasm)
206                    | MemoryUniqueName::MemoryTrapAnchor(wasm)
207                    | MemoryUniqueName::MemoryDirector(wasm)
208                    | MemoryUniqueName::MemoryDirectorAnchor(wasm)
209                    | MemoryUniqueName::Memory(wasm) => {
210                        fmt!(Memory; "{wasm}_{name}")
211                    }
212                }
213            }
214        }
215    }
216}
217
218/// A marker trait for structured references that can be converted to strings for unique WASM names.
219pub trait UniqueNameMarker: ToString + Copy {}
220
221impl UniqueNameMarker for &'_ UniqueName<'_, '_> {}
222
223impl ToString for &'_ UniqueName<'_, '_> {
224    fn to_string(&self) -> String {
225        self.to_str()
226    }
227}
228
229impl ToString for UniqueName<'_, '_> {
230    fn to_string(&self) -> String {
231        self.to_str()
232    }
233}
234
235impl<'a> From<&'a SharedGlobalFnsName> for UniqueName<'_, 'a> {
236    fn from(value: &'a SharedGlobalFnsName) -> Self {
237        UniqueName::SharedGlobalFns(value)
238    }
239}
240
241impl<'a> From<&'a Wasip1ABIName<'_>> for UniqueName<'_, 'a> {
242    fn from(value: &'a Wasip1ABIName<'_>) -> Self {
243        UniqueName::Wasip1ABI(value)
244    }
245}
246
247impl<'a> From<&'a ThreadsSpawnName<'_>> for UniqueName<'_, 'a> {
248    fn from(value: &'a ThreadsSpawnName<'_>) -> Self {
249        UniqueName::ThreadsSpawn(value)
250    }
251}
252
253impl<'a> From<&'a SpecialFuncUniqueName<'_>> for UniqueName<'_, 'a> {
254    fn from(value: &'a SpecialFuncUniqueName<'_>) -> Self {
255        UniqueName::SpecialFunc(value)
256    }
257}
258
259impl<'a> From<&'a MemoryUniqueName<'_>> for UniqueName<'_, 'a> {
260    fn from(value: &'a MemoryUniqueName<'_>) -> Self {
261        UniqueName::Memory(value)
262    }
263}
264
265/// To verify whether an identical entry exists
266/// in the destination for generating UniqueName, prepare an iterator.
267#[allow(dead_code)]
268trait UniqueNameIterator<'a>
269where
270    Self: Sized,
271{
272    type REQUIRED;
273
274    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self>;
275}
276
277impl<'a> UniqueNameIterator<'a> for WasmName {
278    type REQUIRED = WasmName;
279
280    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
281        let v = vec![require.clone()];
282        assert_eq!(v.len(), 1);
283        v
284    }
285}
286
287impl<'a> UniqueNameIterator<'a> for SharedGlobalFnsName {
288    type REQUIRED = usize;
289
290    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
291        let v = vec![
292            SharedGlobalFnsName::GlobalAltSet,
293            SharedGlobalFnsName::GlobalAltGet,
294            SharedGlobalFnsName::GlobalAltGetNoWait,
295            SharedGlobalFnsName::GlobalAltInitOnce,
296            SharedGlobalFnsName::GlobalAltPos,
297            SharedGlobalFnsName::Locker(*require),
298            SharedGlobalFnsName::LockerBase,
299            SharedGlobalFnsName::MemoryGrowAlt,
300            SharedGlobalFnsName::GlobalAltSetWithLock,
301        ];
302        assert_eq!(v.len(), SharedGlobalFnsName::COUNT);
303        v
304    }
305}
306
307impl<'a> UniqueNameIterator<'a> for Wasip1ABIName<'a> {
308    type REQUIRED = (WasmName, &'a str);
309
310    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
311        let (wasm, import) = require;
312        let v = vec![
313            Wasip1ABIName::SelfDefault { import },
314            Wasip1ABIName::TargetTemporal { import, wasm },
315        ];
316        assert_eq!(v.len(), Wasip1ABIName::COUNT);
317        v
318    }
319}
320
321impl<'a> UniqueNameIterator<'a> for ThreadsSpawnName<'a> {
322    type REQUIRED = (WasmName, &'a str);
323
324    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
325        let (wasm, import) = require;
326        let v = vec![
327            ThreadsSpawnName::ImportAnchor(import),
328            ThreadsSpawnName::IsRootSpawn,
329            ThreadsSpawnName::WasiThreadSpawnSelf,
330            ThreadsSpawnName::SelfWasiThreadStart,
331            ThreadsSpawnName::SelfWasiThreadStartAnchor,
332            ThreadsSpawnName::RealThreadSpawnFn,
333            ThreadsSpawnName::WasiThreadStartEntry,
334            ThreadsSpawnName::WasiThreadSpawn(wasm),
335            ThreadsSpawnName::WasiThreadStart(wasm),
336            ThreadsSpawnName::WasiThreadStartAnchor(wasm),
337            ThreadsSpawnName::WasiThreadStartDestination(wasm),
338            ThreadsSpawnName::ThreadInitializer,
339            ThreadsSpawnName::OldStart,
340        ];
341        assert_eq!(v.len(), ThreadsSpawnName::COUNT);
342        v
343    }
344}
345
346impl<'a> UniqueNameIterator<'a> for SpecialFuncUniqueName<'a> {
347    type REQUIRED = WasmName;
348
349    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
350        let v = vec![
351            SpecialFuncUniqueName::Resetter(require),
352            SpecialFuncUniqueName::ResetOnThread,
353            SpecialFuncUniqueName::ResetOnThreadOnce,
354            SpecialFuncUniqueName::StartInitOld,
355            SpecialFuncUniqueName::Start(require),
356            SpecialFuncUniqueName::MainVoid(require),
357            SpecialFuncUniqueName::Reset(require),
358        ];
359        assert_eq!(v.len(), SpecialFuncUniqueName::COUNT);
360        v
361    }
362}
363
364impl<'a> UniqueNameIterator<'a> for MemoryUniqueName<'a> {
365    type REQUIRED = WasmName;
366
367    fn iter_unique_names(require: &'a Self::REQUIRED) -> Vec<Self> {
368        let v = vec![
369            MemoryUniqueName::MemoryCopyFrom(require),
370            MemoryUniqueName::MemoryCopyTo(require),
371            MemoryUniqueName::MemoryTrap(require),
372            MemoryUniqueName::MemoryTrapAnchor(require),
373            MemoryUniqueName::MemoryDirector(require),
374            MemoryUniqueName::MemoryDirectorAnchor(require),
375            MemoryUniqueName::Memory(require),
376        ];
377        assert_eq!(v.len(), MemoryUniqueName::COUNT);
378        v
379    }
380}
381
382#[cfg(test)]
383mod unique_name_iterator_tests {
384    use std::collections::HashSet;
385
386    use crate::util::WasmNameHolder;
387
388    use super::*;
389
390    #[test]
391    fn test_unique_name_iterator_start_alternative() {
392        let holder = WasmNameHolder::new(vec!["#original_import".into()].into_boxed_slice());
393        let require_import = holder.iter().next().unwrap();
394        let require_name = "#original_name";
395        let require_num = 5;
396        let requires = (require_import.clone(), require_name);
397        let t3 = SharedGlobalFnsName::iter_unique_names(&require_num);
398        let t4 = Wasip1ABIName::iter_unique_names(&requires);
399        let t5 = ThreadsSpawnName::iter_unique_names(&requires);
400        let t6 = SpecialFuncUniqueName::iter_unique_names(&require_import);
401        let t7 = MemoryUniqueName::iter_unique_names(&require_import);
402        let t3 = t3.iter().map(Into::into);
403        let t4 = t4.iter().map(Into::into);
404        let t5 = t5.iter().map(Into::into);
405        let t6 = t6.iter().map(Into::into);
406        let t7 = t7.iter().map(Into::into);
407        let t = t3
408            .chain(t4)
409            .chain(t5)
410            .chain(t6)
411            .chain(t7)
412            .collect::<Vec<UniqueName>>();
413
414        // Check whether there is the same output destination
415        let mut seen = std::collections::HashMap::new();
416        let mut duplicates = HashSet::new();
417        for t in &t {
418            let name = t.to_string();
419            if seen.insert(name.clone(), t).is_some() {
420                duplicates.insert(t);
421                duplicates.insert(seen.get(&name).unwrap());
422            }
423        }
424        assert!(
425            duplicates.is_empty(),
426            "Found duplicate unique names: {duplicates:?}",
427        );
428    }
429}
430
431#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
432#[strum(serialize_all = "snake_case")]
433pub enum Wasip1ABIName<'a> {
434    #[strum(serialize = "__self")]
435    /// Reference to a self-contained import.
436    SelfDefault {
437        /// Identifier string representation of the import.
438        import: &'a str,
439    },
440    #[strum(serialize = "")]
441    /// Temporarily constructed linking to a specified module during intermediate compilation.
442    TargetTemporal {
443        /// Specific wasm module binding origin.
444        wasm: &'a WasmName,
445        /// Specific imported signature target.
446        import: &'a str,
447    },
448}
449
450#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq, strum::VariantNames)]
451#[strum(serialize_all = "snake_case")]
452pub enum MemoryUniqueName<'a> {
453    /// Copies contents from Target Memory to VFS Memory.
454    MemoryCopyFrom(&'a WasmName),
455    /// Copies contents from VFS Memory to Target Memory.
456    MemoryCopyTo(&'a WasmName),
457    /// Emplaces a runtime trap to deduce pointer arithmetic limits.
458    MemoryTrap(&'a WasmName),
459    /// Serves as a linked anchor ensuring `MemoryTrap` preserves its compiled identity.
460    MemoryTrapAnchor(&'a WasmName),
461    /// Wraps dynamic function dispatch controlling pointers to merged targets.
462    MemoryDirector(&'a WasmName),
463    /// Serves as a linked anchor preserving the compiled `MemoryDirector` identity.
464    MemoryDirectorAnchor(&'a WasmName),
465    /// The fundamental reference identifying the exported memory location of the underlying module.
466    Memory(&'a WasmName),
467}
468
469#[derive(Debug, Default)]
470pub struct SharedGlobal {
471    before_globals: Option<usize>,
472    before_memories: Option<usize>,
473}
474
475/// Enum containing identifiers for alternative shared global function replacements and locker usages.
476#[derive(Debug, strum::AsRefStr, strum::EnumCount, PartialEq, Eq, Hash)]
477#[strum(serialize_all = "snake_case")]
478pub enum SharedGlobalFnsName {
479    /// Wrapper replacing a global variable assignment internally without locking overhead.
480    GlobalAltSet,
481    GlobalAltSetWithLock,
482    /// Thread-safe wrapper evaluating and retrieving the global value.
483    GlobalAltGet,
484    /// Fast wrapper evaluating the global value bypassing thread synchronization lock operations.
485    GlobalAltGetNoWait,
486    /// Singleton wrapper assigning an initializing value solely on a one-time startup sequence.
487    GlobalAltInitOnce,
488    /// Utility function yielding the exact offset index memory location storing the global proxy.
489    GlobalAltPos,
490    /// Locking function instance controlling concurrent memory accesses for a specific table identified by index.
491    Locker(usize),
492    #[strum(serialize = "locker")]
493    /// Uniquely identified primary initial lock mechanism controlling baseline single-memory environments.
494    LockerBase,
495    #[strum(serialize = "alt")]
496    /// Replaced function logic hooking WebAssembly natively executed `memory.grow` allocation algorithms.
497    MemoryGrowAlt,
498}
499
500#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
501#[strum(serialize_all = "snake_case")]
502pub enum SpecialFuncUniqueName<'a> {
503    /// Function that initializes memory resets.
504    Resetter(&'a WasmName),
505    /// Function that handles thread resets.
506    ResetOnThread,
507    /// Function that ensures thread reset occurs precisely once.
508    ResetOnThreadOnce,
509    /// Preserved original initialization function.
510    StartInitOld,
511    /// The primary start wrapper routine function.
512    Start(&'a WasmName),
513    /// Early application termination safe wrapper function.
514    MainVoid(&'a WasmName),
515    /// State reset function generated for given module.
516    Reset(&'a WasmName),
517}
518
519#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
520#[strum(serialize_all = "snake_case")]
521pub enum ThreadsSpawnName<'a> {
522    /// Custom spawn anchor injected for bridging definitions.
523    ImportAnchor(&'a str),
524    /// Flag indicating whether the current instance is the root spawner thread.
525    IsRootSpawn,
526    #[strum(serialize = "wasi_thread_spawn___self")]
527    /// Function identifier for native WASI spawn capability.
528    WasiThreadSpawnSelf,
529    #[strum(serialize = "__self_wasi_thread_start")]
530    /// The starting routine mapping on thread creation execution.
531    SelfWasiThreadStart,
532    #[strum(serialize = "__self_wasi_thread_start_anchor")]
533    /// The underlying static bridge to anchor thread origins.
534    SelfWasiThreadStartAnchor,
535    /// Low level function signature to actually request system spawn.
536    RealThreadSpawnFn,
537    /// Entry stub function used when entering newly spawned routines.
538    WasiThreadStartEntry,
539    /// Specialized start function per WASM module target.
540    WasiThreadStart(&'a WasmName),
541    #[strum(serialize = "wasi_thread_start")]
542    /// Target resolving memory start capabilities per component.
543    WasiThreadStartDestination(&'a WasmName),
544    /// Wraps dynamic spawn allocations over components.
545    WasiThreadSpawn(&'a WasmName),
546    /// Cross-linking anchor marking a spawn location.
547    WasiThreadStartAnchor(&'a WasmName),
548    /// Initializer function for thread memory limits scaling.
549    ThreadInitializer,
550    /// Reference to the existing deprecated `_start` handling.
551    OldStart,
552}