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