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 #[serde(default)]
266 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
267 pub inlining: Option<wasmtime::Inlining>,
268
269 pub metadata_for_internal_asserts: Option<bool>,
272 pub metadata_for_gc_heap_corruption: Option<bool>,
275
276 #[prefixed = "cranelift"]
277 #[serde(default)]
278 pub cranelift: Vec<(String, Option<String>)>,
281 }
282
283 enum Codegen {
284 ...
285 }
286}
287
288wasmtime_option_group! {
289 #[derive(PartialEq, Clone, Deserialize)]
290 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
291 pub struct DebugOptions {
292 pub debug_info: Option<bool>,
294 pub guest_debug: Option<bool>,
296 pub address_map: Option<bool>,
298 pub logging: Option<bool>,
300 pub log_to_files: Option<bool>,
302 pub coredump: Option<String>,
304 pub debugger: Option<PathBuf>,
307 #[serde(default)]
310 pub arg: Vec<String>,
311 pub inherit_stdin: Option<bool>,
314 pub inherit_stdout: Option<bool>,
317 pub inherit_stderr: Option<bool>,
320 pub max_backtrace: Option<usize>,
322 pub symbols: Option<bool>,
324 }
325
326 enum Debug {
327 ...
328 }
329}
330
331wasmtime_option_group! {
332 #[derive(PartialEq, Clone, Deserialize)]
333 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
334 pub struct WasmOptions {
335 pub nan_canonicalization: Option<bool>,
337 pub fuel: Option<u64>,
345 pub epoch_interruption: Option<bool>,
348 pub max_wasm_stack: Option<usize>,
351 pub async_stack_size: Option<usize>,
357 pub async_stack_zeroing: Option<bool>,
360 pub unknown_exports_allow: Option<bool>,
362 pub unknown_imports_trap: Option<bool>,
365 pub unknown_imports_default: Option<bool>,
368 pub wmemcheck: Option<bool>,
370 pub max_memory_size: Option<usize>,
375 pub max_table_elements: Option<usize>,
377 pub max_instances: Option<usize>,
379 pub max_tables: Option<usize>,
381 pub max_memories: Option<usize>,
383 pub trap_on_grow_failure: Option<bool>,
390 pub timeout: Option<Duration>,
392 pub all_proposals: Option<bool>,
394 pub bulk_memory: Option<bool>,
396 pub multi_memory: Option<bool>,
398 pub multi_value: Option<bool>,
400 pub reference_types: Option<bool>,
402 pub simd: Option<bool>,
404 pub relaxed_simd: Option<bool>,
406 pub relaxed_simd_deterministic: Option<bool>,
415 pub tail_call: Option<bool>,
417 pub threads: Option<bool>,
419 pub shared_memory: Option<bool>,
421 pub shared_everything_threads: Option<bool>,
423 pub memory64: Option<bool>,
425 pub component_model: Option<bool>,
427 pub component_model_async: Option<bool>,
429 pub component_model_more_async_builtins: Option<bool>,
432 pub component_model_async_stackful: Option<bool>,
435 pub component_model_threading: Option<bool>,
438 pub component_model_error_context: Option<bool>,
441 pub component_model_gc: Option<bool>,
444 pub component_model_map: Option<bool>,
446 pub function_references: Option<bool>,
448 pub stack_switching: Option<bool>,
450 pub gc: Option<bool>,
452 pub custom_page_sizes: Option<bool>,
454 pub wide_arithmetic: Option<bool>,
456 pub branch_hinting: Option<bool>,
458 pub extended_const: Option<bool>,
460 pub exceptions: Option<bool>,
462 pub gc_support: Option<bool>,
464 pub component_model_fixed_length_lists: Option<bool>,
467 pub component_model_implements: Option<bool>,
470 pub concurrency_support: Option<bool>,
473 }
474
475 enum Wasm {
476 ...
477 }
478}
479
480wasmtime_option_group! {
481 #[derive(PartialEq, Clone, Deserialize)]
482 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
483 pub struct WasiOptions {
484 pub cli: Option<bool>,
486 pub cli_exit_with_code: Option<bool>,
488 pub common: Option<bool>,
490 pub nn: Option<bool>,
492 pub threads: Option<bool>,
494 pub http: Option<bool>,
496 pub http_outgoing_body_buffer_chunks: Option<usize>,
500 pub http_outgoing_body_chunk_size: Option<usize>,
503 pub config: Option<bool>,
505 pub keyvalue: Option<bool>,
507 pub listenfd: Option<bool>,
511 #[serde(default)]
514 pub tcplisten: Vec<String>,
515 pub tls: Option<bool>,
517 pub preview2: Option<bool>,
520 #[serde(skip)]
529 pub nn_graph: Vec<WasiNnGraph>,
530 pub inherit_network: Option<bool>,
533 pub allow_ip_name_lookup: Option<bool>,
535 pub tcp: Option<bool>,
537 pub udp: Option<bool>,
539 pub network_error_code: Option<bool>,
541 pub preview0: Option<bool>,
543 pub inherit_env: Option<bool>,
547 pub inherit_stdin: Option<bool>,
549 pub inherit_stdout: Option<bool>,
551 pub inherit_stderr: Option<bool>,
553 pub cwd: Option<String>,
555 #[serde(skip)]
557 pub config_var: Vec<KeyValuePair>,
558 #[serde(skip)]
560 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
561 pub p3: Option<bool>,
563 pub max_resources: Option<usize>,
565 pub hostcall_fuel: Option<usize>,
567 pub max_random_size: Option<u64>,
571 pub max_http_fields_size: Option<usize>,
575 }
576
577 enum Wasi {
578 ...
579 }
580}
581
582wasmtime_option_group! {
583 #[derive(PartialEq, Clone, Deserialize)]
584 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
585 pub struct RecordOptions {
586 pub path: Option<String>,
588 pub validation_metadata: Option<bool>,
591 pub event_window_size: Option<usize>,
594 }
595
596 enum Record {
597 ...
598 }
599}
600
601#[derive(Debug, Clone, PartialEq)]
602pub struct WasiNnGraph {
603 pub format: String,
604 pub dir: String,
605}
606
607#[derive(Debug, Clone, PartialEq)]
608pub struct KeyValuePair {
609 pub key: String,
610 pub value: String,
611}
612
613#[derive(Parser, Clone, Deserialize)]
615#[serde(deny_unknown_fields)]
616pub struct CommonOptions {
617 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
627 #[serde(skip)]
628 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
629
630 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
632 #[serde(skip)]
633 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
634
635 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
637 #[serde(skip)]
638 debug_raw: Vec<opt::CommaSeparated<Debug>>,
639
640 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
643 #[serde(skip)]
644 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
645
646 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
648 #[serde(skip)]
649 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
650
651 #[arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")]
660 #[serde(skip)]
661 record_raw: Vec<opt::CommaSeparated<Record>>,
662
663 #[arg(skip)]
666 #[serde(skip)]
667 configured: bool,
668
669 #[arg(skip)]
670 #[serde(rename = "optimize", default)]
671 pub opts: OptimizeOptions,
672
673 #[arg(skip)]
674 #[serde(rename = "codegen", default)]
675 pub codegen: CodegenOptions,
676
677 #[arg(skip)]
678 #[serde(rename = "debug", default)]
679 pub debug: DebugOptions,
680
681 #[arg(skip)]
682 #[serde(rename = "wasm", default)]
683 pub wasm: WasmOptions,
684
685 #[arg(skip)]
686 #[serde(rename = "wasi", default)]
687 pub wasi: WasiOptions,
688
689 #[arg(skip)]
690 #[serde(rename = "record", default)]
691 pub record: RecordOptions,
692
693 #[arg(long, value_name = "TARGET")]
695 #[serde(skip)]
696 pub target: Option<String>,
697
698 #[arg(long = "config", value_name = "FILE")]
705 #[serde(skip)]
706 pub config: Option<PathBuf>,
707}
708
709macro_rules! match_feature {
710 (
711 [$feat:tt : $config:expr]
712 $val:ident => $e:expr,
713 $p:pat => err,
714 ) => {
715 #[cfg(feature = $feat)]
716 {
717 if let Some($val) = $config {
718 $e;
719 }
720 }
721 #[cfg(not(feature = $feat))]
722 {
723 if let Some($p) = $config {
724 bail!(concat!("support for ", $feat, " disabled at compile time"));
725 }
726 }
727 };
728}
729
730impl CommonOptions {
731 pub fn new() -> CommonOptions {
733 CommonOptions {
734 opts_raw: Vec::new(),
735 codegen_raw: Vec::new(),
736 debug_raw: Vec::new(),
737 wasm_raw: Vec::new(),
738 wasi_raw: Vec::new(),
739 record_raw: Vec::new(),
740 configured: true,
741 opts: Default::default(),
742 codegen: Default::default(),
743 debug: Default::default(),
744 wasm: Default::default(),
745 wasi: Default::default(),
746 record: Default::default(),
747 target: None,
748 config: None,
749 }
750 }
751
752 fn configure(&mut self) -> Result<()> {
753 if self.configured {
754 return Ok(());
755 }
756 self.configured = true;
757 if let Some(toml_config_path) = &self.config {
758 let toml_options = CommonOptions::from_file(toml_config_path)?;
759 self.opts = toml_options.opts;
760 self.codegen = toml_options.codegen;
761 self.debug = toml_options.debug;
762 self.wasm = toml_options.wasm;
763 self.wasi = toml_options.wasi;
764 self.record = toml_options.record;
765 }
766 self.opts.configure_with(&self.opts_raw);
767 self.codegen.configure_with(&self.codegen_raw);
768 self.debug.configure_with(&self.debug_raw);
769 self.wasm.configure_with(&self.wasm_raw);
770 self.wasi.configure_with(&self.wasi_raw);
771 self.record.configure_with(&self.record_raw);
772 Ok(())
773 }
774
775 pub fn init_logging(&mut self) -> Result<()> {
776 self.configure()?;
777 if self.debug.logging == Some(false) {
778 return Ok(());
779 }
780 #[cfg(feature = "logging")]
781 if self.debug.log_to_files == Some(true) {
782 let prefix = "wasmtime.dbg.";
783 init_file_per_thread_logger(prefix);
784 } else {
785 use std::io::IsTerminal;
786 use tracing_subscriber::{EnvFilter, FmtSubscriber};
787 let builder = FmtSubscriber::builder()
788 .with_writer(std::io::stderr)
789 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
790 .with_ansi(std::io::stderr().is_terminal());
791 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
792 builder
793 .with_level(false)
794 .with_target(false)
795 .without_time()
796 .init()
797 } else {
798 builder.init();
799 }
800 }
801 #[cfg(not(feature = "logging"))]
802 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
803 bail!("support for logging disabled at compile time");
804 }
805 Ok(())
806 }
807
808 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
809 self.configure()?;
810 let mut config = Config::new();
811
812 match_feature! {
813 ["cranelift" : self.codegen.compiler]
814 strategy => config.strategy(strategy),
815 _ => err,
816 }
817 match_feature! {
818 ["gc" : self.codegen.collector]
819 collector => config.collector(collector),
820 _ => err,
821 }
822 if let Some(target) = &self.target {
823 config.target(target)?;
824 }
825 match_feature! {
826 ["cranelift" : self.codegen.cranelift_debug_verifier]
827 enable => config.cranelift_debug_verifier(enable),
828 true => err,
829 }
830 if let Some(enable) = self.debug.debug_info {
831 config.debug_info(enable);
832 }
833 match_feature! {
834 ["debug" : self.debug.guest_debug]
835 enable => config.guest_debug(enable),
836 _ => err,
837 }
838 if self.debug.coredump.is_some() {
839 #[cfg(feature = "coredump")]
840 config.coredump_on_trap(true);
841 #[cfg(not(feature = "coredump"))]
842 bail!("support for coredumps disabled at compile time");
843 }
844 match_feature! {
845 ["cranelift" : self.opts.opt_level]
846 level => config.cranelift_opt_level(level),
847 _ => err,
848 }
849 match_feature! {
850 ["cranelift": self.opts.regalloc_algorithm]
851 algo => config.cranelift_regalloc_algorithm(algo),
852 _ => err,
853 }
854 match_feature! {
855 ["cranelift" : self.wasm.nan_canonicalization]
856 enable => config.cranelift_nan_canonicalization(enable),
857 true => err,
858 }
859
860 self.enable_wasm_features(&mut config)?;
861
862 #[cfg(feature = "cranelift")]
863 for (name, value) in self.codegen.cranelift.iter() {
864 let name = name.replace('-', "_");
865 unsafe {
866 match value {
867 Some(val) => {
868 config.cranelift_flag_set(&name, val);
869 }
870 None => {
871 config.cranelift_flag_enable(&name);
872 }
873 }
874 }
875 }
876 #[cfg(not(feature = "cranelift"))]
877 if !self.codegen.cranelift.is_empty() {
878 bail!("support for cranelift disabled at compile time");
879 }
880
881 #[cfg(feature = "cache")]
882 if self.codegen.cache != Some(false) {
883 use wasmtime::Cache;
884 let cache = match &self.codegen.cache_config {
885 Some(path) => Cache::from_file(Some(Path::new(path)))?,
886 None => Cache::from_file(None)?,
887 };
888 config.cache(Some(cache));
889 }
890 #[cfg(not(feature = "cache"))]
891 if self.codegen.cache == Some(true) {
892 bail!("support for caching disabled at compile time");
893 }
894
895 match_feature! {
896 ["parallel-compilation" : self.codegen.parallel_compilation]
897 enable => config.parallel_compilation(enable),
898 true => err,
899 }
900
901 let memory_reservation = self
902 .opts
903 .memory_reservation
904 .or(self.opts.static_memory_maximum_size);
905 if let Some(size) = memory_reservation {
906 config.memory_reservation(size);
907 }
908
909 if let Some(enable) = self.opts.static_memory_forced {
910 config.memory_may_move(!enable);
911 }
912 if let Some(enable) = self.opts.memory_may_move {
913 config.memory_may_move(enable);
914 }
915
916 let memory_guard_size = self
917 .opts
918 .static_memory_guard_size
919 .or(self.opts.dynamic_memory_guard_size)
920 .or(self.opts.memory_guard_size);
921 if let Some(size) = memory_guard_size {
922 config.memory_guard_size(size);
923 }
924
925 let mem_for_growth = self
926 .opts
927 .memory_reservation_for_growth
928 .or(self.opts.dynamic_memory_reserved_for_growth);
929 if let Some(size) = mem_for_growth {
930 config.memory_reservation_for_growth(size);
931 }
932 if let Some(enable) = self.opts.guard_before_linear_memory {
933 config.guard_before_linear_memory(enable);
934 }
935
936 if let Some(size) = self.opts.gc_heap_reservation {
937 config.gc_heap_reservation(size);
938 }
939 if let Some(enable) = self.opts.gc_heap_may_move {
940 config.gc_heap_may_move(enable);
941 }
942 if let Some(size) = self.opts.gc_heap_guard_size {
943 config.gc_heap_guard_size(size);
944 }
945 if let Some(size) = self.opts.gc_heap_reservation_for_growth {
946 config.gc_heap_reservation_for_growth(size);
947 }
948 if let Some(enable) = self.opts.table_lazy_init {
949 config.table_lazy_init(enable);
950 }
951
952 if let Some(n) = self.opts.gc_zeal_alloc_counter
953 && (cfg!(gc_zeal) || cfg!(fuzzing))
954 {
955 config.gc_zeal_alloc_counter(Some(n))?;
956 }
957
958 if self.wasm.fuel.is_some() {
960 config.consume_fuel(true);
961 }
962
963 if let Some(enable) = self.wasm.epoch_interruption {
964 config.epoch_interruption(enable);
965 }
966 if let Some(enable) = self.debug.address_map {
967 config.generate_address_map(enable);
968 }
969 if let Some(frames) = self.debug.max_backtrace {
970 match NonZeroUsize::new(frames) {
971 None => {
972 config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
973 }
974 Some(amt) => {
975 config.wasm_backtrace_max_frames(Some(amt));
976 }
977 }
978 }
979 if let Some(enable) = self.debug.symbols {
980 config.debug_symbols(enable);
981 }
982 if let Some(enable) = self.opts.memory_init_cow {
983 config.memory_init_cow(enable);
984 }
985 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
986 config.memory_guaranteed_dense_image_size(size);
987 }
988 if let Some(enable) = self.opts.signals_based_traps {
989 config.signals_based_traps(enable);
990 }
991 if let Some(enable) = self.codegen.native_unwind_info {
992 config.native_unwind_info(enable);
993 }
994 if let Some(enable) = self.codegen.inlining {
995 config.compiler_inlining(enable);
996 }
997 if let Some(enable) = self.codegen.metadata_for_internal_asserts {
998 config.metadata_for_internal_asserts(enable);
999 }
1000 if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1001 config.metadata_for_gc_heap_corruption(enable);
1002 }
1003
1004 #[cfg(any(feature = "async", feature = "stack-switching"))]
1007 {
1008 if let Some(size) = self.wasm.async_stack_size {
1009 config.async_stack_size(size);
1010 }
1011 }
1012 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1013 {
1014 if let Some(_size) = self.wasm.async_stack_size {
1015 bail!(concat!(
1016 "support for async/stack-switching disabled at compile time"
1017 ));
1018 }
1019 }
1020
1021 match_feature! {
1022 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1023 enable => {
1024 if enable {
1025 let mut cfg = wasmtime::PoolingAllocationConfig::default();
1026 if let Some(size) = self.opts.pooling_memory_keep_resident {
1027 cfg.linear_memory_keep_resident(size);
1028 }
1029 if let Some(size) = self.opts.pooling_table_keep_resident {
1030 cfg.table_keep_resident(size);
1031 }
1032 if let Some(limit) = self.opts.pooling_total_core_instances {
1033 cfg.total_core_instances(limit);
1034 }
1035 if let Some(limit) = self.opts.pooling_total_component_instances {
1036 cfg.total_component_instances(limit);
1037 }
1038 if let Some(limit) = self.opts.pooling_total_memories {
1039 cfg.total_memories(limit);
1040 }
1041 if let Some(limit) = self.opts.pooling_total_tables {
1042 cfg.total_tables(limit);
1043 }
1044 if let Some(limit) = self.opts.pooling_table_elements
1045 .or(self.wasm.max_table_elements)
1046 {
1047 cfg.table_elements(limit);
1048 }
1049 if let Some(limit) = self.opts.pooling_max_core_instance_size {
1050 cfg.max_core_instance_size(limit);
1051 }
1052 match_feature! {
1053 ["async" : self.opts.pooling_total_stacks]
1054 limit => cfg.total_stacks(limit),
1055 _ => err,
1056 }
1057 if let Some(max) = self.opts.pooling_max_memory_size
1058 .or(self.wasm.max_memory_size)
1059 {
1060 cfg.max_memory_size(max);
1061 }
1062 if let Some(size) = self.opts.pooling_decommit_batch_size {
1063 cfg.decommit_batch_size(size);
1064 }
1065 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1066 cfg.max_unused_warm_slots(max);
1067 }
1068 match_feature! {
1069 ["async" : self.opts.pooling_async_stack_keep_resident]
1070 size => cfg.async_stack_keep_resident(size),
1071 _ => err,
1072 }
1073 if let Some(max) = self.opts.pooling_max_component_instance_size {
1074 cfg.max_component_instance_size(max);
1075 }
1076 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1077 cfg.max_core_instances_per_component(max);
1078 }
1079 if let Some(max) = self.opts.pooling_max_memories_per_component {
1080 cfg.max_memories_per_component(max);
1081 }
1082 if let Some(max) = self.opts.pooling_max_tables_per_component {
1083 cfg.max_tables_per_component(max);
1084 }
1085 if let Some(max) = self.opts.pooling_max_tables_per_module {
1086 cfg.max_tables_per_module(max);
1087 }
1088 if let Some(max) = self.opts.pooling_max_memories_per_module {
1089 cfg.max_memories_per_module(max);
1090 }
1091 match_feature! {
1092 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1093 enable => cfg.memory_protection_keys(enable),
1094 _ => err,
1095 }
1096 match_feature! {
1097 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1098 max => cfg.max_memory_protection_keys(max),
1099 _ => err,
1100 }
1101 match_feature! {
1102 ["gc" : self.opts.pooling_total_gc_heaps]
1103 max => cfg.total_gc_heaps(max),
1104 _ => err,
1105 }
1106 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1107 cfg.pagemap_scan(enabled);
1108 }
1109 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1110 }
1111 },
1112 true => err,
1113 }
1114
1115 if self.opts.pooling_memory_protection_keys.is_some()
1116 && !self.opts.pooling_allocator.unwrap_or(false)
1117 {
1118 bail!("memory protection keys require the pooling allocator");
1119 }
1120
1121 if self.opts.pooling_max_memory_protection_keys.is_some()
1122 && !self.opts.pooling_memory_protection_keys.is_some()
1123 {
1124 bail!("max memory protection keys requires memory protection keys to be enabled");
1125 }
1126
1127 match_feature! {
1128 ["async" : self.wasm.async_stack_zeroing]
1129 enable => config.async_stack_zeroing(enable),
1130 _ => err,
1131 }
1132
1133 if let Some(max) = self.wasm.max_wasm_stack {
1134 config.max_wasm_stack(max);
1135
1136 #[cfg(any(feature = "async", feature = "stack-switching"))]
1140 if self.wasm.async_stack_size.is_none() {
1141 const DEFAULT_HOST_STACK: usize = 512 << 10;
1142 config.async_stack_size(max + DEFAULT_HOST_STACK);
1143 }
1144 }
1145
1146 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1147 config.relaxed_simd_deterministic(enable);
1148 }
1149 match_feature! {
1150 ["cranelift" : self.wasm.wmemcheck]
1151 enable => config.wmemcheck(enable),
1152 true => err,
1153 }
1154
1155 if let Some(enable) = self.wasm.gc_support {
1156 config.gc_support(enable);
1157 }
1158
1159 if let Some(enable) = self.wasm.concurrency_support {
1160 config.concurrency_support(enable);
1161 }
1162
1163 if let Some(enable) = self.wasm.shared_memory {
1164 config.shared_memory(enable);
1165 }
1166
1167 let record = &self.record;
1168 match_feature! {
1169 ["rr" : &record.path]
1170 _path => {
1171 bail!("recording configuration for `rr` feature is not supported yet");
1172 },
1173 _ => err,
1174 }
1175
1176 Ok(config)
1177 }
1178
1179 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1180 let all = self.wasm.all_proposals;
1181
1182 if let Some(enable) = self.wasm.simd.or(all) {
1183 config.wasm_simd(enable);
1184 }
1185 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1186 config.wasm_relaxed_simd(enable);
1187 }
1188 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1189 config.wasm_bulk_memory(enable);
1190 }
1191 if let Some(enable) = self.wasm.multi_value.or(all) {
1192 config.wasm_multi_value(enable);
1193 }
1194 if let Some(enable) = self.wasm.tail_call.or(all) {
1195 config.wasm_tail_call(enable);
1196 }
1197 if let Some(enable) = self.wasm.multi_memory.or(all) {
1198 config.wasm_multi_memory(enable);
1199 }
1200 if let Some(enable) = self.wasm.memory64.or(all) {
1201 config.wasm_memory64(enable);
1202 }
1203 if let Some(enable) = self.wasm.stack_switching {
1204 config.wasm_stack_switching(enable);
1205 }
1206 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1207 config.wasm_custom_page_sizes(enable);
1208 }
1209 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1210 config.wasm_wide_arithmetic(enable);
1211 }
1212 if let Some(enable) = self.wasm.branch_hinting {
1214 config.wasm_branch_hinting(enable);
1215 }
1216 if let Some(enable) = self.wasm.extended_const.or(all) {
1217 config.wasm_extended_const(enable);
1218 }
1219
1220 macro_rules! handle_conditionally_compiled {
1221 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1222 if let Some(enable) = self.wasm.$field.or(all) {
1223 #[cfg(feature = $feature)]
1224 config.$method(enable);
1225 #[cfg(not(feature = $feature))]
1226 if enable && all.is_none() {
1227 bail!("support for {} was disabled at compile-time", $feature);
1228 }
1229 }
1230 )*)
1231 }
1232
1233 handle_conditionally_compiled! {
1234 ("component-model", component_model, wasm_component_model)
1235 ("component-model-async", component_model_async, wasm_component_model_async)
1236 ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1237 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1238 ("component-model-async", component_model_threading, wasm_component_model_threading)
1239 ("component-model", component_model_error_context, wasm_component_model_error_context)
1240 ("component-model", component_model_map, wasm_component_model_map)
1241 ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1242 ("component-model", component_model_implements, wasm_component_model_implements)
1243 ("threads", threads, wasm_threads)
1244 ("gc", gc, wasm_gc)
1245 ("gc", reference_types, wasm_reference_types)
1246 ("gc", function_references, wasm_function_references)
1247 ("gc", exceptions, wasm_exceptions)
1248 ("stack-switching", stack_switching, wasm_stack_switching)
1249 }
1250
1251 if let Some(enable) = self.wasm.component_model_gc {
1252 #[cfg(all(feature = "component-model", feature = "gc"))]
1253 config.wasm_component_model_gc(enable);
1254 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1255 if enable && all.is_none() {
1256 bail!("support for `component-model-gc` was disabled at compile time")
1257 }
1258 }
1259
1260 Ok(())
1261 }
1262
1263 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1264 let path_ref = path.as_ref();
1265 let file_contents = fs::read_to_string(path_ref)
1266 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1267 toml::from_str::<CommonOptions>(&file_contents)
1268 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1269 }
1270}
1271
1272#[cfg(test)]
1273mod tests {
1274 use wasmtime::{OptLevel, RegallocAlgorithm};
1275
1276 use super::*;
1277
1278 #[test]
1279 fn from_toml() {
1280 let empty_toml = "";
1282 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1283 common_options.config(None).unwrap();
1284
1285 let basic_toml = r#"
1287 [optimize]
1288 [codegen]
1289 [debug]
1290 [wasm]
1291 [wasi]
1292 [record]
1293 "#;
1294 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1295 common_options.config(None).unwrap();
1296
1297 for (opt_value, expected) in [
1299 ("0", Some(OptLevel::None)),
1300 ("1", Some(OptLevel::Speed)),
1301 ("2", Some(OptLevel::Speed)),
1302 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1303 ("\"hello\"", None), ("3", None), ] {
1306 let toml = format!(
1307 r#"
1308 [optimize]
1309 opt-level = {opt_value}
1310 "#,
1311 );
1312 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1313 .ok()
1314 .and_then(|common_options| common_options.opts.opt_level);
1315
1316 assert_eq!(
1317 parsed_opt_level, expected,
1318 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1319 );
1320 }
1321
1322 for (regalloc_value, expected) in [
1324 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1325 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1326 ("\"hello\"", None), ("3", None), ("true", None), ] {
1330 let toml = format!(
1331 r#"
1332 [optimize]
1333 regalloc-algorithm = {regalloc_value}
1334 "#,
1335 );
1336 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1337 .ok()
1338 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1339 assert_eq!(
1340 parsed_regalloc_algorithm, expected,
1341 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1342 );
1343 }
1344
1345 for (strategy_value, expected) in [
1347 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1348 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1349 ("\"hello\"", None), ("5", None), ("true", None), ] {
1353 let toml = format!(
1354 r#"
1355 [codegen]
1356 compiler = {strategy_value}
1357 "#,
1358 );
1359 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1360 .ok()
1361 .and_then(|common_options| common_options.codegen.compiler);
1362 assert_eq!(
1363 parsed_strategy, expected,
1364 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1365 );
1366 }
1367
1368 for (collector_value, expected) in [
1370 (
1371 "\"drc\"",
1372 Some(wasmtime::Collector::DeferredReferenceCounting),
1373 ),
1374 ("\"null\"", Some(wasmtime::Collector::Null)),
1375 ("\"copying\"", Some(wasmtime::Collector::Copying)),
1376 ("\"hello\"", None), ("5", None), ("true", None), ] {
1380 let toml = format!(
1381 r#"
1382 [codegen]
1383 collector = {collector_value}
1384 "#,
1385 );
1386 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1387 .ok()
1388 .and_then(|common_options| common_options.codegen.collector);
1389 assert_eq!(
1390 parsed_collector, expected,
1391 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1392 );
1393 }
1394 }
1395}
1396
1397impl Default for CommonOptions {
1398 fn default() -> CommonOptions {
1399 CommonOptions::new()
1400 }
1401}
1402
1403impl fmt::Display for CommonOptions {
1404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1405 let CommonOptions {
1406 codegen_raw,
1407 codegen,
1408 debug_raw,
1409 debug,
1410 opts_raw,
1411 opts,
1412 wasm_raw,
1413 wasm,
1414 wasi_raw,
1415 wasi,
1416 record_raw,
1417 record,
1418 configured,
1419 target,
1420 config,
1421 } = self;
1422 if let Some(target) = target {
1423 write!(f, "--target {target} ")?;
1424 }
1425 if let Some(config) = config {
1426 write!(f, "--config {} ", config.display())?;
1427 }
1428
1429 let codegen_flags;
1430 let opts_flags;
1431 let wasi_flags;
1432 let wasm_flags;
1433 let debug_flags;
1434 let record_flags;
1435
1436 if *configured {
1437 codegen_flags = codegen.to_options();
1438 debug_flags = debug.to_options();
1439 wasi_flags = wasi.to_options();
1440 wasm_flags = wasm.to_options();
1441 opts_flags = opts.to_options();
1442 record_flags = record.to_options();
1443 } else {
1444 codegen_flags = codegen_raw
1445 .iter()
1446 .flat_map(|t| t.0.iter())
1447 .cloned()
1448 .collect();
1449 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1450 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1451 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1452 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1453 record_flags = record_raw
1454 .iter()
1455 .flat_map(|t| t.0.iter())
1456 .cloned()
1457 .collect();
1458 }
1459
1460 for flag in codegen_flags {
1461 write!(f, "-C{flag} ")?;
1462 }
1463 for flag in opts_flags {
1464 write!(f, "-O{flag} ")?;
1465 }
1466 for flag in wasi_flags {
1467 write!(f, "-S{flag} ")?;
1468 }
1469 for flag in wasm_flags {
1470 write!(f, "-W{flag} ")?;
1471 }
1472 for flag in debug_flags {
1473 write!(f, "-D{flag} ")?;
1474 }
1475 for flag in record_flags {
1476 write!(f, "-R{flag} ")?;
1477 }
1478
1479 Ok(())
1480 }
1481}