-
Notifications
You must be signed in to change notification settings - Fork 2k
/
RegExpObject.cpp
1131 lines (947 loc) · 32.5 KB
/
RegExpObject.cpp
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: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* 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/. */
#include "vm/RegExpObject.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "jsstr.h"
#include "builtin/RegExp.h"
#include "frontend/TokenStream.h"
#include "irregexp/RegExpParser.h"
#include "vm/MatchPairs.h"
#include "vm/RegExpStatics.h"
#include "vm/StringBuffer.h"
#include "vm/TraceLogging.h"
#include "vm/Xdr.h"
#include "jsobjinlines.h"
#include "vm/NativeObject-inl.h"
#include "vm/Shape-inl.h"
using namespace js;
using mozilla::ArrayLength;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::PodCopy;
using js::frontend::TokenStream;
using JS::AutoCheckCannotGC;
JS_STATIC_ASSERT(IgnoreCaseFlag == JSREG_FOLD);
JS_STATIC_ASSERT(GlobalFlag == JSREG_GLOB);
JS_STATIC_ASSERT(MultilineFlag == JSREG_MULTILINE);
JS_STATIC_ASSERT(StickyFlag == JSREG_STICKY);
/* RegExpObjectBuilder */
RegExpObjectBuilder::RegExpObjectBuilder(ExclusiveContext* cx, RegExpObject* reobj)
: cx(cx), reobj_(cx, reobj)
{}
bool
RegExpObjectBuilder::getOrCreate()
{
if (reobj_)
return true;
// Note: RegExp objects are always allocated in the tenured heap. This is
// not strictly required, but simplifies embedding them in jitcode.
reobj_ = NewBuiltinClassInstance<RegExpObject>(cx, TenuredObject);
if (!reobj_)
return false;
reobj_->initPrivate(nullptr);
return true;
}
bool
RegExpObjectBuilder::getOrCreateClone(HandleObjectGroup group)
{
MOZ_ASSERT(!reobj_);
MOZ_ASSERT(group->clasp() == &RegExpObject::class_);
// Note: RegExp objects are always allocated in the tenured heap. This is
// not strictly required, but simplifies embedding them in jitcode.
reobj_ = NewObjectWithGroup<RegExpObject>(cx->asJSContext(), group, TenuredObject);
if (!reobj_)
return false;
reobj_->initPrivate(nullptr);
return true;
}
RegExpObject*
RegExpObjectBuilder::build(HandleAtom source, RegExpShared& shared)
{
if (!getOrCreate())
return nullptr;
if (!reobj_->init(cx, source, shared.getFlags()))
return nullptr;
reobj_->setShared(shared);
return reobj_;
}
RegExpObject*
RegExpObjectBuilder::build(HandleAtom source, RegExpFlag flags)
{
if (!getOrCreate())
return nullptr;
return reobj_->init(cx, source, flags) ? reobj_.get() : nullptr;
}
RegExpObject*
RegExpObjectBuilder::clone(Handle<RegExpObject*> other)
{
RootedObjectGroup group(cx, other->group());
if (!getOrCreateClone(group))
return nullptr;
/*
* Check that the RegExpShared for the original is okay to use in
* the clone -- if the |RegExpStatics| provides more flags we'll
* need a different |RegExpShared|.
*/
RegExpStatics* res = other->getProto()->global().getRegExpStatics(cx);
if (!res)
return nullptr;
RegExpFlag origFlags = other->getFlags();
RegExpFlag staticsFlags = res->getFlags();
if ((origFlags & staticsFlags) != staticsFlags) {
RegExpFlag newFlags = RegExpFlag(origFlags | staticsFlags);
Rooted<JSAtom*> source(cx, other->getSource());
return build(source, newFlags);
}
RegExpGuard g(cx);
if (!other->getShared(cx->asJSContext(), &g))
return nullptr;
Rooted<JSAtom*> source(cx, other->getSource());
return build(source, *g);
}
/* MatchPairs */
bool
MatchPairs::initArray(size_t pairCount)
{
MOZ_ASSERT(pairCount > 0);
/* Guarantee adequate space in buffer. */
if (!allocOrExpandArray(pairCount))
return false;
/* Initialize all MatchPair objects to invalid locations. */
for (size_t i = 0; i < pairCount; i++) {
pairs_[i].start = -1;
pairs_[i].limit = -1;
}
return true;
}
bool
MatchPairs::initArrayFrom(MatchPairs& copyFrom)
{
MOZ_ASSERT(copyFrom.pairCount() > 0);
if (!allocOrExpandArray(copyFrom.pairCount()))
return false;
PodCopy(pairs_, copyFrom.pairs_, pairCount_);
return true;
}
void
MatchPairs::displace(size_t disp)
{
if (disp == 0)
return;
for (size_t i = 0; i < pairCount_; i++) {
MOZ_ASSERT(pairs_[i].check());
pairs_[i].start += (pairs_[i].start < 0) ? 0 : disp;
pairs_[i].limit += (pairs_[i].limit < 0) ? 0 : disp;
}
}
bool
ScopedMatchPairs::allocOrExpandArray(size_t pairCount)
{
/* Array expansion is forbidden, but array reuse is acceptable. */
if (pairCount_) {
MOZ_ASSERT(pairs_);
MOZ_ASSERT(pairCount_ == pairCount);
return true;
}
MOZ_ASSERT(!pairs_);
pairs_ = (MatchPair*)lifoScope_.alloc().alloc(sizeof(MatchPair) * pairCount);
if (!pairs_)
return false;
pairCount_ = pairCount;
return true;
}
bool
VectorMatchPairs::allocOrExpandArray(size_t pairCount)
{
if (!vec_.resizeUninitialized(sizeof(MatchPair) * pairCount))
return false;
pairs_ = &vec_[0];
pairCount_ = pairCount;
return true;
}
/* RegExpObject */
static inline void
MaybeTraceRegExpShared(JSContext* cx, RegExpShared* shared)
{
Zone* zone = cx->zone();
if (zone->needsIncrementalBarrier())
shared->trace(zone->barrierTracer());
}
bool
RegExpObject::getShared(JSContext* cx, RegExpGuard* g)
{
if (RegExpShared* shared = maybeShared()) {
// Fetching a RegExpShared from an object requires a read
// barrier, as the shared pointer might be weak.
MaybeTraceRegExpShared(cx, shared);
g->init(*shared);
return true;
}
return createShared(cx, g);
}
/* static */ void
RegExpObject::trace(JSTracer* trc, JSObject* obj)
{
RegExpShared* shared = obj->as<RegExpObject>().maybeShared();
if (!shared)
return;
// When tracing through the object normally, we have the option of
// unlinking the object from its RegExpShared so that the RegExpShared may
// be collected. To detect this we need to test all the following
// conditions, since:
// 1. During TraceRuntime, isHeapBusy() is true, but the tracer might not
// be a marking tracer.
// 2. When a write barrier executes, IsMarkingTracer is true, but
// isHeapBusy() will be false.
if (trc->runtime()->isHeapBusy() &&
trc->isMarkingTracer() &&
!obj->asTenured().zone()->isPreservingCode())
{
obj->as<RegExpObject>().NativeObject::setPrivate(nullptr);
} else {
shared->trace(trc);
}
}
const Class RegExpObject::class_ = {
js_RegExp_str,
JSCLASS_HAS_PRIVATE | JSCLASS_IMPLEMENTS_BARRIERS |
JSCLASS_HAS_RESERVED_SLOTS(RegExpObject::RESERVED_SLOTS) |
JSCLASS_HAS_CACHED_PROTO(JSProto_RegExp),
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* getProperty */
nullptr, /* setProperty */
nullptr, /* enumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* convert */
nullptr, /* finalize */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
RegExpObject::trace,
// ClassSpec
{
GenericCreateConstructor<js::regexp_construct, 2, gc::AllocKind::FUNCTION>,
CreateRegExpPrototype,
nullptr,
js::regexp_static_props,
js::regexp_methods,
js::regexp_properties
}
};
RegExpObject*
RegExpObject::create(ExclusiveContext* cx, RegExpStatics* res, const char16_t* chars, size_t length,
RegExpFlag flags, TokenStream* tokenStream, LifoAlloc& alloc)
{
RegExpFlag staticsFlags = res->getFlags();
return createNoStatics(cx, chars, length, RegExpFlag(flags | staticsFlags), tokenStream, alloc);
}
RegExpObject*
RegExpObject::createNoStatics(ExclusiveContext* cx, const char16_t* chars, size_t length, RegExpFlag flags,
TokenStream* tokenStream, LifoAlloc& alloc)
{
RootedAtom source(cx, AtomizeChars(cx, chars, length));
if (!source)
return nullptr;
return createNoStatics(cx, source, flags, tokenStream, alloc);
}
RegExpObject*
RegExpObject::createNoStatics(ExclusiveContext* cx, HandleAtom source, RegExpFlag flags,
TokenStream* tokenStream, LifoAlloc& alloc)
{
Maybe<CompileOptions> dummyOptions;
Maybe<TokenStream> dummyTokenStream;
if (!tokenStream) {
dummyOptions.emplace(cx->asJSContext());
dummyTokenStream.emplace(cx, *dummyOptions,
(const char16_t*) nullptr, 0,
(frontend::StrictModeGetter*) nullptr);
tokenStream = dummyTokenStream.ptr();
}
if (!irregexp::ParsePatternSyntax(*tokenStream, alloc, source))
return nullptr;
RegExpObjectBuilder builder(cx);
return builder.build(source, flags);
}
bool
RegExpObject::createShared(JSContext* cx, RegExpGuard* g)
{
Rooted<RegExpObject*> self(cx, this);
MOZ_ASSERT(!maybeShared());
if (!cx->compartment()->regExps.get(cx, getSource(), getFlags(), g))
return false;
self->setShared(**g);
return true;
}
Shape*
RegExpObject::assignInitialShape(ExclusiveContext* cx, Handle<RegExpObject*> self)
{
MOZ_ASSERT(self->empty());
JS_STATIC_ASSERT(LAST_INDEX_SLOT == 0);
/* The lastIndex property alone is writable but non-configurable. */
return self->addDataProperty(cx, cx->names().lastIndex, LAST_INDEX_SLOT, JSPROP_PERMANENT);
}
bool
RegExpObject::init(ExclusiveContext* cx, HandleAtom source, RegExpFlag flags)
{
Rooted<RegExpObject*> self(cx, this);
if (!EmptyShape::ensureInitialCustomShape<RegExpObject>(cx, self))
return false;
MOZ_ASSERT(self->lookup(cx, NameToId(cx->names().lastIndex))->slot() ==
LAST_INDEX_SLOT);
/*
* If this is a re-initialization with an existing RegExpShared, 'flags'
* may not match getShared()->flags, so forget the RegExpShared.
*/
self->NativeObject::setPrivate(nullptr);
self->zeroLastIndex();
self->setSource(source);
self->setGlobal(flags & GlobalFlag);
self->setIgnoreCase(flags & IgnoreCaseFlag);
self->setMultiline(flags & MultilineFlag);
self->setSticky(flags & StickyFlag);
return true;
}
static MOZ_ALWAYS_INLINE bool
IsLineTerminator(const JS::Latin1Char c)
{
return c == '\n' || c == '\r';
}
static MOZ_ALWAYS_INLINE bool
IsLineTerminator(const char16_t c)
{
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
}
static MOZ_ALWAYS_INLINE bool
AppendEscapedLineTerminator(StringBuffer& sb, const JS::Latin1Char c)
{
switch (c) {
case '\n':
if (!sb.append('n'))
return false;
break;
case '\r':
if (!sb.append('r'))
return false;
break;
default:
MOZ_CRASH("Bad LineTerminator");
}
return true;
}
static MOZ_ALWAYS_INLINE bool
AppendEscapedLineTerminator(StringBuffer& sb, const char16_t c)
{
switch (c) {
case '\n':
if (!sb.append('n'))
return false;
break;
case '\r':
if (!sb.append('r'))
return false;
break;
case 0x2028:
if (!sb.append("u2028"))
return false;
break;
case 0x2029:
if (!sb.append("u2029"))
return false;
break;
default:
MOZ_CRASH("Bad LineTerminator");
}
return true;
}
template <typename CharT>
static MOZ_ALWAYS_INLINE bool
SetupBuffer(StringBuffer& sb, const CharT* oldChars, size_t oldLen, const CharT* it)
{
if (mozilla::IsSame<CharT, char16_t>::value && !sb.ensureTwoByteChars())
return false;
if (!sb.reserve(oldLen + 1))
return false;
sb.infallibleAppend(oldChars, size_t(it - oldChars));
return true;
}
// Note: returns the original if no escaping need be performed.
template <typename CharT>
static bool
EscapeRegExpPattern(StringBuffer& sb, const CharT* oldChars, size_t oldLen)
{
bool inBrackets = false;
bool previousCharacterWasBackslash = false;
for (const CharT* it = oldChars; it < oldChars + oldLen; ++it) {
CharT ch = *it;
if (!previousCharacterWasBackslash) {
if (inBrackets) {
if (ch == ']')
inBrackets = false;
} else if (ch == '/') {
// There's a forward slash that needs escaping.
if (sb.empty()) {
// This is the first char we've seen that needs escaping,
// copy everything up to this point.
if (!SetupBuffer(sb, oldChars, oldLen, it))
return false;
}
if (!sb.append('\\'))
return false;
} else if (ch == '[') {
inBrackets = true;
}
}
if (IsLineTerminator(ch)) {
// There's LineTerminator that needs escaping.
if (sb.empty()) {
// This is the first char we've seen that needs escaping,
// copy everything up to this point.
if (!SetupBuffer(sb, oldChars, oldLen, it))
return false;
}
if (!previousCharacterWasBackslash) {
if (!sb.append('\\'))
return false;
}
if (!AppendEscapedLineTerminator(sb, ch))
return false;
} else if (!sb.empty()) {
if (!sb.append(ch))
return false;
}
if (previousCharacterWasBackslash)
previousCharacterWasBackslash = false;
else if (ch == '\\')
previousCharacterWasBackslash = true;
}
return true;
}
// ES6 draft rev32 21.2.3.2.4.
JSAtom*
js::EscapeRegExpPattern(JSContext* cx, HandleAtom src)
{
// Step 2.
if (src->length() == 0)
return cx->names().emptyRegExp;
// We may never need to use |sb|. Start using it lazily.
StringBuffer sb(cx);
if (src->hasLatin1Chars()) {
JS::AutoCheckCannotGC nogc;
if (!::EscapeRegExpPattern(sb, src->latin1Chars(nogc), src->length()))
return nullptr;
} else {
JS::AutoCheckCannotGC nogc;
if (!::EscapeRegExpPattern(sb, src->twoByteChars(nogc), src->length()))
return nullptr;
}
// Step 3.
return sb.empty() ? src : sb.finishAtom();
}
// ES6 draft rev32 21.2.5.14. Optimized for RegExpObject.
JSFlatString*
RegExpObject::toString(JSContext* cx) const
{
// Steps 3-4.
RootedAtom src(cx, getSource());
if (!src)
return nullptr;
RootedAtom escapedSrc(cx, EscapeRegExpPattern(cx, src));
// Step 7.
StringBuffer sb(cx);
size_t len = escapedSrc->length();
if (!sb.reserve(len + 2))
return nullptr;
sb.infallibleAppend('/');
if (!sb.append(escapedSrc))
return nullptr;
sb.infallibleAppend('/');
// Steps 5-7.
if (global() && !sb.append('g'))
return nullptr;
if (ignoreCase() && !sb.append('i'))
return nullptr;
if (multiline() && !sb.append('m'))
return nullptr;
if (sticky() && !sb.append('y'))
return nullptr;
return sb.finishString();
}
/* RegExpShared */
RegExpShared::RegExpShared(JSAtom* source, RegExpFlag flags)
: source(source), flags(flags), parenCount(0), canStringMatch(false), marked_(false)
{}
RegExpShared::~RegExpShared()
{
for (size_t i = 0; i < tables.length(); i++)
js_delete(tables[i]);
}
void
RegExpShared::trace(JSTracer* trc)
{
if (trc->isMarkingTracer())
marked_ = true;
if (source)
TraceEdge(trc, &source, "RegExpShared source");
for (size_t i = 0; i < ArrayLength(compilationArray); i++) {
RegExpCompilation& compilation = compilationArray[i];
if (compilation.jitCode)
TraceEdge(trc, &compilation.jitCode, "RegExpShared code");
}
}
bool
RegExpShared::compile(JSContext* cx, HandleLinearString input,
CompilationMode mode, ForceByteCodeEnum force)
{
TraceLoggerThread* logger = TraceLoggerForMainThread(cx->runtime());
AutoTraceLog logCompile(logger, TraceLogger_IrregexpCompile);
if (!sticky()) {
RootedAtom pattern(cx, source);
return compile(cx, pattern, input, mode, force);
}
/*
* The sticky case we implement hackily by prepending a caret onto the front
* and relying on |::execute| to pseudo-slice the string when it sees a sticky regexp.
*/
static const char prefix[] = {'^', '(', '?', ':'};
static const char postfix[] = {')'};
using mozilla::ArrayLength;
StringBuffer sb(cx);
if (!sb.reserve(ArrayLength(prefix) + source->length() + ArrayLength(postfix)))
return false;
sb.infallibleAppend(prefix, ArrayLength(prefix));
if (!sb.append(source))
return false;
sb.infallibleAppend(postfix, ArrayLength(postfix));
RootedAtom fakeySource(cx, sb.finishAtom());
if (!fakeySource)
return false;
return compile(cx, fakeySource, input, mode, force);
}
bool
RegExpShared::compile(JSContext* cx, HandleAtom pattern, HandleLinearString input,
CompilationMode mode, ForceByteCodeEnum force)
{
if (!ignoreCase() && !StringHasRegExpMetaChars(pattern))
canStringMatch = true;
CompileOptions options(cx);
TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
LifoAllocScope scope(&cx->tempLifoAlloc());
/* Parse the pattern. */
irregexp::RegExpCompileData data;
if (!irregexp::ParsePattern(dummyTokenStream, cx->tempLifoAlloc(), pattern,
multiline(), mode == MatchOnly, &data))
{
return false;
}
this->parenCount = data.capture_count;
irregexp::RegExpCode code = irregexp::CompilePattern(cx, this, &data, input,
false /* global() */,
ignoreCase(),
input->hasLatin1Chars(),
mode == MatchOnly,
force == ForceByteCode);
if (code.empty())
return false;
MOZ_ASSERT(!code.jitCode || !code.byteCode);
MOZ_ASSERT_IF(force == ForceByteCode, code.byteCode);
RegExpCompilation& compilation = this->compilation(mode, input->hasLatin1Chars());
if (code.jitCode)
compilation.jitCode = code.jitCode;
else if (code.byteCode)
compilation.byteCode = code.byteCode;
return true;
}
bool
RegExpShared::compileIfNecessary(JSContext* cx, HandleLinearString input,
CompilationMode mode, ForceByteCodeEnum force)
{
if (isCompiled(mode, input->hasLatin1Chars(), force))
return true;
return compile(cx, input, mode, force);
}
RegExpRunStatus
RegExpShared::execute(JSContext* cx, HandleLinearString input, size_t start,
MatchPairs* matches)
{
TraceLoggerThread* logger = TraceLoggerForMainThread(cx->runtime());
CompilationMode mode = matches ? Normal : MatchOnly;
/* Compile the code at point-of-use. */
if (!compileIfNecessary(cx, input, mode, DontForceByteCode))
return RegExpRunStatus_Error;
/*
* Ensure sufficient memory for output vector.
* No need to initialize it. The RegExp engine fills them in on a match.
*/
if (matches && !matches->allocOrExpandArray(pairCount())) {
ReportOutOfMemory(cx);
return RegExpRunStatus_Error;
}
/*
* |displacement| emulates sticky mode by matching from this offset
* into the char buffer and subtracting the delta off at the end.
*/
size_t charsOffset = 0;
size_t length = input->length();
size_t origLength = length;
size_t displacement = 0;
if (sticky()) {
displacement = start;
charsOffset += displacement;
length -= displacement;
start = 0;
}
// Reset the Irregexp backtrack stack if it grows during execution.
irregexp::RegExpStackScope stackScope(cx->runtime());
if (canStringMatch) {
MOZ_ASSERT(pairCount() == 1);
int res = StringFindPattern(input, source, start + charsOffset);
if (res == -1)
return RegExpRunStatus_Success_NotFound;
if (matches) {
(*matches)[0].start = res;
(*matches)[0].limit = res + source->length();
matches->checkAgainst(origLength);
}
return RegExpRunStatus_Success;
}
do {
jit::JitCode* code = compilation(mode, input->hasLatin1Chars()).jitCode;
if (!code)
break;
RegExpRunStatus result;
{
AutoTraceLog logJIT(logger, TraceLogger_IrregexpExecute);
AutoCheckCannotGC nogc;
if (input->hasLatin1Chars()) {
const Latin1Char* chars = input->latin1Chars(nogc) + charsOffset;
result = irregexp::ExecuteCode(cx, code, chars, start, length, matches);
} else {
const char16_t* chars = input->twoByteChars(nogc) + charsOffset;
result = irregexp::ExecuteCode(cx, code, chars, start, length, matches);
}
}
if (result == RegExpRunStatus_Error) {
// An 'Error' result is returned if a stack overflow guard or
// interrupt guard failed. If CheckOverRecursed doesn't throw, break
// out and retry the regexp in the bytecode interpreter, which can
// execute while tolerating future interrupts. Otherwise, if we keep
// getting interrupted we will never finish executing the regexp.
if (!jit::CheckOverRecursed(cx))
return RegExpRunStatus_Error;
break;
}
if (result == RegExpRunStatus_Success_NotFound)
return RegExpRunStatus_Success_NotFound;
MOZ_ASSERT(result == RegExpRunStatus_Success);
if (matches) {
matches->displace(displacement);
matches->checkAgainst(origLength);
}
return RegExpRunStatus_Success;
} while (false);
// Compile bytecode for the RegExp if necessary.
if (!compileIfNecessary(cx, input, mode, ForceByteCode))
return RegExpRunStatus_Error;
uint8_t* byteCode = compilation(mode, input->hasLatin1Chars()).byteCode;
AutoTraceLog logInterpreter(logger, TraceLogger_IrregexpExecute);
AutoStableStringChars inputChars(cx);
if (!inputChars.init(cx, input))
return RegExpRunStatus_Error;
RegExpRunStatus result;
if (inputChars.isLatin1()) {
const Latin1Char* chars = inputChars.latin1Range().start().get() + charsOffset;
result = irregexp::InterpretCode(cx, byteCode, chars, start, length, matches);
} else {
const char16_t* chars = inputChars.twoByteRange().start().get() + charsOffset;
result = irregexp::InterpretCode(cx, byteCode, chars, start, length, matches);
}
if (result == RegExpRunStatus_Success && matches) {
matches->displace(displacement);
matches->checkAgainst(origLength);
}
return result;
}
size_t
RegExpShared::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf)
{
size_t n = mallocSizeOf(this);
for (size_t i = 0; i < ArrayLength(compilationArray); i++) {
const RegExpCompilation& compilation = compilationArray[i];
if (compilation.byteCode)
n += mallocSizeOf(compilation.byteCode);
}
n += tables.sizeOfExcludingThis(mallocSizeOf);
for (size_t i = 0; i < tables.length(); i++)
n += mallocSizeOf(tables[i]);
return n;
}
/* RegExpCompartment */
RegExpCompartment::RegExpCompartment(JSRuntime* rt)
: set_(rt), matchResultTemplateObject_(nullptr)
{}
RegExpCompartment::~RegExpCompartment()
{
// Because of stray mark bits being set (see RegExpCompartment::sweep)
// there might still be RegExpShared instances which haven't been deleted.
if (set_.initialized()) {
for (Set::Enum e(set_); !e.empty(); e.popFront()) {
RegExpShared* shared = e.front();
js_delete(shared);
}
}
}
ArrayObject*
RegExpCompartment::createMatchResultTemplateObject(JSContext* cx)
{
MOZ_ASSERT(!matchResultTemplateObject_);
/* Create template array object */
RootedArrayObject templateObject(cx, NewDenseUnallocatedArray(cx, 0, nullptr, TenuredObject));
if (!templateObject)
return matchResultTemplateObject_; // = nullptr
// Create a new group for the template.
Rooted<TaggedProto> proto(cx, templateObject->getTaggedProto());
ObjectGroup* group = ObjectGroupCompartment::makeGroup(cx, templateObject->getClass(), proto);
if (!group)
return matchResultTemplateObject_; // = nullptr
templateObject->setGroup(group);
/* Set dummy index property */
RootedValue index(cx, Int32Value(0));
if (!NativeDefineProperty(cx, templateObject, cx->names().index, index, nullptr, nullptr,
JSPROP_ENUMERATE))
{
return matchResultTemplateObject_; // = nullptr
}
/* Set dummy input property */
RootedValue inputVal(cx, StringValue(cx->runtime()->emptyString));
if (!NativeDefineProperty(cx, templateObject, cx->names().input, inputVal, nullptr, nullptr,
JSPROP_ENUMERATE))
{
return matchResultTemplateObject_; // = nullptr
}
// Make sure that the properties are in the right slots.
DebugOnly<Shape*> shape = templateObject->lastProperty();
MOZ_ASSERT(shape->previous()->slot() == 0 &&
shape->previous()->propidRef() == NameToId(cx->names().index));
MOZ_ASSERT(shape->slot() == 1 &&
shape->propidRef() == NameToId(cx->names().input));
// Make sure type information reflects the indexed properties which might
// be added.
AddTypePropertyId(cx, templateObject, JSID_VOID, TypeSet::StringType());
AddTypePropertyId(cx, templateObject, JSID_VOID, TypeSet::UndefinedType());
matchResultTemplateObject_.set(templateObject);
return matchResultTemplateObject_;
}
bool
RegExpCompartment::init(JSContext* cx)
{
if (!set_.init(0)) {
if (cx)
ReportOutOfMemory(cx);
return false;
}
return true;
}
void
RegExpCompartment::sweep(JSRuntime* rt)
{
if (!set_.initialized())
return;
for (Set::Enum e(set_); !e.empty(); e.popFront()) {
RegExpShared* shared = e.front();
// Sometimes RegExpShared instances are marked without the
// compartment being subsequently cleared. This can happen if a GC is
// restarted while in progress (i.e. performing a full GC in the
// middle of an incremental GC) or if a RegExpShared referenced via the
// stack is traced but is not in a zone being collected.
//
// Because of this we only treat the marked_ bit as a hint, and destroy
// the RegExpShared if it was accidentally marked earlier but wasn't
// marked by the current trace.
bool keep = shared->marked() &&
IsMarked(&shared->source);
for (size_t i = 0; i < ArrayLength(shared->compilationArray); i++) {
RegExpShared::RegExpCompilation& compilation = shared->compilationArray[i];
if (compilation.jitCode &&
IsAboutToBeFinalized(&compilation.jitCode))
{
keep = false;
}
}
MOZ_ASSERT(rt->isHeapMajorCollecting());
if (keep || rt->gc.isHeapCompacting()) {
shared->clearMarked();
} else {
js_delete(shared);
e.removeFront();
}
}
if (matchResultTemplateObject_ &&
IsAboutToBeFinalized(&matchResultTemplateObject_))
{
matchResultTemplateObject_.set(nullptr);
}
}
bool
RegExpCompartment::get(JSContext* cx, JSAtom* source, RegExpFlag flags, RegExpGuard* g)
{
Key key(source, flags);
Set::AddPtr p = set_.lookupForAdd(key);
if (p) {
// Trigger a read barrier on existing RegExpShared instances fetched
// from the table (which only holds weak references).
MaybeTraceRegExpShared(cx, *p);
g->init(**p);
return true;
}
ScopedJSDeletePtr<RegExpShared> shared(cx->new_<RegExpShared>(source, flags));
if (!shared)
return false;
if (!set_.add(p, shared)) {
ReportOutOfMemory(cx);
return false;
}
// Trace RegExpShared instances created during an incremental GC.
MaybeTraceRegExpShared(cx, shared);
g->init(*shared.forget());
return true;
}
bool
RegExpCompartment::get(JSContext* cx, HandleAtom atom, JSString* opt, RegExpGuard* g)
{
RegExpFlag flags = RegExpFlag(0);
if (opt && !ParseRegExpFlags(cx, opt, &flags))
return false;
return get(cx, atom, flags, g);
}
size_t
RegExpCompartment::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf)
{
size_t n = 0;
n += set_.sizeOfExcludingThis(mallocSizeOf);
for (Set::Enum e(set_); !e.empty(); e.popFront()) {
RegExpShared* shared = e.front();
n += shared->sizeOfIncludingThis(mallocSizeOf);
}
return n;
}
/* Functions */
JSObject*