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