Skip to main content

wasm_bindgen_cli_support/
lib.rs

1use anyhow::{bail, Context, Error};
2use std::collections::{hash_map::Entry, BTreeMap, HashMap, HashSet};
3use std::env;
4use std::fs;
5use std::mem;
6use std::path::{Path, PathBuf};
7use std::str;
8use walrus::Module;
9
10pub(crate) const PLACEHOLDER_MODULE: &str = "__wbindgen_placeholder__";
11
12mod decode;
13mod descriptor;
14mod descriptors;
15mod externref;
16mod interpreter;
17mod intrinsic;
18mod js;
19mod multivalue;
20mod suggest;
21mod transforms;
22pub mod wasm2es6js;
23mod wasm_conventions;
24mod wit;
25
26pub struct Bindgen {
27    input: Input,
28    out_name: Option<String>,
29    mode: OutputMode,
30    debug: bool,
31    typescript: bool,
32    omit_imports: bool,
33    demangle: bool,
34    keep_lld_exports: bool,
35    keep_debug: bool,
36    split_debug_info: bool,
37    debug_info_url: Option<String>,
38    remove_name_section: bool,
39    remove_producers_section: bool,
40    omit_default_module_path: bool,
41    ts_typed_array_buffers: bool,
42    emit_start: bool,
43    externref: bool,
44    multi_value: bool,
45    encode_into: EncodeInto,
46    split_linked_modules: bool,
47    generate_reset_state: bool,
48    force_enable_abort_handler: bool,
49}
50
51pub struct Output {
52    module: walrus::Module,
53    stem: String,
54    split_debug_info: bool,
55    debug_info_url: Option<String>,
56    generated: Generated,
57}
58
59struct Generated {
60    mode: OutputMode,
61    js: String,
62    ts: String,
63    start: Option<String>,
64    snippets: BTreeMap<String, Vec<String>>,
65    local_modules: HashMap<String, String>,
66    npm_dependencies: HashMap<String, (PathBuf, String)>,
67    typescript: bool,
68    /// For `OutputMode::Emscripten` only: the contents of a sidecar file
69    /// emcc loads via `--extern-pre-js`, containing ESM `import` statements
70    /// that must live at module top-level. Empty for other modes.
71    emscripten_extern_pre_js: String,
72}
73
74#[derive(Clone)]
75enum OutputMode {
76    Bundler { browser_only: bool },
77    Web,
78    NoModules { global: String },
79    Node { module: bool },
80    Deno,
81    Module,
82    Emscripten,
83}
84
85enum Input {
86    Path(PathBuf),
87    Module(Module, String),
88    Bytes(Vec<u8>, String),
89    None,
90}
91
92#[derive(Debug, Clone, Copy)]
93pub enum EncodeInto {
94    Test,
95    Always,
96    Never,
97}
98
99impl Bindgen {
100    pub fn new() -> Bindgen {
101        let externref =
102            env::var("WASM_BINDGEN_ANYREF").is_ok() || env::var("WASM_BINDGEN_EXTERNREF").is_ok();
103        let multi_value = env::var("WASM_BINDGEN_MULTI_VALUE").is_ok();
104        Bindgen {
105            input: Input::None,
106            out_name: None,
107            mode: OutputMode::Bundler {
108                browser_only: false,
109            },
110            debug: false,
111            typescript: false,
112            omit_imports: false,
113            demangle: true,
114            keep_lld_exports: false,
115            keep_debug: false,
116            split_debug_info: false,
117            debug_info_url: None,
118            remove_name_section: false,
119            remove_producers_section: false,
120            emit_start: true,
121            externref,
122            multi_value,
123            encode_into: EncodeInto::Test,
124            omit_default_module_path: true,
125            ts_typed_array_buffers: false,
126            split_linked_modules: false,
127            generate_reset_state: false,
128            force_enable_abort_handler: false,
129        }
130    }
131
132    pub fn input_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Bindgen {
133        self.input = Input::Path(path.as_ref().to_path_buf());
134        self
135    }
136
137    pub fn out_name(&mut self, name: &str) -> &mut Bindgen {
138        self.out_name = Some(name.to_string());
139        self
140    }
141
142    #[deprecated = "automatically detected via `-Ctarget-feature=+reference-types`"]
143    pub fn reference_types(&mut self, enable: bool) -> &mut Bindgen {
144        self.externref = enable;
145        self
146    }
147
148    /// Explicitly specify the already parsed input module.
149    pub fn input_module(&mut self, name: &str, module: Module) -> &mut Bindgen {
150        let name = name.to_string();
151        self.input = Input::Module(module, name);
152        self
153    }
154
155    /// Specify the input as the provided Wasm bytes.
156    pub fn input_bytes(&mut self, name: &str, bytes: Vec<u8>) -> &mut Bindgen {
157        let name = name.to_string();
158        self.input = Input::Bytes(bytes, name);
159        self
160    }
161
162    fn switch_mode(&mut self, mode: OutputMode, flag: &str) -> Result<(), Error> {
163        match self.mode {
164            OutputMode::Bundler { .. } => self.mode = mode,
165            _ => bail!("cannot specify `{flag}` with another output mode already specified"),
166        }
167        Ok(())
168    }
169
170    pub fn nodejs(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
171        if node {
172            self.switch_mode(OutputMode::Node { module: false }, "--target nodejs")?;
173        }
174        Ok(self)
175    }
176
177    pub fn nodejs_module(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
178        if node {
179            self.switch_mode(
180                OutputMode::Node { module: true },
181                "--target experimental-nodejs-module",
182            )?;
183        }
184        Ok(self)
185    }
186
187    pub fn bundler(&mut self, bundler: bool) -> Result<&mut Bindgen, Error> {
188        if bundler {
189            self.switch_mode(
190                OutputMode::Bundler {
191                    browser_only: false,
192                },
193                "--target bundler",
194            )?;
195        }
196        Ok(self)
197    }
198
199    pub fn web(&mut self, web: bool) -> Result<&mut Bindgen, Error> {
200        if web {
201            self.switch_mode(OutputMode::Web, "--target web")?;
202        }
203        Ok(self)
204    }
205
206    pub fn no_modules(&mut self, no_modules: bool) -> Result<&mut Bindgen, Error> {
207        if no_modules {
208            self.switch_mode(
209                OutputMode::NoModules {
210                    global: "wasm_bindgen".to_string(),
211                },
212                "--target no-modules",
213            )?;
214        }
215        Ok(self)
216    }
217
218    pub fn browser(&mut self, browser: bool) -> Result<&mut Bindgen, Error> {
219        if browser {
220            match &mut self.mode {
221                OutputMode::Bundler { browser_only } => *browser_only = true,
222                _ => bail!("cannot specify `--browser` with other output types"),
223            }
224        }
225        Ok(self)
226    }
227
228    pub fn deno(&mut self, deno: bool) -> Result<&mut Bindgen, Error> {
229        if deno {
230            self.switch_mode(OutputMode::Deno, "--target deno")?;
231            self.encode_into(EncodeInto::Always);
232        }
233        Ok(self)
234    }
235
236    pub fn module(&mut self, source_phase: bool) -> Result<&mut Bindgen, Error> {
237        if source_phase {
238            self.switch_mode(OutputMode::Module, "--target module")?;
239        }
240        Ok(self)
241    }
242
243    pub fn no_modules_global(&mut self, name: &str) -> Result<&mut Bindgen, Error> {
244        if !wasm_bindgen_shared::identifier::is_valid_ident(name) {
245            bail!("`--no-modules-global` must be a valid JS identifier, got `{name}`");
246        }
247        match &mut self.mode {
248            OutputMode::NoModules { global } => *global = name.to_string(),
249            _ => bail!("can only specify `--no-modules-global` with `--target no-modules`"),
250        }
251        Ok(self)
252    }
253
254    pub fn debug(&mut self, debug: bool) -> &mut Bindgen {
255        self.debug = debug;
256        self
257    }
258
259    pub fn typescript(&mut self, typescript: bool) -> &mut Bindgen {
260        self.typescript = typescript;
261        self
262    }
263
264    pub fn omit_imports(&mut self, omit_imports: bool) -> &mut Bindgen {
265        self.omit_imports = omit_imports;
266        self
267    }
268
269    pub fn demangle(&mut self, demangle: bool) -> &mut Bindgen {
270        self.demangle = demangle;
271        self
272    }
273
274    pub fn keep_lld_exports(&mut self, keep_lld_exports: bool) -> &mut Bindgen {
275        self.keep_lld_exports = keep_lld_exports;
276        self
277    }
278
279    pub fn keep_debug(&mut self, keep_debug: bool) -> &mut Bindgen {
280        self.keep_debug = keep_debug;
281        self
282    }
283
284    pub fn split_debug_info(&mut self, split: bool) -> &mut Bindgen {
285        self.split_debug_info = split;
286        self
287    }
288
289    pub fn debug_info_url(&mut self, url: &str) -> &mut Bindgen {
290        self.debug_info_url = Some(url.to_string());
291        self
292    }
293
294    pub fn remove_name_section(&mut self, remove: bool) -> &mut Bindgen {
295        self.remove_name_section = remove;
296        self
297    }
298
299    pub fn remove_producers_section(&mut self, remove: bool) -> &mut Bindgen {
300        self.remove_producers_section = remove;
301        self
302    }
303
304    pub fn emit_start(&mut self, emit: bool) -> &mut Bindgen {
305        self.emit_start = emit;
306        self
307    }
308
309    pub fn encode_into(&mut self, mode: EncodeInto) -> &mut Bindgen {
310        self.encode_into = mode;
311        self
312    }
313
314    pub fn omit_default_module_path(&mut self, omit_default_module_path: bool) -> &mut Bindgen {
315        self.omit_default_module_path = omit_default_module_path;
316        self
317    }
318
319    pub fn ts_typed_array_buffers(&mut self, ts_typed_array_buffers: bool) -> &mut Bindgen {
320        self.ts_typed_array_buffers = ts_typed_array_buffers;
321        self
322    }
323
324    pub fn split_linked_modules(&mut self, split_linked_modules: bool) -> &mut Bindgen {
325        self.split_linked_modules = split_linked_modules;
326        self
327    }
328
329    pub fn reset_state_function(&mut self, generate_reset_state: bool) -> &mut Bindgen {
330        self.generate_reset_state = generate_reset_state;
331        self
332    }
333
334    pub fn force_enable_abort_handler(&mut self, force_enable_abort_handler: bool) -> &mut Self {
335        self.force_enable_abort_handler = force_enable_abort_handler;
336        self
337    }
338
339    pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
340        self.generate_output()?.emit(path.as_ref())
341    }
342
343    pub fn stem(&self) -> Result<&str, Error> {
344        Ok(match &self.input {
345            Input::None => bail!("must have an input by now"),
346            Input::Module(_, name) | Input::Bytes(_, name) => name,
347            Input::Path(path) => match &self.out_name {
348                Some(name) => name,
349                None => path.file_stem().unwrap().to_str().unwrap(),
350            },
351        })
352    }
353
354    pub fn generate_output(&mut self) -> Result<Output, Error> {
355        if self.debug_info_url.is_some() && !self.split_debug_info {
356            bail!("cannot specify `debug_info_url` without `split_debug_info`");
357        }
358        let mut module = match self.input {
359            Input::None => bail!("must have an input by now"),
360            Input::Module(ref mut m, _) => {
361                let blank_module = Module::default();
362                mem::replace(m, blank_module)
363            }
364            Input::Path(ref path) => {
365                let bytes = std::fs::read(path)
366                    .with_context(|| format!("failed reading '{}'", path.display()))?;
367                self.module_from_bytes(&bytes).with_context(|| {
368                    format!("failed getting Wasm module for '{}'", path.display())
369                })?
370            }
371            Input::Bytes(ref bytes, _) => self
372                .module_from_bytes(bytes)
373                .context("failed getting Wasm module")?,
374        };
375
376        if module
377            .customs
378            .remove_raw("__wasm_bindgen_emscripten_marker")
379            .is_some()
380        {
381            // Force the internal configuration to Emscripten mode.
382            self.mode = OutputMode::Emscripten;
383        }
384
385        // Enable reference type transformations if the module is already using it.
386        if let Ok(true) = wasm_conventions::target_feature(&module, "reference-types") {
387            self.externref = true;
388        }
389
390        // Enable multivalue transformations if the module is already using it.
391        if let Ok(true) = wasm_conventions::target_feature(&module, "multivalue") {
392            self.multi_value = true;
393        }
394
395        // Check that no exported symbol is called "default" if we target web.
396        if matches!(self.mode, OutputMode::Web)
397            && module.exports.iter().any(|export| export.name == "default")
398        {
399            bail!("exported symbol \"default\" not allowed for --target web")
400        }
401
402        // Check that reset_state is only used with --target module, web, or node
403        if self.generate_reset_state
404            && !matches!(
405                self.mode,
406                OutputMode::Module | OutputMode::Web | OutputMode::Node { module: false }
407            )
408        {
409            bail!("--experimental-reset-state-function is only supported for --target module, --target web, or --target nodejs")
410        }
411
412        let thread_count = if self.mode.emscripten() {
413            // Emscripten owns multithreading bootstrap logic.
414            None
415        } else {
416            transforms::threads::run(&mut module)
417                .with_context(|| "failed to prepare module for threading")?
418        };
419
420        // If requested, turn all mangled symbols into prettier unmangled
421        // symbols with the help of `rustc-demangle`.
422        if self.demangle {
423            demangle(&mut module);
424        }
425        if !self.keep_lld_exports && !self.mode.emscripten() {
426            unexported_unused_lld_things(&mut module);
427        }
428        // Quick fix for https://github.com/wasm-bindgen/wasm-bindgen/pull/4931
429        // which is likely a compiler bug
430        {
431            let exn_import = module.imports.iter().find_map(|impt| match impt.kind {
432                walrus::ImportKind::Tag(id)
433                    if impt.module == "env" && impt.name == "__cpp_exception" =>
434                {
435                    Some((impt, id))
436                }
437                _ => None,
438            });
439            if let Some((import, id)) = exn_import {
440                let original_import_id = import.id();
441                let tag = module.tags.get_mut(id);
442                tag.kind = walrus::TagKind::Local;
443                module.imports.delete(original_import_id);
444                module.exports.add("__cpp_exception", tag.id);
445            }
446
447            // We're making quite a few changes, list ourselves as a producer.
448            module
449                .producers
450                .add_processed_by("wasm-bindgen", &wasm_bindgen_shared::version());
451        }
452        // Parse and remove our custom section before executing descriptors.
453        // That includes checking that the binary has the same schema version
454        // as this version of the CLI, which is why we do it first - to make
455        // sure that this binary was produced by a compatible version of the
456        // wasm-bindgen macro before attempting to interpret our unstable
457        // descriptor format. That way, we give a more helpful version mismatch
458        // error instead of an unhelpful panic if an incompatible descriptor is
459        // found.
460        let mut storage = Vec::new();
461        let programs = wit::extract_programs(&mut module, &mut storage)?;
462
463        // Learn about the type signatures of all wasm-bindgen imports and
464        // exports by executing `__wbindgen_describe_*` functions. This'll
465        // effectively move all the descriptor functions to their own custom
466        // sections.
467        descriptors::execute(&mut module)?;
468
469        // Process the custom section we extracted earlier. In its stead insert
470        // a forward-compatible Wasm interface types section as well as an
471        // auxiliary section for all sorts of miscellaneous information and
472        // features #[wasm_bindgen] supports that aren't covered by wasm
473        // interface types.
474        wit::process(self, &mut module, programs, thread_count)?;
475
476        // Now that we've got type information from the webidl processing pass,
477        // touch up the output of rustc to insert externref shims where necessary.
478        // This is only done if the externref pass is enabled, which it's
479        // currently off-by-default since `externref` is still in development in
480        // engines.
481        //
482        // If the externref pass isn't necessary, then we blanket delete the
483        // export of all our externref intrinsics which will get cleaned up in the
484        // GC pass before JS generation.
485        if self.externref {
486            externref::process(&mut module)?;
487        } else {
488            let ids = module
489                .exports
490                .iter()
491                .filter(|e| e.name.starts_with("__externref"))
492                .map(|e| e.id())
493                .collect::<Vec<_>>();
494            for id in ids {
495                module.exports.delete(id);
496            }
497            // Clean up element segments as well if they have holes in them
498            // after some of our transformations, because non-externref engines
499            // only support contiguous arrays of function references in element
500            // segments.
501            externref::force_contiguous_elements(&mut module)?;
502        }
503
504        // Using all of our metadata convert our module to a multi-value using
505        // module if applicable.
506        if self.multi_value {
507            multivalue::run(&mut module)
508                .context("failed to transform return pointers into multi-value Wasm")?;
509        }
510
511        // Detect the exception-handling version before the JSPI transform
512        // runs: the JSPI suspending wrappers contain `try_table`s of their
513        // own, which would otherwise reclassify a `panic=abort` module as
514        // having full (unwinding) exception support.
515        let eh_version =
516            transforms::detect_exception_handling_version(&module, self.force_enable_abort_handler);
517
518        // Instrument JSPI exports and suspending imports with the in-wasm
519        // shadow-stack save/restore wrappers. This must run after the
520        // externref/multi-value passes (which repoint export items) and
521        // before the catch-wrapper pass, which then wraps *outside* the
522        // suspending wrappers (via the repointed `implements` entries) so
523        // that promise rejections are consumed innermost as data while
524        // SuspendError misuse and rethrown exceptions still reach the
525        // abort/catch machinery over a restored shadow stack. The transform
526        // is target agnostic: on emscripten it operates against emscripten's
527        // `__stack_pointer` in exactly the same way, with no interaction
528        // with emscripten's own JSPI machinery.
529        run_jspi_transform(&mut module, self.externref)?;
530
531        // Generate Wasm catch wrappers for imports with #[wasm_bindgen(catch)].
532        // This runs after externref processing so that we have access to the
533        // externref table and allocation function.
534        //
535        // Emscripten output may contain wasm exception-handling instructions
536        // from linked libc++ / embind that have no relation to wasm-bindgen's
537        // `#[wasm_bindgen(catch)]` machinery, and the wasm-bindgen runtime
538        // intrinsics (`__externref_table`, `__externref_table_alloc`,
539        // `__wbindgen_exn_store`) may be absent. Skip the transform until
540        // proper emscripten-mode catch support lands.
541        if !matches!(self.mode, OutputMode::Emscripten) {
542            run_exception_handling_transforms(&mut module, eh_version)?;
543        }
544
545        // We've done a whole bunch of transformations to the Wasm module, many
546        // of which leave "garbage" lying around, so let's prune out all our
547        // unnecessary things here.
548        gc_module_and_adapters(&mut module);
549
550        let stem = self.stem()?;
551
552        // Now we execute the JS generation passes to actually emit JS/TypeScript/etc.
553        let aux = module
554            .customs
555            .delete_typed::<wit::WasmBindgenAux>()
556            .expect("aux section should be present");
557        let adapters = module
558            .customs
559            .delete_typed::<wit::NonstandardWitSection>()
560            .unwrap();
561        let mut cx = js::Context::new(&mut module, self, &adapters, &aux)?;
562        cx.generate()?;
563        let js::FinalizedOutput {
564            js,
565            ts,
566            start,
567            emscripten_extern_pre_js,
568        } = cx.finalize(stem)?;
569        let generated = Generated {
570            snippets: aux.snippets.clone(),
571            local_modules: aux.local_modules.clone(),
572            mode: self.mode.clone(),
573            typescript: self.typescript,
574            npm_dependencies: cx.npm_dependencies.clone(),
575            js,
576            ts,
577            start,
578            emscripten_extern_pre_js,
579        };
580
581        Ok(Output {
582            module,
583            stem: stem.to_string(),
584            split_debug_info: self.split_debug_info,
585            debug_info_url: self.debug_info_url.clone(),
586            generated,
587        })
588    }
589
590    fn module_from_bytes(&self, bytes: &[u8]) -> Result<Module, Error> {
591        walrus::ModuleConfig::new()
592            // Skip validation of the module as LLVM's output is
593            // generally already well-formed and so we won't gain much
594            // from re-validating. Additionally LLVM's current output
595            // for threads includes atomic instructions but doesn't
596            // include shared memory, so it fails that part of
597            // validation!
598            .strict_validate(false)
599            .generate_dwarf(self.keep_debug || self.split_debug_info)
600            .generate_name_section(!self.remove_name_section)
601            .generate_producers_section(!self.remove_producers_section)
602            .parse(bytes)
603            .context("failed to parse input as wasm")
604    }
605
606    fn local_module_name(&self, module: &str) -> String {
607        format!("./snippets/{module}")
608    }
609
610    fn inline_js_module_name(
611        &self,
612        unique_crate_identifier: &str,
613        snippet_idx_in_crate: usize,
614    ) -> String {
615        format!("./snippets/{unique_crate_identifier}/inline{snippet_idx_in_crate}.js",)
616    }
617}
618
619fn reset_indentation(s: &str) -> String {
620    let mut indent: u32 = 0;
621    let mut dst = String::new();
622
623    fn is_doc_comment(line: &str) -> bool {
624        line.starts_with("*")
625    }
626
627    static TAB: &str = "    ";
628
629    for line in s.trim().lines() {
630        let line = line.trim();
631
632        // handle doc comments separately
633        if is_doc_comment(line) {
634            for _ in 0..indent {
635                dst.push_str(TAB);
636            }
637            dst.push(' ');
638            dst.push_str(line);
639            dst.push('\n');
640            continue;
641        }
642
643        if line.starts_with('}') {
644            indent = indent.saturating_sub(1);
645        }
646
647        let extra = if line.starts_with(':') || line.starts_with('?') {
648            1
649        } else {
650            0
651        };
652        if !line.is_empty() {
653            for _ in 0..indent + extra {
654                dst.push_str(TAB);
655            }
656            dst.push_str(line);
657        }
658        dst.push('\n');
659
660        if line.ends_with('{') {
661            indent += 1;
662        }
663    }
664    dst
665}
666
667/// Since Rust will soon adopt v0 mangling as the default,
668/// and the `rustc_demangle` crate doesn't output closure disambiguators,
669/// duplicate symbols can appear. We handle this case manually.
670///
671/// issue: <https://github.com/wasm-bindgen/wasm-bindgen/issues/4820>
672fn demangle(module: &mut Module) {
673    let (lower, upper) = module.funcs.iter().size_hint();
674    let mut counter: HashMap<String, i32> = HashMap::with_capacity(upper.unwrap_or(lower));
675
676    for func in module.funcs.iter_mut() {
677        let Some(name) = &func.name else {
678            continue;
679        };
680
681        let Ok(sym) = rustc_demangle::try_demangle(name) else {
682            continue;
683        };
684
685        let demangled = sym.to_string();
686        match counter.entry(demangled) {
687            Entry::Occupied(mut entry) => {
688                func.name = Some(format!("{}[{}]", entry.key(), entry.get()));
689                *entry.get_mut() += 1;
690            }
691            Entry::Vacant(entry) => {
692                func.name = Some(entry.key().clone());
693                entry.insert(1);
694            }
695        }
696    }
697}
698
699impl OutputMode {
700    fn uses_es_modules(&self) -> bool {
701        matches!(
702            self,
703            OutputMode::Bundler { .. }
704                | OutputMode::Web
705                | OutputMode::Node { module: true }
706                | OutputMode::Deno
707                | OutputMode::Module
708        )
709    }
710
711    fn nodejs(&self) -> bool {
712        matches!(self, OutputMode::Node { .. })
713    }
714
715    fn no_modules(&self) -> bool {
716        matches!(self, OutputMode::NoModules { .. })
717    }
718
719    fn bundler(&self) -> bool {
720        matches!(self, OutputMode::Bundler { .. })
721    }
722
723    fn emscripten(&self) -> bool {
724        matches!(self, OutputMode::Emscripten)
725    }
726}
727
728/// Remove a number of internal exports that are synthesized by Rust's linker,
729/// LLD. These exports aren't typically ever needed and just add extra space to
730/// the binary.
731fn unexported_unused_lld_things(module: &mut Module) {
732    let mut to_remove = Vec::new();
733    for export in module.exports.iter() {
734        match export.name.as_str() {
735            "__heap_base" | "__data_end" | "__indirect_function_table" => {
736                to_remove.push(export.id());
737            }
738            _ => {}
739        }
740    }
741    for id in to_remove {
742        module.exports.delete(id);
743    }
744}
745
746impl Output {
747    pub fn js(&self) -> &str {
748        &self.generated.js
749    }
750
751    pub fn ts(&self) -> Option<&str> {
752        if self.generated.typescript {
753            Some(&self.generated.ts)
754        } else {
755            None
756        }
757    }
758
759    pub fn start(&self) -> Option<&String> {
760        self.generated.start.as_ref()
761    }
762
763    pub fn snippets(&self) -> &BTreeMap<String, Vec<String>> {
764        &self.generated.snippets
765    }
766
767    pub fn local_modules(&self) -> &HashMap<String, String> {
768        &self.generated.local_modules
769    }
770
771    pub fn npm_dependencies(&self) -> &HashMap<String, (PathBuf, String)> {
772        &self.generated.npm_dependencies
773    }
774
775    pub fn wasm(&self) -> &walrus::Module {
776        &self.module
777    }
778
779    pub fn wasm_mut(&mut self) -> &mut walrus::Module {
780        &mut self.module
781    }
782
783    pub fn emit(&mut self, out_dir: impl AsRef<Path>) -> Result<(), Error> {
784        self._emit(out_dir.as_ref())
785    }
786
787    fn _emit(&mut self, out_dir: &Path) -> Result<(), Error> {
788        let wasm_name = format!("{}_bg", self.stem);
789        let wasm_path = out_dir.join(&wasm_name).with_extension("wasm");
790        fs::create_dir_all(out_dir)?;
791
792        let wasm_bytes = self.module.emit_wasm();
793        let wasm_bytes = if self.split_debug_info {
794            let debug_name = format!("{wasm_name}.debug.wasm");
795            let url = self.debug_info_url.as_deref().unwrap_or(&debug_name);
796            let main_bytes = split_debug_info(&wasm_bytes, url)?;
797            let debug_path = out_dir.join(&debug_name);
798            fs::write(&debug_path, &wasm_bytes)
799                .with_context(|| format!("failed to write `{}`", debug_path.display()))?;
800            main_bytes
801        } else {
802            wasm_bytes
803        };
804        fs::write(&wasm_path, wasm_bytes)
805            .with_context(|| format!("failed to write `{}`", wasm_path.display()))?;
806
807        let gen = &self.generated;
808
809        // Write out all local JS snippets to the final destination now that
810        // we've collected them from all the programs.
811        for (identifier, list) in gen.snippets.iter() {
812            for (i, js) in list.iter().enumerate() {
813                let name = format!("inline{i}.js");
814                let path = out_dir.join("snippets").join(identifier).join(name);
815                fs::create_dir_all(path.parent().unwrap())?;
816                fs::write(&path, js)
817                    .with_context(|| format!("failed to write `{}`", path.display()))?;
818            }
819        }
820
821        for (path, contents) in gen.local_modules.iter() {
822            let path = out_dir.join("snippets").join(path);
823            fs::create_dir_all(path.parent().unwrap())?;
824            fs::write(&path, contents)
825                .with_context(|| format!("failed to write `{}`", path.display()))?;
826        }
827
828        let is_genmode_nodemodule = matches!(gen.mode, OutputMode::Node { module: true });
829        if !gen.npm_dependencies.is_empty() || is_genmode_nodemodule {
830            #[derive(serde::Serialize)]
831            struct PackageJson<'a> {
832                #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
833                ty: Option<&'static str>,
834                dependencies: BTreeMap<&'a str, &'a str>,
835            }
836            let pj = PackageJson {
837                ty: is_genmode_nodemodule.then_some("module"),
838                dependencies: gen
839                    .npm_dependencies
840                    .iter()
841                    .map(|(k, v)| (k.as_str(), v.1.as_str()))
842                    .collect(),
843            };
844            let json = serde_json::to_string_pretty(&pj)?;
845            fs::write(out_dir.join("package.json"), json)?;
846        }
847
848        // And now that we've got all our JS and TypeScript, actually write it
849        // out to the filesystem.
850        let extension = "js";
851
852        fn write<P, C>(path: P, contents: C) -> Result<(), anyhow::Error>
853        where
854            P: AsRef<Path>,
855            C: AsRef<[u8]>,
856        {
857            fs::write(&path, contents)
858                .with_context(|| format!("failed to write `{}`", path.as_ref().display()))
859        }
860
861        let js_path = out_dir.join(&self.stem).with_extension(extension);
862        if matches!(self.generated.mode, OutputMode::Emscripten) {
863            let emscripten_js_path = out_dir.join("library_bindgen.js");
864            write(&emscripten_js_path, reset_indentation(&gen.js))?;
865            // When the user crate imports from an ESM module
866            // (`#[wasm_bindgen(module = "...")]`), we emit those imports to a
867            // sidecar `library_bindgen.extern-pre.js`. Consumers pass it to
868            // emcc with `--extern-pre-js`, which prepends it before emcc's
869            // modularize wrapper — ESM imports can only legally live there.
870            // Skip writing when empty so consumers don't accidentally pick
871            // up a stale file from a previous build.
872            let extern_pre_js_path = out_dir.join("library_bindgen.extern-pre.js");
873            if gen.emscripten_extern_pre_js.is_empty() {
874                let _ = fs::remove_file(&extern_pre_js_path);
875            } else {
876                write(
877                    &extern_pre_js_path,
878                    reset_indentation(&gen.emscripten_extern_pre_js),
879                )?;
880            }
881        } else {
882            write(&js_path, reset_indentation(&gen.js))?;
883        }
884
885        if let Some(start) = &gen.start {
886            let js_path = out_dir.join(wasm_name).with_extension(extension);
887            write(&js_path, reset_indentation(start))?;
888        }
889
890        if gen.typescript {
891            let ts_path = js_path.with_extension("d.ts");
892            fs::write(&ts_path, reset_indentation(&gen.ts))
893                .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
894        }
895
896        if gen.typescript {
897            let ts_path = wasm_path.with_extension("wasm.d.ts");
898            let ts = wasm2es6js::typescript(&self.module)?;
899            fs::write(&ts_path, reset_indentation(&ts))
900                .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
901        }
902
903        Ok(())
904    }
905}
906
907/// Remove the `.debug_*` custom sections from an emitted Wasm module and
908/// append an `external_debug_info` custom section that holds `url`.
909///
910/// Ref: https://github.com/WebAssembly/tool-conventions/blob/main/Debugging.md
911fn split_debug_info(wasm: &[u8], url: &str) -> Result<Vec<u8>, Error> {
912    let mut kept = Vec::new();
913    let mut keep_from = 0;
914    let mut section_start = 0;
915    for payload in wasmparser::Parser::new(0).parse_all(wasm) {
916        let payload = payload?;
917        if let wasmparser::Payload::CustomSection(section) = &payload {
918            if section.name().starts_with(".debug_") {
919                kept.push(keep_from..section_start);
920                keep_from = section.range().end;
921            }
922        }
923        if let wasmparser::Payload::Version { range, .. } = &payload {
924            section_start = range.end;
925        } else if let Some((_, range)) = payload.as_section() {
926            section_start = range.end;
927        }
928    }
929    kept.push(keep_from..wasm.len());
930
931    let mut contents = Vec::new();
932    let name = "external_debug_info";
933    leb128::write::unsigned(&mut contents, name.len() as u64)?;
934    contents.extend_from_slice(name.as_bytes());
935    leb128::write::unsigned(&mut contents, url.len() as u64)?;
936    contents.extend_from_slice(url.as_bytes());
937
938    let kept_len: usize = kept.iter().map(|range| range.len()).sum();
939    let mut out = Vec::with_capacity(kept_len + contents.len() + 6);
940    for range in kept {
941        out.extend_from_slice(&wasm[range]);
942    }
943    out.push(0);
944    leb128::write::unsigned(&mut out, contents.len() as u64)?;
945    out.extend_from_slice(&contents);
946    Ok(out)
947}
948
949/// Instrument `#[wasm_bindgen(jspi)]` exports and `#[wasm_bindgen(suspending)]`
950/// imports with in-wasm shadow-stack management. See `transforms::jspi`.
951fn run_jspi_transform(module: &mut Module, externref: bool) -> Result<(), Error> {
952    let mut aux = module
953        .customs
954        .delete_typed::<wit::WasmBindgenAux>()
955        .expect("aux section should exist");
956    let mut wit = module
957        .customs
958        .delete_typed::<wit::NonstandardWitSection>()
959        .expect("wit section should exist");
960
961    let result = transforms::jspi::run(module, &mut aux, &mut wit, externref)
962        .context("failed to instrument module for JSPI");
963
964    module.customs.add(*wit);
965    module.customs.add(*aux);
966
967    result
968}
969
970/// Run the exception-handling transforms: catch wrappers for imports marked
971/// `#[wasm_bindgen(catch)]`, then shadow stack restore wrappers for the exports
972/// a panic can unwind out of.
973///
974/// They share a function so they share one EH detection. Re-detecting in
975/// between would see `catch_handler`'s own `try_table`s and reclassify a
976/// `panic=abort` module as `Modern`.
977fn run_exception_handling_transforms(
978    module: &mut Module,
979    eh_version: transforms::ExceptionHandlingVersion,
980) -> Result<(), Error> {
981    log::debug!("Exception handling version: {eh_version:?}");
982
983    if eh_version == transforms::ExceptionHandlingVersion::None {
984        return Ok(());
985    }
986
987    // We need to temporarily remove the custom sections to avoid borrow issues
988    let mut aux = module
989        .customs
990        .delete_typed::<wit::WasmBindgenAux>()
991        .expect("aux section should exist");
992    let wit = module
993        .customs
994        .delete_typed::<wit::NonstandardWitSection>()
995        .expect("wit section should exist");
996
997    log::debug!(
998        "Running catch handler: imports_with_catch={}, externref_table={:?}, externref_alloc={:?}, exn_store={:?}",
999        aux.imports_with_catch.len(),
1000        aux.externref_table,
1001        aux.externref_alloc,
1002        aux.exn_store
1003    );
1004
1005    let result = transforms::catch_handler::run(module, &mut aux, &wit, eh_version)
1006        .context("failed to generate catch wrappers");
1007    if result.is_ok() {
1008        transforms::export_sp_restore::run(module, &wit, eh_version);
1009    }
1010
1011    // Re-add the custom sections
1012    module.customs.add(*wit);
1013    module.customs.add(*aux);
1014
1015    result
1016}
1017
1018fn gc_module_and_adapters(module: &mut Module) {
1019    loop {
1020        // Fist up, cleanup the native Wasm module. Note that roots can come
1021        // from custom sections, namely our Wasm interface types custom section
1022        // as well as the aux section.
1023        walrus::passes::gc::run(module);
1024
1025        // ... and afterwards we can delete any `implements` directives for any
1026        // imports that have been deleted.
1027        let imports_remaining = module
1028            .imports
1029            .iter()
1030            .map(|i| i.id())
1031            .collect::<HashSet<_>>();
1032        let mut section = module
1033            .customs
1034            .delete_typed::<wit::NonstandardWitSection>()
1035            .unwrap();
1036        section
1037            .implements
1038            .retain(|pair| imports_remaining.contains(&pair.0));
1039
1040        // ... and after we delete the `implements` directive we try to
1041        // delete some adapters themselves. If nothing is deleted, then we're
1042        // good to go. If something is deleted though then we may have free'd up
1043        // some functions in the main module to get deleted, so go again to gc
1044        // things.
1045        let any_removed = section.gc();
1046        module.customs.add(*section);
1047        if !any_removed {
1048            break;
1049        }
1050    }
1051}
1052
1053/// Returns a sorted iterator over a hash map, sorted based on key.
1054///
1055/// The intention of this API is to be used whenever the iteration order of a
1056/// `HashMap` might affect the generated JS bindings. We want to ensure that the
1057/// generated output is deterministic and we do so by ensuring that iteration of
1058/// hash maps is consistently sorted.
1059fn sorted_iter<K, V>(map: &HashMap<K, V>) -> impl Iterator<Item = (&K, &V)>
1060where
1061    K: Ord,
1062{
1063    let mut pairs = map.iter().collect::<Vec<_>>();
1064    pairs.sort_by_key(|(k, _)| *k);
1065    pairs.into_iter()
1066}