pcre.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. // Copyright 2003-2009 Google Inc. 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. // This is a variant of PCRE's pcrecpp.cc, originally written at Google.
  5. // The main changes are the addition of the HitLimit method and
  6. // compilation as PCRE in namespace re2.
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <errno.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <limits>
  13. #include <string>
  14. #include <utility>
  15. #include "absl/flags/flag.h"
  16. #include "absl/strings/str_format.h"
  17. #include "util/logging.h"
  18. #include "util/pcre.h"
  19. // Silence warnings about the wacky formatting in the operator() functions.
  20. #if !defined(__clang__) && defined(__GNUC__)
  21. #pragma GCC diagnostic ignored "-Wmisleading-indentation"
  22. #endif
  23. #define PCREPORT(level) LOG(level)
  24. // Default PCRE limits.
  25. // Defaults chosen to allow a plausible amount of CPU and
  26. // not exceed main thread stacks. Note that other threads
  27. // often have smaller stacks, and therefore tightening
  28. // regexp_stack_limit may frequently be necessary.
  29. ABSL_FLAG(int, regexp_stack_limit, 256 << 10,
  30. "default PCRE stack limit (bytes)");
  31. ABSL_FLAG(int, regexp_match_limit, 1000000,
  32. "default PCRE match limit (function calls)");
  33. #ifndef USEPCRE
  34. // Fake just enough of the PCRE API to allow this file to build. :)
  35. struct pcre_extra {
  36. int flags;
  37. int match_limit;
  38. int match_limit_recursion;
  39. };
  40. #define PCRE_EXTRA_MATCH_LIMIT 0
  41. #define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0
  42. #define PCRE_ANCHORED 0
  43. #define PCRE_NOTEMPTY 0
  44. #define PCRE_ERROR_NOMATCH 1
  45. #define PCRE_ERROR_MATCHLIMIT 2
  46. #define PCRE_ERROR_RECURSIONLIMIT 3
  47. #define PCRE_INFO_CAPTURECOUNT 0
  48. void pcre_free(void*) {
  49. }
  50. pcre* pcre_compile(const char*, int, const char**, int*, const unsigned char*) {
  51. return NULL;
  52. }
  53. int pcre_exec(const pcre*, const pcre_extra*, const char*, int, int, int, int*, int) {
  54. return 0;
  55. }
  56. int pcre_fullinfo(const pcre*, const pcre_extra*, int, void*) {
  57. return 0;
  58. }
  59. #endif
  60. namespace re2 {
  61. // Maximum number of args we can set
  62. static const int kMaxArgs = 16;
  63. static const int kVecSize = (1 + kMaxArgs) * 3; // results + PCRE workspace
  64. // Approximate size of a recursive invocation of PCRE's
  65. // internal "match()" frame. This varies depending on the
  66. // compiler and architecture, of course, so the constant is
  67. // just a conservative estimate. To find the exact number,
  68. // run regexp_unittest with --regexp_stack_limit=0 under
  69. // a debugger and look at the frames when it crashes.
  70. // The exact frame size was 656 in production on 2008/02/03.
  71. static const int kPCREFrameSize = 700;
  72. // Special name for missing C++ arguments.
  73. PCRE::Arg PCRE::no_more_args((void*)NULL);
  74. const PCRE::PartialMatchFunctor PCRE::PartialMatch = { };
  75. const PCRE::FullMatchFunctor PCRE::FullMatch = { } ;
  76. const PCRE::ConsumeFunctor PCRE::Consume = { };
  77. const PCRE::FindAndConsumeFunctor PCRE::FindAndConsume = { };
  78. // If a regular expression has no error, its error_ field points here
  79. static const std::string empty_string;
  80. void PCRE::Init(const char* pattern, Option options, int match_limit,
  81. int stack_limit, bool report_errors) {
  82. pattern_ = pattern;
  83. options_ = options;
  84. match_limit_ = match_limit;
  85. stack_limit_ = stack_limit;
  86. hit_limit_ = false;
  87. error_ = &empty_string;
  88. report_errors_ = report_errors;
  89. re_full_ = NULL;
  90. re_partial_ = NULL;
  91. if (options & ~(EnabledCompileOptions | EnabledExecOptions)) {
  92. error_ = new std::string("illegal regexp option");
  93. PCREPORT(ERROR)
  94. << "Error compiling '" << pattern << "': illegal regexp option";
  95. } else {
  96. re_partial_ = Compile(UNANCHORED);
  97. if (re_partial_ != NULL) {
  98. re_full_ = Compile(ANCHOR_BOTH);
  99. }
  100. }
  101. }
  102. PCRE::PCRE(const char* pattern) {
  103. Init(pattern, None, 0, 0, true);
  104. }
  105. PCRE::PCRE(const char* pattern, Option option) {
  106. Init(pattern, option, 0, 0, true);
  107. }
  108. PCRE::PCRE(const std::string& pattern) {
  109. Init(pattern.c_str(), None, 0, 0, true);
  110. }
  111. PCRE::PCRE(const std::string& pattern, Option option) {
  112. Init(pattern.c_str(), option, 0, 0, true);
  113. }
  114. PCRE::PCRE(const std::string& pattern, const PCRE_Options& re_option) {
  115. Init(pattern.c_str(), re_option.option(), re_option.match_limit(),
  116. re_option.stack_limit(), re_option.report_errors());
  117. }
  118. PCRE::PCRE(const char *pattern, const PCRE_Options& re_option) {
  119. Init(pattern, re_option.option(), re_option.match_limit(),
  120. re_option.stack_limit(), re_option.report_errors());
  121. }
  122. PCRE::~PCRE() {
  123. if (re_full_ != NULL) pcre_free(re_full_);
  124. if (re_partial_ != NULL) pcre_free(re_partial_);
  125. if (error_ != &empty_string) delete error_;
  126. }
  127. pcre* PCRE::Compile(Anchor anchor) {
  128. // Special treatment for anchoring. This is needed because at
  129. // runtime pcre only provides an option for anchoring at the
  130. // beginning of a string.
  131. //
  132. // There are three types of anchoring we want:
  133. // UNANCHORED Compile the original pattern, and use
  134. // a pcre unanchored match.
  135. // ANCHOR_START Compile the original pattern, and use
  136. // a pcre anchored match.
  137. // ANCHOR_BOTH Tack a "\z" to the end of the original pattern
  138. // and use a pcre anchored match.
  139. const char* error = "";
  140. int eoffset;
  141. pcre* re;
  142. if (anchor != ANCHOR_BOTH) {
  143. re = pcre_compile(pattern_.c_str(),
  144. (options_ & EnabledCompileOptions),
  145. &error, &eoffset, NULL);
  146. } else {
  147. // Tack a '\z' at the end of PCRE. Parenthesize it first so that
  148. // the '\z' applies to all top-level alternatives in the regexp.
  149. std::string wrapped = "(?:"; // A non-counting grouping operator
  150. wrapped += pattern_;
  151. wrapped += ")\\z";
  152. re = pcre_compile(wrapped.c_str(),
  153. (options_ & EnabledCompileOptions),
  154. &error, &eoffset, NULL);
  155. }
  156. if (re == NULL) {
  157. if (error_ == &empty_string) error_ = new std::string(error);
  158. PCREPORT(ERROR) << "Error compiling '" << pattern_ << "': " << error;
  159. }
  160. return re;
  161. }
  162. /***** Convenience interfaces *****/
  163. bool PCRE::FullMatchFunctor::operator()(
  164. absl::string_view text, const PCRE& re, const Arg& a0, const Arg& a1,
  165. const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6,
  166. const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11,
  167. const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15) const {
  168. const Arg* args[kMaxArgs];
  169. int n = 0;
  170. if (&a0 == &no_more_args) goto done; args[n++] = &a0;
  171. if (&a1 == &no_more_args) goto done; args[n++] = &a1;
  172. if (&a2 == &no_more_args) goto done; args[n++] = &a2;
  173. if (&a3 == &no_more_args) goto done; args[n++] = &a3;
  174. if (&a4 == &no_more_args) goto done; args[n++] = &a4;
  175. if (&a5 == &no_more_args) goto done; args[n++] = &a5;
  176. if (&a6 == &no_more_args) goto done; args[n++] = &a6;
  177. if (&a7 == &no_more_args) goto done; args[n++] = &a7;
  178. if (&a8 == &no_more_args) goto done; args[n++] = &a8;
  179. if (&a9 == &no_more_args) goto done; args[n++] = &a9;
  180. if (&a10 == &no_more_args) goto done; args[n++] = &a10;
  181. if (&a11 == &no_more_args) goto done; args[n++] = &a11;
  182. if (&a12 == &no_more_args) goto done; args[n++] = &a12;
  183. if (&a13 == &no_more_args) goto done; args[n++] = &a13;
  184. if (&a14 == &no_more_args) goto done; args[n++] = &a14;
  185. if (&a15 == &no_more_args) goto done; args[n++] = &a15;
  186. done:
  187. size_t consumed;
  188. int vec[kVecSize] = {};
  189. return re.DoMatchImpl(text, ANCHOR_BOTH, &consumed, args, n, vec, kVecSize);
  190. }
  191. bool PCRE::PartialMatchFunctor::operator()(
  192. absl::string_view text, const PCRE& re, const Arg& a0, const Arg& a1,
  193. const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6,
  194. const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11,
  195. const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15) const {
  196. const Arg* args[kMaxArgs];
  197. int n = 0;
  198. if (&a0 == &no_more_args) goto done; args[n++] = &a0;
  199. if (&a1 == &no_more_args) goto done; args[n++] = &a1;
  200. if (&a2 == &no_more_args) goto done; args[n++] = &a2;
  201. if (&a3 == &no_more_args) goto done; args[n++] = &a3;
  202. if (&a4 == &no_more_args) goto done; args[n++] = &a4;
  203. if (&a5 == &no_more_args) goto done; args[n++] = &a5;
  204. if (&a6 == &no_more_args) goto done; args[n++] = &a6;
  205. if (&a7 == &no_more_args) goto done; args[n++] = &a7;
  206. if (&a8 == &no_more_args) goto done; args[n++] = &a8;
  207. if (&a9 == &no_more_args) goto done; args[n++] = &a9;
  208. if (&a10 == &no_more_args) goto done; args[n++] = &a10;
  209. if (&a11 == &no_more_args) goto done; args[n++] = &a11;
  210. if (&a12 == &no_more_args) goto done; args[n++] = &a12;
  211. if (&a13 == &no_more_args) goto done; args[n++] = &a13;
  212. if (&a14 == &no_more_args) goto done; args[n++] = &a14;
  213. if (&a15 == &no_more_args) goto done; args[n++] = &a15;
  214. done:
  215. size_t consumed;
  216. int vec[kVecSize] = {};
  217. return re.DoMatchImpl(text, UNANCHORED, &consumed, args, n, vec, kVecSize);
  218. }
  219. bool PCRE::ConsumeFunctor::operator()(
  220. absl::string_view* input, const PCRE& pattern, const Arg& a0, const Arg& a1,
  221. const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6,
  222. const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11,
  223. const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15) const {
  224. const Arg* args[kMaxArgs];
  225. int n = 0;
  226. if (&a0 == &no_more_args) goto done; args[n++] = &a0;
  227. if (&a1 == &no_more_args) goto done; args[n++] = &a1;
  228. if (&a2 == &no_more_args) goto done; args[n++] = &a2;
  229. if (&a3 == &no_more_args) goto done; args[n++] = &a3;
  230. if (&a4 == &no_more_args) goto done; args[n++] = &a4;
  231. if (&a5 == &no_more_args) goto done; args[n++] = &a5;
  232. if (&a6 == &no_more_args) goto done; args[n++] = &a6;
  233. if (&a7 == &no_more_args) goto done; args[n++] = &a7;
  234. if (&a8 == &no_more_args) goto done; args[n++] = &a8;
  235. if (&a9 == &no_more_args) goto done; args[n++] = &a9;
  236. if (&a10 == &no_more_args) goto done; args[n++] = &a10;
  237. if (&a11 == &no_more_args) goto done; args[n++] = &a11;
  238. if (&a12 == &no_more_args) goto done; args[n++] = &a12;
  239. if (&a13 == &no_more_args) goto done; args[n++] = &a13;
  240. if (&a14 == &no_more_args) goto done; args[n++] = &a14;
  241. if (&a15 == &no_more_args) goto done; args[n++] = &a15;
  242. done:
  243. size_t consumed;
  244. int vec[kVecSize] = {};
  245. if (pattern.DoMatchImpl(*input, ANCHOR_START, &consumed,
  246. args, n, vec, kVecSize)) {
  247. input->remove_prefix(consumed);
  248. return true;
  249. } else {
  250. return false;
  251. }
  252. }
  253. bool PCRE::FindAndConsumeFunctor::operator()(
  254. absl::string_view* input, const PCRE& pattern, const Arg& a0, const Arg& a1,
  255. const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6,
  256. const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11,
  257. const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15) const {
  258. const Arg* args[kMaxArgs];
  259. int n = 0;
  260. if (&a0 == &no_more_args) goto done; args[n++] = &a0;
  261. if (&a1 == &no_more_args) goto done; args[n++] = &a1;
  262. if (&a2 == &no_more_args) goto done; args[n++] = &a2;
  263. if (&a3 == &no_more_args) goto done; args[n++] = &a3;
  264. if (&a4 == &no_more_args) goto done; args[n++] = &a4;
  265. if (&a5 == &no_more_args) goto done; args[n++] = &a5;
  266. if (&a6 == &no_more_args) goto done; args[n++] = &a6;
  267. if (&a7 == &no_more_args) goto done; args[n++] = &a7;
  268. if (&a8 == &no_more_args) goto done; args[n++] = &a8;
  269. if (&a9 == &no_more_args) goto done; args[n++] = &a9;
  270. if (&a10 == &no_more_args) goto done; args[n++] = &a10;
  271. if (&a11 == &no_more_args) goto done; args[n++] = &a11;
  272. if (&a12 == &no_more_args) goto done; args[n++] = &a12;
  273. if (&a13 == &no_more_args) goto done; args[n++] = &a13;
  274. if (&a14 == &no_more_args) goto done; args[n++] = &a14;
  275. if (&a15 == &no_more_args) goto done; args[n++] = &a15;
  276. done:
  277. size_t consumed;
  278. int vec[kVecSize] = {};
  279. if (pattern.DoMatchImpl(*input, UNANCHORED, &consumed,
  280. args, n, vec, kVecSize)) {
  281. input->remove_prefix(consumed);
  282. return true;
  283. } else {
  284. return false;
  285. }
  286. }
  287. bool PCRE::Replace(std::string* str, const PCRE& pattern,
  288. absl::string_view rewrite) {
  289. int vec[kVecSize] = {};
  290. int matches = pattern.TryMatch(*str, 0, UNANCHORED, true, vec, kVecSize);
  291. if (matches == 0)
  292. return false;
  293. std::string s;
  294. if (!pattern.Rewrite(&s, rewrite, *str, vec, matches))
  295. return false;
  296. assert(vec[0] >= 0);
  297. assert(vec[1] >= 0);
  298. str->replace(vec[0], vec[1] - vec[0], s);
  299. return true;
  300. }
  301. int PCRE::GlobalReplace(std::string* str, const PCRE& pattern,
  302. absl::string_view rewrite) {
  303. int count = 0;
  304. int vec[kVecSize] = {};
  305. std::string out;
  306. size_t start = 0;
  307. bool last_match_was_empty_string = false;
  308. while (start <= str->size()) {
  309. // If the previous match was for the empty string, we shouldn't
  310. // just match again: we'll match in the same way and get an
  311. // infinite loop. Instead, we do the match in a special way:
  312. // anchored -- to force another try at the same position --
  313. // and with a flag saying that this time, ignore empty matches.
  314. // If this special match returns, that means there's a non-empty
  315. // match at this position as well, and we can continue. If not,
  316. // we do what perl does, and just advance by one.
  317. // Notice that perl prints '@@@' for this;
  318. // perl -le '$_ = "aa"; s/b*|aa/@/g; print'
  319. int matches;
  320. if (last_match_was_empty_string) {
  321. matches = pattern.TryMatch(*str, start, ANCHOR_START, false,
  322. vec, kVecSize);
  323. if (matches <= 0) {
  324. if (start < str->size())
  325. out.push_back((*str)[start]);
  326. start++;
  327. last_match_was_empty_string = false;
  328. continue;
  329. }
  330. } else {
  331. matches = pattern.TryMatch(*str, start, UNANCHORED, true,
  332. vec, kVecSize);
  333. if (matches <= 0)
  334. break;
  335. }
  336. size_t matchstart = vec[0], matchend = vec[1];
  337. assert(matchstart >= start);
  338. assert(matchend >= matchstart);
  339. out.append(*str, start, matchstart - start);
  340. pattern.Rewrite(&out, rewrite, *str, vec, matches);
  341. start = matchend;
  342. count++;
  343. last_match_was_empty_string = (matchstart == matchend);
  344. }
  345. if (count == 0)
  346. return 0;
  347. if (start < str->size())
  348. out.append(*str, start, str->size() - start);
  349. using std::swap;
  350. swap(out, *str);
  351. return count;
  352. }
  353. bool PCRE::Extract(absl::string_view text, const PCRE& pattern,
  354. absl::string_view rewrite, std::string* out) {
  355. int vec[kVecSize] = {};
  356. int matches = pattern.TryMatch(text, 0, UNANCHORED, true, vec, kVecSize);
  357. if (matches == 0)
  358. return false;
  359. out->clear();
  360. return pattern.Rewrite(out, rewrite, text, vec, matches);
  361. }
  362. std::string PCRE::QuoteMeta(absl::string_view unquoted) {
  363. std::string result;
  364. result.reserve(unquoted.size() << 1);
  365. // Escape any ascii character not in [A-Za-z_0-9].
  366. //
  367. // Note that it's legal to escape a character even if it has no
  368. // special meaning in a regular expression -- so this function does
  369. // that. (This also makes it identical to the perl function of the
  370. // same name except for the null-character special case;
  371. // see `perldoc -f quotemeta`.)
  372. for (size_t ii = 0; ii < unquoted.size(); ++ii) {
  373. // Note that using 'isalnum' here raises the benchmark time from
  374. // 32ns to 58ns:
  375. if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
  376. (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
  377. (unquoted[ii] < '0' || unquoted[ii] > '9') &&
  378. unquoted[ii] != '_' &&
  379. // If this is the part of a UTF8 or Latin1 character, we need
  380. // to copy this byte without escaping. Experimentally this is
  381. // what works correctly with the regexp library.
  382. !(unquoted[ii] & 128)) {
  383. if (unquoted[ii] == '\0') { // Special handling for null chars.
  384. // Can't use "\\0" since the next character might be a digit.
  385. result += "\\x00";
  386. continue;
  387. }
  388. result += '\\';
  389. }
  390. result += unquoted[ii];
  391. }
  392. return result;
  393. }
  394. /***** Actual matching and rewriting code *****/
  395. bool PCRE::HitLimit() {
  396. return hit_limit_ != 0;
  397. }
  398. void PCRE::ClearHitLimit() {
  399. hit_limit_ = 0;
  400. }
  401. int PCRE::TryMatch(absl::string_view text, size_t startpos, Anchor anchor,
  402. bool empty_ok, int* vec, int vecsize) const {
  403. pcre* re = (anchor == ANCHOR_BOTH) ? re_full_ : re_partial_;
  404. if (re == NULL) {
  405. PCREPORT(ERROR) << "Matching against invalid re: " << *error_;
  406. return 0;
  407. }
  408. int match_limit = match_limit_;
  409. if (match_limit <= 0) {
  410. match_limit = absl::GetFlag(FLAGS_regexp_match_limit);
  411. }
  412. int stack_limit = stack_limit_;
  413. if (stack_limit <= 0) {
  414. stack_limit = absl::GetFlag(FLAGS_regexp_stack_limit);
  415. }
  416. pcre_extra extra = { 0 };
  417. if (match_limit > 0) {
  418. extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
  419. extra.match_limit = match_limit;
  420. }
  421. if (stack_limit > 0) {
  422. extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  423. extra.match_limit_recursion = stack_limit / kPCREFrameSize;
  424. }
  425. int options = 0;
  426. if (anchor != UNANCHORED)
  427. options |= PCRE_ANCHORED;
  428. if (!empty_ok)
  429. options |= PCRE_NOTEMPTY;
  430. int rc = pcre_exec(re, // The regular expression object
  431. &extra,
  432. (text.data() == NULL) ? "" : text.data(),
  433. static_cast<int>(text.size()),
  434. static_cast<int>(startpos),
  435. options,
  436. vec,
  437. vecsize);
  438. // Handle errors
  439. if (rc == 0) {
  440. // pcre_exec() returns 0 as a special case when the number of
  441. // capturing subpatterns exceeds the size of the vector.
  442. // When this happens, there is a match and the output vector
  443. // is filled, but we miss out on the positions of the extra subpatterns.
  444. rc = vecsize / 2;
  445. } else if (rc < 0) {
  446. switch (rc) {
  447. case PCRE_ERROR_NOMATCH:
  448. return 0;
  449. case PCRE_ERROR_MATCHLIMIT:
  450. // Writing to hit_limit is not safe if multiple threads
  451. // are using the PCRE, but the flag is only intended
  452. // for use by unit tests anyway, so we let it go.
  453. hit_limit_ = true;
  454. PCREPORT(WARNING) << "Exceeded match limit of " << match_limit
  455. << " when matching '" << pattern_ << "'"
  456. << " against text that is " << text.size() << " bytes.";
  457. return 0;
  458. case PCRE_ERROR_RECURSIONLIMIT:
  459. // See comment about hit_limit above.
  460. hit_limit_ = true;
  461. PCREPORT(WARNING) << "Exceeded stack limit of " << stack_limit
  462. << " when matching '" << pattern_ << "'"
  463. << " against text that is " << text.size() << " bytes.";
  464. return 0;
  465. default:
  466. // There are other return codes from pcre.h :
  467. // PCRE_ERROR_NULL (-2)
  468. // PCRE_ERROR_BADOPTION (-3)
  469. // PCRE_ERROR_BADMAGIC (-4)
  470. // PCRE_ERROR_UNKNOWN_NODE (-5)
  471. // PCRE_ERROR_NOMEMORY (-6)
  472. // PCRE_ERROR_NOSUBSTRING (-7)
  473. // ...
  474. PCREPORT(ERROR) << "Unexpected return code: " << rc
  475. << " when matching '" << pattern_ << "'"
  476. << ", re=" << re
  477. << ", text=" << text
  478. << ", vec=" << vec
  479. << ", vecsize=" << vecsize;
  480. return 0;
  481. }
  482. }
  483. return rc;
  484. }
  485. bool PCRE::DoMatchImpl(absl::string_view text, Anchor anchor, size_t* consumed,
  486. const Arg* const* args, int n, int* vec,
  487. int vecsize) const {
  488. assert((1 + n) * 3 <= vecsize); // results + PCRE workspace
  489. if (NumberOfCapturingGroups() < n) {
  490. // RE has fewer capturing groups than number of Arg pointers passed in.
  491. return false;
  492. }
  493. int matches = TryMatch(text, 0, anchor, true, vec, vecsize);
  494. assert(matches >= 0); // TryMatch never returns negatives
  495. if (matches == 0)
  496. return false;
  497. *consumed = vec[1];
  498. if (n == 0 || args == NULL) {
  499. // We are not interested in results
  500. return true;
  501. }
  502. // If we got here, we must have matched the whole pattern.
  503. // We do not need (can not do) any more checks on the value of 'matches' here
  504. // -- see the comment for TryMatch.
  505. for (int i = 0; i < n; i++) {
  506. const int start = vec[2*(i+1)];
  507. const int limit = vec[2*(i+1)+1];
  508. // Avoid invoking undefined behavior when text.data() happens
  509. // to be null and start happens to be -1, the latter being the
  510. // case for an unmatched subexpression. Even if text.data() is
  511. // not null, pointing one byte before was a longstanding bug.
  512. const char* addr = NULL;
  513. if (start != -1) {
  514. addr = text.data() + start;
  515. }
  516. if (!args[i]->Parse(addr, limit-start)) {
  517. // TODO: Should we indicate what the error was?
  518. return false;
  519. }
  520. }
  521. return true;
  522. }
  523. bool PCRE::DoMatch(absl::string_view text, Anchor anchor, size_t* consumed,
  524. const Arg* const args[], int n) const {
  525. assert(n >= 0);
  526. const int vecsize = (1 + n) * 3; // results + PCRE workspace
  527. // (as for kVecSize)
  528. int* vec = new int[vecsize];
  529. bool b = DoMatchImpl(text, anchor, consumed, args, n, vec, vecsize);
  530. delete[] vec;
  531. return b;
  532. }
  533. bool PCRE::Rewrite(std::string* out, absl::string_view rewrite,
  534. absl::string_view text, int* vec, int veclen) const {
  535. int number_of_capturing_groups = NumberOfCapturingGroups();
  536. for (const char *s = rewrite.data(), *end = s + rewrite.size();
  537. s < end; s++) {
  538. int c = *s;
  539. if (c == '\\') {
  540. c = *++s;
  541. if (isdigit(c)) {
  542. int n = (c - '0');
  543. if (n >= veclen) {
  544. if (n <= number_of_capturing_groups) {
  545. // unmatched optional capturing group. treat
  546. // its value as empty string; i.e., nothing to append.
  547. } else {
  548. PCREPORT(ERROR) << "requested group " << n
  549. << " in regexp " << rewrite.data();
  550. return false;
  551. }
  552. }
  553. int start = vec[2 * n];
  554. if (start >= 0)
  555. out->append(text.data() + start, vec[2 * n + 1] - start);
  556. } else if (c == '\\') {
  557. out->push_back('\\');
  558. } else {
  559. PCREPORT(ERROR) << "invalid rewrite pattern: " << rewrite.data();
  560. return false;
  561. }
  562. } else {
  563. out->push_back(c);
  564. }
  565. }
  566. return true;
  567. }
  568. bool PCRE::CheckRewriteString(absl::string_view rewrite,
  569. std::string* error) const {
  570. int max_token = -1;
  571. for (const char *s = rewrite.data(), *end = s + rewrite.size();
  572. s < end; s++) {
  573. int c = *s;
  574. if (c != '\\') {
  575. continue;
  576. }
  577. if (++s == end) {
  578. *error = "Rewrite schema error: '\\' not allowed at end.";
  579. return false;
  580. }
  581. c = *s;
  582. if (c == '\\') {
  583. continue;
  584. }
  585. if (!isdigit(c)) {
  586. *error = "Rewrite schema error: "
  587. "'\\' must be followed by a digit or '\\'.";
  588. return false;
  589. }
  590. int n = (c - '0');
  591. if (max_token < n) {
  592. max_token = n;
  593. }
  594. }
  595. if (max_token > NumberOfCapturingGroups()) {
  596. *error = absl::StrFormat(
  597. "Rewrite schema requests %d matches, but the regexp only has %d "
  598. "parenthesized subexpressions.",
  599. max_token, NumberOfCapturingGroups());
  600. return false;
  601. }
  602. return true;
  603. }
  604. // Return the number of capturing subpatterns, or -1 if the
  605. // regexp wasn't valid on construction.
  606. int PCRE::NumberOfCapturingGroups() const {
  607. if (re_partial_ == NULL) return -1;
  608. int result;
  609. int rc = pcre_fullinfo(re_partial_, // The regular expression object
  610. NULL, // We did not study the pattern
  611. PCRE_INFO_CAPTURECOUNT,
  612. &result);
  613. if (rc != 0) {
  614. PCREPORT(ERROR) << "Unexpected return code: " << rc;
  615. return -1;
  616. }
  617. return result;
  618. }
  619. /***** Parsers for various types *****/
  620. bool PCRE::Arg::parse_null(const char* str, size_t n, void* dest) {
  621. // We fail if somebody asked us to store into a non-NULL void* pointer
  622. return (dest == NULL);
  623. }
  624. bool PCRE::Arg::parse_string(const char* str, size_t n, void* dest) {
  625. if (dest == NULL) return true;
  626. reinterpret_cast<std::string*>(dest)->assign(str, n);
  627. return true;
  628. }
  629. bool PCRE::Arg::parse_string_view(const char* str, size_t n, void* dest) {
  630. if (dest == NULL) return true;
  631. *(reinterpret_cast<absl::string_view*>(dest)) = absl::string_view(str, n);
  632. return true;
  633. }
  634. bool PCRE::Arg::parse_char(const char* str, size_t n, void* dest) {
  635. if (n != 1) return false;
  636. if (dest == NULL) return true;
  637. *(reinterpret_cast<char*>(dest)) = str[0];
  638. return true;
  639. }
  640. bool PCRE::Arg::parse_schar(const char* str, size_t n, void* dest) {
  641. if (n != 1) return false;
  642. if (dest == NULL) return true;
  643. *(reinterpret_cast<signed char*>(dest)) = str[0];
  644. return true;
  645. }
  646. bool PCRE::Arg::parse_uchar(const char* str, size_t n, void* dest) {
  647. if (n != 1) return false;
  648. if (dest == NULL) return true;
  649. *(reinterpret_cast<unsigned char*>(dest)) = str[0];
  650. return true;
  651. }
  652. // Largest number spec that we are willing to parse
  653. static const int kMaxNumberLength = 32;
  654. // PCREQUIPCRES "buf" must have length at least kMaxNumberLength+1
  655. // PCREQUIPCRES "n > 0"
  656. // Copies "str" into "buf" and null-terminates if necessary.
  657. // Returns one of:
  658. // a. "str" if no termination is needed
  659. // b. "buf" if the string was copied and null-terminated
  660. // c. "" if the input was invalid and has no hope of being parsed
  661. static const char* TerminateNumber(char* buf, const char* str, size_t n) {
  662. if ((n > 0) && isspace(*str)) {
  663. // We are less forgiving than the strtoxxx() routines and do not
  664. // allow leading spaces.
  665. return "";
  666. }
  667. // See if the character right after the input text may potentially
  668. // look like a digit.
  669. if (isdigit(str[n]) ||
  670. ((str[n] >= 'a') && (str[n] <= 'f')) ||
  671. ((str[n] >= 'A') && (str[n] <= 'F'))) {
  672. if (n > kMaxNumberLength) return ""; // Input too big to be a valid number
  673. memcpy(buf, str, n);
  674. buf[n] = '\0';
  675. return buf;
  676. } else {
  677. // We can parse right out of the supplied string, so return it.
  678. return str;
  679. }
  680. }
  681. bool PCRE::Arg::parse_long_radix(const char* str,
  682. size_t n,
  683. void* dest,
  684. int radix) {
  685. if (n == 0) return false;
  686. char buf[kMaxNumberLength+1];
  687. str = TerminateNumber(buf, str, n);
  688. char* end;
  689. errno = 0;
  690. long r = strtol(str, &end, radix);
  691. if (end != str + n) return false; // Leftover junk
  692. if (errno) return false;
  693. if (dest == NULL) return true;
  694. *(reinterpret_cast<long*>(dest)) = r;
  695. return true;
  696. }
  697. bool PCRE::Arg::parse_ulong_radix(const char* str,
  698. size_t n,
  699. void* dest,
  700. int radix) {
  701. if (n == 0) return false;
  702. char buf[kMaxNumberLength+1];
  703. str = TerminateNumber(buf, str, n);
  704. if (str[0] == '-') {
  705. // strtoul() will silently accept negative numbers and parse
  706. // them. This module is more strict and treats them as errors.
  707. return false;
  708. }
  709. char* end;
  710. errno = 0;
  711. unsigned long r = strtoul(str, &end, radix);
  712. if (end != str + n) return false; // Leftover junk
  713. if (errno) return false;
  714. if (dest == NULL) return true;
  715. *(reinterpret_cast<unsigned long*>(dest)) = r;
  716. return true;
  717. }
  718. bool PCRE::Arg::parse_short_radix(const char* str,
  719. size_t n,
  720. void* dest,
  721. int radix) {
  722. long r;
  723. if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
  724. if ((short)r != r) return false; // Out of range
  725. if (dest == NULL) return true;
  726. *(reinterpret_cast<short*>(dest)) = (short)r;
  727. return true;
  728. }
  729. bool PCRE::Arg::parse_ushort_radix(const char* str,
  730. size_t n,
  731. void* dest,
  732. int radix) {
  733. unsigned long r;
  734. if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
  735. if ((unsigned short)r != r) return false; // Out of range
  736. if (dest == NULL) return true;
  737. *(reinterpret_cast<unsigned short*>(dest)) = (unsigned short)r;
  738. return true;
  739. }
  740. bool PCRE::Arg::parse_int_radix(const char* str,
  741. size_t n,
  742. void* dest,
  743. int radix) {
  744. long r;
  745. if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
  746. if ((int)r != r) return false; // Out of range
  747. if (dest == NULL) return true;
  748. *(reinterpret_cast<int*>(dest)) = (int)r;
  749. return true;
  750. }
  751. bool PCRE::Arg::parse_uint_radix(const char* str,
  752. size_t n,
  753. void* dest,
  754. int radix) {
  755. unsigned long r;
  756. if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
  757. if ((unsigned int)r != r) return false; // Out of range
  758. if (dest == NULL) return true;
  759. *(reinterpret_cast<unsigned int*>(dest)) = (unsigned int)r;
  760. return true;
  761. }
  762. bool PCRE::Arg::parse_longlong_radix(const char* str,
  763. size_t n,
  764. void* dest,
  765. int radix) {
  766. if (n == 0) return false;
  767. char buf[kMaxNumberLength+1];
  768. str = TerminateNumber(buf, str, n);
  769. char* end;
  770. errno = 0;
  771. long long r = strtoll(str, &end, radix);
  772. if (end != str + n) return false; // Leftover junk
  773. if (errno) return false;
  774. if (dest == NULL) return true;
  775. *(reinterpret_cast<long long*>(dest)) = r;
  776. return true;
  777. }
  778. bool PCRE::Arg::parse_ulonglong_radix(const char* str,
  779. size_t n,
  780. void* dest,
  781. int radix) {
  782. if (n == 0) return false;
  783. char buf[kMaxNumberLength+1];
  784. str = TerminateNumber(buf, str, n);
  785. if (str[0] == '-') {
  786. // strtoull() will silently accept negative numbers and parse
  787. // them. This module is more strict and treats them as errors.
  788. return false;
  789. }
  790. char* end;
  791. errno = 0;
  792. unsigned long long r = strtoull(str, &end, radix);
  793. if (end != str + n) return false; // Leftover junk
  794. if (errno) return false;
  795. if (dest == NULL) return true;
  796. *(reinterpret_cast<unsigned long long*>(dest)) = r;
  797. return true;
  798. }
  799. static bool parse_double_float(const char* str, size_t n, bool isfloat,
  800. void* dest) {
  801. if (n == 0) return false;
  802. static const int kMaxLength = 200;
  803. char buf[kMaxLength];
  804. if (n >= kMaxLength) return false;
  805. memcpy(buf, str, n);
  806. buf[n] = '\0';
  807. char* end;
  808. errno = 0;
  809. double r;
  810. if (isfloat) {
  811. r = strtof(buf, &end);
  812. } else {
  813. r = strtod(buf, &end);
  814. }
  815. if (end != buf + n) return false; // Leftover junk
  816. if (errno) return false;
  817. if (dest == NULL) return true;
  818. if (isfloat) {
  819. *(reinterpret_cast<float*>(dest)) = (float)r;
  820. } else {
  821. *(reinterpret_cast<double*>(dest)) = r;
  822. }
  823. return true;
  824. }
  825. bool PCRE::Arg::parse_double(const char* str, size_t n, void* dest) {
  826. return parse_double_float(str, n, false, dest);
  827. }
  828. bool PCRE::Arg::parse_float(const char* str, size_t n, void* dest) {
  829. return parse_double_float(str, n, true, dest);
  830. }
  831. #define DEFINE_INTEGER_PARSER(name) \
  832. bool PCRE::Arg::parse_##name(const char* str, size_t n, void* dest) { \
  833. return parse_##name##_radix(str, n, dest, 10); \
  834. } \
  835. bool PCRE::Arg::parse_##name##_hex(const char* str, size_t n, void* dest) { \
  836. return parse_##name##_radix(str, n, dest, 16); \
  837. } \
  838. bool PCRE::Arg::parse_##name##_octal(const char* str, size_t n, \
  839. void* dest) { \
  840. return parse_##name##_radix(str, n, dest, 8); \
  841. } \
  842. bool PCRE::Arg::parse_##name##_cradix(const char* str, size_t n, \
  843. void* dest) { \
  844. return parse_##name##_radix(str, n, dest, 0); \
  845. }
  846. DEFINE_INTEGER_PARSER(short);
  847. DEFINE_INTEGER_PARSER(ushort);
  848. DEFINE_INTEGER_PARSER(int);
  849. DEFINE_INTEGER_PARSER(uint);
  850. DEFINE_INTEGER_PARSER(long);
  851. DEFINE_INTEGER_PARSER(ulong);
  852. DEFINE_INTEGER_PARSER(longlong);
  853. DEFINE_INTEGER_PARSER(ulonglong);
  854. #undef DEFINE_INTEGER_PARSER
  855. } // namespace re2