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