Coverage Report

Created: 2026-05-27 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/external/re2~/re2/re2.cc
Line
Count
Source
1
// Copyright 2003-2009 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
// Regular expression interface RE2.
6
//
7
// Originally the PCRE C++ wrapper, but adapted to use
8
// the new automata-based regular expression engines.
9
10
#include "re2/re2.h"
11
12
#include <errno.h>
13
#include <stddef.h>
14
#include <stdint.h>
15
#include <stdlib.h>
16
#include <string.h>
17
18
#include <algorithm>
19
#include <atomic>
20
#include <map>
21
#include <string>
22
#include <utility>
23
#include <vector>
24
25
#include "absl/base/call_once.h"
26
#include "absl/base/macros.h"
27
#include "absl/container/fixed_array.h"
28
#include "absl/log/absl_check.h"
29
#include "absl/log/absl_log.h"
30
#include "absl/strings/ascii.h"
31
#include "absl/strings/str_format.h"
32
#include "absl/strings/string_view.h"
33
#include "re2/prog.h"
34
#include "re2/regexp.h"
35
#include "re2/sparse_array.h"
36
#include "util/strutil.h"
37
#include "util/utf.h"
38
39
#ifdef _MSC_VER
40
#include <intrin.h>
41
#endif
42
43
namespace re2 {
44
45
// Controls the maximum count permitted by GlobalReplace(); -1 is unlimited.
46
static int maximum_global_replace_count = -1;
47
48
0
void RE2::FUZZING_ONLY_set_maximum_global_replace_count(int i) {
49
0
  maximum_global_replace_count = i;
50
0
}
51
52
// Maximum number of args we can set
53
static const int kMaxArgs = 16;
54
static const int kVecSize = 1+kMaxArgs;
55
56
const int RE2::Options::kDefaultMaxMem;  // initialized in re2.h
57
58
RE2::Options::Options(RE2::CannedOptions opt)
59
0
  : max_mem_(kDefaultMaxMem),
60
0
    encoding_(opt == RE2::Latin1 ? EncodingLatin1 : EncodingUTF8),
61
0
    posix_syntax_(opt == RE2::POSIX),
62
0
    longest_match_(opt == RE2::POSIX),
63
0
    log_errors_(opt != RE2::Quiet),
64
0
    literal_(false),
65
0
    never_nl_(false),
66
0
    dot_nl_(false),
67
0
    never_capture_(false),
68
0
    case_sensitive_(true),
69
0
    perl_classes_(false),
70
0
    word_boundary_(false),
71
0
    one_line_(false) {
72
0
}
73
74
// Empty objects for use as const references.
75
// Statically allocating the storage and then
76
// lazily constructing the objects (in a once
77
// in RE2::Init()) avoids global constructors
78
// and the false positives (thanks, Valgrind)
79
// about memory leaks at program termination.
80
struct EmptyStorage {
81
  std::string empty_string;
82
  std::map<std::string, int> empty_named_groups;
83
  std::map<int, std::string> empty_group_names;
84
};
85
alignas(EmptyStorage) static char empty_storage[sizeof(EmptyStorage)];
86
87
0
static inline std::string* empty_string() {
88
0
  return &reinterpret_cast<EmptyStorage*>(empty_storage)->empty_string;
89
0
}
90
91
0
static inline std::map<std::string, int>* empty_named_groups() {
92
0
  return &reinterpret_cast<EmptyStorage*>(empty_storage)->empty_named_groups;
93
0
}
94
95
0
static inline std::map<int, std::string>* empty_group_names() {
96
0
  return &reinterpret_cast<EmptyStorage*>(empty_storage)->empty_group_names;
97
0
}
98
99
// Converts from Regexp error code to RE2 error code.
100
// Maybe some day they will diverge.  In any event, this
101
// hides the existence of Regexp from RE2 users.
102
0
static RE2::ErrorCode RegexpErrorToRE2(re2::RegexpStatusCode code) {
103
0
  switch (code) {
104
0
    case re2::kRegexpSuccess:
105
0
      return RE2::NoError;
106
0
    case re2::kRegexpInternalError:
107
0
      return RE2::ErrorInternal;
108
0
    case re2::kRegexpBadEscape:
109
0
      return RE2::ErrorBadEscape;
110
0
    case re2::kRegexpBadCharClass:
111
0
      return RE2::ErrorBadCharClass;
112
0
    case re2::kRegexpBadCharRange:
113
0
      return RE2::ErrorBadCharRange;
114
0
    case re2::kRegexpMissingBracket:
115
0
      return RE2::ErrorMissingBracket;
116
0
    case re2::kRegexpMissingParen:
117
0
      return RE2::ErrorMissingParen;
118
0
    case re2::kRegexpUnexpectedParen:
119
0
      return RE2::ErrorUnexpectedParen;
120
0
    case re2::kRegexpTrailingBackslash:
121
0
      return RE2::ErrorTrailingBackslash;
122
0
    case re2::kRegexpRepeatArgument:
123
0
      return RE2::ErrorRepeatArgument;
124
0
    case re2::kRegexpRepeatSize:
125
0
      return RE2::ErrorRepeatSize;
126
0
    case re2::kRegexpRepeatOp:
127
0
      return RE2::ErrorRepeatOp;
128
0
    case re2::kRegexpBadPerlOp:
129
0
      return RE2::ErrorBadPerlOp;
130
0
    case re2::kRegexpBadUTF8:
131
0
      return RE2::ErrorBadUTF8;
132
0
    case re2::kRegexpBadNamedCapture:
133
0
      return RE2::ErrorBadNamedCapture;
134
0
  }
135
0
  return RE2::ErrorInternal;
136
0
}
137
138
0
static std::string trunc(absl::string_view pattern) {
139
0
  if (pattern.size() < 100)
140
0
    return std::string(pattern);
141
0
  return std::string(pattern.substr(0, 100)) + "...";
142
0
}
143
144
145
0
RE2::RE2(const char* pattern) {
146
  // If absl::string_view becomes an alias for std::string_view,
147
  // it will stop allowing NULL to be converted.
148
  // Handle NULL explicitly to keep callers working no matter what.
149
0
  if (pattern == NULL)
150
0
    pattern = "";
151
0
  Init(pattern, DefaultOptions);
152
0
}
153
154
0
RE2::RE2(const std::string& pattern) {
155
0
  Init(pattern, DefaultOptions);
156
0
}
157
158
0
RE2::RE2(absl::string_view pattern) {
159
0
  Init(pattern, DefaultOptions);
160
0
}
161
162
0
RE2::RE2(absl::string_view pattern, const Options& options) {
163
0
  Init(pattern, options);
164
0
}
165
166
0
int RE2::Options::ParseFlags() const {
167
0
  int flags = Regexp::ClassNL;
168
0
  switch (encoding()) {
169
0
    default:
170
0
      if (log_errors())
171
0
        ABSL_LOG(ERROR) << "Unknown encoding " << encoding();
172
0
      break;
173
0
    case RE2::Options::EncodingUTF8:
174
0
      break;
175
0
    case RE2::Options::EncodingLatin1:
176
0
      flags |= Regexp::Latin1;
177
0
      break;
178
0
  }
179
180
0
  if (!posix_syntax())
181
0
    flags |= Regexp::LikePerl;
182
183
0
  if (literal())
184
0
    flags |= Regexp::Literal;
185
186
0
  if (never_nl())
187
0
    flags |= Regexp::NeverNL;
188
189
0
  if (dot_nl())
190
0
    flags |= Regexp::DotNL;
191
192
0
  if (never_capture())
193
0
    flags |= Regexp::NeverCapture;
194
195
0
  if (!case_sensitive())
196
0
    flags |= Regexp::FoldCase;
197
198
0
  if (perl_classes())
199
0
    flags |= Regexp::PerlClasses;
200
201
0
  if (word_boundary())
202
0
    flags |= Regexp::PerlB;
203
204
0
  if (one_line())
205
0
    flags |= Regexp::OneLine;
206
207
0
  return flags;
208
0
}
209
210
0
void RE2::Init(absl::string_view pattern, const Options& options) {
211
0
  static absl::once_flag empty_once;
212
0
  absl::call_once(empty_once, []() {
213
0
    (void) new (empty_storage) EmptyStorage;
214
0
  });
215
216
0
  pattern_ = new std::string(pattern);
217
0
  options_.Copy(options);
218
0
  entire_regexp_ = NULL;
219
0
  suffix_regexp_ = NULL;
220
0
  error_ = empty_string();
221
0
  error_arg_ = empty_string();
222
223
0
  num_captures_ = -1;
224
0
  error_code_ = NoError;
225
0
  longest_match_ = options_.longest_match();
226
0
  is_one_pass_ = false;
227
0
  prefix_foldcase_ = false;
228
0
  prefix_.clear();
229
0
  prog_ = NULL;
230
231
0
  rprog_ = NULL;
232
0
  named_groups_ = NULL;
233
0
  group_names_ = NULL;
234
235
0
  RegexpStatus status;
236
0
  entire_regexp_ = Regexp::Parse(
237
0
    *pattern_,
238
0
    static_cast<Regexp::ParseFlags>(options_.ParseFlags()),
239
0
    &status);
240
0
  if (entire_regexp_ == NULL) {
241
0
    if (options_.log_errors()) {
242
0
      ABSL_LOG(ERROR) << "Error parsing '" << trunc(*pattern_) << "': "
243
0
                      << status.Text();
244
0
    }
245
0
    error_ = new std::string(status.Text());
246
0
    error_code_ = RegexpErrorToRE2(status.code());
247
0
    error_arg_ = new std::string(status.error_arg());
248
0
    return;
249
0
  }
250
251
0
  bool foldcase;
252
0
  re2::Regexp* suffix;
253
0
  if (entire_regexp_->RequiredPrefix(&prefix_, &foldcase, &suffix)) {
254
0
    prefix_foldcase_ = foldcase;
255
0
    suffix_regexp_ = suffix;
256
0
  }
257
0
  else {
258
0
    suffix_regexp_ = entire_regexp_->Incref();
259
0
  }
260
261
  // Two thirds of the memory goes to the forward Prog,
262
  // one third to the reverse prog, because the forward
263
  // Prog has two DFAs but the reverse prog has one.
264
0
  prog_ = suffix_regexp_->CompileToProg(options_.max_mem()*2/3);
265
0
  if (prog_ == NULL) {
266
0
    if (options_.log_errors())
267
0
      ABSL_LOG(ERROR) << "Error compiling '" << trunc(*pattern_) << "'";
268
0
    error_ = new std::string("pattern too large - compile failed");
269
0
    error_code_ = RE2::ErrorPatternTooLarge;
270
0
    return;
271
0
  }
272
273
  // We used to compute this lazily, but it's used during the
274
  // typical control flow for a match call, so we now compute
275
  // it eagerly, which avoids the overhead of absl::once_flag.
276
0
  num_captures_ = suffix_regexp_->NumCaptures();
277
278
  // Could delay this until the first match call that
279
  // cares about submatch information, but the one-pass
280
  // machine's memory gets cut from the DFA memory budget,
281
  // and that is harder to do if the DFA has already
282
  // been built.
283
0
  is_one_pass_ = prog_->IsOnePass();
284
0
}
285
286
// Returns rprog_, computing it if needed.
287
0
re2::Prog* RE2::ReverseProg() const {
288
0
  absl::call_once(rprog_once_, [](const RE2* re) {
289
0
    re->rprog_ =
290
0
        re->suffix_regexp_->CompileToReverseProg(re->options_.max_mem() / 3);
291
0
    if (re->rprog_ == NULL) {
292
0
      if (re->options_.log_errors())
293
0
        ABSL_LOG(ERROR) << "Error reverse compiling '" << trunc(*re->pattern_)
294
0
                        << "'";
295
      // We no longer touch error_ and error_code_ because failing to compile
296
      // the reverse Prog is not a showstopper: falling back to NFA execution
297
      // is fine. More importantly, an RE2 object is supposed to be logically
298
      // immutable: whatever ok() would have returned after Init() completed,
299
      // it should continue to return that no matter what ReverseProg() does.
300
0
    }
301
0
  }, this);
302
0
  return rprog_;
303
0
}
304
305
0
RE2::~RE2() {
306
0
  if (group_names_ != empty_group_names())
307
0
    delete group_names_;
308
0
  if (named_groups_ != empty_named_groups())
309
0
    delete named_groups_;
310
0
  delete rprog_;
311
0
  delete prog_;
312
0
  if (error_arg_ != empty_string())
313
0
    delete error_arg_;
314
0
  if (error_ != empty_string())
315
0
    delete error_;
316
0
  if (suffix_regexp_)
317
0
    suffix_regexp_->Decref();
318
0
  if (entire_regexp_)
319
0
    entire_regexp_->Decref();
320
0
  delete pattern_;
321
0
}
322
323
0
int RE2::ProgramSize() const {
324
0
  if (prog_ == NULL)
325
0
    return -1;
326
0
  return prog_->size();
327
0
}
328
329
0
int RE2::ReverseProgramSize() const {
330
0
  if (prog_ == NULL)
331
0
    return -1;
332
0
  Prog* prog = ReverseProg();
333
0
  if (prog == NULL)
334
0
    return -1;
335
0
  return prog->size();
336
0
}
337
338
// Finds the most significant non-zero bit in n.
339
static int FindMSBSet(uint32_t n) {
340
  ABSL_DCHECK_NE(n, uint32_t{0});
341
#if defined(__GNUC__)
342
  return 31 ^ __builtin_clz(n);
343
#elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
344
  unsigned long c;
345
  _BitScanReverse(&c, n);
346
  return static_cast<int>(c);
347
#else
348
  int c = 0;
349
  for (int shift = 1 << 4; shift != 0; shift >>= 1) {
350
    uint32_t word = n >> shift;
351
    if (word != 0) {
352
      n = word;
353
      c += shift;
354
    }
355
  }
356
  return c;
357
#endif
358
}
359
360
0
static int Fanout(Prog* prog, std::vector<int>* histogram) {
361
0
  SparseArray<int> fanout(prog->size());
362
0
  prog->Fanout(&fanout);
363
0
  int data[32] = {};
364
0
  int size = 0;
365
0
  for (SparseArray<int>::iterator i = fanout.begin(); i != fanout.end(); ++i) {
366
0
    if (i->value() == 0)
367
0
      continue;
368
0
    uint32_t value = i->value();
369
0
    int bucket = FindMSBSet(value);
370
0
    bucket += value & (value-1) ? 1 : 0;
371
0
    ++data[bucket];
372
0
    size = std::max(size, bucket+1);
373
0
  }
374
0
  if (histogram != NULL)
375
0
    histogram->assign(data, data+size);
376
0
  return size-1;
377
0
}
378
379
0
int RE2::ProgramFanout(std::vector<int>* histogram) const {
380
0
  if (prog_ == NULL)
381
0
    return -1;
382
0
  return Fanout(prog_, histogram);
383
0
}
384
385
0
int RE2::ReverseProgramFanout(std::vector<int>* histogram) const {
386
0
  if (prog_ == NULL)
387
0
    return -1;
388
0
  Prog* prog = ReverseProg();
389
0
  if (prog == NULL)
390
0
    return -1;
391
0
  return Fanout(prog, histogram);
392
0
}
393
394
// Returns named_groups_, computing it if needed.
395
0
const std::map<std::string, int>& RE2::NamedCapturingGroups() const {
396
0
  absl::call_once(named_groups_once_, [](const RE2* re) {
397
0
    if (re->suffix_regexp_ != NULL)
398
0
      re->named_groups_ = re->suffix_regexp_->NamedCaptures();
399
0
    if (re->named_groups_ == NULL)
400
0
      re->named_groups_ = empty_named_groups();
401
0
  }, this);
402
0
  return *named_groups_;
403
0
}
404
405
// Returns group_names_, computing it if needed.
406
0
const std::map<int, std::string>& RE2::CapturingGroupNames() const {
407
0
  absl::call_once(group_names_once_, [](const RE2* re) {
408
0
    if (re->suffix_regexp_ != NULL)
409
0
      re->group_names_ = re->suffix_regexp_->CaptureNames();
410
0
    if (re->group_names_ == NULL)
411
0
      re->group_names_ = empty_group_names();
412
0
  }, this);
413
0
  return *group_names_;
414
0
}
415
416
/***** Convenience interfaces *****/
417
418
bool RE2::FullMatchN(absl::string_view text, const RE2& re,
419
0
                     const Arg* const args[], int n) {
420
0
  return re.DoMatch(text, ANCHOR_BOTH, NULL, args, n);
421
0
}
422
423
bool RE2::PartialMatchN(absl::string_view text, const RE2& re,
424
0
                        const Arg* const args[], int n) {
425
0
  return re.DoMatch(text, UNANCHORED, NULL, args, n);
426
0
}
427
428
bool RE2::ConsumeN(absl::string_view* input, const RE2& re,
429
0
                   const Arg* const args[], int n) {
430
0
  size_t consumed;
431
0
  if (re.DoMatch(*input, ANCHOR_START, &consumed, args, n)) {
432
0
    input->remove_prefix(consumed);
433
0
    return true;
434
0
  } else {
435
0
    return false;
436
0
  }
437
0
}
438
439
bool RE2::FindAndConsumeN(absl::string_view* input, const RE2& re,
440
0
                          const Arg* const args[], int n) {
441
0
  size_t consumed;
442
0
  if (re.DoMatch(*input, UNANCHORED, &consumed, args, n)) {
443
0
    input->remove_prefix(consumed);
444
0
    return true;
445
0
  } else {
446
0
    return false;
447
0
  }
448
0
}
449
450
bool RE2::Replace(std::string* str,
451
                  const RE2& re,
452
0
                  absl::string_view rewrite) {
453
0
  absl::string_view vec[kVecSize];
454
0
  int nvec = 1 + MaxSubmatch(rewrite);
455
0
  if (nvec > 1 + re.NumberOfCapturingGroups())
456
0
    return false;
457
0
  if (nvec > static_cast<int>(ABSL_ARRAYSIZE(vec)))
458
0
    return false;
459
0
  if (!re.Match(*str, 0, str->size(), UNANCHORED, vec, nvec))
460
0
    return false;
461
462
0
  std::string s;
463
0
  if (!re.Rewrite(&s, rewrite, vec, nvec))
464
0
    return false;
465
466
0
  ABSL_DCHECK_GE(vec[0].data(), str->data());
467
0
  ABSL_DCHECK_LE(vec[0].data() + vec[0].size(), str->data() + str->size());
468
0
  str->replace(vec[0].data() - str->data(), vec[0].size(), s);
469
0
  return true;
470
0
}
471
472
int RE2::GlobalReplace(std::string* str,
473
                       const RE2& re,
474
0
                       absl::string_view rewrite) {
475
0
  absl::string_view vec[kVecSize];
476
0
  int nvec = 1 + MaxSubmatch(rewrite);
477
0
  if (nvec > 1 + re.NumberOfCapturingGroups())
478
0
    return false;
479
0
  if (nvec > static_cast<int>(ABSL_ARRAYSIZE(vec)))
480
0
    return false;
481
482
0
  const char* p = str->data();
483
0
  const char* ep = p + str->size();
484
0
  const char* lastend = NULL;
485
0
  std::string out;
486
0
  int count = 0;
487
0
  while (p <= ep) {
488
0
    if (maximum_global_replace_count != -1 &&
489
0
        count >= maximum_global_replace_count)
490
0
      break;
491
0
    if (!re.Match(*str, static_cast<size_t>(p - str->data()),
492
0
                  str->size(), UNANCHORED, vec, nvec))
493
0
      break;
494
0
    if (p < vec[0].data())
495
0
      out.append(p, vec[0].data() - p);
496
0
    if (vec[0].data() == lastend && vec[0].empty()) {
497
      // Disallow empty match at end of last match: skip ahead.
498
      //
499
      // fullrune() takes int, not ptrdiff_t. However, it just looks
500
      // at the leading byte and treats any length >= 4 the same.
501
0
      if (re.options().encoding() == RE2::Options::EncodingUTF8 &&
502
0
          fullrune(p, static_cast<int>(std::min(ptrdiff_t{4}, ep - p)))) {
503
        // re is in UTF-8 mode and there is enough left of str
504
        // to allow us to advance by up to UTFmax bytes.
505
0
        Rune r;
506
0
        int n = chartorune(&r, p);
507
        // Some copies of chartorune have a bug that accepts
508
        // encodings of values in (10FFFF, 1FFFFF] as valid.
509
0
        if (r > Runemax) {
510
0
          n = 1;
511
0
          r = Runeerror;
512
0
        }
513
0
        if (!(n == 1 && r == Runeerror)) {  // no decoding error
514
0
          out.append(p, n);
515
0
          p += n;
516
0
          continue;
517
0
        }
518
0
      }
519
      // Most likely, re is in Latin-1 mode. If it is in UTF-8 mode,
520
      // we fell through from above and the GIGO principle applies.
521
0
      if (p < ep)
522
0
        out.append(p, 1);
523
0
      p++;
524
0
      continue;
525
0
    }
526
0
    re.Rewrite(&out, rewrite, vec, nvec);
527
0
    p = vec[0].data() + vec[0].size();
528
0
    lastend = p;
529
0
    count++;
530
0
  }
531
532
0
  if (count == 0)
533
0
    return 0;
534
535
0
  if (p < ep)
536
0
    out.append(p, ep - p);
537
0
  using std::swap;
538
0
  swap(out, *str);
539
0
  return count;
540
0
}
541
542
bool RE2::Extract(absl::string_view text,
543
                  const RE2& re,
544
                  absl::string_view rewrite,
545
0
                  std::string* out) {
546
0
  absl::string_view vec[kVecSize];
547
0
  int nvec = 1 + MaxSubmatch(rewrite);
548
0
  if (nvec > 1 + re.NumberOfCapturingGroups())
549
0
    return false;
550
0
  if (nvec > static_cast<int>(ABSL_ARRAYSIZE(vec)))
551
0
    return false;
552
0
  if (!re.Match(text, 0, text.size(), UNANCHORED, vec, nvec))
553
0
    return false;
554
555
0
  out->clear();
556
0
  return re.Rewrite(out, rewrite, vec, nvec);
557
0
}
558
559
0
std::string RE2::QuoteMeta(absl::string_view unquoted) {
560
0
  std::string result;
561
0
  result.reserve(unquoted.size() << 1);
562
563
  // Escape any ascii character not in [A-Za-z_0-9].
564
  //
565
  // Note that it's legal to escape a character even if it has no
566
  // special meaning in a regular expression -- so this function does
567
  // that.  (This also makes it identical to the perl function of the
568
  // same name except for the null-character special case;
569
  // see `perldoc -f quotemeta`.)
570
0
  for (size_t ii = 0; ii < unquoted.size(); ++ii) {
571
    // Note that using 'isalnum' here raises the benchmark time from
572
    // 32ns to 58ns:
573
0
    if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
574
0
        (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
575
0
        (unquoted[ii] < '0' || unquoted[ii] > '9') &&
576
0
        unquoted[ii] != '_' &&
577
        // If this is the part of a UTF8 or Latin1 character, we need
578
        // to copy this byte without escaping.  Experimentally this is
579
        // what works correctly with the regexp library.
580
0
        !(unquoted[ii] & 128)) {
581
0
      if (unquoted[ii] == '\0') {  // Special handling for null chars.
582
        // Note that this special handling is not strictly required for RE2,
583
        // but this quoting is required for other regexp libraries such as
584
        // PCRE.
585
        // Can't use "\\0" since the next character might be a digit.
586
0
        result += "\\x00";
587
0
        continue;
588
0
      }
589
0
      result += '\\';
590
0
    }
591
0
    result += unquoted[ii];
592
0
  }
593
594
0
  return result;
595
0
}
596
597
bool RE2::PossibleMatchRange(std::string* min, std::string* max,
598
0
                             int maxlen) const {
599
0
  if (prog_ == NULL)
600
0
    return false;
601
602
0
  int n = static_cast<int>(prefix_.size());
603
0
  if (n > maxlen)
604
0
    n = maxlen;
605
606
  // Determine initial min max from prefix_ literal.
607
0
  *min = prefix_.substr(0, n);
608
0
  *max = prefix_.substr(0, n);
609
0
  if (prefix_foldcase_) {
610
    // prefix is ASCII lowercase; change *min to uppercase.
611
0
    for (int i = 0; i < n; i++) {
612
0
      char& c = (*min)[i];
613
0
      if ('a' <= c && c <= 'z')
614
0
        c += 'A' - 'a';
615
0
    }
616
0
  }
617
618
  // Add to prefix min max using PossibleMatchRange on regexp.
619
0
  std::string dmin, dmax;
620
0
  maxlen -= n;
621
0
  if (maxlen > 0 && prog_->PossibleMatchRange(&dmin, &dmax, maxlen)) {
622
0
    min->append(dmin);
623
0
    max->append(dmax);
624
0
  } else if (!max->empty()) {
625
    // prog_->PossibleMatchRange has failed us,
626
    // but we still have useful information from prefix_.
627
    // Round up *max to allow any possible suffix.
628
0
    PrefixSuccessor(max);
629
0
  } else {
630
    // Nothing useful.
631
0
    *min = "";
632
0
    *max = "";
633
0
    return false;
634
0
  }
635
636
0
  return true;
637
0
}
638
639
// Avoid possible locale nonsense in standard strcasecmp.
640
// The string a is known to be all lowercase.
641
0
static int ascii_strcasecmp(const char* a, const char* b, size_t len) {
642
0
  const char* ae = a + len;
643
644
0
  for (; a < ae; a++, b++) {
645
0
    uint8_t x = *a;
646
0
    uint8_t y = *b;
647
0
    if ('A' <= y && y <= 'Z')
648
0
      y += 'a' - 'A';
649
0
    if (x != y)
650
0
      return x - y;
651
0
  }
652
0
  return 0;
653
0
}
654
655
656
/***** Actual matching and rewriting code *****/
657
658
bool RE2::Match(absl::string_view text,
659
                size_t startpos,
660
                size_t endpos,
661
                Anchor re_anchor,
662
                absl::string_view* submatch,
663
0
                int nsubmatch) const {
664
0
  if (!ok()) {
665
0
    if (options_.log_errors())
666
0
      ABSL_LOG(ERROR) << "Invalid RE2: " << *error_;
667
0
    return false;
668
0
  }
669
670
0
  if (startpos > endpos || endpos > text.size()) {
671
0
    if (options_.log_errors())
672
0
      ABSL_LOG(ERROR) << "RE2: invalid startpos, endpos pair. ["
673
0
                      << "startpos: " << startpos << ", "
674
0
                      << "endpos: " << endpos << ", "
675
0
                      << "text size: " << text.size() << "]";
676
0
    return false;
677
0
  }
678
679
0
  absl::string_view subtext = text;
680
0
  subtext.remove_prefix(startpos);
681
0
  subtext.remove_suffix(text.size() - endpos);
682
683
  // Use DFAs to find exact location of match, filter out non-matches.
684
685
  // Don't ask for the location if we won't use it.
686
  // SearchDFA can do extra optimizations in that case.
687
0
  absl::string_view match;
688
0
  absl::string_view* matchp = &match;
689
0
  if (nsubmatch == 0)
690
0
    matchp = NULL;
691
692
0
  int ncap = 1 + NumberOfCapturingGroups();
693
0
  if (ncap > nsubmatch)
694
0
    ncap = nsubmatch;
695
696
  // If the regexp is anchored explicitly, must not be in middle of text.
697
0
  if (prog_->anchor_start() && startpos != 0)
698
0
    return false;
699
0
  if (prog_->anchor_end() && endpos != text.size())
700
0
    return false;
701
702
  // If the regexp is anchored explicitly, update re_anchor
703
  // so that we can potentially fall into a faster case below.
704
0
  if (prog_->anchor_start() && prog_->anchor_end())
705
0
    re_anchor = ANCHOR_BOTH;
706
0
  else if (prog_->anchor_start() && re_anchor != ANCHOR_BOTH)
707
0
    re_anchor = ANCHOR_START;
708
709
  // Check for the required prefix, if any.
710
0
  size_t prefixlen = 0;
711
0
  if (!prefix_.empty()) {
712
0
    if (startpos != 0)
713
0
      return false;
714
0
    prefixlen = prefix_.size();
715
0
    if (prefixlen > subtext.size())
716
0
      return false;
717
0
    if (prefix_foldcase_) {
718
0
      if (ascii_strcasecmp(&prefix_[0], subtext.data(), prefixlen) != 0)
719
0
        return false;
720
0
    } else {
721
0
      if (memcmp(&prefix_[0], subtext.data(), prefixlen) != 0)
722
0
        return false;
723
0
    }
724
0
    subtext.remove_prefix(prefixlen);
725
    // If there is a required prefix, the anchor must be at least ANCHOR_START.
726
0
    if (re_anchor != ANCHOR_BOTH)
727
0
      re_anchor = ANCHOR_START;
728
0
  }
729
730
0
  Prog::Anchor anchor = Prog::kUnanchored;
731
0
  Prog::MatchKind kind =
732
0
      longest_match_ ? Prog::kLongestMatch : Prog::kFirstMatch;
733
734
0
  bool can_one_pass = is_one_pass_ && ncap <= Prog::kMaxOnePassCapture;
735
0
  bool can_bit_state = prog_->CanBitState();
736
0
  size_t bit_state_text_max_size = prog_->bit_state_text_max_size();
737
738
0
#ifdef RE2_HAVE_THREAD_LOCAL
739
0
  hooks::context = this;
740
0
#endif
741
0
  bool dfa_failed = false;
742
0
  bool skipped_test = false;
743
0
  switch (re_anchor) {
744
0
    default:
745
0
      ABSL_LOG(DFATAL) << "Unexpected re_anchor value: " << re_anchor;
746
0
      return false;
747
748
0
    case UNANCHORED: {
749
0
      if (prog_->anchor_end()) {
750
        // This is a very special case: we don't need the forward DFA because
751
        // we already know where the match must end! Instead, the reverse DFA
752
        // can say whether there is a match and (optionally) where it starts.
753
0
        Prog* prog = ReverseProg();
754
0
        if (prog == NULL) {
755
          // Fall back to NFA below.
756
0
          skipped_test = true;
757
0
          break;
758
0
        }
759
0
        if (!prog->SearchDFA(subtext, text, Prog::kAnchored,
760
0
                             Prog::kLongestMatch, matchp, &dfa_failed, NULL)) {
761
0
          if (dfa_failed) {
762
0
            if (options_.log_errors())
763
0
              ABSL_LOG(ERROR) << "DFA out of memory: "
764
0
                              << "pattern length " << pattern_->size() << ", "
765
0
                              << "program size " << prog->size() << ", "
766
0
                              << "list count " << prog->list_count() << ", "
767
0
                              << "bytemap range " << prog->bytemap_range();
768
            // Fall back to NFA below.
769
0
            skipped_test = true;
770
0
            break;
771
0
          }
772
0
          return false;
773
0
        }
774
0
        if (matchp == NULL)  // Matched.  Don't care where.
775
0
          return true;
776
0
        break;
777
0
      }
778
779
0
      if (!prog_->SearchDFA(subtext, text, anchor, kind,
780
0
                            matchp, &dfa_failed, NULL)) {
781
0
        if (dfa_failed) {
782
0
          if (options_.log_errors())
783
0
            ABSL_LOG(ERROR) << "DFA out of memory: "
784
0
                            << "pattern length " << pattern_->size() << ", "
785
0
                            << "program size " << prog_->size() << ", "
786
0
                            << "list count " << prog_->list_count() << ", "
787
0
                            << "bytemap range " << prog_->bytemap_range();
788
          // Fall back to NFA below.
789
0
          skipped_test = true;
790
0
          break;
791
0
        }
792
0
        return false;
793
0
      }
794
0
      if (matchp == NULL)  // Matched.  Don't care where.
795
0
        return true;
796
      // SearchDFA set match.end() but didn't know where the
797
      // match started.  Run the regexp backward from match.end()
798
      // to find the longest possible match -- that's where it started.
799
0
      Prog* prog = ReverseProg();
800
0
      if (prog == NULL) {
801
        // Fall back to NFA below.
802
0
        skipped_test = true;
803
0
        break;
804
0
      }
805
0
      if (!prog->SearchDFA(match, text, Prog::kAnchored,
806
0
                           Prog::kLongestMatch, &match, &dfa_failed, NULL)) {
807
0
        if (dfa_failed) {
808
0
          if (options_.log_errors())
809
0
            ABSL_LOG(ERROR) << "DFA out of memory: "
810
0
                            << "pattern length " << pattern_->size() << ", "
811
0
                            << "program size " << prog->size() << ", "
812
0
                            << "list count " << prog->list_count() << ", "
813
0
                            << "bytemap range " << prog->bytemap_range();
814
          // Fall back to NFA below.
815
0
          skipped_test = true;
816
0
          break;
817
0
        }
818
0
        if (options_.log_errors())
819
0
          ABSL_LOG(ERROR) << "SearchDFA inconsistency";
820
0
        return false;
821
0
      }
822
0
      break;
823
0
    }
824
825
0
    case ANCHOR_BOTH:
826
0
    case ANCHOR_START:
827
0
      if (re_anchor == ANCHOR_BOTH)
828
0
        kind = Prog::kFullMatch;
829
0
      anchor = Prog::kAnchored;
830
831
      // If only a small amount of text and need submatch
832
      // information anyway and we're going to use OnePass or BitState
833
      // to get it, we might as well not even bother with the DFA:
834
      // OnePass or BitState will be fast enough.
835
      // On tiny texts, OnePass outruns even the DFA, and
836
      // it doesn't have the shared state and occasional mutex that
837
      // the DFA does.
838
0
      if (can_one_pass && text.size() <= 4096 &&
839
0
          (ncap > 1 || text.size() <= 16)) {
840
0
        skipped_test = true;
841
0
        break;
842
0
      }
843
0
      if (can_bit_state && text.size() <= bit_state_text_max_size &&
844
0
          ncap > 1) {
845
0
        skipped_test = true;
846
0
        break;
847
0
      }
848
0
      if (!prog_->SearchDFA(subtext, text, anchor, kind,
849
0
                            &match, &dfa_failed, NULL)) {
850
0
        if (dfa_failed) {
851
0
          if (options_.log_errors())
852
0
            ABSL_LOG(ERROR) << "DFA out of memory: "
853
0
                            << "pattern length " << pattern_->size() << ", "
854
0
                            << "program size " << prog_->size() << ", "
855
0
                            << "list count " << prog_->list_count() << ", "
856
0
                            << "bytemap range " << prog_->bytemap_range();
857
          // Fall back to NFA below.
858
0
          skipped_test = true;
859
0
          break;
860
0
        }
861
0
        return false;
862
0
      }
863
0
      break;
864
0
  }
865
866
0
  if (!skipped_test && ncap <= 1) {
867
    // We know exactly where it matches.  That's enough.
868
0
    if (ncap == 1)
869
0
      submatch[0] = match;
870
0
  } else {
871
0
    absl::string_view subtext1;
872
0
    if (skipped_test) {
873
      // DFA ran out of memory or was skipped:
874
      // need to search in entire original text.
875
0
      subtext1 = subtext;
876
0
    } else {
877
      // DFA found the exact match location:
878
      // let NFA run an anchored, full match search
879
      // to find submatch locations.
880
0
      subtext1 = match;
881
0
      anchor = Prog::kAnchored;
882
0
      kind = Prog::kFullMatch;
883
0
    }
884
885
0
    if (can_one_pass && anchor != Prog::kUnanchored) {
886
0
      if (!prog_->SearchOnePass(subtext1, text, anchor, kind, submatch, ncap)) {
887
0
        if (!skipped_test && options_.log_errors())
888
0
          ABSL_LOG(ERROR) << "SearchOnePass inconsistency";
889
0
        return false;
890
0
      }
891
0
    } else if (can_bit_state && subtext1.size() <= bit_state_text_max_size) {
892
0
      if (!prog_->SearchBitState(subtext1, text, anchor,
893
0
                                 kind, submatch, ncap)) {
894
0
        if (!skipped_test && options_.log_errors())
895
0
          ABSL_LOG(ERROR) << "SearchBitState inconsistency";
896
0
        return false;
897
0
      }
898
0
    } else {
899
0
      if (!prog_->SearchNFA(subtext1, text, anchor, kind, submatch, ncap)) {
900
0
        if (!skipped_test && options_.log_errors())
901
0
          ABSL_LOG(ERROR) << "SearchNFA inconsistency";
902
0
        return false;
903
0
      }
904
0
    }
905
0
  }
906
907
  // Adjust overall match for required prefix that we stripped off.
908
0
  if (prefixlen > 0 && nsubmatch > 0)
909
0
    submatch[0] = absl::string_view(submatch[0].data() - prefixlen,
910
0
                                    submatch[0].size() + prefixlen);
911
912
  // Zero submatches that don't exist in the regexp.
913
0
  for (int i = ncap; i < nsubmatch; i++)
914
0
    submatch[i] = absl::string_view();
915
0
  return true;
916
0
}
917
918
// Internal matcher - like Match() but takes Args not string_views.
919
bool RE2::DoMatch(absl::string_view text,
920
                  Anchor re_anchor,
921
                  size_t* consumed,
922
                  const Arg* const* args,
923
0
                  int n) const {
924
0
  if (!ok()) {
925
0
    if (options_.log_errors())
926
0
      ABSL_LOG(ERROR) << "Invalid RE2: " << *error_;
927
0
    return false;
928
0
  }
929
930
0
  if (NumberOfCapturingGroups() < n) {
931
    // RE has fewer capturing groups than number of Arg pointers passed in.
932
0
    return false;
933
0
  }
934
935
  // Count number of capture groups needed.
936
0
  int nvec;
937
0
  if (n == 0 && consumed == NULL)
938
0
    nvec = 0;
939
0
  else
940
0
    nvec = n+1;
941
942
0
  absl::FixedArray<absl::string_view, kVecSize> vec_storage(nvec);
943
0
  absl::string_view* vec = vec_storage.data();
944
945
0
  if (!Match(text, 0, text.size(), re_anchor, vec, nvec)) {
946
0
    return false;
947
0
  }
948
949
0
  if (consumed != NULL)
950
0
    *consumed = static_cast<size_t>(EndPtr(vec[0]) - BeginPtr(text));
951
952
0
  if (n == 0 || args == NULL) {
953
    // We are not interested in results
954
0
    return true;
955
0
  }
956
957
  // If we got here, we must have matched the whole pattern.
958
0
  for (int i = 0; i < n; i++) {
959
0
    absl::string_view s = vec[i+1];
960
0
    if (!args[i]->Parse(s.data(), s.size())) {
961
      // TODO: Should we indicate what the error was?
962
0
      return false;
963
0
    }
964
0
  }
965
966
0
  return true;
967
0
}
968
969
// Checks that the rewrite string is well-formed with respect to this
970
// regular expression.
971
bool RE2::CheckRewriteString(absl::string_view rewrite,
972
0
                             std::string* error) const {
973
0
  int max_token = -1;
974
0
  for (const char *s = rewrite.data(), *end = s + rewrite.size();
975
0
       s < end; s++) {
976
0
    int c = *s;
977
0
    if (c != '\\') {
978
0
      continue;
979
0
    }
980
0
    if (++s == end) {
981
0
      *error = "Rewrite schema error: '\\' not allowed at end.";
982
0
      return false;
983
0
    }
984
0
    c = *s;
985
0
    if (c == '\\') {
986
0
      continue;
987
0
    }
988
0
    if (!absl::ascii_isdigit(c)) {
989
0
      *error = "Rewrite schema error: "
990
0
               "'\\' must be followed by a digit or '\\'.";
991
0
      return false;
992
0
    }
993
0
    int n = (c - '0');
994
0
    if (max_token < n) {
995
0
      max_token = n;
996
0
    }
997
0
  }
998
999
0
  if (max_token > NumberOfCapturingGroups()) {
1000
0
    *error = absl::StrFormat(
1001
0
        "Rewrite schema requests %d matches, but the regexp only has %d "
1002
0
        "parenthesized subexpressions.",
1003
0
        max_token, NumberOfCapturingGroups());
1004
0
    return false;
1005
0
  }
1006
0
  return true;
1007
0
}
1008
1009
// Returns the maximum submatch needed for the rewrite to be done by Replace().
1010
// E.g. if rewrite == "foo \\2,\\1", returns 2.
1011
0
int RE2::MaxSubmatch(absl::string_view rewrite) {
1012
0
  int max = 0;
1013
0
  for (const char *s = rewrite.data(), *end = s + rewrite.size();
1014
0
       s < end; s++) {
1015
0
    if (*s == '\\') {
1016
0
      s++;
1017
0
      int c = (s < end) ? *s : -1;
1018
0
      if (absl::ascii_isdigit(c)) {
1019
0
        int n = (c - '0');
1020
0
        if (n > max)
1021
0
          max = n;
1022
0
      }
1023
0
    }
1024
0
  }
1025
0
  return max;
1026
0
}
1027
1028
// Append the "rewrite" string, with backslash substitutions from "vec",
1029
// to string "out".
1030
bool RE2::Rewrite(std::string* out,
1031
                  absl::string_view rewrite,
1032
                  const absl::string_view* vec,
1033
0
                  int veclen) const {
1034
0
  for (const char *s = rewrite.data(), *end = s + rewrite.size();
1035
0
       s < end; s++) {
1036
0
    if (*s != '\\') {
1037
0
      out->push_back(*s);
1038
0
      continue;
1039
0
    }
1040
0
    s++;
1041
0
    int c = (s < end) ? *s : -1;
1042
0
    if (absl::ascii_isdigit(c)) {
1043
0
      int n = (c - '0');
1044
0
      if (n >= veclen) {
1045
0
        if (options_.log_errors()) {
1046
0
          ABSL_LOG(ERROR) << "invalid substitution \\" << n
1047
0
                          << " from " << veclen << " groups";
1048
0
        }
1049
0
        return false;
1050
0
      }
1051
0
      absl::string_view snip = vec[n];
1052
0
      if (!snip.empty())
1053
0
        out->append(snip.data(), snip.size());
1054
0
    } else if (c == '\\') {
1055
0
      out->push_back('\\');
1056
0
    } else {
1057
0
      if (options_.log_errors())
1058
0
        ABSL_LOG(ERROR) << "invalid rewrite pattern: " << rewrite;
1059
0
      return false;
1060
0
    }
1061
0
  }
1062
0
  return true;
1063
0
}
1064
1065
/***** Parsers for various types *****/
1066
1067
namespace re2_internal {
1068
1069
template <>
1070
0
bool Parse(const char* str, size_t n, void* dest) {
1071
  // We fail if somebody asked us to store into a non-NULL void* pointer
1072
0
  return (dest == NULL);
1073
0
}
1074
1075
template <>
1076
0
bool Parse(const char* str, size_t n, std::string* dest) {
1077
0
  if (dest == NULL) return true;
1078
0
  dest->assign(str, n);
1079
0
  return true;
1080
0
}
1081
1082
template <>
1083
0
bool Parse(const char* str, size_t n, absl::string_view* dest) {
1084
0
  if (dest == NULL) return true;
1085
0
  *dest = absl::string_view(str, n);
1086
0
  return true;
1087
0
}
1088
1089
template <>
1090
0
bool Parse(const char* str, size_t n, char* dest) {
1091
0
  if (n != 1) return false;
1092
0
  if (dest == NULL) return true;
1093
0
  *dest = str[0];
1094
0
  return true;
1095
0
}
1096
1097
template <>
1098
0
bool Parse(const char* str, size_t n, signed char* dest) {
1099
0
  if (n != 1) return false;
1100
0
  if (dest == NULL) return true;
1101
0
  *dest = str[0];
1102
0
  return true;
1103
0
}
1104
1105
template <>
1106
0
bool Parse(const char* str, size_t n, unsigned char* dest) {
1107
0
  if (n != 1) return false;
1108
0
  if (dest == NULL) return true;
1109
0
  *dest = str[0];
1110
0
  return true;
1111
0
}
1112
1113
// Largest number spec that we are willing to parse
1114
static const int kMaxNumberLength = 32;
1115
1116
// REQUIRES "buf" must have length at least nbuf.
1117
// Copies "str" into "buf" and null-terminates.
1118
// Overwrites *np with the new length.
1119
static const char* TerminateNumber(char* buf, size_t nbuf, const char* str,
1120
0
                                   size_t* np, bool accept_spaces) {
1121
0
  size_t n = *np;
1122
0
  if (n == 0) return "";
1123
0
  if (n > 0 && absl::ascii_isspace(*str)) {
1124
    // We are less forgiving than the strtoxxx() routines and do not
1125
    // allow leading spaces. We do allow leading spaces for floats.
1126
0
    if (!accept_spaces) {
1127
0
      return "";
1128
0
    }
1129
0
    while (n > 0 && absl::ascii_isspace(*str)) {
1130
0
      n--;
1131
0
      str++;
1132
0
    }
1133
0
  }
1134
1135
  // Although buf has a fixed maximum size, we can still handle
1136
  // arbitrarily large integers correctly by omitting leading zeros.
1137
  // (Numbers that are still too long will be out of range.)
1138
  // Before deciding whether str is too long,
1139
  // remove leading zeros with s/000+/00/.
1140
  // Leaving the leading two zeros in place means that
1141
  // we don't change 0000x123 (invalid) into 0x123 (valid).
1142
  // Skip over leading - before replacing.
1143
0
  bool neg = false;
1144
0
  if (n >= 1 && str[0] == '-') {
1145
0
    neg = true;
1146
0
    n--;
1147
0
    str++;
1148
0
  }
1149
1150
0
  if (n >= 3 && str[0] == '0' && str[1] == '0') {
1151
0
    while (n >= 3 && str[2] == '0') {
1152
0
      n--;
1153
0
      str++;
1154
0
    }
1155
0
  }
1156
1157
0
  if (neg) {  // make room in buf for -
1158
0
    n++;
1159
0
    str--;
1160
0
  }
1161
1162
0
  if (n > nbuf-1) return "";
1163
1164
0
  memmove(buf, str, n);
1165
0
  if (neg) {
1166
0
    buf[0] = '-';
1167
0
  }
1168
0
  buf[n] = '\0';
1169
0
  *np = n;
1170
0
  return buf;
1171
0
}
1172
1173
template <>
1174
0
bool Parse(const char* str, size_t n, float* dest) {
1175
0
  if (n == 0) return false;
1176
0
  static const int kMaxLength = 200;
1177
0
  char buf[kMaxLength+1];
1178
0
  str = TerminateNumber(buf, sizeof buf, str, &n, true);
1179
0
  char* end;
1180
0
  errno = 0;
1181
0
  float r = strtof(str, &end);
1182
0
  if (end != str + n) return false;   // Leftover junk
1183
0
  if (errno) return false;
1184
0
  if (dest == NULL) return true;
1185
0
  *dest = r;
1186
0
  return true;
1187
0
}
1188
1189
template <>
1190
0
bool Parse(const char* str, size_t n, double* dest) {
1191
0
  if (n == 0) return false;
1192
0
  static const int kMaxLength = 200;
1193
0
  char buf[kMaxLength+1];
1194
0
  str = TerminateNumber(buf, sizeof buf, str, &n, true);
1195
0
  char* end;
1196
0
  errno = 0;
1197
0
  double r = strtod(str, &end);
1198
0
  if (end != str + n) return false;   // Leftover junk
1199
0
  if (errno) return false;
1200
0
  if (dest == NULL) return true;
1201
0
  *dest = r;
1202
0
  return true;
1203
0
}
1204
1205
template <>
1206
0
bool Parse(const char* str, size_t n, long* dest, int radix) {
1207
0
  if (n == 0) return false;
1208
0
  char buf[kMaxNumberLength+1];
1209
0
  str = TerminateNumber(buf, sizeof buf, str, &n, false);
1210
0
  char* end;
1211
0
  errno = 0;
1212
0
  long r = strtol(str, &end, radix);
1213
0
  if (end != str + n) return false;   // Leftover junk
1214
0
  if (errno) return false;
1215
0
  if (dest == NULL) return true;
1216
0
  *dest = r;
1217
0
  return true;
1218
0
}
1219
1220
template <>
1221
0
bool Parse(const char* str, size_t n, unsigned long* dest, int radix) {
1222
0
  if (n == 0) return false;
1223
0
  char buf[kMaxNumberLength+1];
1224
0
  str = TerminateNumber(buf, sizeof buf, str, &n, false);
1225
0
  if (str[0] == '-') {
1226
    // strtoul() will silently accept negative numbers and parse
1227
    // them.  This module is more strict and treats them as errors.
1228
0
    return false;
1229
0
  }
1230
1231
0
  char* end;
1232
0
  errno = 0;
1233
0
  unsigned long r = strtoul(str, &end, radix);
1234
0
  if (end != str + n) return false;   // Leftover junk
1235
0
  if (errno) return false;
1236
0
  if (dest == NULL) return true;
1237
0
  *dest = r;
1238
0
  return true;
1239
0
}
1240
1241
template <>
1242
0
bool Parse(const char* str, size_t n, short* dest, int radix) {
1243
0
  long r;
1244
0
  if (!Parse(str, n, &r, radix)) return false;  // Could not parse
1245
0
  if ((short)r != r) return false;              // Out of range
1246
0
  if (dest == NULL) return true;
1247
0
  *dest = (short)r;
1248
0
  return true;
1249
0
}
1250
1251
template <>
1252
0
bool Parse(const char* str, size_t n, unsigned short* dest, int radix) {
1253
0
  unsigned long r;
1254
0
  if (!Parse(str, n, &r, radix)) return false;  // Could not parse
1255
0
  if ((unsigned short)r != r) return false;     // Out of range
1256
0
  if (dest == NULL) return true;
1257
0
  *dest = (unsigned short)r;
1258
0
  return true;
1259
0
}
1260
1261
template <>
1262
0
bool Parse(const char* str, size_t n, int* dest, int radix) {
1263
0
  long r;
1264
0
  if (!Parse(str, n, &r, radix)) return false;  // Could not parse
1265
0
  if ((int)r != r) return false;                // Out of range
1266
0
  if (dest == NULL) return true;
1267
0
  *dest = (int)r;
1268
0
  return true;
1269
0
}
1270
1271
template <>
1272
0
bool Parse(const char* str, size_t n, unsigned int* dest, int radix) {
1273
0
  unsigned long r;
1274
0
  if (!Parse(str, n, &r, radix)) return false;  // Could not parse
1275
0
  if ((unsigned int)r != r) return false;       // Out of range
1276
0
  if (dest == NULL) return true;
1277
0
  *dest = (unsigned int)r;
1278
0
  return true;
1279
0
}
1280
1281
template <>
1282
0
bool Parse(const char* str, size_t n, long long* dest, int radix) {
1283
0
  if (n == 0) return false;
1284
0
  char buf[kMaxNumberLength+1];
1285
0
  str = TerminateNumber(buf, sizeof buf, str, &n, false);
1286
0
  char* end;
1287
0
  errno = 0;
1288
0
  long long r = strtoll(str, &end, radix);
1289
0
  if (end != str + n) return false;   // Leftover junk
1290
0
  if (errno) return false;
1291
0
  if (dest == NULL) return true;
1292
0
  *dest = r;
1293
0
  return true;
1294
0
}
1295
1296
template <>
1297
0
bool Parse(const char* str, size_t n, unsigned long long* dest, int radix) {
1298
0
  if (n == 0) return false;
1299
0
  char buf[kMaxNumberLength+1];
1300
0
  str = TerminateNumber(buf, sizeof buf, str, &n, false);
1301
0
  if (str[0] == '-') {
1302
    // strtoull() will silently accept negative numbers and parse
1303
    // them.  This module is more strict and treats them as errors.
1304
0
    return false;
1305
0
  }
1306
0
  char* end;
1307
0
  errno = 0;
1308
0
  unsigned long long r = strtoull(str, &end, radix);
1309
0
  if (end != str + n) return false;   // Leftover junk
1310
0
  if (errno) return false;
1311
0
  if (dest == NULL) return true;
1312
0
  *dest = r;
1313
0
  return true;
1314
0
}
1315
1316
}  // namespace re2_internal
1317
1318
namespace hooks {
1319
1320
#ifdef RE2_HAVE_THREAD_LOCAL
1321
thread_local const RE2* context = NULL;
1322
#endif
1323
1324
template <typename T>
1325
union Hook {
1326
0
  void Store(T* cb) { cb_.store(cb, std::memory_order_release); }
Unexecuted instantiation: re2::hooks::Hook<void (re2::hooks::DFAStateCacheReset const&)>::Store(void (*)(re2::hooks::DFAStateCacheReset const&))
Unexecuted instantiation: re2::hooks::Hook<void (re2::hooks::DFASearchFailure const&)>::Store(void (*)(re2::hooks::DFASearchFailure const&))
1327
0
  T* Load() const { return cb_.load(std::memory_order_acquire); }
Unexecuted instantiation: re2::hooks::Hook<void (re2::hooks::DFAStateCacheReset const&)>::Load() const
Unexecuted instantiation: re2::hooks::Hook<void (re2::hooks::DFASearchFailure const&)>::Load() const
1328
1329
#if !defined(__clang__) && defined(_MSC_VER)
1330
  // Citing https://github.com/protocolbuffers/protobuf/pull/4777 as precedent,
1331
  // this is a gross hack to make std::atomic<T*> constant-initialized on MSVC.
1332
  static_assert(ATOMIC_POINTER_LOCK_FREE == 2,
1333
                "std::atomic<T*> must be always lock-free");
1334
  T* cb_for_constinit_;
1335
#endif
1336
1337
  std::atomic<T*> cb_;
1338
};
1339
1340
template <typename T>
1341
0
static void DoNothing(const T&) {}
Unexecuted instantiation: re2.cc:void re2::hooks::DoNothing<re2::hooks::DFAStateCacheReset>(re2::hooks::DFAStateCacheReset const&)
Unexecuted instantiation: re2.cc:void re2::hooks::DoNothing<re2::hooks::DFASearchFailure>(re2::hooks::DFASearchFailure const&)
1342
1343
#define DEFINE_HOOK(type, name)                                       \
1344
  static Hook<type##Callback> name##_hook = {{&DoNothing<type>}};     \
1345
0
  void Set##type##Hook(type##Callback* cb) { name##_hook.Store(cb); } \
Unexecuted instantiation: re2::hooks::SetDFAStateCacheResetHook(void (*)(re2::hooks::DFAStateCacheReset const&))
Unexecuted instantiation: re2::hooks::SetDFASearchFailureHook(void (*)(re2::hooks::DFASearchFailure const&))
1346
0
  type##Callback* Get##type##Hook() { return name##_hook.Load(); }
Unexecuted instantiation: re2::hooks::GetDFAStateCacheResetHook()
Unexecuted instantiation: re2::hooks::GetDFASearchFailureHook()
1347
1348
DEFINE_HOOK(DFAStateCacheReset, dfa_state_cache_reset)
1349
DEFINE_HOOK(DFASearchFailure, dfa_search_failure)
1350
1351
#undef DEFINE_HOOK
1352
1353
}  // namespace hooks
1354
1355
}  // namespace re2