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