wasi_virt_layer_cli/
util.rs

1use std::{
2    borrow::Borrow,
3    collections::HashMap,
4    fmt::Debug,
5    path::{Path, PathBuf},
6    str::FromStr,
7    sync::atomic::AtomicUsize,
8};
9
10use compact_str::CompactString;
11use eyre::{Context as _, ContextCompat as _};
12use itertools::Itertools;
13use walrus::{ir::InstrSeqId, *};
14
15use crate::{
16    args::TargetMemoryType,
17    instrs::{InstrRead, InstrRewrite as _},
18};
19
20#[allow(dead_code)]
21pub(crate) trait WalrusUtilImport: Debug {
22    fn find_mut<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<&mut Import>;
23
24    /// Swap two imports but if other not found, skip
25    /// This is useful when you want to swap imports that may not exist
26    fn may_swap_import<A>(
27        &mut self,
28        one: impl WalrusFID<A>,
29        other: (impl AsRef<str>, impl AsRef<str>),
30    ) -> eyre::Result<()>
31    where
32        Self: Sized,
33    {
34        let other_module = other.0.as_ref();
35        let other_name = other.1.as_ref();
36
37        let one_import = self
38            .find_mut(one)
39            .wrap_err_with(|| eyre::eyre!("One Import {} not found", one.as_str()))?;
40
41        let one_module = one_import.module.clone();
42        let one_name = one_import.name.clone();
43
44        one_import.module = "archived".to_string();
45
46        self.find_mut((other_module, other_name))
47            .ok()
48            .map(|import| {
49                import.module = one_module;
50                import.name = one_name.clone();
51            });
52
53        let one_import = self.find_mut(("archived", &one_name)).unwrap();
54
55        one_import.module = other_module.to_string();
56        one_import.name = other_name.to_string();
57
58        Ok(())
59    }
60
61    fn swap_import<A, B>(
62        &mut self,
63        one: impl WalrusFID<A>,
64        other: impl WalrusFID<B>,
65    ) -> eyre::Result<()>
66    where
67        Self: Sized,
68    {
69        let (other_module, other_name) = {
70            let other_import = self
71                .find_mut(other)
72                .wrap_err_with(|| eyre::eyre!("Other Import {} not found", other.as_str()))?;
73            (other_import.module.clone(), other_import.name.clone())
74        };
75
76        let one_import = self
77            .find_mut(one)
78            .wrap_err_with(|| eyre::eyre!("One Import {} not found", one.as_str()))?;
79
80        let one_module = one_import.module.clone();
81        let one_name = one_import.name.clone();
82
83        one_import.module = "archived".to_string();
84
85        let other_import = self.find_mut(other).unwrap();
86
87        other_import.module = one_module;
88        other_import.name = one_name.clone();
89
90        let one_import = self.find_mut(("archived", &one_name)).unwrap();
91
92        one_import.module = other_module;
93        one_import.name = other_name.clone();
94
95        Ok(())
96    }
97
98    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()>;
99}
100
101pub(crate) trait WalrusUtilExport: Debug {
102    /// As it deletes based on the fid, it may involve functions that export the same function.
103    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()>;
104    /// As it deletes based on the fid, it may involve functions that export the same function.
105    fn erase_with<A>(&mut self, as_fn: impl WalrusFID<A>, debug: bool) -> eyre::Result<()> {
106        if !debug { self.erase(as_fn) } else { Ok(()) }
107    }
108}
109
110pub(crate) trait WalrusUtilFuncs {
111    /// Find children flat functions
112    fn find_children(
113        &self,
114        fid: impl Borrow<FunctionId>,
115        allow_call_indirect: bool,
116    ) -> eyre::Result<Vec<FunctionId>>;
117
118    /// Find children flat functions with self
119    fn find_children_with(
120        &self,
121        fid: impl Borrow<FunctionId>,
122        allow_call_indirect: bool,
123    ) -> eyre::Result<Vec<FunctionId>> {
124        let fid = *fid.borrow();
125        let mut children = self.find_children(fid, allow_call_indirect)?;
126        if !children.contains(&fid) {
127            children.insert(0, fid);
128        }
129        Ok(children)
130    }
131
132    /// call rewrite on function
133    fn rewrite<T>(
134        &mut self,
135        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
136        fid: impl Borrow<FunctionId>,
137    ) -> eyre::Result<Vec<T>>
138    where
139        Self: Sized;
140
141    /// call rewrite on children functions
142    fn flat_rewrite<T>(
143        &mut self,
144        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
145        fid: impl Borrow<FunctionId>,
146        allow_call_indirect: bool,
147    ) -> eyre::Result<Vec<T>>
148    where
149        Self: Sized;
150
151    fn read<T>(
152        &self,
153        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
154        fid: impl Borrow<FunctionId>,
155    ) -> eyre::Result<Vec<T>>
156    where
157        Self: Sized;
158
159    fn flat_read<T>(
160        &self,
161        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
162        fid: impl Borrow<FunctionId>,
163    ) -> eyre::Result<Vec<T>>
164    where
165        Self: Sized;
166
167    fn all_rewrite<T>(
168        &mut self,
169        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
170        exclude: &[impl Borrow<FunctionId>],
171    ) -> eyre::Result<Vec<T>>
172    where
173        Self: Sized;
174
175    fn all_read<T>(
176        &self,
177        find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
178        exclude: &[impl Borrow<FunctionId>],
179    ) -> eyre::Result<Vec<T>>
180    where
181        Self: Sized;
182}
183
184#[allow(dead_code)]
185pub(crate) trait WalrusUtilModule {
186    /// connect function from import to export
187    /// export will be removed
188    /// and import will be replaced with the export function
189    fn connect_func<A, B>(
190        &mut self,
191        import: impl WalrusFID<A>,
192        export: impl WalrusFID<B>,
193    ) -> eyre::Result<()> {
194        self.connect_func_with_is_delete(import, export, true)
195    }
196
197    fn connect_func_alt<A, B>(
198        &mut self,
199        import: impl WalrusFID<A>,
200        export: impl WalrusFID<B>,
201    ) -> eyre::Result<()>;
202
203    fn connect_func_alt_with_remove_export<A>(
204        &mut self,
205        import: impl WalrusFID<A>,
206        export: impl AsRef<str>,
207        is_debug: bool,
208    ) -> eyre::Result<()>;
209
210    fn connect_func_without_remove<A, B>(
211        &mut self,
212        import: impl WalrusFID<A>,
213        export: impl WalrusFID<B>,
214    ) -> eyre::Result<()> {
215        self.connect_func_with_is_delete(import, export, false)
216    }
217
218    fn connect_func_with_is_delete<A, B>(
219        &mut self,
220        import: impl WalrusFID<A>,
221        export: impl WalrusFID<B>,
222        is_delete: bool,
223    ) -> eyre::Result<()>;
224
225    /// add fake function to the module
226    /// and return the function id
227    fn add_func(
228        &mut self,
229        params: &[ValType],
230        results: &[ValType],
231        fn_: impl FnMut(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
232    ) -> eyre::Result<FunctionId>;
233
234    /// get the memory id from target name
235    /// and remove anchor
236    fn get_memory_anchor(&mut self, name: impl AsRef<str>, remove: bool) -> eyre::Result<MemoryId> {
237        self.get_memory_anchor_with_info::<String>(name, remove)
238            .map(|(mem_id, _)| mem_id)
239    }
240
241    fn get_memory_anchor_with_info<T: ToString + std::str::FromStr>(
242        &mut self,
243        name: impl AsRef<str>,
244        remove: bool,
245    ) -> eyre::Result<(MemoryId, Option<T>)>
246    where
247        <T as std::str::FromStr>::Err: Debug;
248
249    fn find_used_memory_id(&self, memory_hint: Option<usize>) -> eyre::Result<MemoryId>;
250
251    /// create memory anchor function
252    fn create_memory_anchor(
253        &mut self,
254        name: impl AsRef<str>,
255        memory_id: MemoryId,
256    ) -> eyre::Result<MemoryId> {
257        self.create_memory_anchor_with_info(name, memory_id, None::<String>)?;
258
259        Ok(memory_id)
260    }
261
262    fn create_memory_anchor_with_info(
263        &mut self,
264        name: impl AsRef<str>,
265        memory_id: MemoryId,
266        with_info: Option<impl ToString + FromStr>,
267    ) -> eyre::Result<()>;
268
269    fn get_memory_type(&mut self, is_remove: bool) -> eyre::Result<TargetMemoryType>;
270
271    fn get_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<Box<[GlobalId]>>;
272
273    fn create_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<()>;
274
275    /// Return all functions that call functions in this fid
276    fn get_using_func<A>(
277        &self,
278        as_fn: impl WalrusFID<A>,
279        allow_call_indirect: bool,
280    ) -> eyre::Result<Vec<(FunctionId, InstrSeqId, usize)>>;
281
282    fn renew_id_on_table<A, B>(
283        &mut self,
284        old: impl WalrusFID<A>,
285        new: impl WalrusFID<B>,
286    ) -> eyre::Result<()>
287    where
288        Self: Sized;
289
290    fn fid_pos_on_table<A>(
291        &self,
292        as_fn: impl WalrusFID<A>,
293    ) -> eyre::Result<Box<[(TableId, usize)]>>;
294
295    fn renew_call_fn<A, B>(
296        &mut self,
297        old: impl WalrusFID<A>,
298        new: impl WalrusFID<B>,
299    ) -> eyre::Result<()>
300    where
301        Self: Sized;
302
303    // this is broken
304    // fn renew_call_fn_in_the_fn(
305    //     &mut self,
306    //     old_id: impl Borrow<FunctionId>,
307    //     new_id: impl Borrow<FunctionId>,
308    //     fn_id: impl Borrow<FunctionId>,
309    // ) -> eyre::Result<()>
310    // where
311    //     Self: Sized;
312
313    fn gen_new_function(
314        &mut self,
315        params: &[ValType],
316        results: &[ValType],
317        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
318    ) -> eyre::Result<FunctionId>
319    where
320        Self: Sized;
321
322    fn check_function_type<A, B>(
323        &self,
324        before: impl WalrusFID<A>,
325        after: impl WalrusFID<B>,
326    ) -> eyre::Result<()>
327    where
328        Self: Sized;
329
330    #[allow(dead_code)]
331    fn debug_call_indirect<A>(&mut self, debugger: impl WalrusFID<A>) -> eyre::Result<()>
332    where
333        Self: Sized;
334
335    #[allow(dead_code)]
336    fn gen_inspect<const N: usize, A>(
337        &mut self,
338        inspector: impl WalrusFID<A>,
339        params: &[ValType],
340        exclude: &[impl Borrow<FunctionId>],
341        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
342    ) -> eyre::Result<()>
343    where
344        Self: Sized,
345    {
346        self.gen_inspect_with_finalize(
347            Some(inspector),
348            None::<FunctionId>,
349            params,
350            &[],
351            exclude,
352            filter,
353        )
354    }
355
356    #[allow(dead_code)]
357    fn gen_finalize<const N: usize, A>(
358        &mut self,
359        finalize: impl WalrusFID<A>,
360        params: &[ValType],
361        exclude: &[impl Borrow<FunctionId>],
362        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
363    ) -> eyre::Result<()>
364    where
365        Self: Sized,
366    {
367        self.gen_inspect_with_finalize(
368            None::<FunctionId>,
369            Some(finalize),
370            &[],
371            params,
372            exclude,
373            filter,
374        )
375    }
376
377    #[allow(dead_code)]
378    fn gen_inspect_with_finalize<const N: usize, A, B>(
379        &mut self,
380        inspector: Option<impl WalrusFID<A>>,
381        finalize: Option<impl WalrusFID<B>>,
382        params: &[ValType],
383        results: &[ValType],
384        exclude: &[impl Borrow<FunctionId>],
385        filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
386    ) -> eyre::Result<()>
387    where
388        Self: Sized;
389
390    #[allow(dead_code)]
391    fn assert_i32_const(
392        &mut self,
393        val: i32,
394    ) -> eyre::Result<impl FnMut(&mut walrus::InstrSeqBuilder) -> eyre::Result<()> + 'static>;
395
396    fn load(path: impl AsRef<Path>, dwarf: bool) -> eyre::Result<Self>
397    where
398        Self: Sized;
399
400    fn copy_func<A>(&mut self, from: impl WalrusFID<A>) -> eyre::Result<walrus::FunctionId>
401    where
402        Self: Sized;
403
404    /// This method copies functions by copying the functions called internally.
405    /// It is used to rewrite the internal instructions of functions called under specific conditions.
406    /// Note: that calls_indirect may throw errors.
407    /// If you include yourself in the exclude list, only the function being called will be copied.
408    /// Note: that even if a function not included in the exclude list is called, that call will not be updated.
409    fn nested_copy_func<A>(
410        &mut self,
411        from: impl WalrusFID<A>,
412        exclude: &[impl Borrow<FunctionId>],
413        allow_import_func: bool,
414        allow_call_indirect: bool,
415    ) -> eyre::Result<walrus::FunctionId>
416    where
417        Self: Sized;
418
419    fn renew_export<A, B>(
420        &mut self,
421        old: impl WalrusFID<A>,
422        new: impl WalrusFID<B>,
423    ) -> eyre::Result<()>
424    where
425        Self: Sized;
426
427    fn save_info(
428        &mut self,
429        salt: impl AsRef<str>,
430        info: impl ToString + FromStr,
431    ) -> eyre::Result<()>;
432
433    fn load_info<T: ToString + FromStr>(&mut self, salt: impl AsRef<str>) -> eyre::Result<T>
434    where
435        <T as std::str::FromStr>::Err: Debug;
436}
437
438impl WalrusUtilImport for ModuleImports {
439    fn find_mut<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<&mut Import> {
440        let fid = as_fn.get_fid(self)?;
441
442        let import_id = self.get_imported_func(fid).unwrap().id();
443
444        Ok(self.get_mut(import_id))
445    }
446
447    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()> {
448        let fid = as_fn.get_fid(self)?;
449        let import_id = self
450            .iter()
451            .find(|f| {
452                if let walrus::ImportKind::Function(f) = f.kind {
453                    f == fid
454                } else {
455                    false
456                }
457            })
458            .map(|f| f.id())
459            .ok_or_else(|| eyre::eyre!("Import not found: {}", as_fn.as_str()))?;
460
461        self.delete(import_id);
462
463        Ok(())
464    }
465}
466
467impl WalrusUtilExport for ModuleExports {
468    fn erase<A>(&mut self, as_fn: impl WalrusFID<A>) -> eyre::Result<()> {
469        let fid = as_fn.get_fid(self)?;
470
471        let export_id = self
472            .iter()
473            .filter(|f| matches!(f.item, walrus::ExportItem::Function(f) if f == fid))
474            .map(|f| f.id())
475            .exactly_one()
476            .to_eyre()
477            .wrap_err("Expected exactly one export for function")?;
478
479        self.delete(export_id);
480
481        Ok(())
482    }
483}
484
485impl WalrusUtilModule for walrus::Module {
486    fn connect_func_with_is_delete<A, B>(
487        &mut self,
488        import: impl WalrusFID<A>,
489        export: impl WalrusFID<B>,
490        is_delete: bool,
491    ) -> eyre::Result<()> {
492        let fid = import.get_fid(&self.imports)?;
493        let export_id = export.get_fid(&self.exports)?;
494
495        self.check_function_type(fid, export_id)
496            .wrap_err("Function types do not match on connect func inner")?;
497
498        self.replace_imported_func(fid, |(builder, arg_locals)| {
499            let mut func_body = builder.func_body();
500
501            for local in arg_locals {
502                func_body.local_get(*local);
503            }
504            func_body.call(export_id);
505            func_body.return_();
506        })
507        .to_eyre()
508        .wrap_err_with(|| eyre::eyre!("Failed to replace imported function"))?;
509
510        let export_id = self
511            .exports
512            .iter()
513            .find(|f| {
514                if let walrus::ExportItem::Function(f) = f.item {
515                    f == export_id
516                } else {
517                    false
518                }
519            })
520            .map(|f| f.id())
521            .ok_or_else(|| eyre::eyre!("Export not found"))?;
522
523        if is_delete {
524            self.exports.delete(export_id);
525        }
526
527        Ok(())
528    }
529
530    fn add_func(
531        &mut self,
532        params: &[ValType],
533        results: &[ValType],
534        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
535    ) -> eyre::Result<FunctionId> {
536        let mut builder = FunctionBuilder::new(&mut self.types, params, results);
537
538        let args = params
539            .iter()
540            .map(|ty| self.locals.add(*ty))
541            .collect::<Vec<_>>();
542
543        fn_(&mut builder, &args)?;
544
545        Ok(builder.finish(args, &mut self.funcs))
546    }
547
548    /// if vfs, get vfs memory_id
549    fn get_memory_anchor_with_info<T: ToString + std::str::FromStr>(
550        &mut self,
551        name: impl AsRef<str>,
552        remove: bool,
553    ) -> eyre::Result<(MemoryId, Option<T>)>
554    where
555        <T as std::str::FromStr>::Err: Debug,
556    {
557        let name = name.as_ref();
558
559        let anchor_name = self
560            .exports
561            .iter()
562            .find_map(|export| {
563                if matches!(export.item, walrus::ExportItem::Function(_))
564                    && export
565                        .name
566                        .starts_with(&format!("__wasip1_vfs_flag_{name}_memory"))
567                {
568                    Some(export.name.clone())
569                } else {
570                    None
571                }
572            })
573            .ok_or_else(|| eyre::eyre!("Memory anchor function not found"))?;
574        let anchor_func_id = anchor_name.get_fid(&self.exports).unwrap();
575
576        self.exports.erase_with(anchor_func_id, !remove)?;
577
578        let anchor_body = &self.funcs.get(anchor_func_id).kind;
579
580        let local_func = anchor_body.unwrap_local();
581
582        let func_body = local_func.block(local_func.entry_block());
583        let memory_id = func_body
584            .iter()
585            .map(|(block, _)| block)
586            .filter_map(|block| match block {
587                ir::Instr::Load(ir::Load { memory, .. }) => Some(*memory),
588                ir::Instr::Store(ir::Store { memory, .. }) => Some(*memory),
589                _ => None,
590            })
591            .fold(Ok(Option::<MemoryId>::None), |a, b| match a? {
592                Some(a) if a == b => Ok(Some(a)),
593                None => Ok(Some(b)),
594                Some(_) => eyre::bail!("Anchor access double memory, cannot determine memory id"),
595            })?
596            .ok_or_else(|| eyre::eyre!("Memory not found"))?;
597
598        let anchor_name_ex = anchor_name
599            .strip_prefix(&format!("__wasip1_vfs_flag_{name}_memory"))
600            .unwrap();
601        let with_info = if anchor_name_ex.starts_with("_with_") {
602            Some(
603                anchor_name_ex
604                    .strip_prefix("_with_")
605                    .unwrap()
606                    .parse::<T>()
607                    .map_err(|e| eyre::eyre!("{e:?}"))
608                    .wrap_err_with(|| {
609                        eyre::eyre!("Failed to parse memory anchor info: {anchor_name_ex}")
610                    })?,
611            )
612        } else {
613            None
614        };
615
616        Ok((memory_id, with_info))
617    }
618
619    fn find_used_memory_id(&self, memory_hint: Option<usize>) -> eyre::Result<MemoryId> {
620        let memories = self
621            .memories
622            .iter()
623            .map(|memory| memory.id())
624            .collect::<Vec<_>>();
625
626        if memories.is_empty() {
627            eyre::bail!("No memories found");
628        }
629
630        // After calling environ_sizes_get,
631        // identify the memory using the memory referenced
632        // by the code trying to read the pointer
633        let memory_id = if memories.len() > 1 && memory_hint.is_none() {
634            let gen_memory_id = || -> eyre::Result<MemoryId> {
635                // environ_sizes_get
636                let import_id =
637                    ("wasi_snapshot_preview1", "environ_sizes_get").get_fid(&self.imports)?;
638
639                let using_funcs = self.get_using_func(import_id, true)?;
640
641                let ret_mem_id = std::sync::Arc::new(std::sync::Mutex::new(None));
642
643                for (fid, _, _) in using_funcs {
644                    let arg_ptr =
645                        std::sync::Arc::new(std::sync::Mutex::new(Option::<Vec<u32>>::None));
646                    let arg_ptr_c = arg_ptr.clone();
647
648                    let ret_mem_id_c = ret_mem_id.clone();
649
650                    let mut interpreter = walrus_simple_interpreter::Interpreter::new(self)
651                        .to_eyre()
652                        .wrap_err_with(|| eyre::eyre!("Failed to create interpreter"))?;
653
654                    interpreter.set_interrupt_handler_mem(move |_, _, _, (id, address, _, ty)| {
655
656                    if matches!(ty, walrus_simple_interpreter::MemoryAccessType::Load) {
657                        if let Some(v) = arg_ptr_c.lock().unwrap().as_ref() {
658                            if v.contains(&address) {
659                                if let Some(mem_id) = ret_mem_id_c.clone().lock().unwrap().as_ref() {
660                                    if *mem_id != id {
661                                        return Err(anyhow::anyhow!(
662                                            "Memory access double memory, cannot determine memory id"
663                                        ));
664                                    }
665                                } else {
666                                    ret_mem_id_c.clone().lock().unwrap().replace(id);
667                                }
668                            }
669                        }
670                    }
671
672                    Ok(())
673                });
674
675                    let memories = memories.clone();
676
677                    interpreter.add_function("environ_sizes_get", move |interpreter, args| {
678                        let args = args
679                            .iter()
680                            .map(|arg| {
681                                if let ir::Value::I32(arg) = arg {
682                                    Ok(*arg as u32)
683                                } else {
684                                    Err(anyhow::anyhow!("Invalid argument type"))
685                                }
686                            })
687                            .collect::<Result<Vec<_>, _>>()?;
688                        interpreter.mem_set_i32(memories[0], args[0], 0)?;
689                        interpreter.mem_set_i32(memories[0], args[1], 0)?;
690
691                        arg_ptr.lock().unwrap().replace(args);
692
693                        Ok(vec![ir::Value::I32(0)])
694                    });
695
696                    let args = self
697                        .types
698                        .get(self.funcs.get(fid).ty())
699                        .params()
700                        .iter()
701                        .map(|ty| ty.normal())
702                        .collect::<eyre::Result<Vec<_>>>()
703                        .wrap_err_with(|| eyre::eyre!("Failed to get function args"))?;
704                    if let Err(e) = interpreter.call(fid, self, &args).to_eyre() {
705                        if ret_mem_id.lock().unwrap().is_none() {
706                            eprintln!("Error: {e}");
707                        }
708                    }
709                }
710
711                if let Some(mem_id) = ret_mem_id.lock().unwrap().as_ref() {
712                    Ok(*mem_id)
713                } else {
714                    return Err(eyre::eyre!("Memory not found"));
715                }
716            };
717            gen_memory_id().wrap_err_with(|| {
718                eyre::eyre!("Failed to detect memory id. You can use memory hint.")
719            })?
720        } else if let Some(memory_hint) = memory_hint {
721            if memory_hint >= memories.len() {
722                return Err(eyre::eyre!(
723                    "Memory hint {} is out of bounds for memories: {:?}",
724                    memory_hint,
725                    memories
726                ));
727            }
728            memories[memory_hint]
729        } else {
730            memories[0]
731        };
732
733        Ok(memory_id)
734    }
735
736    fn create_memory_anchor_with_info(
737        &mut self,
738        name: impl AsRef<str>,
739        memory_id: MemoryId,
740        with_info: Option<impl ToString + FromStr>,
741    ) -> eyre::Result<()> {
742        let name = name.as_ref();
743
744        // unsafe extern "C" fn __wasip1_vfs_flag_vfs_memory(ptr: *mut u8, src: *mut u8) {
745        //     unsafe { core::ptr::copy_nonoverlapping(src, ptr, 1) };
746        // }
747        let id = self.add_func(&[ValType::I32, ValType::I32], &[], |builder, arg_locals| {
748            let mut func_body = builder.func_body();
749
750            func_body
751                .local_get(arg_locals[0])
752                .local_get(arg_locals[1])
753                .load(
754                    memory_id,
755                    ir::LoadKind::I32_8 {
756                        kind: ir::ExtendedLoad::ZeroExtend,
757                    },
758                    ir::MemArg {
759                        offset: 0,
760                        align: 0,
761                    },
762                )
763                .store(
764                    memory_id,
765                    ir::StoreKind::I32_8 { atomic: false },
766                    ir::MemArg {
767                        offset: 0,
768                        align: 0,
769                    },
770                );
771
772            func_body.return_();
773
774            Ok(())
775        })?;
776
777        let ex_name = if let Some(with_info) = with_info {
778            format!(
779                "__wasip1_vfs_flag_{name}_memory_with_{}",
780                with_info.to_string()
781            )
782        } else {
783            format!("__wasip1_vfs_flag_{name}_memory")
784        };
785        self.exports.add(&ex_name, id);
786
787        Ok(())
788    }
789
790    fn get_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<Box<[GlobalId]>> {
791        let name = name.as_ref();
792        let anchor_name = format!("__wasip1_vfs_flag_{name}_global");
793
794        let anchor_func_id = anchor_name.get_fid(&self.exports)?;
795
796        self.exports.erase(anchor_func_id)?;
797
798        let anchor_body = &self.funcs.get(anchor_func_id).kind;
799        if let FunctionKind::Local(local_func) = anchor_body {
800            let entry_id = local_func.entry_block();
801            let func_body = local_func.block(entry_id);
802            let global_ids = func_body
803                .iter()
804                .map(|(block, _)| block)
805                .filter_map(|block| match block {
806                    ir::Instr::GlobalSet(ir::GlobalSet { global, .. })
807                    | ir::Instr::GlobalGet(ir::GlobalGet { global, .. }) => Some(*global),
808                    _ => None,
809                })
810                .collect::<Box<_>>();
811
812            Ok(global_ids)
813        } else {
814            Err(eyre::eyre!(
815                "anchor (local function) {anchor_name} not found",
816            ))
817        }
818    }
819
820    fn create_global_anchor(&mut self, name: impl AsRef<str>) -> eyre::Result<()> {
821        let name = name.as_ref();
822
823        let global_ids = self
824            .globals
825            .iter()
826            .map(|global| (global.id(), global.ty, global.mutable))
827            .collect::<Vec<_>>();
828
829        let results = global_ids
830            .iter()
831            .filter(|(_, _, mutable)| !*mutable)
832            .map(|(_, ty, _)| ty)
833            .cloned()
834            .collect::<Vec<_>>();
835
836        let id = self.add_func(&[], &results, |builder, _| {
837            let mut func_body = builder.func_body();
838
839            for (id, ty, mutable) in global_ids.iter() {
840                if *mutable {
841                    func_body
842                        .const_(
843                            ty.normal()
844                                .wrap_err_with(|| eyre::eyre!("Failed to get global type"))?,
845                        )
846                        .global_set(*id);
847                } else {
848                    func_body.global_get(*id);
849                }
850            }
851
852            func_body.return_();
853
854            Ok(())
855        })?;
856
857        self.exports
858            .add(&format!("__wasip1_vfs_flag_{name}_global"), id);
859
860        Ok(())
861    }
862
863    fn get_using_func<A>(
864        &self,
865        as_fn: impl WalrusFID<A>,
866        allow_call_indirect: bool,
867    ) -> eyre::Result<Vec<(FunctionId, InstrSeqId, usize)>> {
868        let fid = as_fn.get_fid(self)?;
869
870        self.funcs
871            .iter_local()
872            .map(|(id, func)| {
873                func.read(|instr, place| {
874                    use walrus::ir::*;
875                    match instr {
876                        Instr::Call(Call { func }) | Instr::ReturnCall(ReturnCall { func })
877                            if fid == *func =>
878                        {
879                            Ok(Some((id, place)))
880                        }
881                        Instr::CallIndirect(CallIndirect { table: _, ty: _ })
882                            if !allow_call_indirect =>
883                        {
884                            eyre::bail!("call_indirect is not supported in get_using_func");
885                        }
886                        _ => Ok(None),
887                    }
888                })
889                .and_then(|v| {
890                    v.into_iter()
891                        .filter_map_ok(|v| v)
892                        .map_ok(|(a, (b, c))| (a, c, b))
893                        .collect::<eyre::Result<Vec<_>>>()
894                })
895            })
896            .flatten_ok()
897            .collect::<eyre::Result<Vec<_>>>()
898    }
899
900    fn renew_id_on_table<A, B>(
901        &mut self,
902        old: impl WalrusFID<A>,
903        new: impl WalrusFID<B>,
904    ) -> eyre::Result<()>
905    where
906        Self: Sized,
907    {
908        let old_id = old.get_fid(self)?;
909        let new_id = new.get_fid(self)?;
910
911        self.check_function_type(old_id, new_id)
912            .wrap_err("Function types do not match on renew id on table")?;
913
914        for table in self.tables.iter_mut() {
915            for elem in &table.elem_segments {
916                let elem = self.elements.get_mut(*elem);
917                if let walrus::ElementKind::Active {
918                    table: table_id, ..
919                } = elem.kind
920                {
921                    if table_id != table.id() {
922                        unreachable!();
923                    }
924                } else {
925                    unreachable!();
926                }
927                match &mut elem.items {
928                    walrus::ElementItems::Functions(ids) => {
929                        ids.iter_mut().for_each(|id| {
930                            if *id == old_id {
931                                log::info!(
932                                    "Rewriting function id on table. Old: {:?}, New: {:?}",
933                                    old_id,
934                                    new_id
935                                );
936                                *id = new_id;
937                            }
938                        });
939                    }
940                    walrus::ElementItems::Expressions(..) => unimplemented!(),
941                }
942            }
943        }
944
945        Ok(())
946    }
947
948    fn fid_pos_on_table<A>(&self, fid: impl WalrusFID<A>) -> eyre::Result<Box<[(TableId, usize)]>> {
949        let fid = fid.get_fid(self)?;
950
951        let mut positions = vec![];
952        for table in self.tables.iter() {
953            for elem in &table.elem_segments {
954                let elem = self.elements.get(*elem);
955                if let walrus::ElementKind::Active {
956                    table: table_id, ..
957                } = elem.kind
958                {
959                    if table_id != table.id() {
960                        unreachable!();
961                    }
962                } else {
963                    unreachable!();
964                }
965                match &elem.items {
966                    walrus::ElementItems::Functions(ids) => {
967                        ids.iter().copied().enumerate().for_each(|(i, id)| {
968                            if id == fid {
969                                positions.push((table.id(), i));
970                            }
971                        });
972                    }
973                    walrus::ElementItems::Expressions(..) => unimplemented!(),
974                }
975            }
976        }
977        Ok(positions.into_boxed_slice())
978    }
979
980    fn renew_call_fn<A, B>(
981        &mut self,
982        old: impl WalrusFID<A>,
983        new: impl WalrusFID<B>,
984    ) -> eyre::Result<()>
985    where
986        Self: Sized,
987    {
988        let old_id = old.get_fid(self)?;
989        let new_id = new.get_fid(self)?;
990
991        for (id, _, _) in self
992            .get_using_func(old_id, true)
993            .wrap_err("Failed to get using func")?
994        {
995            self.funcs
996                .rewrite(
997                    |instr, _| {
998                        if let walrus::ir::Instr::Call(call) = instr {
999                            if call.func == old_id {
1000                                call.func = new_id;
1001                            }
1002                        }
1003                    },
1004                    id,
1005                )
1006                .wrap_err("Failed to renew function call")?;
1007        }
1008
1009        self.renew_id_on_table(old_id, new_id)?;
1010
1011        // if old function is imported
1012        if let walrus::FunctionKind::Import(import) = &self.funcs.get(old_id).kind {
1013            self.imports.delete(import.import);
1014        }
1015        // renew export
1016        self.exports
1017            .iter_mut()
1018            .filter(|export| match export.item {
1019                walrus::ExportItem::Function(f) if f == old_id => true,
1020                _ => false,
1021            })
1022            .for_each(|export| {
1023                export.item = walrus::ExportItem::Function(new_id);
1024            });
1025        self.funcs.delete(old_id);
1026
1027        Ok(())
1028    }
1029
1030    fn gen_new_function(
1031        &mut self,
1032        params: &[ValType],
1033        results: &[ValType],
1034        fn_: impl FnOnce(&mut FunctionBuilder, &Vec<LocalId>) -> eyre::Result<()>,
1035    ) -> eyre::Result<FunctionId>
1036    where
1037        Self: Sized,
1038    {
1039        let args = params
1040            .iter()
1041            .map(|ty| self.locals.add(*ty))
1042            .collect::<Vec<_>>();
1043
1044        let mut func = FunctionBuilder::new(&mut self.types, &params, &results);
1045
1046        fn_(&mut func, &args)?;
1047
1048        Ok(func.finish(args, &mut self.funcs))
1049    }
1050
1051    fn check_function_type<A, B>(
1052        &self,
1053        before: impl WalrusFID<A>,
1054        after: impl WalrusFID<B>,
1055    ) -> eyre::Result<()>
1056    where
1057        Self: Sized,
1058    {
1059        let before = before.get_fid(self)?;
1060        let after = after.get_fid(self)?;
1061
1062        let a_ty = self.funcs.get(before).ty();
1063        let a_ty_params = self.types.get(a_ty).params();
1064        let a_ty_results = self.types.get(a_ty).results();
1065
1066        let b_ty = self.funcs.get(after).ty();
1067        let b_ty_params = self.types.get(b_ty).params();
1068        let b_ty_results = self.types.get(b_ty).results();
1069
1070        if a_ty_params != b_ty_params || a_ty_results != b_ty_results {
1071            eyre::bail!(
1072                "Function types do not match. Before: {a_ty_params:?} -> {a_ty_results:?}, After: {b_ty_params:?} -> {b_ty_results:?}"
1073            );
1074        }
1075
1076        Ok(())
1077    }
1078
1079    // Insert a specific function into every call_indirect within all functions.
1080    // The type of the received function is fn (table_id, pos);
1081    fn debug_call_indirect<A>(&mut self, id: impl WalrusFID<A>) -> eyre::Result<()>
1082    where
1083        Self: Sized,
1084    {
1085        let id = id.get_fid(self)?;
1086
1087        // check id type
1088        if self.types.get(self.funcs.get(id).ty()).params() != [ValType::I32, ValType::I32]
1089            || self.types.get(self.funcs.get(id).ty()).results() != []
1090        {
1091            eyre::bail!("Function type must be (i32, i32) -> ()");
1092        }
1093
1094        let ids = self.funcs.find_children_with(id, false)?;
1095
1096        let tables = self
1097            .funcs
1098            .iter_local()
1099            .filter(|(fid, _)| !ids.contains(fid))
1100            .map(|(fid, fn_)| {
1101                fn_.read(|instr, pos| {
1102                    if let walrus::ir::Instr::CallIndirect(call) = instr {
1103                        Some((call.table, (fid, pos)))
1104                    } else if let walrus::ir::Instr::ReturnCallIndirect(..) = instr {
1105                        unimplemented!("return_call_indirect is not supported yet")
1106                    } else {
1107                        None
1108                    }
1109                })
1110            })
1111            .flatten_ok()
1112            .filter_map_ok(|x| x)
1113            .collect::<eyre::Result<Vec<_>>>()?;
1114
1115        let table_fns = tables
1116            .iter()
1117            .map(|(table, _)| *table)
1118            .collect::<std::collections::HashSet<_>>()
1119            .into_iter()
1120            .map(|table| {
1121                // As if nothing had happened, it passes the value again.
1122                let middle_fn_id =
1123                    self.add_func(&[ValType::I32], &[ValType::I32], |builder, args| {
1124                        builder
1125                            .func_body()
1126                            .i32_const(table.index() as i32)
1127                            .local_get(args[0])
1128                            .call(id)
1129                            .local_get(args[0])
1130                            .return_();
1131                        Ok(())
1132                    })?;
1133
1134                Ok((table, middle_fn_id))
1135            })
1136            .collect::<eyre::Result<std::collections::HashMap<_, _>>>()?;
1137
1138        for (tid, (fid, (pos, seq_id))) in tables
1139            .into_iter()
1140            .sorted_by(
1141                |(_, (fid_a, (pos_a, seq_id_a))), (_, (fid_b, (pos_b, seq_id_b)))| match fid_a
1142                    .cmp(&fid_b)
1143                {
1144                    std::cmp::Ordering::Equal => match seq_id_a.cmp(&seq_id_b) {
1145                        std::cmp::Ordering::Equal => pos_a.cmp(&pos_b),
1146                        other => other,
1147                    },
1148                    other => other,
1149                },
1150            )
1151            .rev()
1152        {
1153            match self.funcs.get_mut(fid).kind {
1154                FunctionKind::Local(ref mut local_func) => {
1155                    if let Some(walrus::ir::Instr::CallIndirect(walrus::ir::CallIndirect {
1156                        table,
1157                        ..
1158                    })) = local_func
1159                        .builder_mut()
1160                        .instr_seq(seq_id)
1161                        .instrs()
1162                        .get(pos)
1163                        .map(|(instr, _)| instr)
1164                    {
1165                        if *table != tid {
1166                            eyre::bail!("Table id mismatch");
1167                        }
1168                    } else {
1169                        eyre::bail!("Instruction at position is not call_indirect");
1170                    }
1171                    local_func
1172                        .builder_mut()
1173                        .instr_seq(seq_id)
1174                        .call_at(pos, table_fns[&tid]);
1175                }
1176                _ => unreachable!(),
1177            }
1178        }
1179
1180        Ok(())
1181    }
1182
1183    fn gen_inspect_with_finalize<const N: usize, A, B>(
1184        &mut self,
1185        inspector: Option<impl WalrusFID<A>>,
1186        finalize: Option<impl WalrusFID<B>>,
1187        params: &[ValType],
1188        results: &[ValType],
1189        exclude: &[impl Borrow<FunctionId>],
1190        mut filter: impl FnMut(&ir::Instr) -> Option<[i32; N]>,
1191    ) -> eyre::Result<()>
1192    where
1193        Self: Sized,
1194    {
1195        let inspector: Option<FunctionId> = inspector.map(|id| id.get_fid(self)).transpose()?;
1196        let finalize: Option<FunctionId> = finalize.map(|id| id.get_fid(self)).transpose()?;
1197
1198        // check inspector type
1199        let check_inspector = |params: &[ValType], name: &str, fid| {
1200            if self.types.get(self.funcs.get(fid).ty()).params()
1201                != params
1202                    .iter()
1203                    .cloned()
1204                    .chain(std::iter::repeat(ValType::I32).take(N))
1205                    .collect::<Vec<_>>()
1206            {
1207                eyre::bail!("{name} function type must be ({params:?}) -> ()",);
1208            }
1209
1210            Ok(())
1211        };
1212
1213        if let Some(inspector) = inspector {
1214            check_inspector(params, "Inspector", inspector)?;
1215        }
1216
1217        if let Some(finalize) = finalize {
1218            check_inspector(results, "Finalize", finalize)?;
1219        }
1220
1221        let exclude = [inspector, finalize]
1222            .iter()
1223            .filter_map(|id| *id)
1224            .map(|f| self.funcs.find_children_with(f, false))
1225            .flatten_ok()
1226            .chain(exclude.iter().map(|id| Ok(*id.borrow())))
1227            .collect::<eyre::Result<std::collections::HashSet<_>>>()
1228            .wrap_err("Failed to find exclude functions")?;
1229
1230        let instrs = self
1231            .funcs
1232            .iter_local()
1233            .filter(|(fid, _)| !exclude.contains(fid))
1234            .map(|(fid, fn_)| {
1235                fn_.read(|instr, pos| {
1236                    if let Some(ret) = filter(instr) {
1237                        Some((ret, fid, pos))
1238                    } else {
1239                        None
1240                    }
1241                })
1242            })
1243            .flatten_ok()
1244            .filter_map_ok(|x| x)
1245            .collect::<eyre::Result<Vec<_>>>()?;
1246
1247        let instrs_set = instrs
1248            .iter()
1249            .map(|(ret, _, _)| *ret)
1250            .collect::<std::collections::HashSet<_>>();
1251
1252        let mut group_by_fns = |fns: Option<FunctionId>, params: &[ValType]| {
1253            fns.map(|fns| {
1254                instrs_set
1255                    .iter()
1256                    .map(|ret| {
1257                        let middle_fn_id = self.add_func(&params, &params, |builder, args| {
1258                            let mut func_body = builder.func_body();
1259                            for ret in ret {
1260                                func_body.i32_const(*ret);
1261                            }
1262                            for arg in args {
1263                                func_body.local_get(*arg);
1264                            }
1265                            func_body.call(fns);
1266                            for arg in args {
1267                                func_body.local_get(*arg);
1268                            }
1269                            func_body.return_();
1270                            Ok(())
1271                        })?;
1272                        Ok((ret, middle_fn_id))
1273                    })
1274                    .collect::<eyre::Result<std::collections::HashMap<_, _>>>()
1275            })
1276            .transpose()
1277        };
1278
1279        let group_inspector_fns = group_by_fns(inspector, params)?;
1280        let group_finalize_fns = group_by_fns(finalize, results)?;
1281
1282        let ids = [inspector, finalize]
1283            .iter()
1284            .filter_map(|id| *id)
1285            .map(|fid| self.funcs.find_children_with(fid, false))
1286            .flatten_ok()
1287            .collect::<eyre::Result<std::collections::HashSet<_>>>()
1288            .wrap_err("Failed to find exclude functions")?;
1289
1290        for (ret, fid, (pos, seq_id)) in instrs
1291            .into_iter()
1292            .sorted_by(
1293                |(_, fid_a, (pos_a, seq_id_a)), (_, fid_b, (pos_b, seq_id_b))| match fid_a
1294                    .cmp(&fid_b)
1295                {
1296                    std::cmp::Ordering::Equal => match seq_id_a.cmp(&seq_id_b) {
1297                        std::cmp::Ordering::Equal => pos_a.cmp(&pos_b),
1298                        other => other,
1299                    },
1300                    other => other,
1301                },
1302            )
1303            .rev()
1304        {
1305            if ids.contains(&fid) {
1306                continue;
1307            }
1308
1309            match self.funcs.get_mut(fid).kind {
1310                FunctionKind::Local(ref mut local_func) => {
1311                    let mut instr_seq = local_func.builder_mut().instr_seq(seq_id);
1312                    let instr = instr_seq
1313                        .instrs()
1314                        .get(pos)
1315                        .map(|(instr, _)| instr)
1316                        .ok_or_else(|| eyre::eyre!("Instruction at position not found"))?;
1317
1318                    if filter(instr).is_none() {
1319                        eyre::bail!("Instruction at position does not match filter");
1320                    }
1321
1322                    if let Some(_) = finalize {
1323                        instr_seq.call_at(pos + 1, group_finalize_fns.as_ref().unwrap()[&ret]);
1324                    }
1325                    if let Some(_) = inspector {
1326                        instr_seq.call_at(pos, group_inspector_fns.as_ref().unwrap()[&ret]);
1327                    }
1328                }
1329                _ => unreachable!(),
1330            }
1331        }
1332
1333        Ok(())
1334    }
1335
1336    fn assert_i32_const(
1337        &mut self,
1338        val: i32,
1339    ) -> eyre::Result<impl FnMut(&mut walrus::InstrSeqBuilder) -> eyre::Result<()> + 'static> {
1340        use walrus::ValType::I32;
1341        let fid = self.add_func(&[I32], &[I32], |builder, args| {
1342            builder
1343                .func_body()
1344                .i32_const(val)
1345                .local_get(args[0])
1346                .binop(walrus::ir::BinaryOp::I32Eq)
1347                .if_else(
1348                    None,
1349                    |cons| {
1350                        cons.local_get(args[0]);
1351                        cons.return_();
1352                    },
1353                    |els| {
1354                        els.unreachable();
1355                    },
1356                );
1357            Ok(())
1358        })?;
1359
1360        Ok(
1361            move |func_body: &mut walrus::InstrSeqBuilder| -> eyre::Result<()> {
1362                func_body.call(fid);
1363                Ok(())
1364            },
1365        )
1366    }
1367
1368    fn load(path: impl AsRef<Path>, dwarf: bool) -> eyre::Result<Self>
1369    where
1370        Self: Sized,
1371    {
1372        let mut config = walrus::ModuleConfig::new();
1373        config.generate_dwarf(dwarf);
1374        let module = walrus::Module::from_file_with_config(path.as_ref(), &config)
1375            .to_eyre()
1376            .wrap_err_with(|| {
1377                eyre::eyre!("Failed to load Wasm file: {}", path.as_ref().display())
1378            })?;
1379        Ok(module)
1380    }
1381
1382    fn connect_func_alt<A, B>(
1383        &mut self,
1384        import: impl WalrusFID<A>,
1385        export: impl WalrusFID<B>,
1386    ) -> eyre::Result<()> {
1387        let err_msg = || {
1388            format!(
1389                "Function types do not match on connect func alt: {} -> {}",
1390                import.as_str(),
1391                export.as_str()
1392            )
1393        };
1394        let export = export
1395            .get_fid(&self.exports)
1396            .wrap_err("Export function not found")
1397            .wrap_err_with(err_msg)?;
1398
1399        self.renew_call_fn(import, export)
1400            .wrap_err("Failed to renew call function")
1401            .wrap_err_with(err_msg)?;
1402
1403        Ok(())
1404    }
1405
1406    fn copy_func<A>(&mut self, from: impl WalrusFID<A>) -> eyre::Result<walrus::FunctionId>
1407    where
1408        Self: Sized,
1409    {
1410        let from = from.get_fid(self)?;
1411
1412        let func_base = self.funcs.get(from);
1413        let ty_base = func_base.ty();
1414        let types_base = self.types.get(ty_base);
1415        let params_base = types_base.params().to_vec();
1416        let results_base = types_base.results().to_vec();
1417        let local_func_base = func_base.kind.unwrap_local();
1418
1419        let local_ids_base = local_func_base
1420            .args
1421            .iter()
1422            .copied()
1423            .chain(
1424                local_func_base
1425                    .read(|instr, _| match instr {
1426                        walrus::ir::Instr::LocalGet(walrus::ir::LocalGet { local }) => Some(*local),
1427                        walrus::ir::Instr::LocalSet(walrus::ir::LocalSet { local }) => Some(*local),
1428                        walrus::ir::Instr::LocalTee(walrus::ir::LocalTee { local }) => Some(*local),
1429                        _ => None,
1430                    })?
1431                    .into_iter()
1432                    .filter_map(|x| x)
1433                    .filter(|id| !local_func_base.args.contains(id))
1434                    .collect::<std::collections::HashSet<_>>()
1435                    .into_iter(),
1436            )
1437            .collect::<Vec<_>>();
1438
1439        let locals_base = local_ids_base
1440            .iter()
1441            .map(|ty| self.locals.get(*ty).ty())
1442            .collect::<Vec<_>>();
1443
1444        let entry_base = local_func_base.entry_block();
1445        let mut instrs_base = local_func_base
1446            .read(|instr, (pos, id)| (pos, id, instr.clone()))?
1447            .into_iter()
1448            .into_group_map_by(|(_, id, _)| *id)
1449            .into_iter()
1450            .map(|(id, vec)| {
1451                let instrs = vec
1452                    .into_iter()
1453                    .map(|(pos, _, instr)| (pos, instr))
1454                    .sorted_by_key(|(pos, _)| *pos)
1455                    .enumerate()
1456                    .inspect(|(i, (pos, _))| assert_eq!(i, pos))
1457                    .map(|(_, (_, instr))| instr)
1458                    .collect::<Vec<_>>();
1459
1460                (id, instrs)
1461            })
1462            .collect::<HashMap<_, _>>();
1463
1464        let mut builder = FunctionBuilder::new(&mut self.types, &params_base, &results_base);
1465
1466        let new_locals = locals_base
1467            .iter()
1468            .map(|ty| self.locals.add(*ty))
1469            .collect::<Vec<_>>();
1470
1471        let new_args = new_locals
1472            .iter()
1473            .copied()
1474            .take(local_func_base.args.len())
1475            .collect::<Vec<_>>();
1476
1477        let local_map = local_ids_base
1478            .iter()
1479            .zip(new_locals.iter())
1480            .map(|(a, b)| (*a, *b))
1481            .collect::<HashMap<_, _>>();
1482
1483        let new_body_id = builder.func_body_id();
1484
1485        let mut seq_map = instrs_base
1486            .keys()
1487            .filter(|id| **id != entry_base)
1488            .map(|id| {
1489                (
1490                    *id,
1491                    builder
1492                        .dangling_instr_seq(local_func_base.block(*id).ty)
1493                        .id(),
1494                )
1495            })
1496            .chain(std::iter::once((entry_base, new_body_id)))
1497            .collect::<HashMap<_, _>>();
1498
1499        use walrus::ir::*;
1500
1501        for (seq, instrs_base) in instrs_base.drain() {
1502            instrs_base
1503                .iter()
1504                .map(|instr| match instr {
1505                    Instr::Block(Block { seq }) => {
1506                        vec![seq]
1507                    }
1508                    Instr::Loop(Loop { seq }) => {
1509                        vec![seq]
1510                    }
1511                    Instr::Br(Br { block }) => {
1512                        vec![block]
1513                    }
1514                    Instr::BrIf(BrIf { block }) => {
1515                        vec![block]
1516                    }
1517                    Instr::IfElse(IfElse {
1518                        alternative,
1519                        consequent,
1520                    }) => {
1521                        vec![alternative, consequent]
1522                    }
1523                    Instr::BrTable(BrTable { blocks, default }) => blocks
1524                        .iter()
1525                        .chain(std::iter::once(default))
1526                        .collect::<Vec<_>>(),
1527                    _ => Vec::new(),
1528                })
1529                .flatten()
1530                .for_each(|b| {
1531                    if !seq_map.contains_key(&b) {
1532                        let blank_seq = builder
1533                            .dangling_instr_seq(local_func_base.block(*b).ty)
1534                            .id();
1535                        seq_map.insert(*b, blank_seq);
1536                    }
1537                });
1538
1539            let mut now_seq = builder.instr_seq(seq_map[&seq]);
1540
1541            for instr in instrs_base {
1542                match instr {
1543                    Instr::Block(Block { seq }) => {
1544                        now_seq.instr(Instr::Block(Block { seq: seq_map[&seq] }));
1545                    }
1546                    Instr::Loop(Loop { seq }) => {
1547                        now_seq.instr(Instr::Loop(Loop { seq: seq_map[&seq] }));
1548                    }
1549                    Instr::Br(Br { block }) => {
1550                        now_seq.instr(Instr::Br(Br {
1551                            block: seq_map[&block],
1552                        }));
1553                    }
1554                    Instr::BrIf(BrIf { block }) => {
1555                        now_seq.instr(Instr::BrIf(BrIf {
1556                            block: seq_map[&block],
1557                        }));
1558                    }
1559                    Instr::IfElse(IfElse {
1560                        consequent,
1561                        alternative,
1562                    }) => {
1563                        now_seq.instr(Instr::IfElse(IfElse {
1564                            consequent: seq_map[&consequent],
1565                            alternative: seq_map[&alternative],
1566                        }));
1567                    }
1568                    Instr::BrTable(BrTable { blocks, default }) => {
1569                        now_seq.instr(Instr::BrTable(BrTable {
1570                            blocks: blocks
1571                                .iter()
1572                                .map(|b| seq_map[b])
1573                                .collect::<Vec<_>>()
1574                                .into_boxed_slice(),
1575                            default: seq_map[&default],
1576                        }));
1577                    }
1578                    Instr::LocalGet(LocalGet { local }) => {
1579                        now_seq.instr(Instr::LocalGet(LocalGet {
1580                            local: local_map[&local],
1581                        }));
1582                    }
1583                    Instr::LocalSet(LocalSet { local }) => {
1584                        now_seq.instr(Instr::LocalSet(LocalSet {
1585                            local: local_map[&local],
1586                        }));
1587                    }
1588                    Instr::LocalTee(LocalTee { local }) => {
1589                        now_seq.instr(Instr::LocalTee(LocalTee {
1590                            local: local_map[&local],
1591                        }));
1592                    }
1593                    _ => {
1594                        now_seq.instr(instr);
1595                    }
1596                }
1597            }
1598        }
1599
1600        Ok(builder.finish(new_args, &mut self.funcs))
1601    }
1602
1603    fn nested_copy_func<A>(
1604        &mut self,
1605        from: impl WalrusFID<A>,
1606        exclude: &[impl Borrow<FunctionId>],
1607        allow_import_func: bool,
1608        allow_call_indirect: bool,
1609    ) -> eyre::Result<walrus::FunctionId>
1610    where
1611        Self: Sized,
1612    {
1613        let from = from.get_fid(self)?;
1614        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
1615
1616        let mut fid_map: HashMap<FunctionId, FunctionId> = HashMap::new();
1617
1618        let fids = self
1619            .funcs
1620            .find_children_with(from, allow_call_indirect)
1621            .wrap_err("Failed to find children functions")?;
1622
1623        for fid in fids {
1624            if exclude.contains(&fid) {
1625                fid_map.insert(fid, fid);
1626                continue;
1627            }
1628            if fid_map.contains_key(&fid) {
1629                unreachable!();
1630            }
1631
1632            let func = self.funcs.get(fid);
1633            match &func.kind {
1634                FunctionKind::Import(import) => {
1635                    if !allow_import_func {
1636                        let import = self.imports.get(import.import);
1637                        eyre::bail!("Import function found: {:?}", import);
1638                    }
1639                    fid_map.insert(fid, fid);
1640                }
1641                FunctionKind::Local(_) => {
1642                    let new_fid = self.copy_func(fid)?;
1643                    fid_map.insert(fid, new_fid);
1644                }
1645                _ => {
1646                    eyre::bail!("Unknown function kind: {:?}", func.kind);
1647                }
1648            }
1649        }
1650
1651        for (old_fid, new_fid) in fid_map.iter() {
1652            // If included in the exclude list, it is normally ignored; however, in its own case, it is rewritten.
1653            if (old_fid == new_fid || exclude.contains(new_fid)) && *new_fid != from {
1654                continue;
1655            }
1656
1657            let local = self.funcs.get_mut(*new_fid).kind.unwrap_local_mut();
1658            local
1659                .builder_mut()
1660                .func_body()
1661                .rewrite(|instr, _| {
1662                    use walrus::ir::*;
1663                    match instr {
1664                        Instr::Call(Call { func, .. })
1665                        | Instr::ReturnCall(ReturnCall { func, .. }) => {
1666                            if let Some(new_func) = fid_map.get(func) {
1667                                *func = *new_func;
1668                            }
1669                        }
1670                        Instr::CallIndirect(call) if !allow_call_indirect => {
1671                            eyre::bail!("Call indirect found: {call:?} in nested copy");
1672                        }
1673                        Instr::ReturnCallIndirect(call) if !allow_call_indirect => {
1674                            eyre::bail!("Return call indirect found: {call:?} in nested copy");
1675                        }
1676                        _ => {}
1677                    }
1678                    Ok(())
1679                })
1680                .wrap_err("Failed to renew function call")?;
1681        }
1682
1683        Ok(fid_map[&from])
1684    }
1685
1686    fn renew_export<A, B>(
1687        &mut self,
1688        old: impl WalrusFID<A>,
1689        new: impl WalrusFID<B>,
1690    ) -> eyre::Result<()>
1691    where
1692        Self: Sized,
1693    {
1694        let old_id = old.get_fid(self)?;
1695        let new_id = new.get_fid(self)?;
1696
1697        self.check_function_type(old_id, new_id)
1698            .wrap_err("Function types do not match on renew export")?;
1699
1700        self.exports
1701            .iter_mut()
1702            .filter(|export| matches!(export.item, walrus::ExportItem::Function(f) if f == old_id))
1703            .for_each(|export| {
1704                export.item = walrus::ExportItem::Function(new_id);
1705            });
1706
1707        Ok(())
1708    }
1709
1710    fn get_memory_type(&mut self, is_remove: bool) -> eyre::Result<TargetMemoryType> {
1711        let (target_memory_type, eid) = self
1712            .exports
1713            .iter()
1714            .find(|e| e.name == "__wasip1_vfs_flag_vfs_multi_memory")
1715            .map(|e| Ok((TargetMemoryType::Multi, e.id())))
1716            .unwrap_or(
1717                self.exports
1718                    .iter()
1719                    .find(|e| e.name == "__wasip1_vfs_flag_vfs_single_memory")
1720                    .map(|e| Ok((TargetMemoryType::Single, e.id())))
1721                    .unwrap_or(Err(eyre::eyre!("No target memory type found"))),
1722            )?;
1723
1724        if is_remove {
1725            self.exports.delete(eid);
1726        }
1727
1728        Ok(target_memory_type)
1729    }
1730
1731    fn save_info(
1732        &mut self,
1733        key: impl AsRef<str>,
1734        info: impl ToString + FromStr,
1735    ) -> eyre::Result<()> {
1736        let blank_fn = self.add_func(&[], &[], |builder, _| {
1737            builder.func_body().unreachable();
1738            Ok(())
1739        })?;
1740
1741        let name = format!(
1742            "__wasip1_vfs_flag_info_{}_{}",
1743            key.as_ref(),
1744            info.to_string()
1745        );
1746
1747        self.exports.add(&name, blank_fn);
1748
1749        Ok(())
1750    }
1751
1752    fn load_info<T: ToString + FromStr>(&mut self, key: impl AsRef<str>) -> eyre::Result<T>
1753    where
1754        <T as std::str::FromStr>::Err: Debug,
1755    {
1756        let name = format!("__wasip1_vfs_flag_info_{}_", key.as_ref());
1757        let export = self
1758            .exports
1759            .iter()
1760            .find(|e| e.name.starts_with(&name))
1761            .ok_or_else(|| eyre::eyre!("No info found"))?;
1762        let info_str = &export.name[name.len()..];
1763        let info = info_str
1764            .parse::<T>()
1765            .map_err(|e| eyre::eyre!("Failed to parse info: {:?}", e))?;
1766
1767        self.exports.delete(export.id());
1768
1769        Ok(info)
1770    }
1771
1772    fn connect_func_alt_with_remove_export<A>(
1773        &mut self,
1774        import: impl WalrusFID<A>,
1775        export: impl AsRef<str>,
1776        is_debug: bool,
1777    ) -> eyre::Result<()> {
1778        self.connect_func_alt(import, export.as_ref())?;
1779        if !is_debug {
1780            self.exports.remove(export.as_ref()).unwrap();
1781        }
1782
1783        Ok(())
1784    }
1785}
1786
1787impl WalrusUtilFuncs for walrus::ModuleFunctions {
1788    fn find_children(
1789        &self,
1790        fid: impl Borrow<FunctionId>,
1791        allow_call_indirect: bool,
1792    ) -> eyre::Result<Vec<FunctionId>> {
1793        let fid = *fid.borrow();
1794
1795        let mut children = vec![];
1796        let mut stack = vec![fid];
1797        while let Some(fid) = stack.pop() {
1798            match &self.get(fid).kind {
1799                FunctionKind::Local(imported_function) => {
1800                    imported_function
1801                        .read(|instr, _| {
1802                            use walrus::ir::*;
1803                            match instr {
1804                                Instr::Call(Call { func })
1805                                | Instr::ReturnCall(ReturnCall { func, .. }) => {
1806                                    if !children.contains(func) {
1807                                        children.push(*func);
1808                                        stack.push(*func);
1809                                    }
1810                                }
1811                                Instr::CallIndirect(call) if !allow_call_indirect => {
1812                                    eyre::bail!("Call indirect found: {call:?} in find children");
1813                                }
1814                                Instr::ReturnCallIndirect(call) if !allow_call_indirect => {
1815                                    eyre::bail!(
1816                                        "Return call indirect found: {call:?} in find children"
1817                                    );
1818                                }
1819                                _ => {}
1820                            }
1821                            Ok(())
1822                        })?
1823                        .into_iter()
1824                        .collect::<eyre::Result<Vec<_>>>()?;
1825                }
1826                _ => {}
1827            }
1828        }
1829        Ok(children)
1830    }
1831
1832    fn rewrite<T>(
1833        &mut self,
1834        find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
1835        fid: impl Borrow<FunctionId>,
1836    ) -> eyre::Result<Vec<T>>
1837    where
1838        Self: Sized,
1839    {
1840        let fid = *fid.borrow();
1841
1842        let func = self.get_mut(fid);
1843        if let FunctionKind::Local(local_func) = &mut func.kind {
1844            local_func.builder_mut().func_body().rewrite(find)
1845        } else {
1846            eyre::bail!("Function is not local");
1847        }
1848    }
1849
1850    fn read<T>(
1851        &self,
1852        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
1853        fid: impl Borrow<FunctionId>,
1854    ) -> eyre::Result<Vec<T>>
1855    where
1856        Self: Sized,
1857    {
1858        let fid = *fid.borrow();
1859
1860        let func = self.get(fid);
1861        if let FunctionKind::Local(local_func) = &func.kind {
1862            local_func.read(&mut find)
1863        } else {
1864            eyre::bail!("Function is not local");
1865        }
1866    }
1867
1868    fn flat_rewrite<T>(
1869        &mut self,
1870        mut find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
1871        fid: impl Borrow<FunctionId>,
1872        allow_call_indirect: bool,
1873    ) -> eyre::Result<Vec<T>>
1874    where
1875        Self: Sized,
1876    {
1877        self.find_children_with(fid, allow_call_indirect)?
1878            .into_iter()
1879            .filter(|fid| {
1880                if let walrus::FunctionKind::Local(_) = self.get(*fid).kind {
1881                    true
1882                } else {
1883                    false
1884                }
1885            })
1886            .collect::<Vec<_>>()
1887            .into_iter()
1888            .map(|fid| self.rewrite(&mut find, fid))
1889            .flatten_ok()
1890            .collect()
1891    }
1892
1893    fn flat_read<T>(
1894        &self,
1895        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
1896        fid: impl Borrow<FunctionId>,
1897    ) -> eyre::Result<Vec<T>>
1898    where
1899        Self: Sized,
1900    {
1901        self.find_children_with(fid, false)?
1902            .into_iter()
1903            .filter(|fid| {
1904                if let walrus::FunctionKind::Local(_) = self.get(*fid).kind {
1905                    true
1906                } else {
1907                    false
1908                }
1909            })
1910            .map(|fid| self.read(&mut find, fid))
1911            .flatten_ok()
1912            .collect()
1913    }
1914
1915    fn all_read<T>(
1916        &self,
1917        mut find: impl FnMut(&ir::Instr, (usize, InstrSeqId)) -> T,
1918        exclude: &[impl Borrow<FunctionId>],
1919    ) -> eyre::Result<Vec<T>>
1920    where
1921        Self: Sized,
1922    {
1923        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
1924        self.iter_local()
1925            .filter(|(fid, _)| !exclude.contains(fid))
1926            .map(|(fid, _)| self.read(&mut find, fid))
1927            .flatten_ok()
1928            .collect()
1929    }
1930
1931    fn all_rewrite<T>(
1932        &mut self,
1933        mut find: impl FnMut(&mut ir::Instr, (usize, InstrSeqId)) -> T,
1934        exclude: &[impl Borrow<FunctionId>],
1935    ) -> eyre::Result<Vec<T>>
1936    where
1937        Self: Sized,
1938    {
1939        let exclude = exclude.iter().map(|e| *e.borrow()).collect::<Vec<_>>();
1940        self.iter_local()
1941            .filter(|(fid, _)| !exclude.contains(fid))
1942            .map(|(fid, _)| fid)
1943            .collect::<Vec<_>>()
1944            .into_iter()
1945            .map(|fid| self.rewrite(&mut find, fid))
1946            .flatten_ok()
1947            .collect()
1948    }
1949}
1950
1951pub trait CaminoUtilModule {
1952    fn get_file_main_name(&self) -> Option<CompactString>;
1953}
1954
1955impl CaminoUtilModule for camino::Utf8Path {
1956    fn get_file_main_name(&self) -> Option<CompactString> {
1957        let binding = self.file_name().unwrap().split(".").collect::<Vec<_>>();
1958        let file_name_poss = binding.iter().rev();
1959        let mut file_name = None;
1960        for name in file_name_poss {
1961            if *name == "opt"
1962                || *name == "adjusted"
1963                || *name == "wasm"
1964                || *name == "core"
1965                || *name == "component"
1966            {
1967                continue;
1968            }
1969            file_name = Some(name);
1970            break;
1971        }
1972        let file_name = file_name.map(ToOwned::to_owned).or_else(|| {
1973            self.file_name()
1974                .unwrap()
1975                .split(".")
1976                .next()
1977                .as_ref()
1978                .cloned()
1979        });
1980
1981        file_name.map(CompactString::from)
1982    }
1983}
1984
1985impl CaminoUtilModule for PathBuf {
1986    fn get_file_main_name(&self) -> Option<CompactString> {
1987        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
1988    }
1989}
1990
1991impl CaminoUtilModule for Path {
1992    fn get_file_main_name(&self) -> Option<CompactString> {
1993        camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
1994    }
1995}
1996
1997pub trait ResultUtil<T> {
1998    fn to_eyre(self) -> eyre::Result<T>;
1999}
2000
2001// https://github.com/eyre-rs/eyre/issues/31
2002impl<T> ResultUtil<T> for anyhow::Result<T> {
2003    fn to_eyre(self) -> eyre::Result<T> {
2004        self.map_err(|e| {
2005            eyre::eyre!(Box::<dyn std::error::Error + Send + Sync + 'static>::from(
2006                e
2007            ))
2008        })
2009    }
2010}
2011
2012impl<T, I: Iterator> ResultUtil<T> for Result<T, itertools::ExactlyOneError<I>> {
2013    fn to_eyre(self) -> eyre::Result<T> {
2014        self.map_err(|e| eyre::eyre!(e.to_string()))
2015    }
2016}
2017
2018pub trait Normal<T> {
2019    fn normal(self) -> eyre::Result<T>;
2020}
2021
2022impl Normal<walrus::ir::Value> for walrus::ValType {
2023    fn normal(self) -> eyre::Result<walrus::ir::Value> {
2024        match self {
2025            walrus::ValType::I32 => Ok(walrus::ir::Value::I32(0)),
2026            walrus::ValType::I64 => Ok(walrus::ir::Value::I64(0)),
2027            walrus::ValType::F32 => Ok(walrus::ir::Value::F32(0.0)),
2028            walrus::ValType::F64 => Ok(walrus::ir::Value::F64(0.0)),
2029            walrus::ValType::V128 => Err(eyre::eyre!("V128 not supported")),
2030            ValType::Ref(_) => Err(eyre::eyre!("Ref not supported")),
2031        }
2032    }
2033}
2034
2035pub const CORE_MODULE_ROOT: &str = "wasip1-vfs:host/virtual-file-system-wasip1-core";
2036pub const THREADS_MODULE_ROOT: &str = "wasip1-vfs:host/virtual-file-system-wasip1-threads-import";
2037pub const NAMESPACE: &str = "wasip1-vfs";
2038
2039pub trait WalrusFID<Marker>: Copy {
2040    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId>;
2041    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId>;
2042    fn as_str(self) -> String;
2043}
2044
2045pub trait WalrusFIDAssister {
2046    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId>;
2047    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId>;
2048    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId>;
2049    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId>;
2050    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId>;
2051    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId>;
2052}
2053
2054pub struct FunctionIdMarker;
2055pub struct StrMarker;
2056pub struct DoubleStrMarker;
2057
2058impl<B: Borrow<FunctionId> + Copy> WalrusFID<FunctionIdMarker> for B {
2059    fn as_str(self) -> String {
2060        format!("{:?}", self.borrow())
2061    }
2062
2063    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2064        let fid = *self.borrow();
2065        assist
2066            .get_fid_by_fid(fid)
2067            .wrap_err_with(|| eyre::eyre!("FunctionId {:?} not found in get_fid", fid))
2068    }
2069
2070    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2071        let fid = *self.borrow();
2072        assist.find_fid_by_fid(fid)
2073    }
2074}
2075
2076impl<S: AsRef<str> + Copy> WalrusFID<StrMarker> for S {
2077    fn as_str(self) -> String {
2078        self.as_ref().to_string()
2079    }
2080
2081    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2082        let name = self.as_ref();
2083        assist
2084            .get_fid_by_name(name)
2085            .wrap_err_with(|| eyre::eyre!("Function name {name} not found in get_fid"))
2086    }
2087
2088    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2089        let name = self.as_ref();
2090        assist.find_fid_by_name(name)
2091    }
2092}
2093
2094impl<S1: AsRef<str> + Copy, S2: AsRef<str> + Copy> WalrusFID<DoubleStrMarker> for (S1, S2) {
2095    fn as_str(self) -> String {
2096        format!("{}.{}", self.0.as_ref(), self.1.as_ref())
2097    }
2098
2099    fn get_fid(self, assist: &impl WalrusFIDAssister) -> eyre::Result<FunctionId> {
2100        let module = self.0.as_ref();
2101        let name = self.1.as_ref();
2102        assist
2103            .get_fid_by_double_name(module, name)
2104            .wrap_err_with(|| eyre::eyre!("Function name {module}.{name} not found in get_fid"))
2105    }
2106
2107    fn find_fid(self, assist: &impl WalrusFIDAssister) -> Option<FunctionId> {
2108        let module = self.0.as_ref();
2109        let name = self.1.as_ref();
2110        assist.find_fid_by_double_name(module, name)
2111    }
2112}
2113
2114impl WalrusFIDAssister for walrus::Module {
2115    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2116        if self.funcs.iter().any(|f| f.id() == fid) {
2117            Ok(fid)
2118        } else {
2119            eyre::bail!("FunctionId {:?} not found in get_fid_by_fid", fid);
2120        }
2121    }
2122
2123    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2124        if self.funcs.iter().any(|f| f.id() == fid) {
2125            Some(fid)
2126        } else {
2127            None
2128        }
2129    }
2130
2131    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2132        if let Ok(id) = self.exports.get_fid_by_name(name) {
2133            Some(id)
2134        } else {
2135            self.imports.find_fid_by_name(name)
2136        }
2137    }
2138
2139    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2140        if let Ok(id) = self.exports.get_fid_by_name(name) {
2141            Ok(id)
2142        } else {
2143            self.imports.get_fid_by_name(name)
2144        }
2145    }
2146
2147    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId> {
2148        self.imports.get_fid_by_double_name(module, name)
2149    }
2150
2151    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId> {
2152        self.imports.find_fid_by_double_name(module, name)
2153    }
2154}
2155
2156impl WalrusFIDAssister for walrus::ModuleImports {
2157    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2158        if self.iter().any(|im| match im.kind {
2159            walrus::ImportKind::Function(f) if f == fid => true,
2160            _ => false,
2161        }) {
2162            Ok(fid)
2163        } else {
2164            eyre::bail!("FunctionId {fid:?} not found in get_fid_by_fid");
2165        }
2166    }
2167
2168    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2169        if self.iter().any(|im| match im.kind {
2170            walrus::ImportKind::Function(f) if f == fid => true,
2171            _ => false,
2172        }) {
2173            Some(fid)
2174        } else {
2175            None
2176        }
2177    }
2178
2179    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2180        self.iter()
2181            .filter_map(|im| match im.kind {
2182                walrus::ImportKind::Function(fid) if im.name == name => Some(fid),
2183                _ => None,
2184            })
2185            .exactly_one()
2186            .ok()
2187    }
2188
2189    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2190        self.iter()
2191            .filter_map(|im| match im.kind {
2192                walrus::ImportKind::Function(fid) if im.name == name => Some(fid),
2193                _ => None,
2194            })
2195            .exactly_one()
2196            .to_eyre()
2197            .wrap_err_with(|| {
2198                eyre::eyre!("Multiple or no function name {name} found in get_fid_by_name")
2199            })
2200    }
2201
2202    fn get_fid_by_double_name(&self, module: &str, name: &str) -> eyre::Result<FunctionId> {
2203        self.iter()
2204            .filter_map(|im| match im.kind {
2205                walrus::ImportKind::Function(fid) if im.name == name && im.module == module => {
2206                    Some(fid)
2207                }
2208                _ => None,
2209            })
2210            .exactly_one()
2211            .to_eyre()
2212            .wrap_err_with(|| {
2213                eyre::eyre!("Function name {module}.{name} not found in get_fid_by_double_name")
2214            })
2215    }
2216
2217    fn find_fid_by_double_name(&self, module: &str, name: &str) -> Option<FunctionId> {
2218        self.iter()
2219            .filter_map(|im| match im.kind {
2220                walrus::ImportKind::Function(fid) if im.name == name && im.module == module => {
2221                    Some(fid)
2222                }
2223                _ => None,
2224            })
2225            .exactly_one()
2226            .ok()
2227    }
2228}
2229
2230impl WalrusFIDAssister for ModuleExports {
2231    fn get_fid_by_fid(&self, fid: FunctionId) -> eyre::Result<FunctionId> {
2232        if self.iter().any(|ex| match ex.item {
2233            walrus::ExportItem::Function(f) if f == fid => true,
2234            _ => false,
2235        }) {
2236            Ok(fid)
2237        } else {
2238            eyre::bail!("FunctionId {:?} not found in get_fid_by_fid", fid);
2239        }
2240    }
2241
2242    fn find_fid_by_fid(&self, fid: FunctionId) -> Option<FunctionId> {
2243        if self.iter().any(|ex| match ex.item {
2244            walrus::ExportItem::Function(f) if f == fid => true,
2245            _ => false,
2246        }) {
2247            Some(fid)
2248        } else {
2249            None
2250        }
2251    }
2252
2253    fn find_fid_by_name(&self, name: &str) -> Option<FunctionId> {
2254        self.iter().find_map(|ex| match ex.item {
2255            walrus::ExportItem::Function(fid) if ex.name == name => Some(fid),
2256            _ => None,
2257        })
2258    }
2259
2260    fn get_fid_by_name(&self, name: &str) -> eyre::Result<FunctionId> {
2261        self.iter()
2262            .find_map(|ex| match ex.item {
2263                walrus::ExportItem::Function(fid) if ex.name == name => Some(fid),
2264                _ => None,
2265            })
2266            .wrap_err_with(|| eyre::eyre!("Function name {name} not found in get_fid_by_name"))
2267    }
2268
2269    fn get_fid_by_double_name(&self, _: &str, _: &str) -> eyre::Result<FunctionId> {
2270        panic!("Module name is not stored in exports, cannot get by double name");
2271    }
2272
2273    fn find_fid_by_double_name(&self, _: &str, _: &str) -> Option<FunctionId> {
2274        panic!("Module name is not stored in exports, cannot find by double name");
2275    }
2276}
2277
2278// pub fn init_data_set(buff: &mut walrus::ModuleData, offset: u32, data: &[u8]) -> eyre::Result<()> {
2279//     let data_ids = buff.iter().map(|data| data.id()).collect::<Vec<_>>();
2280
2281//     for id in data_ids {
2282//         let data = buff.get_mut(id);
2283//         if let walrus::DataKind::Active(walrus::ActiveData {
2284//             memory: _,
2285//             offset: walrus::ir::Value::I32(current_offset),
2286//             ..
2287//         }) = &data.kind
2288//         {
2289//             let current_offset = *current_offset as u32;
2290//             if current_offset <= offset && offset < current_offset + data.value.len() as u32 {
2291//                 let start = (offset - current_offset) as usize;
2292//                 let end = std::cmp::min(start + data.value.len(), start + data.len());
2293//                 data.value[start..end].copy_from_slice(&data[..(end - start)]);
2294//                 return Ok(());
2295//             }
2296//         }
2297//     }
2298
2299//     Ok(())
2300// }
2301
2302#[derive(Debug)]
2303pub struct LStringHolder(&'static [compact_str::CompactString], &'static AtomicUsize);
2304
2305impl LStringHolder {
2306    pub fn new(strings: Box<[compact_str::CompactString]>) -> Self {
2307        let count = Box::leak(Box::new(AtomicUsize::new(0)));
2308
2309        let strings = Box::leak(strings);
2310        LStringHolder(strings, count)
2311    }
2312
2313    pub fn iter(&self) -> impl Iterator<Item = LString> {
2314        self.0.iter().map(|s| LString::new(s.as_str(), self.1))
2315    }
2316}
2317
2318impl Drop for LStringHolder {
2319    fn drop(&mut self) {
2320        unsafe {
2321            let _ = Box::from_raw(self.0 as *const _ as *mut [compact_str::CompactString]);
2322            let count = self.1.load(std::sync::atomic::Ordering::SeqCst);
2323            let _ = Box::from_raw(self.1 as *const _ as *mut AtomicUsize);
2324            if count != 0 {
2325                panic!(
2326                    "LStringHolder dropped while there are still {count} LString instances alive"
2327                );
2328            }
2329        }
2330    }
2331}
2332
2333/// Literal String
2334pub struct LString(&'static str, &'static AtomicUsize);
2335impl LString {
2336    pub fn new(s: &'static str, counter: &'static AtomicUsize) -> Self {
2337        counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2338        LString(s, counter)
2339    }
2340}
2341impl Drop for LString {
2342    fn drop(&mut self) {
2343        self.1.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
2344    }
2345}
2346impl Clone for LString {
2347    fn clone(&self) -> Self {
2348        self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2349        LString(self.0, self.1)
2350    }
2351}
2352impl std::hash::Hash for LString {
2353    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2354        (self.0 as *const str).hash(state);
2355    }
2356}
2357impl PartialEq for LString {
2358    fn eq(&self, other: &Self) -> bool {
2359        std::ptr::addr_eq(self.0 as *const _, other.0 as *const _)
2360    }
2361}
2362impl Eq for LString {}
2363impl std::fmt::Debug for LString {
2364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2365        write!(f, "{:?}", self.0)
2366    }
2367}
2368impl std::fmt::Display for LString {
2369    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2370        write!(f, "{}", self.0)
2371    }
2372}
2373impl AsRef<str> for LString {
2374    fn as_ref(&self) -> &str {
2375        &self.0
2376    }
2377}
2378impl Borrow<str> for LString {
2379    fn borrow(&self) -> &str {
2380        &self.0
2381    }
2382}
2383
2384pub const CRATE_NAME: &str = "wasi_virt_layer";
2385
2386#[cfg(test)]
2387mod tests {
2388    use super::*;
2389
2390    #[test]
2391    fn test_get_file_main_name() {
2392        let path = camino::Utf8Path::new("name.opt.adjusted.wasm");
2393        let file_name = path.get_file_main_name();
2394        assert_eq!(file_name.unwrap(), "name");
2395    }
2396}