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 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 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 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 self.mode = OutputMode::Emscripten;
383 }
384
385 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 if let Ok(true) = wasm_conventions::target_feature(&module, "reference-types") {
395 self.externref = true;
396 }
397
398 if let Ok(true) = wasm_conventions::target_feature(&module, "multivalue") {
400 self.multi_value = true;
401 }
402
403 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 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 None
423 } else {
424 transforms::threads::run(&mut module)
425 .with_context(|| "failed to prepare module for threading")?
426 };
427
428 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 {
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 module
457 .producers
458 .add_processed_by("wasm-bindgen", &wasm_bindgen_shared::version());
459 }
460 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 descriptors::execute(&mut module)?;
483
484 wit::process(self, &mut module, programs, thread_count)?;
490
491 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 externref::force_contiguous_elements(&mut module)?;
517 }
518
519 if self.multi_value {
522 multivalue::run(&mut module)
523 .context("failed to transform return pointers into multi-value Wasm")?;
524 }
525
526 let eh_version =
531 transforms::detect_exception_handling_version(&module, self.force_enable_abort_handler);
532
533 let hooks = emscripten_jspi_hooks.then_some(eh_version);
545 run_jspi_transform(&mut module, self.externref, hooks)?;
546
547 if !matches!(self.mode, OutputMode::Emscripten) {
558 run_exception_handling_transforms(&mut module, eh_version)?;
559 }
560
561 gc_module_and_adapters(&mut module);
565
566 let stem = self.stem()?;
567
568 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 .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 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
683fn 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
744fn 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 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 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 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
923fn 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
965fn 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
991fn 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 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 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 walrus::passes::gc::run(module);
1045
1046 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 let any_removed = section.gc();
1067 module.customs.add(*section);
1068 if !any_removed {
1069 break;
1070 }
1071 }
1072}
1073
1074fn 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}