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