forked from charlietuna/JavaScriptCore-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcre_exec.cpp
More file actions
2177 lines (1812 loc) · 99.3 KB
/
pcre_exec.cpp
File metadata and controls
2177 lines (1812 loc) · 99.3 KB
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
/* This is JavaScriptCore's variant of the PCRE library. While this library
started out as a copy of PCRE, many of the features of PCRE have been
removed. This library now supports only the regular expression features
required by the JavaScript language specification, and has only the functions
needed by JavaScriptCore and the rest of WebKit.
Originally written by Philip Hazel
Copyright (c) 1997-2006 University of Cambridge
Copyright (C) 2002, 2004, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
Copyright (C) 2007 Eric Seidel <[email protected]>
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This module contains jsRegExpExecute(), the externally visible function
that does pattern matching using an NFA algorithm, following the rules from
the JavaScript specification. There are also some supporting functions. */
#include "config.h"
#include "pcre_internal.h"
#include <limits.h>
#include <wtf/ASCIICType.h>
#include <wtf/Vector.h>
#if REGEXP_HISTOGRAM
#include <wtf/DateMath.h>
#include <runtime/UString.h>
#endif
using namespace WTF;
#if COMPILER(GCC)
#define USE_COMPUTED_GOTO_FOR_MATCH_RECURSION
//#define USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
#endif
/* Avoid warnings on Windows. */
#undef min
#undef max
#ifndef USE_COMPUTED_GOTO_FOR_MATCH_RECURSION
typedef int ReturnLocation;
#else
typedef void* ReturnLocation;
#endif
#if !REGEXP_HISTOGRAM
class HistogramTimeLogger {
public:
HistogramTimeLogger(const JSRegExp*) { }
};
#else
using namespace JSC;
class Histogram {
public:
~Histogram();
void add(const JSRegExp*, double);
private:
typedef HashMap<RefPtr<UString::Rep>, double> Map;
Map times;
};
class HistogramTimeLogger {
public:
HistogramTimeLogger(const JSRegExp*);
~HistogramTimeLogger();
private:
const JSRegExp* m_re;
double m_startTime;
};
#endif
/* Structure for building a chain of data for holding the values of
the subject pointer at the start of each bracket, used to detect when
an empty string has been matched by a bracket to break infinite loops. */
struct BracketChainNode {
BracketChainNode* previousBracket;
const UChar* bracketStart;
};
struct MatchFrame : FastAllocBase {
ReturnLocation returnLocation;
struct MatchFrame* previousFrame;
/* Function arguments that may change */
struct {
const UChar* subjectPtr;
const unsigned char* instructionPtr;
int offsetTop;
BracketChainNode* bracketChain;
} args;
/* PCRE uses "fake" recursion built off of gotos, thus
stack-based local variables are not safe to use. Instead we have to
store local variables on the current MatchFrame. */
struct {
const unsigned char* data;
const unsigned char* startOfRepeatingBracket;
const UChar* subjectPtrAtStartOfInstruction; // Several instrutions stash away a subjectPtr here for later compare
const unsigned char* instructionPtrAtStartOfOnce;
int repeatOthercase;
int ctype;
int fc;
int fi;
int length;
int max;
int number;
int offset;
int saveOffset1;
int saveOffset2;
int saveOffset3;
BracketChainNode bracketChainNode;
} locals;
};
/* Structure for passing "static" information around between the functions
doing traditional NFA matching, so that they are thread-safe. */
struct MatchData {
int* offsetVector; /* Offset vector */
int offsetEnd; /* One past the end */
int offsetMax; /* The maximum usable for return data */
bool offsetOverflow; /* Set if too many extractions */
const UChar* startSubject; /* Start of the subject string */
const UChar* endSubject; /* End of the subject string */
const UChar* endMatchPtr; /* Subject position at end match */
int endOffsetTop; /* Highwater mark at end of match */
bool multiline;
bool ignoreCase;
};
/* The maximum remaining length of subject we are prepared to search for a
reqByte match. */
#define REQ_BYTE_MAX 1000
/* The below limit restricts the number of "recursive" match calls in order to
avoid spending exponential time on complex regular expressions. */
static const unsigned matchLimit = 1000000;
#ifdef DEBUG
/*************************************************
* Debugging function to print chars *
*************************************************/
/* Print a sequence of chars in printable format, stopping at the end of the
subject if the requested.
Arguments:
p points to characters
length number to print
isSubject true if printing from within md.startSubject
md pointer to matching data block, if isSubject is true
*/
static void pchars(const UChar* p, int length, bool isSubject, const MatchData& md)
{
if (isSubject && length > md.endSubject - p)
length = md.endSubject - p;
while (length-- > 0) {
int c;
if (isASCIIPrintable(c = *(p++)))
printf("%c", c);
else if (c < 256)
printf("\\x%02x", c);
else
printf("\\x{%x}", c);
}
}
#endif
/*************************************************
* Match a back-reference *
*************************************************/
/* If a back reference hasn't been set, the length that is passed is greater
than the number of characters left in the string, so the match fails.
Arguments:
offset index into the offset vector
subjectPtr points into the subject
length length to be matched
md points to match data block
Returns: true if matched
*/
static bool matchRef(int offset, const UChar* subjectPtr, int length, const MatchData& md)
{
const UChar* p = md.startSubject + md.offsetVector[offset];
#ifdef DEBUG
if (subjectPtr >= md.endSubject)
printf("matching subject <null>");
else {
printf("matching subject ");
pchars(subjectPtr, length, true, md);
}
printf(" against backref ");
pchars(p, length, false, md);
printf("\n");
#endif
/* Always fail if not enough characters left */
if (length > md.endSubject - subjectPtr)
return false;
/* Separate the caselesss case for speed */
if (md.ignoreCase) {
while (length-- > 0) {
UChar c = *p++;
int othercase = jsc_pcre_ucp_othercase(c);
UChar d = *subjectPtr++;
if (c != d && othercase != d)
return false;
}
}
else {
while (length-- > 0)
if (*p++ != *subjectPtr++)
return false;
}
return true;
}
#ifndef USE_COMPUTED_GOTO_FOR_MATCH_RECURSION
/* Use numbered labels and switch statement at the bottom of the match function. */
#define RMATCH_WHERE(num) num
#define RRETURN_LABEL RRETURN_SWITCH
#else
/* Use GCC's computed goto extension. */
/* For one test case this is more than 40% faster than the switch statement.
We could avoid the use of the num argument entirely by using local labels,
but using it for the GCC case as well as the non-GCC case allows us to share
a bit more code and notice if we use conflicting numbers.*/
#define RMATCH_WHERE(num) &&RRETURN_##num
#define RRETURN_LABEL *stack.currentFrame->returnLocation
#endif
#define RECURSIVE_MATCH_COMMON(num) \
goto RECURSE;\
RRETURN_##num: \
stack.popCurrentFrame();
#define RECURSIVE_MATCH(num, ra, rb) \
do { \
stack.pushNewFrame((ra), (rb), RMATCH_WHERE(num)); \
RECURSIVE_MATCH_COMMON(num) \
} while (0)
#define RECURSIVE_MATCH_NEW_GROUP(num, ra, rb) \
do { \
stack.pushNewFrame((ra), (rb), RMATCH_WHERE(num)); \
startNewGroup(stack.currentFrame); \
RECURSIVE_MATCH_COMMON(num) \
} while (0)
#define RRETURN goto RRETURN_LABEL
#define RRETURN_NO_MATCH do { isMatch = false; RRETURN; } while (0)
/*************************************************
* Match from current position *
*************************************************/
/* On entry instructionPtr points to the first opcode, and subjectPtr to the first character
in the subject string, while substringStart holds the value of subjectPtr at the start of the
last bracketed group - used for breaking infinite loops matching zero-length
strings. This function is called recursively in many circumstances. Whenever it
returns a negative (error) response, the outer match() call must also return the
same response.
Arguments:
subjectPtr pointer in subject
instructionPtr position in code
offsetTop current top pointer
md pointer to "static" info for the match
Returns: 1 if matched ) these values are >= 0
0 if failed to match )
a negative error value if aborted by an error condition
(e.g. stopped by repeated call or recursion limit)
*/
static const unsigned numFramesOnStack = 16;
struct MatchStack {
MatchStack()
: framesEnd(frames + numFramesOnStack)
, currentFrame(frames)
, size(1) // match() creates accesses the first frame w/o calling pushNewFrame
{
ASSERT((sizeof(frames) / sizeof(frames[0])) == numFramesOnStack);
}
MatchFrame frames[numFramesOnStack];
MatchFrame* framesEnd;
MatchFrame* currentFrame;
unsigned size;
inline bool canUseStackBufferForNextFrame()
{
return size < numFramesOnStack;
}
inline MatchFrame* allocateNextFrame()
{
if (canUseStackBufferForNextFrame())
return currentFrame + 1;
return new MatchFrame;
}
inline void pushNewFrame(const unsigned char* instructionPtr, BracketChainNode* bracketChain, ReturnLocation returnLocation)
{
MatchFrame* newframe = allocateNextFrame();
newframe->previousFrame = currentFrame;
newframe->args.subjectPtr = currentFrame->args.subjectPtr;
newframe->args.offsetTop = currentFrame->args.offsetTop;
newframe->args.instructionPtr = instructionPtr;
newframe->args.bracketChain = bracketChain;
newframe->returnLocation = returnLocation;
size++;
currentFrame = newframe;
}
inline void popCurrentFrame()
{
MatchFrame* oldFrame = currentFrame;
currentFrame = currentFrame->previousFrame;
if (size > numFramesOnStack)
delete oldFrame;
size--;
}
void popAllFrames()
{
while (size)
popCurrentFrame();
}
};
static int matchError(int errorCode, MatchStack& stack)
{
stack.popAllFrames();
return errorCode;
}
/* Get the next UTF-8 character, not advancing the pointer, incrementing length
if there are extra bytes. This is called when we know we are in UTF-8 mode. */
static inline void getUTF8CharAndIncrementLength(int& c, const unsigned char* subjectPtr, int& len)
{
c = *subjectPtr;
if ((c & 0xc0) == 0xc0) {
int gcaa = jsc_pcre_utf8_table4[c & 0x3f]; /* Number of additional bytes */
int gcss = 6 * gcaa;
c = (c & jsc_pcre_utf8_table3[gcaa]) << gcss;
for (int gcii = 1; gcii <= gcaa; gcii++) {
gcss -= 6;
c |= (subjectPtr[gcii] & 0x3f) << gcss;
}
len += gcaa;
}
}
static inline void startNewGroup(MatchFrame* currentFrame)
{
/* At the start of a bracketed group, add the current subject pointer to the
stack of such pointers, to be re-instated at the end of the group when we hit
the closing ket. When match() is called in other circumstances, we don't add to
this stack. */
currentFrame->locals.bracketChainNode.previousBracket = currentFrame->args.bracketChain;
currentFrame->locals.bracketChainNode.bracketStart = currentFrame->args.subjectPtr;
currentFrame->args.bracketChain = ¤tFrame->locals.bracketChainNode;
}
// FIXME: "minimize" means "not greedy", we should invert the callers to ask for "greedy" to be less confusing
static inline void repeatInformationFromInstructionOffset(short instructionOffset, bool& minimize, int& minimumRepeats, int& maximumRepeats)
{
// Instruction offsets are based off of OP_CRSTAR, OP_STAR, OP_TYPESTAR, OP_NOTSTAR
static const char minimumRepeatsFromInstructionOffset[] = { 0, 0, 1, 1, 0, 0 };
static const int maximumRepeatsFromInstructionOffset[] = { INT_MAX, INT_MAX, INT_MAX, INT_MAX, 1, 1 };
ASSERT(instructionOffset >= 0);
ASSERT(instructionOffset <= (OP_CRMINQUERY - OP_CRSTAR));
minimize = (instructionOffset & 1); // this assumes ordering: Instruction, MinimizeInstruction, Instruction2, MinimizeInstruction2
minimumRepeats = minimumRepeatsFromInstructionOffset[instructionOffset];
maximumRepeats = maximumRepeatsFromInstructionOffset[instructionOffset];
}
static int match(const UChar* subjectPtr, const unsigned char* instructionPtr, int offsetTop, MatchData& md)
{
bool isMatch = false;
int min;
bool minimize = false; /* Initialization not really needed, but some compilers think so. */
unsigned remainingMatchCount = matchLimit;
int othercase; /* Declare here to avoid errors during jumps */
MatchStack stack;
/* The opcode jump table. */
#ifdef USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
#define EMIT_JUMP_TABLE_ENTRY(opcode) &&LABEL_OP_##opcode,
static void* opcodeJumpTable[256] = { FOR_EACH_OPCODE(EMIT_JUMP_TABLE_ENTRY) };
#undef EMIT_JUMP_TABLE_ENTRY
#endif
/* One-time setup of the opcode jump table. */
#ifdef USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
for (int i = 255; !opcodeJumpTable[i]; i--)
opcodeJumpTable[i] = &&CAPTURING_BRACKET;
#endif
#ifdef USE_COMPUTED_GOTO_FOR_MATCH_RECURSION
// Shark shows this as a hot line
// Using a static const here makes this line disappear, but makes later access hotter (not sure why)
stack.currentFrame->returnLocation = &&RETURN;
#else
stack.currentFrame->returnLocation = 0;
#endif
stack.currentFrame->args.subjectPtr = subjectPtr;
stack.currentFrame->args.instructionPtr = instructionPtr;
stack.currentFrame->args.offsetTop = offsetTop;
stack.currentFrame->args.bracketChain = 0;
startNewGroup(stack.currentFrame);
/* This is where control jumps back to to effect "recursion" */
RECURSE:
if (!--remainingMatchCount)
return matchError(JSRegExpErrorHitLimit, stack);
/* Now start processing the operations. */
#ifndef USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
while (true)
#endif
{
#ifdef USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
#define BEGIN_OPCODE(opcode) LABEL_OP_##opcode
#define NEXT_OPCODE goto *opcodeJumpTable[*stack.currentFrame->args.instructionPtr]
#else
#define BEGIN_OPCODE(opcode) case OP_##opcode
#define NEXT_OPCODE continue
#endif
#ifdef USE_COMPUTED_GOTO_FOR_MATCH_OPCODE_LOOP
NEXT_OPCODE;
#else
switch (*stack.currentFrame->args.instructionPtr)
#endif
{
/* Non-capturing bracket: optimized */
BEGIN_OPCODE(BRA):
NON_CAPTURING_BRACKET:
DPRINTF(("start bracket 0\n"));
do {
RECURSIVE_MATCH_NEW_GROUP(2, stack.currentFrame->args.instructionPtr + 1 + LINK_SIZE, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
stack.currentFrame->args.instructionPtr += getLinkValue(stack.currentFrame->args.instructionPtr + 1);
} while (*stack.currentFrame->args.instructionPtr == OP_ALT);
DPRINTF(("bracket 0 failed\n"));
RRETURN;
/* Skip over large extraction number data if encountered. */
BEGIN_OPCODE(BRANUMBER):
stack.currentFrame->args.instructionPtr += 3;
NEXT_OPCODE;
/* End of the pattern. */
BEGIN_OPCODE(END):
md.endMatchPtr = stack.currentFrame->args.subjectPtr; /* Record where we ended */
md.endOffsetTop = stack.currentFrame->args.offsetTop; /* and how many extracts were taken */
isMatch = true;
RRETURN;
/* Assertion brackets. Check the alternative branches in turn - the
matching won't pass the KET for an assertion. If any one branch matches,
the assertion is true. Lookbehind assertions have an OP_REVERSE item at the
start of each branch to move the current point backwards, so the code at
this level is identical to the lookahead case. */
BEGIN_OPCODE(ASSERT):
do {
RECURSIVE_MATCH_NEW_GROUP(6, stack.currentFrame->args.instructionPtr + 1 + LINK_SIZE, NULL);
if (isMatch)
break;
stack.currentFrame->args.instructionPtr += getLinkValue(stack.currentFrame->args.instructionPtr + 1);
} while (*stack.currentFrame->args.instructionPtr == OP_ALT);
if (*stack.currentFrame->args.instructionPtr == OP_KET)
RRETURN_NO_MATCH;
/* Continue from after the assertion, updating the offsets high water
mark, since extracts may have been taken during the assertion. */
advanceToEndOfBracket(stack.currentFrame->args.instructionPtr);
stack.currentFrame->args.instructionPtr += 1 + LINK_SIZE;
stack.currentFrame->args.offsetTop = md.endOffsetTop;
NEXT_OPCODE;
/* Negative assertion: all branches must fail to match */
BEGIN_OPCODE(ASSERT_NOT):
do {
RECURSIVE_MATCH_NEW_GROUP(7, stack.currentFrame->args.instructionPtr + 1 + LINK_SIZE, NULL);
if (isMatch)
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr += getLinkValue(stack.currentFrame->args.instructionPtr + 1);
} while (*stack.currentFrame->args.instructionPtr == OP_ALT);
stack.currentFrame->args.instructionPtr += 1 + LINK_SIZE;
NEXT_OPCODE;
/* An alternation is the end of a branch; scan along to find the end of the
bracketed group and go to there. */
BEGIN_OPCODE(ALT):
advanceToEndOfBracket(stack.currentFrame->args.instructionPtr);
NEXT_OPCODE;
/* BRAZERO and BRAMINZERO occur just before a bracket group, indicating
that it may occur zero times. It may repeat infinitely, or not at all -
i.e. it could be ()* or ()? in the pattern. Brackets with fixed upper
repeat limits are compiled as a number of copies, with the optional ones
preceded by BRAZERO or BRAMINZERO. */
BEGIN_OPCODE(BRAZERO): {
stack.currentFrame->locals.startOfRepeatingBracket = stack.currentFrame->args.instructionPtr + 1;
RECURSIVE_MATCH_NEW_GROUP(14, stack.currentFrame->locals.startOfRepeatingBracket, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
advanceToEndOfBracket(stack.currentFrame->locals.startOfRepeatingBracket);
stack.currentFrame->args.instructionPtr = stack.currentFrame->locals.startOfRepeatingBracket + 1 + LINK_SIZE;
NEXT_OPCODE;
}
BEGIN_OPCODE(BRAMINZERO): {
stack.currentFrame->locals.startOfRepeatingBracket = stack.currentFrame->args.instructionPtr + 1;
advanceToEndOfBracket(stack.currentFrame->locals.startOfRepeatingBracket);
RECURSIVE_MATCH_NEW_GROUP(15, stack.currentFrame->locals.startOfRepeatingBracket + 1 + LINK_SIZE, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
}
/* End of a group, repeated or non-repeating. If we are at the end of
an assertion "group", stop matching and return 1, but record the
current high water mark for use by positive assertions. Do this also
for the "once" (not-backup up) groups. */
BEGIN_OPCODE(KET):
BEGIN_OPCODE(KETRMIN):
BEGIN_OPCODE(KETRMAX):
stack.currentFrame->locals.instructionPtrAtStartOfOnce = stack.currentFrame->args.instructionPtr - getLinkValue(stack.currentFrame->args.instructionPtr + 1);
stack.currentFrame->locals.subjectPtrAtStartOfInstruction = stack.currentFrame->args.bracketChain->bracketStart;
/* Back up the stack of bracket start pointers. */
stack.currentFrame->args.bracketChain = stack.currentFrame->args.bracketChain->previousBracket;
if (*stack.currentFrame->locals.instructionPtrAtStartOfOnce == OP_ASSERT || *stack.currentFrame->locals.instructionPtrAtStartOfOnce == OP_ASSERT_NOT) {
md.endOffsetTop = stack.currentFrame->args.offsetTop;
isMatch = true;
RRETURN;
}
/* In all other cases except a conditional group we have to check the
group number back at the start and if necessary complete handling an
extraction by setting the offsets and bumping the high water mark. */
stack.currentFrame->locals.number = *stack.currentFrame->locals.instructionPtrAtStartOfOnce - OP_BRA;
/* For extended extraction brackets (large number), we have to fish out
the number from a dummy opcode at the start. */
if (stack.currentFrame->locals.number > EXTRACT_BASIC_MAX)
stack.currentFrame->locals.number = get2ByteValue(stack.currentFrame->locals.instructionPtrAtStartOfOnce + 2 + LINK_SIZE);
stack.currentFrame->locals.offset = stack.currentFrame->locals.number << 1;
#ifdef DEBUG
printf("end bracket %d", stack.currentFrame->locals.number);
printf("\n");
#endif
/* Test for a numbered group. This includes groups called as a result
of recursion. Note that whole-pattern recursion is coded as a recurse
into group 0, so it won't be picked up here. Instead, we catch it when
the OP_END is reached. */
if (stack.currentFrame->locals.number > 0) {
if (stack.currentFrame->locals.offset >= md.offsetMax)
md.offsetOverflow = true;
else {
md.offsetVector[stack.currentFrame->locals.offset] =
md.offsetVector[md.offsetEnd - stack.currentFrame->locals.number];
md.offsetVector[stack.currentFrame->locals.offset+1] = stack.currentFrame->args.subjectPtr - md.startSubject;
if (stack.currentFrame->args.offsetTop <= stack.currentFrame->locals.offset)
stack.currentFrame->args.offsetTop = stack.currentFrame->locals.offset + 2;
}
}
/* For a non-repeating ket, just continue at this level. This also
happens for a repeating ket if no characters were matched in the group.
This is the forcible breaking of infinite loops as implemented in Perl
5.005. If there is an options reset, it will get obeyed in the normal
course of events. */
if (*stack.currentFrame->args.instructionPtr == OP_KET || stack.currentFrame->args.subjectPtr == stack.currentFrame->locals.subjectPtrAtStartOfInstruction) {
stack.currentFrame->args.instructionPtr += 1 + LINK_SIZE;
NEXT_OPCODE;
}
/* The repeating kets try the rest of the pattern or restart from the
preceding bracket, in the appropriate order. */
if (*stack.currentFrame->args.instructionPtr == OP_KETRMIN) {
RECURSIVE_MATCH(16, stack.currentFrame->args.instructionPtr + 1 + LINK_SIZE, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
RECURSIVE_MATCH_NEW_GROUP(17, stack.currentFrame->locals.instructionPtrAtStartOfOnce, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
} else { /* OP_KETRMAX */
RECURSIVE_MATCH_NEW_GROUP(18, stack.currentFrame->locals.instructionPtrAtStartOfOnce, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
RECURSIVE_MATCH(19, stack.currentFrame->args.instructionPtr + 1 + LINK_SIZE, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
}
RRETURN;
/* Start of subject. */
BEGIN_OPCODE(CIRC):
if (stack.currentFrame->args.subjectPtr != md.startSubject)
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
/* After internal newline if multiline. */
BEGIN_OPCODE(BOL):
if (stack.currentFrame->args.subjectPtr != md.startSubject && !isNewline(stack.currentFrame->args.subjectPtr[-1]))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
/* End of subject. */
BEGIN_OPCODE(DOLL):
if (stack.currentFrame->args.subjectPtr < md.endSubject)
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
/* Before internal newline if multiline. */
BEGIN_OPCODE(EOL):
if (stack.currentFrame->args.subjectPtr < md.endSubject && !isNewline(*stack.currentFrame->args.subjectPtr))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
/* Word boundary assertions */
BEGIN_OPCODE(NOT_WORD_BOUNDARY):
BEGIN_OPCODE(WORD_BOUNDARY): {
bool currentCharIsWordChar = false;
bool previousCharIsWordChar = false;
if (stack.currentFrame->args.subjectPtr > md.startSubject)
previousCharIsWordChar = isWordChar(stack.currentFrame->args.subjectPtr[-1]);
if (stack.currentFrame->args.subjectPtr < md.endSubject)
currentCharIsWordChar = isWordChar(*stack.currentFrame->args.subjectPtr);
/* Now see if the situation is what we want */
bool wordBoundaryDesired = (*stack.currentFrame->args.instructionPtr++ == OP_WORD_BOUNDARY);
if (wordBoundaryDesired ? currentCharIsWordChar == previousCharIsWordChar : currentCharIsWordChar != previousCharIsWordChar)
RRETURN_NO_MATCH;
NEXT_OPCODE;
}
/* Match a single character type; inline for speed */
BEGIN_OPCODE(NOT_NEWLINE):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (isNewline(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(NOT_DIGIT):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (isASCIIDigit(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(DIGIT):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (!isASCIIDigit(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(NOT_WHITESPACE):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (isSpaceChar(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(WHITESPACE):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (!isSpaceChar(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(NOT_WORDCHAR):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (isWordChar(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
BEGIN_OPCODE(WORDCHAR):
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
if (!isWordChar(*stack.currentFrame->args.subjectPtr++))
RRETURN_NO_MATCH;
stack.currentFrame->args.instructionPtr++;
NEXT_OPCODE;
/* Match a back reference, possibly repeatedly. Look past the end of the
item to see if there is repeat information following. The code is similar
to that for character classes, but repeated for efficiency. Then obey
similar code to character type repeats - written out again for speed.
However, if the referenced string is the empty string, always treat
it as matched, any number of times (otherwise there could be infinite
loops). */
BEGIN_OPCODE(REF):
stack.currentFrame->locals.offset = get2ByteValue(stack.currentFrame->args.instructionPtr + 1) << 1; /* Doubled ref number */
stack.currentFrame->args.instructionPtr += 3; /* Advance past item */
/* If the reference is unset, set the length to be longer than the amount
of subject left; this ensures that every attempt at a match fails. We
can't just fail here, because of the possibility of quantifiers with zero
minima. */
if (stack.currentFrame->locals.offset >= stack.currentFrame->args.offsetTop || md.offsetVector[stack.currentFrame->locals.offset] < 0)
stack.currentFrame->locals.length = 0;
else
stack.currentFrame->locals.length = md.offsetVector[stack.currentFrame->locals.offset+1] - md.offsetVector[stack.currentFrame->locals.offset];
/* Set up for repetition, or handle the non-repeated case */
switch (*stack.currentFrame->args.instructionPtr) {
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRQUERY:
case OP_CRMINQUERY:
repeatInformationFromInstructionOffset(*stack.currentFrame->args.instructionPtr++ - OP_CRSTAR, minimize, min, stack.currentFrame->locals.max);
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
minimize = (*stack.currentFrame->args.instructionPtr == OP_CRMINRANGE);
min = get2ByteValue(stack.currentFrame->args.instructionPtr + 1);
stack.currentFrame->locals.max = get2ByteValue(stack.currentFrame->args.instructionPtr + 3);
if (stack.currentFrame->locals.max == 0)
stack.currentFrame->locals.max = INT_MAX;
stack.currentFrame->args.instructionPtr += 5;
break;
default: /* No repeat follows */
if (!matchRef(stack.currentFrame->locals.offset, stack.currentFrame->args.subjectPtr, stack.currentFrame->locals.length, md))
RRETURN_NO_MATCH;
stack.currentFrame->args.subjectPtr += stack.currentFrame->locals.length;
NEXT_OPCODE;
}
/* If the length of the reference is zero, just continue with the
main loop. */
if (stack.currentFrame->locals.length == 0)
NEXT_OPCODE;
/* First, ensure the minimum number of matches are present. */
for (int i = 1; i <= min; i++) {
if (!matchRef(stack.currentFrame->locals.offset, stack.currentFrame->args.subjectPtr, stack.currentFrame->locals.length, md))
RRETURN_NO_MATCH;
stack.currentFrame->args.subjectPtr += stack.currentFrame->locals.length;
}
/* If min = max, continue at the same level without recursion.
They are not both allowed to be zero. */
if (min == stack.currentFrame->locals.max)
NEXT_OPCODE;
/* If minimizing, keep trying and advancing the pointer */
if (minimize) {
for (stack.currentFrame->locals.fi = min;; stack.currentFrame->locals.fi++) {
RECURSIVE_MATCH(20, stack.currentFrame->args.instructionPtr, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
if (stack.currentFrame->locals.fi >= stack.currentFrame->locals.max || !matchRef(stack.currentFrame->locals.offset, stack.currentFrame->args.subjectPtr, stack.currentFrame->locals.length, md))
RRETURN;
stack.currentFrame->args.subjectPtr += stack.currentFrame->locals.length;
}
/* Control never reaches here */
}
/* If maximizing, find the longest string and work backwards */
else {
stack.currentFrame->locals.subjectPtrAtStartOfInstruction = stack.currentFrame->args.subjectPtr;
for (int i = min; i < stack.currentFrame->locals.max; i++) {
if (!matchRef(stack.currentFrame->locals.offset, stack.currentFrame->args.subjectPtr, stack.currentFrame->locals.length, md))
break;
stack.currentFrame->args.subjectPtr += stack.currentFrame->locals.length;
}
while (stack.currentFrame->args.subjectPtr >= stack.currentFrame->locals.subjectPtrAtStartOfInstruction) {
RECURSIVE_MATCH(21, stack.currentFrame->args.instructionPtr, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
stack.currentFrame->args.subjectPtr -= stack.currentFrame->locals.length;
}
RRETURN_NO_MATCH;
}
/* Control never reaches here */
/* Match a bit-mapped character class, possibly repeatedly. This op code is
used when all the characters in the class have values in the range 0-255,
and either the matching is caseful, or the characters are in the range
0-127 when UTF-8 processing is enabled. The only difference between
OP_CLASS and OP_NCLASS occurs when a data character outside the range is
encountered.
First, look past the end of the item to see if there is repeat information
following. Then obey similar code to character type repeats - written out
again for speed. */
BEGIN_OPCODE(NCLASS):
BEGIN_OPCODE(CLASS):
stack.currentFrame->locals.data = stack.currentFrame->args.instructionPtr + 1; /* Save for matching */
stack.currentFrame->args.instructionPtr += 33; /* Advance past the item */
switch (*stack.currentFrame->args.instructionPtr) {
case OP_CRSTAR:
case OP_CRMINSTAR:
case OP_CRPLUS:
case OP_CRMINPLUS:
case OP_CRQUERY:
case OP_CRMINQUERY:
repeatInformationFromInstructionOffset(*stack.currentFrame->args.instructionPtr++ - OP_CRSTAR, minimize, min, stack.currentFrame->locals.max);
break;
case OP_CRRANGE:
case OP_CRMINRANGE:
minimize = (*stack.currentFrame->args.instructionPtr == OP_CRMINRANGE);
min = get2ByteValue(stack.currentFrame->args.instructionPtr + 1);
stack.currentFrame->locals.max = get2ByteValue(stack.currentFrame->args.instructionPtr + 3);
if (stack.currentFrame->locals.max == 0)
stack.currentFrame->locals.max = INT_MAX;
stack.currentFrame->args.instructionPtr += 5;
break;
default: /* No repeat follows */
min = stack.currentFrame->locals.max = 1;
break;
}
/* First, ensure the minimum number of matches are present. */
for (int i = 1; i <= min; i++) {
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN_NO_MATCH;
int c = *stack.currentFrame->args.subjectPtr++;
if (c > 255) {
if (stack.currentFrame->locals.data[-1] == OP_CLASS)
RRETURN_NO_MATCH;
} else {
if (!(stack.currentFrame->locals.data[c / 8] & (1 << (c & 7))))
RRETURN_NO_MATCH;
}
}
/* If max == min we can continue with the main loop without the
need to recurse. */
if (min == stack.currentFrame->locals.max)
NEXT_OPCODE;
/* If minimizing, keep testing the rest of the expression and advancing
the pointer while it matches the class. */
if (minimize) {
for (stack.currentFrame->locals.fi = min;; stack.currentFrame->locals.fi++) {
RECURSIVE_MATCH(22, stack.currentFrame->args.instructionPtr, stack.currentFrame->args.bracketChain);
if (isMatch)
RRETURN;
if (stack.currentFrame->locals.fi >= stack.currentFrame->locals.max || stack.currentFrame->args.subjectPtr >= md.endSubject)
RRETURN;
int c = *stack.currentFrame->args.subjectPtr++;
if (c > 255) {
if (stack.currentFrame->locals.data[-1] == OP_CLASS)
RRETURN;
} else {
if ((stack.currentFrame->locals.data[c/8] & (1 << (c&7))) == 0)
RRETURN;
}
}
/* Control never reaches here */
}
/* If maximizing, find the longest possible run, then work backwards. */
else {
stack.currentFrame->locals.subjectPtrAtStartOfInstruction = stack.currentFrame->args.subjectPtr;
for (int i = min; i < stack.currentFrame->locals.max; i++) {
if (stack.currentFrame->args.subjectPtr >= md.endSubject)
break;
int c = *stack.currentFrame->args.subjectPtr;
if (c > 255) {
if (stack.currentFrame->locals.data[-1] == OP_CLASS)
break;
} else {
if (!(stack.currentFrame->locals.data[c / 8] & (1 << (c & 7))))
break;