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