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 #[prefixed = "cranelift"]
241 #[serde(default)]
242 pub cranelift: Vec<(String, Option<String>)>,
245 }
246
247 enum Codegen {
248 ...
249 }
250}
251
252wasmtime_option_group! {
253 #[derive(PartialEq, Clone, Deserialize)]
254 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
255 pub struct DebugOptions {
256 pub debug_info: Option<bool>,
258 pub address_map: Option<bool>,
260 pub logging: Option<bool>,
262 pub log_to_files: Option<bool>,
264 pub coredump: Option<String>,
266 }
267
268 enum Debug {
269 ...
270 }
271}
272
273wasmtime_option_group! {
274 #[derive(PartialEq, Clone, Deserialize)]
275 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
276 pub struct WasmOptions {
277 pub nan_canonicalization: Option<bool>,
279 pub fuel: Option<u64>,
287 pub epoch_interruption: Option<bool>,
290 pub max_wasm_stack: Option<usize>,
293 pub async_stack_size: Option<usize>,
299 pub async_stack_zeroing: Option<bool>,
302 pub unknown_exports_allow: Option<bool>,
304 pub unknown_imports_trap: Option<bool>,
307 pub unknown_imports_default: Option<bool>,
310 pub wmemcheck: Option<bool>,
312 pub max_memory_size: Option<usize>,
317 pub max_table_elements: Option<usize>,
319 pub max_instances: Option<usize>,
321 pub max_tables: Option<usize>,
323 pub max_memories: Option<usize>,
325 pub trap_on_grow_failure: Option<bool>,
332 pub timeout: Option<Duration>,
334 pub all_proposals: Option<bool>,
336 pub bulk_memory: Option<bool>,
338 pub multi_memory: Option<bool>,
340 pub multi_value: Option<bool>,
342 pub reference_types: Option<bool>,
344 pub simd: Option<bool>,
346 pub relaxed_simd: Option<bool>,
348 pub relaxed_simd_deterministic: Option<bool>,
357 pub tail_call: Option<bool>,
359 pub threads: Option<bool>,
361 pub shared_everything_threads: Option<bool>,
363 pub memory64: Option<bool>,
365 pub component_model: Option<bool>,
367 pub component_model_async: Option<bool>,
369 pub component_model_async_builtins: Option<bool>,
372 pub component_model_async_stackful: Option<bool>,
375 pub component_model_error_context: Option<bool>,
378 pub component_model_gc: Option<bool>,
381 pub function_references: Option<bool>,
383 pub stack_switching: Option<bool>,
385 pub gc: Option<bool>,
387 pub custom_page_sizes: Option<bool>,
389 pub wide_arithmetic: Option<bool>,
391 pub extended_const: Option<bool>,
393 pub exceptions: Option<bool>,
395 pub legacy_exceptions: Option<bool>,
397 }
398
399 enum Wasm {
400 ...
401 }
402}
403
404wasmtime_option_group! {
405 #[derive(PartialEq, Clone, Deserialize)]
406 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
407 pub struct WasiOptions {
408 pub cli: Option<bool>,
410 pub cli_exit_with_code: Option<bool>,
412 pub common: Option<bool>,
414 pub nn: Option<bool>,
416 pub threads: Option<bool>,
418 pub http: Option<bool>,
420 pub http_outgoing_body_buffer_chunks: Option<usize>,
424 pub http_outgoing_body_chunk_size: Option<usize>,
427 pub config: Option<bool>,
429 pub keyvalue: Option<bool>,
431 pub listenfd: Option<bool>,
435 #[serde(default)]
438 pub tcplisten: Vec<String>,
439 pub tls: Option<bool>,
441 pub preview2: Option<bool>,
444 #[serde(skip)]
453 pub nn_graph: Vec<WasiNnGraph>,
454 pub inherit_network: Option<bool>,
457 pub allow_ip_name_lookup: Option<bool>,
459 pub tcp: Option<bool>,
461 pub udp: Option<bool>,
463 pub network_error_code: Option<bool>,
465 pub preview0: Option<bool>,
467 pub inherit_env: Option<bool>,
471 #[serde(skip)]
473 pub config_var: Vec<KeyValuePair>,
474 #[serde(skip)]
476 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
477 }
478
479 enum Wasi {
480 ...
481 }
482}
483
484#[derive(Debug, Clone, PartialEq)]
485pub struct WasiNnGraph {
486 pub format: String,
487 pub dir: String,
488}
489
490#[derive(Debug, Clone, PartialEq)]
491pub struct KeyValuePair {
492 pub key: String,
493 pub value: String,
494}
495
496#[derive(Parser, Clone, Deserialize)]
498#[serde(deny_unknown_fields)]
499pub struct CommonOptions {
500 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
510 #[serde(skip)]
511 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
512
513 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
515 #[serde(skip)]
516 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
517
518 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
520 #[serde(skip)]
521 debug_raw: Vec<opt::CommaSeparated<Debug>>,
522
523 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
526 #[serde(skip)]
527 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
528
529 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
531 #[serde(skip)]
532 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
533
534 #[arg(skip)]
537 #[serde(skip)]
538 configured: bool,
539
540 #[arg(skip)]
541 #[serde(rename = "optimize", default)]
542 pub opts: OptimizeOptions,
543
544 #[arg(skip)]
545 #[serde(rename = "codegen", default)]
546 pub codegen: CodegenOptions,
547
548 #[arg(skip)]
549 #[serde(rename = "debug", default)]
550 pub debug: DebugOptions,
551
552 #[arg(skip)]
553 #[serde(rename = "wasm", default)]
554 pub wasm: WasmOptions,
555
556 #[arg(skip)]
557 #[serde(rename = "wasi", default)]
558 pub wasi: WasiOptions,
559
560 #[arg(long, value_name = "TARGET")]
562 #[serde(skip)]
563 pub target: Option<String>,
564
565 #[arg(long = "config", value_name = "FILE")]
572 #[serde(skip)]
573 pub config: Option<PathBuf>,
574}
575
576macro_rules! match_feature {
577 (
578 [$feat:tt : $config:expr]
579 $val:ident => $e:expr,
580 $p:pat => err,
581 ) => {
582 #[cfg(feature = $feat)]
583 {
584 if let Some($val) = $config {
585 $e;
586 }
587 }
588 #[cfg(not(feature = $feat))]
589 {
590 if let Some($p) = $config {
591 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
592 }
593 }
594 };
595}
596
597impl CommonOptions {
598 pub fn new() -> CommonOptions {
600 CommonOptions {
601 opts_raw: Vec::new(),
602 codegen_raw: Vec::new(),
603 debug_raw: Vec::new(),
604 wasm_raw: Vec::new(),
605 wasi_raw: Vec::new(),
606 configured: true,
607 opts: Default::default(),
608 codegen: Default::default(),
609 debug: Default::default(),
610 wasm: Default::default(),
611 wasi: Default::default(),
612 target: None,
613 config: None,
614 }
615 }
616
617 fn configure(&mut self) -> Result<()> {
618 if self.configured {
619 return Ok(());
620 }
621 self.configured = true;
622 if let Some(toml_config_path) = &self.config {
623 let toml_options = CommonOptions::from_file(toml_config_path)?;
624 self.opts = toml_options.opts;
625 self.codegen = toml_options.codegen;
626 self.debug = toml_options.debug;
627 self.wasm = toml_options.wasm;
628 self.wasi = toml_options.wasi;
629 }
630 self.opts.configure_with(&self.opts_raw);
631 self.codegen.configure_with(&self.codegen_raw);
632 self.debug.configure_with(&self.debug_raw);
633 self.wasm.configure_with(&self.wasm_raw);
634 self.wasi.configure_with(&self.wasi_raw);
635 Ok(())
636 }
637
638 pub fn init_logging(&mut self) -> Result<()> {
639 self.configure()?;
640 if self.debug.logging == Some(false) {
641 return Ok(());
642 }
643 #[cfg(feature = "logging")]
644 if self.debug.log_to_files == Some(true) {
645 let prefix = "wasmtime.dbg.";
646 init_file_per_thread_logger(prefix);
647 } else {
648 use std::io::IsTerminal;
649 use tracing_subscriber::{EnvFilter, FmtSubscriber};
650 let builder = FmtSubscriber::builder()
651 .with_writer(std::io::stderr)
652 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
653 .with_ansi(std::io::stderr().is_terminal());
654 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
655 builder
656 .with_level(false)
657 .with_target(false)
658 .without_time()
659 .init()
660 } else {
661 builder.init();
662 }
663 }
664 #[cfg(not(feature = "logging"))]
665 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
666 anyhow::bail!("support for logging disabled at compile time");
667 }
668 Ok(())
669 }
670
671 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
672 self.configure()?;
673 let mut config = Config::new();
674
675 match_feature! {
676 ["cranelift" : self.codegen.compiler]
677 strategy => config.strategy(strategy),
678 _ => err,
679 }
680 match_feature! {
681 ["gc" : self.codegen.collector]
682 collector => config.collector(collector),
683 _ => err,
684 }
685 if let Some(target) = &self.target {
686 config.target(target)?;
687 }
688 match_feature! {
689 ["cranelift" : self.codegen.cranelift_debug_verifier]
690 enable => config.cranelift_debug_verifier(enable),
691 true => err,
692 }
693 if let Some(enable) = self.debug.debug_info {
694 config.debug_info(enable);
695 }
696 if self.debug.coredump.is_some() {
697 #[cfg(feature = "coredump")]
698 config.coredump_on_trap(true);
699 #[cfg(not(feature = "coredump"))]
700 anyhow::bail!("support for coredumps disabled at compile time");
701 }
702 match_feature! {
703 ["cranelift" : self.opts.opt_level]
704 level => config.cranelift_opt_level(level),
705 _ => err,
706 }
707 match_feature! {
708 ["cranelift": self.opts.regalloc_algorithm]
709 algo => config.cranelift_regalloc_algorithm(algo),
710 _ => err,
711 }
712 match_feature! {
713 ["cranelift" : self.wasm.nan_canonicalization]
714 enable => config.cranelift_nan_canonicalization(enable),
715 true => err,
716 }
717 match_feature! {
718 ["cranelift" : self.codegen.pcc]
719 enable => config.cranelift_pcc(enable),
720 true => err,
721 }
722
723 self.enable_wasm_features(&mut config)?;
724
725 #[cfg(feature = "cranelift")]
726 for (name, value) in self.codegen.cranelift.iter() {
727 let name = name.replace('-', "_");
728 unsafe {
729 match value {
730 Some(val) => {
731 config.cranelift_flag_set(&name, val);
732 }
733 None => {
734 config.cranelift_flag_enable(&name);
735 }
736 }
737 }
738 }
739 #[cfg(not(feature = "cranelift"))]
740 if !self.codegen.cranelift.is_empty() {
741 anyhow::bail!("support for cranelift disabled at compile time");
742 }
743
744 #[cfg(feature = "cache")]
745 if self.codegen.cache != Some(false) {
746 use wasmtime::Cache;
747 let cache = match &self.codegen.cache_config {
748 Some(path) => Cache::from_file(Some(Path::new(path)))?,
749 None => Cache::from_file(None)?,
750 };
751 config.cache(Some(cache));
752 }
753 #[cfg(not(feature = "cache"))]
754 if self.codegen.cache == Some(true) {
755 anyhow::bail!("support for caching disabled at compile time");
756 }
757
758 match_feature! {
759 ["parallel-compilation" : self.codegen.parallel_compilation]
760 enable => config.parallel_compilation(enable),
761 true => err,
762 }
763
764 let memory_reservation = self
765 .opts
766 .memory_reservation
767 .or(self.opts.static_memory_maximum_size);
768 if let Some(size) = memory_reservation {
769 config.memory_reservation(size);
770 }
771
772 if let Some(enable) = self.opts.static_memory_forced {
773 config.memory_may_move(!enable);
774 }
775 if let Some(enable) = self.opts.memory_may_move {
776 config.memory_may_move(enable);
777 }
778
779 let memory_guard_size = self
780 .opts
781 .static_memory_guard_size
782 .or(self.opts.dynamic_memory_guard_size)
783 .or(self.opts.memory_guard_size);
784 if let Some(size) = memory_guard_size {
785 config.memory_guard_size(size);
786 }
787
788 let mem_for_growth = self
789 .opts
790 .memory_reservation_for_growth
791 .or(self.opts.dynamic_memory_reserved_for_growth);
792 if let Some(size) = mem_for_growth {
793 config.memory_reservation_for_growth(size);
794 }
795 if let Some(enable) = self.opts.guard_before_linear_memory {
796 config.guard_before_linear_memory(enable);
797 }
798 if let Some(enable) = self.opts.table_lazy_init {
799 config.table_lazy_init(enable);
800 }
801
802 if self.wasm.fuel.is_some() {
804 config.consume_fuel(true);
805 }
806
807 if let Some(enable) = self.wasm.epoch_interruption {
808 config.epoch_interruption(enable);
809 }
810 if let Some(enable) = self.debug.address_map {
811 config.generate_address_map(enable);
812 }
813 if let Some(enable) = self.opts.memory_init_cow {
814 config.memory_init_cow(enable);
815 }
816 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
817 config.memory_guaranteed_dense_image_size(size);
818 }
819 if let Some(enable) = self.opts.signals_based_traps {
820 config.signals_based_traps(enable);
821 }
822 if let Some(enable) = self.codegen.native_unwind_info {
823 config.native_unwind_info(enable);
824 }
825
826 #[cfg(any(feature = "async", feature = "stack-switching"))]
829 {
830 if let Some(size) = self.wasm.async_stack_size {
831 config.async_stack_size(size);
832 }
833 }
834 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
835 {
836 if let Some(_size) = self.wasm.async_stack_size {
837 anyhow::bail!(concat!(
838 "support for async/stack-switching disabled at compile time"
839 ));
840 }
841 }
842
843 match_feature! {
844 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
845 enable => {
846 if enable {
847 let mut cfg = wasmtime::PoolingAllocationConfig::default();
848 if let Some(size) = self.opts.pooling_memory_keep_resident {
849 cfg.linear_memory_keep_resident(size);
850 }
851 if let Some(size) = self.opts.pooling_table_keep_resident {
852 cfg.table_keep_resident(size);
853 }
854 if let Some(limit) = self.opts.pooling_total_core_instances {
855 cfg.total_core_instances(limit);
856 }
857 if let Some(limit) = self.opts.pooling_total_component_instances {
858 cfg.total_component_instances(limit);
859 }
860 if let Some(limit) = self.opts.pooling_total_memories {
861 cfg.total_memories(limit);
862 }
863 if let Some(limit) = self.opts.pooling_total_tables {
864 cfg.total_tables(limit);
865 }
866 if let Some(limit) = self.opts.pooling_table_elements
867 .or(self.wasm.max_table_elements)
868 {
869 cfg.table_elements(limit);
870 }
871 if let Some(limit) = self.opts.pooling_max_core_instance_size {
872 cfg.max_core_instance_size(limit);
873 }
874 match_feature! {
875 ["async" : self.opts.pooling_total_stacks]
876 limit => cfg.total_stacks(limit),
877 _ => err,
878 }
879 if let Some(max) = self.opts.pooling_max_memory_size
880 .or(self.wasm.max_memory_size)
881 {
882 cfg.max_memory_size(max);
883 }
884 if let Some(size) = self.opts.pooling_decommit_batch_size {
885 cfg.decommit_batch_size(size);
886 }
887 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
888 cfg.max_unused_warm_slots(max);
889 }
890 match_feature! {
891 ["async" : self.opts.pooling_async_stack_keep_resident]
892 size => cfg.async_stack_keep_resident(size),
893 _ => err,
894 }
895 if let Some(max) = self.opts.pooling_max_component_instance_size {
896 cfg.max_component_instance_size(max);
897 }
898 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
899 cfg.max_core_instances_per_component(max);
900 }
901 if let Some(max) = self.opts.pooling_max_memories_per_component {
902 cfg.max_memories_per_component(max);
903 }
904 if let Some(max) = self.opts.pooling_max_tables_per_component {
905 cfg.max_tables_per_component(max);
906 }
907 if let Some(max) = self.opts.pooling_max_tables_per_module {
908 cfg.max_tables_per_module(max);
909 }
910 if let Some(max) = self.opts.pooling_max_memories_per_module {
911 cfg.max_memories_per_module(max);
912 }
913 match_feature! {
914 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
915 enable => cfg.memory_protection_keys(enable),
916 _ => err,
917 }
918 match_feature! {
919 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
920 max => cfg.max_memory_protection_keys(max),
921 _ => err,
922 }
923 match_feature! {
924 ["gc" : self.opts.pooling_total_gc_heaps]
925 max => cfg.total_gc_heaps(max),
926 _ => err,
927 }
928 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
929 }
930 },
931 true => err,
932 }
933
934 if self.opts.pooling_memory_protection_keys.is_some()
935 && !self.opts.pooling_allocator.unwrap_or(false)
936 {
937 anyhow::bail!("memory protection keys require the pooling allocator");
938 }
939
940 if self.opts.pooling_max_memory_protection_keys.is_some()
941 && !self.opts.pooling_memory_protection_keys.is_some()
942 {
943 anyhow::bail!(
944 "max memory protection keys requires memory protection keys to be enabled"
945 );
946 }
947
948 match_feature! {
949 ["async" : self.wasm.async_stack_zeroing]
950 enable => config.async_stack_zeroing(enable),
951 _ => err,
952 }
953
954 if let Some(max) = self.wasm.max_wasm_stack {
955 config.max_wasm_stack(max);
956
957 #[cfg(any(feature = "async", feature = "stack-switching"))]
961 if self.wasm.async_stack_size.is_none() {
962 const DEFAULT_HOST_STACK: usize = 512 << 10;
963 config.async_stack_size(max + DEFAULT_HOST_STACK);
964 }
965 }
966
967 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
968 config.relaxed_simd_deterministic(enable);
969 }
970 match_feature! {
971 ["cranelift" : self.wasm.wmemcheck]
972 enable => config.wmemcheck(enable),
973 true => err,
974 }
975
976 Ok(config)
977 }
978
979 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
980 let all = self.wasm.all_proposals;
981
982 if let Some(enable) = self.wasm.simd.or(all) {
983 config.wasm_simd(enable);
984 }
985 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
986 config.wasm_relaxed_simd(enable);
987 }
988 if let Some(enable) = self.wasm.bulk_memory.or(all) {
989 config.wasm_bulk_memory(enable);
990 }
991 if let Some(enable) = self.wasm.multi_value.or(all) {
992 config.wasm_multi_value(enable);
993 }
994 if let Some(enable) = self.wasm.tail_call.or(all) {
995 config.wasm_tail_call(enable);
996 }
997 if let Some(enable) = self.wasm.multi_memory.or(all) {
998 config.wasm_multi_memory(enable);
999 }
1000 if let Some(enable) = self.wasm.memory64.or(all) {
1001 config.wasm_memory64(enable);
1002 }
1003 if let Some(enable) = self.wasm.stack_switching {
1004 config.wasm_stack_switching(enable);
1005 }
1006 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1007 config.wasm_custom_page_sizes(enable);
1008 }
1009 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1010 config.wasm_wide_arithmetic(enable);
1011 }
1012 if let Some(enable) = self.wasm.extended_const.or(all) {
1013 config.wasm_extended_const(enable);
1014 }
1015 if let Some(enable) = self.wasm.exceptions.or(all) {
1016 config.wasm_exceptions(enable);
1017 }
1018 if let Some(enable) = self.wasm.legacy_exceptions.or(all) {
1019 #[expect(deprecated, reason = "forwarding CLI flag")]
1020 config.wasm_legacy_exceptions(enable);
1021 }
1022
1023 macro_rules! handle_conditionally_compiled {
1024 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1025 if let Some(enable) = self.wasm.$field.or(all) {
1026 #[cfg(feature = $feature)]
1027 config.$method(enable);
1028 #[cfg(not(feature = $feature))]
1029 if enable && all.is_none() {
1030 anyhow::bail!("support for {} was disabled at compile-time", $feature);
1031 }
1032 }
1033 )*)
1034 }
1035
1036 handle_conditionally_compiled! {
1037 ("component-model", component_model, wasm_component_model)
1038 ("component-model-async", component_model_async, wasm_component_model_async)
1039 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1040 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1041 ("component-model", component_model_error_context, wasm_component_model_error_context)
1042 ("threads", threads, wasm_threads)
1043 ("gc", gc, wasm_gc)
1044 ("gc", reference_types, wasm_reference_types)
1045 ("gc", function_references, wasm_function_references)
1046 ("stack-switching", stack_switching, wasm_stack_switching)
1047 }
1048
1049 if let Some(enable) = self.wasm.component_model_gc {
1050 #[cfg(all(feature = "component-model", feature = "gc"))]
1051 config.wasm_component_model_gc(enable);
1052 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1053 if enable && all.is_none() {
1054 anyhow::bail!("support for `component-model-gc` was disabled at compile time")
1055 }
1056 }
1057
1058 Ok(())
1059 }
1060
1061 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1062 let path_ref = path.as_ref();
1063 let file_contents = fs::read_to_string(path_ref)
1064 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1065 toml::from_str::<CommonOptions>(&file_contents)
1066 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1067 }
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072 use wasmtime::{OptLevel, RegallocAlgorithm};
1073
1074 use super::*;
1075
1076 #[test]
1077 fn from_toml() {
1078 let empty_toml = "";
1080 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1081 common_options.config(None).unwrap();
1082
1083 let basic_toml = r#"
1085 [optimize]
1086 [codegen]
1087 [debug]
1088 [wasm]
1089 [wasi]
1090 "#;
1091 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1092 common_options.config(None).unwrap();
1093
1094 for (opt_value, expected) in [
1096 ("0", Some(OptLevel::None)),
1097 ("1", Some(OptLevel::Speed)),
1098 ("2", Some(OptLevel::Speed)),
1099 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1100 ("\"hello\"", None), ("3", None), ] {
1103 let toml = format!(
1104 r#"
1105 [optimize]
1106 opt-level = {opt_value}
1107 "#,
1108 );
1109 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1110 .ok()
1111 .and_then(|common_options| common_options.opts.opt_level);
1112
1113 assert_eq!(
1114 parsed_opt_level, expected,
1115 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1116 );
1117 }
1118
1119 for (regalloc_value, expected) in [
1121 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1122 ("\"hello\"", None), ("3", None), ("true", None), ] {
1126 let toml = format!(
1127 r#"
1128 [optimize]
1129 regalloc-algorithm = {regalloc_value}
1130 "#,
1131 );
1132 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1133 .ok()
1134 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1135 assert_eq!(
1136 parsed_regalloc_algorithm, expected,
1137 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1138 );
1139 }
1140
1141 for (strategy_value, expected) in [
1143 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1144 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1145 ("\"hello\"", None), ("5", None), ("true", None), ] {
1149 let toml = format!(
1150 r#"
1151 [codegen]
1152 compiler = {strategy_value}
1153 "#,
1154 );
1155 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1156 .ok()
1157 .and_then(|common_options| common_options.codegen.compiler);
1158 assert_eq!(
1159 parsed_strategy, expected,
1160 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1161 );
1162 }
1163
1164 for (collector_value, expected) in [
1166 (
1167 "\"drc\"",
1168 Some(wasmtime::Collector::DeferredReferenceCounting),
1169 ),
1170 ("\"null\"", Some(wasmtime::Collector::Null)),
1171 ("\"hello\"", None), ("5", None), ("true", None), ] {
1175 let toml = format!(
1176 r#"
1177 [codegen]
1178 collector = {collector_value}
1179 "#,
1180 );
1181 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1182 .ok()
1183 .and_then(|common_options| common_options.codegen.collector);
1184 assert_eq!(
1185 parsed_collector, expected,
1186 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1187 );
1188 }
1189 }
1190}
1191
1192impl Default for CommonOptions {
1193 fn default() -> CommonOptions {
1194 CommonOptions::new()
1195 }
1196}
1197
1198impl fmt::Display for CommonOptions {
1199 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1200 let CommonOptions {
1201 codegen_raw,
1202 codegen,
1203 debug_raw,
1204 debug,
1205 opts_raw,
1206 opts,
1207 wasm_raw,
1208 wasm,
1209 wasi_raw,
1210 wasi,
1211 configured,
1212 target,
1213 config,
1214 } = self;
1215 if let Some(target) = target {
1216 write!(f, "--target {target} ")?;
1217 }
1218 if let Some(config) = config {
1219 write!(f, "--config {} ", config.display())?;
1220 }
1221
1222 let codegen_flags;
1223 let opts_flags;
1224 let wasi_flags;
1225 let wasm_flags;
1226 let debug_flags;
1227
1228 if *configured {
1229 codegen_flags = codegen.to_options();
1230 debug_flags = debug.to_options();
1231 wasi_flags = wasi.to_options();
1232 wasm_flags = wasm.to_options();
1233 opts_flags = opts.to_options();
1234 } else {
1235 codegen_flags = codegen_raw
1236 .iter()
1237 .flat_map(|t| t.0.iter())
1238 .cloned()
1239 .collect();
1240 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1241 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1242 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1243 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1244 }
1245
1246 for flag in codegen_flags {
1247 write!(f, "-C{flag} ")?;
1248 }
1249 for flag in opts_flags {
1250 write!(f, "-O{flag} ")?;
1251 }
1252 for flag in wasi_flags {
1253 write!(f, "-S{flag} ")?;
1254 }
1255 for flag in wasm_flags {
1256 write!(f, "-W{flag} ")?;
1257 }
1258 for flag in debug_flags {
1259 write!(f, "-D{flag} ")?;
1260 }
1261
1262 Ok(())
1263 }
1264}