1use crate::opt::NonzeroDuration;
15use std::num::NonZeroUsize;
16use std::{fmt, num::NonZeroU32, path::PathBuf};
17use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};
18
19pub mod opt;
20
21#[cfg(feature = "logging")]
22fn init_file_per_thread_logger(prefix: &'static str) {
23 file_per_thread_logger::initialize(prefix);
24 file_per_thread_logger::allow_uninitialized();
25
26 #[cfg(feature = "parallel-compilation")]
31 rayon::ThreadPoolBuilder::new()
32 .spawn_handler(move |thread| {
33 let mut b = std::thread::Builder::new();
34 if let Some(name) = thread.name() {
35 b = b.name(name.to_owned());
36 }
37 if let Some(stack_size) = thread.stack_size() {
38 b = b.stack_size(stack_size);
39 }
40 b.spawn(move || {
41 file_per_thread_logger::initialize(prefix);
42 thread.run()
43 })?;
44 Ok(())
45 })
46 .build_global()
47 .unwrap();
48}
49
50wasmtime_option_group! {
51 #[env = "OPTIMIZE"]
52 pub struct OptimizeOptions {
53 #[serde(default)]
55 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
56 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
57 pub opt_level: Option<wasmtime::OptLevel>,
58
59 #[serde(default)]
61 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
62 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
63 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
64
65 pub memory_may_move: Option<bool>,
68
69 pub memory_reservation: Option<u64>,
71
72 pub memory_reservation_for_growth: Option<u64>,
74
75 pub memory_guard_size: Option<u64>,
77
78 pub gc_heap_may_move: Option<bool>,
81
82 pub gc_heap_reservation: Option<u64>,
84
85 pub gc_heap_reservation_for_growth: Option<u64>,
87
88 pub gc_heap_guard_size: Option<u64>,
90
91 pub gc_heap_initial_size: Option<u64>,
93
94 pub guard_before_linear_memory: Option<bool>,
97
98 pub table_lazy_init: Option<bool>,
103
104 pub pooling_allocator: Option<bool>,
106
107 pub pooling_decommit_batch_size: Option<usize>,
110
111 pub pooling_memory_keep_resident: Option<usize>,
114
115 pub pooling_table_keep_resident: Option<usize>,
118
119 #[serde(default)]
122 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
123 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
124 pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
125
126 pub pooling_max_memory_protection_keys: Option<usize>,
129
130 pub memory_init_cow: Option<bool>,
133
134 pub memory_guaranteed_dense_image_size: Option<u64>,
137
138 pub pooling_total_core_instances: Option<u32>,
141
142 pub pooling_total_component_instances: Option<u32>,
145
146 pub pooling_total_memories: Option<u32>,
149
150 pub pooling_total_tables: Option<u32>,
153
154 pub pooling_total_stacks: Option<u32>,
157
158 pub pooling_max_memory_size: Option<usize>,
161
162 pub pooling_table_elements: Option<usize>,
165
166 pub pooling_max_core_instance_size: Option<usize>,
169
170 pub pooling_max_unused_warm_slots: Option<u32>,
173
174 pub pooling_async_stack_keep_resident: Option<usize>,
177
178 pub pooling_max_component_instance_size: Option<usize>,
181
182 pub pooling_max_core_instances_per_component: Option<u32>,
185
186 pub pooling_max_memories_per_component: Option<u32>,
189
190 pub pooling_max_tables_per_component: Option<u32>,
193
194 pub pooling_max_tables_per_module: Option<u32>,
196
197 pub pooling_max_memories_per_module: Option<u32>,
199
200 pub pooling_total_gc_heaps: Option<u32>,
202
203 pub signals_based_traps: Option<bool>,
205
206 pub dynamic_memory_guard_size: Option<u64>,
208
209 pub static_memory_guard_size: Option<u64>,
211
212 pub static_memory_forced: Option<bool>,
214
215 pub static_memory_maximum_size: Option<u64>,
217
218 pub dynamic_memory_reserved_for_growth: Option<u64>,
220
221 #[serde(default)]
224 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
225 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
226 pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
227
228 #[doc(hidden)]
230 pub gc_zeal_alloc_counter: Option<NonZeroU32>,
231 }
232
233 enum Optimize {
234 ...
235 }
236}
237
238wasmtime_option_group! {
239 #[env = "CODEGEN"]
240 pub struct CodegenOptions {
241 #[serde(default)]
246 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
247 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
248 pub compiler: Option<wasmtime::Strategy>,
249 #[serde(default)]
261 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
262 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
263 pub collector: Option<wasmtime::Collector>,
264 pub cranelift_debug_verifier: Option<bool>,
266 pub cache: Option<bool>,
268 pub cache_config: Option<String>,
270 pub parallel_compilation: Option<bool>,
272 pub native_unwind_info: Option<bool>,
275 pub asan_compatible_code: Option<bool>,
279
280 #[serde(default)]
282 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
283 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
284 pub inlining: Option<wasmtime::Inlining>,
285
286 pub metadata_for_internal_asserts: Option<bool>,
289 pub metadata_for_gc_heap_corruption: Option<bool>,
292
293 #[serde(default)]
313 #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
314 #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
315 pub unsafe_intrinsics: Option<UnsafeIntrinsicsImport>,
316
317 #[serde(skip)]
340 pub compile_time_builtin: Vec<CompileTimeBuiltin>,
341
342 #[prefixed = "cranelift"]
343 #[serde(default)]
344 pub cranelift: Vec<(String, Option<String>)>,
347 }
348
349 enum Codegen {
350 ...
351 }
352}
353
354wasmtime_option_group! {
355 #[env = "DEBUG"]
356 pub struct DebugOptions {
357 pub debug_info: Option<bool>,
359 pub guest_debug: Option<bool>,
361 pub address_map: Option<bool>,
363 pub logging: Option<bool>,
365 pub log_to_files: Option<bool>,
367 pub coredump: Option<String>,
369 pub debugger: Option<PathBuf>,
372 #[serde(default)]
375 pub arg: Vec<String>,
376 pub inherit_stdin: Option<bool>,
379 pub inherit_stdout: Option<bool>,
382 pub inherit_stderr: Option<bool>,
385 pub max_backtrace: Option<usize>,
387 pub symbols: Option<bool>,
389 }
390
391 enum Debug {
392 ...
393 }
394}
395
396wasmtime_option_group! {
397 #[env = "WASM"]
398 pub struct WasmOptions {
399 pub nan_canonicalization: Option<bool>,
401 pub fuel: Option<u64>,
409 pub epoch_interruption: Option<bool>,
412 pub max_wasm_stack: Option<usize>,
415 pub async_stack_size: Option<usize>,
421 pub async_stack_zeroing: Option<bool>,
424 pub unknown_exports_allow: Option<bool>,
426 pub unknown_imports_trap: Option<bool>,
429 pub unknown_imports_default: Option<bool>,
432 pub wmemcheck: Option<bool>,
434 pub max_memory_size: Option<usize>,
439 pub max_table_elements: Option<usize>,
441 pub max_instances: Option<usize>,
443 pub max_tables: Option<usize>,
445 pub max_memories: Option<usize>,
447 pub trap_on_grow_failure: Option<bool>,
454 pub timeout: Option<NonzeroDuration>,
460 pub all_proposals: Option<bool>,
462 pub bulk_memory: Option<bool>,
464 pub multi_memory: Option<bool>,
466 pub multi_value: Option<bool>,
468 pub reference_types: Option<bool>,
470 pub simd: Option<bool>,
472 pub relaxed_simd: Option<bool>,
474 pub relaxed_simd_deterministic: Option<bool>,
483 pub tail_call: Option<bool>,
485 pub threads: Option<bool>,
487 pub shared_memory: Option<bool>,
489 pub shared_everything_threads: Option<bool>,
491 pub memory64: Option<bool>,
493 pub component_model: Option<bool>,
495 pub component_model_async: Option<bool>,
497 pub component_model_more_async_builtins: Option<bool>,
500 pub component_model_async_stackful: Option<bool>,
503 pub component_model_threading: Option<bool>,
506 pub component_model_error_context: Option<bool>,
509 pub component_model_gc: Option<bool>,
512 pub component_model_map: Option<bool>,
515 pub component_model_memory64: Option<bool>,
518 pub function_references: Option<bool>,
520 pub stack_switching: Option<bool>,
522 pub gc: Option<bool>,
524 pub custom_page_sizes: Option<bool>,
526 pub wide_arithmetic: Option<bool>,
528 pub branch_hinting: Option<bool>,
530 pub compact_imports: Option<bool>,
532 pub extended_const: Option<bool>,
534 pub exceptions: Option<bool>,
536 pub legacy_exceptions: Option<bool>,
541 pub gc_support: Option<bool>,
543 pub component_model_fixed_length_lists: Option<bool>,
546 pub component_model_implements: Option<bool>,
550 pub component_model_canonical_names: Option<bool>,
553 pub component_model_accessors: Option<bool>,
556 pub concurrency_support: Option<bool>,
559 }
560
561 enum Wasm {
562 ...
563 }
564}
565
566wasmtime_option_group! {
567 #[env = "WASI"]
568 pub struct WasiOptions {
569 pub cli: Option<bool>,
571 pub cli_exit_with_code: Option<bool>,
573 pub common: Option<bool>,
575 pub nn: Option<bool>,
577 pub threads: Option<bool>,
579 pub http: Option<bool>,
581 pub http_outgoing_body_buffer_chunks: Option<NonZeroUsize>,
585 pub http_outgoing_body_chunk_size: Option<NonZeroUsize>,
588 pub config: Option<bool>,
590 pub keyvalue: Option<bool>,
592 #[serde(default)]
595 pub tcplisten: Vec<String>,
596 pub tls: Option<bool>,
598 pub preview2: Option<bool>,
601 #[serde(skip)]
610 pub nn_graph: Vec<WasiNnGraph>,
611 pub inherit_network: Option<bool>,
614 pub allow_ip_name_lookup: Option<bool>,
616 pub tcp: Option<bool>,
618 pub udp: Option<bool>,
620 pub network_error_code: Option<bool>,
622 pub preview0: Option<bool>,
624 pub inherit_env: Option<bool>,
628 pub inherit_stdin: Option<bool>,
630 pub inherit_stdout: Option<bool>,
632 pub inherit_stderr: Option<bool>,
634 pub cwd: Option<String>,
636 #[serde(skip)]
638 pub config_var: Vec<KeyValuePair>,
639 #[serde(skip)]
641 pub keyvalue_in_memory_data: Vec<KeyValuePair>,
642 pub p3: Option<bool>,
644 pub max_resources: Option<usize>,
646 pub hostcall_fuel: Option<usize>,
648 pub max_io_size: Option<NonZeroUsize>,
652 pub max_component_handles: Option<usize>,
656 pub max_fibers: Option<u32>,
658 pub max_random_size: Option<u64>,
662 pub max_http_fields_size: Option<usize>,
666 }
667
668 enum Wasi {
669 ...
670 }
671}
672
673wasmtime_option_group! {
674 #[env = "RECORD"]
675 pub struct RecordOptions {
676 pub path: Option<String>,
678 pub validation_metadata: Option<bool>,
681 pub event_window_size: Option<usize>,
684 }
685
686 enum Record {
687 ...
688 }
689}
690
691#[derive(Debug, Clone, PartialEq)]
692pub struct WasiNnGraph {
693 pub format: String,
694 pub dir: String,
695}
696
697#[derive(Debug, Clone, PartialEq)]
698pub struct KeyValuePair {
699 pub key: String,
700 pub value: String,
701}
702
703#[derive(Debug, Clone, PartialEq)]
706pub struct UnsafeIntrinsicsImport(pub String);
707
708#[derive(Debug, Clone, PartialEq)]
710pub struct CompileTimeBuiltin {
711 pub name: String,
713 pub path: PathBuf,
715}
716
717#[derive(Clone)]
719#[cfg_attr(feature = "clap", derive(clap::Parser))]
720#[cfg_attr(
721 feature = "serde",
722 derive(serde_derive::Deserialize, serde_derive::Serialize)
723)]
724#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
725pub struct CommonOptions {
726 #[cfg_attr(
736 feature = "clap",
737 arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
738 )]
739 #[cfg_attr(feature = "serde", serde(skip))]
740 opts_raw: Vec<opt::CommaSeparated<Optimize>>,
741
742 #[cfg_attr(
744 feature = "clap",
745 arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
746 )]
747 #[cfg_attr(feature = "serde", serde(skip))]
748 codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
749
750 #[cfg_attr(
752 feature = "clap",
753 arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
754 )]
755 #[cfg_attr(feature = "serde", serde(skip))]
756 debug_raw: Vec<opt::CommaSeparated<Debug>>,
757
758 #[cfg_attr(
761 feature = "clap",
762 arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
763 )]
764 #[cfg_attr(feature = "serde", serde(skip))]
765 wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
766
767 #[cfg_attr(
769 feature = "clap",
770 arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
771 )]
772 #[cfg_attr(feature = "serde", serde(skip))]
773 wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
774
775 #[cfg_attr(
784 feature = "clap",
785 arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
786 )]
787 #[cfg_attr(feature = "serde", serde(skip))]
788 record_raw: Vec<opt::CommaSeparated<Record>>,
789
790 #[cfg_attr(feature = "clap", arg(skip))]
793 #[cfg_attr(feature = "serde", serde(skip))]
794 configured: bool,
795
796 #[cfg_attr(feature = "clap", arg(skip))]
799 #[cfg_attr(feature = "serde", serde(skip))]
800 pub ignore_env: bool,
801
802 #[cfg_attr(feature = "clap", arg(skip))]
803 #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
804 pub opts: OptimizeOptions,
805
806 #[cfg_attr(feature = "clap", arg(skip))]
807 #[cfg_attr(feature = "serde", serde(default))]
808 pub codegen: CodegenOptions,
809
810 #[cfg_attr(feature = "clap", arg(skip))]
811 #[cfg_attr(feature = "serde", serde(default))]
812 pub debug: DebugOptions,
813
814 #[cfg_attr(feature = "clap", arg(skip))]
815 #[cfg_attr(feature = "serde", serde(default))]
816 pub wasm: WasmOptions,
817
818 #[cfg_attr(feature = "clap", arg(skip))]
819 #[cfg_attr(feature = "serde", serde(default))]
820 pub wasi: WasiOptions,
821
822 #[cfg_attr(feature = "clap", arg(skip))]
823 #[cfg_attr(feature = "serde", serde(default))]
824 pub record: RecordOptions,
825
826 #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
828 #[cfg_attr(feature = "serde", serde(skip))]
829 pub target: Option<String>,
830
831 #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
838 #[cfg_attr(feature = "serde", serde(skip))]
839 pub config: Option<PathBuf>,
840}
841
842type F = WasmFeatures;
843
844static WASM_FEATURE_OPTIONS: &[(WasmFeatures, fn(&WasmOptions) -> Option<bool>, Option<&str>)] = &[
850 (F::SIMD, |w| w.simd, None),
851 (F::RELAXED_SIMD, |w| w.relaxed_simd, None),
852 (F::BULK_MEMORY, |w| w.bulk_memory, None),
853 (F::MULTI_VALUE, |w| w.multi_value, None),
854 (F::TAIL_CALL, |w| w.tail_call, None),
855 (F::MULTI_MEMORY, |w| w.multi_memory, None),
856 (F::MEMORY64, |w| w.memory64, None),
857 (F::CUSTOM_PAGE_SIZES, |w| w.custom_page_sizes, None),
858 (F::WIDE_ARITHMETIC, |w| w.wide_arithmetic, None),
859 (F::COMPACT_IMPORTS, |w| w.compact_imports, None),
860 (F::EXTENDED_CONST, |w| w.extended_const, None),
861 (F::THREADS, |w| w.threads, None),
862 (
863 F::SHARED_EVERYTHING_THREADS,
864 |w| w.shared_everything_threads,
865 None,
866 ),
867 (F::GC, |w| w.gc, None),
868 (F::GC_TYPES, |w| w.gc_support, Some("gc-support")),
869 (F::REFERENCE_TYPES, |w| w.reference_types, None),
870 (F::FUNCTION_REFERENCES, |w| w.function_references, None),
871 (F::EXCEPTIONS, |w| w.exceptions, None),
872 (F::LEGACY_EXCEPTIONS, |w| w.legacy_exceptions, None),
873 (F::STACK_SWITCHING, |w| w.stack_switching, None),
874 (F::COMPONENT_MODEL, |w| w.component_model, None),
875 (
876 F::CM_ASYNC,
877 |w| w.component_model_async,
878 Some("component-model-async"),
879 ),
880 (
881 F::CM_MORE_ASYNC_BUILTINS,
882 |w| w.component_model_more_async_builtins,
883 Some("component-model-more-async-builtins"),
884 ),
885 (
886 F::CM_ASYNC_STACKFUL,
887 |w| w.component_model_async_stackful,
888 Some("component-model-async-stackful"),
889 ),
890 (
891 F::CM_THREADING,
892 |w| w.component_model_threading,
893 Some("component-model-threading"),
894 ),
895 (
896 F::CM_ERROR_CONTEXT,
897 |w| w.component_model_error_context,
898 Some("component-model-error-context"),
899 ),
900 (
901 F::CM_MAP,
902 |w| w.component_model_map,
903 Some("component-model-map"),
904 ),
905 (
906 F::CM_FIXED_LENGTH_LISTS,
907 |w| w.component_model_fixed_length_lists,
908 Some("component-model-fixed-length-lists"),
909 ),
910 (
911 F::CM_IMPLEMENTS,
912 |w| w.component_model_implements,
913 Some("component-model-implements"),
914 ),
915 (
916 F::CM_CANON_NAMES,
917 |w| w.component_model_canonical_names,
918 Some("component-model-canonical-names"),
919 ),
920 (
921 F::CM_ACCESSORS,
922 |w| w.component_model_accessors,
923 Some("component-model-accessors"),
924 ),
925 (
926 F::CM64,
927 |w| w.component_model_memory64,
928 Some("component-model-memory64"),
929 ),
930 (
931 F::CM_GC,
932 |w| w.component_model_gc,
933 Some("component-model-gc"),
934 ),
935];
936
937macro_rules! match_feature {
938 (
939 [$feat:tt : $config:expr]
940 $val:ident => $e:expr,
941 $p:pat => err,
942 ) => {
943 #[cfg(feature = $feat)]
944 {
945 if let Some($val) = $config {
946 $e;
947 }
948 }
949 #[cfg(not(feature = $feat))]
950 {
951 if let Some($p) = $config {
952 bail!(concat!("support for ", $feat, " disabled at compile time"));
953 }
954 }
955 };
956}
957
958impl CommonOptions {
959 pub fn new() -> CommonOptions {
961 CommonOptions {
962 opts_raw: Vec::new(),
963 codegen_raw: Vec::new(),
964 debug_raw: Vec::new(),
965 wasm_raw: Vec::new(),
966 wasi_raw: Vec::new(),
967 record_raw: Vec::new(),
968 configured: true,
969 ignore_env: false,
970 opts: Default::default(),
971 codegen: Default::default(),
972 debug: Default::default(),
973 wasm: Default::default(),
974 wasi: Default::default(),
975 record: Default::default(),
976 target: None,
977 config: None,
978 }
979 }
980
981 fn configure(&mut self) -> Result<()> {
982 if self.configured {
983 return Ok(());
984 }
985 self.configured = true;
986 if let Some(toml_config_path) = &self.config {
987 #[cfg(feature = "toml")]
988 {
989 let toml_options = CommonOptions::from_file(toml_config_path)?;
990 self.opts = toml_options.opts;
991 self.codegen = toml_options.codegen;
992 self.debug = toml_options.debug;
993 self.wasm = toml_options.wasm;
994 self.wasi = toml_options.wasi;
995 self.record = toml_options.record;
996 }
997 #[cfg(not(feature = "toml"))]
998 {
999 bail!(
1000 "support for loading a configuration file from \
1001 {toml_config_path:?} disabled at compile time"
1002 );
1003 }
1004 }
1005 self.opts.configure_with(&self.opts_raw, !self.ignore_env)?;
1006 self.codegen
1007 .configure_with(&self.codegen_raw, !self.ignore_env)?;
1008 self.debug
1009 .configure_with(&self.debug_raw, !self.ignore_env)?;
1010 self.wasm.configure_with(&self.wasm_raw, !self.ignore_env)?;
1011 self.wasi.configure_with(&self.wasi_raw, !self.ignore_env)?;
1012 self.record
1013 .configure_with(&self.record_raw, !self.ignore_env)?;
1014 Ok(())
1015 }
1016
1017 pub fn merge(&mut self, other: &mut CommonOptions) -> Result<()> {
1022 self.configure()?;
1023 other.configure()?;
1024 let CommonOptions {
1025 opts_raw: _,
1027 codegen_raw: _,
1028 debug_raw: _,
1029 wasm_raw: _,
1030 wasi_raw: _,
1031 record_raw: _,
1032 configured: _,
1033 ignore_env: _,
1034 config: _,
1035
1036 opts,
1037 codegen,
1038 debug,
1039 wasm,
1040 wasi,
1041 record,
1042 target,
1043 } = other;
1044 for opt in opts.to_options() {
1045 self.opts.configure(&opt);
1046 }
1047 for opt in codegen.to_options() {
1048 self.codegen.configure(&opt);
1049 }
1050 for opt in debug.to_options() {
1051 self.debug.configure(&opt);
1052 }
1053 for opt in wasm.to_options() {
1054 self.wasm.configure(&opt);
1055 }
1056 for opt in wasi.to_options() {
1057 self.wasi.configure(&opt);
1058 }
1059 for opt in record.to_options() {
1060 self.record.configure(&opt);
1061 }
1062 if target.is_some() {
1063 self.target = target.clone();
1064 }
1065 Ok(())
1066 }
1067
1068 pub fn init_logging(&mut self) -> Result<()> {
1069 self.configure()?;
1070 if self.debug.logging == Some(false) {
1071 return Ok(());
1072 }
1073 #[cfg(feature = "logging")]
1074 if self.debug.log_to_files == Some(true) {
1075 let prefix = "wasmtime.dbg.";
1076 init_file_per_thread_logger(prefix);
1077 } else {
1078 use std::io::IsTerminal;
1079 use tracing_subscriber::{EnvFilter, FmtSubscriber};
1080 let builder = FmtSubscriber::builder()
1081 .with_writer(std::io::stderr)
1082 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
1083 .with_ansi(std::io::stderr().is_terminal());
1084 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
1085 builder
1086 .with_level(false)
1087 .with_target(false)
1088 .without_time()
1089 .init()
1090 } else {
1091 builder.init();
1092 }
1093 }
1094 #[cfg(not(feature = "logging"))]
1095 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
1096 bail!("support for logging disabled at compile time");
1097 }
1098 Ok(())
1099 }
1100
1101 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
1104 let mut config = Config::new();
1105 self.apply_config(&mut config, pooling_allocator_default)?;
1106 Ok(config)
1107 }
1108
1109 pub fn apply_config(
1111 &mut self,
1112 config: &mut Config,
1113 pooling_allocator_default: Option<bool>,
1114 ) -> Result<()> {
1115 self.configure()?;
1116
1117 match_feature! {
1118 ["cranelift" : self.codegen.compiler]
1119 strategy => config.strategy(strategy),
1120 _ => err,
1121 }
1122 match_feature! {
1123 ["gc" : self.codegen.collector]
1124 collector => config.collector(collector),
1125 _ => err,
1126 }
1127 if let Some(target) = &self.target {
1128 config.target(target)?;
1129 }
1130 match_feature! {
1131 ["cranelift" : self.codegen.cranelift_debug_verifier]
1132 enable => config.cranelift_debug_verifier(enable),
1133 true => err,
1134 }
1135 if let Some(enable) = self.debug.debug_info {
1136 config.debug_info(enable);
1137 }
1138 match_feature! {
1139 ["debug" : self.debug.guest_debug]
1140 enable => config.guest_debug(enable),
1141 _ => err,
1142 }
1143 if self.debug.coredump.is_some() {
1144 #[cfg(feature = "coredump")]
1145 config.coredump_on_trap(true);
1146 #[cfg(not(feature = "coredump"))]
1147 bail!("support for coredumps disabled at compile time");
1148 }
1149 match_feature! {
1150 ["cranelift" : self.opts.opt_level]
1151 level => config.cranelift_opt_level(level),
1152 _ => err,
1153 }
1154 match_feature! {
1155 ["cranelift": self.opts.regalloc_algorithm]
1156 algo => config.cranelift_regalloc_algorithm(algo),
1157 _ => err,
1158 }
1159 match_feature! {
1160 ["cranelift" : self.wasm.nan_canonicalization]
1161 enable => config.cranelift_nan_canonicalization(enable),
1162 true => err,
1163 }
1164
1165 self.enable_wasm_features(config)?;
1166
1167 #[cfg(feature = "cranelift")]
1168 for (name, value) in self.codegen.cranelift.iter() {
1169 let name = name.replace('-', "_");
1170 unsafe {
1171 match value {
1172 Some(val) => {
1173 config.cranelift_flag_set(&name, val);
1174 }
1175 None => {
1176 config.cranelift_flag_enable(&name);
1177 }
1178 }
1179 }
1180 }
1181 #[cfg(not(feature = "cranelift"))]
1182 if !self.codegen.cranelift.is_empty() {
1183 bail!("support for cranelift disabled at compile time");
1184 }
1185
1186 #[cfg(feature = "cache")]
1187 if self.codegen.cache != Some(false) {
1188 use wasmtime::Cache;
1189 let cache = match &self.codegen.cache_config {
1190 Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
1191 None => Cache::from_file(None)?,
1192 };
1193 config.cache(Some(cache));
1194 }
1195 #[cfg(not(feature = "cache"))]
1196 if self.codegen.cache == Some(true) {
1197 bail!("support for caching disabled at compile time");
1198 }
1199
1200 match_feature! {
1201 ["parallel-compilation" : self.codegen.parallel_compilation]
1202 enable => config.parallel_compilation(enable),
1203 true => err,
1204 }
1205
1206 let memory_reservation = self
1207 .opts
1208 .memory_reservation
1209 .or(self.opts.static_memory_maximum_size);
1210 if let Some(size) = memory_reservation {
1211 config.memory_reservation(size);
1212 }
1213
1214 if let Some(enable) = self.opts.static_memory_forced {
1215 config.memory_may_move(!enable);
1216 }
1217 if let Some(enable) = self.opts.memory_may_move {
1218 config.memory_may_move(enable);
1219 }
1220
1221 let memory_guard_size = self
1222 .opts
1223 .static_memory_guard_size
1224 .or(self.opts.dynamic_memory_guard_size)
1225 .or(self.opts.memory_guard_size);
1226 if let Some(size) = memory_guard_size {
1227 config.memory_guard_size(size);
1228 }
1229
1230 let mem_for_growth = self
1231 .opts
1232 .memory_reservation_for_growth
1233 .or(self.opts.dynamic_memory_reserved_for_growth);
1234 if let Some(size) = mem_for_growth {
1235 config.memory_reservation_for_growth(size);
1236 }
1237 if let Some(enable) = self.opts.guard_before_linear_memory {
1238 config.guard_before_linear_memory(enable);
1239 }
1240
1241 if let Some(size) = self.opts.gc_heap_reservation {
1242 config.gc_heap_reservation(size);
1243 }
1244 if let Some(enable) = self.opts.gc_heap_may_move {
1245 config.gc_heap_may_move(enable);
1246 }
1247 if let Some(size) = self.opts.gc_heap_guard_size {
1248 config.gc_heap_guard_size(size);
1249 }
1250 if let Some(size) = self.opts.gc_heap_reservation_for_growth {
1251 config.gc_heap_reservation_for_growth(size);
1252 }
1253
1254 if let Some(size) = self.opts.gc_heap_initial_size {
1255 config.gc_heap_initial_size(size);
1256 }
1257
1258 if let Some(enable) = self.opts.table_lazy_init {
1259 config.table_lazy_init(enable);
1260 }
1261
1262 if let Some(n) = self.opts.gc_zeal_alloc_counter
1263 && (cfg!(gc_zeal) || cfg!(fuzzing))
1264 {
1265 config.gc_zeal_alloc_counter(Some(n))?;
1266 }
1267
1268 if self.wasm.fuel.is_some() {
1270 config.consume_fuel(true);
1271 }
1272
1273 if let Some(enable) = self.wasm.epoch_interruption {
1274 config.epoch_interruption(enable);
1275 }
1276 if let Some(enable) = self.debug.address_map {
1277 config.generate_address_map(enable);
1278 }
1279 if let Some(frames) = self.debug.max_backtrace {
1280 match NonZeroUsize::new(frames) {
1281 None => {
1282 config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1283 }
1284 Some(amt) => {
1285 config.wasm_backtrace_max_frames(Some(amt));
1286 }
1287 }
1288 }
1289 if let Some(enable) = self.debug.symbols {
1290 config.debug_symbols(enable);
1291 }
1292 if let Some(enable) = self.opts.memory_init_cow {
1293 config.memory_init_cow(enable);
1294 }
1295 if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1296 config.memory_guaranteed_dense_image_size(size);
1297 }
1298 if let Some(enable) = self.opts.signals_based_traps {
1299 config.signals_based_traps(enable);
1300 }
1301 if let Some(enable) = self.codegen.native_unwind_info {
1302 config.native_unwind_info(enable);
1303 }
1304 if let Some(enable) = self.codegen.asan_compatible_code {
1305 config.asan_compatible_code(enable);
1306 }
1307 if let Some(enable) = self.codegen.inlining {
1308 config.compiler_inlining(enable);
1309 }
1310 if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1311 config.metadata_for_internal_asserts(enable);
1312 }
1313 if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1314 config.metadata_for_gc_heap_corruption(enable);
1315 }
1316
1317 #[cfg(any(feature = "async", feature = "stack-switching"))]
1320 {
1321 if let Some(size) = self.wasm.async_stack_size {
1322 config.async_stack_size(size);
1323 }
1324 }
1325 #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1326 {
1327 if let Some(_size) = self.wasm.async_stack_size {
1328 bail!(concat!(
1329 "support for async/stack-switching disabled at compile time"
1330 ));
1331 }
1332 }
1333
1334 match_feature! {
1335 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1336 enable => {
1337 if enable {
1338 let mut cfg = wasmtime::PoolingAllocationConfig::default();
1339 if let Some(size) = self.opts.pooling_memory_keep_resident {
1340 cfg.linear_memory_keep_resident(size);
1341 }
1342 if let Some(size) = self.opts.pooling_table_keep_resident {
1343 cfg.table_keep_resident(size);
1344 }
1345 if let Some(limit) = self.opts.pooling_total_core_instances {
1346 cfg.total_core_instances(limit);
1347 }
1348 if let Some(limit) = self.opts.pooling_total_component_instances {
1349 cfg.total_component_instances(limit);
1350 }
1351 if let Some(limit) = self.opts.pooling_total_memories {
1352 cfg.total_memories(limit);
1353 }
1354 if let Some(limit) = self.opts.pooling_total_tables {
1355 cfg.total_tables(limit);
1356 }
1357 if let Some(limit) = self.opts.pooling_table_elements
1358 .or(self.wasm.max_table_elements)
1359 {
1360 cfg.table_elements(limit);
1361 }
1362 if let Some(limit) = self.opts.pooling_max_core_instance_size {
1363 cfg.max_core_instance_size(limit);
1364 }
1365 match_feature! {
1366 ["async" : self.opts.pooling_total_stacks]
1367 limit => cfg.total_stacks(limit),
1368 _ => err,
1369 }
1370 if let Some(max) = self.opts.pooling_max_memory_size
1371 .or(self.wasm.max_memory_size)
1372 {
1373 cfg.max_memory_size(max);
1374 }
1375 if let Some(size) = self.opts.pooling_decommit_batch_size {
1376 cfg.decommit_batch_size(size);
1377 }
1378 if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1379 cfg.max_unused_warm_slots(max);
1380 }
1381 match_feature! {
1382 ["async" : self.opts.pooling_async_stack_keep_resident]
1383 size => cfg.async_stack_keep_resident(size),
1384 _ => err,
1385 }
1386 if let Some(max) = self.opts.pooling_max_component_instance_size {
1387 cfg.max_component_instance_size(max);
1388 }
1389 if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1390 cfg.max_core_instances_per_component(max);
1391 }
1392 if let Some(max) = self.opts.pooling_max_memories_per_component {
1393 cfg.max_memories_per_component(max);
1394 }
1395 if let Some(max) = self.opts.pooling_max_tables_per_component {
1396 cfg.max_tables_per_component(max);
1397 }
1398 if let Some(max) = self.opts.pooling_max_tables_per_module {
1399 cfg.max_tables_per_module(max);
1400 }
1401 if let Some(max) = self.opts.pooling_max_memories_per_module {
1402 cfg.max_memories_per_module(max);
1403 }
1404 match_feature! {
1405 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1406 enable => cfg.memory_protection_keys(enable),
1407 _ => err,
1408 }
1409 match_feature! {
1410 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1411 max => cfg.max_memory_protection_keys(max),
1412 _ => err,
1413 }
1414 match_feature! {
1415 ["gc" : self.opts.pooling_total_gc_heaps]
1416 max => cfg.total_gc_heaps(max),
1417 _ => err,
1418 }
1419 if let Some(enabled) = self.opts.pooling_pagemap_scan {
1420 cfg.pagemap_scan(enabled);
1421 }
1422 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1423 }
1424 },
1425 true => err,
1426 }
1427
1428 if self.opts.pooling_memory_protection_keys.is_some()
1429 && !self.opts.pooling_allocator.unwrap_or(false)
1430 {
1431 bail!("memory protection keys require the pooling allocator");
1432 }
1433
1434 if self.opts.pooling_max_memory_protection_keys.is_some()
1435 && !self.opts.pooling_memory_protection_keys.is_some()
1436 {
1437 bail!("max memory protection keys requires memory protection keys to be enabled");
1438 }
1439
1440 match_feature! {
1441 ["async" : self.wasm.async_stack_zeroing]
1442 enable => config.async_stack_zeroing(enable),
1443 _ => err,
1444 }
1445
1446 if let Some(max) = self.wasm.max_wasm_stack {
1447 config.max_wasm_stack(max);
1448
1449 #[cfg(any(feature = "async", feature = "stack-switching"))]
1453 if self.wasm.async_stack_size.is_none() {
1454 const DEFAULT_HOST_STACK: usize = 512 << 10;
1455 config.async_stack_size(max.saturating_add(DEFAULT_HOST_STACK));
1456 }
1457 }
1458
1459 if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1460 config.relaxed_simd_deterministic(enable);
1461 }
1462 match_feature! {
1463 ["cranelift" : self.wasm.wmemcheck]
1464 enable => config.wmemcheck(enable),
1465 true => err,
1466 }
1467
1468 if let Some(enable) = self.wasm.concurrency_support {
1469 config.concurrency_support(enable);
1470 }
1471
1472 if let Some(enable) = self.wasm.shared_memory {
1473 config.shared_memory(enable);
1474 }
1475
1476 let record = &self.record;
1477 match_feature! {
1478 ["rr" : &record.path]
1479 _path => {
1480 bail!("recording configuration for `rr` feature is not supported yet");
1481 },
1482 _ => err,
1483 }
1484
1485 Ok(())
1486 }
1487
1488 #[cfg(feature = "runtime")]
1494 pub fn configure_store<T>(&self, store: &mut wasmtime::Store<T>) -> Result<()> {
1495 debug_assert!(self.configured, "`config` or `apply_config` not called");
1496 #[cfg(feature = "component-model")]
1497 {
1498 if let Some(fuel) = self.wasi.hostcall_fuel {
1499 store.set_hostcall_fuel(fuel);
1500 }
1501 if let Some(max) = self.wasi.max_component_handles {
1502 store.set_max_component_handles(max);
1503 }
1504 }
1505 #[cfg(feature = "async")]
1506 if let Some(max) = self.wasi.max_fibers {
1507 store.set_max_fibers(max);
1508 }
1509 if let Some(fuel) = self.wasm.fuel {
1510 store.set_fuel(fuel)?;
1511 }
1512 Ok(())
1513 }
1514
1515 fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1516 let all = self.wasm.all_proposals;
1517 for (feature, option, _) in WASM_FEATURE_OPTIONS {
1518 let mut value = option(&self.wasm);
1519 if *feature != F::LEGACY_EXCEPTIONS {
1521 value = value.or(all);
1522 }
1523 if let Some(enable) = value {
1524 config.wasm_features(*feature, enable);
1525 }
1526 }
1527
1528 if let Some(enable) = self.wasm.branch_hinting.or(all) {
1531 config.wasm_branch_hinting(enable);
1532 }
1533
1534 Ok(())
1535 }
1536
1537 pub fn wasm_features_specified(&self) -> Vec<String> {
1542 let mut ret = Vec::new();
1543 for (feature, option, name) in WASM_FEATURE_OPTIONS {
1544 if option(&self.wasm).is_none() {
1545 continue;
1546 }
1547 ret.push(match name {
1548 Some(name) => name.to_string(),
1549 None => {
1550 let (name, _) = feature.iter_names().next().unwrap();
1551 name.to_lowercase().replace('_', "-")
1552 }
1553 });
1554 }
1555 if self.wasm.all_proposals.is_some() {
1556 ret.push("all-proposals".to_string());
1557 }
1558 ret
1559 }
1560
1561 #[cfg(feature = "toml")]
1562 pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1563 use wasmtime::error::Context;
1564
1565 let path_ref = path.as_ref();
1566 let file_contents = std::fs::read_to_string(path_ref)
1567 .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1568 toml::from_str::<CommonOptions>(&file_contents)
1569 .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1570 }
1571
1572 pub fn from_engine(engine: &Engine) -> Self {
1585 let features = engine.get_wasm_features();
1586 let pooling = engine.get_pooling_config();
1587 CommonOptions {
1588 target: engine.get_target(),
1589 opts: OptimizeOptions {
1590 memory_may_move: Some(engine.get_memory_may_move()),
1591 memory_reservation: Some(engine.get_memory_reservation()),
1592 memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1593 memory_guard_size: Some(engine.get_memory_guard_size()),
1594 gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1595 gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1596 gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1597 gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1598 gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1599 guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1600 table_lazy_init: Some(engine.get_table_lazy_init()),
1601 memory_init_cow: Some(engine.get_memory_init_cow()),
1602 memory_guaranteed_dense_image_size: Some(
1603 engine.get_memory_guaranteed_dense_image_size(),
1604 ),
1605 signals_based_traps: Some(engine.get_signals_based_traps()),
1606 gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1607 opt_level: engine.get_cranelift_opt_level(),
1608 regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1609 pooling_allocator: Some(pooling.is_some()),
1610 pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1611 pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1612 pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1613 pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1614 pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1615 pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1616 pooling_total_component_instances: pooling
1617 .map(|c| c.get_total_component_instances()),
1618 pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1619 pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1620 pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1621 pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1622 pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1623 pooling_max_component_instance_size: pooling
1624 .map(|c| c.get_max_component_instance_size()),
1625 pooling_max_core_instances_per_component: pooling
1626 .map(|c| c.get_max_core_instances_per_component()),
1627 pooling_max_memories_per_component: pooling
1628 .map(|c| c.get_max_memories_per_component()),
1629 pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1630 pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1631 pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1632 pooling_async_stack_keep_resident: pooling
1633 .map(|c| c.get_async_stack_keep_resident()),
1634 pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1635 pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1636 pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1637 pooling_max_memory_protection_keys: pooling
1638 .map(|c| c.get_max_memory_protection_keys()),
1639 dynamic_memory_guard_size: None,
1642 static_memory_guard_size: None,
1643 static_memory_forced: None,
1644 static_memory_maximum_size: None,
1645 dynamic_memory_reserved_for_growth: None,
1646 },
1647 codegen: CodegenOptions {
1648 compiler: engine.get_strategy(),
1649 collector: engine.get_collector(),
1650 cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1651 inlining: Some(engine.get_compiler_inlining()),
1652 native_unwind_info: engine.get_native_unwind_info(),
1653 asan_compatible_code: Some(engine.get_asan_compatible_code()),
1654 parallel_compilation: Some(engine.get_parallel_compilation()),
1655 metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1656 metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1657 cranelift: engine
1658 .get_cranelift_flags_set()
1659 .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1660 .chain(
1661 engine
1662 .get_cranelift_flags_enabled()
1663 .map(|k| (k.to_string(), None)),
1664 )
1665 .collect(),
1666
1667 cache: None,
1670 cache_config: None,
1671
1672 unsafe_intrinsics: None,
1675 compile_time_builtin: Vec::new(),
1676 },
1677 debug: DebugOptions {
1678 address_map: Some(engine.get_generate_address_map()),
1679 debug_info: Some(engine.get_debug_info()),
1680 guest_debug: Some(engine.get_guest_debug()),
1681 symbols: Some(engine.get_debug_symbols()),
1682 max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1683
1684 coredump: None,
1687 debugger: None,
1689 arg: Vec::new(),
1690 inherit_stderr: None,
1691 inherit_stdout: None,
1692 inherit_stdin: None,
1693 log_to_files: None,
1695 logging: None,
1696 },
1697 wasm: WasmOptions {
1698 async_stack_size: Some(engine.get_async_stack_size()),
1699 async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1700 branch_hinting: Some(engine.get_wasm_branch_hinting()),
1701 compact_imports: Some(features.contains(WasmFeatures::COMPACT_IMPORTS)),
1702 bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1703 component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1704 component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1705 component_model_async_stackful: Some(
1706 features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1707 ),
1708 component_model_error_context: Some(
1709 features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1710 ),
1711 component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1712 component_model_fixed_length_lists: Some(
1713 features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1714 ),
1715 component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1716 component_model_canonical_names: Some(
1717 features.contains(WasmFeatures::CM_CANON_NAMES),
1718 ),
1719 component_model_accessors: Some(features.contains(WasmFeatures::CM_ACCESSORS)),
1720 component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1721 component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1722 component_model_more_async_builtins: Some(
1723 features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1724 ),
1725 component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1726 custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1727 exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1728 legacy_exceptions: Some(features.contains(WasmFeatures::LEGACY_EXCEPTIONS)),
1729 extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1730 function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1731 gc: Some(features.contains(WasmFeatures::GC)),
1732 gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1733 memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1734 multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1735 multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1736 reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1737 relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1738 shared_everything_threads: Some(
1739 features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1740 ),
1741 simd: Some(features.contains(WasmFeatures::SIMD)),
1742 stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1743 tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1744 threads: Some(features.contains(WasmFeatures::THREADS)),
1745 wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1746 concurrency_support: Some(engine.get_concurrency_support()),
1747 epoch_interruption: Some(engine.get_epoch_interruption()),
1748 fuel: if engine.get_consume_fuel() {
1749 Some(1)
1750 } else {
1751 None
1752 },
1753 max_wasm_stack: Some(engine.get_max_wasm_stack()),
1754 nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1755 relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1756 shared_memory: Some(engine.get_shared_memory()),
1757
1758 all_proposals: None,
1760 max_instances: None,
1763 max_memories: None,
1764 max_memory_size: None,
1765 max_table_elements: None,
1766 max_tables: None,
1767 timeout: None,
1769 trap_on_grow_failure: None,
1770 unknown_exports_allow: None,
1771 unknown_imports_default: None,
1772 unknown_imports_trap: None,
1773 wmemcheck: None,
1774 },
1775
1776 record: RecordOptions::default(),
1778
1779 wasi: Default::default(),
1781
1782 configured: true,
1784 ignore_env: false,
1785 codegen_raw: Default::default(),
1786 debug_raw: Default::default(),
1787 opts_raw: Default::default(),
1788 record_raw: Default::default(),
1789 wasi_raw: Default::default(),
1790 wasm_raw: Default::default(),
1791
1792 config: None,
1794 }
1799 }
1800}
1801
1802#[cfg(test)]
1803mod tests {
1804 use wasmtime::{OptLevel, RegallocAlgorithm};
1805
1806 use super::*;
1807
1808 #[test]
1809 fn from_toml() {
1810 let empty_toml = "";
1812 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1813 common_options.config(None).unwrap();
1814
1815 let basic_toml = r#"
1817 [optimize]
1818 [codegen]
1819 [debug]
1820 [wasm]
1821 [wasi]
1822 [record]
1823 "#;
1824 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1825 common_options.config(None).unwrap();
1826
1827 for (opt_value, expected) in [
1829 ("0", Some(OptLevel::None)),
1830 ("1", Some(OptLevel::Speed)),
1831 ("2", Some(OptLevel::Speed)),
1832 ("\"s\"", Some(OptLevel::SpeedAndSize)),
1833 ("\"hello\"", None), ("3", None), ] {
1836 let toml = format!(
1837 r#"
1838 [optimize]
1839 opt-level = {opt_value}
1840 "#,
1841 );
1842 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1843 .ok()
1844 .and_then(|common_options| common_options.opts.opt_level);
1845
1846 assert_eq!(
1847 parsed_opt_level, expected,
1848 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1849 );
1850 }
1851
1852 for (regalloc_value, expected) in [
1854 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1855 ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1856 ("\"hello\"", None), ("3", None), ("true", None), ] {
1860 let toml = format!(
1861 r#"
1862 [optimize]
1863 regalloc-algorithm = {regalloc_value}
1864 "#,
1865 );
1866 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1867 .ok()
1868 .and_then(|common_options| common_options.opts.regalloc_algorithm);
1869 assert_eq!(
1870 parsed_regalloc_algorithm, expected,
1871 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1872 );
1873 }
1874
1875 for (strategy_value, expected) in [
1877 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1878 ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1879 ("\"hello\"", None), ("5", None), ("true", None), ] {
1883 let toml = format!(
1884 r#"
1885 [codegen]
1886 compiler = {strategy_value}
1887 "#,
1888 );
1889 let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1890 .ok()
1891 .and_then(|common_options| common_options.codegen.compiler);
1892 assert_eq!(
1893 parsed_strategy, expected,
1894 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1895 );
1896 }
1897
1898 for (collector_value, expected) in [
1900 (
1901 "\"drc\"",
1902 Some(wasmtime::Collector::DeferredReferenceCounting),
1903 ),
1904 ("\"null\"", Some(wasmtime::Collector::Null)),
1905 ("\"copying\"", Some(wasmtime::Collector::Copying)),
1906 ("\"hello\"", None), ("5", None), ("true", None), ] {
1910 let toml = format!(
1911 r#"
1912 [codegen]
1913 collector = {collector_value}
1914 "#,
1915 );
1916 let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1917 .ok()
1918 .and_then(|common_options| common_options.codegen.collector);
1919 assert_eq!(
1920 parsed_collector, expected,
1921 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1922 );
1923 }
1924 }
1925}
1926
1927impl Default for CommonOptions {
1928 fn default() -> CommonOptions {
1929 CommonOptions::new()
1930 }
1931}
1932
1933impl fmt::Display for CommonOptions {
1934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1935 let CommonOptions {
1936 codegen_raw,
1937 codegen,
1938 debug_raw,
1939 debug,
1940 opts_raw,
1941 opts,
1942 wasm_raw,
1943 wasm,
1944 wasi_raw,
1945 wasi,
1946 record_raw,
1947 record,
1948 configured,
1949 ignore_env: _,
1950 target,
1951 config,
1952 } = self;
1953 if let Some(target) = target {
1954 write!(f, "--target {target} ")?;
1955 }
1956 if let Some(config) = config {
1957 write!(f, "--config {} ", config.display())?;
1958 }
1959
1960 let codegen_flags;
1961 let opts_flags;
1962 let wasi_flags;
1963 let wasm_flags;
1964 let debug_flags;
1965 let record_flags;
1966
1967 if *configured {
1968 codegen_flags = codegen.to_options();
1969 debug_flags = debug.to_options();
1970 wasi_flags = wasi.to_options();
1971 wasm_flags = wasm.to_options();
1972 opts_flags = opts.to_options();
1973 record_flags = record.to_options();
1974 } else {
1975 codegen_flags = codegen_raw
1976 .iter()
1977 .flat_map(|t| t.0.iter())
1978 .cloned()
1979 .collect();
1980 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1981 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1982 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1983 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1984 record_flags = record_raw
1985 .iter()
1986 .flat_map(|t| t.0.iter())
1987 .cloned()
1988 .collect();
1989 }
1990
1991 for flag in codegen_flags {
1992 write!(f, "-C{flag} ")?;
1993 }
1994 for flag in opts_flags {
1995 write!(f, "-O{flag} ")?;
1996 }
1997 for flag in wasi_flags {
1998 write!(f, "-S{flag} ")?;
1999 }
2000 for flag in wasm_flags {
2001 write!(f, "-W{flag} ")?;
2002 }
2003 for flag in debug_flags {
2004 write!(f, "-D{flag} ")?;
2005 }
2006 for flag in record_flags {
2007 write!(f, "-R{flag} ")?;
2008 }
2009
2010 Ok(())
2011 }
2012}