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