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