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