1 // Copyright 2008 The RE2 Authors. All Rights Reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // A DFA (deterministic finite automaton)-based regular expression search.
6 //
7 // The DFA search has two main parts: the construction of the automaton,
8 // which is represented by a graph of State structures, and the execution
9 // of the automaton over a given input string.
10 //
11 // The basic idea is that the State graph is constructed so that the
12 // execution can simply start with a state s, and then for each byte c in
13 // the input string, execute "s = s->next[c]", checking at each point whether
14 // the current s represents a matching state.
15 //
16 // The simple explanation just given does convey the essence of this code,
17 // but it omits the details of how the State graph gets constructed as well
18 // as some performance-driven optimizations to the execution of the automaton.
19 // All these details are explained in the comments for the code following
20 // the definition of class DFA.
21 //
22 // See http://swtch.com/~rsc/regexp/ for a very bare-bones equivalent.
23
24 #include <stddef.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <algorithm>
29 #include <atomic>
30 #include <deque>
31 #include <mutex>
32 #include <new>
33 #include <string>
34 #include <unordered_map>
35 #include <unordered_set>
36 #include <utility>
37 #include <vector>
38
39 #include "util/logging.h"
40 #include "util/mix.h"
41 #include "util/mutex.h"
42 #include "util/pod_array.h"
43 #include "util/sparse_set.h"
44 #include "util/strutil.h"
45 #include "re2/prog.h"
46 #include "re2/stringpiece.h"
47
48 // Silence "zero-sized array in struct/union" warning for DFA::State::next_.
49 #ifdef _MSC_VER
50 #pragma warning(disable: 4200)
51 #endif
52
53 namespace re2 {
54
55 #if !defined(__linux__) /* only Linux seems to have memrchr */
memrchr(const void * s,int c,size_t n)56 static void* memrchr(const void* s, int c, size_t n) {
57 const unsigned char* p = (const unsigned char*)s;
58 for (p += n; n > 0; n--)
59 if (*--p == c)
60 return (void*)p;
61
62 return NULL;
63 }
64 #endif
65
66 // Controls whether the DFA should bail out early if the NFA would be faster.
67 static bool dfa_should_bail_when_slow = true;
68
69 // Changing this to true compiles in prints that trace execution of the DFA.
70 // Generates a lot of output -- only useful for debugging.
71 static const bool ExtraDebug = false;
72
73 // A DFA implementation of a regular expression program.
74 // Since this is entirely a forward declaration mandated by C++,
75 // some of the comments here are better understood after reading
76 // the comments in the sections that follow the DFA definition.
77 class DFA {
78 public:
79 DFA(Prog* prog, Prog::MatchKind kind, int64_t max_mem);
80 ~DFA();
ok() const81 bool ok() const { return !init_failed_; }
kind()82 Prog::MatchKind kind() { return kind_; }
83
84 // Searches for the regular expression in text, which is considered
85 // as a subsection of context for the purposes of interpreting flags
86 // like ^ and $ and \A and \z.
87 // Returns whether a match was found.
88 // If a match is found, sets *ep to the end point of the best match in text.
89 // If "anchored", the match must begin at the start of text.
90 // If "want_earliest_match", the match that ends first is used, not
91 // necessarily the best one.
92 // If "run_forward" is true, the DFA runs from text.begin() to text.end().
93 // If it is false, the DFA runs from text.end() to text.begin(),
94 // returning the leftmost end of the match instead of the rightmost one.
95 // If the DFA cannot complete the search (for example, if it is out of
96 // memory), it sets *failed and returns false.
97 bool Search(const StringPiece& text, const StringPiece& context,
98 bool anchored, bool want_earliest_match, bool run_forward,
99 bool* failed, const char** ep, SparseSet* matches);
100
101 // Builds out all states for the entire DFA.
102 // If cb is not empty, it receives one callback per state built.
103 // Returns the number of states built.
104 // FOR TESTING OR EXPERIMENTAL PURPOSES ONLY.
105 int BuildAllStates(const Prog::DFAStateCallback& cb);
106
107 // Computes min and max for matching strings. Won't return strings
108 // bigger than maxlen.
109 bool PossibleMatchRange(string* min, string* max, int maxlen);
110
111 // These data structures are logically private, but C++ makes it too
112 // difficult to mark them as such.
113 class RWLocker;
114 class StateSaver;
115 class Workq;
116
117 // A single DFA state. The DFA is represented as a graph of these
118 // States, linked by the next_ pointers. If in state s and reading
119 // byte c, the next state should be s->next_[c].
120 struct State {
IsMatchre2::DFA::State121 inline bool IsMatch() const { return (flag_ & kFlagMatch) != 0; }
122 void SaveMatch(std::vector<int>* v);
123
124 int* inst_; // Instruction pointers in the state.
125 int ninst_; // # of inst_ pointers.
126 uint32_t flag_; // Empty string bitfield flags in effect on the way
127 // into this state, along with kFlagMatch if this
128 // is a matching state.
129
130 // Work around the bug affecting flexible array members in GCC 6.x (for x >= 1).
131 // (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70932)
132 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ == 6 && __GNUC_MINOR__ >= 1
133 std::atomic<State*> next_[0]; // Outgoing arrows from State,
134 #else
135 std::atomic<State*> next_[]; // Outgoing arrows from State,
136 #endif
137
138 // one per input byte class
139 };
140
141 enum {
142 kByteEndText = 256, // imaginary byte at end of text
143
144 kFlagEmptyMask = 0xFF, // State.flag_: bits holding kEmptyXXX flags
145 kFlagMatch = 0x0100, // State.flag_: this is a matching state
146 kFlagLastWord = 0x0200, // State.flag_: last byte was a word char
147 kFlagNeedShift = 16, // needed kEmpty bits are or'ed in shifted left
148 };
149
150 struct StateHash {
operator ()re2::DFA::StateHash151 size_t operator()(const State* a) const {
152 DCHECK(a != NULL);
153 HashMix mix(a->flag_);
154 for (int i = 0; i < a->ninst_; i++)
155 mix.Mix(a->inst_[i]);
156 mix.Mix(0);
157 return mix.get();
158 }
159 };
160
161 struct StateEqual {
operator ()re2::DFA::StateEqual162 bool operator()(const State* a, const State* b) const {
163 DCHECK(a != NULL);
164 DCHECK(b != NULL);
165 if (a == b)
166 return true;
167 if (a->flag_ != b->flag_)
168 return false;
169 if (a->ninst_ != b->ninst_)
170 return false;
171 for (int i = 0; i < a->ninst_; i++)
172 if (a->inst_[i] != b->inst_[i])
173 return false;
174 return true;
175 }
176 };
177
178 typedef std::unordered_set<State*, StateHash, StateEqual> StateSet;
179
180 private:
181 // Special "first_byte" values for a state. (Values >= 0 denote actual bytes.)
182 enum {
183 kFbUnknown = -1, // No analysis has been performed.
184 kFbNone = -2, // The first-byte trick cannot be used.
185 };
186
187 enum {
188 // Indices into start_ for unanchored searches.
189 // Add kStartAnchored for anchored searches.
190 kStartBeginText = 0, // text at beginning of context
191 kStartBeginLine = 2, // text at beginning of line
192 kStartAfterWordChar = 4, // text follows a word character
193 kStartAfterNonWordChar = 6, // text follows non-word character
194 kMaxStart = 8,
195
196 kStartAnchored = 1,
197 };
198
199 // Resets the DFA State cache, flushing all saved State* information.
200 // Releases and reacquires cache_mutex_ via cache_lock, so any
201 // State* existing before the call are not valid after the call.
202 // Use a StateSaver to preserve important states across the call.
203 // cache_mutex_.r <= L < mutex_
204 // After: cache_mutex_.w <= L < mutex_
205 void ResetCache(RWLocker* cache_lock);
206
207 // Looks up and returns the State corresponding to a Workq.
208 // L >= mutex_
209 State* WorkqToCachedState(Workq* q, Workq* mq, uint32_t flag);
210
211 // Looks up and returns a State matching the inst, ninst, and flag.
212 // L >= mutex_
213 State* CachedState(int* inst, int ninst, uint32_t flag);
214
215 // Clear the cache entirely.
216 // Must hold cache_mutex_.w or be in destructor.
217 void ClearCache();
218
219 // Converts a State into a Workq: the opposite of WorkqToCachedState.
220 // L >= mutex_
221 void StateToWorkq(State* s, Workq* q);
222
223 // Runs a State on a given byte, returning the next state.
224 State* RunStateOnByteUnlocked(State*, int); // cache_mutex_.r <= L < mutex_
225 State* RunStateOnByte(State*, int); // L >= mutex_
226
227 // Runs a Workq on a given byte followed by a set of empty-string flags,
228 // producing a new Workq in nq. If a match instruction is encountered,
229 // sets *ismatch to true.
230 // L >= mutex_
231 void RunWorkqOnByte(Workq* q, Workq* nq,
232 int c, uint32_t flag, bool* ismatch);
233
234 // Runs a Workq on a set of empty-string flags, producing a new Workq in nq.
235 // L >= mutex_
236 void RunWorkqOnEmptyString(Workq* q, Workq* nq, uint32_t flag);
237
238 // Adds the instruction id to the Workq, following empty arrows
239 // according to flag.
240 // L >= mutex_
241 void AddToQueue(Workq* q, int id, uint32_t flag);
242
243 // For debugging, returns a text representation of State.
244 static string DumpState(State* state);
245
246 // For debugging, returns a text representation of a Workq.
247 static string DumpWorkq(Workq* q);
248
249 // Search parameters
250 struct SearchParams {
SearchParamsre2::DFA::SearchParams251 SearchParams(const StringPiece& text, const StringPiece& context,
252 RWLocker* cache_lock)
253 : text(text), context(context),
254 anchored(false),
255 want_earliest_match(false),
256 run_forward(false),
257 start(NULL),
258 first_byte(kFbUnknown),
259 cache_lock(cache_lock),
260 failed(false),
261 ep(NULL),
262 matches(NULL) { }
263
264 StringPiece text;
265 StringPiece context;
266 bool anchored;
267 bool want_earliest_match;
268 bool run_forward;
269 State* start;
270 int first_byte;
271 RWLocker *cache_lock;
272 bool failed; // "out" parameter: whether search gave up
273 const char* ep; // "out" parameter: end pointer for match
274 SparseSet* matches;
275
276 private:
277 SearchParams(const SearchParams&) = delete;
278 SearchParams& operator=(const SearchParams&) = delete;
279 };
280
281 // Before each search, the parameters to Search are analyzed by
282 // AnalyzeSearch to determine the state in which to start and the
283 // "first_byte" for that state, if any.
284 struct StartInfo {
StartInfore2::DFA::StartInfo285 StartInfo() : start(NULL), first_byte(kFbUnknown) {}
286 State* start;
287 std::atomic<int> first_byte;
288 };
289
290 // Fills in params->start and params->first_byte using
291 // the other search parameters. Returns true on success,
292 // false on failure.
293 // cache_mutex_.r <= L < mutex_
294 bool AnalyzeSearch(SearchParams* params);
295 bool AnalyzeSearchHelper(SearchParams* params, StartInfo* info,
296 uint32_t flags);
297
298 // The generic search loop, inlined to create specialized versions.
299 // cache_mutex_.r <= L < mutex_
300 // Might unlock and relock cache_mutex_ via params->cache_lock.
301 inline bool InlinedSearchLoop(SearchParams* params,
302 bool have_first_byte,
303 bool want_earliest_match,
304 bool run_forward);
305
306 // The specialized versions of InlinedSearchLoop. The three letters
307 // at the ends of the name denote the true/false values used as the
308 // last three parameters of InlinedSearchLoop.
309 // cache_mutex_.r <= L < mutex_
310 // Might unlock and relock cache_mutex_ via params->cache_lock.
311 bool SearchFFF(SearchParams* params);
312 bool SearchFFT(SearchParams* params);
313 bool SearchFTF(SearchParams* params);
314 bool SearchFTT(SearchParams* params);
315 bool SearchTFF(SearchParams* params);
316 bool SearchTFT(SearchParams* params);
317 bool SearchTTF(SearchParams* params);
318 bool SearchTTT(SearchParams* params);
319
320 // The main search loop: calls an appropriate specialized version of
321 // InlinedSearchLoop.
322 // cache_mutex_.r <= L < mutex_
323 // Might unlock and relock cache_mutex_ via params->cache_lock.
324 bool FastSearchLoop(SearchParams* params);
325
326 // For debugging, a slow search loop that calls InlinedSearchLoop
327 // directly -- because the booleans passed are not constants, the
328 // loop is not specialized like the SearchFFF etc. versions, so it
329 // runs much more slowly. Useful only for debugging.
330 // cache_mutex_.r <= L < mutex_
331 // Might unlock and relock cache_mutex_ via params->cache_lock.
332 bool SlowSearchLoop(SearchParams* params);
333
334 // Looks up bytes in bytemap_ but handles case c == kByteEndText too.
ByteMap(int c)335 int ByteMap(int c) {
336 if (c == kByteEndText)
337 return prog_->bytemap_range();
338 return prog_->bytemap()[c];
339 }
340
341 // Constant after initialization.
342 Prog* prog_; // The regular expression program to run.
343 Prog::MatchKind kind_; // The kind of DFA.
344 bool init_failed_; // initialization failed (out of memory)
345
346 Mutex mutex_; // mutex_ >= cache_mutex_.r
347
348 // Scratch areas, protected by mutex_.
349 Workq* q0_; // Two pre-allocated work queues.
350 Workq* q1_;
351 PODArray<int> stack_; // Pre-allocated stack for AddToQueue
352
353 // State* cache. Many threads use and add to the cache simultaneously,
354 // holding cache_mutex_ for reading and mutex_ (above) when adding.
355 // If the cache fills and needs to be discarded, the discarding is done
356 // while holding cache_mutex_ for writing, to avoid interrupting other
357 // readers. Any State* pointers are only valid while cache_mutex_
358 // is held.
359 Mutex cache_mutex_;
360 int64_t mem_budget_; // Total memory budget for all States.
361 int64_t state_budget_; // Amount of memory remaining for new States.
362 StateSet state_cache_; // All States computed so far.
363 StartInfo start_[kMaxStart];
364 };
365
366 // Shorthand for casting to uint8_t*.
BytePtr(const void * v)367 static inline const uint8_t* BytePtr(const void* v) {
368 return reinterpret_cast<const uint8_t*>(v);
369 }
370
371 // Work queues
372
373 // Marks separate thread groups of different priority
374 // in the work queue when in leftmost-longest matching mode.
375 #define Mark (-1)
376
377 // Separates the match IDs from the instructions in inst_.
378 // Used only for "many match" DFA states.
379 #define MatchSep (-2)
380
381 // Internally, the DFA uses a sparse array of
382 // program instruction pointers as a work queue.
383 // In leftmost longest mode, marks separate sections
384 // of workq that started executing at different
385 // locations in the string (earlier locations first).
386 class DFA::Workq : public SparseSet {
387 public:
388 // Constructor: n is number of normal slots, maxmark number of mark slots.
Workq(int n,int maxmark)389 Workq(int n, int maxmark) :
390 SparseSet(n+maxmark),
391 n_(n),
392 maxmark_(maxmark),
393 nextmark_(n),
394 last_was_mark_(true) {
395 }
396
is_mark(int i)397 bool is_mark(int i) { return i >= n_; }
398
maxmark()399 int maxmark() { return maxmark_; }
400
clear()401 void clear() {
402 SparseSet::clear();
403 nextmark_ = n_;
404 }
405
mark()406 void mark() {
407 if (last_was_mark_)
408 return;
409 last_was_mark_ = false;
410 SparseSet::insert_new(nextmark_++);
411 }
412
size()413 int size() {
414 return n_ + maxmark_;
415 }
416
insert(int id)417 void insert(int id) {
418 if (contains(id))
419 return;
420 insert_new(id);
421 }
422
insert_new(int id)423 void insert_new(int id) {
424 last_was_mark_ = false;
425 SparseSet::insert_new(id);
426 }
427
428 private:
429 int n_; // size excluding marks
430 int maxmark_; // maximum number of marks
431 int nextmark_; // id of next mark
432 bool last_was_mark_; // last inserted was mark
433
434 Workq(const Workq&) = delete;
435 Workq& operator=(const Workq&) = delete;
436 };
437
DFA(Prog * prog,Prog::MatchKind kind,int64_t max_mem)438 DFA::DFA(Prog* prog, Prog::MatchKind kind, int64_t max_mem)
439 : prog_(prog),
440 kind_(kind),
441 init_failed_(false),
442 q0_(NULL),
443 q1_(NULL),
444 mem_budget_(max_mem) {
445 if (ExtraDebug)
446 fprintf(stderr, "\nkind %d\n%s\n", (int)kind_, prog_->DumpUnanchored().c_str());
447 int nmark = 0;
448 if (kind_ == Prog::kLongestMatch)
449 nmark = prog_->size();
450 // See DFA::AddToQueue() for why this is so.
451 int nstack = prog_->inst_count(kInstCapture) +
452 prog_->inst_count(kInstEmptyWidth) +
453 prog_->inst_count(kInstNop) +
454 nmark + 1; // + 1 for start inst
455
456 // Account for space needed for DFA, q0, q1, stack.
457 mem_budget_ -= sizeof(DFA);
458 mem_budget_ -= (prog_->size() + nmark) *
459 (sizeof(int)+sizeof(int)) * 2; // q0, q1
460 mem_budget_ -= nstack * sizeof(int); // stack
461 if (mem_budget_ < 0) {
462 init_failed_ = true;
463 return;
464 }
465
466 state_budget_ = mem_budget_;
467
468 // Make sure there is a reasonable amount of working room left.
469 // At minimum, the search requires room for two states in order
470 // to limp along, restarting frequently. We'll get better performance
471 // if there is room for a larger number of states, say 20.
472 // Note that a state stores list heads only, so we use the program
473 // list count for the upper bound, not the program size.
474 int nnext = prog_->bytemap_range() + 1; // + 1 for kByteEndText slot
475 int64_t one_state = sizeof(State) + nnext*sizeof(std::atomic<State*>) +
476 (prog_->list_count()+nmark)*sizeof(int);
477 if (state_budget_ < 20*one_state) {
478 init_failed_ = true;
479 return;
480 }
481
482 q0_ = new Workq(prog_->size(), nmark);
483 q1_ = new Workq(prog_->size(), nmark);
484 stack_ = PODArray<int>(nstack);
485 }
486
~DFA()487 DFA::~DFA() {
488 delete q0_;
489 delete q1_;
490 ClearCache();
491 }
492
493 // In the DFA state graph, s->next[c] == NULL means that the
494 // state has not yet been computed and needs to be. We need
495 // a different special value to signal that s->next[c] is a
496 // state that can never lead to a match (and thus the search
497 // can be called off). Hence DeadState.
498 #define DeadState reinterpret_cast<State*>(1)
499
500 // Signals that the rest of the string matches no matter what it is.
501 #define FullMatchState reinterpret_cast<State*>(2)
502
503 #define SpecialStateMax FullMatchState
504
505 // Debugging printouts
506
507 // For debugging, returns a string representation of the work queue.
DumpWorkq(Workq * q)508 string DFA::DumpWorkq(Workq* q) {
509 string s;
510 const char* sep = "";
511 for (Workq::iterator it = q->begin(); it != q->end(); ++it) {
512 if (q->is_mark(*it)) {
513 StringAppendF(&s, "|");
514 sep = "";
515 } else {
516 StringAppendF(&s, "%s%d", sep, *it);
517 sep = ",";
518 }
519 }
520 return s;
521 }
522
523 // For debugging, returns a string representation of the state.
DumpState(State * state)524 string DFA::DumpState(State* state) {
525 if (state == NULL)
526 return "_";
527 if (state == DeadState)
528 return "X";
529 if (state == FullMatchState)
530 return "*";
531 string s;
532 const char* sep = "";
533 StringAppendF(&s, "(%p)", state);
534 for (int i = 0; i < state->ninst_; i++) {
535 if (state->inst_[i] == Mark) {
536 StringAppendF(&s, "|");
537 sep = "";
538 } else if (state->inst_[i] == MatchSep) {
539 StringAppendF(&s, "||");
540 sep = "";
541 } else {
542 StringAppendF(&s, "%s%d", sep, state->inst_[i]);
543 sep = ",";
544 }
545 }
546 StringAppendF(&s, " flag=%#x", state->flag_);
547 return s;
548 }
549
550 //////////////////////////////////////////////////////////////////////
551 //
552 // DFA state graph construction.
553 //
554 // The DFA state graph is a heavily-linked collection of State* structures.
555 // The state_cache_ is a set of all the State structures ever allocated,
556 // so that if the same state is reached by two different paths,
557 // the same State structure can be used. This reduces allocation
558 // requirements and also avoids duplication of effort across the two
559 // identical states.
560 //
561 // A State is defined by an ordered list of instruction ids and a flag word.
562 //
563 // The choice of an ordered list of instructions differs from a typical
564 // textbook DFA implementation, which would use an unordered set.
565 // Textbook descriptions, however, only care about whether
566 // the DFA matches, not where it matches in the text. To decide where the
567 // DFA matches, we need to mimic the behavior of the dominant backtracking
568 // implementations like PCRE, which try one possible regular expression
569 // execution, then another, then another, stopping when one of them succeeds.
570 // The DFA execution tries these many executions in parallel, representing
571 // each by an instruction id. These pointers are ordered in the State.inst_
572 // list in the same order that the executions would happen in a backtracking
573 // search: if a match is found during execution of inst_[2], inst_[i] for i>=3
574 // can be discarded.
575 //
576 // Textbooks also typically do not consider context-aware empty string operators
577 // like ^ or $. These are handled by the flag word, which specifies the set
578 // of empty-string operators that should be matched when executing at the
579 // current text position. These flag bits are defined in prog.h.
580 // The flag word also contains two DFA-specific bits: kFlagMatch if the state
581 // is a matching state (one that reached a kInstMatch in the program)
582 // and kFlagLastWord if the last processed byte was a word character, for the
583 // implementation of \B and \b.
584 //
585 // The flag word also contains, shifted up 16 bits, the bits looked for by
586 // any kInstEmptyWidth instructions in the state. These provide a useful
587 // summary indicating when new flags might be useful.
588 //
589 // The permanent representation of a State's instruction ids is just an array,
590 // but while a state is being analyzed, these instruction ids are represented
591 // as a Workq, which is an array that allows iteration in insertion order.
592
593 // NOTE(rsc): The choice of State construction determines whether the DFA
594 // mimics backtracking implementations (so-called leftmost first matching) or
595 // traditional DFA implementations (so-called leftmost longest matching as
596 // prescribed by POSIX). This implementation chooses to mimic the
597 // backtracking implementations, because we want to replace PCRE. To get
598 // POSIX behavior, the states would need to be considered not as a simple
599 // ordered list of instruction ids, but as a list of unordered sets of instruction
600 // ids. A match by a state in one set would inhibit the running of sets
601 // farther down the list but not other instruction ids in the same set. Each
602 // set would correspond to matches beginning at a given point in the string.
603 // This is implemented by separating different sets with Mark pointers.
604
605 // Looks in the State cache for a State matching q, flag.
606 // If one is found, returns it. If one is not found, allocates one,
607 // inserts it in the cache, and returns it.
608 // If mq is not null, MatchSep and the match IDs in mq will be appended
609 // to the State.
WorkqToCachedState(Workq * q,Workq * mq,uint32_t flag)610 DFA::State* DFA::WorkqToCachedState(Workq* q, Workq* mq, uint32_t flag) {
611 //mutex_.AssertHeld();
612
613 // Construct array of instruction ids for the new state.
614 // Only ByteRange, EmptyWidth, and Match instructions are useful to keep:
615 // those are the only operators with any effect in
616 // RunWorkqOnEmptyString or RunWorkqOnByte.
617 int* inst = new int[q->size()];
618 int n = 0;
619 uint32_t needflags = 0; // flags needed by kInstEmptyWidth instructions
620 bool sawmatch = false; // whether queue contains guaranteed kInstMatch
621 bool sawmark = false; // whether queue contains a Mark
622 if (ExtraDebug)
623 fprintf(stderr, "WorkqToCachedState %s [%#x]", DumpWorkq(q).c_str(), flag);
624 for (Workq::iterator it = q->begin(); it != q->end(); ++it) {
625 int id = *it;
626 if (sawmatch && (kind_ == Prog::kFirstMatch || q->is_mark(id)))
627 break;
628 if (q->is_mark(id)) {
629 if (n > 0 && inst[n-1] != Mark) {
630 sawmark = true;
631 inst[n++] = Mark;
632 }
633 continue;
634 }
635 Prog::Inst* ip = prog_->inst(id);
636 switch (ip->opcode()) {
637 case kInstAltMatch:
638 // This state will continue to a match no matter what
639 // the rest of the input is. If it is the highest priority match
640 // being considered, return the special FullMatchState
641 // to indicate that it's all matches from here out.
642 if (kind_ != Prog::kManyMatch &&
643 (kind_ != Prog::kFirstMatch ||
644 (it == q->begin() && ip->greedy(prog_))) &&
645 (kind_ != Prog::kLongestMatch || !sawmark) &&
646 (flag & kFlagMatch)) {
647 delete[] inst;
648 if (ExtraDebug)
649 fprintf(stderr, " -> FullMatchState\n");
650 return FullMatchState;
651 }
652 FALLTHROUGH_INTENDED;
653 default:
654 // Record iff id is the head of its list, which must
655 // be the case if id-1 is the last of *its* list. :)
656 if (prog_->inst(id-1)->last())
657 inst[n++] = *it;
658 if (ip->opcode() == kInstEmptyWidth)
659 needflags |= ip->empty();
660 if (ip->opcode() == kInstMatch && !prog_->anchor_end())
661 sawmatch = true;
662 break;
663 }
664 }
665 DCHECK_LE(n, q->size());
666 if (n > 0 && inst[n-1] == Mark)
667 n--;
668
669 // If there are no empty-width instructions waiting to execute,
670 // then the extra flag bits will not be used, so there is no
671 // point in saving them. (Discarding them reduces the number
672 // of distinct states.)
673 if (needflags == 0)
674 flag &= kFlagMatch;
675
676 // NOTE(rsc): The code above cannot do flag &= needflags,
677 // because if the right flags were present to pass the current
678 // kInstEmptyWidth instructions, new kInstEmptyWidth instructions
679 // might be reached that in turn need different flags.
680 // The only sure thing is that if there are no kInstEmptyWidth
681 // instructions at all, no flags will be needed.
682 // We could do the extra work to figure out the full set of
683 // possibly needed flags by exploring past the kInstEmptyWidth
684 // instructions, but the check above -- are any flags needed
685 // at all? -- handles the most common case. More fine-grained
686 // analysis can only be justified by measurements showing that
687 // too many redundant states are being allocated.
688
689 // If there are no Insts in the list, it's a dead state,
690 // which is useful to signal with a special pointer so that
691 // the execution loop can stop early. This is only okay
692 // if the state is *not* a matching state.
693 if (n == 0 && flag == 0) {
694 delete[] inst;
695 if (ExtraDebug)
696 fprintf(stderr, " -> DeadState\n");
697 return DeadState;
698 }
699
700 // If we're in longest match mode, the state is a sequence of
701 // unordered state sets separated by Marks. Sort each set
702 // to canonicalize, to reduce the number of distinct sets stored.
703 if (kind_ == Prog::kLongestMatch) {
704 int* ip = inst;
705 int* ep = ip + n;
706 while (ip < ep) {
707 int* markp = ip;
708 while (markp < ep && *markp != Mark)
709 markp++;
710 std::sort(ip, markp);
711 if (markp < ep)
712 markp++;
713 ip = markp;
714 }
715 }
716
717 // Append MatchSep and the match IDs in mq if necessary.
718 if (mq != NULL) {
719 inst[n++] = MatchSep;
720 for (Workq::iterator i = mq->begin(); i != mq->end(); ++i) {
721 int id = *i;
722 Prog::Inst* ip = prog_->inst(id);
723 if (ip->opcode() == kInstMatch)
724 inst[n++] = ip->match_id();
725 }
726 }
727
728 // Save the needed empty-width flags in the top bits for use later.
729 flag |= needflags << kFlagNeedShift;
730
731 State* state = CachedState(inst, n, flag);
732 delete[] inst;
733 return state;
734 }
735
736 // Looks in the State cache for a State matching inst, ninst, flag.
737 // If one is found, returns it. If one is not found, allocates one,
738 // inserts it in the cache, and returns it.
CachedState(int * inst,int ninst,uint32_t flag)739 DFA::State* DFA::CachedState(int* inst, int ninst, uint32_t flag) {
740 //mutex_.AssertHeld();
741
742 // Look in the cache for a pre-existing state.
743 // We have to initialise the struct like this because otherwise
744 // MSVC will complain about the flexible array member. :(
745 State state;
746 state.inst_ = inst;
747 state.ninst_ = ninst;
748 state.flag_ = flag;
749 StateSet::iterator it = state_cache_.find(&state);
750 if (it != state_cache_.end()) {
751 if (ExtraDebug)
752 fprintf(stderr, " -cached-> %s\n", DumpState(*it).c_str());
753 return *it;
754 }
755
756 // Must have enough memory for new state.
757 // In addition to what we're going to allocate,
758 // the state cache hash table seems to incur about 40 bytes per
759 // State*, empirically.
760 const int kStateCacheOverhead = 40;
761 int nnext = prog_->bytemap_range() + 1; // + 1 for kByteEndText slot
762 int mem = sizeof(State) + nnext*sizeof(std::atomic<State*>) +
763 ninst*sizeof(int);
764 if (mem_budget_ < mem + kStateCacheOverhead) {
765 mem_budget_ = -1;
766 return NULL;
767 }
768 mem_budget_ -= mem + kStateCacheOverhead;
769
770 // Allocate new state along with room for next_ and inst_.
771 char* space = std::allocator<char>().allocate(mem);
772 State* s = new (space) State;
773 (void) new (s->next_) std::atomic<State*>[nnext];
774 // Work around a unfortunate bug in older versions of libstdc++.
775 // (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64658)
776 for (int i = 0; i < nnext; i++)
777 (void) new (s->next_ + i) std::atomic<State*>(NULL);
778 s->inst_ = new (s->next_ + nnext) int[ninst];
779 memmove(s->inst_, inst, ninst*sizeof s->inst_[0]);
780 s->ninst_ = ninst;
781 s->flag_ = flag;
782 if (ExtraDebug)
783 fprintf(stderr, " -> %s\n", DumpState(s).c_str());
784
785 // Put state in cache and return it.
786 state_cache_.insert(s);
787 return s;
788 }
789
790 // Clear the cache. Must hold cache_mutex_.w or be in destructor.
ClearCache()791 void DFA::ClearCache() {
792 StateSet::iterator begin = state_cache_.begin();
793 StateSet::iterator end = state_cache_.end();
794 while (begin != end) {
795 StateSet::iterator tmp = begin;
796 ++begin;
797 // Deallocate the blob of memory that we allocated in DFA::CachedState().
798 // We recompute mem in order to benefit from sized delete where possible.
799 int ninst = (*tmp)->ninst_;
800 int nnext = prog_->bytemap_range() + 1; // + 1 for kByteEndText slot
801 int mem = sizeof(State) + nnext*sizeof(std::atomic<State*>) +
802 ninst*sizeof(int);
803 std::allocator<char>().deallocate(reinterpret_cast<char*>(*tmp), mem);
804 }
805 state_cache_.clear();
806 }
807
808 // Copies insts in state s to the work queue q.
StateToWorkq(State * s,Workq * q)809 void DFA::StateToWorkq(State* s, Workq* q) {
810 q->clear();
811 for (int i = 0; i < s->ninst_; i++) {
812 if (s->inst_[i] == Mark) {
813 q->mark();
814 } else if (s->inst_[i] == MatchSep) {
815 // Nothing after this is an instruction!
816 break;
817 } else {
818 // Explore from the head of the list.
819 AddToQueue(q, s->inst_[i], s->flag_ & kFlagEmptyMask);
820 }
821 }
822 }
823
824 // Adds ip to the work queue, following empty arrows according to flag.
AddToQueue(Workq * q,int id,uint32_t flag)825 void DFA::AddToQueue(Workq* q, int id, uint32_t flag) {
826
827 // Use stack_ to hold our stack of instructions yet to process.
828 // It was preallocated as follows:
829 // one entry per Capture;
830 // one entry per EmptyWidth; and
831 // one entry per Nop.
832 // This reflects the maximum number of stack pushes that each can
833 // perform. (Each instruction can be processed at most once.)
834 // When using marks, we also added nmark == prog_->size().
835 // (Otherwise, nmark == 0.)
836 int* stk = stack_.data();
837 int nstk = 0;
838
839 stk[nstk++] = id;
840 while (nstk > 0) {
841 DCHECK_LE(nstk, stack_.size());
842 id = stk[--nstk];
843
844 Loop:
845 if (id == Mark) {
846 q->mark();
847 continue;
848 }
849
850 if (id == 0)
851 continue;
852
853 // If ip is already on the queue, nothing to do.
854 // Otherwise add it. We don't actually keep all the
855 // ones that get added, but adding all of them here
856 // increases the likelihood of q->contains(id),
857 // reducing the amount of duplicated work.
858 if (q->contains(id))
859 continue;
860 q->insert_new(id);
861
862 // Process instruction.
863 Prog::Inst* ip = prog_->inst(id);
864 switch (ip->opcode()) {
865 default:
866 LOG(DFATAL) << "unhandled opcode: " << ip->opcode();
867 break;
868
869 case kInstByteRange: // just save these on the queue
870 case kInstMatch:
871 if (ip->last())
872 break;
873 id = id+1;
874 goto Loop;
875
876 case kInstCapture: // DFA treats captures as no-ops.
877 case kInstNop:
878 if (!ip->last())
879 stk[nstk++] = id+1;
880
881 // If this instruction is the [00-FF]* loop at the beginning of
882 // a leftmost-longest unanchored search, separate with a Mark so
883 // that future threads (which will start farther to the right in
884 // the input string) are lower priority than current threads.
885 if (ip->opcode() == kInstNop && q->maxmark() > 0 &&
886 id == prog_->start_unanchored() && id != prog_->start())
887 stk[nstk++] = Mark;
888 id = ip->out();
889 goto Loop;
890
891 case kInstAltMatch:
892 DCHECK(!ip->last());
893 id = id+1;
894 goto Loop;
895
896 case kInstEmptyWidth:
897 if (!ip->last())
898 stk[nstk++] = id+1;
899
900 // Continue on if we have all the right flag bits.
901 if (ip->empty() & ~flag)
902 break;
903 id = ip->out();
904 goto Loop;
905 }
906 }
907 }
908
909 // Running of work queues. In the work queue, order matters:
910 // the queue is sorted in priority order. If instruction i comes before j,
911 // then the instructions that i produces during the run must come before
912 // the ones that j produces. In order to keep this invariant, all the
913 // work queue runners have to take an old queue to process and then
914 // also a new queue to fill in. It's not acceptable to add to the end of
915 // an existing queue, because new instructions will not end up in the
916 // correct position.
917
918 // Runs the work queue, processing the empty strings indicated by flag.
919 // For example, flag == kEmptyBeginLine|kEmptyEndLine means to match
920 // both ^ and $. It is important that callers pass all flags at once:
921 // processing both ^ and $ is not the same as first processing only ^
922 // and then processing only $. Doing the two-step sequence won't match
923 // ^$^$^$ but processing ^ and $ simultaneously will (and is the behavior
924 // exhibited by existing implementations).
RunWorkqOnEmptyString(Workq * oldq,Workq * newq,uint32_t flag)925 void DFA::RunWorkqOnEmptyString(Workq* oldq, Workq* newq, uint32_t flag) {
926 newq->clear();
927 for (Workq::iterator i = oldq->begin(); i != oldq->end(); ++i) {
928 if (oldq->is_mark(*i))
929 AddToQueue(newq, Mark, flag);
930 else
931 AddToQueue(newq, *i, flag);
932 }
933 }
934
935 // Runs the work queue, processing the single byte c followed by any empty
936 // strings indicated by flag. For example, c == 'a' and flag == kEmptyEndLine,
937 // means to match c$. Sets the bool *ismatch to true if the end of the
938 // regular expression program has been reached (the regexp has matched).
RunWorkqOnByte(Workq * oldq,Workq * newq,int c,uint32_t flag,bool * ismatch)939 void DFA::RunWorkqOnByte(Workq* oldq, Workq* newq,
940 int c, uint32_t flag, bool* ismatch) {
941 //mutex_.AssertHeld();
942
943 newq->clear();
944 for (Workq::iterator i = oldq->begin(); i != oldq->end(); ++i) {
945 if (oldq->is_mark(*i)) {
946 if (*ismatch)
947 return;
948 newq->mark();
949 continue;
950 }
951 int id = *i;
952 Prog::Inst* ip = prog_->inst(id);
953 switch (ip->opcode()) {
954 default:
955 LOG(DFATAL) << "unhandled opcode: " << ip->opcode();
956 break;
957
958 case kInstFail: // never succeeds
959 case kInstCapture: // already followed
960 case kInstNop: // already followed
961 case kInstAltMatch: // already followed
962 case kInstEmptyWidth: // already followed
963 break;
964
965 case kInstByteRange: // can follow if c is in range
966 if (ip->Matches(c))
967 AddToQueue(newq, ip->out(), flag);
968 break;
969
970 case kInstMatch:
971 if (prog_->anchor_end() && c != kByteEndText &&
972 kind_ != Prog::kManyMatch)
973 break;
974 *ismatch = true;
975 if (kind_ == Prog::kFirstMatch) {
976 // Can stop processing work queue since we found a match.
977 return;
978 }
979 break;
980 }
981 }
982
983 if (ExtraDebug)
984 fprintf(stderr, "%s on %d[%#x] -> %s [%d]\n", DumpWorkq(oldq).c_str(),
985 c, flag, DumpWorkq(newq).c_str(), *ismatch);
986 }
987
988 // Processes input byte c in state, returning new state.
989 // Caller does not hold mutex.
RunStateOnByteUnlocked(State * state,int c)990 DFA::State* DFA::RunStateOnByteUnlocked(State* state, int c) {
991 // Keep only one RunStateOnByte going
992 // even if the DFA is being run by multiple threads.
993 MutexLock l(&mutex_);
994 return RunStateOnByte(state, c);
995 }
996
997 // Processes input byte c in state, returning new state.
RunStateOnByte(State * state,int c)998 DFA::State* DFA::RunStateOnByte(State* state, int c) {
999 //mutex_.AssertHeld();
1000
1001 if (state <= SpecialStateMax) {
1002 if (state == FullMatchState) {
1003 // It is convenient for routines like PossibleMatchRange
1004 // if we implement RunStateOnByte for FullMatchState:
1005 // once you get into this state you never get out,
1006 // so it's pretty easy.
1007 return FullMatchState;
1008 }
1009 if (state == DeadState) {
1010 LOG(DFATAL) << "DeadState in RunStateOnByte";
1011 return NULL;
1012 }
1013 if (state == NULL) {
1014 LOG(DFATAL) << "NULL state in RunStateOnByte";
1015 return NULL;
1016 }
1017 LOG(DFATAL) << "Unexpected special state in RunStateOnByte";
1018 return NULL;
1019 }
1020
1021 // If someone else already computed this, return it.
1022 State* ns = state->next_[ByteMap(c)].load(std::memory_order_relaxed);
1023 if (ns != NULL)
1024 return ns;
1025
1026 // Convert state into Workq.
1027 StateToWorkq(state, q0_);
1028
1029 // Flags marking the kinds of empty-width things (^ $ etc)
1030 // around this byte. Before the byte we have the flags recorded
1031 // in the State structure itself. After the byte we have
1032 // nothing yet (but that will change: read on).
1033 uint32_t needflag = state->flag_ >> kFlagNeedShift;
1034 uint32_t beforeflag = state->flag_ & kFlagEmptyMask;
1035 uint32_t oldbeforeflag = beforeflag;
1036 uint32_t afterflag = 0;
1037
1038 if (c == '\n') {
1039 // Insert implicit $ and ^ around \n
1040 beforeflag |= kEmptyEndLine;
1041 afterflag |= kEmptyBeginLine;
1042 }
1043
1044 if (c == kByteEndText) {
1045 // Insert implicit $ and \z before the fake "end text" byte.
1046 beforeflag |= kEmptyEndLine | kEmptyEndText;
1047 }
1048
1049 // The state flag kFlagLastWord says whether the last
1050 // byte processed was a word character. Use that info to
1051 // insert empty-width (non-)word boundaries.
1052 bool islastword = (state->flag_ & kFlagLastWord) != 0;
1053 bool isword = c != kByteEndText && Prog::IsWordChar(static_cast<uint8_t>(c));
1054 if (isword == islastword)
1055 beforeflag |= kEmptyNonWordBoundary;
1056 else
1057 beforeflag |= kEmptyWordBoundary;
1058
1059 // Okay, finally ready to run.
1060 // Only useful to rerun on empty string if there are new, useful flags.
1061 if (beforeflag & ~oldbeforeflag & needflag) {
1062 RunWorkqOnEmptyString(q0_, q1_, beforeflag);
1063 using std::swap;
1064 swap(q0_, q1_);
1065 }
1066 bool ismatch = false;
1067 RunWorkqOnByte(q0_, q1_, c, afterflag, &ismatch);
1068 using std::swap;
1069 swap(q0_, q1_);
1070
1071 // Save afterflag along with ismatch and isword in new state.
1072 uint32_t flag = afterflag;
1073 if (ismatch)
1074 flag |= kFlagMatch;
1075 if (isword)
1076 flag |= kFlagLastWord;
1077
1078 if (ismatch && kind_ == Prog::kManyMatch)
1079 ns = WorkqToCachedState(q0_, q1_, flag);
1080 else
1081 ns = WorkqToCachedState(q0_, NULL, flag);
1082
1083 // Flush ns before linking to it.
1084 // Write barrier before updating state->next_ so that the
1085 // main search loop can proceed without any locking, for speed.
1086 // (Otherwise it would need one mutex operation per input byte.)
1087 state->next_[ByteMap(c)].store(ns, std::memory_order_release);
1088 return ns;
1089 }
1090
1091
1092 //////////////////////////////////////////////////////////////////////
1093 // DFA cache reset.
1094
1095 // Reader-writer lock helper.
1096 //
1097 // The DFA uses a reader-writer mutex to protect the state graph itself.
1098 // Traversing the state graph requires holding the mutex for reading,
1099 // and discarding the state graph and starting over requires holding the
1100 // lock for writing. If a search needs to expand the graph but is out
1101 // of memory, it will need to drop its read lock and then acquire the
1102 // write lock. Since it cannot then atomically downgrade from write lock
1103 // to read lock, it runs the rest of the search holding the write lock.
1104 // (This probably helps avoid repeated contention, but really the decision
1105 // is forced by the Mutex interface.) It's a bit complicated to keep
1106 // track of whether the lock is held for reading or writing and thread
1107 // that through the search, so instead we encapsulate it in the RWLocker
1108 // and pass that around.
1109
1110 class DFA::RWLocker {
1111 public:
1112 explicit RWLocker(Mutex* mu);
1113 ~RWLocker();
1114
1115 // If the lock is only held for reading right now,
1116 // drop the read lock and re-acquire for writing.
1117 // Subsequent calls to LockForWriting are no-ops.
1118 // Notice that the lock is *released* temporarily.
1119 void LockForWriting();
1120
1121 private:
1122 Mutex* mu_;
1123 bool writing_;
1124
1125 RWLocker(const RWLocker&) = delete;
1126 RWLocker& operator=(const RWLocker&) = delete;
1127 };
1128
RWLocker(Mutex * mu)1129 DFA::RWLocker::RWLocker(Mutex* mu) : mu_(mu), writing_(false) {
1130 mu_->ReaderLock();
1131 }
1132
1133 // This function is marked as NO_THREAD_SAFETY_ANALYSIS because the annotations
1134 // does not support lock upgrade.
LockForWriting()1135 void DFA::RWLocker::LockForWriting() NO_THREAD_SAFETY_ANALYSIS {
1136 if (!writing_) {
1137 mu_->ReaderUnlock();
1138 mu_->WriterLock();
1139 writing_ = true;
1140 }
1141 }
1142
~RWLocker()1143 DFA::RWLocker::~RWLocker() {
1144 if (!writing_)
1145 mu_->ReaderUnlock();
1146 else
1147 mu_->WriterUnlock();
1148 }
1149
1150
1151 // When the DFA's State cache fills, we discard all the states in the
1152 // cache and start over. Many threads can be using and adding to the
1153 // cache at the same time, so we synchronize using the cache_mutex_
1154 // to keep from stepping on other threads. Specifically, all the
1155 // threads using the current cache hold cache_mutex_ for reading.
1156 // When a thread decides to flush the cache, it drops cache_mutex_
1157 // and then re-acquires it for writing. That ensures there are no
1158 // other threads accessing the cache anymore. The rest of the search
1159 // runs holding cache_mutex_ for writing, avoiding any contention
1160 // with or cache pollution caused by other threads.
1161
ResetCache(RWLocker * cache_lock)1162 void DFA::ResetCache(RWLocker* cache_lock) {
1163 // Re-acquire the cache_mutex_ for writing (exclusive use).
1164 cache_lock->LockForWriting();
1165
1166 // Clear the cache, reset the memory budget.
1167 for (int i = 0; i < kMaxStart; i++) {
1168 start_[i].start = NULL;
1169 start_[i].first_byte.store(kFbUnknown, std::memory_order_relaxed);
1170 }
1171 ClearCache();
1172 mem_budget_ = state_budget_;
1173 }
1174
1175 // Typically, a couple States do need to be preserved across a cache
1176 // reset, like the State at the current point in the search.
1177 // The StateSaver class helps keep States across cache resets.
1178 // It makes a copy of the state's guts outside the cache (before the reset)
1179 // and then can be asked, after the reset, to recreate the State
1180 // in the new cache. For example, in a DFA method ("this" is a DFA):
1181 //
1182 // StateSaver saver(this, s);
1183 // ResetCache(cache_lock);
1184 // s = saver.Restore();
1185 //
1186 // The saver should always have room in the cache to re-create the state,
1187 // because resetting the cache locks out all other threads, and the cache
1188 // is known to have room for at least a couple states (otherwise the DFA
1189 // constructor fails).
1190
1191 class DFA::StateSaver {
1192 public:
1193 explicit StateSaver(DFA* dfa, State* state);
1194 ~StateSaver();
1195
1196 // Recreates and returns a state equivalent to the
1197 // original state passed to the constructor.
1198 // Returns NULL if the cache has filled, but
1199 // since the DFA guarantees to have room in the cache
1200 // for a couple states, should never return NULL
1201 // if used right after ResetCache.
1202 State* Restore();
1203
1204 private:
1205 DFA* dfa_; // the DFA to use
1206 int* inst_; // saved info from State
1207 int ninst_;
1208 uint32_t flag_;
1209 bool is_special_; // whether original state was special
1210 State* special_; // if is_special_, the original state
1211
1212 StateSaver(const StateSaver&) = delete;
1213 StateSaver& operator=(const StateSaver&) = delete;
1214 };
1215
StateSaver(DFA * dfa,State * state)1216 DFA::StateSaver::StateSaver(DFA* dfa, State* state) {
1217 dfa_ = dfa;
1218 if (state <= SpecialStateMax) {
1219 inst_ = NULL;
1220 ninst_ = 0;
1221 flag_ = 0;
1222 is_special_ = true;
1223 special_ = state;
1224 return;
1225 }
1226 is_special_ = false;
1227 special_ = NULL;
1228 flag_ = state->flag_;
1229 ninst_ = state->ninst_;
1230 inst_ = new int[ninst_];
1231 memmove(inst_, state->inst_, ninst_*sizeof inst_[0]);
1232 }
1233
~StateSaver()1234 DFA::StateSaver::~StateSaver() {
1235 if (!is_special_)
1236 delete[] inst_;
1237 }
1238
Restore()1239 DFA::State* DFA::StateSaver::Restore() {
1240 if (is_special_)
1241 return special_;
1242 MutexLock l(&dfa_->mutex_);
1243 State* s = dfa_->CachedState(inst_, ninst_, flag_);
1244 if (s == NULL)
1245 LOG(DFATAL) << "StateSaver failed to restore state.";
1246 return s;
1247 }
1248
1249
1250 //////////////////////////////////////////////////////////////////////
1251 //
1252 // DFA execution.
1253 //
1254 // The basic search loop is easy: start in a state s and then for each
1255 // byte c in the input, s = s->next[c].
1256 //
1257 // This simple description omits a few efficiency-driven complications.
1258 //
1259 // First, the State graph is constructed incrementally: it is possible
1260 // that s->next[c] is null, indicating that that state has not been
1261 // fully explored. In this case, RunStateOnByte must be invoked to
1262 // determine the next state, which is cached in s->next[c] to save
1263 // future effort. An alternative reason for s->next[c] to be null is
1264 // that the DFA has reached a so-called "dead state", in which any match
1265 // is no longer possible. In this case RunStateOnByte will return NULL
1266 // and the processing of the string can stop early.
1267 //
1268 // Second, a 256-element pointer array for s->next_ makes each State
1269 // quite large (2kB on 64-bit machines). Instead, dfa->bytemap_[]
1270 // maps from bytes to "byte classes" and then next_ only needs to have
1271 // as many pointers as there are byte classes. A byte class is simply a
1272 // range of bytes that the regexp never distinguishes between.
1273 // A regexp looking for a[abc] would have four byte ranges -- 0 to 'a'-1,
1274 // 'a', 'b' to 'c', and 'c' to 0xFF. The bytemap slows us a little bit
1275 // but in exchange we typically cut the size of a State (and thus our
1276 // memory footprint) by about 5-10x. The comments still refer to
1277 // s->next[c] for simplicity, but code should refer to s->next_[bytemap_[c]].
1278 //
1279 // Third, it is common for a DFA for an unanchored match to begin in a
1280 // state in which only one particular byte value can take the DFA to a
1281 // different state. That is, s->next[c] != s for only one c. In this
1282 // situation, the DFA can do better than executing the simple loop.
1283 // Instead, it can call memchr to search very quickly for the byte c.
1284 // Whether the start state has this property is determined during a
1285 // pre-compilation pass, and if so, the byte b is passed to the search
1286 // loop as the "first_byte" argument, along with a boolean "have_first_byte".
1287 //
1288 // Fourth, the desired behavior is to search for the leftmost-best match
1289 // (approximately, the same one that Perl would find), which is not
1290 // necessarily the match ending earliest in the string. Each time a
1291 // match is found, it must be noted, but the DFA must continue on in
1292 // hope of finding a higher-priority match. In some cases, the caller only
1293 // cares whether there is any match at all, not which one is found.
1294 // The "want_earliest_match" flag causes the search to stop at the first
1295 // match found.
1296 //
1297 // Fifth, one algorithm that uses the DFA needs it to run over the
1298 // input string backward, beginning at the end and ending at the beginning.
1299 // Passing false for the "run_forward" flag causes the DFA to run backward.
1300 //
1301 // The checks for these last three cases, which in a naive implementation
1302 // would be performed once per input byte, slow the general loop enough
1303 // to merit specialized versions of the search loop for each of the
1304 // eight possible settings of the three booleans. Rather than write
1305 // eight different functions, we write one general implementation and then
1306 // inline it to create the specialized ones.
1307 //
1308 // Note that matches are delayed by one byte, to make it easier to
1309 // accomodate match conditions depending on the next input byte (like $ and \b).
1310 // When s->next[c]->IsMatch(), it means that there is a match ending just
1311 // *before* byte c.
1312
1313 // The generic search loop. Searches text for a match, returning
1314 // the pointer to the end of the chosen match, or NULL if no match.
1315 // The bools are equal to the same-named variables in params, but
1316 // making them function arguments lets the inliner specialize
1317 // this function to each combination (see two paragraphs above).
InlinedSearchLoop(SearchParams * params,bool have_first_byte,bool want_earliest_match,bool run_forward)1318 inline bool DFA::InlinedSearchLoop(SearchParams* params,
1319 bool have_first_byte,
1320 bool want_earliest_match,
1321 bool run_forward) {
1322 State* start = params->start;
1323 const uint8_t* bp = BytePtr(params->text.begin()); // start of text
1324 const uint8_t* p = bp; // text scanning point
1325 const uint8_t* ep = BytePtr(params->text.end()); // end of text
1326 const uint8_t* resetp = NULL; // p at last cache reset
1327 if (!run_forward) {
1328 using std::swap;
1329 swap(p, ep);
1330 }
1331
1332 const uint8_t* bytemap = prog_->bytemap();
1333 const uint8_t* lastmatch = NULL; // most recent matching position in text
1334 bool matched = false;
1335
1336 State* s = start;
1337 if (ExtraDebug)
1338 fprintf(stderr, "@stx: %s\n", DumpState(s).c_str());
1339
1340 if (s->IsMatch()) {
1341 matched = true;
1342 lastmatch = p;
1343 if (ExtraDebug)
1344 fprintf(stderr, "match @stx! [%s]\n", DumpState(s).c_str());
1345 if (params->matches != NULL && kind_ == Prog::kManyMatch) {
1346 for (int i = s->ninst_ - 1; i >= 0; i--) {
1347 int id = s->inst_[i];
1348 if (id == MatchSep)
1349 break;
1350 params->matches->insert(id);
1351 }
1352 }
1353 if (want_earliest_match) {
1354 params->ep = reinterpret_cast<const char*>(lastmatch);
1355 return true;
1356 }
1357 }
1358
1359 while (p != ep) {
1360 if (ExtraDebug)
1361 fprintf(stderr, "@%td: %s\n",
1362 p - bp, DumpState(s).c_str());
1363
1364 if (have_first_byte && s == start) {
1365 // In start state, only way out is to find first_byte,
1366 // so use optimized assembly in memchr to skip ahead.
1367 // If first_byte isn't found, we can skip to the end
1368 // of the string.
1369 if (run_forward) {
1370 if ((p = BytePtr(memchr(p, params->first_byte, ep - p))) == NULL) {
1371 p = ep;
1372 break;
1373 }
1374 } else {
1375 if ((p = BytePtr(memrchr(ep, params->first_byte, p - ep))) == NULL) {
1376 p = ep;
1377 break;
1378 }
1379 p++;
1380 }
1381 }
1382
1383 int c;
1384 if (run_forward)
1385 c = *p++;
1386 else
1387 c = *--p;
1388
1389 // Note that multiple threads might be consulting
1390 // s->next_[bytemap[c]] simultaneously.
1391 // RunStateOnByte takes care of the appropriate locking,
1392 // including a memory barrier so that the unlocked access
1393 // (sometimes known as "double-checked locking") is safe.
1394 // The alternative would be either one DFA per thread
1395 // or one mutex operation per input byte.
1396 //
1397 // ns == DeadState means the state is known to be dead
1398 // (no more matches are possible).
1399 // ns == NULL means the state has not yet been computed
1400 // (need to call RunStateOnByteUnlocked).
1401 // RunStateOnByte returns ns == NULL if it is out of memory.
1402 // ns == FullMatchState means the rest of the string matches.
1403 //
1404 // Okay to use bytemap[] not ByteMap() here, because
1405 // c is known to be an actual byte and not kByteEndText.
1406
1407 State* ns = s->next_[bytemap[c]].load(std::memory_order_acquire);
1408 if (ns == NULL) {
1409 ns = RunStateOnByteUnlocked(s, c);
1410 if (ns == NULL) {
1411 // After we reset the cache, we hold cache_mutex exclusively,
1412 // so if resetp != NULL, it means we filled the DFA state
1413 // cache with this search alone (without any other threads).
1414 // Benchmarks show that doing a state computation on every
1415 // byte runs at about 0.2 MB/s, while the NFA (nfa.cc) can do the
1416 // same at about 2 MB/s. Unless we're processing an average
1417 // of 10 bytes per state computation, fail so that RE2 can
1418 // fall back to the NFA.
1419 if (dfa_should_bail_when_slow && resetp != NULL &&
1420 static_cast<size_t>(p - resetp) < 10*state_cache_.size()) {
1421 params->failed = true;
1422 return false;
1423 }
1424 resetp = p;
1425
1426 // Prepare to save start and s across the reset.
1427 StateSaver save_start(this, start);
1428 StateSaver save_s(this, s);
1429
1430 // Discard all the States in the cache.
1431 ResetCache(params->cache_lock);
1432
1433 // Restore start and s so we can continue.
1434 if ((start = save_start.Restore()) == NULL ||
1435 (s = save_s.Restore()) == NULL) {
1436 // Restore already did LOG(DFATAL).
1437 params->failed = true;
1438 return false;
1439 }
1440 ns = RunStateOnByteUnlocked(s, c);
1441 if (ns == NULL) {
1442 LOG(DFATAL) << "RunStateOnByteUnlocked failed after ResetCache";
1443 params->failed = true;
1444 return false;
1445 }
1446 }
1447 }
1448 if (ns <= SpecialStateMax) {
1449 if (ns == DeadState) {
1450 params->ep = reinterpret_cast<const char*>(lastmatch);
1451 return matched;
1452 }
1453 // FullMatchState
1454 params->ep = reinterpret_cast<const char*>(ep);
1455 return true;
1456 }
1457
1458 s = ns;
1459 if (s->IsMatch()) {
1460 matched = true;
1461 // The DFA notices the match one byte late,
1462 // so adjust p before using it in the match.
1463 if (run_forward)
1464 lastmatch = p - 1;
1465 else
1466 lastmatch = p + 1;
1467 if (ExtraDebug)
1468 fprintf(stderr, "match @%td! [%s]\n",
1469 lastmatch - bp, DumpState(s).c_str());
1470 if (params->matches != NULL && kind_ == Prog::kManyMatch) {
1471 for (int i = s->ninst_ - 1; i >= 0; i--) {
1472 int id = s->inst_[i];
1473 if (id == MatchSep)
1474 break;
1475 params->matches->insert(id);
1476 }
1477 }
1478 if (want_earliest_match) {
1479 params->ep = reinterpret_cast<const char*>(lastmatch);
1480 return true;
1481 }
1482 }
1483 }
1484
1485 // Process one more byte to see if it triggers a match.
1486 // (Remember, matches are delayed one byte.)
1487 if (ExtraDebug)
1488 fprintf(stderr, "@etx: %s\n", DumpState(s).c_str());
1489
1490 int lastbyte;
1491 if (run_forward) {
1492 if (params->text.end() == params->context.end())
1493 lastbyte = kByteEndText;
1494 else
1495 lastbyte = params->text.end()[0] & 0xFF;
1496 } else {
1497 if (params->text.begin() == params->context.begin())
1498 lastbyte = kByteEndText;
1499 else
1500 lastbyte = params->text.begin()[-1] & 0xFF;
1501 }
1502
1503 State* ns = s->next_[ByteMap(lastbyte)].load(std::memory_order_acquire);
1504 if (ns == NULL) {
1505 ns = RunStateOnByteUnlocked(s, lastbyte);
1506 if (ns == NULL) {
1507 StateSaver save_s(this, s);
1508 ResetCache(params->cache_lock);
1509 if ((s = save_s.Restore()) == NULL) {
1510 params->failed = true;
1511 return false;
1512 }
1513 ns = RunStateOnByteUnlocked(s, lastbyte);
1514 if (ns == NULL) {
1515 LOG(DFATAL) << "RunStateOnByteUnlocked failed after Reset";
1516 params->failed = true;
1517 return false;
1518 }
1519 }
1520 }
1521 if (ns <= SpecialStateMax) {
1522 if (ns == DeadState) {
1523 params->ep = reinterpret_cast<const char*>(lastmatch);
1524 return matched;
1525 }
1526 // FullMatchState
1527 params->ep = reinterpret_cast<const char*>(ep);
1528 return true;
1529 }
1530
1531 s = ns;
1532 if (s->IsMatch()) {
1533 matched = true;
1534 lastmatch = p;
1535 if (ExtraDebug)
1536 fprintf(stderr, "match @etx! [%s]\n", DumpState(s).c_str());
1537 if (params->matches != NULL && kind_ == Prog::kManyMatch) {
1538 for (int i = s->ninst_ - 1; i >= 0; i--) {
1539 int id = s->inst_[i];
1540 if (id == MatchSep)
1541 break;
1542 params->matches->insert(id);
1543 }
1544 }
1545 }
1546
1547 params->ep = reinterpret_cast<const char*>(lastmatch);
1548 return matched;
1549 }
1550
1551 // Inline specializations of the general loop.
SearchFFF(SearchParams * params)1552 bool DFA::SearchFFF(SearchParams* params) {
1553 return InlinedSearchLoop(params, 0, 0, 0);
1554 }
SearchFFT(SearchParams * params)1555 bool DFA::SearchFFT(SearchParams* params) {
1556 return InlinedSearchLoop(params, 0, 0, 1);
1557 }
SearchFTF(SearchParams * params)1558 bool DFA::SearchFTF(SearchParams* params) {
1559 return InlinedSearchLoop(params, 0, 1, 0);
1560 }
SearchFTT(SearchParams * params)1561 bool DFA::SearchFTT(SearchParams* params) {
1562 return InlinedSearchLoop(params, 0, 1, 1);
1563 }
SearchTFF(SearchParams * params)1564 bool DFA::SearchTFF(SearchParams* params) {
1565 return InlinedSearchLoop(params, 1, 0, 0);
1566 }
SearchTFT(SearchParams * params)1567 bool DFA::SearchTFT(SearchParams* params) {
1568 return InlinedSearchLoop(params, 1, 0, 1);
1569 }
SearchTTF(SearchParams * params)1570 bool DFA::SearchTTF(SearchParams* params) {
1571 return InlinedSearchLoop(params, 1, 1, 0);
1572 }
SearchTTT(SearchParams * params)1573 bool DFA::SearchTTT(SearchParams* params) {
1574 return InlinedSearchLoop(params, 1, 1, 1);
1575 }
1576
1577 // For debugging, calls the general code directly.
SlowSearchLoop(SearchParams * params)1578 bool DFA::SlowSearchLoop(SearchParams* params) {
1579 return InlinedSearchLoop(params,
1580 params->first_byte >= 0,
1581 params->want_earliest_match,
1582 params->run_forward);
1583 }
1584
1585 // For performance, calls the appropriate specialized version
1586 // of InlinedSearchLoop.
FastSearchLoop(SearchParams * params)1587 bool DFA::FastSearchLoop(SearchParams* params) {
1588 // Because the methods are private, the Searches array
1589 // cannot be declared at top level.
1590 static bool (DFA::*Searches[])(SearchParams*) = {
1591 &DFA::SearchFFF,
1592 &DFA::SearchFFT,
1593 &DFA::SearchFTF,
1594 &DFA::SearchFTT,
1595 &DFA::SearchTFF,
1596 &DFA::SearchTFT,
1597 &DFA::SearchTTF,
1598 &DFA::SearchTTT,
1599 };
1600
1601 bool have_first_byte = params->first_byte >= 0;
1602 int index = 4 * have_first_byte +
1603 2 * params->want_earliest_match +
1604 1 * params->run_forward;
1605 return (this->*Searches[index])(params);
1606 }
1607
1608
1609 // The discussion of DFA execution above ignored the question of how
1610 // to determine the initial state for the search loop. There are two
1611 // factors that influence the choice of start state.
1612 //
1613 // The first factor is whether the search is anchored or not.
1614 // The regexp program (Prog*) itself has
1615 // two different entry points: one for anchored searches and one for
1616 // unanchored searches. (The unanchored version starts with a leading ".*?"
1617 // and then jumps to the anchored one.)
1618 //
1619 // The second factor is where text appears in the larger context, which
1620 // determines which empty-string operators can be matched at the beginning
1621 // of execution. If text is at the very beginning of context, \A and ^ match.
1622 // Otherwise if text is at the beginning of a line, then ^ matches.
1623 // Otherwise it matters whether the character before text is a word character
1624 // or a non-word character.
1625 //
1626 // The two cases (unanchored vs not) and four cases (empty-string flags)
1627 // combine to make the eight cases recorded in the DFA's begin_text_[2],
1628 // begin_line_[2], after_wordchar_[2], and after_nonwordchar_[2] cached
1629 // StartInfos. The start state for each is filled in the first time it
1630 // is used for an actual search.
1631
1632 // Examines text, context, and anchored to determine the right start
1633 // state for the DFA search loop. Fills in params and returns true on success.
1634 // Returns false on failure.
AnalyzeSearch(SearchParams * params)1635 bool DFA::AnalyzeSearch(SearchParams* params) {
1636 const StringPiece& text = params->text;
1637 const StringPiece& context = params->context;
1638
1639 // Sanity check: make sure that text lies within context.
1640 if (text.begin() < context.begin() || text.end() > context.end()) {
1641 LOG(DFATAL) << "context does not contain text";
1642 params->start = DeadState;
1643 return true;
1644 }
1645
1646 // Determine correct search type.
1647 int start;
1648 uint32_t flags;
1649 if (params->run_forward) {
1650 if (text.begin() == context.begin()) {
1651 start = kStartBeginText;
1652 flags = kEmptyBeginText|kEmptyBeginLine;
1653 } else if (text.begin()[-1] == '\n') {
1654 start = kStartBeginLine;
1655 flags = kEmptyBeginLine;
1656 } else if (Prog::IsWordChar(text.begin()[-1] & 0xFF)) {
1657 start = kStartAfterWordChar;
1658 flags = kFlagLastWord;
1659 } else {
1660 start = kStartAfterNonWordChar;
1661 flags = 0;
1662 }
1663 } else {
1664 if (text.end() == context.end()) {
1665 start = kStartBeginText;
1666 flags = kEmptyBeginText|kEmptyBeginLine;
1667 } else if (text.end()[0] == '\n') {
1668 start = kStartBeginLine;
1669 flags = kEmptyBeginLine;
1670 } else if (Prog::IsWordChar(text.end()[0] & 0xFF)) {
1671 start = kStartAfterWordChar;
1672 flags = kFlagLastWord;
1673 } else {
1674 start = kStartAfterNonWordChar;
1675 flags = 0;
1676 }
1677 }
1678 if (params->anchored)
1679 start |= kStartAnchored;
1680 StartInfo* info = &start_[start];
1681
1682 // Try once without cache_lock for writing.
1683 // Try again after resetting the cache
1684 // (ResetCache will relock cache_lock for writing).
1685 if (!AnalyzeSearchHelper(params, info, flags)) {
1686 ResetCache(params->cache_lock);
1687 if (!AnalyzeSearchHelper(params, info, flags)) {
1688 LOG(DFATAL) << "Failed to analyze start state.";
1689 params->failed = true;
1690 return false;
1691 }
1692 }
1693
1694 if (ExtraDebug)
1695 fprintf(stderr, "anchored=%d fwd=%d flags=%#x state=%s first_byte=%d\n",
1696 params->anchored, params->run_forward, flags,
1697 DumpState(info->start).c_str(), info->first_byte.load());
1698
1699 params->start = info->start;
1700 params->first_byte = info->first_byte.load(std::memory_order_acquire);
1701
1702 return true;
1703 }
1704
1705 // Fills in info if needed. Returns true on success, false on failure.
AnalyzeSearchHelper(SearchParams * params,StartInfo * info,uint32_t flags)1706 bool DFA::AnalyzeSearchHelper(SearchParams* params, StartInfo* info,
1707 uint32_t flags) {
1708 // Quick check.
1709 int fb = info->first_byte.load(std::memory_order_acquire);
1710 if (fb != kFbUnknown)
1711 return true;
1712
1713 MutexLock l(&mutex_);
1714 fb = info->first_byte.load(std::memory_order_relaxed);
1715 if (fb != kFbUnknown)
1716 return true;
1717
1718 q0_->clear();
1719 AddToQueue(q0_,
1720 params->anchored ? prog_->start() : prog_->start_unanchored(),
1721 flags);
1722 info->start = WorkqToCachedState(q0_, NULL, flags);
1723 if (info->start == NULL)
1724 return false;
1725
1726 if (info->start == DeadState) {
1727 // Synchronize with "quick check" above.
1728 info->first_byte.store(kFbNone, std::memory_order_release);
1729 return true;
1730 }
1731
1732 if (info->start == FullMatchState) {
1733 // Synchronize with "quick check" above.
1734 info->first_byte.store(kFbNone, std::memory_order_release); // will be ignored
1735 return true;
1736 }
1737
1738 // Even if we have a first_byte, we cannot use it when anchored and,
1739 // less obviously, we cannot use it when we are going to need flags.
1740 // This trick works only when there is a single byte that leads to a
1741 // different state!
1742 int first_byte = prog_->first_byte();
1743 if (first_byte == -1 ||
1744 params->anchored ||
1745 info->start->flag_ >> kFlagNeedShift != 0)
1746 first_byte = kFbNone;
1747
1748 // Synchronize with "quick check" above.
1749 info->first_byte.store(first_byte, std::memory_order_release);
1750 return true;
1751 }
1752
1753 // The actual DFA search: calls AnalyzeSearch and then FastSearchLoop.
Search(const StringPiece & text,const StringPiece & context,bool anchored,bool want_earliest_match,bool run_forward,bool * failed,const char ** epp,SparseSet * matches)1754 bool DFA::Search(const StringPiece& text,
1755 const StringPiece& context,
1756 bool anchored,
1757 bool want_earliest_match,
1758 bool run_forward,
1759 bool* failed,
1760 const char** epp,
1761 SparseSet* matches) {
1762 *epp = NULL;
1763 if (!ok()) {
1764 *failed = true;
1765 return false;
1766 }
1767 *failed = false;
1768
1769 if (ExtraDebug) {
1770 fprintf(stderr, "\nprogram:\n%s\n", prog_->DumpUnanchored().c_str());
1771 fprintf(stderr, "text %s anchored=%d earliest=%d fwd=%d kind %d\n",
1772 string(text).c_str(), anchored, want_earliest_match,
1773 run_forward, kind_);
1774 }
1775
1776 RWLocker l(&cache_mutex_);
1777 SearchParams params(text, context, &l);
1778 params.anchored = anchored;
1779 params.want_earliest_match = want_earliest_match;
1780 params.run_forward = run_forward;
1781 params.matches = matches;
1782
1783 if (!AnalyzeSearch(¶ms)) {
1784 *failed = true;
1785 return false;
1786 }
1787 if (params.start == DeadState)
1788 return false;
1789 if (params.start == FullMatchState) {
1790 if (run_forward == want_earliest_match)
1791 *epp = text.begin();
1792 else
1793 *epp = text.end();
1794 return true;
1795 }
1796 if (ExtraDebug)
1797 fprintf(stderr, "start %s\n", DumpState(params.start).c_str());
1798 bool ret = FastSearchLoop(¶ms);
1799 if (params.failed) {
1800 *failed = true;
1801 return false;
1802 }
1803 *epp = params.ep;
1804 return ret;
1805 }
1806
GetDFA(MatchKind kind)1807 DFA* Prog::GetDFA(MatchKind kind) {
1808 // For a forward DFA, half the memory goes to each DFA.
1809 // However, if it is a "many match" DFA, then there is
1810 // no counterpart with which the memory must be shared.
1811 //
1812 // For a reverse DFA, all the memory goes to the
1813 // "longest match" DFA, because RE2 never does reverse
1814 // "first match" searches.
1815 if (kind == kFirstMatch) {
1816 std::call_once(dfa_first_once_, [](Prog* prog) {
1817 prog->dfa_first_ = new DFA(prog, kFirstMatch, prog->dfa_mem_ / 2);
1818 }, this);
1819 return dfa_first_;
1820 } else if (kind == kManyMatch) {
1821 std::call_once(dfa_first_once_, [](Prog* prog) {
1822 prog->dfa_first_ = new DFA(prog, kManyMatch, prog->dfa_mem_);
1823 }, this);
1824 return dfa_first_;
1825 } else {
1826 std::call_once(dfa_longest_once_, [](Prog* prog) {
1827 if (!prog->reversed_)
1828 prog->dfa_longest_ = new DFA(prog, kLongestMatch, prog->dfa_mem_ / 2);
1829 else
1830 prog->dfa_longest_ = new DFA(prog, kLongestMatch, prog->dfa_mem_);
1831 }, this);
1832 return dfa_longest_;
1833 }
1834 }
1835
DeleteDFA(DFA * dfa)1836 void Prog::DeleteDFA(DFA* dfa) {
1837 delete dfa;
1838 }
1839
1840 // Executes the regexp program to search in text,
1841 // which itself is inside the larger context. (As a convenience,
1842 // passing a NULL context is equivalent to passing text.)
1843 // Returns true if a match is found, false if not.
1844 // If a match is found, fills in match0->end() to point at the end of the match
1845 // and sets match0->begin() to text.begin(), since the DFA can't track
1846 // where the match actually began.
1847 //
1848 // This is the only external interface (class DFA only exists in this file).
1849 //
SearchDFA(const StringPiece & text,const StringPiece & const_context,Anchor anchor,MatchKind kind,StringPiece * match0,bool * failed,SparseSet * matches)1850 bool Prog::SearchDFA(const StringPiece& text, const StringPiece& const_context,
1851 Anchor anchor, MatchKind kind, StringPiece* match0,
1852 bool* failed, SparseSet* matches) {
1853 *failed = false;
1854
1855 StringPiece context = const_context;
1856 if (context.begin() == NULL)
1857 context = text;
1858 bool carat = anchor_start();
1859 bool dollar = anchor_end();
1860 if (reversed_) {
1861 using std::swap;
1862 swap(carat, dollar);
1863 }
1864 if (carat && context.begin() != text.begin())
1865 return false;
1866 if (dollar && context.end() != text.end())
1867 return false;
1868
1869 // Handle full match by running an anchored longest match
1870 // and then checking if it covers all of text.
1871 bool anchored = anchor == kAnchored || anchor_start() || kind == kFullMatch;
1872 bool endmatch = false;
1873 if (kind == kManyMatch) {
1874 // This is split out in order to avoid clobbering kind.
1875 } else if (kind == kFullMatch || anchor_end()) {
1876 endmatch = true;
1877 kind = kLongestMatch;
1878 }
1879
1880 // If the caller doesn't care where the match is (just whether one exists),
1881 // then we can stop at the very first match we find, the so-called
1882 // "earliest match".
1883 bool want_earliest_match = false;
1884 if (kind == kManyMatch) {
1885 // This is split out in order to avoid clobbering kind.
1886 if (matches == NULL) {
1887 want_earliest_match = true;
1888 }
1889 } else if (match0 == NULL && !endmatch) {
1890 want_earliest_match = true;
1891 kind = kLongestMatch;
1892 }
1893
1894 DFA* dfa = GetDFA(kind);
1895 const char* ep;
1896 bool matched = dfa->Search(text, context, anchored,
1897 want_earliest_match, !reversed_,
1898 failed, &ep, matches);
1899 if (*failed)
1900 return false;
1901 if (!matched)
1902 return false;
1903 if (endmatch && ep != (reversed_ ? text.begin() : text.end()))
1904 return false;
1905
1906 // If caller cares, record the boundary of the match.
1907 // We only know where it ends, so use the boundary of text
1908 // as the beginning.
1909 if (match0) {
1910 if (reversed_)
1911 *match0 = StringPiece(ep, static_cast<size_t>(text.end() - ep));
1912 else
1913 *match0 =
1914 StringPiece(text.begin(), static_cast<size_t>(ep - text.begin()));
1915 }
1916 return true;
1917 }
1918
1919 // Build out all states in DFA. Returns number of states.
BuildAllStates(const Prog::DFAStateCallback & cb)1920 int DFA::BuildAllStates(const Prog::DFAStateCallback& cb) {
1921 if (!ok())
1922 return 0;
1923
1924 // Pick out start state for unanchored search
1925 // at beginning of text.
1926 RWLocker l(&cache_mutex_);
1927 SearchParams params(StringPiece(), StringPiece(), &l);
1928 params.anchored = false;
1929 if (!AnalyzeSearch(¶ms) ||
1930 params.start == NULL ||
1931 params.start == DeadState)
1932 return 0;
1933
1934 // Add start state to work queue.
1935 // Note that any State* that we handle here must point into the cache,
1936 // so we can simply depend on pointer-as-a-number hashing and equality.
1937 std::unordered_map<State*, int> m;
1938 std::deque<State*> q;
1939 m.emplace(params.start, static_cast<int>(m.size()));
1940 q.push_back(params.start);
1941
1942 // Compute the input bytes needed to cover all of the next pointers.
1943 int nnext = prog_->bytemap_range() + 1; // + 1 for kByteEndText slot
1944 std::vector<int> input(nnext);
1945 for (int c = 0; c < 256; c++) {
1946 int b = prog_->bytemap()[c];
1947 while (c < 256-1 && prog_->bytemap()[c+1] == b)
1948 c++;
1949 input[b] = c;
1950 }
1951 input[prog_->bytemap_range()] = kByteEndText;
1952
1953 // Scratch space for the output.
1954 std::vector<int> output(nnext);
1955
1956 // Flood to expand every state.
1957 bool oom = false;
1958 while (!q.empty()) {
1959 State* s = q.front();
1960 q.pop_front();
1961 for (int c : input) {
1962 State* ns = RunStateOnByteUnlocked(s, c);
1963 if (ns == NULL) {
1964 oom = true;
1965 break;
1966 }
1967 if (ns == DeadState) {
1968 output[ByteMap(c)] = -1;
1969 continue;
1970 }
1971 if (m.find(ns) == m.end()) {
1972 m.emplace(ns, static_cast<int>(m.size()));
1973 q.push_back(ns);
1974 }
1975 output[ByteMap(c)] = m[ns];
1976 }
1977 if (cb)
1978 cb(oom ? NULL : output.data(),
1979 s == FullMatchState || s->IsMatch());
1980 if (oom)
1981 break;
1982 }
1983
1984 return static_cast<int>(m.size());
1985 }
1986
1987 // Build out all states in DFA for kind. Returns number of states.
BuildEntireDFA(MatchKind kind,const DFAStateCallback & cb)1988 int Prog::BuildEntireDFA(MatchKind kind, const DFAStateCallback& cb) {
1989 return GetDFA(kind)->BuildAllStates(cb);
1990 }
1991
TEST_dfa_should_bail_when_slow(bool b)1992 void Prog::TEST_dfa_should_bail_when_slow(bool b) {
1993 dfa_should_bail_when_slow = b;
1994 }
1995
1996 // Computes min and max for matching string.
1997 // Won't return strings bigger than maxlen.
PossibleMatchRange(string * min,string * max,int maxlen)1998 bool DFA::PossibleMatchRange(string* min, string* max, int maxlen) {
1999 if (!ok())
2000 return false;
2001
2002 // NOTE: if future users of PossibleMatchRange want more precision when
2003 // presented with infinitely repeated elements, consider making this a
2004 // parameter to PossibleMatchRange.
2005 static int kMaxEltRepetitions = 0;
2006
2007 // Keep track of the number of times we've visited states previously. We only
2008 // revisit a given state if it's part of a repeated group, so if the value
2009 // portion of the map tuple exceeds kMaxEltRepetitions we bail out and set
2010 // |*max| to |PrefixSuccessor(*max)|.
2011 //
2012 // Also note that previously_visited_states[UnseenStatePtr] will, in the STL
2013 // tradition, implicitly insert a '0' value at first use. We take advantage
2014 // of that property below.
2015 std::unordered_map<State*, int> previously_visited_states;
2016
2017 // Pick out start state for anchored search at beginning of text.
2018 RWLocker l(&cache_mutex_);
2019 SearchParams params(StringPiece(), StringPiece(), &l);
2020 params.anchored = true;
2021 if (!AnalyzeSearch(¶ms))
2022 return false;
2023 if (params.start == DeadState) { // No matching strings
2024 *min = "";
2025 *max = "";
2026 return true;
2027 }
2028 if (params.start == FullMatchState) // Every string matches: no max
2029 return false;
2030
2031 // The DFA is essentially a big graph rooted at params.start,
2032 // and paths in the graph correspond to accepted strings.
2033 // Each node in the graph has potentially 256+1 arrows
2034 // coming out, one for each byte plus the magic end of
2035 // text character kByteEndText.
2036
2037 // To find the smallest possible prefix of an accepted
2038 // string, we just walk the graph preferring to follow
2039 // arrows with the lowest bytes possible. To find the
2040 // largest possible prefix, we follow the largest bytes
2041 // possible.
2042
2043 // The test for whether there is an arrow from s on byte j is
2044 // ns = RunStateOnByteUnlocked(s, j);
2045 // if (ns == NULL)
2046 // return false;
2047 // if (ns != DeadState && ns->ninst > 0)
2048 // The RunStateOnByteUnlocked call asks the DFA to build out the graph.
2049 // It returns NULL only if the DFA has run out of memory,
2050 // in which case we can't be sure of anything.
2051 // The second check sees whether there was graph built
2052 // and whether it is interesting graph. Nodes might have
2053 // ns->ninst == 0 if they exist only to represent the fact
2054 // that a match was found on the previous byte.
2055
2056 // Build minimum prefix.
2057 State* s = params.start;
2058 min->clear();
2059 MutexLock lock(&mutex_);
2060 for (int i = 0; i < maxlen; i++) {
2061 if (previously_visited_states[s] > kMaxEltRepetitions)
2062 break;
2063 previously_visited_states[s]++;
2064
2065 // Stop if min is a match.
2066 State* ns = RunStateOnByte(s, kByteEndText);
2067 if (ns == NULL) // DFA out of memory
2068 return false;
2069 if (ns != DeadState && (ns == FullMatchState || ns->IsMatch()))
2070 break;
2071
2072 // Try to extend the string with low bytes.
2073 bool extended = false;
2074 for (int j = 0; j < 256; j++) {
2075 ns = RunStateOnByte(s, j);
2076 if (ns == NULL) // DFA out of memory
2077 return false;
2078 if (ns == FullMatchState ||
2079 (ns > SpecialStateMax && ns->ninst_ > 0)) {
2080 extended = true;
2081 min->append(1, static_cast<char>(j));
2082 s = ns;
2083 break;
2084 }
2085 }
2086 if (!extended)
2087 break;
2088 }
2089
2090 // Build maximum prefix.
2091 previously_visited_states.clear();
2092 s = params.start;
2093 max->clear();
2094 for (int i = 0; i < maxlen; i++) {
2095 if (previously_visited_states[s] > kMaxEltRepetitions)
2096 break;
2097 previously_visited_states[s] += 1;
2098
2099 // Try to extend the string with high bytes.
2100 bool extended = false;
2101 for (int j = 255; j >= 0; j--) {
2102 State* ns = RunStateOnByte(s, j);
2103 if (ns == NULL)
2104 return false;
2105 if (ns == FullMatchState ||
2106 (ns > SpecialStateMax && ns->ninst_ > 0)) {
2107 extended = true;
2108 max->append(1, static_cast<char>(j));
2109 s = ns;
2110 break;
2111 }
2112 }
2113 if (!extended) {
2114 // Done, no need for PrefixSuccessor.
2115 return true;
2116 }
2117 }
2118
2119 // Stopped while still adding to *max - round aaaaaaaaaa... to aaaa...b
2120 PrefixSuccessor(max);
2121
2122 // If there are no bytes left, we have no way to say "there is no maximum
2123 // string". We could make the interface more complicated and be able to
2124 // return "there is no maximum but here is a minimum", but that seems like
2125 // overkill -- the most common no-max case is all possible strings, so not
2126 // telling the caller that the empty string is the minimum match isn't a
2127 // great loss.
2128 if (max->empty())
2129 return false;
2130
2131 return true;
2132 }
2133
2134 // PossibleMatchRange for a Prog.
PossibleMatchRange(string * min,string * max,int maxlen)2135 bool Prog::PossibleMatchRange(string* min, string* max, int maxlen) {
2136 // Have to use dfa_longest_ to get all strings for full matches.
2137 // For example, (a|aa) never matches aa in first-match mode.
2138 return GetDFA(kLongestMatch)->PossibleMatchRange(min, max, maxlen);
2139 }
2140
2141 } // namespace re2
2142