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