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