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        // Emitted by the runtime under `--cfg wasm_bindgen_unstable_jspi`:
386        // JSPI goes through Emscripten's lifecycle hooks.
387        let emscripten_jspi_hooks = module
388            .customs
389            .remove_raw("__wasm_bindgen_emscripten_jspi_marker")
390            .is_some()
391            && matches!(self.mode, OutputMode::Emscripten);
392
393        // Enable reference type transformations if the module is already using it.
394        if let Ok(true) = wasm_conventions::target_feature(&module, "reference-types") {
395            self.externref = true;
396        }
397
398        // Enable multivalue transformations if the module is already using it.
399        if let Ok(true) = wasm_conventions::target_feature(&module, "multivalue") {
400            self.multi_value = true;
401        }
402
403        // Check that no exported symbol is called "default" if we target web.
404        if matches!(self.mode, OutputMode::Web)
405            && module.exports.iter().any(|export| export.name == "default")
406        {
407            bail!("exported symbol \"default\" not allowed for --target web")
408        }
409
410        // Check that reset_state is only used with --target module, web, or node
411        if self.generate_reset_state
412            && !matches!(
413                self.mode,
414                OutputMode::Module | OutputMode::Web | OutputMode::Node { module: false }
415            )
416        {
417            bail!("--experimental-reset-state-function is only supported for --target module, --target web, or --target nodejs")
418        }
419
420        let thread_count = if self.mode.emscripten() {
421            // Emscripten owns multithreading bootstrap logic.
422            None
423        } else {
424            transforms::threads::run(&mut module)
425                .with_context(|| "failed to prepare module for threading")?
426        };
427
428        // If requested, turn all mangled symbols into prettier unmangled
429        // symbols with the help of `rustc-demangle`.
430        if self.demangle {
431            demangle(&mut module);
432        }
433        if !self.keep_lld_exports && !self.mode.emscripten() {
434            unexported_unused_lld_things(&mut module);
435        }
436        // Quick fix for https://github.com/wasm-bindgen/wasm-bindgen/pull/4931
437        // which is likely a compiler bug
438        {
439            let exn_import = module.imports.iter().find_map(|impt| match impt.kind {
440                walrus::ImportKind::Tag(id)
441                    if impt.module == "env" && impt.name == "__cpp_exception" =>
442                {
443                    Some((impt, id))
444                }
445                _ => None,
446            });
447            if let Some((import, id)) = exn_import {
448                let original_import_id = import.id();
449                let tag = module.tags.get_mut(id);
450                tag.kind = walrus::TagKind::Local;
451                module.imports.delete(original_import_id);
452                module.exports.add("__cpp_exception", tag.id);
453            }
454
455            // We're making quite a few changes, list ourselves as a producer.
456            module
457                .producers
458                .add_processed_by("wasm-bindgen", &wasm_bindgen_shared::version());
459        }
460        // Parse and remove our custom section before executing descriptors.
461        // That includes checking that the binary has the same schema version
462        // as this version of the CLI, which is why we do it first - to make
463        // sure that this binary was produced by a compatible version of the
464        // wasm-bindgen macro before attempting to interpret our unstable
465        // descriptor format. That way, we give a more helpful version mismatch
466        // error instead of an unhelpful panic if an incompatible descriptor is
467        // found.
468        let mut storage = Vec::new();
469        let programs =
470            wit::extract_programs(&mut module, &mut storage).map_err(|err| match &self.input {
471                Input::Path(path) => err.context(format!(
472                    "failed to read wasm-bindgen data from '{}'",
473                    path.display()
474                )),
475                _ => err,
476            })?;
477
478        // Learn about the type signatures of all wasm-bindgen imports and
479        // exports by executing `__wbindgen_describe_*` functions. This'll
480        // effectively move all the descriptor functions to their own custom
481        // sections.
482        descriptors::execute(&mut module)?;
483
484        // Process the custom section we extracted earlier. In its stead insert
485        // a forward-compatible Wasm interface types section as well as an
486        // auxiliary section for all sorts of miscellaneous information and
487        // features #[wasm_bindgen] supports that aren't covered by wasm
488        // interface types.
489        wit::process(self, &mut module, programs, thread_count)?;
490
491        // Now that we've got type information from the webidl processing pass,
492        // touch up the output of rustc to insert externref shims where necessary.
493        // This is only done if the externref pass is enabled, which it's
494        // currently off-by-default since `externref` is still in development in
495        // engines.
496        //
497        // If the externref pass isn't necessary, then we blanket delete the
498        // export of all our externref intrinsics which will get cleaned up in the
499        // GC pass before JS generation.
500        if self.externref {
501            externref::process(&mut module)?;
502        } else {
503            let ids = module
504                .exports
505                .iter()
506                .filter(|e| e.name.starts_with("__externref"))
507                .map(|e| e.id())
508                .collect::<Vec<_>>();
509            for id in ids {
510                module.exports.delete(id);
511            }
512            // Clean up element segments as well if they have holes in them
513            // after some of our transformations, because non-externref engines
514            // only support contiguous arrays of function references in element
515            // segments.
516            externref::force_contiguous_elements(&mut module)?;
517        }
518
519        // Using all of our metadata convert our module to a multi-value using
520        // module if applicable.
521        if self.multi_value {
522            multivalue::run(&mut module)
523                .context("failed to transform return pointers into multi-value Wasm")?;
524        }
525
526        // Detect the exception-handling version before the JSPI transform
527        // runs: the JSPI suspending wrappers contain `try_table`s of their
528        // own, which would otherwise reclassify a `panic=abort` module as
529        // having full (unwinding) exception support.
530        let eh_version =
531            transforms::detect_exception_handling_version(&module, self.force_enable_abort_handler);
532
533        // Instrument JSPI exports and suspending imports with the in-wasm
534        // shadow-stack save/restore wrappers. This must run after the
535        // externref/multi-value passes (which repoint export items) and
536        // before the catch-wrapper pass, which then wraps *outside* the
537        // suspending wrappers (via the repointed `implements` entries) so
538        // that promise rejections are consumed innermost as data while
539        // SuspendError misuse and rethrown exceptions still reach the
540        // abort/catch machinery over a restored shadow stack. On emscripten
541        // under `wasm_bindgen_unstable_jspi` the fibers belong to
542        // emscripten's JSPI runtime, so the wrappers call its lifecycle hooks
543        // instead and touch no stack state.
544        let hooks = emscripten_jspi_hooks.then_some(eh_version);
545        run_jspi_transform(&mut module, self.externref, hooks)?;
546
547        // Generate Wasm catch wrappers for imports with #[wasm_bindgen(catch)].
548        // This runs after externref processing so that we have access to the
549        // externref table and allocation function.
550        //
551        // Emscripten output may contain wasm exception-handling instructions
552        // from linked libc++ / embind that have no relation to wasm-bindgen's
553        // `#[wasm_bindgen(catch)]` machinery, and the wasm-bindgen runtime
554        // intrinsics (`__externref_table`, `__externref_table_alloc`,
555        // `__wbindgen_exn_store`) may be absent. Skip the transform until
556        // proper emscripten-mode catch support lands.
557        if !matches!(self.mode, OutputMode::Emscripten) {
558            run_exception_handling_transforms(&mut module, eh_version)?;
559        }
560
561        // We've done a whole bunch of transformations to the Wasm module, many
562        // of which leave "garbage" lying around, so let's prune out all our
563        // unnecessary things here.
564        gc_module_and_adapters(&mut module);
565
566        let stem = self.stem()?;
567
568        // Now we execute the JS generation passes to actually emit JS/TypeScript/etc.
569        let aux = module
570            .customs
571            .delete_typed::<wit::WasmBindgenAux>()
572            .expect("aux section should be present");
573        let adapters = module
574            .customs
575            .delete_typed::<wit::NonstandardWitSection>()
576            .unwrap();
577        let mut cx = js::Context::new(&mut module, self, &adapters, &aux)?;
578        cx.generate()?;
579        let js::FinalizedOutput {
580            js,
581            ts,
582            start,
583            emscripten_extern_pre_js,
584        } = cx.finalize(stem)?;
585        let generated = Generated {
586            snippets: aux.snippets.clone(),
587            local_modules: aux.local_modules.clone(),
588            mode: self.mode.clone(),
589            typescript: self.typescript,
590            npm_dependencies: cx.npm_dependencies.clone(),
591            js,
592            ts,
593            start,
594            emscripten_extern_pre_js,
595        };
596
597        Ok(Output {
598            module,
599            stem: stem.to_string(),
600            split_debug_info: self.split_debug_info,
601            debug_info_url: self.debug_info_url.clone(),
602            generated,
603        })
604    }
605
606    fn module_from_bytes(&self, bytes: &[u8]) -> Result<Module, Error> {
607        walrus::ModuleConfig::new()
608            // Skip validation of the module as LLVM's output is
609            // generally already well-formed and so we won't gain much
610            // from re-validating. Additionally LLVM's current output
611            // for threads includes atomic instructions but doesn't
612            // include shared memory, so it fails that part of
613            // validation!
614            .strict_validate(false)
615            .generate_dwarf(self.keep_debug || self.split_debug_info)
616            .generate_name_section(!self.remove_name_section)
617            .generate_producers_section(!self.remove_producers_section)
618            .parse(bytes)
619            .context("failed to parse input as wasm")
620    }
621
622    fn local_module_name(&self, module: &str) -> String {
623        format!("./snippets/{module}")
624    }
625
626    fn inline_js_module_name(
627        &self,
628        unique_crate_identifier: &str,
629        snippet_idx_in_crate: usize,
630    ) -> String {
631        format!("./snippets/{unique_crate_identifier}/inline{snippet_idx_in_crate}.js",)
632    }
633}
634
635fn reset_indentation(s: &str) -> String {
636    let mut indent: u32 = 0;
637    let mut dst = String::new();
638
639    fn is_doc_comment(line: &str) -> bool {
640        line.starts_with("*")
641    }
642
643    static TAB: &str = "    ";
644
645    for line in s.trim().lines() {
646        let line = line.trim();
647
648        // handle doc comments separately
649        if is_doc_comment(line) {
650            for _ in 0..indent {
651                dst.push_str(TAB);
652            }
653            dst.push(' ');
654            dst.push_str(line);
655            dst.push('\n');
656            continue;
657        }
658
659        if line.starts_with('}') {
660            indent = indent.saturating_sub(1);
661        }
662
663        let extra = if line.starts_with(':') || line.starts_with('?') {
664            1
665        } else {
666            0
667        };
668        if !line.is_empty() {
669            for _ in 0..indent + extra {
670                dst.push_str(TAB);
671            }
672            dst.push_str(line);
673        }
674        dst.push('\n');
675
676        if line.ends_with('{') {
677            indent += 1;
678        }
679    }
680    dst
681}
682
683/// Since Rust will soon adopt v0 mangling as the default,
684/// and the `rustc_demangle` crate doesn't output closure disambiguators,
685/// duplicate symbols can appear. We handle this case manually.
686///
687/// issue: <https://github.com/wasm-bindgen/wasm-bindgen/issues/4820>
688fn demangle(module: &mut Module) {
689    let (lower, upper) = module.funcs.iter().size_hint();
690    let mut counter: HashMap<String, i32> = HashMap::with_capacity(upper.unwrap_or(lower));
691
692    for func in module.funcs.iter_mut() {
693        let Some(name) = &func.name else {
694            continue;
695        };
696
697        let Ok(sym) = rustc_demangle::try_demangle(name) else {
698            continue;
699        };
700
701        let demangled = sym.to_string();
702        match counter.entry(demangled) {
703            Entry::Occupied(mut entry) => {
704                func.name = Some(format!("{}[{}]", entry.key(), entry.get()));
705                *entry.get_mut() += 1;
706            }
707            Entry::Vacant(entry) => {
708                func.name = Some(entry.key().clone());
709                entry.insert(1);
710            }
711        }
712    }
713}
714
715impl OutputMode {
716    fn uses_es_modules(&self) -> bool {
717        matches!(
718            self,
719            OutputMode::Bundler { .. }
720                | OutputMode::Web
721                | OutputMode::Node { module: true }
722                | OutputMode::Deno
723                | OutputMode::Module
724        )
725    }
726
727    fn nodejs(&self) -> bool {
728        matches!(self, OutputMode::Node { .. })
729    }
730
731    fn no_modules(&self) -> bool {
732        matches!(self, OutputMode::NoModules { .. })
733    }
734
735    fn bundler(&self) -> bool {
736        matches!(self, OutputMode::Bundler { .. })
737    }
738
739    fn emscripten(&self) -> bool {
740        matches!(self, OutputMode::Emscripten)
741    }
742}
743
744/// Remove a number of internal exports that are synthesized by Rust's linker,
745/// LLD. These exports aren't typically ever needed and just add extra space to
746/// the binary.
747fn unexported_unused_lld_things(module: &mut Module) {
748    let mut to_remove = Vec::new();
749    for export in module.exports.iter() {
750        match export.name.as_str() {
751            "__heap_base" | "__data_end" | "__indirect_function_table" => {
752                to_remove.push(export.id());
753            }
754            _ => {}
755        }
756    }
757    for id in to_remove {
758        module.exports.delete(id);
759    }
760}
761
762impl Output {
763    pub fn js(&self) -> &str {
764        &self.generated.js
765    }
766
767    pub fn ts(&self) -> Option<&str> {
768        if self.generated.typescript {
769            Some(&self.generated.ts)
770        } else {
771            None
772        }
773    }
774
775    pub fn start(&self) -> Option<&String> {
776        self.generated.start.as_ref()
777    }
778
779    pub fn snippets(&self) -> &BTreeMap<String, Vec<String>> {
780        &self.generated.snippets
781    }
782
783    pub fn local_modules(&self) -> &HashMap<String, String> {
784        &self.generated.local_modules
785    }
786
787    pub fn npm_dependencies(&self) -> &HashMap<String, (PathBuf, String)> {
788        &self.generated.npm_dependencies
789    }
790
791    pub fn wasm(&self) -> &walrus::Module {
792        &self.module
793    }
794
795    pub fn wasm_mut(&mut self) -> &mut walrus::Module {
796        &mut self.module
797    }
798
799    pub fn emit(&mut self, out_dir: impl AsRef<Path>) -> Result<(), Error> {
800        self._emit(out_dir.as_ref())
801    }
802
803    fn _emit(&mut self, out_dir: &Path) -> Result<(), Error> {
804        let wasm_name = format!("{}_bg", self.stem);
805        let wasm_path = out_dir.join(&wasm_name).with_extension("wasm");
806        fs::create_dir_all(out_dir)?;
807
808        let wasm_bytes = self.module.emit_wasm();
809        let wasm_bytes = if self.split_debug_info {
810            let debug_name = format!("{wasm_name}.debug.wasm");
811            let url = self.debug_info_url.as_deref().unwrap_or(&debug_name);
812            let main_bytes = split_debug_info(&wasm_bytes, url)?;
813            let debug_path = out_dir.join(&debug_name);
814            fs::write(&debug_path, &wasm_bytes)
815                .with_context(|| format!("failed to write `{}`", debug_path.display()))?;
816            main_bytes
817        } else {
818            wasm_bytes
819        };
820        fs::write(&wasm_path, wasm_bytes)
821            .with_context(|| format!("failed to write `{}`", wasm_path.display()))?;
822
823        let gen = &self.generated;
824
825        // Write out all local JS snippets to the final destination now that
826        // we've collected them from all the programs.
827        for (identifier, list) in gen.snippets.iter() {
828            for (i, js) in list.iter().enumerate() {
829                let name = format!("inline{i}.js");
830                let path = out_dir.join("snippets").join(identifier).join(name);
831                fs::create_dir_all(path.parent().unwrap())?;
832                fs::write(&path, js)
833                    .with_context(|| format!("failed to write `{}`", path.display()))?;
834            }
835        }
836
837        for (path, contents) in gen.local_modules.iter() {
838            let path = out_dir.join("snippets").join(path);
839            fs::create_dir_all(path.parent().unwrap())?;
840            fs::write(&path, contents)
841                .with_context(|| format!("failed to write `{}`", path.display()))?;
842        }
843
844        let is_genmode_nodemodule = matches!(gen.mode, OutputMode::Node { module: true });
845        if !gen.npm_dependencies.is_empty() || is_genmode_nodemodule {
846            #[derive(serde::Serialize)]
847            struct PackageJson<'a> {
848                #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
849                ty: Option<&'static str>,
850                dependencies: BTreeMap<&'a str, &'a str>,
851            }
852            let pj = PackageJson {
853                ty: is_genmode_nodemodule.then_some("module"),
854                dependencies: gen
855                    .npm_dependencies
856                    .iter()
857                    .map(|(k, v)| (k.as_str(), v.1.as_str()))
858                    .collect(),
859            };
860            let json = serde_json::to_string_pretty(&pj)?;
861            fs::write(out_dir.join("package.json"), json)?;
862        }
863
864        // And now that we've got all our JS and TypeScript, actually write it
865        // out to the filesystem.
866        let extension = "js";
867
868        fn write<P, C>(path: P, contents: C) -> Result<(), anyhow::Error>
869        where
870            P: AsRef<Path>,
871            C: AsRef<[u8]>,
872        {
873            fs::write(&path, contents)
874                .with_context(|| format!("failed to write `{}`", path.as_ref().display()))
875        }
876
877        let js_path = out_dir.join(&self.stem).with_extension(extension);
878        if matches!(self.generated.mode, OutputMode::Emscripten) {
879            let emscripten_js_path = out_dir.join("library_bindgen.js");
880            write(&emscripten_js_path, reset_indentation(&gen.js))?;
881            // When the user crate imports from an ESM module
882            // (`#[wasm_bindgen(module = "...")]`), we emit those imports to a
883            // sidecar `library_bindgen.extern-pre.js`. Consumers pass it to
884            // emcc with `--extern-pre-js`, which prepends it before emcc's
885            // modularize wrapper — ESM imports can only legally live there.
886            // Skip writing when empty so consumers don't accidentally pick
887            // up a stale file from a previous build.
888            let extern_pre_js_path = out_dir.join("library_bindgen.extern-pre.js");
889            if gen.emscripten_extern_pre_js.is_empty() {
890                let _ = fs::remove_file(&extern_pre_js_path);
891            } else {
892                write(
893                    &extern_pre_js_path,
894                    reset_indentation(&gen.emscripten_extern_pre_js),
895                )?;
896            }
897        } else {
898            write(&js_path, reset_indentation(&gen.js))?;
899        }
900
901        if let Some(start) = &gen.start {
902            let js_path = out_dir.join(wasm_name).with_extension(extension);
903            write(&js_path, reset_indentation(start))?;
904        }
905
906        if gen.typescript {
907            let ts_path = js_path.with_extension("d.ts");
908            fs::write(&ts_path, reset_indentation(&gen.ts))
909                .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
910        }
911
912        if gen.typescript {
913            let ts_path = wasm_path.with_extension("wasm.d.ts");
914            let ts = wasm2es6js::typescript(&self.module)?;
915            fs::write(&ts_path, reset_indentation(&ts))
916                .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
917        }
918
919        Ok(())
920    }
921}
922
923/// Remove the `.debug_*` custom sections from an emitted Wasm module and
924/// append an `external_debug_info` custom section that holds `url`.
925///
926/// Ref: https://github.com/WebAssembly/tool-conventions/blob/main/Debugging.md
927fn split_debug_info(wasm: &[u8], url: &str) -> Result<Vec<u8>, Error> {
928    let mut kept = Vec::new();
929    let mut keep_from = 0;
930    let mut section_start = 0;
931    for payload in wasmparser::Parser::new(0).parse_all(wasm) {
932        let payload = payload?;
933        if let wasmparser::Payload::CustomSection(section) = &payload {
934            if section.name().starts_with(".debug_") {
935                kept.push(keep_from..section_start);
936                keep_from = section.range().end;
937            }
938        }
939        if let wasmparser::Payload::Version { range, .. } = &payload {
940            section_start = range.end;
941        } else if let Some((_, range)) = payload.as_section() {
942            section_start = range.end;
943        }
944    }
945    kept.push(keep_from..wasm.len());
946
947    let mut contents = Vec::new();
948    let name = "external_debug_info";
949    leb128::write::unsigned(&mut contents, name.len() as u64)?;
950    contents.extend_from_slice(name.as_bytes());
951    leb128::write::unsigned(&mut contents, url.len() as u64)?;
952    contents.extend_from_slice(url.as_bytes());
953
954    let kept_len: usize = kept.iter().map(|range| range.len()).sum();
955    let mut out = Vec::with_capacity(kept_len + contents.len() + 6);
956    for range in kept {
957        out.extend_from_slice(&wasm[range]);
958    }
959    out.push(0);
960    leb128::write::unsigned(&mut out, contents.len() as u64)?;
961    out.extend_from_slice(&contents);
962    Ok(out)
963}
964
965/// Instrument `#[wasm_bindgen(jspi)]` exports and `#[wasm_bindgen(suspending)]`
966/// imports with in-wasm shadow-stack management, or with emscripten's JSPI
967/// lifecycle hooks when `hooks` is set. See `transforms::jspi`.
968fn run_jspi_transform(
969    module: &mut Module,
970    externref: bool,
971    hooks: Option<transforms::ExceptionHandlingVersion>,
972) -> Result<(), Error> {
973    let mut aux = module
974        .customs
975        .delete_typed::<wit::WasmBindgenAux>()
976        .expect("aux section should exist");
977    let mut wit = module
978        .customs
979        .delete_typed::<wit::NonstandardWitSection>()
980        .expect("wit section should exist");
981
982    let result = transforms::jspi::run(module, &mut aux, &mut wit, externref, hooks)
983        .context("failed to instrument module for JSPI");
984
985    module.customs.add(*wit);
986    module.customs.add(*aux);
987
988    result
989}
990
991/// Run the exception-handling transforms: catch wrappers for imports marked
992/// `#[wasm_bindgen(catch)]`, then shadow stack restore wrappers for the exports
993/// a panic can unwind out of.
994///
995/// They share a function so they share one EH detection. Re-detecting in
996/// between would see `catch_handler`'s own `try_table`s and reclassify a
997/// `panic=abort` module as `Modern`.
998fn run_exception_handling_transforms(
999    module: &mut Module,
1000    eh_version: transforms::ExceptionHandlingVersion,
1001) -> Result<(), Error> {
1002    log::debug!("Exception handling version: {eh_version:?}");
1003
1004    if eh_version == transforms::ExceptionHandlingVersion::None {
1005        return Ok(());
1006    }
1007
1008    // We need to temporarily remove the custom sections to avoid borrow issues
1009    let mut aux = module
1010        .customs
1011        .delete_typed::<wit::WasmBindgenAux>()
1012        .expect("aux section should exist");
1013    let wit = module
1014        .customs
1015        .delete_typed::<wit::NonstandardWitSection>()
1016        .expect("wit section should exist");
1017
1018    log::debug!(
1019        "Running catch handler: imports_with_catch={}, externref_table={:?}, externref_alloc={:?}, exn_store={:?}",
1020        aux.imports_with_catch.len(),
1021        aux.externref_table,
1022        aux.externref_alloc,
1023        aux.exn_store
1024    );
1025
1026    let result = transforms::catch_handler::run(module, &mut aux, &wit, eh_version)
1027        .context("failed to generate catch wrappers");
1028    if result.is_ok() {
1029        transforms::export_sp_restore::run(module, &wit, eh_version);
1030    }
1031
1032    // Re-add the custom sections
1033    module.customs.add(*wit);
1034    module.customs.add(*aux);
1035
1036    result
1037}
1038
1039fn gc_module_and_adapters(module: &mut Module) {
1040    loop {
1041        // Fist up, cleanup the native Wasm module. Note that roots can come
1042        // from custom sections, namely our Wasm interface types custom section
1043        // as well as the aux section.
1044        walrus::passes::gc::run(module);
1045
1046        // ... and afterwards we can delete any `implements` directives for any
1047        // imports that have been deleted.
1048        let imports_remaining = module
1049            .imports
1050            .iter()
1051            .map(|i| i.id())
1052            .collect::<HashSet<_>>();
1053        let mut section = module
1054            .customs
1055            .delete_typed::<wit::NonstandardWitSection>()
1056            .unwrap();
1057        section
1058            .implements
1059            .retain(|pair| imports_remaining.contains(&pair.0));
1060
1061        // ... and after we delete the `implements` directive we try to
1062        // delete some adapters themselves. If nothing is deleted, then we're
1063        // good to go. If something is deleted though then we may have free'd up
1064        // some functions in the main module to get deleted, so go again to gc
1065        // things.
1066        let any_removed = section.gc();
1067        module.customs.add(*section);
1068        if !any_removed {
1069            break;
1070        }
1071    }
1072}
1073
1074/// Returns a sorted iterator over a hash map, sorted based on key.
1075///
1076/// The intention of this API is to be used whenever the iteration order of a
1077/// `HashMap` might affect the generated JS bindings. We want to ensure that the
1078/// generated output is deterministic and we do so by ensuring that iteration of
1079/// hash maps is consistently sorted.
1080fn sorted_iter<K, V>(map: &HashMap<K, V>) -> impl Iterator<Item = (&K, &V)>
1081where
1082    K: Ord,
1083{
1084    let mut pairs = map.iter().collect::<Vec<_>>();
1085    pairs.sort_by_key(|(k, _)| *k);
1086    pairs.into_iter()
1087}