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