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