Debian Codegraph @

js/src/vm/JSScript.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 /*
8 * JS script operations.
9 */
10
11 #include "vm/JSScript-inl.h"
12
13 #include "mozilla/ArrayUtils.h"
14 #include "mozilla/CheckedInt.h"
15 #include "mozilla/DebugOnly.h"
16 #include "mozilla/Maybe.h"
17 #include "mozilla/MemoryReporting.h"
18 #include "mozilla/ScopeExit.h"
19 #include "mozilla/Span.h" // mozilla::{Span,Span}
20 #include "mozilla/Sprintf.h"
21 #include "mozilla/Utf8.h"
22 #include "mozilla/Vector.h"
23
24 #include <algorithm>
25 #include <new>
26 #include <string.h>
27 #include <type_traits>
28 #include <utility>
29
30 #include "jstypes.h"
31
32 #include "frontend/BytecodeSection.h"
33 #include "frontend/CompilationStencil.h" // frontend::CompilationStencil, frontend::InitialStencilAndDelazifications
34 #include "frontend/FrontendContext.h" // AutoReportFrontendContext
35 #include "frontend/ParseContext.h"
36 #include "frontend/SourceNotes.h" // SrcNote, SrcNoteType, SrcNoteIterator
37 #include "frontend/Stencil.h" // DumpFunctionFlagsItems, DumpImmutableScriptFlags
38 #include "frontend/StencilXdr.h" // XDRStencilEncoder
39 #include "gc/GCContext.h"
40 #include "jit/BaselineJIT.h"
41 #include "jit/CacheIRHealth.h"
42 #include "jit/Ion.h"
43 #include "jit/IonScript.h"
44 #include "jit/JitCode.h"
45 #include "jit/JitOptions.h"
46 #include "jit/JitRuntime.h"
47 #include "js/CharacterEncoding.h" // JS_EncodeStringToUTF8
48 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::ColumnNumberOneOrigin, JS::ColumnNumberOffset
49 #include "js/CompileOptions.h"
50 #include "js/experimental/SourceHook.h"
51 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
52 #include "js/HeapAPI.h" // JS::GCCellPtr
53 #include "js/MemoryMetrics.h"
54 #include "js/Printer.h" // js::GenericPrinter, js::Fprinter, js::Sprinter, js::QuoteString
55 #include "js/Transcoding.h"
56 #include "js/UniquePtr.h"
57 #include "js/Utility.h" // JS::UniqueChars
58 #include "js/Value.h" // JS::Value
59 #include "util/Poison.h"
60 #include "util/StringBuilder.h"
61 #include "util/Text.h"
62 #include "vm/BigIntType.h" // JS::BigInt
63 #include "vm/BytecodeIterator.h"
64 #include "vm/BytecodeLocation.h"
65 #include "vm/BytecodeUtil.h" // Disassemble
66 #include "vm/Compression.h"
67 #include "vm/HelperThreadState.h" // js::RunPendingSourceCompressions
68 #include "vm/JSFunction.h"
69 #include "vm/JSObject.h"
70 #include "vm/JSONPrinter.h" // JSONPrinter
71 #include "vm/Opcodes.h"
72 #include "vm/PortableBaselineInterpret.h"
73 #include "vm/Scope.h" // Scope
74 #include "vm/SharedImmutableStringsCache.h"
75 #include "vm/StencilEnums.h" // TryNote, TryNoteKind, ScopeNote
76 #include "vm/StringType.h" // JSString, JSAtom
77 #include "vm/Time.h" // AutoIncrementalTimer
78 #include "vm/ToSource.h" // JS::ValueToSource
79 #ifdef MOZ_VTUNE
80 # include "vtune/VTuneWrapper.h"
81 #endif
82
83 #include "gc/Marking-inl.h"
84 #include "vm/BytecodeIterator-inl.h"
85 #include "vm/BytecodeLocation-inl.h"
86 #include "vm/Compartment-inl.h"
87 #include "vm/JSContext-inl.h"
88 #include "vm/JSObject-inl.h"
89 #include "vm/SharedImmutableStringsCache-inl.h"
90 #include "vm/Stack-inl.h"
91
92 using namespace js;
93
94 using mozilla::CheckedInt;
95 using mozilla::Maybe;
96 using mozilla::PointerRangeSize;
97 using mozilla::Utf8Unit;
98
99 using JS::ReadOnlyCompileOptions;
100 using JS::SourceText;
101
102 bool js::BaseScript::isUsingInterpreterTrampoline(JSRuntime* rt) const {
103 return jitCodeRaw() == rt->jitRuntime()->interpreterStub().value;
104 }
105
106 js::ScriptSource* js::BaseScript::maybeForwardedScriptSource() const {
107 return MaybeForwarded(sourceObject())->source();
108 }
109
110 void js::BaseScript::setEnclosingScript(BaseScript* enclosingScript) {
111 MOZ_ASSERT(enclosingScript);
112 warmUpData_.initEnclosingScript(enclosingScript);
113 }
114
115 void js::BaseScript::setEnclosingScope(Scope* enclosingScope) {
116 if (warmUpData_.isEnclosingScript()) {
117 warmUpData_.clearEnclosingScript();
118 }
119
120 MOZ_ASSERT(enclosingScope);
121 warmUpData_.initEnclosingScope(enclosingScope);
122 }
123
124 void js::BaseScript::finalize(JS::GCContext* gcx) {
125 // Scripts with bytecode may have optional data stored in per-runtime or
126 // per-zone maps. Note that a failed compilation must not have entries since
127 // the script itself will not be marked as having bytecode.
128 if (hasBytecode()) {
129 JSScript* script = this->asJSScript();
130
131 if (coverage::IsLCovEnabled()) {
132 coverage::CollectScriptCoverage(script, true);
133 }
134
135 script->destroyScriptCounts();
136 }
137
138 {
139 JSRuntime* rt = gcx->runtime();
140 if (rt->hasJitRuntime() && rt->jitRuntime()->hasInterpreterEntryMap()) {
141 rt->jitRuntime()->getInterpreterEntryMap()->remove(this);
142 }
143
144 rt->geckoProfiler().onScriptFinalized(this);
145 }
146
147 #ifdef MOZ_VTUNE
148 if (zone()->scriptVTuneIdMap) {
149 // Note: we should only get here if the VTune JIT profiler is running.
150 zone()->scriptVTuneIdMap->remove(this);
151 }
152 #endif
153
154 if (warmUpData_.isJitScript()) {
155 JSScript* script = this->asJSScript();
156 #ifdef JS_CACHEIR_SPEW
157 maybeUpdateWarmUpCount(script);
158 #endif
159 script->releaseJitScriptOnFinalize(gcx);
160 }
161
162 #ifdef JS_CACHEIR_SPEW
163 if (hasBytecode()) {
164 maybeSpewScriptFinalWarmUpCount(this->asJSScript());
165 }
166 #endif
167
168 if (data_) {
169 // We don't need to triger any barriers here, just free the memory.
170 size_t size = data_->allocationSize();
171 AlwaysPoison(data_, JS_POISONED_JSSCRIPT_DATA_PATTERN, size,
172 MemCheckKind::MakeNoAccess);
173 gcx->free_(this, data_, size, MemoryUse::ScriptPrivateData);
174 }
175
176 freeSharedData();
177 }
178
179 js::Scope* js::BaseScript::releaseEnclosingScope() {
180 Scope* enclosing = warmUpData_.toEnclosingScope();
181 warmUpData_.clearEnclosingScope();
182 return enclosing;
183 }
184
185 void js::BaseScript::swapData(UniquePtr<PrivateScriptData>& other) {
186 if (data_) {
187 RemoveCellMemory(this, data_->allocationSize(),
188 MemoryUse::ScriptPrivateData);
189 }
190
191 PrivateScriptData* old = data_;
192 data_.set(zone(), other.release());
193 other.reset(old);
194
195 if (data_) {
196 AddCellMemory(this, data_->allocationSize(), MemoryUse::ScriptPrivateData);
197 }
198 }
199
200 js::Scope* js::BaseScript::enclosingScope() const {
201 MOZ_ASSERT(!warmUpData_.isEnclosingScript(),
202 "Enclosing scope is not computed yet");
203
204 if (warmUpData_.isEnclosingScope()) {
205 return warmUpData_.toEnclosingScope();
206 }
207
208 MOZ_ASSERT(data_, "Script doesn't seem to be compiled");
209
210 return gcthings()[js::GCThingIndex::outermostScopeIndex()]
211 .as<Scope>()
212 .enclosing();
213 }
214
215 size_t JSScript::numAlwaysLiveFixedSlots() const {
216 if (bodyScope()->is<js::FunctionScope>()) {
217 return bodyScope()->as<js::FunctionScope>().nextFrameSlot();
218 }
219 if (bodyScope()->is<js::ModuleScope>()) {
220 return bodyScope()->as<js::ModuleScope>().nextFrameSlot();
221 }
222 if (bodyScope()->is<js::EvalScope>() &&
223 bodyScope()->kind() == ScopeKind::StrictEval) {
224 return bodyScope()->as<js::EvalScope>().nextFrameSlot();
225 }
226 return 0;
227 }
228
229 unsigned JSScript::numArgs() const {
230 if (bodyScope()->is<js::FunctionScope>()) {
231 return bodyScope()->as<js::FunctionScope>().numPositionalFormalParameters();
232 }
233 return 0;
234 }
235
236 bool JSScript::functionHasParameterExprs() const {
237 // Only functions have parameters.
238 js::Scope* scope = bodyScope();
239 if (!scope->is<js::FunctionScope>()) {
240 return false;
241 }
242 return scope->as<js::FunctionScope>().hasParameterExprs();
243 }
244
245 bool JSScript::isModule() const { return bodyScope()->is<js::ModuleScope>(); }
246
247 js::ModuleObject* JSScript::module() const {
248 MOZ_ASSERT(isModule());
249 return bodyScope()->as<js::ModuleScope>().module();
250 }
251
252 bool JSScript::isGlobalCode() const {
253 return bodyScope()->is<js::GlobalScope>();
254 }
255
256 js::VarScope* JSScript::functionExtraBodyVarScope() const {
257 MOZ_ASSERT(functionHasExtraBodyVarScope());
258 for (JS::GCCellPtr gcThing : gcthings()) {
259 if (!gcThing.is<js::Scope>()) {
260 continue;
261 }
262 js::Scope* scope = &gcThing.as<js::Scope>();
263 if (scope->kind() == js::ScopeKind::FunctionBodyVar) {
264 return &scope->as<js::VarScope>();
265 }
266 }
267 MOZ_CRASH("Function extra body var scope not found");
268 }
269
270 bool JSScript::needsBodyEnvironment() const {
271 for (JS::GCCellPtr gcThing : gcthings()) {
272 if (!gcThing.is<js::Scope>()) {
273 continue;
274 }
275 js::Scope* scope = &gcThing.as<js::Scope>();
276 if (ScopeKindIsInBody(scope->kind()) && scope->hasEnvironment()) {
277 return true;
278 }
279 }
280 return false;
281 }
282
283 bool JSScript::isDirectEvalInFunction() const {
284 if (!isForEval()) {
285 return false;
286 }
287 return bodyScope()->hasOnChain(js::ScopeKind::Function);
288 }
289
290 // Initialize the optional arrays in the trailing allocation. This is a set of
291 // offsets that delimit each optional array followed by the arrays themselves.
292 // See comment before 'ImmutableScriptData' for more details.
293 void ImmutableScriptData::initOptionalArrays(Offset* pcursor,
294 uint32_t numResumeOffsets,
295 uint32_t numScopeNotes,
296 uint32_t numTryNotes) {
297 Offset cursor = (*pcursor);
298
299 // The byte arrays must have already been padded.
300 MOZ_ASSERT(isAlignedOffset<CodeNoteAlign>(cursor),
301 "Bytecode and source notes should be padded to keep alignment");
302
303 // Each non-empty optional array needs will need an offset to its end.
304 unsigned numOptionalArrays = unsigned(numResumeOffsets > 0) +
305 unsigned(numScopeNotes > 0) +
306 unsigned(numTryNotes > 0);
307
308 // Default-initialize the optional-offsets.
309 initElements<Offset>(cursor, numOptionalArrays);
310 cursor += numOptionalArrays * sizeof(Offset);
311
312 // Offset between optional-offsets table and the optional arrays. This is
313 // later used to access the optional-offsets table as well as first optional
314 // array.
315 optArrayOffset_ = cursor;
316
317 // Each optional array that follows must store an end-offset in the offset
318 // table. Assign table entries by using this 'offsetIndex'. The index 0 is
319 // reserved for implicit value 'optArrayOffset'.
320 int offsetIndex = 0;
321
322 // Default-initialize optional 'resumeOffsets'.
323 MOZ_ASSERT(resumeOffsetsOffset() == cursor);
324 if (numResumeOffsets > 0) {
325 initElements<uint32_t>(cursor, numResumeOffsets);
326 cursor += numResumeOffsets * sizeof(uint32_t);
327 setOptionalOffset(++offsetIndex, cursor);
328 }
329 flagsRef().resumeOffsetsEndIndex = offsetIndex;
330
331 // Default-initialize optional 'scopeNotes'.
332 MOZ_ASSERT(scopeNotesOffset() == cursor);
333 if (numScopeNotes > 0) {
334 initElements<ScopeNote>(cursor, numScopeNotes);
335 cursor += numScopeNotes * sizeof(ScopeNote);
336 setOptionalOffset(++offsetIndex, cursor);
337 }
338 flagsRef().scopeNotesEndIndex = offsetIndex;
339
340 // Default-initialize optional 'tryNotes'
341 MOZ_ASSERT(tryNotesOffset() == cursor);
342 if (numTryNotes > 0) {
343 initElements<TryNote>(cursor, numTryNotes);
344 cursor += numTryNotes * sizeof(TryNote);
345 setOptionalOffset(++offsetIndex, cursor);
346 }
347 flagsRef().tryNotesEndIndex = offsetIndex;
348
349 MOZ_ASSERT(endOffset() == cursor);
350 (*pcursor) = cursor;
351 }
352
353 ImmutableScriptData::ImmutableScriptData(uint32_t codeLength,
354 uint32_t noteLength,
355 uint32_t numResumeOffsets,
356 uint32_t numScopeNotes,
357 uint32_t numTryNotes)
358 : codeLength_(codeLength) {
359 // Variable-length data begins immediately after ImmutableScriptData itself.
360 Offset cursor = sizeof(ImmutableScriptData);
361
362 // The following arrays are byte-aligned with additional padding to ensure
363 // that together they maintain uint32_t-alignment.
364 {
365 MOZ_ASSERT(isAlignedOffset<CodeNoteAlign>(cursor));
366
367 // Zero-initialize 'flags'
368 MOZ_ASSERT(isAlignedOffset<Flags>(cursor));
369 new (offsetToPointer<void>(cursor)) Flags{};
370 cursor += sizeof(Flags);
371
372 initElements<jsbytecode>(cursor, codeLength);
373 cursor += codeLength * sizeof(jsbytecode);
374
375 initElements<SrcNote>(cursor, noteLength);
376 cursor += noteLength * sizeof(SrcNote);
377
378 MOZ_ASSERT(isAlignedOffset<CodeNoteAlign>(cursor));
379 }
380
381 // Initialization for remaining arrays.
382 initOptionalArrays(&cursor, numResumeOffsets, numScopeNotes, numTryNotes);
383
384 // Check that we correctly recompute the expected values.
385 MOZ_ASSERT(this->codeLength() == codeLength);
386 MOZ_ASSERT(this->noteLength() == noteLength);
387
388 // Sanity check
389 MOZ_ASSERT(endOffset() == cursor);
390 }
391
392 void js::FillImmutableFlagsFromCompileOptionsForTopLevel(
393 const ReadOnlyCompileOptions& options, ImmutableScriptFlags& flags) {
394 using ImmutableFlags = ImmutableScriptFlagsEnum;
395
396 js::FillImmutableFlagsFromCompileOptionsForFunction(options, flags);
397
398 flags.setFlag(ImmutableFlags::TreatAsRunOnce, options.isRunOnce);
399 flags.setFlag(ImmutableFlags::NoScriptRval, options.noScriptRval);
400 }
401
402 void js::FillImmutableFlagsFromCompileOptionsForFunction(
403 const ReadOnlyCompileOptions& options, ImmutableScriptFlags& flags) {
404 using ImmutableFlags = ImmutableScriptFlagsEnum;
405
406 flags.setFlag(ImmutableFlags::SelfHosted, options.selfHostingMode);
407 flags.setFlag(ImmutableFlags::ForceStrict, options.forceStrictMode());
408 flags.setFlag(ImmutableFlags::HasNonSyntacticScope,
409 options.nonSyntacticScope);
410 }
411
412 // Check if flags matches to compile options for flags set by
413 // FillImmutableFlagsFromCompileOptionsForTopLevel above.
414 bool js::CheckCompileOptionsMatch(const ReadOnlyCompileOptions& options,
415 ImmutableScriptFlags flags) {
416 using ImmutableFlags = ImmutableScriptFlagsEnum;
417
418 bool selfHosted = !!(flags & uint32_t(ImmutableFlags::SelfHosted));
419 bool forceStrict = !!(flags & uint32_t(ImmutableFlags::ForceStrict));
420 bool hasNonSyntacticScope =
421 !!(flags & uint32_t(ImmutableFlags::HasNonSyntacticScope));
422 bool noScriptRval = !!(flags & uint32_t(ImmutableFlags::NoScriptRval));
423 bool treatAsRunOnce = !!(flags & uint32_t(ImmutableFlags::TreatAsRunOnce));
424
425 return options.selfHostingMode == selfHosted &&
426 options.noScriptRval == noScriptRval &&
427 options.isRunOnce == treatAsRunOnce &&
428 options.forceStrictMode() == forceStrict &&
429 options.nonSyntacticScope == hasNonSyntacticScope;
430 }
431
432 JS_PUBLIC_API bool JS::CheckCompileOptionsMatch(
433 const ReadOnlyCompileOptions& options, JSScript* script) {
434 return js::CheckCompileOptionsMatch(options, script->immutableFlags());
435 }
436
437 bool JSScript::initScriptCounts(JSContext* cx) {
438 MOZ_ASSERT(!hasScriptCounts());
439
440 // Record all pc which are the first instruction of a basic block.
441 mozilla::Vector<jsbytecode*, 16, SystemAllocPolicy> jumpTargets;
442
443 js::BytecodeLocation main = mainLocation();
444 AllBytecodesIterable iterable(this);
445 for (auto& loc : iterable) {
446 if (loc.isJumpTarget() || loc == main) {
447 if (!jumpTargets.append(loc.toRawBytecode())) {
448 ReportOutOfMemory(cx);
449 return false;
450 }
451 }
452 }
453
454 // Initialize all PCCounts counters to 0.
455 ScriptCounts::PCCountsVector base;
456 if (!base.reserve(jumpTargets.length())) {
457 ReportOutOfMemory(cx);
458 return false;
459 }
460
461 for (size_t i = 0; i < jumpTargets.length(); i++) {
462 base.infallibleEmplaceBack(pcToOffset(jumpTargets[i]));
463 }
464
465 // Create zone's scriptCountsMap if necessary.
466 if (!zone()->scriptCountsMap) {
467 auto map = cx->make_unique<ScriptCountsMap>();
468 if (!map) {
469 return false;
470 }
471
472 zone()->scriptCountsMap = std::move(map);
473 }
474
475 // Allocate the ScriptCounts.
476 UniqueScriptCounts sc = cx->make_unique<ScriptCounts>(std::move(base));
477 if (!sc) {
478 return false;
479 }
480
481 MOZ_ASSERT(this->hasBytecode());
482
483 // Register the current ScriptCounts in the zone's map.
484 if (!zone()->scriptCountsMap->putNew(this, std::move(sc))) {
485 ReportOutOfMemory(cx);
486 return false;
487 }
488
489 // safe to set this; we can't fail after this point.
490 setHasScriptCounts();
491
492 // Enable interrupts in any interpreter frames running on this script. This
493 // is used to let the interpreter increment the PCCounts, if present.
494 for (ActivationIterator iter(cx); !iter.done(); ++iter) {
495 if (iter->isInterpreter()) {
496 iter->asInterpreter()->enableInterruptsIfRunning(this);
497 }
498 }
499
500 return true;
501 }
502
503 static inline ScriptCountsMap::Ptr GetScriptCountsMapEntry(JSScript* script) {
504 MOZ_ASSERT(script->hasScriptCounts());
505 ScriptCountsMap::Ptr p = script->zone()->scriptCountsMap->lookup(script);
506 MOZ_ASSERT(p);
507 return p;
508 }
509
510 ScriptCounts& JSScript::getScriptCounts() {
511 ScriptCountsMap::Ptr p = GetScriptCountsMapEntry(this);
512 return *p->value();
513 }
514
515 js::PCCounts* ScriptCounts::maybeGetPCCounts(size_t offset) {
516 PCCounts searched = PCCounts(offset);
517 PCCounts* elem =
518 std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
519 if (elem == pcCounts_.end() || elem->pcOffset() != offset) {
520 return nullptr;
521 }
522 return elem;
523 }
524
525 const js::PCCounts* ScriptCounts::maybeGetPCCounts(size_t offset) const {
526 PCCounts searched = PCCounts(offset);
527 const PCCounts* elem =
528 std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
529 if (elem == pcCounts_.end() || elem->pcOffset() != offset) {
530 return nullptr;
531 }
532 return elem;
533 }
534
535 js::PCCounts* ScriptCounts::getImmediatePrecedingPCCounts(size_t offset) {
536 PCCounts searched = PCCounts(offset);
537 PCCounts* elem =
538 std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
539 if (elem == pcCounts_.end()) {
540 return &pcCounts_.back();
541 }
542 if (elem->pcOffset() == offset) {
543 return elem;
544 }
545 if (elem != pcCounts_.begin()) {
546 return elem - 1;
547 }
548 return nullptr;
549 }
550
551 const js::PCCounts* ScriptCounts::maybeGetThrowCounts(size_t offset) const {
552 PCCounts searched = PCCounts(offset);
553 const PCCounts* elem =
554 std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
555 if (elem == throwCounts_.end() || elem->pcOffset() != offset) {
556 return nullptr;
557 }
558 return elem;
559 }
560
561 const js::PCCounts* ScriptCounts::getImmediatePrecedingThrowCounts(
562 size_t offset) const {
563 PCCounts searched = PCCounts(offset);
564 const PCCounts* elem =
565 std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
566 if (elem == throwCounts_.end()) {
567 if (throwCounts_.begin() == throwCounts_.end()) {
568 return nullptr;
569 }
570 return &throwCounts_.back();
571 }
572 if (elem->pcOffset() == offset) {
573 return elem;
574 }
575 if (elem != throwCounts_.begin()) {
576 return elem - 1;
577 }
578 return nullptr;
579 }
580
581 js::PCCounts* ScriptCounts::getThrowCounts(size_t offset) {
582 PCCounts searched = PCCounts(offset);
583 PCCounts* elem =
584 std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
585 if (elem == throwCounts_.end() || elem->pcOffset() != offset) {
586 elem = throwCounts_.insert(elem, searched);
587 }
588 return elem;
589 }
590
591 size_t ScriptCounts::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) {
592 size_t size = mallocSizeOf(this);
593 size += pcCounts_.sizeOfExcludingThis(mallocSizeOf);
594 size += throwCounts_.sizeOfExcludingThis(mallocSizeOf);
595 if (ionCounts_) {
596 size += ionCounts_->sizeOfIncludingThis(mallocSizeOf);
597 }
598 return size;
599 }
600
601 js::PCCounts* JSScript::maybeGetPCCounts(jsbytecode* pc) {
602 MOZ_ASSERT(containsPC(pc));
603 return getScriptCounts().maybeGetPCCounts(pcToOffset(pc));
604 }
605
606 const js::PCCounts* JSScript::maybeGetThrowCounts(jsbytecode* pc) {
607 MOZ_ASSERT(containsPC(pc));
608 return getScriptCounts().maybeGetThrowCounts(pcToOffset(pc));
609 }
610
611 js::PCCounts* JSScript::getThrowCounts(jsbytecode* pc) {
612 MOZ_ASSERT(containsPC(pc));
613 return getScriptCounts().getThrowCounts(pcToOffset(pc));
614 }
615
616 uint64_t JSScript::getHitCount(jsbytecode* pc) {
617 MOZ_ASSERT(containsPC(pc));
618 if (pc < main()) {
619 pc = main();
620 }
621
622 ScriptCounts& sc = getScriptCounts();
623 size_t targetOffset = pcToOffset(pc);
624 const js::PCCounts* baseCount =
625 sc.getImmediatePrecedingPCCounts(targetOffset);
626 if (!baseCount) {
627 return 0;
628 }
629 if (baseCount->pcOffset() == targetOffset) {
630 return baseCount->numExec();
631 }
632 MOZ_ASSERT(baseCount->pcOffset() < targetOffset);
633 uint64_t count = baseCount->numExec();
634 do {
635 const js::PCCounts* throwCount =
636 sc.getImmediatePrecedingThrowCounts(targetOffset);
637 if (!throwCount) {
638 return count;
639 }
640 if (throwCount->pcOffset() <= baseCount->pcOffset()) {
641 return count;
642 }
643 count -= throwCount->numExec();
644 targetOffset = throwCount->pcOffset() - 1;
645 } while (true);
646 }
647
648 void JSScript::addIonCounts(jit::IonScriptCounts* ionCounts) {
649 ScriptCounts& sc = getScriptCounts();
650 if (sc.ionCounts_) {
651 ionCounts->setPrevious(sc.ionCounts_);
652 }
653 sc.ionCounts_ = ionCounts;
654 }
655
656 jit::IonScriptCounts* JSScript::getIonCounts() {
657 return getScriptCounts().ionCounts_;
658 }
659
660 void JSScript::releaseScriptCounts(ScriptCounts* counts) {
661 ScriptCountsMap::Ptr p = GetScriptCountsMapEntry(this);
662 *counts = std::move(*p->value().get());
663 zone()->scriptCountsMap->remove(p);
664 clearHasScriptCounts();
665 }
666
667 void JSScript::destroyScriptCounts() {
668 if (hasScriptCounts()) {
669 ScriptCounts scriptCounts;
670 releaseScriptCounts(&scriptCounts);
671 }
672 }
673
674 void JSScript::resetScriptCounts() {
675 if (!hasScriptCounts()) {
676 return;
677 }
678
679 ScriptCounts& sc = getScriptCounts();
680
681 for (PCCounts& elem : sc.pcCounts_) {
682 elem.numExec() = 0;
683 }
684
685 for (PCCounts& elem : sc.throwCounts_) {
686 elem.numExec() = 0;
687 }
688 }
689
690 void ScriptSourceObject::finalize(JS::GCContext* gcx, JSObject* obj) {
691 MOZ_ASSERT(gcx->onMainThread());
692 ScriptSourceObject* sso = &obj->as<ScriptSourceObject>();
693 sso->source()->Release();
694
695 // Clear the private value, calling the release hook if necessary.
696 sso->setPrivate(gcx->runtime(), UndefinedValue());
697
698 sso->clearStencils();
699 }
700
701 static const JSClassOps ScriptSourceObjectClassOps = {
702 nullptr, // addProperty
703 nullptr, // delProperty
704 nullptr, // enumerate
705 nullptr, // newEnumerate
706 nullptr, // resolve
707 nullptr, // mayResolve
708 ScriptSourceObject::finalize, // finalize
709 nullptr, // call
710 nullptr, // construct
711 nullptr, // trace
712 };
713
714 const JSClass ScriptSourceObject::class_ = {
715 "ScriptSource",
716 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) | JSCLASS_FOREGROUND_FINALIZE,
717 &ScriptSourceObjectClassOps,
718 };
719
720 ScriptSourceObject* ScriptSourceObject::create(JSContext* cx,
721 ScriptSource* source) {
722 ScriptSourceObject* obj =
723 NewObjectWithGivenProto<ScriptSourceObject>(cx, nullptr);
724 if (!obj) {
725 return nullptr;
726 }
727
728 // The matching decref is in ScriptSourceObject::finalize.
729 obj->initReservedSlot(SOURCE_SLOT, PrivateValue(do_AddRef(source).take()));
730
731 // The slots below should be populated by a call to initFromOptions. Poison
732 // them.
733 obj->initReservedSlot(ELEMENT_PROPERTY_SLOT, MagicValue(JS_GENERIC_MAGIC));
734 obj->initReservedSlot(INTRODUCTION_SCRIPT_SLOT, MagicValue(JS_GENERIC_MAGIC));
735
736 obj->initReservedSlot(STENCILS_SLOT, UndefinedValue());
737
738 return obj;
739 }
740
741 [[nodiscard]] static bool MaybeValidateFilename(
742 JSContext* cx, Handle<ScriptSourceObject*> sso,
743 const JS::InstantiateOptions& options) {
744 if (!gFilenameValidationCallback) {
745 return true;
746 }
747
748 const char* filename = sso->source()->filename();
749 if (!filename || options.skipFilenameValidation) {
750 return true;
751 }
752
753 if (gFilenameValidationCallback(cx, filename)) {
754 return true;
755 }
756
757 const char* utf8Filename;
758 if (mozilla::IsUtf8(mozilla::MakeStringSpan(filename))) {
759 utf8Filename = filename;
760 } else {
761 utf8Filename = "(invalid UTF-8 filename)";
762 }
763 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_UNSAFE_FILENAME,
764 utf8Filename);
765 return false;
766 }
767
768 /* static */
769 bool ScriptSourceObject::initFromOptions(
770 JSContext* cx, Handle<ScriptSourceObject*> source,
771 const JS::InstantiateOptions& options) {
772 cx->releaseCheck(source);
773 MOZ_ASSERT(
774 source->getReservedSlot(ELEMENT_PROPERTY_SLOT).isMagic(JS_GENERIC_MAGIC));
775 MOZ_ASSERT(source->getReservedSlot(INTRODUCTION_SCRIPT_SLOT)
776 .isMagic(JS_GENERIC_MAGIC));
777
778 if (!MaybeValidateFilename(cx, source, options)) {
779 return false;
780 }
781
782 if (options.deferDebugMetadata) {
783 return true;
784 }
785
786 // Initialize the element attribute slot and introduction script slot
787 // this marks the SSO as initialized for asserts.
788
789 RootedString elementAttributeName(cx);
790 if (!initElementProperties(cx, source, elementAttributeName)) {
791 return false;
792 }
793
794 RootedValue introductionScript(cx);
795 source->setReservedSlot(INTRODUCTION_SCRIPT_SLOT, introductionScript);
796
797 return true;
798 }
799
800 /* static */
801 bool ScriptSourceObject::initElementProperties(
802 JSContext* cx, Handle<ScriptSourceObject*> source,
803 HandleString elementAttrName) {
804 RootedValue nameValue(cx);
805 if (elementAttrName) {
806 nameValue = StringValue(elementAttrName);
807 }
808 if (!cx->compartment()->wrap(cx, &nameValue)) {
809 return false;
810 }
811
812 source->setReservedSlot(ELEMENT_PROPERTY_SLOT, nameValue);
813
814 return true;
815 }
816
817 void ScriptSourceObject::setPrivate(JSRuntime* rt, const Value& value) {
818 // Update the private value, calling addRef/release hooks if necessary
819 // to allow the embedding to maintain a reference count for the
820 // private data.
821 JS::AutoSuppressGCAnalysis nogc;
822 Value prevValue = getReservedSlot(PRIVATE_SLOT);
823 rt->releaseScriptPrivate(prevValue);
824 setReservedSlot(PRIVATE_SLOT, value);
825 rt->addRefScriptPrivate(value);
826 }
827
828 void ScriptSourceObject::clearPrivate(JSRuntime* rt) {
829 // Clear the private value, calling release hook if necessary.
830 // |this| may be gray, be careful not to create edges to it.
831 JS::AutoSuppressGCAnalysis nogc;
832 Value prevValue = getReservedSlot(PRIVATE_SLOT);
833 rt->releaseScriptPrivate(prevValue);
834 getSlotRef(PRIVATE_SLOT).setUndefinedUnchecked();
835 }
836
837 class ScriptSource::LoadSourceMatcher {
838 JSContext* const cx_;
839 ScriptSource* const ss_;
840 bool* const loaded_;
841
842 public:
843 explicit LoadSourceMatcher(JSContext* cx, ScriptSource* ss, bool* loaded)
844 : cx_(cx), ss_(ss), loaded_(loaded) {}
845
846 template <typename Unit, SourceRetrievable CanRetrieve>
847 bool operator()(const Compressed<Unit, CanRetrieve>&) const {
848 *loaded_ = true;
849 return true;
850 }
851
852 template <typename Unit, SourceRetrievable CanRetrieve>
853 bool operator()(const Uncompressed<Unit, CanRetrieve>&) const {
854 *loaded_ = true;
855 return true;
856 }
857
858 template <typename Unit>
859 bool operator()(const Retrievable<Unit>&) {
860 if (!cx_->runtime()->sourceHook.ref()) {
861 *loaded_ = false;
862 return true;
863 }
864
865 size_t length;
866
867 // The first argument is just for overloading -- its value doesn't matter.
868 if (!tryLoadAndSetSource(Unit('0'), &length)) {
869 return false;
870 }
871
872 return true;
873 }
874
875 bool operator()(const Missing&) const {
876 *loaded_ = false;
877 return true;
878 }
879
880 private:
881 bool tryLoadAndSetSource(const Utf8Unit&, size_t* length) const {
882 char* utf8Source;
883 if (!cx_->runtime()->sourceHook->load(cx_, ss_->filename(), nullptr,
884 &utf8Source, length)) {
885 return false;
886 }
887
888 if (!utf8Source) {
889 *loaded_ = false;
890 return true;
891 }
892
893 if (!ss_->setRetrievedSource(
894 cx_, EntryUnits<Utf8Unit>(reinterpret_cast<Utf8Unit*>(utf8Source)),
895 *length)) {
896 return false;
897 }
898
899 *loaded_ = true;
900 return true;
901 }
902
903 bool tryLoadAndSetSource(const char16_t&, size_t* length) const {
904 char16_t* utf16Source;
905 if (!cx_->runtime()->sourceHook->load(cx_, ss_->filename(), &utf16Source,
906 nullptr, length)) {
907 return false;
908 }
909
910 if (!utf16Source) {
911 *loaded_ = false;
912 return true;
913 }
914
915 if (!ss_->setRetrievedSource(cx_, EntryUnits<char16_t>(utf16Source),
916 *length)) {
917 return false;
918 }
919
920 *loaded_ = true;
921 return true;
922 }
923 };
924
925 /* static */
926 bool ScriptSource::loadSource(JSContext* cx, ScriptSource* ss, bool* loaded) {
927 return ss->data.match(LoadSourceMatcher(cx, ss, loaded));
928 }
929
930 /* static */
931 JSLinearString* JSScript::sourceData(JSContext* cx, HandleScript script) {
932 MOZ_ASSERT(script->scriptSource()->hasSourceText());
933 return script->scriptSource()->substring(cx, script->sourceStart(),
934 script->sourceEnd());
935 }
936
937 bool BaseScript::appendSourceDataForToString(JSContext* cx,
938 StringBuilder& buf) {
939 MOZ_ASSERT(scriptSource()->hasSourceText());
940 return scriptSource()->appendSubstring(cx, buf, toStringStart(),
941 toStringEnd());
942 }
943
944 void UncompressedSourceCache::holdEntry(AutoHoldEntry& holder,
945 const ScriptSourceChunk& ssc) {
946 MOZ_ASSERT(!holder_);
947 holder.holdEntry(this, ssc);
948 holder_ = &holder;
949 }
950
951 void UncompressedSourceCache::releaseEntry(AutoHoldEntry& holder) {
952 MOZ_ASSERT(holder_ == &holder);
953 holder_ = nullptr;
954 }
955
956 template <typename Unit>
957 const Unit* UncompressedSourceCache::lookup(const ScriptSourceChunk& ssc,
958 AutoHoldEntry& holder) {
959 MOZ_ASSERT(!holder_);
960 MOZ_ASSERT(ssc.ss->isCompressed<Unit>());
961
962 if (!map_) {
963 return nullptr;
964 }
965
966 if (Map::Ptr p = map_->lookup(ssc)) {
967 holdEntry(holder, ssc);
968 return static_cast<const Unit*>(p->value().get());
969 }
970
971 return nullptr;
972 }
973
974 bool UncompressedSourceCache::put(const ScriptSourceChunk& ssc, SourceData data,
975 AutoHoldEntry& holder) {
976 MOZ_ASSERT(!holder_);
977
978 if (!map_) {
979 map_ = MakeUnique<Map>();
980 if (!map_) {
981 return false;
982 }
983 }
984
985 if (!map_->put(ssc, std::move(data))) {
986 return false;
987 }
988
989 holdEntry(holder, ssc);
990 return true;
991 }
992
993 void UncompressedSourceCache::purge() {
994 if (!map_) {
995 return;
996 }
997
998 for (Map::Range r = map_->all(); !r.empty(); r.popFront()) {
999 if (holder_ && r.front().key() == holder_->sourceChunk()) {
1000 holder_->deferDelete(std::move(r.front().value()));
1001 holder_ = nullptr;
1002 }
1003 }
1004
1005 map_ = nullptr;
1006 }
1007
1008 size_t UncompressedSourceCache::sizeOfExcludingThis(
1009 mozilla::MallocSizeOf mallocSizeOf) {
1010 size_t n = 0;
1011 if (map_ && !map_->empty()) {
1012 n += map_->shallowSizeOfIncludingThis(mallocSizeOf);
1013 for (Map::Range r = map_->all(); !r.empty(); r.popFront()) {
1014 n += mallocSizeOf(r.front().value().get());
1015 }
1016 }
1017 return n;
1018 }
1019
1020 template <typename Unit>
1021 const Unit* ScriptSource::chunkUnits(
1022 JSContext* cx, UncompressedSourceCache::AutoHoldEntry& holder,
1023 size_t chunk) {
1024 const CompressedData<Unit>& c = *compressedData<Unit>();
1025
1026 ScriptSourceChunk ssc(this, chunk);
1027 if (const Unit* decompressed =
1028 cx->caches().uncompressedSourceCache.lookup<Unit>(ssc, holder)) {
1029 return decompressed;
1030 }
1031
1032 size_t totalLengthInBytes = length() * sizeof(Unit);
1033 size_t chunkBytes = Compressor::chunkSize(totalLengthInBytes, chunk);
1034
1035 MOZ_ASSERT((chunkBytes % sizeof(Unit)) == 0);
1036 const size_t chunkLength = chunkBytes / sizeof(Unit);
1037 EntryUnits<Unit> decompressed(js_pod_malloc<Unit>(chunkLength));
1038 if (!decompressed) {
1039 JS_ReportOutOfMemory(cx);
1040 return nullptr;
1041 }
1042
1043 // Compression treats input and output memory as plain ol' bytes. These
1044 // reinterpret_cast<>s accord exactly with that.
1045 if (!DecompressStringChunk(
1046 reinterpret_cast<const unsigned char*>(c.raw.chars()), chunk,
1047 reinterpret_cast<unsigned char*>(decompressed.get()), chunkBytes)) {
1048 JS_ReportOutOfMemory(cx);
1049 return nullptr;
1050 }
1051
1052 const Unit* ret = decompressed.get();
1053 if (!cx->caches().uncompressedSourceCache.put(
1054 ssc, ToSourceData(std::move(decompressed)), holder)) {
1055 JS_ReportOutOfMemory(cx);
1056 return nullptr;
1057 }
1058 return ret;
1059 }
1060
1061 template <typename Unit>
1062 void ScriptSource::convertToCompressedSource(SharedImmutableString compressed,
1063 size_t uncompressedLength) {
1064 MOZ_ASSERT(isUncompressed<Unit>());
1065 MOZ_ASSERT(uncompressedData<Unit>()->length() == uncompressedLength);
1066
1067 if (data.is<Uncompressed<Unit, SourceRetrievable::Yes>>()) {
1068 data = SourceType(Compressed<Unit, SourceRetrievable::Yes>(
1069 std::move(compressed), uncompressedLength));
1070 } else {
1071 data = SourceType(Compressed<Unit, SourceRetrievable::No>(
1072 std::move(compressed), uncompressedLength));
1073 }
1074 }
1075
1076 template <typename Unit>
1077 void ScriptSource::performDelayedConvertToCompressedSource(
1078 ExclusiveData<ReaderInstances>::Guard& g) {
1079 // There might not be a conversion to compressed source happening at all.
1080 if (g->pendingCompressed.empty()) {
1081 return;
1082 }
1083
1084 CompressedData<Unit>& pending =
1085 g->pendingCompressed.ref<CompressedData<Unit>>();
1086
1087 convertToCompressedSource<Unit>(std::move(pending.raw),
1088 pending.uncompressedLength);
1089
1090 g->pendingCompressed.destroy();
1091 }
1092
1093 ScriptSource::GenericReader::GenericReader(ScriptSource* source)
1094 : PinnedUnitsBase(source) {
1095 addReader();
1096 }
1097
1098 ScriptSource::GenericReader::~GenericReader() {
1099 if (!source_->hasSourceText()) {
1100 // For script sources without text, the reader is added just to access the
1101 // other fields. There shouldn't be any pending compression, and we can
1102 // just remove the reader.
1103 auto guard = source_->readers_.lock();
1104 MOZ_ASSERT(guard->pendingCompressed.empty());
1105 MOZ_ASSERT(guard->count > 0);
1106 guard->count--;
1107 return;
1108 }
1109
1110 if (source_->hasSourceType<Utf8Unit>()) {
1111 removeReader<Utf8Unit>();
1112 } else {
1113 removeReader<char16_t>();
1114 }
1115 }
1116
1117 void ScriptSource::PinnedUnitsBase::addReader() {
1118 auto guard = source_->readers_.lock();
1119 guard->count++;
1120 }
1121
1122 template <typename Unit>
1123 void ScriptSource::PinnedUnitsBase::removeReader() {
1124 // If the off-thread compression task couldn't perform
1125 // convertToCompressedSource, the conversion is pending on
1126 // the pendingCompressed field.
1127 //
1128 // If there's no other reader at this point, perform the pending conversion
1129 // here.
1130 //
1131 // See also ScriptSource::triggerConvertToCompressedSource.
1132 auto guard = source_->readers_.lock();
1133 MOZ_ASSERT(guard->count > 0);
1134 if (--guard->count == 0) {
1135 source_->performDelayedConvertToCompressedSource<Unit>(guard);
1136 }
1137 }
1138
1139 template <typename Unit>
1140 ScriptSource::PinnedUnits<Unit>::~PinnedUnits() {
1141 if (units_) {
1142 removeReader<Unit>();
1143 }
1144 }
1145
1146 template <typename Unit>
1147 ScriptSource::PinnedUnitsIfUncompressed<Unit>::~PinnedUnitsIfUncompressed() {
1148 if (units_) {
1149 removeReader<Unit>();
1150 }
1151 }
1152
1153 template <typename Unit>
1154 const Unit* ScriptSource::units(JSContext* cx,
1155 UncompressedSourceCache::AutoHoldEntry& holder,
1156 size_t begin, size_t len) {
1157 MOZ_ASSERT(begin <= length());
1158 MOZ_ASSERT(begin + len <= length());
1159
1160 if (isUncompressed<Unit>()) {
1161 const Unit* units = uncompressedData<Unit>()->units();
1162 if (!units) {
1163 return nullptr;
1164 }
1165 return units + begin;
1166 }
1167
1168 if (data.is<Missing>()) {
1169 MOZ_CRASH("ScriptSource::units() on ScriptSource with missing source");
1170 }
1171
1172 if (data.is<Retrievable<Unit>>()) {
1173 MOZ_CRASH("ScriptSource::units() on ScriptSource with retrievable source");
1174 }
1175
1176 MOZ_ASSERT(isCompressed<Unit>());
1177
1178 // Determine first/last chunks, the offset (in bytes) into the first chunk
1179 // of the requested units, and the number of bytes in the last chunk.
1180 //
1181 // Note that first and last chunk sizes are miscomputed and *must not be
1182 // used* when the first chunk is the last chunk.
1183 size_t firstChunk, firstChunkOffset, firstChunkSize;
1184 size_t lastChunk, lastChunkSize;
1185 Compressor::rangeToChunkAndOffset(
1186 begin * sizeof(Unit), (begin + len) * sizeof(Unit), &firstChunk,
1187 &firstChunkOffset, &firstChunkSize, &lastChunk, &lastChunkSize);
1188 MOZ_ASSERT(firstChunk <= lastChunk);
1189 MOZ_ASSERT(firstChunkOffset % sizeof(Unit) == 0);
1190 MOZ_ASSERT(firstChunkSize % sizeof(Unit) == 0);
1191
1192 size_t firstUnit = firstChunkOffset / sizeof(Unit);
1193
1194 // Directly return units within a single chunk. UncompressedSourceCache
1195 // and |holder| will hold the units alive past function return.
1196 if (firstChunk == lastChunk) {
1197 const Unit* units = chunkUnits<Unit>(cx, holder, firstChunk);
1198 if (!units) {
1199 return nullptr;
1200 }
1201
1202 return units + firstUnit;
1203 }
1204
1205 // Otherwise the units span multiple chunks. Copy successive chunks'
1206 // decompressed units into freshly-allocated memory to return.
1207 EntryUnits<Unit> decompressed(js_pod_malloc<Unit>(len));
1208 if (!decompressed) {
1209 JS_ReportOutOfMemory(cx);
1210 return nullptr;
1211 }
1212
1213 Unit* cursor;
1214
1215 {
1216 // |AutoHoldEntry| is single-shot, and a holder successfully filled in
1217 // by |chunkUnits| must be destroyed before another can be used. Thus
1218 // we can't use |holder| with |chunkUnits| when |chunkUnits| is used
1219 // with multiple chunks, and we must use and destroy distinct, fresh
1220 // holders for each chunk.
1221 UncompressedSourceCache::AutoHoldEntry firstHolder;
1222 const Unit* units = chunkUnits<Unit>(cx, firstHolder, firstChunk);
1223 if (!units) {
1224 return nullptr;
1225 }
1226
1227 cursor = std::copy_n(units + firstUnit, firstChunkSize / sizeof(Unit),
1228 decompressed.get());
1229 }
1230
1231 for (size_t i = firstChunk + 1; i < lastChunk; i++) {
1232 UncompressedSourceCache::AutoHoldEntry chunkHolder;
1233 const Unit* units = chunkUnits<Unit>(cx, chunkHolder, i);
1234 if (!units) {
1235 return nullptr;
1236 }
1237
1238 cursor = std::copy_n(units, Compressor::CHUNK_SIZE / sizeof(Unit), cursor);
1239 }
1240
1241 {
1242 UncompressedSourceCache::AutoHoldEntry lastHolder;
1243 const Unit* units = chunkUnits<Unit>(cx, lastHolder, lastChunk);
1244 if (!units) {
1245 return nullptr;
1246 }
1247
1248 cursor = std::copy_n(units, lastChunkSize / sizeof(Unit), cursor);
1249 }
1250
1251 MOZ_ASSERT(PointerRangeSize(decompressed.get(), cursor) == len);
1252
1253 // Transfer ownership to |holder|.
1254 const Unit* ret = decompressed.get();
1255 holder.holdUnits(std::move(decompressed));
1256 return ret;
1257 }
1258
1259 template <typename Unit>
1260 const Unit* ScriptSource::uncompressedUnits(size_t begin, size_t len) {
1261 MOZ_ASSERT(begin <= length());
1262 MOZ_ASSERT(begin + len <= length());
1263
1264 if (!isUncompressed<Unit>()) {
1265 return nullptr;
1266 }
1267
1268 const Unit* units = uncompressedData<Unit>()->units();
1269 if (!units) {
1270 return nullptr;
1271 }
1272 return units + begin;
1273 }
1274
1275 template <typename Unit>
1276 ScriptSource::PinnedUnits<Unit>::PinnedUnits(
1277 JSContext* cx, ScriptSource* source,
1278 UncompressedSourceCache::AutoHoldEntry& holder, size_t begin, size_t len)
1279 : PinnedUnitsBase(source) {
1280 MOZ_ASSERT(source->hasSourceType<Unit>(), "must pin units of source's type");
1281
1282 addReader();
1283
1284 units_ = source->units<Unit>(cx, holder, begin, len);
1285 if (!units_) {
1286 removeReader<Unit>();
1287 }
1288 }
1289
1290 template class ScriptSource::PinnedUnits<Utf8Unit>;
1291 template class ScriptSource::PinnedUnits<char16_t>;
1292
1293 template <typename Unit>
1294 ScriptSource::PinnedUnitsIfUncompressed<Unit>::PinnedUnitsIfUncompressed(
1295 ScriptSource* source, size_t begin, size_t len)
1296 : PinnedUnitsBase(source) {
1297 MOZ_ASSERT(source->hasSourceType<Unit>(), "must pin units of source's type");
1298
1299 addReader();
1300
1301 units_ = source->uncompressedUnits<Unit>(begin, len);
1302 if (!units_) {
1303 removeReader<Unit>();
1304 }
1305 }
1306
1307 template class ScriptSource::PinnedUnitsIfUncompressed<Utf8Unit>;
1308 template class ScriptSource::PinnedUnitsIfUncompressed<char16_t>;
1309
1310 JSLinearString* ScriptSource::substring(JSContext* cx, size_t start,
1311 size_t stop) {
1312 MOZ_ASSERT(start <= stop);
1313
1314 size_t len = stop - start;
1315 if (!len) {
1316 return cx->emptyString();
1317 }
1318 UncompressedSourceCache::AutoHoldEntry holder;
1319
1320 // UTF-8 source text.
1321 if (hasSourceType<Utf8Unit>()) {
1322 PinnedUnits<Utf8Unit> units(cx, this, holder, start, len);
1323 if (!units.asChars()) {
1324 return nullptr;
1325 }
1326
1327 const char* str = units.asChars();
1328 return NewStringCopyUTF8N(cx, JS::UTF8Chars(str, len));
1329 }
1330
1331 // UTF-16 source text.
1332 PinnedUnits<char16_t> units(cx, this, holder, start, len);
1333 if (!units.asChars()) {
1334 return nullptr;
1335 }
1336
1337 return NewStringCopyN<CanGC>(cx, units.asChars(), len);
1338 }
1339
1340 JSLinearString* ScriptSource::substringDontDeflate(JSContext* cx, size_t start,
1341 size_t stop) {
1342 MOZ_ASSERT(start <= stop);
1343
1344 size_t len = stop - start;
1345 if (!len) {
1346 return cx->emptyString();
1347 }
1348 UncompressedSourceCache::AutoHoldEntry holder;
1349
1350 // UTF-8 source text.
1351 if (hasSourceType<Utf8Unit>()) {
1352 PinnedUnits<Utf8Unit> units(cx, this, holder, start, len);
1353 if (!units.asChars()) {
1354 return nullptr;
1355 }
1356
1357 const char* str = units.asChars();
1358
1359 // There doesn't appear to be a non-deflating UTF-8 string creation
1360 // function -- but then again, it's not entirely clear how current
1361 // callers benefit from non-deflation.
1362 return NewStringCopyUTF8N(cx, JS::UTF8Chars(str, len));
1363 }
1364
1365 // UTF-16 source text.
1366 PinnedUnits<char16_t> units(cx, this, holder, start, len);
1367 if (!units.asChars()) {
1368 return nullptr;
1369 }
1370
1371 return NewStringCopyNDontDeflate<CanGC>(cx, units.asChars(), len);
1372 }
1373
1374 bool ScriptSource::appendSubstring(JSContext* cx, StringBuilder& buf,
1375 size_t start, size_t stop) {
1376 MOZ_ASSERT(start <= stop);
1377
1378 size_t len = stop - start;
1379 UncompressedSourceCache::AutoHoldEntry holder;
1380
1381 if (hasSourceType<Utf8Unit>()) {
1382 PinnedUnits<Utf8Unit> pinned(cx, this, holder, start, len);
1383 if (!pinned.get()) {
1384 return false;
1385 }
1386 if (len > SourceDeflateLimit && !buf.ensureTwoByteChars()) {
1387 return false;
1388 }
1389
1390 const Utf8Unit* units = pinned.get();
1391 return buf.append(units, len);
1392 } else {
1393 PinnedUnits<char16_t> pinned(cx, this, holder, start, len);
1394 if (!pinned.get()) {
1395 return false;
1396 }
1397 if (len > SourceDeflateLimit && !buf.ensureTwoByteChars()) {
1398 return false;
1399 }
1400
1401 const char16_t* units = pinned.get();
1402 return buf.append(units, len);
1403 }
1404 }
1405
1406 JSLinearString* ScriptSource::functionBodyString(JSContext* cx) {
1407 MOZ_ASSERT(isFunctionBody());
1408
1409 size_t start = parameterListEnd_ + FunctionConstructorMedialSigils.length();
1410 size_t stop = length() - FunctionConstructorFinalBrace.length();
1411 return substring(cx, start, stop);
1412 }
1413
1414 template <typename ContextT, typename Unit>
1415 [[nodiscard]] bool ScriptSource::setUncompressedSourceHelper(
1416 ContextT* cx, EntryUnits<Unit>&& source, size_t length,
1417 SourceRetrievable retrievable) {
1418 auto& cache = SharedImmutableStringsCache::getSingleton();
1419
1420 auto uniqueChars = SourceTypeTraits<Unit>::toCacheable(std::move(source));
1421 auto deduped = cache.getOrCreate(std::move(uniqueChars), length);
1422 if (!deduped) {
1423 ReportOutOfMemory(cx);
1424 return false;
1425 }
1426
1427 if (retrievable == SourceRetrievable::Yes) {
1428 data = SourceType(
1429 Uncompressed<Unit, SourceRetrievable::Yes>(std::move(deduped)));
1430 } else {
1431 data = SourceType(
1432 Uncompressed<Unit, SourceRetrievable::No>(std::move(deduped)));
1433 }
1434 return true;
1435 }
1436
1437 template <typename Unit>
1438 [[nodiscard]] bool ScriptSource::setRetrievedSource(JSContext* cx,
1439 EntryUnits<Unit>&& source,
1440 size_t length) {
1441 MOZ_ASSERT(data.is<Retrievable<Unit>>(),
1442 "retrieved source can only overwrite the corresponding "
1443 "retrievable source");
1444 return setUncompressedSourceHelper(cx, std::move(source), length,
1445 SourceRetrievable::Yes);
1446 }
1447
1448 bool js::IsOffThreadSourceCompressionEnabled() {
1449 // If we don't have concurrent execution compression will contend with
1450 // main-thread execution, in which case we disable. Similarly we don't want to
1451 // block the thread pool if it is too small.
1452 return GetHelperThreadCPUCount() > 1 && GetHelperThreadCount() > 1 &&
1453 CanUseExtraThreads();
1454 }
1455
1456 bool ScriptSource::tryCompressOffThread(JSContext* cx) {
1457 // Beware: |js::SynchronouslyCompressSource| assumes that this function is
1458 // only called once, just after a script has been compiled, and it's never
1459 // called at some random time after that. If multiple calls of this can ever
1460 // occur, that function may require changes.
1461
1462 // The SourceCompressionTask needs to record the major GC number for
1463 // scheduling.
1464 MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
1465
1466 // If source compression was already attempted, do not queue a new task.
1467 if (hadCompressionTask_) {
1468 return true;
1469 }
1470
1471 if (!hasUncompressedSource()) {
1472 // This excludes compressed, missing, and retrievable source.
1473 return true;
1474 }
1475
1476 // There are several cases where source compression is not a good idea:
1477 // - If the script is tiny, then compression will save little or no space.
1478 // - If there is only one core, then compression will contend with JS
1479 // execution (which hurts benchmarketing).
1480 //
1481 // Otherwise, enqueue a compression task to be processed when a major
1482 // GC is requested.
1483
1484 if (length() < ScriptSource::MinimumCompressibleLength ||
1485 !IsOffThreadSourceCompressionEnabled()) {
1486 return true;
1487 }
1488
1489 // Heap allocate the task. It will be freed upon compression
1490 // completing in AttachFinishedCompressedSources.
1491 auto task = MakeUnique<SourceCompressionTask>(cx->runtime(), this);
1492 if (!task) {
1493 ReportOutOfMemory(cx);
1494 return false;
1495 }
1496 return EnqueueOffThreadCompression(cx, std::move(task));
1497 }
1498
1499 template <typename Unit>
1500 void ScriptSource::triggerConvertToCompressedSource(
1501 SharedImmutableString compressed, size_t uncompressedLength) {
1502 MOZ_ASSERT(isUncompressed<Unit>(),
1503 "should only be triggering compressed source installation to "
1504 "overwrite identically-encoded uncompressed source");
1505 MOZ_ASSERT(uncompressedData<Unit>()->length() == uncompressedLength);
1506
1507 // If units aren't pinned -- and they probably won't be, we'd have to have a
1508 // GC in the small window of time where a |PinnedUnits| was live -- then we
1509 // can immediately convert.
1510 {
1511 auto guard = readers_.lock();
1512 if (MOZ_LIKELY(!guard->count)) {
1513 convertToCompressedSource<Unit>(std::move(compressed),
1514 uncompressedLength);
1515 return;
1516 }
1517
1518 // Otherwise, set aside the compressed-data info. The conversion is
1519 // performed when the last |PinnedUnits| dies.
1520 MOZ_ASSERT(guard->pendingCompressed.empty(),
1521 "shouldn't be multiple conversions happening");
1522 guard->pendingCompressed.construct<CompressedData<Unit>>(
1523 std::move(compressed), uncompressedLength);
1524 }
1525 }
1526
1527 template <typename Unit>
1528 [[nodiscard]] bool ScriptSource::initializeWithUnretrievableCompressedSource(
1529 FrontendContext* fc, UniqueChars&& compressed, size_t rawLength,
1530 size_t sourceLength) {
1531 MOZ_ASSERT(data.is<Missing>(), "shouldn't be double-initializing");
1532 MOZ_ASSERT(compressed != nullptr);
1533
1534 auto& cache = SharedImmutableStringsCache::getSingleton();
1535 auto deduped = cache.getOrCreate(std::move(compressed), rawLength);
1536 if (!deduped) {
1537 ReportOutOfMemory(fc);
1538 return false;
1539 }
1540
1541 #ifdef DEBUG
1542 {
1543 auto guard = readers_.lock();
1544 MOZ_ASSERT(
1545 guard->count == 0,
1546 "shouldn't be initializing a ScriptSource while its characters "
1547 "are pinned -- that only makes sense with a ScriptSource actively "
1548 "being inspected");
1549 }
1550 #endif
1551
1552 data = SourceType(Compressed<Unit, SourceRetrievable::No>(std::move(deduped),
1553 sourceLength));
1554
1555 return true;
1556 }
1557
1558 template bool ScriptSource::initializeWithUnretrievableCompressedSource<
1559 Utf8Unit>(FrontendContext* fc, UniqueChars&& compressed, size_t rawLength,
1560 size_t sourceLength);
1561 template bool ScriptSource::initializeWithUnretrievableCompressedSource<
1562 char16_t>(FrontendContext* fc, UniqueChars&& compressed, size_t rawLength,
1563 size_t sourceLength);
1564
1565 template <typename Unit>
1566 bool ScriptSource::assignSource(FrontendContext* fc,
1567 const ReadOnlyCompileOptions& options,
1568 SourceText<Unit>& srcBuf) {
1569 MOZ_ASSERT(data.is<Missing>(),
1570 "source assignment should only occur on fresh ScriptSources");
1571
1572 mutedErrors_ = options.mutedErrors();
1573 delazificationMode_ = options.eagerDelazificationStrategy();
1574
1575 if (options.discardSource) {
1576 return true;
1577 }
1578
1579 if (options.sourceIsLazy) {
1580 data = SourceType(Retrievable<Unit>());
1581 return true;
1582 }
1583
1584 auto& cache = SharedImmutableStringsCache::getSingleton();
1585 auto deduped = cache.getOrCreate(srcBuf.get(), srcBuf.length(), [&srcBuf]() {
1586 using CharT = typename SourceTypeTraits<Unit>::CharT;
1587 return srcBuf.ownsUnits()
1588 ? UniquePtr<CharT[], JS::FreePolicy>(srcBuf.takeChars())
1589 : DuplicateString(srcBuf.get(), srcBuf.length());
1590 });
1591 if (!deduped) {
1592 ReportOutOfMemory(fc);
1593 return false;
1594 }
1595
1596 data =
1597 SourceType(Uncompressed<Unit, SourceRetrievable::No>(std::move(deduped)));
1598 return true;
1599 }
1600
1601 template bool ScriptSource::assignSource(FrontendContext* fc,
1602 const ReadOnlyCompileOptions& options,
1603 SourceText<char16_t>& srcBuf);
1604 template bool ScriptSource::assignSource(FrontendContext* fc,
1605 const ReadOnlyCompileOptions& options,
1606 SourceText<Utf8Unit>& srcBuf);
1607
1608 [[nodiscard]] static bool reallocUniquePtr(UniqueChars& unique, size_t size) {
1609 auto newPtr = static_cast<char*>(js_realloc(unique.get(), size));
1610 if (!newPtr) {
1611 return false;
1612 }
1613
1614 // Since the realloc succeeded, unique is now holding a freed pointer.
1615 (void)unique.release();
1616 unique.reset(newPtr);
1617 return true;
1618 }
1619
1620 template <typename Unit>
1621 void SourceCompressionTask::workEncodingSpecific() {
1622 MOZ_ASSERT(source_->isUncompressed<Unit>());
1623
1624 // Try to keep the maximum memory usage down by only allocating half the
1625 // size of the string, first.
1626 size_t inputBytes = source_->length() * sizeof(Unit);
1627 size_t firstSize = inputBytes / 2;
1628 UniqueChars compressed(js_pod_malloc<char>(firstSize));
1629 if (!compressed) {
1630 return;
1631 }
1632
1633 const Unit* chars = source_->uncompressedData<Unit>()->units();
1634 Compressor comp(reinterpret_cast<const unsigned char*>(chars), inputBytes);
1635 if (!comp.init()) {
1636 return;
1637 }
1638
1639 comp.setOutput(reinterpret_cast<unsigned char*>(compressed.get()), firstSize);
1640 bool cont = true;
1641 bool reallocated = false;
1642 while (cont) {
1643 if (shouldCancel()) {
1644 return;
1645 }
1646
1647 switch (comp.compressMore()) {
1648 case Compressor::CONTINUE:
1649 break;
1650 case Compressor::MOREOUTPUT: {
1651 if (reallocated) {
1652 // The compressed string is longer than the original string.
1653 return;
1654 }
1655
1656 // The compressed output is greater than half the size of the
1657 // original string. Reallocate to the full size.
1658 if (!reallocUniquePtr(compressed, inputBytes)) {
1659 return;
1660 }
1661
1662 comp.setOutput(reinterpret_cast<unsigned char*>(compressed.get()),
1663 inputBytes);
1664 reallocated = true;
1665 break;
1666 }
1667 case Compressor::DONE:
1668 cont = false;
1669 break;
1670 case Compressor::OOM:
1671 return;
1672 }
1673 }
1674
1675 size_t totalBytes = comp.totalBytesNeeded();
1676
1677 // Shrink the buffer to the size of the compressed data.
1678 if (!reallocUniquePtr(compressed, totalBytes)) {
1679 return;
1680 }
1681
1682 comp.finish(compressed.get(), totalBytes);
1683
1684 if (shouldCancel()) {
1685 return;
1686 }
1687
1688 auto& strings = SharedImmutableStringsCache::getSingleton();
1689 resultString_ = strings.getOrCreate(std::move(compressed), totalBytes);
1690 }
1691
1692 struct SourceCompressionTask::PerformTaskWork {
1693 SourceCompressionTask* const task_;
1694
1695 explicit PerformTaskWork(SourceCompressionTask* task) : task_(task) {}
1696
1697 template <typename Unit, SourceRetrievable CanRetrieve>
1698 void operator()(const ScriptSource::Uncompressed<Unit, CanRetrieve>&) {
1699 task_->workEncodingSpecific<Unit>();
1700 }
1701
1702 template <typename T>
1703 void operator()(const T&) {
1704 MOZ_CRASH(
1705 "why are we compressing missing, missing-but-retrievable, "
1706 "or already-compressed source?");
1707 }
1708 };
1709
1710 void ScriptSource::performTaskWork(SourceCompressionTask* task) {
1711 MOZ_ASSERT(hasUncompressedSource());
1712 data.match(SourceCompressionTask::PerformTaskWork(task));
1713 }
1714
1715 void SourceCompressionTask::runTask() {
1716 if (shouldCancel()) {
1717 return;
1718 }
1719
1720 MOZ_ASSERT(source_->hasUncompressedSource());
1721
1722 source_->performTaskWork(this);
1723 }
1724
1725 void SourceCompressionTask::runHelperThreadTask(
1726 AutoLockHelperThreadState& locked) {
1727 {
1728 AutoUnlockHelperThreadState unlock(locked);
1729 this->runTask();
1730 }
1731
1732 {
1733 AutoEnterOOMUnsafeRegion oomUnsafe;
1734 if (!HelperThreadState().compressionFinishedList(locked).append(this)) {
1735 oomUnsafe.crash("SourceCompressionTask::runHelperThreadTask");
1736 }
1737 }
1738 }
1739
1740 void ScriptSource::triggerConvertToCompressedSourceFromTask(
1741 SharedImmutableString compressed) {
1742 data.match(TriggerConvertToCompressedSourceFromTask(this, compressed));
1743 }
1744
1745 void SourceCompressionTask::complete() {
1746 if (!shouldCancel() && resultString_) {
1747 source_->triggerConvertToCompressedSourceFromTask(std::move(resultString_));
1748 }
1749 }
1750
1751 bool js::SynchronouslyCompressSource(JSContext* cx,
1752 JS::Handle<BaseScript*> script) {
1753 // Finish all pending source compressions, including the single compression
1754 // task that may have been created (by |ScriptSource::tryCompressOffThread|)
1755 // just after the script was compiled. Because we have flushed this queue,
1756 // no code below needs to synchronize with an off-thread parse task that
1757 // assumes the immutability of a |ScriptSource|'s data.
1758 //
1759 // This *may* end up compressing |script|'s source. If it does -- we test
1760 // this below -- that takes care of things. But if it doesn't, we will
1761 // synchronously compress ourselves (and as noted above, this won't race
1762 // anything).
1763 RunPendingSourceCompressions(cx->runtime());
1764
1765 ScriptSource* ss = script->scriptSource();
1766 #ifdef DEBUG
1767 {
1768 auto guard = ss->readers_.lock();
1769 MOZ_ASSERT(guard->count == 0,
1770 "can't synchronously compress while source units are in use");
1771 }
1772 #endif
1773
1774 // In principle a previously-triggered compression on a helper thread could
1775 // have already completed. If that happens, there's nothing more to do.
1776 if (ss->hasCompressedSource()) {
1777 return true;
1778 }
1779
1780 MOZ_ASSERT(ss->hasUncompressedSource(),
1781 "shouldn't be compressing uncompressible source");
1782
1783 // Use an explicit scope to delineate the lifetime of |task|, for simplicity.
1784 {
1785 #ifdef DEBUG
1786 uint32_t sourceRefs = ss->refs;
1787 #endif
1788 MOZ_ASSERT(sourceRefs > 0, "at least |script| here should have a ref");
1789
1790 // |SourceCompressionTask::shouldCancel| can periodically result in source
1791 // compression being canceled if we're not careful. Guarantee that two refs
1792 // to |ss| are always live in this function (at least one preexisting and
1793 // one held by the task) so that compression is never canceled.
1794 auto task = MakeUnique<SourceCompressionTask>(cx->runtime(), ss);
1795 if (!task) {
1796 ReportOutOfMemory(cx);
1797 return false;
1798 }
1799
1800 MOZ_ASSERT(ss->refs > sourceRefs, "must have at least two refs now");
1801
1802 // Attempt to compress. This may not succeed if OOM happens, but (because
1803 // it ordinarily happens on a helper thread) no error will ever be set here.
1804 MOZ_ASSERT(!cx->isExceptionPending());
1805 ss->performTaskWork(task.get());
1806 MOZ_ASSERT(!cx->isExceptionPending());
1807
1808 // Convert |ss| from uncompressed to compressed data.
1809 task->complete();
1810
1811 MOZ_ASSERT(!cx->isExceptionPending());
1812 }
1813
1814 // The only way source won't be compressed here is if OOM happened.
1815 return ss->hasCompressedSource();
1816 }
1817
1818 void ScriptSource::addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
1819 JS::ScriptSourceInfo* info) const {
1820 info->misc += mallocSizeOf(this);
1821 info->numScripts++;
1822 }
1823
1824 frontend::InitialStencilAndDelazifications*
1825 ScriptSourceObject::maybeGetStencils() {
1826 Value stencilsVal = getReservedSlot(STENCILS_SLOT);
1827 if (stencilsVal.isUndefined()) {
1828 return nullptr;
1829 }
1830
1831 return reinterpret_cast<frontend::InitialStencilAndDelazifications*>(
1832 uintptr_t(stencilsVal.toPrivate()) & ~STENCILS_MASK);
1833 }
1834
1835 void ScriptSourceObject::clearStencils() {
1836 auto* stencils = maybeGetStencils();
1837 if (!stencils) {
1838 return;
1839 }
1840
1841 stencils->Release();
1842 setReservedSlot(STENCILS_SLOT, UndefinedValue());
1843 }
1844
1845 template <uintptr_t flag>
1846 void ScriptSourceObject::setStencilsFlag() {
1847 JS::Value stencilsVal = getReservedSlot(STENCILS_SLOT);
1848 MOZ_ASSERT(!stencilsVal.isUndefined(),
1849 "This should be called after setStencils");
1850 uintptr_t raw = uintptr_t(stencilsVal.toPrivate());
1851 MOZ_ASSERT((raw & flag) == 0);
1852 raw |= flag;
1853 setReservedSlot(STENCILS_SLOT, PrivateValue(raw));
1854 }
1855
1856 template <uintptr_t flag>
1857 void ScriptSourceObject::unsetStencilsFlag() {
1858 JS::Value stencilsVal = getReservedSlot(STENCILS_SLOT);
1859 MOZ_ASSERT(!stencilsVal.isUndefined(),
1860 "This should be called after setStencils");
1861 uintptr_t raw = uintptr_t(stencilsVal.toPrivate());
1862 raw &= ~flag;
1863 if (raw & STENCILS_MASK) {
1864 setReservedSlot(STENCILS_SLOT, PrivateValue(raw));
1865 } else {
1866 clearStencils();
1867 }
1868 }
1869
1870 template <uintptr_t flag>
1871 bool ScriptSourceObject::isStencilsFlagSet() const {
1872 JS::Value stencilsVal = getReservedSlot(STENCILS_SLOT);
1873 if (stencilsVal.isUndefined()) {
1874 return false;
1875 }
1876 uintptr_t raw = uintptr_t(stencilsVal.toPrivate());
1877 return bool(raw & flag);
1878 }
1879
1880 void ScriptSourceObject::setStencils(
1881 already_AddRefed<frontend::InitialStencilAndDelazifications> stencils) {
1882 MOZ_ASSERT(!maybeGetStencils());
1883 setReservedSlot(STENCILS_SLOT, PrivateValue(stencils.take()));
1884 }
1885
1886 void ScriptSourceObject::setCollectingDelazifications() {
1887 setStencilsFlag<STENCILS_COLLECTING_DELAZIFICATIONS_FLAG>();
1888 }
1889
1890 void ScriptSourceObject::unsetCollectingDelazifications() {
1891 unsetStencilsFlag<STENCILS_COLLECTING_DELAZIFICATIONS_FLAG>();
1892 }
1893
1894 bool ScriptSourceObject::isCollectingDelazifications() const {
1895 return isStencilsFlagSet<STENCILS_COLLECTING_DELAZIFICATIONS_FLAG>();
1896 }
1897
1898 void ScriptSourceObject::setSharingDelazifications() {
1899 setStencilsFlag<STENCILS_SHARING_DELAZIFICATIONS_FLAG>();
1900 }
1901
1902 bool ScriptSourceObject::isSharingDelazifications() const {
1903 return isStencilsFlagSet<STENCILS_SHARING_DELAZIFICATIONS_FLAG>();
1904 }
1905
1906 template <typename Unit>
1907 [[nodiscard]] bool ScriptSource::initializeUnretrievableUncompressedSource(
1908 FrontendContext* fc, EntryUnits<Unit>&& source, size_t length) {
1909 MOZ_ASSERT(data.is<Missing>(), "must be initializing a fresh ScriptSource");
1910 return setUncompressedSourceHelper(fc, std::move(source), length,
1911 SourceRetrievable::No);
1912 }
1913
1914 template bool ScriptSource::initializeUnretrievableUncompressedSource(
1915 FrontendContext* fc, EntryUnits<Utf8Unit>&& source, size_t length);
1916 template bool ScriptSource::initializeUnretrievableUncompressedSource(
1917 FrontendContext* fc, EntryUnits<char16_t>&& source, size_t length);
1918
1919 // Format and return a cx->pod_malloc'ed URL for a generated script like:
1920 // {filename} line {lineno} > {introducer}
1921 // For example:
1922 // foo.js line 7 > eval
1923 // indicating code compiled by the call to 'eval' on line 7 of foo.js.
1924 UniqueChars js::FormatIntroducedFilename(const char* filename, uint32_t lineno,
1925 const char* introducer) {
1926 // Compute the length of the string in advance, so we can allocate a
1927 // buffer of the right size on the first shot.
1928 //
1929 // (JS_smprintf would be perfect, as that allocates the result
1930 // dynamically as it formats the string, but it won't allocate from cx,
1931 // and wants us to use a special free function.)
1932 char linenoBuf[15];
1933 size_t filenameLen = strlen(filename);
1934 size_t linenoLen = SprintfLiteral(linenoBuf, "%u", lineno);
1935 size_t introducerLen = strlen(introducer);
1936 size_t len = filenameLen + 6 /* == strlen(" line ") */ + linenoLen +
1937 3 /* == strlen(" > ") */ + introducerLen + 1 /* \0 */;
1938 UniqueChars formatted(js_pod_malloc<char>(len));
1939 if (!formatted) {
1940 return nullptr;
1941 }
1942
1943 mozilla::DebugOnly<size_t> checkLen = snprintf(
1944 formatted.get(), len, "%s line %s > %s", filename, linenoBuf, introducer);
1945 MOZ_ASSERT(checkLen == len - 1);
1946
1947 return formatted;
1948 }
1949
1950 bool ScriptSource::initFromOptions(FrontendContext* fc,
1951 const ReadOnlyCompileOptions& options) {
1952 MOZ_ASSERT(!filename_);
1953 MOZ_ASSERT(!introducerFilename_);
1954
1955 mutedErrors_ = options.mutedErrors();
1956 delazificationMode_ = options.eagerDelazificationStrategy();
1957
1958 startLine_ = options.lineno;
1959 startColumn_ = JS::LimitedColumnNumberOneOrigin::fromUnlimited(
1960 JS::ColumnNumberOneOrigin(options.column));
1961 introductionType_ = options.introductionType;
1962 setIntroductionOffset(options.introductionOffset);
1963 // The parameterListEnd_ is initialized later by setParameterListEnd, before
1964 // we expose any scripts that use this ScriptSource to the debugger.
1965
1966 if (options.hasIntroductionInfo) {
1967 MOZ_ASSERT(options.introductionType != nullptr);
1968 const char* filename =
1969 options.filename() ? options.filename().c_str() : "<unknown>";
1970 UniqueChars formatted = FormatIntroducedFilename(
1971 filename, options.introductionLineno, options.introductionType);
1972 if (!formatted) {
1973 ReportOutOfMemory(fc);
1974 return false;
1975 }
1976 if (!setFilename(fc, std::move(formatted))) {
1977 return false;
1978 }
1979 } else if (options.filename()) {
1980 if (!setFilename(fc, options.filename().c_str())) {
1981 return false;
1982 }
1983 }
1984
1985 if (options.introducerFilename()) {
1986 if (!setIntroducerFilename(fc, options.introducerFilename().c_str())) {
1987 return false;
1988 }
1989 }
1990
1991 return true;
1992 }
1993
1994 // Use the SharedImmutableString map to deduplicate input string. The input
1995 // string must be null-terminated.
1996 template <typename SharedT, typename CharT>
1997 static SharedT GetOrCreateStringZ(FrontendContext* fc,
1998 UniquePtr<CharT[], JS::FreePolicy>&& str) {
1999 size_t lengthWithNull = std::char_traits<CharT>::length(str.get()) + 1;
2000 auto res = SharedImmutableStringsCache::getSingleton().getOrCreate(
2001 std::move(str), lengthWithNull);
2002 if (!res) {
2003 ReportOutOfMemory(fc);
2004 }
2005 return res;
2006 }
2007
2008 SharedImmutableString ScriptSource::getOrCreateStringZ(FrontendContext* fc,
2009 UniqueChars&& str) {
2010 return GetOrCreateStringZ<SharedImmutableString>(fc, std::move(str));
2011 }
2012
2013 SharedImmutableTwoByteString ScriptSource::getOrCreateStringZ(
2014 FrontendContext* fc, UniqueTwoByteChars&& str) {
2015 return GetOrCreateStringZ<SharedImmutableTwoByteString>(fc, std::move(str));
2016 }
2017
2018 bool ScriptSource::setFilename(FrontendContext* fc, const char* filename) {
2019 UniqueChars owned = DuplicateString(fc, filename);
2020 if (!owned) {
2021 return false;
2022 }
2023 return setFilename(fc, std::move(owned));
2024 }
2025
2026 bool ScriptSource::setFilename(FrontendContext* fc, UniqueChars&& filename) {
2027 MOZ_ASSERT(!filename_);
2028 filename_ = getOrCreateStringZ(fc, std::move(filename));
2029 if (filename_) {
2030 filenameHash_ =
2031 mozilla::HashStringKnownLength(filename_.chars(), filename_.length());
2032 return true;
2033 }
2034 return false;
2035 }
2036
2037 bool ScriptSource::setIntroducerFilename(FrontendContext* fc,
2038 const char* filename) {
2039 UniqueChars owned = DuplicateString(fc, filename);
2040 if (!owned) {
2041 return false;
2042 }
2043 return setIntroducerFilename(fc, std::move(owned));
2044 }
2045
2046 bool ScriptSource::setIntroducerFilename(FrontendContext* fc,
2047 UniqueChars&& filename) {
2048 MOZ_ASSERT(!introducerFilename_);
2049 introducerFilename_ = getOrCreateStringZ(fc, std::move(filename));
2050 return bool(introducerFilename_);
2051 }
2052
2053 bool ScriptSource::setDisplayURL(FrontendContext* fc, const char16_t* url) {
2054 UniqueTwoByteChars owned = DuplicateString(fc, url);
2055 if (!owned) {
2056 return false;
2057 }
2058 return setDisplayURL(fc, std::move(owned));
2059 }
2060
2061 bool ScriptSource::setDisplayURL(FrontendContext* fc,
2062 UniqueTwoByteChars&& url) {
2063 MOZ_ASSERT(!hasDisplayURL());
2064 MOZ_ASSERT(url);
2065 if (url[0] == '\0') {
2066 return true;
2067 }
2068
2069 displayURL_ = getOrCreateStringZ(fc, std::move(url));
2070 return bool(displayURL_);
2071 }
2072
2073 bool ScriptSource::setSourceMapURL(FrontendContext* fc, const char16_t* url) {
2074 UniqueTwoByteChars owned = DuplicateString(fc, url);
2075 if (!owned) {
2076 return false;
2077 }
2078 return setSourceMapURL(fc, std::move(owned));
2079 }
2080
2081 bool ScriptSource::setSourceMapURL(FrontendContext* fc,
2082 UniqueTwoByteChars&& url) {
2083 MOZ_ASSERT(url);
2084 if (url[0] == '\0') {
2085 return true;
2086 }
2087
2088 sourceMapURL_ = getOrCreateStringZ(fc, std::move(url));
2089 return bool(sourceMapURL_);
2090 }
2091
2092 /* static */ mozilla::Atomic<uint32_t, mozilla::SequentiallyConsistent>
2093 ScriptSource::idCount_;
2094
2095 /*
2096 * [SMDOC] JSScript data layout (immutable)
2097 *
2098 * Script data that shareable across processes. There are no pointers (GC or
2099 * otherwise) and the data is relocatable.
2100 *
2101 * Array elements Pointed to by Length
2102 * -------------- ------------- ------
2103 * jsbytecode code() codeLength()
2104 * jsscrnote notes() noteLength()
2105 * uint32_t resumeOffsets()
2106 * ScopeNote scopeNotes()
2107 * TryNote tryNotes()
2108 */
2109
2110 /* static */ CheckedInt<uint32_t> ImmutableScriptData::sizeFor(
2111 uint32_t codeLength, uint32_t noteLength, uint32_t numResumeOffsets,
2112 uint32_t numScopeNotes, uint32_t numTryNotes) {
2113 // Take a count of which optional arrays will be used and need offset info.
2114 unsigned numOptionalArrays = unsigned(numResumeOffsets > 0) +
2115 unsigned(numScopeNotes > 0) +
2116 unsigned(numTryNotes > 0);
2117
2118 // Compute size including trailing arrays.
2119 CheckedInt<uint32_t> size = sizeof(ImmutableScriptData);
2120 size += sizeof(Flags);
2121 size += CheckedInt<uint32_t>(codeLength) * sizeof(jsbytecode);
2122 size += CheckedInt<uint32_t>(noteLength) * sizeof(SrcNote);
2123 size += CheckedInt<uint32_t>(numOptionalArrays) * sizeof(Offset);
2124 size += CheckedInt<uint32_t>(numResumeOffsets) * sizeof(uint32_t);
2125 size += CheckedInt<uint32_t>(numScopeNotes) * sizeof(ScopeNote);
2126 size += CheckedInt<uint32_t>(numTryNotes) * sizeof(TryNote);
2127
2128 return size;
2129 }
2130
2131 js::UniquePtr<ImmutableScriptData> js::ImmutableScriptData::new_(
2132 FrontendContext* fc, uint32_t codeLength, uint32_t noteLength,
2133 uint32_t numResumeOffsets, uint32_t numScopeNotes, uint32_t numTryNotes) {
2134 auto size = sizeFor(codeLength, noteLength, numResumeOffsets, numScopeNotes,
2135 numTryNotes);
2136 if (!size.isValid()) {
2137 ReportAllocationOverflow(fc);
2138 return nullptr;
2139 }
2140
2141 // Allocate contiguous raw buffer.
2142 void* raw = fc->getAllocator()->pod_malloc<uint8_t>(size.value());
2143 MOZ_ASSERT(uintptr_t(raw) % alignof(ImmutableScriptData) == 0);
2144 if (!raw) {
2145 return nullptr;
2146 }
2147
2148 // Constuct the ImmutableScriptData. Trailing arrays are uninitialized but
2149 // GCPtrs are put into a safe state.
2150 UniquePtr<ImmutableScriptData> result(new (raw) ImmutableScriptData(
2151 codeLength, noteLength, numResumeOffsets, numScopeNotes, numTryNotes));
2152 if (!result) {
2153 return nullptr;
2154 }
2155
2156 // Sanity check
2157 MOZ_ASSERT(result->endOffset() == size.value());
2158
2159 return result;
2160 }
2161
2162 js::UniquePtr<ImmutableScriptData> js::ImmutableScriptData::new_(
2163 FrontendContext* fc, uint32_t totalSize) {
2164 void* raw = fc->getAllocator()->pod_malloc<uint8_t>(totalSize);
2165 MOZ_ASSERT(uintptr_t(raw) % alignof(ImmutableScriptData) == 0);
2166 UniquePtr<ImmutableScriptData> result(
2167 reinterpret_cast<ImmutableScriptData*>(raw));
2168 return result;
2169 }
2170
2171 bool js::ImmutableScriptData::validateLayout(uint32_t expectedSize) {
2172 constexpr size_t HeaderSize = sizeof(js::ImmutableScriptData);
2173 constexpr size_t OptionalOffsetsMaxSize = 3 * sizeof(Offset);
2174
2175 // Check that the optional-offsets array lies within the allocation before we
2176 // try to read from it while computing sizes. Remember that the array *ends*
2177 // at the `optArrayOffset_`.
2178 static_assert(OptionalOffsetsMaxSize <= HeaderSize);
2179 if (HeaderSize > optArrayOffset_) {
2180 return false;
2181 }
2182 if (optArrayOffset_ > expectedSize) {
2183 return false;
2184 }
2185
2186 // Round-trip the size computation using `CheckedInt` to detect overflow. This
2187 // should indirectly validate most alignment, size, and ordering requirments.
2188 auto size = sizeFor(codeLength(), noteLength(), resumeOffsets().size(),
2189 scopeNotes().size(), tryNotes().size());
2190 return size.isValid() && (size.value() == expectedSize);
2191 }
2192
2193 /* static */
2194 SharedImmutableScriptData* SharedImmutableScriptData::create(
2195 FrontendContext* fc) {
2196 return fc->getAllocator()->new_<SharedImmutableScriptData>();
2197 }
2198
2199 /* static */
2200 SharedImmutableScriptData* SharedImmutableScriptData::createWith(
2201 FrontendContext* fc, js::UniquePtr<ImmutableScriptData>&& isd) {
2202 MOZ_ASSERT(isd.get());
2203 SharedImmutableScriptData* sisd = create(fc);
2204 if (!sisd) {
2205 return nullptr;
2206 }
2207
2208 sisd->setOwn(std::move(isd));
2209 return sisd;
2210 }
2211
2212 void JSScript::relazify(JSRuntime* rt) {
2213 js::Scope* scope = enclosingScope();
2214 UniquePtr<PrivateScriptData> scriptData;
2215
2216 // Any JIT compiles should have been released, so we already point to the
2217 // interpreter trampoline which supports lazy scripts.
2218 MOZ_ASSERT_IF(jit::HasJitBackend(), isUsingInterpreterTrampoline(rt));
2219
2220 realm()->removeFromCompileQueue(this);
2221
2222 // Without bytecode, the script counts are invalid so destroy them if they
2223 // still exist.
2224 destroyScriptCounts();
2225
2226 // Release the bytecode and gcthings list.
2227 // NOTE: We clear the PrivateScriptData to nullptr. This is fine because we
2228 // only allowed relazification (via AllowRelazify) if the original lazy
2229 // script we compiled from had a nullptr PrivateScriptData.
2230 swapData(scriptData);
2231 freeSharedData();
2232
2233 // We should not still be in any side-tables for the debugger or
2234 // code-coverage. The finalizer will not be able to clean them up once
2235 // bytecode is released. We check in JSFunction::maybeRelazify() for these
2236 // conditions before requesting relazification.
2237 MOZ_ASSERT(!coverage::IsLCovEnabled());
2238 MOZ_ASSERT(!hasScriptCounts());
2239 MOZ_ASSERT(!hasDebugScript());
2240
2241 // Rollback warmUpData_ to have enclosingScope.
2242 MOZ_ASSERT(warmUpData_.isWarmUpCount(),
2243 "JitScript should already be released");
2244 warmUpData_.resetWarmUpCount(0);
2245 warmUpData_.initEnclosingScope(scope);
2246
2247 MOZ_ASSERT(isReadyForDelazification());
2248 }
2249
2250 // Takes ownership of the passed SharedImmutableScriptData and either adds it
2251 // into the runtime's SharedImmutableScriptDataTable, or frees it if a matching
2252 // entry already exists and replaces the passed RefPtr with the existing entry.
2253 /* static */
2254 bool SharedImmutableScriptData::shareScriptData(
2255 FrontendContext* fc, RefPtr<SharedImmutableScriptData>& sisd) {
2256 MOZ_ASSERT(sisd);
2257 MOZ_ASSERT(sisd->refCount() == 1);
2258
2259 SharedImmutableScriptData* data = sisd.get();
2260
2261 SharedImmutableScriptData::Hasher::Lookup lookup(data);
2262
2263 Maybe<AutoLockGlobalScriptData> lock;
2264 js::SharedImmutableScriptDataTable& table =
2265 fc->scriptDataTableHolder()->getMaybeLocked(lock);
2266
2267 SharedImmutableScriptDataTable::AddPtr p = table.lookupForAdd(lookup);
2268 if (p) {
2269 MOZ_ASSERT(data != *p);
2270 sisd = *p;
2271 } else {
2272 if (!table.add(p, data)) {
2273 ReportOutOfMemory(fc);
2274 return false;
2275 }
2276
2277 // Being in the table counts as a reference on the script data.
2278 data->AddRef();
2279 }
2280
2281 // Refs: sisd argument, SharedImmutableScriptDataTable
2282 MOZ_ASSERT(sisd->refCount() >= 2);
2283
2284 return true;
2285 }
2286
2287 static void SweepScriptDataTable(SharedImmutableScriptDataTable& table) {
2288 // Entries are removed from the table when their reference count is one,
2289 // i.e. when the only reference to them is from the table entry.
2290
2291 for (SharedImmutableScriptDataTable::Enum e(table); !e.empty();
2292 e.popFront()) {
2293 SharedImmutableScriptData* sharedData = e.front();
2294 if (sharedData->refCount() == 1) {
2295 sharedData->Release();
2296 e.removeFront();
2297 }
2298 }
2299 }
2300
2301 void js::SweepScriptData(JSRuntime* rt) {
2302 SweepScriptDataTable(rt->scriptDataTableHolder().getWithoutLock());
2303
2304 AutoLockGlobalScriptData lock;
2305 SweepScriptDataTable(js::globalSharedScriptDataTableHolder.get(lock));
2306 }
2307
2308 inline size_t PrivateScriptData::allocationSize() const { return endOffset(); }
2309
2310 // Initialize and placement-new the trailing arrays.
2311 PrivateScriptData::PrivateScriptData(uint32_t ngcthings)
2312 : ngcthings(ngcthings) {
2313 // Variable-length data begins immediately after PrivateScriptData itself.
2314 // NOTE: Alignment is computed using cursor/offset so the alignment of
2315 // PrivateScriptData must be stricter than any trailing array type.
2316 Offset cursor = sizeof(PrivateScriptData);
2317
2318 // Layout and initialize the gcthings array.
2319 {
2320 initElements<JS::GCCellPtr>(cursor, ngcthings);
2321 cursor += ngcthings * sizeof(JS::GCCellPtr);
2322 }
2323
2324 // Sanity check.
2325 MOZ_ASSERT(endOffset() == cursor);
2326 }
2327
2328 /* static */
2329 PrivateScriptData* PrivateScriptData::new_(JSContext* cx, uint32_t ngcthings) {
2330 // Compute size including trailing arrays.
2331 CheckedInt<Offset> size = sizeof(PrivateScriptData);
2332 size += CheckedInt<Offset>(ngcthings) * sizeof(JS::GCCellPtr);
2333 if (!size.isValid()) {
2334 ReportAllocationOverflow(cx);
2335 return nullptr;
2336 }
2337
2338 // Allocate contiguous raw buffer for the trailing arrays.
2339 void* raw = cx->pod_malloc<uint8_t>(size.value());
2340 MOZ_ASSERT(uintptr_t(raw) % alignof(PrivateScriptData) == 0);
2341 if (!raw) {
2342 return nullptr;
2343 }
2344
2345 // Constuct the PrivateScriptData. Trailing arrays are uninitialized but
2346 // GCPtrs are put into a safe state.
2347 PrivateScriptData* result = new (raw) PrivateScriptData(ngcthings);
2348 if (!result) {
2349 return nullptr;
2350 }
2351
2352 // Sanity check.
2353 MOZ_ASSERT(result->endOffset() == size.value());
2354
2355 return result;
2356 }
2357
2358 /* static */
2359 bool PrivateScriptData::InitFromStencil(
2360 JSContext* cx, js::HandleScript script,
2361 const js::frontend::CompilationAtomCache& atomCache,
2362 const js::frontend::CompilationStencil& stencil,
2363 js::frontend::CompilationGCOutput& gcOutput,
2364 const js::frontend::ScriptIndex scriptIndex) {
2365 js::frontend::ScriptStencil& scriptStencil = stencil.scriptData[scriptIndex];
2366 uint32_t ngcthings = scriptStencil.gcThingsLength;
2367
2368 MOZ_ASSERT(ngcthings <= INDEX_LIMIT);
2369
2370 // Create and initialize PrivateScriptData
2371 if (!JSScript::createPrivateScriptData(cx, script, ngcthings)) {
2372 return false;
2373 }
2374
2375 js::PrivateScriptData* data = script->data_;
2376 if (ngcthings) {
2377 if (!EmitScriptThingsVector(cx, atomCache, stencil, gcOutput,
2378 scriptStencil.gcthings(stencil),
2379 data->gcthings())) {
2380 return false;
2381 }
2382 }
2383
2384 return true;
2385 }
2386
2387 void PrivateScriptData::trace(JSTracer* trc) {
2388 for (JS::GCCellPtr& elem : gcthings()) {
2389 TraceManuallyBarrieredGCCellPtr(trc, &elem, "script-gcthing");
2390 }
2391 }
2392
2393 /*static*/
2394 JSScript* JSScript::Create(JSContext* cx, JS::Handle<JSFunction*> function,
2395 js::Handle<ScriptSourceObject*> sourceObject,
2396 const SourceExtent& extent,
2397 js::ImmutableScriptFlags flags) {
2398 return static_cast<JSScript*>(
2399 BaseScript::New(cx, function, sourceObject, extent, flags));
2400 }
2401
2402 #ifdef MOZ_VTUNE
2403 uint32_t JSScript::vtuneMethodID() {
2404 if (!zone()->scriptVTuneIdMap) {
2405 auto map = MakeUnique<ScriptVTuneIdMap>();
2406 if (!map) {
2407 MOZ_CRASH("Failed to allocate ScriptVTuneIdMap");
2408 }
2409
2410 zone()->scriptVTuneIdMap = std::move(map);
2411 }
2412
2413 ScriptVTuneIdMap::AddPtr p = zone()->scriptVTuneIdMap->lookupForAdd(this);
2414 if (p) {
2415 return p->value();
2416 }
2417
2418 MOZ_ASSERT(this->hasBytecode());
2419
2420 uint32_t id = vtune::GenerateUniqueMethodID();
2421 if (!zone()->scriptVTuneIdMap->add(p, this, id)) {
2422 MOZ_CRASH("Failed to add vtune method id");
2423 }
2424
2425 return id;
2426 }
2427 #endif
2428
2429 /* static */
2430 bool JSScript::createPrivateScriptData(JSContext* cx, HandleScript script,
2431 uint32_t ngcthings) {
2432 cx->check(script);
2433
2434 UniquePtr<PrivateScriptData> data(PrivateScriptData::new_(cx, ngcthings));
2435 if (!data) {
2436 return false;
2437 }
2438
2439 script->swapData(data);
2440 MOZ_ASSERT(!data);
2441
2442 return true;
2443 }
2444
2445 /* static */
2446 bool JSScript::fullyInitFromStencil(
2447 JSContext* cx, const js::frontend::CompilationAtomCache& atomCache,
2448 const js::frontend::CompilationStencil& stencil,
2449 frontend::CompilationGCOutput& gcOutput, HandleScript script,
2450 const js::frontend::ScriptIndex scriptIndex) {
2451 MutableScriptFlags lazyMutableFlags;
2452 Rooted<Scope*> lazyEnclosingScope(cx);
2453
2454 // A holder for the lazy PrivateScriptData that we must keep around in case
2455 // this process fails and we must return the script to its original state.
2456 //
2457 // This is initialized by BaseScript::swapData() which will run pre-barriers
2458 // for us. On successful conversion to non-lazy script, the old script data
2459 // here will be released by the UniquePtr.
2460 Rooted<UniquePtr<PrivateScriptData>> lazyData(cx);
2461
2462 // Whether we are a newborn script or an existing lazy script, we should
2463 // already be pointing to the interpreter trampoline.
2464 MOZ_ASSERT_IF(jit::HasJitBackend(),
2465 script->isUsingInterpreterTrampoline(cx->runtime()));
2466
2467 // If we are using an existing lazy script, record enough info to be able to
2468 // rollback on failure.
2469 if (script->isReadyForDelazification()) {
2470 lazyMutableFlags = script->mutableFlags_;
2471 lazyEnclosingScope = script->releaseEnclosingScope();
2472 script->swapData(lazyData.get());
2473 MOZ_ASSERT(script->sharedData_ == nullptr);
2474 }
2475
2476 // Restore the script to lazy state on failure. If this was a fresh script, we
2477 // just need to clear bytecode to mark script as incomplete.
2478 auto rollbackGuard = mozilla::MakeScopeExit([&] {
2479 if (lazyEnclosingScope) {
2480 script->mutableFlags_ = lazyMutableFlags;
2481 script->warmUpData_.initEnclosingScope(lazyEnclosingScope);
2482 script->swapData(lazyData.get());
2483 script->sharedData_ = nullptr;
2484
2485 MOZ_ASSERT(script->isReadyForDelazification());
2486 } else {
2487 script->sharedData_ = nullptr;
2488 }
2489 });
2490
2491 // The counts of indexed things must be checked during code generation.
2492 MOZ_ASSERT(stencil.scriptData[scriptIndex].gcThingsLength <= INDEX_LIMIT);
2493
2494 // Note: These flags should already be correct when the BaseScript was
2495 // allocated.
2496 MOZ_ASSERT_IF(stencil.isInitialStencil(),
2497 script->immutableFlags() ==
2498 stencil.scriptExtra[scriptIndex].immutableFlags);
2499
2500 // Create and initialize PrivateScriptData
2501 if (!PrivateScriptData::InitFromStencil(cx, script, atomCache, stencil,
2502 gcOutput, scriptIndex)) {
2503 return false;
2504 }
2505
2506 // Member-initializer data is computed in initial parse only. If we are
2507 // delazifying, make sure to copy it off the `lazyData` before we throw it
2508 // away.
2509 if (script->useMemberInitializers()) {
2510 if (stencil.isInitialStencil()) {
2511 MemberInitializers initializers(
2512 stencil.scriptExtra[scriptIndex].memberInitializers());
2513 script->setMemberInitializers(initializers);
2514 } else {
2515 script->setMemberInitializers(lazyData.get()->getMemberInitializers());
2516 }
2517 }
2518 auto* scriptData = stencil.sharedData.get(scriptIndex);
2519 script->initSharedData(scriptData);
2520
2521 // NOTE: JSScript is now constructed and should be linked in.
2522 rollbackGuard.release();
2523
2524 // Link Scope -> JSFunction -> BaseScript.
2525 if (script->isFunction()) {
2526 JSFunction* fun = gcOutput.getFunction(scriptIndex);
2527 script->bodyScope()->as<FunctionScope>().initCanonicalFunction(fun);
2528 if (fun->isIncomplete()) {
2529 fun->initScript(script);
2530 } else if (fun->hasSelfHostedLazyScript()) {
2531 fun->clearSelfHostedLazyScript();
2532 fun->initScript(script);
2533 } else {
2534 // We are delazifying in-place.
2535 MOZ_ASSERT(fun->baseScript() == script);
2536 }
2537 }
2538
2539 // NOTE: The caller is responsible for linking ModuleObjects if this is a
2540 // module script.
2541
2542 #ifdef JS_STRUCTURED_SPEW
2543 // We want this to happen after line number initialization to allow filtering
2544 // to work.
2545 script->setSpewEnabled(cx->spewer().enabled(script));
2546 #endif
2547
2548 #ifdef DEBUG
2549 script->assertValidJumpTargets();
2550 #endif
2551
2552 if (coverage::IsLCovEnabled()) {
2553 if (!coverage::InitScriptCoverage(cx, script)) {
2554 return false;
2555 }
2556 }
2557
2558 return true;
2559 }
2560
2561 JSScript* JSScript::fromStencil(JSContext* cx,
2562 frontend::CompilationAtomCache& atomCache,
2563 const frontend::CompilationStencil& stencil,
2564 frontend::CompilationGCOutput& gcOutput,
2565 frontend::ScriptIndex scriptIndex) {
2566 js::frontend::ScriptStencil& scriptStencil = stencil.scriptData[scriptIndex];
2567 js::frontend::ScriptStencilExtra& scriptExtra =
2568 stencil.scriptExtra[scriptIndex];
2569 MOZ_ASSERT(scriptStencil.hasSharedData(),
2570 "Need generated bytecode to use JSScript::fromStencil");
2571
2572 Rooted<JSFunction*> function(cx);
2573 if (scriptStencil.isFunction()) {
2574 function = gcOutput.getFunction(scriptIndex);
2575 }
2576
2577 Rooted<ScriptSourceObject*> sourceObject(cx, gcOutput.sourceObject);
2578 RootedScript script(cx, Create(cx, function, sourceObject, scriptExtra.extent,
2579 scriptExtra.immutableFlags));
2580 if (!script) {
2581 return nullptr;
2582 }
2583
2584 if (!fullyInitFromStencil(cx, atomCache, stencil, gcOutput, script,
2585 scriptIndex)) {
2586 return nullptr;
2587 }
2588
2589 return script;
2590 }
2591
2592 #ifdef DEBUG
2593 void JSScript::assertValidJumpTargets() const {
2594 BytecodeLocation mainLoc = mainLocation();
2595 BytecodeLocation endLoc = endLocation();
2596 AllBytecodesIterable iter(this);
2597 for (BytecodeLocation loc : iter) {
2598 // Check jump instructions' target.
2599 if (loc.isJump()) {
2600 BytecodeLocation target = loc.getJumpTarget();
2601 MOZ_ASSERT(mainLoc <= target && target < endLoc);
2602 MOZ_ASSERT(target.isJumpTarget());
2603
2604 // All backward jumps must be to a JSOp::LoopHead op. This is an invariant
2605 // we want to maintain to simplify JIT compilation and bytecode analysis.
2606 MOZ_ASSERT_IF(target < loc, target.is(JSOp::LoopHead));
2607 MOZ_ASSERT_IF(target < loc, IsBackedgePC(loc.toRawBytecode()));
2608
2609 // All forward jumps must be to a JSOp::JumpTarget op.
2610 MOZ_ASSERT_IF(target > loc, target.is(JSOp::JumpTarget));
2611
2612 // Jumps must not cross scope boundaries.
2613 MOZ_ASSERT(loc.innermostScope(this) == target.innermostScope(this));
2614
2615 // Check fallthrough of conditional jump instructions.
2616 if (loc.fallsThrough()) {
2617 BytecodeLocation fallthrough = loc.next();
2618 MOZ_ASSERT(mainLoc <= fallthrough && fallthrough < endLoc);
2619 MOZ_ASSERT(fallthrough.isJumpTarget());
2620 }
2621 }
2622
2623 // Check table switch case labels.
2624 if (loc.is(JSOp::TableSwitch)) {
2625 BytecodeLocation target = loc.getTableSwitchDefaultTarget();
2626
2627 // Default target.
2628 MOZ_ASSERT(mainLoc <= target && target < endLoc);
2629 MOZ_ASSERT(target.is(JSOp::JumpTarget));
2630
2631 int32_t low = loc.getTableSwitchLow();
2632 int32_t high = loc.getTableSwitchHigh();
2633
2634 for (int i = 0; i < high - low + 1; i++) {
2635 BytecodeLocation switchCase = loc.getTableSwitchCaseTarget(this, i);
2636 MOZ_ASSERT(mainLoc <= switchCase && switchCase < endLoc);
2637 MOZ_ASSERT(switchCase.is(JSOp::JumpTarget));
2638 }
2639 }
2640 }
2641
2642 // Check catch/finally blocks as jump targets.
2643 for (const TryNote& tn : trynotes()) {
2644 if (tn.kind() != TryNoteKind::Catch && tn.kind() != TryNoteKind::Finally) {
2645 continue;
2646 }
2647
2648 jsbytecode* tryStart = offsetToPC(tn.start);
2649 jsbytecode* tryPc = tryStart - JSOpLength_Try;
2650 MOZ_ASSERT(JSOp(*tryPc) == JSOp::Try);
2651
2652 jsbytecode* tryTarget = tryStart + tn.length;
2653 MOZ_ASSERT(main() <= tryTarget && tryTarget < codeEnd());
2654 MOZ_ASSERT(BytecodeIsJumpTarget(JSOp(*tryTarget)));
2655 }
2656 }
2657 #endif
2658
2659 void JSScript::addSizeOfJitScript(mozilla::MallocSizeOf mallocSizeOf,
2660 size_t* sizeOfJitScript,
2661 size_t* sizeOfAllocSites) const {
2662 if (!hasJitScript()) {
2663 return;
2664 }
2665
2666 jitScript()->addSizeOfIncludingThis(mallocSizeOf, sizeOfJitScript,
2667 sizeOfAllocSites);
2668 }
2669
2670 js::GlobalObject& JSScript::uninlinedGlobal() const { return global(); }
2671
2672 unsigned js::PCToLineNumber(unsigned startLine,
2673 JS::LimitedColumnNumberOneOrigin startCol,
2674 SrcNote* notes, SrcNote* notesEnd, jsbytecode* code,
2675 jsbytecode* pc,
2676 JS::LimitedColumnNumberOneOrigin* columnp) {
2677 unsigned lineno = startLine;
2678 JS::LimitedColumnNumberOneOrigin column = startCol;
2679
2680 /*
2681 * Walk through source notes accumulating their deltas, keeping track of
2682 * line-number notes, until we pass the note for pc's offset within
2683 * script->code.
2684 */
2685 ptrdiff_t offset = 0;
2686 ptrdiff_t target = pc - code;
2687 for (SrcNoteIterator iter(notes, notesEnd); !iter.atEnd(); ++iter) {
2688 const auto* sn = *iter;
2689 offset += sn->delta();
2690 if (offset > target) {
2691 break;
2692 }
2693
2694 SrcNoteType type = sn->type();
2695 if (type == SrcNoteType::SetLine) {
2696 lineno = SrcNote::SetLine::getLine(sn, startLine);
2697 column = JS::LimitedColumnNumberOneOrigin();
2698 } else if (type == SrcNoteType::SetLineColumn) {
2699 lineno = SrcNote::SetLineColumn::getLine(sn, startLine);
2700 column = SrcNote::SetLineColumn::getColumn(sn);
2701 } else if (type == SrcNoteType::NewLine) {
2702 lineno++;
2703 column = JS::LimitedColumnNumberOneOrigin();
2704 } else if (type == SrcNoteType::NewLineColumn) {
2705 lineno++;
2706 column = SrcNote::NewLineColumn::getColumn(sn);
2707 } else if (type == SrcNoteType::ColSpan) {
2708 column += SrcNote::ColSpan::getSpan(sn);
2709 }
2710 }
2711
2712 if (columnp) {
2713 *columnp = column;
2714 }
2715
2716 return lineno;
2717 }
2718
2719 unsigned js::PCToLineNumber(JSScript* script, jsbytecode* pc,
2720 JS::LimitedColumnNumberOneOrigin* columnp) {
2721 /* Cope with InterpreterFrame.pc value prior to entering Interpret. */
2722 if (!pc) {
2723 return 0;
2724 }
2725
2726 return PCToLineNumber(
2727 script->lineno(), JS::LimitedColumnNumberOneOrigin(script->column()),
2728 script->notes(), script->notesEnd(), script->code(), pc, columnp);
2729 }
2730
2731 jsbytecode* js::LineNumberToPC(JSScript* script, unsigned target) {
2732 ptrdiff_t offset = 0;
2733 ptrdiff_t best = -1;
2734 unsigned lineno = script->lineno();
2735 unsigned bestdiff = SrcNote::MaxOperand;
2736 for (SrcNoteIterator iter(script->notes(), script->notesEnd()); !iter.atEnd();
2737 ++iter) {
2738 const auto* sn = *iter;
2739 /*
2740 * Exact-match only if offset is not in the prologue; otherwise use
2741 * nearest greater-or-equal line number match.
2742 */
2743 if (lineno == target && offset >= ptrdiff_t(script->mainOffset())) {
2744 goto out;
2745 }
2746 if (lineno >= target) {
2747 unsigned diff = lineno - target;
2748 if (diff < bestdiff) {
2749 bestdiff = diff;
2750 best = offset;
2751 }
2752 }
2753 offset += sn->delta();
2754 SrcNoteType type = sn->type();
2755 if (type == SrcNoteType::SetLine) {
2756 lineno = SrcNote::SetLine::getLine(sn, script->lineno());
2757 } else if (type == SrcNoteType::SetLineColumn) {
2758 lineno = SrcNote::SetLineColumn::getLine(sn, script->lineno());
2759 } else if (type == SrcNoteType::NewLine ||
2760 type == SrcNoteType::NewLineColumn) {
2761 lineno++;
2762 }
2763 }
2764 if (best >= 0) {
2765 offset = best;
2766 }
2767 out:
2768 return script->offsetToPC(offset);
2769 }
2770
2771 JS_PUBLIC_API unsigned js::GetScriptLineExtent(
2772 JSScript* script, JS::LimitedColumnNumberOneOrigin* columnp) {
2773 unsigned lineno = script->lineno();
2774 JS::LimitedColumnNumberOneOrigin column = script->column();
2775 unsigned maxLineNo = lineno;
2776 for (SrcNoteIterator iter(script->notes(), script->notesEnd()); !iter.atEnd();
2777 ++iter) {
2778 const auto* sn = *iter;
2779 SrcNoteType type = sn->type();
2780 if (type == SrcNoteType::SetLine) {
2781 lineno = SrcNote::SetLine::getLine(sn, script->lineno());
2782 column = JS::LimitedColumnNumberOneOrigin();
2783 } else if (type == SrcNoteType::SetLineColumn) {
2784 lineno = SrcNote::SetLineColumn::getLine(sn, script->lineno());
2785 column = SrcNote::SetLineColumn::getColumn(sn);
2786 } else if (type == SrcNoteType::NewLine) {
2787 lineno++;
2788 column = JS::LimitedColumnNumberOneOrigin();
2789 } else if (type == SrcNoteType::NewLineColumn) {
2790 lineno++;
2791 column = SrcNote::NewLineColumn::getColumn(sn);
2792 } else if (type == SrcNoteType::ColSpan) {
2793 column += SrcNote::ColSpan::getSpan(sn);
2794 }
2795
2796 if (maxLineNo < lineno) {
2797 maxLineNo = lineno;
2798 }
2799 }
2800
2801 if (columnp) {
2802 *columnp = column;
2803 }
2804
2805 return 1 + maxLineNo - script->lineno();
2806 }
2807
2808 #ifdef JS_CACHEIR_SPEW
2809 void js::maybeUpdateWarmUpCount(JSScript* script) {
2810 if (script->needsFinalWarmUpCount()) {
2811 ScriptFinalWarmUpCountMap* map =
2812 script->zone()->scriptFinalWarmUpCountMap.get();
2813 // If needsFinalWarmUpCount is true, ScriptFinalWarmUpCountMap must have
2814 // already been created and thus must be asserted.
2815 MOZ_ASSERT(map);
2816 ScriptFinalWarmUpCountMap::Ptr p = map->lookup(script);
2817 MOZ_ASSERT(p);
2818
2819 std::get<0>(p->value()) += script->jitScript()->warmUpCount();
2820 }
2821 }
2822
2823 void js::maybeSpewScriptFinalWarmUpCount(JSScript* script) {
2824 if (script->needsFinalWarmUpCount()) {
2825 ScriptFinalWarmUpCountMap* map =
2826 script->zone()->scriptFinalWarmUpCountMap.get();
2827 // If needsFinalWarmUpCount is true, ScriptFinalWarmUpCountMap must have
2828 // already been created and thus must be asserted.
2829 MOZ_ASSERT(map);
2830 ScriptFinalWarmUpCountMap::Ptr p = map->lookup(script);
2831 MOZ_ASSERT(p);
2832 auto& tuple = p->value();
2833 uint32_t warmUpCount = std::get<0>(tuple);
2834 SharedImmutableString& scriptName = std::get<1>(tuple);
2835
2836 JSContext* cx = TlsContext.get();
2837 cx->spewer().enableSpewing();
2838
2839 // In the case that we care about a script's final warmup count but the
2840 // spewer is not enabled, AutoSpewChannel automatically sets and unsets
2841 // the proper channel for the duration of spewing a health report's warm
2842 // up count.
2843 AutoSpewChannel channel(cx, SpewChannel::CacheIRHealthReport, script);
2844 jit::CacheIRHealth cih;
2845 cih.spewScriptFinalWarmUpCount(cx, scriptName.chars(), script, warmUpCount);
2846
2847 script->zone()->scriptFinalWarmUpCountMap->remove(script);
2848 script->setNeedsFinalWarmUpCount(false);
2849 }
2850 }
2851 #endif
2852
2853 void js::DescribeScriptedCallerForDirectEval(JSContext* cx, HandleScript script,
2854 jsbytecode* pc, const char** file,
2855 uint32_t* linenop,
2856 uint32_t* pcOffset,
2857 bool* mutedErrors) {
2858 MOZ_ASSERT(script->containsPC(pc));
2859
2860 static_assert(JSOpLength_SpreadEval == JSOpLength_StrictSpreadEval,
2861 "next op after a spread must be at consistent offset");
2862 static_assert(JSOpLength_Eval == JSOpLength_StrictEval,
2863 "next op after a direct eval must be at consistent offset");
2864
2865 MOZ_ASSERT(JSOp(*pc) == JSOp::Eval || JSOp(*pc) == JSOp::StrictEval ||
2866 JSOp(*pc) == JSOp::SpreadEval ||
2867 JSOp(*pc) == JSOp::StrictSpreadEval);
2868
2869 bool isSpread =
2870 (JSOp(*pc) == JSOp::SpreadEval || JSOp(*pc) == JSOp::StrictSpreadEval);
2871 jsbytecode* nextpc =
2872 pc + (isSpread ? JSOpLength_SpreadEval : JSOpLength_Eval);
2873 MOZ_ASSERT(JSOp(*nextpc) == JSOp::Lineno);
2874
2875 *file = script->filename();
2876 *linenop = GET_UINT32(nextpc);
2877 *pcOffset = script->pcToOffset(pc);
2878 *mutedErrors = script->mutedErrors();
2879 }
2880
2881 void js::DescribeScriptedCallerForCompilation(
2882 JSContext* cx, MutableHandleScript maybeScript, const char** file,
2883 uint32_t* linenop, uint32_t* pcOffset, bool* mutedErrors) {
2884 NonBuiltinFrameIter iter(cx, cx->realm()->principals());
2885
2886 if (iter.done()) {
2887 maybeScript.set(nullptr);
2888 *file = nullptr;
2889 *linenop = 0;
2890 *pcOffset = 0;
2891 *mutedErrors = false;
2892 return;
2893 }
2894
2895 *file = iter.filename();
2896 *linenop = iter.computeLine();
2897 *mutedErrors = iter.mutedErrors();
2898
2899 // These values are only used for introducer fields which are debugging
2900 // information and can be safely left null for wasm frames.
2901 if (iter.hasScript()) {
2902 maybeScript.set(iter.script());
2903 *pcOffset = iter.pc() - maybeScript->code();
2904 } else {
2905 maybeScript.set(nullptr);
2906 *pcOffset = 0;
2907 }
2908 }
2909
2910 template <typename SourceSpan, typename TargetSpan>
2911 void CopySpan(const SourceSpan& source, TargetSpan target) {
2912 MOZ_ASSERT(source.size() == target.size());
2913 std::copy(source.cbegin(), source.cend(), target.begin());
2914 }
2915
2916 /* static */
2917 js::UniquePtr<ImmutableScriptData> ImmutableScriptData::new_(
2918 FrontendContext* fc, uint32_t mainOffset, uint32_t nfixed, uint32_t nslots,
2919 GCThingIndex bodyScopeIndex, uint32_t numICEntries, bool isFunction,
2920 uint16_t funLength, uint16_t propertyCountEstimate,
2921 mozilla::Span<const jsbytecode> code, mozilla::Span<const SrcNote> notes,
2922 mozilla::Span<const uint32_t> resumeOffsets,
2923 mozilla::Span<const ScopeNote> scopeNotes,
2924 mozilla::Span<const TryNote> tryNotes) {
2925 MOZ_RELEASE_ASSERT(code.Length() <= frontend::MaxBytecodeLength);
2926
2927 // There are 1-4 copies of SrcNoteType::Null appended after the source
2928 // notes. These are a combination of sentinel and padding values.
2929 static_assert(frontend::MaxSrcNotesLength <= UINT32_MAX - CodeNoteAlign,
2930 "Length + CodeNoteAlign shouldn't overflow UINT32_MAX");
2931 size_t noteLength = notes.Length();
2932 MOZ_RELEASE_ASSERT(noteLength <= frontend::MaxSrcNotesLength);
2933
2934 size_t notePaddingLength = ComputeNotePadding(code.Length(), noteLength);
2935
2936 // Allocate ImmutableScriptData
2937 js::UniquePtr<ImmutableScriptData> data(ImmutableScriptData::new_(
2938 fc, code.Length(), noteLength + notePaddingLength, resumeOffsets.Length(),
2939 scopeNotes.Length(), tryNotes.Length()));
2940 if (!data) {
2941 return data;
2942 }
2943
2944 // Initialize POD fields
2945 data->mainOffset = mainOffset;
2946 data->nfixed = nfixed;
2947 data->nslots = nslots;
2948 data->bodyScopeIndex = bodyScopeIndex;
2949 data->numICEntries = numICEntries;
2950 data->propertyCountEstimate = propertyCountEstimate;
2951
2952 if (isFunction) {
2953 data->funLength = funLength;
2954 }
2955
2956 // Initialize trailing arrays
2957 CopySpan(code, data->codeSpan());
2958 CopySpan(notes, data->notesSpan().To(noteLength));
2959 std::fill_n(data->notes() + noteLength, notePaddingLength,
2960 SrcNote::padding());
2961 CopySpan(resumeOffsets, data->resumeOffsets());
2962 CopySpan(scopeNotes, data->scopeNotes());
2963 CopySpan(tryNotes, data->tryNotes());
2964
2965 return data;
2966 }
2967
2968 void ScriptWarmUpData::trace(JSTracer* trc) {
2969 uintptr_t tag = data_ & TagMask;
2970 switch (tag) {
2971 case EnclosingScriptTag: {
2972 BaseScript* enclosingScript = toEnclosingScript();
2973 BaseScript* prior = enclosingScript;
2974 TraceManuallyBarrieredEdge(trc, &enclosingScript, "enclosingScript");
2975 if (enclosingScript != prior) {
2976 setTaggedPtr<EnclosingScriptTag>(enclosingScript);
2977 }
2978 break;
2979 }
2980
2981 case EnclosingScopeTag: {
2982 Scope* enclosingScope = toEnclosingScope();
2983 Scope* prior = enclosingScope;
2984 TraceManuallyBarrieredEdge(trc, &enclosingScope, "enclosingScope");
2985 if (enclosingScope != prior) {
2986 setTaggedPtr<EnclosingScopeTag>(enclosingScope);
2987 }
2988 break;
2989 }
2990
2991 case JitScriptTag: {
2992 toJitScript()->trace(trc);
2993 break;
2994 }
2995
2996 default: {
2997 MOZ_ASSERT(isWarmUpCount());
2998 break;
2999 }
3000 }
3001 }
3002
3003 size_t JSScript::calculateLiveFixed(jsbytecode* pc) {
3004 size_t nlivefixed = numAlwaysLiveFixedSlots();
3005
3006 if (nfixed() != nlivefixed) {
3007 Scope* scope = lookupScope(pc);
3008 if (scope) {
3009 scope = MaybeForwarded(scope);
3010 }
3011
3012 // Find the nearest LexicalScope in the same script.
3013 while (scope && scope->is<WithScope>()) {
3014 scope = scope->enclosing();
3015 if (scope) {
3016 scope = MaybeForwarded(scope);
3017 }
3018 }
3019
3020 if (scope) {
3021 if (scope->is<LexicalScope>()) {
3022 nlivefixed = scope->as<LexicalScope>().nextFrameSlot();
3023 } else if (scope->is<VarScope>()) {
3024 nlivefixed = scope->as<VarScope>().nextFrameSlot();
3025 } else if (scope->is<ClassBodyScope>()) {
3026 nlivefixed = scope->as<ClassBodyScope>().nextFrameSlot();
3027 }
3028 }
3029 }
3030
3031 MOZ_ASSERT(nlivefixed <= nfixed());
3032 MOZ_ASSERT(nlivefixed >= numAlwaysLiveFixedSlots());
3033
3034 return nlivefixed;
3035 }
3036
3037 Scope* JSScript::lookupScope(const jsbytecode* pc) const {
3038 MOZ_ASSERT(containsPC(pc));
3039
3040 size_t offset = pc - code();
3041
3042 auto notes = scopeNotes();
3043 Scope* scope = nullptr;
3044
3045 // Find the innermost block chain using a binary search.
3046 size_t bottom = 0;
3047 size_t top = notes.size();
3048
3049 while (bottom < top) {
3050 size_t mid = bottom + (top - bottom) / 2;
3051 const ScopeNote* note = &notes[mid];
3052 if (note->start <= offset) {
3053 // Block scopes are ordered in the list by their starting offset, and
3054 // since blocks form a tree ones earlier in the list may cover the pc even
3055 // if later blocks end before the pc. This only happens when the earlier
3056 // block is a parent of the later block, so we need to check parents of
3057 // |mid| in the searched range for coverage.
3058 size_t check = mid;
3059 while (check >= bottom) {
3060 const ScopeNote* checkNote = &notes[check];
3061 MOZ_ASSERT(checkNote->start <= offset);
3062 if (offset < checkNote->start + checkNote->length) {
3063 // We found a matching block chain but there may be inner ones
3064 // at a higher block chain index than mid. Continue the binary search.
3065 if (checkNote->index == ScopeNote::NoScopeIndex) {
3066 scope = nullptr;
3067 } else {
3068 scope = getScope(checkNote->index);
3069 }
3070 break;
3071 }
3072 if (checkNote->parent == UINT32_MAX) {
3073 break;
3074 }
3075 check = checkNote->parent;
3076 }
3077 bottom = mid + 1;
3078 } else {
3079 top = mid;
3080 }
3081 }
3082
3083 return scope;
3084 }
3085
3086 Scope* JSScript::innermostScope(const jsbytecode* pc) const {
3087 if (Scope* scope = lookupScope(pc)) {
3088 return scope;
3089 }
3090 return bodyScope();
3091 }
3092
3093 void js::SetFrameArgumentsObject(JSContext* cx, AbstractFramePtr frame,
3094 HandleScript script, JSObject* argsobj) {
3095 /*
3096 * If the arguments object was optimized out by scalar replacement,
3097 * we must recreate it when we bail out. Because 'arguments' may have
3098 * already been overwritten, we must check to see if the slot already
3099 * contains a value.
3100 */
3101
3102 Rooted<BindingIter> bi(cx, BindingIter(script));
3103 while (bi && bi.name() != cx->names().arguments) {
3104 bi++;
3105 }
3106 if (!bi) {
3107 return;
3108 }
3109
3110 if (bi.location().kind() == BindingLocation::Kind::Environment) {
3111 #ifdef DEBUG
3112 /*
3113 * If |arguments| lives in the call object, we should not have
3114 * optimized it. Scan the script to find the slot in the call
3115 * object that |arguments| is assigned to and verify that it
3116 * already exists.
3117 */
3118 jsbytecode* pc = script->code();
3119 while (JSOp(*pc) != JSOp::Arguments) {
3120 pc += GetBytecodeLength(pc);
3121 }
3122 pc += JSOpLength_Arguments;
3123 MOZ_ASSERT(JSOp(*pc) == JSOp::SetAliasedVar);
3124
3125 EnvironmentObject& env = frame.callObj().as<EnvironmentObject>();
3126 MOZ_ASSERT(!env.aliasedBinding(bi).isMagic(JS_OPTIMIZED_OUT));
3127 #endif
3128 return;
3129 }
3130
3131 MOZ_ASSERT(bi.location().kind() == BindingLocation::Kind::Frame);
3132 uint32_t frameSlot = bi.location().slot();
3133 if (frame.unaliasedLocal(frameSlot).isMagic(JS_OPTIMIZED_OUT)) {
3134 frame.unaliasedLocal(frameSlot) = ObjectValue(*argsobj);
3135 }
3136 }
3137
3138 bool JSScript::formalIsAliased(unsigned argSlot) {
3139 if (functionHasParameterExprs()) {
3140 return false;
3141 }
3142
3143 for (PositionalFormalParameterIter fi(this); fi; fi++) {
3144 if (fi.argumentSlot() == argSlot) {
3145 return fi.closedOver();
3146 }
3147 }
3148 MOZ_CRASH("Argument slot not found");
3149 }
3150
3151 // Returns true if any formal argument is mapped by the arguments
3152 // object, but lives in the call object.
3153 bool JSScript::anyFormalIsForwarded() {
3154 if (!argsObjAliasesFormals()) {
3155 return false;
3156 }
3157
3158 for (PositionalFormalParameterIter fi(this); fi; fi++) {
3159 if (fi.closedOver()) {
3160 return true;
3161 }
3162 }
3163 return false;
3164 }
3165
3166 bool JSScript::formalLivesInArgumentsObject(unsigned argSlot) {
3167 return argsObjAliasesFormals() && !formalIsAliased(argSlot);
3168 }
3169
3170 BaseScript::BaseScript(uint8_t* stubEntry, JSFunction* function,
3171 ScriptSourceObject* sourceObject,
3172 const SourceExtent& extent, uint32_t immutableFlags)
3173 : TenuredCellWithNonGCPointer(stubEntry),
3174 function_(function),
3175 sourceObject_(sourceObject),
3176 extent_(extent),
3177 immutableFlags_(immutableFlags) {
3178 MOZ_ASSERT(extent_.toStringStart <= extent_.sourceStart);
3179 MOZ_ASSERT(extent_.sourceStart <= extent_.sourceEnd);
3180 MOZ_ASSERT(extent_.sourceEnd <= extent_.toStringEnd);
3181 }
3182
3183 /* static */
3184 BaseScript* BaseScript::New(JSContext* cx, JS::Handle<JSFunction*> function,
3185 Handle<ScriptSourceObject*> sourceObject,
3186 const SourceExtent& extent,
3187 uint32_t immutableFlags) {
3188 uint8_t* stubEntry = nullptr;
3189 if (jit::HasJitBackend()) {
3190 stubEntry = cx->runtime()->jitRuntime()->interpreterStub().value;
3191 }
3192
3193 MOZ_ASSERT_IF(function,
3194 function->compartment() == sourceObject->compartment());
3195 MOZ_ASSERT_IF(function, function->realm() == sourceObject->realm());
3196
3197 return cx->newCell<BaseScript>(stubEntry, function, sourceObject, extent,
3198 immutableFlags);
3199 }
3200
3201 /* static */
3202 BaseScript* BaseScript::CreateRawLazy(JSContext* cx, uint32_t ngcthings,
3203 HandleFunction fun,
3204 Handle<ScriptSourceObject*> sourceObject,
3205 const SourceExtent& extent,
3206 uint32_t immutableFlags) {
3207 cx->check(fun);
3208
3209 BaseScript* lazy = New(cx, fun, sourceObject, extent, immutableFlags);
3210 if (!lazy) {
3211 return nullptr;
3212 }
3213
3214 // Allocate a PrivateScriptData if it will not be empty. Lazy class
3215 // constructors that use member initializers also need PrivateScriptData for
3216 // field data.
3217 //
3218 // This condition is implicit in BaseScript::hasPrivateScriptData, and should
3219 // be mirrored on InputScript::hasPrivateScriptData.
3220 if (ngcthings || lazy->useMemberInitializers()) {
3221 UniquePtr<PrivateScriptData> data(PrivateScriptData::new_(cx, ngcthings));
3222 if (!data) {
3223 return nullptr;
3224 }
3225 lazy->swapData(data);
3226 MOZ_ASSERT(!data);
3227 }
3228
3229 return lazy;
3230 }
3231
3232 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
3233 // This is an arbitrary non-null pointer that we use as a placeholder
3234 // for scripts that can be run in PBL: the rest of the engine expects
3235 // a "non-null jitcode pointer" but we'll never actually call it. We
3236 // have to ensure alignment to keep GC happy.
3237 static uint8_t* const PBLJitCodePtr = reinterpret_cast<uint8_t*>(8);
3238 #endif
3239
3240 void JSScript::updateJitCodeRaw(JSRuntime* rt) {
3241 MOZ_ASSERT(rt);
3242 if (hasBaselineScript() && baselineScript()->hasPendingIonCompileTask()) {
3243 MOZ_ASSERT(!isIonCompilingOffThread());
3244 setJitCodeRaw(rt->jitRuntime()->lazyLinkStub().value);
3245 } else if (hasIonScript()) {
3246 jit::IonScript* ion = ionScript();
3247 setJitCodeRaw(ion->method()->raw());
3248 } else if (hasBaselineScript()) {
3249 setJitCodeRaw(baselineScript()->method()->raw());
3250 } else if (hasJitScript() && js::jit::IsBaselineInterpreterEnabled()) {
3251 bool usingEntryTrampoline = false;
3252 if (js::jit::JitOptions.emitInterpreterEntryTrampoline) {
3253 auto p = rt->jitRuntime()->getInterpreterEntryMap()->lookup(this);
3254 if (p) {
3255 setJitCodeRaw(p->value().raw());
3256 usingEntryTrampoline = true;
3257 }
3258 }
3259 if (!usingEntryTrampoline) {
3260 setJitCodeRaw(rt->jitRuntime()->baselineInterpreter().codeRaw());
3261 }
3262 #ifdef ENABLE_PORTABLE_BASELINE_INTERP
3263 } else if (hasJitScript() &&
3264 js::jit::IsPortableBaselineInterpreterEnabled()) {
3265 // The portable baseline interpreter does not dispatch on this
3266 // pointer, but it needs to be non-null to trigger the appropriate
3267 // code-paths, so we set it to a placeholder value here.
3268 setJitCodeRaw(PBLJitCodePtr);
3269 #endif // ENABLE_PORTABLE_BASELINE_INTERP
3270 } else if (!js::jit::IsBaselineInterpreterEnabled()) {
3271 setJitCodeRaw(nullptr);
3272 } else {
3273 setJitCodeRaw(rt->jitRuntime()->interpreterStub().value);
3274 }
3275 MOZ_ASSERT_IF(!js::jit::IsPortableBaselineInterpreterEnabled(), jitCodeRaw());
3276 }
3277
3278 bool JSScript::hasLoops() {
3279 for (const TryNote& tn : trynotes()) {
3280 if (tn.isLoop()) {
3281 return true;
3282 }
3283 }
3284 return false;
3285 }
3286
3287 bool JSScript::mayReadFrameArgsDirectly() {
3288 return needsArgsObj() || usesArgumentsIntrinsics() || hasRest();
3289 }
3290
3291 void JSScript::resetWarmUpCounterToDelayIonCompilation() {
3292 // Reset the warm-up count only if it's greater than the BaselineCompiler
3293 // threshold. We do this to ensure this has no effect on Baseline compilation
3294 // because we don't want scripts to get stuck in the (Baseline) interpreter in
3295 // pathological cases.
3296
3297 if (getWarmUpCount() > jit::JitOptions.baselineJitWarmUpThreshold) {
3298 incWarmUpResetCounter();
3299 uint32_t newCount = jit::JitOptions.baselineJitWarmUpThreshold;
3300 if (warmUpData_.isWarmUpCount()) {
3301 warmUpData_.resetWarmUpCount(newCount);
3302 } else {
3303 warmUpData_.toJitScript()->resetWarmUpCount(newCount);
3304 }
3305 }
3306 }
3307
3308 #if defined(DEBUG) || defined(JS_JITSPEW)
3309
3310 void BaseScript::dumpStringContent(js::GenericPrinter& out) const {
3311 StringEscape esc('"');
3312 EscapePrinter ep(out, esc);
3313 ep.printf("%s:%u:%u @ 0x%p", filename() ? filename() : "<null>", lineno(),
3314 column().oneOriginValue(), this);
3315 }
3316
3317 void JSScript::dump(JSContext* cx) {
3318 JS::Rooted<JSScript*> script(cx, this);
3319
3320 js::Sprinter sp(cx);
3321 if (!sp.init()) {
3322 return;
3323 }
3324
3325 DumpOptions options;
3326 options.runtimeData = true;
3327 if (!dump(cx, script, options, &sp)) {
3328 return;
3329 }
3330
3331 JS::UniqueChars str = sp.release();
3332 if (!str) {
3333 return;
3334 }
3335 fprintf(stderr, "%s\n", str.get());
3336 }
3337
3338 void JSScript::dumpRecursive(JSContext* cx) {
3339 JS::Rooted<JSScript*> script(cx, this);
3340
3341 js::Sprinter sp(cx);
3342 if (!sp.init()) {
3343 return;
3344 }
3345
3346 DumpOptions options;
3347 options.runtimeData = true;
3348 options.recursive = true;
3349 if (!dump(cx, script, options, &sp)) {
3350 return;
3351 }
3352
3353 JS::UniqueChars str = sp.release();
3354 if (!str) {
3355 return;
3356 }
3357 fprintf(stderr, "%s\n", str.get());
3358 }
3359
3360 static void DumpMutableScriptFlags(js::JSONPrinter& json,
3361 MutableScriptFlags mutableFlags) {
3362 // Skip warmup data.
3363 static_assert(int(MutableScriptFlagsEnum::WarmupResets_MASK) == 0xff);
3364
3365 for (uint32_t i = 0x100; i; i = i << 1) {
3366 if (uint32_t(mutableFlags) & i) {
3367 switch (MutableScriptFlagsEnum(i)) {
3368 case MutableScriptFlagsEnum::HasRunOnce:
3369 json.value("HasRunOnce");
3370 break;
3371 case MutableScriptFlagsEnum::HasBeenCloned:
3372 json.value("HasBeenCloned");
3373 break;
3374 case MutableScriptFlagsEnum::HasScriptCounts:
3375 json.value("HasScriptCounts");
3376 break;
3377 case MutableScriptFlagsEnum::HasDebugScript:
3378 json.value("HasDebugScript");
3379 break;
3380 case MutableScriptFlagsEnum::AllowRelazify:
3381 json.value("AllowRelazify");
3382 break;
3383 case MutableScriptFlagsEnum::SpewEnabled:
3384 json.value("SpewEnabled");
3385 break;
3386 case MutableScriptFlagsEnum::NeedsFinalWarmUpCount:
3387 json.value("NeedsFinalWarmUpCount");
3388 break;
3389 case MutableScriptFlagsEnum::BaselineDisabled:
3390 json.value("BaselineDisabled");
3391 break;
3392 case MutableScriptFlagsEnum::IonDisabled:
3393 json.value("IonDisabled");
3394 break;
3395 case MutableScriptFlagsEnum::Uninlineable:
3396 json.value("Uninlineable");
3397 break;
3398 case MutableScriptFlagsEnum::NoEagerBaselineHint:
3399 json.value("NoEagerBaselineHint");
3400 break;
3401 case MutableScriptFlagsEnum::FailedBoundsCheck:
3402 json.value("FailedBoundsCheck");
3403 break;
3404 case MutableScriptFlagsEnum::HadLICMInvalidation:
3405 json.value("HadLICMInvalidation");
3406 break;
3407 case MutableScriptFlagsEnum::HadReorderingBailout:
3408 json.value("HadReorderingBailout");
3409 break;
3410 case MutableScriptFlagsEnum::HadEagerTruncationBailout:
3411 json.value("HadEagerTruncationBailout");
3412 break;
3413 case MutableScriptFlagsEnum::FailedLexicalCheck:
3414 json.value("FailedLexicalCheck");
3415 break;
3416 case MutableScriptFlagsEnum::HadSpeculativePhiBailout:
3417 json.value("HadSpeculativePhiBailout");
3418 break;
3419 case MutableScriptFlagsEnum::HadUnboxFoldingBailout:
3420 json.value("HadUnboxFoldingBailout");
3421 break;
3422 default:
3423 json.value("Unknown(%x)", i);
3424 break;
3425 }
3426 }
3427 }
3428 }
3429
3430 /* static */
3431 bool JSScript::dump(JSContext* cx, JS::Handle<JSScript*> script,
3432 DumpOptions& options, js::StringPrinter* sp) {
3433 {
3434 JSONPrinter json(*sp);
3435
3436 json.beginObject();
3437
3438 if (const char* filename = script->filename()) {
3439 json.property("file", filename);
3440 } else {
3441 json.nullProperty("file");
3442 }
3443
3444 json.property("lineno", script->lineno());
3445 json.property("column", script->column().oneOriginValue());
3446
3447 json.beginListProperty("immutableFlags");
3448 DumpImmutableScriptFlags(json, script->immutableFlags());
3449 json.endList();
3450
3451 if (options.runtimeData) {
3452 json.beginListProperty("mutableFlags");
3453 DumpMutableScriptFlags(json, script->mutableFlags_);
3454 json.endList();
3455 }
3456
3457 if (script->isFunction()) {
3458 JS::Rooted<JSFunction*> fun(cx, script->function());
3459
3460 JS::Rooted<JSAtom*> name(cx, fun->fullDisplayAtom());
3461 if (name) {
3462 UniqueChars bytes = JS_EncodeStringToUTF8(cx, name);
3463 if (!bytes) {
3464 return false;
3465 }
3466 json.property("functionName", bytes.get());
3467 } else {
3468 json.nullProperty("functionName");
3469 }
3470
3471 json.beginListProperty("functionFlags");
3472 DumpFunctionFlagsItems(json, fun->flags());
3473 json.endList();
3474 }
3475
3476 json.endObject();
3477 }
3478
3479 if (sp->hadOutOfMemory()) {
3480 sp->forwardOutOfMemory();
3481 return false;
3482 }
3483
3484 sp->put("\n");
3485
3486 if (!Disassemble(cx, script, /* lines = */ true, sp)) {
3487 return false;
3488 }
3489 if (!dumpSrcNotes(cx, script, sp)) {
3490 return false;
3491 }
3492 if (!dumpTryNotes(cx, script, sp)) {
3493 return false;
3494 }
3495 if (!dumpScopeNotes(cx, script, sp)) {
3496 return false;
3497 }
3498 if (!dumpGCThings(cx, script, sp)) {
3499 return false;
3500 }
3501
3502 if (options.recursive) {
3503 for (JS::GCCellPtr gcThing : script->gcthings()) {
3504 if (!gcThing.is<JSObject>()) {
3505 continue;
3506 }
3507
3508 JSObject* obj = &gcThing.as<JSObject>();
3509 if (obj->is<JSFunction>()) {
3510 sp->put("\n");
3511
3512 JS::Rooted<JSFunction*> fun(cx, &obj->as<JSFunction>());
3513 if (fun->isInterpreted()) {
3514 JS::Rooted<JSScript*> innerScript(
3515 cx, JSFunction::getOrCreateScript(cx, fun));
3516 if (!innerScript) {
3517 return false;
3518 }
3519 if (!dump(cx, innerScript, options, sp)) {
3520 return false;
3521 }
3522 } else {
3523 sp->put("[native code]\n");
3524 }
3525 }
3526 }
3527 }
3528
3529 return true;
3530 }
3531
3532 /* static */
3533 bool JSScript::dumpSrcNotes(JSContext* cx, JS::Handle<JSScript*> script,
3534 js::GenericPrinter* sp) {
3535 sp->put("\nSource notes:\n");
3536 sp->printf("%4s %4s %6s %5s %6s %-16s %s\n", "ofs", "line", "column", "pc",
3537 "delta", "desc", "args");
3538 sp->put("---- ---- ------ ----- ------ ---------------- ------\n");
3539 unsigned offset = 0;
3540 unsigned lineno = script->lineno();
3541 JS::LimitedColumnNumberOneOrigin column = script->column();
3542 SrcNote* notes = script->notes();
3543 SrcNote* notesEnd = script->notesEnd();
3544 for (SrcNoteIterator iter(notes, notesEnd); !iter.atEnd(); ++iter) {
3545 const auto* sn = *iter;
3546
3547 unsigned delta = sn->delta();
3548 offset += delta;
3549 SrcNoteType type = sn->type();
3550 const char* name = sn->name();
3551 sp->printf("%3u: %4u %6u %5u [%4u] %-16s", unsigned(sn - notes), lineno,
3552 column.oneOriginValue(), offset, delta, name);
3553
3554 switch (type) {
3555 case SrcNoteType::Breakpoint:
3556 case SrcNoteType::BreakpointStepSep:
3557 case SrcNoteType::XDelta:
3558 break;
3559
3560 case SrcNoteType::ColSpan: {
3561 JS::ColumnNumberOffset colspan = SrcNote::ColSpan::getSpan(sn);
3562 sp->printf(" colspan %u", colspan.value());
3563 column += colspan;
3564 break;
3565 }
3566
3567 case SrcNoteType::SetLine:
3568 lineno = SrcNote::SetLine::getLine(sn, script->lineno());
3569 sp->printf(" lineno %u", lineno);
3570 column = JS::LimitedColumnNumberOneOrigin();
3571 break;
3572
3573 case SrcNoteType::SetLineColumn:
3574 lineno = SrcNote::SetLineColumn::getLine(sn, script->lineno());
3575 column = SrcNote::SetLineColumn::getColumn(sn);
3576 sp->printf(" lineno %u column %u", lineno, column.oneOriginValue());
3577 break;
3578
3579 case SrcNoteType::NewLine:
3580 ++lineno;
3581 column = JS::LimitedColumnNumberOneOrigin();
3582 break;
3583
3584 case SrcNoteType::NewLineColumn:
3585 column = SrcNote::NewLineColumn::getColumn(sn);
3586 sp->printf(" column %u", column.oneOriginValue());
3587 ++lineno;
3588 break;
3589
3590 default:
3591 MOZ_ASSERT_UNREACHABLE("unrecognized srcnote");
3592 }
3593 sp->put("\n");
3594 }
3595
3596 return true;
3597 }
3598
3599 static const char* TryNoteName(TryNoteKind kind) {
3600 switch (kind) {
3601 case TryNoteKind::Catch:
3602 return "catch";
3603 case TryNoteKind::Finally:
3604 return "finally";
3605 case TryNoteKind::ForIn:
3606 return "for-in";
3607 case TryNoteKind::ForOf:
3608 return "for-of";
3609 case TryNoteKind::Loop:
3610 return "loop";
3611 case TryNoteKind::ForOfIterClose:
3612 return "for-of-iterclose";
3613 case TryNoteKind::Destructuring:
3614 return "destructuring";
3615 }
3616
3617 MOZ_CRASH("Bad TryNoteKind");
3618 }
3619
3620 /* static */
3621 bool JSScript::dumpTryNotes(JSContext* cx, JS::Handle<JSScript*> script,
3622 js::GenericPrinter* sp) {
3623 sp->put("\nException table:\nkind stack start end\n");
3624
3625 for (const js::TryNote& tn : script->trynotes()) {
3626 sp->printf(" %-16s %6u %8u %8u\n", TryNoteName(tn.kind()), tn.stackDepth,
3627 tn.start, tn.start + tn.length);
3628 }
3629 return true;
3630 }
3631
3632 /* static */
3633 bool JSScript::dumpScopeNotes(JSContext* cx, JS::Handle<JSScript*> script,
3634 js::GenericPrinter* sp) {
3635 sp->put("\nScope notes:\n index parent start end\n");
3636
3637 for (const ScopeNote& note : script->scopeNotes()) {
3638 if (note.index == ScopeNote::NoScopeIndex) {
3639 sp->printf("%8s ", "(none)");
3640 } else {
3641 sp->printf("%8u ", note.index.index);
3642 }
3643 if (note.parent == ScopeNote::NoScopeIndex) {
3644 sp->printf("%8s ", "(none)");
3645 } else {
3646 sp->printf("%8u ", note.parent);
3647 }
3648 sp->printf("%8u %8u\n", note.start, note.start + note.length);
3649 }
3650 return true;
3651 }
3652
3653 /* static */
3654 bool JSScript::dumpGCThings(JSContext* cx, JS::Handle<JSScript*> script,
3655 js::GenericPrinter* sp) {
3656 sp->put("\nGC things:\n index type value\n");
3657
3658 size_t i = 0;
3659 for (JS::GCCellPtr gcThing : script->gcthings()) {
3660 sp->printf("%8zu ", i);
3661 if (gcThing.is<JS::BigInt>()) {
3662 sp->put("BigInt ");
3663 gcThing.as<JS::BigInt>().dump(*sp);
3664 sp->put("\n");
3665 } else if (gcThing.is<Scope>()) {
3666 sp->put("Scope ");
3667 JS::Rooted<Scope*> scope(cx, &gcThing.as<Scope>());
3668 if (!Scope::dumpForDisassemble(cx, scope, *sp,
3669 " ")) {
3670 return false;
3671 }
3672 sp->put("\n");
3673 } else if (gcThing.is<JSObject>()) {
3674 JSObject* obj = &gcThing.as<JSObject>();
3675 if (obj->is<JSFunction>()) {
3676 sp->put("Function ");
3677 JS::Rooted<JSFunction*> fun(cx, &obj->as<JSFunction>());
3678 if (fun->fullDisplayAtom()) {
3679 JS::Rooted<JSAtom*> name(cx, fun->fullDisplayAtom());
3680 JS::UniqueChars utf8chars = JS_EncodeStringToUTF8(cx, name);
3681 if (!utf8chars) {
3682 return false;
3683 }
3684 sp->put(utf8chars.get());
3685 } else {
3686 sp->put("(anonymous)");
3687 }
3688
3689 if (fun->hasBaseScript()) {
3690 BaseScript* script = fun->baseScript();
3691 sp->printf(" @ %u:%u\n", script->lineno(),
3692 script->column().oneOriginValue());
3693 } else {
3694 sp->put(" (no script)\n");
3695 }
3696 } else {
3697 if (obj->is<RegExpObject>()) {
3698 sp->put("RegExp ");
3699 } else {
3700 sp->put("Object ");
3701 }
3702
3703 JS::Rooted<JS::Value> objValue(cx, ObjectValue(*obj));
3704 JS::UniqueChars source = ToDisassemblySource(cx, objValue);
3705 if (!source) {
3706 return false;
3707 }
3708 sp->put(source.get());
3709 sp->put("\n");
3710 }
3711 } else if (gcThing.is<JSString>()) {
3712 JS::Rooted<JSString*> str(cx, &gcThing.as<JSString>());
3713 if (str->isAtom()) {
3714 sp->put("Atom ");
3715 } else {
3716 sp->put("String ");
3717 }
3718 JS::UniqueChars chars = QuoteString(cx, str, '"');
3719 if (!chars) {
3720 return false;
3721 }
3722 sp->put(chars.get());
3723 sp->put("\n");
3724 } else {
3725 sp->put("Unknown\n");
3726 }
3727 i++;
3728 }
3729
3730 return true;
3731 }
3732
3733 #endif // defined(DEBUG) || defined(JS_JITSPEW)
3734
3735 void JSScript::AutoDelazify::holdScript(JS::HandleFunction fun) {
3736 if (fun) {
3737 JSAutoRealm ar(cx_, fun);
3738 script_ = JSFunction::getOrCreateScript(cx_, fun);
3739 if (script_) {
3740 oldAllowRelazify_ = script_->allowRelazify();
3741 script_->clearAllowRelazify();
3742 }
3743 }
3744 }
3745
3746 void JSScript::AutoDelazify::dropScript() {
3747 if (script_) {
3748 script_->setAllowRelazify(oldAllowRelazify_);
3749 }
3750 script_ = nullptr;
3751 }
3752
3753 JS::ubi::Base::Size JS::ubi::Concrete<BaseScript>::size(
3754 mozilla::MallocSizeOf mallocSizeOf) const {
3755 BaseScript* base = &get();
3756
3757 Size size = gc::Arena::thingSize(base->getAllocKind());
3758 size += base->sizeOfExcludingThis(mallocSizeOf);
3759
3760 // Include any JIT data if it exists.
3761 if (base->hasJitScript()) {
3762 JSScript* script = base->asJSScript();
3763
3764 size_t jitScriptSize = 0;
3765 size_t allocSitesSize = 0;
3766 script->addSizeOfJitScript(mallocSizeOf, &jitScriptSize, &allocSitesSize);
3767 size += jitScriptSize;
3768 size += allocSitesSize;
3769
3770 size_t baselineSize = 0;
3771 jit::AddSizeOfBaselineData(script, mallocSizeOf, &baselineSize);
3772 size += baselineSize;
3773
3774 size += jit::SizeOfIonData(script, mallocSizeOf);
3775 }
3776
3777 MOZ_ASSERT(size > 0);
3778 return size;
3779 }
3780
3781 const char* JS::ubi::Concrete<BaseScript>::scriptFilename() const {
3782 return get().filename();
3783 }