1use clap::Parser;
4use serde::Deserialize;
5use std::{
6 fmt, fs,
7 path::{Path, PathBuf},
8 time::Duration,
9};
10use wasmtime::{Config, Result, bail, error::Context as _};
11
12pub mod opt;
13
14#[cfg(feature = "logging")]
15fn init_file_per_thread_logger(prefix: &'static str) {
16 file_per_thread_logger::initialize(prefix);
17 file_per_thread_logger::allow_uninitialized();
18
19 #[cfg(feature = "parallel-compilation")]
24 rayon::ThreadPoolBuilder::new()
25 .spawn_handler(move |thread| {
26 let mut b = std::thread::Builder::new();
27 if let Some(name) = thread.name() {
28 b = b.name(name.to_owned());
29 }
30 if let Some(stack_size) = thread.stack_size() {
31 b = b.stack_size(stack_size);
32 }
33 b.spawn(move || {
34 file_per_thread_logger::initialize(prefix);
35 thread.run()
36 })?;
37 Ok(())
38 })
39 .build_global()
40 .unwrap();
41}
42
43wasmtime_option_group! {
44 #[derive(PartialEq, Clone, Deserialize)]
45 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
46 pub struct OptimizeOptions {
47 #[serde(default)]
49 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
50 pub opt_level: Option<wasmtime::OptLevel>,
51
52 #[serde(default)]
54 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
55 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
56
57 pub memory_may_move: Option<bool>,
60
61 pub memory_reservation: Option<u64>,
63
64 pub memory_reservation_for_growth: Option<u64>,
66
67 pub memory_guard_size: Option<u64>,
69
70 pub guard_before_linear_memory: Option<bool>,
73
74 pub table_lazy_init: Option<bool>,
79
80 pub pooling_allocator: Option<bool>,
82
83 pub pooling_decommit_batch_size: Option<usize>,
86
87 pub pooling_memory_keep_resident: Option<usize>,
90
91 pub pooling_table_keep_resident: Option<usize>,
94
95 #[serde(default)]
98 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
99 pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
100
101 pub pooling_max_memory_protection_keys: Option<usize>,
104
105 pub memory_init_cow: Option<bool>,
108
109 pub memory_guaranteed_dense_image_size: Option<u64>,
112
113 pub pooling_total_core_instances: Option<u32>,
116
117 pub pooling_total_component_instances: Option<u32>,
120
121 pub pooling_total_memories: Option<u32>,
124
125 pub pooling_total_tables: Option<u32>,
128
129 pub pooling_total_stacks: Option<u32>,
132
133 pub pooling_max_memory_size: Option<usize>,
136
137 pub pooling_table_elements: Option<usize>,
140
141 pub pooling_max_core_instance_size: Option<usize>,
144
145 pub pooling_max_unused_warm_slots: Option<u32>,
148
149 pub pooling_async_stack_keep_resident: Option<usize>,
152
153 pub pooling_max_component_instance_size: Option<usize>,
156
157 pub pooling_max_core_instances_per_component: Option<u32>,
160
161 pub pooling_max_memories_per_component: Option<u32>,
164
165 pub pooling_max_tables_per_component: Option<u32>,
168
169 pub pooling_max_tables_per_module: Option<u32>,
171
172 pub pooling_max_memories_per_module: Option<u32>,
174
175 pub pooling_total_gc_heaps: Option<u32>,
177
178 pub signals_based_traps: Option<bool>,
180
181 pub dynamic_memory_guard_size: Option<u64>,
183
184 pub static_memory_guard_size: Option<u64>,
186
187 pub static_memory_forced: Option<bool>,
189
190 pub static_memory_maximum_size: Option<u64>,
192
193 pub dynamic_memory_reserved_for_growth: Option<u64>,
195
196 #[serde(default)]
199 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
200 pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
201 }
202
203 enum Optimize {
204 ...
205 }
206}
207
208wasmtime_option_group! {
209 #[derive(PartialEq, Clone, Deserialize)]
210 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
211 pub struct CodegenOptions {
212 #[serde(default)]
217 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
218 pub compiler: Option<wasmtime::Strategy>,
219 #[serde(default)]
229 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
230 pub collector: Option<wasmtime::Collector>,
231 pub cranelift_debug_verifier: Option<bool>,
233 pub cache: Option<bool>,
235 pub cache_config: Option<String>,
237 pub parallel_compilation: Option<bool>,
239 pub native_unwind_info: Option<bool>,
242
243 pub inlining: Option<bool>,
245
246 #[prefixed = "cranelift"]
247 #[serde(default)]
248 pub cranelift: Vec<(String, Option<String>)>,
251 }
252
253 enum Codegen {
254 ...
255 }
256}
257
258wasmtime_option_group! {
259 #[derive(PartialEq, Clone, Deserialize)]
260 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
261 pub struct DebugOptions {
262 pub debug_info: Option<bool>,
264 pub guest_debug: Option<bool>,
266 pub address_map: Option<bool>,
268 pub logging: Option<bool>,
270 pub log_to_files: Option<bool>,
272 pub coredump: Option<String>,
274 pub debugger: Option<PathBuf>,
277 #[serde(default)]
280 pub arg: Vec<String>,
281 pub inherit_stdin: Option<bool>,
284 pub inherit_stdout: Option<bool>,
287 pub inherit_stderr: Option<bool>,
290 }
291
292 enum Debug {
293 ...
294 }
295}
296
297wasmtime_option_group! {
298 #[derive(PartialEq, Clone, Deserialize)]
299 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
300 pub struct WasmOptions {
301 pub nan_canonicalization: Option<bool>,
303 pub fuel: Option<u64>,
311 pub epoch_interruption: Option<bool>,
314 pub max_wasm_stack: Option<usize>,
317 pub async_stack_size: Option<usize>,
323 pub async_stack_zeroing: Option<bool>,
326 pub unknown_exports_allow: Option<bool>,
328 pub unknown_imports_trap: Option<bool>,
331 pub unknown_imports_default: Option<bool>,
334 pub wmemcheck: Option<bool>,
336 pub max_memory_size: Option<usize>,
341 pub max_table_elements: Option<usize>,
343 pub max_instances: Option<usize>,
345 pub max_tables: Option<usize>,
347 pub max_memories: Option<usize>,
349 pub trap_on_grow_failure: Option<bool>,
356 pub timeout: Option<Duration>,
358 pub all_proposals: Option<bool>,
360 pub bulk_memory: Option<bool>,
362 pub multi_memory: Option<bool>,
364 pub multi_value: Option<bool>,
366 pub reference_types: Option<bool>,
368 pub simd: Option<bool>,
370 pub relaxed_simd: Option<bool>,
372 pub relaxed_simd_deterministic: Option<bool>,
381 pub tail_call: Option<bool>,
383 pub threads: Option<bool>,
385 pub shared_memory: Option<bool>,
387 pub shared_everything_threads: Option<bool>,
389 pub memory64: Option<bool>,
391 pub component_model: Option<bool>,
393 pub component_model_async: Option<bool>,
395 pub component_model_async_builtins: Option<bool>,
398 pub component_model_async_stackful: Option<bool>,
401 pub component_model_threading: Option<bool>,
404 pub component_model_error_context: Option<bool>,
407 pub component_model_gc: Option<bool>,
410 pub component_model_map: Option<bool>,
412 pub function_references: Option<bool>,
414 pub stack_switching: Option<bool>,
416 pub gc: Option<bool>,
418 pub custom_page_sizes: Option<bool>,
420 pub wide_arithmetic: Option<bool>,
422 pub extended_const: Option<bool>,
424 pub exceptions: Option<bool>,
426 pub gc_support: Option<bool>,
428 pub component_model_fixed_length_lists: Option<bool>,
431 pub concurrency_support: Option<bool>,
434 }
435
436 enum Wasm {
437 ...
438 }
439}
440
441wasmtime_option_group! {
442 #[derive(PartialEq, Clone, Deserialize)]
443 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
444 pub struct WasiOptions {
445 pub cli: Option<bool>,
447 pub cli_exit_with_code: Option<bool>,
449 pub common: Option<bool>,
451 pub nn: Option<bool>,
453 pub threads: Option<bool>,
455 pub http: Option<bool>,
457 pub http_outgoing_body_buffer_chunks: Option<usize>,
461 pub http_outgoing_body_chunk_size: Option<usize>,
464 pub config: Option<bool>,
466 pub keyvalue: Option<bool>,
468 pub listenfd: Option<bool>,
472 #[serde(default)]
475 pub tcplisten: Vec<String>,
476 pub tls: Option<bool>,
478 pub preview2: Option<bool>,
481 #[serde(skip)]
490 pub nn_graph: Vec<WasiNnGraph>,
491 pub inherit_network: Option<bool>,
494 pub allow_ip_name_lookup: Option<bool>,
496 pub tcp: Option<bool>,
498 pub udp: Option<bool>,
500 pub network_error_code: Option<bool>,
502 pub preview0: Option<bool>,
504 pub inherit_env: Option<bool>,
508 pub inherit_stdin: Option<bool>,
510 pub inherit_stdout: Option<bool>,
512 pub inherit_stderr: Option<bool>,
514 #[serde(skip)]
516 pub config_var: Vec<KeyValuePair>,
517 #[serde(skip)]
519 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
520 pub p3: Option<bool>,
522 pub max_resources: Option<usize>,
524 pub hostcall_fuel: Option<usize>,
526 pub max_random_size: Option<u64>,
530 pub max_http_fields_size: Option<usize>,
534 }
535
536 enum Wasi {
537 ...
538 }
539}
540
541wasmtime_option_group! {
542 #[derive(PartialEq, Clone, Deserialize)]
543 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
544 pub struct RecordOptions {
545 pub path: Option<String>,
547 pub validation_metadata: Option<bool>,
550 pub event_window_size: Option<usize>,
553 }
554
555 enum Record {
556 ...
557 }
558}
559
560#[derive(Debug, Clone, PartialEq)]
561pub struct WasiNnGraph {
562 pub format: String,
563 pub dir: String,
564}
565
566#[derive(Debug, Clone, PartialEq)]
567pub struct KeyValuePair {
568 pub key: String,
569 pub value: String,
570}
571
572#[derive(Parser, Clone, Deserialize)]
574#[serde(deny_unknown_fields)]
575pub struct CommonOptions {
576 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
586 #[serde(skip)]
587 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
588
589 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
591 #[serde(skip)]
592 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
593
594 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
596 #[serde(skip)]
597 debug_raw: Vec<opt::CommaSeparated<Debug>>,
598
599 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
602 #[serde(skip)]
603 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
604
605 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
607 #[serde(skip)]
608 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
609
610 #[arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")]
619 #[serde(skip)]
620 record_raw: Vec<opt::CommaSeparated<Record>>,
621
622 #[arg(skip)]
625 #[serde(skip)]
626 configured: bool,
627
628 #[arg(skip)]
629 #[serde(rename = "optimize", default)]
630 pub opts: OptimizeOptions,
631
632 #[arg(skip)]
633 #[serde(rename = "codegen", default)]
634 pub codegen: CodegenOptions,
635
636 #[arg(skip)]
637 #[serde(rename = "debug", default)]
638 pub debug: DebugOptions,
639
640 #[arg(skip)]
641 #[serde(rename = "wasm", default)]
642 pub wasm: WasmOptions,
643
644 #[arg(skip)]
645 #[serde(rename = "wasi", default)]
646 pub wasi: WasiOptions,
647
648 #[arg(skip)]
649 #[serde(rename = "record", default)]
650 pub record: RecordOptions,
651
652 #[arg(long, value_name = "TARGET")]
654 #[serde(skip)]
655 pub target: Option<String>,
656
657 #[arg(long = "config", value_name = "FILE")]
664 #[serde(skip)]
665 pub config: Option<PathBuf>,
666}
667
668macro_rules! match_feature {
669 (
670 [$feat:tt : $config:expr]
671 $val:ident => $e:expr,
672 $p:pat => err,
673 ) => {
674 #[cfg(feature = $feat)]
675 {
676 if let Some($val) = $config {
677 $e;
678 }
679 }
680 #[cfg(not(feature = $feat))]
681 {
682 if let Some($p) = $config {
683 bail!(concat!("support for ", $feat, " disabled at compile time"));
684 }
685 }
686 };
687}
688
689impl CommonOptions {
690 pub fn new() -> CommonOptions {
692 CommonOptions {
693 opts_raw: Vec::new(),
694 codegen_raw: Vec::new(),
695 debug_raw: Vec::new(),
696 wasm_raw: Vec::new(),
697 wasi_raw: Vec::new(),
698 record_raw: Vec::new(),
699 configured: true,
700 opts: Default::default(),
701 codegen: Default::default(),
702 debug: Default::default(),
703 wasm: Default::default(),
704 wasi: Default::default(),
705 record: Default::default(),
706 target: None,
707 config: None,
708 }
709 }
710
711 fn configure(&mut self) -> Result<()> {
712 if self.configured {
713 return Ok(());
714 }
715 self.configured = true;
716 if let Some(toml_config_path) = &self.config {
717 let toml_options = CommonOptions::from_file(toml_config_path)?;
718 self.opts = toml_options.opts;
719 self.codegen = toml_options.codegen;
720 self.debug = toml_options.debug;
721 self.wasm = toml_options.wasm;
722 self.wasi = toml_options.wasi;
723 self.record = toml_options.record;
724 }
725 self.opts.configure_with(&self.opts_raw);
726 self.codegen.configure_with(&self.codegen_raw);
727 self.debug.configure_with(&self.debug_raw);
728 self.wasm.configure_with(&self.wasm_raw);
729 self.wasi.configure_with(&self.wasi_raw);
730 self.record.configure_with(&self.record_raw);
731 Ok(())
732 }
733
734 pub fn init_logging(&mut self) -> Result<()> {
735 self.configure()?;
736 if self.debug.logging == Some(false) {
737 return Ok(());
738 }
739 #[cfg(feature = "logging")]
740 if self.debug.log_to_files == Some(true) {
741 let prefix = "wasmtime.dbg.";
742 init_file_per_thread_logger(prefix);
743 } else {
744 use std::io::IsTerminal;
745 use tracing_subscriber::{EnvFilter, FmtSubscriber};
746 let builder = FmtSubscriber::builder()
747 .with_writer(std::io::stderr)
748 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
749 .with_ansi(std::io::stderr().is_terminal());
750 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
751 builder
752 .with_level(false)
753 .with_target(false)
754 .without_time()
755 .init()
756 } else {
757 builder.init();
758 }
759 }
760 #[cfg(not(feature = "logging"))]
761 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
762 bail!("support for logging disabled at compile time");
763 }
764 Ok(())
765 }
766
767 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
768 self.configure()?;
769 let mut config = Config::new();
770
771 match_feature! {
772 ["cranelift" : self.codegen.compiler]
773 strategy => config.strategy(strategy),
774 _ => err,
775 }
776 match_feature! {
777 ["gc" : self.codegen.collector]
778 collector => config.collector(collector),
779 _ => err,
780 }
781 if let Some(target) = &self.target {
782 config.target(target)?;
783 }
784 match_feature! {
785 ["cranelift" : self.codegen.cranelift_debug_verifier]
786 enable => config.cranelift_debug_verifier(enable),
787 true => err,
788 }
789 if let Some(enable) = self.debug.debug_info {
790 config.debug_info(enable);
791 }
792 match_feature! {
793 ["debug" : self.debug.guest_debug]
794 enable => config.guest_debug(enable),
795 _ => err,
796 }
797 if self.debug.coredump.is_some() {
798 #[cfg(feature = "coredump")]
799 config.coredump_on_trap(true);
800 #[cfg(not(feature = "coredump"))]
801 bail!("support for coredumps disabled at compile time");
802 }
803 match_feature! {
804 ["cranelift" : self.opts.opt_level]
805 level => config.cranelift_opt_level(level),
806 _ => err,
807 }
808 match_feature! {
809 ["cranelift": self.opts.regalloc_algorithm]
810 algo => config.cranelift_regalloc_algorithm(algo),
811 _ => err,
812 }
813 match_feature! {
814 ["cranelift" : self.wasm.nan_canonicalization]
815 enable => config.cranelift_nan_canonicalization(enable),
816 true => err,
817 }
818
819 self.enable_wasm_features(&mut config)?;
820
821 #[cfg(feature = "cranelift")]
822 for (name, value) in self.codegen.cranelift.iter() {
823 let name = name.replace('-', "_");
824 unsafe {
825 match value {
826 Some(val) => {
827 config.cranelift_flag_set(&name, val);
828 }
829 None => {
830 config.cranelift_flag_enable(&name);
831 }
832 }
833 }
834 }
835 #[cfg(not(feature = "cranelift"))]
836 if !self.codegen.cranelift.is_empty() {
837 bail!("support for cranelift disabled at compile time");
838 }
839
840 #[cfg(feature = "cache")]
841 if self.codegen.cache != Some(false) {
842 use wasmtime::Cache;
843 let cache = match &self.codegen.cache_config {
844 Some(path) => Cache::from_file(Some(Path::new(path)))?,
845 None => Cache::from_file(None)?,
846 };
847 config.cache(Some(cache));
848 }
849 #[cfg(not(feature = "cache"))]
850 if self.codegen.cache == Some(true) {
851 bail!("support for caching disabled at compile time");
852 }
853
854 match_feature! {
855 ["parallel-compilation" : self.codegen.parallel_compilation]
856 enable => config.parallel_compilation(enable),
857 true => err,
858 }
859
860 let memory_reservation = self
861 .opts
862 .memory_reservation
863 .or(self.opts.static_memory_maximum_size);
864 if let Some(size) = memory_reservation {
865 config.memory_reservation(size);
866 }
867
868 if let Some(enable) = self.opts.static_memory_forced {
869 config.memory_may_move(!enable);
870 }
871 if let Some(enable) = self.opts.memory_may_move {
872 config.memory_may_move(enable);
873 }
874
875 let memory_guard_size = self
876 .opts
877 .static_memory_guard_size
878 .or(self.opts.dynamic_memory_guard_size)
879 .or(self.opts.memory_guard_size);
880 if let Some(size) = memory_guard_size {
881 config.memory_guard_size(size);
882 }
883
884 let mem_for_growth = self
885 .opts
886 .memory_reservation_for_growth
887 .or(self.opts.dynamic_memory_reserved_for_growth);
888 if let Some(size) = mem_for_growth {
889 config.memory_reservation_for_growth(size);
890 }
891 if let Some(enable) = self.opts.guard_before_linear_memory {
892 config.guard_before_linear_memory(enable);
893 }
894 if let Some(enable) = self.opts.table_lazy_init {
895 config.table_lazy_init(enable);
896 }
897
898 if self.wasm.fuel.is_some() {
900 config.consume_fuel(true);
901 }
902
903 if let Some(enable) = self.wasm.epoch_interruption {
904 config.epoch_interruption(enable);
905 }
906 if let Some(enable) = self.debug.address_map {
907 config.generate_address_map(enable);
908 }
909 if let Some(enable) = self.opts.memory_init_cow {
910 config.memory_init_cow(enable);
911 }
912 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
913 config.memory_guaranteed_dense_image_size(size);
914 }
915 if let Some(enable) = self.opts.signals_based_traps {
916 config.signals_based_traps(enable);
917 }
918 if let Some(enable) = self.codegen.native_unwind_info {
919 config.native_unwind_info(enable);
920 }
921 if let Some(enable) = self.codegen.inlining {
922 config.compiler_inlining(enable);
923 }
924
925 #[cfg(any(feature = "async", feature = "stack-switching"))]
928 {
929 if let Some(size) = self.wasm.async_stack_size {
930 config.async_stack_size(size);
931 }
932 }
933 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
934 {
935 if let Some(_size) = self.wasm.async_stack_size {
936 bail!(concat!(
937 "support for async/stack-switching disabled at compile time"
938 ));
939 }
940 }
941
942 match_feature! {
943 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
944 enable => {
945 if enable {
946 let mut cfg = wasmtime::PoolingAllocationConfig::default();
947 if let Some(size) = self.opts.pooling_memory_keep_resident {
948 cfg.linear_memory_keep_resident(size);
949 }
950 if let Some(size) = self.opts.pooling_table_keep_resident {
951 cfg.table_keep_resident(size);
952 }
953 if let Some(limit) = self.opts.pooling_total_core_instances {
954 cfg.total_core_instances(limit);
955 }
956 if let Some(limit) = self.opts.pooling_total_component_instances {
957 cfg.total_component_instances(limit);
958 }
959 if let Some(limit) = self.opts.pooling_total_memories {
960 cfg.total_memories(limit);
961 }
962 if let Some(limit) = self.opts.pooling_total_tables {
963 cfg.total_tables(limit);
964 }
965 if let Some(limit) = self.opts.pooling_table_elements
966 .or(self.wasm.max_table_elements)
967 {
968 cfg.table_elements(limit);
969 }
970 if let Some(limit) = self.opts.pooling_max_core_instance_size {
971 cfg.max_core_instance_size(limit);
972 }
973 match_feature! {
974 ["async" : self.opts.pooling_total_stacks]
975 limit => cfg.total_stacks(limit),
976 _ => err,
977 }
978 if let Some(max) = self.opts.pooling_max_memory_size
979 .or(self.wasm.max_memory_size)
980 {
981 cfg.max_memory_size(max);
982 }
983 if let Some(size) = self.opts.pooling_decommit_batch_size {
984 cfg.decommit_batch_size(size);
985 }
986 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
987 cfg.max_unused_warm_slots(max);
988 }
989 match_feature! {
990 ["async" : self.opts.pooling_async_stack_keep_resident]
991 size => cfg.async_stack_keep_resident(size),
992 _ => err,
993 }
994 if let Some(max) = self.opts.pooling_max_component_instance_size {
995 cfg.max_component_instance_size(max);
996 }
997 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
998 cfg.max_core_instances_per_component(max);
999 }
1000 if let Some(max) = self.opts.pooling_max_memories_per_component {
1001 cfg.max_memories_per_component(max);
1002 }
1003 if let Some(max) = self.opts.pooling_max_tables_per_component {
1004 cfg.max_tables_per_component(max);
1005 }
1006 if let Some(max) = self.opts.pooling_max_tables_per_module {
1007 cfg.max_tables_per_module(max);
1008 }
1009 if let Some(max) = self.opts.pooling_max_memories_per_module {
1010 cfg.max_memories_per_module(max);
1011 }
1012 match_feature! {
1013 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1014 enable => cfg.memory_protection_keys(enable),
1015 _ => err,
1016 }
1017 match_feature! {
1018 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1019 max => cfg.max_memory_protection_keys(max),
1020 _ => err,
1021 }
1022 match_feature! {
1023 ["gc" : self.opts.pooling_total_gc_heaps]
1024 max => cfg.total_gc_heaps(max),
1025 _ => err,
1026 }
1027 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1028 cfg.pagemap_scan(enabled);
1029 }
1030 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1031 }
1032 },
1033 true => err,
1034 }
1035
1036 if self.opts.pooling_memory_protection_keys.is_some()
1037 && !self.opts.pooling_allocator.unwrap_or(false)
1038 {
1039 bail!("memory protection keys require the pooling allocator");
1040 }
1041
1042 if self.opts.pooling_max_memory_protection_keys.is_some()
1043 && !self.opts.pooling_memory_protection_keys.is_some()
1044 {
1045 bail!("max memory protection keys requires memory protection keys to be enabled");
1046 }
1047
1048 match_feature! {
1049 ["async" : self.wasm.async_stack_zeroing]
1050 enable => config.async_stack_zeroing(enable),
1051 _ => err,
1052 }
1053
1054 if let Some(max) = self.wasm.max_wasm_stack {
1055 config.max_wasm_stack(max);
1056
1057 #[cfg(any(feature = "async", feature = "stack-switching"))]
1061 if self.wasm.async_stack_size.is_none() {
1062 const DEFAULT_HOST_STACK: usize = 512 << 10;
1063 config.async_stack_size(max + DEFAULT_HOST_STACK);
1064 }
1065 }
1066
1067 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1068 config.relaxed_simd_deterministic(enable);
1069 }
1070 match_feature! {
1071 ["cranelift" : self.wasm.wmemcheck]
1072 enable => config.wmemcheck(enable),
1073 true => err,
1074 }
1075
1076 if let Some(enable) = self.wasm.gc_support {
1077 config.gc_support(enable);
1078 }
1079
1080 if let Some(enable) = self.wasm.concurrency_support {
1081 config.concurrency_support(enable);
1082 }
1083
1084 if let Some(enable) = self.wasm.shared_memory {
1085 config.shared_memory(enable);
1086 }
1087
1088 let record = &self.record;
1089 match_feature! {
1090 ["rr" : &record.path]
1091 _path => {
1092 bail!("recording configuration for `rr` feature is not supported yet");
1093 },
1094 _ => err,
1095 }
1096
1097 Ok(config)
1098 }
1099
1100 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1101 let all = self.wasm.all_proposals;
1102
1103 if let Some(enable) = self.wasm.simd.or(all) {
1104 config.wasm_simd(enable);
1105 }
1106 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1107 config.wasm_relaxed_simd(enable);
1108 }
1109 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1110 config.wasm_bulk_memory(enable);
1111 }
1112 if let Some(enable) = self.wasm.multi_value.or(all) {
1113 config.wasm_multi_value(enable);
1114 }
1115 if let Some(enable) = self.wasm.tail_call.or(all) {
1116 config.wasm_tail_call(enable);
1117 }
1118 if let Some(enable) = self.wasm.multi_memory.or(all) {
1119 config.wasm_multi_memory(enable);
1120 }
1121 if let Some(enable) = self.wasm.memory64.or(all) {
1122 config.wasm_memory64(enable);
1123 }
1124 if let Some(enable) = self.wasm.stack_switching {
1125 config.wasm_stack_switching(enable);
1126 }
1127 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1128 config.wasm_custom_page_sizes(enable);
1129 }
1130 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1131 config.wasm_wide_arithmetic(enable);
1132 }
1133 if let Some(enable) = self.wasm.extended_const.or(all) {
1134 config.wasm_extended_const(enable);
1135 }
1136
1137 macro_rules! handle_conditionally_compiled {
1138 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1139 if let Some(enable) = self.wasm.$field.or(all) {
1140 #[cfg(feature = $feature)]
1141 config.$method(enable);
1142 #[cfg(not(feature = $feature))]
1143 if enable && all.is_none() {
1144 bail!("support for {} was disabled at compile-time", $feature);
1145 }
1146 }
1147 )*)
1148 }
1149
1150 handle_conditionally_compiled! {
1151 ("component-model", component_model, wasm_component_model)
1152 ("component-model-async", component_model_async, wasm_component_model_async)
1153 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1154 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1155 ("component-model-async", component_model_threading, wasm_component_model_threading)
1156 ("component-model", component_model_error_context, wasm_component_model_error_context)
1157 ("component-model", component_model_map, wasm_component_model_map)
1158 ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1159 ("threads", threads, wasm_threads)
1160 ("gc", gc, wasm_gc)
1161 ("gc", reference_types, wasm_reference_types)
1162 ("gc", function_references, wasm_function_references)
1163 ("gc", exceptions, wasm_exceptions)
1164 ("stack-switching", stack_switching, wasm_stack_switching)
1165 }
1166
1167 if let Some(enable) = self.wasm.component_model_gc {
1168 #[cfg(all(feature = "component-model", feature = "gc"))]
1169 config.wasm_component_model_gc(enable);
1170 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1171 if enable && all.is_none() {
1172 bail!("support for `component-model-gc` was disabled at compile time")
1173 }
1174 }
1175
1176 Ok(())
1177 }
1178
1179 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1180 let path_ref = path.as_ref();
1181 let file_contents = fs::read_to_string(path_ref)
1182 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1183 toml::from_str::<CommonOptions>(&file_contents)
1184 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1185 }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190 use wasmtime::{OptLevel, RegallocAlgorithm};
1191
1192 use super::*;
1193
1194 #[test]
1195 fn from_toml() {
1196 let empty_toml = "";
1198 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1199 common_options.config(None).unwrap();
1200
1201 let basic_toml = r#"
1203 [optimize]
1204 [codegen]
1205 [debug]
1206 [wasm]
1207 [wasi]
1208 [record]
1209 "#;
1210 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1211 common_options.config(None).unwrap();
1212
1213 for (opt_value, expected) in [
1215 ("0", Some(OptLevel::None)),
1216 ("1", Some(OptLevel::Speed)),
1217 ("2", Some(OptLevel::Speed)),
1218 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1219 ("\"hello\"", None), ("3", None), ] {
1222 let toml = format!(
1223 r#"
1224 [optimize]
1225 opt-level = {opt_value}
1226 "#,
1227 );
1228 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1229 .ok()
1230 .and_then(|common_options| common_options.opts.opt_level);
1231
1232 assert_eq!(
1233 parsed_opt_level, expected,
1234 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1235 );
1236 }
1237
1238 for (regalloc_value, expected) in [
1240 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1241 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1242 ("\"hello\"", None), ("3", None), ("true", None), ] {
1246 let toml = format!(
1247 r#"
1248 [optimize]
1249 regalloc-algorithm = {regalloc_value}
1250 "#,
1251 );
1252 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1253 .ok()
1254 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1255 assert_eq!(
1256 parsed_regalloc_algorithm, expected,
1257 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1258 );
1259 }
1260
1261 for (strategy_value, expected) in [
1263 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1264 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1265 ("\"hello\"", None), ("5", None), ("true", None), ] {
1269 let toml = format!(
1270 r#"
1271 [codegen]
1272 compiler = {strategy_value}
1273 "#,
1274 );
1275 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1276 .ok()
1277 .and_then(|common_options| common_options.codegen.compiler);
1278 assert_eq!(
1279 parsed_strategy, expected,
1280 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1281 );
1282 }
1283
1284 for (collector_value, expected) in [
1286 (
1287 "\"drc\"",
1288 Some(wasmtime::Collector::DeferredReferenceCounting),
1289 ),
1290 ("\"null\"", Some(wasmtime::Collector::Null)),
1291 ("\"hello\"", None), ("5", None), ("true", None), ] {
1295 let toml = format!(
1296 r#"
1297 [codegen]
1298 collector = {collector_value}
1299 "#,
1300 );
1301 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1302 .ok()
1303 .and_then(|common_options| common_options.codegen.collector);
1304 assert_eq!(
1305 parsed_collector, expected,
1306 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1307 );
1308 }
1309 }
1310}
1311
1312impl Default for CommonOptions {
1313 fn default() -> CommonOptions {
1314 CommonOptions::new()
1315 }
1316}
1317
1318impl fmt::Display for CommonOptions {
1319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320 let CommonOptions {
1321 codegen_raw,
1322 codegen,
1323 debug_raw,
1324 debug,
1325 opts_raw,
1326 opts,
1327 wasm_raw,
1328 wasm,
1329 wasi_raw,
1330 wasi,
1331 record_raw,
1332 record,
1333 configured,
1334 target,
1335 config,
1336 } = self;
1337 if let Some(target) = target {
1338 write!(f, "--target {target} ")?;
1339 }
1340 if let Some(config) = config {
1341 write!(f, "--config {} ", config.display())?;
1342 }
1343
1344 let codegen_flags;
1345 let opts_flags;
1346 let wasi_flags;
1347 let wasm_flags;
1348 let debug_flags;
1349 let record_flags;
1350
1351 if *configured {
1352 codegen_flags = codegen.to_options();
1353 debug_flags = debug.to_options();
1354 wasi_flags = wasi.to_options();
1355 wasm_flags = wasm.to_options();
1356 opts_flags = opts.to_options();
1357 record_flags = record.to_options();
1358 } else {
1359 codegen_flags = codegen_raw
1360 .iter()
1361 .flat_map(|t| t.0.iter())
1362 .cloned()
1363 .collect();
1364 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1365 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1366 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1367 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1368 record_flags = record_raw
1369 .iter()
1370 .flat_map(|t| t.0.iter())
1371 .cloned()
1372 .collect();
1373 }
1374
1375 for flag in codegen_flags {
1376 write!(f, "-C{flag} ")?;
1377 }
1378 for flag in opts_flags {
1379 write!(f, "-O{flag} ")?;
1380 }
1381 for flag in wasi_flags {
1382 write!(f, "-S{flag} ")?;
1383 }
1384 for flag in wasm_flags {
1385 write!(f, "-W{flag} ")?;
1386 }
1387 for flag in debug_flags {
1388 write!(f, "-D{flag} ")?;
1389 }
1390 for flag in record_flags {
1391 write!(f, "-R{flag} ")?;
1392 }
1393
1394 Ok(())
1395 }
1396}