1use std::num::NonZeroUsize;
15use std::{fmt, num::NonZeroU32, path::PathBuf, time::Duration};
16use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};
17
18pub mod opt;
19
20#[cfg(feature = "logging")]
21fn init_file_per_thread_logger(prefix: &'static str) {
22 file_per_thread_logger::initialize(prefix);
23 file_per_thread_logger::allow_uninitialized();
24
25 #[cfg(feature = "parallel-compilation")]
30 rayon::ThreadPoolBuilder::new()
31 .spawn_handler(move |thread| {
32 let mut b = std::thread::Builder::new();
33 if let Some(name) = thread.name() {
34 b = b.name(name.to_owned());
35 }
36 if let Some(stack_size) = thread.stack_size() {
37 b = b.stack_size(stack_size);
38 }
39 b.spawn(move || {
40 file_per_thread_logger::initialize(prefix);
41 thread.run()
42 })?;
43 Ok(())
44 })
45 .build_global()
46 .unwrap();
47}
48
49wasmtime_option_group! {
50 #[env = "OPTIMIZE"]
51 pub struct OptimizeOptions {
52 #[serde(default)]
54 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
55 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
56 pub opt_level: Option<wasmtime::OptLevel>,
57
58 #[serde(default)]
60 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
61 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
62 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
63
64 pub memory_may_move: Option<bool>,
67
68 pub memory_reservation: Option<u64>,
70
71 pub memory_reservation_for_growth: Option<u64>,
73
74 pub memory_guard_size: Option<u64>,
76
77 pub gc_heap_may_move: Option<bool>,
80
81 pub gc_heap_reservation: Option<u64>,
83
84 pub gc_heap_reservation_for_growth: Option<u64>,
86
87 pub gc_heap_guard_size: Option<u64>,
89
90 pub gc_heap_initial_size: Option<u64>,
92
93 pub guard_before_linear_memory: Option<bool>,
96
97 pub table_lazy_init: Option<bool>,
102
103 pub pooling_allocator: Option<bool>,
105
106 pub pooling_decommit_batch_size: Option<usize>,
109
110 pub pooling_memory_keep_resident: Option<usize>,
113
114 pub pooling_table_keep_resident: Option<usize>,
117
118 #[serde(default)]
121 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
122 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
123 pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
124
125 pub pooling_max_memory_protection_keys: Option<usize>,
128
129 pub memory_init_cow: Option<bool>,
132
133 pub memory_guaranteed_dense_image_size: Option<u64>,
136
137 pub pooling_total_core_instances: Option<u32>,
140
141 pub pooling_total_component_instances: Option<u32>,
144
145 pub pooling_total_memories: Option<u32>,
148
149 pub pooling_total_tables: Option<u32>,
152
153 pub pooling_total_stacks: Option<u32>,
156
157 pub pooling_max_memory_size: Option<usize>,
160
161 pub pooling_table_elements: Option<usize>,
164
165 pub pooling_max_core_instance_size: Option<usize>,
168
169 pub pooling_max_unused_warm_slots: Option<u32>,
172
173 pub pooling_async_stack_keep_resident: Option<usize>,
176
177 pub pooling_max_component_instance_size: Option<usize>,
180
181 pub pooling_max_core_instances_per_component: Option<u32>,
184
185 pub pooling_max_memories_per_component: Option<u32>,
188
189 pub pooling_max_tables_per_component: Option<u32>,
192
193 pub pooling_max_tables_per_module: Option<u32>,
195
196 pub pooling_max_memories_per_module: Option<u32>,
198
199 pub pooling_total_gc_heaps: Option<u32>,
201
202 pub signals_based_traps: Option<bool>,
204
205 pub dynamic_memory_guard_size: Option<u64>,
207
208 pub static_memory_guard_size: Option<u64>,
210
211 pub static_memory_forced: Option<bool>,
213
214 pub static_memory_maximum_size: Option<u64>,
216
217 pub dynamic_memory_reserved_for_growth: Option<u64>,
219
220 #[serde(default)]
223 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
224 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
225 pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
226
227 #[doc(hidden)]
229 pub gc_zeal_alloc_counter: Option<NonZeroU32>,
230 }
231
232 enum Optimize {
233 ...
234 }
235}
236
237wasmtime_option_group! {
238 #[env = "CODEGEN"]
239 pub struct CodegenOptions {
240 #[serde(default)]
245 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
246 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
247 pub compiler: Option<wasmtime::Strategy>,
248 #[serde(default)]
260 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
261 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
262 pub collector: Option<wasmtime::Collector>,
263 pub cranelift_debug_verifier: Option<bool>,
265 pub cache: Option<bool>,
267 pub cache_config: Option<String>,
269 pub parallel_compilation: Option<bool>,
271 pub native_unwind_info: Option<bool>,
274 pub asan_compatible_code: Option<bool>,
278
279 #[serde(default)]
281 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
282 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
283 pub inlining: Option<wasmtime::Inlining>,
284
285 pub metadata_for_internal_asserts: Option<bool>,
288 pub metadata_for_gc_heap_corruption: Option<bool>,
291
292 #[serde(default)]
312 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
313 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
314 pub unsafe_intrinsics: Option<UnsafeIntrinsicsImport>,
315
316 #[serde(skip)]
339 pub compile_time_builtin: Vec<CompileTimeBuiltin>,
340
341 #[prefixed = "cranelift"]
342 #[serde(default)]
343 pub cranelift: Vec<(String, Option<String>)>,
346 }
347
348 enum Codegen {
349 ...
350 }
351}
352
353wasmtime_option_group! {
354 #[env = "DEBUG"]
355 pub struct DebugOptions {
356 pub debug_info: Option<bool>,
358 pub guest_debug: Option<bool>,
360 pub address_map: Option<bool>,
362 pub logging: Option<bool>,
364 pub log_to_files: Option<bool>,
366 pub coredump: Option<String>,
368 pub debugger: Option<PathBuf>,
371 #[serde(default)]
374 pub arg: Vec<String>,
375 pub inherit_stdin: Option<bool>,
378 pub inherit_stdout: Option<bool>,
381 pub inherit_stderr: Option<bool>,
384 pub max_backtrace: Option<usize>,
386 pub symbols: Option<bool>,
388 }
389
390 enum Debug {
391 ...
392 }
393}
394
395wasmtime_option_group! {
396 #[env = "WASM"]
397 pub struct WasmOptions {
398 pub nan_canonicalization: Option<bool>,
400 pub fuel: Option<u64>,
408 pub epoch_interruption: Option<bool>,
411 pub max_wasm_stack: Option<usize>,
414 pub async_stack_size: Option<usize>,
420 pub async_stack_zeroing: Option<bool>,
423 pub unknown_exports_allow: Option<bool>,
425 pub unknown_imports_trap: Option<bool>,
428 pub unknown_imports_default: Option<bool>,
431 pub wmemcheck: Option<bool>,
433 pub max_memory_size: Option<usize>,
438 pub max_table_elements: Option<usize>,
440 pub max_instances: Option<usize>,
442 pub max_tables: Option<usize>,
444 pub max_memories: Option<usize>,
446 pub trap_on_grow_failure: Option<bool>,
453 pub timeout: Option<Duration>,
459 pub all_proposals: Option<bool>,
461 pub bulk_memory: Option<bool>,
463 pub multi_memory: Option<bool>,
465 pub multi_value: Option<bool>,
467 pub reference_types: Option<bool>,
469 pub simd: Option<bool>,
471 pub relaxed_simd: Option<bool>,
473 pub relaxed_simd_deterministic: Option<bool>,
482 pub tail_call: Option<bool>,
484 pub threads: Option<bool>,
486 pub shared_memory: Option<bool>,
488 pub shared_everything_threads: Option<bool>,
490 pub memory64: Option<bool>,
492 pub component_model: Option<bool>,
494 pub component_model_async: Option<bool>,
496 pub component_model_more_async_builtins: Option<bool>,
499 pub component_model_async_stackful: Option<bool>,
502 pub component_model_threading: Option<bool>,
505 pub component_model_error_context: Option<bool>,
508 pub component_model_gc: Option<bool>,
511 pub component_model_map: Option<bool>,
514 pub component_model_memory64: Option<bool>,
517 pub function_references: Option<bool>,
519 pub stack_switching: Option<bool>,
521 pub gc: Option<bool>,
523 pub custom_page_sizes: Option<bool>,
525 pub wide_arithmetic: Option<bool>,
527 pub branch_hinting: Option<bool>,
529 pub compact_imports: Option<bool>,
531 pub extended_const: Option<bool>,
533 pub exceptions: Option<bool>,
535 pub gc_support: Option<bool>,
537 pub component_model_fixed_length_lists: Option<bool>,
540 pub component_model_implements: Option<bool>,
544 pub component_model_canonical_names: Option<bool>,
547 pub component_model_accessors: Option<bool>,
550 pub concurrency_support: Option<bool>,
553 }
554
555 enum Wasm {
556 ...
557 }
558}
559
560wasmtime_option_group! {
561 #[env = "WASI"]
562 pub struct WasiOptions {
563 pub cli: Option<bool>,
565 pub cli_exit_with_code: Option<bool>,
567 pub common: Option<bool>,
569 pub nn: Option<bool>,
571 pub threads: Option<bool>,
573 pub http: Option<bool>,
575 pub http_outgoing_body_buffer_chunks: Option<NonZeroUsize>,
579 pub http_outgoing_body_chunk_size: Option<NonZeroUsize>,
582 pub config: Option<bool>,
584 pub keyvalue: Option<bool>,
586 #[serde(default)]
589 pub tcplisten: Vec<String>,
590 pub tls: Option<bool>,
592 pub preview2: Option<bool>,
595 #[serde(skip)]
604 pub nn_graph: Vec<WasiNnGraph>,
605 pub inherit_network: Option<bool>,
608 pub allow_ip_name_lookup: Option<bool>,
610 pub tcp: Option<bool>,
612 pub udp: Option<bool>,
614 pub network_error_code: Option<bool>,
616 pub preview0: Option<bool>,
618 pub inherit_env: Option<bool>,
622 pub inherit_stdin: Option<bool>,
624 pub inherit_stdout: Option<bool>,
626 pub inherit_stderr: Option<bool>,
628 pub cwd: Option<String>,
630 #[serde(skip)]
632 pub config_var: Vec<KeyValuePair>,
633 #[serde(skip)]
635 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
636 pub p3: Option<bool>,
638 pub max_resources: Option<usize>,
640 pub hostcall_fuel: Option<usize>,
642 pub max_io_size: Option<NonZeroUsize>,
646 pub max_component_handles: Option<usize>,
650 pub max_fibers: Option<u32>,
652 pub max_random_size: Option<u64>,
656 pub max_http_fields_size: Option<usize>,
660 }
661
662 enum Wasi {
663 ...
664 }
665}
666
667wasmtime_option_group! {
668 #[env = "RECORD"]
669 pub struct RecordOptions {
670 pub path: Option<String>,
672 pub validation_metadata: Option<bool>,
675 pub event_window_size: Option<usize>,
678 }
679
680 enum Record {
681 ...
682 }
683}
684
685#[derive(Debug, Clone, PartialEq)]
686pub struct WasiNnGraph {
687 pub format: String,
688 pub dir: String,
689}
690
691#[derive(Debug, Clone, PartialEq)]
692pub struct KeyValuePair {
693 pub key: String,
694 pub value: String,
695}
696
697#[derive(Debug, Clone, PartialEq)]
700pub struct UnsafeIntrinsicsImport(pub String);
701
702#[derive(Debug, Clone, PartialEq)]
704pub struct CompileTimeBuiltin {
705 pub name: String,
707 pub path: PathBuf,
709}
710
711#[derive(Clone)]
713#[cfg_attr(feature = "clap", derive(clap::Parser))]
714#[cfg_attr(
715 feature = "serde",
716 derive(serde_derive::Deserialize, serde_derive::Serialize)
717)]
718#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
719pub struct CommonOptions {
720 #[cfg_attr(
730 feature = "clap",
731 arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
732 )]
733 #[cfg_attr(feature = "serde", serde(skip))]
734 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
735
736 #[cfg_attr(
738 feature = "clap",
739 arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
740 )]
741 #[cfg_attr(feature = "serde", serde(skip))]
742 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
743
744 #[cfg_attr(
746 feature = "clap",
747 arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
748 )]
749 #[cfg_attr(feature = "serde", serde(skip))]
750 debug_raw: Vec<opt::CommaSeparated<Debug>>,
751
752 #[cfg_attr(
755 feature = "clap",
756 arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
757 )]
758 #[cfg_attr(feature = "serde", serde(skip))]
759 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
760
761 #[cfg_attr(
763 feature = "clap",
764 arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
765 )]
766 #[cfg_attr(feature = "serde", serde(skip))]
767 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
768
769 #[cfg_attr(
778 feature = "clap",
779 arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
780 )]
781 #[cfg_attr(feature = "serde", serde(skip))]
782 record_raw: Vec<opt::CommaSeparated<Record>>,
783
784 #[cfg_attr(feature = "clap", arg(skip))]
787 #[cfg_attr(feature = "serde", serde(skip))]
788 configured: bool,
789
790 #[cfg_attr(feature = "clap", arg(skip))]
791 #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
792 pub opts: OptimizeOptions,
793
794 #[cfg_attr(feature = "clap", arg(skip))]
795 #[cfg_attr(feature = "serde", serde(default))]
796 pub codegen: CodegenOptions,
797
798 #[cfg_attr(feature = "clap", arg(skip))]
799 #[cfg_attr(feature = "serde", serde(default))]
800 pub debug: DebugOptions,
801
802 #[cfg_attr(feature = "clap", arg(skip))]
803 #[cfg_attr(feature = "serde", serde(default))]
804 pub wasm: WasmOptions,
805
806 #[cfg_attr(feature = "clap", arg(skip))]
807 #[cfg_attr(feature = "serde", serde(default))]
808 pub wasi: WasiOptions,
809
810 #[cfg_attr(feature = "clap", arg(skip))]
811 #[cfg_attr(feature = "serde", serde(default))]
812 pub record: RecordOptions,
813
814 #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
816 #[cfg_attr(feature = "serde", serde(skip))]
817 pub target: Option<String>,
818
819 #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
826 #[cfg_attr(feature = "serde", serde(skip))]
827 pub config: Option<PathBuf>,
828}
829
830macro_rules! match_feature {
831 (
832 [$feat:tt : $config:expr]
833 $val:ident => $e:expr,
834 $p:pat => err,
835 ) => {
836 #[cfg(feature = $feat)]
837 {
838 if let Some($val) = $config {
839 $e;
840 }
841 }
842 #[cfg(not(feature = $feat))]
843 {
844 if let Some($p) = $config {
845 bail!(concat!("support for ", $feat, " disabled at compile time"));
846 }
847 }
848 };
849}
850
851impl CommonOptions {
852 pub fn new() -> CommonOptions {
854 CommonOptions {
855 opts_raw: Vec::new(),
856 codegen_raw: Vec::new(),
857 debug_raw: Vec::new(),
858 wasm_raw: Vec::new(),
859 wasi_raw: Vec::new(),
860 record_raw: Vec::new(),
861 configured: true,
862 opts: Default::default(),
863 codegen: Default::default(),
864 debug: Default::default(),
865 wasm: Default::default(),
866 wasi: Default::default(),
867 record: Default::default(),
868 target: None,
869 config: None,
870 }
871 }
872
873 fn configure(&mut self) -> Result<()> {
874 if self.configured {
875 return Ok(());
876 }
877 self.configured = true;
878 if let Some(toml_config_path) = &self.config {
879 #[cfg(feature = "toml")]
880 {
881 let toml_options = CommonOptions::from_file(toml_config_path)?;
882 self.opts = toml_options.opts;
883 self.codegen = toml_options.codegen;
884 self.debug = toml_options.debug;
885 self.wasm = toml_options.wasm;
886 self.wasi = toml_options.wasi;
887 self.record = toml_options.record;
888 }
889 #[cfg(not(feature = "toml"))]
890 {
891 bail!(
892 "support for loading a configuration file from \
893 {toml_config_path:?} disabled at compile time"
894 );
895 }
896 }
897 self.opts.configure_with(&self.opts_raw)?;
898 self.codegen.configure_with(&self.codegen_raw)?;
899 self.debug.configure_with(&self.debug_raw)?;
900 self.wasm.configure_with(&self.wasm_raw)?;
901 self.wasi.configure_with(&self.wasi_raw)?;
902 self.record.configure_with(&self.record_raw)?;
903 Ok(())
904 }
905
906 pub fn init_logging(&mut self) -> Result<()> {
907 self.configure()?;
908 if self.debug.logging == Some(false) {
909 return Ok(());
910 }
911 #[cfg(feature = "logging")]
912 if self.debug.log_to_files == Some(true) {
913 let prefix = "wasmtime.dbg.";
914 init_file_per_thread_logger(prefix);
915 } else {
916 use std::io::IsTerminal;
917 use tracing_subscriber::{EnvFilter, FmtSubscriber};
918 let builder = FmtSubscriber::builder()
919 .with_writer(std::io::stderr)
920 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
921 .with_ansi(std::io::stderr().is_terminal());
922 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
923 builder
924 .with_level(false)
925 .with_target(false)
926 .without_time()
927 .init()
928 } else {
929 builder.init();
930 }
931 }
932 #[cfg(not(feature = "logging"))]
933 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
934 bail!("support for logging disabled at compile time");
935 }
936 Ok(())
937 }
938
939 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
940 self.configure()?;
941 let mut config = Config::new();
942
943 match_feature! {
944 ["cranelift" : self.codegen.compiler]
945 strategy => config.strategy(strategy),
946 _ => err,
947 }
948 match_feature! {
949 ["gc" : self.codegen.collector]
950 collector => config.collector(collector),
951 _ => err,
952 }
953 if let Some(target) = &self.target {
954 config.target(target)?;
955 }
956 match_feature! {
957 ["cranelift" : self.codegen.cranelift_debug_verifier]
958 enable => config.cranelift_debug_verifier(enable),
959 true => err,
960 }
961 if let Some(enable) = self.debug.debug_info {
962 config.debug_info(enable);
963 }
964 match_feature! {
965 ["debug" : self.debug.guest_debug]
966 enable => config.guest_debug(enable),
967 _ => err,
968 }
969 if self.debug.coredump.is_some() {
970 #[cfg(feature = "coredump")]
971 config.coredump_on_trap(true);
972 #[cfg(not(feature = "coredump"))]
973 bail!("support for coredumps disabled at compile time");
974 }
975 match_feature! {
976 ["cranelift" : self.opts.opt_level]
977 level => config.cranelift_opt_level(level),
978 _ => err,
979 }
980 match_feature! {
981 ["cranelift": self.opts.regalloc_algorithm]
982 algo => config.cranelift_regalloc_algorithm(algo),
983 _ => err,
984 }
985 match_feature! {
986 ["cranelift" : self.wasm.nan_canonicalization]
987 enable => config.cranelift_nan_canonicalization(enable),
988 true => err,
989 }
990
991 self.enable_wasm_features(&mut config)?;
992
993 #[cfg(feature = "cranelift")]
994 for (name, value) in self.codegen.cranelift.iter() {
995 let name = name.replace('-', "_");
996 unsafe {
997 match value {
998 Some(val) => {
999 config.cranelift_flag_set(&name, val);
1000 }
1001 None => {
1002 config.cranelift_flag_enable(&name);
1003 }
1004 }
1005 }
1006 }
1007 #[cfg(not(feature = "cranelift"))]
1008 if !self.codegen.cranelift.is_empty() {
1009 bail!("support for cranelift disabled at compile time");
1010 }
1011
1012 #[cfg(feature = "cache")]
1013 if self.codegen.cache != Some(false) {
1014 use wasmtime::Cache;
1015 let cache = match &self.codegen.cache_config {
1016 Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
1017 None => Cache::from_file(None)?,
1018 };
1019 config.cache(Some(cache));
1020 }
1021 #[cfg(not(feature = "cache"))]
1022 if self.codegen.cache == Some(true) {
1023 bail!("support for caching disabled at compile time");
1024 }
1025
1026 match_feature! {
1027 ["parallel-compilation" : self.codegen.parallel_compilation]
1028 enable => config.parallel_compilation(enable),
1029 true => err,
1030 }
1031
1032 let memory_reservation = self
1033 .opts
1034 .memory_reservation
1035 .or(self.opts.static_memory_maximum_size);
1036 if let Some(size) = memory_reservation {
1037 config.memory_reservation(size);
1038 }
1039
1040 if let Some(enable) = self.opts.static_memory_forced {
1041 config.memory_may_move(!enable);
1042 }
1043 if let Some(enable) = self.opts.memory_may_move {
1044 config.memory_may_move(enable);
1045 }
1046
1047 let memory_guard_size = self
1048 .opts
1049 .static_memory_guard_size
1050 .or(self.opts.dynamic_memory_guard_size)
1051 .or(self.opts.memory_guard_size);
1052 if let Some(size) = memory_guard_size {
1053 config.memory_guard_size(size);
1054 }
1055
1056 let mem_for_growth = self
1057 .opts
1058 .memory_reservation_for_growth
1059 .or(self.opts.dynamic_memory_reserved_for_growth);
1060 if let Some(size) = mem_for_growth {
1061 config.memory_reservation_for_growth(size);
1062 }
1063 if let Some(enable) = self.opts.guard_before_linear_memory {
1064 config.guard_before_linear_memory(enable);
1065 }
1066
1067 if let Some(size) = self.opts.gc_heap_reservation {
1068 config.gc_heap_reservation(size);
1069 }
1070 if let Some(enable) = self.opts.gc_heap_may_move {
1071 config.gc_heap_may_move(enable);
1072 }
1073 if let Some(size) = self.opts.gc_heap_guard_size {
1074 config.gc_heap_guard_size(size);
1075 }
1076 if let Some(size) = self.opts.gc_heap_reservation_for_growth {
1077 config.gc_heap_reservation_for_growth(size);
1078 }
1079
1080 if let Some(size) = self.opts.gc_heap_initial_size {
1081 config.gc_heap_initial_size(size);
1082 }
1083
1084 if let Some(enable) = self.opts.table_lazy_init {
1085 config.table_lazy_init(enable);
1086 }
1087
1088 if let Some(n) = self.opts.gc_zeal_alloc_counter
1089 && (cfg!(gc_zeal) || cfg!(fuzzing))
1090 {
1091 config.gc_zeal_alloc_counter(Some(n))?;
1092 }
1093
1094 if self.wasm.fuel.is_some() {
1096 config.consume_fuel(true);
1097 }
1098
1099 if let Some(enable) = self.wasm.epoch_interruption {
1100 config.epoch_interruption(enable);
1101 }
1102 if let Some(enable) = self.debug.address_map {
1103 config.generate_address_map(enable);
1104 }
1105 if let Some(frames) = self.debug.max_backtrace {
1106 match NonZeroUsize::new(frames) {
1107 None => {
1108 config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1109 }
1110 Some(amt) => {
1111 config.wasm_backtrace_max_frames(Some(amt));
1112 }
1113 }
1114 }
1115 if let Some(enable) = self.debug.symbols {
1116 config.debug_symbols(enable);
1117 }
1118 if let Some(enable) = self.opts.memory_init_cow {
1119 config.memory_init_cow(enable);
1120 }
1121 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1122 config.memory_guaranteed_dense_image_size(size);
1123 }
1124 if let Some(enable) = self.opts.signals_based_traps {
1125 config.signals_based_traps(enable);
1126 }
1127 if let Some(enable) = self.codegen.native_unwind_info {
1128 config.native_unwind_info(enable);
1129 }
1130 if let Some(enable) = self.codegen.asan_compatible_code {
1131 config.asan_compatible_code(enable);
1132 }
1133 if let Some(enable) = self.codegen.inlining {
1134 config.compiler_inlining(enable);
1135 }
1136 if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1137 config.metadata_for_internal_asserts(enable);
1138 }
1139 if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1140 config.metadata_for_gc_heap_corruption(enable);
1141 }
1142
1143 #[cfg(any(feature = "async", feature = "stack-switching"))]
1146 {
1147 if let Some(size) = self.wasm.async_stack_size {
1148 config.async_stack_size(size);
1149 }
1150 }
1151 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1152 {
1153 if let Some(_size) = self.wasm.async_stack_size {
1154 bail!(concat!(
1155 "support for async/stack-switching disabled at compile time"
1156 ));
1157 }
1158 }
1159
1160 match_feature! {
1161 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1162 enable => {
1163 if enable {
1164 let mut cfg = wasmtime::PoolingAllocationConfig::default();
1165 if let Some(size) = self.opts.pooling_memory_keep_resident {
1166 cfg.linear_memory_keep_resident(size);
1167 }
1168 if let Some(size) = self.opts.pooling_table_keep_resident {
1169 cfg.table_keep_resident(size);
1170 }
1171 if let Some(limit) = self.opts.pooling_total_core_instances {
1172 cfg.total_core_instances(limit);
1173 }
1174 if let Some(limit) = self.opts.pooling_total_component_instances {
1175 cfg.total_component_instances(limit);
1176 }
1177 if let Some(limit) = self.opts.pooling_total_memories {
1178 cfg.total_memories(limit);
1179 }
1180 if let Some(limit) = self.opts.pooling_total_tables {
1181 cfg.total_tables(limit);
1182 }
1183 if let Some(limit) = self.opts.pooling_table_elements
1184 .or(self.wasm.max_table_elements)
1185 {
1186 cfg.table_elements(limit);
1187 }
1188 if let Some(limit) = self.opts.pooling_max_core_instance_size {
1189 cfg.max_core_instance_size(limit);
1190 }
1191 match_feature! {
1192 ["async" : self.opts.pooling_total_stacks]
1193 limit => cfg.total_stacks(limit),
1194 _ => err,
1195 }
1196 if let Some(max) = self.opts.pooling_max_memory_size
1197 .or(self.wasm.max_memory_size)
1198 {
1199 cfg.max_memory_size(max);
1200 }
1201 if let Some(size) = self.opts.pooling_decommit_batch_size {
1202 cfg.decommit_batch_size(size);
1203 }
1204 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1205 cfg.max_unused_warm_slots(max);
1206 }
1207 match_feature! {
1208 ["async" : self.opts.pooling_async_stack_keep_resident]
1209 size => cfg.async_stack_keep_resident(size),
1210 _ => err,
1211 }
1212 if let Some(max) = self.opts.pooling_max_component_instance_size {
1213 cfg.max_component_instance_size(max);
1214 }
1215 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1216 cfg.max_core_instances_per_component(max);
1217 }
1218 if let Some(max) = self.opts.pooling_max_memories_per_component {
1219 cfg.max_memories_per_component(max);
1220 }
1221 if let Some(max) = self.opts.pooling_max_tables_per_component {
1222 cfg.max_tables_per_component(max);
1223 }
1224 if let Some(max) = self.opts.pooling_max_tables_per_module {
1225 cfg.max_tables_per_module(max);
1226 }
1227 if let Some(max) = self.opts.pooling_max_memories_per_module {
1228 cfg.max_memories_per_module(max);
1229 }
1230 match_feature! {
1231 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1232 enable => cfg.memory_protection_keys(enable),
1233 _ => err,
1234 }
1235 match_feature! {
1236 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1237 max => cfg.max_memory_protection_keys(max),
1238 _ => err,
1239 }
1240 match_feature! {
1241 ["gc" : self.opts.pooling_total_gc_heaps]
1242 max => cfg.total_gc_heaps(max),
1243 _ => err,
1244 }
1245 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1246 cfg.pagemap_scan(enabled);
1247 }
1248 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1249 }
1250 },
1251 true => err,
1252 }
1253
1254 if self.opts.pooling_memory_protection_keys.is_some()
1255 && !self.opts.pooling_allocator.unwrap_or(false)
1256 {
1257 bail!("memory protection keys require the pooling allocator");
1258 }
1259
1260 if self.opts.pooling_max_memory_protection_keys.is_some()
1261 && !self.opts.pooling_memory_protection_keys.is_some()
1262 {
1263 bail!("max memory protection keys requires memory protection keys to be enabled");
1264 }
1265
1266 match_feature! {
1267 ["async" : self.wasm.async_stack_zeroing]
1268 enable => config.async_stack_zeroing(enable),
1269 _ => err,
1270 }
1271
1272 if let Some(max) = self.wasm.max_wasm_stack {
1273 config.max_wasm_stack(max);
1274
1275 #[cfg(any(feature = "async", feature = "stack-switching"))]
1279 if self.wasm.async_stack_size.is_none() {
1280 const DEFAULT_HOST_STACK: usize = 512 << 10;
1281 config.async_stack_size(max.saturating_add(DEFAULT_HOST_STACK));
1282 }
1283 }
1284
1285 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1286 config.relaxed_simd_deterministic(enable);
1287 }
1288 match_feature! {
1289 ["cranelift" : self.wasm.wmemcheck]
1290 enable => config.wmemcheck(enable),
1291 true => err,
1292 }
1293
1294 if let Some(enable) = self.wasm.gc_support {
1295 config.gc_support(enable);
1296 }
1297
1298 if let Some(enable) = self.wasm.concurrency_support {
1299 config.concurrency_support(enable);
1300 }
1301
1302 if let Some(enable) = self.wasm.shared_memory {
1303 config.shared_memory(enable);
1304 }
1305
1306 let record = &self.record;
1307 match_feature! {
1308 ["rr" : &record.path]
1309 _path => {
1310 bail!("recording configuration for `rr` feature is not supported yet");
1311 },
1312 _ => err,
1313 }
1314
1315 Ok(config)
1316 }
1317
1318 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1319 let all = self.wasm.all_proposals;
1320
1321 if let Some(enable) = self.wasm.simd.or(all) {
1322 config.wasm_simd(enable);
1323 }
1324 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1325 config.wasm_relaxed_simd(enable);
1326 }
1327 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1328 config.wasm_bulk_memory(enable);
1329 }
1330 if let Some(enable) = self.wasm.multi_value.or(all) {
1331 config.wasm_multi_value(enable);
1332 }
1333 if let Some(enable) = self.wasm.tail_call.or(all) {
1334 config.wasm_tail_call(enable);
1335 }
1336 if let Some(enable) = self.wasm.multi_memory.or(all) {
1337 config.wasm_multi_memory(enable);
1338 }
1339 if let Some(enable) = self.wasm.memory64.or(all) {
1340 config.wasm_memory64(enable);
1341 }
1342 if let Some(enable) = self.wasm.stack_switching {
1343 config.wasm_stack_switching(enable);
1344 }
1345 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1346 config.wasm_custom_page_sizes(enable);
1347 }
1348 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1349 config.wasm_wide_arithmetic(enable);
1350 }
1351 if let Some(enable) = self.wasm.branch_hinting {
1353 config.wasm_branch_hinting(enable);
1354 }
1355 if let Some(enable) = self.wasm.compact_imports {
1357 config.wasm_compact_imports(enable);
1358 }
1359 if let Some(enable) = self.wasm.extended_const.or(all) {
1360 config.wasm_extended_const(enable);
1361 }
1362
1363 macro_rules! handle_conditionally_compiled {
1364 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1365 if let Some(enable) = self.wasm.$field.or(all) {
1366 #[cfg(feature = $feature)]
1367 config.$method(enable);
1368 #[cfg(not(feature = $feature))]
1369 if enable && all.is_none() {
1370 bail!("support for {} was disabled at compile-time", $feature);
1371 }
1372 }
1373 )*)
1374 }
1375
1376 handle_conditionally_compiled! {
1377 ("component-model", component_model, wasm_component_model)
1378 ("component-model-async", component_model_async, wasm_component_model_async)
1379 ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1380 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1381 ("component-model-async", component_model_threading, wasm_component_model_threading)
1382 ("component-model", component_model_error_context, wasm_component_model_error_context)
1383 ("component-model", component_model_map, wasm_component_model_map)
1384 ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1385 ("component-model", component_model_implements, wasm_component_model_implements)
1386 ("component-model", component_model_canonical_names, wasm_component_model_canonical_names)
1387 ("component-model", component_model_accessors, wasm_component_model_accessors)
1388 ("component-model", component_model_memory64, wasm_component_model_memory64)
1389 ("threads", threads, wasm_threads)
1390 ("gc", gc, wasm_gc)
1391 ("gc", reference_types, wasm_reference_types)
1392 ("gc", function_references, wasm_function_references)
1393 ("gc", exceptions, wasm_exceptions)
1394 ("stack-switching", stack_switching, wasm_stack_switching)
1395 }
1396
1397 if let Some(enable) = self.wasm.component_model_gc {
1398 #[cfg(all(feature = "component-model", feature = "gc"))]
1399 config.wasm_component_model_gc(enable);
1400 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1401 if enable && all.is_none() {
1402 bail!("support for `component-model-gc` was disabled at compile time")
1403 }
1404 }
1405
1406 Ok(())
1407 }
1408
1409 #[cfg(feature = "toml")]
1410 pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1411 use wasmtime::error::Context;
1412
1413 let path_ref = path.as_ref();
1414 let file_contents = std::fs::read_to_string(path_ref)
1415 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1416 toml::from_str::<CommonOptions>(&file_contents)
1417 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1418 }
1419
1420 pub fn from_engine(engine: &Engine) -> Self {
1433 let features = engine.get_wasm_features();
1434 let pooling = engine.get_pooling_config();
1435 CommonOptions {
1436 target: engine.get_target(),
1437 opts: OptimizeOptions {
1438 memory_may_move: Some(engine.get_memory_may_move()),
1439 memory_reservation: Some(engine.get_memory_reservation()),
1440 memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1441 memory_guard_size: Some(engine.get_memory_guard_size()),
1442 gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1443 gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1444 gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1445 gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1446 gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1447 guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1448 table_lazy_init: Some(engine.get_table_lazy_init()),
1449 memory_init_cow: Some(engine.get_memory_init_cow()),
1450 memory_guaranteed_dense_image_size: Some(
1451 engine.get_memory_guaranteed_dense_image_size(),
1452 ),
1453 signals_based_traps: Some(engine.get_signals_based_traps()),
1454 gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1455 opt_level: engine.get_cranelift_opt_level(),
1456 regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1457 pooling_allocator: Some(pooling.is_some()),
1458 pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1459 pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1460 pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1461 pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1462 pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1463 pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1464 pooling_total_component_instances: pooling
1465 .map(|c| c.get_total_component_instances()),
1466 pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1467 pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1468 pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1469 pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1470 pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1471 pooling_max_component_instance_size: pooling
1472 .map(|c| c.get_max_component_instance_size()),
1473 pooling_max_core_instances_per_component: pooling
1474 .map(|c| c.get_max_core_instances_per_component()),
1475 pooling_max_memories_per_component: pooling
1476 .map(|c| c.get_max_memories_per_component()),
1477 pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1478 pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1479 pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1480 pooling_async_stack_keep_resident: pooling
1481 .map(|c| c.get_async_stack_keep_resident()),
1482 pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1483 pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1484 pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1485 pooling_max_memory_protection_keys: pooling
1486 .map(|c| c.get_max_memory_protection_keys()),
1487 dynamic_memory_guard_size: None,
1490 static_memory_guard_size: None,
1491 static_memory_forced: None,
1492 static_memory_maximum_size: None,
1493 dynamic_memory_reserved_for_growth: None,
1494 },
1495 codegen: CodegenOptions {
1496 compiler: engine.get_strategy(),
1497 collector: engine.get_collector(),
1498 cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1499 inlining: Some(engine.get_compiler_inlining()),
1500 native_unwind_info: engine.get_native_unwind_info(),
1501 asan_compatible_code: Some(engine.get_asan_compatible_code()),
1502 parallel_compilation: Some(engine.get_parallel_compilation()),
1503 metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1504 metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1505 cranelift: engine
1506 .get_cranelift_flags_set()
1507 .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1508 .chain(
1509 engine
1510 .get_cranelift_flags_enabled()
1511 .map(|k| (k.to_string(), None)),
1512 )
1513 .collect(),
1514
1515 cache: None,
1518 cache_config: None,
1519
1520 unsafe_intrinsics: None,
1523 compile_time_builtin: Vec::new(),
1524 },
1525 debug: DebugOptions {
1526 address_map: Some(engine.get_generate_address_map()),
1527 debug_info: Some(engine.get_debug_info()),
1528 guest_debug: Some(engine.get_guest_debug()),
1529 symbols: Some(engine.get_debug_symbols()),
1530 max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1531
1532 coredump: None,
1535 debugger: None,
1537 arg: Vec::new(),
1538 inherit_stderr: None,
1539 inherit_stdout: None,
1540 inherit_stdin: None,
1541 log_to_files: None,
1543 logging: None,
1544 },
1545 wasm: WasmOptions {
1546 async_stack_size: Some(engine.get_async_stack_size()),
1547 async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1548 branch_hinting: Some(engine.get_wasm_branch_hinting()),
1549 compact_imports: Some(features.contains(WasmFeatures::COMPACT_IMPORTS)),
1550 bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1551 component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1552 component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1553 component_model_async_stackful: Some(
1554 features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1555 ),
1556 component_model_error_context: Some(
1557 features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1558 ),
1559 component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1560 component_model_fixed_length_lists: Some(
1561 features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1562 ),
1563 component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1564 component_model_canonical_names: Some(
1565 features.contains(WasmFeatures::CM_CANON_NAMES),
1566 ),
1567 component_model_accessors: Some(features.contains(WasmFeatures::CM_ACCESSORS)),
1568 component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1569 component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1570 component_model_more_async_builtins: Some(
1571 features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1572 ),
1573 component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1574 custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1575 exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1576 extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1577 function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1578 gc: Some(features.contains(WasmFeatures::GC)),
1579 gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1580 memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1581 multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1582 multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1583 reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1584 relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1585 shared_everything_threads: Some(
1586 features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1587 ),
1588 simd: Some(features.contains(WasmFeatures::SIMD)),
1589 stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1590 tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1591 threads: Some(features.contains(WasmFeatures::THREADS)),
1592 wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1593 concurrency_support: Some(engine.get_concurrency_support()),
1594 epoch_interruption: Some(engine.get_epoch_interruption()),
1595 fuel: if engine.get_consume_fuel() {
1596 Some(1)
1597 } else {
1598 None
1599 },
1600 max_wasm_stack: Some(engine.get_max_wasm_stack()),
1601 nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1602 relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1603 shared_memory: Some(engine.get_shared_memory()),
1604
1605 all_proposals: None,
1607 max_instances: None,
1610 max_memories: None,
1611 max_memory_size: None,
1612 max_table_elements: None,
1613 max_tables: None,
1614 timeout: None,
1616 trap_on_grow_failure: None,
1617 unknown_exports_allow: None,
1618 unknown_imports_default: None,
1619 unknown_imports_trap: None,
1620 wmemcheck: None,
1621 },
1622
1623 record: RecordOptions::default(),
1625
1626 wasi: Default::default(),
1628
1629 configured: true,
1631 codegen_raw: Default::default(),
1632 debug_raw: Default::default(),
1633 opts_raw: Default::default(),
1634 record_raw: Default::default(),
1635 wasi_raw: Default::default(),
1636 wasm_raw: Default::default(),
1637
1638 config: None,
1640 }
1645 }
1646}
1647
1648#[cfg(test)]
1649mod tests {
1650 use wasmtime::{OptLevel, RegallocAlgorithm};
1651
1652 use super::*;
1653
1654 #[test]
1655 fn from_toml() {
1656 let empty_toml = "";
1658 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1659 common_options.config(None).unwrap();
1660
1661 let basic_toml = r#"
1663 [optimize]
1664 [codegen]
1665 [debug]
1666 [wasm]
1667 [wasi]
1668 [record]
1669 "#;
1670 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1671 common_options.config(None).unwrap();
1672
1673 for (opt_value, expected) in [
1675 ("0", Some(OptLevel::None)),
1676 ("1", Some(OptLevel::Speed)),
1677 ("2", Some(OptLevel::Speed)),
1678 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1679 ("\"hello\"", None), ("3", None), ] {
1682 let toml = format!(
1683 r#"
1684 [optimize]
1685 opt-level = {opt_value}
1686 "#,
1687 );
1688 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1689 .ok()
1690 .and_then(|common_options| common_options.opts.opt_level);
1691
1692 assert_eq!(
1693 parsed_opt_level, expected,
1694 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1695 );
1696 }
1697
1698 for (regalloc_value, expected) in [
1700 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1701 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1702 ("\"hello\"", None), ("3", None), ("true", None), ] {
1706 let toml = format!(
1707 r#"
1708 [optimize]
1709 regalloc-algorithm = {regalloc_value}
1710 "#,
1711 );
1712 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1713 .ok()
1714 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1715 assert_eq!(
1716 parsed_regalloc_algorithm, expected,
1717 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1718 );
1719 }
1720
1721 for (strategy_value, expected) in [
1723 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1724 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1725 ("\"hello\"", None), ("5", None), ("true", None), ] {
1729 let toml = format!(
1730 r#"
1731 [codegen]
1732 compiler = {strategy_value}
1733 "#,
1734 );
1735 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1736 .ok()
1737 .and_then(|common_options| common_options.codegen.compiler);
1738 assert_eq!(
1739 parsed_strategy, expected,
1740 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1741 );
1742 }
1743
1744 for (collector_value, expected) in [
1746 (
1747 "\"drc\"",
1748 Some(wasmtime::Collector::DeferredReferenceCounting),
1749 ),
1750 ("\"null\"", Some(wasmtime::Collector::Null)),
1751 ("\"copying\"", Some(wasmtime::Collector::Copying)),
1752 ("\"hello\"", None), ("5", None), ("true", None), ] {
1756 let toml = format!(
1757 r#"
1758 [codegen]
1759 collector = {collector_value}
1760 "#,
1761 );
1762 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1763 .ok()
1764 .and_then(|common_options| common_options.codegen.collector);
1765 assert_eq!(
1766 parsed_collector, expected,
1767 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1768 );
1769 }
1770 }
1771}
1772
1773impl Default for CommonOptions {
1774 fn default() -> CommonOptions {
1775 CommonOptions::new()
1776 }
1777}
1778
1779impl fmt::Display for CommonOptions {
1780 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1781 let CommonOptions {
1782 codegen_raw,
1783 codegen,
1784 debug_raw,
1785 debug,
1786 opts_raw,
1787 opts,
1788 wasm_raw,
1789 wasm,
1790 wasi_raw,
1791 wasi,
1792 record_raw,
1793 record,
1794 configured,
1795 target,
1796 config,
1797 } = self;
1798 if let Some(target) = target {
1799 write!(f, "--target {target} ")?;
1800 }
1801 if let Some(config) = config {
1802 write!(f, "--config {} ", config.display())?;
1803 }
1804
1805 let codegen_flags;
1806 let opts_flags;
1807 let wasi_flags;
1808 let wasm_flags;
1809 let debug_flags;
1810 let record_flags;
1811
1812 if *configured {
1813 codegen_flags = codegen.to_options();
1814 debug_flags = debug.to_options();
1815 wasi_flags = wasi.to_options();
1816 wasm_flags = wasm.to_options();
1817 opts_flags = opts.to_options();
1818 record_flags = record.to_options();
1819 } else {
1820 codegen_flags = codegen_raw
1821 .iter()
1822 .flat_map(|t| t.0.iter())
1823 .cloned()
1824 .collect();
1825 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1826 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1827 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1828 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1829 record_flags = record_raw
1830 .iter()
1831 .flat_map(|t| t.0.iter())
1832 .cloned()
1833 .collect();
1834 }
1835
1836 for flag in codegen_flags {
1837 write!(f, "-C{flag} ")?;
1838 }
1839 for flag in opts_flags {
1840 write!(f, "-O{flag} ")?;
1841 }
1842 for flag in wasi_flags {
1843 write!(f, "-S{flag} ")?;
1844 }
1845 for flag in wasm_flags {
1846 write!(f, "-W{flag} ")?;
1847 }
1848 for flag in debug_flags {
1849 write!(f, "-D{flag} ")?;
1850 }
1851 for flag in record_flags {
1852 write!(f, "-R{flag} ")?;
1853 }
1854
1855 Ok(())
1856 }
1857}