1use anyhow::{Context, Result};
4use clap::Parser;
5use serde::Deserialize;
6use std::{
7 fmt, fs,
8 path::{Path, PathBuf},
9 time::Duration,
10};
11use wasmtime::Config;
12
13pub mod opt;
14
15#[cfg(feature = "logging")]
16fn init_file_per_thread_logger(prefix: &'static str) {
17 file_per_thread_logger::initialize(prefix);
18 file_per_thread_logger::allow_uninitialized();
19
20 #[cfg(feature = "parallel-compilation")]
25 rayon::ThreadPoolBuilder::new()
26 .spawn_handler(move |thread| {
27 let mut b = std::thread::Builder::new();
28 if let Some(name) = thread.name() {
29 b = b.name(name.to_owned());
30 }
31 if let Some(stack_size) = thread.stack_size() {
32 b = b.stack_size(stack_size);
33 }
34 b.spawn(move || {
35 file_per_thread_logger::initialize(prefix);
36 thread.run()
37 })?;
38 Ok(())
39 })
40 .build_global()
41 .unwrap();
42}
43
44wasmtime_option_group! {
45 #[derive(PartialEq, Clone, Deserialize)]
46 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
47 pub struct OptimizeOptions {
48 #[serde(default)]
50 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
51 pub opt_level: Option<wasmtime::OptLevel>,
52
53 #[serde(default)]
55 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
56 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
57
58 pub memory_may_move: Option<bool>,
61
62 pub memory_reservation: Option<u64>,
64
65 pub memory_reservation_for_growth: Option<u64>,
67
68 pub memory_guard_size: Option<u64>,
70
71 pub guard_before_linear_memory: Option<bool>,
74
75 pub table_lazy_init: Option<bool>,
80
81 pub pooling_allocator: Option<bool>,
83
84 pub pooling_decommit_batch_size: Option<usize>,
87
88 pub pooling_memory_keep_resident: Option<usize>,
91
92 pub pooling_table_keep_resident: Option<usize>,
95
96 #[serde(default)]
99 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
100 pub pooling_memory_protection_keys: Option<wasmtime::MpkEnabled>,
101
102 pub pooling_max_memory_protection_keys: Option<usize>,
105
106 pub memory_init_cow: Option<bool>,
109
110 pub memory_guaranteed_dense_image_size: Option<u64>,
113
114 pub pooling_total_core_instances: Option<u32>,
117
118 pub pooling_total_component_instances: Option<u32>,
121
122 pub pooling_total_memories: Option<u32>,
125
126 pub pooling_total_tables: Option<u32>,
129
130 pub pooling_total_stacks: Option<u32>,
133
134 pub pooling_max_memory_size: Option<usize>,
137
138 pub pooling_table_elements: Option<usize>,
141
142 pub pooling_max_core_instance_size: Option<usize>,
145
146 pub pooling_max_unused_warm_slots: Option<u32>,
149
150 pub pooling_async_stack_keep_resident: Option<usize>,
153
154 pub pooling_max_component_instance_size: Option<usize>,
157
158 pub pooling_max_core_instances_per_component: Option<u32>,
161
162 pub pooling_max_memories_per_component: Option<u32>,
165
166 pub pooling_max_tables_per_component: Option<u32>,
169
170 pub pooling_max_tables_per_module: Option<u32>,
172
173 pub pooling_max_memories_per_module: Option<u32>,
175
176 pub pooling_total_gc_heaps: Option<u32>,
178
179 pub signals_based_traps: Option<bool>,
181
182 pub dynamic_memory_guard_size: Option<u64>,
184
185 pub static_memory_guard_size: Option<u64>,
187
188 pub static_memory_forced: Option<bool>,
190
191 pub static_memory_maximum_size: Option<u64>,
193
194 pub dynamic_memory_reserved_for_growth: Option<u64>,
196 }
197
198 enum Optimize {
199 ...
200 }
201}
202
203wasmtime_option_group! {
204 #[derive(PartialEq, Clone, Deserialize)]
205 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
206 pub struct CodegenOptions {
207 #[serde(default)]
212 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
213 pub compiler: Option<wasmtime::Strategy>,
214 #[serde(default)]
224 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
225 pub collector: Option<wasmtime::Collector>,
226 pub cranelift_debug_verifier: Option<bool>,
228 pub cache: Option<bool>,
230 pub cache_config: Option<String>,
232 pub parallel_compilation: Option<bool>,
234 pub pcc: Option<bool>,
236 pub native_unwind_info: Option<bool>,
239
240 pub inlining: Option<bool>,
242
243 #[prefixed = "cranelift"]
244 #[serde(default)]
245 pub cranelift: Vec<(String, Option<String>)>,
248 }
249
250 enum Codegen {
251 ...
252 }
253}
254
255wasmtime_option_group! {
256 #[derive(PartialEq, Clone, Deserialize)]
257 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
258 pub struct DebugOptions {
259 pub debug_info: Option<bool>,
261 pub address_map: Option<bool>,
263 pub logging: Option<bool>,
265 pub log_to_files: Option<bool>,
267 pub coredump: Option<String>,
269 }
270
271 enum Debug {
272 ...
273 }
274}
275
276wasmtime_option_group! {
277 #[derive(PartialEq, Clone, Deserialize)]
278 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
279 pub struct WasmOptions {
280 pub nan_canonicalization: Option<bool>,
282 pub fuel: Option<u64>,
290 pub epoch_interruption: Option<bool>,
293 pub max_wasm_stack: Option<usize>,
296 pub async_stack_size: Option<usize>,
302 pub async_stack_zeroing: Option<bool>,
305 pub unknown_exports_allow: Option<bool>,
307 pub unknown_imports_trap: Option<bool>,
310 pub unknown_imports_default: Option<bool>,
313 pub wmemcheck: Option<bool>,
315 pub max_memory_size: Option<usize>,
320 pub max_table_elements: Option<usize>,
322 pub max_instances: Option<usize>,
324 pub max_tables: Option<usize>,
326 pub max_memories: Option<usize>,
328 pub trap_on_grow_failure: Option<bool>,
335 pub timeout: Option<Duration>,
337 pub all_proposals: Option<bool>,
339 pub bulk_memory: Option<bool>,
341 pub multi_memory: Option<bool>,
343 pub multi_value: Option<bool>,
345 pub reference_types: Option<bool>,
347 pub simd: Option<bool>,
349 pub relaxed_simd: Option<bool>,
351 pub relaxed_simd_deterministic: Option<bool>,
360 pub tail_call: Option<bool>,
362 pub threads: Option<bool>,
364 pub shared_everything_threads: Option<bool>,
366 pub memory64: Option<bool>,
368 pub component_model: Option<bool>,
370 pub component_model_async: Option<bool>,
372 pub component_model_async_builtins: Option<bool>,
375 pub component_model_async_stackful: Option<bool>,
378 pub component_model_error_context: Option<bool>,
381 pub component_model_gc: Option<bool>,
384 pub function_references: Option<bool>,
386 pub stack_switching: Option<bool>,
388 pub gc: Option<bool>,
390 pub custom_page_sizes: Option<bool>,
392 pub wide_arithmetic: Option<bool>,
394 pub extended_const: Option<bool>,
396 pub exceptions: Option<bool>,
398 pub legacy_exceptions: Option<bool>,
400 }
401
402 enum Wasm {
403 ...
404 }
405}
406
407wasmtime_option_group! {
408 #[derive(PartialEq, Clone, Deserialize)]
409 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
410 pub struct WasiOptions {
411 pub cli: Option<bool>,
413 pub cli_exit_with_code: Option<bool>,
415 pub common: Option<bool>,
417 pub nn: Option<bool>,
419 pub threads: Option<bool>,
421 pub http: Option<bool>,
423 pub http_outgoing_body_buffer_chunks: Option<usize>,
427 pub http_outgoing_body_chunk_size: Option<usize>,
430 pub config: Option<bool>,
432 pub keyvalue: Option<bool>,
434 pub listenfd: Option<bool>,
438 #[serde(default)]
441 pub tcplisten: Vec<String>,
442 pub tls: Option<bool>,
444 pub preview2: Option<bool>,
447 #[serde(skip)]
456 pub nn_graph: Vec<WasiNnGraph>,
457 pub inherit_network: Option<bool>,
460 pub allow_ip_name_lookup: Option<bool>,
462 pub tcp: Option<bool>,
464 pub udp: Option<bool>,
466 pub network_error_code: Option<bool>,
468 pub preview0: Option<bool>,
470 pub inherit_env: Option<bool>,
474 #[serde(skip)]
476 pub config_var: Vec<KeyValuePair>,
477 #[serde(skip)]
479 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
480 }
481
482 enum Wasi {
483 ...
484 }
485}
486
487#[derive(Debug, Clone, PartialEq)]
488pub struct WasiNnGraph {
489 pub format: String,
490 pub dir: String,
491}
492
493#[derive(Debug, Clone, PartialEq)]
494pub struct KeyValuePair {
495 pub key: String,
496 pub value: String,
497}
498
499#[derive(Parser, Clone, Deserialize)]
501#[serde(deny_unknown_fields)]
502pub struct CommonOptions {
503 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
513 #[serde(skip)]
514 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
515
516 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
518 #[serde(skip)]
519 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
520
521 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
523 #[serde(skip)]
524 debug_raw: Vec<opt::CommaSeparated<Debug>>,
525
526 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
529 #[serde(skip)]
530 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
531
532 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
534 #[serde(skip)]
535 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
536
537 #[arg(skip)]
540 #[serde(skip)]
541 configured: bool,
542
543 #[arg(skip)]
544 #[serde(rename = "optimize", default)]
545 pub opts: OptimizeOptions,
546
547 #[arg(skip)]
548 #[serde(rename = "codegen", default)]
549 pub codegen: CodegenOptions,
550
551 #[arg(skip)]
552 #[serde(rename = "debug", default)]
553 pub debug: DebugOptions,
554
555 #[arg(skip)]
556 #[serde(rename = "wasm", default)]
557 pub wasm: WasmOptions,
558
559 #[arg(skip)]
560 #[serde(rename = "wasi", default)]
561 pub wasi: WasiOptions,
562
563 #[arg(long, value_name = "TARGET")]
565 #[serde(skip)]
566 pub target: Option<String>,
567
568 #[arg(long = "config", value_name = "FILE")]
575 #[serde(skip)]
576 pub config: Option<PathBuf>,
577}
578
579macro_rules! match_feature {
580 (
581 [$feat:tt : $config:expr]
582 $val:ident => $e:expr,
583 $p:pat => err,
584 ) => {
585 #[cfg(feature = $feat)]
586 {
587 if let Some($val) = $config {
588 $e;
589 }
590 }
591 #[cfg(not(feature = $feat))]
592 {
593 if let Some($p) = $config {
594 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
595 }
596 }
597 };
598}
599
600impl CommonOptions {
601 pub fn new() -> CommonOptions {
603 CommonOptions {
604 opts_raw: Vec::new(),
605 codegen_raw: Vec::new(),
606 debug_raw: Vec::new(),
607 wasm_raw: Vec::new(),
608 wasi_raw: Vec::new(),
609 configured: true,
610 opts: Default::default(),
611 codegen: Default::default(),
612 debug: Default::default(),
613 wasm: Default::default(),
614 wasi: Default::default(),
615 target: None,
616 config: None,
617 }
618 }
619
620 fn configure(&mut self) -> Result<()> {
621 if self.configured {
622 return Ok(());
623 }
624 self.configured = true;
625 if let Some(toml_config_path) = &self.config {
626 let toml_options = CommonOptions::from_file(toml_config_path)?;
627 self.opts = toml_options.opts;
628 self.codegen = toml_options.codegen;
629 self.debug = toml_options.debug;
630 self.wasm = toml_options.wasm;
631 self.wasi = toml_options.wasi;
632 }
633 self.opts.configure_with(&self.opts_raw);
634 self.codegen.configure_with(&self.codegen_raw);
635 self.debug.configure_with(&self.debug_raw);
636 self.wasm.configure_with(&self.wasm_raw);
637 self.wasi.configure_with(&self.wasi_raw);
638 Ok(())
639 }
640
641 pub fn init_logging(&mut self) -> Result<()> {
642 self.configure()?;
643 if self.debug.logging == Some(false) {
644 return Ok(());
645 }
646 #[cfg(feature = "logging")]
647 if self.debug.log_to_files == Some(true) {
648 let prefix = "wasmtime.dbg.";
649 init_file_per_thread_logger(prefix);
650 } else {
651 use std::io::IsTerminal;
652 use tracing_subscriber::{EnvFilter, FmtSubscriber};
653 let builder = FmtSubscriber::builder()
654 .with_writer(std::io::stderr)
655 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
656 .with_ansi(std::io::stderr().is_terminal());
657 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
658 builder
659 .with_level(false)
660 .with_target(false)
661 .without_time()
662 .init()
663 } else {
664 builder.init();
665 }
666 }
667 #[cfg(not(feature = "logging"))]
668 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
669 anyhow::bail!("support for logging disabled at compile time");
670 }
671 Ok(())
672 }
673
674 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
675 self.configure()?;
676 let mut config = Config::new();
677
678 match_feature! {
679 ["cranelift" : self.codegen.compiler]
680 strategy => config.strategy(strategy),
681 _ => err,
682 }
683 match_feature! {
684 ["gc" : self.codegen.collector]
685 collector => config.collector(collector),
686 _ => err,
687 }
688 if let Some(target) = &self.target {
689 config.target(target)?;
690 }
691 match_feature! {
692 ["cranelift" : self.codegen.cranelift_debug_verifier]
693 enable => config.cranelift_debug_verifier(enable),
694 true => err,
695 }
696 if let Some(enable) = self.debug.debug_info {
697 config.debug_info(enable);
698 }
699 if self.debug.coredump.is_some() {
700 #[cfg(feature = "coredump")]
701 config.coredump_on_trap(true);
702 #[cfg(not(feature = "coredump"))]
703 anyhow::bail!("support for coredumps disabled at compile time");
704 }
705 match_feature! {
706 ["cranelift" : self.opts.opt_level]
707 level => config.cranelift_opt_level(level),
708 _ => err,
709 }
710 match_feature! {
711 ["cranelift": self.opts.regalloc_algorithm]
712 algo => config.cranelift_regalloc_algorithm(algo),
713 _ => err,
714 }
715 match_feature! {
716 ["cranelift" : self.wasm.nan_canonicalization]
717 enable => config.cranelift_nan_canonicalization(enable),
718 true => err,
719 }
720 match_feature! {
721 ["cranelift" : self.codegen.pcc]
722 enable => config.cranelift_pcc(enable),
723 true => err,
724 }
725
726 self.enable_wasm_features(&mut config)?;
727
728 #[cfg(feature = "cranelift")]
729 for (name, value) in self.codegen.cranelift.iter() {
730 let name = name.replace('-', "_");
731 unsafe {
732 match value {
733 Some(val) => {
734 config.cranelift_flag_set(&name, val);
735 }
736 None => {
737 config.cranelift_flag_enable(&name);
738 }
739 }
740 }
741 }
742 #[cfg(not(feature = "cranelift"))]
743 if !self.codegen.cranelift.is_empty() {
744 anyhow::bail!("support for cranelift disabled at compile time");
745 }
746
747 #[cfg(feature = "cache")]
748 if self.codegen.cache != Some(false) {
749 use wasmtime::Cache;
750 let cache = match &self.codegen.cache_config {
751 Some(path) => Cache::from_file(Some(Path::new(path)))?,
752 None => Cache::from_file(None)?,
753 };
754 config.cache(Some(cache));
755 }
756 #[cfg(not(feature = "cache"))]
757 if self.codegen.cache == Some(true) {
758 anyhow::bail!("support for caching disabled at compile time");
759 }
760
761 match_feature! {
762 ["parallel-compilation" : self.codegen.parallel_compilation]
763 enable => config.parallel_compilation(enable),
764 true => err,
765 }
766
767 let memory_reservation = self
768 .opts
769 .memory_reservation
770 .or(self.opts.static_memory_maximum_size);
771 if let Some(size) = memory_reservation {
772 config.memory_reservation(size);
773 }
774
775 if let Some(enable) = self.opts.static_memory_forced {
776 config.memory_may_move(!enable);
777 }
778 if let Some(enable) = self.opts.memory_may_move {
779 config.memory_may_move(enable);
780 }
781
782 let memory_guard_size = self
783 .opts
784 .static_memory_guard_size
785 .or(self.opts.dynamic_memory_guard_size)
786 .or(self.opts.memory_guard_size);
787 if let Some(size) = memory_guard_size {
788 config.memory_guard_size(size);
789 }
790
791 let mem_for_growth = self
792 .opts
793 .memory_reservation_for_growth
794 .or(self.opts.dynamic_memory_reserved_for_growth);
795 if let Some(size) = mem_for_growth {
796 config.memory_reservation_for_growth(size);
797 }
798 if let Some(enable) = self.opts.guard_before_linear_memory {
799 config.guard_before_linear_memory(enable);
800 }
801 if let Some(enable) = self.opts.table_lazy_init {
802 config.table_lazy_init(enable);
803 }
804
805 if self.wasm.fuel.is_some() {
807 config.consume_fuel(true);
808 }
809
810 if let Some(enable) = self.wasm.epoch_interruption {
811 config.epoch_interruption(enable);
812 }
813 if let Some(enable) = self.debug.address_map {
814 config.generate_address_map(enable);
815 }
816 if let Some(enable) = self.opts.memory_init_cow {
817 config.memory_init_cow(enable);
818 }
819 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
820 config.memory_guaranteed_dense_image_size(size);
821 }
822 if let Some(enable) = self.opts.signals_based_traps {
823 config.signals_based_traps(enable);
824 }
825 if let Some(enable) = self.codegen.native_unwind_info {
826 config.native_unwind_info(enable);
827 }
828 if let Some(enable) = self.codegen.inlining {
829 config.compiler_inlining(enable);
830 }
831
832 #[cfg(any(feature = "async", feature = "stack-switching"))]
835 {
836 if let Some(size) = self.wasm.async_stack_size {
837 config.async_stack_size(size);
838 }
839 }
840 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
841 {
842 if let Some(_size) = self.wasm.async_stack_size {
843 anyhow::bail!(concat!(
844 "support for async/stack-switching disabled at compile time"
845 ));
846 }
847 }
848
849 match_feature! {
850 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
851 enable => {
852 if enable {
853 let mut cfg = wasmtime::PoolingAllocationConfig::default();
854 if let Some(size) = self.opts.pooling_memory_keep_resident {
855 cfg.linear_memory_keep_resident(size);
856 }
857 if let Some(size) = self.opts.pooling_table_keep_resident {
858 cfg.table_keep_resident(size);
859 }
860 if let Some(limit) = self.opts.pooling_total_core_instances {
861 cfg.total_core_instances(limit);
862 }
863 if let Some(limit) = self.opts.pooling_total_component_instances {
864 cfg.total_component_instances(limit);
865 }
866 if let Some(limit) = self.opts.pooling_total_memories {
867 cfg.total_memories(limit);
868 }
869 if let Some(limit) = self.opts.pooling_total_tables {
870 cfg.total_tables(limit);
871 }
872 if let Some(limit) = self.opts.pooling_table_elements
873 .or(self.wasm.max_table_elements)
874 {
875 cfg.table_elements(limit);
876 }
877 if let Some(limit) = self.opts.pooling_max_core_instance_size {
878 cfg.max_core_instance_size(limit);
879 }
880 match_feature! {
881 ["async" : self.opts.pooling_total_stacks]
882 limit => cfg.total_stacks(limit),
883 _ => err,
884 }
885 if let Some(max) = self.opts.pooling_max_memory_size
886 .or(self.wasm.max_memory_size)
887 {
888 cfg.max_memory_size(max);
889 }
890 if let Some(size) = self.opts.pooling_decommit_batch_size {
891 cfg.decommit_batch_size(size);
892 }
893 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
894 cfg.max_unused_warm_slots(max);
895 }
896 match_feature! {
897 ["async" : self.opts.pooling_async_stack_keep_resident]
898 size => cfg.async_stack_keep_resident(size),
899 _ => err,
900 }
901 if let Some(max) = self.opts.pooling_max_component_instance_size {
902 cfg.max_component_instance_size(max);
903 }
904 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
905 cfg.max_core_instances_per_component(max);
906 }
907 if let Some(max) = self.opts.pooling_max_memories_per_component {
908 cfg.max_memories_per_component(max);
909 }
910 if let Some(max) = self.opts.pooling_max_tables_per_component {
911 cfg.max_tables_per_component(max);
912 }
913 if let Some(max) = self.opts.pooling_max_tables_per_module {
914 cfg.max_tables_per_module(max);
915 }
916 if let Some(max) = self.opts.pooling_max_memories_per_module {
917 cfg.max_memories_per_module(max);
918 }
919 match_feature! {
920 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
921 enable => cfg.memory_protection_keys(enable),
922 _ => err,
923 }
924 match_feature! {
925 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
926 max => cfg.max_memory_protection_keys(max),
927 _ => err,
928 }
929 match_feature! {
930 ["gc" : self.opts.pooling_total_gc_heaps]
931 max => cfg.total_gc_heaps(max),
932 _ => err,
933 }
934 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
935 }
936 },
937 true => err,
938 }
939
940 if self.opts.pooling_memory_protection_keys.is_some()
941 && !self.opts.pooling_allocator.unwrap_or(false)
942 {
943 anyhow::bail!("memory protection keys require the pooling allocator");
944 }
945
946 if self.opts.pooling_max_memory_protection_keys.is_some()
947 && !self.opts.pooling_memory_protection_keys.is_some()
948 {
949 anyhow::bail!(
950 "max memory protection keys requires memory protection keys to be enabled"
951 );
952 }
953
954 match_feature! {
955 ["async" : self.wasm.async_stack_zeroing]
956 enable => config.async_stack_zeroing(enable),
957 _ => err,
958 }
959
960 if let Some(max) = self.wasm.max_wasm_stack {
961 config.max_wasm_stack(max);
962
963 #[cfg(any(feature = "async", feature = "stack-switching"))]
967 if self.wasm.async_stack_size.is_none() {
968 const DEFAULT_HOST_STACK: usize = 512 << 10;
969 config.async_stack_size(max + DEFAULT_HOST_STACK);
970 }
971 }
972
973 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
974 config.relaxed_simd_deterministic(enable);
975 }
976 match_feature! {
977 ["cranelift" : self.wasm.wmemcheck]
978 enable => config.wmemcheck(enable),
979 true => err,
980 }
981
982 Ok(config)
983 }
984
985 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
986 let all = self.wasm.all_proposals;
987
988 if let Some(enable) = self.wasm.simd.or(all) {
989 config.wasm_simd(enable);
990 }
991 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
992 config.wasm_relaxed_simd(enable);
993 }
994 if let Some(enable) = self.wasm.bulk_memory.or(all) {
995 config.wasm_bulk_memory(enable);
996 }
997 if let Some(enable) = self.wasm.multi_value.or(all) {
998 config.wasm_multi_value(enable);
999 }
1000 if let Some(enable) = self.wasm.tail_call.or(all) {
1001 config.wasm_tail_call(enable);
1002 }
1003 if let Some(enable) = self.wasm.multi_memory.or(all) {
1004 config.wasm_multi_memory(enable);
1005 }
1006 if let Some(enable) = self.wasm.memory64.or(all) {
1007 config.wasm_memory64(enable);
1008 }
1009 if let Some(enable) = self.wasm.stack_switching {
1010 config.wasm_stack_switching(enable);
1011 }
1012 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1013 config.wasm_custom_page_sizes(enable);
1014 }
1015 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1016 config.wasm_wide_arithmetic(enable);
1017 }
1018 if let Some(enable) = self.wasm.extended_const.or(all) {
1019 config.wasm_extended_const(enable);
1020 }
1021 if let Some(enable) = self.wasm.exceptions.or(all) {
1022 config.wasm_exceptions(enable);
1023 }
1024 if let Some(enable) = self.wasm.legacy_exceptions.or(all) {
1025 #[expect(deprecated, reason = "forwarding CLI flag")]
1026 config.wasm_legacy_exceptions(enable);
1027 }
1028
1029 macro_rules! handle_conditionally_compiled {
1030 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1031 if let Some(enable) = self.wasm.$field.or(all) {
1032 #[cfg(feature = $feature)]
1033 config.$method(enable);
1034 #[cfg(not(feature = $feature))]
1035 if enable && all.is_none() {
1036 anyhow::bail!("support for {} was disabled at compile-time", $feature);
1037 }
1038 }
1039 )*)
1040 }
1041
1042 handle_conditionally_compiled! {
1043 ("component-model", component_model, wasm_component_model)
1044 ("component-model-async", component_model_async, wasm_component_model_async)
1045 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1046 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1047 ("component-model", component_model_error_context, wasm_component_model_error_context)
1048 ("threads", threads, wasm_threads)
1049 ("gc", gc, wasm_gc)
1050 ("gc", reference_types, wasm_reference_types)
1051 ("gc", function_references, wasm_function_references)
1052 ("stack-switching", stack_switching, wasm_stack_switching)
1053 }
1054
1055 if let Some(enable) = self.wasm.component_model_gc {
1056 #[cfg(all(feature = "component-model", feature = "gc"))]
1057 config.wasm_component_model_gc(enable);
1058 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1059 if enable && all.is_none() {
1060 anyhow::bail!("support for `component-model-gc` was disabled at compile time")
1061 }
1062 }
1063
1064 Ok(())
1065 }
1066
1067 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1068 let path_ref = path.as_ref();
1069 let file_contents = fs::read_to_string(path_ref)
1070 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1071 toml::from_str::<CommonOptions>(&file_contents)
1072 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1073 }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078 use wasmtime::{OptLevel, RegallocAlgorithm};
1079
1080 use super::*;
1081
1082 #[test]
1083 fn from_toml() {
1084 let empty_toml = "";
1086 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1087 common_options.config(None).unwrap();
1088
1089 let basic_toml = r#"
1091 [optimize]
1092 [codegen]
1093 [debug]
1094 [wasm]
1095 [wasi]
1096 "#;
1097 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1098 common_options.config(None).unwrap();
1099
1100 for (opt_value, expected) in [
1102 ("0", Some(OptLevel::None)),
1103 ("1", Some(OptLevel::Speed)),
1104 ("2", Some(OptLevel::Speed)),
1105 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1106 ("\"hello\"", None), ("3", None), ] {
1109 let toml = format!(
1110 r#"
1111 [optimize]
1112 opt-level = {opt_value}
1113 "#,
1114 );
1115 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1116 .ok()
1117 .and_then(|common_options| common_options.opts.opt_level);
1118
1119 assert_eq!(
1120 parsed_opt_level, expected,
1121 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1122 );
1123 }
1124
1125 for (regalloc_value, expected) in [
1127 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1128 ("\"hello\"", None), ("3", None), ("true", None), ] {
1132 let toml = format!(
1133 r#"
1134 [optimize]
1135 regalloc-algorithm = {regalloc_value}
1136 "#,
1137 );
1138 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1139 .ok()
1140 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1141 assert_eq!(
1142 parsed_regalloc_algorithm, expected,
1143 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1144 );
1145 }
1146
1147 for (strategy_value, expected) in [
1149 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1150 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1151 ("\"hello\"", None), ("5", None), ("true", None), ] {
1155 let toml = format!(
1156 r#"
1157 [codegen]
1158 compiler = {strategy_value}
1159 "#,
1160 );
1161 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1162 .ok()
1163 .and_then(|common_options| common_options.codegen.compiler);
1164 assert_eq!(
1165 parsed_strategy, expected,
1166 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1167 );
1168 }
1169
1170 for (collector_value, expected) in [
1172 (
1173 "\"drc\"",
1174 Some(wasmtime::Collector::DeferredReferenceCounting),
1175 ),
1176 ("\"null\"", Some(wasmtime::Collector::Null)),
1177 ("\"hello\"", None), ("5", None), ("true", None), ] {
1181 let toml = format!(
1182 r#"
1183 [codegen]
1184 collector = {collector_value}
1185 "#,
1186 );
1187 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1188 .ok()
1189 .and_then(|common_options| common_options.codegen.collector);
1190 assert_eq!(
1191 parsed_collector, expected,
1192 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1193 );
1194 }
1195 }
1196}
1197
1198impl Default for CommonOptions {
1199 fn default() -> CommonOptions {
1200 CommonOptions::new()
1201 }
1202}
1203
1204impl fmt::Display for CommonOptions {
1205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1206 let CommonOptions {
1207 codegen_raw,
1208 codegen,
1209 debug_raw,
1210 debug,
1211 opts_raw,
1212 opts,
1213 wasm_raw,
1214 wasm,
1215 wasi_raw,
1216 wasi,
1217 configured,
1218 target,
1219 config,
1220 } = self;
1221 if let Some(target) = target {
1222 write!(f, "--target {target} ")?;
1223 }
1224 if let Some(config) = config {
1225 write!(f, "--config {} ", config.display())?;
1226 }
1227
1228 let codegen_flags;
1229 let opts_flags;
1230 let wasi_flags;
1231 let wasm_flags;
1232 let debug_flags;
1233
1234 if *configured {
1235 codegen_flags = codegen.to_options();
1236 debug_flags = debug.to_options();
1237 wasi_flags = wasi.to_options();
1238 wasm_flags = wasm.to_options();
1239 opts_flags = opts.to_options();
1240 } else {
1241 codegen_flags = codegen_raw
1242 .iter()
1243 .flat_map(|t| t.0.iter())
1244 .cloned()
1245 .collect();
1246 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1247 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1248 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1249 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1250 }
1251
1252 for flag in codegen_flags {
1253 write!(f, "-C{flag} ")?;
1254 }
1255 for flag in opts_flags {
1256 write!(f, "-O{flag} ")?;
1257 }
1258 for flag in wasi_flags {
1259 write!(f, "-S{flag} ")?;
1260 }
1261 for flag in wasm_flags {
1262 write!(f, "-W{flag} ")?;
1263 }
1264 for flag in debug_flags {
1265 write!(f, "-D{flag} ")?;
1266 }
1267
1268 Ok(())
1269 }
1270}