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