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::Enabled>,
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 #[serde(default)]
200 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
201 pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
202 }
203
204 enum Optimize {
205 ...
206 }
207}
208
209wasmtime_option_group! {
210 #[derive(PartialEq, Clone, Deserialize)]
211 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
212 pub struct CodegenOptions {
213 #[serde(default)]
218 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
219 pub compiler: Option<wasmtime::Strategy>,
220 #[serde(default)]
230 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")]
231 pub collector: Option<wasmtime::Collector>,
232 pub cranelift_debug_verifier: Option<bool>,
234 pub cache: Option<bool>,
236 pub cache_config: Option<String>,
238 pub parallel_compilation: Option<bool>,
240 pub pcc: Option<bool>,
242 pub native_unwind_info: Option<bool>,
245
246 pub inlining: Option<bool>,
248
249 #[prefixed = "cranelift"]
250 #[serde(default)]
251 pub cranelift: Vec<(String, Option<String>)>,
254 }
255
256 enum Codegen {
257 ...
258 }
259}
260
261wasmtime_option_group! {
262 #[derive(PartialEq, Clone, Deserialize)]
263 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
264 pub struct DebugOptions {
265 pub debug_info: Option<bool>,
267 pub guest_debug: Option<bool>,
269 pub address_map: Option<bool>,
271 pub logging: Option<bool>,
273 pub log_to_files: Option<bool>,
275 pub coredump: Option<String>,
277 }
278
279 enum Debug {
280 ...
281 }
282}
283
284wasmtime_option_group! {
285 #[derive(PartialEq, Clone, Deserialize)]
286 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
287 pub struct WasmOptions {
288 pub nan_canonicalization: Option<bool>,
290 pub fuel: Option<u64>,
298 pub epoch_interruption: Option<bool>,
301 pub max_wasm_stack: Option<usize>,
304 pub async_stack_size: Option<usize>,
310 pub async_stack_zeroing: Option<bool>,
313 pub unknown_exports_allow: Option<bool>,
315 pub unknown_imports_trap: Option<bool>,
318 pub unknown_imports_default: Option<bool>,
321 pub wmemcheck: Option<bool>,
323 pub max_memory_size: Option<usize>,
328 pub max_table_elements: Option<usize>,
330 pub max_instances: Option<usize>,
332 pub max_tables: Option<usize>,
334 pub max_memories: Option<usize>,
336 pub trap_on_grow_failure: Option<bool>,
343 pub timeout: Option<Duration>,
345 pub all_proposals: Option<bool>,
347 pub bulk_memory: Option<bool>,
349 pub multi_memory: Option<bool>,
351 pub multi_value: Option<bool>,
353 pub reference_types: Option<bool>,
355 pub simd: Option<bool>,
357 pub relaxed_simd: Option<bool>,
359 pub relaxed_simd_deterministic: Option<bool>,
368 pub tail_call: Option<bool>,
370 pub threads: Option<bool>,
372 pub shared_everything_threads: Option<bool>,
374 pub memory64: Option<bool>,
376 pub component_model: Option<bool>,
378 pub component_model_async: Option<bool>,
380 pub component_model_async_builtins: Option<bool>,
383 pub component_model_async_stackful: Option<bool>,
386 pub component_model_threading: Option<bool>,
389 pub component_model_error_context: Option<bool>,
392 pub component_model_gc: Option<bool>,
395 pub function_references: Option<bool>,
397 pub stack_switching: Option<bool>,
399 pub gc: Option<bool>,
401 pub custom_page_sizes: Option<bool>,
403 pub wide_arithmetic: Option<bool>,
405 pub extended_const: Option<bool>,
407 pub exceptions: Option<bool>,
409 pub gc_support: Option<bool>,
411 }
412
413 enum Wasm {
414 ...
415 }
416}
417
418wasmtime_option_group! {
419 #[derive(PartialEq, Clone, Deserialize)]
420 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
421 pub struct WasiOptions {
422 pub cli: Option<bool>,
424 pub cli_exit_with_code: Option<bool>,
426 pub common: Option<bool>,
428 pub nn: Option<bool>,
430 pub threads: Option<bool>,
432 pub http: Option<bool>,
434 pub http_outgoing_body_buffer_chunks: Option<usize>,
438 pub http_outgoing_body_chunk_size: Option<usize>,
441 pub config: Option<bool>,
443 pub keyvalue: Option<bool>,
445 pub listenfd: Option<bool>,
449 #[serde(default)]
452 pub tcplisten: Vec<String>,
453 pub tls: Option<bool>,
455 pub preview2: Option<bool>,
458 #[serde(skip)]
467 pub nn_graph: Vec<WasiNnGraph>,
468 pub inherit_network: Option<bool>,
471 pub allow_ip_name_lookup: Option<bool>,
473 pub tcp: Option<bool>,
475 pub udp: Option<bool>,
477 pub network_error_code: Option<bool>,
479 pub preview0: Option<bool>,
481 pub inherit_env: Option<bool>,
485 #[serde(skip)]
487 pub config_var: Vec<KeyValuePair>,
488 #[serde(skip)]
490 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
491 pub p3: Option<bool>,
493 }
494
495 enum Wasi {
496 ...
497 }
498}
499
500#[derive(Debug, Clone, PartialEq)]
501pub struct WasiNnGraph {
502 pub format: String,
503 pub dir: String,
504}
505
506#[derive(Debug, Clone, PartialEq)]
507pub struct KeyValuePair {
508 pub key: String,
509 pub value: String,
510}
511
512#[derive(Parser, Clone, Deserialize)]
514#[serde(deny_unknown_fields)]
515pub struct CommonOptions {
516 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")]
526 #[serde(skip)]
527 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
528
529 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")]
531 #[serde(skip)]
532 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
533
534 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")]
536 #[serde(skip)]
537 debug_raw: Vec<opt::CommaSeparated<Debug>>,
538
539 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")]
542 #[serde(skip)]
543 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
544
545 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")]
547 #[serde(skip)]
548 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
549
550 #[arg(skip)]
553 #[serde(skip)]
554 configured: bool,
555
556 #[arg(skip)]
557 #[serde(rename = "optimize", default)]
558 pub opts: OptimizeOptions,
559
560 #[arg(skip)]
561 #[serde(rename = "codegen", default)]
562 pub codegen: CodegenOptions,
563
564 #[arg(skip)]
565 #[serde(rename = "debug", default)]
566 pub debug: DebugOptions,
567
568 #[arg(skip)]
569 #[serde(rename = "wasm", default)]
570 pub wasm: WasmOptions,
571
572 #[arg(skip)]
573 #[serde(rename = "wasi", default)]
574 pub wasi: WasiOptions,
575
576 #[arg(long, value_name = "TARGET")]
578 #[serde(skip)]
579 pub target: Option<String>,
580
581 #[arg(long = "config", value_name = "FILE")]
588 #[serde(skip)]
589 pub config: Option<PathBuf>,
590}
591
592macro_rules! match_feature {
593 (
594 [$feat:tt : $config:expr]
595 $val:ident => $e:expr,
596 $p:pat => err,
597 ) => {
598 #[cfg(feature = $feat)]
599 {
600 if let Some($val) = $config {
601 $e;
602 }
603 }
604 #[cfg(not(feature = $feat))]
605 {
606 if let Some($p) = $config {
607 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time"));
608 }
609 }
610 };
611}
612
613impl CommonOptions {
614 pub fn new() -> CommonOptions {
616 CommonOptions {
617 opts_raw: Vec::new(),
618 codegen_raw: Vec::new(),
619 debug_raw: Vec::new(),
620 wasm_raw: Vec::new(),
621 wasi_raw: Vec::new(),
622 configured: true,
623 opts: Default::default(),
624 codegen: Default::default(),
625 debug: Default::default(),
626 wasm: Default::default(),
627 wasi: Default::default(),
628 target: None,
629 config: None,
630 }
631 }
632
633 fn configure(&mut self) -> Result<()> {
634 if self.configured {
635 return Ok(());
636 }
637 self.configured = true;
638 if let Some(toml_config_path) = &self.config {
639 let toml_options = CommonOptions::from_file(toml_config_path)?;
640 self.opts = toml_options.opts;
641 self.codegen = toml_options.codegen;
642 self.debug = toml_options.debug;
643 self.wasm = toml_options.wasm;
644 self.wasi = toml_options.wasi;
645 }
646 self.opts.configure_with(&self.opts_raw);
647 self.codegen.configure_with(&self.codegen_raw);
648 self.debug.configure_with(&self.debug_raw);
649 self.wasm.configure_with(&self.wasm_raw);
650 self.wasi.configure_with(&self.wasi_raw);
651 Ok(())
652 }
653
654 pub fn init_logging(&mut self) -> Result<()> {
655 self.configure()?;
656 if self.debug.logging == Some(false) {
657 return Ok(());
658 }
659 #[cfg(feature = "logging")]
660 if self.debug.log_to_files == Some(true) {
661 let prefix = "wasmtime.dbg.";
662 init_file_per_thread_logger(prefix);
663 } else {
664 use std::io::IsTerminal;
665 use tracing_subscriber::{EnvFilter, FmtSubscriber};
666 let builder = FmtSubscriber::builder()
667 .with_writer(std::io::stderr)
668 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
669 .with_ansi(std::io::stderr().is_terminal());
670 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
671 builder
672 .with_level(false)
673 .with_target(false)
674 .without_time()
675 .init()
676 } else {
677 builder.init();
678 }
679 }
680 #[cfg(not(feature = "logging"))]
681 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
682 anyhow::bail!("support for logging disabled at compile time");
683 }
684 Ok(())
685 }
686
687 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
688 self.configure()?;
689 let mut config = Config::new();
690
691 match_feature! {
692 ["cranelift" : self.codegen.compiler]
693 strategy => config.strategy(strategy),
694 _ => err,
695 }
696 match_feature! {
697 ["gc" : self.codegen.collector]
698 collector => config.collector(collector),
699 _ => err,
700 }
701 if let Some(target) = &self.target {
702 config.target(target)?;
703 }
704 match_feature! {
705 ["cranelift" : self.codegen.cranelift_debug_verifier]
706 enable => config.cranelift_debug_verifier(enable),
707 true => err,
708 }
709 if let Some(enable) = self.debug.debug_info {
710 config.debug_info(enable);
711 }
712 match_feature! {
713 ["debug" : self.debug.guest_debug]
714 enable => config.guest_debug(enable),
715 _ => err,
716 }
717 if self.debug.coredump.is_some() {
718 #[cfg(feature = "coredump")]
719 config.coredump_on_trap(true);
720 #[cfg(not(feature = "coredump"))]
721 anyhow::bail!("support for coredumps disabled at compile time");
722 }
723 match_feature! {
724 ["cranelift" : self.opts.opt_level]
725 level => config.cranelift_opt_level(level),
726 _ => err,
727 }
728 match_feature! {
729 ["cranelift": self.opts.regalloc_algorithm]
730 algo => config.cranelift_regalloc_algorithm(algo),
731 _ => err,
732 }
733 match_feature! {
734 ["cranelift" : self.wasm.nan_canonicalization]
735 enable => config.cranelift_nan_canonicalization(enable),
736 true => err,
737 }
738 match_feature! {
739 ["cranelift" : self.codegen.pcc]
740 enable => config.cranelift_pcc(enable),
741 true => err,
742 }
743
744 self.enable_wasm_features(&mut config)?;
745
746 #[cfg(feature = "cranelift")]
747 for (name, value) in self.codegen.cranelift.iter() {
748 let name = name.replace('-', "_");
749 unsafe {
750 match value {
751 Some(val) => {
752 config.cranelift_flag_set(&name, val);
753 }
754 None => {
755 config.cranelift_flag_enable(&name);
756 }
757 }
758 }
759 }
760 #[cfg(not(feature = "cranelift"))]
761 if !self.codegen.cranelift.is_empty() {
762 anyhow::bail!("support for cranelift disabled at compile time");
763 }
764
765 #[cfg(feature = "cache")]
766 if self.codegen.cache != Some(false) {
767 use wasmtime::Cache;
768 let cache = match &self.codegen.cache_config {
769 Some(path) => Cache::from_file(Some(Path::new(path)))?,
770 None => Cache::from_file(None)?,
771 };
772 config.cache(Some(cache));
773 }
774 #[cfg(not(feature = "cache"))]
775 if self.codegen.cache == Some(true) {
776 anyhow::bail!("support for caching disabled at compile time");
777 }
778
779 match_feature! {
780 ["parallel-compilation" : self.codegen.parallel_compilation]
781 enable => config.parallel_compilation(enable),
782 true => err,
783 }
784
785 let memory_reservation = self
786 .opts
787 .memory_reservation
788 .or(self.opts.static_memory_maximum_size);
789 if let Some(size) = memory_reservation {
790 config.memory_reservation(size);
791 }
792
793 if let Some(enable) = self.opts.static_memory_forced {
794 config.memory_may_move(!enable);
795 }
796 if let Some(enable) = self.opts.memory_may_move {
797 config.memory_may_move(enable);
798 }
799
800 let memory_guard_size = self
801 .opts
802 .static_memory_guard_size
803 .or(self.opts.dynamic_memory_guard_size)
804 .or(self.opts.memory_guard_size);
805 if let Some(size) = memory_guard_size {
806 config.memory_guard_size(size);
807 }
808
809 let mem_for_growth = self
810 .opts
811 .memory_reservation_for_growth
812 .or(self.opts.dynamic_memory_reserved_for_growth);
813 if let Some(size) = mem_for_growth {
814 config.memory_reservation_for_growth(size);
815 }
816 if let Some(enable) = self.opts.guard_before_linear_memory {
817 config.guard_before_linear_memory(enable);
818 }
819 if let Some(enable) = self.opts.table_lazy_init {
820 config.table_lazy_init(enable);
821 }
822
823 if self.wasm.fuel.is_some() {
825 config.consume_fuel(true);
826 }
827
828 if let Some(enable) = self.wasm.epoch_interruption {
829 config.epoch_interruption(enable);
830 }
831 if let Some(enable) = self.debug.address_map {
832 config.generate_address_map(enable);
833 }
834 if let Some(enable) = self.opts.memory_init_cow {
835 config.memory_init_cow(enable);
836 }
837 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
838 config.memory_guaranteed_dense_image_size(size);
839 }
840 if let Some(enable) = self.opts.signals_based_traps {
841 config.signals_based_traps(enable);
842 }
843 if let Some(enable) = self.codegen.native_unwind_info {
844 config.native_unwind_info(enable);
845 }
846 if let Some(enable) = self.codegen.inlining {
847 config.compiler_inlining(enable);
848 }
849
850 #[cfg(any(feature = "async", feature = "stack-switching"))]
853 {
854 if let Some(size) = self.wasm.async_stack_size {
855 config.async_stack_size(size);
856 }
857 }
858 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
859 {
860 if let Some(_size) = self.wasm.async_stack_size {
861 anyhow::bail!(concat!(
862 "support for async/stack-switching disabled at compile time"
863 ));
864 }
865 }
866
867 match_feature! {
868 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
869 enable => {
870 if enable {
871 let mut cfg = wasmtime::PoolingAllocationConfig::default();
872 if let Some(size) = self.opts.pooling_memory_keep_resident {
873 cfg.linear_memory_keep_resident(size);
874 }
875 if let Some(size) = self.opts.pooling_table_keep_resident {
876 cfg.table_keep_resident(size);
877 }
878 if let Some(limit) = self.opts.pooling_total_core_instances {
879 cfg.total_core_instances(limit);
880 }
881 if let Some(limit) = self.opts.pooling_total_component_instances {
882 cfg.total_component_instances(limit);
883 }
884 if let Some(limit) = self.opts.pooling_total_memories {
885 cfg.total_memories(limit);
886 }
887 if let Some(limit) = self.opts.pooling_total_tables {
888 cfg.total_tables(limit);
889 }
890 if let Some(limit) = self.opts.pooling_table_elements
891 .or(self.wasm.max_table_elements)
892 {
893 cfg.table_elements(limit);
894 }
895 if let Some(limit) = self.opts.pooling_max_core_instance_size {
896 cfg.max_core_instance_size(limit);
897 }
898 match_feature! {
899 ["async" : self.opts.pooling_total_stacks]
900 limit => cfg.total_stacks(limit),
901 _ => err,
902 }
903 if let Some(max) = self.opts.pooling_max_memory_size
904 .or(self.wasm.max_memory_size)
905 {
906 cfg.max_memory_size(max);
907 }
908 if let Some(size) = self.opts.pooling_decommit_batch_size {
909 cfg.decommit_batch_size(size);
910 }
911 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
912 cfg.max_unused_warm_slots(max);
913 }
914 match_feature! {
915 ["async" : self.opts.pooling_async_stack_keep_resident]
916 size => cfg.async_stack_keep_resident(size),
917 _ => err,
918 }
919 if let Some(max) = self.opts.pooling_max_component_instance_size {
920 cfg.max_component_instance_size(max);
921 }
922 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
923 cfg.max_core_instances_per_component(max);
924 }
925 if let Some(max) = self.opts.pooling_max_memories_per_component {
926 cfg.max_memories_per_component(max);
927 }
928 if let Some(max) = self.opts.pooling_max_tables_per_component {
929 cfg.max_tables_per_component(max);
930 }
931 if let Some(max) = self.opts.pooling_max_tables_per_module {
932 cfg.max_tables_per_module(max);
933 }
934 if let Some(max) = self.opts.pooling_max_memories_per_module {
935 cfg.max_memories_per_module(max);
936 }
937 match_feature! {
938 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
939 enable => cfg.memory_protection_keys(enable),
940 _ => err,
941 }
942 match_feature! {
943 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
944 max => cfg.max_memory_protection_keys(max),
945 _ => err,
946 }
947 match_feature! {
948 ["gc" : self.opts.pooling_total_gc_heaps]
949 max => cfg.total_gc_heaps(max),
950 _ => err,
951 }
952 if let Some(enabled) = self.opts.pooling_pagemap_scan {
953 cfg.pagemap_scan(enabled);
954 }
955 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
956 }
957 },
958 true => err,
959 }
960
961 if self.opts.pooling_memory_protection_keys.is_some()
962 && !self.opts.pooling_allocator.unwrap_or(false)
963 {
964 anyhow::bail!("memory protection keys require the pooling allocator");
965 }
966
967 if self.opts.pooling_max_memory_protection_keys.is_some()
968 && !self.opts.pooling_memory_protection_keys.is_some()
969 {
970 anyhow::bail!(
971 "max memory protection keys requires memory protection keys to be enabled"
972 );
973 }
974
975 match_feature! {
976 ["async" : self.wasm.async_stack_zeroing]
977 enable => config.async_stack_zeroing(enable),
978 _ => err,
979 }
980
981 if let Some(max) = self.wasm.max_wasm_stack {
982 config.max_wasm_stack(max);
983
984 #[cfg(any(feature = "async", feature = "stack-switching"))]
988 if self.wasm.async_stack_size.is_none() {
989 const DEFAULT_HOST_STACK: usize = 512 << 10;
990 config.async_stack_size(max + DEFAULT_HOST_STACK);
991 }
992 }
993
994 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
995 config.relaxed_simd_deterministic(enable);
996 }
997 match_feature! {
998 ["cranelift" : self.wasm.wmemcheck]
999 enable => config.wmemcheck(enable),
1000 true => err,
1001 }
1002
1003 if let Some(enable) = self.wasm.gc_support {
1004 config.gc_support(enable);
1005 }
1006
1007 Ok(config)
1008 }
1009
1010 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1011 let all = self.wasm.all_proposals;
1012
1013 if let Some(enable) = self.wasm.simd.or(all) {
1014 config.wasm_simd(enable);
1015 }
1016 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1017 config.wasm_relaxed_simd(enable);
1018 }
1019 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1020 config.wasm_bulk_memory(enable);
1021 }
1022 if let Some(enable) = self.wasm.multi_value.or(all) {
1023 config.wasm_multi_value(enable);
1024 }
1025 if let Some(enable) = self.wasm.tail_call.or(all) {
1026 config.wasm_tail_call(enable);
1027 }
1028 if let Some(enable) = self.wasm.multi_memory.or(all) {
1029 config.wasm_multi_memory(enable);
1030 }
1031 if let Some(enable) = self.wasm.memory64.or(all) {
1032 config.wasm_memory64(enable);
1033 }
1034 if let Some(enable) = self.wasm.stack_switching {
1035 config.wasm_stack_switching(enable);
1036 }
1037 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1038 config.wasm_custom_page_sizes(enable);
1039 }
1040 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1041 config.wasm_wide_arithmetic(enable);
1042 }
1043 if let Some(enable) = self.wasm.extended_const.or(all) {
1044 config.wasm_extended_const(enable);
1045 }
1046
1047 macro_rules! handle_conditionally_compiled {
1048 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1049 if let Some(enable) = self.wasm.$field.or(all) {
1050 #[cfg(feature = $feature)]
1051 config.$method(enable);
1052 #[cfg(not(feature = $feature))]
1053 if enable && all.is_none() {
1054 anyhow::bail!("support for {} was disabled at compile-time", $feature);
1055 }
1056 }
1057 )*)
1058 }
1059
1060 handle_conditionally_compiled! {
1061 ("component-model", component_model, wasm_component_model)
1062 ("component-model-async", component_model_async, wasm_component_model_async)
1063 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins)
1064 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1065 ("component-model-async", component_model_threading, wasm_component_model_threading)
1066 ("component-model", component_model_error_context, wasm_component_model_error_context)
1067 ("threads", threads, wasm_threads)
1068 ("gc", gc, wasm_gc)
1069 ("gc", reference_types, wasm_reference_types)
1070 ("gc", function_references, wasm_function_references)
1071 ("gc", exceptions, wasm_exceptions)
1072 ("stack-switching", stack_switching, wasm_stack_switching)
1073 }
1074
1075 if let Some(enable) = self.wasm.component_model_gc {
1076 #[cfg(all(feature = "component-model", feature = "gc"))]
1077 config.wasm_component_model_gc(enable);
1078 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1079 if enable && all.is_none() {
1080 anyhow::bail!("support for `component-model-gc` was disabled at compile time")
1081 }
1082 }
1083
1084 Ok(())
1085 }
1086
1087 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
1088 let path_ref = path.as_ref();
1089 let file_contents = fs::read_to_string(path_ref)
1090 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1091 toml::from_str::<CommonOptions>(&file_contents)
1092 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1093 }
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098 use wasmtime::{OptLevel, RegallocAlgorithm};
1099
1100 use super::*;
1101
1102 #[test]
1103 fn from_toml() {
1104 let empty_toml = "";
1106 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1107 common_options.config(None).unwrap();
1108
1109 let basic_toml = r#"
1111 [optimize]
1112 [codegen]
1113 [debug]
1114 [wasm]
1115 [wasi]
1116 "#;
1117 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1118 common_options.config(None).unwrap();
1119
1120 for (opt_value, expected) in [
1122 ("0", Some(OptLevel::None)),
1123 ("1", Some(OptLevel::Speed)),
1124 ("2", Some(OptLevel::Speed)),
1125 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1126 ("\"hello\"", None), ("3", None), ] {
1129 let toml = format!(
1130 r#"
1131 [optimize]
1132 opt-level = {opt_value}
1133 "#,
1134 );
1135 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1136 .ok()
1137 .and_then(|common_options| common_options.opts.opt_level);
1138
1139 assert_eq!(
1140 parsed_opt_level, expected,
1141 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1142 );
1143 }
1144
1145 for (regalloc_value, expected) in [
1147 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1148 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1149 ("\"hello\"", None), ("3", None), ("true", None), ] {
1153 let toml = format!(
1154 r#"
1155 [optimize]
1156 regalloc-algorithm = {regalloc_value}
1157 "#,
1158 );
1159 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1160 .ok()
1161 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1162 assert_eq!(
1163 parsed_regalloc_algorithm, expected,
1164 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1165 );
1166 }
1167
1168 for (strategy_value, expected) in [
1170 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1171 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1172 ("\"hello\"", None), ("5", None), ("true", None), ] {
1176 let toml = format!(
1177 r#"
1178 [codegen]
1179 compiler = {strategy_value}
1180 "#,
1181 );
1182 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1183 .ok()
1184 .and_then(|common_options| common_options.codegen.compiler);
1185 assert_eq!(
1186 parsed_strategy, expected,
1187 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1188 );
1189 }
1190
1191 for (collector_value, expected) in [
1193 (
1194 "\"drc\"",
1195 Some(wasmtime::Collector::DeferredReferenceCounting),
1196 ),
1197 ("\"null\"", Some(wasmtime::Collector::Null)),
1198 ("\"hello\"", None), ("5", None), ("true", None), ] {
1202 let toml = format!(
1203 r#"
1204 [codegen]
1205 collector = {collector_value}
1206 "#,
1207 );
1208 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1209 .ok()
1210 .and_then(|common_options| common_options.codegen.collector);
1211 assert_eq!(
1212 parsed_collector, expected,
1213 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1214 );
1215 }
1216 }
1217}
1218
1219impl Default for CommonOptions {
1220 fn default() -> CommonOptions {
1221 CommonOptions::new()
1222 }
1223}
1224
1225impl fmt::Display for CommonOptions {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 let CommonOptions {
1228 codegen_raw,
1229 codegen,
1230 debug_raw,
1231 debug,
1232 opts_raw,
1233 opts,
1234 wasm_raw,
1235 wasm,
1236 wasi_raw,
1237 wasi,
1238 configured,
1239 target,
1240 config,
1241 } = self;
1242 if let Some(target) = target {
1243 write!(f, "--target {target} ")?;
1244 }
1245 if let Some(config) = config {
1246 write!(f, "--config {} ", config.display())?;
1247 }
1248
1249 let codegen_flags;
1250 let opts_flags;
1251 let wasi_flags;
1252 let wasm_flags;
1253 let debug_flags;
1254
1255 if *configured {
1256 codegen_flags = codegen.to_options();
1257 debug_flags = debug.to_options();
1258 wasi_flags = wasi.to_options();
1259 wasm_flags = wasm.to_options();
1260 opts_flags = opts.to_options();
1261 } else {
1262 codegen_flags = codegen_raw
1263 .iter()
1264 .flat_map(|t| t.0.iter())
1265 .cloned()
1266 .collect();
1267 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1268 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1269 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1270 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1271 }
1272
1273 for flag in codegen_flags {
1274 write!(f, "-C{flag} ")?;
1275 }
1276 for flag in opts_flags {
1277 write!(f, "-O{flag} ")?;
1278 }
1279 for flag in wasi_flags {
1280 write!(f, "-S{flag} ")?;
1281 }
1282 for flag in wasm_flags {
1283 write!(f, "-W{flag} ")?;
1284 }
1285 for flag in debug_flags {
1286 write!(f, "-D{flag} ")?;
1287 }
1288
1289 Ok(())
1290 }
1291}