Debian Codegraph @

js/src/wasm/WasmMetadata.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #ifndef wasm_WasmMetadata_h
8 #define wasm_WasmMetadata_h
9
10 #include "mozilla/Atomics.h"
11
12 #include "wasm/WasmBinaryTypes.h"
13 #include "wasm/WasmHeuristics.h"
14 #include "wasm/WasmInstanceData.h" // various of *InstanceData
15 #include "wasm/WasmModuleTypes.h"
16 #include "wasm/WasmProcess.h" // IsHugeMemoryEnabled
17
18 namespace js {
19 namespace wasm {
20
21 using BuiltinModuleFuncIdVector =
22 Vector<BuiltinModuleFuncId, 0, SystemAllocPolicy>;
23
24 // ==== Printing of names
25 //
26 // The Developer-Facing Display Conventions section of the WebAssembly Web
27 // API spec defines two cases for displaying a wasm function name:
28 // 1. the function name stands alone
29 // 2. the function name precedes the location
30
31 enum class NameContext { Standalone, BeforeLocation };
32
33 // wasm::CodeMetadata contains metadata whose lifetime ends at the same time
34 // that the lifetime of wasm::Code ends. This encompasses a wide variety of
35 // uses. In practice that means metadata needed for any and all aspects of
36 // compilation or execution of wasm code. Hence this metadata conceptually
37 // belongs to, and is kept alive by, wasm::Code. Note also that wasm::Code is
38 // in turn kept alive by wasm::Instance(s), hence this metadata will be kept
39 // alive as long as any instance for it exists.
40
41 using ModuleHash = uint8_t[8];
42
43 struct CodeMetadata : public ShareableBase<CodeMetadata> {
44 // NOTE: if you add, remove, rename or reorder fields here, be sure to
45 // update CodeCodeMetadata() to keep it in sync.
46
47 // Constant parameters for the entire compilation. These are not marked
48 // `const` only because it breaks constructor delegation in
49 // CodeMetadata::CodeMetadata, which is a shame.
50 ModuleKind kind;
51
52 // The compile arguments that were used for this module.
53 SharedCompileArgs compileArgs;
54
55 // The number of imported functions in the module.
56 uint32_t numFuncImports;
57 // A vector of the builtin func id (or 'none') for all imported functions.
58 // This may be empty for internally constructed modules which don't care
59 // about this information.
60 BuiltinModuleFuncIdVector knownFuncImports;
61 // Treat imported wasm functions as if they were JS functions. This is used
62 // when compiling the module for new WebAssembly.Function.
63 bool funcImportsAreJS;
64 // The number of imported globals in the module.
65 uint32_t numGlobalImports;
66
67 // Info about all types in the module.
68 MutableTypeContext types;
69 // Info about all functions in the module.
70 FuncDescVector funcs;
71 // Info about all tables in the module.
72 TableDescVector tables;
73 // Info about all memories in the module.
74 MemoryDescVector memories;
75 // Info about all tags in the module.
76 TagDescVector tags;
77 // Info about all globals in the module.
78 GlobalDescVector globals;
79
80 // The start function for the module, if any
81 mozilla::Maybe<uint32_t> startFuncIndex;
82
83 // Info about elem segments needed only for validation and compilation.
84 // Should have the same length as ModuleMetadata::elemSegments, and each
85 // entry here should be identical the corresponding .elemType field in
86 // ModuleMetadata::elemSegments.
87 RefTypeVector elemSegmentTypes;
88
89 // The number of data segments this module will have. Pre-declared before the
90 // code section so that we can validate instructions that reference data
91 // segments.
92 mozilla::Maybe<uint32_t> dataCount;
93
94 // A sorted vector of the index of every function that is exported from this
95 // module. An index into this vector is a 'exported function index' and can
96 // be used to lookup exported functions on an instance.
97 Uint32Vector exportedFuncIndices;
98
99 // asm.js tables are homogenous and only store functions of the same type.
100 // This maps from a function type to the table index to use for an indirect
101 // call.
102 Uint32Vector asmJSSigToTableIndex;
103
104 // Branch hints to apply to functions
105 BranchHintCollection branchHints;
106
107 // Name section information
108 mozilla::Maybe<NameSection> nameSection;
109
110 // Bytecode ranges for custom sections.
111 CustomSectionRangeVector customSectionRanges;
112
113 // Bytecode range for the code section.
114 MaybeBytecodeRange codeSectionRange;
115
116 // ==== Instance layout fields
117 //
118 // The start offset of the FuncDefInstanceData[] section of the instance
119 // data. There is one entry for every function definition.
120 uint32_t funcDefsOffsetStart;
121 // The start offset of the FuncImportInstanceData[] section of the instance
122 // data. There is one entry for every imported function.
123 uint32_t funcImportsOffsetStart;
124 // The start offset of the FuncExportInstanceData[] section of the instance
125 // data. There is one entry for every exported function.
126 uint32_t funcExportsOffsetStart;
127 // The start offset of the TypeDefInstanceData[] section of the instance
128 // data. There is one entry for every type.
129 uint32_t typeDefsOffsetStart;
130 // The start offset of the MemoryInstanceData[] section of the instance data.
131 // There is one entry for every memory.
132 uint32_t memoriesOffsetStart;
133 // The start offset of the TableInstanceData[] section of the instance data.
134 // There is one entry for every table.
135 uint32_t tablesOffsetStart;
136 // The start offset of the tag section of the instance data. There is one
137 // entry for every tag.
138 uint32_t tagsOffsetStart;
139 // The total size of the instance data.
140 uint32_t instanceDataLength;
141
142 explicit CodeMetadata(const CompileArgs* compileArgs = nullptr,
143 ModuleKind kind = ModuleKind::Wasm)
144 : kind(kind),
145 compileArgs(compileArgs),
146 numFuncImports(0),
147 funcImportsAreJS(false),
148 numGlobalImports(0),
149 funcDefsOffsetStart(UINT32_MAX),
150 funcImportsOffsetStart(UINT32_MAX),
151 funcExportsOffsetStart(UINT32_MAX),
152 typeDefsOffsetStart(UINT32_MAX),
153 memoriesOffsetStart(UINT32_MAX),
154 tablesOffsetStart(UINT32_MAX),
155 tagsOffsetStart(UINT32_MAX),
156 instanceDataLength(UINT32_MAX) {}
157
158 [[nodiscard]] bool init() {
159 MOZ_ASSERT(!types);
160 types = js_new<TypeContext>();
161 return types;
162 }
163
164 // Generates any new metadata necessary to compile this module. This must be
165 // called after the 'module environment' (everything before the code section)
166 // has been decoded.
167 [[nodiscard]] bool prepareForCompile(CompileMode mode);
168 bool isPreparedForCompile() const { return instanceDataLength != UINT32_MAX; }
169
170 bool isAsmJS() const { return kind == ModuleKind::AsmJS; }
171 // A builtin module is a host constructed wasm module that exports host
172 // functionality, using special opcodes. Otherwise, it has the same rules
173 // as wasm modules and so it does not get a new ModuleKind.
174 bool isBuiltinModule() const { return features().isBuiltinModule; }
175
176 #define WASM_FEATURE(NAME, SHORT_NAME, ...) \
177 bool SHORT_NAME##Enabled() const { return features().SHORT_NAME; }
178 JS_FOR_WASM_FEATURES(WASM_FEATURE)
179 #undef WASM_FEATURE
180 Shareable sharedMemoryEnabled() const { return features().sharedMemory; }
181 bool simdAvailable() const { return features().simd; }
182
183 bool hugeMemoryEnabled(uint32_t memoryIndex) const {
184 return !isAsmJS() && memoryIndex < memories.length() &&
185 IsHugeMemoryEnabled(memories[memoryIndex].addressType());
186 }
187 bool usesSharedMemory(uint32_t memoryIndex) const {
188 return memoryIndex < memories.length() && memories[memoryIndex].isShared();
189 }
190
191 const FeatureArgs& features() const { return compileArgs->features; }
192 const ScriptedCaller& scriptedCaller() const {
193 return compileArgs->scriptedCaller;
194 }
195 const UniqueChars& sourceMapURL() const { return compileArgs->sourceMapURL; }
196
197 size_t numTypes() const { return types->length(); }
198 size_t numFuncs() const { return funcs.length(); }
199 size_t numFuncDefs() const { return funcs.length() - numFuncImports; }
200 size_t numTables() const { return tables.length(); }
201 size_t numMemories() const { return memories.length(); }
202
203 bool funcIsImport(uint32_t funcIndex) const {
204 return funcIndex < numFuncImports;
205 }
206 const TypeDef& getFuncTypeDef(uint32_t funcIndex) const {
207 return types->type(funcs[funcIndex].typeIndex);
208 }
209 const FuncType& getFuncType(uint32_t funcIndex) const {
210 return getFuncTypeDef(funcIndex).funcType();
211 }
212
213 BuiltinModuleFuncId knownFuncImport(uint32_t funcIndex) const {
214 MOZ_ASSERT(funcIndex < numFuncImports);
215 if (knownFuncImports.empty()) {
216 return BuiltinModuleFuncId::None;
217 }
218 return knownFuncImports[funcIndex];
219 }
220
221 // Find the exported function index for a function index
222 uint32_t findFuncExportIndex(uint32_t funcIndex) const;
223
224 // The number of functions that are exported in this module
225 uint32_t numExportedFuncs() const { return exportedFuncIndices.length(); }
226
227 size_t codeSectionSize() const {
228 if (codeSectionRange) {
229 return codeSectionRange->size();
230 }
231 return 0;
232 }
233
234 // This gets names for wasm only.
235 // For asm.js, see CodeMetadataForAsmJS::getFuncNameForAsmJS.
236 bool getFuncNameForWasm(NameContext ctx, uint32_t funcIndex,
237 const ShareableBytes* nameSectionPayload,
238 UTF8Bytes* name) const;
239
240 uint32_t offsetOfFuncDefInstanceData(uint32_t funcIndex) const {
241 MOZ_ASSERT(funcIndex >= numFuncImports && funcIndex < numFuncs());
242 return funcDefsOffsetStart +
243 (funcIndex - numFuncImports) * sizeof(FuncDefInstanceData);
244 }
245
246 uint32_t offsetOfFuncImportInstanceData(uint32_t funcIndex) const {
247 MOZ_ASSERT(funcIndex < numFuncImports);
248 return funcImportsOffsetStart + funcIndex * sizeof(FuncImportInstanceData);
249 }
250
251 uint32_t offsetOfFuncExportInstanceData(uint32_t funcExportIndex) const {
252 MOZ_ASSERT(funcExportIndex < exportedFuncIndices.length());
253 return funcExportsOffsetStart +
254 funcExportIndex * sizeof(FuncExportInstanceData);
255 }
256
257 uint32_t offsetOfTypeDefInstanceData(uint32_t typeIndex) const {
258 MOZ_ASSERT(typeIndex < types->length());
259 return typeDefsOffsetStart + typeIndex * sizeof(TypeDefInstanceData);
260 }
261
262 uint32_t offsetOfTypeDef(uint32_t typeIndex) const {
263 return offsetOfTypeDefInstanceData(typeIndex) +
264 offsetof(TypeDefInstanceData, typeDef);
265 }
266 uint32_t offsetOfSuperTypeVector(uint32_t typeIndex) const {
267 return offsetOfTypeDefInstanceData(typeIndex) +
268 offsetof(TypeDefInstanceData, superTypeVector);
269 }
270
271 uint32_t offsetOfMemoryInstanceData(uint32_t memoryIndex) const {
272 MOZ_ASSERT(memoryIndex < memories.length());
273 return memoriesOffsetStart + memoryIndex * sizeof(MemoryInstanceData);
274 }
275 uint32_t offsetOfTableInstanceData(uint32_t tableIndex) const {
276 MOZ_ASSERT(tableIndex < tables.length());
277 return tablesOffsetStart + tableIndex * sizeof(TableInstanceData);
278 }
279
280 uint32_t offsetOfTagInstanceData(uint32_t tagIndex) const {
281 MOZ_ASSERT(tagIndex < tags.length());
282 return tagsOffsetStart + tagIndex * sizeof(TagInstanceData);
283 }
284
285 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
286
287 private:
288 // Allocate space for `bytes`@`align` in the instance, updating
289 // `instanceDataLength` and returning the offset in in `assignedOffset`.
290 [[nodiscard]] bool allocateInstanceDataBytes(uint32_t bytes, uint32_t align,
291 uint32_t* assignedOffset);
292 // The same for an array of allocations.
293 [[nodiscard]] bool allocateInstanceDataBytesN(uint32_t bytes, uint32_t align,
294 uint32_t count,
295 uint32_t* assignedOffset);
296 };
297
298 using MutableCodeMetadata = RefPtr<CodeMetadata>;
299 using SharedCodeMetadata = RefPtr<const CodeMetadata>;
300
301 using InliningBudget = ExclusiveData<int64_t>;
302
303 // wasm::CodeTailMetadata contains all metadata needed by wasm::Code that is
304 // only after the whole module has been downloaded. It is sometimes available
305 // for Ion compilation, and never available for baseline compilation.
306 struct CodeTailMetadata : public ShareableBase<CodeTailMetadata> {
307 // Default initializer only used for serialization.
308 CodeTailMetadata();
309
310 // Initialize the metadata with a given wasm::CodeMetadata.
311 explicit CodeTailMetadata(const CodeMetadata& codeMeta);
312
313 // The code metadata for this module.
314 SharedCodeMetadata codeMeta;
315
316 // The bytes for the code section.
317 SharedBytes codeSectionBytecode;
318
319 // Whether this module was compiled with debugging support.
320 bool debugEnabled;
321
322 // A SHA-1 hash of the module bytecode for use in display urls. Only
323 // available if we're debugging.
324 ModuleHash debugHash;
325
326 // The full bytecode for this module. Only available for debuggable modules.
327 BytecodeBuffer debugBytecode;
328
329 // Shared and mutable inlining budget for this module.
330 mutable InliningBudget inliningBudget;
331
332 // The ranges of every function defined in this module.
333 BytecodeRangeVector funcDefRanges;
334
335 // The feature usage for every function defined in this module.
336 FeatureUsageVector funcDefFeatureUsages;
337
338 // Tracks the range of CallRefMetrics created for each function definition in
339 // this module.
340 CallRefMetricsRangeVector funcDefCallRefs;
341
342 // Tracks the range of AllocSites created for each function definition in
343 // this module. If we are compiling with a 'once' compilation and using just
344 // ion, this will be empty and ion will instead use per-typedef alloc sites.
345 AllocSitesRangeVector funcDefAllocSites;
346
347 // An array of hints to use when compiling a call_ref.
348 //
349 // This is written into when an instance requests a function to be tiered up,
350 // and read from our function compilers.
351 MutableCallRefHints callRefHints;
352
353 // nameSectionPayload points at the name section's CustomSection::payload so
354 // that the Names (which are use payload-relative offsets) can be used
355 // independently of the Module without duplicating the name section.
356 SharedBytes nameSectionPayload;
357
358 // The number of call ref metrics in Instance::callRefs_
359 uint32_t numCallRefMetrics;
360
361 // The number of AllocSites in Instance::allocSites_.
362 uint32_t numAllocSites;
363
364 // Given a bytecode offset inside a function definition, find the function
365 // index.
366 uint32_t findFuncIndex(uint32_t bytecodeOffset) const;
367 uint32_t funcBytecodeOffset(uint32_t funcIndex) const {
368 if (funcIndex < codeMeta->numFuncImports) {
369 return 0;
370 }
371 uint32_t funcDefIndex = funcIndex - codeMeta->numFuncImports;
372 return funcDefRanges[funcDefIndex].start;
373 }
374 const BytecodeRange& funcDefRange(uint32_t funcIndex) const {
375 MOZ_ASSERT(funcIndex >= codeMeta->numFuncImports);
376 uint32_t funcDefIndex = funcIndex - codeMeta->numFuncImports;
377 return funcDefRanges[funcDefIndex];
378 }
379 BytecodeSpan funcDefBody(uint32_t funcIndex) const {
380 return funcDefRange(funcIndex)
381 .relativeTo(*codeMeta->codeSectionRange)
382 .toSpan(*codeSectionBytecode);
383 }
384 FeatureUsage funcDefFeatureUsage(uint32_t funcIndex) const {
385 MOZ_ASSERT(funcIndex >= codeMeta->numFuncImports);
386 uint32_t funcDefIndex = funcIndex - codeMeta->numFuncImports;
387 return funcDefFeatureUsages[funcDefIndex];
388 }
389
390 CallRefMetricsRange getFuncDefCallRefs(uint32_t funcIndex) const {
391 MOZ_ASSERT(funcIndex >= codeMeta->numFuncImports);
392 uint32_t funcDefIndex = funcIndex - codeMeta->numFuncImports;
393 return funcDefCallRefs[funcDefIndex];
394 }
395
396 AllocSitesRange getFuncDefAllocSites(uint32_t funcIndex) const {
397 MOZ_ASSERT(funcIndex >= codeMeta->numFuncImports);
398 uint32_t funcDefIndex = funcIndex - codeMeta->numFuncImports;
399 return funcDefAllocSites[funcDefIndex];
400 }
401
402 bool hasFuncDefAllocSites() const { return !funcDefAllocSites.empty(); }
403
404 CallRefHint getCallRefHint(uint32_t callRefIndex) const {
405 if (!callRefHints) {
406 return CallRefHint();
407 }
408 return CallRefHint::fromRepr(callRefHints[callRefIndex]);
409 }
410 void setCallRefHint(uint32_t callRefIndex, CallRefHint hint) const {
411 callRefHints[callRefIndex] = hint.toRepr();
412 }
413 };
414
415 using MutableCodeTailMetadata = RefPtr<CodeTailMetadata>;
416 using SharedCodeTailMetadata = RefPtr<const CodeTailMetadata>;
417
418 // wasm::ModuleMetadata contains metadata whose lifetime ends at the same time
419 // that the lifetime of wasm::Module ends. In practice that means metadata
420 // that is needed only for creating wasm::Instances. Hence this metadata
421 // conceptually belongs to, and is held alive by, wasm::Module.
422
423 struct ModuleMetadata : public ShareableBase<ModuleMetadata> {
424 // NOTE: if you add, remove, rename or reorder fields here, be sure to
425 // update CodeModuleMetadata() to keep it in sync.
426
427 // The subset of module metadata that is shared between a module and
428 // instance (i.e. wasm::Code), and is available for all compilation. It
429 // does not contain any data that is only available after the whole module
430 // has been downloaded.
431 MutableCodeMetadata codeMeta;
432
433 // The subset of module metadata that is shared between a module and
434 // instance (i.e. wasm::Code), and is only available after the whole module
435 // has been downloaded.
436 MutableCodeTailMetadata codeTailMeta;
437
438 // Module fields decoded from the module environment (or initialized while
439 // validating an asm.js module) and immutable during compilation:
440 ImportVector imports;
441 ExportVector exports;
442
443 // Info about elem segments needed for instantiation. Should have the same
444 // length as CodeMetadata::elemSegmentTypes.
445 ModuleElemSegmentVector elemSegments;
446
447 // Info about data segments needed for instantiation. These wind up having
448 // the same length. Initially both are empty. `dataSegmentRanges` is
449 // filled in during validation, and `dataSegments` remains empty. Later, at
450 // module-generation time, `dataSegments` is filled in, by copying the
451 // underlying data blocks, and so the two vectors have the same length after
452 // that.
453 DataSegmentRangeVector dataSegmentRanges;
454 DataSegmentVector dataSegments;
455
456 CustomSectionVector customSections;
457
458 // Which features were observed when compiling this module.
459 FeatureUsage featureUsage = FeatureUsage::None;
460
461 explicit ModuleMetadata() = default;
462
463 [[nodiscard]] bool init(const CompileArgs& compileArgs,
464 ModuleKind kind = ModuleKind::Wasm) {
465 codeMeta = js_new<CodeMetadata>(&compileArgs, kind);
466 return !!codeMeta && codeMeta->init();
467 }
468
469 bool addDefinedFunc(ValTypeVector&& params, ValTypeVector&& results,
470 bool declareForRef = false,
471 mozilla::Maybe<CacheableName>&& optionalExportedName =
472 mozilla::Nothing());
473 bool addImportedFunc(ValTypeVector&& params, ValTypeVector&& results,
474 CacheableName&& importModName,
475 CacheableName&& importFieldName);
476
477 // Generates any new metadata necessary to compile this module. This must be
478 // called after the 'module environment' (everything before the code section)
479 // has been decoded.
480 [[nodiscard]] bool prepareForCompile(CompileMode mode) {
481 return codeMeta->prepareForCompile(mode);
482 }
483 bool isPreparedForCompile() const { return codeMeta->isPreparedForCompile(); }
484
485 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
486 };
487
488 using MutableModuleMetadata = RefPtr<ModuleMetadata>;
489 using SharedModuleMetadata = RefPtr<const ModuleMetadata>;
490
491 } // namespace wasm
492 } // namespace js
493
494 #endif /* wasm_WasmMetadata_h */