pcrecpp.cc 34 KB

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