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