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