1use clap::Parser;
4use serde::Deserialize;
5use std::num::NonZeroUsize;
6use std::{
7 fmt, fs,
8 num::NonZeroU32,
9 path::{Path, PathBuf},
10 time::Duration,
11};
12use wasmtime::{Config, Result, WasmBacktraceDetails, bail, error::Context as _};
13
14pub mod opt;
15
16#[cfg(feature = "logging")]
17fn init_file_per_thread_logger(prefix: &'static str) {
18 file_per_thread_logger::initialize(prefix);
19 file_per_thread_logger::allow_uninitialized();
20
21 #[cfg(feature = "parallel-compilation")]
26 rayon::ThreadPoolBuilder::new()
27 .spawn_handler(move |thread| {
28 let mut b = std::thread::Builder::new();
29 if let Some(name) = thread.name() {
30 b = b.name(name.to_owned());
31 }
32 if let Some(stack_size) = thread.stack_size() {
33 b = b.stack_size(stack_size);
34 }
35 b.spawn(move || {
36 file_per_thread_logger::initialize(prefix);
37 thread.run()
38 })?;
39 Ok(())
40 })
41 .build_global()
42 .unwrap();
43}
44
45wasmtime_option_group! {
46 #[derive(PartialEq, Clone, Deserialize)]
47 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
48 pub struct OptimizeOptions {
49 #[serde(default)]
51 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
52 pub opt_level: Option<wasmtime::OptLevel>,
53
54 #[serde(default)]
56 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
57 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
58
59 pub memory_may_move: Option<bool>,
62
63 pub memory_reservation: Option<u64>,
65
66 pub memory_reservation_for_growth: Option<u64>,
68
69 pub memory_guard_size: Option<u64>,
71
72 pub gc_heap_may_move: Option<bool>,
75
76 pub gc_heap_reservation: Option<u64>,
78
79 pub gc_heap_reservation_for_growth: Option<u64>,
81
82 pub gc_heap_guard_size: Option<u64>,
84
85 pub guard_before_linear_memory: Option<bool>,
88
89 pub table_lazy_init: Option<bool>,
94
95 pub pooling_allocator: Option<bool>,
97
98 pub pooling_decommit_batch_size: Option<usize>,
101
102 pub pooling_memory_keep_resident: Option<usize>,
105
106 pub pooling_table_keep_resident: Option<usize>,
109
110 #[serde(default)]
113 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
114 pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
115
116 pub pooling_max_memory_protection_keys: Option<usize>,
119
120 pub memory_init_cow: Option<bool>,
123
124 pub memory_guaranteed_dense_image_size: Option<u64>,
127
128 pub pooling_total_core_instances: Option<u32>,
131
132 pub pooling_total_component_instances: Option<u32>,
135
136 pub pooling_total_memories: Option<u32>,
139
140 pub pooling_total_tables: Option<u32>,
143
144 pub pooling_total_stacks: Option<u32>,
147
148 pub pooling_max_memory_size: Option<usize>,
151
152 pub pooling_table_elements: Option<usize>,
155
156 pub pooling_max_core_instance_size: Option<usize>,
159
160 pub pooling_max_unused_warm_slots: Option<u32>,
163
164 pub pooling_async_stack_keep_resident: Option<usize>,
167
168 pub pooling_max_component_instance_size: Option<usize>,
171
172 pub pooling_max_core_instances_per_component: Option<u32>,
175
176 pub pooling_max_memories_per_component: Option<u32>,
179
180 pub pooling_max_tables_per_component: Option<u32>,
183
184 pub pooling_max_tables_per_module: Option<u32>,
186
187 pub pooling_max_memories_per_module: Option<u32>,
189
190 pub pooling_total_gc_heaps: Option<u32>,
192
193 pub signals_based_traps: Option<bool>,
195
196 pub dynamic_memory_guard_size: Option<u64>,
198
199 pub static_memory_guard_size: Option<u64>,
201
202 pub static_memory_forced: Option<bool>,
204
205 pub static_memory_maximum_size: Option<u64>,
207
208 pub dynamic_memory_reserved_for_growth: Option<u64>,
210
211 #[serde(default)]
214 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
215 pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
216
217 #[doc(hidden)]
219 pub gc_zeal_alloc_counter: Option<NonZeroU32>,
220 }
221
222 enum Optimize {
223 ...
224 }
225}
226
227wasmtime_option_group! {
228 #[derive(PartialEq, Clone, Deserialize)]
229 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
230 pub struct CodegenOptions {
231 #[serde(default)]
236 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
237 pub compiler: Option<wasmtime::Strategy>,
238 #[serde(default)]
250 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
251 pub collector: Option<wasmtime::Collector>,
252 pub cranelift_debug_verifier: Option<bool>,
254 pub cache: Option<bool>,
256 pub cache_config: Option<String>,
258 pub parallel_compilation: Option<bool>,
260 pub native_unwind_info: Option<bool>,
263
264 pub inlining: Option<bool>,
266
267 #[prefixed = "cranelift"]
268 #[serde(default)]
269 pub cranelift: Vec<(String, Option<String>)>,
272 }
273
274 enum Codegen {
275 ...
276 }
277}
278
279wasmtime_option_group! {
280 #[derive(PartialEq, Clone, Deserialize)]
281 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
282 pub struct DebugOptions {
283 pub debug_info: Option<bool>,
285 pub guest_debug: Option<bool>,
287 pub address_map: Option<bool>,
289 pub logging: Option<bool>,
291 pub log_to_files: Option<bool>,
293 pub coredump: Option<String>,
295 pub debugger: Option<PathBuf>,
298 #[serde(default)]
301 pub arg: Vec<String>,
302 pub inherit_stdin: Option<bool>,
305 pub inherit_stdout: Option<bool>,
308 pub inherit_stderr: Option<bool>,
311 pub max_backtrace: Option<usize>,
313 }
314
315 enum Debug {
316 ...
317 }
318}
319
320wasmtime_option_group! {
321 #[derive(PartialEq, Clone, Deserialize)]
322 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
323 pub struct WasmOptions {
324 pub nan_canonicalization: Option<bool>,
326 pub fuel: Option<u64>,
334 pub epoch_interruption: Option<bool>,
337 pub max_wasm_stack: Option<usize>,
340 pub async_stack_size: Option<usize>,
346 pub async_stack_zeroing: Option<bool>,
349 pub unknown_exports_allow: Option<bool>,
351 pub unknown_imports_trap: Option<bool>,
354 pub unknown_imports_default: Option<bool>,
357 pub wmemcheck: Option<bool>,
359 pub max_memory_size: Option<usize>,
364 pub max_table_elements: Option<usize>,
366 pub max_instances: Option<usize>,
368 pub max_tables: Option<usize>,
370 pub max_memories: Option<usize>,
372 pub trap_on_grow_failure: Option<bool>,
379 pub timeout: Option<Duration>,
381 pub all_proposals: Option<bool>,
383 pub bulk_memory: Option<bool>,
385 pub multi_memory: Option<bool>,
387 pub multi_value: Option<bool>,
389 pub reference_types: Option<bool>,
391 pub simd: Option<bool>,
393 pub relaxed_simd: Option<bool>,
395 pub relaxed_simd_deterministic: Option<bool>,
404 pub tail_call: Option<bool>,
406 pub threads: Option<bool>,
408 pub shared_memory: Option<bool>,
410 pub shared_everything_threads: Option<bool>,
412 pub memory64: Option<bool>,
414 pub component_model: Option<bool>,
416 pub component_model_async: Option<bool>,
418 pub component_model_more_async_builtins: Option<bool>,
421 pub component_model_async_stackful: Option<bool>,
424 pub component_model_threading: Option<bool>,
427 pub component_model_error_context: Option<bool>,
430 pub component_model_gc: Option<bool>,
433 pub component_model_map: Option<bool>,
435 pub function_references: Option<bool>,
437 pub stack_switching: Option<bool>,
439 pub gc: Option<bool>,
441 pub custom_page_sizes: Option<bool>,
443 pub wide_arithmetic: Option<bool>,
445 pub extended_const: Option<bool>,
447 pub exceptions: Option<bool>,
449 pub gc_support: Option<bool>,
451 pub component_model_fixed_length_lists: Option<bool>,
454 pub concurrency_support: Option<bool>,
457 }
458
459 enum Wasm {
460 ...
461 }
462}
463
464wasmtime_option_group! {
465 #[derive(PartialEq, Clone, Deserialize)]
466 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
467 pub struct WasiOptions {
468 pub cli: Option<bool>,
470 pub cli_exit_with_code: Option<bool>,
472 pub common: Option<bool>,
474 pub nn: Option<bool>,
476 pub threads: Option<bool>,
478 pub http: Option<bool>,
480 pub http_outgoing_body_buffer_chunks: Option<usize>,
484 pub http_outgoing_body_chunk_size: Option<usize>,
487 pub config: Option<bool>,
489 pub keyvalue: Option<bool>,
491 pub listenfd: Option<bool>,
495 #[serde(default)]
498 pub tcplisten: Vec<String>,
499 pub tls: Option<bool>,
501 pub preview2: Option<bool>,
504 #[serde(skip)]
513 pub nn_graph: Vec<WasiNnGraph>,
514 pub inherit_network: Option<bool>,
517 pub allow_ip_name_lookup: Option<bool>,
519 pub tcp: Option<bool>,
521 pub udp: Option<bool>,
523 pub network_error_code: Option<bool>,
525 pub preview0: Option<bool>,
527 pub inherit_env: Option<bool>,
531 pub inherit_stdin: Option<bool>,
533 pub inherit_stdout: Option<bool>,
535 pub inherit_stderr: Option<bool>,
537 #[serde(skip)]
539 pub config_var: Vec<KeyValuePair>,
540 #[serde(skip)]
542 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
543 pub p3: Option<bool>,
545 pub max_resources: Option<usize>,
547 pub hostcall_fuel: Option<usize>,
549 pub max_random_size: Option<u64>,
553 pub max_http_fields_size: Option<usize>,
557 }
558
559 enum Wasi {
560 ...
561 }
562}
563
564wasmtime_option_group! {
565 #[derive(PartialEq, Clone, Deserialize)]
566 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
567 pub struct RecordOptions {
568 pub path: Option<String>,
570 pub validation_metadata: Option<bool>,
573 pub event_window_size: Option<usize>,
576 }
577
578 enum Record {
579 ...
580 }
581}
582
583#[derive(Debug, Clone, PartialEq)]
584pub struct WasiNnGraph {
585 pub format: String,
586 pub dir: String,
587}
588
589#[derive(Debug, Clone, PartialEq)]
590pub struct KeyValuePair {
591 pub key: String,
592 pub value: String,
593}
594
595#[derive(Parser, Clone, Deserialize)]
597#[serde(deny_unknown_fields)]
598pub struct CommonOptions {
599 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
609 #[serde(skip)]
610 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
611
612 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
614 #[serde(skip)]
615 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
616
617 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
619 #[serde(skip)]
620 debug_raw: Vec<opt::CommaSeparated<Debug>>,
621
622 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
625 #[serde(skip)]
626 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
627
628 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
630 #[serde(skip)]
631 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
632
633 #[arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")]
642 #[serde(skip)]
643 record_raw: Vec<opt::CommaSeparated<Record>>,
644
645 #[arg(skip)]
648 #[serde(skip)]
649 configured: bool,
650
651 #[arg(skip)]
652 #[serde(rename = "optimize", default)]
653 pub opts: OptimizeOptions,
654
655 #[arg(skip)]
656 #[serde(rename = "codegen", default)]
657 pub codegen: CodegenOptions,
658
659 #[arg(skip)]
660 #[serde(rename = "debug", default)]
661 pub debug: DebugOptions,
662
663 #[arg(skip)]
664 #[serde(rename = "wasm", default)]
665 pub wasm: WasmOptions,
666
667 #[arg(skip)]
668 #[serde(rename = "wasi", default)]
669 pub wasi: WasiOptions,
670
671 #[arg(skip)]
672 #[serde(rename = "record", default)]
673 pub record: RecordOptions,
674
675 #[arg(long, value_name = "TARGET")]
677 #[serde(skip)]
678 pub target: Option<String>,
679
680 #[arg(long = "config", value_name = "FILE")]
687 #[serde(skip)]
688 pub config: Option<PathBuf>,
689}
690
691macro_rules! match_feature {
692 (
693 [$feat:tt : $config:expr]
694 $val:ident => $e:expr,
695 $p:pat => err,
696 ) => {
697 #[cfg(feature = $feat)]
698 {
699 if let Some($val) = $config {
700 $e;
701 }
702 }
703 #[cfg(not(feature = $feat))]
704 {
705 if let Some($p) = $config {
706 bail!(concat!("support for ", $feat, " disabled at compile time"));
707 }
708 }
709 };
710}
711
712impl CommonOptions {
713 pub fn new() -> CommonOptions {
715 CommonOptions {
716 opts_raw: Vec::new(),
717 codegen_raw: Vec::new(),
718 debug_raw: Vec::new(),
719 wasm_raw: Vec::new(),
720 wasi_raw: Vec::new(),
721 record_raw: Vec::new(),
722 configured: true,
723 opts: Default::default(),
724 codegen: Default::default(),
725 debug: Default::default(),
726 wasm: Default::default(),
727 wasi: Default::default(),
728 record: Default::default(),
729 target: None,
730 config: None,
731 }
732 }
733
734 fn configure(&mut self) -> Result<()> {
735 if self.configured {
736 return Ok(());
737 }
738 self.configured = true;
739 if let Some(toml_config_path) = &self.config {
740 let toml_options = CommonOptions::from_file(toml_config_path)?;
741 self.opts = toml_options.opts;
742 self.codegen = toml_options.codegen;
743 self.debug = toml_options.debug;
744 self.wasm = toml_options.wasm;
745 self.wasi = toml_options.wasi;
746 self.record = toml_options.record;
747 }
748 self.opts.configure_with(&self.opts_raw);
749 self.codegen.configure_with(&self.codegen_raw);
750 self.debug.configure_with(&self.debug_raw);
751 self.wasm.configure_with(&self.wasm_raw);
752 self.wasi.configure_with(&self.wasi_raw);
753 self.record.configure_with(&self.record_raw);
754 Ok(())
755 }
756
757 pub fn init_logging(&mut self) -> Result<()> {
758 self.configure()?;
759 if self.debug.logging == Some(false) {
760 return Ok(());
761 }
762 #[cfg(feature = "logging")]
763 if self.debug.log_to_files == Some(true) {
764 let prefix = "wasmtime.dbg.";
765 init_file_per_thread_logger(prefix);
766 } else {
767 use std::io::IsTerminal;
768 use tracing_subscriber::{EnvFilter, FmtSubscriber};
769 let builder = FmtSubscriber::builder()
770 .with_writer(std::io::stderr)
771 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
772 .with_ansi(std::io::stderr().is_terminal());
773 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
774 builder
775 .with_level(false)
776 .with_target(false)
777 .without_time()
778 .init()
779 } else {
780 builder.init();
781 }
782 }
783 #[cfg(not(feature = "logging"))]
784 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
785 bail!("support for logging disabled at compile time");
786 }
787 Ok(())
788 }
789
790 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
791 self.configure()?;
792 let mut config = Config::new();
793
794 match_feature! {
795 ["cranelift" : self.codegen.compiler]
796 strategy => config.strategy(strategy),
797 _ => err,
798 }
799 match_feature! {
800 ["gc" : self.codegen.collector]
801 collector => config.collector(collector),
802 _ => err,
803 }
804 if let Some(target) = &self.target {
805 config.target(target)?;
806 }
807 match_feature! {
808 ["cranelift" : self.codegen.cranelift_debug_verifier]
809 enable => config.cranelift_debug_verifier(enable),
810 true => err,
811 }
812 if let Some(enable) = self.debug.debug_info {
813 config.debug_info(enable);
814 }
815 match_feature! {
816 ["debug" : self.debug.guest_debug]
817 enable => config.guest_debug(enable),
818 _ => err,
819 }
820 if self.debug.coredump.is_some() {
821 #[cfg(feature = "coredump")]
822 config.coredump_on_trap(true);
823 #[cfg(not(feature = "coredump"))]
824 bail!("support for coredumps disabled at compile time");
825 }
826 match_feature! {
827 ["cranelift" : self.opts.opt_level]
828 level => config.cranelift_opt_level(level),
829 _ => err,
830 }
831 match_feature! {
832 ["cranelift": self.opts.regalloc_algorithm]
833 algo => config.cranelift_regalloc_algorithm(algo),
834 _ => err,
835 }
836 match_feature! {
837 ["cranelift" : self.wasm.nan_canonicalization]
838 enable => config.cranelift_nan_canonicalization(enable),
839 true => err,
840 }
841
842 self.enable_wasm_features(&mut config)?;
843
844 #[cfg(feature = "cranelift")]
845 for (name, value) in self.codegen.cranelift.iter() {
846 let name = name.replace('-', "_");
847 unsafe {
848 match value {
849 Some(val) => {
850 config.cranelift_flag_set(&name, val);
851 }
852 None => {
853 config.cranelift_flag_enable(&name);
854 }
855 }
856 }
857 }
858 #[cfg(not(feature = "cranelift"))]
859 if !self.codegen.cranelift.is_empty() {
860 bail!("support for cranelift disabled at compile time");
861 }
862
863 #[cfg(feature = "cache")]
864 if self.codegen.cache != Some(false) {
865 use wasmtime::Cache;
866 let cache = match &self.codegen.cache_config {
867 Some(path) => Cache::from_file(Some(Path::new(path)))?,
868 None => Cache::from_file(None)?,
869 };
870 config.cache(Some(cache));
871 }
872 #[cfg(not(feature = "cache"))]
873 if self.codegen.cache == Some(true) {
874 bail!("support for caching disabled at compile time");
875 }
876
877 match_feature! {
878 ["parallel-compilation" : self.codegen.parallel_compilation]
879 enable => config.parallel_compilation(enable),
880 true => err,
881 }
882
883 let memory_reservation = self
884 .opts
885 .memory_reservation
886 .or(self.opts.static_memory_maximum_size);
887 if let Some(size) = memory_reservation {
888 config.memory_reservation(size);
889 }
890
891 if let Some(enable) = self.opts.static_memory_forced {
892 config.memory_may_move(!enable);
893 }
894 if let Some(enable) = self.opts.memory_may_move {
895 config.memory_may_move(enable);
896 }
897
898 let memory_guard_size = self
899 .opts
900 .static_memory_guard_size
901 .or(self.opts.dynamic_memory_guard_size)
902 .or(self.opts.memory_guard_size);
903 if let Some(size) = memory_guard_size {
904 config.memory_guard_size(size);
905 }
906
907 let mem_for_growth = self
908 .opts
909 .memory_reservation_for_growth
910 .or(self.opts.dynamic_memory_reserved_for_growth);
911 if let Some(size) = mem_for_growth {
912 config.memory_reservation_for_growth(size);
913 }
914 if let Some(enable) = self.opts.guard_before_linear_memory {
915 config.guard_before_linear_memory(enable);
916 }
917
918 if let Some(size) = self.opts.gc_heap_reservation {
919 config.gc_heap_reservation(size);
920 }
921 if let Some(enable) = self.opts.gc_heap_may_move {
922 config.gc_heap_may_move(enable);
923 }
924 if let Some(size) = self.opts.gc_heap_guard_size {
925 config.gc_heap_guard_size(size);
926 }
927 if let Some(size) = self.opts.gc_heap_reservation_for_growth {
928 config.gc_heap_reservation_for_growth(size);
929 }
930 if let Some(enable) = self.opts.table_lazy_init {
931 config.table_lazy_init(enable);
932 }
933
934 if let Some(n) = self.opts.gc_zeal_alloc_counter
935 && (cfg!(gc_zeal) || cfg!(fuzzing))
936 {
937 config.gc_zeal_alloc_counter(Some(n))?;
938 }
939
940 if self.wasm.fuel.is_some() {
942 config.consume_fuel(true);
943 }
944
945 if let Some(enable) = self.wasm.epoch_interruption {
946 config.epoch_interruption(enable);
947 }
948 if let Some(enable) = self.debug.address_map {
949 config.generate_address_map(enable);
950 }
951 if let Some(frames) = self.debug.max_backtrace {
952 match NonZeroUsize::new(frames) {
953 None => {
954 config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
955 }
956 Some(amt) => {
957 config.wasm_backtrace_max_frames(Some(amt));
958 }
959 }
960 }
961 if let Some(enable) = self.opts.memory_init_cow {
962 config.memory_init_cow(enable);
963 }
964 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
965 config.memory_guaranteed_dense_image_size(size);
966 }
967 if let Some(enable) = self.opts.signals_based_traps {
968 config.signals_based_traps(enable);
969 }
970 if let Some(enable) = self.codegen.native_unwind_info {
971 config.native_unwind_info(enable);
972 }
973 if let Some(enable) = self.codegen.inlining {
974 config.compiler_inlining(enable);
975 }
976
977 #[cfg(any(feature = "async", feature = "stack-switching"))]
980 {
981 if let Some(size) = self.wasm.async_stack_size {
982 config.async_stack_size(size);
983 }
984 }
985 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
986 {
987 if let Some(_size) = self.wasm.async_stack_size {
988 bail!(concat!(
989 "support for async/stack-switching disabled at compile time"
990 ));
991 }
992 }
993
994 match_feature! {
995 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
996 enable => {
997 if enable {
998 let mut cfg = wasmtime::PoolingAllocationConfig::default();
999 if let Some(size) = self.opts.pooling_memory_keep_resident {
1000 cfg.linear_memory_keep_resident(size);
1001 }
1002 if let Some(size) = self.opts.pooling_table_keep_resident {
1003 cfg.table_keep_resident(size);
1004 }
1005 if let Some(limit) = self.opts.pooling_total_core_instances {
1006 cfg.total_core_instances(limit);
1007 }
1008 if let Some(limit) = self.opts.pooling_total_component_instances {
1009 cfg.total_component_instances(limit);
1010 }
1011 if let Some(limit) = self.opts.pooling_total_memories {
1012 cfg.total_memories(limit);
1013 }
1014 if let Some(limit) = self.opts.pooling_total_tables {
1015 cfg.total_tables(limit);
1016 }
1017 if let Some(limit) = self.opts.pooling_table_elements
1018 .or(self.wasm.max_table_elements)
1019 {
1020 cfg.table_elements(limit);
1021 }
1022 if let Some(limit) = self.opts.pooling_max_core_instance_size {
1023 cfg.max_core_instance_size(limit);
1024 }
1025 match_feature! {
1026 ["async" : self.opts.pooling_total_stacks]
1027 limit => cfg.total_stacks(limit),
1028 _ => err,
1029 }
1030 if let Some(max) = self.opts.pooling_max_memory_size
1031 .or(self.wasm.max_memory_size)
1032 {
1033 cfg.max_memory_size(max);
1034 }
1035 if let Some(size) = self.opts.pooling_decommit_batch_size {
1036 cfg.decommit_batch_size(size);
1037 }
1038 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1039 cfg.max_unused_warm_slots(max);
1040 }
1041 match_feature! {
1042 ["async" : self.opts.pooling_async_stack_keep_resident]
1043 size => cfg.async_stack_keep_resident(size),
1044 _ => err,
1045 }
1046 if let Some(max) = self.opts.pooling_max_component_instance_size {
1047 cfg.max_component_instance_size(max);
1048 }
1049 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1050 cfg.max_core_instances_per_component(max);
1051 }
1052 if let Some(max) = self.opts.pooling_max_memories_per_component {
1053 cfg.max_memories_per_component(max);
1054 }
1055 if let Some(max) = self.opts.pooling_max_tables_per_component {
1056 cfg.max_tables_per_component(max);
1057 }
1058 if let Some(max) = self.opts.pooling_max_tables_per_module {
1059 cfg.max_tables_per_module(max);
1060 }
1061 if let Some(max) = self.opts.pooling_max_memories_per_module {
1062 cfg.max_memories_per_module(max);
1063 }
1064 match_feature! {
1065 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1066 enable => cfg.memory_protection_keys(enable),
1067 _ => err,
1068 }
1069 match_feature! {
1070 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1071 max => cfg.max_memory_protection_keys(max),
1072 _ => err,
1073 }
1074 match_feature! {
1075 ["gc" : self.opts.pooling_total_gc_heaps]
1076 max => cfg.total_gc_heaps(max),
1077 _ => err,
1078 }
1079 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1080 cfg.pagemap_scan(enabled);
1081 }
1082 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1083 }
1084 },
1085 true => err,
1086 }
1087
1088 if self.opts.pooling_memory_protection_keys.is_some()
1089 && !self.opts.pooling_allocator.unwrap_or(false)
1090 {
1091 bail!("memory protection keys require the pooling allocator");
1092 }
1093
1094 if self.opts.pooling_max_memory_protection_keys.is_some()
1095 && !self.opts.pooling_memory_protection_keys.is_some()
1096 {
1097 bail!("max memory protection keys requires memory protection keys to be enabled");
1098 }
1099
1100 match_feature! {
1101 ["async" : self.wasm.async_stack_zeroing]
1102 enable => config.async_stack_zeroing(enable),
1103 _ => err,
1104 }
1105
1106 if let Some(max) = self.wasm.max_wasm_stack {
1107 config.max_wasm_stack(max);
1108
1109 #[cfg(any(feature = "async", feature = "stack-switching"))]
1113 if self.wasm.async_stack_size.is_none() {
1114 const DEFAULT_HOST_STACK: usize = 512 << 10;
1115 config.async_stack_size(max + DEFAULT_HOST_STACK);
1116 }
1117 }
1118
1119 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1120 config.relaxed_simd_deterministic(enable);
1121 }
1122 match_feature! {
1123 ["cranelift" : self.wasm.wmemcheck]
1124 enable => config.wmemcheck(enable),
1125 true => err,
1126 }
1127
1128 if let Some(enable) = self.wasm.gc_support {
1129 config.gc_support(enable);
1130 }
1131
1132 if let Some(enable) = self.wasm.concurrency_support {
1133 config.concurrency_support(enable);
1134 }
1135
1136 if let Some(enable) = self.wasm.shared_memory {
1137 config.shared_memory(enable);
1138 }
1139
1140 let record = &self.record;
1141 match_feature! {
1142 ["rr" : &record.path]
1143 _path => {
1144 bail!("recording configuration for `rr` feature is not supported yet");
1145 },
1146 _ => err,
1147 }
1148
1149 Ok(config)
1150 }
1151
1152 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1153 let all = self.wasm.all_proposals;
1154
1155 if let Some(enable) = self.wasm.simd.or(all) {
1156 config.wasm_simd(enable);
1157 }
1158 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1159 config.wasm_relaxed_simd(enable);
1160 }
1161 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1162 config.wasm_bulk_memory(enable);
1163 }
1164 if let Some(enable) = self.wasm.multi_value.or(all) {
1165 config.wasm_multi_value(enable);
1166 }
1167 if let Some(enable) = self.wasm.tail_call.or(all) {
1168 config.wasm_tail_call(enable);
1169 }
1170 if let Some(enable) = self.wasm.multi_memory.or(all) {
1171 config.wasm_multi_memory(enable);
1172 }
1173 if let Some(enable) = self.wasm.memory64.or(all) {
1174 config.wasm_memory64(enable);
1175 }
1176 if let Some(enable) = self.wasm.stack_switching {
1177 config.wasm_stack_switching(enable);
1178 }
1179 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1180 config.wasm_custom_page_sizes(enable);
1181 }
1182 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1183 config.wasm_wide_arithmetic(enable);
1184 }
1185 if let Some(enable) = self.wasm.extended_const.or(all) {
1186 config.wasm_extended_const(enable);
1187 }
1188
1189 macro_rules! handle_conditionally_compiled {
1190 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1191 if let Some(enable) = self.wasm.$field.or(all) {
1192 #[cfg(feature = $feature)]
1193 config.$method(enable);
1194 #[cfg(not(feature = $feature))]
1195 if enable && all.is_none() {
1196 bail!("support for {} was disabled at compile-time", $feature);
1197 }
1198 }
1199 )*)
1200 }
1201
1202 handle_conditionally_compiled! {
1203 ("component-model", component_model, wasm_component_model)
1204 ("component-model-async", component_model_async, wasm_component_model_async)
1205 ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1206 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1207 ("component-model-async", component_model_threading, wasm_component_model_threading)
1208 ("component-model", component_model_error_context, wasm_component_model_error_context)
1209 ("component-model", component_model_map, wasm_component_model_map)
1210 ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1211 ("threads", threads, wasm_threads)
1212 ("gc", gc, wasm_gc)
1213 ("gc", reference_types, wasm_reference_types)
1214 ("gc", function_references, wasm_function_references)
1215 ("gc", exceptions, wasm_exceptions)
1216 ("stack-switching", stack_switching, wasm_stack_switching)
1217 }
1218
1219 if let Some(enable) = self.wasm.component_model_gc {
1220 #[cfg(all(feature = "component-model", feature = "gc"))]
1221 config.wasm_component_model_gc(enable);
1222 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1223 if enable && all.is_none() {
1224 bail!("support for `component-model-gc` was disabled at compile time")
1225 }
1226 }
1227
1228 Ok(())
1229 }
1230
1231 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1232 let path_ref = path.as_ref();
1233 let file_contents = fs::read_to_string(path_ref)
1234 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1235 toml::from_str::<CommonOptions>(&file_contents)
1236 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1237 }
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242 use wasmtime::{OptLevel, RegallocAlgorithm};
1243
1244 use super::*;
1245
1246 #[test]
1247 fn from_toml() {
1248 let empty_toml = "";
1250 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1251 common_options.config(None).unwrap();
1252
1253 let basic_toml = r#"
1255 [optimize]
1256 [codegen]
1257 [debug]
1258 [wasm]
1259 [wasi]
1260 [record]
1261 "#;
1262 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1263 common_options.config(None).unwrap();
1264
1265 for (opt_value, expected) in [
1267 ("0", Some(OptLevel::None)),
1268 ("1", Some(OptLevel::Speed)),
1269 ("2", Some(OptLevel::Speed)),
1270 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1271 ("\"hello\"", None), ("3", None), ] {
1274 let toml = format!(
1275 r#"
1276 [optimize]
1277 opt-level = {opt_value}
1278 "#,
1279 );
1280 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1281 .ok()
1282 .and_then(|common_options| common_options.opts.opt_level);
1283
1284 assert_eq!(
1285 parsed_opt_level, expected,
1286 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1287 );
1288 }
1289
1290 for (regalloc_value, expected) in [
1292 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1293 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1294 ("\"hello\"", None), ("3", None), ("true", None), ] {
1298 let toml = format!(
1299 r#"
1300 [optimize]
1301 regalloc-algorithm = {regalloc_value}
1302 "#,
1303 );
1304 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1305 .ok()
1306 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1307 assert_eq!(
1308 parsed_regalloc_algorithm, expected,
1309 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1310 );
1311 }
1312
1313 for (strategy_value, expected) in [
1315 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1316 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1317 ("\"hello\"", None), ("5", None), ("true", None), ] {
1321 let toml = format!(
1322 r#"
1323 [codegen]
1324 compiler = {strategy_value}
1325 "#,
1326 );
1327 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1328 .ok()
1329 .and_then(|common_options| common_options.codegen.compiler);
1330 assert_eq!(
1331 parsed_strategy, expected,
1332 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1333 );
1334 }
1335
1336 for (collector_value, expected) in [
1338 (
1339 "\"drc\"",
1340 Some(wasmtime::Collector::DeferredReferenceCounting),
1341 ),
1342 ("\"null\"", Some(wasmtime::Collector::Null)),
1343 ("\"copying\"", Some(wasmtime::Collector::Copying)),
1344 ("\"hello\"", None), ("5", None), ("true", None), ] {
1348 let toml = format!(
1349 r#"
1350 [codegen]
1351 collector = {collector_value}
1352 "#,
1353 );
1354 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1355 .ok()
1356 .and_then(|common_options| common_options.codegen.collector);
1357 assert_eq!(
1358 parsed_collector, expected,
1359 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1360 );
1361 }
1362 }
1363}
1364
1365impl Default for CommonOptions {
1366 fn default() -> CommonOptions {
1367 CommonOptions::new()
1368 }
1369}
1370
1371impl fmt::Display for CommonOptions {
1372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1373 let CommonOptions {
1374 codegen_raw,
1375 codegen,
1376 debug_raw,
1377 debug,
1378 opts_raw,
1379 opts,
1380 wasm_raw,
1381 wasm,
1382 wasi_raw,
1383 wasi,
1384 record_raw,
1385 record,
1386 configured,
1387 target,
1388 config,
1389 } = self;
1390 if let Some(target) = target {
1391 write!(f, "--target {target} ")?;
1392 }
1393 if let Some(config) = config {
1394 write!(f, "--config {} ", config.display())?;
1395 }
1396
1397 let codegen_flags;
1398 let opts_flags;
1399 let wasi_flags;
1400 let wasm_flags;
1401 let debug_flags;
1402 let record_flags;
1403
1404 if *configured {
1405 codegen_flags = codegen.to_options();
1406 debug_flags = debug.to_options();
1407 wasi_flags = wasi.to_options();
1408 wasm_flags = wasm.to_options();
1409 opts_flags = opts.to_options();
1410 record_flags = record.to_options();
1411 } else {
1412 codegen_flags = codegen_raw
1413 .iter()
1414 .flat_map(|t| t.0.iter())
1415 .cloned()
1416 .collect();
1417 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1418 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1419 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1420 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1421 record_flags = record_raw
1422 .iter()
1423 .flat_map(|t| t.0.iter())
1424 .cloned()
1425 .collect();
1426 }
1427
1428 for flag in codegen_flags {
1429 write!(f, "-C{flag} ")?;
1430 }
1431 for flag in opts_flags {
1432 write!(f, "-O{flag} ")?;
1433 }
1434 for flag in wasi_flags {
1435 write!(f, "-S{flag} ")?;
1436 }
1437 for flag in wasm_flags {
1438 write!(f, "-W{flag} ")?;
1439 }
1440 for flag in debug_flags {
1441 write!(f, "-D{flag} ")?;
1442 }
1443 for flag in record_flags {
1444 write!(f, "-R{flag} ")?;
1445 }
1446
1447 Ok(())
1448 }
1449}