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