wasmer_types/
features.rs

1use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
2#[cfg(feature = "enable-serde")]
3use serde::{Deserialize, Serialize};
4#[cfg(feature = "detect-wasm-features")]
5use wasmparser::{Parser, Payload, Validator, WasmFeatures};
6
7/// Controls which experimental features will be enabled.
8/// Features usually have a corresponding [WebAssembly proposal].
9///
10/// [WebAssembly proposal]: https://github.com/WebAssembly/proposals
11#[derive(Clone, Debug, Eq, PartialEq, Hash)]
12#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
13#[cfg_attr(feature = "artifact-size", derive(loupe::MemoryUsage))]
14#[derive(RkyvSerialize, RkyvDeserialize, Archive)]
15#[rkyv(derive(Debug), compare(PartialEq))]
16pub struct Features {
17    /// Threads proposal should be enabled
18    pub threads: bool,
19    /// Reference Types proposal should be enabled
20    pub reference_types: bool,
21    /// SIMD proposal should be enabled
22    pub simd: bool,
23    /// Bulk Memory proposal should be enabled
24    pub bulk_memory: bool,
25    /// Multi Value proposal should be enabled
26    pub multi_value: bool,
27    /// Tail call proposal should be enabled
28    pub tail_call: bool,
29    /// Module Linking proposal should be enabled
30    pub module_linking: bool,
31    /// Multi Memory proposal should be enabled
32    pub multi_memory: bool,
33    /// 64-bit Memory proposal should be enabled
34    pub memory64: bool,
35    /// Wasm exceptions proposal should be enabled
36    pub exceptions: bool,
37    /// Relaxed SIMD proposal should be enabled
38    pub relaxed_simd: bool,
39    /// Extended constant expressions proposal should be enabled
40    pub extended_const: bool,
41    /// Wide Arithmetic proposal should be enabled
42    pub wide_arithmetic: bool,
43}
44
45impl Features {
46    /// Create a new feature
47    pub fn new() -> Self {
48        Self {
49            threads: true,
50            // Reference types should be on by default
51            reference_types: true,
52            // SIMD should be on by default
53            simd: true,
54            // Bulk Memory should be on by default
55            bulk_memory: true,
56            // Multivalue should be on by default
57            multi_value: true,
58            tail_call: false,
59            module_linking: false,
60            // Multi-memory should be on by default
61            multi_memory: true,
62            memory64: false,
63            exceptions: false,
64            relaxed_simd: false,
65            wide_arithmetic: false,
66            // Extended Constant Expressions should be on by default
67            extended_const: true,
68        }
69    }
70
71    /// Create a new feature set with all features enabled.
72    pub fn all() -> Self {
73        Self {
74            threads: true,
75            reference_types: true,
76            simd: true,
77            bulk_memory: true,
78            multi_value: true,
79            tail_call: true,
80            module_linking: true,
81            multi_memory: true,
82            memory64: true,
83            exceptions: true,
84            relaxed_simd: true,
85            extended_const: true,
86            wide_arithmetic: true,
87        }
88    }
89
90    /// Create a new feature set with all features disabled.
91    pub fn none() -> Self {
92        Self {
93            threads: false,
94            reference_types: false,
95            simd: false,
96            bulk_memory: false,
97            multi_value: false,
98            tail_call: false,
99            module_linking: false,
100            multi_memory: false,
101            memory64: false,
102            exceptions: false,
103            relaxed_simd: false,
104            extended_const: false,
105            wide_arithmetic: false,
106        }
107    }
108
109    /// Configures whether the WebAssembly threads proposal will be enabled.
110    ///
111    /// The [WebAssembly threads proposal][threads] is not currently fully
112    /// standardized and is undergoing development. Support for this feature can
113    /// be enabled through this method for appropriate WebAssembly modules.
114    ///
115    /// This feature gates items such as shared memories and atomic
116    /// instructions.
117    ///
118    /// This is `true` by default.
119    ///
120    /// [threads]: https://github.com/webassembly/threads
121    pub fn threads(&mut self, enable: bool) -> &mut Self {
122        self.threads = enable;
123        self
124    }
125
126    /// Configures whether the WebAssembly reference types proposal will be
127    /// enabled.
128    ///
129    /// The [WebAssembly reference types proposal][proposal] is now
130    /// fully standardized and enabled by default.
131    ///
132    /// This feature gates items such as the `externref` type and multiple tables
133    /// being in a module. Note that enabling the reference types feature will
134    /// also enable the bulk memory feature.
135    ///
136    /// This is `true` by default.
137    ///
138    /// [proposal]: https://github.com/webassembly/reference-types
139    pub fn reference_types(&mut self, enable: bool) -> &mut Self {
140        self.reference_types = enable;
141        // The reference types proposal depends on the bulk memory proposal
142        if enable {
143            self.bulk_memory(true);
144        }
145        self
146    }
147
148    /// Configures whether the WebAssembly SIMD proposal will be
149    /// enabled.
150    ///
151    /// The [WebAssembly SIMD proposal][proposal] is now
152    /// fully standardized.
153    /// Support for this feature can be enabled through this method
154    /// for appropriate WebAssembly modules.
155    ///
156    /// This feature gates items such as the `v128` type and all of its
157    /// operators being in a module.
158    ///
159    /// This is `true` by default.
160    ///
161    /// [proposal]: https://github.com/webassembly/simd
162    pub fn simd(&mut self, enable: bool) -> &mut Self {
163        self.simd = enable;
164        self
165    }
166
167    /// Configures whether the WebAssembly Relaxed SIMD proposal will be
168    /// enabled.
169    ///
170    /// The [WebAssembly Relaxed SIMD proposal][proposal] is now
171    /// fully standardized.
172    /// Support for this feature can be enabled through this method
173    /// for appropriate WebAssembly modules.
174    ///
175    /// This is `false` by default.
176    ///
177    /// [proposal]: https://github.com/WebAssembly/relaxed-simd
178    pub fn relaxed_simd(&mut self, enable: bool) -> &mut Self {
179        self.relaxed_simd = enable;
180        self
181    }
182
183    /// Configures whether the WebAssembly bulk memory operations proposal will
184    /// be enabled.
185    ///
186    /// The [WebAssembly bulk memory operations proposal][proposal] is now
187    /// fully standardized and enabled by default.
188    ///
189    /// This feature gates items such as the `memory.copy` instruction, passive
190    /// data/table segments, etc, being in a module.
191    ///
192    /// This is `true` by default.
193    ///
194    /// [proposal]: https://github.com/webassembly/bulk-memory-operations
195    pub fn bulk_memory(&mut self, enable: bool) -> &mut Self {
196        self.bulk_memory = enable;
197        // In case is false, we disable both threads and reference types
198        // since they both depend on bulk memory
199        if !enable {
200            self.reference_types(false);
201        }
202        self
203    }
204
205    /// Configures whether the WebAssembly multi-value proposal will
206    /// be enabled.
207    ///
208    /// The [WebAssembly multi-value proposal][proposal] is now fully
209    /// standardized and enabled by default.
210    ///
211    /// This feature gates functions and blocks returning multiple values in a
212    /// module, for example.
213    ///
214    /// This is `true` by default.
215    ///
216    /// [proposal]: https://github.com/webassembly/multi-value
217    pub fn multi_value(&mut self, enable: bool) -> &mut Self {
218        self.multi_value = enable;
219        self
220    }
221
222    /// Configures whether the WebAssembly tail-call proposal will
223    /// be enabled.
224    ///
225    /// The [WebAssembly tail-call proposal][proposal] is now
226    /// fully standardized.
227    /// Support for this feature can be enabled through this method
228    /// for appropriate WebAssembly modules.
229    ///
230    /// This feature gates tail-call functions in WebAssembly.
231    ///
232    /// This is `false` by default.
233    ///
234    /// [proposal]: https://github.com/webassembly/tail-call
235    pub fn tail_call(&mut self, enable: bool) -> &mut Self {
236        self.tail_call = enable;
237        self
238    }
239
240    /// Configures whether the WebAssembly module linking proposal will
241    /// be enabled.
242    ///
243    /// The [WebAssembly module linking proposal][proposal] is not
244    /// currently fully standardized and is undergoing development.
245    /// Support for this feature can be enabled through this method for
246    /// appropriate WebAssembly modules.
247    ///
248    /// This feature allows WebAssembly modules to define, import and
249    /// export modules and instances.
250    ///
251    /// This is `false` by default.
252    ///
253    /// [proposal]: https://github.com/webassembly/module-linking
254    pub fn module_linking(&mut self, enable: bool) -> &mut Self {
255        self.module_linking = enable;
256        self
257    }
258
259    /// Configures whether the WebAssembly multi-memory proposal will
260    /// be enabled.
261    ///
262    /// The [WebAssembly multi-memory proposal][proposal] is now
263    /// fully standardized.
264    /// Support for this feature can be enabled through this method
265    /// for appropriate WebAssembly modules.
266    ///
267    /// This feature adds the ability to use multiple memories within a
268    /// single Wasm module.
269    ///
270    /// This is `true` by default.
271    ///
272    /// [proposal]: https://github.com/WebAssembly/multi-memory
273    pub fn multi_memory(&mut self, enable: bool) -> &mut Self {
274        self.multi_memory = enable;
275        self
276    }
277
278    /// Configures whether the WebAssembly 64-bit memory proposal will
279    /// be enabled.
280    ///
281    /// The [WebAssembly 64-bit memory proposal][proposal] is now
282    /// fully standardized.
283    /// Support for this feature can be enabled through this method
284    /// for appropriate WebAssembly modules.
285    ///
286    /// This feature gates support for linear memory of sizes larger than
287    /// 2^32 bits.
288    ///
289    /// This is `false` by default.
290    ///
291    /// [proposal]: https://github.com/WebAssembly/memory64
292    pub fn memory64(&mut self, enable: bool) -> &mut Self {
293        self.memory64 = enable;
294        self
295    }
296
297    /// Configures whether the WebAssembly exception-handling proposal will be enabled.
298    ///
299    /// The [WebAssembly exception-handling proposal][eh] is now
300    /// fully standardized.
301    /// Support for this feature can be enabled through this method
302    /// for appropriate WebAssembly modules.
303    ///
304    /// This is `false` by default.
305    ///
306    /// [eh]: https://github.com/webassembly/exception-handling
307    pub fn exceptions(&mut self, enable: bool) -> &mut Self {
308        self.exceptions = enable;
309        self
310    }
311
312    /// Configures whether the WebAssembly wide arithmetic proposal will be enabled.
313    ///
314    /// The [Wide Arithmetic][wa] is not currently fully
315    /// standardized and is undergoing development. Support for this feature can
316    /// be enabled through this method for appropriate WebAssembly modules.
317    ///
318    /// This is `false` by default.
319    ///
320    /// [wa]: https://github.com/WebAssembly/wide-arithmetic
321    pub fn wide_arithmetic(&mut self, enable: bool) -> &mut Self {
322        self.wide_arithmetic = enable;
323        self
324    }
325
326    /// Configures whether the WebAssembly Extended Constant Expressions proposal will be enabled.
327    ///
328    /// The [WebAssembly Extended Constant Expressions][extended-const] is now
329    /// fully standardized.
330    /// Support for this feature can be enabled through this method
331    /// for appropriate WebAssembly modules.
332    ///
333    /// This is `true` by default.
334    ///
335    /// [extended-const]: https://github.com/WebAssembly/extended-const
336    pub fn extended_const(&mut self, enable: bool) -> &mut Self {
337        self.extended_const = enable;
338        self
339    }
340
341    /// Checks if this features set contains all the features required by another set
342    pub fn contains_features(&self, required: &Self) -> bool {
343        // Check all required features
344        (!required.simd || self.simd)
345            && (!required.bulk_memory || self.bulk_memory)
346            && (!required.reference_types || self.reference_types)
347            && (!required.threads || self.threads)
348            && (!required.multi_value || self.multi_value)
349            && (!required.exceptions || self.exceptions)
350            && (!required.tail_call || self.tail_call)
351            && (!required.module_linking || self.module_linking)
352            && (!required.multi_memory || self.multi_memory)
353            && (!required.memory64 || self.memory64)
354            && (!required.relaxed_simd || self.relaxed_simd)
355            && (!required.extended_const || self.extended_const)
356            && (!required.wide_arithmetic || self.wide_arithmetic)
357    }
358
359    #[cfg(feature = "detect-wasm-features")]
360    /// Detects required WebAssembly features from a module binary.
361    ///
362    /// This method analyzes a WebAssembly module's binary to determine which
363    /// features it requires. It does this by:
364    /// 1. Attempting to validate the module with different feature sets
365    /// 2. Analyzing validation errors to detect required features
366    /// 3. Parsing the module to detect certain common patterns
367    ///
368    /// # Arguments
369    ///
370    /// * `wasm_bytes` - The binary content of the WebAssembly module
371    ///
372    /// # Returns
373    ///
374    /// A new `Features` instance with the detected features enabled.
375    pub fn detect_from_wasm(wasm_bytes: &[u8]) -> Result<Self, wasmparser::BinaryReaderError> {
376        let mut features = Self::default();
377
378        // Simple test for exceptions - try to validate with exceptions disabled
379        let mut exceptions_test = WasmFeatures::default();
380        // Enable most features except exceptions
381        exceptions_test.set(WasmFeatures::BULK_MEMORY, true);
382        exceptions_test.set(WasmFeatures::REFERENCE_TYPES, true);
383        exceptions_test.set(WasmFeatures::SIMD, true);
384        exceptions_test.set(WasmFeatures::MULTI_VALUE, true);
385        exceptions_test.set(WasmFeatures::THREADS, true);
386        exceptions_test.set(WasmFeatures::TAIL_CALL, true);
387        exceptions_test.set(WasmFeatures::MULTI_MEMORY, true);
388        exceptions_test.set(WasmFeatures::MEMORY64, true);
389        exceptions_test.set(WasmFeatures::EXCEPTIONS, false);
390
391        let mut validator = Validator::new_with_features(exceptions_test);
392
393        if let Err(e) = validator.validate_all(wasm_bytes) {
394            let err_msg = e.to_string();
395            if err_msg.contains("exception") {
396                features.exceptions(true);
397            }
398        }
399
400        // Now try with all features enabled to catch anything we might have missed
401        let mut wasm_features = WasmFeatures::default();
402        wasm_features.set(WasmFeatures::EXCEPTIONS, true);
403        wasm_features.set(WasmFeatures::BULK_MEMORY, true);
404        wasm_features.set(WasmFeatures::REFERENCE_TYPES, true);
405        wasm_features.set(WasmFeatures::SIMD, true);
406        wasm_features.set(WasmFeatures::MULTI_VALUE, true);
407        wasm_features.set(WasmFeatures::THREADS, true);
408        wasm_features.set(WasmFeatures::TAIL_CALL, true);
409        wasm_features.set(WasmFeatures::MULTI_MEMORY, true);
410        wasm_features.set(WasmFeatures::MEMORY64, true);
411        wasm_features.set(WasmFeatures::RELAXED_SIMD, false);
412
413        let mut validator = Validator::new_with_features(wasm_features);
414        match validator.validate_all(wasm_bytes) {
415            Err(e) => {
416                // If validation fails due to missing feature support, check which feature it is
417                let err_msg = e.to_string().to_lowercase();
418
419                if err_msg.contains("exception") || err_msg.contains("try/catch") {
420                    features.exceptions(true);
421                }
422
423                if err_msg.contains("bulk memory") {
424                    features.bulk_memory(true);
425                }
426
427                if err_msg.contains("reference type") {
428                    features.reference_types(true);
429                }
430
431                if err_msg.contains("relaxed simd") {
432                    features.relaxed_simd(true);
433                } else if err_msg.contains("simd") {
434                    features.simd(true);
435                }
436
437                if err_msg.contains("multi value") || err_msg.contains("multiple values") {
438                    features.multi_value(true);
439                }
440
441                if err_msg.contains("thread") || err_msg.contains("shared memory") {
442                    features.threads(true);
443                }
444
445                if err_msg.contains("tail call") {
446                    features.tail_call(true);
447                }
448
449                if err_msg.contains("module linking") {
450                    features.module_linking(true);
451                }
452
453                if err_msg.contains("multi memory") {
454                    features.multi_memory(true);
455                }
456
457                if err_msg.contains("memory64") {
458                    features.memory64(true);
459                }
460                if err_msg.contains("wide arithmetic") {
461                    features.wide_arithmetic(true);
462                }
463                if err_msg.contains("constant expression") {
464                    features.extended_const(true);
465                }
466            }
467            Ok(_) => {
468                // The module validated successfully with all features enabled,
469                // which means it could potentially use any of them.
470                // We'll do a more detailed analysis by parsing the module.
471            }
472        }
473
474        // A simple pass to detect certain common patterns
475        for payload in Parser::new(0).parse_all(wasm_bytes) {
476            let payload = payload?;
477            if let Payload::CustomSection(section) = payload {
478                let name = section.name();
479                // Exception handling has a custom section
480                if name.contains("exception") {
481                    features.exceptions(true);
482                }
483            }
484        }
485
486        Ok(features)
487    }
488
489    /// Extend this feature set with another set.
490    ///
491    /// Self will be modified to include all features that are required by
492    /// either set.
493    pub fn extend(&mut self, other: &Self) {
494        // Written this way to cause compile errors when new features are added.
495        let Self {
496            threads,
497            reference_types,
498            simd,
499            bulk_memory,
500            multi_value,
501            tail_call,
502            module_linking,
503            multi_memory,
504            memory64,
505            exceptions,
506            relaxed_simd,
507            extended_const,
508            wide_arithmetic,
509        } = other.clone();
510
511        *self = Self {
512            threads: self.threads || threads,
513            reference_types: self.reference_types || reference_types,
514            simd: self.simd || simd,
515            bulk_memory: self.bulk_memory || bulk_memory,
516            multi_value: self.multi_value || multi_value,
517            tail_call: self.tail_call || tail_call,
518            module_linking: self.module_linking || module_linking,
519            multi_memory: self.multi_memory || multi_memory,
520            memory64: self.memory64 || memory64,
521            exceptions: self.exceptions || exceptions,
522            relaxed_simd: self.relaxed_simd || relaxed_simd,
523            extended_const: self.extended_const || extended_const,
524            wide_arithmetic: self.wide_arithmetic || wide_arithmetic,
525        };
526    }
527}
528
529impl Default for Features {
530    fn default() -> Self {
531        Self::new()
532    }
533}
534
535#[cfg(test)]
536mod test_features {
537    use super::*;
538    #[test]
539    fn default_features() {
540        let default = Features::default();
541        assert_eq!(
542            default,
543            Features {
544                threads: true,
545                reference_types: true,
546                simd: true,
547                bulk_memory: true,
548                multi_value: true,
549                tail_call: false,
550                module_linking: false,
551                multi_memory: true,
552                memory64: false,
553                exceptions: false,
554                relaxed_simd: false,
555                extended_const: true,
556                wide_arithmetic: false
557            }
558        );
559    }
560
561    #[test]
562    fn features_extend() {
563        let all = Features::all();
564        let mut target = Features::none();
565        target.extend(&all);
566        assert_eq!(target, all);
567    }
568
569    #[test]
570    fn enable_threads() {
571        let mut features = Features::new();
572        features.bulk_memory(false).threads(true);
573
574        assert!(features.threads);
575    }
576
577    #[test]
578    fn enable_reference_types() {
579        let mut features = Features::new();
580        features.bulk_memory(false).reference_types(true);
581        assert!(features.reference_types);
582        assert!(features.bulk_memory);
583    }
584
585    #[test]
586    fn enable_simd() {
587        let mut features = Features::new();
588        features.simd(true);
589        assert!(features.simd);
590    }
591
592    #[test]
593    fn enable_multi_value() {
594        let mut features = Features::new();
595        features.multi_value(true);
596        assert!(features.multi_value);
597    }
598
599    #[test]
600    fn enable_bulk_memory() {
601        let mut features = Features::new();
602        features.bulk_memory(true);
603        assert!(features.bulk_memory);
604    }
605
606    #[test]
607    fn disable_bulk_memory() {
608        let mut features = Features::new();
609        features
610            .threads(true)
611            .reference_types(true)
612            .bulk_memory(false);
613        assert!(!features.bulk_memory);
614        assert!(!features.reference_types);
615    }
616
617    #[test]
618    fn enable_tail_call() {
619        let mut features = Features::new();
620        features.tail_call(true);
621        assert!(features.tail_call);
622    }
623
624    #[test]
625    fn enable_module_linking() {
626        let mut features = Features::new();
627        features.module_linking(true);
628        assert!(features.module_linking);
629    }
630
631    #[test]
632    fn enable_multi_memory() {
633        let mut features = Features::new();
634        features.multi_memory(true);
635        assert!(features.multi_memory);
636    }
637
638    #[test]
639    fn enable_memory64() {
640        let mut features = Features::new();
641        features.memory64(true);
642        assert!(features.memory64);
643    }
644}