1use anyhow::{Context, Result};
4use clap::Parser;
5use serde::Deserialize;
6use std::{
7 fmt, fs,
8 path::{Path, PathBuf},
9 time::Duration,
10};
11use wasmtime::Config;
12
13pub mod opt;
14
15#[cfg(feature = "logging")]
16fn init_file_per_thread_logger(prefix: &'static str) {
17 file_per_thread_logger::initialize(prefix);
18 file_per_thread_logger::allow_uninitialized();
19
20 #[cfg(feature = "parallel-compilation")]
25 rayon::ThreadPoolBuilder::new()
26 .spawn_handler(move |thread| {
27 let mut b = std::thread::Builder::new();
28 if let Some(name) = thread.name() {
29 b = b.name(name.to_owned());
30 }
31 if let Some(stack_size) = thread.stack_size() {
32 b = b.stack_size(stack_size);
33 }
34 b.spawn(move || {
35 file_per_thread_logger::initialize(prefix);
36 thread.run()
37 })?;
38 Ok(())
39 })
40 .build_global()
41 .unwrap();
42}
43
44wasmtime_option_group! {
45 #[derive(PartialEq, Clone, Deserialize)]
46 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
47 pub struct OptimizeOptions {
48 #[serde(default)]
50 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
51 pub opt_level: Option<wasmtime::OptLevel>,
52
53 #[serde(default)]
55 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
56 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
57
58 pub memory_may_move: Option<bool>,
61
62 pub memory_reservation: Option<u64>,
64
65 pub memory_reservation_for_growth: Option<u64>,
67
68 pub memory_guard_size: Option<u64>,
70
71 pub guard_before_linear_memory: Option<bool>,
74
75 pub table_lazy_init: Option<bool>,
80
81 pub pooling_allocator: Option<bool>,
83
84 pub pooling_decommit_batch_size: Option<usize>,
87
88 pub pooling_memory_keep_resident: Option<usize>,
91
92 pub pooling_table_keep_resident: Option<usize>,
95
96 #[serde(default)]
99 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
100 pub pooling_memory_protection_keys: Option<wasmtime::MpkEnabled>,
101
102 pub pooling_max_memory_protection_keys: Option<usize>,
105
106 pub memory_init_cow: Option<bool>,
109
110 pub memory_guaranteed_dense_image_size: Option<u64>,
113
114 pub pooling_total_core_instances: Option<u32>,
117
118 pub pooling_total_component_instances: Option<u32>,
121
122 pub pooling_total_memories: Option<u32>,
125
126 pub pooling_total_tables: Option<u32>,
129
130 pub pooling_total_stacks: Option<u32>,
133
134 pub pooling_max_memory_size: Option<usize>,
137
138 pub pooling_table_elements: Option<usize>,
141
142 pub pooling_max_core_instance_size: Option<usize>,
145
146 pub pooling_max_unused_warm_slots: Option<u32>,
149
150 pub pooling_async_stack_keep_resident: Option<usize>,
153
154 pub pooling_max_component_instance_size: Option<usize>,
157
158 pub pooling_max_core_instances_per_component: Option<u32>,
161
162 pub pooling_max_memories_per_component: Option<u32>,
165
166 pub pooling_max_tables_per_component: Option<u32>,
169
170 pub pooling_max_tables_per_module: Option<u32>,
172
173 pub pooling_max_memories_per_module: Option<u32>,
175
176 pub pooling_total_gc_heaps: Option<u32>,
178
179 pub signals_based_traps: Option<bool>,
181
182 pub dynamic_memory_guard_size: Option<u64>,
184
185 pub static_memory_guard_size: Option<u64>,
187
188 pub static_memory_forced: Option<bool>,
190
191 pub static_memory_maximum_size: Option<u64>,
193
194 pub dynamic_memory_reserved_for_growth: Option<u64>,
196 }
197
198 enum Optimize {
199 ...
200 }
201}
202
203wasmtime_option_group! {
204 #[derive(PartialEq, Clone, Deserialize)]
205 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
206 pub struct CodegenOptions {
207 #[serde(default)]
212 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
213 pub compiler: Option<wasmtime::Strategy>,
214 #[serde(default)]
224 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
225 pub collector: Option<wasmtime::Collector>,
226 pub cranelift_debug_verifier: Option<bool>,
228 pub cache: Option<bool>,
230 pub cache_config: Option<String>,
232 pub parallel_compilation: Option<bool>,
234 pub pcc: Option<bool>,
236 pub native_unwind_info: Option<bool>,
239
240 #[prefixed = "cranelift"]
241 #[serde(default)]
242 pub cranelift: Vec<(String, Option<String>)>,
245 }
246
247 enum Codegen {
248 ...
249 }
250}
251
252wasmtime_option_group! {
253 #[derive(PartialEq, Clone, Deserialize)]
254 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
255 pub struct DebugOptions {
256 pub debug_info: Option<bool>,
258 pub address_map: Option<bool>,
260 pub logging: Option<bool>,
262 pub log_to_files: Option<bool>,
264 pub coredump: Option<String>,
266 }
267
268 enum Debug {
269 ...
270 }
271}
272
273wasmtime_option_group! {
274 #[derive(PartialEq, Clone, Deserialize)]
275 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
276 pub struct WasmOptions {
277 pub nan_canonicalization: Option<bool>,
279 pub fuel: Option<u64>,
287 pub epoch_interruption: Option<bool>,
290 pub max_wasm_stack: Option<usize>,
293 pub async_stack_size: Option<usize>,
299 pub async_stack_zeroing: Option<bool>,
302 pub unknown_exports_allow: Option<bool>,
304 pub unknown_imports_trap: Option<bool>,
307 pub unknown_imports_default: Option<bool>,
310 pub wmemcheck: Option<bool>,
312 pub max_memory_size: Option<usize>,
317 pub max_table_elements: Option<usize>,
319 pub max_instances: Option<usize>,
321 pub max_tables: Option<usize>,
323 pub max_memories: Option<usize>,
325 pub trap_on_grow_failure: Option<bool>,
332 pub timeout: Option<Duration>,
334 pub all_proposals: Option<bool>,
336 pub bulk_memory: Option<bool>,
338 pub multi_memory: Option<bool>,
340 pub multi_value: Option<bool>,
342 pub reference_types: Option<bool>,
344 pub simd: Option<bool>,
346 pub relaxed_simd: Option<bool>,
348 pub relaxed_simd_deterministic: Option<bool>,
357 pub tail_call: Option<bool>,
359 pub threads: Option<bool>,
361 pub shared_everything_threads: Option<bool>,
363 pub memory64: Option<bool>,
365 pub component_model: Option<bool>,
367 pub component_model_async: Option<bool>,
369 pub component_model_async_builtins: Option<bool>,
372 pub component_model_async_stackful: Option<bool>,
375 pub function_references: Option<bool>,
377 pub gc: Option<bool>,
379 pub custom_page_sizes: Option<bool>,
381 pub wide_arithmetic: Option<bool>,
383 pub extended_const: Option<bool>,
385 pub exceptions: Option<bool>,
387 pub legacy_exceptions: Option<bool>,
389 }
390
391 enum Wasm {
392 ...
393 }
394}
395
396wasmtime_option_group! {
397 #[derive(PartialEq, Clone, Deserialize)]
398 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
399 pub struct WasiOptions {
400 pub cli: Option<bool>,
402 pub cli_exit_with_code: Option<bool>,
404 pub common: Option<bool>,
406 pub nn: Option<bool>,
408 pub threads: Option<bool>,
410 pub http: Option<bool>,
412 pub http_outgoing_body_buffer_chunks: Option<usize>,
416 pub http_outgoing_body_chunk_size: Option<usize>,
419 pub config: Option<bool>,
421 pub keyvalue: Option<bool>,
423 pub listenfd: Option<bool>,
427 #[serde(default)]
430 pub tcplisten: Vec<String>,
431 pub tls: Option<bool>,
433 pub preview2: Option<bool>,
436 #[serde(skip)]
445 pub nn_graph: Vec<WasiNnGraph>,
446 pub inherit_network: Option<bool>,
449 pub allow_ip_name_lookup: Option<bool>,
451 pub tcp: Option<bool>,
453 pub udp: Option<bool>,
455 pub network_error_code: Option<bool>,
457 pub preview0: Option<bool>,
459 pub inherit_env: Option<bool>,
463 #[serde(skip)]
465 pub config_var: Vec<KeyValuePair>,
466 #[serde(skip)]
468 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
469 }
470
471 enum Wasi {
472 ...
473 }
474}
475
476#[derive(Debug, Clone, PartialEq)]
477pub struct WasiNnGraph {
478 pub format: String,
479 pub dir: String,
480}
481
482#[derive(Debug, Clone, PartialEq)]
483pub struct KeyValuePair {
484 pub key: String,
485 pub value: String,
486}
487
488#[derive(Parser, Clone, Deserialize)]
490#[serde(deny_unknown_fields)]
491pub struct CommonOptions {
492 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
502 #[serde(skip)]
503 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
504
505 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
507 #[serde(skip)]
508 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
509
510 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
512 #[serde(skip)]
513 debug_raw: Vec<opt::CommaSeparated<Debug>>,
514
515 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
518 #[serde(skip)]
519 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
520
521 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
523 #[serde(skip)]
524 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
525
526 #[arg(skip)]
529 #[serde(skip)]
530 configured: bool,
531
532 #[arg(skip)]
533 #[serde(rename = "optimize", default)]
534 pub opts: OptimizeOptions,
535
536 #[arg(skip)]
537 #[serde(rename = "codegen", default)]
538 pub codegen: CodegenOptions,
539
540 #[arg(skip)]
541 #[serde(rename = "debug", default)]
542 pub debug: DebugOptions,
543
544 #[arg(skip)]
545 #[serde(rename = "wasm", default)]
546 pub wasm: WasmOptions,
547
548 #[arg(skip)]
549 #[serde(rename = "wasi", default)]
550 pub wasi: WasiOptions,
551
552 #[arg(long, value_name = "TARGET")]
554 #[serde(skip)]
555 pub target: Option<String>,
556
557 #[arg(long = "config", value_name = "FILE")]
564 #[serde(skip)]
565 pub config: Option<PathBuf>,
566}
567
568macro_rules! match_feature {
569 (
570 [$feat:tt : $config:expr]
571 $val:ident => $e:expr,
572 $p:pat => err,
573 ) => {
574 #[cfg(feature = $feat)]
575 {
576 if let Some($val) = $config {
577 $e;
578 }
579 }
580 #[cfg(not(feature = $feat))]
581 {
582 if let Some($p) = $config {
583 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
584 }
585 }
586 };
587}
588
589impl CommonOptions {
590 pub fn new() -> CommonOptions {
592 CommonOptions {
593 opts_raw: Vec::new(),
594 codegen_raw: Vec::new(),
595 debug_raw: Vec::new(),
596 wasm_raw: Vec::new(),
597 wasi_raw: Vec::new(),
598 configured: true,
599 opts: Default::default(),
600 codegen: Default::default(),
601 debug: Default::default(),
602 wasm: Default::default(),
603 wasi: Default::default(),
604 target: None,
605 config: None,
606 }
607 }
608
609 fn configure(&mut self) -> Result<()> {
610 if self.configured {
611 return Ok(());
612 }
613 self.configured = true;
614 if let Some(toml_config_path) = &self.config {
615 let toml_options = CommonOptions::from_file(toml_config_path)?;
616 self.opts = toml_options.opts;
617 self.codegen = toml_options.codegen;
618 self.debug = toml_options.debug;
619 self.wasm = toml_options.wasm;
620 self.wasi = toml_options.wasi;
621 }
622 self.opts.configure_with(&self.opts_raw);
623 self.codegen.configure_with(&self.codegen_raw);
624 self.debug.configure_with(&self.debug_raw);
625 self.wasm.configure_with(&self.wasm_raw);
626 self.wasi.configure_with(&self.wasi_raw);
627 Ok(())
628 }
629
630 pub fn init_logging(&mut self) -> Result<()> {
631 self.configure()?;
632 if self.debug.logging == Some(false) {
633 return Ok(());
634 }
635 #[cfg(feature = "logging")]
636 if self.debug.log_to_files == Some(true) {
637 let prefix = "wasmtime.dbg.";
638 init_file_per_thread_logger(prefix);
639 } else {
640 use std::io::IsTerminal;
641 use tracing_subscriber::{EnvFilter, FmtSubscriber};
642 let builder = FmtSubscriber::builder()
643 .with_writer(std::io::stderr)
644 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
645 .with_ansi(std::io::stderr().is_terminal());
646 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
647 builder
648 .with_level(false)
649 .with_target(false)
650 .without_time()
651 .init()
652 } else {
653 builder.init();
654 }
655 }
656 #[cfg(not(feature = "logging"))]
657 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
658 anyhow::bail!("support for logging disabled at compile time");
659 }
660 Ok(())
661 }
662
663 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
664 self.configure()?;
665 let mut config = Config::new();
666
667 match_feature! {
668 ["cranelift" : self.codegen.compiler]
669 strategy => config.strategy(strategy),
670 _ => err,
671 }
672 match_feature! {
673 ["gc" : self.codegen.collector]
674 collector => config.collector(collector),
675 _ => err,
676 }
677 if let Some(target) = &self.target {
678 config.target(target)?;
679 }
680 match_feature! {
681 ["cranelift" : self.codegen.cranelift_debug_verifier]
682 enable => config.cranelift_debug_verifier(enable),
683 true => err,
684 }
685 if let Some(enable) = self.debug.debug_info {
686 config.debug_info(enable);
687 }
688 if self.debug.coredump.is_some() {
689 #[cfg(feature = "coredump")]
690 config.coredump_on_trap(true);
691 #[cfg(not(feature = "coredump"))]
692 anyhow::bail!("support for coredumps disabled at compile time");
693 }
694 match_feature! {
695 ["cranelift" : self.opts.opt_level]
696 level => config.cranelift_opt_level(level),
697 _ => err,
698 }
699 match_feature! {
700 ["cranelift": self.opts.regalloc_algorithm]
701 algo => config.cranelift_regalloc_algorithm(algo),
702 _ => err,
703 }
704 match_feature! {
705 ["cranelift" : self.wasm.nan_canonicalization]
706 enable => config.cranelift_nan_canonicalization(enable),
707 true => err,
708 }
709 match_feature! {
710 ["cranelift" : self.codegen.pcc]
711 enable => config.cranelift_pcc(enable),
712 true => err,
713 }
714
715 self.enable_wasm_features(&mut config)?;
716
717 #[cfg(feature = "cranelift")]
718 for (name, value) in self.codegen.cranelift.iter() {
719 let name = name.replace('-', "_");
720 unsafe {
721 match value {
722 Some(val) => {
723 config.cranelift_flag_set(&name, val);
724 }
725 None => {
726 config.cranelift_flag_enable(&name);
727 }
728 }
729 }
730 }
731 #[cfg(not(feature = "cranelift"))]
732 if !self.codegen.cranelift.is_empty() {
733 anyhow::bail!("support for cranelift disabled at compile time");
734 }
735
736 #[cfg(feature = "cache")]
737 if self.codegen.cache != Some(false) {
738 use wasmtime::Cache;
739 let cache = match &self.codegen.cache_config {
740 Some(path) => Cache::from_file(Some(Path::new(path)))?,
741 None => Cache::from_file(None)?,
742 };
743 config.cache(Some(cache));
744 }
745 #[cfg(not(feature = "cache"))]
746 if self.codegen.cache == Some(true) {
747 anyhow::bail!("support for caching disabled at compile time");
748 }
749
750 match_feature! {
751 ["parallel-compilation" : self.codegen.parallel_compilation]
752 enable => config.parallel_compilation(enable),
753 true => err,
754 }
755
756 let memory_reservation = self
757 .opts
758 .memory_reservation
759 .or(self.opts.static_memory_maximum_size);
760 if let Some(size) = memory_reservation {
761 config.memory_reservation(size);
762 }
763
764 if let Some(enable) = self.opts.static_memory_forced {
765 config.memory_may_move(!enable);
766 }
767 if let Some(enable) = self.opts.memory_may_move {
768 config.memory_may_move(enable);
769 }
770
771 let memory_guard_size = self
772 .opts
773 .static_memory_guard_size
774 .or(self.opts.dynamic_memory_guard_size)
775 .or(self.opts.memory_guard_size);
776 if let Some(size) = memory_guard_size {
777 config.memory_guard_size(size);
778 }
779
780 let mem_for_growth = self
781 .opts
782 .memory_reservation_for_growth
783 .or(self.opts.dynamic_memory_reserved_for_growth);
784 if let Some(size) = mem_for_growth {
785 config.memory_reservation_for_growth(size);
786 }
787 if let Some(enable) = self.opts.guard_before_linear_memory {
788 config.guard_before_linear_memory(enable);
789 }
790 if let Some(enable) = self.opts.table_lazy_init {
791 config.table_lazy_init(enable);
792 }
793
794 if self.wasm.fuel.is_some() {
796 config.consume_fuel(true);
797 }
798
799 if let Some(enable) = self.wasm.epoch_interruption {
800 config.epoch_interruption(enable);
801 }
802 if let Some(enable) = self.debug.address_map {
803 config.generate_address_map(enable);
804 }
805 if let Some(enable) = self.opts.memory_init_cow {
806 config.memory_init_cow(enable);
807 }
808 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
809 config.memory_guaranteed_dense_image_size(size);
810 }
811 if let Some(enable) = self.opts.signals_based_traps {
812 config.signals_based_traps(enable);
813 }
814 if let Some(enable) = self.codegen.native_unwind_info {
815 config.native_unwind_info(enable);
816 }
817
818 match_feature! {
819 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
820 enable => {
821 if enable {
822 let mut cfg = wasmtime::PoolingAllocationConfig::default();
823 if let Some(size) = self.opts.pooling_memory_keep_resident {
824 cfg.linear_memory_keep_resident(size);
825 }
826 if let Some(size) = self.opts.pooling_table_keep_resident {
827 cfg.table_keep_resident(size);
828 }
829 if let Some(limit) = self.opts.pooling_total_core_instances {
830 cfg.total_core_instances(limit);
831 }
832 if let Some(limit) = self.opts.pooling_total_component_instances {
833 cfg.total_component_instances(limit);
834 }
835 if let Some(limit) = self.opts.pooling_total_memories {
836 cfg.total_memories(limit);
837 }
838 if let Some(limit) = self.opts.pooling_total_tables {
839 cfg.total_tables(limit);
840 }
841 if let Some(limit) = self.opts.pooling_table_elements
842 .or(self.wasm.max_table_elements)
843 {
844 cfg.table_elements(limit);
845 }
846 if let Some(limit) = self.opts.pooling_max_core_instance_size {
847 cfg.max_core_instance_size(limit);
848 }
849 match_feature! {
850 ["async" : self.opts.pooling_total_stacks]
851 limit => cfg.total_stacks(limit),
852 _ => err,
853 }
854 if let Some(max) = self.opts.pooling_max_memory_size
855 .or(self.wasm.max_memory_size)
856 {
857 cfg.max_memory_size(max);
858 }
859 if let Some(size) = self.opts.pooling_decommit_batch_size {
860 cfg.decommit_batch_size(size);
861 }
862 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
863 cfg.max_unused_warm_slots(max);
864 }
865 match_feature! {
866 ["async" : self.opts.pooling_async_stack_keep_resident]
867 size => cfg.async_stack_keep_resident(size),
868 _ => err,
869 }
870 if let Some(max) = self.opts.pooling_max_component_instance_size {
871 cfg.max_component_instance_size(max);
872 }
873 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
874 cfg.max_core_instances_per_component(max);
875 }
876 if let Some(max) = self.opts.pooling_max_memories_per_component {
877 cfg.max_memories_per_component(max);
878 }
879 if let Some(max) = self.opts.pooling_max_tables_per_component {
880 cfg.max_tables_per_component(max);
881 }
882 if let Some(max) = self.opts.pooling_max_tables_per_module {
883 cfg.max_tables_per_module(max);
884 }
885 if let Some(max) = self.opts.pooling_max_memories_per_module {
886 cfg.max_memories_per_module(max);
887 }
888 match_feature! {
889 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
890 enable => cfg.memory_protection_keys(enable),
891 _ => err,
892 }
893 match_feature! {
894 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
895 max => cfg.max_memory_protection_keys(max),
896 _ => err,
897 }
898 match_feature! {
899 ["gc" : self.opts.pooling_total_gc_heaps]
900 max => cfg.total_gc_heaps(max),
901 _ => err,
902 }
903 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
904 }
905 },
906 true => err,
907 }
908
909 if self.opts.pooling_memory_protection_keys.is_some()
910 && !self.opts.pooling_allocator.unwrap_or(false)
911 {
912 anyhow::bail!("memory protection keys require the pooling allocator");
913 }
914
915 if self.opts.pooling_max_memory_protection_keys.is_some()
916 && !self.opts.pooling_memory_protection_keys.is_some()
917 {
918 anyhow::bail!(
919 "max memory protection keys requires memory protection keys to be enabled"
920 );
921 }
922
923 match_feature! {
924 ["async" : self.wasm.async_stack_size]
925 size => config.async_stack_size(size),
926 _ => err,
927 }
928 match_feature! {
929 ["async" : self.wasm.async_stack_zeroing]
930 enable => config.async_stack_zeroing(enable),
931 _ => err,
932 }
933
934 if let Some(max) = self.wasm.max_wasm_stack {
935 config.max_wasm_stack(max);
936
937 #[cfg(feature = "async")]
941 if self.wasm.async_stack_size.is_none() {
942 const DEFAULT_HOST_STACK: usize = 512 << 10;
943 config.async_stack_size(max + DEFAULT_HOST_STACK);
944 }
945 }
946
947 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
948 config.relaxed_simd_deterministic(enable);
949 }
950 match_feature! {
951 ["cranelift" : self.wasm.wmemcheck]
952 enable => config.wmemcheck(enable),
953 true => err,
954 }
955
956 Ok(config)
957 }
958
959 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
960 let all = self.wasm.all_proposals;
961
962 if let Some(enable) = self.wasm.simd.or(all) {
963 config.wasm_simd(enable);
964 }
965 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
966 config.wasm_relaxed_simd(enable);
967 }
968 if let Some(enable) = self.wasm.bulk_memory.or(all) {
969 config.wasm_bulk_memory(enable);
970 }
971 if let Some(enable) = self.wasm.multi_value.or(all) {
972 config.wasm_multi_value(enable);
973 }
974 if let Some(enable) = self.wasm.tail_call.or(all) {
975 config.wasm_tail_call(enable);
976 }
977 if let Some(enable) = self.wasm.multi_memory.or(all) {
978 config.wasm_multi_memory(enable);
979 }
980 if let Some(enable) = self.wasm.memory64.or(all) {
981 config.wasm_memory64(enable);
982 }
983 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
984 config.wasm_custom_page_sizes(enable);
985 }
986 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
987 config.wasm_wide_arithmetic(enable);
988 }
989 if let Some(enable) = self.wasm.extended_const.or(all) {
990 config.wasm_extended_const(enable);
991 }
992 if let Some(enable) = self.wasm.exceptions.or(all) {
993 config.wasm_exceptions(enable);
994 }
995 if let Some(enable) = self.wasm.legacy_exceptions.or(all) {
996 #[expect(deprecated, reason = "forwarding CLI flag")]
997 config.wasm_legacy_exceptions(enable);
998 }
999
1000 macro_rules! handle_conditionally_compiled {
1001 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1002 if let Some(enable) = self.wasm.$field.or(all) {
1003 #[cfg(feature = $feature)]
1004 config.$method(enable);
1005 #[cfg(not(feature = $feature))]
1006 if enable && all.is_none() {
1007 anyhow::bail!("support for {} was disabled at compile-time", $feature);
1008 }
1009 }
1010 )*)
1011 }
1012
1013 handle_conditionally_compiled! {
1014 ("component-model", component_model, wasm_component_model)
1015 ("component-model-async", component_model_async, wasm_component_model_async)
1016 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1017 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1018 ("threads", threads, wasm_threads)
1019 ("gc", gc, wasm_gc)
1020 ("gc", reference_types, wasm_reference_types)
1021 ("gc", function_references, wasm_function_references)
1022 }
1023 Ok(())
1024 }
1025
1026 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1027 let path_ref = path.as_ref();
1028 let file_contents = fs::read_to_string(path_ref)
1029 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1030 toml::from_str::<CommonOptions>(&file_contents)
1031 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1032 }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037 use wasmtime::{OptLevel, RegallocAlgorithm};
1038
1039 use super::*;
1040
1041 #[test]
1042 fn from_toml() {
1043 let empty_toml = "";
1045 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1046 common_options.config(None).unwrap();
1047
1048 let basic_toml = r#"
1050 [optimize]
1051 [codegen]
1052 [debug]
1053 [wasm]
1054 [wasi]
1055 "#;
1056 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1057 common_options.config(None).unwrap();
1058
1059 for (opt_value, expected) in [
1061 ("0", Some(OptLevel::None)),
1062 ("1", Some(OptLevel::Speed)),
1063 ("2", Some(OptLevel::Speed)),
1064 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1065 ("\"hello\"", None), ("3", None), ] {
1068 let toml = format!(
1069 r#"
1070 [optimize]
1071 opt-level = {opt_value}
1072 "#,
1073 );
1074 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1075 .ok()
1076 .and_then(|common_options| common_options.opts.opt_level);
1077
1078 assert_eq!(
1079 parsed_opt_level, expected,
1080 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1081 );
1082 }
1083
1084 for (regalloc_value, expected) in [
1086 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1087 ("\"hello\"", None), ("3", None), ("true", None), ] {
1091 let toml = format!(
1092 r#"
1093 [optimize]
1094 regalloc-algorithm = {regalloc_value}
1095 "#,
1096 );
1097 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1098 .ok()
1099 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1100 assert_eq!(
1101 parsed_regalloc_algorithm, expected,
1102 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1103 );
1104 }
1105
1106 for (strategy_value, expected) in [
1108 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1109 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1110 ("\"hello\"", None), ("5", None), ("true", None), ] {
1114 let toml = format!(
1115 r#"
1116 [codegen]
1117 compiler = {strategy_value}
1118 "#,
1119 );
1120 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1121 .ok()
1122 .and_then(|common_options| common_options.codegen.compiler);
1123 assert_eq!(
1124 parsed_strategy, expected,
1125 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1126 );
1127 }
1128
1129 for (collector_value, expected) in [
1131 (
1132 "\"drc\"",
1133 Some(wasmtime::Collector::DeferredReferenceCounting),
1134 ),
1135 ("\"null\"", Some(wasmtime::Collector::Null)),
1136 ("\"hello\"", None), ("5", None), ("true", None), ] {
1140 let toml = format!(
1141 r#"
1142 [codegen]
1143 collector = {collector_value}
1144 "#,
1145 );
1146 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1147 .ok()
1148 .and_then(|common_options| common_options.codegen.collector);
1149 assert_eq!(
1150 parsed_collector, expected,
1151 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1152 );
1153 }
1154 }
1155}
1156
1157impl Default for CommonOptions {
1158 fn default() -> CommonOptions {
1159 CommonOptions::new()
1160 }
1161}
1162
1163impl fmt::Display for CommonOptions {
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 let CommonOptions {
1166 codegen_raw,
1167 codegen,
1168 debug_raw,
1169 debug,
1170 opts_raw,
1171 opts,
1172 wasm_raw,
1173 wasm,
1174 wasi_raw,
1175 wasi,
1176 configured,
1177 target,
1178 config,
1179 } = self;
1180 if let Some(target) = target {
1181 write!(f, "--target {target} ")?;
1182 }
1183 if let Some(config) = config {
1184 write!(f, "--config {} ", config.display())?;
1185 }
1186
1187 let codegen_flags;
1188 let opts_flags;
1189 let wasi_flags;
1190 let wasm_flags;
1191 let debug_flags;
1192
1193 if *configured {
1194 codegen_flags = codegen.to_options();
1195 debug_flags = debug.to_options();
1196 wasi_flags = wasi.to_options();
1197 wasm_flags = wasm.to_options();
1198 opts_flags = opts.to_options();
1199 } else {
1200 codegen_flags = codegen_raw
1201 .iter()
1202 .flat_map(|t| t.0.iter())
1203 .cloned()
1204 .collect();
1205 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1206 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1207 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1208 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1209 }
1210
1211 for flag in codegen_flags {
1212 write!(f, "-C{flag} ")?;
1213 }
1214 for flag in opts_flags {
1215 write!(f, "-O{flag} ")?;
1216 }
1217 for flag in wasi_flags {
1218 write!(f, "-S{flag} ")?;
1219 }
1220 for flag in wasm_flags {
1221 write!(f, "-W{flag} ")?;
1222 }
1223 for flag in debug_flags {
1224 write!(f, "-D{flag} ")?;
1225 }
1226
1227 Ok(())
1228 }
1229}