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