/src/wasmtime/crates/environ/src/compile/module_environ.rs
Line | Count | Source |
1 | | use crate::error::{OutOfMemory, Result, bail}; |
2 | | use crate::module::{ |
3 | | FuncRefIndex, Initializer, MemoryInitialization, Module, TableSegment, TableSegmentElements, |
4 | | TableSegmentInit, |
5 | | }; |
6 | | use crate::prelude::*; |
7 | | use crate::{ |
8 | | ConstExpr, ConstOp, DataIndex, DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex, |
9 | | DefinedTableIndex, ElemIndex, EngineOrModuleTypeIndex, EntityIndex, EntityType, FuncIndex, |
10 | | FuncKey, GlobalIndex, IndexType, MemoryIndex, MemoryInitializer, ModuleInternedTypeIndex, |
11 | | ModuleStartup, ModuleTypesBuilder, PanicOnOom as _, PassiveElemIndex, PrimaryMap, |
12 | | RuntimeDataIndex, StaticModuleIndex, TableIndex, TableInitialValue, TableInitialization, Tag, |
13 | | TagIndex, Trap, Tunables, TypeConvert, TypeIndex, WasmHeapTopType, WasmHeapType, WasmResult, |
14 | | WasmValType, WasmparserTypeConverter, |
15 | | }; |
16 | | use alloc::borrow::Cow; |
17 | | use cranelift_entity::packed_option::{PackedOption, ReservedValue}; |
18 | | use cranelift_entity::{EntitySet, SecondaryMap}; |
19 | | use std::collections::HashMap; |
20 | | use std::mem; |
21 | | use std::path::PathBuf; |
22 | | use std::sync::Arc; |
23 | | use wasmparser::{ |
24 | | CustomSectionReader, DataKind, ElementItems, ElementKind, Encoding, ExternalKind, |
25 | | FuncToValidate, FunctionBody, KnownCustom, NameSectionReader, Naming, Parser, Payload, TypeRef, |
26 | | Validator, ValidatorResources, types::Types, |
27 | | }; |
28 | | |
29 | | /// Object containing the standalone environment information. |
30 | | pub struct ModuleEnvironment<'a, 'data> { |
31 | | /// The current module being translated |
32 | | result: ModuleTranslation<'data>, |
33 | | |
34 | | /// Intern'd types for this entire translation, shared by all modules. |
35 | | types: &'a mut ModuleTypesBuilder, |
36 | | |
37 | | // Various bits and pieces of configuration |
38 | | validator: &'a mut Validator, |
39 | | tunables: &'a Tunables, |
40 | | } |
41 | | |
42 | | /// Identifies a FACT adapter-module import that the compiler lowers inline when |
43 | | /// translating the adapter function. |
44 | | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] |
45 | | pub enum FactInlineIntrinsic { |
46 | | /// `enter-sync-call`: push a deferred component-model thread inline. |
47 | | EnterSyncCall, |
48 | | |
49 | | /// `exit-sync-call`: pop the deferred thread inline on the fast path, or |
50 | | /// fall back to the out-of-line `exit-sync-call` libcall when the thread |
51 | | /// was promoted. |
52 | | ExitSyncCall, |
53 | | |
54 | | /// `trap`: raise the given trap. |
55 | | Trap(Trap), |
56 | | |
57 | | /// An intrinsic that only exists for components. |
58 | | #[cfg(feature = "component-model")] |
59 | | Component(crate::component::FactComponentIntrinsic), |
60 | | } |
61 | | |
62 | | /// A statically-known function import. |
63 | | #[derive(Clone, Debug)] |
64 | | pub enum KnownFunc { |
65 | | /// A function described by the given key. |
66 | | FuncKey(FuncKey), |
67 | | /// An always-inlined FACT intrinsic. |
68 | | FactIntrinsic(FactInlineIntrinsic), |
69 | | } |
70 | | |
71 | | impl From<FuncKey> for KnownFunc { |
72 | 34.6k | fn from(key: FuncKey) -> Self { |
73 | 34.6k | Self::FuncKey(key) |
74 | 34.6k | } |
75 | | } |
76 | | |
77 | | impl From<FactInlineIntrinsic> for KnownFunc { |
78 | 20.5k | fn from(intrinsic: FactInlineIntrinsic) -> Self { |
79 | 20.5k | Self::FactIntrinsic(intrinsic) |
80 | 20.5k | } |
81 | | } |
82 | | |
83 | | /// A statically-known import of a core Wasm global, memory, or table. |
84 | | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] |
85 | | pub struct KnownEntity<T> { |
86 | | /// The module that defines this entity. |
87 | | pub module: StaticModuleIndex, |
88 | | /// The entity's index in the defining module's defined-entity index space. |
89 | | pub index: T, |
90 | | } |
91 | | |
92 | | /// A statically-known import of a core wasm global. |
93 | | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] |
94 | | pub enum KnownGlobal { |
95 | | /// A global defined by a module in the same component. |
96 | | Defined(KnownEntity<DefinedGlobalIndex>), |
97 | | |
98 | | /// A component instance's runtime-managed flags, such as its `may-leave` |
99 | | /// flag. |
100 | | #[cfg(feature = "component-model")] |
101 | | ComponentInstanceFlags(crate::component::RuntimeComponentInstanceIndex), |
102 | | } |
103 | | |
104 | | /// The result of translating via `ModuleEnvironment`. |
105 | | /// |
106 | | /// Function bodies are not yet translated, and data initializers have not yet |
107 | | /// been copied out of the original buffer. |
108 | | pub struct ModuleTranslation<'data> { |
109 | | /// Module information. |
110 | | pub module: Module, |
111 | | |
112 | | /// The input wasm binary. |
113 | | /// |
114 | | /// This can be useful, for example, when modules are parsed from a |
115 | | /// component and the embedder wants access to the raw wasm modules |
116 | | /// themselves. |
117 | | pub wasm: &'data [u8], |
118 | | |
119 | | /// The byte offset of this module's Wasm binary within the outer |
120 | | /// binary (e.g. a component). For standalone modules this is 0. |
121 | | /// This is used to convert component-relative source locations to |
122 | | /// module-relative source locations. |
123 | | pub wasm_module_offset: u64, |
124 | | |
125 | | /// References to the function bodies. |
126 | | pub function_body_inputs: PrimaryMap<DefinedFuncIndex, FunctionBodyData<'data>>, |
127 | | |
128 | | /// For each imported function, the single statically-known function that |
129 | | /// always satisfies that import, if any. |
130 | | /// |
131 | | /// This is used to turn what would otherwise be indirect calls through the |
132 | | /// imports table into direct calls, when possible. |
133 | | /// |
134 | | /// When filled in, this only ever contains |
135 | | /// `FuncKey::DefinedWasmFunction(..)`s, `FuncKey::Intrinsic(..)`s, and |
136 | | /// `FuncKey::FactInlineIntrinsic`s. |
137 | | pub known_imported_functions: SecondaryMap<FuncIndex, Option<KnownFunc>>, |
138 | | |
139 | | /// For each function import, the function import whose `vmctx` this one |
140 | | /// is statically guaranteed to always share, when that is not itself. |
141 | | /// |
142 | | /// Function imports that always resolve to functions from the same |
143 | | /// instance hold the same `vmctx` pointer in their `VMFunctionImport` |
144 | | /// slots, so they can all load the callee `vmctx` from a single slot and |
145 | | /// let GVN collapse what would otherwise be many identical loads into one. |
146 | | /// |
147 | | /// No value means this import must use its own slot. |
148 | | /// |
149 | | /// Only filled in for modules compiled as part of a component. |
150 | | pub imported_func_vmctx_representative: SecondaryMap<FuncIndex, PackedOption<FuncIndex>>, |
151 | | |
152 | | /// Imported functions that never unwind a Wasm exception into their |
153 | | /// caller, such as the host intrinsics imported by FACT adapter modules. |
154 | | /// |
155 | | /// Calls to these need no exception handlers, even inside a `try_table`. |
156 | | pub imported_funcs_never_throw: EntitySet<FuncIndex>, |
157 | | |
158 | | /// For each imported global, memory, or table, the single statically-known |
159 | | /// defined entity that always satisfies that import, if any. |
160 | | /// |
161 | | /// This is used to access the entity via the defining module's precise |
162 | | /// `AliasRegionKey::Defined{Global,Memory,Table}` region instead of the |
163 | | /// conservative `AliasRegionKey::Public{Global,Memory,Table}` region that is |
164 | | /// shared by every entity of that kind which crosses a module boundary. |
165 | | /// |
166 | | /// XXX: Being "known" requires more here than it does for functions: it is |
167 | | /// not enough that *this* module's import is always the same entity, |
168 | | /// *every* module that may import that entity must also always import that |
169 | | /// same entity. Otherwise a function from one of those other modules, which |
170 | | /// accesses the entity via the conservative region, could be inlined next |
171 | | /// to one of our accesses via the precise region, and accessing the same |
172 | | /// memory through two different alias regions is invalid. |
173 | | /// |
174 | | /// This extra condition is an artifact of this implementation, and how we |
175 | | /// consume this data to choose the alias region for loads and stores to a |
176 | | /// global/memory/table, not something inherent to knowing exactly which |
177 | | /// entity satisfies a particular import. Really, there are two independent |
178 | | /// axes here: |
179 | | /// |
180 | | /// 1. Is this import always satisfied by the same defined entity? |
181 | | /// |
182 | | /// 2. Is that entity's identity additionally known to *every* other module |
183 | | /// that may import it? |
184 | | /// |
185 | | /// Only alias regions need (2), but other theoretical optimizations could |
186 | | /// be perfectly happy with just (1). For example, if we know that an import |
187 | | /// of an immutable global is always a particular defined global, then we |
188 | | /// could inline that global's value at each `global.get` of the import, |
189 | | /// regardless what any other module does or does not know about that |
190 | | /// global. |
191 | | /// |
192 | | /// TODO(#14164): Actually record (1) and (2) in separate maps, enabling |
193 | | /// optimizations that rely on just (1) but not (2), instead of folding them |
194 | | /// into this same map. |
195 | | pub known_imported_globals: SecondaryMap<GlobalIndex, Option<KnownGlobal>>, |
196 | | |
197 | | /// Same as `known_imported_globals`, but for memories. |
198 | | pub known_imported_memories: SecondaryMap<MemoryIndex, Option<KnownEntity<DefinedMemoryIndex>>>, |
199 | | |
200 | | /// Same as `known_imported_globals`, but for tables. |
201 | | pub known_imported_tables: SecondaryMap<TableIndex, Option<KnownEntity<DefinedTableIndex>>>, |
202 | | |
203 | | /// For each global defined by this module, whether every module that may |
204 | | /// import this global always imports exactly this global. |
205 | | /// |
206 | | /// When this holds, accesses of the global may use its precise |
207 | | /// `AliasRegionKey::DefinedGlobal` region even when the global is exported, |
208 | | /// because every module that can reach it agrees on that same region. This |
209 | | /// is vacuously true of globals that nothing in the component imports. |
210 | | /// |
211 | | /// This can only be determined by looking at the whole component, so it is |
212 | | /// always `false` for standalone modules. |
213 | | pub globals_known_to_importers: EntitySet<DefinedGlobalIndex>, |
214 | | |
215 | | /// Same as [`Self::globals_known_to_importers`], but for memories. |
216 | | pub memories_known_to_importers: EntitySet<DefinedMemoryIndex>, |
217 | | |
218 | | /// Same as [`Self::globals_known_to_importers`], but for tables. |
219 | | pub tables_known_to_importers: EntitySet<DefinedTableIndex>, |
220 | | |
221 | | /// A list of type signatures which are considered exported from this |
222 | | /// module, or those that can possibly be called. This list is sorted, and |
223 | | /// trampolines for each of these signatures are required. |
224 | | pub exported_signatures: Vec<ModuleInternedTypeIndex>, |
225 | | |
226 | | /// DWARF debug information, if enabled, parsed from the module. |
227 | | pub debuginfo: DebugInfoData<'data>, |
228 | | |
229 | | /// Set if debuginfo was found but it was not parsed due to `Tunables` |
230 | | /// configuration. |
231 | | pub has_unparsed_debuginfo: bool, |
232 | | |
233 | | /// The desired alignment of `data` in the final data section of the object |
234 | | /// file that we'll emit. |
235 | | /// |
236 | | /// Note that this is 1 by default but `MemoryInitialization::Static` might |
237 | | /// switch this to a higher alignment to facilitate mmap-ing data from |
238 | | /// an object file into a linear memory. |
239 | | pub data_align: Option<u64>, |
240 | | |
241 | | /// Map from a data segment to whether it's a passive data segment or not. |
242 | | pub runtime_data_map: SecondaryMap<DataIndex, Option<RuntimeDataIndex>>, |
243 | | |
244 | | /// Map from an elem segment to whether it's a passive elem segment or not. |
245 | | pub passive_elem_map: SecondaryMap<ElemIndex, Option<PassiveElemIndex>>, |
246 | | |
247 | | /// List of passive element segments found in this module which will get |
248 | | /// concatenated for the final artifact. |
249 | | pub runtime_data: PrimaryMap<RuntimeDataIndex, Cow<'data, [u8]>>, |
250 | | |
251 | | /// Record of all passive data segments that this module contains. |
252 | | /// |
253 | | /// These are processed during [`ModuleTranslation::finalize_memory_init`] |
254 | | /// and eventually moved over into the `runtime_data` list above. Until |
255 | | /// then, however, their `RuntimeDataIndex` is not yet assigned. |
256 | | passive_data: Vec<(DataIndex, &'data [u8])>, |
257 | | |
258 | | /// When we're parsing the code section this will be incremented so we know |
259 | | /// which function is currently being defined. |
260 | | code_index: u32, |
261 | | |
262 | | /// The type information of the current module made available at the end of the |
263 | | /// validation process. |
264 | | types: Option<Types>, |
265 | | |
266 | | /// Per-function [`BranchHintReader`]s from the `metadata.code.branch_hint` |
267 | | /// section, keyed by function index. Populated only when |
268 | | /// [`Tunables::branch_hinting`] is enabled. |
269 | | branch_hints: HashMap<FuncIndex, BranchHintReader<'data>>, |
270 | | |
271 | | /// The WebAssembly `start` function, if defined. |
272 | | pub start_func: Option<FuncIndex>, |
273 | | |
274 | | /// Initializers for `global` values which aren't considered "simple". |
275 | | /// |
276 | | /// These initializers are later compiled into a "module startup" function. |
277 | | pub global_initializers: Vec<(DefinedGlobalIndex, ConstExpr)>, |
278 | | |
279 | | /// Definitions of all passive elements found within a module. |
280 | | /// |
281 | | /// This maps passive element segments to their definition, either functions |
282 | | /// or expressions-basd. |
283 | | pub passive_elements: PrimaryMap<PassiveElemIndex, TableSegmentElements>, |
284 | | |
285 | | /// WebAssembly table initialization data, per table. |
286 | | /// |
287 | | /// This keeps track of all per-table initialization (e.g. initial value for |
288 | | /// non-null tables) as well as active element segments. This is processed |
289 | | /// and refined by [`ModuleTranslation::finalize_table_init`] after |
290 | | /// translation. |
291 | | pub table_initialization: TableInitialization, |
292 | | |
293 | | /// WebAssembly memory initialization. |
294 | | /// |
295 | | /// This is held here in an `Unprocessed` form during translation, and then |
296 | | /// this is later finished with [`ModuleTranslation::finalize_memory_init`]. |
297 | | pub memory_init: MemoryInit<'data>, |
298 | | } |
299 | | |
300 | | /// Different forms of memory initialization that happens for a module. |
301 | | pub enum MemoryInit<'a> { |
302 | | /// Raw active data segments that are being applied for an instance. |
303 | | /// |
304 | | /// This list contains the raw data which hasn't yet been processed into |
305 | | /// `RuntimeDataIndex`, for example. This is later processed during |
306 | | /// [`ModuleTranslation::finalize_memory_init`] to optionally shuffle things |
307 | | /// around. |
308 | | Unprocessed(Vec<MemoryInitializer<'a>>), |
309 | | |
310 | | /// Finalized memory initialization to be executed after |
311 | | /// [`ModuleTranslation::finalize_memory_init`] has run. This represents |
312 | | /// active data segments which may have been merged from the `Unprocessed` |
313 | | /// list above, and may or may not have statically know offsets. |
314 | | Processed(Vec<(MemoryIndex, MemorySegmentOffset, RuntimeDataIndex)>), |
315 | | } |
316 | | |
317 | | /// Offset within [`MemoryInit::Processed`] which indicates the initial offset |
318 | | /// a data segment is applied at. |
319 | | pub enum MemorySegmentOffset { |
320 | | /// A "complicated" constant expression deferred to get evaluated at runtime |
321 | | /// with compiled code. |
322 | | Expr(ConstExpr), |
323 | | |
324 | | /// A statically known, in-bounds, constant value. |
325 | | Static(u64), |
326 | | } |
327 | | |
328 | | /// Lazy decoder over the branch hints attached to a single function in the |
329 | | /// `metadata.code.branch_hint` custom section |
330 | | /// ([branch-hinting proposal](https://github.com/WebAssembly/branch-hinting)). |
331 | | pub type BranchHintReader<'a> = wasmparser::SectionLimited<'a, wasmparser::BranchHint>; |
332 | | |
333 | | impl<'data> ModuleTranslation<'data> { |
334 | | /// Create a new translation for the module with the given index. |
335 | 246k | pub fn new(module_index: StaticModuleIndex) -> Self { |
336 | 246k | Self { |
337 | 246k | module: Module::new(module_index), |
338 | 246k | wasm: &[], |
339 | 246k | wasm_module_offset: 0, |
340 | 246k | function_body_inputs: PrimaryMap::default(), |
341 | 246k | known_imported_functions: SecondaryMap::default(), |
342 | 246k | imported_func_vmctx_representative: SecondaryMap::default(), |
343 | 246k | imported_funcs_never_throw: EntitySet::new(), |
344 | 246k | known_imported_globals: SecondaryMap::default(), |
345 | 246k | known_imported_memories: SecondaryMap::default(), |
346 | 246k | known_imported_tables: SecondaryMap::default(), |
347 | 246k | globals_known_to_importers: EntitySet::new(), |
348 | 246k | memories_known_to_importers: EntitySet::new(), |
349 | 246k | tables_known_to_importers: EntitySet::new(), |
350 | 246k | exported_signatures: Vec::default(), |
351 | 246k | debuginfo: DebugInfoData::default(), |
352 | 246k | has_unparsed_debuginfo: false, |
353 | 246k | data_align: None, |
354 | 246k | runtime_data: Default::default(), |
355 | 246k | code_index: 0, |
356 | 246k | types: None, |
357 | 246k | runtime_data_map: Default::default(), |
358 | 246k | passive_elem_map: Default::default(), |
359 | 246k | branch_hints: HashMap::default(), |
360 | 246k | start_func: None, |
361 | 246k | global_initializers: Vec::new(), |
362 | 246k | passive_elements: Default::default(), |
363 | 246k | table_initialization: Default::default(), |
364 | 246k | memory_init: MemoryInit::Unprocessed(Vec::new()), |
365 | 246k | passive_data: Default::default(), |
366 | 246k | } |
367 | 246k | } |
368 | | |
369 | | /// Returns the [`BranchHintReader`] for `func`, if the section attached any. |
370 | 1.67M | pub fn branch_hints(&self, func: FuncIndex) -> Option<BranchHintReader<'data>> { |
371 | 1.67M | self.branch_hints.get(&func).cloned() |
372 | 1.67M | } |
373 | | |
374 | | /// Returns a reference to the type information of the current module. |
375 | 15.2k | pub fn get_types(&self) -> &Types { |
376 | 15.2k | self.types |
377 | 15.2k | .as_ref() |
378 | 15.2k | .expect("module type information to be available") |
379 | 15.2k | } |
380 | | |
381 | | /// Get this translation's module's index. |
382 | 6.65M | pub fn module_index(&self) -> StaticModuleIndex { |
383 | 6.65M | self.module.module_index |
384 | 6.65M | } |
385 | | } |
386 | | |
387 | | /// Contains function data: byte code and its offset in the module. |
388 | | pub struct FunctionBodyData<'a> { |
389 | | /// The body of the function, containing code and locals. |
390 | | pub body: FunctionBody<'a>, |
391 | | /// Validator for the function body |
392 | | pub validator: FuncToValidate<ValidatorResources>, |
393 | | } |
394 | | |
395 | | #[derive(Debug, Default)] |
396 | | #[expect(missing_docs, reason = "self-describing fields")] |
397 | | pub struct DebugInfoData<'a> { |
398 | | pub dwarf: Dwarf<'a>, |
399 | | pub name_section: NameSection<'a>, |
400 | | pub wasm_file: WasmFileInfo, |
401 | | pub debug_loc: gimli::DebugLoc<Reader<'a>>, |
402 | | pub debug_loclists: gimli::DebugLocLists<Reader<'a>>, |
403 | | pub debug_ranges: gimli::DebugRanges<Reader<'a>>, |
404 | | pub debug_rnglists: gimli::DebugRngLists<Reader<'a>>, |
405 | | pub debug_cu_index: gimli::DebugCuIndex<Reader<'a>>, |
406 | | pub debug_tu_index: gimli::DebugTuIndex<Reader<'a>>, |
407 | | } |
408 | | |
409 | | #[expect(missing_docs, reason = "self-describing")] |
410 | | pub type Dwarf<'input> = gimli::Dwarf<Reader<'input>>; |
411 | | |
412 | | type Reader<'input> = gimli::EndianSlice<'input, gimli::LittleEndian>; |
413 | | |
414 | | #[derive(Debug, Default)] |
415 | | #[expect(missing_docs, reason = "self-describing fields")] |
416 | | pub struct NameSection<'a> { |
417 | | pub module_name: Option<&'a str>, |
418 | | pub func_names: HashMap<FuncIndex, &'a str>, |
419 | | pub locals_names: HashMap<FuncIndex, HashMap<u32, &'a str>>, |
420 | | } |
421 | | |
422 | | #[derive(Debug, Default)] |
423 | | #[expect(missing_docs, reason = "self-describing fields")] |
424 | | pub struct WasmFileInfo { |
425 | | pub path: Option<PathBuf>, |
426 | | pub code_section_offset: u64, |
427 | | pub imported_func_count: u32, |
428 | | pub funcs: Vec<FunctionMetadata>, |
429 | | } |
430 | | |
431 | | #[derive(Debug)] |
432 | | #[expect(missing_docs, reason = "self-describing fields")] |
433 | | pub struct FunctionMetadata { |
434 | | pub params: Box<[WasmValType]>, |
435 | | pub locals: Box<[(u32, WasmValType)]>, |
436 | | } |
437 | | |
438 | | impl<'a, 'data> ModuleEnvironment<'a, 'data> { |
439 | | /// Allocates the environment data structures. |
440 | 246k | pub fn new( |
441 | 246k | tunables: &'a Tunables, |
442 | 246k | validator: &'a mut Validator, |
443 | 246k | types: &'a mut ModuleTypesBuilder, |
444 | 246k | module_index: StaticModuleIndex, |
445 | 246k | ) -> Self { |
446 | 246k | Self { |
447 | 246k | result: ModuleTranslation::new(module_index), |
448 | 246k | types, |
449 | 246k | tunables, |
450 | 246k | validator, |
451 | 246k | } |
452 | 246k | } |
453 | | |
454 | | /// Translate a wasm module using this environment. |
455 | | /// |
456 | | /// This function will translate the `data` provided with `parser`, |
457 | | /// validating everything along the way with this environment's validator. |
458 | | /// |
459 | | /// The result of translation, [`ModuleTranslation`], contains everything |
460 | | /// necessary to compile functions afterwards as well as learn type |
461 | | /// information about the module at runtime. |
462 | 246k | pub fn translate( |
463 | 246k | mut self, |
464 | 246k | parser: Parser, |
465 | 246k | data: &'data [u8], |
466 | 246k | ) -> Result<ModuleTranslation<'data>> { |
467 | 246k | self.result.wasm = data; |
468 | 246k | self.result.module.has_shadow_memories = self.tunables.memory_watchpoints; |
469 | | |
470 | 3.67M | for payload in parser.parse_all(data) { |
471 | 3.67M | self.translate_payload(payload?)?; |
472 | | } |
473 | | |
474 | 236k | Ok(self.result) |
475 | 246k | } |
476 | | |
477 | 3.67M | fn translate_payload(&mut self, payload: Payload<'data>) -> Result<()> { |
478 | 226k | match payload { |
479 | | Payload::Version { |
480 | 246k | num, |
481 | 246k | encoding, |
482 | 246k | range, |
483 | | } => { |
484 | 246k | self.validator.version(num, encoding, &range)?; |
485 | 246k | match encoding { |
486 | 246k | Encoding::Module => {} |
487 | | Encoding::Component => { |
488 | 7 | bail!("expected a WebAssembly module but was given a WebAssembly component") |
489 | | } |
490 | | } |
491 | | } |
492 | | |
493 | 236k | Payload::End(offset) => { |
494 | 236k | self.result.types = Some(self.validator.end(offset)?); |
495 | | |
496 | | // With the `escaped_funcs` set of functions finished |
497 | | // we can calculate the set of signatures that are exported as |
498 | | // the set of exported functions' signatures. |
499 | 236k | self.result.exported_signatures = self |
500 | 236k | .result |
501 | 236k | .module |
502 | 236k | .functions |
503 | 236k | .iter() |
504 | 2.14M | .filter_map(|(_, func)| { |
505 | 2.14M | if func.is_escaping() { |
506 | 800k | Some(func.signature.unwrap_module_type_index()) |
507 | | } else { |
508 | 1.34M | None |
509 | | } |
510 | 2.14M | }) |
511 | 236k | .collect(); |
512 | 236k | self.result.exported_signatures.sort_unstable(); |
513 | 236k | self.result.exported_signatures.dedup(); |
514 | | } |
515 | | |
516 | 199k | Payload::TypeSection(types) => { |
517 | 199k | self.validator.type_section(&types)?; |
518 | | |
519 | 197k | let count = self.validator.types(0).unwrap().core_type_count_in_module(); |
520 | 197k | log::trace!("interning {count} Wasm types"); |
521 | | |
522 | 197k | let capacity = usize::try_from(count).unwrap(); |
523 | 197k | self.result.module.types.reserve(capacity)?; |
524 | 197k | self.types.reserve_wasm_signatures(capacity); |
525 | | |
526 | | // Iterate over each *rec group* -- not type -- defined in the |
527 | | // types section. Rec groups are the unit of canonicalization |
528 | | // and therefore the unit at which we need to process at a |
529 | | // time. `wasmparser` has already done the hard work of |
530 | | // de-duplicating and canonicalizing the rec groups within the |
531 | | // module for us, we just need to translate them into our data |
532 | | // structures. Note that, if the Wasm defines duplicate rec |
533 | | // groups, we need copy the duplicates over (shallowly) as well, |
534 | | // so that our types index space doesn't have holes. |
535 | 197k | let mut type_index = 0; |
536 | 1.24M | while type_index < count { |
537 | 1.05M | let validator_types = self.validator.types(0).unwrap(); |
538 | | |
539 | | // Get the rec group for the current type index, which is |
540 | | // always the first type defined in a rec group. |
541 | 1.05M | log::trace!("looking up wasmparser type for index {type_index}"); |
542 | 1.05M | let core_type_id = validator_types.core_type_at_in_module(type_index); |
543 | 1.05M | log::trace!( |
544 | | " --> {core_type_id:?} = {:?}", |
545 | 0 | validator_types[core_type_id], |
546 | | ); |
547 | 1.05M | let rec_group_id = validator_types.rec_group_id_of(core_type_id); |
548 | 1.05M | debug_assert_eq!( |
549 | 0 | validator_types |
550 | 0 | .rec_group_elements(rec_group_id) |
551 | 0 | .position(|id| id == core_type_id), |
552 | | Some(0) |
553 | | ); |
554 | | |
555 | | // Intern the rec group and then fill in this module's types |
556 | | // index space. |
557 | 1.05M | let interned = self.types.intern_rec_group(validator_types, rec_group_id)?; |
558 | 1.05M | let elems = self.types.rec_group_elements(interned); |
559 | 1.05M | let len = elems.len(); |
560 | 1.05M | self.result.module.types.reserve(len)?; |
561 | 7.91M | for ty in elems { |
562 | 7.91M | self.result.module.types.push(ty.into())?; |
563 | | } |
564 | | |
565 | | // Advance `type_index` to the start of the next rec group. |
566 | 1.05M | type_index += u32::try_from(len).unwrap(); |
567 | | } |
568 | | } |
569 | | |
570 | 119k | Payload::ImportSection(imports) => { |
571 | 119k | self.validator.import_section(&imports)?; |
572 | | |
573 | 118k | let cnt = usize::try_from(imports.count()).unwrap(); |
574 | 118k | self.result.module.initializers.reserve(cnt)?; |
575 | | |
576 | 1.26M | for entry in imports.into_imports() { |
577 | 1.26M | let import = entry?; |
578 | 1.26M | let ty = match import.ty { |
579 | 358k | TypeRef::Func(index) => { |
580 | 358k | let index = TypeIndex::from_u32(index); |
581 | 358k | let interned_index = self.result.module.types[index]; |
582 | 358k | self.result.module.num_imported_funcs += 1; |
583 | 358k | self.result.debuginfo.wasm_file.imported_func_count += 1; |
584 | 358k | EntityType::Function(interned_index) |
585 | | } |
586 | 32.9k | TypeRef::Memory(ty) => { |
587 | 32.9k | self.result.module.num_imported_memories += 1; |
588 | 32.9k | EntityType::Memory(ty.into()) |
589 | | } |
590 | 397k | TypeRef::Global(ty) => { |
591 | 397k | self.result.module.num_imported_globals += 1; |
592 | 397k | EntityType::Global(self.convert_global_type(&ty)?) |
593 | | } |
594 | 113k | TypeRef::Table(ty) => { |
595 | 113k | self.result.module.num_imported_tables += 1; |
596 | 113k | EntityType::Table(self.convert_table_type(&ty)?) |
597 | | } |
598 | 367k | TypeRef::Tag(ty) => { |
599 | 367k | let index = TypeIndex::from_u32(ty.func_type_idx); |
600 | 367k | let signature = self.result.module.types[index]; |
601 | 367k | let exception = self.types.define_exception_type_for_tag( |
602 | 367k | signature.unwrap_module_type_index(), |
603 | | ); |
604 | 367k | let tag = Tag { |
605 | 367k | signature, |
606 | 367k | exception: EngineOrModuleTypeIndex::Module(exception), |
607 | 367k | }; |
608 | 367k | self.result.module.num_imported_tags += 1; |
609 | 367k | EntityType::Tag(tag) |
610 | | } |
611 | | TypeRef::FuncExact(_) => { |
612 | 0 | bail!("custom-descriptors proposal not implemented yet"); |
613 | | } |
614 | | }; |
615 | 1.26M | self.declare_import(import.module, import.name, ty)?; |
616 | | } |
617 | | } |
618 | | |
619 | 169k | Payload::FunctionSection(functions) => { |
620 | 169k | self.validator.function_section(&functions)?; |
621 | | |
622 | 169k | let cnt = usize::try_from(functions.count()).unwrap(); |
623 | 169k | self.result.module.functions.reserve_exact(cnt)?; |
624 | | |
625 | 1.79M | for entry in functions { |
626 | 1.79M | let sigindex = entry?; |
627 | 1.79M | let ty = TypeIndex::from_u32(sigindex); |
628 | 1.79M | let interned_index = self.result.module.types[ty]; |
629 | 1.79M | self.result.module.push_function(interned_index); |
630 | | } |
631 | | } |
632 | | |
633 | 57.2k | Payload::TableSection(tables) => { |
634 | 57.2k | self.validator.table_section(&tables)?; |
635 | 57.0k | let cnt = usize::try_from(tables.count()).unwrap(); |
636 | 57.0k | self.result.module.tables.reserve_exact(cnt)?; |
637 | | |
638 | 226k | for entry in tables { |
639 | 226k | let wasmparser::Table { ty, init } = entry?; |
640 | 226k | let table = self.convert_table_type(&ty)?; |
641 | 226k | self.result.module.needs_gc_heap |= table.ref_type.is_vmgcref_type(); |
642 | 226k | self.result.module.tables.push(table)?; |
643 | 226k | let init = match init { |
644 | 207k | wasmparser::TableInit::RefNull => TableInitialValue::Null, |
645 | 19.0k | wasmparser::TableInit::Expr(expr) => { |
646 | 19.0k | let (init, escaped) = ConstExpr::from_wasmparser(self, expr)?; |
647 | 19.0k | for f in escaped { |
648 | 545 | self.flag_func_escaped(f); |
649 | 545 | } |
650 | 19.0k | TableInitialValue::Expr(init) |
651 | | } |
652 | | }; |
653 | 226k | self.result.table_initialization.initial_values.push(init)?; |
654 | 226k | self.result |
655 | 226k | .module |
656 | 226k | .table_initialization |
657 | 226k | .push(Default::default())?; |
658 | | } |
659 | | } |
660 | | |
661 | 58.1k | Payload::MemorySection(memories) => { |
662 | 58.1k | self.validator.memory_section(&memories)?; |
663 | | |
664 | 57.8k | let cnt = usize::try_from(memories.count()).unwrap(); |
665 | 57.8k | self.result.module.memories.reserve_exact(cnt)?; |
666 | | |
667 | 72.1k | for entry in memories { |
668 | 72.1k | let memory = entry?; |
669 | 72.1k | self.result.module.memories.push(memory.into())?; |
670 | | } |
671 | | } |
672 | | |
673 | 18.9k | Payload::TagSection(tags) => { |
674 | 18.9k | self.validator.tag_section(&tags)?; |
675 | | |
676 | 310k | for entry in tags { |
677 | 310k | let sigindex = entry?.func_type_idx; |
678 | 310k | let ty = TypeIndex::from_u32(sigindex); |
679 | 310k | let interned_index = self.result.module.types[ty]; |
680 | 310k | let exception = self |
681 | 310k | .types |
682 | 310k | .define_exception_type_for_tag(interned_index.unwrap_module_type_index()); |
683 | 310k | self.result.module.push_tag(interned_index, exception); |
684 | | } |
685 | | } |
686 | | |
687 | 124k | Payload::GlobalSection(globals) => { |
688 | 124k | self.validator.global_section(&globals)?; |
689 | | |
690 | 123k | let cnt = usize::try_from(globals.count()).unwrap(); |
691 | 123k | self.result.module.globals.reserve_exact(cnt)?; |
692 | | |
693 | 987k | for entry in globals { |
694 | 987k | let wasmparser::Global { ty, init_expr } = entry?; |
695 | 987k | let (initializer, escaped) = ConstExpr::from_wasmparser(self, init_expr)?; |
696 | 987k | for f in escaped { |
697 | 7.33k | self.flag_func_escaped(f); |
698 | 7.33k | } |
699 | 987k | let ty = self.convert_global_type(&ty)?; |
700 | 987k | let index = self.result.module.globals.push(ty)?; |
701 | 987k | let defined_index = self.result.module.defined_global_index(index).unwrap(); |
702 | 987k | match initializer.const_eval() { |
703 | 560k | Some(val) => { |
704 | 560k | self.result |
705 | 560k | .module |
706 | 560k | .global_initializers |
707 | 560k | .push((defined_index, val))?; |
708 | | } |
709 | 427k | None => { |
710 | 427k | // "Complicated" global initializers are deferred |
711 | 427k | // to get evaluated in the startup function. |
712 | 427k | self.require_startup_func(); |
713 | 427k | self.result |
714 | 427k | .global_initializers |
715 | 427k | .push((defined_index, initializer)); |
716 | 427k | } |
717 | | } |
718 | | } |
719 | | } |
720 | | |
721 | 145k | Payload::ExportSection(exports) => { |
722 | 145k | self.validator.export_section(&exports)?; |
723 | | |
724 | 144k | let cnt = usize::try_from(exports.count()).unwrap(); |
725 | 144k | self.result.module.exports.reserve(cnt)?; |
726 | | |
727 | 1.06M | for entry in exports { |
728 | 1.06M | let wasmparser::Export { name, kind, index } = entry?; |
729 | 1.06M | let entity = match kind { |
730 | | ExternalKind::Func | ExternalKind::FuncExact => { |
731 | 471k | let index = FuncIndex::from_u32(index); |
732 | 471k | self.flag_func_escaped(index); |
733 | 471k | EntityIndex::Function(index) |
734 | | } |
735 | 127k | ExternalKind::Table => EntityIndex::Table(TableIndex::from_u32(index)), |
736 | 87.9k | ExternalKind::Memory => EntityIndex::Memory(MemoryIndex::from_u32(index)), |
737 | 378k | ExternalKind::Global => EntityIndex::Global(GlobalIndex::from_u32(index)), |
738 | 86 | ExternalKind::Tag => EntityIndex::Tag(TagIndex::from_u32(index)), |
739 | | }; |
740 | 1.06M | let name = self.result.module.strings.insert(name)?; |
741 | 1.06M | self.result.module.exports.insert(name, entity)?; |
742 | | } |
743 | | } |
744 | | |
745 | 11.2k | Payload::StartSection { func, range } => { |
746 | 11.2k | self.validator.start_section(func, &range)?; |
747 | | |
748 | 11.2k | let func_index = FuncIndex::from_u32(func); |
749 | 11.2k | debug_assert!(self.result.start_func.is_none()); |
750 | 11.2k | self.result.start_func = Some(func_index); |
751 | | |
752 | | // To make startup a bit easier, invoking the `start` function |
753 | | // is a responsibility deferred to the startup function. |
754 | 11.2k | self.require_startup_func(); |
755 | | } |
756 | | |
757 | 41.9k | Payload::ElementSection(elements) => { |
758 | 41.9k | self.validator.element_section(&elements)?; |
759 | | |
760 | | // Whether writes to tables made so far during instantiation |
761 | | // could be observed outside of this instance, which becomes |
762 | | // true once an active segment applies to an imported table. |
763 | 40.3k | let mut side_effects_visible = false; |
764 | | |
765 | 600k | for (index, entry) in elements.into_iter().enumerate() { |
766 | | let wasmparser::Element { |
767 | 600k | kind, |
768 | 600k | items, |
769 | | range: _, |
770 | 600k | } = entry?; |
771 | | |
772 | | // Build up a list of `FuncIndex` corresponding to all the |
773 | | // entries listed in this segment. Note that it's not |
774 | | // possible to create anything other than a `ref.null |
775 | | // extern` for externref segments, so those just get |
776 | | // translated to the reserved value of `FuncIndex`. |
777 | 600k | let elements = match items { |
778 | 276k | ElementItems::Functions(funcs) => { |
779 | 276k | let mut elems = |
780 | 276k | Vec::with_capacity(usize::try_from(funcs.count()).unwrap()); |
781 | 276k | for func in funcs { |
782 | 156k | let func = FuncIndex::from_u32(func?); |
783 | 156k | self.flag_func_escaped(func); |
784 | 156k | elems.push(func); |
785 | | } |
786 | 276k | TableSegmentElements::Functions(elems.into()) |
787 | | } |
788 | 323k | ElementItems::Expressions(ty, items) => { |
789 | 323k | let ty = self.convert_ref_type(ty)?; |
790 | 323k | let mut exprs = |
791 | 323k | Vec::with_capacity(usize::try_from(items.count()).unwrap()); |
792 | 323k | for expr in items { |
793 | 67.4k | let (expr, escaped) = ConstExpr::from_wasmparser(self, expr?)?; |
794 | 67.4k | exprs.push(expr); |
795 | 67.4k | for func in escaped { |
796 | 18.3k | self.flag_func_escaped(func); |
797 | 18.3k | } |
798 | | } |
799 | 323k | TableSegmentElements::Expressions { |
800 | 323k | ty, |
801 | 323k | exprs: exprs.into(), |
802 | 323k | } |
803 | | } |
804 | | }; |
805 | | |
806 | 600k | let passive_index = match kind { |
807 | | ElementKind::Active { |
808 | 340k | table_index, |
809 | 340k | offset_expr, |
810 | | } => { |
811 | 340k | let table_index = TableIndex::from_u32(table_index.unwrap_or(0)); |
812 | 340k | let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?; |
813 | 340k | debug_assert!(escaped.is_empty()); |
814 | | |
815 | | // The spec's instantiation evaluates the |
816 | | // expressions of all element segments before |
817 | | // executing any active segment's `table.init` |
818 | | // (https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation). |
819 | | // So if any element expression may trap, and an |
820 | | // earlier write (including from this segment) |
821 | | // could be observed, then stage its evaluation |
822 | | // into a passive element segment, which is |
823 | | // evaluated before any active segment is applied. |
824 | | // Note that this passive segment isn't registered |
825 | | // in `passive_elem_map` so it's not reachable from |
826 | | // wasm itself. |
827 | | // |
828 | | // If no imported table has been written yet then a |
829 | | // trap is unobservable, so evaluating in place is |
830 | | // fine and avoids the extra copy. |
831 | 340k | side_effects_visible |= |
832 | 340k | self.result.module.is_imported_table(table_index); |
833 | 340k | let init = if side_effects_visible && elements_may_trap(&elements) { |
834 | 17 | let len = elements.len(); |
835 | 17 | let index = self |
836 | 17 | .result |
837 | 17 | .module |
838 | 17 | .passive_elements |
839 | 17 | .push((elements.ty(), len))?; |
840 | 17 | self.result.passive_elements.push(elements); |
841 | 17 | self.require_startup_func(); |
842 | 17 | TableSegmentInit::Staged { index, len } |
843 | | } else { |
844 | 340k | TableSegmentInit::Direct(elements) |
845 | | }; |
846 | | |
847 | 340k | self.result |
848 | 340k | .table_initialization |
849 | 340k | .segments |
850 | 340k | .push(TableSegment { |
851 | 340k | table_index, |
852 | 340k | offset, |
853 | 340k | init, |
854 | 340k | })?; |
855 | 340k | None |
856 | | } |
857 | | |
858 | | ElementKind::Passive => { |
859 | 85.0k | let passive_index = self |
860 | 85.0k | .result |
861 | 85.0k | .module |
862 | 85.0k | .passive_elements |
863 | 85.0k | .push((elements.ty(), elements.len()))?; |
864 | 85.0k | self.result.passive_elements.push(elements); |
865 | | // One-time initialization of passive element |
866 | | // segments is deferred to the startup function. |
867 | 85.0k | self.require_startup_func(); |
868 | 85.0k | Some(passive_index) |
869 | | } |
870 | | |
871 | 174k | ElementKind::Declared => None, |
872 | | }; |
873 | 600k | let elem_index = ElemIndex::from_u32(index as u32); |
874 | 600k | self.result |
875 | 600k | .passive_elem_map |
876 | 600k | .insert(elem_index, passive_index); |
877 | | } |
878 | | } |
879 | | |
880 | | Payload::CodeSectionStart { |
881 | 168k | count, |
882 | 168k | unchecked_range, |
883 | | .. |
884 | | } => { |
885 | 168k | self.validator.code_section_start(&unchecked_range)?; |
886 | 168k | let cnt = usize::try_from(count).unwrap(); |
887 | 168k | self.result.function_body_inputs.reserve_exact(cnt); |
888 | 168k | self.result.debuginfo.wasm_file.code_section_offset = unchecked_range.start; |
889 | | } |
890 | | |
891 | 1.78M | Payload::CodeSectionEntry(body) => { |
892 | 1.78M | let validator = self.validator.code_section_entry(&body)?; |
893 | 1.78M | let func_index = |
894 | 1.78M | self.result.code_index + self.result.module.num_imported_funcs as u32; |
895 | 1.78M | let func_index = FuncIndex::from_u32(func_index); |
896 | | |
897 | 1.78M | if self.tunables.debug_native { |
898 | 0 | let sig_index = self.result.module.functions[func_index] |
899 | 0 | .signature |
900 | 0 | .unwrap_module_type_index(); |
901 | 0 | let sig = self.types[sig_index].unwrap_func(); |
902 | 0 | let mut locals = Vec::new(); |
903 | 0 | for pair in body.get_locals_reader()? { |
904 | 0 | let (cnt, ty) = pair?; |
905 | 0 | let ty = self.convert_valtype(ty)?; |
906 | 0 | locals.push((cnt, ty)); |
907 | | } |
908 | 0 | self.result |
909 | 0 | .debuginfo |
910 | 0 | .wasm_file |
911 | 0 | .funcs |
912 | 0 | .push(FunctionMetadata { |
913 | 0 | locals: locals.into_boxed_slice(), |
914 | 0 | params: sig.params().into(), |
915 | 0 | }); |
916 | 1.78M | } |
917 | 1.78M | if self.tunables.debug_guest { |
918 | 6 | // All functions are potentially reachable and |
919 | 6 | // callable by the guest debugger, so they must |
920 | 6 | // all be flagged as escaping. |
921 | 6 | self.flag_func_escaped(func_index); |
922 | 1.78M | } |
923 | 1.78M | self.result |
924 | 1.78M | .function_body_inputs |
925 | 1.78M | .push(FunctionBodyData { validator, body }); |
926 | 1.78M | self.result.code_index += 1; |
927 | | } |
928 | | |
929 | 38.7k | Payload::DataSection(data) => { |
930 | 38.7k | self.validator.data_section(&data)?; |
931 | | |
932 | 36.7k | assert!(self.result.module.memory_initialization.is_segmented()); |
933 | | |
934 | 444k | for (index, entry) in data.into_iter().enumerate() { |
935 | | let wasmparser::Data { |
936 | 444k | kind, |
937 | 444k | data, |
938 | | range: _, |
939 | 444k | } = entry?; |
940 | 444k | let data_index = DataIndex::from_u32(index.try_into().unwrap()); |
941 | 444k | match kind { |
942 | | DataKind::Active { |
943 | 174k | memory_index, |
944 | 174k | offset_expr, |
945 | | } => { |
946 | 174k | let memory_index = MemoryIndex::from_u32(memory_index); |
947 | 174k | let (offset, escaped) = ConstExpr::from_wasmparser(self, offset_expr)?; |
948 | 174k | debug_assert!(escaped.is_empty()); |
949 | | |
950 | 174k | let MemoryInit::Unprocessed(list) = &mut self.result.memory_init else { |
951 | 0 | panic!("memory initializers should be unprocessed at this point"); |
952 | | }; |
953 | 174k | list.push(MemoryInitializer { |
954 | 174k | memory_index, |
955 | 174k | offset, |
956 | 174k | data, |
957 | 174k | }); |
958 | | } |
959 | 270k | DataKind::Passive => { |
960 | 270k | self.result.passive_data.push((data_index, data)); |
961 | 270k | } |
962 | | } |
963 | | } |
964 | | } |
965 | | |
966 | 25.0k | Payload::DataCountSection { count, range } => { |
967 | 25.0k | self.validator.data_count_section(count, &range)?; |
968 | | |
969 | | // Note: the count passed in here is the *total* segment count |
970 | | // There is no way to reserve for just the passive segments as |
971 | | // they are discovered when iterating the data section entries |
972 | | // Given that the total segment count might be much larger than |
973 | | // the passive count, do not reserve anything here. |
974 | | } |
975 | | |
976 | 2 | Payload::CustomSection(s) |
977 | 226k | if s.name() == "webidl-bindings" || s.name() == "wasm-interface-types" => |
978 | | { |
979 | 2 | bail!( |
980 | | "\ |
981 | | Support for interface types has temporarily been removed from `wasmtime`. |
982 | | |
983 | | For more information about this temporary change you can read on the issue online: |
984 | | |
985 | | https://github.com/bytecodealliance/wasmtime/issues/1271 |
986 | | |
987 | | and for re-adding support for interface types you can see this issue: |
988 | | |
989 | | https://github.com/bytecodealliance/wasmtime/issues/677 |
990 | | " |
991 | | ) |
992 | | } |
993 | | |
994 | 226k | Payload::CustomSection(s) => { |
995 | 226k | self.register_custom_section(&s); |
996 | 226k | } |
997 | | |
998 | | // It's expected that validation will probably reject other |
999 | | // payloads such as `UnknownSection` or those related to the |
1000 | | // component model. If, however, something gets past validation then |
1001 | | // that's a bug in Wasmtime as we forgot to implement something. |
1002 | 60 | other => { |
1003 | 60 | self.validator.payload(&other)?; |
1004 | 0 | panic!("unimplemented section in wasm file {other:?}"); |
1005 | | } |
1006 | | } |
1007 | 3.66M | Ok(()) |
1008 | 3.67M | } |
1009 | | |
1010 | 226k | fn register_custom_section(&mut self, section: &CustomSectionReader<'data>) { |
1011 | 226k | match section.as_known() { |
1012 | 39.1k | KnownCustom::Name(name) => { |
1013 | 39.1k | let result = self.name_section(name); |
1014 | 39.1k | if let Err(e) = result { |
1015 | 1.14k | log::warn!("failed to parse name section {e:?}"); |
1016 | 38.0k | } |
1017 | | } |
1018 | 3 | KnownCustom::BranchHints(reader) if self.tunables.branch_hinting => { |
1019 | | // Branch hints are advisory and this section is never validated; |
1020 | | // it is decoded lazily during compilation, so record only the |
1021 | | // per-function sub-readers here. Discard the whole section if any |
1022 | | // entry is malformed rather than applying it partially. |
1023 | 3 | let mut hints = HashMap::new(); |
1024 | 4 | let result: wasmparser::Result<()> = reader.into_iter().try_for_each(|func| { |
1025 | 4 | let func = func?; |
1026 | | // A well-formed section lists each function at most once; keep |
1027 | | // the first entry deterministically if it repeats. |
1028 | 2 | hints |
1029 | 2 | .entry(FuncIndex::from_u32(func.func)) |
1030 | 2 | .or_insert(func.hints); |
1031 | 2 | Ok(()) |
1032 | 4 | }); |
1033 | 3 | match result { |
1034 | 1 | Ok(()) => self.result.branch_hints = hints, |
1035 | 2 | Err(e) => log::warn!("failed to parse branch-hint section {e:?}"), |
1036 | | } |
1037 | | } |
1038 | | _ => { |
1039 | 187k | let name = section.name().trim_end_matches(".dwo"); |
1040 | 187k | if name.starts_with(".debug_") { |
1041 | 179k | self.dwarf_section(name, section); |
1042 | 179k | } |
1043 | | } |
1044 | | } |
1045 | 226k | } |
1046 | | |
1047 | 179k | fn dwarf_section(&mut self, name: &str, section: &CustomSectionReader<'data>) { |
1048 | 179k | if !self.tunables.debug_native && !self.tunables.parse_wasm_debuginfo { |
1049 | 179k | self.result.has_unparsed_debuginfo = true; |
1050 | 179k | return; |
1051 | 0 | } |
1052 | 0 | let info = &mut self.result.debuginfo; |
1053 | 0 | let dwarf = &mut info.dwarf; |
1054 | 0 | let endian = gimli::LittleEndian; |
1055 | 0 | let data = section.data(); |
1056 | 0 | let slice = gimli::EndianSlice::new(data, endian); |
1057 | | |
1058 | 0 | match name { |
1059 | | // `gimli::Dwarf` fields. |
1060 | 0 | ".debug_abbrev" => dwarf.debug_abbrev = gimli::DebugAbbrev::new(data, endian), |
1061 | 0 | ".debug_addr" => dwarf.debug_addr = gimli::DebugAddr::from(slice), |
1062 | 0 | ".debug_info" => { |
1063 | 0 | dwarf.debug_info = gimli::DebugInfo::new(data, endian); |
1064 | 0 | } |
1065 | 0 | ".debug_line" => dwarf.debug_line = gimli::DebugLine::new(data, endian), |
1066 | 0 | ".debug_line_str" => dwarf.debug_line_str = gimli::DebugLineStr::from(slice), |
1067 | 0 | ".debug_str" => dwarf.debug_str = gimli::DebugStr::new(data, endian), |
1068 | 0 | ".debug_str_offsets" => dwarf.debug_str_offsets = gimli::DebugStrOffsets::from(slice), |
1069 | 0 | ".debug_str_sup" => { |
1070 | 0 | let mut dwarf_sup: Dwarf<'data> = Default::default(); |
1071 | 0 | dwarf_sup.debug_str = gimli::DebugStr::from(slice); |
1072 | 0 | dwarf.sup = Some(Arc::new(dwarf_sup)); |
1073 | 0 | } |
1074 | 0 | ".debug_types" => dwarf.debug_types = gimli::DebugTypes::from(slice), |
1075 | | |
1076 | | // Additional fields. |
1077 | 0 | ".debug_loc" => info.debug_loc = gimli::DebugLoc::from(slice), |
1078 | 0 | ".debug_loclists" => info.debug_loclists = gimli::DebugLocLists::from(slice), |
1079 | 0 | ".debug_ranges" => info.debug_ranges = gimli::DebugRanges::new(data, endian), |
1080 | 0 | ".debug_rnglists" => info.debug_rnglists = gimli::DebugRngLists::new(data, endian), |
1081 | | |
1082 | | // DWARF package fields |
1083 | 0 | ".debug_cu_index" => info.debug_cu_index = gimli::DebugCuIndex::new(data, endian), |
1084 | 0 | ".debug_tu_index" => info.debug_tu_index = gimli::DebugTuIndex::new(data, endian), |
1085 | | |
1086 | | // We don't use these at the moment. |
1087 | 0 | ".debug_aranges" | ".debug_pubnames" | ".debug_pubtypes" => return, |
1088 | 0 | other => { |
1089 | 0 | log::warn!("unknown debug section `{other}`"); |
1090 | 0 | return; |
1091 | | } |
1092 | | } |
1093 | | |
1094 | 0 | dwarf.ranges = gimli::RangeLists::new(info.debug_ranges, info.debug_rnglists); |
1095 | 0 | dwarf.locations = gimli::LocationLists::new(info.debug_loc, info.debug_loclists); |
1096 | 179k | } |
1097 | | |
1098 | | /// Declares a new import with the `module` and `field` names, importing the |
1099 | | /// `ty` specified. |
1100 | | /// |
1101 | | /// Note that this method is somewhat tricky due to the implementation of |
1102 | | /// the module linking proposal. In the module linking proposal two-level |
1103 | | /// imports are recast as single-level imports of instances. That recasting |
1104 | | /// happens here by recording an import of an instance for the first time |
1105 | | /// we see a two-level import. |
1106 | | /// |
1107 | | /// When the module linking proposal is disabled, however, disregard this |
1108 | | /// logic and instead work directly with two-level imports since no |
1109 | | /// instances are defined. |
1110 | 1.26M | fn declare_import( |
1111 | 1.26M | &mut self, |
1112 | 1.26M | module: &'data str, |
1113 | 1.26M | field: &'data str, |
1114 | 1.26M | ty: EntityType, |
1115 | 1.26M | ) -> Result<(), OutOfMemory> { |
1116 | 1.26M | let index = self.push_type(ty); |
1117 | 1.26M | self.result.module.initializers.push(Initializer::Import { |
1118 | 1.26M | name: self.result.module.strings.insert(module)?, |
1119 | 1.26M | field: self.result.module.strings.insert(field)?, |
1120 | 1.26M | index, |
1121 | 0 | })?; |
1122 | 1.26M | Ok(()) |
1123 | 1.26M | } |
1124 | | |
1125 | 1.26M | fn push_type(&mut self, ty: EntityType) -> EntityIndex { |
1126 | 1.26M | match ty { |
1127 | 358k | EntityType::Function(ty) => EntityIndex::Function({ |
1128 | 358k | let func_index = self |
1129 | 358k | .result |
1130 | 358k | .module |
1131 | 358k | .push_function(ty.unwrap_module_type_index()); |
1132 | 358k | // Imported functions can escape; in fact, they've already done |
1133 | 358k | // so to get here. |
1134 | 358k | self.flag_func_escaped(func_index); |
1135 | 358k | func_index |
1136 | 358k | }), |
1137 | 113k | EntityType::Table(ty) => { |
1138 | 113k | EntityIndex::Table(self.result.module.tables.push(ty).panic_on_oom()) |
1139 | | } |
1140 | 32.9k | EntityType::Memory(ty) => { |
1141 | 32.9k | EntityIndex::Memory(self.result.module.memories.push(ty).panic_on_oom()) |
1142 | | } |
1143 | 397k | EntityType::Global(ty) => { |
1144 | 397k | EntityIndex::Global(self.result.module.globals.push(ty).panic_on_oom()) |
1145 | | } |
1146 | 367k | EntityType::Tag(ty) => { |
1147 | 367k | EntityIndex::Tag(self.result.module.tags.push(ty).panic_on_oom()) |
1148 | | } |
1149 | | } |
1150 | 1.26M | } |
1151 | | |
1152 | 1.01M | fn flag_func_escaped(&mut self, func: FuncIndex) { |
1153 | 1.01M | let ty = &mut self.result.module.functions[func]; |
1154 | | // If this was already assigned a funcref index no need to re-assign it. |
1155 | 1.01M | if ty.is_escaping() { |
1156 | 211k | return; |
1157 | 801k | } |
1158 | 801k | let index = self.result.module.num_escaped_funcs as u32; |
1159 | 801k | ty.func_ref = FuncRefIndex::from_u32(index); |
1160 | 801k | self.result.module.num_escaped_funcs += 1; |
1161 | 1.01M | } |
1162 | | |
1163 | | /// Parses the Name section of the wasm module. |
1164 | 39.1k | fn name_section(&mut self, names: NameSectionReader<'data>) -> WasmResult<()> { |
1165 | 66.7k | for subsection in names { |
1166 | 66.7k | match subsection? { |
1167 | 24.4k | wasmparser::Name::Function(names) => { |
1168 | 76.6k | for name in names { |
1169 | 76.6k | let Naming { index, name } = name?; |
1170 | | // Skip this naming if it's naming a function that |
1171 | | // doesn't actually exist. |
1172 | 76.4k | if (index as usize) >= self.result.module.functions.len() { |
1173 | 121 | continue; |
1174 | 76.3k | } |
1175 | | |
1176 | | // Store the name unconditionally, regardless of |
1177 | | // whether we're parsing debuginfo, since function |
1178 | | // names are almost always present in the |
1179 | | // final compilation artifact. |
1180 | 76.3k | let index = FuncIndex::from_u32(index); |
1181 | 76.3k | self.result |
1182 | 76.3k | .debuginfo |
1183 | 76.3k | .name_section |
1184 | 76.3k | .func_names |
1185 | 76.3k | .insert(index, name); |
1186 | | } |
1187 | | } |
1188 | 19.6k | wasmparser::Name::Module { name, .. } => { |
1189 | 19.6k | self.result.module.name = |
1190 | 19.6k | Some(self.result.module.strings.insert(name).panic_on_oom()); |
1191 | 19.6k | if self.tunables.debug_native { |
1192 | 0 | self.result.debuginfo.name_section.module_name = Some(name); |
1193 | 19.6k | } |
1194 | | } |
1195 | 7.69k | wasmparser::Name::Local(reader) => { |
1196 | 7.69k | if !self.tunables.debug_native { |
1197 | 7.69k | continue; |
1198 | 0 | } |
1199 | 0 | for f in reader { |
1200 | 0 | let f = f?; |
1201 | | // Skip this naming if it's naming a function that |
1202 | | // doesn't actually exist. |
1203 | 0 | if (f.index as usize) >= self.result.module.functions.len() { |
1204 | 0 | continue; |
1205 | 0 | } |
1206 | 0 | for name in f.names { |
1207 | 0 | let Naming { index, name } = name?; |
1208 | | |
1209 | 0 | self.result |
1210 | 0 | .debuginfo |
1211 | 0 | .name_section |
1212 | 0 | .locals_names |
1213 | 0 | .entry(FuncIndex::from_u32(f.index)) |
1214 | 0 | .or_insert(HashMap::new()) |
1215 | 0 | .insert(index, name); |
1216 | | } |
1217 | | } |
1218 | | } |
1219 | | wasmparser::Name::Label(_) |
1220 | | | wasmparser::Name::Type(_) |
1221 | | | wasmparser::Name::Table(_) |
1222 | | | wasmparser::Name::Global(_) |
1223 | | | wasmparser::Name::Memory(_) |
1224 | | | wasmparser::Name::Element(_) |
1225 | | | wasmparser::Name::Data(_) |
1226 | | | wasmparser::Name::Tag(_) |
1227 | | | wasmparser::Name::Field(_) |
1228 | | | wasmparser::Name::Parameter(_) |
1229 | | | wasmparser::Name::TagParameter(_) |
1230 | 13.9k | | wasmparser::Name::Unknown { .. } => {} |
1231 | | } |
1232 | | } |
1233 | 38.0k | Ok(()) |
1234 | 39.1k | } |
1235 | | |
1236 | 523k | fn require_startup_func(&mut self) { |
1237 | 523k | self.result.require_startup_func(self.types); |
1238 | 523k | } |
1239 | | } |
1240 | | |
1241 | | impl TypeConvert for ModuleEnvironment<'_, '_> { |
1242 | 409k | fn lookup_heap_type(&self, index: wasmparser::UnpackedIndex) -> WasmHeapType { |
1243 | 409k | WasmparserTypeConverter::new(&self.types, |idx| { |
1244 | 409k | self.result.module.types[idx].unwrap_module_type_index() |
1245 | 409k | }) |
1246 | 409k | .lookup_heap_type(index) |
1247 | 409k | } |
1248 | | |
1249 | 0 | fn lookup_type_index(&self, index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex { |
1250 | 0 | WasmparserTypeConverter::new(&self.types, |idx| { |
1251 | 0 | self.result.module.types[idx].unwrap_module_type_index() |
1252 | 0 | }) |
1253 | 0 | .lookup_type_index(index) |
1254 | 0 | } |
1255 | | } |
1256 | | |
1257 | | impl ModuleTranslation<'_> { |
1258 | | /// Called after translation is complete this will finalize the memory |
1259 | | /// initialization strategy for this module. |
1260 | | /// |
1261 | | /// This will notably use `Self::try_static_init` to attempt to massage |
1262 | | /// data segments to being CoW-init-friendly. Afterwards the |
1263 | | /// `self.memory_init` field is transitioned from `Unprocessed` to |
1264 | | /// `Processed`. |
1265 | 236k | pub fn finalize_memory_init( |
1266 | 236k | &mut self, |
1267 | 236k | tunables: &Tunables, |
1268 | 236k | page_size: u64, |
1269 | 236k | max_image_size_always_allowed: u64, |
1270 | 236k | types: &mut ModuleTypesBuilder, |
1271 | 236k | ) { |
1272 | | // Memory images are installed before the module's startup function |
1273 | | // runs. If a table initializer can trap, using a memory image would |
1274 | | // initialize memory even though the startup function should trap |
1275 | | // before reaching the memory initializers. |
1276 | 236k | if tunables.memory_init_cow && !self.table_initialization_may_trap() { |
1277 | 124k | self.try_static_init(page_size, max_image_size_always_allowed); |
1278 | 124k | } |
1279 | | |
1280 | | // If any memory is statically initialized, and if that memory has an |
1281 | | // initial data segment, then a startup function is at least |
1282 | | // conditionally needed if the memory needs initialization. Flag as such |
1283 | | // here. |
1284 | 236k | if let MemoryInitialization::Static { map } = &self.module.memory_initialization { |
1285 | 120k | if map.iter().any(|(_, v)| v.is_some()) { |
1286 | 4.03k | self.require_startup_func_if_memories_need_init(types); |
1287 | 116k | } |
1288 | 116k | } |
1289 | | |
1290 | | // If, after `try_static_init`, initializers are still `Unprocessed` |
1291 | | // then this is the catch-all fallback path for initialization. All |
1292 | | // segments are promoted into `self.runtime_data` and then the |
1293 | | // initialization is rewritten to `Processed`. |
1294 | 236k | if let MemoryInit::Unprocessed(list) = &mut self.memory_init { |
1295 | 116k | let segments = mem::take(list); |
1296 | 116k | let mut new_initializers = Vec::new(); |
1297 | 137k | for segment in segments { |
1298 | 137k | new_initializers.push(( |
1299 | 137k | segment.memory_index, |
1300 | 137k | MemorySegmentOffset::Expr(segment.offset), |
1301 | 137k | self.runtime_data.push(segment.data.into()), |
1302 | 137k | )); |
1303 | 137k | } |
1304 | 116k | if !new_initializers.is_empty() { |
1305 | 14.3k | self.require_startup_func(types); |
1306 | 101k | } |
1307 | 116k | self.memory_init = MemoryInit::Processed(new_initializers); |
1308 | 120k | } |
1309 | | |
1310 | | // At this point append all passive data to the `runtime_data` list. |
1311 | | // This notably occurs after `try_static_init` above to ensure that the |
1312 | | // page-aligned data for static initialization, if applicable, comes |
1313 | | // first. |
1314 | 270k | for (data_index, segment) in self.passive_data.iter() { |
1315 | 270k | let runtime_index = self.runtime_data.push((*segment).into()); |
1316 | 270k | self.runtime_data_map |
1317 | 270k | .insert(*data_index, Some(runtime_index)); |
1318 | 270k | } |
1319 | | |
1320 | | // And, finally, record all chunks from `self.runtime_data` within |
1321 | | // `self.module.runtime_data` as well. |
1322 | 236k | let mut cur = 0; |
1323 | 412k | for (idx, data) in self.runtime_data.iter() { |
1324 | 412k | let len = u32::try_from(data.len()).unwrap(); |
1325 | 412k | let i = self.module.runtime_data.push(cur..cur + len).panic_on_oom(); |
1326 | 412k | cur += len; |
1327 | 412k | assert_eq!(idx, i); |
1328 | | } |
1329 | 236k | } |
1330 | | |
1331 | | /// Returns whether an active table initializer may trap during startup. |
1332 | | /// |
1333 | | /// Memory images are installed while allocating an instance, before the |
1334 | | /// startup function executes. Therefore a memory image cannot be used when |
1335 | | /// a table initializer might trap: doing so would make the memory |
1336 | | /// observable even though execution should stop before reaching the memory |
1337 | | /// initializers. |
1338 | 125k | fn table_initialization_may_trap(&self) -> bool { |
1339 | 202k | self.table_initialization.segments.iter().any(|segment| { |
1340 | 202k | let offset = match segment.offset.ops() { |
1341 | 192k | &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()), |
1342 | 10.1k | &[ConstOp::I64Const(offset)] => offset.cast_unsigned(), |
1343 | | // A dynamic offset cannot be proven to be in bounds here. |
1344 | 220 | _ => return true, |
1345 | | }; |
1346 | 202k | let top = match offset.checked_add(segment.init.len()) { |
1347 | 202k | Some(top) => top, |
1348 | 4 | None => return true, |
1349 | | }; |
1350 | 202k | if top > self.module.tables[segment.table_index].limits.min { |
1351 | 396 | return true; |
1352 | 202k | } |
1353 | 202k | match &segment.init { |
1354 | 202k | TableSegmentInit::Direct(elements) => elements_may_trap(elements), |
1355 | 3 | TableSegmentInit::Staged { .. } => true, |
1356 | | } |
1357 | 202k | }) |
1358 | 125k | } |
1359 | | |
1360 | | /// Attempts to convert segmented memory initialization into static |
1361 | | /// initialization for the module that this translation represents. |
1362 | | /// |
1363 | | /// If this module's memory initialization is not compatible with paged |
1364 | | /// initialization then this won't change anything. Otherwise if it is |
1365 | | /// compatible then the `memory_initialization` field will be updated. |
1366 | | /// |
1367 | | /// Takes a `page_size` argument in order to ensure that all |
1368 | | /// initialization is page-aligned for mmap-ability, and |
1369 | | /// `max_image_size_always_allowed` to control how we decide |
1370 | | /// whether to use static init. |
1371 | | /// |
1372 | | /// We will try to avoid generating very sparse images, which are |
1373 | | /// possible if e.g. a module has an initializer at offset 0 and a |
1374 | | /// very high offset (say, 1 GiB). To avoid this, we use a dual |
1375 | | /// condition: we always allow images less than |
1376 | | /// `max_image_size_always_allowed`, and the embedder of Wasmtime |
1377 | | /// can set this if desired to ensure that static init should |
1378 | | /// always be done if the size of the module or its heaps is |
1379 | | /// otherwise bounded by the system. We also allow images with |
1380 | | /// static init data bigger than that, but only if it is "dense", |
1381 | | /// defined as having at least half (50%) of its pages with some |
1382 | | /// data. |
1383 | | /// |
1384 | | /// We could do something slightly better by building a dense part |
1385 | | /// and keeping a sparse list of outlier/leftover segments (see |
1386 | | /// issue #3820). This would also allow mostly-static init of |
1387 | | /// modules that have some dynamically-placed data segments. But, |
1388 | | /// for now, this is sufficient to allow a system that "knows what |
1389 | | /// it's doing" to always get static init. |
1390 | 124k | fn try_static_init(&mut self, page_size: u64, max_image_size_always_allowed: u64) { |
1391 | 124k | let segments = match &mut self.memory_init { |
1392 | 124k | MemoryInit::Unprocessed(list) => list, |
1393 | 0 | _ => return, |
1394 | | }; |
1395 | | |
1396 | | // First a dry run of memory initialization is performed. This |
1397 | | // collects information about the extent of memory initialized for each |
1398 | | // memory as well as the size of all data segments being copied in. |
1399 | | struct Memory<'a> { |
1400 | | data_size: u64, |
1401 | | min_addr: u64, |
1402 | | max_addr: u64, |
1403 | | segments: Vec<(u64, &'a [u8])>, |
1404 | | } |
1405 | 124k | let mut info = PrimaryMap::with_capacity(self.module.memories.len()); |
1406 | 124k | for _ in 0..self.module.memories.len() { |
1407 | 53.1k | info.push(Memory { |
1408 | 53.1k | data_size: 0, |
1409 | 53.1k | min_addr: u64::MAX, |
1410 | 53.1k | max_addr: 0, |
1411 | 53.1k | segments: Vec::new(), |
1412 | 53.1k | }); |
1413 | 53.1k | } |
1414 | | |
1415 | 124k | for initializer in segments.iter() { |
1416 | | let &MemoryInitializer { |
1417 | 58.1k | memory_index, |
1418 | 58.1k | ref offset, |
1419 | 58.1k | ref data, |
1420 | 58.1k | } = initializer; |
1421 | | |
1422 | | // Currently `Static` only applies to locally-defined memories, |
1423 | | // so if a data segment references an imported memory then |
1424 | | // transitioning to a `Static` memory initializer is not |
1425 | | // possible. |
1426 | 58.1k | if self.module.defined_memory_index(memory_index).is_none() { |
1427 | 2.71k | return; |
1428 | 55.4k | } |
1429 | | |
1430 | | // First up determine the start/end range and verify that they're |
1431 | | // in-bounds for the initial size of the memory at `memory_index`. |
1432 | | // Note that this can bail if we don't have access to globals yet |
1433 | | // (e.g. this is a task happening before instantiation at |
1434 | | // compile-time). |
1435 | 55.4k | let start = match (offset.ops(), self.module.memories[memory_index].idx_type) { |
1436 | 49.6k | (&[ConstOp::I32Const(offset)], IndexType::I32) => offset.cast_unsigned().into(), |
1437 | 5.70k | (&[ConstOp::I64Const(offset)], IndexType::I64) => offset.cast_unsigned(), |
1438 | 81 | _ => return, |
1439 | | }; |
1440 | 55.3k | let len = u64::try_from(data.len()).unwrap(); |
1441 | 55.3k | let end = match start.checked_add(len) { |
1442 | 55.3k | Some(end) => end, |
1443 | 5 | None => return, |
1444 | | }; |
1445 | | |
1446 | 55.3k | match self.module.memories[memory_index].minimum_byte_size() { |
1447 | 55.3k | Ok(max) => { |
1448 | 55.3k | if end > max { |
1449 | 231 | return; |
1450 | 55.1k | } |
1451 | | } |
1452 | | |
1453 | | // Note that computing the minimum can overflow if the page |
1454 | | // size is the default 64KiB and the memory's minimum size in |
1455 | | // pages is `1 << 48`, the maximum number of minimum pages for |
1456 | | // 64-bit memories. We don't return `false` to signal an error |
1457 | | // here and instead defer the error to runtime, when it will be |
1458 | | // impossible to allocate that much memory anyways. |
1459 | 2 | Err(_) => return, |
1460 | | } |
1461 | | |
1462 | | // Skip empty in-bounds data segments. |
1463 | 55.1k | if data.is_empty() { |
1464 | 21.0k | continue; |
1465 | 34.0k | } |
1466 | | |
1467 | 34.0k | let info = &mut info[memory_index]; |
1468 | 34.0k | let len64 = u64::try_from(data.len()).unwrap(); |
1469 | 34.0k | info.data_size += len64; |
1470 | 34.0k | info.min_addr = info.min_addr.min(start); |
1471 | 34.0k | info.max_addr = info.max_addr.max(start + len64); |
1472 | 34.0k | info.segments.push((start, data)); |
1473 | | } |
1474 | | |
1475 | | // Validate that the memory information collected is indeed valid for |
1476 | | // static memory initialization. |
1477 | 121k | for (i, info) in info.iter().filter(|(_, info)| info.data_size > 0) { |
1478 | 5.75k | let image_size = info.max_addr - info.min_addr; |
1479 | | |
1480 | | // Simplify things for now by bailing out entirely if any memory has |
1481 | | // a page size smaller than the host's page size. This fixes a case |
1482 | | // where currently initializers are created in host-page-size units |
1483 | | // of length which means that a larger-than-the-entire-memory |
1484 | | // initializer can be created. This can be handled technically but |
1485 | | // would require some more changes to help fix the assert elsewhere |
1486 | | // that this protects against. |
1487 | 5.75k | if self.module.memories[i].page_size() < page_size { |
1488 | 1.44k | return; |
1489 | 4.31k | } |
1490 | | |
1491 | | // If the range of memory being initialized is less than twice the |
1492 | | // total size of the data itself then it's assumed that static |
1493 | | // initialization is ok. This means we'll at most double memory |
1494 | | // consumption during the memory image creation process, which is |
1495 | | // currently assumed to "probably be ok" but this will likely need |
1496 | | // tweaks over time. |
1497 | 4.31k | if image_size < info.data_size.saturating_mul(2) { |
1498 | 3.09k | continue; |
1499 | 1.22k | } |
1500 | | |
1501 | | // If the memory initialization image is larger than the size of all |
1502 | | // data, then we still allow memory initialization if the image will |
1503 | | // be of a relatively modest size, such as 1MB here. |
1504 | 1.22k | if image_size < max_image_size_always_allowed { |
1505 | 1.12k | continue; |
1506 | 93 | } |
1507 | | |
1508 | | // At this point memory initialization is concluded to be too |
1509 | | // expensive to do at compile time so it's entirely deferred to |
1510 | | // happen at runtime. |
1511 | 93 | return; |
1512 | | } |
1513 | | |
1514 | | // Here's where we've now committed to changing to static memory. The |
1515 | | // memory initialization image is built here from the page data and then |
1516 | | // it's converted to a single initializer. |
1517 | 120k | let mut map = TryPrimaryMap::with_capacity(info.len()).panic_on_oom(); |
1518 | 120k | let mut new_initializers = Vec::new(); |
1519 | 120k | for (memory, info) in info.iter() { |
1520 | | // Create the in-memory `image` which is the initialized contents of |
1521 | | // this linear memory. |
1522 | 46.6k | let extent = if info.segments.len() > 0 { |
1523 | 4.21k | (info.max_addr - info.min_addr) as usize |
1524 | | } else { |
1525 | 42.4k | 0 |
1526 | | }; |
1527 | 46.6k | let mut image = Vec::with_capacity(extent); |
1528 | 46.6k | for (offset, data) in info.segments.iter() { |
1529 | 18.4k | let offset = usize::try_from(*offset - info.min_addr).unwrap(); |
1530 | 18.4k | if image.len() < offset { |
1531 | 1.63k | image.resize(offset, 0u8); |
1532 | 1.63k | image.extend_from_slice(data); |
1533 | 16.8k | } else { |
1534 | 16.8k | image.splice( |
1535 | 16.8k | offset..(offset + data.len()).min(image.len()), |
1536 | 16.8k | data.iter().copied(), |
1537 | 16.8k | ); |
1538 | 16.8k | } |
1539 | | } |
1540 | 46.6k | assert_eq!(image.len(), extent); |
1541 | 46.6k | assert_eq!(image.capacity(), extent); |
1542 | 46.6k | let mut offset = if info.segments.len() > 0 { |
1543 | 4.21k | info.min_addr |
1544 | | } else { |
1545 | 42.4k | 0 |
1546 | | }; |
1547 | | |
1548 | | // Chop off trailing zeros from the image as memory is already |
1549 | | // zero-initialized. Note that `i` is the position of a nonzero |
1550 | | // entry here, so to not lose it we truncate to `i + 1`. |
1551 | 15.6M | if let Some(i) = image.iter().rposition(|i| *i != 0) { |
1552 | 4.09k | image.truncate(i + 1); |
1553 | 42.6k | } |
1554 | | |
1555 | | // Also chop off leading zeros, if any. |
1556 | 35.7M | if let Some(i) = image.iter().position(|i| *i != 0) { |
1557 | 4.09k | offset += i as u64; |
1558 | 4.09k | image.drain(..i); |
1559 | 42.6k | } |
1560 | 46.6k | let mut len = u64::try_from(image.len()).unwrap(); |
1561 | | |
1562 | | // The goal is to enable mapping this image directly into memory, so |
1563 | | // the offset into linear memory must be a multiple of the page |
1564 | | // size. If that's not already the case then the image is padded at |
1565 | | // the front and back with extra zeros as necessary |
1566 | 46.6k | if offset % page_size != 0 { |
1567 | 3.00k | let zero_padding = offset % page_size; |
1568 | 3.00k | image.splice(0..0, std::iter::repeat(0).take(zero_padding as usize)); |
1569 | 3.00k | offset -= zero_padding; |
1570 | 3.00k | len += zero_padding; |
1571 | 43.6k | } |
1572 | 46.6k | if len % page_size != 0 { |
1573 | 3.99k | let zero_padding = page_size - (len % page_size); |
1574 | 3.99k | image.extend(std::iter::repeat(0).take(zero_padding as usize)); |
1575 | 3.99k | len += zero_padding; |
1576 | 42.7k | } |
1577 | 46.6k | let runtime_index = if image.is_empty() { |
1578 | 42.4k | None |
1579 | | } else { |
1580 | 4.21k | Some(self.runtime_data.push(image.into())) |
1581 | | }; |
1582 | | |
1583 | | // Offset/length should now always be page-aligned. |
1584 | 46.6k | assert!(offset % page_size == 0); |
1585 | 46.6k | assert!(len % page_size == 0); |
1586 | | |
1587 | | // Record the static memory initializer which describes this image, |
1588 | | // only needed if the image is actually present and has a nonzero |
1589 | | // length. The `offset` has been calculates above, originally |
1590 | | // sourced from `info.min_addr`. The `data` field is the extent |
1591 | | // within the final data segment we'll emit to an ELF image, which |
1592 | | // is the concatenation of `self.data`, so here it's the size of |
1593 | | // the section-so-far plus the current segment we're appending. |
1594 | 46.6k | let idx = map.push(runtime_index.map(|i| (offset, i))).panic_on_oom(); |
1595 | 46.6k | assert_eq!(idx, memory); |
1596 | 46.6k | if let Some(runtime_index) = runtime_index { |
1597 | 4.21k | new_initializers.push((idx, MemorySegmentOffset::Static(offset), runtime_index)); |
1598 | 42.4k | } |
1599 | | } |
1600 | 120k | self.data_align = Some(page_size); |
1601 | 120k | self.module.memory_initialization = MemoryInitialization::Static { map }; |
1602 | 120k | self.memory_init = MemoryInit::Processed(new_initializers); |
1603 | 124k | } |
1604 | | |
1605 | | /// Finalizes the initialization of tables. |
1606 | | /// |
1607 | | /// This is invoked after translation and notably uses |
1608 | | /// `Self::try_func_table_init` to attempt to optimize initialization of |
1609 | | /// tables into static precomputed images. |
1610 | 236k | pub fn finalize_table_init(&mut self, tunables: &Tunables, types: &mut ModuleTypesBuilder) { |
1611 | 236k | if tunables.table_lazy_init { |
1612 | 140k | self.try_func_table_init(); |
1613 | 140k | } |
1614 | | |
1615 | | // If any table has a non-null initializers, or if there's any active |
1616 | | // data segments, then a startup function is unconditionally required to |
1617 | | // configure the table. |
1618 | 236k | if self |
1619 | 236k | .table_initialization |
1620 | 236k | .initial_values |
1621 | 236k | .iter() |
1622 | 236k | .any(|(_, v)| !matches!(v, TableInitialValue::Null)) |
1623 | 228k | || !self.table_initialization.segments.is_empty() |
1624 | 20.4k | { |
1625 | 20.4k | self.require_startup_func(types); |
1626 | 215k | } |
1627 | 236k | } |
1628 | | |
1629 | | /// Attempts to convert the module's table initializers to |
1630 | | /// FuncTable form where possible. This enables lazy table |
1631 | | /// initialization later by providing a one-to-one map of initial |
1632 | | /// table values, without having to parse all segments. |
1633 | 140k | fn try_func_table_init(&mut self) { |
1634 | | // This should be large enough to support very large Wasm |
1635 | | // modules with huge funcref tables, but small enough to avoid |
1636 | | // OOMs or DoS on truly sparse tables. |
1637 | | const MAX_FUNC_TABLE_SIZE: u64 = 1024 * 1024; |
1638 | | |
1639 | | // First convert any element-initialized tables to images of just that |
1640 | | // single function if the minimum size of the table allows doing so. |
1641 | 140k | for ((i, init), (_, table)) in self.table_initialization.initial_values.iter_mut().zip( |
1642 | 140k | self.module |
1643 | 140k | .tables |
1644 | 140k | .iter() |
1645 | 140k | .skip(self.module.num_imported_tables), |
1646 | | ) { |
1647 | 131k | let table_size = table.limits.min; |
1648 | 131k | if table_size > MAX_FUNC_TABLE_SIZE { |
1649 | 2 | continue; |
1650 | 131k | } |
1651 | 131k | if let TableInitialValue::Expr(expr) = init { |
1652 | 11.8k | if let [ConstOp::RefFunc(f)] = expr.ops() { |
1653 | 258 | assert!(self.module.table_initialization[i].is_empty()); |
1654 | 258 | self.module.table_initialization[i] = |
1655 | 258 | try_vec![*f; table_size as usize].panic_on_oom(); |
1656 | 258 | *init = TableInitialValue::Null; |
1657 | 11.5k | } |
1658 | 119k | } |
1659 | | } |
1660 | | |
1661 | 140k | let mut segments = mem::take(&mut self.table_initialization.segments) |
1662 | 140k | .into_iter() |
1663 | 140k | .peekable(); |
1664 | | |
1665 | | // The goal of this loop is to interpret a table segment and apply it |
1666 | | // "statically" to a local table. This will iterate over segments and |
1667 | | // apply them one-by-one to each table. |
1668 | | // |
1669 | | // If any segment can't be applied, however, then this loop exits and |
1670 | | // all remaining segments are placed back into the segment list. This is |
1671 | | // because segments are supposed to be initialized one-at-a-time which |
1672 | | // means that intermediate state is visible with respect to traps. If |
1673 | | // anything isn't statically known to not trap it's pessimistically |
1674 | | // assumed to trap meaning all further segment initializers must be |
1675 | | // applied manually at instantiation time. |
1676 | 187k | while let Some(segment) = segments.peek() { |
1677 | 54.1k | let defined_index = match self.module.defined_table_index(segment.table_index) { |
1678 | 49.8k | Some(index) => index, |
1679 | | // Skip imported tables: we can't provide a preconstructed |
1680 | | // table for them, because their values depend on the |
1681 | | // imported table overlaid with whatever segments we have. |
1682 | 4.29k | None => break, |
1683 | | }; |
1684 | | |
1685 | | // If the base of this segment is dynamic, then we can't |
1686 | | // include it in the statically-built array of initial |
1687 | | // contents. |
1688 | 49.8k | let offset = match segment.offset.ops() { |
1689 | 47.3k | &[ConstOp::I32Const(offset)] => u64::from(offset.cast_unsigned()), |
1690 | 2.42k | &[ConstOp::I64Const(offset)] => offset.cast_unsigned(), |
1691 | 100 | _ => break, |
1692 | | }; |
1693 | | |
1694 | | // Get the end of this segment. If out-of-bounds, or too |
1695 | | // large for our dense table representation, then skip the |
1696 | | // segment. |
1697 | 49.7k | let top = match offset.checked_add(segment.init.len()) { |
1698 | 49.7k | Some(top) => top, |
1699 | 4 | None => break, |
1700 | | }; |
1701 | 49.7k | let table_size = self.module.tables[segment.table_index].limits.min; |
1702 | 49.7k | if top > table_size || top > MAX_FUNC_TABLE_SIZE { |
1703 | 218 | break; |
1704 | 49.5k | } |
1705 | | |
1706 | 49.5k | match self.module.tables[segment.table_index] |
1707 | 49.5k | .ref_type |
1708 | 49.5k | .heap_type |
1709 | 49.5k | .top() |
1710 | | { |
1711 | 47.7k | WasmHeapTopType::Func => {} |
1712 | | // If this is not a funcref table, then we can't support a |
1713 | | // pre-computed table of function indices. Technically this |
1714 | | // initializer won't trap so we could continue processing |
1715 | | // segments, but that's left as a future optimization if |
1716 | | // necessary. |
1717 | | WasmHeapTopType::Any |
1718 | | | WasmHeapTopType::Extern |
1719 | | | WasmHeapTopType::Cont |
1720 | 1.74k | | WasmHeapTopType::Exn => break, |
1721 | | } |
1722 | | |
1723 | | // Function indices can be optimized here, but fully general |
1724 | | // expressions are deferred to get evaluated at runtime. |
1725 | 47.7k | let function_elements = match &segment.init { |
1726 | 46.7k | TableSegmentInit::Direct(TableSegmentElements::Functions(indices)) => indices, |
1727 | | TableSegmentInit::Direct(TableSegmentElements::Expressions { .. }) |
1728 | 1.00k | | TableSegmentInit::Staged { .. } => break, |
1729 | | }; |
1730 | | |
1731 | 46.7k | match &self.table_initialization.initial_values[defined_index] { |
1732 | 46.7k | TableInitialValue::Null => {} |
1733 | | |
1734 | | // If this table is still listed as an initial value here |
1735 | | // then that means the initial size of the table doesn't |
1736 | | // support a precomputed function list, so skip this. |
1737 | | // Technically this won't trap so it's possible to process |
1738 | | // further initializers, but that's left as a future |
1739 | | // optimization. |
1740 | 13 | TableInitialValue::Expr(_) => break, |
1741 | | } |
1742 | 46.7k | let precomputed = &mut self.module.table_initialization[defined_index]; |
1743 | | |
1744 | | // At this point we're committing to pre-initializing the table |
1745 | | // with the `segment` that's being iterated over. This segment is |
1746 | | // applied to the `precomputed` list for the table by ensuring |
1747 | | // it's large enough to hold the segment and then copying the |
1748 | | // segment into the precomputed list. |
1749 | 46.7k | if precomputed.len() < top as usize { |
1750 | 4.63k | precomputed |
1751 | 4.63k | .resize(top as usize, FuncIndex::reserved_value()) |
1752 | 4.63k | .panic_on_oom(); |
1753 | 42.1k | } |
1754 | 46.7k | let dst = &mut precomputed[offset as usize..top as usize]; |
1755 | 46.7k | dst.copy_from_slice(&function_elements); |
1756 | | |
1757 | | // advance the iterator to see the next segment |
1758 | 46.7k | let _ = segments.next(); |
1759 | | } |
1760 | 140k | self.table_initialization.segments = segments.try_collect().panic_on_oom(); |
1761 | 140k | } |
1762 | | |
1763 | | /// Helper function to ratchet the `startup` function for this module as |
1764 | | /// `Always`. |
1765 | 558k | fn require_startup_func(&mut self, types: &mut ModuleTypesBuilder) { |
1766 | 558k | let ty = match self.module.startup { |
1767 | 71.1k | ModuleStartup::None => types.startup_func_type().into(), |
1768 | 487k | ModuleStartup::Always(_) => return, |
1769 | 401 | ModuleStartup::IfMemoriesNeedInit(ty) => ty, |
1770 | | }; |
1771 | 71.5k | self.module.startup = ModuleStartup::Always(ty); |
1772 | 558k | } |
1773 | | |
1774 | | /// Helper function to ratchet the `startup` function for this module as |
1775 | | /// `IfMemoriesNeedInit`. |
1776 | 4.03k | fn require_startup_func_if_memories_need_init(&mut self, types: &mut ModuleTypesBuilder) { |
1777 | 4.03k | let ty = match self.module.startup { |
1778 | 2.87k | ModuleStartup::None => types.startup_func_type().into(), |
1779 | 1.16k | ModuleStartup::Always(_) | ModuleStartup::IfMemoriesNeedInit(_) => return, |
1780 | | }; |
1781 | 2.87k | self.module.startup = ModuleStartup::IfMemoriesNeedInit(ty); |
1782 | 4.03k | } |
1783 | | } |
1784 | | |
1785 | | /// Returns whether evaluating any element of `elements` may trap. |
1786 | 360k | fn elements_may_trap(elements: &TableSegmentElements) -> bool { |
1787 | 360k | match elements { |
1788 | 135k | TableSegmentElements::Functions(_) => false, |
1789 | 225k | TableSegmentElements::Expressions { exprs, .. } => exprs |
1790 | 225k | .iter() |
1791 | 225k | .any(|expr| expr.ops().iter().any(|op| op.may_trap())), |
1792 | | } |
1793 | 360k | } |