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