-
Notifications
You must be signed in to change notification settings - Fork 54
/
JSScript.h
2823 lines (2328 loc) · 97.8 KB
/
JSScript.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* JS script descriptor. */
#ifndef vm_JSScript_h
#define vm_JSScript_h
#include "mozilla/ArrayUtils.h"
#include "mozilla/Atomics.h"
#include "mozilla/Maybe.h"
#include "mozilla/MaybeOneOf.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Span.h"
#include "mozilla/Tuple.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Utf8.h"
#include "mozilla/Variant.h"
#include <type_traits> // std::is_same
#include <utility> // std::move
#include "jstypes.h"
#include "frontend/BinASTRuntimeSupport.h"
#include "frontend/NameAnalysisTypes.h"
#include "frontend/SourceNotes.h" // SrcNote
#include "gc/Barrier.h"
#include "gc/Rooting.h"
#include "jit/JitCode.h"
#include "js/CompileOptions.h"
#include "js/UbiNode.h"
#include "js/UniquePtr.h"
#include "js/Utility.h"
#include "util/StructuredSpewer.h"
#include "util/TrailingArray.h"
#include "vm/BigIntType.h"
#include "vm/BytecodeIterator.h"
#include "vm/BytecodeLocation.h"
#include "vm/BytecodeUtil.h"
#include "vm/GeneratorAndAsyncKind.h" // GeneratorKind, FunctionAsyncKind
#include "vm/JSAtom.h"
#include "vm/NativeObject.h"
#include "vm/Scope.h"
#include "vm/Shape.h"
#include "vm/SharedImmutableStringsCache.h"
#include "vm/SharedStencil.h"
#include "vm/Time.h"
namespace JS {
struct ScriptSourceInfo;
template <typename UnitT>
class SourceText;
} // namespace JS
namespace js {
namespace coverage {
class LCovSource;
} // namespace coverage
namespace jit {
class AutoKeepJitScripts;
class BaselineScript;
struct IonScriptCounts;
class JitScript;
} // namespace jit
class AutoSweepJitScript;
class ModuleObject;
class RegExpObject;
class ScriptSourceHolder;
class SourceCompressionTask;
class Shape;
class DebugAPI;
class DebugScript;
namespace frontend {
struct CompilationInfo;
class FunctionIndex;
class FunctionBox;
class ModuleSharedContext;
class ScriptStencil;
} // namespace frontend
class ScriptCounts {
public:
typedef mozilla::Vector<PCCounts, 0, SystemAllocPolicy> PCCountsVector;
inline ScriptCounts();
inline explicit ScriptCounts(PCCountsVector&& jumpTargets);
inline ScriptCounts(ScriptCounts&& src);
inline ~ScriptCounts();
inline ScriptCounts& operator=(ScriptCounts&& src);
// Return the counter used to count the number of visits. Returns null if
// the element is not found.
PCCounts* maybeGetPCCounts(size_t offset);
const PCCounts* maybeGetPCCounts(size_t offset) const;
// PCCounts are stored at jump-target offsets. This function looks for the
// previous PCCount which is in the same basic block as the current offset.
PCCounts* getImmediatePrecedingPCCounts(size_t offset);
// Return the counter used to count the number of throws. Returns null if
// the element is not found.
const PCCounts* maybeGetThrowCounts(size_t offset) const;
// Throw counts are stored at the location of each throwing
// instruction. This function looks for the previous throw count.
//
// Note: if the offset of the returned count is higher than the offset of
// the immediate preceding PCCount, then this throw happened in the same
// basic block.
const PCCounts* getImmediatePrecedingThrowCounts(size_t offset) const;
// Return the counter used to count the number of throws. Allocate it if
// none exists yet. Returns null if the allocation failed.
PCCounts* getThrowCounts(size_t offset);
size_t sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf);
private:
friend class ::JSScript;
friend struct ScriptAndCounts;
// This sorted array is used to map an offset to the number of times a
// branch got visited.
PCCountsVector pcCounts_;
// This sorted vector is used to map an offset to the number of times an
// instruction throw.
PCCountsVector throwCounts_;
// Information about any Ion compilations for the script.
jit::IonScriptCounts* ionCounts_;
};
// The key of these side-table hash maps are intentionally not traced GC
// references to JSScript. Instead, we use bare pointers and manually fix up
// when objects could have moved (see Zone::fixupScriptMapsAfterMovingGC) and
// remove when the realm is destroyed (see Zone::clearScriptCounts and
// Zone::clearScriptNames). They essentially behave as weak references, except
// that the references are not cleared early by the GC. They must be non-strong
// references because the tables are kept at the Zone level and otherwise the
// table keys would keep scripts alive, thus keeping Realms alive, beyond their
// expected lifetimes. However, We do not use actual weak references (e.g. as
// used by WeakMap tables provided in gc/WeakMap.h) because they would be
// collected before the calls to the JSScript::finalize function which are used
// to aggregate code coverage results on the realm.
//
// Note carefully, however, that there is an exceptional case for which we *do*
// want the JSScripts to be strong references (and thus traced): when the
// --dump-bytecode command line option or the PCCount JSFriend API is used,
// then the scripts for all counts must remain alive. See
// Zone::traceScriptTableRoots() for more details.
//
// TODO: Clean this up by either aggregating coverage results in some other
// way, or by tweaking sweep ordering.
using UniqueScriptCounts = js::UniquePtr<ScriptCounts>;
using ScriptCountsMap = HashMap<BaseScript*, UniqueScriptCounts,
DefaultHasher<BaseScript*>, SystemAllocPolicy>;
// The 'const char*' for the function name is a pointer within the LCovSource's
// LifoAlloc and will be discarded at the same time.
using ScriptLCovEntry = mozilla::Tuple<coverage::LCovSource*, const char*>;
using ScriptLCovMap = HashMap<BaseScript*, ScriptLCovEntry,
DefaultHasher<BaseScript*>, SystemAllocPolicy>;
#ifdef MOZ_VTUNE
using ScriptVTuneIdMap = HashMap<BaseScript*, uint32_t,
DefaultHasher<BaseScript*>, SystemAllocPolicy>;
#endif
using UniqueDebugScript = js::UniquePtr<DebugScript, JS::FreePolicy>;
using DebugScriptMap = HashMap<BaseScript*, UniqueDebugScript,
DefaultHasher<BaseScript*>, SystemAllocPolicy>;
class ScriptSource;
struct ScriptSourceChunk {
ScriptSource* ss = nullptr;
uint32_t chunk = 0;
ScriptSourceChunk() = default;
ScriptSourceChunk(ScriptSource* ss, uint32_t chunk) : ss(ss), chunk(chunk) {
MOZ_ASSERT(valid());
}
bool valid() const { return ss != nullptr; }
bool operator==(const ScriptSourceChunk& other) const {
return ss == other.ss && chunk == other.chunk;
}
};
struct ScriptSourceChunkHasher {
using Lookup = ScriptSourceChunk;
static HashNumber hash(const ScriptSourceChunk& ssc) {
return mozilla::AddToHash(DefaultHasher<ScriptSource*>::hash(ssc.ss),
ssc.chunk);
}
static bool match(const ScriptSourceChunk& c1, const ScriptSourceChunk& c2) {
return c1 == c2;
}
};
template <typename Unit>
using EntryUnits = mozilla::UniquePtr<Unit[], JS::FreePolicy>;
// The uncompressed source cache contains *either* UTF-8 source data *or*
// UTF-16 source data. ScriptSourceChunk implies a ScriptSource that
// contains either UTF-8 data or UTF-16 data, so the nature of the key to
// Map below indicates how each SourceData ought to be interpreted.
using SourceData = mozilla::UniquePtr<void, JS::FreePolicy>;
template <typename Unit>
inline SourceData ToSourceData(EntryUnits<Unit> chars) {
static_assert(std::is_same_v<SourceData::DeleterType,
typename EntryUnits<Unit>::DeleterType>,
"EntryUnits and SourceData must share the same deleter "
"type, that need not know the type of the data being freed, "
"for the upcast below to be safe");
return SourceData(chars.release());
}
class UncompressedSourceCache {
using Map = HashMap<ScriptSourceChunk, SourceData, ScriptSourceChunkHasher,
SystemAllocPolicy>;
public:
// Hold an entry in the source data cache and prevent it from being purged on
// GC.
class AutoHoldEntry {
UncompressedSourceCache* cache_ = nullptr;
ScriptSourceChunk sourceChunk_ = {};
SourceData data_ = nullptr;
public:
explicit AutoHoldEntry() = default;
~AutoHoldEntry() {
if (cache_) {
MOZ_ASSERT(sourceChunk_.valid());
cache_->releaseEntry(*this);
}
}
template <typename Unit>
void holdUnits(EntryUnits<Unit> units) {
MOZ_ASSERT(!cache_);
MOZ_ASSERT(!sourceChunk_.valid());
MOZ_ASSERT(!data_);
data_ = ToSourceData(std::move(units));
}
private:
void holdEntry(UncompressedSourceCache* cache,
const ScriptSourceChunk& sourceChunk) {
// Initialise the holder for a specific cache and script source.
// This will hold on to the cached source chars in the event that
// the cache is purged.
MOZ_ASSERT(!cache_);
MOZ_ASSERT(!sourceChunk_.valid());
MOZ_ASSERT(!data_);
cache_ = cache;
sourceChunk_ = sourceChunk;
}
void deferDelete(SourceData data) {
// Take ownership of source chars now the cache is being purged. Remove
// our reference to the ScriptSource which might soon be destroyed.
MOZ_ASSERT(cache_);
MOZ_ASSERT(sourceChunk_.valid());
MOZ_ASSERT(!data_);
cache_ = nullptr;
sourceChunk_ = ScriptSourceChunk();
data_ = std::move(data);
}
const ScriptSourceChunk& sourceChunk() const { return sourceChunk_; }
friend class UncompressedSourceCache;
};
private:
UniquePtr<Map> map_ = nullptr;
AutoHoldEntry* holder_ = nullptr;
public:
UncompressedSourceCache() = default;
template <typename Unit>
const Unit* lookup(const ScriptSourceChunk& ssc, AutoHoldEntry& asp);
bool put(const ScriptSourceChunk& ssc, SourceData data, AutoHoldEntry& asp);
void purge();
size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf);
private:
void holdEntry(AutoHoldEntry& holder, const ScriptSourceChunk& ssc);
void releaseEntry(AutoHoldEntry& holder);
};
template <typename Unit>
struct SourceTypeTraits;
template <>
struct SourceTypeTraits<mozilla::Utf8Unit> {
using CharT = char;
using SharedImmutableString = js::SharedImmutableString;
static const mozilla::Utf8Unit* units(const SharedImmutableString& string) {
// Casting |char| data to |Utf8Unit| is safe because |Utf8Unit|
// contains a |char|. See the long comment in |Utf8Unit|'s definition.
return reinterpret_cast<const mozilla::Utf8Unit*>(string.chars());
}
static char* toString(const mozilla::Utf8Unit* units) {
auto asUnsigned =
const_cast<unsigned char*>(mozilla::Utf8AsUnsignedChars(units));
return reinterpret_cast<char*>(asUnsigned);
}
static UniqueChars toCacheable(EntryUnits<mozilla::Utf8Unit> str) {
// The cache only stores strings of |char| or |char16_t|, and right now
// it seems best not to gunk up the cache with |Utf8Unit| too. So
// cache |Utf8Unit| strings by interpreting them as |char| strings.
char* chars = toString(str.release());
return UniqueChars(chars);
}
};
template <>
struct SourceTypeTraits<char16_t> {
using CharT = char16_t;
using SharedImmutableString = js::SharedImmutableTwoByteString;
static const char16_t* units(const SharedImmutableString& string) {
return string.chars();
}
static char16_t* toString(const char16_t* units) {
return const_cast<char16_t*>(units);
}
static UniqueTwoByteChars toCacheable(EntryUnits<char16_t> str) {
return UniqueTwoByteChars(std::move(str));
}
};
// Synchronously compress the source of |script|, for testing purposes.
extern MOZ_MUST_USE bool SynchronouslyCompressSource(
JSContext* cx, JS::Handle<BaseScript*> script);
// Retrievable source can be retrieved using the source hook (and therefore
// need not be XDR'd, can be discarded if desired because it can always be
// reconstituted later, etc.).
enum class SourceRetrievable { Yes, No };
// [SMDOC] ScriptSource
//
// This class abstracts over the source we used to compile from. The current
// representation may transition to different modes in order to save memory.
// Abstractly the source may be one of UTF-8, UTF-16, or BinAST. The data
// itself may be unavailable, retrieveable-using-source-hook, compressed, or
// uncompressed. If source is retrieved or decompressed for use, we may update
// the ScriptSource to hold the result.
class ScriptSource {
// NOTE: While ScriptSources may be compressed off thread, they are only
// modified by the main thread, and all members are always safe to access
// on the main thread.
friend class SourceCompressionTask;
friend bool SynchronouslyCompressSource(JSContext* cx,
JS::Handle<BaseScript*> script);
private:
// Common base class of the templated variants of PinnedUnits<T>.
class PinnedUnitsBase {
protected:
PinnedUnitsBase** stack_ = nullptr;
PinnedUnitsBase* prev_ = nullptr;
ScriptSource* source_;
explicit PinnedUnitsBase(ScriptSource* source) : source_(source) {}
};
public:
// Any users that wish to manipulate the char buffer of the ScriptSource
// needs to do so via PinnedUnits for GC safety. A GC may compress
// ScriptSources. If the source were initially uncompressed, then any raw
// pointers to the char buffer would now point to the freed, uncompressed
// chars. This is analogous to Rooted.
template <typename Unit>
class PinnedUnits : public PinnedUnitsBase {
const Unit* units_;
public:
PinnedUnits(JSContext* cx, ScriptSource* source,
UncompressedSourceCache::AutoHoldEntry& holder, size_t begin,
size_t len);
~PinnedUnits();
const Unit* get() const { return units_; }
const typename SourceTypeTraits<Unit>::CharT* asChars() const {
return SourceTypeTraits<Unit>::toString(get());
}
};
private:
// Missing source text that isn't retrievable using the source hook. (All
// ScriptSources initially begin in this state. Users that are compiling
// source text will overwrite |data| to store a different state.)
struct Missing {};
// Source that can be retrieved using the registered source hook. |Unit|
// records the source type so that source-text coordinates in functions and
// scripts that depend on this |ScriptSource| are correct.
template <typename Unit>
struct Retrievable {
// The source hook and script URL required to retrieve source are stored
// elsewhere, so nothing is needed here. It'd be better hygiene to store
// something source-hook-like in each |ScriptSource| that needs it, but that
// requires reimagining a source-hook API that currently depends on source
// hooks being uniquely-owned pointers...
};
// Uncompressed source text. Templates distinguish if we are interconvertable
// to |Retrievable| or not.
template <typename Unit>
class UncompressedData {
typename SourceTypeTraits<Unit>::SharedImmutableString string_;
public:
explicit UncompressedData(
typename SourceTypeTraits<Unit>::SharedImmutableString str)
: string_(std::move(str)) {}
const Unit* units() const { return SourceTypeTraits<Unit>::units(string_); }
size_t length() const { return string_.length(); }
};
template <typename Unit, SourceRetrievable CanRetrieve>
class Uncompressed : public UncompressedData<Unit> {
using Base = UncompressedData<Unit>;
public:
using Base::Base;
};
// Compressed source text. Templates distinguish if we are interconvertable
// to |Retrievable| or not.
template <typename Unit>
struct CompressedData {
// Single-byte compressed text, regardless whether the original text
// was single-byte or two-byte.
SharedImmutableString raw;
size_t uncompressedLength;
CompressedData(SharedImmutableString raw, size_t uncompressedLength)
: raw(std::move(raw)), uncompressedLength(uncompressedLength) {}
};
template <typename Unit, SourceRetrievable CanRetrieve>
struct Compressed : public CompressedData<Unit> {
using Base = CompressedData<Unit>;
public:
using Base::Base;
};
// BinAST source.
struct BinAST {
SharedImmutableString string;
UniquePtr<frontend::BinASTSourceMetadata> metadata;
BinAST(SharedImmutableString&& str,
UniquePtr<frontend::BinASTSourceMetadata> metadata)
: string(std::move(str)), metadata(std::move(metadata)) {}
};
// The set of currently allowed encoding modes.
using SourceType =
mozilla::Variant<Compressed<mozilla::Utf8Unit, SourceRetrievable::Yes>,
Uncompressed<mozilla::Utf8Unit, SourceRetrievable::Yes>,
Compressed<mozilla::Utf8Unit, SourceRetrievable::No>,
Uncompressed<mozilla::Utf8Unit, SourceRetrievable::No>,
Compressed<char16_t, SourceRetrievable::Yes>,
Uncompressed<char16_t, SourceRetrievable::Yes>,
Compressed<char16_t, SourceRetrievable::No>,
Uncompressed<char16_t, SourceRetrievable::No>,
Retrievable<mozilla::Utf8Unit>, Retrievable<char16_t>,
Missing, BinAST>;
//
// Start of fields.
//
mozilla::Atomic<uint32_t, mozilla::ReleaseAcquire> refs = {};
// An id for this source that is unique across the process. This can be used
// to refer to this source from places that don't want to hold a strong
// reference on the source itself.
//
// This is a 32 bit ID and could overflow, in which case the ID will not be
// unique anymore.
uint32_t id_ = 0;
// Source data (as a mozilla::Variant).
SourceType data = SourceType(Missing());
// If the GC calls triggerConvertToCompressedSource with PinnedUnits present,
// the first PinnedUnits (that is, bottom of the stack) will install the
// compressed chars upon destruction.
//
// Retrievability isn't part of the type here because uncompressed->compressed
// transitions must preserve existing retrievability.
PinnedUnitsBase* pinnedUnitsStack_ = nullptr;
mozilla::MaybeOneOf<CompressedData<mozilla::Utf8Unit>,
CompressedData<char16_t>>
pendingCompressed_;
// The filename of this script.
mozilla::Maybe<SharedImmutableString> filename_;
// If this ScriptSource was generated by a code-introduction mechanism such
// as |eval| or |new Function|, the debugger needs access to the "raw"
// filename of the top-level script that contains the eval-ing code. To
// keep track of this, we must preserve the original outermost filename (of
// the original introducer script), so that instead of a filename of
// "foo.js line 30 > eval line 10 > Function", we can obtain the original
// raw filename of "foo.js".
//
// In the case described above, this field will be set to to the original raw
// filename from above, otherwise it will be mozilla::Nothing.
mozilla::Maybe<SharedImmutableString> introducerFilename_;
mozilla::Maybe<SharedImmutableTwoByteString> displayURL_;
mozilla::Maybe<SharedImmutableTwoByteString> sourceMapURL_;
// The bytecode cache encoder is used to encode only the content of function
// which are delazified. If this value is not nullptr, then each delazified
// function should be recorded before their first execution.
// This value is logically owned by the canonical ScriptSourceObject, and
// will be released in the canonical SSO's finalizer.
UniquePtr<XDRIncrementalEncoder> xdrEncoder_ = nullptr;
// Instant at which the first parse of this source ended, or null
// if the source hasn't been parsed yet.
//
// Used for statistics purposes, to determine how much time code spends
// syntax parsed before being full parsed, to help determine whether
// our syntax parse vs. full parse heuristics are correct.
mozilla::TimeStamp parseEnded_;
// A string indicating how this source code was introduced into the system.
// This is a constant, statically allocated C string, so does not need memory
// management.
const char* introductionType_ = nullptr;
// Bytecode offset in caller script that generated this code. This is
// present for eval-ed code, as well as "new Function(...)"-introduced
// scripts.
mozilla::Maybe<uint32_t> introductionOffset_;
// If this source is for Function constructor, the position of ")" after
// parameter list in the source. This is used to get function body.
// 0 for other cases.
uint32_t parameterListEnd_ = 0;
// Line number within the file where this source starts.
uint32_t startLine_ = 0;
// See: CompileOptions::mutedErrors.
bool mutedErrors_ = false;
// Set to true if parser saw asmjs directives.
bool containsAsmJS_ = false;
//
// End of fields.
//
// How many ids have been handed out to sources.
static mozilla::Atomic<uint32_t, mozilla::SequentiallyConsistent> idCount_;
template <typename Unit>
const Unit* chunkUnits(JSContext* cx,
UncompressedSourceCache::AutoHoldEntry& holder,
size_t chunk);
// Return a string containing the chars starting at |begin| and ending at
// |begin + len|.
//
// Warning: this is *not* GC-safe! Any chars to be handed out must use
// PinnedUnits. See comment below.
template <typename Unit>
const Unit* units(JSContext* cx, UncompressedSourceCache::AutoHoldEntry& asp,
size_t begin, size_t len);
public:
// When creating a JSString* from TwoByte source characters, we don't try to
// to deflate to Latin1 for longer strings, because this can be slow.
static const size_t SourceDeflateLimit = 100;
explicit ScriptSource() : id_(++idCount_) {}
void finalizeGCData();
~ScriptSource();
void incref() { refs++; }
void decref() {
MOZ_ASSERT(refs != 0);
if (--refs == 0) {
js_delete(this);
}
}
MOZ_MUST_USE bool initFromOptions(JSContext* cx,
const JS::ReadOnlyCompileOptions& options);
/**
* The minimum script length (in code units) necessary for a script to be
* eligible to be compressed.
*/
static constexpr size_t MinimumCompressibleLength = 256;
mozilla::Maybe<SharedImmutableString> getOrCreateStringZ(JSContext* cx,
UniqueChars&& str);
mozilla::Maybe<SharedImmutableTwoByteString> getOrCreateStringZ(
JSContext* cx, UniqueTwoByteChars&& str);
private:
class LoadSourceMatcher;
public:
// Attempt to load usable source for |ss| -- source text on which substring
// operations and the like can be performed. On success return true and set
// |*loaded| to indicate whether usable source could be loaded; otherwise
// return false.
static bool loadSource(JSContext* cx, ScriptSource* ss, bool* loaded);
// Assign source data from |srcBuf| to this recently-created |ScriptSource|.
template <typename Unit>
MOZ_MUST_USE bool assignSource(JSContext* cx,
const JS::ReadOnlyCompileOptions& options,
JS::SourceText<Unit>& srcBuf);
bool hasSourceText() const {
return hasUncompressedSource() || hasCompressedSource();
}
bool hasBinASTSource() const { return data.is<BinAST>(); }
void setBinASTSourceMetadata(frontend::BinASTSourceMetadata* metadata) {
MOZ_ASSERT(hasBinASTSource());
data.as<BinAST>().metadata.reset(metadata);
}
frontend::BinASTSourceMetadata* binASTSourceMetadata() const {
MOZ_ASSERT(hasBinASTSource());
return data.as<BinAST>().metadata.get();
}
private:
template <typename Unit>
struct UncompressedDataMatcher {
template <SourceRetrievable CanRetrieve>
const UncompressedData<Unit>* operator()(
const Uncompressed<Unit, CanRetrieve>& u) {
return &u;
}
template <typename T>
const UncompressedData<Unit>* operator()(const T&) {
MOZ_CRASH(
"attempting to access uncompressed data in a ScriptSource not "
"containing it");
return nullptr;
}
};
public:
template <typename Unit>
const UncompressedData<Unit>* uncompressedData() {
return data.match(UncompressedDataMatcher<Unit>());
}
private:
template <typename Unit>
struct CompressedDataMatcher {
template <SourceRetrievable CanRetrieve>
const CompressedData<Unit>* operator()(
const Compressed<Unit, CanRetrieve>& c) {
return &c;
}
template <typename T>
const CompressedData<Unit>* operator()(const T&) {
MOZ_CRASH(
"attempting to access compressed data in a ScriptSource not "
"containing it");
return nullptr;
}
};
public:
template <typename Unit>
const CompressedData<Unit>* compressedData() {
return data.match(CompressedDataMatcher<Unit>());
}
private:
struct BinASTDataMatcher {
void* operator()(const BinAST& b) {
return const_cast<char*>(b.string.chars());
}
void notBinAST() { MOZ_CRASH("ScriptSource isn't backed by BinAST data"); }
template <typename T>
void* operator()(const T&) {
notBinAST();
return nullptr;
}
};
public:
void* binASTData() { return data.match(BinASTDataMatcher()); }
private:
struct HasUncompressedSource {
template <typename Unit, SourceRetrievable CanRetrieve>
bool operator()(const Uncompressed<Unit, CanRetrieve>&) {
return true;
}
template <typename Unit, SourceRetrievable CanRetrieve>
bool operator()(const Compressed<Unit, CanRetrieve>&) {
return false;
}
template <typename Unit>
bool operator()(const Retrievable<Unit>&) {
return false;
}
bool operator()(const BinAST&) { return false; }
bool operator()(const Missing&) { return false; }
};
public:
bool hasUncompressedSource() const {
return data.match(HasUncompressedSource());
}
private:
template <typename Unit>
struct IsUncompressed {
template <SourceRetrievable CanRetrieve>
bool operator()(const Uncompressed<Unit, CanRetrieve>&) {
return true;
}
template <typename T>
bool operator()(const T&) {
return false;
}
};
public:
template <typename Unit>
bool isUncompressed() const {
return data.match(IsUncompressed<Unit>());
}
private:
struct HasCompressedSource {
template <typename Unit, SourceRetrievable CanRetrieve>
bool operator()(const Compressed<Unit, CanRetrieve>&) {
return true;
}
template <typename T>
bool operator()(const T&) {
return false;
}
};
public:
bool hasCompressedSource() const { return data.match(HasCompressedSource()); }
private:
template <typename Unit>
struct IsCompressed {
template <SourceRetrievable CanRetrieve>
bool operator()(const Compressed<Unit, CanRetrieve>&) {
return true;
}
template <typename T>
bool operator()(const T&) {
return false;
}
};
public:
template <typename Unit>
bool isCompressed() const {
return data.match(IsCompressed<Unit>());
}
private:
template <typename Unit>
struct SourceTypeMatcher {
template <template <typename C, SourceRetrievable R> class Data,
SourceRetrievable CanRetrieve>
bool operator()(const Data<Unit, CanRetrieve>&) {
return true;
}
template <template <typename C, SourceRetrievable R> class Data,
typename NotUnit, SourceRetrievable CanRetrieve>
bool operator()(const Data<NotUnit, CanRetrieve>&) {
return false;
}
bool operator()(const Retrievable<Unit>&) {
MOZ_CRASH("source type only applies where actual text is available");
return false;
}
template <typename NotUnit>
bool operator()(const Retrievable<NotUnit>&) {
return false;
}
bool operator()(const BinAST&) {
MOZ_CRASH("doesn't make sense to ask source type of BinAST data");
return false;
}
bool operator()(const Missing&) {
MOZ_CRASH("doesn't make sense to ask source type when missing");
return false;
}
};
public:
template <typename Unit>
bool hasSourceType() const {
return data.match(SourceTypeMatcher<Unit>());
}
private:
struct UncompressedLengthMatcher {
template <typename Unit, SourceRetrievable CanRetrieve>
size_t operator()(const Uncompressed<Unit, CanRetrieve>& u) {
return u.length();
}
template <typename Unit, SourceRetrievable CanRetrieve>
size_t operator()(const Compressed<Unit, CanRetrieve>& u) {
return u.uncompressedLength;
}
template <typename Unit>
size_t operator()(const Retrievable<Unit>&) {
MOZ_CRASH("ScriptSource::length on a missing-but-retrievable source");
return 0;
}
size_t operator()(const BinAST& b) { return b.string.length(); }
size_t operator()(const Missing& m) {
MOZ_CRASH("ScriptSource::length on a missing source");
return 0;
}
};
public:
size_t length() const {
MOZ_ASSERT(hasSourceText() || hasBinASTSource());
return data.match(UncompressedLengthMatcher());
}
JSLinearString* substring(JSContext* cx, size_t start, size_t stop);
JSLinearString* substringDontDeflate(JSContext* cx, size_t start,
size_t stop);
MOZ_MUST_USE bool appendSubstring(JSContext* cx, js::StringBuffer& buf,
size_t start, size_t stop);
void setParameterListEnd(uint32_t parameterListEnd) {
parameterListEnd_ = parameterListEnd;
}
bool isFunctionBody() { return parameterListEnd_ != 0; }
JSLinearString* functionBodyString(JSContext* cx);
void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
JS::ScriptSourceInfo* info) const;
private:
// Overwrites |data| with the uncompressed data from |source|.
//
// This function asserts nothing about |data|. Users should use assertions to
// double-check their own understandings of the |data| state transition being
// performed.
template <typename Unit>
MOZ_MUST_USE bool setUncompressedSourceHelper(JSContext* cx,
EntryUnits<Unit>&& source,
size_t length,
SourceRetrievable retrievable);
public:
// Initialize a fresh |ScriptSource| with unretrievable, uncompressed source.
template <typename Unit>
MOZ_MUST_USE bool initializeUnretrievableUncompressedSource(
JSContext* cx, EntryUnits<Unit>&& source, size_t length);
// Set the retrieved source for a |ScriptSource| whose source was recorded as
// missing but retrievable.
template <typename Unit>
MOZ_MUST_USE bool setRetrievedSource(JSContext* cx, EntryUnits<Unit>&& source,
size_t length);
MOZ_MUST_USE bool tryCompressOffThread(JSContext* cx);
// *Trigger* the conversion of this ScriptSource from containing uncompressed
// |Unit|-encoded source to containing compressed source. Conversion may not
// be complete when this function returns: it'll be delayed if there's ongoing
// use of the uncompressed source via |PinnedUnits|, in which case conversion
// won't occur until the outermost |PinnedUnits| is destroyed.
//
// Compressed source is in bytes, no matter that |Unit| might be |char16_t|.
// |sourceLength| is the length in code units (not bytes) of the uncompressed
// source.
template <typename Unit>
void triggerConvertToCompressedSource(SharedImmutableString compressed,
size_t sourceLength);
// Initialize a fresh ScriptSource as containing unretrievable compressed
// source of the indicated original encoding.
template <typename Unit>
MOZ_MUST_USE bool initializeWithUnretrievableCompressedSource(
JSContext* cx, UniqueChars&& raw, size_t rawLength, size_t sourceLength);
#if defined(JS_BUILD_BINAST)
/*
* Do not take ownership of the given `buf`. Store the canonical, shared
* and de-duplicated version. If there is no extant shared version of
* `buf`, make a copy.
*/
MOZ_MUST_USE bool setBinASTSourceCopy(JSContext* cx, const uint8_t* buf,
size_t len);
const uint8_t* binASTSource();
#endif /* JS_BUILD_BINAST */
private:
void performTaskWork(SourceCompressionTask* task);
struct TriggerConvertToCompressedSourceFromTask {
ScriptSource* const source_;
SharedImmutableString& compressed_;
TriggerConvertToCompressedSourceFromTask(ScriptSource* source,
SharedImmutableString& compressed)
: source_(source), compressed_(compressed) {}
template <typename Unit, SourceRetrievable CanRetrieve>
void operator()(const Uncompressed<Unit, CanRetrieve>&) {
source_->triggerConvertToCompressedSource<Unit>(std::move(compressed_),
source_->length());
}
template <typename Unit, SourceRetrievable CanRetrieve>
void operator()(const Compressed<Unit, CanRetrieve>&) {
MOZ_CRASH(
"can't set compressed source when source is already compressed -- "
"ScriptSource::tryCompressOffThread shouldn't have queued up this "
"task?");