pcrecpp.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. // Copyright (c) 2010, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: Sanjay Ghemawat
  31. #ifdef HAVE_CONFIG_H
  32. #include "config.h"
  33. #endif
  34. #include <stdlib.h>
  35. #include <stdio.h>
  36. #include <ctype.h>
  37. #include <limits.h> /* for SHRT_MIN, USHRT_MAX, etc */
  38. #include <string.h> /* for memcpy */
  39. #include <assert.h>
  40. #include <errno.h>
  41. #include <string>
  42. #include <algorithm>
  43. #include "pcrecpp_internal.h"
  44. #include "pcre.h"
  45. #include "pcrecpp.h"
  46. #include "pcre_stringpiece.h"
  47. namespace pcrecpp {
  48. // Maximum number of args we can set
  49. static const int kMaxArgs = 16;
  50. static const int kVecSize = (1 + kMaxArgs) * 3; // results + PCRE workspace
  51. // Special object that stands-in for no argument
  52. Arg RE::no_arg((void*)NULL);
  53. // This is for ABI compatibility with old versions of pcre (pre-7.6),
  54. // which defined a global no_arg variable instead of putting it in the
  55. // RE class. This works on GCC >= 3, at least. It definitely works
  56. // for ELF, but may not for other object formats (Mach-O, for
  57. // instance, does not support aliases.) We could probably have a more
  58. // inclusive test if we ever needed it. (Note that not only the
  59. // __attribute__ syntax, but also __USER_LABEL_PREFIX__, are
  60. // gnu-specific.)
  61. #if defined(__GNUC__) && __GNUC__ >= 3 && defined(__ELF__) && !defined(__INTEL_COMPILER)
  62. # define ULP_AS_STRING(x) ULP_AS_STRING_INTERNAL(x)
  63. # define ULP_AS_STRING_INTERNAL(x) #x
  64. # define USER_LABEL_PREFIX_STR ULP_AS_STRING(__USER_LABEL_PREFIX__)
  65. extern Arg no_arg
  66. __attribute__((alias(USER_LABEL_PREFIX_STR "_ZN7pcrecpp2RE6no_argE")));
  67. #endif
  68. // If a regular expression has no error, its error_ field points here
  69. static const string empty_string;
  70. // If the user doesn't ask for any options, we just use this one
  71. static RE_Options default_options;
  72. // Specials for the start of patterns. See comments where start_options is used
  73. // below. (PH June 2018)
  74. static const char *start_options[] = {
  75. "(*UTF8)",
  76. "(*UTF)",
  77. "(*UCP)",
  78. "(*NO_START_OPT)",
  79. "(*NO_AUTO_POSSESS)",
  80. "(*LIMIT_RECURSION=",
  81. "(*LIMIT_MATCH=",
  82. "(*CRLF)",
  83. "(*CR)",
  84. "(*BSR_UNICODE)",
  85. "(*BSR_ANYCRLF)",
  86. "(*ANYCRLF)",
  87. "(*ANY)",
  88. "" };
  89. void RE::Init(const string& pat, const RE_Options* options) {
  90. pattern_ = pat;
  91. if (options == NULL) {
  92. options_ = default_options;
  93. } else {
  94. options_ = *options;
  95. }
  96. error_ = &empty_string;
  97. re_full_ = NULL;
  98. re_partial_ = NULL;
  99. re_partial_ = Compile(UNANCHORED);
  100. if (re_partial_ != NULL) {
  101. re_full_ = Compile(ANCHOR_BOTH);
  102. }
  103. }
  104. void RE::Cleanup() {
  105. if (re_full_ != NULL) (*pcre_free)(re_full_);
  106. if (re_partial_ != NULL) (*pcre_free)(re_partial_);
  107. if (error_ != &empty_string) delete error_;
  108. }
  109. RE::~RE() {
  110. Cleanup();
  111. }
  112. pcre* RE::Compile(Anchor anchor) {
  113. // First, convert RE_Options into pcre options
  114. int pcre_options = 0;
  115. pcre_options = options_.all_options();
  116. // Special treatment for anchoring. This is needed because at
  117. // runtime pcre only provides an option for anchoring at the
  118. // beginning of a string (unless you use offset).
  119. //
  120. // There are three types of anchoring we want:
  121. // UNANCHORED Compile the original pattern, and use
  122. // a pcre unanchored match.
  123. // ANCHOR_START Compile the original pattern, and use
  124. // a pcre anchored match.
  125. // ANCHOR_BOTH Tack a "\z" to the end of the original pattern
  126. // and use a pcre anchored match.
  127. const char* compile_error;
  128. int eoffset;
  129. pcre* re;
  130. if (anchor != ANCHOR_BOTH) {
  131. re = pcre_compile(pattern_.c_str(), pcre_options,
  132. &compile_error, &eoffset, NULL);
  133. } else {
  134. // Tack a '\z' at the end of RE. Parenthesize it first so that
  135. // the '\z' applies to all top-level alternatives in the regexp.
  136. /* When this code was written (for PCRE 6.0) it was enough just to
  137. parenthesize the entire pattern. Unfortunately, when the feature of
  138. starting patterns with (*UTF8) or (*CR) etc. was added to PCRE patterns,
  139. this code was never updated. This bug was not noticed till 2018, long after
  140. PCRE became obsolescent and its maintainer no longer around. Since PCRE is
  141. frozen, I have added a hack to check for all the existing "start of
  142. pattern" specials - knowing that no new ones will ever be added. I am not a
  143. C++ programmer, so the code style is no doubt crude. It is also
  144. inefficient, but is only run when the pattern starts with "(*".
  145. PH June 2018. */
  146. string wrapped = "";
  147. if (pattern_.c_str()[0] == '(' && pattern_.c_str()[1] == '*') {
  148. int kk, klen, kmat;
  149. for (;;) { // Loop for any number of leading items
  150. for (kk = 0; start_options[kk][0] != 0; kk++) {
  151. klen = strlen(start_options[kk]);
  152. kmat = strncmp(pattern_.c_str(), start_options[kk], klen);
  153. if (kmat >= 0) break;
  154. }
  155. if (kmat != 0) break; // Not found
  156. // If the item ended in "=" we must copy digits up to ")".
  157. if (start_options[kk][klen-1] == '=') {
  158. while (isdigit(pattern_.c_str()[klen])) klen++;
  159. if (pattern_.c_str()[klen] != ')') break; // Syntax error
  160. klen++;
  161. }
  162. // Move the item from the pattern to the start of the wrapped string.
  163. wrapped += pattern_.substr(0, klen);
  164. pattern_.erase(0, klen);
  165. }
  166. }
  167. // Wrap the rest of the pattern.
  168. wrapped += "(?:"; // A non-counting grouping operator
  169. wrapped += pattern_;
  170. wrapped += ")\\z";
  171. re = pcre_compile(wrapped.c_str(), pcre_options,
  172. &compile_error, &eoffset, NULL);
  173. }
  174. if (re == NULL) {
  175. if (error_ == &empty_string) error_ = new string(compile_error);
  176. }
  177. return re;
  178. }
  179. /***** Matching interfaces *****/
  180. bool RE::FullMatch(const StringPiece& text,
  181. const Arg& ptr1,
  182. const Arg& ptr2,
  183. const Arg& ptr3,
  184. const Arg& ptr4,
  185. const Arg& ptr5,
  186. const Arg& ptr6,
  187. const Arg& ptr7,
  188. const Arg& ptr8,
  189. const Arg& ptr9,
  190. const Arg& ptr10,
  191. const Arg& ptr11,
  192. const Arg& ptr12,
  193. const Arg& ptr13,
  194. const Arg& ptr14,
  195. const Arg& ptr15,
  196. const Arg& ptr16) const {
  197. const Arg* args[kMaxArgs];
  198. int n = 0;
  199. if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
  200. if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
  201. if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
  202. if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
  203. if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
  204. if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
  205. if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
  206. if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
  207. if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
  208. if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
  209. if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
  210. if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
  211. if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
  212. if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
  213. if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
  214. if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
  215. done:
  216. int consumed;
  217. int vec[kVecSize];
  218. return DoMatchImpl(text, ANCHOR_BOTH, &consumed, args, n, vec, kVecSize);
  219. }
  220. bool RE::PartialMatch(const StringPiece& text,
  221. const Arg& ptr1,
  222. const Arg& ptr2,
  223. const Arg& ptr3,
  224. const Arg& ptr4,
  225. const Arg& ptr5,
  226. const Arg& ptr6,
  227. const Arg& ptr7,
  228. const Arg& ptr8,
  229. const Arg& ptr9,
  230. const Arg& ptr10,
  231. const Arg& ptr11,
  232. const Arg& ptr12,
  233. const Arg& ptr13,
  234. const Arg& ptr14,
  235. const Arg& ptr15,
  236. const Arg& ptr16) const {
  237. const Arg* args[kMaxArgs];
  238. int n = 0;
  239. if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
  240. if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
  241. if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
  242. if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
  243. if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
  244. if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
  245. if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
  246. if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
  247. if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
  248. if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
  249. if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
  250. if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
  251. if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
  252. if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
  253. if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
  254. if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
  255. done:
  256. int consumed;
  257. int vec[kVecSize];
  258. return DoMatchImpl(text, UNANCHORED, &consumed, args, n, vec, kVecSize);
  259. }
  260. bool RE::Consume(StringPiece* input,
  261. const Arg& ptr1,
  262. const Arg& ptr2,
  263. const Arg& ptr3,
  264. const Arg& ptr4,
  265. const Arg& ptr5,
  266. const Arg& ptr6,
  267. const Arg& ptr7,
  268. const Arg& ptr8,
  269. const Arg& ptr9,
  270. const Arg& ptr10,
  271. const Arg& ptr11,
  272. const Arg& ptr12,
  273. const Arg& ptr13,
  274. const Arg& ptr14,
  275. const Arg& ptr15,
  276. const Arg& ptr16) const {
  277. const Arg* args[kMaxArgs];
  278. int n = 0;
  279. if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
  280. if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
  281. if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
  282. if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
  283. if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
  284. if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
  285. if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
  286. if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
  287. if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
  288. if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
  289. if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
  290. if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
  291. if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
  292. if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
  293. if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
  294. if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
  295. done:
  296. int consumed;
  297. int vec[kVecSize];
  298. if (DoMatchImpl(*input, ANCHOR_START, &consumed,
  299. args, n, vec, kVecSize)) {
  300. input->remove_prefix(consumed);
  301. return true;
  302. } else {
  303. return false;
  304. }
  305. }
  306. bool RE::FindAndConsume(StringPiece* input,
  307. const Arg& ptr1,
  308. const Arg& ptr2,
  309. const Arg& ptr3,
  310. const Arg& ptr4,
  311. const Arg& ptr5,
  312. const Arg& ptr6,
  313. const Arg& ptr7,
  314. const Arg& ptr8,
  315. const Arg& ptr9,
  316. const Arg& ptr10,
  317. const Arg& ptr11,
  318. const Arg& ptr12,
  319. const Arg& ptr13,
  320. const Arg& ptr14,
  321. const Arg& ptr15,
  322. const Arg& ptr16) const {
  323. const Arg* args[kMaxArgs];
  324. int n = 0;
  325. if (&ptr1 == &no_arg) { goto done; } args[n++] = &ptr1;
  326. if (&ptr2 == &no_arg) { goto done; } args[n++] = &ptr2;
  327. if (&ptr3 == &no_arg) { goto done; } args[n++] = &ptr3;
  328. if (&ptr4 == &no_arg) { goto done; } args[n++] = &ptr4;
  329. if (&ptr5 == &no_arg) { goto done; } args[n++] = &ptr5;
  330. if (&ptr6 == &no_arg) { goto done; } args[n++] = &ptr6;
  331. if (&ptr7 == &no_arg) { goto done; } args[n++] = &ptr7;
  332. if (&ptr8 == &no_arg) { goto done; } args[n++] = &ptr8;
  333. if (&ptr9 == &no_arg) { goto done; } args[n++] = &ptr9;
  334. if (&ptr10 == &no_arg) { goto done; } args[n++] = &ptr10;
  335. if (&ptr11 == &no_arg) { goto done; } args[n++] = &ptr11;
  336. if (&ptr12 == &no_arg) { goto done; } args[n++] = &ptr12;
  337. if (&ptr13 == &no_arg) { goto done; } args[n++] = &ptr13;
  338. if (&ptr14 == &no_arg) { goto done; } args[n++] = &ptr14;
  339. if (&ptr15 == &no_arg) { goto done; } args[n++] = &ptr15;
  340. if (&ptr16 == &no_arg) { goto done; } args[n++] = &ptr16;
  341. done:
  342. int consumed;
  343. int vec[kVecSize];
  344. if (DoMatchImpl(*input, UNANCHORED, &consumed,
  345. args, n, vec, kVecSize)) {
  346. input->remove_prefix(consumed);
  347. return true;
  348. } else {
  349. return false;
  350. }
  351. }
  352. bool RE::Replace(const StringPiece& rewrite,
  353. string *str) const {
  354. int vec[kVecSize];
  355. int matches = TryMatch(*str, 0, UNANCHORED, true, vec, kVecSize);
  356. if (matches == 0)
  357. return false;
  358. string s;
  359. if (!Rewrite(&s, rewrite, *str, vec, matches))
  360. return false;
  361. assert(vec[0] >= 0);
  362. assert(vec[1] >= 0);
  363. str->replace(vec[0], vec[1] - vec[0], s);
  364. return true;
  365. }
  366. // Returns PCRE_NEWLINE_CRLF, PCRE_NEWLINE_CR, or PCRE_NEWLINE_LF.
  367. // Note that PCRE_NEWLINE_CRLF is defined to be P_N_CR | P_N_LF.
  368. // Modified by PH to add PCRE_NEWLINE_ANY and PCRE_NEWLINE_ANYCRLF.
  369. static int NewlineMode(int pcre_options) {
  370. // TODO: if we can make it threadsafe, cache this var
  371. int newline_mode = 0;
  372. /* if (newline_mode) return newline_mode; */ // do this once it's cached
  373. if (pcre_options & (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
  374. PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF)) {
  375. newline_mode = (pcre_options &
  376. (PCRE_NEWLINE_CRLF|PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|
  377. PCRE_NEWLINE_ANY|PCRE_NEWLINE_ANYCRLF));
  378. } else {
  379. int newline;
  380. pcre_config(PCRE_CONFIG_NEWLINE, &newline);
  381. if (newline == 10)
  382. newline_mode = PCRE_NEWLINE_LF;
  383. else if (newline == 13)
  384. newline_mode = PCRE_NEWLINE_CR;
  385. else if (newline == 3338)
  386. newline_mode = PCRE_NEWLINE_CRLF;
  387. else if (newline == -1)
  388. newline_mode = PCRE_NEWLINE_ANY;
  389. else if (newline == -2)
  390. newline_mode = PCRE_NEWLINE_ANYCRLF;
  391. else
  392. assert(NULL == "Unexpected return value from pcre_config(NEWLINE)");
  393. }
  394. return newline_mode;
  395. }
  396. int RE::GlobalReplace(const StringPiece& rewrite,
  397. string *str) const {
  398. int count = 0;
  399. int vec[kVecSize];
  400. string out;
  401. int start = 0;
  402. bool last_match_was_empty_string = false;
  403. while (start <= static_cast<int>(str->length())) {
  404. // If the previous match was for the empty string, we shouldn't
  405. // just match again: we'll match in the same way and get an
  406. // infinite loop. Instead, we do the match in a special way:
  407. // anchored -- to force another try at the same position --
  408. // and with a flag saying that this time, ignore empty matches.
  409. // If this special match returns, that means there's a non-empty
  410. // match at this position as well, and we can continue. If not,
  411. // we do what perl does, and just advance by one.
  412. // Notice that perl prints '@@@' for this;
  413. // perl -le '$_ = "aa"; s/b*|aa/@/g; print'
  414. int matches;
  415. if (last_match_was_empty_string) {
  416. matches = TryMatch(*str, start, ANCHOR_START, false, vec, kVecSize);
  417. if (matches <= 0) {
  418. int matchend = start + 1; // advance one character.
  419. // If the current char is CR and we're in CRLF mode, skip LF too.
  420. // Note it's better to call pcre_fullinfo() than to examine
  421. // all_options(), since options_ could have changed bewteen
  422. // compile-time and now, but this is simpler and safe enough.
  423. // Modified by PH to add ANY and ANYCRLF.
  424. if (matchend < static_cast<int>(str->length()) &&
  425. (*str)[start] == '\r' && (*str)[matchend] == '\n' &&
  426. (NewlineMode(options_.all_options()) == PCRE_NEWLINE_CRLF ||
  427. NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANY ||
  428. NewlineMode(options_.all_options()) == PCRE_NEWLINE_ANYCRLF)) {
  429. matchend++;
  430. }
  431. // We also need to advance more than one char if we're in utf8 mode.
  432. #ifdef SUPPORT_UTF
  433. if (options_.utf8()) {
  434. while (matchend < static_cast<int>(str->length()) &&
  435. ((*str)[matchend] & 0xc0) == 0x80)
  436. matchend++;
  437. }
  438. #endif
  439. if (start < static_cast<int>(str->length()))
  440. out.append(*str, start, matchend - start);
  441. start = matchend;
  442. last_match_was_empty_string = false;
  443. continue;
  444. }
  445. } else {
  446. matches = TryMatch(*str, start, UNANCHORED, true, vec, kVecSize);
  447. if (matches <= 0)
  448. break;
  449. }
  450. int matchstart = vec[0], matchend = vec[1];
  451. assert(matchstart >= start);
  452. assert(matchend >= matchstart);
  453. out.append(*str, start, matchstart - start);
  454. Rewrite(&out, rewrite, *str, vec, matches);
  455. start = matchend;
  456. count++;
  457. last_match_was_empty_string = (matchstart == matchend);
  458. }
  459. if (count == 0)
  460. return 0;
  461. if (start < static_cast<int>(str->length()))
  462. out.append(*str, start, str->length() - start);
  463. swap(out, *str);
  464. return count;
  465. }
  466. bool RE::Extract(const StringPiece& rewrite,
  467. const StringPiece& text,
  468. string *out) const {
  469. int vec[kVecSize];
  470. int matches = TryMatch(text, 0, UNANCHORED, true, vec, kVecSize);
  471. if (matches == 0)
  472. return false;
  473. out->erase();
  474. return Rewrite(out, rewrite, text, vec, matches);
  475. }
  476. /*static*/ string RE::QuoteMeta(const StringPiece& unquoted) {
  477. string result;
  478. // Escape any ascii character not in [A-Za-z_0-9].
  479. //
  480. // Note that it's legal to escape a character even if it has no
  481. // special meaning in a regular expression -- so this function does
  482. // that. (This also makes it identical to the perl function of the
  483. // same name; see `perldoc -f quotemeta`.) The one exception is
  484. // escaping NUL: rather than doing backslash + NUL, like perl does,
  485. // we do '\0', because pcre itself doesn't take embedded NUL chars.
  486. for (int ii = 0; ii < unquoted.size(); ++ii) {
  487. // Note that using 'isalnum' here raises the benchmark time from
  488. // 32ns to 58ns:
  489. if (unquoted[ii] == '\0') {
  490. result += "\\0";
  491. } else if ((unquoted[ii] < 'a' || unquoted[ii] > 'z') &&
  492. (unquoted[ii] < 'A' || unquoted[ii] > 'Z') &&
  493. (unquoted[ii] < '0' || unquoted[ii] > '9') &&
  494. unquoted[ii] != '_' &&
  495. // If this is the part of a UTF8 or Latin1 character, we need
  496. // to copy this byte without escaping. Experimentally this is
  497. // what works correctly with the regexp library.
  498. !(unquoted[ii] & 128)) {
  499. result += '\\';
  500. result += unquoted[ii];
  501. } else {
  502. result += unquoted[ii];
  503. }
  504. }
  505. return result;
  506. }
  507. /***** Actual matching and rewriting code *****/
  508. int RE::TryMatch(const StringPiece& text,
  509. int startpos,
  510. Anchor anchor,
  511. bool empty_ok,
  512. int *vec,
  513. int vecsize) const {
  514. pcre* re = (anchor == ANCHOR_BOTH) ? re_full_ : re_partial_;
  515. if (re == NULL) {
  516. //fprintf(stderr, "Matching against invalid re: %s\n", error_->c_str());
  517. return 0;
  518. }
  519. pcre_extra extra = { 0, 0, 0, 0, 0, 0, 0, 0 };
  520. if (options_.match_limit() > 0) {
  521. extra.flags |= PCRE_EXTRA_MATCH_LIMIT;
  522. extra.match_limit = options_.match_limit();
  523. }
  524. if (options_.match_limit_recursion() > 0) {
  525. extra.flags |= PCRE_EXTRA_MATCH_LIMIT_RECURSION;
  526. extra.match_limit_recursion = options_.match_limit_recursion();
  527. }
  528. // int options = 0;
  529. // Changed by PH as a result of bugzilla #1288
  530. int options = (options_.all_options() & PCRE_NO_UTF8_CHECK);
  531. if (anchor != UNANCHORED)
  532. options |= PCRE_ANCHORED;
  533. if (!empty_ok)
  534. options |= PCRE_NOTEMPTY;
  535. int rc = pcre_exec(re, // The regular expression object
  536. &extra,
  537. (text.data() == NULL) ? "" : text.data(),
  538. text.size(),
  539. startpos,
  540. options,
  541. vec,
  542. vecsize);
  543. // Handle errors
  544. if (rc == PCRE_ERROR_NOMATCH) {
  545. return 0;
  546. } else if (rc < 0) {
  547. //fprintf(stderr, "Unexpected return code: %d when matching '%s'\n",
  548. // re, pattern_.c_str());
  549. return 0;
  550. } else if (rc == 0) {
  551. // pcre_exec() returns 0 as a special case when the number of
  552. // capturing subpatterns exceeds the size of the vector.
  553. // When this happens, there is a match and the output vector
  554. // is filled, but we miss out on the positions of the extra subpatterns.
  555. rc = vecsize / 2;
  556. }
  557. return rc;
  558. }
  559. bool RE::DoMatchImpl(const StringPiece& text,
  560. Anchor anchor,
  561. int* consumed,
  562. const Arg* const* args,
  563. int n,
  564. int* vec,
  565. int vecsize) const {
  566. assert((1 + n) * 3 <= vecsize); // results + PCRE workspace
  567. int matches = TryMatch(text, 0, anchor, true, vec, vecsize);
  568. assert(matches >= 0); // TryMatch never returns negatives
  569. if (matches == 0)
  570. return false;
  571. *consumed = vec[1];
  572. if (n == 0 || args == NULL) {
  573. // We are not interested in results
  574. return true;
  575. }
  576. if (NumberOfCapturingGroups() < n) {
  577. // RE has fewer capturing groups than number of arg pointers passed in
  578. return false;
  579. }
  580. // If we got here, we must have matched the whole pattern.
  581. // We do not need (can not do) any more checks on the value of 'matches' here
  582. // -- see the comment for TryMatch.
  583. for (int i = 0; i < n; i++) {
  584. const int start = vec[2*(i+1)];
  585. const int limit = vec[2*(i+1)+1];
  586. if (!args[i]->Parse(text.data() + start, limit-start)) {
  587. // TODO: Should we indicate what the error was?
  588. return false;
  589. }
  590. }
  591. return true;
  592. }
  593. bool RE::DoMatch(const StringPiece& text,
  594. Anchor anchor,
  595. int* consumed,
  596. const Arg* const args[],
  597. int n) const {
  598. assert(n >= 0);
  599. size_t const vecsize = (1 + n) * 3; // results + PCRE workspace
  600. // (as for kVecSize)
  601. int space[21]; // use stack allocation for small vecsize (common case)
  602. int* vec = vecsize <= 21 ? space : new int[vecsize];
  603. bool retval = DoMatchImpl(text, anchor, consumed, args, n, vec, (int)vecsize);
  604. if (vec != space) delete [] vec;
  605. return retval;
  606. }
  607. bool RE::Rewrite(string *out, const StringPiece &rewrite,
  608. const StringPiece &text, int *vec, int veclen) const {
  609. for (const char *s = rewrite.data(), *end = s + rewrite.size();
  610. s < end; s++) {
  611. int c = *s;
  612. if (c == '\\') {
  613. c = *++s;
  614. if (isdigit(c)) {
  615. int n = (c - '0');
  616. if (n >= veclen) {
  617. //fprintf(stderr, requested group %d in regexp %.*s\n",
  618. // n, rewrite.size(), rewrite.data());
  619. return false;
  620. }
  621. int start = vec[2 * n];
  622. if (start >= 0)
  623. out->append(text.data() + start, vec[2 * n + 1] - start);
  624. } else if (c == '\\') {
  625. *out += '\\';
  626. } else {
  627. //fprintf(stderr, "invalid rewrite pattern: %.*s\n",
  628. // rewrite.size(), rewrite.data());
  629. return false;
  630. }
  631. } else {
  632. *out += c;
  633. }
  634. }
  635. return true;
  636. }
  637. // Return the number of capturing subpatterns, or -1 if the
  638. // regexp wasn't valid on construction.
  639. int RE::NumberOfCapturingGroups() const {
  640. if (re_partial_ == NULL) return -1;
  641. int result;
  642. int pcre_retval = pcre_fullinfo(re_partial_, // The regular expression object
  643. NULL, // We did not study the pattern
  644. PCRE_INFO_CAPTURECOUNT,
  645. &result);
  646. assert(pcre_retval == 0);
  647. return result;
  648. }
  649. /***** Parsers for various types *****/
  650. bool Arg::parse_null(const char* str, int n, void* dest) {
  651. (void)str;
  652. (void)n;
  653. // We fail if somebody asked us to store into a non-NULL void* pointer
  654. return (dest == NULL);
  655. }
  656. bool Arg::parse_string(const char* str, int n, void* dest) {
  657. if (dest == NULL) return true;
  658. reinterpret_cast<string*>(dest)->assign(str, n);
  659. return true;
  660. }
  661. bool Arg::parse_stringpiece(const char* str, int n, void* dest) {
  662. if (dest == NULL) return true;
  663. reinterpret_cast<StringPiece*>(dest)->set(str, n);
  664. return true;
  665. }
  666. bool Arg::parse_char(const char* str, int n, void* dest) {
  667. if (n != 1) return false;
  668. if (dest == NULL) return true;
  669. *(reinterpret_cast<char*>(dest)) = str[0];
  670. return true;
  671. }
  672. bool Arg::parse_uchar(const char* str, int n, void* dest) {
  673. if (n != 1) return false;
  674. if (dest == NULL) return true;
  675. *(reinterpret_cast<unsigned char*>(dest)) = str[0];
  676. return true;
  677. }
  678. // Largest number spec that we are willing to parse
  679. static const int kMaxNumberLength = 32;
  680. // REQUIRES "buf" must have length at least kMaxNumberLength+1
  681. // REQUIRES "n > 0"
  682. // Copies "str" into "buf" and null-terminates if necessary.
  683. // Returns one of:
  684. // a. "str" if no termination is needed
  685. // b. "buf" if the string was copied and null-terminated
  686. // c. "" if the input was invalid and has no hope of being parsed
  687. static const char* TerminateNumber(char* buf, const char* str, int n) {
  688. if ((n > 0) && isspace(*str)) {
  689. // We are less forgiving than the strtoxxx() routines and do not
  690. // allow leading spaces.
  691. return "";
  692. }
  693. // See if the character right after the input text may potentially
  694. // look like a digit.
  695. if (isdigit(str[n]) ||
  696. ((str[n] >= 'a') && (str[n] <= 'f')) ||
  697. ((str[n] >= 'A') && (str[n] <= 'F'))) {
  698. if (n > kMaxNumberLength) return ""; // Input too big to be a valid number
  699. memcpy(buf, str, n);
  700. buf[n] = '\0';
  701. return buf;
  702. } else {
  703. // We can parse right out of the supplied string, so return it.
  704. return str;
  705. }
  706. }
  707. bool Arg::parse_long_radix(const char* str,
  708. int n,
  709. void* dest,
  710. int radix) {
  711. if (n == 0) return false;
  712. char buf[kMaxNumberLength+1];
  713. str = TerminateNumber(buf, str, n);
  714. char* end;
  715. errno = 0;
  716. long r = strtol(str, &end, radix);
  717. if (end != str + n) return false; // Leftover junk
  718. if (errno) return false;
  719. if (dest == NULL) return true;
  720. *(reinterpret_cast<long*>(dest)) = r;
  721. return true;
  722. }
  723. bool Arg::parse_ulong_radix(const char* str,
  724. int n,
  725. void* dest,
  726. int radix) {
  727. if (n == 0) return false;
  728. char buf[kMaxNumberLength+1];
  729. str = TerminateNumber(buf, str, n);
  730. if (str[0] == '-') return false; // strtoul() on a negative number?!
  731. char* end;
  732. errno = 0;
  733. unsigned long r = strtoul(str, &end, radix);
  734. if (end != str + n) return false; // Leftover junk
  735. if (errno) return false;
  736. if (dest == NULL) return true;
  737. *(reinterpret_cast<unsigned long*>(dest)) = r;
  738. return true;
  739. }
  740. bool Arg::parse_short_radix(const char* str,
  741. int 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 (r < SHRT_MIN || r > SHRT_MAX) return false; // Out of range
  747. if (dest == NULL) return true;
  748. *(reinterpret_cast<short*>(dest)) = static_cast<short>(r);
  749. return true;
  750. }
  751. bool Arg::parse_ushort_radix(const char* str,
  752. int 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 (r > USHRT_MAX) return false; // Out of range
  758. if (dest == NULL) return true;
  759. *(reinterpret_cast<unsigned short*>(dest)) = static_cast<unsigned short>(r);
  760. return true;
  761. }
  762. bool Arg::parse_int_radix(const char* str,
  763. int n,
  764. void* dest,
  765. int radix) {
  766. long r;
  767. if (!parse_long_radix(str, n, &r, radix)) return false; // Could not parse
  768. if (r < INT_MIN || r > INT_MAX) return false; // Out of range
  769. if (dest == NULL) return true;
  770. *(reinterpret_cast<int*>(dest)) = r;
  771. return true;
  772. }
  773. bool Arg::parse_uint_radix(const char* str,
  774. int n,
  775. void* dest,
  776. int radix) {
  777. unsigned long r;
  778. if (!parse_ulong_radix(str, n, &r, radix)) return false; // Could not parse
  779. if (r > UINT_MAX) return false; // Out of range
  780. if (dest == NULL) return true;
  781. *(reinterpret_cast<unsigned int*>(dest)) = r;
  782. return true;
  783. }
  784. bool Arg::parse_longlong_radix(const char* str,
  785. int n,
  786. void* dest,
  787. int radix) {
  788. #ifndef HAVE_LONG_LONG
  789. return false;
  790. #else
  791. if (n == 0) return false;
  792. char buf[kMaxNumberLength+1];
  793. str = TerminateNumber(buf, str, n);
  794. char* end;
  795. errno = 0;
  796. #if defined HAVE_STRTOQ
  797. long long r = strtoq(str, &end, radix);
  798. #elif defined HAVE_STRTOLL
  799. long long r = strtoll(str, &end, radix);
  800. #elif defined HAVE__STRTOI64
  801. long long r = _strtoi64(str, &end, radix);
  802. #elif defined HAVE_STRTOIMAX
  803. long long r = strtoimax(str, &end, radix);
  804. #else
  805. #error parse_longlong_radix: cannot convert input to a long-long
  806. #endif
  807. if (end != str + n) return false; // Leftover junk
  808. if (errno) return false;
  809. if (dest == NULL) return true;
  810. *(reinterpret_cast<long long*>(dest)) = r;
  811. return true;
  812. #endif /* HAVE_LONG_LONG */
  813. }
  814. bool Arg::parse_ulonglong_radix(const char* str,
  815. int n,
  816. void* dest,
  817. int radix) {
  818. #ifndef HAVE_UNSIGNED_LONG_LONG
  819. return false;
  820. #else
  821. if (n == 0) return false;
  822. char buf[kMaxNumberLength+1];
  823. str = TerminateNumber(buf, str, n);
  824. if (str[0] == '-') return false; // strtoull() on a negative number?!
  825. char* end;
  826. errno = 0;
  827. #if defined HAVE_STRTOQ
  828. unsigned long long r = strtouq(str, &end, radix);
  829. #elif defined HAVE_STRTOLL
  830. unsigned long long r = strtoull(str, &end, radix);
  831. #elif defined HAVE__STRTOI64
  832. unsigned long long r = _strtoui64(str, &end, radix);
  833. #elif defined HAVE_STRTOIMAX
  834. unsigned long long r = strtoumax(str, &end, radix);
  835. #else
  836. #error parse_ulonglong_radix: cannot convert input to a long-long
  837. #endif
  838. if (end != str + n) return false; // Leftover junk
  839. if (errno) return false;
  840. if (dest == NULL) return true;
  841. *(reinterpret_cast<unsigned long long*>(dest)) = r;
  842. return true;
  843. #endif /* HAVE_UNSIGNED_LONG_LONG */
  844. }
  845. bool Arg::parse_double(const char* str, int n, void* dest) {
  846. if (n == 0) return false;
  847. static const int kMaxLength = 200;
  848. char buf[kMaxLength];
  849. if (n >= kMaxLength) return false;
  850. memcpy(buf, str, n);
  851. buf[n] = '\0';
  852. errno = 0;
  853. char* end;
  854. double r = strtod(buf, &end);
  855. if (end != buf + n) return false; // Leftover junk
  856. if (errno) return false;
  857. if (dest == NULL) return true;
  858. *(reinterpret_cast<double*>(dest)) = r;
  859. return true;
  860. }
  861. bool Arg::parse_float(const char* str, int n, void* dest) {
  862. double r;
  863. if (!parse_double(str, n, &r)) return false;
  864. if (dest == NULL) return true;
  865. *(reinterpret_cast<float*>(dest)) = static_cast<float>(r);
  866. return true;
  867. }
  868. #define DEFINE_INTEGER_PARSERS(name) \
  869. bool Arg::parse_##name(const char* str, int n, void* dest) { \
  870. return parse_##name##_radix(str, n, dest, 10); \
  871. } \
  872. bool Arg::parse_##name##_hex(const char* str, int n, void* dest) { \
  873. return parse_##name##_radix(str, n, dest, 16); \
  874. } \
  875. bool Arg::parse_##name##_octal(const char* str, int n, void* dest) { \
  876. return parse_##name##_radix(str, n, dest, 8); \
  877. } \
  878. bool Arg::parse_##name##_cradix(const char* str, int n, void* dest) { \
  879. return parse_##name##_radix(str, n, dest, 0); \
  880. }
  881. DEFINE_INTEGER_PARSERS(short) /* */
  882. DEFINE_INTEGER_PARSERS(ushort) /* */
  883. DEFINE_INTEGER_PARSERS(int) /* Don't use semicolons after these */
  884. DEFINE_INTEGER_PARSERS(uint) /* statements because they can cause */
  885. DEFINE_INTEGER_PARSERS(long) /* compiler warnings if the checking */
  886. DEFINE_INTEGER_PARSERS(ulong) /* level is turned up high enough. */
  887. DEFINE_INTEGER_PARSERS(longlong) /* */
  888. DEFINE_INTEGER_PARSERS(ulonglong) /* */
  889. #undef DEFINE_INTEGER_PARSERS
  890. } // namespace pcrecpp