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