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