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