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
275 #[serde(default)]
277 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
278 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
279 pub inlining: Option<wasmtime::Inlining>,
280
281 pub metadata_for_internal_asserts: Option<bool>,
284 pub metadata_for_gc_heap_corruption: Option<bool>,
287
288 #[serde(default)]
308 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
309 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
310 pub unsafe_intrinsics: Option<UnsafeIntrinsicsImport>,
311
312 #[serde(skip)]
335 pub compile_time_builtin: Vec<CompileTimeBuiltin>,
336
337 #[prefixed = "cranelift"]
338 #[serde(default)]
339 pub cranelift: Vec<(String, Option<String>)>,
342 }
343
344 enum Codegen {
345 ...
346 }
347}
348
349wasmtime_option_group! {
350 #[env = "DEBUG"]
351 pub struct DebugOptions {
352 pub debug_info: Option<bool>,
354 pub guest_debug: Option<bool>,
356 pub address_map: Option<bool>,
358 pub logging: Option<bool>,
360 pub log_to_files: Option<bool>,
362 pub coredump: Option<String>,
364 pub debugger: Option<PathBuf>,
367 #[serde(default)]
370 pub arg: Vec<String>,
371 pub inherit_stdin: Option<bool>,
374 pub inherit_stdout: Option<bool>,
377 pub inherit_stderr: Option<bool>,
380 pub max_backtrace: Option<usize>,
382 pub symbols: Option<bool>,
384 }
385
386 enum Debug {
387 ...
388 }
389}
390
391wasmtime_option_group! {
392 #[env = "WASM"]
393 pub struct WasmOptions {
394 pub nan_canonicalization: Option<bool>,
396 pub fuel: Option<u64>,
404 pub epoch_interruption: Option<bool>,
407 pub max_wasm_stack: Option<usize>,
410 pub async_stack_size: Option<usize>,
416 pub async_stack_zeroing: Option<bool>,
419 pub unknown_exports_allow: Option<bool>,
421 pub unknown_imports_trap: Option<bool>,
424 pub unknown_imports_default: Option<bool>,
427 pub wmemcheck: Option<bool>,
429 pub max_memory_size: Option<usize>,
434 pub max_table_elements: Option<usize>,
436 pub max_instances: Option<usize>,
438 pub max_tables: Option<usize>,
440 pub max_memories: Option<usize>,
442 pub trap_on_grow_failure: Option<bool>,
449 pub timeout: Option<Duration>,
451 pub all_proposals: Option<bool>,
453 pub bulk_memory: Option<bool>,
455 pub multi_memory: Option<bool>,
457 pub multi_value: Option<bool>,
459 pub reference_types: Option<bool>,
461 pub simd: Option<bool>,
463 pub relaxed_simd: Option<bool>,
465 pub relaxed_simd_deterministic: Option<bool>,
474 pub tail_call: Option<bool>,
476 pub threads: Option<bool>,
478 pub shared_memory: Option<bool>,
480 pub shared_everything_threads: Option<bool>,
482 pub memory64: Option<bool>,
484 pub component_model: Option<bool>,
486 pub component_model_async: Option<bool>,
488 pub component_model_more_async_builtins: Option<bool>,
491 pub component_model_async_stackful: Option<bool>,
494 pub component_model_threading: Option<bool>,
497 pub component_model_error_context: Option<bool>,
500 pub component_model_gc: Option<bool>,
503 pub component_model_map: Option<bool>,
506 pub component_model_memory64: Option<bool>,
509 pub function_references: Option<bool>,
511 pub stack_switching: Option<bool>,
513 pub gc: Option<bool>,
515 pub custom_page_sizes: Option<bool>,
517 pub wide_arithmetic: Option<bool>,
519 pub branch_hinting: Option<bool>,
521 pub compact_imports: Option<bool>,
523 pub extended_const: Option<bool>,
525 pub exceptions: Option<bool>,
527 pub gc_support: Option<bool>,
529 pub component_model_fixed_length_lists: Option<bool>,
532 pub component_model_implements: Option<bool>,
536 pub component_model_canonical_names: Option<bool>,
539 pub component_model_accessors: Option<bool>,
542 pub concurrency_support: Option<bool>,
545 }
546
547 enum Wasm {
548 ...
549 }
550}
551
552wasmtime_option_group! {
553 #[env = "WASI"]
554 pub struct WasiOptions {
555 pub cli: Option<bool>,
557 pub cli_exit_with_code: Option<bool>,
559 pub common: Option<bool>,
561 pub nn: Option<bool>,
563 pub threads: Option<bool>,
565 pub http: Option<bool>,
567 pub http_outgoing_body_buffer_chunks: Option<NonZeroUsize>,
571 pub http_outgoing_body_chunk_size: Option<NonZeroUsize>,
574 pub config: Option<bool>,
576 pub keyvalue: Option<bool>,
578 #[serde(default)]
581 pub tcplisten: Vec<String>,
582 pub tls: Option<bool>,
584 pub preview2: Option<bool>,
587 #[serde(skip)]
596 pub nn_graph: Vec<WasiNnGraph>,
597 pub inherit_network: Option<bool>,
600 pub allow_ip_name_lookup: Option<bool>,
602 pub tcp: Option<bool>,
604 pub udp: Option<bool>,
606 pub network_error_code: Option<bool>,
608 pub preview0: Option<bool>,
610 pub inherit_env: Option<bool>,
614 pub inherit_stdin: Option<bool>,
616 pub inherit_stdout: Option<bool>,
618 pub inherit_stderr: Option<bool>,
620 pub cwd: Option<String>,
622 #[serde(skip)]
624 pub config_var: Vec<KeyValuePair>,
625 #[serde(skip)]
627 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
628 pub p3: Option<bool>,
630 pub max_resources: Option<usize>,
632 pub hostcall_fuel: Option<usize>,
634 pub max_component_handles: Option<usize>,
638 pub max_random_size: Option<u64>,
642 pub max_http_fields_size: Option<usize>,
646 }
647
648 enum Wasi {
649 ...
650 }
651}
652
653wasmtime_option_group! {
654 #[env = "RECORD"]
655 pub struct RecordOptions {
656 pub path: Option<String>,
658 pub validation_metadata: Option<bool>,
661 pub event_window_size: Option<usize>,
664 }
665
666 enum Record {
667 ...
668 }
669}
670
671#[derive(Debug, Clone, PartialEq)]
672pub struct WasiNnGraph {
673 pub format: String,
674 pub dir: String,
675}
676
677#[derive(Debug, Clone, PartialEq)]
678pub struct KeyValuePair {
679 pub key: String,
680 pub value: String,
681}
682
683#[derive(Debug, Clone, PartialEq)]
686pub struct UnsafeIntrinsicsImport(pub String);
687
688#[derive(Debug, Clone, PartialEq)]
690pub struct CompileTimeBuiltin {
691 pub name: String,
693 pub path: PathBuf,
695}
696
697#[derive(Clone)]
699#[cfg_attr(feature = "clap", derive(clap::Parser))]
700#[cfg_attr(
701 feature = "serde",
702 derive(serde_derive::Deserialize, serde_derive::Serialize)
703)]
704#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
705pub struct CommonOptions {
706 #[cfg_attr(
716 feature = "clap",
717 arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
718 )]
719 #[cfg_attr(feature = "serde", serde(skip))]
720 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
721
722 #[cfg_attr(
724 feature = "clap",
725 arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
726 )]
727 #[cfg_attr(feature = "serde", serde(skip))]
728 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
729
730 #[cfg_attr(
732 feature = "clap",
733 arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
734 )]
735 #[cfg_attr(feature = "serde", serde(skip))]
736 debug_raw: Vec<opt::CommaSeparated<Debug>>,
737
738 #[cfg_attr(
741 feature = "clap",
742 arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
743 )]
744 #[cfg_attr(feature = "serde", serde(skip))]
745 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
746
747 #[cfg_attr(
749 feature = "clap",
750 arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
751 )]
752 #[cfg_attr(feature = "serde", serde(skip))]
753 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
754
755 #[cfg_attr(
764 feature = "clap",
765 arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
766 )]
767 #[cfg_attr(feature = "serde", serde(skip))]
768 record_raw: Vec<opt::CommaSeparated<Record>>,
769
770 #[cfg_attr(feature = "clap", arg(skip))]
773 #[cfg_attr(feature = "serde", serde(skip))]
774 configured: bool,
775
776 #[cfg_attr(feature = "clap", arg(skip))]
777 #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
778 pub opts: OptimizeOptions,
779
780 #[cfg_attr(feature = "clap", arg(skip))]
781 #[cfg_attr(feature = "serde", serde(default))]
782 pub codegen: CodegenOptions,
783
784 #[cfg_attr(feature = "clap", arg(skip))]
785 #[cfg_attr(feature = "serde", serde(default))]
786 pub debug: DebugOptions,
787
788 #[cfg_attr(feature = "clap", arg(skip))]
789 #[cfg_attr(feature = "serde", serde(default))]
790 pub wasm: WasmOptions,
791
792 #[cfg_attr(feature = "clap", arg(skip))]
793 #[cfg_attr(feature = "serde", serde(default))]
794 pub wasi: WasiOptions,
795
796 #[cfg_attr(feature = "clap", arg(skip))]
797 #[cfg_attr(feature = "serde", serde(default))]
798 pub record: RecordOptions,
799
800 #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
802 #[cfg_attr(feature = "serde", serde(skip))]
803 pub target: Option<String>,
804
805 #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
812 #[cfg_attr(feature = "serde", serde(skip))]
813 pub config: Option<PathBuf>,
814}
815
816macro_rules! match_feature {
817 (
818 [$feat:tt : $config:expr]
819 $val:ident => $e:expr,
820 $p:pat => err,
821 ) => {
822 #[cfg(feature = $feat)]
823 {
824 if let Some($val) = $config {
825 $e;
826 }
827 }
828 #[cfg(not(feature = $feat))]
829 {
830 if let Some($p) = $config {
831 bail!(concat!("support for ", $feat, " disabled at compile time"));
832 }
833 }
834 };
835}
836
837impl CommonOptions {
838 pub fn new() -> CommonOptions {
840 CommonOptions {
841 opts_raw: Vec::new(),
842 codegen_raw: Vec::new(),
843 debug_raw: Vec::new(),
844 wasm_raw: Vec::new(),
845 wasi_raw: Vec::new(),
846 record_raw: Vec::new(),
847 configured: true,
848 opts: Default::default(),
849 codegen: Default::default(),
850 debug: Default::default(),
851 wasm: Default::default(),
852 wasi: Default::default(),
853 record: Default::default(),
854 target: None,
855 config: None,
856 }
857 }
858
859 fn configure(&mut self) -> Result<()> {
860 if self.configured {
861 return Ok(());
862 }
863 self.configured = true;
864 if let Some(toml_config_path) = &self.config {
865 #[cfg(feature = "toml")]
866 {
867 let toml_options = CommonOptions::from_file(toml_config_path)?;
868 self.opts = toml_options.opts;
869 self.codegen = toml_options.codegen;
870 self.debug = toml_options.debug;
871 self.wasm = toml_options.wasm;
872 self.wasi = toml_options.wasi;
873 self.record = toml_options.record;
874 }
875 #[cfg(not(feature = "toml"))]
876 {
877 bail!(
878 "support for loading a configuration file from \
879 {toml_config_path:?} disabled at compile time"
880 );
881 }
882 }
883 self.opts.configure_with(&self.opts_raw)?;
884 self.codegen.configure_with(&self.codegen_raw)?;
885 self.debug.configure_with(&self.debug_raw)?;
886 self.wasm.configure_with(&self.wasm_raw)?;
887 self.wasi.configure_with(&self.wasi_raw)?;
888 self.record.configure_with(&self.record_raw)?;
889 Ok(())
890 }
891
892 pub fn init_logging(&mut self) -> Result<()> {
893 self.configure()?;
894 if self.debug.logging == Some(false) {
895 return Ok(());
896 }
897 #[cfg(feature = "logging")]
898 if self.debug.log_to_files == Some(true) {
899 let prefix = "wasmtime.dbg.";
900 init_file_per_thread_logger(prefix);
901 } else {
902 use std::io::IsTerminal;
903 use tracing_subscriber::{EnvFilter, FmtSubscriber};
904 let builder = FmtSubscriber::builder()
905 .with_writer(std::io::stderr)
906 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
907 .with_ansi(std::io::stderr().is_terminal());
908 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
909 builder
910 .with_level(false)
911 .with_target(false)
912 .without_time()
913 .init()
914 } else {
915 builder.init();
916 }
917 }
918 #[cfg(not(feature = "logging"))]
919 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
920 bail!("support for logging disabled at compile time");
921 }
922 Ok(())
923 }
924
925 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
926 self.configure()?;
927 let mut config = Config::new();
928
929 match_feature! {
930 ["cranelift" : self.codegen.compiler]
931 strategy => config.strategy(strategy),
932 _ => err,
933 }
934 match_feature! {
935 ["gc" : self.codegen.collector]
936 collector => config.collector(collector),
937 _ => err,
938 }
939 if let Some(target) = &self.target {
940 config.target(target)?;
941 }
942 match_feature! {
943 ["cranelift" : self.codegen.cranelift_debug_verifier]
944 enable => config.cranelift_debug_verifier(enable),
945 true => err,
946 }
947 if let Some(enable) = self.debug.debug_info {
948 config.debug_info(enable);
949 }
950 match_feature! {
951 ["debug" : self.debug.guest_debug]
952 enable => config.guest_debug(enable),
953 _ => err,
954 }
955 if self.debug.coredump.is_some() {
956 #[cfg(feature = "coredump")]
957 config.coredump_on_trap(true);
958 #[cfg(not(feature = "coredump"))]
959 bail!("support for coredumps disabled at compile time");
960 }
961 match_feature! {
962 ["cranelift" : self.opts.opt_level]
963 level => config.cranelift_opt_level(level),
964 _ => err,
965 }
966 match_feature! {
967 ["cranelift": self.opts.regalloc_algorithm]
968 algo => config.cranelift_regalloc_algorithm(algo),
969 _ => err,
970 }
971 match_feature! {
972 ["cranelift" : self.wasm.nan_canonicalization]
973 enable => config.cranelift_nan_canonicalization(enable),
974 true => err,
975 }
976
977 self.enable_wasm_features(&mut config)?;
978
979 #[cfg(feature = "cranelift")]
980 for (name, value) in self.codegen.cranelift.iter() {
981 let name = name.replace('-', "_");
982 unsafe {
983 match value {
984 Some(val) => {
985 config.cranelift_flag_set(&name, val);
986 }
987 None => {
988 config.cranelift_flag_enable(&name);
989 }
990 }
991 }
992 }
993 #[cfg(not(feature = "cranelift"))]
994 if !self.codegen.cranelift.is_empty() {
995 bail!("support for cranelift disabled at compile time");
996 }
997
998 #[cfg(feature = "cache")]
999 if self.codegen.cache != Some(false) {
1000 use wasmtime::Cache;
1001 let cache = match &self.codegen.cache_config {
1002 Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
1003 None => Cache::from_file(None)?,
1004 };
1005 config.cache(Some(cache));
1006 }
1007 #[cfg(not(feature = "cache"))]
1008 if self.codegen.cache == Some(true) {
1009 bail!("support for caching disabled at compile time");
1010 }
1011
1012 match_feature! {
1013 ["parallel-compilation" : self.codegen.parallel_compilation]
1014 enable => config.parallel_compilation(enable),
1015 true => err,
1016 }
1017
1018 let memory_reservation = self
1019 .opts
1020 .memory_reservation
1021 .or(self.opts.static_memory_maximum_size);
1022 if let Some(size) = memory_reservation {
1023 config.memory_reservation(size);
1024 }
1025
1026 if let Some(enable) = self.opts.static_memory_forced {
1027 config.memory_may_move(!enable);
1028 }
1029 if let Some(enable) = self.opts.memory_may_move {
1030 config.memory_may_move(enable);
1031 }
1032
1033 let memory_guard_size = self
1034 .opts
1035 .static_memory_guard_size
1036 .or(self.opts.dynamic_memory_guard_size)
1037 .or(self.opts.memory_guard_size);
1038 if let Some(size) = memory_guard_size {
1039 config.memory_guard_size(size);
1040 }
1041
1042 let mem_for_growth = self
1043 .opts
1044 .memory_reservation_for_growth
1045 .or(self.opts.dynamic_memory_reserved_for_growth);
1046 if let Some(size) = mem_for_growth {
1047 config.memory_reservation_for_growth(size);
1048 }
1049 if let Some(enable) = self.opts.guard_before_linear_memory {
1050 config.guard_before_linear_memory(enable);
1051 }
1052
1053 if let Some(size) = self.opts.gc_heap_reservation {
1054 config.gc_heap_reservation(size);
1055 }
1056 if let Some(enable) = self.opts.gc_heap_may_move {
1057 config.gc_heap_may_move(enable);
1058 }
1059 if let Some(size) = self.opts.gc_heap_guard_size {
1060 config.gc_heap_guard_size(size);
1061 }
1062 if let Some(size) = self.opts.gc_heap_reservation_for_growth {
1063 config.gc_heap_reservation_for_growth(size);
1064 }
1065
1066 if let Some(size) = self.opts.gc_heap_initial_size {
1067 config.gc_heap_initial_size(size);
1068 }
1069
1070 if let Some(enable) = self.opts.table_lazy_init {
1071 config.table_lazy_init(enable);
1072 }
1073
1074 if let Some(n) = self.opts.gc_zeal_alloc_counter
1075 && (cfg!(gc_zeal) || cfg!(fuzzing))
1076 {
1077 config.gc_zeal_alloc_counter(Some(n))?;
1078 }
1079
1080 if self.wasm.fuel.is_some() {
1082 config.consume_fuel(true);
1083 }
1084
1085 if let Some(enable) = self.wasm.epoch_interruption {
1086 config.epoch_interruption(enable);
1087 }
1088 if let Some(enable) = self.debug.address_map {
1089 config.generate_address_map(enable);
1090 }
1091 if let Some(frames) = self.debug.max_backtrace {
1092 match NonZeroUsize::new(frames) {
1093 None => {
1094 config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1095 }
1096 Some(amt) => {
1097 config.wasm_backtrace_max_frames(Some(amt));
1098 }
1099 }
1100 }
1101 if let Some(enable) = self.debug.symbols {
1102 config.debug_symbols(enable);
1103 }
1104 if let Some(enable) = self.opts.memory_init_cow {
1105 config.memory_init_cow(enable);
1106 }
1107 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1108 config.memory_guaranteed_dense_image_size(size);
1109 }
1110 if let Some(enable) = self.opts.signals_based_traps {
1111 config.signals_based_traps(enable);
1112 }
1113 if let Some(enable) = self.codegen.native_unwind_info {
1114 config.native_unwind_info(enable);
1115 }
1116 if let Some(enable) = self.codegen.inlining {
1117 config.compiler_inlining(enable);
1118 }
1119 if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1120 config.metadata_for_internal_asserts(enable);
1121 }
1122 if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1123 config.metadata_for_gc_heap_corruption(enable);
1124 }
1125
1126 #[cfg(any(feature = "async", feature = "stack-switching"))]
1129 {
1130 if let Some(size) = self.wasm.async_stack_size {
1131 config.async_stack_size(size);
1132 }
1133 }
1134 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1135 {
1136 if let Some(_size) = self.wasm.async_stack_size {
1137 bail!(concat!(
1138 "support for async/stack-switching disabled at compile time"
1139 ));
1140 }
1141 }
1142
1143 match_feature! {
1144 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1145 enable => {
1146 if enable {
1147 let mut cfg = wasmtime::PoolingAllocationConfig::default();
1148 if let Some(size) = self.opts.pooling_memory_keep_resident {
1149 cfg.linear_memory_keep_resident(size);
1150 }
1151 if let Some(size) = self.opts.pooling_table_keep_resident {
1152 cfg.table_keep_resident(size);
1153 }
1154 if let Some(limit) = self.opts.pooling_total_core_instances {
1155 cfg.total_core_instances(limit);
1156 }
1157 if let Some(limit) = self.opts.pooling_total_component_instances {
1158 cfg.total_component_instances(limit);
1159 }
1160 if let Some(limit) = self.opts.pooling_total_memories {
1161 cfg.total_memories(limit);
1162 }
1163 if let Some(limit) = self.opts.pooling_total_tables {
1164 cfg.total_tables(limit);
1165 }
1166 if let Some(limit) = self.opts.pooling_table_elements
1167 .or(self.wasm.max_table_elements)
1168 {
1169 cfg.table_elements(limit);
1170 }
1171 if let Some(limit) = self.opts.pooling_max_core_instance_size {
1172 cfg.max_core_instance_size(limit);
1173 }
1174 match_feature! {
1175 ["async" : self.opts.pooling_total_stacks]
1176 limit => cfg.total_stacks(limit),
1177 _ => err,
1178 }
1179 if let Some(max) = self.opts.pooling_max_memory_size
1180 .or(self.wasm.max_memory_size)
1181 {
1182 cfg.max_memory_size(max);
1183 }
1184 if let Some(size) = self.opts.pooling_decommit_batch_size {
1185 cfg.decommit_batch_size(size);
1186 }
1187 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1188 cfg.max_unused_warm_slots(max);
1189 }
1190 match_feature! {
1191 ["async" : self.opts.pooling_async_stack_keep_resident]
1192 size => cfg.async_stack_keep_resident(size),
1193 _ => err,
1194 }
1195 if let Some(max) = self.opts.pooling_max_component_instance_size {
1196 cfg.max_component_instance_size(max);
1197 }
1198 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1199 cfg.max_core_instances_per_component(max);
1200 }
1201 if let Some(max) = self.opts.pooling_max_memories_per_component {
1202 cfg.max_memories_per_component(max);
1203 }
1204 if let Some(max) = self.opts.pooling_max_tables_per_component {
1205 cfg.max_tables_per_component(max);
1206 }
1207 if let Some(max) = self.opts.pooling_max_tables_per_module {
1208 cfg.max_tables_per_module(max);
1209 }
1210 if let Some(max) = self.opts.pooling_max_memories_per_module {
1211 cfg.max_memories_per_module(max);
1212 }
1213 match_feature! {
1214 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1215 enable => cfg.memory_protection_keys(enable),
1216 _ => err,
1217 }
1218 match_feature! {
1219 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1220 max => cfg.max_memory_protection_keys(max),
1221 _ => err,
1222 }
1223 match_feature! {
1224 ["gc" : self.opts.pooling_total_gc_heaps]
1225 max => cfg.total_gc_heaps(max),
1226 _ => err,
1227 }
1228 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1229 cfg.pagemap_scan(enabled);
1230 }
1231 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1232 }
1233 },
1234 true => err,
1235 }
1236
1237 if self.opts.pooling_memory_protection_keys.is_some()
1238 && !self.opts.pooling_allocator.unwrap_or(false)
1239 {
1240 bail!("memory protection keys require the pooling allocator");
1241 }
1242
1243 if self.opts.pooling_max_memory_protection_keys.is_some()
1244 && !self.opts.pooling_memory_protection_keys.is_some()
1245 {
1246 bail!("max memory protection keys requires memory protection keys to be enabled");
1247 }
1248
1249 match_feature! {
1250 ["async" : self.wasm.async_stack_zeroing]
1251 enable => config.async_stack_zeroing(enable),
1252 _ => err,
1253 }
1254
1255 if let Some(max) = self.wasm.max_wasm_stack {
1256 config.max_wasm_stack(max);
1257
1258 #[cfg(any(feature = "async", feature = "stack-switching"))]
1262 if self.wasm.async_stack_size.is_none() {
1263 const DEFAULT_HOST_STACK: usize = 512 << 10;
1264 config.async_stack_size(max.saturating_add(DEFAULT_HOST_STACK));
1265 }
1266 }
1267
1268 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1269 config.relaxed_simd_deterministic(enable);
1270 }
1271 match_feature! {
1272 ["cranelift" : self.wasm.wmemcheck]
1273 enable => config.wmemcheck(enable),
1274 true => err,
1275 }
1276
1277 if let Some(enable) = self.wasm.gc_support {
1278 config.gc_support(enable);
1279 }
1280
1281 if let Some(enable) = self.wasm.concurrency_support {
1282 config.concurrency_support(enable);
1283 }
1284
1285 if let Some(enable) = self.wasm.shared_memory {
1286 config.shared_memory(enable);
1287 }
1288
1289 let record = &self.record;
1290 match_feature! {
1291 ["rr" : &record.path]
1292 _path => {
1293 bail!("recording configuration for `rr` feature is not supported yet");
1294 },
1295 _ => err,
1296 }
1297
1298 Ok(config)
1299 }
1300
1301 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1302 let all = self.wasm.all_proposals;
1303
1304 if let Some(enable) = self.wasm.simd.or(all) {
1305 config.wasm_simd(enable);
1306 }
1307 if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1308 config.wasm_relaxed_simd(enable);
1309 }
1310 if let Some(enable) = self.wasm.bulk_memory.or(all) {
1311 config.wasm_bulk_memory(enable);
1312 }
1313 if let Some(enable) = self.wasm.multi_value.or(all) {
1314 config.wasm_multi_value(enable);
1315 }
1316 if let Some(enable) = self.wasm.tail_call.or(all) {
1317 config.wasm_tail_call(enable);
1318 }
1319 if let Some(enable) = self.wasm.multi_memory.or(all) {
1320 config.wasm_multi_memory(enable);
1321 }
1322 if let Some(enable) = self.wasm.memory64.or(all) {
1323 config.wasm_memory64(enable);
1324 }
1325 if let Some(enable) = self.wasm.stack_switching {
1326 config.wasm_stack_switching(enable);
1327 }
1328 if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1329 config.wasm_custom_page_sizes(enable);
1330 }
1331 if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1332 config.wasm_wide_arithmetic(enable);
1333 }
1334 if let Some(enable) = self.wasm.branch_hinting {
1336 config.wasm_branch_hinting(enable);
1337 }
1338 if let Some(enable) = self.wasm.compact_imports {
1340 config.wasm_compact_imports(enable);
1341 }
1342 if let Some(enable) = self.wasm.extended_const.or(all) {
1343 config.wasm_extended_const(enable);
1344 }
1345
1346 macro_rules! handle_conditionally_compiled {
1347 ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1348 if let Some(enable) = self.wasm.$field.or(all) {
1349 #[cfg(feature = $feature)]
1350 config.$method(enable);
1351 #[cfg(not(feature = $feature))]
1352 if enable && all.is_none() {
1353 bail!("support for {} was disabled at compile-time", $feature);
1354 }
1355 }
1356 )*)
1357 }
1358
1359 handle_conditionally_compiled! {
1360 ("component-model", component_model, wasm_component_model)
1361 ("component-model-async", component_model_async, wasm_component_model_async)
1362 ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1363 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1364 ("component-model-async", component_model_threading, wasm_component_model_threading)
1365 ("component-model", component_model_error_context, wasm_component_model_error_context)
1366 ("component-model", component_model_map, wasm_component_model_map)
1367 ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1368 ("component-model", component_model_implements, wasm_component_model_implements)
1369 ("component-model", component_model_canonical_names, wasm_component_model_canonical_names)
1370 ("component-model", component_model_accessors, wasm_component_model_accessors)
1371 ("component-model", component_model_memory64, wasm_component_model_memory64)
1372 ("threads", threads, wasm_threads)
1373 ("gc", gc, wasm_gc)
1374 ("gc", reference_types, wasm_reference_types)
1375 ("gc", function_references, wasm_function_references)
1376 ("gc", exceptions, wasm_exceptions)
1377 ("stack-switching", stack_switching, wasm_stack_switching)
1378 }
1379
1380 if let Some(enable) = self.wasm.component_model_gc {
1381 #[cfg(all(feature = "component-model", feature = "gc"))]
1382 config.wasm_component_model_gc(enable);
1383 #[cfg(not(all(feature = "component-model", feature = "gc")))]
1384 if enable && all.is_none() {
1385 bail!("support for `component-model-gc` was disabled at compile time")
1386 }
1387 }
1388
1389 Ok(())
1390 }
1391
1392 #[cfg(feature = "toml")]
1393 pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1394 use wasmtime::error::Context;
1395
1396 let path_ref = path.as_ref();
1397 let file_contents = std::fs::read_to_string(path_ref)
1398 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1399 toml::from_str::<CommonOptions>(&file_contents)
1400 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1401 }
1402
1403 pub fn from_engine(engine: &Engine) -> Self {
1416 let features = engine.get_wasm_features();
1417 let pooling = engine.get_pooling_config();
1418 CommonOptions {
1419 target: engine.get_target(),
1420 opts: OptimizeOptions {
1421 memory_may_move: Some(engine.get_memory_may_move()),
1422 memory_reservation: Some(engine.get_memory_reservation()),
1423 memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1424 memory_guard_size: Some(engine.get_memory_guard_size()),
1425 gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1426 gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1427 gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1428 gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1429 gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1430 guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1431 table_lazy_init: Some(engine.get_table_lazy_init()),
1432 memory_init_cow: Some(engine.get_memory_init_cow()),
1433 memory_guaranteed_dense_image_size: Some(
1434 engine.get_memory_guaranteed_dense_image_size(),
1435 ),
1436 signals_based_traps: Some(engine.get_signals_based_traps()),
1437 gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1438 opt_level: engine.get_cranelift_opt_level(),
1439 regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1440 pooling_allocator: Some(pooling.is_some()),
1441 pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1442 pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1443 pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1444 pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1445 pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1446 pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1447 pooling_total_component_instances: pooling
1448 .map(|c| c.get_total_component_instances()),
1449 pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1450 pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1451 pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1452 pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1453 pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1454 pooling_max_component_instance_size: pooling
1455 .map(|c| c.get_max_component_instance_size()),
1456 pooling_max_core_instances_per_component: pooling
1457 .map(|c| c.get_max_core_instances_per_component()),
1458 pooling_max_memories_per_component: pooling
1459 .map(|c| c.get_max_memories_per_component()),
1460 pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1461 pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1462 pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1463 pooling_async_stack_keep_resident: pooling
1464 .map(|c| c.get_async_stack_keep_resident()),
1465 pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1466 pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1467 pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1468 pooling_max_memory_protection_keys: pooling
1469 .map(|c| c.get_max_memory_protection_keys()),
1470 dynamic_memory_guard_size: None,
1473 static_memory_guard_size: None,
1474 static_memory_forced: None,
1475 static_memory_maximum_size: None,
1476 dynamic_memory_reserved_for_growth: None,
1477 },
1478 codegen: CodegenOptions {
1479 compiler: engine.get_strategy(),
1480 collector: engine.get_collector(),
1481 cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1482 inlining: Some(engine.get_compiler_inlining()),
1483 native_unwind_info: engine.get_native_unwind_info(),
1484 parallel_compilation: Some(engine.get_parallel_compilation()),
1485 metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1486 metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1487 cranelift: engine
1488 .get_cranelift_flags_set()
1489 .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1490 .chain(
1491 engine
1492 .get_cranelift_flags_enabled()
1493 .map(|k| (k.to_string(), None)),
1494 )
1495 .collect(),
1496
1497 cache: None,
1500 cache_config: None,
1501
1502 unsafe_intrinsics: None,
1505 compile_time_builtin: Vec::new(),
1506 },
1507 debug: DebugOptions {
1508 address_map: Some(engine.get_generate_address_map()),
1509 debug_info: Some(engine.get_debug_info()),
1510 guest_debug: Some(engine.get_guest_debug()),
1511 symbols: Some(engine.get_debug_symbols()),
1512 max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1513
1514 coredump: None,
1517 debugger: None,
1519 arg: Vec::new(),
1520 inherit_stderr: None,
1521 inherit_stdout: None,
1522 inherit_stdin: None,
1523 log_to_files: None,
1525 logging: None,
1526 },
1527 wasm: WasmOptions {
1528 async_stack_size: Some(engine.get_async_stack_size()),
1529 async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1530 branch_hinting: Some(engine.get_wasm_branch_hinting()),
1531 compact_imports: Some(features.contains(WasmFeatures::COMPACT_IMPORTS)),
1532 bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1533 component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1534 component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1535 component_model_async_stackful: Some(
1536 features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1537 ),
1538 component_model_error_context: Some(
1539 features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1540 ),
1541 component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1542 component_model_fixed_length_lists: Some(
1543 features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1544 ),
1545 component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1546 component_model_canonical_names: Some(
1547 features.contains(WasmFeatures::CM_CANON_NAMES),
1548 ),
1549 component_model_accessors: Some(features.contains(WasmFeatures::CM_ACCESSORS)),
1550 component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1551 component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1552 component_model_more_async_builtins: Some(
1553 features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1554 ),
1555 component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1556 custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1557 exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1558 extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1559 function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1560 gc: Some(features.contains(WasmFeatures::GC)),
1561 gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1562 memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1563 multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1564 multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1565 reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1566 relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1567 shared_everything_threads: Some(
1568 features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1569 ),
1570 simd: Some(features.contains(WasmFeatures::SIMD)),
1571 stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1572 tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1573 threads: Some(features.contains(WasmFeatures::THREADS)),
1574 wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1575 concurrency_support: Some(engine.get_concurrency_support()),
1576 epoch_interruption: Some(engine.get_epoch_interruption()),
1577 fuel: if engine.get_consume_fuel() {
1578 Some(1)
1579 } else {
1580 None
1581 },
1582 max_wasm_stack: Some(engine.get_max_wasm_stack()),
1583 nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1584 relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1585 shared_memory: Some(engine.get_shared_memory()),
1586
1587 all_proposals: None,
1589 max_instances: None,
1592 max_memories: None,
1593 max_memory_size: None,
1594 max_table_elements: None,
1595 max_tables: None,
1596 timeout: None,
1598 trap_on_grow_failure: None,
1599 unknown_exports_allow: None,
1600 unknown_imports_default: None,
1601 unknown_imports_trap: None,
1602 wmemcheck: None,
1603 },
1604
1605 record: RecordOptions::default(),
1607
1608 wasi: Default::default(),
1610
1611 configured: true,
1613 codegen_raw: Default::default(),
1614 debug_raw: Default::default(),
1615 opts_raw: Default::default(),
1616 record_raw: Default::default(),
1617 wasi_raw: Default::default(),
1618 wasm_raw: Default::default(),
1619
1620 config: None,
1622 }
1627 }
1628}
1629
1630#[cfg(test)]
1631mod tests {
1632 use wasmtime::{OptLevel, RegallocAlgorithm};
1633
1634 use super::*;
1635
1636 #[test]
1637 fn from_toml() {
1638 let empty_toml = "";
1640 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1641 common_options.config(None).unwrap();
1642
1643 let basic_toml = r#"
1645 [optimize]
1646 [codegen]
1647 [debug]
1648 [wasm]
1649 [wasi]
1650 [record]
1651 "#;
1652 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1653 common_options.config(None).unwrap();
1654
1655 for (opt_value, expected) in [
1657 ("0", Some(OptLevel::None)),
1658 ("1", Some(OptLevel::Speed)),
1659 ("2", Some(OptLevel::Speed)),
1660 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1661 ("\"hello\"", None), ("3", None), ] {
1664 let toml = format!(
1665 r#"
1666 [optimize]
1667 opt-level = {opt_value}
1668 "#,
1669 );
1670 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1671 .ok()
1672 .and_then(|common_options| common_options.opts.opt_level);
1673
1674 assert_eq!(
1675 parsed_opt_level, expected,
1676 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1677 );
1678 }
1679
1680 for (regalloc_value, expected) in [
1682 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1683 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1684 ("\"hello\"", None), ("3", None), ("true", None), ] {
1688 let toml = format!(
1689 r#"
1690 [optimize]
1691 regalloc-algorithm = {regalloc_value}
1692 "#,
1693 );
1694 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1695 .ok()
1696 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1697 assert_eq!(
1698 parsed_regalloc_algorithm, expected,
1699 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1700 );
1701 }
1702
1703 for (strategy_value, expected) in [
1705 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1706 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1707 ("\"hello\"", None), ("5", None), ("true", None), ] {
1711 let toml = format!(
1712 r#"
1713 [codegen]
1714 compiler = {strategy_value}
1715 "#,
1716 );
1717 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1718 .ok()
1719 .and_then(|common_options| common_options.codegen.compiler);
1720 assert_eq!(
1721 parsed_strategy, expected,
1722 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1723 );
1724 }
1725
1726 for (collector_value, expected) in [
1728 (
1729 "\"drc\"",
1730 Some(wasmtime::Collector::DeferredReferenceCounting),
1731 ),
1732 ("\"null\"", Some(wasmtime::Collector::Null)),
1733 ("\"copying\"", Some(wasmtime::Collector::Copying)),
1734 ("\"hello\"", None), ("5", None), ("true", None), ] {
1738 let toml = format!(
1739 r#"
1740 [codegen]
1741 collector = {collector_value}
1742 "#,
1743 );
1744 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1745 .ok()
1746 .and_then(|common_options| common_options.codegen.collector);
1747 assert_eq!(
1748 parsed_collector, expected,
1749 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1750 );
1751 }
1752 }
1753}
1754
1755impl Default for CommonOptions {
1756 fn default() -> CommonOptions {
1757 CommonOptions::new()
1758 }
1759}
1760
1761impl fmt::Display for CommonOptions {
1762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1763 let CommonOptions {
1764 codegen_raw,
1765 codegen,
1766 debug_raw,
1767 debug,
1768 opts_raw,
1769 opts,
1770 wasm_raw,
1771 wasm,
1772 wasi_raw,
1773 wasi,
1774 record_raw,
1775 record,
1776 configured,
1777 target,
1778 config,
1779 } = self;
1780 if let Some(target) = target {
1781 write!(f, "--target {target} ")?;
1782 }
1783 if let Some(config) = config {
1784 write!(f, "--config {} ", config.display())?;
1785 }
1786
1787 let codegen_flags;
1788 let opts_flags;
1789 let wasi_flags;
1790 let wasm_flags;
1791 let debug_flags;
1792 let record_flags;
1793
1794 if *configured {
1795 codegen_flags = codegen.to_options();
1796 debug_flags = debug.to_options();
1797 wasi_flags = wasi.to_options();
1798 wasm_flags = wasm.to_options();
1799 opts_flags = opts.to_options();
1800 record_flags = record.to_options();
1801 } else {
1802 codegen_flags = codegen_raw
1803 .iter()
1804 .flat_map(|t| t.0.iter())
1805 .cloned()
1806 .collect();
1807 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1808 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1809 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1810 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1811 record_flags = record_raw
1812 .iter()
1813 .flat_map(|t| t.0.iter())
1814 .cloned()
1815 .collect();
1816 }
1817
1818 for flag in codegen_flags {
1819 write!(f, "-C{flag} ")?;
1820 }
1821 for flag in opts_flags {
1822 write!(f, "-O{flag} ")?;
1823 }
1824 for flag in wasi_flags {
1825 write!(f, "-S{flag} ")?;
1826 }
1827 for flag in wasm_flags {
1828 write!(f, "-W{flag} ")?;
1829 }
1830 for flag in debug_flags {
1831 write!(f, "-D{flag} ")?;
1832 }
1833 for flag in record_flags {
1834 write!(f, "-R{flag} ")?;
1835 }
1836
1837 Ok(())
1838 }
1839}