Debian Codegraph @

js/src/frontend/Stencil.cpp

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 #include "frontend/Stencil.h"
8
9 #include "mozilla/AlreadyAddRefed.h" // already_AddRefed
10 #include "mozilla/Assertions.h" // MOZ_RELEASE_ASSERT
11 #include "mozilla/CheckedInt.h" // mozilla::CheckedInt
12 #include "mozilla/Maybe.h" // mozilla::Maybe
13 #include "mozilla/OperatorNewExtensions.h" // mozilla::KnownNotNull
14 #include "mozilla/PodOperations.h" // mozilla::PodCopy
15 #include "mozilla/RefPtr.h" // RefPtr
16 #include "mozilla/ScopeExit.h" // mozilla::ScopeExit
17 #include "mozilla/Sprintf.h" // SprintfLiteral
18
19 #include <algorithm> // std::fill
20 #include <string.h> // strlen
21
22 #include "ds/LifoAlloc.h" // LifoAlloc
23 #include "frontend/AbstractScopePtr.h" // ScopeIndex
24 #include "frontend/BytecodeCompiler.h" // CompileGlobalScriptToStencil, InstantiateStencils, CanLazilyParse, ParseModuleToStencil
25 #include "frontend/BytecodeSection.h" // EmitScriptThingsVector
26 #include "frontend/CompilationStencil.h" // CompilationStencil, CompilationState, ExtensibleCompilationStencil, CompilationGCOutput, CompilationStencilMerger
27 #include "frontend/FrontendContext.h"
28 #include "frontend/NameAnalysisTypes.h" // EnvironmentCoordinate
29 #include "frontend/ParserAtom.h" // ParserAtom, ParserAtomIndex, TaggedParserAtomIndex, ParserAtomsTable, Length{1,2,3}StaticParserString, InstantiateMarkedAtoms, InstantiateMarkedAtomsAsPermanent, GetWellKnownAtom
30 #include "frontend/ScopeBindingCache.h" // ScopeBindingCache
31 #include "frontend/SharedContext.h"
32 #include "frontend/StencilXdr.h" // XDRStencilEncoder, XDRStencilDecoder
33 #include "gc/AllocKind.h" // gc::AllocKind
34 #include "gc/Tracer.h" // TraceNullableRoot
35 #include "jit/BaselineJIT.h" // jit::BaselineScript
36 #include "jit/JitRuntime.h" // jit::JitRuntime
37 #include "jit/JitScript.h" // AutoKeepJitScripts
38 #include "js/CallArgs.h" // JSNative
39 #include "js/CompileOptions.h" // JS::DecodeOptions, JS::ReadOnlyDecodeOptions
40 #include "js/experimental/CompileScript.h" // JS::PrepareForInstantiate
41 #include "js/experimental/JSStencil.h" // JS::Stencil
42 #include "js/GCAPI.h" // JS::AutoCheckCannotGC
43 #include "js/Prefs.h" // JS::Prefs
44 #include "js/Printer.h" // js::Fprinter
45 #include "js/RealmOptions.h" // JS::RealmBehaviors
46 #include "js/RootingAPI.h" // Rooted
47 #include "js/Transcoding.h" // JS::TranscodeBuffer
48 #include "js/Utility.h" // js_malloc, js_calloc, js_free
49 #include "js/Value.h" // ObjectValue
50 #include "js/WasmModule.h" // JS::WasmModule
51 #include "vm/BigIntType.h" // ParseBigIntLiteral, BigInt::createFromInt64
52 #include "vm/BindingKind.h" // BindingKind
53 #include "vm/EnvironmentObject.h"
54 #include "vm/GeneratorAndAsyncKind.h" // GeneratorKind, FunctionAsyncKind
55 #include "vm/JSAtomUtils.h" // AtomToPrintableString
56 #include "vm/JSContext.h" // JSContext
57 #include "vm/JSFunction.h" // JSFunction, GetFunctionPrototype, NewFunctionWithProto
58 #include "vm/JSObject.h" // JSObject, TenuredObject
59 #include "vm/JSONPrinter.h" // js::JSONPrinter
60 #include "vm/JSScript.h" // BaseScript, JSScript
61 #include "vm/Realm.h" // JS::Realm
62 #include "vm/RegExpObject.h" // js::RegExpObject
63 #include "vm/Scope.h" // Scope, *Scope, ScopeKind::*, ScopeKindString, ScopeIter, ScopeKindIsCatch, BindingIter, GetScopeDataTrailingNames, SizeOfParserScopeData
64 #include "vm/ScopeKind.h" // ScopeKind
65 #include "vm/SelfHosting.h" // SetClonedSelfHostedFunctionName
66 #include "vm/StaticStrings.h"
67 #include "vm/StencilEnums.h" // ImmutableScriptFlagsEnum
68 #include "vm/StringType.h" // JSAtom, js::CopyChars
69 #include "wasm/AsmJS.h" // InstantiateAsmJS
70
71 #include "jit/JitScript-inl.h" // AutoKeepJitScripts constructor
72 #include "vm/EnvironmentObject-inl.h" // JSObject::enclosingEnvironment
73 #include "vm/JSFunction-inl.h" // JSFunction::create
74 #include "vm/JSScript-inl.h" // JSScript::baselineScript
75
76 using namespace js;
77 using namespace js::frontend;
78
79 // These 2 functions are used to write the same code with lambda using auto
80 // arguments. The auto argument type is set by the Variant.match function of the
81 // InputScope variant. Thus dispatching to either a Scope* or to a
82 // ScopeStencilRef. This function can then be used as a way to specialize the
83 // code within the lambda without duplicating the code.
84 //
85 // Identically, an InputName is constructed using the scope type and the
86 // matching binding name type. This way, functions which are called by this
87 // lambda can manipulate an InputName and do not have to be duplicated.
88 //
89 // for (InputScopeIter si(...); si; si++) {
90 // si.scope().match([](auto& scope) {
91 // for (auto bi = InputBindingIter(scope); bi; bi++) {
92 // InputName name(scope, bi.name());
93 // }
94 // });
95 // }
96 static js::BindingIter InputBindingIter(Scope* ptr) {
97 return js::BindingIter(ptr);
98 }
99
100 static ParserBindingIter InputBindingIter(const ScopeStencilRef& ref) {
101 return ParserBindingIter(ref);
102 }
103
104 static ParserBindingIter InputBindingIter(const FakeStencilGlobalScope&) {
105 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("No bindings on empty global.");
106 }
107
108 InputName InputScript::displayAtom() const {
109 return script_.match(
110 [](BaseScript* ptr) {
111 return InputName(ptr, ptr->function()->fullDisplayAtom());
112 },
113 [](const ScriptStencilRef& ref) {
114 return InputName(ref, ref.scriptData().functionAtom);
115 });
116 }
117
118 TaggedParserAtomIndex InputName::internInto(FrontendContext* fc,
119 ParserAtomsTable& parserAtoms,
120 CompilationAtomCache& atomCache) {
121 return variant_.match(
122 [&](JSAtom* ptr) -> TaggedParserAtomIndex {
123 return parserAtoms.internJSAtom(fc, atomCache, ptr);
124 },
125 [&](NameStencilRef& ref) -> TaggedParserAtomIndex {
126 return parserAtoms.internExternalParserAtomIndex(fc, ref.context_,
127 ref.atomIndex_);
128 });
129 }
130
131 bool InputName::isEqualTo(FrontendContext* fc, ParserAtomsTable& parserAtoms,
132 CompilationAtomCache& atomCache,
133 TaggedParserAtomIndex other,
134 JSAtom** otherCached) const {
135 return variant_.match(
136 [&](const JSAtom* ptr) -> bool {
137 if (ptr->hash() != parserAtoms.hash(other)) {
138 return false;
139 }
140
141 // JSAtom variant is used only on the main thread delazification,
142 // where JSContext is always available.
143 JSContext* cx = fc->maybeCurrentJSContext();
144 MOZ_ASSERT(cx);
145
146 if (!*otherCached) {
147 // TODO-Stencil:
148 // Here, we convert our name into a JSAtom*, and hard-crash on failure
149 // to allocate. This conversion should not be required as we should be
150 // able to iterate up snapshotted scope chains that use parser atoms.
151 //
152 // This will be fixed when the enclosing scopes are snapshotted.
153 //
154 // See bug 1690277.
155 AutoEnterOOMUnsafeRegion oomUnsafe;
156 *otherCached = parserAtoms.toJSAtom(cx, fc, other, atomCache);
157 if (!*otherCached) {
158 oomUnsafe.crash("InputName::isEqualTo");
159 }
160 } else {
161 MOZ_ASSERT(atomCache.getExistingAtomAt(cx, other) == *otherCached);
162 }
163 return ptr == *otherCached;
164 },
165 [&](const NameStencilRef& ref) -> bool {
166 return parserAtoms.isEqualToExternalParserAtomIndex(other, ref.context_,
167 ref.atomIndex_);
168 });
169 }
170
171 GenericAtom::GenericAtom(FrontendContext* fc, ParserAtomsTable& parserAtoms,
172 CompilationAtomCache& atomCache,
173 TaggedParserAtomIndex index)
174 : ref(EmitterName(fc, parserAtoms, atomCache, index)) {
175 hash = parserAtoms.hash(index);
176 }
177
178 GenericAtom::GenericAtom(const CompilationStencil& context,
179 TaggedParserAtomIndex index)
180 : ref(StencilName{context, index}) {
181 if (index.isParserAtomIndex()) {
182 ParserAtom* atom = context.parserAtomData[index.toParserAtomIndex()];
183 hash = atom->hash();
184 } else {
185 hash = index.staticOrWellKnownHash();
186 }
187 }
188
189 GenericAtom::GenericAtom(ScopeStencilRef& scope, TaggedParserAtomIndex index)
190 : GenericAtom(scope.context_, index) {}
191
192 BindingHasher<TaggedParserAtomIndex>::Lookup::Lookup(ScopeStencilRef& scope_ref,
193 const GenericAtom& other)
194 : keyStencil(scope_ref.context_), other(other) {}
195
196 bool GenericAtom::operator==(const GenericAtom& other) const {
197 return ref.match(
198 [&other](const EmitterName& name) -> bool {
199 return other.ref.match(
200 [&name](const EmitterName& other) -> bool {
201 // We never have multiple Emitter context at the same time.
202 MOZ_ASSERT(name.fc == other.fc);
203 MOZ_ASSERT(&name.parserAtoms == &other.parserAtoms);
204 MOZ_ASSERT(&name.atomCache == &other.atomCache);
205 return name.index == other.index;
206 },
207 [&name](const StencilName& other) -> bool {
208 return name.parserAtoms.isEqualToExternalParserAtomIndex(
209 name.index, other.stencil, other.index);
210 },
211 [&name](JSAtom* other) -> bool {
212 // JSAtom variant is used only on the main thread delazification,
213 // where JSContext is always available.
214 JSContext* cx = name.fc->maybeCurrentJSContext();
215 MOZ_ASSERT(cx);
216 AutoEnterOOMUnsafeRegion oomUnsafe;
217 JSAtom* namePtr = name.parserAtoms.toJSAtom(
218 cx, name.fc, name.index, name.atomCache);
219 if (!namePtr) {
220 oomUnsafe.crash("GenericAtom(EmitterName == JSAtom*)");
221 }
222 return namePtr == other;
223 });
224 },
225 [&other](const StencilName& name) -> bool {
226 return other.ref.match(
227 [&name](const EmitterName& other) -> bool {
228 return other.parserAtoms.isEqualToExternalParserAtomIndex(
229 other.index, name.stencil, name.index);
230 },
231 [&name](const StencilName& other) -> bool {
232 // Technically it is possible to have multiple stencils, but in
233 // this particular case let's assume we never encounter a case
234 // where we are comparing names from different stencils.
235 //
236 // The reason this assumption is safe today is that we are only
237 // using this in the context of a stencil-delazification, where
238 // the only StencilNames are coming from the CompilationStencil
239 // provided to CompilationInput::initFromStencil.
240 MOZ_ASSERT(&name.stencil == &other.stencil);
241 return name.index == other.index;
242 },
243 [](JSAtom* other) -> bool {
244 MOZ_CRASH("Never used.");
245 return false;
246 });
247 },
248 [&other](JSAtom* name) -> bool {
249 return other.ref.match(
250 [&name](const EmitterName& other) -> bool {
251 // JSAtom variant is used only on the main thread delazification,
252 // where JSContext is always available.
253 JSContext* cx = other.fc->maybeCurrentJSContext();
254 MOZ_ASSERT(cx);
255 AutoEnterOOMUnsafeRegion oomUnsafe;
256 JSAtom* otherPtr = other.parserAtoms.toJSAtom(
257 cx, other.fc, other.index, other.atomCache);
258 if (!otherPtr) {
259 oomUnsafe.crash("GenericAtom(JSAtom* == EmitterName)");
260 }
261 return name == otherPtr;
262 },
263 [](const StencilName& other) -> bool {
264 MOZ_CRASH("Never used.");
265 return false;
266 },
267 [&name](JSAtom* other) -> bool { return name == other; });
268 });
269 }
270
271 #ifdef DEBUG
272 template <typename SpanT, typename VecT>
273 void AssertBorrowingSpan(const SpanT& span, const VecT& vec) {
274 MOZ_ASSERT(span.size() == vec.length());
275 MOZ_ASSERT(span.data() == vec.begin());
276 }
277 #endif
278
279 bool ScopeBindingCache::canCacheFor(Scope* ptr) {
280 MOZ_CRASH("Unexpected scope chain type: Scope*");
281 }
282
283 bool ScopeBindingCache::canCacheFor(ScopeStencilRef ref) {
284 MOZ_CRASH("Unexpected scope chain type: ScopeStencilRef");
285 }
286
287 bool ScopeBindingCache::canCacheFor(const FakeStencilGlobalScope& ref) {
288 MOZ_CRASH("Unexpected scope chain type: FakeStencilGlobalScope");
289 }
290
291 BindingMap<JSAtom*>* ScopeBindingCache::createCacheFor(Scope* ptr) {
292 MOZ_CRASH("Unexpected scope chain type: Scope*");
293 }
294
295 BindingMap<JSAtom*>* ScopeBindingCache::lookupScope(Scope* ptr,
296 CacheGeneration gen) {
297 MOZ_CRASH("Unexpected scope chain type: Scope*");
298 }
299
300 BindingMap<TaggedParserAtomIndex>* ScopeBindingCache::createCacheFor(
301 ScopeStencilRef ref) {
302 MOZ_CRASH("Unexpected scope chain type: ScopeStencilRef");
303 }
304
305 BindingMap<TaggedParserAtomIndex>* ScopeBindingCache::lookupScope(
306 ScopeStencilRef ref, CacheGeneration gen) {
307 MOZ_CRASH("Unexpected scope chain type: ScopeStencilRef");
308 }
309
310 BindingMap<TaggedParserAtomIndex>* ScopeBindingCache::createCacheFor(
311 const FakeStencilGlobalScope& ref) {
312 MOZ_CRASH("Unexpected scope chain type: FakeStencilGlobalScope");
313 }
314
315 BindingMap<TaggedParserAtomIndex>* ScopeBindingCache::lookupScope(
316 const FakeStencilGlobalScope& ref, CacheGeneration gen) {
317 MOZ_CRASH("Unexpected scope chain type: FakeStencilGlobalScope");
318 }
319
320 bool NoScopeBindingCache::canCacheFor(Scope* ptr) { return false; }
321
322 bool NoScopeBindingCache::canCacheFor(ScopeStencilRef ref) { return false; }
323
324 bool NoScopeBindingCache::canCacheFor(const FakeStencilGlobalScope& ref) {
325 return false;
326 }
327
328 bool RuntimeScopeBindingCache::canCacheFor(Scope* ptr) { return true; }
329
330 BindingMap<JSAtom*>* RuntimeScopeBindingCache::createCacheFor(Scope* ptr) {
331 BaseScopeData* dataPtr = ptr->rawData();
332 BindingMap<JSAtom*> bindingCache;
333 if (!scopeMap.putNew(dataPtr, std::move(bindingCache))) {
334 return nullptr;
335 }
336
337 return lookupScope(ptr, cacheGeneration);
338 }
339
340 BindingMap<JSAtom*>* RuntimeScopeBindingCache::lookupScope(
341 Scope* ptr, CacheGeneration gen) {
342 MOZ_ASSERT(gen == cacheGeneration);
343 BaseScopeData* dataPtr = ptr->rawData();
344 auto valuePtr = scopeMap.lookup(dataPtr);
345 if (!valuePtr) {
346 return nullptr;
347 }
348 return &valuePtr->value();
349 }
350
351 bool StencilScopeBindingCache::canCacheFor(ScopeStencilRef ref) { return true; }
352
353 BindingMap<TaggedParserAtomIndex>* StencilScopeBindingCache::createCacheFor(
354 ScopeStencilRef ref) {
355 #ifdef DEBUG
356 AssertBorrowingSpan(ref.context_.scopeNames, merger_.getResult().scopeNames);
357 #endif
358 auto* dataPtr = ref.context_.scopeNames[ref.scopeIndex_];
359 BindingMap<TaggedParserAtomIndex> bindingCache;
360 if (!scopeMap.putNew(dataPtr, std::move(bindingCache))) {
361 return nullptr;
362 }
363
364 return lookupScope(ref, 1);
365 }
366
367 BindingMap<TaggedParserAtomIndex>* StencilScopeBindingCache::lookupScope(
368 ScopeStencilRef ref, CacheGeneration gen) {
369 #ifdef DEBUG
370 AssertBorrowingSpan(ref.context_.scopeNames, merger_.getResult().scopeNames);
371 #endif
372 auto* dataPtr = ref.context_.scopeNames[ref.scopeIndex_];
373 auto ptr = scopeMap.lookup(dataPtr);
374 if (!ptr) {
375 return nullptr;
376 }
377 return &ptr->value();
378 }
379
380 static AbstractBaseScopeData<TaggedParserAtomIndex>
381 moduleGlobalAbstractScopeData;
382
383 bool StencilScopeBindingCache::canCacheFor(const FakeStencilGlobalScope& ref) {
384 return true;
385 }
386
387 BindingMap<TaggedParserAtomIndex>* StencilScopeBindingCache::createCacheFor(
388 const FakeStencilGlobalScope& ref) {
389 auto* dataPtr = &moduleGlobalAbstractScopeData;
390 BindingMap<TaggedParserAtomIndex> bindingCache;
391 if (!scopeMap.putNew(dataPtr, std::move(bindingCache))) {
392 return nullptr;
393 }
394
395 return lookupScope(ref, 1);
396 }
397
398 BindingMap<TaggedParserAtomIndex>* StencilScopeBindingCache::lookupScope(
399 const FakeStencilGlobalScope& ref, CacheGeneration gen) {
400 auto* dataPtr = &moduleGlobalAbstractScopeData;
401 auto ptr = scopeMap.lookup(dataPtr);
402 if (!ptr) {
403 return nullptr;
404 }
405 return &ptr->value();
406 }
407
408 bool ScopeContext::init(FrontendContext* fc, CompilationInput& input,
409 ParserAtomsTable& parserAtoms,
410 ScopeBindingCache* scopeCache, InheritThis inheritThis,
411 JSObject* enclosingEnv) {
412 // Record the scopeCache to be used while looking up NameLocation bindings.
413 this->scopeCache = scopeCache;
414 scopeCacheGen = scopeCache->getCurrentGeneration();
415
416 InputScope maybeNonDefaultEnclosingScope(
417 input.maybeNonDefaultEnclosingScope());
418
419 // If this eval is in response to Debugger.Frame.eval, we may have an
420 // incomplete scope chain. In order to provide a better debugging experience,
421 // we inspect the (optional) environment chain to determine it's enclosing
422 // FunctionScope if there is one. If there is no such scope, we use the
423 // orignal scope provided.
424 //
425 // NOTE: This is used to compute the ThisBinding kind and to allow access to
426 // private fields and methods, while other contextual information only
427 // uses the actual scope passed to the compile.
428 auto effectiveScope =
429 determineEffectiveScope(maybeNonDefaultEnclosingScope, enclosingEnv);
430
431 if (inheritThis == InheritThis::Yes) {
432 computeThisBinding(effectiveScope);
433 computeThisEnvironment(maybeNonDefaultEnclosingScope);
434 }
435 computeInScope(maybeNonDefaultEnclosingScope);
436
437 cacheEnclosingScope(input.enclosingScope);
438
439 if (input.target == CompilationInput::CompilationTarget::Eval) {
440 if (!cacheEnclosingScopeBindingForEval(fc, input, parserAtoms)) {
441 return false;
442 }
443 if (!cachePrivateFieldsForEval(fc, input, enclosingEnv, effectiveScope,
444 parserAtoms)) {
445 return false;
446 }
447 }
448
449 return true;
450 }
451
452 void ScopeContext::computeThisEnvironment(const InputScope& enclosingScope) {
453 uint32_t envCount = 0;
454 for (InputScopeIter si(enclosingScope); si; si++) {
455 if (si.kind() == ScopeKind::Function) {
456 // Arrow function inherit the "this" environment of the enclosing script,
457 // so continue ignore them.
458 if (!si.scope().isArrow()) {
459 allowNewTarget = true;
460
461 if (si.scope().allowSuperProperty()) {
462 allowSuperProperty = true;
463 enclosingThisEnvironmentHops = envCount;
464 }
465
466 if (si.scope().isClassConstructor()) {
467 memberInitializers =
468 si.scope().useMemberInitializers()
469 ? mozilla::Some(si.scope().getMemberInitializers())
470 : mozilla::Some(MemberInitializers::Empty());
471 MOZ_ASSERT(memberInitializers->valid);
472 } else {
473 if (si.scope().isSyntheticFunction()) {
474 allowArguments = false;
475 }
476 }
477
478 if (si.scope().isDerivedClassConstructor()) {
479 allowSuperCall = true;
480 }
481
482 // Found the effective "this" environment, so stop.
483 return;
484 }
485 }
486
487 if (si.scope().hasEnvironment()) {
488 envCount++;
489 }
490 }
491 }
492
493 void ScopeContext::computeThisBinding(const InputScope& scope) {
494 // Inspect the scope-chain.
495 for (InputScopeIter si(scope); si; si++) {
496 if (si.kind() == ScopeKind::Module) {
497 thisBinding = ThisBinding::Module;
498 return;
499 }
500
501 if (si.kind() == ScopeKind::Function) {
502 // Arrow functions don't have their own `this` binding.
503 if (si.scope().isArrow()) {
504 continue;
505 }
506
507 // Derived class constructors (and their nested arrow functions and evals)
508 // use ThisBinding::DerivedConstructor, which ensures TDZ checks happen
509 // when accessing |this|.
510 if (si.scope().isDerivedClassConstructor()) {
511 thisBinding = ThisBinding::DerivedConstructor;
512 } else {
513 thisBinding = ThisBinding::Function;
514 }
515
516 return;
517 }
518 }
519
520 thisBinding = ThisBinding::Global;
521 }
522
523 void ScopeContext::computeInScope(const InputScope& enclosingScope) {
524 for (InputScopeIter si(enclosingScope); si; si++) {
525 if (si.kind() == ScopeKind::ClassBody) {
526 inClass = true;
527 }
528
529 if (si.kind() == ScopeKind::With) {
530 inWith = true;
531 }
532 }
533 }
534
535 void ScopeContext::cacheEnclosingScope(const InputScope& enclosingScope) {
536 if (enclosingScope.isNull()) {
537 return;
538 }
539
540 enclosingScopeEnvironmentChainLength =
541 enclosingScope.environmentChainLength();
542 enclosingScopeKind = enclosingScope.kind();
543
544 if (enclosingScopeKind == ScopeKind::Function) {
545 enclosingScopeIsArrow = enclosingScope.isArrow();
546 }
547
548 enclosingScopeHasEnvironment = enclosingScope.hasEnvironment();
549
550 #ifdef DEBUG
551 hasNonSyntacticScopeOnChain =
552 enclosingScope.hasOnChain(ScopeKind::NonSyntactic);
553
554 // This computes a general answer for the query "does the enclosing scope
555 // have a function scope that needs a home object?", but it's only asserted
556 // if the parser parses eval body that contains `super` that needs a home
557 // object.
558 for (InputScopeIter si(enclosingScope); si; si++) {
559 if (si.kind() == ScopeKind::Function) {
560 if (si.scope().isArrow()) {
561 continue;
562 }
563 if (si.scope().allowSuperProperty() && si.scope().needsHomeObject()) {
564 hasFunctionNeedsHomeObjectOnChain = true;
565 }
566 break;
567 }
568 }
569 #endif
570
571 // Pre-fill the scope cache by iterating over all the names. Stop iterating
572 // as soon as we find a scope which already has a filled scope cache.
573 AutoEnterOOMUnsafeRegion oomUnsafe;
574 for (InputScopeIter si(enclosingScope); si; si++) {
575 // If the current scope already exists, then there is no need to go deeper
576 // as the scope which are encoded after this one should already be present
577 // in the cache.
578 bool hasScopeCache = si.scope().match([&](auto& scope_ref) -> bool {
579 MOZ_ASSERT(scopeCache->canCacheFor(scope_ref));
580 return scopeCache->lookupScope(scope_ref, scopeCacheGen);
581 });
582 if (hasScopeCache) {
583 return;
584 }
585
586 bool hasEnv = si.hasSyntacticEnvironment();
587 auto setCatchAll = [&](NameLocation loc) {
588 return si.scope().match([&](auto& scope_ref) {
589 using BindingMapPtr = decltype(scopeCache->createCacheFor(scope_ref));
590 BindingMapPtr bindingMapPtr = scopeCache->createCacheFor(scope_ref);
591 if (!bindingMapPtr) {
592 oomUnsafe.crash(
593 "ScopeContext::cacheEnclosingScope: scopeCache->createCacheFor");
594 return;
595 }
596
597 bindingMapPtr->catchAll.emplace(loc);
598 });
599 };
600 auto createEmpty = [&]() {
601 return si.scope().match([&](auto& scope_ref) {
602 using BindingMapPtr = decltype(scopeCache->createCacheFor(scope_ref));
603 BindingMapPtr bindingMapPtr = scopeCache->createCacheFor(scope_ref);
604 if (!bindingMapPtr) {
605 oomUnsafe.crash(
606 "ScopeContext::cacheEnclosingScope: scopeCache->createCacheFor");
607 return;
608 }
609 });
610 };
611
612 switch (si.kind()) {
613 case ScopeKind::Function:
614 if (hasEnv) {
615 if (si.scope().funHasExtensibleScope()) {
616 setCatchAll(NameLocation::Dynamic());
617 return;
618 }
619
620 si.scope().match([&](auto& scope_ref) {
621 using BindingMapPtr =
622 decltype(scopeCache->createCacheFor(scope_ref));
623 using Lookup =
624 typename std::remove_pointer_t<BindingMapPtr>::Lookup;
625 BindingMapPtr bindingMapPtr = scopeCache->createCacheFor(scope_ref);
626 if (!bindingMapPtr) {
627 oomUnsafe.crash(
628 "ScopeContext::cacheEnclosingScope: "
629 "scopeCache->createCacheFor");
630 return;
631 }
632
633 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
634 NameLocation loc = bi.nameLocation();
635 if (loc.kind() != NameLocation::Kind::EnvironmentCoordinate) {
636 continue;
637 }
638 auto ctxFreeKey = bi.name();
639 GenericAtom ctxKey(scope_ref, ctxFreeKey);
640 Lookup ctxLookup(scope_ref, ctxKey);
641 if (!bindingMapPtr->hashMap.put(ctxLookup, ctxFreeKey, loc)) {
642 oomUnsafe.crash(
643 "ScopeContext::cacheEnclosingScope: bindingMapPtr->put");
644 return;
645 }
646 }
647 });
648 } else {
649 createEmpty();
650 }
651 break;
652
653 case ScopeKind::StrictEval:
654 case ScopeKind::FunctionBodyVar:
655 case ScopeKind::Lexical:
656 case ScopeKind::NamedLambda:
657 case ScopeKind::StrictNamedLambda:
658 case ScopeKind::SimpleCatch:
659 case ScopeKind::Catch:
660 case ScopeKind::FunctionLexical:
661 case ScopeKind::ClassBody:
662 if (hasEnv) {
663 si.scope().match([&](auto& scope_ref) {
664 using BindingMapPtr =
665 decltype(scopeCache->createCacheFor(scope_ref));
666 using Lookup =
667 typename std::remove_pointer_t<BindingMapPtr>::Lookup;
668 BindingMapPtr bindingMapPtr = scopeCache->createCacheFor(scope_ref);
669 if (!bindingMapPtr) {
670 oomUnsafe.crash(
671 "ScopeContext::cacheEnclosingScope: "
672 "scopeCache->createCacheFor");
673 return;
674 }
675
676 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
677 NameLocation loc = bi.nameLocation();
678 if (loc.kind() != NameLocation::Kind::EnvironmentCoordinate) {
679 continue;
680 }
681 auto ctxFreeKey = bi.name();
682 GenericAtom ctxKey(scope_ref, ctxFreeKey);
683 Lookup ctxLookup(scope_ref, ctxKey);
684 if (!bindingMapPtr->hashMap.putNew(ctxLookup, ctxFreeKey, loc)) {
685 oomUnsafe.crash(
686 "ScopeContext::cacheEnclosingScope: bindingMapPtr->put");
687 return;
688 }
689 }
690 });
691 } else {
692 createEmpty();
693 }
694 break;
695
696 case ScopeKind::Module:
697 // This case is used only when delazifying a function inside
698 // module.
699 // Initial compilation of module doesn't have enlcosing scope.
700 if (hasEnv) {
701 si.scope().match([&](auto& scope_ref) {
702 using BindingMapPtr =
703 decltype(scopeCache->createCacheFor(scope_ref));
704 using Lookup =
705 typename std::remove_pointer_t<BindingMapPtr>::Lookup;
706 BindingMapPtr bindingMapPtr = scopeCache->createCacheFor(scope_ref);
707 if (!bindingMapPtr) {
708 oomUnsafe.crash(
709 "ScopeContext::cacheEnclosingScope: "
710 "scopeCache->createCacheFor");
711 return;
712 }
713
714 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
715 // Imports are on the environment but are indirect
716 // bindings and must be accessed dynamically instead of
717 // using an EnvironmentCoordinate.
718 NameLocation loc = bi.nameLocation();
719 if (loc.kind() != NameLocation::Kind::EnvironmentCoordinate &&
720 loc.kind() != NameLocation::Kind::Import) {
721 continue;
722 }
723 auto ctxFreeKey = bi.name();
724 GenericAtom ctxKey(scope_ref, ctxFreeKey);
725 Lookup ctxLookup(scope_ref, ctxKey);
726 if (!bindingMapPtr->hashMap.putNew(ctxLookup, ctxFreeKey, loc)) {
727 oomUnsafe.crash(
728 "ScopeContext::cacheEnclosingScope: bindingMapPtr->put");
729 return;
730 }
731 }
732 });
733 } else {
734 createEmpty();
735 }
736 break;
737
738 case ScopeKind::Eval:
739 // As an optimization, if the eval doesn't have its own var
740 // environment and its immediate enclosing scope is a global
741 // scope, all accesses are global.
742 if (!hasEnv) {
743 ScopeKind kind = si.scope().enclosing().kind();
744 if (kind == ScopeKind::Global || kind == ScopeKind::NonSyntactic) {
745 setCatchAll(NameLocation::Global(BindingKind::Var));
746 return;
747 }
748 }
749
750 setCatchAll(NameLocation::Dynamic());
751 return;
752
753 case ScopeKind::Global:
754 setCatchAll(NameLocation::Global(BindingKind::Var));
755 return;
756
757 case ScopeKind::With:
758 case ScopeKind::NonSyntactic:
759 setCatchAll(NameLocation::Dynamic());
760 return;
761
762 case ScopeKind::WasmInstance:
763 case ScopeKind::WasmFunction:
764 MOZ_CRASH("No direct eval inside wasm functions");
765 }
766 }
767
768 MOZ_CRASH("Malformed scope chain");
769 }
770
771 // Given an input scope, possibly refine this to a more precise scope.
772 // This is used during eval in the debugger to provide the appropriate scope and
773 // ThisBinding kind and environment, which is key to making private field eval
774 // work correctly.
775 //
776 // The trick here is that an eval may have a non-syntatic scope but nevertheless
777 // have an 'interesting' environment which can be traversed to find the
778 // appropriate scope the the eval to function as desired. See the diagram below.
779 //
780 // Eval Scope Eval Env Frame Env Frame Scope
781 // ============ ============= ========= =============
782 //
783 // NonSyntactic
784 // |
785 // v
786 // null DebugEnvProxy LexicalScope
787 // | |
788 // v v
789 // DebugEnvProxy --> CallObj --> FunctionScope
790 // | | |
791 // v v v
792 // ... ... ...
793 //
794 InputScope ScopeContext::determineEffectiveScope(InputScope& scope,
795 JSObject* environment) {
796 MOZ_ASSERT(effectiveScopeHops == 0);
797 // If the scope-chain is non-syntactic, we may still determine a more precise
798 // effective-scope to use instead.
799 if (environment && scope.hasOnChain(ScopeKind::NonSyntactic)) {
800 JSObject* env = environment;
801 while (env) {
802 // Look at target of any DebugEnvironmentProxy, but be sure to use
803 // enclosingEnvironment() of the proxy itself.
804 JSObject* unwrapped = env;
805 if (env->is<DebugEnvironmentProxy>()) {
806 unwrapped = &env->as<DebugEnvironmentProxy>().environment();
807 #ifdef DEBUG
808 enclosingEnvironmentIsDebugProxy_ = true;
809 #endif
810 }
811
812 if (unwrapped->is<CallObject>()) {
813 JSFunction* callee = &unwrapped->as<CallObject>().callee();
814 return InputScope(callee->nonLazyScript()->bodyScope());
815 }
816
817 env = env->enclosingEnvironment();
818 effectiveScopeHops++;
819 }
820 }
821
822 return scope;
823 }
824
825 static uint32_t DepthOfNearestVarScopeForDirectEval(const InputScope& scope) {
826 uint32_t depth = 0;
827 if (scope.isNull()) {
828 return depth;
829 }
830 for (InputScopeIter si(scope); si; si++) {
831 depth++;
832 switch (si.scope().kind()) {
833 case ScopeKind::Function:
834 case ScopeKind::FunctionBodyVar:
835 case ScopeKind::Global:
836 case ScopeKind::NonSyntactic:
837 return depth;
838 default:
839 break;
840 }
841 }
842 return depth;
843 }
844
845 bool ScopeContext::cacheEnclosingScopeBindingForEval(
846 FrontendContext* fc, CompilationInput& input,
847 ParserAtomsTable& parserAtoms) {
848 enclosingLexicalBindingCache_.emplace();
849
850 uint32_t varScopeDepth =
851 DepthOfNearestVarScopeForDirectEval(input.enclosingScope);
852 uint32_t depth = 0;
853 for (InputScopeIter si(input.enclosingScope); si; si++) {
854 bool success = si.scope().match([&](auto& scope_ref) {
855 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
856 switch (bi.kind()) {
857 case BindingKind::Let: {
858 // Annex B.3.5 allows redeclaring simple (non-destructured)
859 // catch parameters with var declarations.
860 bool annexB35Allowance = si.kind() == ScopeKind::SimpleCatch;
861 if (!annexB35Allowance) {
862 auto kind = ScopeKindIsCatch(si.kind())
863 ? EnclosingLexicalBindingKind::CatchParameter
864 : EnclosingLexicalBindingKind::Let;
865 InputName binding(scope_ref, bi.name());
866 if (!addToEnclosingLexicalBindingCache(
867 fc, parserAtoms, input.atomCache, binding, kind)) {
868 return false;
869 }
870 }
871 break;
872 }
873
874 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
875 // TODO: Optimize cache population for `using` bindings. (Bug 1899502)
876 case BindingKind::Using:
877 break;
878 #endif
879 case BindingKind::Const: {
880 InputName binding(scope_ref, bi.name());
881 if (!addToEnclosingLexicalBindingCache(
882 fc, parserAtoms, input.atomCache, binding,
883 EnclosingLexicalBindingKind::Const)) {
884 return false;
885 }
886 break;
887 }
888
889 case BindingKind::Synthetic: {
890 InputName binding(scope_ref, bi.name());
891 if (!addToEnclosingLexicalBindingCache(
892 fc, parserAtoms, input.atomCache, binding,
893 EnclosingLexicalBindingKind::Synthetic)) {
894 return false;
895 }
896 break;
897 }
898
899 case BindingKind::PrivateMethod: {
900 InputName binding(scope_ref, bi.name());
901 if (!addToEnclosingLexicalBindingCache(
902 fc, parserAtoms, input.atomCache, binding,
903 EnclosingLexicalBindingKind::PrivateMethod)) {
904 return false;
905 }
906 break;
907 }
908
909 case BindingKind::Import:
910 case BindingKind::FormalParameter:
911 case BindingKind::Var:
912 case BindingKind::NamedLambdaCallee:
913 break;
914 }
915 }
916 return true;
917 });
918 if (!success) {
919 return false;
920 }
921
922 if (++depth == varScopeDepth) {
923 break;
924 }
925 }
926
927 return true;
928 }
929
930 bool ScopeContext::addToEnclosingLexicalBindingCache(
931 FrontendContext* fc, ParserAtomsTable& parserAtoms,
932 CompilationAtomCache& atomCache, InputName& name,
933 EnclosingLexicalBindingKind kind) {
934 TaggedParserAtomIndex parserName =
935 name.internInto(fc, parserAtoms, atomCache);
936 if (!parserName) {
937 return false;
938 }
939
940 // Same lexical binding can appear multiple times across scopes.
941 //
942 // enclosingLexicalBindingCache_ map is used for detecting conflicting
943 // `var` binding, and inner binding should be reported in the error.
944 //
945 // cacheEnclosingScopeBindingForEval iterates from inner scope, and
946 // inner-most binding is added to the map first.
947 //
948 // Do not overwrite the value with outer bindings.
949 auto p = enclosingLexicalBindingCache_->lookupForAdd(parserName);
950 if (!p) {
951 if (!enclosingLexicalBindingCache_->add(p, parserName, kind)) {
952 ReportOutOfMemory(fc);
953 return false;
954 }
955 }
956
957 return true;
958 }
959
960 static bool IsPrivateField(Scope*, JSAtom* atom) {
961 MOZ_ASSERT(atom->length() > 0);
962
963 JS::AutoCheckCannotGC nogc;
964 if (atom->hasLatin1Chars()) {
965 return atom->latin1Chars(nogc)[0] == '#';
966 }
967
968 return atom->twoByteChars(nogc)[0] == '#';
969 }
970
971 static bool IsPrivateField(ScopeStencilRef& scope, TaggedParserAtomIndex atom) {
972 if (atom.isParserAtomIndex()) {
973 const CompilationStencil& context = scope.context_;
974 ParserAtom* parserAtom = context.parserAtomData[atom.toParserAtomIndex()];
975 return parserAtom->isPrivateName();
976 }
977
978 #ifdef DEBUG
979 if (atom.isWellKnownAtomId()) {
980 const auto& info = GetWellKnownAtomInfo(atom.toWellKnownAtomId());
981 // #constructor is a well-known term, but it is invalid private name.
982 MOZ_ASSERT(!(info.length > 1 && info.content[0] == '#'));
983 } else if (atom.isLength2StaticParserString()) {
984 char content[2];
985 ParserAtomsTable::getLength2Content(atom.toLength2StaticParserString(),
986 content);
987 // # character is not part of the allowed character of static strings.
988 MOZ_ASSERT(content[0] != '#');
989 }
990 #endif
991
992 return false;
993 }
994
995 static bool IsPrivateField(const FakeStencilGlobalScope&,
996 TaggedParserAtomIndex) {
997 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("No private fields on empty global.");
998 }
999
1000 bool ScopeContext::cachePrivateFieldsForEval(FrontendContext* fc,
1001 CompilationInput& input,
1002 JSObject* enclosingEnvironment,
1003 const InputScope& effectiveScope,
1004 ParserAtomsTable& parserAtoms) {
1005 effectiveScopePrivateFieldCache_.emplace();
1006
1007 // We compute an environment coordinate relative to the effective scope
1008 // environment. In order to safely consume these environment coordinates,
1009 // we re-map them to include the hops to get the to the effective scope:
1010 // see EmitterScope::lookupPrivate
1011 uint32_t hops = effectiveScopeHops;
1012 for (InputScopeIter si(effectiveScope); si; si++) {
1013 if (si.scope().kind() == ScopeKind::ClassBody) {
1014 uint32_t slots = 0;
1015 bool success = si.scope().match([&](auto& scope_ref) {
1016 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
1017 if (bi.kind() == BindingKind::PrivateMethod ||
1018 (bi.kind() == BindingKind::Synthetic &&
1019 IsPrivateField(scope_ref, bi.name()))) {
1020 InputName binding(scope_ref, bi.name());
1021 auto parserName =
1022 binding.internInto(fc, parserAtoms, input.atomCache);
1023 if (!parserName) {
1024 return false;
1025 }
1026
1027 NameLocation loc = NameLocation::DebugEnvironmentCoordinate(
1028 bi.kind(), hops, slots);
1029
1030 if (!effectiveScopePrivateFieldCache_->put(parserName, loc)) {
1031 ReportOutOfMemory(fc);
1032 return false;
1033 }
1034 }
1035 slots++;
1036 }
1037 return true;
1038 });
1039 if (!success) {
1040 return false;
1041 }
1042 }
1043
1044 // Hops is only consumed by GetAliasedDebugVar, which uses this to
1045 // traverse the debug environment chain. See the [SMDOC] for Debug
1046 // Environment Chain, which explains why we don't check for
1047 // isEnvironment when computing hops here (basically, debug proxies
1048 // pretend all scopes have environments, even if they were actually
1049 // optimized out).
1050 hops++;
1051 }
1052
1053 return true;
1054 }
1055
1056 #ifdef DEBUG
1057 static bool NameIsOnEnvironment(FrontendContext* fc,
1058 ParserAtomsTable& parserAtoms,
1059 CompilationAtomCache& atomCache,
1060 InputScope& scope, TaggedParserAtomIndex name) {
1061 JSAtom* jsname = nullptr;
1062 return scope.match([&](auto& scope_ref) {
1063 if (std::is_same_v<decltype(scope_ref), FakeStencilGlobalScope&>) {
1064 // This condition is added to handle the FakeStencilGlobalScope which is
1065 // used to emulate the global object when delazifying while executing, and
1066 // which is not provided by the Stencil.
1067 return true;
1068 }
1069 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
1070 // If found, the name must already be on the environment or an import,
1071 // or else there is a bug in the closed-over name analysis in the
1072 // Parser.
1073 InputName binding(scope_ref, bi.name());
1074 if (binding.isEqualTo(fc, parserAtoms, atomCache, name, &jsname)) {
1075 BindingLocation::Kind kind = bi.location().kind();
1076
1077 if (bi.hasArgumentSlot()) {
1078 // The following is equivalent to
1079 // functionScope.script()->functionAllowsParameterRedeclaration()
1080 if (scope.hasMappedArgsObj()) {
1081 // Check for duplicate positional formal parameters.
1082 using InputBindingIter = decltype(bi);
1083 for (InputBindingIter bi2(bi); bi2 && bi2.hasArgumentSlot();
1084 bi2++) {
1085 InputName binding2(scope_ref, bi2.name());
1086 if (binding2.isEqualTo(fc, parserAtoms, atomCache, name,
1087 &jsname)) {
1088 kind = bi2.location().kind();
1089 }
1090 }
1091 }
1092 }
1093
1094 return kind == BindingLocation::Kind::Global ||
1095 kind == BindingLocation::Kind::Environment ||
1096 kind == BindingLocation::Kind::Import;
1097 }
1098 }
1099
1100 // If not found, assume it's on the global or dynamically accessed.
1101 return true;
1102 });
1103 }
1104 #endif
1105
1106 NameLocation ScopeContext::searchInEnclosingScope(FrontendContext* fc,
1107 CompilationInput& input,
1108 ParserAtomsTable& parserAtoms,
1109 TaggedParserAtomIndex name) {
1110 MOZ_ASSERT(input.target ==
1111 CompilationInput::CompilationTarget::Delazification ||
1112 input.target == CompilationInput::CompilationTarget::Eval);
1113
1114 MOZ_ASSERT(scopeCache);
1115 if (scopeCacheGen != scopeCache->getCurrentGeneration()) {
1116 return searchInEnclosingScopeNoCache(fc, input, parserAtoms, name);
1117 }
1118
1119 #ifdef DEBUG
1120 // Catch assertion failures in the NoCache variant before looking at the
1121 // cached content.
1122 NameLocation expect =
1123 searchInEnclosingScopeNoCache(fc, input, parserAtoms, name);
1124 #endif
1125
1126 NameLocation found =
1127 searchInEnclosingScopeWithCache(fc, input, parserAtoms, name);
1128 MOZ_ASSERT(expect == found);
1129 return found;
1130 }
1131
1132 NameLocation ScopeContext::searchInEnclosingScopeWithCache(
1133 FrontendContext* fc, CompilationInput& input, ParserAtomsTable& parserAtoms,
1134 TaggedParserAtomIndex name) {
1135 MOZ_ASSERT(input.target ==
1136 CompilationInput::CompilationTarget::Delazification ||
1137 input.target == CompilationInput::CompilationTarget::Eval);
1138
1139 // Generic atom of the looked up name.
1140 GenericAtom genName(fc, parserAtoms, input.atomCache, name);
1141 mozilla::Maybe<NameLocation> found;
1142
1143 // Number of enclosing scope we walked over.
1144 uint8_t hops = 0;
1145
1146 for (InputScopeIter si(input.enclosingScope); si; si++) {
1147 MOZ_ASSERT(NameIsOnEnvironment(fc, parserAtoms, input.atomCache, si.scope(),
1148 name));
1149
1150 // If the result happens to be in the cached content of the scope that we
1151 // are iterating over, then return it.
1152 si.scope().match([&](auto& scope_ref) {
1153 using BindingMapPtr =
1154 decltype(scopeCache->lookupScope(scope_ref, scopeCacheGen));
1155 BindingMapPtr bindingMapPtr =
1156 scopeCache->lookupScope(scope_ref, scopeCacheGen);
1157 MOZ_ASSERT(bindingMapPtr);
1158
1159 auto& bindingMap = *bindingMapPtr;
1160 if (bindingMap.catchAll.isSome()) {
1161 found = bindingMap.catchAll;
1162 return;
1163 }
1164
1165 // The scope_ref is given as argument to know where to lookup the key
1166 // index of the hash table if the names have to be compared.
1167 using Lookup = typename std::remove_pointer_t<BindingMapPtr>::Lookup;
1168 Lookup ctxName(scope_ref, genName);
1169 auto ptr = bindingMap.hashMap.lookup(ctxName);
1170 if (!ptr) {
1171 return;
1172 }
1173
1174 found.emplace(ptr->value());
1175 });
1176
1177 if (found.isSome()) {
1178 // Cached entries do not store the number of hops, as it might be reused
1179 // by multiple inner functions, which might different number of hops.
1180 found = found.map([&hops](NameLocation loc) {
1181 if (loc.kind() != NameLocation::Kind::EnvironmentCoordinate) {
1182 return loc;
1183 }
1184 return loc.addHops(hops);
1185 });
1186 return found.value();
1187 }
1188
1189 bool hasEnv = si.hasSyntacticEnvironment();
1190
1191 if (hasEnv) {
1192 MOZ_ASSERT(hops < ENVCOORD_HOPS_LIMIT - 1);
1193 hops++;
1194 }
1195 }
1196
1197 MOZ_CRASH("Malformed scope chain");
1198 }
1199
1200 NameLocation ScopeContext::searchInEnclosingScopeNoCache(
1201 FrontendContext* fc, CompilationInput& input, ParserAtomsTable& parserAtoms,
1202 TaggedParserAtomIndex name) {
1203 MOZ_ASSERT(input.target ==
1204 CompilationInput::CompilationTarget::Delazification ||
1205 input.target == CompilationInput::CompilationTarget::Eval);
1206
1207 // Cached JSAtom equivalent of the TaggedParserAtomIndex `name` argument.
1208 JSAtom* jsname = nullptr;
1209
1210 // NameLocation which contains relative locations to access `name`.
1211 mozilla::Maybe<NameLocation> result;
1212
1213 // Number of enclosing scoep we walked over.
1214 uint8_t hops = 0;
1215
1216 for (InputScopeIter si(input.enclosingScope); si; si++) {
1217 MOZ_ASSERT(NameIsOnEnvironment(fc, parserAtoms, input.atomCache, si.scope(),
1218 name));
1219
1220 bool hasEnv = si.hasSyntacticEnvironment();
1221 switch (si.kind()) {
1222 case ScopeKind::Function:
1223 if (hasEnv) {
1224 if (si.scope().funHasExtensibleScope()) {
1225 return NameLocation::Dynamic();
1226 }
1227
1228 si.scope().match([&](auto& scope_ref) {
1229 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
1230 InputName binding(scope_ref, bi.name());
1231 if (!binding.isEqualTo(fc, parserAtoms, input.atomCache, name,
1232 &jsname)) {
1233 continue;
1234 }
1235
1236 BindingLocation bindLoc = bi.location();
1237 // hasMappedArgsObj == script.functionAllowsParameterRedeclaration
1238 if (bi.hasArgumentSlot() && si.scope().hasMappedArgsObj()) {
1239 // Check for duplicate positional formal parameters.
1240 using InputBindingIter = decltype(bi);
1241 for (InputBindingIter bi2(bi); bi2 && bi2.hasArgumentSlot();
1242 bi2++) {
1243 if (bi.name() == bi2.name()) {
1244 bindLoc = bi2.location();
1245 }
1246 }
1247 }
1248
1249 MOZ_ASSERT(bindLoc.kind() == BindingLocation::Kind::Environment);
1250 result.emplace(NameLocation::EnvironmentCoordinate(
1251 bi.kind(), hops, bindLoc.slot()));
1252 return;
1253 }
1254 });
1255 }
1256 break;
1257
1258 case ScopeKind::StrictEval:
1259 case ScopeKind::FunctionBodyVar:
1260 case ScopeKind::Lexical:
1261 case ScopeKind::NamedLambda:
1262 case ScopeKind::StrictNamedLambda:
1263 case ScopeKind::SimpleCatch:
1264 case ScopeKind::Catch:
1265 case ScopeKind::FunctionLexical:
1266 case ScopeKind::ClassBody:
1267 if (hasEnv) {
1268 si.scope().match([&](auto& scope_ref) {
1269 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
1270 InputName binding(scope_ref, bi.name());
1271 if (!binding.isEqualTo(fc, parserAtoms, input.atomCache, name,
1272 &jsname)) {
1273 continue;
1274 }
1275
1276 // The name must already have been marked as closed
1277 // over. If this assertion is hit, there is a bug in the
1278 // name analysis.
1279 BindingLocation bindLoc = bi.location();
1280 MOZ_ASSERT(bindLoc.kind() == BindingLocation::Kind::Environment);
1281 result.emplace(NameLocation::EnvironmentCoordinate(
1282 bi.kind(), hops, bindLoc.slot()));
1283 return;
1284 }
1285 });
1286 }
1287 break;
1288
1289 case ScopeKind::Module:
1290 // This case is used only when delazifying a function inside
1291 // module.
1292 // Initial compilation of module doesn't have enlcosing scope.
1293 if (hasEnv) {
1294 si.scope().match([&](auto& scope_ref) {
1295 for (auto bi = InputBindingIter(scope_ref); bi; bi++) {
1296 InputName binding(scope_ref, bi.name());
1297 if (!binding.isEqualTo(fc, parserAtoms, input.atomCache, name,
1298 &jsname)) {
1299 continue;
1300 }
1301
1302 BindingLocation bindLoc = bi.location();
1303
1304 // Imports are on the environment but are indirect
1305 // bindings and must be accessed dynamically instead of
1306 // using an EnvironmentCoordinate.
1307 if (bindLoc.kind() == BindingLocation::Kind::Import) {
1308 MOZ_ASSERT(si.kind() == ScopeKind::Module);
1309 result.emplace(NameLocation::Import());
1310 return;
1311 }
1312
1313 MOZ_ASSERT(bindLoc.kind() == BindingLocation::Kind::Environment);
1314 result.emplace(NameLocation::EnvironmentCoordinate(
1315 bi.kind(), hops, bindLoc.slot()));
1316 return;
1317 }
1318 });
1319 }
1320 break;
1321
1322 case ScopeKind::Eval:
1323 // As an optimization, if the eval doesn't have its own var
1324 // environment and its immediate enclosing scope is a global
1325 // scope, all accesses are global.
1326 if (!hasEnv) {
1327 ScopeKind kind = si.scope().enclosing().kind();
1328 if (kind == ScopeKind::Global || kind == ScopeKind::NonSyntactic) {
1329 return NameLocation::Global(BindingKind::Var);
1330 }
1331 }
1332 return NameLocation::Dynamic();
1333
1334 case ScopeKind::Global:
1335 return NameLocation::Global(BindingKind::Var);
1336
1337 case ScopeKind::With:
1338 case ScopeKind::NonSyntactic:
1339 return NameLocation::Dynamic();
1340
1341 case ScopeKind::WasmInstance:
1342 case ScopeKind::WasmFunction:
1343 MOZ_CRASH("No direct eval inside wasm functions");
1344 }
1345
1346 if (result.isSome()) {
1347 return result.value();
1348 }
1349
1350 if (hasEnv) {
1351 MOZ_ASSERT(hops < ENVCOORD_HOPS_LIMIT - 1);
1352 hops++;
1353 }
1354 }
1355
1356 MOZ_CRASH("Malformed scope chain");
1357 }
1358
1359 mozilla::Maybe<ScopeContext::EnclosingLexicalBindingKind>
1360 ScopeContext::lookupLexicalBindingInEnclosingScope(TaggedParserAtomIndex name) {
1361 auto p = enclosingLexicalBindingCache_->lookup(name);
1362 if (!p) {
1363 return mozilla::Nothing();
1364 }
1365
1366 return mozilla::Some(p->value());
1367 }
1368
1369 bool ScopeContext::effectiveScopePrivateFieldCacheHas(
1370 TaggedParserAtomIndex name) {
1371 return effectiveScopePrivateFieldCache_->has(name);
1372 }
1373
1374 mozilla::Maybe<NameLocation> ScopeContext::getPrivateFieldLocation(
1375 TaggedParserAtomIndex name) {
1376 // The locations returned by this method are only valid for
1377 // traversing debug environments.
1378 //
1379 // See the comment in cachePrivateFieldsForEval
1380 MOZ_ASSERT(enclosingEnvironmentIsDebugProxy_);
1381 auto p = effectiveScopePrivateFieldCache_->lookup(name);
1382 if (!p) {
1383 return mozilla::Nothing();
1384 }
1385 return mozilla::Some(p->value());
1386 }
1387
1388 bool CompilationInput::initScriptSource(FrontendContext* fc) {
1389 source = do_AddRef(fc->getAllocator()->new_<ScriptSource>());
1390 if (!source) {
1391 return false;
1392 }
1393
1394 return source->initFromOptions(fc, options);
1395 }
1396
1397 bool CompilationInput::initForStandaloneFunctionInNonSyntacticScope(
1398 FrontendContext* fc, Handle<Scope*> functionEnclosingScope) {
1399 MOZ_ASSERT(!functionEnclosingScope->as<GlobalScope>().isSyntactic());
1400
1401 target = CompilationTarget::StandaloneFunctionInNonSyntacticScope;
1402 if (!initScriptSource(fc)) {
1403 return false;
1404 }
1405 enclosingScope = InputScope(functionEnclosingScope);
1406 return true;
1407 }
1408
1409 FunctionSyntaxKind CompilationInput::functionSyntaxKind() const {
1410 if (functionFlags().isClassConstructor()) {
1411 if (functionFlags().hasBaseScript() && isDerivedClassConstructor()) {
1412 return FunctionSyntaxKind::DerivedClassConstructor;
1413 }
1414 return FunctionSyntaxKind::ClassConstructor;
1415 }
1416 if (functionFlags().isMethod()) {
1417 if (functionFlags().hasBaseScript() && isSyntheticFunction()) {
1418 // return FunctionSyntaxKind::FieldInitializer;
1419 MOZ_ASSERT_UNREACHABLE(
1420 "Lazy parsing of class field initializers not supported (yet)");
1421 }
1422 return FunctionSyntaxKind::Method;
1423 }
1424 if (functionFlags().isGetter()) {
1425 return FunctionSyntaxKind::Getter;
1426 }
1427 if (functionFlags().isSetter()) {
1428 return FunctionSyntaxKind::Setter;
1429 }
1430 if (functionFlags().isArrow()) {
1431 return FunctionSyntaxKind::Arrow;
1432 }
1433 return FunctionSyntaxKind::Statement;
1434 }
1435
1436 bool CompilationInput::internExtraBindings(FrontendContext* fc,
1437 ParserAtomsTable& parserAtoms) {
1438 MOZ_ASSERT(hasExtraBindings());
1439
1440 for (auto& bindingInfo : *maybeExtraBindings_) {
1441 if (bindingInfo.isShadowed) {
1442 continue;
1443 }
1444
1445 const char* chars = bindingInfo.nameChars.get();
1446 auto index = parserAtoms.internUtf8(
1447 fc, reinterpret_cast<const mozilla::Utf8Unit*>(chars), strlen(chars));
1448 if (!index) {
1449 return false;
1450 }
1451
1452 bindingInfo.nameIndex = index;
1453 }
1454
1455 return true;
1456 }
1457
1458 void InputScope::trace(JSTracer* trc) {
1459 using ScopePtr = Scope*;
1460 if (scope_.is<ScopePtr>()) {
1461 ScopePtr* ptrAddr = &scope_.as<ScopePtr>();
1462 TraceNullableRoot(trc, ptrAddr, "compilation-input-scope");
1463 }
1464 }
1465
1466 void InputScript::trace(JSTracer* trc) {
1467 using ScriptPtr = BaseScript*;
1468 if (script_.is<ScriptPtr>()) {
1469 ScriptPtr* ptrAddr = &script_.as<ScriptPtr>();
1470 TraceNullableRoot(trc, ptrAddr, "compilation-input-lazy");
1471 }
1472 }
1473
1474 void CompilationInput::trace(JSTracer* trc) {
1475 atomCache.trace(trc);
1476 lazy_.trace(trc);
1477 enclosingScope.trace(trc);
1478 }
1479
1480 bool CompilationSyntaxParseCache::init(FrontendContext* fc, LifoAlloc& alloc,
1481 ParserAtomsTable& parseAtoms,
1482 CompilationAtomCache& atomCache,
1483 const InputScript& lazy) {
1484 if (!copyFunctionInfo(fc, parseAtoms, atomCache, lazy)) {
1485 return false;
1486 }
1487 bool success = lazy.raw().match([&](auto& ref) {
1488 if (!copyScriptInfo(fc, alloc, parseAtoms, atomCache, ref)) {
1489 return false;
1490 }
1491 if (!copyClosedOverBindings(fc, alloc, parseAtoms, atomCache, ref)) {
1492 return false;
1493 }
1494 return true;
1495 });
1496 if (!success) {
1497 return false;
1498 }
1499 #ifdef DEBUG
1500 isInitialized = true;
1501 #endif
1502 return true;
1503 }
1504
1505 bool CompilationSyntaxParseCache::copyFunctionInfo(
1506 FrontendContext* fc, ParserAtomsTable& parseAtoms,
1507 CompilationAtomCache& atomCache, const InputScript& lazy) {
1508 InputName name = lazy.displayAtom();
1509 if (!name.isNull()) {
1510 displayAtom_ = name.internInto(fc, parseAtoms, atomCache);
1511 if (!displayAtom_) {
1512 return false;
1513 }
1514 }
1515
1516 funExtra_.immutableFlags = lazy.immutableFlags();
1517 funExtra_.extent = lazy.extent();
1518 if (funExtra_.useMemberInitializers()) {
1519 funExtra_.setMemberInitializers(lazy.getMemberInitializers());
1520 }
1521
1522 return true;
1523 }
1524
1525 bool CompilationSyntaxParseCache::copyScriptInfo(
1526 FrontendContext* fc, LifoAlloc& alloc, ParserAtomsTable& parseAtoms,
1527 CompilationAtomCache& atomCache, BaseScript* lazy) {
1528 using GCThingsSpan = mozilla::Span<TaggedScriptThingIndex>;
1529 using ScriptDataSpan = mozilla::Span<ScriptStencil>;
1530 using ScriptExtraSpan = mozilla::Span<ScriptStencilExtra>;
1531 cachedGCThings_ = GCThingsSpan(nullptr);
1532 cachedScriptData_ = ScriptDataSpan(nullptr);
1533 cachedScriptExtra_ = ScriptExtraSpan(nullptr);
1534
1535 auto gcthings = lazy->gcthings();
1536 size_t length = gcthings.Length();
1537 if (length == 0) {
1538 return true;
1539 }
1540
1541 // Reduce the length to the first element which is not a function.
1542 for (size_t i = 0; i < length; i++) {
1543 gc::Cell* cell = gcthings[i].asCell();
1544 if (!cell || !cell->is<JSObject>()) {
1545 length = i;
1546 break;
1547 }
1548 MOZ_ASSERT(cell->as<JSObject>()->is<JSFunction>());
1549 }
1550
1551 TaggedScriptThingIndex* gcThingsData =
1552 alloc.newArrayUninitialized<TaggedScriptThingIndex>(length);
1553 ScriptStencil* scriptData =
1554 alloc.newArrayUninitialized<ScriptStencil>(length);
1555 ScriptStencilExtra* scriptExtra =
1556 alloc.newArrayUninitialized<ScriptStencilExtra>(length);
1557 if (!gcThingsData || !scriptData || !scriptExtra) {
1558 ReportOutOfMemory(fc);
1559 return false;
1560 }
1561
1562 for (size_t i = 0; i < length; i++) {
1563 gc::Cell* cell = gcthings[i].asCell();
1564 JSFunction* fun = &cell->as<JSObject>()->as<JSFunction>();
1565 gcThingsData[i] = TaggedScriptThingIndex(ScriptIndex(i));
1566 new (mozilla::KnownNotNull, &scriptData[i]) ScriptStencil();
1567 ScriptStencil& data = scriptData[i];
1568 new (mozilla::KnownNotNull, &scriptExtra[i]) ScriptStencilExtra();
1569 ScriptStencilExtra& extra = scriptExtra[i];
1570
1571 if (fun->fullDisplayAtom()) {
1572 TaggedParserAtomIndex displayAtom =
1573 parseAtoms.internJSAtom(fc, atomCache, fun->fullDisplayAtom());
1574 if (!displayAtom) {
1575 return false;
1576 }
1577 data.functionAtom = displayAtom;
1578 }
1579 data.functionFlags = fun->flags();
1580
1581 BaseScript* lazy = fun->baseScript();
1582 extra.immutableFlags = lazy->immutableFlags();
1583 extra.extent = lazy->extent();
1584
1585 // Info derived from parent compilation should not be set yet for our inner
1586 // lazy functions. Instead that info will be updated when we finish our
1587 // compilation.
1588 MOZ_ASSERT(lazy->hasEnclosingScript());
1589 }
1590
1591 cachedGCThings_ = GCThingsSpan(gcThingsData, length);
1592 cachedScriptData_ = ScriptDataSpan(scriptData, length);
1593 cachedScriptExtra_ = ScriptExtraSpan(scriptExtra, length);
1594 return true;
1595 }
1596
1597 bool CompilationSyntaxParseCache::copyScriptInfo(
1598 FrontendContext* fc, LifoAlloc& alloc, ParserAtomsTable& parseAtoms,
1599 CompilationAtomCache& atomCache, const ScriptStencilRef& lazy) {
1600 using GCThingsSpan = mozilla::Span<TaggedScriptThingIndex>;
1601 using ScriptDataSpan = mozilla::Span<ScriptStencil>;
1602 using ScriptExtraSpan = mozilla::Span<ScriptStencilExtra>;
1603 cachedGCThings_ = GCThingsSpan(nullptr);
1604 cachedScriptData_ = ScriptDataSpan(nullptr);
1605 cachedScriptExtra_ = ScriptExtraSpan(nullptr);
1606
1607 size_t offset = lazy.scriptData().gcThingsOffset.index;
1608 size_t length = lazy.scriptData().gcThingsLength;
1609 if (length == 0) {
1610 return true;
1611 }
1612
1613 // Reduce the length to the first element which is not a function.
1614 for (size_t i = offset; i < offset + length; i++) {
1615 if (!lazy.context_.gcThingData[i].isFunction()) {
1616 length = i - offset;
1617 break;
1618 }
1619 }
1620
1621 TaggedScriptThingIndex* gcThingsData =
1622 alloc.newArrayUninitialized<TaggedScriptThingIndex>(length);
1623 ScriptStencil* scriptData =
1624 alloc.newArrayUninitialized<ScriptStencil>(length);
1625 ScriptStencilExtra* scriptExtra =
1626 alloc.newArrayUninitialized<ScriptStencilExtra>(length);
1627 if (!gcThingsData || !scriptData || !scriptExtra) {
1628 ReportOutOfMemory(fc);
1629 return false;
1630 }
1631
1632 for (size_t i = 0; i < length; i++) {
1633 ScriptStencilRef inner{lazy.context_,
1634 lazy.context_.gcThingData[i + offset].toFunction()};
1635 gcThingsData[i] = TaggedScriptThingIndex(ScriptIndex(i));
1636 new (mozilla::KnownNotNull, &scriptData[i]) ScriptStencil();
1637 ScriptStencil& data = scriptData[i];
1638 ScriptStencilExtra& extra = scriptExtra[i];
1639
1640 InputName name{inner, inner.scriptData().functionAtom};
1641 if (!name.isNull()) {
1642 auto displayAtom = name.internInto(fc, parseAtoms, atomCache);
1643 if (!displayAtom) {
1644 return false;
1645 }
1646 data.functionAtom = displayAtom;
1647 }
1648 data.functionFlags = inner.scriptData().functionFlags;
1649
1650 extra = inner.scriptExtra();
1651 }
1652
1653 cachedGCThings_ = GCThingsSpan(gcThingsData, length);
1654 cachedScriptData_ = ScriptDataSpan(scriptData, length);
1655 cachedScriptExtra_ = ScriptExtraSpan(scriptExtra, length);
1656 return true;
1657 }
1658
1659 bool CompilationSyntaxParseCache::copyClosedOverBindings(
1660 FrontendContext* fc, LifoAlloc& alloc, ParserAtomsTable& parseAtoms,
1661 CompilationAtomCache& atomCache, BaseScript* lazy) {
1662 using ClosedOverBindingsSpan = mozilla::Span<TaggedParserAtomIndex>;
1663 closedOverBindings_ = ClosedOverBindingsSpan(nullptr);
1664
1665 // The gcthings() array contains the inner function list followed by the
1666 // closed-over bindings data. Skip the inner function list, as it is already
1667 // cached in cachedGCThings_. See also: BaseScript::CreateLazy.
1668 size_t start = cachedGCThings_.Length();
1669 auto gcthings = lazy->gcthings();
1670 size_t length = gcthings.Length();
1671 MOZ_ASSERT(start <= length);
1672 if (length - start == 0) {
1673 return true;
1674 }
1675
1676 TaggedParserAtomIndex* closedOverBindings =
1677 alloc.newArrayUninitialized<TaggedParserAtomIndex>(length - start);
1678 if (!closedOverBindings) {
1679 ReportOutOfMemory(fc);
1680 return false;
1681 }
1682
1683 for (size_t i = start; i < length; i++) {
1684 gc::Cell* cell = gcthings[i].asCell();
1685 if (!cell) {
1686 closedOverBindings[i - start] = TaggedParserAtomIndex::null();
1687 continue;
1688 }
1689
1690 MOZ_ASSERT(cell->as<JSString>()->isAtom());
1691
1692 auto name = static_cast<JSAtom*>(cell);
1693 auto parserAtom = parseAtoms.internJSAtom(fc, atomCache, name);
1694 if (!parserAtom) {
1695 return false;
1696 }
1697
1698 closedOverBindings[i - start] = parserAtom;
1699 }
1700
1701 closedOverBindings_ =
1702 ClosedOverBindingsSpan(closedOverBindings, length - start);
1703 return true;
1704 }
1705
1706 bool CompilationSyntaxParseCache::copyClosedOverBindings(
1707 FrontendContext* fc, LifoAlloc& alloc, ParserAtomsTable& parseAtoms,
1708 CompilationAtomCache& atomCache, const ScriptStencilRef& lazy) {
1709 using ClosedOverBindingsSpan = mozilla::Span<TaggedParserAtomIndex>;
1710 closedOverBindings_ = ClosedOverBindingsSpan(nullptr);
1711
1712 // The gcthings array contains the inner function list followed by the
1713 // closed-over bindings data. Skip the inner function list, as it is already
1714 // cached in cachedGCThings_. See also: BaseScript::CreateLazy.
1715 size_t offset = lazy.scriptData().gcThingsOffset.index;
1716 size_t length = lazy.scriptData().gcThingsLength;
1717 size_t start = cachedGCThings_.Length();
1718 MOZ_ASSERT(start <= length);
1719 if (length - start == 0) {
1720 return true;
1721 }
1722 length -= start;
1723 start += offset;
1724
1725 // Atoms from the lazy.context (CompilationStencil) are not registered in the
1726 // the parseAtoms table. Thus we create a new span which will contain all the
1727 // interned atoms.
1728 TaggedParserAtomIndex* closedOverBindings =
1729 alloc.newArrayUninitialized<TaggedParserAtomIndex>(length);
1730 if (!closedOverBindings) {
1731 ReportOutOfMemory(fc);
1732 return false;
1733 }
1734
1735 for (size_t i = 0; i < length; i++) {
1736 auto gcThing = lazy.context_.gcThingData[i + start];
1737 if (gcThing.isNull()) {
1738 closedOverBindings[i] = TaggedParserAtomIndex::null();
1739 continue;
1740 }
1741
1742 MOZ_ASSERT(gcThing.isAtom());
1743 InputName name(lazy, gcThing.toAtom());
1744 auto parserAtom = name.internInto(fc, parseAtoms, atomCache);
1745 if (!parserAtom) {
1746 return false;
1747 }
1748
1749 closedOverBindings[i] = parserAtom;
1750 }
1751
1752 closedOverBindings_ = ClosedOverBindingsSpan(closedOverBindings, length);
1753 return true;
1754 }
1755
1756 template <typename T>
1757 PreAllocateableGCArray<T>::~PreAllocateableGCArray() {
1758 if (elems_) {
1759 js_free(elems_);
1760 elems_ = nullptr;
1761 }
1762 }
1763
1764 template <typename T>
1765 bool PreAllocateableGCArray<T>::allocate(size_t length) {
1766 MOZ_ASSERT(empty());
1767
1768 length_ = length;
1769
1770 if (isInline()) {
1771 inlineElem_ = nullptr;
1772 return true;
1773 }
1774
1775 elems_ = reinterpret_cast<T*>(js_calloc(sizeof(T) * length_));
1776 if (!elems_) {
1777 return false;
1778 }
1779
1780 return true;
1781 }
1782
1783 template <typename T>
1784 bool PreAllocateableGCArray<T>::allocateWith(T init, size_t length) {
1785 MOZ_ASSERT(empty());
1786
1787 length_ = length;
1788
1789 if (isInline()) {
1790 inlineElem_ = init;
1791 return true;
1792 }
1793
1794 elems_ = reinterpret_cast<T*>(js_malloc(sizeof(T) * length_));
1795 if (!elems_) {
1796 return false;
1797 }
1798
1799 std::fill(elems_, elems_ + length_, init);
1800 return true;
1801 }
1802
1803 template <typename T>
1804 void PreAllocateableGCArray<T>::steal(Preallocated&& buffer) {
1805 MOZ_ASSERT(empty());
1806
1807 length_ = buffer.length_;
1808 buffer.length_ = 0;
1809
1810 if (isInline()) {
1811 inlineElem_ = nullptr;
1812 return;
1813 }
1814
1815 elems_ = reinterpret_cast<T*>(buffer.elems_);
1816 buffer.elems_ = nullptr;
1817
1818 #ifdef DEBUG
1819 for (size_t i = 0; i < length_; i++) {
1820 MOZ_ASSERT(elems_[i] == nullptr);
1821 }
1822 #endif
1823 }
1824
1825 template <typename T>
1826 void PreAllocateableGCArray<T>::trace(JSTracer* trc) {
1827 if (empty()) {
1828 return;
1829 }
1830
1831 if (isInline()) {
1832 TraceNullableRoot(trc, &inlineElem_, "PreAllocateableGCArray::inlineElem_");
1833 return;
1834 }
1835
1836 for (size_t i = 0; i < length_; i++) {
1837 TraceNullableRoot(trc, &elems_[i], "PreAllocateableGCArray::elems_");
1838 }
1839 }
1840
1841 template <typename T>
1842 PreAllocateableGCArray<T>::Preallocated::~Preallocated() {
1843 if (elems_) {
1844 js_free(elems_);
1845 elems_ = nullptr;
1846 }
1847 }
1848
1849 template <typename T>
1850 bool PreAllocateableGCArray<T>::Preallocated::allocate(size_t length) {
1851 MOZ_ASSERT(empty());
1852
1853 length_ = length;
1854
1855 if (isInline()) {
1856 return true;
1857 }
1858
1859 elems_ = reinterpret_cast<uintptr_t*>(js_calloc(sizeof(uintptr_t) * length_));
1860 if (!elems_) {
1861 return false;
1862 }
1863
1864 return true;
1865 }
1866
1867 template struct js::frontend::PreAllocateableGCArray<JSFunction*>;
1868 template struct js::frontend::PreAllocateableGCArray<js::Scope*>;
1869
1870 void CompilationAtomCache::trace(JSTracer* trc) { atoms_.trace(trc); }
1871
1872 void CompilationGCOutput::trace(JSTracer* trc) {
1873 TraceNullableRoot(trc, &script, "compilation-gc-output-script");
1874 TraceNullableRoot(trc, &module, "compilation-gc-output-module");
1875 TraceNullableRoot(trc, &sourceObject, "compilation-gc-output-source");
1876 functions.trace(trc);
1877 scopes.trace(trc);
1878 }
1879
1880 RegExpObject* RegExpStencil::createRegExp(
1881 JSContext* cx, const CompilationAtomCache& atomCache) const {
1882 Rooted<JSAtom*> atom(cx, atomCache.getExistingAtomAt(cx, atom_));
1883 return RegExpObject::createSyntaxChecked(cx, atom, flags(), TenuredObject);
1884 }
1885
1886 RegExpObject* RegExpStencil::createRegExpAndEnsureAtom(
1887 JSContext* cx, FrontendContext* fc, ParserAtomsTable& parserAtoms,
1888 CompilationAtomCache& atomCache) const {
1889 Rooted<JSAtom*> atom(cx, parserAtoms.toJSAtom(cx, fc, atom_, atomCache));
1890 if (!atom) {
1891 return nullptr;
1892 }
1893 return RegExpObject::createSyntaxChecked(cx, atom, flags(), TenuredObject);
1894 }
1895
1896 AbstractScopePtr ScopeStencil::enclosing(
1897 CompilationState& compilationState) const {
1898 if (hasEnclosing()) {
1899 return AbstractScopePtr(compilationState, enclosing());
1900 }
1901
1902 return AbstractScopePtr::compilationEnclosingScope(compilationState);
1903 }
1904
1905 Scope* ScopeStencil::enclosingExistingScope(
1906 const CompilationInput& input, const CompilationGCOutput& gcOutput) const {
1907 if (hasEnclosing()) {
1908 Scope* result = gcOutput.getScopeNoBaseIndex(enclosing());
1909 MOZ_ASSERT(result, "Scope must already exist to use this method");
1910 return result;
1911 }
1912
1913 // When creating a scope based on the input and a gc-output, we assume that
1914 // the scope stencil that we are looking at has not been merged into another
1915 // stencil, and thus that we still have the compilation input of the stencil.
1916 //
1917 // Otherwise, if this was in the case of an input generated from a Stencil
1918 // instead of live-gc values, we would not know its associated gcOutput as it
1919 // might not even have one yet.
1920 return input.enclosingScope.variant().as<Scope*>();
1921 }
1922
1923 Scope* ScopeStencil::createScope(JSContext* cx, CompilationInput& input,
1924 CompilationGCOutput& gcOutput,
1925 BaseParserScopeData* baseScopeData) const {
1926 Rooted<Scope*> enclosingScope(cx, enclosingExistingScope(input, gcOutput));
1927 return createScope(cx, input.atomCache, enclosingScope, baseScopeData);
1928 }
1929
1930 Scope* ScopeStencil::createScope(JSContext* cx, CompilationAtomCache& atomCache,
1931 Handle<Scope*> enclosingScope,
1932 BaseParserScopeData* baseScopeData) const {
1933 switch (kind()) {
1934 case ScopeKind::Function: {
1935 using ScopeType = FunctionScope;
1936 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1937 return createSpecificScope<ScopeType, CallObject>(
1938 cx, atomCache, enclosingScope, baseScopeData);
1939 }
1940 case ScopeKind::Lexical:
1941 case ScopeKind::SimpleCatch:
1942 case ScopeKind::Catch:
1943 case ScopeKind::NamedLambda:
1944 case ScopeKind::StrictNamedLambda:
1945 case ScopeKind::FunctionLexical: {
1946 using ScopeType = LexicalScope;
1947 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1948 return createSpecificScope<ScopeType, BlockLexicalEnvironmentObject>(
1949 cx, atomCache, enclosingScope, baseScopeData);
1950 }
1951 case ScopeKind::ClassBody: {
1952 using ScopeType = ClassBodyScope;
1953 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1954 return createSpecificScope<ScopeType, BlockLexicalEnvironmentObject>(
1955 cx, atomCache, enclosingScope, baseScopeData);
1956 }
1957 case ScopeKind::FunctionBodyVar: {
1958 using ScopeType = VarScope;
1959 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1960 return createSpecificScope<ScopeType, VarEnvironmentObject>(
1961 cx, atomCache, enclosingScope, baseScopeData);
1962 }
1963 case ScopeKind::Global:
1964 case ScopeKind::NonSyntactic: {
1965 using ScopeType = GlobalScope;
1966 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1967 return createSpecificScope<ScopeType, std::nullptr_t>(
1968 cx, atomCache, enclosingScope, baseScopeData);
1969 }
1970 case ScopeKind::Eval:
1971 case ScopeKind::StrictEval: {
1972 using ScopeType = EvalScope;
1973 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1974 return createSpecificScope<ScopeType, VarEnvironmentObject>(
1975 cx, atomCache, enclosingScope, baseScopeData);
1976 }
1977 case ScopeKind::Module: {
1978 using ScopeType = ModuleScope;
1979 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1980 return createSpecificScope<ScopeType, ModuleEnvironmentObject>(
1981 cx, atomCache, enclosingScope, baseScopeData);
1982 }
1983 case ScopeKind::With: {
1984 using ScopeType = WithScope;
1985 MOZ_ASSERT(matchScopeKind<ScopeType>(kind()));
1986 return createSpecificScope<ScopeType, std::nullptr_t>(
1987 cx, atomCache, enclosingScope, baseScopeData);
1988 }
1989 case ScopeKind::WasmFunction:
1990 case ScopeKind::WasmInstance: {
1991 // ScopeStencil does not support WASM
1992 break;
1993 }
1994 }
1995 MOZ_CRASH();
1996 }
1997
1998 bool CompilationState::prepareSharedDataStorage(FrontendContext* fc) {
1999 size_t allScriptCount = scriptData.length();
2000 size_t nonLazyScriptCount = nonLazyFunctionCount;
2001 if (!scriptData[0].isFunction()) {
2002 nonLazyScriptCount++;
2003 }
2004 return sharedData.prepareStorageFor(fc, nonLazyScriptCount, allScriptCount);
2005 }
2006
2007 static bool CreateLazyScript(JSContext* cx,
2008 const CompilationAtomCache& atomCache,
2009 const CompilationStencil& stencil,
2010 CompilationGCOutput& gcOutput,
2011 const ScriptStencil& script,
2012 const ScriptStencilExtra& scriptExtra,
2013 ScriptIndex scriptIndex, HandleFunction function) {
2014 Rooted<ScriptSourceObject*> sourceObject(cx, gcOutput.sourceObject);
2015
2016 size_t ngcthings = script.gcThingsLength;
2017
2018 Rooted<BaseScript*> lazy(
2019 cx, BaseScript::CreateRawLazy(cx, ngcthings, function, sourceObject,
2020 scriptExtra.extent,
2021 scriptExtra.immutableFlags));
2022 if (!lazy) {
2023 return false;
2024 }
2025
2026 if (ngcthings) {
2027 if (!EmitScriptThingsVector(cx, atomCache, stencil, gcOutput,
2028 script.gcthings(stencil),
2029 lazy->gcthingsForInit())) {
2030 return false;
2031 }
2032 }
2033
2034 if (scriptExtra.useMemberInitializers()) {
2035 lazy->setMemberInitializers(scriptExtra.memberInitializers());
2036 }
2037
2038 function->initScript(lazy);
2039
2040 return true;
2041 }
2042
2043 // Parser-generated functions with the same prototype will share the same shape.
2044 // By computing the correct values up front, we can save a lot of time in the
2045 // Object creation code. For simplicity, we focus only on plain synchronous
2046 // functions which are by far the most common.
2047 //
2048 // NOTE: Keep this in sync with `js::NewFunctionWithProto`.
2049 static JSFunction* CreateFunctionFast(JSContext* cx,
2050 CompilationAtomCache& atomCache,
2051 Handle<SharedShape*> shape,
2052 const ScriptStencil& script,
2053 const ScriptStencilExtra& scriptExtra) {
2054 MOZ_ASSERT(
2055 !scriptExtra.immutableFlags.hasFlag(ImmutableScriptFlagsEnum::IsAsync));
2056 MOZ_ASSERT(!scriptExtra.immutableFlags.hasFlag(
2057 ImmutableScriptFlagsEnum::IsGenerator));
2058 MOZ_ASSERT(!script.functionFlags.isAsmJSNative());
2059
2060 FunctionFlags flags = script.functionFlags;
2061 gc::AllocKind allocKind = flags.isExtended()
2062 ? gc::AllocKind::FUNCTION_EXTENDED
2063 : gc::AllocKind::FUNCTION;
2064
2065 JSFunction* fun = JSFunction::create(cx, allocKind, gc::Heap::Tenured, shape);
2066 if (!fun) {
2067 return nullptr;
2068 }
2069
2070 fun->setArgCount(scriptExtra.nargs);
2071 fun->setFlags(flags);
2072
2073 fun->initScript(nullptr);
2074 fun->initEnvironment(nullptr);
2075
2076 if (script.functionAtom) {
2077 JSAtom* atom = atomCache.getExistingAtomAt(cx, script.functionAtom);
2078 MOZ_ASSERT(atom);
2079 fun->initAtom(atom);
2080 }
2081
2082 #ifdef DEBUG
2083 fun->assertFunctionKindIntegrity();
2084 #endif
2085
2086 return fun;
2087 }
2088
2089 static JSFunction* CreateFunction(JSContext* cx,
2090 CompilationAtomCache& atomCache,
2091 const CompilationStencil& stencil,
2092 const ScriptStencil& script,
2093 const ScriptStencilExtra& scriptExtra,
2094 ScriptIndex functionIndex) {
2095 GeneratorKind generatorKind =
2096 scriptExtra.immutableFlags.hasFlag(ImmutableScriptFlagsEnum::IsGenerator)
2097 ? GeneratorKind::Generator
2098 : GeneratorKind::NotGenerator;
2099 FunctionAsyncKind asyncKind =
2100 scriptExtra.immutableFlags.hasFlag(ImmutableScriptFlagsEnum::IsAsync)
2101 ? FunctionAsyncKind::AsyncFunction
2102 : FunctionAsyncKind::SyncFunction;
2103
2104 // Determine the new function's proto. This must be done for singleton
2105 // functions.
2106 RootedObject proto(cx);
2107 if (!GetFunctionPrototype(cx, generatorKind, asyncKind, &proto)) {
2108 return nullptr;
2109 }
2110
2111 gc::AllocKind allocKind = script.functionFlags.isExtended()
2112 ? gc::AllocKind::FUNCTION_EXTENDED
2113 : gc::AllocKind::FUNCTION;
2114 bool isAsmJS = script.functionFlags.isAsmJSNative();
2115
2116 JSNative maybeNative = isAsmJS ? InstantiateAsmJS : nullptr;
2117
2118 Rooted<JSAtom*> displayAtom(cx);
2119 if (script.functionAtom) {
2120 displayAtom.set(atomCache.getExistingAtomAt(cx, script.functionAtom));
2121 MOZ_ASSERT(displayAtom);
2122 }
2123 RootedFunction fun(
2124 cx, NewFunctionWithProto(cx, maybeNative, scriptExtra.nargs,
2125 script.functionFlags, nullptr, displayAtom,
2126 proto, allocKind, TenuredObject));
2127 if (!fun) {
2128 return nullptr;
2129 }
2130
2131 if (isAsmJS) {
2132 RefPtr<const JS::WasmModule> asmJS =
2133 stencil.asmJS->moduleMap.lookup(functionIndex)->value();
2134
2135 JSObject* moduleObj = asmJS->createObjectForAsmJS(cx);
2136 if (!moduleObj) {
2137 return nullptr;
2138 }
2139
2140 fun->setExtendedSlot(FunctionExtended::ASMJS_MODULE_SLOT,
2141 ObjectValue(*moduleObj));
2142 }
2143
2144 return fun;
2145 }
2146
2147 static bool InstantiateAtoms(JSContext* cx, FrontendContext* fc,
2148 CompilationAtomCache& atomCache,
2149 const CompilationStencil& stencil) {
2150 return InstantiateMarkedAtoms(cx, fc, stencil.parserAtomData, atomCache);
2151 }
2152
2153 static bool InstantiateScriptSourceObject(JSContext* cx,
2154 const JS::InstantiateOptions& options,
2155 const CompilationStencil& stencil,
2156 CompilationGCOutput& gcOutput) {
2157 MOZ_ASSERT(stencil.source);
2158
2159 gcOutput.sourceObject = ScriptSourceObject::create(cx, stencil.source.get());
2160 if (!gcOutput.sourceObject) {
2161 return false;
2162 }
2163
2164 Rooted<ScriptSourceObject*> sourceObject(cx, gcOutput.sourceObject);
2165 if (!ScriptSourceObject::initFromOptions(cx, sourceObject, options)) {
2166 return false;
2167 }
2168
2169 return true;
2170 }
2171
2172 // Instantiate ModuleObject. Further initialization is done after the associated
2173 // BaseScript is instantiated in InstantiateTopLevel.
2174 static bool InstantiateModuleObject(JSContext* cx, FrontendContext* fc,
2175 CompilationAtomCache& atomCache,
2176 const CompilationStencil& stencil,
2177 CompilationGCOutput& gcOutput) {
2178 MOZ_ASSERT(stencil.isModule());
2179
2180 gcOutput.module = ModuleObject::create(cx);
2181 if (!gcOutput.module) {
2182 return false;
2183 }
2184
2185 Rooted<ModuleObject*> module(cx, gcOutput.module);
2186 return stencil.moduleMetadata->initModule(cx, fc, atomCache, module);
2187 }
2188
2189 // Instantiate JSFunctions for each FunctionBox.
2190 static bool InstantiateFunctions(JSContext* cx, FrontendContext* fc,
2191 CompilationAtomCache& atomCache,
2192 const CompilationStencil& stencil,
2193 CompilationGCOutput& gcOutput) {
2194 using ImmutableFlags = ImmutableScriptFlagsEnum;
2195
2196 MOZ_ASSERT(gcOutput.functions.length() == stencil.scriptData.size());
2197
2198 // Most JSFunctions will be have the same Shape so we can compute it now to
2199 // allow fast object creation. Generators / Async will use the slow path
2200 // instead.
2201 Rooted<SharedShape*> functionShape(
2202 cx, GlobalObject::getFunctionShapeWithDefaultProto(
2203 cx, /* extended = */ false));
2204 if (!functionShape) {
2205 return false;
2206 }
2207
2208 Rooted<SharedShape*> extendedShape(
2209 cx, GlobalObject::getFunctionShapeWithDefaultProto(
2210 cx, /* extended = */ true));
2211 if (!extendedShape) {
2212 return false;
2213 }
2214
2215 for (auto item :
2216 CompilationStencil::functionScriptStencils(stencil, gcOutput)) {
2217 const auto& scriptStencil = item.script;
2218 const auto& scriptExtra = (*item.scriptExtra);
2219 auto index = item.index;
2220
2221 MOZ_ASSERT(!item.function);
2222
2223 // Plain functions can use a fast path.
2224 bool useFastPath =
2225 !scriptExtra.immutableFlags.hasFlag(ImmutableFlags::IsAsync) &&
2226 !scriptExtra.immutableFlags.hasFlag(ImmutableFlags::IsGenerator) &&
2227 !scriptStencil.functionFlags.isAsmJSNative();
2228
2229 JSFunction* fun;
2230 if (useFastPath) {
2231 Handle<SharedShape*> shape = scriptStencil.functionFlags.isExtended()
2232 ? extendedShape
2233 : functionShape;
2234 fun =
2235 CreateFunctionFast(cx, atomCache, shape, scriptStencil, scriptExtra);
2236 } else {
2237 fun = CreateFunction(cx, atomCache, stencil, scriptStencil, scriptExtra,
2238 index);
2239 }
2240
2241 if (!fun) {
2242 return false;
2243 }
2244
2245 // Self-hosted functions may have a canonical name to use when instantiating
2246 // into other realms.
2247 if (scriptStencil.hasSelfHostedCanonicalName()) {
2248 JSAtom* canonicalName = atomCache.getExistingAtomAt(
2249 cx, scriptStencil.selfHostedCanonicalName());
2250 fun->setAtom(canonicalName);
2251 }
2252
2253 gcOutput.getFunctionNoBaseIndex(index) = fun;
2254 }
2255
2256 return true;
2257 }
2258
2259 // Instantiate Scope for each ScopeStencil.
2260 //
2261 // This should be called after InstantiateFunctions, given FunctionScope needs
2262 // associated JSFunction pointer, and also should be called before
2263 // InstantiateScriptStencils, given JSScript needs Scope pointer in gc things.
2264 static bool InstantiateScopes(JSContext* cx, CompilationInput& input,
2265 const CompilationStencil& stencil,
2266 CompilationGCOutput& gcOutput) {
2267 // While allocating Scope object from ScopeStencil, Scope object for the
2268 // enclosing Scope should already be allocated.
2269 //
2270 // Enclosing scope of ScopeStencil can be either ScopeStencil or Scope*
2271 // pointer.
2272 //
2273 // If the enclosing scope is ScopeStencil, it's guaranteed to be earlier
2274 // element in stencil.scopeData, because enclosing_ field holds
2275 // index into it, and newly created ScopeStencil is pushed back to the array.
2276 //
2277 // If the enclosing scope is Scope*, it's CompilationInput.enclosingScope.
2278
2279 MOZ_ASSERT(stencil.scopeData.size() == stencil.scopeNames.size());
2280 size_t scopeCount = stencil.scopeData.size();
2281 for (size_t i = 0; i < scopeCount; i++) {
2282 Scope* scope = stencil.scopeData[i].createScope(cx, input, gcOutput,
2283 stencil.scopeNames[i]);
2284 if (!scope) {
2285 return false;
2286 }
2287 gcOutput.scopes[i] = scope;
2288 }
2289
2290 return true;
2291 }
2292
2293 // Instantiate js::BaseScripts from ScriptStencils for inner functions of the
2294 // compilation. Note that standalone functions and functions being delazified
2295 // are handled below with other top-levels.
2296 static bool InstantiateScriptStencils(JSContext* cx,
2297 CompilationAtomCache& atomCache,
2298 const CompilationStencil& stencil,
2299 CompilationGCOutput& gcOutput) {
2300 MOZ_ASSERT(stencil.isInitialStencil());
2301
2302 Rooted<JSFunction*> fun(cx);
2303 for (auto item :
2304 CompilationStencil::functionScriptStencils(stencil, gcOutput)) {
2305 auto& scriptStencil = item.script;
2306 auto* scriptExtra = item.scriptExtra;
2307 fun = item.function;
2308 auto index = item.index;
2309 if (scriptStencil.hasSharedData()) {
2310 // If the function was not referenced by enclosing script's bytecode, we
2311 // do not generate a BaseScript for it. For example, `(function(){});`.
2312 //
2313 // `wasEmittedByEnclosingScript` is false also for standalone
2314 // functions. They are handled in InstantiateTopLevel.
2315 if (!scriptStencil.wasEmittedByEnclosingScript()) {
2316 continue;
2317 }
2318
2319 RootedScript script(
2320 cx, JSScript::fromStencil(cx, atomCache, stencil, gcOutput, index));
2321 if (!script) {
2322 return false;
2323 }
2324
2325 if (scriptStencil.allowRelazify()) {
2326 MOZ_ASSERT(script->isRelazifiable());
2327 script->setAllowRelazify();
2328 }
2329 } else if (scriptStencil.functionFlags.isAsmJSNative()) {
2330 MOZ_ASSERT(fun->isAsmJSNative());
2331 } else {
2332 MOZ_ASSERT(fun->isIncomplete());
2333 if (!CreateLazyScript(cx, atomCache, stencil, gcOutput, scriptStencil,
2334 *scriptExtra, index, fun)) {
2335 return false;
2336 }
2337 }
2338 }
2339
2340 return true;
2341 }
2342
2343 // Instantiate the Stencil for the top-level script of the compilation. This
2344 // includes standalone functions and functions being delazified.
2345 static bool InstantiateTopLevel(JSContext* cx, CompilationInput& input,
2346 const CompilationStencil& stencil,
2347 CompilationGCOutput& gcOutput) {
2348 const ScriptStencil& scriptStencil =
2349 stencil.scriptData[CompilationStencil::TopLevelIndex];
2350
2351 // Top-level asm.js does not generate a JSScript.
2352 if (scriptStencil.functionFlags.isAsmJSNative()) {
2353 return true;
2354 }
2355
2356 MOZ_ASSERT(scriptStencil.hasSharedData());
2357 MOZ_ASSERT(stencil.sharedData.get(CompilationStencil::TopLevelIndex));
2358
2359 if (!stencil.isInitialStencil()) {
2360 MOZ_ASSERT(input.lazyOuterBaseScript());
2361 RootedScript script(cx,
2362 JSScript::CastFromLazy(input.lazyOuterBaseScript()));
2363 if (!JSScript::fullyInitFromStencil(cx, input.atomCache, stencil, gcOutput,
2364 script,
2365 CompilationStencil::TopLevelIndex)) {
2366 return false;
2367 }
2368
2369 if (scriptStencil.allowRelazify()) {
2370 MOZ_ASSERT(script->isRelazifiable());
2371 script->setAllowRelazify();
2372 }
2373
2374 gcOutput.script = script;
2375 return true;
2376 }
2377
2378 gcOutput.script =
2379 JSScript::fromStencil(cx, input.atomCache, stencil, gcOutput,
2380 CompilationStencil::TopLevelIndex);
2381 if (!gcOutput.script) {
2382 return false;
2383 }
2384
2385 if (scriptStencil.allowRelazify()) {
2386 MOZ_ASSERT(gcOutput.script->isRelazifiable());
2387 gcOutput.script->setAllowRelazify();
2388 }
2389
2390 const ScriptStencilExtra& scriptExtra =
2391 stencil.scriptExtra[CompilationStencil::TopLevelIndex];
2392
2393 // Finish initializing the ModuleObject if needed.
2394 if (scriptExtra.isModule()) {
2395 RootedScript script(cx, gcOutput.script);
2396 Rooted<ModuleObject*> module(cx, gcOutput.module);
2397
2398 script->outermostScope()->as<ModuleScope>().initModule(module);
2399
2400 module->initScriptSlots(script);
2401
2402 if (!ModuleObject::createEnvironment(cx, module)) {
2403 return false;
2404 }
2405
2406 if (!ModuleObject::Freeze(cx, module)) {
2407 return false;
2408 }
2409 }
2410
2411 return true;
2412 }
2413
2414 // When a function is first referenced by enclosing script's bytecode, we need
2415 // to update it with information determined by the BytecodeEmitter. This applies
2416 // to both initial and delazification parses. The functions being update may or
2417 // may not have bytecode at this point.
2418 static void UpdateEmittedInnerFunctions(JSContext* cx,
2419 CompilationAtomCache& atomCache,
2420 const CompilationStencil& stencil,
2421 CompilationGCOutput& gcOutput) {
2422 for (auto item :
2423 CompilationStencil::functionScriptStencils(stencil, gcOutput)) {
2424 auto& scriptStencil = item.script;
2425 auto& fun = item.function;
2426 if (!scriptStencil.wasEmittedByEnclosingScript()) {
2427 continue;
2428 }
2429
2430 if (scriptStencil.functionFlags.isAsmJSNative() ||
2431 fun->baseScript()->hasBytecode()) {
2432 // Non-lazy inner functions don't use the enclosingScope_ field.
2433 MOZ_ASSERT(!scriptStencil.hasLazyFunctionEnclosingScopeIndex());
2434 } else {
2435 // Apply updates from FunctionEmitter::emitLazy().
2436 BaseScript* script = fun->baseScript();
2437
2438 ScopeIndex index = scriptStencil.lazyFunctionEnclosingScopeIndex();
2439 Scope* scope = gcOutput.getScopeNoBaseIndex(index);
2440 script->setEnclosingScope(scope);
2441
2442 // Inferred and Guessed names are computed by BytecodeEmitter and so may
2443 // need to be applied to existing JSFunctions during delazification.
2444 if (fun->fullDisplayAtom() == nullptr) {
2445 JSAtom* funcAtom = nullptr;
2446 if (scriptStencil.functionFlags.hasInferredName() ||
2447 scriptStencil.functionFlags.hasGuessedAtom()) {
2448 funcAtom =
2449 atomCache.getExistingAtomAt(cx, scriptStencil.functionAtom);
2450 MOZ_ASSERT(funcAtom);
2451 }
2452 if (scriptStencil.functionFlags.hasInferredName()) {
2453 fun->setInferredName(funcAtom);
2454 }
2455 if (scriptStencil.functionFlags.hasGuessedAtom()) {
2456 fun->setGuessedAtom(funcAtom);
2457 }
2458 }
2459 }
2460 }
2461 }
2462
2463 // During initial parse we must link lazy-functions-inside-lazy-functions to
2464 // their enclosing script.
2465 static void LinkEnclosingLazyScript(const CompilationStencil& stencil,
2466 CompilationGCOutput& gcOutput) {
2467 for (auto item :
2468 CompilationStencil::functionScriptStencils(stencil, gcOutput)) {
2469 auto& scriptStencil = item.script;
2470 auto& fun = item.function;
2471 if (!scriptStencil.functionFlags.hasBaseScript()) {
2472 continue;
2473 }
2474
2475 if (!fun->baseScript()) {
2476 continue;
2477 }
2478
2479 if (fun->baseScript()->hasBytecode()) {
2480 continue;
2481 }
2482
2483 BaseScript* script = fun->baseScript();
2484 MOZ_ASSERT(!script->hasBytecode());
2485
2486 for (auto inner : script->gcthings()) {
2487 if (!inner.is<JSObject>()) {
2488 continue;
2489 }
2490 JSFunction* innerFun = &inner.as<JSObject>().as<JSFunction>();
2491
2492 MOZ_ASSERT(innerFun->hasBaseScript(),
2493 "inner function should have base script");
2494 if (!innerFun->hasBaseScript()) {
2495 continue;
2496 }
2497
2498 // Check for the case that the inner function has the base script flag,
2499 // but still doesn't have the actual base script pointer.
2500 // `baseScript` method asserts the pointer itself, so no extra MOZ_ASSERT
2501 // here.
2502 if (!innerFun->baseScript()) {
2503 continue;
2504 }
2505
2506 innerFun->setEnclosingLazyScript(script);
2507 }
2508 }
2509 }
2510
2511 #ifdef DEBUG
2512 // Some fields aren't used in delazification, given the target functions and
2513 // scripts are already instantiated, but they still should match.
2514 static void AssertDelazificationFieldsMatch(const CompilationStencil& stencil,
2515 CompilationGCOutput& gcOutput) {
2516 for (auto item :
2517 CompilationStencil::functionScriptStencils(stencil, gcOutput)) {
2518 auto& scriptStencil = item.script;
2519 auto* scriptExtra = item.scriptExtra;
2520 auto& fun = item.function;
2521
2522 MOZ_ASSERT(scriptExtra == nullptr);
2523
2524 // Names are updated by UpdateInnerFunctions.
2525 constexpr uint16_t HAS_INFERRED_NAME =
2526 uint16_t(FunctionFlags::Flags::HAS_INFERRED_NAME);
2527 constexpr uint16_t HAS_GUESSED_ATOM =
2528 uint16_t(FunctionFlags::Flags::HAS_GUESSED_ATOM);
2529 constexpr uint16_t MUTABLE_FLAGS =
2530 uint16_t(FunctionFlags::Flags::MUTABLE_FLAGS);
2531 constexpr uint16_t acceptableDifferenceForFunction =
2532 HAS_INFERRED_NAME | HAS_GUESSED_ATOM | MUTABLE_FLAGS;
2533
2534 MOZ_ASSERT((fun->flags().toRaw() | acceptableDifferenceForFunction) ==
2535 (scriptStencil.functionFlags.toRaw() |
2536 acceptableDifferenceForFunction));
2537
2538 // Delazification shouldn't delazify inner scripts.
2539 MOZ_ASSERT_IF(item.index == CompilationStencil::TopLevelIndex,
2540 scriptStencil.hasSharedData());
2541 MOZ_ASSERT_IF(item.index > CompilationStencil::TopLevelIndex,
2542 !scriptStencil.hasSharedData());
2543 }
2544 }
2545 #endif // DEBUG
2546
2547 // When delazifying, use the existing JSFunctions. The initial and delazifying
2548 // parse are required to generate the same sequence of functions for lazy
2549 // parsing to work at all.
2550 static void FunctionsFromExistingLazy(CompilationInput& input,
2551 CompilationGCOutput& gcOutput) {
2552 MOZ_ASSERT(!gcOutput.functions[0]);
2553
2554 size_t instantiatedFunIndex = 0;
2555 gcOutput.functions[instantiatedFunIndex++] = input.function();
2556
2557 for (JS::GCCellPtr elem : input.lazyOuterBaseScript()->gcthings()) {
2558 if (!elem.is<JSObject>()) {
2559 continue;
2560 }
2561 JSFunction* fun = &elem.as<JSObject>().as<JSFunction>();
2562 gcOutput.functions[instantiatedFunIndex++] = fun;
2563 }
2564 }
2565
2566 void CompilationStencil::borrowFromExtensibleCompilationStencil(
2567 ExtensibleCompilationStencil& extensibleStencil) {
2568 canLazilyParse = extensibleStencil.canLazilyParse;
2569 functionKey = extensibleStencil.functionKey;
2570
2571 // Borrow the vector content as span.
2572 scriptData = extensibleStencil.scriptData;
2573 scriptExtra = extensibleStencil.scriptExtra;
2574
2575 gcThingData = extensibleStencil.gcThingData;
2576
2577 scopeData = extensibleStencil.scopeData;
2578 scopeNames = extensibleStencil.scopeNames;
2579
2580 regExpData = extensibleStencil.regExpData;
2581 bigIntData = extensibleStencil.bigIntData;
2582 objLiteralData = extensibleStencil.objLiteralData;
2583
2584 // Borrow the parser atoms as span.
2585 parserAtomData = extensibleStencil.parserAtoms.entries_;
2586
2587 // Borrow container.
2588 sharedData.setBorrow(&extensibleStencil.sharedData);
2589
2590 // Share ref-counted data.
2591 source = extensibleStencil.source;
2592 asmJS = extensibleStencil.asmJS;
2593 moduleMetadata = extensibleStencil.moduleMetadata;
2594 }
2595
2596 #ifdef DEBUG
2597 void CompilationStencil::assertBorrowingFromExtensibleCompilationStencil(
2598 const ExtensibleCompilationStencil& extensibleStencil) const {
2599 MOZ_ASSERT(canLazilyParse == extensibleStencil.canLazilyParse);
2600 MOZ_ASSERT(functionKey == extensibleStencil.functionKey);
2601
2602 AssertBorrowingSpan(scriptData, extensibleStencil.scriptData);
2603 AssertBorrowingSpan(scriptExtra, extensibleStencil.scriptExtra);
2604
2605 AssertBorrowingSpan(gcThingData, extensibleStencil.gcThingData);
2606
2607 AssertBorrowingSpan(scopeData, extensibleStencil.scopeData);
2608 AssertBorrowingSpan(scopeNames, extensibleStencil.scopeNames);
2609
2610 AssertBorrowingSpan(regExpData, extensibleStencil.regExpData);
2611 AssertBorrowingSpan(bigIntData, extensibleStencil.bigIntData);
2612 AssertBorrowingSpan(objLiteralData, extensibleStencil.objLiteralData);
2613
2614 AssertBorrowingSpan(parserAtomData, extensibleStencil.parserAtoms.entries_);
2615
2616 MOZ_ASSERT(sharedData.isBorrow());
2617 MOZ_ASSERT(sharedData.asBorrow() == &extensibleStencil.sharedData);
2618
2619 MOZ_ASSERT(source == extensibleStencil.source);
2620 MOZ_ASSERT(asmJS == extensibleStencil.asmJS);
2621 MOZ_ASSERT(moduleMetadata == extensibleStencil.moduleMetadata);
2622 }
2623 #endif
2624
2625 CompilationStencil::CompilationStencil(
2626 UniquePtr<ExtensibleCompilationStencil>&& extensibleStencil)
2627 : alloc(LifoAllocChunkSize, js::BackgroundMallocArena) {
2628 ownedBorrowStencil = std::move(extensibleStencil);
2629
2630 storageType = StorageType::OwnedExtensible;
2631
2632 borrowFromExtensibleCompilationStencil(*ownedBorrowStencil);
2633
2634 #ifdef DEBUG
2635 assertNoExternalDependency();
2636 #endif
2637 }
2638
2639 /* static */
2640 bool CompilationStencil::instantiateStencils(JSContext* cx,
2641 CompilationInput& input,
2642 const CompilationStencil& stencil,
2643 CompilationGCOutput& gcOutput) {
2644 AutoReportFrontendContext fc(cx);
2645 if (!prepareForInstantiate(&fc, input.atomCache, stencil, gcOutput)) {
2646 return false;
2647 }
2648
2649 return instantiateStencilAfterPreparation(cx, input, stencil, gcOutput);
2650 }
2651
2652 /* static */
2653 bool CompilationStencil::instantiateStencilAfterPreparation(
2654 JSContext* cx, CompilationInput& input, const CompilationStencil& stencil,
2655 CompilationGCOutput& gcOutput) {
2656 // Distinguish between the initial (possibly lazy) compile and any subsequent
2657 // delazification compiles. Delazification will update existing GC things.
2658 bool isInitialParse = stencil.isInitialStencil();
2659 MOZ_ASSERT(stencil.isInitialStencil() == input.isInitialStencil());
2660
2661 // Assert the consistency between the compile option and the target global.
2662 MOZ_ASSERT_IF(cx->realm()->behaviors().discardSource(),
2663 !stencil.canLazilyParse);
2664
2665 CompilationAtomCache& atomCache = input.atomCache;
2666 const JS::InstantiateOptions options(input.options);
2667
2668 // Phase 1: Instantiate JSAtom/JSStrings.
2669 AutoReportFrontendContext fc(cx);
2670 if (!InstantiateAtoms(cx, &fc, atomCache, stencil)) {
2671 return false;
2672 }
2673
2674 // Phase 2: Instantiate ScriptSourceObject, ModuleObject, JSFunctions.
2675 if (isInitialParse) {
2676 if (!InstantiateScriptSourceObject(cx, options, stencil, gcOutput)) {
2677 return false;
2678 }
2679
2680 if (stencil.moduleMetadata) {
2681 // The enclosing script of a module is always the global scope. Fetch the
2682 // scope of the current global and update input data.
2683 MOZ_ASSERT(input.enclosingScope.isNull());
2684 input.enclosingScope = InputScope(&cx->global()->emptyGlobalScope());
2685 MOZ_ASSERT(input.enclosingScope.environmentChainLength() ==
2686 ModuleScope::EnclosingEnvironmentChainLength);
2687
2688 if (!InstantiateModuleObject(cx, &fc, atomCache, stencil, gcOutput)) {
2689 return false;
2690 }
2691 }
2692
2693 if (!InstantiateFunctions(cx, &fc, atomCache, stencil, gcOutput)) {
2694 return false;
2695 }
2696 } else {
2697 MOZ_ASSERT(
2698 stencil.scriptData[CompilationStencil::TopLevelIndex].isFunction());
2699
2700 // FunctionKey is used when caching to map a delazification stencil to a
2701 // specific lazy script. It is not used by instantiation, but we should
2702 // ensure it is correctly defined.
2703 MOZ_ASSERT(stencil.functionKey == input.extent().toFunctionKey());
2704
2705 FunctionsFromExistingLazy(input, gcOutput);
2706 MOZ_ASSERT(gcOutput.functions.length() == stencil.scriptData.size());
2707
2708 #ifdef DEBUG
2709 AssertDelazificationFieldsMatch(stencil, gcOutput);
2710 #endif
2711 }
2712
2713 // Phase 3: Instantiate js::Scopes.
2714 if (!InstantiateScopes(cx, input, stencil, gcOutput)) {
2715 return false;
2716 }
2717
2718 // Phase 4: Instantiate (inner) BaseScripts.
2719 if (isInitialParse) {
2720 if (!InstantiateScriptStencils(cx, atomCache, stencil, gcOutput)) {
2721 return false;
2722 }
2723 }
2724
2725 // Phase 5: Finish top-level handling
2726 if (!InstantiateTopLevel(cx, input, stencil, gcOutput)) {
2727 return false;
2728 }
2729
2730 // !! Must be infallible from here forward !!
2731
2732 // Phase 6: Update lazy scripts.
2733 if (stencil.canLazilyParse) {
2734 UpdateEmittedInnerFunctions(cx, atomCache, stencil, gcOutput);
2735
2736 if (isInitialParse) {
2737 LinkEnclosingLazyScript(stencil, gcOutput);
2738 }
2739 }
2740
2741 return true;
2742 }
2743
2744 // The top-level self-hosted script is created and executed in each realm that
2745 // needs it. While the stencil has a gcthings list for the various top-level
2746 // functions, we use special machinery to create them on demand. So instead we
2747 // use a placeholder JSFunction that should never be called.
2748 static bool SelfHostedDummyFunction(JSContext* cx, unsigned argc,
2749 JS::Value* vp) {
2750 MOZ_CRASH("Self-hosting top-level should not use functions directly");
2751 }
2752
2753 bool CompilationStencil::instantiateSelfHostedAtoms(
2754 JSContext* cx, AtomSet& atomSet, CompilationAtomCache& atomCache) const {
2755 MOZ_ASSERT(isInitialStencil());
2756
2757 // We must instantiate atoms during startup so they can be made permanent
2758 // across multiple runtimes.
2759 AutoReportFrontendContext fc(cx);
2760 return InstantiateMarkedAtomsAsPermanent(cx, &fc, atomSet, parserAtomData,
2761 atomCache);
2762 }
2763
2764 JSScript* CompilationStencil::instantiateSelfHostedTopLevelForRealm(
2765 JSContext* cx, CompilationInput& input) {
2766 MOZ_ASSERT(isInitialStencil());
2767
2768 Rooted<CompilationGCOutput> gcOutput(cx);
2769
2770 gcOutput.get().sourceObject = SelfHostingScriptSourceObject(cx);
2771 if (!gcOutput.get().sourceObject) {
2772 return nullptr;
2773 }
2774
2775 // The top-level script has ScriptIndex references in its gcthings list, but
2776 // we do not want to instantiate those functions here since they are instead
2777 // created on demand from the stencil. Create a dummy function and populate
2778 // the functions array of the CompilationGCOutput with references to it.
2779 RootedFunction dummy(
2780 cx, NewNativeFunction(cx, SelfHostedDummyFunction, 0, nullptr));
2781 if (!dummy) {
2782 return nullptr;
2783 }
2784
2785 if (!gcOutput.get().functions.allocateWith(dummy, scriptData.size())) {
2786 ReportOutOfMemory(cx);
2787 return nullptr;
2788 }
2789
2790 if (!InstantiateTopLevel(cx, input, *this, gcOutput.get())) {
2791 return nullptr;
2792 }
2793
2794 return gcOutput.get().script;
2795 }
2796
2797 JSFunction* CompilationStencil::instantiateSelfHostedLazyFunction(
2798 JSContext* cx, CompilationAtomCache& atomCache, ScriptIndex index,
2799 Handle<JSAtom*> name) {
2800 MOZ_ASSERT(cx->zone()->suppressAllocationMetadataBuilder);
2801
2802 GeneratorKind generatorKind = scriptExtra[index].immutableFlags.hasFlag(
2803 ImmutableScriptFlagsEnum::IsGenerator)
2804 ? GeneratorKind::Generator
2805 : GeneratorKind::NotGenerator;
2806 FunctionAsyncKind asyncKind = scriptExtra[index].immutableFlags.hasFlag(
2807 ImmutableScriptFlagsEnum::IsAsync)
2808 ? FunctionAsyncKind::AsyncFunction
2809 : FunctionAsyncKind::SyncFunction;
2810
2811 Rooted<JSAtom*> funName(cx);
2812 if (scriptData[index].hasSelfHostedCanonicalName()) {
2813 // SetCanonicalName was used to override the name.
2814 funName = atomCache.getExistingAtomAt(
2815 cx, scriptData[index].selfHostedCanonicalName());
2816 } else if (name) {
2817 // Our caller has a name it wants to use.
2818 funName = name;
2819 } else {
2820 MOZ_ASSERT(scriptData[index].functionAtom);
2821 funName = atomCache.getExistingAtomAt(cx, scriptData[index].functionAtom);
2822 }
2823
2824 RootedObject proto(cx);
2825 if (!GetFunctionPrototype(cx, generatorKind, asyncKind, &proto)) {
2826 return nullptr;
2827 }
2828
2829 RootedObject env(cx, &cx->global()->lexicalEnvironment());
2830
2831 RootedFunction fun(
2832 cx,
2833 NewFunctionWithProto(cx, nullptr, scriptExtra[index].nargs,
2834 scriptData[index].functionFlags, env, funName, proto,
2835 gc::AllocKind::FUNCTION_EXTENDED, TenuredObject));
2836 if (!fun) {
2837 return nullptr;
2838 }
2839
2840 fun->initSelfHostedLazyScript(&cx->runtime()->selfHostedLazyScript.ref());
2841
2842 JSAtom* selfHostedName =
2843 atomCache.getExistingAtomAt(cx, scriptData[index].functionAtom);
2844 SetClonedSelfHostedFunctionName(fun, selfHostedName->asPropertyName());
2845
2846 return fun;
2847 }
2848
2849 bool CompilationStencil::delazifySelfHostedFunction(
2850 JSContext* cx, CompilationAtomCache& atomCache, ScriptIndexRange range,
2851 Handle<JSAtom*> name, HandleFunction fun) {
2852 // Determine the equivalent ScopeIndex range by looking at the outermost scope
2853 // of the scripts defining the range. Take special care if this is the last
2854 // script in the list.
2855 auto getOutermostScope = [this](ScriptIndex scriptIndex) -> ScopeIndex {
2856 MOZ_ASSERT(scriptData[scriptIndex].hasSharedData());
2857 auto gcthings = scriptData[scriptIndex].gcthings(*this);
2858 return gcthings[GCThingIndex::outermostScopeIndex()].toScope();
2859 };
2860 ScopeIndex scopeIndex = getOutermostScope(range.start);
2861 ScopeIndex scopeLimit = (range.limit < scriptData.size())
2862 ? getOutermostScope(range.limit)
2863 : ScopeIndex(scopeData.size());
2864 Rooted<JSAtom*> jitCacheKey(cx, name);
2865
2866 // Prepare to instantiate by allocating the output arrays. We also set a base
2867 // index to avoid allocations in most cases.
2868 AutoReportFrontendContext fc(cx);
2869 Rooted<CompilationGCOutput> gcOutput(cx);
2870 if (!gcOutput.get().ensureAllocatedWithBaseIndex(
2871 &fc, range.start, range.limit, scopeIndex, scopeLimit)) {
2872 return false;
2873 }
2874
2875 // Phase 1: Instantiate JSAtoms.
2876 // NOTE: The self-hosted atoms are all "permanent" and the
2877 // CompilationAtomCache is already stored on the JSRuntime.
2878
2879 // Phase 2: Instantiate ScriptSourceObject, ModuleObject, JSFunctions.
2880
2881 // Get the corresponding ScriptSourceObject to use in current realm.
2882 gcOutput.get().sourceObject = SelfHostingScriptSourceObject(cx);
2883 if (!gcOutput.get().sourceObject) {
2884 return false;
2885 }
2886
2887 size_t instantiatedFunIndex = 0;
2888
2889 // Delazification target function.
2890 gcOutput.get().functions[instantiatedFunIndex++] = fun;
2891
2892 // Allocate inner functions. Self-hosted functions do not allocate these with
2893 // the initial function.
2894 for (size_t i = range.start + 1; i < range.limit; i++) {
2895 JSFunction* innerFun = CreateFunction(cx, atomCache, *this, scriptData[i],
2896 scriptExtra[i], ScriptIndex(i));
2897 if (!innerFun) {
2898 return false;
2899 }
2900 gcOutput.get().functions[instantiatedFunIndex++] = innerFun;
2901 }
2902
2903 // Phase 3: Instantiate js::Scopes.
2904 // NOTE: When the enclosing scope is not a stencil, directly use the
2905 // `emptyGlobalScope` instead of reading from CompilationInput. This is
2906 // a special case for self-hosted delazification that allows us to reuse
2907 // the CompilationInput between different realms.
2908 size_t instantiatedScopeIndex = 0;
2909 for (size_t i = scopeIndex; i < scopeLimit; i++) {
2910 ScopeStencil& data = scopeData[i];
2911 Rooted<Scope*> enclosingScope(
2912 cx, data.hasEnclosing() ? gcOutput.get().getScope(data.enclosing())
2913 : &cx->global()->emptyGlobalScope());
2914
2915 js::Scope* scope =
2916 data.createScope(cx, atomCache, enclosingScope, scopeNames[i]);
2917 if (!scope) {
2918 return false;
2919 }
2920 gcOutput.get().scopes[instantiatedScopeIndex++] = scope;
2921 }
2922
2923 // Phase 4: Instantiate (inner) BaseScripts.
2924 ScriptIndex innerStart(range.start + 1);
2925 for (size_t i = innerStart; i < range.limit; i++) {
2926 if (!JSScript::fromStencil(cx, atomCache, *this, gcOutput.get(),
2927 ScriptIndex(i))) {
2928 return false;
2929 }
2930 }
2931
2932 // Phase 5: Finish top-level handling
2933 // NOTE: We do not have a `CompilationInput` handy here, so avoid using the
2934 // `InstantiateTopLevel` helper and directly create the JSScript. Our
2935 // caller also handles the `AllowRelazify` flag for us since self-hosted
2936 // delazification is a special case.
2937 Rooted<JSScript*> script(
2938 cx,
2939 JSScript::fromStencil(cx, atomCache, *this, gcOutput.get(), range.start));
2940 if (!script) {
2941 return false;
2942 }
2943
2944 if (JS::Prefs::experimental_self_hosted_cache()) {
2945 // We eagerly baseline-compile self-hosted functions, and cache their
2946 // JitCode for reuse across the runtime. If the cache already contains an
2947 // entry for this function, update the JitScript. If not, compile it now and
2948 // store it in the cache.
2949 UniqueChars nameStr;
2950 if (JS_SHOULD_LOG(selfHosted, Debug)) {
2951 nameStr = AtomToPrintableString(cx, name);
2952 }
2953 auto& jitCache = cx->runtime()->selfHostJitCache.ref();
2954 auto v = jitCache.readonlyThreadsafeLookup(jitCacheKey);
2955 if (v && v->value()->method()) {
2956 JS_LOG(selfHosted, Debug,
2957 "self_hosted_cache: reusing JIT code for script '%s'",
2958 nameStr.get());
2959
2960 if (!cx->zone()->ensureJitZoneExists(cx)) {
2961 return false;
2962 }
2963 jit::AutoKeepJitScripts keepJitScript(cx);
2964 if (!script->ensureHasJitScript(cx, keepJitScript)) {
2965 return false;
2966 }
2967 MOZ_ASSERT(!script->hasBaselineScript());
2968
2969 // JSScript destroys its BaselineScript on finalize, so we need another
2970 // copy here (for now)
2971 jit::BaselineScript* baselineScript =
2972 jit::BaselineScript::Copy(cx, v->value());
2973 if (!baselineScript) {
2974 return false;
2975 }
2976 mozilla::DebugOnly<bool> instrumentationEnabled =
2977 cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
2978 cx->runtime());
2979 MOZ_ASSERT(instrumentationEnabled ==
2980 baselineScript->isProfilerInstrumentationOn());
2981 script->jitScript()->setBaselineScript(script, baselineScript);
2982 } else if (jit::IsBaselineJitEnabled(cx) && script->canBaselineCompile() &&
2983 !script->hasBaselineScript() &&
2984 jit::CanBaselineInterpretScript(script)) {
2985 JS_LOG(selfHosted, Debug,
2986 "self_hosted_cache: new JIT code entry for script '%s'",
2987 nameStr.get());
2988
2989 if (!cx->zone()->ensureJitZoneExists(cx)) {
2990 return false;
2991 }
2992
2993 jit::AutoKeepJitScripts keep(cx);
2994 if (!script->ensureHasJitScript(cx, keep)) {
2995 return false;
2996 }
2997
2998 jit::BaselineOptions options(
2999 {jit::BaselineOption::ForceMainThreadCompilation});
3000 jit::MethodStatus result =
3001 jit::BaselineCompile(cx, script.get(), options);
3002 if (result != jit::Method_Compiled) {
3003 return false;
3004 }
3005 MOZ_ASSERT(script->hasBaselineScript());
3006
3007 jit::BaselineScript* baselineScript =
3008 jit::BaselineScript::Copy(cx, script->baselineScript());
3009 if (!baselineScript) {
3010 return false;
3011 }
3012 if (!jitCache.put(jitCacheKey, baselineScript)) {
3013 return false;
3014 }
3015 } else {
3016 JS_LOG(selfHosted, Debug,
3017 "self_hosted_cache: script '%s' is not eligible for Baseline "
3018 "compilation",
3019 nameStr.get());
3020 }
3021 }
3022
3023 // Phase 6: Update lazy scripts.
3024 // NOTE: Self-hosting is always fully parsed so there is nothing to do here.
3025
3026 return true;
3027 }
3028
3029 /* static */
3030 bool CompilationStencil::prepareForInstantiate(
3031 FrontendContext* fc, CompilationAtomCache& atomCache,
3032 const CompilationStencil& stencil, CompilationGCOutput& gcOutput) {
3033 // Allocate the `gcOutput` arrays.
3034 if (!gcOutput.ensureAllocated(fc, stencil.scriptData.size(),
3035 stencil.scopeData.size())) {
3036 return false;
3037 }
3038
3039 return atomCache.allocate(fc, stencil.parserAtomData.size());
3040 }
3041
3042 /* static */
3043 bool CompilationStencil::prepareForInstantiate(
3044 FrontendContext* fc, const CompilationStencil& stencil,
3045 PreallocatedCompilationGCOutput& gcOutput) {
3046 return gcOutput.allocate(fc, stencil.scriptData.size(),
3047 stencil.scopeData.size());
3048 }
3049
3050 bool JS::PrepareForInstantiate(JS::FrontendContext* fc, JS::Stencil& stencil,
3051 JS::InstantiationStorage& storage) {
3052 if (!storage.gcOutput_) {
3053 storage.gcOutput_ =
3054 fc->getAllocator()
3055 ->new_<js::frontend::PreallocatedCompilationGCOutput>();
3056 if (!storage.gcOutput_) {
3057 return false;
3058 }
3059 }
3060
3061 return CompilationStencil::prepareForInstantiate(fc, *stencil.getInitial(),
3062 *storage.gcOutput_);
3063 }
3064
3065 ExtensibleCompilationStencil::ExtensibleCompilationStencil(ScriptSource* source)
3066 : alloc(CompilationStencil::LifoAllocChunkSize, js::BackgroundMallocArena),
3067 source(source),
3068 parserAtoms(alloc) {}
3069
3070 ExtensibleCompilationStencil::ExtensibleCompilationStencil(
3071 CompilationInput& input)
3072 : canLazilyParse(CanLazilyParse(input.options)),
3073 alloc(CompilationStencil::LifoAllocChunkSize, js::BackgroundMallocArena),
3074 source(input.source),
3075 parserAtoms(alloc) {}
3076
3077 ExtensibleCompilationStencil::ExtensibleCompilationStencil(
3078 const JS::ReadOnlyCompileOptions& options, RefPtr<ScriptSource> source)
3079 : canLazilyParse(CanLazilyParse(options)),
3080 alloc(CompilationStencil::LifoAllocChunkSize, js::BackgroundMallocArena),
3081 source(std::move(source)),
3082 parserAtoms(alloc) {}
3083
3084 CompilationState::CompilationState(FrontendContext* fc,
3085 LifoAllocScope& parserAllocScope,
3086 CompilationInput& input)
3087 : ExtensibleCompilationStencil(input),
3088 directives(input.options.forceStrictMode()),
3089 usedNames(fc),
3090 parserAllocScope(parserAllocScope),
3091 input(input) {}
3092
3093 BorrowingCompilationStencil::BorrowingCompilationStencil(
3094 ExtensibleCompilationStencil& extensibleStencil)
3095 : CompilationStencil(extensibleStencil.source) {
3096 storageType = StorageType::Borrowed;
3097
3098 borrowFromExtensibleCompilationStencil(extensibleStencil);
3099 }
3100
3101 SharedDataContainer::~SharedDataContainer() {
3102 if (isEmpty()) {
3103 // Nothing to do.
3104 } else if (isSingle()) {
3105 asSingle()->Release();
3106 } else if (isVector()) {
3107 js_delete(asVector());
3108 } else if (isMap()) {
3109 js_delete(asMap());
3110 } else {
3111 MOZ_ASSERT(isBorrow());
3112 // Nothing to do.
3113 }
3114 }
3115
3116 bool SharedDataContainer::initVector(FrontendContext* fc) {
3117 MOZ_ASSERT(isEmpty());
3118
3119 auto* vec = js_new<SharedDataVector>();
3120 if (!vec) {
3121 ReportOutOfMemory(fc);
3122 return false;
3123 }
3124 data_ = uintptr_t(vec) | VectorTag;
3125 return true;
3126 }
3127
3128 bool SharedDataContainer::initMap(FrontendContext* fc) {
3129 MOZ_ASSERT(isEmpty());
3130
3131 auto* map = js_new<SharedDataMap>();
3132 if (!map) {
3133 ReportOutOfMemory(fc);
3134 return false;
3135 }
3136 data_ = uintptr_t(map) | MapTag;
3137 return true;
3138 }
3139
3140 bool SharedDataContainer::prepareStorageFor(FrontendContext* fc,
3141 size_t nonLazyScriptCount,
3142 size_t allScriptCount) {
3143 MOZ_ASSERT(isEmpty());
3144
3145 if (nonLazyScriptCount <= 1) {
3146 MOZ_ASSERT(isSingle());
3147 return true;
3148 }
3149
3150 // If the ratio of scripts with bytecode is small, allocating the Vector
3151 // storage with the number of all scripts isn't space-efficient.
3152 // In that case use HashMap instead.
3153 //
3154 // In general, we expect either all scripts to contain bytecode (priviledge
3155 // and self-hosted), or almost none to (eg standard lazy parsing output).
3156 constexpr size_t thresholdRatio = 8;
3157 bool useHashMap = nonLazyScriptCount < allScriptCount / thresholdRatio;
3158 if (useHashMap) {
3159 if (!initMap(fc)) {
3160 return false;
3161 }
3162 if (!asMap()->reserve(nonLazyScriptCount)) {
3163 ReportOutOfMemory(fc);
3164 return false;
3165 }
3166 } else {
3167 if (!initVector(fc)) {
3168 return false;
3169 }
3170 if (!asVector()->resize(allScriptCount)) {
3171 ReportOutOfMemory(fc);
3172 return false;
3173 }
3174 }
3175
3176 return true;
3177 }
3178
3179 bool SharedDataContainer::cloneFrom(FrontendContext* fc,
3180 const SharedDataContainer& other) {
3181 MOZ_ASSERT(isEmpty());
3182
3183 if (other.isBorrow()) {
3184 return cloneFrom(fc, *other.asBorrow());
3185 }
3186
3187 if (other.isSingle()) {
3188 // As we clone, we add an extra reference.
3189 RefPtr<SharedImmutableScriptData> ref(other.asSingle());
3190 setSingle(ref.forget());
3191 } else if (other.isVector()) {
3192 if (!initVector(fc)) {
3193 return false;
3194 }
3195 if (!asVector()->appendAll(*other.asVector())) {
3196 ReportOutOfMemory(fc);
3197 return false;
3198 }
3199 } else if (other.isMap()) {
3200 if (!initMap(fc)) {
3201 return false;
3202 }
3203 auto& otherMap = *other.asMap();
3204 if (!asMap()->reserve(otherMap.count())) {
3205 ReportOutOfMemory(fc);
3206 return false;
3207 }
3208 auto& map = *asMap();
3209 for (auto iter = otherMap.iter(); !iter.done(); iter.next()) {
3210 auto& entry = iter.get();
3211 map.putNewInfallible(entry.key(), entry.value());
3212 }
3213 }
3214 return true;
3215 }
3216
3217 js::SharedImmutableScriptData* SharedDataContainer::get(
3218 ScriptIndex index) const {
3219 if (isSingle()) {
3220 if (index == CompilationStencil::TopLevelIndex) {
3221 return asSingle();
3222 }
3223 return nullptr;
3224 }
3225
3226 if (isVector()) {
3227 auto& vec = *asVector();
3228 if (index.index < vec.length()) {
3229 return vec[index];
3230 }
3231 return nullptr;
3232 }
3233
3234 if (isMap()) {
3235 auto& map = *asMap();
3236 auto p = map.lookup(index);
3237 if (p) {
3238 return p->value();
3239 }
3240 return nullptr;
3241 }
3242
3243 MOZ_ASSERT(isBorrow());
3244 return asBorrow()->get(index);
3245 }
3246
3247 bool SharedDataContainer::convertFromSingleToMap(FrontendContext* fc) {
3248 MOZ_ASSERT(isSingle());
3249
3250 // Use a temporary container so that on OOM we do not break the stencil.
3251 SharedDataContainer other;
3252 if (!other.initMap(fc)) {
3253 return false;
3254 }
3255
3256 if (!other.asMap()->putNew(CompilationStencil::TopLevelIndex, asSingle())) {
3257 ReportOutOfMemory(fc);
3258 return false;
3259 }
3260
3261 std::swap(data_, other.data_);
3262 return true;
3263 }
3264
3265 bool SharedDataContainer::addAndShare(FrontendContext* fc, ScriptIndex index,
3266 js::SharedImmutableScriptData* data) {
3267 MOZ_ASSERT(!isBorrow());
3268
3269 if (isSingle()) {
3270 MOZ_ASSERT(index == CompilationStencil::TopLevelIndex);
3271 RefPtr<SharedImmutableScriptData> ref(data);
3272 if (!SharedImmutableScriptData::shareScriptData(fc, ref)) {
3273 return false;
3274 }
3275 setSingle(ref.forget());
3276 return true;
3277 }
3278
3279 if (isVector()) {
3280 auto& vec = *asVector();
3281 // Resized by SharedDataContainer::prepareStorageFor.
3282 vec[index] = data;
3283 return SharedImmutableScriptData::shareScriptData(fc, vec[index]);
3284 }
3285
3286 MOZ_ASSERT(isMap());
3287 auto& map = *asMap();
3288 // Reserved by SharedDataContainer::prepareStorageFor.
3289 map.putNewInfallible(index, data);
3290 auto p = map.lookup(index);
3291 MOZ_ASSERT(p);
3292 return SharedImmutableScriptData::shareScriptData(fc, p->value());
3293 }
3294
3295 bool SharedDataContainer::addExtraWithoutShare(
3296 FrontendContext* fc, ScriptIndex index,
3297 js::SharedImmutableScriptData* data) {
3298 MOZ_ASSERT(!isEmpty());
3299
3300 if (isSingle()) {
3301 if (!convertFromSingleToMap(fc)) {
3302 return false;
3303 }
3304 }
3305
3306 if (isVector()) {
3307 // SharedDataContainer::prepareStorageFor allocates space for all scripts.
3308 (*asVector())[index] = data;
3309 return true;
3310 }
3311
3312 MOZ_ASSERT(isMap());
3313 // SharedDataContainer::prepareStorageFor doesn't allocate space for
3314 // delazification, and this can fail.
3315 if (!asMap()->putNew(index, data)) {
3316 ReportOutOfMemory(fc);
3317 return false;
3318 }
3319 return true;
3320 }
3321
3322 #ifdef DEBUG
3323 void CompilationStencil::assertNoExternalDependency() const {
3324 if (ownedBorrowStencil) {
3325 ownedBorrowStencil->assertNoExternalDependency();
3326
3327 assertBorrowingFromExtensibleCompilationStencil(*ownedBorrowStencil);
3328 return;
3329 }
3330
3331 MOZ_ASSERT_IF(!scriptData.empty(), alloc.contains(scriptData.data()));
3332 MOZ_ASSERT_IF(!scriptExtra.empty(), alloc.contains(scriptExtra.data()));
3333
3334 MOZ_ASSERT_IF(!scopeData.empty(), alloc.contains(scopeData.data()));
3335 MOZ_ASSERT_IF(!scopeNames.empty(), alloc.contains(scopeNames.data()));
3336 for (const auto* data : scopeNames) {
3337 MOZ_ASSERT_IF(data, alloc.contains(data));
3338 }
3339
3340 MOZ_ASSERT_IF(!regExpData.empty(), alloc.contains(regExpData.data()));
3341
3342 MOZ_ASSERT_IF(!bigIntData.empty(), alloc.contains(bigIntData.data()));
3343 for (const auto& data : bigIntData) {
3344 MOZ_ASSERT(data.isContainedIn(alloc));
3345 }
3346
3347 MOZ_ASSERT_IF(!objLiteralData.empty(), alloc.contains(objLiteralData.data()));
3348 for (const auto& data : objLiteralData) {
3349 MOZ_ASSERT(data.isContainedIn(alloc));
3350 }
3351
3352 MOZ_ASSERT_IF(!parserAtomData.empty(), alloc.contains(parserAtomData.data()));
3353 for (const auto* data : parserAtomData) {
3354 MOZ_ASSERT_IF(data, alloc.contains(data));
3355 }
3356
3357 MOZ_ASSERT(!sharedData.isBorrow());
3358 }
3359
3360 void ExtensibleCompilationStencil::assertNoExternalDependency() const {
3361 for (const auto& data : bigIntData) {
3362 MOZ_ASSERT(data.isContainedIn(alloc));
3363 }
3364
3365 for (const auto& data : objLiteralData) {
3366 MOZ_ASSERT(data.isContainedIn(alloc));
3367 }
3368
3369 for (const auto* data : scopeNames) {
3370 MOZ_ASSERT_IF(data, alloc.contains(data));
3371 }
3372
3373 for (const auto* data : parserAtoms.entries()) {
3374 MOZ_ASSERT_IF(data, alloc.contains(data));
3375 }
3376
3377 MOZ_ASSERT(!sharedData.isBorrow());
3378 }
3379 #endif // DEBUG
3380
3381 template <typename T, typename VectorT>
3382 [[nodiscard]] bool CopySpanToVector(FrontendContext* fc, VectorT& vec,
3383 mozilla::Span<T>& span) {
3384 auto len = span.size();
3385 if (len == 0) {
3386 return true;
3387 }
3388
3389 if (!vec.append(span.data(), len)) {
3390 js::ReportOutOfMemory(fc);
3391 return false;
3392 }
3393 return true;
3394 }
3395
3396 template <typename T, typename IntoSpanT, size_t Inline, typename AllocPolicy>
3397 [[nodiscard]] bool CopyToVector(FrontendContext* fc,
3398 mozilla::Vector<T, Inline, AllocPolicy>& vec,
3399 const IntoSpanT& source) {
3400 mozilla::Span<const T> span = source;
3401 return CopySpanToVector(fc, vec, span);
3402 }
3403
3404 // Span and Vector do not share the same method names.
3405 template <typename T, size_t Inline, typename AllocPolicy>
3406 size_t GetLength(const mozilla::Vector<T, Inline, AllocPolicy>& vec) {
3407 return vec.length();
3408 }
3409 template <typename T>
3410 size_t GetLength(const mozilla::Span<T>& span) {
3411 return span.Length();
3412 }
3413
3414 // Copy scope names from `src` into `alloc`, and returns the allocated data.
3415 BaseParserScopeData* CopyScopeData(FrontendContext* fc, LifoAlloc& alloc,
3416 ScopeKind kind,
3417 const BaseParserScopeData* src) {
3418 MOZ_ASSERT(kind != ScopeKind::With);
3419
3420 size_t dataSize = SizeOfParserScopeData(kind, src->length);
3421
3422 auto* dest = static_cast<BaseParserScopeData*>(alloc.alloc(dataSize));
3423 if (!dest) {
3424 js::ReportOutOfMemory(fc);
3425 return nullptr;
3426 }
3427 memcpy(dest, src, dataSize);
3428
3429 return dest;
3430 }
3431
3432 template <typename Stencil>
3433 bool ExtensibleCompilationStencil::cloneFromImpl(FrontendContext* fc,
3434 const Stencil& other) {
3435 MOZ_ASSERT(alloc.isEmpty());
3436
3437 canLazilyParse = other.canLazilyParse;
3438 functionKey = other.functionKey;
3439
3440 if (!CopyToVector(fc, scriptData, other.scriptData)) {
3441 return false;
3442 }
3443
3444 if (!CopyToVector(fc, scriptExtra, other.scriptExtra)) {
3445 return false;
3446 }
3447
3448 if (!CopyToVector(fc, gcThingData, other.gcThingData)) {
3449 return false;
3450 }
3451
3452 size_t scopeSize = GetLength(other.scopeData);
3453 if (!CopyToVector(fc, scopeData, other.scopeData)) {
3454 return false;
3455 }
3456 if (!scopeNames.reserve(scopeSize)) {
3457 js::ReportOutOfMemory(fc);
3458 return false;
3459 }
3460 for (size_t i = 0; i < scopeSize; i++) {
3461 if (other.scopeNames[i]) {
3462 BaseParserScopeData* data = CopyScopeData(
3463 fc, alloc, other.scopeData[i].kind(), other.scopeNames[i]);
3464 if (!data) {
3465 return false;
3466 }
3467 scopeNames.infallibleEmplaceBack(data);
3468 } else {
3469 scopeNames.infallibleEmplaceBack(nullptr);
3470 }
3471 }
3472
3473 if (!CopyToVector(fc, regExpData, other.regExpData)) {
3474 return false;
3475 }
3476
3477 // If CompilationStencil has external dependency, peform deep copy.
3478
3479 size_t bigIntSize = GetLength(other.bigIntData);
3480 if (!bigIntData.resize(bigIntSize)) {
3481 js::ReportOutOfMemory(fc);
3482 return false;
3483 }
3484 for (size_t i = 0; i < bigIntSize; i++) {
3485 if (!bigIntData[i].init(fc, alloc, other.bigIntData[i])) {
3486 return false;
3487 }
3488 }
3489
3490 size_t objLiteralSize = GetLength(other.objLiteralData);
3491 if (!objLiteralData.reserve(objLiteralSize)) {
3492 js::ReportOutOfMemory(fc);
3493 return false;
3494 }
3495 for (const auto& data : other.objLiteralData) {
3496 size_t length = data.code().size();
3497 auto* code = alloc.newArrayUninitialized<uint8_t>(length);
3498 if (!code) {
3499 js::ReportOutOfMemory(fc);
3500 return false;
3501 }
3502 memcpy(code, data.code().data(), length);
3503 objLiteralData.infallibleEmplaceBack(code, length, data.kind(),
3504 data.flags(), data.propertyCount());
3505 }
3506
3507 // Regardless of whether CompilationStencil has external dependency or not,
3508 // ParserAtoms should be interned, to populate internal HashMap.
3509 for (const auto* entry : other.parserAtomsSpan()) {
3510 if (!entry) {
3511 if (!parserAtoms.addPlaceholder(fc)) {
3512 return false;
3513 }
3514 continue;
3515 }
3516
3517 auto index = parserAtoms.internExternalParserAtom(fc, entry);
3518 if (!index) {
3519 return false;
3520 }
3521 }
3522
3523 // We copy the stencil and increment the reference count of each
3524 // SharedImmutableScriptData.
3525 if (!sharedData.cloneFrom(fc, other.sharedData)) {
3526 return false;
3527 }
3528
3529 // Note: moduleMetadata and asmJS are known after the first parse, and are
3530 // not mutated by any delazifications later on. Thus we can safely increment
3531 // the reference counter and keep these as-is.
3532 moduleMetadata = other.moduleMetadata;
3533 asmJS = other.asmJS;
3534
3535 #ifdef DEBUG
3536 assertNoExternalDependency();
3537 #endif
3538
3539 return true;
3540 }
3541
3542 bool ExtensibleCompilationStencil::cloneFrom(FrontendContext* fc,
3543 const CompilationStencil& other) {
3544 return cloneFromImpl(fc, other);
3545 }
3546 bool ExtensibleCompilationStencil::cloneFrom(
3547 FrontendContext* fc, const ExtensibleCompilationStencil& other) {
3548 return cloneFromImpl(fc, other);
3549 }
3550
3551 bool ExtensibleCompilationStencil::steal(FrontendContext* fc,
3552 RefPtr<CompilationStencil>&& other) {
3553 MOZ_ASSERT(alloc.isEmpty());
3554 using StorageType = CompilationStencil::StorageType;
3555 StorageType storageType = other->storageType;
3556 if (other->hasMultipleReference()) {
3557 storageType = StorageType::Borrowed;
3558 }
3559
3560 if (storageType == StorageType::OwnedExtensible) {
3561 auto& otherExtensible = other->ownedBorrowStencil;
3562
3563 canLazilyParse = otherExtensible->canLazilyParse;
3564 functionKey = otherExtensible->functionKey;
3565
3566 alloc.steal(&otherExtensible->alloc);
3567
3568 source = std::move(otherExtensible->source);
3569
3570 scriptData = std::move(otherExtensible->scriptData);
3571 scriptExtra = std::move(otherExtensible->scriptExtra);
3572 gcThingData = std::move(otherExtensible->gcThingData);
3573 scopeData = std::move(otherExtensible->scopeData);
3574 scopeNames = std::move(otherExtensible->scopeNames);
3575 regExpData = std::move(otherExtensible->regExpData);
3576 bigIntData = std::move(otherExtensible->bigIntData);
3577 objLiteralData = std::move(otherExtensible->objLiteralData);
3578
3579 parserAtoms = std::move(otherExtensible->parserAtoms);
3580 parserAtoms.fixupAlloc(alloc);
3581
3582 sharedData = std::move(otherExtensible->sharedData);
3583 moduleMetadata = std::move(otherExtensible->moduleMetadata);
3584 asmJS = std::move(otherExtensible->asmJS);
3585
3586 #ifdef DEBUG
3587 assertNoExternalDependency();
3588 #endif
3589
3590 return true;
3591 }
3592
3593 if (storageType == StorageType::Borrowed) {
3594 return cloneFrom(fc, *other);
3595 }
3596
3597 MOZ_ASSERT(storageType == StorageType::Owned);
3598
3599 canLazilyParse = other->canLazilyParse;
3600 functionKey = other->functionKey;
3601
3602 #ifdef DEBUG
3603 other->assertNoExternalDependency();
3604 MOZ_ASSERT(!other->hasMultipleReference());
3605 #endif
3606
3607 // If CompilationStencil has no external dependency,
3608 // steal LifoAlloc and perform shallow copy.
3609 alloc.steal(&other->alloc);
3610
3611 if (!CopySpanToVector(fc, scriptData, other->scriptData)) {
3612 return false;
3613 }
3614
3615 if (!CopySpanToVector(fc, scriptExtra, other->scriptExtra)) {
3616 return false;
3617 }
3618
3619 if (!CopySpanToVector(fc, gcThingData, other->gcThingData)) {
3620 return false;
3621 }
3622
3623 if (!CopySpanToVector(fc, scopeData, other->scopeData)) {
3624 return false;
3625 }
3626 if (!CopySpanToVector(fc, scopeNames, other->scopeNames)) {
3627 return false;
3628 }
3629
3630 if (!CopySpanToVector(fc, regExpData, other->regExpData)) {
3631 return false;
3632 }
3633
3634 if (!CopySpanToVector(fc, bigIntData, other->bigIntData)) {
3635 return false;
3636 }
3637
3638 if (!CopySpanToVector(fc, objLiteralData, other->objLiteralData)) {
3639 return false;
3640 }
3641
3642 // Regardless of whether CompilationStencil has external dependency or not,
3643 // ParserAtoms should be interned, to populate internal HashMap.
3644 for (const auto* entry : other->parserAtomData) {
3645 if (!entry) {
3646 if (!parserAtoms.addPlaceholder(fc)) {
3647 return false;
3648 }
3649 continue;
3650 }
3651
3652 auto index = parserAtoms.internExternalParserAtom(fc, entry);
3653 if (!index) {
3654 return false;
3655 }
3656 }
3657
3658 sharedData = std::move(other->sharedData);
3659 moduleMetadata = std::move(other->moduleMetadata);
3660 asmJS = std::move(other->asmJS);
3661
3662 #ifdef DEBUG
3663 assertNoExternalDependency();
3664 #endif
3665
3666 return true;
3667 }
3668
3669 bool CompilationStencil::isModule() const {
3670 return scriptExtra[CompilationStencil::TopLevelIndex].isModule();
3671 }
3672
3673 bool ExtensibleCompilationStencil::isModule() const {
3674 return scriptExtra[CompilationStencil::TopLevelIndex].isModule();
3675 }
3676
3677 bool CompilationStencil::hasAsmJS() const { return asmJS; }
3678
3679 bool ExtensibleCompilationStencil::hasAsmJS() const { return asmJS; }
3680
3681 bool InitialStencilAndDelazifications::hasAsmJS() const {
3682 return initial_->hasAsmJS();
3683 }
3684
3685 InitialStencilAndDelazifications::~InitialStencilAndDelazifications() {
3686 MOZ_ASSERT(refCount_ == 0);
3687
3688 for (size_t i = 0; i < delazifications_.length(); i++) {
3689 CompilationStencil* delazification = delazifications_[i].exchange(nullptr);
3690 if (delazification) {
3691 delazification->Release();
3692 }
3693 }
3694 }
3695
3696 void InitialStencilAndDelazifications::AddRef() { refCount_++; }
3697
3698 void InitialStencilAndDelazifications::Release() {
3699 MOZ_RELEASE_ASSERT(refCount_ > 0);
3700 if (--refCount_ == 0) {
3701 js_delete(this);
3702 }
3703 }
3704
3705 bool InitialStencilAndDelazifications::init(FrontendContext* fc,
3706 const CompilationStencil* initial) {
3707 MOZ_ASSERT(initial->isInitialStencil());
3708
3709 initial_ = initial;
3710
3711 if (!canLazilyParse()) {
3712 // If the initial stencil is known to be fully-parsed, delazification
3713 // never happens, and the delazifications_ vector and the
3714 // functionKeyToInitialScriptIndex_ map is never used.
3715 return true;
3716 }
3717
3718 if (!delazifications_.resize(initial_->scriptData.size())) {
3719 ReportOutOfMemory(fc);
3720 return false;
3721 }
3722
3723 return functionKeyToInitialScriptIndex_.init(fc, initial_);
3724 }
3725
3726 const CompilationStencil* InitialStencilAndDelazifications::getInitial() const {
3727 return initial_.get();
3728 }
3729
3730 const CompilationStencil* InitialStencilAndDelazifications::getDelazificationAt(
3731 size_t functionIndex) const {
3732 MOZ_ASSERT(canLazilyParse());
3733 MOZ_ASSERT(functionIndex > 0);
3734
3735 return delazifications_[functionIndex - 1];
3736 }
3737
3738 const CompilationStencil*
3739 InitialStencilAndDelazifications::getDelazificationFor(
3740 const SourceExtent& extent) const {
3741 MOZ_ASSERT(canLazilyParse());
3742 auto maybeIndex =
3743 functionKeyToInitialScriptIndex_.get(extent.toFunctionKey());
3744 MOZ_ASSERT(maybeIndex,
3745 "The extent parameter should be for a function inside the script");
3746 return getDelazificationAt(*maybeIndex);
3747 }
3748
3749 const CompilationStencil* InitialStencilAndDelazifications::storeDelazification(
3750 RefPtr<CompilationStencil>&& delazification) {
3751 MOZ_ASSERT(!delazification->hasMultipleReference());
3752 MOZ_ASSERT(canLazilyParse());
3753
3754 auto maybeIndex =
3755 functionKeyToInitialScriptIndex_.get(delazification->functionKey);
3756 MOZ_ASSERT(maybeIndex);
3757 size_t functionIndex = *maybeIndex;
3758
3759 CompilationStencil* raw = delazification.forget().take();
3760 if (delazifications_[functionIndex - 1].compareExchange(nullptr, raw)) {
3761 return raw;
3762 }
3763
3764 raw->Release();
3765 return delazifications_[functionIndex - 1];
3766 }
3767
3768 CompilationStencil* InitialStencilAndDelazifications::getMerged(
3769 FrontendContext* fc) const {
3770 MOZ_ASSERT(canLazilyParse());
3771
3772 UniquePtr<ExtensibleCompilationStencil> extensibleStencil(
3773 fc->getAllocator()->new_<ExtensibleCompilationStencil>(initial_->source));
3774 if (!extensibleStencil) {
3775 return nullptr;
3776 }
3777
3778 if (!extensibleStencil->cloneFrom(fc, *initial_)) {
3779 return nullptr;
3780 }
3781
3782 CompilationStencilMerger merger;
3783 if (!merger.setInitial(fc, std::move(extensibleStencil))) {
3784 return nullptr;
3785 }
3786
3787 for (const auto& delazification : delazifications_) {
3788 if (!delazification) {
3789 continue;
3790 }
3791
3792 // NOTE: The delazifications_ vector can be modified by other threads
3793 // during the iteration.
3794 // The enclosing delazification's is not guaranteed to be iterated
3795 // over in this iteration.
3796 // If the enclosing function wasn't merged, all inner functions are
3797 // ignored inside maybeAddDelazification.
3798 if (!merger.maybeAddDelazification(fc, *delazification)) {
3799 return nullptr;
3800 }
3801 }
3802
3803 UniquePtr<ExtensibleCompilationStencil> merged = merger.takeResult();
3804 return fc->getAllocator()->new_<CompilationStencil>(std::move(merged));
3805 }
3806
3807 /* static */
3808 bool InitialStencilAndDelazifications::instantiateStencils(
3809 JSContext* cx, CompilationInput& input,
3810 InitialStencilAndDelazifications& stencils, CompilationGCOutput& gcOutput) {
3811 if (!CompilationStencil::instantiateStencils(cx, input, *stencils.initial_,
3812 gcOutput)) {
3813 return false;
3814 }
3815
3816 if (input.options.populateDelazificationCache()) {
3817 RefPtr<InitialStencilAndDelazifications> stencilsPtr = &stencils;
3818 ScriptSourceObject* sso = gcOutput.script->sourceObject();
3819 MOZ_ASSERT(!sso->maybeGetStencils());
3820 if (!stencils.hasAsmJS()) {
3821 sso->setStencils(stencilsPtr.forget());
3822 sso->setSharingDelazifications();
3823 }
3824 }
3825
3826 // At this point, gcOutput.script contains the top-level script, and
3827 // gcOutput.functions[i] contains i-th function, where 0-th item is
3828 // always nullptr.
3829 // gcOutput.functions[i]->baseScript() is either JSScript or lazy script.
3830 for (size_t i = 0, length = stencils.delazifications_.length(); i < length;
3831 i++) {
3832 const auto& delazification = stencils.delazifications_[i];
3833 if (!delazification) {
3834 continue;
3835 }
3836
3837 ScriptIndex scriptIndex = ScriptIndex(i + 1);
3838 JS::Rooted<JSFunction*> fun(cx, gcOutput.functions[scriptIndex]);
3839 if (!fun->baseScript()->isReadyForDelazification()) {
3840 // NOTE: The delazifications_ vector can be modified by other threads
3841 // during the iteration.
3842 // The enclosing delazification's is not guaranteed to be iterated
3843 // over in this iteration.
3844 // If the enclosing function wasn't instantiated, ignore all inner
3845 // functions.
3846 continue;
3847 }
3848
3849 JS::Rooted<CompilationInput> inputForFunc(cx,
3850 CompilationInput(input.options));
3851 inputForFunc.get().initFromLazy(cx, fun->baseScript(), input.source);
3852
3853 // TODO: The preparation can be shared across iterations.
3854 JS::Rooted<CompilationGCOutput> gcOutputForFunc(cx);
3855 if (!CompilationStencil::instantiateStencils(
3856 cx, inputForFunc.get(), *delazification, gcOutputForFunc.get())) {
3857 return false;
3858 }
3859 }
3860
3861 return true;
3862 }
3863
3864 size_t InitialStencilAndDelazifications::sizeOfExcludingThis(
3865 mozilla::MallocSizeOf mallocSizeOf) const {
3866 size_t size = 0;
3867
3868 if (initial_) {
3869 // The initial stencil can be shared between multiple owners, but
3870 // in most case this instance is considered as the main owner, in term
3871 // of the memory reporting.
3872 size += initial_->sizeOfExcludingThis(mallocSizeOf);
3873 }
3874
3875 size += delazifications_.sizeOfExcludingThis(mallocSizeOf);
3876
3877 for (const auto& delazification : delazifications_) {
3878 if (!delazification) {
3879 continue;
3880 }
3881
3882 // Delazifications are exclusively owned by this instance.
3883 size += (*delazification).sizeOfExcludingThis(mallocSizeOf);
3884 }
3885
3886 size += functionKeyToInitialScriptIndex_.sizeOfExcludingThis(mallocSizeOf);
3887
3888 return size;
3889 }
3890
3891 mozilla::Span<TaggedScriptThingIndex> ScriptStencil::gcthings(
3892 const CompilationStencil& stencil) const {
3893 return stencil.gcThingData.Subspan(gcThingsOffset, gcThingsLength);
3894 }
3895
3896 bool BigIntStencil::initFromChars(FrontendContext* fc, LifoAlloc& alloc,
3897 mozilla::Span<const char16_t> buf) {
3898 MOZ_ASSERT(ParseBigInt64Literal(buf).isNothing(),
3899 "int64-sized BigInts are stored inline");
3900
3901 size_t length = buf.size();
3902 MOZ_ASSERT(length > 0);
3903
3904 char16_t* p = alloc.template newArrayUninitialized<char16_t>(length);
3905 if (!p) {
3906 ReportOutOfMemory(fc);
3907 return false;
3908 }
3909 mozilla::PodCopy(p, buf.data(), length);
3910 bigInt_ = mozilla::AsVariant(mozilla::Span(p, length));
3911 return true;
3912 }
3913
3914 bool BigIntStencil::init(FrontendContext* fc, LifoAlloc& alloc,
3915 mozilla::Span<const char16_t> buf) {
3916 if (auto int64 = ParseBigInt64Literal(buf)) {
3917 bigInt_ = mozilla::AsVariant(*int64);
3918 return true;
3919 }
3920 return initFromChars(fc, alloc, buf);
3921 }
3922
3923 bool BigIntStencil::init(FrontendContext* fc, LifoAlloc& alloc,
3924 const BigIntStencil& other) {
3925 if (other.bigInt_.is<int64_t>()) {
3926 bigInt_ = other.bigInt_;
3927 return true;
3928 }
3929 return initFromChars(fc, alloc, other.source());
3930 }
3931
3932 BigInt* BigIntStencil::createBigInt(JSContext* cx) const {
3933 return bigInt_.match(
3934 [cx](mozilla::Span<char16_t> source) {
3935 return js::ParseBigIntLiteral(cx, source);
3936 },
3937 [cx](int64_t int64) {
3938 // BigInts are stored in the script's data vector and therefore need to
3939 // be allocated in the tenured heap.
3940 constexpr gc::Heap heap = gc::Heap::Tenured;
3941 return BigInt::createFromInt64(cx, int64, heap);
3942 });
3943 }
3944
3945 bool BigIntStencil::isZero() const {
3946 return bigInt_.match([](mozilla::Span<char16_t>) { return false; },
3947 [](int64_t int64) { return int64 == 0; });
3948 }
3949
3950 bool BigIntStencil::inplaceNegate() {
3951 return bigInt_.match([](mozilla::Span<char16_t>) { return false; },
3952 [](int64_t& int64) {
3953 auto negated = -mozilla::CheckedInt<int64_t>{int64};
3954 if (!negated.isValid()) {
3955 return false;
3956 }
3957 int64 = negated.value();
3958 return true;
3959 });
3960 }
3961
3962 bool BigIntStencil::inplaceBitNot() {
3963 return bigInt_.match([](mozilla::Span<char16_t>) { return false; },
3964 [](int64_t& int64) {
3965 int64 = ~int64;
3966 return true;
3967 });
3968 }
3969
3970 #ifdef DEBUG
3971 bool BigIntStencil::isContainedIn(const LifoAlloc& alloc) const {
3972 return bigInt_.match(
3973 [&alloc](mozilla::Span<char16_t> source) {
3974 return alloc.contains(source.data());
3975 },
3976 [](int64_t) { return true; });
3977 }
3978 #endif
3979
3980 #if defined(DEBUG) || defined(JS_JITSPEW)
3981
3982 void frontend::DumpTaggedParserAtomIndex(js::JSONPrinter& json,
3983 TaggedParserAtomIndex taggedIndex,
3984 const CompilationStencil* stencil) {
3985 if (taggedIndex.isParserAtomIndex()) {
3986 json.property("tag", "AtomIndex");
3987 auto index = taggedIndex.toParserAtomIndex();
3988 if (stencil && stencil->parserAtomData[index]) {
3989 GenericPrinter& out = json.beginStringProperty("atom");
3990 stencil->parserAtomData[index]->dumpCharsNoQuote(out);
3991 json.endString();
3992 } else {
3993 json.property("index", size_t(index));
3994 }
3995 return;
3996 }
3997
3998 if (taggedIndex.isWellKnownAtomId()) {
3999 json.property("tag", "WellKnown");
4000 auto index = taggedIndex.toWellKnownAtomId();
4001 switch (index) {
4002 case WellKnownAtomId::empty_:
4003 json.property("atom", "");
4004 break;
4005
4006 # define CASE_(name, _) case WellKnownAtomId::name:
4007 FOR_EACH_NONTINY_COMMON_PROPERTYNAME(CASE_)
4008 # undef CASE_
4009
4010 # define CASE_(name, _) case WellKnownAtomId::name:
4011 JS_FOR_EACH_PROTOTYPE(CASE_)
4012 # undef CASE_
4013
4014 # define CASE_(name) case WellKnownAtomId::name:
4015 JS_FOR_EACH_WELL_KNOWN_SYMBOL(CASE_)
4016 # undef CASE_
4017
4018 {
4019 GenericPrinter& out = json.beginStringProperty("atom");
4020 ParserAtomsTable::dumpCharsNoQuote(out, index);
4021 json.endString();
4022 break;
4023 }
4024
4025 default:
4026 // This includes tiny WellKnownAtomId atoms, which is invalid.
4027 json.property("index", size_t(index));
4028 break;
4029 }
4030 return;
4031 }
4032
4033 if (taggedIndex.isLength1StaticParserString()) {
4034 json.property("tag", "Length1Static");
4035 auto index = taggedIndex.toLength1StaticParserString();
4036 GenericPrinter& out = json.beginStringProperty("atom");
4037 ParserAtomsTable::dumpCharsNoQuote(out, index);
4038 json.endString();
4039 return;
4040 }
4041
4042 if (taggedIndex.isLength2StaticParserString()) {
4043 json.property("tag", "Length2Static");
4044 auto index = taggedIndex.toLength2StaticParserString();
4045 GenericPrinter& out = json.beginStringProperty("atom");
4046 ParserAtomsTable::dumpCharsNoQuote(out, index);
4047 json.endString();
4048 return;
4049 }
4050
4051 if (taggedIndex.isLength3StaticParserString()) {
4052 json.property("tag", "Length3Static");
4053 auto index = taggedIndex.toLength3StaticParserString();
4054 GenericPrinter& out = json.beginStringProperty("atom");
4055 ParserAtomsTable::dumpCharsNoQuote(out, index);
4056 json.endString();
4057 return;
4058 }
4059
4060 MOZ_ASSERT(taggedIndex.isNull());
4061 json.property("tag", "null");
4062 }
4063
4064 void frontend::DumpTaggedParserAtomIndexNoQuote(
4065 GenericPrinter& out, TaggedParserAtomIndex taggedIndex,
4066 const CompilationStencil* stencil) {
4067 if (taggedIndex.isParserAtomIndex()) {
4068 auto index = taggedIndex.toParserAtomIndex();
4069 if (stencil && stencil->parserAtomData[index]) {
4070 stencil->parserAtomData[index]->dumpCharsNoQuote(out);
4071 } else {
4072 out.printf("AtomIndex#%zu", size_t(index));
4073 }
4074 return;
4075 }
4076
4077 if (taggedIndex.isWellKnownAtomId()) {
4078 auto index = taggedIndex.toWellKnownAtomId();
4079 switch (index) {
4080 case WellKnownAtomId::empty_:
4081 out.put("#<zero-length name>");
4082 break;
4083
4084 # define CASE_(name, _) case WellKnownAtomId::name:
4085 FOR_EACH_NONTINY_COMMON_PROPERTYNAME(CASE_)
4086 # undef CASE_
4087
4088 # define CASE_(name, _) case WellKnownAtomId::name:
4089 JS_FOR_EACH_PROTOTYPE(CASE_)
4090 # undef CASE_
4091
4092 # define CASE_(name) case WellKnownAtomId::name:
4093 JS_FOR_EACH_WELL_KNOWN_SYMBOL(CASE_)
4094 # undef CASE_
4095
4096 {
4097 ParserAtomsTable::dumpCharsNoQuote(out, index);
4098 break;
4099 }
4100
4101 default:
4102 // This includes tiny WellKnownAtomId atoms, which is invalid.
4103 out.printf("WellKnown#%zu", size_t(index));
4104 break;
4105 }
4106 return;
4107 }
4108
4109 if (taggedIndex.isLength1StaticParserString()) {
4110 auto index = taggedIndex.toLength1StaticParserString();
4111 ParserAtomsTable::dumpCharsNoQuote(out, index);
4112 return;
4113 }
4114
4115 if (taggedIndex.isLength2StaticParserString()) {
4116 auto index = taggedIndex.toLength2StaticParserString();
4117 ParserAtomsTable::dumpCharsNoQuote(out, index);
4118 return;
4119 }
4120
4121 if (taggedIndex.isLength3StaticParserString()) {
4122 auto index = taggedIndex.toLength3StaticParserString();
4123 ParserAtomsTable::dumpCharsNoQuote(out, index);
4124 return;
4125 }
4126
4127 MOZ_ASSERT(taggedIndex.isNull());
4128 out.put("#<null name>");
4129 }
4130
4131 void RegExpStencil::dump() const {
4132 js::Fprinter out(stderr);
4133 js::JSONPrinter json(out);
4134 dump(json, nullptr);
4135 }
4136
4137 void RegExpStencil::dump(js::JSONPrinter& json,
4138 const CompilationStencil* stencil) const {
4139 json.beginObject();
4140 dumpFields(json, stencil);
4141 json.endObject();
4142 }
4143
4144 void RegExpStencil::dumpFields(js::JSONPrinter& json,
4145 const CompilationStencil* stencil) const {
4146 json.beginObjectProperty("pattern");
4147 DumpTaggedParserAtomIndex(json, atom_, stencil);
4148 json.endObject();
4149
4150 GenericPrinter& out = json.beginStringProperty("flags");
4151
4152 if (flags().global()) {
4153 out.put("g");
4154 }
4155 if (flags().ignoreCase()) {
4156 out.put("i");
4157 }
4158 if (flags().multiline()) {
4159 out.put("m");
4160 }
4161 if (flags().dotAll()) {
4162 out.put("s");
4163 }
4164 if (flags().unicode()) {
4165 out.put("u");
4166 }
4167 if (flags().sticky()) {
4168 out.put("y");
4169 }
4170
4171 json.endStringProperty();
4172 }
4173
4174 void BigIntStencil::dump() const {
4175 js::Fprinter out(stderr);
4176 js::JSONPrinter json(out);
4177 dump(json);
4178 }
4179
4180 void BigIntStencil::dump(js::JSONPrinter& json) const {
4181 GenericPrinter& out = json.beginString();
4182 dumpCharsNoQuote(out);
4183 json.endString();
4184 }
4185
4186 void BigIntStencil::dumpCharsNoQuote(GenericPrinter& out) const {
4187 bigInt_.match(
4188 [&out](mozilla::Span<char16_t> source) {
4189 for (char16_t c : source) {
4190 out.putChar(char(c));
4191 }
4192 },
4193 [&out](int64_t int64) { out.printf("%" PRId64, int64); });
4194 }
4195
4196 void ScopeStencil::dump() const {
4197 js::Fprinter out(stderr);
4198 js::JSONPrinter json(out);
4199 dump(json, nullptr, nullptr);
4200 }
4201
4202 void ScopeStencil::dump(js::JSONPrinter& json,
4203 const BaseParserScopeData* baseScopeData,
4204 const CompilationStencil* stencil) const {
4205 json.beginObject();
4206 dumpFields(json, baseScopeData, stencil);
4207 json.endObject();
4208 }
4209
4210 void ScopeStencil::dumpFields(js::JSONPrinter& json,
4211 const BaseParserScopeData* baseScopeData,
4212 const CompilationStencil* stencil) const {
4213 json.property("kind", ScopeKindString(kind_));
4214
4215 if (hasEnclosing()) {
4216 json.formatProperty("enclosing", "ScopeIndex(%zu)", size_t(enclosing()));
4217 }
4218
4219 json.property("firstFrameSlot", firstFrameSlot_);
4220
4221 if (hasEnvironmentShape()) {
4222 json.formatProperty("numEnvironmentSlots", "%zu",
4223 size_t(numEnvironmentSlots_));
4224 }
4225
4226 if (isFunction()) {
4227 json.formatProperty("functionIndex", "ScriptIndex(%zu)",
4228 size_t(functionIndex_));
4229 }
4230
4231 json.beginListProperty("flags");
4232 if (flags_ & HasEnclosing) {
4233 json.value("HasEnclosing");
4234 }
4235 if (flags_ & HasEnvironmentShape) {
4236 json.value("HasEnvironmentShape");
4237 }
4238 if (flags_ & IsArrow) {
4239 json.value("IsArrow");
4240 }
4241 json.endList();
4242
4243 if (!baseScopeData) {
4244 return;
4245 }
4246
4247 json.beginObjectProperty("data");
4248
4249 mozilla::Span<const ParserBindingName> trailingNames;
4250 switch (kind_) {
4251 case ScopeKind::Function: {
4252 const auto* data =
4253 static_cast<const FunctionScope::ParserData*>(baseScopeData);
4254 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4255 json.property("hasParameterExprs", data->slotInfo.hasParameterExprs());
4256 json.property("nonPositionalFormalStart",
4257 data->slotInfo.nonPositionalFormalStart);
4258 json.property("varStart", data->slotInfo.varStart);
4259
4260 trailingNames = GetScopeDataTrailingNames(data);
4261 break;
4262 }
4263
4264 case ScopeKind::FunctionBodyVar: {
4265 const auto* data =
4266 static_cast<const VarScope::ParserData*>(baseScopeData);
4267 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4268
4269 trailingNames = GetScopeDataTrailingNames(data);
4270 break;
4271 }
4272
4273 case ScopeKind::Lexical:
4274 case ScopeKind::SimpleCatch:
4275 case ScopeKind::Catch:
4276 case ScopeKind::NamedLambda:
4277 case ScopeKind::StrictNamedLambda:
4278 case ScopeKind::FunctionLexical: {
4279 const auto* data =
4280 static_cast<const LexicalScope::ParserData*>(baseScopeData);
4281 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4282 json.property("constStart", data->slotInfo.constStart);
4283
4284 trailingNames = GetScopeDataTrailingNames(data);
4285 break;
4286 }
4287
4288 case ScopeKind::ClassBody: {
4289 const auto* data =
4290 static_cast<const ClassBodyScope::ParserData*>(baseScopeData);
4291 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4292 json.property("privateMethodStart", data->slotInfo.privateMethodStart);
4293
4294 trailingNames = GetScopeDataTrailingNames(data);
4295 break;
4296 }
4297
4298 case ScopeKind::With: {
4299 break;
4300 }
4301
4302 case ScopeKind::Eval:
4303 case ScopeKind::StrictEval: {
4304 const auto* data =
4305 static_cast<const EvalScope::ParserData*>(baseScopeData);
4306 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4307
4308 trailingNames = GetScopeDataTrailingNames(data);
4309 break;
4310 }
4311
4312 case ScopeKind::Global:
4313 case ScopeKind::NonSyntactic: {
4314 const auto* data =
4315 static_cast<const GlobalScope::ParserData*>(baseScopeData);
4316 json.property("letStart", data->slotInfo.letStart);
4317 json.property("constStart", data->slotInfo.constStart);
4318
4319 trailingNames = GetScopeDataTrailingNames(data);
4320 break;
4321 }
4322
4323 case ScopeKind::Module: {
4324 const auto* data =
4325 static_cast<const ModuleScope::ParserData*>(baseScopeData);
4326 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4327 json.property("varStart", data->slotInfo.varStart);
4328 json.property("letStart", data->slotInfo.letStart);
4329 json.property("constStart", data->slotInfo.constStart);
4330
4331 trailingNames = GetScopeDataTrailingNames(data);
4332 break;
4333 }
4334
4335 case ScopeKind::WasmInstance: {
4336 const auto* data =
4337 static_cast<const WasmInstanceScope::ParserData*>(baseScopeData);
4338 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4339 json.property("globalsStart", data->slotInfo.globalsStart);
4340
4341 trailingNames = GetScopeDataTrailingNames(data);
4342 break;
4343 }
4344
4345 case ScopeKind::WasmFunction: {
4346 const auto* data =
4347 static_cast<const WasmFunctionScope::ParserData*>(baseScopeData);
4348 json.property("nextFrameSlot", data->slotInfo.nextFrameSlot);
4349
4350 trailingNames = GetScopeDataTrailingNames(data);
4351 break;
4352 }
4353
4354 default: {
4355 MOZ_CRASH("Unexpected ScopeKind");
4356 break;
4357 }
4358 }
4359
4360 if (!trailingNames.empty()) {
4361 char index[64];
4362 json.beginObjectProperty("trailingNames");
4363 for (size_t i = 0; i < trailingNames.size(); i++) {
4364 const auto& name = trailingNames[i];
4365 SprintfLiteral(index, "%zu", i);
4366 json.beginObjectProperty(index);
4367
4368 json.boolProperty("closedOver", name.closedOver());
4369
4370 json.boolProperty("isTopLevelFunction", name.isTopLevelFunction());
4371
4372 json.beginObjectProperty("name");
4373 DumpTaggedParserAtomIndex(json, name.name(), stencil);
4374 json.endObject();
4375
4376 json.endObject();
4377 }
4378 json.endObject();
4379 }
4380
4381 json.endObject();
4382 }
4383
4384 static void DumpModuleRequestVectorItems(
4385 js::JSONPrinter& json, const StencilModuleMetadata::RequestVector& requests,
4386 const CompilationStencil* stencil) {
4387 for (const auto& request : requests) {
4388 json.beginObject();
4389 if (request.specifier) {
4390 json.beginObjectProperty("specifier");
4391 DumpTaggedParserAtomIndex(json, request.specifier, stencil);
4392 json.endObject();
4393 }
4394 json.endObject();
4395 }
4396 }
4397
4398 static void DumpModuleEntryVectorItems(
4399 js::JSONPrinter& json, const StencilModuleMetadata::EntryVector& entries,
4400 const CompilationStencil* stencil) {
4401 for (const auto& entry : entries) {
4402 json.beginObject();
4403 if (entry.moduleRequest) {
4404 json.property("moduleRequest", entry.moduleRequest.value());
4405 }
4406 if (entry.localName) {
4407 json.beginObjectProperty("localName");
4408 DumpTaggedParserAtomIndex(json, entry.localName, stencil);
4409 json.endObject();
4410 }
4411 if (entry.importName) {
4412 json.beginObjectProperty("importName");
4413 DumpTaggedParserAtomIndex(json, entry.importName, stencil);
4414 json.endObject();
4415 }
4416 if (entry.exportName) {
4417 json.beginObjectProperty("exportName");
4418 DumpTaggedParserAtomIndex(json, entry.exportName, stencil);
4419 json.endObject();
4420 }
4421 // TODO: Dump assertions.
4422 json.endObject();
4423 }
4424 }
4425
4426 void StencilModuleMetadata::dump() const {
4427 js::Fprinter out(stderr);
4428 js::JSONPrinter json(out);
4429 dump(json, nullptr);
4430 }
4431
4432 void StencilModuleMetadata::dump(js::JSONPrinter& json,
4433 const CompilationStencil* stencil) const {
4434 json.beginObject();
4435 dumpFields(json, stencil);
4436 json.endObject();
4437 }
4438
4439 void StencilModuleMetadata::dumpFields(
4440 js::JSONPrinter& json, const CompilationStencil* stencil) const {
4441 json.beginListProperty("moduleRequests");
4442 DumpModuleRequestVectorItems(json, moduleRequests, stencil);
4443 json.endList();
4444
4445 json.beginListProperty("requestedModules");
4446 DumpModuleEntryVectorItems(json, requestedModules, stencil);
4447 json.endList();
4448
4449 json.beginListProperty("importEntries");
4450 DumpModuleEntryVectorItems(json, importEntries, stencil);
4451 json.endList();
4452
4453 json.beginListProperty("localExportEntries");
4454 DumpModuleEntryVectorItems(json, localExportEntries, stencil);
4455 json.endList();
4456
4457 json.beginListProperty("indirectExportEntries");
4458 DumpModuleEntryVectorItems(json, indirectExportEntries, stencil);
4459 json.endList();
4460
4461 json.beginListProperty("starExportEntries");
4462 DumpModuleEntryVectorItems(json, starExportEntries, stencil);
4463 json.endList();
4464
4465 json.beginListProperty("functionDecls");
4466 for (const auto& index : functionDecls) {
4467 json.value("ScriptIndex(%zu)", size_t(index));
4468 }
4469 json.endList();
4470
4471 json.boolProperty("isAsync", isAsync);
4472 }
4473
4474 void js::DumpImmutableScriptFlags(js::JSONPrinter& json,
4475 ImmutableScriptFlags immutableFlags) {
4476 for (uint32_t i = 1; i; i = i << 1) {
4477 if (uint32_t(immutableFlags) & i) {
4478 switch (ImmutableScriptFlagsEnum(i)) {
4479 case ImmutableScriptFlagsEnum::IsForEval:
4480 json.value("IsForEval");
4481 break;
4482 case ImmutableScriptFlagsEnum::IsModule:
4483 json.value("IsModule");
4484 break;
4485 case ImmutableScriptFlagsEnum::IsFunction:
4486 json.value("IsFunction");
4487 break;
4488 case ImmutableScriptFlagsEnum::SelfHosted:
4489 json.value("SelfHosted");
4490 break;
4491 case ImmutableScriptFlagsEnum::ForceStrict:
4492 json.value("ForceStrict");
4493 break;
4494 case ImmutableScriptFlagsEnum::HasNonSyntacticScope:
4495 json.value("HasNonSyntacticScope");
4496 break;
4497 case ImmutableScriptFlagsEnum::NoScriptRval:
4498 json.value("NoScriptRval");
4499 break;
4500 case ImmutableScriptFlagsEnum::TreatAsRunOnce:
4501 json.value("TreatAsRunOnce");
4502 break;
4503 case ImmutableScriptFlagsEnum::Strict:
4504 json.value("Strict");
4505 break;
4506 case ImmutableScriptFlagsEnum::HasModuleGoal:
4507 json.value("HasModuleGoal");
4508 break;
4509 case ImmutableScriptFlagsEnum::HasInnerFunctions:
4510 json.value("HasInnerFunctions");
4511 break;
4512 case ImmutableScriptFlagsEnum::HasDirectEval:
4513 json.value("HasDirectEval");
4514 break;
4515 case ImmutableScriptFlagsEnum::BindingsAccessedDynamically:
4516 json.value("BindingsAccessedDynamically");
4517 break;
4518 case ImmutableScriptFlagsEnum::HasCallSiteObj:
4519 json.value("HasCallSiteObj");
4520 break;
4521 case ImmutableScriptFlagsEnum::IsAsync:
4522 json.value("IsAsync");
4523 break;
4524 case ImmutableScriptFlagsEnum::IsGenerator:
4525 json.value("IsGenerator");
4526 break;
4527 case ImmutableScriptFlagsEnum::FunHasExtensibleScope:
4528 json.value("FunHasExtensibleScope");
4529 break;
4530 case ImmutableScriptFlagsEnum::FunctionHasThisBinding:
4531 json.value("FunctionHasThisBinding");
4532 break;
4533 case ImmutableScriptFlagsEnum::NeedsHomeObject:
4534 json.value("NeedsHomeObject");
4535 break;
4536 case ImmutableScriptFlagsEnum::IsDerivedClassConstructor:
4537 json.value("IsDerivedClassConstructor");
4538 break;
4539 case ImmutableScriptFlagsEnum::IsSyntheticFunction:
4540 json.value("IsSyntheticFunction");
4541 break;
4542 case ImmutableScriptFlagsEnum::UseMemberInitializers:
4543 json.value("UseMemberInitializers");
4544 break;
4545 case ImmutableScriptFlagsEnum::HasRest:
4546 json.value("HasRest");
4547 break;
4548 case ImmutableScriptFlagsEnum::NeedsFunctionEnvironmentObjects:
4549 json.value("NeedsFunctionEnvironmentObjects");
4550 break;
4551 case ImmutableScriptFlagsEnum::FunctionHasExtraBodyVarScope:
4552 json.value("FunctionHasExtraBodyVarScope");
4553 break;
4554 case ImmutableScriptFlagsEnum::ShouldDeclareArguments:
4555 json.value("ShouldDeclareArguments");
4556 break;
4557 case ImmutableScriptFlagsEnum::NeedsArgsObj:
4558 json.value("NeedsArgsObj");
4559 break;
4560 case ImmutableScriptFlagsEnum::HasMappedArgsObj:
4561 json.value("HasMappedArgsObj");
4562 break;
4563 case ImmutableScriptFlagsEnum::IsInlinableLargeFunction:
4564 json.value("IsInlinableLargeFunction");
4565 break;
4566 case ImmutableScriptFlagsEnum::FunctionHasNewTargetBinding:
4567 json.value("FunctionHasNewTargetBinding");
4568 break;
4569 case ImmutableScriptFlagsEnum::UsesArgumentsIntrinsics:
4570 json.value("UsesArgumentsIntrinsics");
4571 break;
4572 default:
4573 json.value("Unknown(%x)", i);
4574 break;
4575 }
4576 }
4577 }
4578 }
4579
4580 void js::DumpFunctionFlagsItems(js::JSONPrinter& json,
4581 FunctionFlags functionFlags) {
4582 switch (functionFlags.kind()) {
4583 case FunctionFlags::FunctionKind::NormalFunction:
4584 json.value("NORMAL_KIND");
4585 break;
4586 case FunctionFlags::FunctionKind::AsmJS:
4587 json.value("ASMJS_KIND");
4588 break;
4589 case FunctionFlags::FunctionKind::Wasm:
4590 json.value("WASM_KIND");
4591 break;
4592 case FunctionFlags::FunctionKind::Arrow:
4593 json.value("ARROW_KIND");
4594 break;
4595 case FunctionFlags::FunctionKind::Method:
4596 json.value("METHOD_KIND");
4597 break;
4598 case FunctionFlags::FunctionKind::ClassConstructor:
4599 json.value("CLASSCONSTRUCTOR_KIND");
4600 break;
4601 case FunctionFlags::FunctionKind::Getter:
4602 json.value("GETTER_KIND");
4603 break;
4604 case FunctionFlags::FunctionKind::Setter:
4605 json.value("SETTER_KIND");
4606 break;
4607 default:
4608 json.value("Unknown(%x)", uint8_t(functionFlags.kind()));
4609 break;
4610 }
4611
4612 static_assert(FunctionFlags::FUNCTION_KIND_MASK == 0x0007,
4613 "FunctionKind should use the lowest 3 bits");
4614 for (uint16_t i = 1 << 3; i; i = i << 1) {
4615 if (functionFlags.toRaw() & i) {
4616 switch (FunctionFlags::Flags(i)) {
4617 case FunctionFlags::Flags::EXTENDED:
4618 json.value("EXTENDED");
4619 break;
4620 case FunctionFlags::Flags::SELF_HOSTED:
4621 json.value("SELF_HOSTED");
4622 break;
4623 case FunctionFlags::Flags::BASESCRIPT:
4624 json.value("BASESCRIPT");
4625 break;
4626 case FunctionFlags::Flags::SELFHOSTLAZY:
4627 json.value("SELFHOSTLAZY");
4628 break;
4629 case FunctionFlags::Flags::CONSTRUCTOR:
4630 json.value("CONSTRUCTOR");
4631 break;
4632 case FunctionFlags::Flags::LAZY_ACCESSOR_NAME:
4633 json.value("LAZY_ACCESSOR_NAME");
4634 break;
4635 case FunctionFlags::Flags::LAMBDA:
4636 json.value("LAMBDA");
4637 break;
4638 case FunctionFlags::Flags::NATIVE_JIT_ENTRY:
4639 json.value("NATIVE_JIT_ENTRY");
4640 break;
4641 case FunctionFlags::Flags::HAS_INFERRED_NAME:
4642 json.value("HAS_INFERRED_NAME");
4643 break;
4644 case FunctionFlags::Flags::HAS_GUESSED_ATOM:
4645 json.value("HAS_GUESSED_ATOM");
4646 break;
4647 case FunctionFlags::Flags::RESOLVED_NAME:
4648 json.value("RESOLVED_NAME");
4649 break;
4650 case FunctionFlags::Flags::RESOLVED_LENGTH:
4651 json.value("RESOLVED_LENGTH");
4652 break;
4653 case FunctionFlags::Flags::GHOST_FUNCTION:
4654 json.value("GHOST_FUNCTION");
4655 break;
4656 default:
4657 json.value("Unknown(%x)", i);
4658 break;
4659 }
4660 }
4661 }
4662 }
4663
4664 static void DumpScriptThing(js::JSONPrinter& json,
4665 const CompilationStencil* stencil,
4666 TaggedScriptThingIndex thing) {
4667 switch (thing.tag()) {
4668 case TaggedScriptThingIndex::Kind::ParserAtomIndex:
4669 case TaggedScriptThingIndex::Kind::WellKnown:
4670 json.beginObject();
4671 json.property("type", "Atom");
4672 DumpTaggedParserAtomIndex(json, thing.toAtom(), stencil);
4673 json.endObject();
4674 break;
4675 case TaggedScriptThingIndex::Kind::Null:
4676 json.nullValue();
4677 break;
4678 case TaggedScriptThingIndex::Kind::BigInt:
4679 json.value("BigIntIndex(%zu)", size_t(thing.toBigInt()));
4680 break;
4681 case TaggedScriptThingIndex::Kind::ObjLiteral:
4682 json.value("ObjLiteralIndex(%zu)", size_t(thing.toObjLiteral()));
4683 break;
4684 case TaggedScriptThingIndex::Kind::RegExp:
4685 json.value("RegExpIndex(%zu)", size_t(thing.toRegExp()));
4686 break;
4687 case TaggedScriptThingIndex::Kind::Scope:
4688 json.value("ScopeIndex(%zu)", size_t(thing.toScope()));
4689 break;
4690 case TaggedScriptThingIndex::Kind::Function:
4691 json.value("ScriptIndex(%zu)", size_t(thing.toFunction()));
4692 break;
4693 case TaggedScriptThingIndex::Kind::EmptyGlobalScope:
4694 json.value("EmptyGlobalScope");
4695 break;
4696 }
4697 }
4698
4699 void ScriptStencil::dump() const {
4700 js::Fprinter out(stderr);
4701 js::JSONPrinter json(out);
4702 dump(json, nullptr);
4703 }
4704
4705 void ScriptStencil::dump(js::JSONPrinter& json,
4706 const CompilationStencil* stencil) const {
4707 json.beginObject();
4708 dumpFields(json, stencil);
4709 json.endObject();
4710 }
4711
4712 void ScriptStencil::dumpFields(js::JSONPrinter& json,
4713 const CompilationStencil* stencil) const {
4714 json.formatProperty("gcThingsOffset", "CompilationGCThingIndex(%u)",
4715 gcThingsOffset.index);
4716 json.property("gcThingsLength", gcThingsLength);
4717
4718 if (stencil) {
4719 json.beginListProperty("gcThings");
4720 for (const auto& thing : gcthings(*stencil)) {
4721 DumpScriptThing(json, stencil, thing);
4722 }
4723 json.endList();
4724 }
4725
4726 json.beginListProperty("flags");
4727 if (flags_ & WasEmittedByEnclosingScriptFlag) {
4728 json.value("WasEmittedByEnclosingScriptFlag");
4729 }
4730 if (flags_ & AllowRelazifyFlag) {
4731 json.value("AllowRelazifyFlag");
4732 }
4733 if (flags_ & HasSharedDataFlag) {
4734 json.value("HasSharedDataFlag");
4735 }
4736 if (flags_ & HasLazyFunctionEnclosingScopeIndexFlag) {
4737 json.value("HasLazyFunctionEnclosingScopeIndexFlag");
4738 }
4739 json.endList();
4740
4741 if (isFunction()) {
4742 json.beginObjectProperty("functionAtom");
4743 DumpTaggedParserAtomIndex(json, functionAtom, stencil);
4744 json.endObject();
4745
4746 json.beginListProperty("functionFlags");
4747 DumpFunctionFlagsItems(json, functionFlags);
4748 json.endList();
4749
4750 if (hasLazyFunctionEnclosingScopeIndex()) {
4751 json.formatProperty("lazyFunctionEnclosingScopeIndex", "ScopeIndex(%zu)",
4752 size_t(lazyFunctionEnclosingScopeIndex()));
4753 }
4754
4755 if (hasSelfHostedCanonicalName()) {
4756 json.beginObjectProperty("selfHostCanonicalName");
4757 DumpTaggedParserAtomIndex(json, selfHostedCanonicalName(), stencil);
4758 json.endObject();
4759 }
4760 }
4761 }
4762
4763 void ScriptStencilExtra::dump() const {
4764 js::Fprinter out(stderr);
4765 js::JSONPrinter json(out);
4766 dump(json);
4767 }
4768
4769 void ScriptStencilExtra::dump(js::JSONPrinter& json) const {
4770 json.beginObject();
4771 dumpFields(json);
4772 json.endObject();
4773 }
4774
4775 void ScriptStencilExtra::dumpFields(js::JSONPrinter& json) const {
4776 json.beginListProperty("immutableFlags");
4777 DumpImmutableScriptFlags(json, immutableFlags);
4778 json.endList();
4779
4780 json.beginObjectProperty("extent");
4781 json.property("sourceStart", extent.sourceStart);
4782 json.property("sourceEnd", extent.sourceEnd);
4783 json.property("toStringStart", extent.toStringStart);
4784 json.property("toStringEnd", extent.toStringEnd);
4785 json.property("lineno", extent.lineno);
4786 json.property("column", extent.column.oneOriginValue());
4787 json.endObject();
4788
4789 json.property("memberInitializers", memberInitializers_);
4790
4791 json.property("nargs", nargs);
4792 }
4793
4794 void SharedDataContainer::dump() const {
4795 js::Fprinter out(stderr);
4796 js::JSONPrinter json(out);
4797 dump(json);
4798 }
4799
4800 void SharedDataContainer::dump(js::JSONPrinter& json) const {
4801 json.beginObject();
4802 dumpFields(json);
4803 json.endObject();
4804 }
4805
4806 void SharedDataContainer::dumpFields(js::JSONPrinter& json) const {
4807 if (isEmpty()) {
4808 json.nullProperty("ScriptIndex(0)");
4809 return;
4810 }
4811
4812 if (isSingle()) {
4813 json.formatProperty("ScriptIndex(0)", "u8[%zu]",
4814 asSingle()->immutableDataLength());
4815 return;
4816 }
4817
4818 if (isVector()) {
4819 auto& vec = *asVector();
4820
4821 char index[64];
4822 for (size_t i = 0; i < vec.length(); i++) {
4823 SprintfLiteral(index, "ScriptIndex(%zu)", i);
4824 if (vec[i]) {
4825 json.formatProperty(index, "u8[%zu]", vec[i]->immutableDataLength());
4826 } else {
4827 json.nullProperty(index);
4828 }
4829 }
4830 return;
4831 }
4832
4833 if (isMap()) {
4834 auto& map = *asMap();
4835
4836 char index[64];
4837 for (auto iter = map.iter(); !iter.done(); iter.next()) {
4838 SprintfLiteral(index, "ScriptIndex(%u)", iter.get().key().index);
4839 json.formatProperty(index, "u8[%zu]",
4840 iter.get().value()->immutableDataLength());
4841 }
4842 return;
4843 }
4844
4845 MOZ_ASSERT(isBorrow());
4846 asBorrow()->dumpFields(json);
4847 }
4848
4849 struct DumpOptionsFields {
4850 js::JSONPrinter& json;
4851
4852 void operator()(const char* name, JS::AsmJSOption value) {
4853 const char* valueStr = nullptr;
4854 switch (value) {
4855 case JS::AsmJSOption::Enabled:
4856 valueStr = "JS::AsmJSOption::Enabled";
4857 break;
4858 case JS::AsmJSOption::DisabledByAsmJSPref:
4859 valueStr = "JS::AsmJSOption::DisabledByAsmJSPref";
4860 break;
4861 case JS::AsmJSOption::DisabledByLinker:
4862 valueStr = "JS::AsmJSOption::DisabledByLinker";
4863 break;
4864 case JS::AsmJSOption::DisabledByNoWasmCompiler:
4865 valueStr = "JS::AsmJSOption::DisabledByNoWasmCompiler";
4866 break;
4867 case JS::AsmJSOption::DisabledByDebugger:
4868 valueStr = "JS::AsmJSOption::DisabledByDebugger";
4869 break;
4870 }
4871 json.property(name, valueStr);
4872 }
4873
4874 void operator()(const char* name, JS::DelazificationOption value) {
4875 const char* valueStr = nullptr;
4876 switch (value) {
4877 # define SelectValueStr_(Strategy) \
4878 case JS::DelazificationOption::Strategy: \
4879 valueStr = "JS::DelazificationOption::" #Strategy; \
4880 break;
4881
4882 FOREACH_DELAZIFICATION_STRATEGY(SelectValueStr_)
4883 # undef SelectValueStr_
4884 }
4885 json.property(name, valueStr);
4886 }
4887
4888 void operator()(const char* name, char16_t* value) {}
4889
4890 void operator()(const char* name, bool value) { json.property(name, value); }
4891
4892 void operator()(const char* name, uint32_t value) {
4893 json.property(name, value);
4894 }
4895
4896 void operator()(const char* name, uint64_t value) {
4897 json.property(name, value);
4898 }
4899
4900 void operator()(const char* name, const char* value) {
4901 if (value) {
4902 json.property(name, value);
4903 return;
4904 }
4905 json.nullProperty(name);
4906 }
4907
4908 void operator()(const char* name, JS::ConstUTF8CharsZ value) {
4909 if (value) {
4910 json.property(name, value.c_str());
4911 return;
4912 }
4913 json.nullProperty(name);
4914 }
4915 };
4916
4917 static void DumpOptionsFields(js::JSONPrinter& json,
4918 const JS::ReadOnlyCompileOptions& options) {
4919 struct DumpOptionsFields printer{json};
4920 options.dumpWith(printer);
4921 }
4922
4923 static void DumpInputScopeFields(js::JSONPrinter& json,
4924 const InputScope& scope) {
4925 json.property("kind", ScopeKindString(scope.kind()));
4926
4927 InputScope enclosing = scope.enclosing();
4928 if (enclosing.isNull()) {
4929 json.nullProperty("enclosing");
4930 } else {
4931 json.beginObjectProperty("enclosing");
4932 DumpInputScopeFields(json, enclosing);
4933 json.endObject();
4934 }
4935 }
4936
4937 static void DumpInputScriptFields(js::JSONPrinter& json,
4938 const InputScript& script) {
4939 json.beginObjectProperty("extent");
4940 {
4941 SourceExtent extent = script.extent();
4942 json.property("sourceStart", extent.sourceStart);
4943 json.property("sourceEnd", extent.sourceEnd);
4944 json.property("toStringStart", extent.toStringStart);
4945 json.property("toStringEnd", extent.toStringEnd);
4946 json.property("lineno", extent.lineno);
4947 json.property("column", extent.column.oneOriginValue());
4948 }
4949 json.endObject();
4950
4951 json.beginListProperty("immutableFlags");
4952 DumpImmutableScriptFlags(json, script.immutableFlags());
4953 json.endList();
4954
4955 json.beginListProperty("functionFlags");
4956 DumpFunctionFlagsItems(json, script.functionFlags());
4957 json.endList();
4958
4959 json.property("hasPrivateScriptData", script.hasPrivateScriptData());
4960
4961 InputScope scope = script.enclosingScope();
4962 if (scope.isNull()) {
4963 json.nullProperty("enclosingScope");
4964 } else {
4965 json.beginObjectProperty("enclosingScope");
4966 DumpInputScopeFields(json, scope);
4967 json.endObject();
4968 }
4969
4970 if (script.useMemberInitializers()) {
4971 json.property("memberInitializers",
4972 script.getMemberInitializers().serialize());
4973 }
4974 }
4975
4976 void CompilationInput::dump() const {
4977 js::Fprinter out(stderr);
4978 js::JSONPrinter json(out);
4979 dump(json);
4980 out.put("\n");
4981 }
4982
4983 void CompilationInput::dump(js::JSONPrinter& json) const {
4984 json.beginObject();
4985 dumpFields(json);
4986 json.endObject();
4987 }
4988
4989 void CompilationInput::dumpFields(js::JSONPrinter& json) const {
4990 const char* targetStr = nullptr;
4991 switch (target) {
4992 case CompilationTarget::Global:
4993 targetStr = "CompilationTarget::Global";
4994 break;
4995 case CompilationTarget::SelfHosting:
4996 targetStr = "CompilationTarget::SelfHosting";
4997 break;
4998 case CompilationTarget::StandaloneFunction:
4999 targetStr = "CompilationTarget::StandaloneFunction";
5000 break;
5001 case CompilationTarget::StandaloneFunctionInNonSyntacticScope:
5002 targetStr = "CompilationTarget::StandaloneFunctionInNonSyntacticScope";
5003 break;
5004 case CompilationTarget::Eval:
5005 targetStr = "CompilationTarget::Eval";
5006 break;
5007 case CompilationTarget::Module:
5008 targetStr = "CompilationTarget::Module";
5009 break;
5010 case CompilationTarget::Delazification:
5011 targetStr = "CompilationTarget::Delazification";
5012 break;
5013 }
5014 json.property("target", targetStr);
5015
5016 json.beginObjectProperty("options");
5017 DumpOptionsFields(json, options);
5018 json.endObject();
5019
5020 if (lazy_.isNull()) {
5021 json.nullProperty("lazy_");
5022 } else {
5023 json.beginObjectProperty("lazy_");
5024 DumpInputScriptFields(json, lazy_);
5025 json.endObject();
5026 }
5027
5028 if (enclosingScope.isNull()) {
5029 json.nullProperty("enclosingScope");
5030 } else {
5031 json.beginObjectProperty("enclosingScope");
5032 DumpInputScopeFields(json, enclosingScope);
5033 json.endObject();
5034 }
5035
5036 // TODO: Support printing the atomCache and the source fields.
5037 }
5038
5039 void CompilationStencil::dump() const {
5040 js::Fprinter out(stderr);
5041 js::JSONPrinter json(out);
5042 dump(json);
5043 out.put("\n");
5044 }
5045
5046 void CompilationStencil::dump(js::JSONPrinter& json) const {
5047 json.beginObject();
5048 dumpFields(json);
5049 json.endObject();
5050 }
5051
5052 void CompilationStencil::dumpFields(js::JSONPrinter& json) const {
5053 char index[64];
5054
5055 json.beginObjectProperty("scriptData");
5056 for (size_t i = 0; i < scriptData.size(); i++) {
5057 SprintfLiteral(index, "ScriptIndex(%zu)", i);
5058 json.beginObjectProperty(index);
5059 scriptData[i].dumpFields(json, this);
5060 json.endObject();
5061 }
5062 json.endObject();
5063
5064 json.beginObjectProperty("scriptExtra");
5065 for (size_t i = 0; i < scriptExtra.size(); i++) {
5066 SprintfLiteral(index, "ScriptIndex(%zu)", i);
5067 json.beginObjectProperty(index);
5068 scriptExtra[i].dumpFields(json);
5069 json.endObject();
5070 }
5071 json.endObject();
5072
5073 json.beginObjectProperty("scopeData");
5074 MOZ_ASSERT(scopeData.size() == scopeNames.size());
5075 for (size_t i = 0; i < scopeData.size(); i++) {
5076 SprintfLiteral(index, "ScopeIndex(%zu)", i);
5077 json.beginObjectProperty(index);
5078 scopeData[i].dumpFields(json, scopeNames[i], this);
5079 json.endObject();
5080 }
5081 json.endObject();
5082
5083 json.beginObjectProperty("sharedData");
5084 sharedData.dumpFields(json);
5085 json.endObject();
5086
5087 json.beginObjectProperty("regExpData");
5088 for (size_t i = 0; i < regExpData.size(); i++) {
5089 SprintfLiteral(index, "RegExpIndex(%zu)", i);
5090 json.beginObjectProperty(index);
5091 regExpData[i].dumpFields(json, this);
5092 json.endObject();
5093 }
5094 json.endObject();
5095
5096 json.beginObjectProperty("bigIntData");
5097 for (size_t i = 0; i < bigIntData.size(); i++) {
5098 SprintfLiteral(index, "BigIntIndex(%zu)", i);
5099 GenericPrinter& out = json.beginStringProperty(index);
5100 bigIntData[i].dumpCharsNoQuote(out);
5101 json.endStringProperty();
5102 }
5103 json.endObject();
5104
5105 json.beginObjectProperty("objLiteralData");
5106 for (size_t i = 0; i < objLiteralData.size(); i++) {
5107 SprintfLiteral(index, "ObjLiteralIndex(%zu)", i);
5108 json.beginObjectProperty(index);
5109 objLiteralData[i].dumpFields(json, this);
5110 json.endObject();
5111 }
5112 json.endObject();
5113
5114 if (moduleMetadata) {
5115 json.beginObjectProperty("moduleMetadata");
5116 moduleMetadata->dumpFields(json, this);
5117 json.endObject();
5118 }
5119
5120 json.beginObjectProperty("asmJS");
5121 if (asmJS) {
5122 for (auto iter = asmJS->moduleMap.iter(); !iter.done(); iter.next()) {
5123 SprintfLiteral(index, "ScriptIndex(%u)", iter.get().key().index);
5124 json.formatProperty(index, "asm.js");
5125 }
5126 }
5127 json.endObject();
5128 }
5129
5130 void CompilationStencil::dumpAtom(TaggedParserAtomIndex index) const {
5131 js::Fprinter out(stderr);
5132 js::JSONPrinter json(out);
5133 json.beginObject();
5134 DumpTaggedParserAtomIndex(json, index, this);
5135 json.endObject();
5136 }
5137
5138 void ExtensibleCompilationStencil::dump() {
5139 frontend::BorrowingCompilationStencil borrowingStencil(*this);
5140 borrowingStencil.dump();
5141 }
5142
5143 void ExtensibleCompilationStencil::dump(js::JSONPrinter& json) {
5144 frontend::BorrowingCompilationStencil borrowingStencil(*this);
5145 borrowingStencil.dump(json);
5146 }
5147
5148 void ExtensibleCompilationStencil::dumpFields(js::JSONPrinter& json) {
5149 frontend::BorrowingCompilationStencil borrowingStencil(*this);
5150 borrowingStencil.dumpFields(json);
5151 }
5152
5153 void ExtensibleCompilationStencil::dumpAtom(TaggedParserAtomIndex index) {
5154 frontend::BorrowingCompilationStencil borrowingStencil(*this);
5155 borrowingStencil.dumpAtom(index);
5156 }
5157
5158 void InitialStencilAndDelazifications::dump() const {
5159 js::Fprinter out(stderr);
5160 js::JSONPrinter json(out);
5161 dump(json);
5162 out.put("\n");
5163 }
5164
5165 void InitialStencilAndDelazifications::dump(js::JSONPrinter& json) const {
5166 json.beginObject();
5167 dumpFields(json);
5168 json.endObject();
5169 }
5170
5171 void InitialStencilAndDelazifications::dumpFields(js::JSONPrinter& json) const {
5172 if (initial_) {
5173 json.beginObjectProperty("initial_");
5174 initial_->dumpFields(json);
5175 json.endObject();
5176 } else {
5177 json.nullProperty("initial_");
5178 }
5179
5180 for (size_t i = 0; i < delazifications_.length(); i++) {
5181 const CompilationStencil* delazification = delazifications_[i];
5182
5183 char index[64];
5184 SprintfLiteral(index, "ScriptIndex(%zu)", i + 1);
5185
5186 if (delazification) {
5187 json.beginObjectProperty(index);
5188 delazification->dumpFields(json);
5189 json.endObject();
5190 } else {
5191 json.nullProperty(index);
5192 }
5193 }
5194 }
5195
5196 #endif // defined(DEBUG) || defined(JS_JITSPEW)
5197
5198 JSString* CompilationAtomCache::getExistingStringAt(
5199 ParserAtomIndex index) const {
5200 MOZ_RELEASE_ASSERT(atoms_.length() >= index);
5201 return atoms_[index];
5202 }
5203
5204 JSString* CompilationAtomCache::getExistingStringAt(
5205 JSContext* cx, TaggedParserAtomIndex taggedIndex) const {
5206 if (taggedIndex.isParserAtomIndex()) {
5207 auto index = taggedIndex.toParserAtomIndex();
5208 return getExistingStringAt(index);
5209 }
5210
5211 if (taggedIndex.isWellKnownAtomId()) {
5212 auto index = taggedIndex.toWellKnownAtomId();
5213 return GetWellKnownAtom(cx, index);
5214 }
5215
5216 if (taggedIndex.isLength1StaticParserString()) {
5217 auto index = taggedIndex.toLength1StaticParserString();
5218 return cx->staticStrings().getUnit(char16_t(index));
5219 }
5220
5221 if (taggedIndex.isLength2StaticParserString()) {
5222 auto index = taggedIndex.toLength2StaticParserString();
5223 return cx->staticStrings().getLength2FromIndex(size_t(index));
5224 }
5225
5226 MOZ_ASSERT(taggedIndex.isLength3StaticParserString());
5227 auto index = taggedIndex.toLength3StaticParserString();
5228 return cx->staticStrings().getUint(uint32_t(index));
5229 }
5230
5231 JSString* CompilationAtomCache::getStringAt(ParserAtomIndex index) const {
5232 if (size_t(index) >= atoms_.length()) {
5233 return nullptr;
5234 }
5235 return atoms_[index];
5236 }
5237
5238 JSAtom* CompilationAtomCache::getExistingAtomAt(ParserAtomIndex index) const {
5239 return &getExistingStringAt(index)->asAtom();
5240 }
5241
5242 JSAtom* CompilationAtomCache::getExistingAtomAt(
5243 JSContext* cx, TaggedParserAtomIndex taggedIndex) const {
5244 return &getExistingStringAt(cx, taggedIndex)->asAtom();
5245 }
5246
5247 JSAtom* CompilationAtomCache::getAtomAt(ParserAtomIndex index) const {
5248 if (size_t(index) >= atoms_.length()) {
5249 return nullptr;
5250 }
5251 if (!atoms_[index]) {
5252 return nullptr;
5253 }
5254 return &atoms_[index]->asAtom();
5255 }
5256
5257 bool CompilationAtomCache::hasAtomAt(ParserAtomIndex index) const {
5258 if (size_t(index) >= atoms_.length()) {
5259 return false;
5260 }
5261 return !!atoms_[index];
5262 }
5263
5264 bool CompilationAtomCache::setAtomAt(FrontendContext* fc, ParserAtomIndex index,
5265 JSString* atom) {
5266 if (size_t(index) < atoms_.length()) {
5267 atoms_[index] = atom;
5268 return true;
5269 }
5270
5271 if (!atoms_.resize(size_t(index) + 1)) {
5272 ReportOutOfMemory(fc);
5273 return false;
5274 }
5275
5276 atoms_[index] = atom;
5277 return true;
5278 }
5279
5280 bool CompilationAtomCache::allocate(FrontendContext* fc, size_t length) {
5281 MOZ_ASSERT(length >= atoms_.length());
5282 if (length == atoms_.length()) {
5283 return true;
5284 }
5285
5286 if (!atoms_.resize(length)) {
5287 ReportOutOfMemory(fc);
5288 return false;
5289 }
5290
5291 return true;
5292 }
5293
5294 void CompilationAtomCache::stealBuffer(AtomCacheVector& atoms) {
5295 atoms_ = std::move(atoms);
5296 // Destroy elements, without unreserving.
5297 atoms_.clear();
5298 }
5299
5300 void CompilationAtomCache::releaseBuffer(AtomCacheVector& atoms) {
5301 atoms = std::move(atoms_);
5302 }
5303
5304 bool CompilationState::allocateGCThingsUninitialized(
5305 FrontendContext* fc, ScriptIndex scriptIndex, size_t length,
5306 TaggedScriptThingIndex** cursor) {
5307 MOZ_ASSERT(gcThingData.length() <= UINT32_MAX);
5308
5309 auto gcThingsOffset = CompilationGCThingIndex(gcThingData.length());
5310
5311 if (length > INDEX_LIMIT) {
5312 ReportAllocationOverflow(fc);
5313 return false;
5314 }
5315 uint32_t gcThingsLength = length;
5316
5317 if (!gcThingData.growByUninitialized(length)) {
5318 js::ReportOutOfMemory(fc);
5319 return false;
5320 }
5321
5322 if (gcThingData.length() > UINT32_MAX) {
5323 ReportAllocationOverflow(fc);
5324 return false;
5325 }
5326
5327 ScriptStencil& script = scriptData[scriptIndex];
5328 script.gcThingsOffset = gcThingsOffset;
5329 script.gcThingsLength = gcThingsLength;
5330
5331 *cursor = gcThingData.begin() + gcThingsOffset;
5332 return true;
5333 }
5334
5335 bool CompilationState::appendScriptStencilAndData(FrontendContext* fc) {
5336 if (!scriptData.emplaceBack()) {
5337 js::ReportOutOfMemory(fc);
5338 return false;
5339 }
5340
5341 if (isInitialStencil()) {
5342 if (!scriptExtra.emplaceBack()) {
5343 scriptData.popBack();
5344 MOZ_ASSERT(scriptData.length() == scriptExtra.length());
5345
5346 js::ReportOutOfMemory(fc);
5347 return false;
5348 }
5349 }
5350
5351 return true;
5352 }
5353
5354 bool CompilationState::appendGCThings(
5355 FrontendContext* fc, ScriptIndex scriptIndex,
5356 mozilla::Span<const TaggedScriptThingIndex> things) {
5357 MOZ_ASSERT(gcThingData.length() <= UINT32_MAX);
5358
5359 auto gcThingsOffset = CompilationGCThingIndex(gcThingData.length());
5360
5361 if (things.size() > INDEX_LIMIT) {
5362 ReportAllocationOverflow(fc);
5363 return false;
5364 }
5365 uint32_t gcThingsLength = uint32_t(things.size());
5366
5367 if (!gcThingData.append(things.data(), things.size())) {
5368 js::ReportOutOfMemory(fc);
5369 return false;
5370 }
5371
5372 if (gcThingData.length() > UINT32_MAX) {
5373 ReportAllocationOverflow(fc);
5374 return false;
5375 }
5376
5377 ScriptStencil& script = scriptData[scriptIndex];
5378 script.gcThingsOffset = gcThingsOffset;
5379 script.gcThingsLength = gcThingsLength;
5380 return true;
5381 }
5382
5383 CompilationState::CompilationStatePosition CompilationState::getPosition() {
5384 return CompilationStatePosition{scriptData.length(),
5385 asmJS ? asmJS->moduleMap.count() : 0};
5386 }
5387
5388 void CompilationState::rewind(
5389 const CompilationState::CompilationStatePosition& pos) {
5390 if (asmJS && asmJS->moduleMap.count() != pos.asmJSCount) {
5391 for (size_t i = pos.scriptDataLength; i < scriptData.length(); i++) {
5392 asmJS->moduleMap.remove(ScriptIndex(i));
5393 }
5394 MOZ_ASSERT(asmJS->moduleMap.count() == pos.asmJSCount);
5395 }
5396 // scriptExtra is empty for delazification.
5397 if (scriptExtra.length()) {
5398 MOZ_ASSERT(scriptExtra.length() == scriptData.length());
5399 scriptExtra.shrinkTo(pos.scriptDataLength);
5400 }
5401 scriptData.shrinkTo(pos.scriptDataLength);
5402 }
5403
5404 void CompilationState::markGhost(
5405 const CompilationState::CompilationStatePosition& pos) {
5406 for (size_t i = pos.scriptDataLength; i < scriptData.length(); i++) {
5407 scriptData[i].setIsGhost();
5408 }
5409 }
5410
5411 ScriptIndex CompilationStencilMerger::getInitialScriptIndexFor(
5412 const CompilationStencil& delazification) const {
5413 auto maybeIndex =
5414 functionKeyToInitialScriptIndex_.get(delazification.functionKey);
5415 MOZ_ASSERT(maybeIndex);
5416 return *maybeIndex;
5417 }
5418
5419 template <typename T>
5420 bool FunctionKeyToScriptIndexMap::init(FrontendContext* fc,
5421 const T& scriptExtra,
5422 size_t scriptExtraSize) {
5423 if (!map_.reserve(scriptExtraSize - 1)) {
5424 ReportOutOfMemory(fc);
5425 return false;
5426 }
5427
5428 for (size_t i = 1; i < scriptExtraSize; i++) {
5429 const auto& extra = scriptExtra[i];
5430 auto key = extra.extent.toFunctionKey();
5431
5432 // There can be multiple ScriptStencilExtra with same extent if
5433 // the function is parsed multiple times because of rewind for
5434 // arrow function, and in that case the last one's index should be used.
5435 // Overwrite with the last one.
5436 //
5437 // Already reserved above, but OOMTest can hit failure mode in
5438 // HashTable::add.
5439 if (!map_.put(key, ScriptIndex(i))) {
5440 ReportOutOfMemory(fc);
5441 return false;
5442 }
5443 }
5444
5445 return true;
5446 }
5447
5448 bool FunctionKeyToScriptIndexMap::init(FrontendContext* fc,
5449 const CompilationStencil* initial) {
5450 return init(fc, initial->scriptExtra, initial->scriptExtra.size());
5451 }
5452
5453 bool FunctionKeyToScriptIndexMap::init(
5454 FrontendContext* fc, const ExtensibleCompilationStencil* initial) {
5455 return init(fc, initial->scriptExtra, initial->scriptExtra.length());
5456 }
5457
5458 mozilla::Maybe<ScriptIndex> FunctionKeyToScriptIndexMap::get(
5459 FunctionKey key) const {
5460 auto p = map_.readonlyThreadsafeLookup(key);
5461 if (!p) {
5462 return mozilla::Nothing();
5463 }
5464 return mozilla::Some(p->value());
5465 }
5466
5467 size_t FunctionKeyToScriptIndexMap::sizeOfExcludingThis(
5468 mozilla::MallocSizeOf mallocSizeOf) const {
5469 return map_.shallowSizeOfExcludingThis(mallocSizeOf);
5470 }
5471
5472 bool CompilationStencilMerger::buildAtomIndexMap(
5473 FrontendContext* fc, const CompilationStencil& delazification,
5474 AtomIndexMap& atomIndexMap) {
5475 uint32_t atomCount = delazification.parserAtomData.size();
5476 if (!atomIndexMap.reserve(atomCount)) {
5477 ReportOutOfMemory(fc);
5478 return false;
5479 }
5480 for (const auto& atom : delazification.parserAtomData) {
5481 auto mappedIndex = initial_->parserAtoms.internExternalParserAtom(fc, atom);
5482 if (!mappedIndex) {
5483 return false;
5484 }
5485 atomIndexMap.infallibleAppend(mappedIndex);
5486 }
5487 return true;
5488 }
5489
5490 bool CompilationStencilMerger::setInitial(
5491 FrontendContext* fc, UniquePtr<ExtensibleCompilationStencil>&& initial) {
5492 MOZ_ASSERT(!initial_);
5493
5494 initial_ = std::move(initial);
5495
5496 return functionKeyToInitialScriptIndex_.init(fc, initial_.get());
5497 }
5498
5499 template <typename GCThingIndexMapFunc, typename AtomIndexMapFunc,
5500 typename ScopeIndexMapFunc>
5501 static void MergeScriptStencil(ScriptStencil& dest, const ScriptStencil& src,
5502 GCThingIndexMapFunc mapGCThingIndex,
5503 AtomIndexMapFunc mapAtomIndex,
5504 ScopeIndexMapFunc mapScopeIndex,
5505 bool isTopLevel) {
5506 // If this function was lazy, all inner functions should have been lazy.
5507 MOZ_ASSERT(!dest.hasSharedData());
5508
5509 // If the inner lazy function is skipped, gcThingsLength is empty.
5510 if (src.gcThingsLength) {
5511 dest.gcThingsOffset = mapGCThingIndex(src.gcThingsOffset);
5512 dest.gcThingsLength = src.gcThingsLength;
5513 }
5514
5515 if (src.functionAtom) {
5516 dest.functionAtom = mapAtomIndex(src.functionAtom);
5517 }
5518
5519 if (!dest.hasLazyFunctionEnclosingScopeIndex() &&
5520 src.hasLazyFunctionEnclosingScopeIndex()) {
5521 // Both enclosing function and this function were lazy, and
5522 // now enclosing function is non-lazy and this function is still lazy.
5523 dest.setLazyFunctionEnclosingScopeIndex(
5524 mapScopeIndex(src.lazyFunctionEnclosingScopeIndex()));
5525 } else if (dest.hasLazyFunctionEnclosingScopeIndex() &&
5526 !src.hasLazyFunctionEnclosingScopeIndex()) {
5527 // The enclosing function was non-lazy and this function was lazy, and
5528 // now this function is non-lazy.
5529 dest.resetHasLazyFunctionEnclosingScopeIndexAfterStencilMerge();
5530 } else {
5531 // The enclosing function is still lazy.
5532 MOZ_ASSERT(!dest.hasLazyFunctionEnclosingScopeIndex());
5533 MOZ_ASSERT(!src.hasLazyFunctionEnclosingScopeIndex());
5534 }
5535
5536 #ifdef DEBUG
5537 uint16_t BASESCRIPT = uint16_t(FunctionFlags::Flags::BASESCRIPT);
5538 uint16_t HAS_INFERRED_NAME =
5539 uint16_t(FunctionFlags::Flags::HAS_INFERRED_NAME);
5540 uint16_t HAS_GUESSED_ATOM = uint16_t(FunctionFlags::Flags::HAS_GUESSED_ATOM);
5541 uint16_t acceptableDifferenceForLazy = HAS_INFERRED_NAME | HAS_GUESSED_ATOM;
5542 uint16_t acceptableDifferenceForNonLazy =
5543 BASESCRIPT | HAS_INFERRED_NAME | HAS_GUESSED_ATOM;
5544
5545 MOZ_ASSERT_IF(
5546 isTopLevel,
5547 (dest.functionFlags.toRaw() | acceptableDifferenceForNonLazy) ==
5548 (src.functionFlags.toRaw() | acceptableDifferenceForNonLazy));
5549
5550 // NOTE: Currently we don't delazify inner functions.
5551 MOZ_ASSERT_IF(!isTopLevel,
5552 (dest.functionFlags.toRaw() | acceptableDifferenceForLazy) ==
5553 (src.functionFlags.toRaw() | acceptableDifferenceForLazy));
5554 #endif // DEBUG
5555 dest.functionFlags = src.functionFlags;
5556
5557 // Other flags.
5558
5559 if (src.wasEmittedByEnclosingScript()) {
5560 // NOTE: the top-level function of the delazification have
5561 // src.wasEmittedByEnclosingScript() == false, and that shouldn't
5562 // be copied.
5563 dest.setWasEmittedByEnclosingScript();
5564 }
5565
5566 if (src.allowRelazify()) {
5567 dest.setAllowRelazify();
5568 }
5569
5570 if (src.hasSharedData()) {
5571 dest.setHasSharedData();
5572 }
5573 }
5574
5575 bool CompilationStencilMerger::addDelazification(
5576 FrontendContext* fc, const CompilationStencil& delazification) {
5577 MOZ_ASSERT(initial_);
5578
5579 auto delazifiedFunctionIndex = getInitialScriptIndexFor(delazification);
5580 auto& destFun = initial_->scriptData[delazifiedFunctionIndex];
5581
5582 if (destFun.hasSharedData()) {
5583 // If the function was already non-lazy, it means the following happened:
5584 // A. delazified twice within single collecting delazifications
5585 // 1. this function is lazily parsed
5586 // 2. collecting delazifications is started
5587 // 3. this function is delazified, encoded, and merged
5588 // 4. this function is relazified
5589 // 5. this function is delazified, encoded, and merged
5590 //
5591 // B. delazified twice across decode
5592 // 1. this function is lazily parsed
5593 // 2. collecting delazifications is started
5594 // 3. this function is delazified, encoded, and merged
5595 // 4. collecting delazifications is finished
5596 // 5. decoded
5597 // 6. collecting delazifications is started
5598 // here, this function is non-lazy
5599 // 7. this function is relazified
5600 // 8. this function is delazified, encoded, and merged
5601 //
5602 // A can happen with public API.
5603 //
5604 // B cannot happen with public API, but can happen if incremental
5605 // encoding at step B.6 is explicitly started by internal function.
5606 // See Evaluate and StartCollectingDelazifications in js/src/shell/js.cpp.
5607 return true;
5608 }
5609
5610 // If any failure happens, the initial stencil is left in the broken state.
5611 // Immediately discard it.
5612 auto failureCase = mozilla::MakeScopeExit([&] { initial_.reset(); });
5613
5614 mozilla::Maybe<ScopeIndex> functionEnclosingScope;
5615 if (destFun.hasLazyFunctionEnclosingScopeIndex()) {
5616 // lazyFunctionEnclosingScopeIndex_ can be Nothing if this is
5617 // top-level function.
5618 functionEnclosingScope =
5619 mozilla::Some(destFun.lazyFunctionEnclosingScopeIndex());
5620 }
5621
5622 // A map from ParserAtomIndex in delazification to TaggedParserAtomIndex
5623 // in initial_.
5624 AtomIndexMap atomIndexMap;
5625 if (!buildAtomIndexMap(fc, delazification, atomIndexMap)) {
5626 return false;
5627 }
5628 auto mapAtomIndex = [&](TaggedParserAtomIndex index) {
5629 if (index.isParserAtomIndex()) {
5630 return atomIndexMap[index.toParserAtomIndex()];
5631 }
5632
5633 return index;
5634 };
5635
5636 size_t gcThingOffset = initial_->gcThingData.length();
5637 size_t regExpOffset = initial_->regExpData.length();
5638 size_t bigIntOffset = initial_->bigIntData.length();
5639 size_t objLiteralOffset = initial_->objLiteralData.length();
5640 size_t scopeOffset = initial_->scopeData.length();
5641
5642 // Map delazification's ScriptIndex to initial's ScriptIndex.
5643 //
5644 // The lazy function's gcthings list stores inner function's ScriptIndex.
5645 // The n-th gcthing holds the ScriptIndex of the (n+1)-th script in
5646 // delazification.
5647 //
5648 // NOTE: Currently we don't delazify inner functions.
5649 auto lazyFunctionGCThingsOffset = destFun.gcThingsOffset;
5650 auto mapScriptIndex = [&](ScriptIndex index) {
5651 if (index == CompilationStencil::TopLevelIndex) {
5652 return delazifiedFunctionIndex;
5653 }
5654
5655 return initial_->gcThingData[lazyFunctionGCThingsOffset + index.index - 1]
5656 .toFunction();
5657 };
5658
5659 // Map other delazification's indices into initial's indices.
5660 auto mapGCThingIndex = [&](CompilationGCThingIndex offset) {
5661 return CompilationGCThingIndex(gcThingOffset + offset.index);
5662 };
5663 auto mapRegExpIndex = [&](RegExpIndex index) {
5664 return RegExpIndex(regExpOffset + index.index);
5665 };
5666 auto mapBigIntIndex = [&](BigIntIndex index) {
5667 return BigIntIndex(bigIntOffset + index.index);
5668 };
5669 auto mapObjLiteralIndex = [&](ObjLiteralIndex index) {
5670 return ObjLiteralIndex(objLiteralOffset + index.index);
5671 };
5672 auto mapScopeIndex = [&](ScopeIndex index) {
5673 return ScopeIndex(scopeOffset + index.index);
5674 };
5675
5676 // Append gcThingData, with mapping TaggedScriptThingIndex.
5677 if (!initial_->gcThingData.append(delazification.gcThingData.data(),
5678 delazification.gcThingData.size())) {
5679 js::ReportOutOfMemory(fc);
5680 return false;
5681 }
5682 for (size_t i = gcThingOffset; i < initial_->gcThingData.length(); i++) {
5683 auto& index = initial_->gcThingData[i];
5684 if (index.isNull()) {
5685 // Nothing to do.
5686 } else if (index.isAtom()) {
5687 index = TaggedScriptThingIndex(mapAtomIndex(index.toAtom()));
5688 } else if (index.isBigInt()) {
5689 index = TaggedScriptThingIndex(mapBigIntIndex(index.toBigInt()));
5690 } else if (index.isObjLiteral()) {
5691 index = TaggedScriptThingIndex(mapObjLiteralIndex(index.toObjLiteral()));
5692 } else if (index.isRegExp()) {
5693 index = TaggedScriptThingIndex(mapRegExpIndex(index.toRegExp()));
5694 } else if (index.isScope()) {
5695 index = TaggedScriptThingIndex(mapScopeIndex(index.toScope()));
5696 } else if (index.isFunction()) {
5697 index = TaggedScriptThingIndex(mapScriptIndex(index.toFunction()));
5698 } else {
5699 MOZ_ASSERT(index.isEmptyGlobalScope());
5700 // Nothing to do
5701 }
5702 }
5703
5704 // Append regExpData, with mapping RegExpStencil.atom_.
5705 if (!initial_->regExpData.append(delazification.regExpData.data(),
5706 delazification.regExpData.size())) {
5707 js::ReportOutOfMemory(fc);
5708 return false;
5709 }
5710 for (size_t i = regExpOffset; i < initial_->regExpData.length(); i++) {
5711 auto& data = initial_->regExpData[i];
5712 data.atom_ = mapAtomIndex(data.atom_);
5713 }
5714
5715 // Append bigIntData, with copying BigIntStencil.bigInt_.
5716 if (!initial_->bigIntData.reserve(bigIntOffset +
5717 delazification.bigIntData.size())) {
5718 js::ReportOutOfMemory(fc);
5719 return false;
5720 }
5721 for (const auto& data : delazification.bigIntData) {
5722 initial_->bigIntData.infallibleEmplaceBack();
5723 if (!initial_->bigIntData.back().init(fc, initial_->alloc, data)) {
5724 return false;
5725 }
5726 }
5727
5728 // Append objLiteralData, with copying ObjLiteralStencil.code_, and mapping
5729 // TaggedParserAtomIndex in it.
5730 if (!initial_->objLiteralData.reserve(objLiteralOffset +
5731 delazification.objLiteralData.size())) {
5732 js::ReportOutOfMemory(fc);
5733 return false;
5734 }
5735 for (const auto& data : delazification.objLiteralData) {
5736 size_t length = data.code().size();
5737 auto* code = initial_->alloc.newArrayUninitialized<uint8_t>(length);
5738 if (!code) {
5739 js::ReportOutOfMemory(fc);
5740 return false;
5741 }
5742 memcpy(code, data.code().data(), length);
5743
5744 ObjLiteralModifier modifier(mozilla::Span(code, length));
5745 modifier.mapAtom(mapAtomIndex);
5746
5747 initial_->objLiteralData.infallibleEmplaceBack(
5748 code, length, data.kind(), data.flags(), data.propertyCount());
5749 }
5750
5751 // Append scopeData, with mapping indices in ScopeStencil fields.
5752 // And append scopeNames, with copying the entire data, and mapping
5753 // trailingNames.
5754 if (!initial_->scopeData.reserve(scopeOffset +
5755 delazification.scopeData.size())) {
5756 js::ReportOutOfMemory(fc);
5757 return false;
5758 }
5759 if (!initial_->scopeNames.reserve(scopeOffset +
5760 delazification.scopeNames.size())) {
5761 js::ReportOutOfMemory(fc);
5762 return false;
5763 }
5764 for (size_t i = 0; i < delazification.scopeData.size(); i++) {
5765 const auto& srcData = delazification.scopeData[i];
5766 const auto* srcNames = delazification.scopeNames[i];
5767
5768 mozilla::Maybe<ScriptIndex> functionIndex = mozilla::Nothing();
5769 if (srcData.isFunction()) {
5770 // Inner functions should be in the same order as initial, beginning from
5771 // the delazification's index.
5772 functionIndex = mozilla::Some(mapScriptIndex(srcData.functionIndex()));
5773 }
5774
5775 BaseParserScopeData* destNames = nullptr;
5776 if (srcNames) {
5777 destNames = CopyScopeData(fc, initial_->alloc, srcData.kind(), srcNames);
5778 if (!destNames) {
5779 return false;
5780 }
5781 auto trailingNames =
5782 GetParserScopeDataTrailingNames(srcData.kind(), destNames);
5783 for (auto& name : trailingNames) {
5784 if (name.name()) {
5785 name.updateNameAfterStencilMerge(mapAtomIndex(name.name()));
5786 }
5787 }
5788 }
5789
5790 initial_->scopeData.infallibleEmplaceBack(
5791 srcData.kind(),
5792 srcData.hasEnclosing()
5793 ? mozilla::Some(mapScopeIndex(srcData.enclosing()))
5794 : functionEnclosingScope,
5795 srcData.firstFrameSlot(),
5796 srcData.hasEnvironmentShape()
5797 ? mozilla::Some(srcData.numEnvironmentSlots())
5798 : mozilla::Nothing(),
5799 functionIndex, srcData.isArrow());
5800
5801 initial_->scopeNames.infallibleEmplaceBack(destNames);
5802 }
5803
5804 // Add delazified function's shared data.
5805 //
5806 // NOTE: Currently we don't delazify inner functions.
5807 if (!initial_->sharedData.addExtraWithoutShare(
5808 fc, delazifiedFunctionIndex,
5809 delazification.sharedData.get(CompilationStencil::TopLevelIndex))) {
5810 return false;
5811 }
5812
5813 // Update scriptData, with mapping indices in ScriptStencil fields.
5814 for (uint32_t i = 0; i < delazification.scriptData.size(); i++) {
5815 auto destIndex = mapScriptIndex(ScriptIndex(i));
5816 MergeScriptStencil(initial_->scriptData[destIndex],
5817 delazification.scriptData[i], mapGCThingIndex,
5818 mapAtomIndex, mapScopeIndex,
5819 i == CompilationStencil::TopLevelIndex);
5820 }
5821
5822 // WARNING: moduleMetadata and asmJS fields are known at script/module
5823 // top-level parsing, any mutation made in this function should be reflected
5824 // to ExtensibleCompilationStencil::steal and CompilationStencil::clone.
5825
5826 // Function shouldn't be a module.
5827 MOZ_ASSERT(!delazification.moduleMetadata);
5828
5829 // asm.js shouldn't appear inside delazification, given asm.js forces
5830 // full-parse.
5831 MOZ_ASSERT(!delazification.hasAsmJS());
5832
5833 failureCase.release();
5834 return true;
5835 }
5836
5837 bool CompilationStencilMerger::maybeAddDelazification(
5838 FrontendContext* fc, const CompilationStencil& delazification) {
5839 auto delazifiedFunctionIndex = getInitialScriptIndexFor(delazification);
5840 auto& destFun = initial_->scriptData[delazifiedFunctionIndex];
5841
5842 if (!destFun.hasLazyFunctionEnclosingScopeIndex()) {
5843 // The enclosing function is still lazy, and this inner function cannot
5844 // be added.
5845 return true;
5846 }
5847
5848 return addDelazification(fc, delazification);
5849 }
5850
5851 void CompilationStencil::AddRef() { refCount_++; }
5852 void CompilationStencil::Release() {
5853 MOZ_RELEASE_ASSERT(refCount_ > 0);
5854 if (--refCount_ == 0) {
5855 js_delete(this);
5856 }
5857 }
5858
5859 void JS::StencilAddRef(JS::Stencil* stencil) { stencil->AddRef(); }
5860 void JS::StencilRelease(JS::Stencil* stencil) { stencil->Release(); }
5861
5862 JS_PUBLIC_API JSScript* JS::InstantiateGlobalStencil(
5863 JSContext* cx, const JS::InstantiateOptions& options, JS::Stencil* stencil,
5864 JS::InstantiationStorage* storage) {
5865 MOZ_ASSERT_IF(storage, storage->isValid());
5866
5867 CompileOptions compileOptions(cx);
5868 options.copyTo(compileOptions);
5869 Rooted<CompilationInput> input(cx, CompilationInput(compileOptions));
5870 Rooted<CompilationGCOutput> gcOutput(cx);
5871 if (storage) {
5872 gcOutput.get().steal(std::move(*storage->gcOutput_));
5873 }
5874
5875 if (!InstantiateStencils(cx, input.get(), *stencil, gcOutput.get())) {
5876 return nullptr;
5877 }
5878 return gcOutput.get().script;
5879 }
5880
5881 JS_PUBLIC_API bool JS::StencilIsBorrowed(JS::Stencil* stencil) {
5882 return stencil->getInitial()->storageType ==
5883 CompilationStencil::StorageType::Borrowed;
5884 }
5885
5886 JS_PUBLIC_API JSObject* JS::InstantiateModuleStencil(
5887 JSContext* cx, const JS::InstantiateOptions& options, JS::Stencil* stencil,
5888 JS::InstantiationStorage* storage) {
5889 MOZ_ASSERT_IF(storage, storage->isValid());
5890
5891 CompileOptions compileOptions(cx);
5892 options.copyTo(compileOptions);
5893 compileOptions.setModule();
5894 Rooted<CompilationInput> input(cx, CompilationInput(compileOptions));
5895 Rooted<CompilationGCOutput> gcOutput(cx);
5896 if (storage) {
5897 gcOutput.get().steal(std::move(*storage->gcOutput_));
5898 }
5899
5900 if (!InstantiateStencils(cx, input.get(), *stencil, gcOutput.get())) {
5901 return nullptr;
5902 }
5903 return gcOutput.get().module;
5904 }
5905
5906 JS_PUBLIC_API size_t JS::SizeOfStencil(Stencil* stencil,
5907 mozilla::MallocSizeOf mallocSizeOf) {
5908 return stencil->sizeOfIncludingThis(mallocSizeOf);
5909 }
5910
5911 JS::InstantiationStorage::~InstantiationStorage() {
5912 if (gcOutput_) {
5913 js_delete(gcOutput_);
5914 gcOutput_ = nullptr;
5915 }
5916 }
5917
5918 bool JS::IsStencilCacheable(JS::Stencil* stencil) {
5919 if (stencil->hasAsmJS()) {
5920 return false;
5921 }
5922
5923 return true;
5924 }