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