PageRenderTime 87ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/regex.c

https://bitbucket.org/cyanogenmod/android_external_lsof
C | 6328 lines | 3947 code | 971 blank | 1410 comment | 985 complexity | 3689ba3b841d387b5ac2efcd77106f5c MD5 | raw file
  1. /*
  2. * regex.c -- POSIX-conformant regular expression function set for the lsof
  3. * library
  4. *
  5. * This file is used when the UNIX dialect does not have a POSIX-conformant
  6. * regular expression function set. In that case USE_LIB_REGEX is defined.
  7. *
  8. * V. Abell <abe@purdue.edu>
  9. * Purdue University Computing Center
  10. */
  11. /*
  12. * Copyright 2000 Purdue Research Foundation, West Lafayette, Indiana
  13. * 47907. All rights reserved.
  14. *
  15. * Written by Victor A. Abell
  16. *
  17. * This software is not subject to any license of the American Telephone
  18. * and Telegraph Company or the Regents of the University of California.
  19. *
  20. * This software has been adapted from snprintf.c in sendmail 8.9.3. It
  21. * is subject to the sendmail copyright statements listed below, and the
  22. * sendmail licensing terms stated in the sendmail LICENSE file comment
  23. * section of this file.
  24. *
  25. * Permission is granted to anyone to use this software for any purpose on
  26. * any computer system, and to alter it and redistribute it freely, subject
  27. * to the following restrictions:
  28. *
  29. * 1. Neither the authors nor Purdue University are responsible for any
  30. * consequences of the use of this software.
  31. *
  32. * 2. The origin of this software must not be misrepresented, either by
  33. * explicit claim or by omission. Credit to the authors and Purdue
  34. * University must appear in documentation and sources.
  35. *
  36. * 3. Altered versions must be plainly marked as such, and must not be
  37. * misrepresented as being the original software.
  38. *
  39. * 4. This notice may not be removed or altered.
  40. */
  41. #include "../machine.h"
  42. #ifdef USE_LIB_REGEX
  43. /*
  44. * This file comes from GLIBC 2.2. It is used when the UNIX dialect does not
  45. * have a POSIX-conformant regular expression function set. In that case
  46. * USE_LIB_REGEX is defined.
  47. */
  48. /* Extended regular expression matching and search library,
  49. version 0.12.
  50. (Implements POSIX draft P1003.2/D11.2, except for some of the
  51. internationalization features.)
  52. Copyright (C) 1993-1999, 2000 Free Software Foundation, Inc.
  53. The GNU C Library is free software; you can redistribute it and/or
  54. modify it under the terms of the GNU Library General Public License as
  55. published by the Free Software Foundation; either version 2 of the
  56. License, or (at your option) any later version.
  57. The GNU C Library is distributed in the hope that it will be useful,
  58. but WITHOUT ANY WARRANTY; without even the implied warranty of
  59. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  60. Library General Public License for more details.
  61. You should have received a copy of the GNU Library General Public
  62. License along with the GNU C Library; see the file COPYING.LIB. If not,
  63. write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  64. Boston, MA 02111-1307, USA. */
  65. /* AIX requires this to be the first thing in the file. */
  66. #if defined _AIX && !defined REGEX_MALLOC
  67. #pragma alloca
  68. #endif
  69. #undef _GNU_SOURCE
  70. #define _GNU_SOURCE
  71. #ifdef HAVE_CONFIG_H
  72. # include <config.h>
  73. #endif
  74. #ifndef PARAMS
  75. # if defined __GNUC__ || (defined __STDC__ && __STDC__)
  76. # define PARAMS(args) args
  77. # else
  78. # define PARAMS(args) ()
  79. # endif /* GCC. */
  80. #endif /* Not PARAMS. */
  81. #if defined STDC_HEADERS && !defined emacs
  82. # include <stddef.h>
  83. #else
  84. /* We need this for `regex.h', and perhaps for the Emacs include files. */
  85. # include <sys/types.h>
  86. #endif
  87. #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
  88. /* For platform which support the ISO C amendement 1 functionality we
  89. support user defined character classes. */
  90. #if defined _LIBC || WIDE_CHAR_SUPPORT
  91. /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
  92. # include <wchar.h>
  93. # include <wctype.h>
  94. #endif
  95. #ifdef _LIBC
  96. /* We have to keep the namespace clean. */
  97. # define regfree(preg) __regfree (preg)
  98. # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
  99. # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
  100. # define regerror(errcode, preg, errbuf, errbuf_size) \
  101. __regerror(errcode, preg, errbuf, errbuf_size)
  102. # define re_set_registers(bu, re, nu, st, en) \
  103. __re_set_registers (bu, re, nu, st, en)
  104. # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
  105. __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
  106. # define re_match(bufp, string, size, pos, regs) \
  107. __re_match (bufp, string, size, pos, regs)
  108. # define re_search(bufp, string, size, startpos, range, regs) \
  109. __re_search (bufp, string, size, startpos, range, regs)
  110. # define re_compile_pattern(pattern, length, bufp) \
  111. __re_compile_pattern (pattern, length, bufp)
  112. # define re_set_syntax(syntax) __re_set_syntax (syntax)
  113. # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
  114. __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
  115. # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
  116. # define btowc __btowc
  117. /* We are also using some library internals. */
  118. # include <locale/localeinfo.h>
  119. # include <locale/elem-hash.h>
  120. # include <langinfo.h>
  121. #endif
  122. /* This is for other GNU distributions with internationalized messages. */
  123. #if HAVE_LIBINTL_H || defined _LIBC
  124. # include <libintl.h>
  125. # ifdef _LIBC
  126. # undef gettext
  127. # define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
  128. # endif
  129. #else
  130. # define gettext(msgid) (msgid)
  131. #endif
  132. #ifndef gettext_noop
  133. /* This define is so xgettext can find the internationalizable
  134. strings. */
  135. # define gettext_noop(String) String
  136. #endif
  137. /* The `emacs' switch turns on certain matching commands
  138. that make sense only in Emacs. */
  139. #ifdef emacs
  140. # include "lisp.h"
  141. # include "buffer.h"
  142. # include "syntax.h"
  143. #else /* not emacs */
  144. /* If we are not linking with Emacs proper,
  145. we can't use the relocating allocator
  146. even if config.h says that we can. */
  147. # undef REL_ALLOC
  148. # if defined STDC_HEADERS || defined _LIBC
  149. # include <stdlib.h>
  150. # else
  151. char *malloc ();
  152. char *realloc ();
  153. # endif
  154. /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
  155. If nothing else has been done, use the method below. */
  156. # ifdef INHIBIT_STRING_HEADER
  157. # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
  158. # if !defined bzero && !defined bcopy
  159. # undef INHIBIT_STRING_HEADER
  160. # endif
  161. # endif
  162. # endif
  163. /* This is the normal way of making sure we have a bcopy and a bzero.
  164. This is used in most programs--a few other programs avoid this
  165. by defining INHIBIT_STRING_HEADER. */
  166. # ifndef INHIBIT_STRING_HEADER
  167. # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
  168. # include <string.h>
  169. # ifndef bzero
  170. # ifndef _LIBC
  171. # define bzero(s, n) (memset (s, '\0', n), (s))
  172. # else
  173. # define bzero(s, n) __bzero (s, n)
  174. # endif
  175. # endif
  176. # else
  177. # include <strings.h>
  178. # ifndef memcmp
  179. # define memcmp(s1, s2, n) bcmp (s1, s2, n)
  180. # endif
  181. # ifndef memcpy
  182. # define memcpy(d, s, n) (bcopy (s, d, n), (d))
  183. # endif
  184. # endif
  185. # endif
  186. /* Define the syntax stuff for \<, \>, etc. */
  187. /* This must be nonzero for the wordchar and notwordchar pattern
  188. commands in re_match_2. */
  189. # ifndef Sword
  190. # define Sword 1
  191. # endif
  192. # ifdef SWITCH_ENUM_BUG
  193. # define SWITCH_ENUM_CAST(x) ((int)(x))
  194. # else
  195. # define SWITCH_ENUM_CAST(x) (x)
  196. # endif
  197. #endif /* not emacs */
  198. #if defined _LIBC || HAVE_LIMITS_H
  199. # include <limits.h>
  200. #endif
  201. #ifndef MB_LEN_MAX
  202. # define MB_LEN_MAX 1
  203. #endif
  204. /* Get the interface, including the syntax bits. */
  205. /* Disabled by V. Abell on January 29, 2001: #include <regex.h> */
  206. #include "../regex.h"
  207. /* isalpha etc. are used for the character classes. */
  208. #include <ctype.h>
  209. /* Jim Meyering writes:
  210. "... Some ctype macros are valid only for character codes that
  211. isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
  212. using /bin/cc or gcc but without giving an ansi option). So, all
  213. ctype uses should be through macros like ISPRINT... If
  214. STDC_HEADERS is defined, then autoconf has verified that the ctype
  215. macros don't need to be guarded with references to isascii. ...
  216. Defining isascii to 1 should let any compiler worth its salt
  217. eliminate the && through constant folding."
  218. Solaris defines some of these symbols so we must undefine them first. */
  219. #undef ISASCII
  220. #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
  221. # define ISASCII(c) 1
  222. #else
  223. # define ISASCII(c) isascii(c)
  224. #endif
  225. #ifdef isblank
  226. # define ISBLANK(c) (ISASCII (c) && isblank (c))
  227. #else
  228. # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
  229. #endif
  230. #ifdef isgraph
  231. # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
  232. #else
  233. # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
  234. #endif
  235. #undef ISPRINT
  236. #define ISPRINT(c) (ISASCII (c) && isprint (c))
  237. #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
  238. #define ISALNUM(c) (ISASCII (c) && isalnum (c))
  239. #define ISALPHA(c) (ISASCII (c) && isalpha (c))
  240. #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
  241. #define ISLOWER(c) (ISASCII (c) && islower (c))
  242. #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
  243. #define ISSPACE(c) (ISASCII (c) && isspace (c))
  244. #define ISUPPER(c) (ISASCII (c) && isupper (c))
  245. #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
  246. #ifdef _tolower
  247. # define TOLOWER(c) _tolower(c)
  248. #else
  249. # define TOLOWER(c) tolower(c)
  250. #endif
  251. #ifndef NULL
  252. # define NULL (void *)0
  253. #endif
  254. /* We remove any previous definition of `SIGN_EXTEND_CHAR',
  255. since ours (we hope) works properly with all combinations of
  256. machines, compilers, `char' and `unsigned char' argument types.
  257. (Per Bothner suggested the basic approach.) */
  258. #undef SIGN_EXTEND_CHAR
  259. #if __STDC__
  260. # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
  261. #else /* not __STDC__ */
  262. /* As in Harbison and Steele. */
  263. # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
  264. #endif
  265. #ifndef emacs
  266. /* How many characters in the character set. */
  267. # define CHAR_SET_SIZE 256
  268. # ifdef SYNTAX_TABLE
  269. extern char *re_syntax_table;
  270. # else /* not SYNTAX_TABLE */
  271. static char re_syntax_table[CHAR_SET_SIZE];
  272. static void
  273. init_syntax_once ()
  274. {
  275. register int c;
  276. static int done = 0;
  277. if (done)
  278. return;
  279. bzero (re_syntax_table, sizeof re_syntax_table);
  280. for (c = 0; c < CHAR_SET_SIZE; ++c)
  281. if (ISALNUM (c))
  282. re_syntax_table[c] = Sword;
  283. re_syntax_table['_'] = Sword;
  284. done = 1;
  285. }
  286. # endif /* not SYNTAX_TABLE */
  287. # define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
  288. #endif /* emacs */
  289. /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
  290. use `alloca' instead of `malloc'. This is because using malloc in
  291. re_search* or re_match* could cause memory leaks when C-g is used in
  292. Emacs; also, malloc is slower and causes storage fragmentation. On
  293. the other hand, malloc is more portable, and easier to debug.
  294. Because we sometimes use alloca, some routines have to be macros,
  295. not functions -- `alloca'-allocated space disappears at the end of the
  296. function it is called in. */
  297. #ifdef REGEX_MALLOC
  298. # define REGEX_ALLOCATE malloc
  299. # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
  300. # define REGEX_FREE free
  301. #else /* not REGEX_MALLOC */
  302. /* Emacs already defines alloca, sometimes. */
  303. # ifndef alloca
  304. /* Make alloca work the best possible way. */
  305. # ifdef __GNUC__
  306. # define alloca __builtin_alloca
  307. # else /* not __GNUC__ */
  308. # if HAVE_ALLOCA_H
  309. # include <alloca.h>
  310. # endif /* HAVE_ALLOCA_H */
  311. # endif /* not __GNUC__ */
  312. # endif /* not alloca */
  313. # define REGEX_ALLOCATE alloca
  314. /* Assumes a `char *destination' variable. */
  315. # define REGEX_REALLOCATE(source, osize, nsize) \
  316. (destination = (char *) alloca (nsize), \
  317. memcpy (destination, source, osize))
  318. /* No need to do anything to free, after alloca. */
  319. # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
  320. #endif /* not REGEX_MALLOC */
  321. /* Define how to allocate the failure stack. */
  322. #if defined REL_ALLOC && defined REGEX_MALLOC
  323. # define REGEX_ALLOCATE_STACK(size) \
  324. r_alloc (&failure_stack_ptr, (size))
  325. # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
  326. r_re_alloc (&failure_stack_ptr, (nsize))
  327. # define REGEX_FREE_STACK(ptr) \
  328. r_alloc_free (&failure_stack_ptr)
  329. #else /* not using relocating allocator */
  330. # ifdef REGEX_MALLOC
  331. # define REGEX_ALLOCATE_STACK malloc
  332. # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
  333. # define REGEX_FREE_STACK free
  334. # else /* not REGEX_MALLOC */
  335. # define REGEX_ALLOCATE_STACK alloca
  336. # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
  337. REGEX_REALLOCATE (source, osize, nsize)
  338. /* No need to explicitly free anything. */
  339. # define REGEX_FREE_STACK(arg)
  340. # endif /* not REGEX_MALLOC */
  341. #endif /* not using relocating allocator */
  342. /* True if `size1' is non-NULL and PTR is pointing anywhere inside
  343. `string1' or just past its end. This works if PTR is NULL, which is
  344. a good thing. */
  345. #define FIRST_STRING_P(ptr) \
  346. (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  347. /* (Re)Allocate N items of type T using malloc, or fail. */
  348. #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
  349. #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
  350. #define RETALLOC_IF(addr, n, t) \
  351. if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
  352. #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
  353. #define BYTEWIDTH 8 /* In bits. */
  354. #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
  355. #undef MAX
  356. #undef MIN
  357. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  358. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  359. typedef char boolean;
  360. #define false 0
  361. #define true 1
  362. static int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
  363. const char *string1, int size1,
  364. const char *string2, int size2,
  365. int pos,
  366. struct re_registers *regs,
  367. int stop));
  368. /* These are the command codes that appear in compiled regular
  369. expressions. Some opcodes are followed by argument bytes. A
  370. command code can specify any interpretation whatsoever for its
  371. arguments. Zero bytes may appear in the compiled regular expression. */
  372. typedef enum
  373. {
  374. no_op = 0,
  375. /* Succeed right away--no more backtracking. */
  376. succeed,
  377. /* Followed by one byte giving n, then by n literal bytes. */
  378. exactn,
  379. /* Matches any (more or less) character. */
  380. anychar,
  381. /* Matches any one char belonging to specified set. First
  382. following byte is number of bitmap bytes. Then come bytes
  383. for a bitmap saying which chars are in. Bits in each byte
  384. are ordered low-bit-first. A character is in the set if its
  385. bit is 1. A character too large to have a bit in the map is
  386. automatically not in the set. */
  387. charset,
  388. /* Same parameters as charset, but match any character that is
  389. not one of those specified. */
  390. charset_not,
  391. /* Start remembering the text that is matched, for storing in a
  392. register. Followed by one byte with the register number, in
  393. the range 0 to one less than the pattern buffer's re_nsub
  394. field. Then followed by one byte with the number of groups
  395. inner to this one. (This last has to be part of the
  396. start_memory only because we need it in the on_failure_jump
  397. of re_match_2.) */
  398. start_memory,
  399. /* Stop remembering the text that is matched and store it in a
  400. memory register. Followed by one byte with the register
  401. number, in the range 0 to one less than `re_nsub' in the
  402. pattern buffer, and one byte with the number of inner groups,
  403. just like `start_memory'. (We need the number of inner
  404. groups here because we don't have any easy way of finding the
  405. corresponding start_memory when we're at a stop_memory.) */
  406. stop_memory,
  407. /* Match a duplicate of something remembered. Followed by one
  408. byte containing the register number. */
  409. duplicate,
  410. /* Fail unless at beginning of line. */
  411. begline,
  412. /* Fail unless at end of line. */
  413. endline,
  414. /* Succeeds if at beginning of buffer (if emacs) or at beginning
  415. of string to be matched (if not). */
  416. begbuf,
  417. /* Analogously, for end of buffer/string. */
  418. endbuf,
  419. /* Followed by two byte relative address to which to jump. */
  420. jump,
  421. /* Same as jump, but marks the end of an alternative. */
  422. jump_past_alt,
  423. /* Followed by two-byte relative address of place to resume at
  424. in case of failure. */
  425. on_failure_jump,
  426. /* Like on_failure_jump, but pushes a placeholder instead of the
  427. current string position when executed. */
  428. on_failure_keep_string_jump,
  429. /* Throw away latest failure point and then jump to following
  430. two-byte relative address. */
  431. pop_failure_jump,
  432. /* Change to pop_failure_jump if know won't have to backtrack to
  433. match; otherwise change to jump. This is used to jump
  434. back to the beginning of a repeat. If what follows this jump
  435. clearly won't match what the repeat does, such that we can be
  436. sure that there is no use backtracking out of repetitions
  437. already matched, then we change it to a pop_failure_jump.
  438. Followed by two-byte address. */
  439. maybe_pop_jump,
  440. /* Jump to following two-byte address, and push a dummy failure
  441. point. This failure point will be thrown away if an attempt
  442. is made to use it for a failure. A `+' construct makes this
  443. before the first repeat. Also used as an intermediary kind
  444. of jump when compiling an alternative. */
  445. dummy_failure_jump,
  446. /* Push a dummy failure point and continue. Used at the end of
  447. alternatives. */
  448. push_dummy_failure,
  449. /* Followed by two-byte relative address and two-byte number n.
  450. After matching N times, jump to the address upon failure. */
  451. succeed_n,
  452. /* Followed by two-byte relative address, and two-byte number n.
  453. Jump to the address N times, then fail. */
  454. jump_n,
  455. /* Set the following two-byte relative address to the
  456. subsequent two-byte number. The address *includes* the two
  457. bytes of number. */
  458. set_number_at,
  459. wordchar, /* Matches any word-constituent character. */
  460. notwordchar, /* Matches any char that is not a word-constituent. */
  461. wordbeg, /* Succeeds if at word beginning. */
  462. wordend, /* Succeeds if at word end. */
  463. wordbound, /* Succeeds if at a word boundary. */
  464. notwordbound /* Succeeds if not at a word boundary. */
  465. #ifdef emacs
  466. ,before_dot, /* Succeeds if before point. */
  467. at_dot, /* Succeeds if at point. */
  468. after_dot, /* Succeeds if after point. */
  469. /* Matches any character whose syntax is specified. Followed by
  470. a byte which contains a syntax code, e.g., Sword. */
  471. syntaxspec,
  472. /* Matches any character whose syntax is not that specified. */
  473. notsyntaxspec
  474. #endif /* emacs */
  475. } re_opcode_t;
  476. /* Common operations on the compiled pattern. */
  477. /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
  478. #define STORE_NUMBER(destination, number) \
  479. do { \
  480. (destination)[0] = (number) & 0377; \
  481. (destination)[1] = (number) >> 8; \
  482. } while (0)
  483. /* Same as STORE_NUMBER, except increment DESTINATION to
  484. the byte after where the number is stored. Therefore, DESTINATION
  485. must be an lvalue. */
  486. #define STORE_NUMBER_AND_INCR(destination, number) \
  487. do { \
  488. STORE_NUMBER (destination, number); \
  489. (destination) += 2; \
  490. } while (0)
  491. /* Put into DESTINATION a number stored in two contiguous bytes starting
  492. at SOURCE. */
  493. #define EXTRACT_NUMBER(destination, source) \
  494. do { \
  495. (destination) = *(source) & 0377; \
  496. (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
  497. } while (0)
  498. #ifdef DEBUG
  499. static void extract_number _RE_ARGS ((int *dest, unsigned char *source));
  500. static void
  501. extract_number (dest, source)
  502. int *dest;
  503. unsigned char *source;
  504. {
  505. int temp = SIGN_EXTEND_CHAR (*(source + 1));
  506. *dest = *source & 0377;
  507. *dest += temp << 8;
  508. }
  509. # ifndef EXTRACT_MACROS /* To debug the macros. */
  510. # undef EXTRACT_NUMBER
  511. # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
  512. # endif /* not EXTRACT_MACROS */
  513. #endif /* DEBUG */
  514. /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
  515. SOURCE must be an lvalue. */
  516. #define EXTRACT_NUMBER_AND_INCR(destination, source) \
  517. do { \
  518. EXTRACT_NUMBER (destination, source); \
  519. (source) += 2; \
  520. } while (0)
  521. #ifdef DEBUG
  522. static void extract_number_and_incr _RE_ARGS ((int *destination,
  523. unsigned char **source));
  524. static void
  525. extract_number_and_incr (destination, source)
  526. int *destination;
  527. unsigned char **source;
  528. {
  529. extract_number (destination, *source);
  530. *source += 2;
  531. }
  532. # ifndef EXTRACT_MACROS
  533. # undef EXTRACT_NUMBER_AND_INCR
  534. # define EXTRACT_NUMBER_AND_INCR(dest, src) \
  535. extract_number_and_incr (&dest, &src)
  536. # endif /* not EXTRACT_MACROS */
  537. #endif /* DEBUG */
  538. /* If DEBUG is defined, Regex prints many voluminous messages about what
  539. it is doing (if the variable `debug' is nonzero). If linked with the
  540. main program in `iregex.c', you can enter patterns and strings
  541. interactively. And if linked with the main program in `main.c' and
  542. the other test files, you can run the already-written tests. */
  543. #ifdef DEBUG
  544. /* We use standard I/O for debugging. */
  545. # include <stdio.h>
  546. /* It is useful to test things that ``must'' be true when debugging. */
  547. # include <assert.h>
  548. static int debug;
  549. # define DEBUG_STATEMENT(e) e
  550. # define DEBUG_PRINT1(x) if (debug) printf (x)
  551. # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
  552. # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
  553. # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
  554. # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
  555. if (debug) print_partial_compiled_pattern (s, e)
  556. # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
  557. if (debug) print_double_string (w, s1, sz1, s2, sz2)
  558. /* Print the fastmap in human-readable form. */
  559. void
  560. print_fastmap (fastmap)
  561. char *fastmap;
  562. {
  563. unsigned was_a_range = 0;
  564. unsigned i = 0;
  565. while (i < (1 << BYTEWIDTH))
  566. {
  567. if (fastmap[i++])
  568. {
  569. was_a_range = 0;
  570. putchar (i - 1);
  571. while (i < (1 << BYTEWIDTH) && fastmap[i])
  572. {
  573. was_a_range = 1;
  574. i++;
  575. }
  576. if (was_a_range)
  577. {
  578. printf ("-");
  579. putchar (i - 1);
  580. }
  581. }
  582. }
  583. putchar ('\n');
  584. }
  585. /* Print a compiled pattern string in human-readable form, starting at
  586. the START pointer into it and ending just before the pointer END. */
  587. void
  588. print_partial_compiled_pattern (start, end)
  589. unsigned char *start;
  590. unsigned char *end;
  591. {
  592. int mcnt, mcnt2;
  593. unsigned char *p1;
  594. unsigned char *p = start;
  595. unsigned char *pend = end;
  596. if (start == NULL)
  597. {
  598. printf ("(null)\n");
  599. return;
  600. }
  601. /* Loop over pattern commands. */
  602. while (p < pend)
  603. {
  604. #ifdef _LIBC
  605. printf ("%t:\t", p - start);
  606. #else
  607. printf ("%ld:\t", (long int) (p - start));
  608. #endif
  609. switch ((re_opcode_t) *p++)
  610. {
  611. case no_op:
  612. printf ("/no_op");
  613. break;
  614. case exactn:
  615. mcnt = *p++;
  616. printf ("/exactn/%d", mcnt);
  617. do
  618. {
  619. putchar ('/');
  620. putchar (*p++);
  621. }
  622. while (--mcnt);
  623. break;
  624. case start_memory:
  625. mcnt = *p++;
  626. printf ("/start_memory/%d/%d", mcnt, *p++);
  627. break;
  628. case stop_memory:
  629. mcnt = *p++;
  630. printf ("/stop_memory/%d/%d", mcnt, *p++);
  631. break;
  632. case duplicate:
  633. printf ("/duplicate/%d", *p++);
  634. break;
  635. case anychar:
  636. printf ("/anychar");
  637. break;
  638. case charset:
  639. case charset_not:
  640. {
  641. register int c, last = -100;
  642. register int in_range = 0;
  643. printf ("/charset [%s",
  644. (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
  645. assert (p + *p < pend);
  646. for (c = 0; c < 256; c++)
  647. if (c / 8 < *p
  648. && (p[1 + (c/8)] & (1 << (c % 8))))
  649. {
  650. /* Are we starting a range? */
  651. if (last + 1 == c && ! in_range)
  652. {
  653. putchar ('-');
  654. in_range = 1;
  655. }
  656. /* Have we broken a range? */
  657. else if (last + 1 != c && in_range)
  658. {
  659. putchar (last);
  660. in_range = 0;
  661. }
  662. if (! in_range)
  663. putchar (c);
  664. last = c;
  665. }
  666. if (in_range)
  667. putchar (last);
  668. putchar (']');
  669. p += 1 + *p;
  670. }
  671. break;
  672. case begline:
  673. printf ("/begline");
  674. break;
  675. case endline:
  676. printf ("/endline");
  677. break;
  678. case on_failure_jump:
  679. extract_number_and_incr (&mcnt, &p);
  680. #ifdef _LIBC
  681. printf ("/on_failure_jump to %t", p + mcnt - start);
  682. #else
  683. printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
  684. #endif
  685. break;
  686. case on_failure_keep_string_jump:
  687. extract_number_and_incr (&mcnt, &p);
  688. #ifdef _LIBC
  689. printf ("/on_failure_keep_string_jump to %t", p + mcnt - start);
  690. #else
  691. printf ("/on_failure_keep_string_jump to %ld",
  692. (long int) (p + mcnt - start));
  693. #endif
  694. break;
  695. case dummy_failure_jump:
  696. extract_number_and_incr (&mcnt, &p);
  697. #ifdef _LIBC
  698. printf ("/dummy_failure_jump to %t", p + mcnt - start);
  699. #else
  700. printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
  701. #endif
  702. break;
  703. case push_dummy_failure:
  704. printf ("/push_dummy_failure");
  705. break;
  706. case maybe_pop_jump:
  707. extract_number_and_incr (&mcnt, &p);
  708. #ifdef _LIBC
  709. printf ("/maybe_pop_jump to %t", p + mcnt - start);
  710. #else
  711. printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
  712. #endif
  713. break;
  714. case pop_failure_jump:
  715. extract_number_and_incr (&mcnt, &p);
  716. #ifdef _LIBC
  717. printf ("/pop_failure_jump to %t", p + mcnt - start);
  718. #else
  719. printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
  720. #endif
  721. break;
  722. case jump_past_alt:
  723. extract_number_and_incr (&mcnt, &p);
  724. #ifdef _LIBC
  725. printf ("/jump_past_alt to %t", p + mcnt - start);
  726. #else
  727. printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
  728. #endif
  729. break;
  730. case jump:
  731. extract_number_and_incr (&mcnt, &p);
  732. #ifdef _LIBC
  733. printf ("/jump to %t", p + mcnt - start);
  734. #else
  735. printf ("/jump to %ld", (long int) (p + mcnt - start));
  736. #endif
  737. break;
  738. case succeed_n:
  739. extract_number_and_incr (&mcnt, &p);
  740. p1 = p + mcnt;
  741. extract_number_and_incr (&mcnt2, &p);
  742. #ifdef _LIBC
  743. printf ("/succeed_n to %t, %d times", p1 - start, mcnt2);
  744. #else
  745. printf ("/succeed_n to %ld, %d times",
  746. (long int) (p1 - start), mcnt2);
  747. #endif
  748. break;
  749. case jump_n:
  750. extract_number_and_incr (&mcnt, &p);
  751. p1 = p + mcnt;
  752. extract_number_and_incr (&mcnt2, &p);
  753. printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
  754. break;
  755. case set_number_at:
  756. extract_number_and_incr (&mcnt, &p);
  757. p1 = p + mcnt;
  758. extract_number_and_incr (&mcnt2, &p);
  759. #ifdef _LIBC
  760. printf ("/set_number_at location %t to %d", p1 - start, mcnt2);
  761. #else
  762. printf ("/set_number_at location %ld to %d",
  763. (long int) (p1 - start), mcnt2);
  764. #endif
  765. break;
  766. case wordbound:
  767. printf ("/wordbound");
  768. break;
  769. case notwordbound:
  770. printf ("/notwordbound");
  771. break;
  772. case wordbeg:
  773. printf ("/wordbeg");
  774. break;
  775. case wordend:
  776. printf ("/wordend");
  777. # ifdef emacs
  778. case before_dot:
  779. printf ("/before_dot");
  780. break;
  781. case at_dot:
  782. printf ("/at_dot");
  783. break;
  784. case after_dot:
  785. printf ("/after_dot");
  786. break;
  787. case syntaxspec:
  788. printf ("/syntaxspec");
  789. mcnt = *p++;
  790. printf ("/%d", mcnt);
  791. break;
  792. case notsyntaxspec:
  793. printf ("/notsyntaxspec");
  794. mcnt = *p++;
  795. printf ("/%d", mcnt);
  796. break;
  797. # endif /* emacs */
  798. case wordchar:
  799. printf ("/wordchar");
  800. break;
  801. case notwordchar:
  802. printf ("/notwordchar");
  803. break;
  804. case begbuf:
  805. printf ("/begbuf");
  806. break;
  807. case endbuf:
  808. printf ("/endbuf");
  809. break;
  810. default:
  811. printf ("?%d", *(p-1));
  812. }
  813. putchar ('\n');
  814. }
  815. #ifdef _LIBC
  816. printf ("%t:\tend of pattern.\n", p - start);
  817. #else
  818. printf ("%ld:\tend of pattern.\n", (long int) (p - start));
  819. #endif
  820. }
  821. void
  822. print_compiled_pattern (bufp)
  823. struct re_pattern_buffer *bufp;
  824. {
  825. unsigned char *buffer = bufp->buffer;
  826. print_partial_compiled_pattern (buffer, buffer + bufp->used);
  827. printf ("%ld bytes used/%ld bytes allocated.\n",
  828. bufp->used, bufp->allocated);
  829. if (bufp->fastmap_accurate && bufp->fastmap)
  830. {
  831. printf ("fastmap: ");
  832. print_fastmap (bufp->fastmap);
  833. }
  834. #ifdef _LIBC
  835. printf ("re_nsub: %Zd\t", bufp->re_nsub);
  836. #else
  837. printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
  838. #endif
  839. printf ("regs_alloc: %d\t", bufp->regs_allocated);
  840. printf ("can_be_null: %d\t", bufp->can_be_null);
  841. printf ("newline_anchor: %d\n", bufp->newline_anchor);
  842. printf ("no_sub: %d\t", bufp->no_sub);
  843. printf ("not_bol: %d\t", bufp->not_bol);
  844. printf ("not_eol: %d\t", bufp->not_eol);
  845. printf ("syntax: %lx\n", bufp->syntax);
  846. /* Perhaps we should print the translate table? */
  847. }
  848. void
  849. print_double_string (where, string1, size1, string2, size2)
  850. const char *where;
  851. const char *string1;
  852. const char *string2;
  853. int size1;
  854. int size2;
  855. {
  856. int this_char;
  857. if (where == NULL)
  858. printf ("(null)");
  859. else
  860. {
  861. if (FIRST_STRING_P (where))
  862. {
  863. for (this_char = where - string1; this_char < size1; this_char++)
  864. putchar (string1[this_char]);
  865. where = string2;
  866. }
  867. for (this_char = where - string2; this_char < size2; this_char++)
  868. putchar (string2[this_char]);
  869. }
  870. }
  871. void
  872. printchar (c)
  873. int c;
  874. {
  875. putc (c, stderr);
  876. }
  877. #else /* not DEBUG */
  878. # undef assert
  879. # define assert(e)
  880. # define DEBUG_STATEMENT(e)
  881. # define DEBUG_PRINT1(x)
  882. # define DEBUG_PRINT2(x1, x2)
  883. # define DEBUG_PRINT3(x1, x2, x3)
  884. # define DEBUG_PRINT4(x1, x2, x3, x4)
  885. # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
  886. # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
  887. #endif /* not DEBUG */
  888. /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
  889. also be assigned to arbitrarily: each pattern buffer stores its own
  890. syntax, so it can be changed between regex compilations. */
  891. /* This has no initializer because initialized variables in Emacs
  892. become read-only after dumping. */
  893. reg_syntax_t re_syntax_options;
  894. /* Specify the precise syntax of regexps for compilation. This provides
  895. for compatibility for various utilities which historically have
  896. different, incompatible syntaxes.
  897. The argument SYNTAX is a bit mask comprised of the various bits
  898. defined in regex.h. We return the old syntax. */
  899. reg_syntax_t
  900. re_set_syntax (syntax)
  901. reg_syntax_t syntax;
  902. {
  903. reg_syntax_t ret = re_syntax_options;
  904. re_syntax_options = syntax;
  905. #ifdef DEBUG
  906. if (syntax & RE_DEBUG)
  907. debug = 1;
  908. else if (debug) /* was on but now is not */
  909. debug = 0;
  910. #endif /* DEBUG */
  911. return ret;
  912. }
  913. #ifdef _LIBC
  914. weak_alias (__re_set_syntax, re_set_syntax)
  915. #endif
  916. /* This table gives an error message for each of the error codes listed
  917. in regex.h. Obviously the order here has to be same as there.
  918. POSIX doesn't require that we do anything for REG_NOERROR,
  919. but why not be nice? */
  920. static const char re_error_msgid[] =
  921. {
  922. #define REG_NOERROR_IDX 0
  923. gettext_noop ("Success") /* REG_NOERROR */
  924. "\0"
  925. #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
  926. gettext_noop ("No match") /* REG_NOMATCH */
  927. "\0"
  928. #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
  929. gettext_noop ("Invalid regular expression") /* REG_BADPAT */
  930. "\0"
  931. #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
  932. gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
  933. "\0"
  934. #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
  935. gettext_noop ("Invalid character class name") /* REG_ECTYPE */
  936. "\0"
  937. #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
  938. gettext_noop ("Trailing backslash") /* REG_EESCAPE */
  939. "\0"
  940. #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
  941. gettext_noop ("Invalid back reference") /* REG_ESUBREG */
  942. "\0"
  943. #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
  944. gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
  945. "\0"
  946. #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
  947. gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
  948. "\0"
  949. #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
  950. gettext_noop ("Unmatched \\{") /* REG_EBRACE */
  951. "\0"
  952. #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
  953. gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
  954. "\0"
  955. #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
  956. gettext_noop ("Invalid range end") /* REG_ERANGE */
  957. "\0"
  958. #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
  959. gettext_noop ("Memory exhausted") /* REG_ESPACE */
  960. "\0"
  961. #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
  962. gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
  963. "\0"
  964. #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
  965. gettext_noop ("Premature end of regular expression") /* REG_EEND */
  966. "\0"
  967. #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
  968. gettext_noop ("Regular expression too big") /* REG_ESIZE */
  969. "\0"
  970. #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
  971. gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
  972. };
  973. static const size_t re_error_msgid_idx[] =
  974. {
  975. REG_NOERROR_IDX,
  976. REG_NOMATCH_IDX,
  977. REG_BADPAT_IDX,
  978. REG_ECOLLATE_IDX,
  979. REG_ECTYPE_IDX,
  980. REG_EESCAPE_IDX,
  981. REG_ESUBREG_IDX,
  982. REG_EBRACK_IDX,
  983. REG_EPAREN_IDX,
  984. REG_EBRACE_IDX,
  985. REG_BADBR_IDX,
  986. REG_ERANGE_IDX,
  987. REG_ESPACE_IDX,
  988. REG_BADRPT_IDX,
  989. REG_EEND_IDX,
  990. REG_ESIZE_IDX,
  991. REG_ERPAREN_IDX
  992. };
  993. /* Avoiding alloca during matching, to placate r_alloc. */
  994. /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
  995. searching and matching functions should not call alloca. On some
  996. systems, alloca is implemented in terms of malloc, and if we're
  997. using the relocating allocator routines, then malloc could cause a
  998. relocation, which might (if the strings being searched are in the
  999. ralloc heap) shift the data out from underneath the regexp
  1000. routines.
  1001. Here's another reason to avoid allocation: Emacs
  1002. processes input from X in a signal handler; processing X input may
  1003. call malloc; if input arrives while a matching routine is calling
  1004. malloc, then we're scrod. But Emacs can't just block input while
  1005. calling matching routines; then we don't notice interrupts when
  1006. they come in. So, Emacs blocks input around all regexp calls
  1007. except the matching calls, which it leaves unprotected, in the
  1008. faith that they will not malloc. */
  1009. /* Normally, this is fine. */
  1010. #define MATCH_MAY_ALLOCATE
  1011. /* When using GNU C, we are not REALLY using the C alloca, no matter
  1012. what config.h may say. So don't take precautions for it. */
  1013. #ifdef __GNUC__
  1014. # undef C_ALLOCA
  1015. #endif
  1016. /* The match routines may not allocate if (1) they would do it with malloc
  1017. and (2) it's not safe for them to use malloc.
  1018. Note that if REL_ALLOC is defined, matching would not use malloc for the
  1019. failure stack, but we would still use it for the register vectors;
  1020. so REL_ALLOC should not affect this. */
  1021. #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
  1022. # undef MATCH_MAY_ALLOCATE
  1023. #endif
  1024. /* Failure stack declarations and macros; both re_compile_fastmap and
  1025. re_match_2 use a failure stack. These have to be macros because of
  1026. REGEX_ALLOCATE_STACK. */
  1027. /* Number of failure points for which to initially allocate space
  1028. when matching. If this number is exceeded, we allocate more
  1029. space, so it is not a hard limit. */
  1030. #ifndef INIT_FAILURE_ALLOC
  1031. # define INIT_FAILURE_ALLOC 5
  1032. #endif
  1033. /* Roughly the maximum number of failure points on the stack. Would be
  1034. exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
  1035. This is a variable only so users of regex can assign to it; we never
  1036. change it ourselves. */
  1037. #ifdef INT_IS_16BIT
  1038. # if defined MATCH_MAY_ALLOCATE
  1039. /* 4400 was enough to cause a crash on Alpha OSF/1,
  1040. whose default stack limit is 2mb. */
  1041. long int re_max_failures = 4000;
  1042. # else
  1043. long int re_max_failures = 2000;
  1044. # endif
  1045. union fail_stack_elt
  1046. {
  1047. unsigned char *pointer;
  1048. long int integer;
  1049. };
  1050. typedef union fail_stack_elt fail_stack_elt_t;
  1051. typedef struct
  1052. {
  1053. fail_stack_elt_t *stack;
  1054. unsigned long int size;
  1055. unsigned long int avail; /* Offset of next open position. */
  1056. } fail_stack_type;
  1057. #else /* not INT_IS_16BIT */
  1058. # if defined MATCH_MAY_ALLOCATE
  1059. /* 4400 was enough to cause a crash on Alpha OSF/1,
  1060. whose default stack limit is 2mb. */
  1061. int re_max_failures = 4000;
  1062. # else
  1063. int re_max_failures = 2000;
  1064. # endif
  1065. union fail_stack_elt
  1066. {
  1067. unsigned char *pointer;
  1068. int integer;
  1069. };
  1070. typedef union fail_stack_elt fail_stack_elt_t;
  1071. typedef struct
  1072. {
  1073. fail_stack_elt_t *stack;
  1074. unsigned size;
  1075. unsigned avail; /* Offset of next open position. */
  1076. } fail_stack_type;
  1077. #endif /* INT_IS_16BIT */
  1078. #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
  1079. #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
  1080. #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
  1081. /* Define macros to initialize and free the failure stack.
  1082. Do `return -2' if the alloc fails. */
  1083. #ifdef MATCH_MAY_ALLOCATE
  1084. # define INIT_FAIL_STACK() \
  1085. do { \
  1086. fail_stack.stack = (fail_stack_elt_t *) \
  1087. REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
  1088. \
  1089. if (fail_stack.stack == NULL) \
  1090. return -2; \
  1091. \
  1092. fail_stack.size = INIT_FAILURE_ALLOC; \
  1093. fail_stack.avail = 0; \
  1094. } while (0)
  1095. # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
  1096. #else
  1097. # define INIT_FAIL_STACK() \
  1098. do { \
  1099. fail_stack.avail = 0; \
  1100. } while (0)
  1101. # define RESET_FAIL_STACK()
  1102. #endif
  1103. /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
  1104. Return 1 if succeeds, and 0 if either ran out of memory
  1105. allocating space for it or it was already too large.
  1106. REGEX_REALLOCATE_STACK requires `destination' be declared. */
  1107. #define DOUBLE_FAIL_STACK(fail_stack) \
  1108. ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
  1109. ? 0 \
  1110. : ((fail_stack).stack = (fail_stack_elt_t *) \
  1111. REGEX_REALLOCATE_STACK ((fail_stack).stack, \
  1112. (fail_stack).size * sizeof (fail_stack_elt_t), \
  1113. ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
  1114. \
  1115. (fail_stack).stack == NULL \
  1116. ? 0 \
  1117. : ((fail_stack).size <<= 1, \
  1118. 1)))
  1119. /* Push pointer POINTER on FAIL_STACK.
  1120. Return 1 if was able to do so and 0 if ran out of memory allocating
  1121. space to do so. */
  1122. #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
  1123. ((FAIL_STACK_FULL () \
  1124. && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
  1125. ? 0 \
  1126. : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
  1127. 1))
  1128. /* Push a pointer value onto the failure stack.
  1129. Assumes the variable `fail_stack'. Probably should only
  1130. be called from within `PUSH_FAILURE_POINT'. */
  1131. #define PUSH_FAILURE_POINTER(item) \
  1132. fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
  1133. /* This pushes an integer-valued item onto the failure stack.
  1134. Assumes the variable `fail_stack'. Probably should only
  1135. be called from within `PUSH_FAILURE_POINT'. */
  1136. #define PUSH_FAILURE_INT(item) \
  1137. fail_stack.stack[fail_stack.avail++].integer = (item)
  1138. /* Push a fail_stack_elt_t value onto the failure stack.
  1139. Assumes the variable `fail_stack'. Probably should only
  1140. be called from within `PUSH_FAILURE_POINT'. */
  1141. #define PUSH_FAILURE_ELT(item) \
  1142. fail_stack.stack[fail_stack.avail++] = (item)
  1143. /* These three POP... operations complement the three PUSH... operations.
  1144. All assume that `fail_stack' is nonempty. */
  1145. #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
  1146. #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
  1147. #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
  1148. /* Used to omit pushing failure point id's when we're not debugging. */
  1149. #ifdef DEBUG
  1150. # define DEBUG_PUSH PUSH_FAILURE_INT
  1151. # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
  1152. #else
  1153. # define DEBUG_PUSH(item)
  1154. # define DEBUG_POP(item_addr)
  1155. #endif
  1156. /* Push the information about the state we will need
  1157. if we ever fail back to it.
  1158. Requires variables fail_stack, regstart, regend, reg_info, and
  1159. num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
  1160. be declared.
  1161. Does `return FAILURE_CODE' if runs out of memory. */
  1162. #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
  1163. do { \
  1164. char *destination; \
  1165. /* Must be int, so when we don't save any registers, the arithmetic \
  1166. of 0 + -1 isn't done as unsigned. */ \
  1167. /* Can't be int, since there is not a shred of a guarantee that int \
  1168. is wide enough to hold a value of something to which pointer can \
  1169. be assigned */ \
  1170. active_reg_t this_reg; \
  1171. \
  1172. DEBUG_STATEMENT (failure_id++); \
  1173. DEBUG_STATEMENT (nfailure_points_pushed++); \
  1174. DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
  1175. DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
  1176. DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
  1177. \
  1178. DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
  1179. DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
  1180. \
  1181. /* Ensure we have enough space allocated for what we will push. */ \
  1182. while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
  1183. { \
  1184. if (!DOUBLE_FAIL_STACK (fail_stack)) \
  1185. return failure_code; \
  1186. \
  1187. DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
  1188. (fail_stack).size); \
  1189. DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
  1190. } \
  1191. \
  1192. /* Push the info, starting with the registers. */ \
  1193. DEBUG_PRINT1 ("\n"); \
  1194. \
  1195. if (1) \
  1196. for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
  1197. this_reg++) \
  1198. { \
  1199. DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
  1200. DEBUG_STATEMENT (num_regs_pushed++); \
  1201. \
  1202. DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
  1203. PUSH_FAILURE_POINTER (regstart[this_reg]); \
  1204. \
  1205. DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
  1206. PUSH_FAILURE_POINTER (regend[this_reg]); \
  1207. \
  1208. DEBUG_PRINT2 (" info: %p\n ", \
  1209. reg_info[this_reg].word.pointer); \
  1210. DEBUG_PRINT2 (" match_null=%d", \
  1211. REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
  1212. DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
  1213. DEBUG_PRINT2 (" matched_something=%d", \
  1214. MATCHED_SOMETHING (reg_info[this_reg])); \
  1215. DEBUG_PRINT2 (" ever_matched=%d", \
  1216. EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
  1217. DEBUG_PRINT1 ("\n"); \
  1218. PUSH_FAILURE_ELT (reg_info[this_reg].word); \
  1219. } \
  1220. \
  1221. DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
  1222. PUSH_FAILURE_INT (lowest_active_reg); \
  1223. \
  1224. DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
  1225. PUSH_FAILURE_INT (highest_active_reg); \
  1226. \
  1227. DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
  1228. DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
  1229. PUSH_FAILURE_POINTER (pattern_place); \
  1230. \
  1231. DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
  1232. DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
  1233. size2); \
  1234. DEBUG_PRINT1 ("'\n"); \
  1235. PUSH_FAILURE_POINTER (string_place); \
  1236. \
  1237. DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
  1238. DEBUG_PUSH (failure_id); \
  1239. } while (0)
  1240. /* This is the number of items that are pushed and popped on the stack
  1241. for each register. */
  1242. #define NUM_REG_ITEMS 3
  1243. /* Individual items aside from the registers. */
  1244. #ifdef DEBUG
  1245. # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
  1246. #else
  1247. # define NUM_NONREG_ITEMS 4
  1248. #endif
  1249. /* We push at most this many items on the stack. */
  1250. /* We used to use (num_regs - 1), which is the number of registers
  1251. this regexp will save; but that was changed to 5
  1252. to avoid stack overflow for a regexp with lots of parens. */
  1253. #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
  1254. /* We actually push this many items. */
  1255. #define NUM_FAILURE_ITEMS \
  1256. (((0 \
  1257. ? 0 : highest_active_reg - lowest_active_reg + 1) \
  1258. * NUM_REG_ITEMS) \
  1259. + NUM_NONREG_ITEMS)
  1260. /* How many items can still be added to the stack without overflowing it. */
  1261. #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
  1262. /* Pops what PUSH_FAIL_STACK pushes.
  1263. We restore into the parameters, all of which should be lvalues:
  1264. STR -- the saved data position.
  1265. PAT -- the saved pattern position.
  1266. LOW_REG, HIGH_REG -- the highest and lowest active registers.
  1267. REGSTART, REGEND -- arrays of string positions.
  1268. REG_INFO -- array of information about each subexpression.
  1269. Also assumes the variables `fail_stack' and (if debugging), `bufp',
  1270. `pend', `string1', `size1', `string2', and `size2'. */
  1271. #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
  1272. { \
  1273. DEBUG_STATEMENT (unsigned failure_id;) \
  1274. active_reg_t this_reg; \
  1275. const unsigned char *string_temp; \
  1276. \
  1277. assert (!FAIL_STACK_EMPTY ()); \
  1278. \
  1279. /* Remove failure points and point to how many regs pushed. */ \
  1280. DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
  1281. DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
  1282. DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
  1283. \
  1284. assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
  1285. \
  1286. DEBUG_POP (&failure_id); \
  1287. DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
  1288. \
  1289. /* If the saved string location is NULL, it came from an \
  1290. on_failure_keep_string_jump opcode, and we want to throw away the \
  1291. saved NULL, thus retaining our current position in the string. */ \
  1292. string_temp = POP_FAILURE_POINTER (); \
  1293. if (string_temp != NULL) \
  1294. str = (const char *) string_temp; \
  1295. \
  1296. DEBUG_PRINT2 (" Popping string %p: `", str); \
  1297. DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
  1298. DEBUG_PRINT1 ("'\n"); \
  1299. \
  1300. pat = (unsigned char *) POP_FAILURE_POINTER (); \
  1301. DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
  1302. DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
  1303. \
  1304. /* Restore register info. */ \
  1305. high_reg = (active_reg_t) POP_FAILURE_INT (); \
  1306. DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
  1307. \
  1308. low_reg = (active_reg_t) POP_FAILURE_INT (); \
  1309. DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
  1310. \
  1311. if (1) \
  1312. for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
  1313. { \
  1314. DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
  1315. \
  1316. reg_info[this_reg].word = POP_FAILURE_ELT (); \
  1317. DEBUG_PRINT2 (" info: %p\n", \
  1318. reg_info[this_reg].word.pointer); \
  1319. \
  1320. regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
  1321. DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
  1322. \
  1323. regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
  1324. DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
  1325. } \
  1326. else \
  1327. { \
  1328. for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
  1329. { \
  1330. reg_info[this_reg].word.integer = 0; \
  1331. regend[this_reg] = 0; \
  1332. regstart[this_reg] = 0; \
  1333. } \
  1334. highest_active_reg = high_reg; \
  1335. } \
  1336. \
  1337. set_regs_matched_done = 0; \
  1338. DEBUG_STATEMENT (nfailure_points_popped++); \
  1339. } /* POP_FAILURE_POINT */
  1340. /* Structure for per-register (a.k.a. per-group) information.
  1341. Other register information, such as the
  1342. starting and ending positions (which are addresses), and the list of
  1343. inner groups (which is a bits list) are maintained in separate
  1344. variables.
  1345. We are making a (strictly speaking) nonportable assumption here: that
  1346. the compiler will pack our bit fields into something that fits into
  1347. the type of `word', i.e., is something that fits into one item on the
  1348. failure stack. */
  1349. /* Declarations and macros for re_match_2. */
  1350. typedef union
  1351. {
  1352. fail_stack_elt_t word;
  1353. struct
  1354. {
  1355. /* This field is one if this group can match the empty string,
  1356. zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
  1357. #define MATCH_NULL_UNSET_VALUE 3
  1358. unsigned match_null_string_p : 2;
  1359. unsigned is_active : 1;
  1360. unsigned matched_something : 1;
  1361. unsigned ever_matched_something : 1;
  1362. } bits;
  1363. } register_info_type;
  1364. #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
  1365. #define IS_ACTIVE(R) ((R).bits.is_active)
  1366. #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
  1367. #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
  1368. /* Call this when have matched a real character; it sets `matched' flags
  1369. for the subexpressions which we are currently inside. Also records
  1370. that those subexprs have matched. */
  1371. #define SET_REGS_MATCHED() \
  1372. do \
  1373. { \
  1374. if (!set_regs_matched_done) \
  1375. { \
  1376. active_reg_t r; \
  1377. set_regs_matched_done = 1; \
  1378. for (r = lowest_active_reg; r <= highest_active_reg; r++) \
  1379. { \
  1380. MATCHED_SOMETHING (reg_info[r]) \
  1381. = EVER_MATCHED_SOMETHING (reg_info[r]) \
  1382. = 1; \
  1383. } \
  1384. } \
  1385. } \
  1386. while (0)
  1387. /* Registers are set to a sentinel when they haven't yet matched. */
  1388. static char reg_unset_dummy;
  1389. #define REG_UNSET_VALUE (&reg_unset_dummy)
  1390. #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
  1391. /* Subroutine declarations and macros for regex_compile. */
  1392. static reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
  1393. reg_syntax_t syntax,
  1394. struct re_pattern_buffer *bufp));
  1395. static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
  1396. static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
  1397. int arg1, int arg2));
  1398. static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
  1399. int arg, unsigned char *end));
  1400. static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
  1401. int arg1, int arg2, unsigned char *end));
  1402. static boolean at_begline_loc_p _RE_ARGS ((const char *pattern, const char *p,
  1403. reg_syntax_t syntax));
  1404. static boolean at_endline_loc_p _RE_ARGS ((const char *p, const char *pend,
  1405. reg_syntax_t syntax));
  1406. static reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
  1407. const char **p_ptr,
  1408. const char *pend,
  1409. char *translate,
  1410. reg_syntax_t syntax,
  1411. unsigned char *b));
  1412. /* Fetch the next character in the uncompiled pattern---translating it
  1413. if necessary. Also cast from a signed character in the constant
  1414. string passed to us by the user to an unsigned char that we can use
  1415. as an array index (in, e.g., `translate'). */
  1416. #ifndef PATFETCH
  1417. # define PATFETCH(c) \
  1418. do {if (p == pend) return REG_EEND; \
  1419. c = (unsigned char) *p++; \
  1420. if (translate) c = (unsigned char) translate[c]; \
  1421. } while (0)
  1422. #endif
  1423. /* Fetch the next character in the uncompiled pattern, with no
  1424. translation. */
  1425. #define PATFETCH_RAW(c) \
  1426. do {if (p == pend) return REG_EEND; \
  1427. c = (unsigned char) *p++; \
  1428. } while (0)
  1429. /* Go backwards one character in the pattern. */
  1430. #define PATUNFETCH p--
  1431. /* If `translate' is non-null, return translate[D], else just D. We
  1432. cast the subscript to translate because some data is declared as
  1433. `char *', to avoid warnings when a string constant is passed. But
  1434. when we use a character as a subscript we must make it unsigned. */
  1435. #ifndef TRANSLATE
  1436. # define TRANSLATE(d) \
  1437. (translate ? (char) translate[(unsigned char) (d)] : (d))
  1438. #endif
  1439. /* Macros for outputting the compiled pattern into `buffer'. */
  1440. /* If the buffer isn't allocated when it comes in, use this. */
  1441. #define INIT_BUF_SIZE 32
  1442. /* Make sure we have at least N more bytes of space in buffer. */
  1443. #define GET_BUFFER_SPACE(n) \
  1444. while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
  1445. EXTEND_BUFFER ()
  1446. /* Make sure we have one more byte of buffer space and then add C to it. */
  1447. #define BUF_PUSH(c) \
  1448. do { \
  1449. GET_BUFFER_SPACE (1); \
  1450. *b++ = (unsigned char) (c); \
  1451. } while (0)
  1452. /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
  1453. #define BUF_PUSH_2(c1, c2) \
  1454. do { \
  1455. GET_BUFFER_SPACE (2); \
  1456. *b++ = (unsigned char) (c1); \
  1457. *b++ = (unsigned char) (c2); \
  1458. } while (0)
  1459. /* As with BUF_PUSH_2, except for three bytes. */
  1460. #define BUF_PUSH_3(c1, c2, c3) \
  1461. do { \
  1462. GET_BUFFER_SPACE (3); \
  1463. *b++ = (unsigned char) (c1); \
  1464. *b++ = (unsigned char) (c2); \
  1465. *b++ = (unsigned char) (c3); \
  1466. } while (0)
  1467. /* Store a jump with opcode OP at LOC to location TO. We store a
  1468. relative address offset by the three bytes the jump itself occupies. */
  1469. #define STORE_JUMP(op, loc, to) \
  1470. store_op1 (op, loc, (int) ((to) - (loc) - 3))
  1471. /* Likewise, for a two-argument jump. */
  1472. #define STORE_JUMP2(op, loc, to, arg) \
  1473. store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
  1474. /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
  1475. #define INSERT_JUMP(op, loc, to) \
  1476. insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
  1477. /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
  1478. #define INSERT_JUMP2(op, loc, to, arg) \
  1479. insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
  1480. /* This is not an arbitrary limit: the arguments which represent offsets
  1481. into the pattern are two bytes long. So if 2^16 bytes turns out to
  1482. be too small, many things would have to change. */
  1483. /* Any other compiler which, like MSC, has allocation limit below 2^16
  1484. bytes will have to use approach similar to what was done below for
  1485. MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
  1486. reallocating to 0 bytes. Such thing is not going to work too well.
  1487. You have been warned!! */
  1488. #if defined _MSC_VER && !defined WIN32
  1489. /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
  1490. The REALLOC define eliminates a flurry of conversion warnings,
  1491. but is not required. */
  1492. # define MAX_BUF_SIZE 65500L
  1493. # define REALLOC(p,s) realloc ((p), (size_t) (s))
  1494. #else
  1495. # define MAX_BUF_SIZE (1L << 16)
  1496. # define REALLOC(p,s) realloc ((p), (s))
  1497. #endif
  1498. /* Extend the buffer by twice its current size via realloc and
  1499. reset the pointers that pointed into the old block to point to the
  1500. correct places in the new one. If extending the buffer results in it
  1501. being larger than MAX_BUF_SIZE, then flag memory exhausted. */
  1502. #if __BOUNDED_POINTERS__
  1503. # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
  1504. # define MOVE_BUFFER_POINTER(P) \
  1505. (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
  1506. # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
  1507. else \
  1508. { \
  1509. SET_HIGH_BOUND (b); \
  1510. SET_HIGH_BOUND (begalt); \
  1511. if (fixup_alt_jump) \
  1512. SET_HIGH_BOUND (fixup_alt_jump); \
  1513. if (laststart) \
  1514. SET_HIGH_BOUND (laststart); \
  1515. if (pending_exact) \
  1516. SET_HIGH_BOUND (pending_exact); \
  1517. }
  1518. #else
  1519. # define MOVE_BUFFER_POINTER(P) (P) += incr
  1520. # define ELSE_EXTEND_BUFFER_HIGH_BOUND
  1521. #endif
  1522. #define EXTEND_BUFFER() \
  1523. do { \
  1524. unsigned char *old_buffer = bufp->buffer; \
  1525. if (bufp->allocated == MAX_BUF_SIZE) \
  1526. return REG_ESIZE; \
  1527. bufp->allocated <<= 1; \
  1528. if (bufp->allocated > MAX_BUF_SIZE) \
  1529. bufp->allocated = MAX_BUF_SIZE; \
  1530. bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
  1531. if (bufp->buffer == NULL) \
  1532. return REG_ESPACE; \
  1533. /* If the buffer moved, move all the pointers into it. */ \
  1534. if (old_buffer != bufp->buffer) \
  1535. { \
  1536. int incr = bufp->buffer - old_buffer; \
  1537. MOVE_BUFFER_POINTER (b); \
  1538. MOVE_BUFFER_POINTER (begalt); \
  1539. if (fixup_alt_jump) \
  1540. MOVE_BUFFER_POINTER (fixup_alt_jump); \
  1541. if (laststart) \
  1542. MOVE_BUFFER_POINTER (laststart); \
  1543. if (pending_exact) \
  1544. MOVE_BUFFER_POINTER (pending_exact); \
  1545. } \
  1546. ELSE_EXTEND_BUFFER_HIGH_BOUND \
  1547. } while (0)
  1548. /* Since we have one byte reserved for the register number argument to
  1549. {start,stop}_memory, the maximum number of groups we can report
  1550. things about is what fits in that byte. */
  1551. #define MAX_REGNUM 255
  1552. /* But patterns can have more than `MAX_REGNUM' registers. We just
  1553. ignore the excess. */
  1554. typedef unsigned regnum_t;
  1555. /* Macros for the compile stack. */
  1556. /* Since offsets can go either forwards or backwards, this type needs to
  1557. be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
  1558. /* int may be not enough when sizeof(int) == 2. */
  1559. typedef long pattern_offset_t;
  1560. typedef struct
  1561. {
  1562. pattern_offset_t begalt_offset;
  1563. pattern_offset_t fixup_alt_jump;
  1564. pattern_offset_t inner_group_offset;
  1565. pattern_offset_t laststart_offset;
  1566. regnum_t regnum;
  1567. } compile_stack_elt_t;
  1568. typedef struct
  1569. {
  1570. compile_stack_elt_t *stack;
  1571. unsigned size;
  1572. unsigned avail; /* Offset of next open position. */
  1573. } compile_stack_type;
  1574. #define INIT_COMPILE_STACK_SIZE 32
  1575. #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
  1576. #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
  1577. /* The next available element. */
  1578. #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
  1579. /* Set the bit for character C in a list. */
  1580. #define SET_LIST_BIT(c) \
  1581. (b[((unsigned char) (c)) / BYTEWIDTH] \
  1582. |= 1 << (((unsigned char) c) % BYTEWIDTH))
  1583. /* Get the next unsigned number in the uncompiled pattern. */
  1584. #define GET_UNSIGNED_NUMBER(num) \
  1585. { if (p != pend) \
  1586. { \
  1587. PATFETCH (c); \
  1588. while ('0' <= c && c <= '9') \
  1589. { \
  1590. if (num < 0) \
  1591. num = 0; \
  1592. num = num * 10 + c - '0'; \
  1593. if (p == pend) \
  1594. break; \
  1595. PATFETCH (c); \
  1596. } \
  1597. } \
  1598. }
  1599. #if defined _LIBC || WIDE_CHAR_SUPPORT
  1600. /* The GNU C library provides support for user-defined character classes
  1601. and the functions from ISO C amendement 1. */
  1602. # ifdef CHARCLASS_NAME_MAX
  1603. # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
  1604. # else
  1605. /* This shouldn't happen but some implementation might still have this
  1606. problem. Use a reasonable default value. */
  1607. # define CHAR_CLASS_MAX_LENGTH 256
  1608. # endif
  1609. # ifdef _LIBC
  1610. # define IS_CHAR_CLASS(string) __wctype (string)
  1611. # else
  1612. # define IS_CHAR_CLASS(string) wctype (string)
  1613. # endif
  1614. #else
  1615. # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
  1616. # define IS_CHAR_CLASS(string) \
  1617. (STREQ (string, "alpha") || STREQ (string, "upper") \
  1618. || STREQ (string, "lower") || STREQ (string, "digit") \
  1619. || STREQ (string, "alnum") || STREQ (string, "xdigit") \
  1620. || STREQ (string, "space") || STREQ (string, "print") \
  1621. || STREQ (string, "punct") || STREQ (string, "graph") \
  1622. || STREQ (string, "cntrl") || STREQ (string, "blank"))
  1623. #endif
  1624. #ifndef MATCH_MAY_ALLOCATE
  1625. /* If we cannot allocate large objects within re_match_2_internal,
  1626. we make the fail stack and register vectors global.
  1627. The fail stack, we grow to the maximum size when a regexp
  1628. is compiled.
  1629. The register vectors, we adjust in size each time we
  1630. compile a regexp, according to the number of registers it needs. */
  1631. static fail_stack_type fail_stack;
  1632. /* Size with which the following vectors are currently allocated.
  1633. That is so we can make them bigger as needed,
  1634. but never make them smaller. */
  1635. static int regs_allocated_size;
  1636. static const char ** regstart, ** regend;
  1637. static const char ** old_regstart, ** old_regend;
  1638. static const char **best_regstart, **best_regend;
  1639. static register_info_type *reg_info;
  1640. static const char **reg_dummy;
  1641. static register_info_type *reg_info_dummy;
  1642. /* Make the register vectors big enough for NUM_REGS registers,
  1643. but don't make them smaller. */
  1644. static
  1645. regex_grow_registers (num_regs)
  1646. int num_regs;
  1647. {
  1648. if (num_regs > regs_allocated_size)
  1649. {
  1650. RETALLOC_IF (regstart, num_regs, const char *);
  1651. RETALLOC_IF (regend, num_regs, const char *);
  1652. RETALLOC_IF (old_regstart, num_regs, const char *);
  1653. RETALLOC_IF (old_regend, num_regs, const char *);
  1654. RETALLOC_IF (best_regstart, num_regs, const char *);
  1655. RETALLOC_IF (best_regend, num_regs, const char *);
  1656. RETALLOC_IF (reg_info, num_regs, register_info_type);
  1657. RETALLOC_IF (reg_dummy, num_regs, const char *);
  1658. RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
  1659. regs_allocated_size = num_regs;
  1660. }
  1661. }
  1662. #endif /* not MATCH_MAY_ALLOCATE */
  1663. static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
  1664. compile_stack,
  1665. regnum_t regnum));
  1666. /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
  1667. Returns one of error codes defined in `regex.h', or zero for success.
  1668. Assumes the `allocated' (and perhaps `buffer') and `translate'
  1669. fields are set in BUFP on entry.
  1670. If it succeeds, results are put in BUFP (if it returns an error, the
  1671. contents of BUFP are undefined):
  1672. `buffer' is the compiled pattern;
  1673. `syntax' is set to SYNTAX;
  1674. `used' is set to the length of the compiled pattern;
  1675. `fastmap_accurate' is zero;
  1676. `re_nsub' is the number of subexpressions in PATTERN;
  1677. `not_bol' and `not_eol' are zero;
  1678. The `fastmap' and `newline_anchor' fields are neither
  1679. examined nor set. */
  1680. /* Return, freeing storage we allocated. */
  1681. #define FREE_STACK_RETURN(value) \
  1682. return (free (compile_stack.stack), value)
  1683. static reg_errcode_t
  1684. regex_compile (pattern, size, syntax, bufp)
  1685. const char *pattern;
  1686. size_t size;
  1687. reg_syntax_t syntax;
  1688. struct re_pattern_buffer *bufp;
  1689. {
  1690. /* We fetch characters from PATTERN here. Even though PATTERN is
  1691. `char *' (i.e., signed), we declare these variables as unsigned, so
  1692. they can be reliably used as array indices. */
  1693. register unsigned char c, c1;
  1694. /* A random temporary spot in PATTERN. */
  1695. const char *p1;
  1696. /* Points to the end of the buffer, where we should append. */
  1697. register unsigned char *b;
  1698. /* Keeps track of unclosed groups. */
  1699. compile_stack_type compile_stack;
  1700. /* Points to the current (ending) position in the pattern. */
  1701. const char *p = pattern;
  1702. const char *pend = pattern + size;
  1703. /* How to translate the characters in the pattern. */
  1704. RE_TRANSLATE_TYPE translate = bufp->translate;
  1705. /* Address of the count-byte of the most recently inserted `exactn'
  1706. command. This makes it possible to tell if a new exact-match
  1707. character can be added to that command or if the character requires
  1708. a new `exactn' command. */
  1709. unsigned char *pending_exact = 0;
  1710. /* Address of start of the most recently finished expression.
  1711. This tells, e.g., postfix * where to find the start of its
  1712. operand. Reset at the beginning of groups and alternatives. */
  1713. unsigned char *laststart = 0;
  1714. /* Address of beginning of regexp, or inside of last group. */
  1715. unsigned char *begalt;
  1716. /* Place in the uncompiled pattern (i.e., the {) to
  1717. which to go back if the interval is invalid. */
  1718. const char *beg_interval;
  1719. /* Address of the place where a forward jump should go to the end of
  1720. the containing expression. Each alternative of an `or' -- except the
  1721. last -- ends with a forward jump of this sort. */
  1722. unsigned char *fixup_alt_jump = 0;
  1723. /* Counts open-groups as they are encountered. Remembered for the
  1724. matching close-group on the compile stack, so the same register
  1725. number is put in the stop_memory as the start_memory. */
  1726. regnum_t regnum = 0;
  1727. #ifdef DEBUG
  1728. DEBUG_PRINT1 ("\nCompiling pattern: ");
  1729. if (debug)
  1730. {
  1731. unsigned debug_count;
  1732. for (debug_count = 0; debug_count < size; debug_count++)
  1733. putchar (pattern[debug_count]);
  1734. putchar ('\n');
  1735. }
  1736. #endif /* DEBUG */
  1737. /* Initialize the compile stack. */
  1738. compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
  1739. if (compile_stack.stack == NULL)
  1740. return REG_ESPACE;
  1741. compile_stack.size = INIT_COMPILE_STACK_SIZE;
  1742. compile_stack.avail = 0;
  1743. /* Initialize the pattern buffer. */
  1744. bufp->syntax = syntax;
  1745. bufp->fastmap_accurate = 0;
  1746. bufp->not_bol = bufp->not_eol = 0;
  1747. /* Set `used' to zero, so that if we return an error, the pattern
  1748. printer (for debugging) will think there's no pattern. We reset it
  1749. at the end. */
  1750. bufp->used = 0;
  1751. /* Always count groups, whether or not bufp->no_sub is set. */
  1752. bufp->re_nsub = 0;
  1753. #if !defined emacs && !defined SYNTAX_TABLE
  1754. /* Initialize the syntax table. */
  1755. init_syntax_once ();
  1756. #endif
  1757. if (bufp->allocated == 0)
  1758. {
  1759. if (bufp->buffer)
  1760. { /* If zero allocated, but buffer is non-null, try to realloc
  1761. enough space. This loses if buffer's address is bogus, but
  1762. that is the user's responsibility. */
  1763. RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
  1764. }
  1765. else
  1766. { /* Caller did not allocate a buffer. Do it for them. */
  1767. bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
  1768. }
  1769. if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
  1770. bufp->allocated = INIT_BUF_SIZE;
  1771. }
  1772. begalt = b = bufp->buffer;
  1773. /* Loop through the uncompiled pattern until we're at the end. */
  1774. while (p != pend)
  1775. {
  1776. PATFETCH (c);
  1777. switch (c)
  1778. {
  1779. case '^':
  1780. {
  1781. if ( /* If at start of pattern, it's an operator. */
  1782. p == pattern + 1
  1783. /* If context independent, it's an operator. */
  1784. || syntax & RE_CONTEXT_INDEP_ANCHORS
  1785. /* Otherwise, depends on what's come before. */
  1786. || at_begline_loc_p (pattern, p, syntax))
  1787. BUF_PUSH (begline);
  1788. else
  1789. goto normal_char;
  1790. }
  1791. break;
  1792. case '$':
  1793. {
  1794. if ( /* If at end of pattern, it's an operator. */
  1795. p == pend
  1796. /* If context independent, it's an operator. */
  1797. || syntax & RE_CONTEXT_INDEP_ANCHORS
  1798. /* Otherwise, depends on what's next. */
  1799. || at_endline_loc_p (p, pend, syntax))
  1800. BUF_PUSH (endline);
  1801. else
  1802. goto normal_char;
  1803. }
  1804. break;
  1805. case '+':
  1806. case '?':
  1807. if ((syntax & RE_BK_PLUS_QM)
  1808. || (syntax & RE_LIMITED_OPS))
  1809. goto normal_char;
  1810. handle_plus:
  1811. case '*':
  1812. /* If there is no previous pattern... */
  1813. if (!laststart)
  1814. {
  1815. if (syntax & RE_CONTEXT_INVALID_OPS)
  1816. FREE_STACK_RETURN (REG_BADRPT);
  1817. else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  1818. goto normal_char;
  1819. }
  1820. {
  1821. /* Are we optimizing this jump? */
  1822. boolean keep_string_p = false;
  1823. /* 1 means zero (many) matches is allowed. */
  1824. char zero_times_ok = 0, many_times_ok = 0;
  1825. /* If there is a sequence of repetition chars, collapse it
  1826. down to just one (the right one). We can't combine
  1827. interval operators with these because of, e.g., `a{2}*',
  1828. which should only match an even number of `a's. */
  1829. for (;;)
  1830. {
  1831. zero_times_ok |= c != '+';
  1832. many_times_ok |= c != '?';
  1833. if (p == pend)
  1834. break;
  1835. PATFETCH (c);
  1836. if (c == '*'
  1837. || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
  1838. ;
  1839. else if (syntax & RE_BK_PLUS_QM && c == '\\')
  1840. {
  1841. if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
  1842. PATFETCH (c1);
  1843. if (!(c1 == '+' || c1 == '?'))
  1844. {
  1845. PATUNFETCH;
  1846. PATUNFETCH;
  1847. break;
  1848. }
  1849. c = c1;
  1850. }
  1851. else
  1852. {
  1853. PATUNFETCH;
  1854. break;
  1855. }
  1856. /* If we get here, we found another repeat character. */
  1857. }
  1858. /* Star, etc. applied to an empty pattern is equivalent
  1859. to an empty pattern. */
  1860. if (!laststart)
  1861. break;
  1862. /* Now we know whether or not zero matches is allowed
  1863. and also whether or not two or more matches is allowed. */
  1864. if (many_times_ok)
  1865. { /* More than one repetition is allowed, so put in at the
  1866. end a backward relative jump from `b' to before the next
  1867. jump we're going to put in below (which jumps from
  1868. laststart to after this jump).
  1869. But if we are at the `*' in the exact sequence `.*\n',
  1870. insert an unconditional jump backwards to the .,
  1871. instead of the beginning of the loop. This way we only
  1872. push a failure point once, instead of every time
  1873. through the loop. */
  1874. assert (p - 1 > pattern);
  1875. /* Allocate the space for the jump. */
  1876. GET_BUFFER_SPACE (3);
  1877. /* We know we are not at the first character of the pattern,
  1878. because laststart was nonzero. And we've already
  1879. incremented `p', by the way, to be the character after
  1880. the `*'. Do we have to do something analogous here
  1881. for null bytes, because of RE_DOT_NOT_NULL? */
  1882. if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
  1883. && zero_times_ok
  1884. && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
  1885. && !(syntax & RE_DOT_NEWLINE))
  1886. { /* We have .*\n. */
  1887. STORE_JUMP (jump, b, laststart);
  1888. keep_string_p = true;
  1889. }
  1890. else
  1891. /* Anything else. */
  1892. STORE_JUMP (maybe_pop_jump, b, laststart - 3);
  1893. /* We've added more stuff to the buffer. */
  1894. b += 3;
  1895. }
  1896. /* On failure, jump from laststart to b + 3, which will be the
  1897. end of the buffer after this jump is inserted. */
  1898. GET_BUFFER_SPACE (3);
  1899. INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
  1900. : on_failure_jump,
  1901. laststart, b + 3);
  1902. pending_exact = 0;
  1903. b += 3;
  1904. if (!zero_times_ok)
  1905. {
  1906. /* At least one repetition is required, so insert a
  1907. `dummy_failure_jump' before the initial
  1908. `on_failure_jump' instruction of the loop. This
  1909. effects a skip over that instruction the first time
  1910. we hit that loop. */
  1911. GET_BUFFER_SPACE (3);
  1912. INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
  1913. b += 3;
  1914. }
  1915. }
  1916. break;
  1917. case '.':
  1918. laststart = b;
  1919. BUF_PUSH (anychar);
  1920. break;
  1921. case '[':
  1922. {
  1923. boolean had_char_class = false;
  1924. unsigned int range_start = 0xffffffff;
  1925. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  1926. /* Ensure that we have enough space to push a charset: the
  1927. opcode, the length count, and the bitset; 34 bytes in all. */
  1928. GET_BUFFER_SPACE (34);
  1929. laststart = b;
  1930. /* We test `*p == '^' twice, instead of using an if
  1931. statement, so we only need one BUF_PUSH. */
  1932. BUF_PUSH (*p == '^' ? charset_not : charset);
  1933. if (*p == '^')
  1934. p++;
  1935. /* Remember the first position in the bracket expression. */
  1936. p1 = p;
  1937. /* Push the number of bytes in the bitmap. */
  1938. BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  1939. /* Clear the whole map. */
  1940. bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  1941. /* charset_not matches newline according to a syntax bit. */
  1942. if ((re_opcode_t) b[-2] == charset_not
  1943. && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
  1944. SET_LIST_BIT ('\n');
  1945. /* Read in characters and ranges, setting map bits. */
  1946. for (;;)
  1947. {
  1948. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  1949. PATFETCH (c);
  1950. /* \ might escape characters inside [...] and [^...]. */
  1951. if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
  1952. {
  1953. if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
  1954. PATFETCH (c1);
  1955. SET_LIST_BIT (c1);
  1956. range_start = c1;
  1957. continue;
  1958. }
  1959. /* Could be the end of the bracket expression. If it's
  1960. not (i.e., when the bracket expression is `[]' so
  1961. far), the ']' character bit gets set way below. */
  1962. if (c == ']' && p != p1 + 1)
  1963. break;
  1964. /* Look ahead to see if it's a range when the last thing
  1965. was a character class. */
  1966. if (had_char_class && c == '-' && *p != ']')
  1967. FREE_STACK_RETURN (REG_ERANGE);
  1968. /* Look ahead to see if it's a range when the last thing
  1969. was a character: if this is a hyphen not at the
  1970. beginning or the end of a list, then it's the range
  1971. operator. */
  1972. if (c == '-'
  1973. && !(p - 2 >= pattern && p[-2] == '[')
  1974. && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
  1975. && *p != ']')
  1976. {
  1977. reg_errcode_t ret
  1978. = compile_range (range_start, &p, pend, translate,
  1979. syntax, b);
  1980. if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
  1981. range_start = 0xffffffff;
  1982. }
  1983. else if (p[0] == '-' && p[1] != ']')
  1984. { /* This handles ranges made up of characters only. */
  1985. reg_errcode_t ret;
  1986. /* Move past the `-'. */
  1987. PATFETCH (c1);
  1988. ret = compile_range (c, &p, pend, translate, syntax, b);
  1989. if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
  1990. range_start = 0xffffffff;
  1991. }
  1992. /* See if we're at the beginning of a possible character
  1993. class. */
  1994. else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
  1995. { /* Leave room for the null. */
  1996. char str[CHAR_CLASS_MAX_LENGTH + 1];
  1997. PATFETCH (c);
  1998. c1 = 0;
  1999. /* If pattern is `[[:'. */
  2000. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  2001. for (;;)
  2002. {
  2003. PATFETCH (c);
  2004. if ((c == ':' && *p == ']') || p == pend)
  2005. break;
  2006. if (c1 < CHAR_CLASS_MAX_LENGTH)
  2007. str[c1++] = c;
  2008. else
  2009. /* This is in any case an invalid class name. */
  2010. str[0] = '\0';
  2011. }
  2012. str[c1] = '\0';
  2013. /* If isn't a word bracketed by `[:' and `:]':
  2014. undo the ending character, the letters, and leave
  2015. the leading `:' and `[' (but set bits for them). */
  2016. if (c == ':' && *p == ']')
  2017. {
  2018. #if defined _LIBC || WIDE_CHAR_SUPPORT
  2019. boolean is_lower = STREQ (str, "lower");
  2020. boolean is_upper = STREQ (str, "upper");
  2021. wctype_t wt;
  2022. int ch;
  2023. wt = IS_CHAR_CLASS (str);
  2024. if (wt == 0)
  2025. FREE_STACK_RETURN (REG_ECTYPE);
  2026. /* Throw away the ] at the end of the character
  2027. class. */
  2028. PATFETCH (c);
  2029. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  2030. for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
  2031. {
  2032. # ifdef _LIBC
  2033. if (__iswctype (__btowc (ch), wt))
  2034. SET_LIST_BIT (ch);
  2035. # else
  2036. if (iswctype (btowc (ch), wt))
  2037. SET_LIST_BIT (ch);
  2038. # endif
  2039. if (translate && (is_upper || is_lower)
  2040. && (ISUPPER (ch) || ISLOWER (ch)))
  2041. SET_LIST_BIT (ch);
  2042. }
  2043. had_char_class = true;
  2044. #else
  2045. int ch;
  2046. boolean is_alnum = STREQ (str, "alnum");
  2047. boolean is_alpha = STREQ (str, "alpha");
  2048. boolean is_blank = STREQ (str, "blank");
  2049. boolean is_cntrl = STREQ (str, "cntrl");
  2050. boolean is_digit = STREQ (str, "digit");
  2051. boolean is_graph = STREQ (str, "graph");
  2052. boolean is_lower = STREQ (str, "lower");
  2053. boolean is_print = STREQ (str, "print");
  2054. boolean is_punct = STREQ (str, "punct");
  2055. boolean is_space = STREQ (str, "space");
  2056. boolean is_upper = STREQ (str, "upper");
  2057. boolean is_xdigit = STREQ (str, "xdigit");
  2058. if (!IS_CHAR_CLASS (str))
  2059. FREE_STACK_RETURN (REG_ECTYPE);
  2060. /* Throw away the ] at the end of the character
  2061. class. */
  2062. PATFETCH (c);
  2063. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  2064. for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
  2065. {
  2066. /* This was split into 3 if's to
  2067. avoid an arbitrary limit in some compiler. */
  2068. if ( (is_alnum && ISALNUM (ch))
  2069. || (is_alpha && ISALPHA (ch))
  2070. || (is_blank && ISBLANK (ch))
  2071. || (is_cntrl && ISCNTRL (ch)))
  2072. SET_LIST_BIT (ch);
  2073. if ( (is_digit && ISDIGIT (ch))
  2074. || (is_graph && ISGRAPH (ch))
  2075. || (is_lower && ISLOWER (ch))
  2076. || (is_print && ISPRINT (ch)))
  2077. SET_LIST_BIT (ch);
  2078. if ( (is_punct && ISPUNCT (ch))
  2079. || (is_space && ISSPACE (ch))
  2080. || (is_upper && ISUPPER (ch))
  2081. || (is_xdigit && ISXDIGIT (ch)))
  2082. SET_LIST_BIT (ch);
  2083. if ( translate && (is_upper || is_lower)
  2084. && (ISUPPER (ch) || ISLOWER (ch)))
  2085. SET_LIST_BIT (ch);
  2086. }
  2087. had_char_class = true;
  2088. #endif /* libc || wctype.h */
  2089. }
  2090. else
  2091. {
  2092. c1++;
  2093. while (c1--)
  2094. PATUNFETCH;
  2095. SET_LIST_BIT ('[');
  2096. SET_LIST_BIT (':');
  2097. range_start = ':';
  2098. had_char_class = false;
  2099. }
  2100. }
  2101. else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
  2102. {
  2103. unsigned char str[MB_LEN_MAX + 1];
  2104. #ifdef _LIBC
  2105. uint32_t nrules =
  2106. _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  2107. #endif
  2108. PATFETCH (c);
  2109. c1 = 0;
  2110. /* If pattern is `[[='. */
  2111. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  2112. for (;;)
  2113. {
  2114. PATFETCH (c);
  2115. if ((c == '=' && *p == ']') || p == pend)
  2116. break;
  2117. if (c1 < MB_LEN_MAX)
  2118. str[c1++] = c;
  2119. else
  2120. /* This is in any case an invalid class name. */
  2121. str[0] = '\0';
  2122. }
  2123. str[c1] = '\0';
  2124. if (c == '=' && *p == ']' && str[0] != '\0')
  2125. {
  2126. /* If we have no collation data we use the default
  2127. collation in which each character is in a class
  2128. by itself. It also means that ASCII is the
  2129. character set and therefore we cannot have character
  2130. with more than one byte in the multibyte
  2131. representation. */
  2132. #ifdef _LIBC
  2133. if (nrules == 0)
  2134. #endif
  2135. {
  2136. if (c1 != 1)
  2137. FREE_STACK_RETURN (REG_ECOLLATE);
  2138. /* Throw away the ] at the end of the equivalence
  2139. class. */
  2140. PATFETCH (c);
  2141. /* Set the bit for the character. */
  2142. SET_LIST_BIT (str[0]);
  2143. }
  2144. #ifdef _LIBC
  2145. else
  2146. {
  2147. /* Try to match the byte sequence in `str' against
  2148. those known to the collate implementation.
  2149. First find out whether the bytes in `str' are
  2150. actually from exactly one character. */
  2151. const int32_t *table;
  2152. const unsigned char *weights;
  2153. const unsigned char *extra;
  2154. const int32_t *indirect;
  2155. int32_t idx;
  2156. const unsigned char *cp = str;
  2157. int ch;
  2158. /* This #include defines a local function! */
  2159. # include <locale/weight.h>
  2160. table = (const int32_t *)
  2161. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
  2162. weights = (const unsigned char *)
  2163. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
  2164. extra = (const unsigned char *)
  2165. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
  2166. indirect = (const int32_t *)
  2167. _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
  2168. idx = findidx (&cp);
  2169. if (idx == 0 || cp < str + c1)
  2170. /* This is no valid character. */
  2171. FREE_STACK_RETURN (REG_ECOLLATE);
  2172. /* Throw away the ] at the end of the equivalence
  2173. class. */
  2174. PATFETCH (c);
  2175. /* Now we have to go throught the whole table
  2176. and find all characters which have the same
  2177. first level weight.
  2178. XXX Note that this is not entirely correct.
  2179. we would have to match multibyte sequences
  2180. but this is not possible with the current
  2181. implementation. */
  2182. for (ch = 1; ch < 256; ++ch)
  2183. /* XXX This test would have to be changed if we
  2184. would allow matching multibyte sequences. */
  2185. if (table[ch] > 0)
  2186. {
  2187. int32_t idx2 = table[ch];
  2188. size_t len = weights[idx2];
  2189. /* Test whether the lenghts match. */
  2190. if (weights[idx] == len)
  2191. {
  2192. /* They do. New compare the bytes of
  2193. the weight. */
  2194. size_t cnt = 0;
  2195. while (cnt < len
  2196. && (weights[idx + 1 + cnt]
  2197. == weights[idx2 + 1 + cnt]))
  2198. ++len;
  2199. if (cnt == len)
  2200. /* They match. Mark the character as
  2201. acceptable. */
  2202. SET_LIST_BIT (ch);
  2203. }
  2204. }
  2205. }
  2206. #endif
  2207. had_char_class = true;
  2208. }
  2209. else
  2210. {
  2211. c1++;
  2212. while (c1--)
  2213. PATUNFETCH;
  2214. SET_LIST_BIT ('[');
  2215. SET_LIST_BIT ('=');
  2216. range_start = '=';
  2217. had_char_class = false;
  2218. }
  2219. }
  2220. else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
  2221. {
  2222. unsigned char str[128]; /* Should be large enough. */
  2223. #ifdef _LIBC
  2224. uint32_t nrules =
  2225. _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
  2226. #endif
  2227. PATFETCH (c);
  2228. c1 = 0;
  2229. /* If pattern is `[[='. */
  2230. if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
  2231. for (;;)
  2232. {
  2233. PATFETCH (c);
  2234. if ((c == '.' && *p == ']') || p == pend)
  2235. break;
  2236. if (c1 < sizeof (str))
  2237. str[c1++] = c;
  2238. else
  2239. /* This is in any case an invalid class name. */
  2240. str[0] = '\0';
  2241. }
  2242. str[c1] = '\0';
  2243. if (c == '.' && *p == ']' && str[0] != '\0')
  2244. {
  2245. /* If we have no collation data we use the default
  2246. collation in which each character is the name
  2247. for its own class which contains only the one
  2248. character. It also means that ASCII is the
  2249. character set and therefore we cannot have character
  2250. with more than one byte in the multibyte
  2251. representation. */
  2252. #ifdef _LIBC
  2253. if (nrules == 0)
  2254. #endif
  2255. {
  2256. if (c1 != 1)
  2257. FREE_STACK_RETURN (REG_ECOLLATE);
  2258. /* Throw away the ] at the end of the equivalence
  2259. class. */
  2260. PATFETCH (c);
  2261. /* Set the bit for the character. */
  2262. SET_LIST_BIT (str[0]);
  2263. range_start = ((const unsigned char *) str)[0];
  2264. }
  2265. #ifdef _LIBC
  2266. else
  2267. {
  2268. /* Try to match the byte sequence in `str' against
  2269. those known to the collate implementation.
  2270. First find out whether the bytes in `str' are
  2271. actually from exactly one character. */
  2272. int32_t table_size;
  2273. const int32_t *symb_table;
  2274. const unsigned char *extra;
  2275. int32_t idx;
  2276. int32_t elem;
  2277. int32_t second;
  2278. int32_t hash;
  2279. table_size =
  2280. _NL_CURRENT_WORD (LC_COLLATE,
  2281. _NL_COLLATE_SYMB_HASH_SIZEMB);
  2282. symb_table = (const int32_t *)
  2283. _NL_CURRENT (LC_COLLATE,
  2284. _NL_COLLATE_SYMB_TABLEMB);
  2285. extra = (const unsigned char *)
  2286. _NL_CURRENT (LC_COLLATE,
  2287. _NL_COLLATE_SYMB_EXTRAMB);
  2288. /* Locate the character in the hashing table. */
  2289. hash = elem_hash (str, c1);
  2290. idx = 0;
  2291. elem = hash % table_size;
  2292. second = hash % (table_size - 2);
  2293. while (symb_table[2 * elem] != 0)
  2294. {
  2295. /* First compare the hashing value. */
  2296. if (symb_table[2 * elem] == hash
  2297. && c1 == extra[symb_table[2 * elem + 1]]
  2298. && memcmp (str,
  2299. &extra[symb_table[2 * elem + 1]
  2300. + 1],
  2301. c1) == 0)
  2302. {
  2303. /* Yep, this is the entry. */
  2304. idx = symb_table[2 * elem + 1];
  2305. idx += 1 + extra[idx];
  2306. break;
  2307. }
  2308. /* Next entry. */
  2309. elem += second;
  2310. }
  2311. if (symb_table[2 * elem] == 0)
  2312. /* This is no valid character. */
  2313. FREE_STACK_RETURN (REG_ECOLLATE);
  2314. /* Throw away the ] at the end of the equivalence
  2315. class. */
  2316. PATFETCH (c);
  2317. /* Now add the multibyte character(s) we found
  2318. to the accept list.
  2319. XXX Note that this is not entirely correct.
  2320. we would have to match multibyte sequences
  2321. but this is not possible with the current
  2322. implementation. Also, we have to match
  2323. collating symbols, which expand to more than
  2324. one file, as a whole and not allow the
  2325. individual bytes. */
  2326. c1 = extra[idx++];
  2327. if (c1 == 1)
  2328. range_start = extra[idx];
  2329. while (c1-- > 0)
  2330. {
  2331. SET_LIST_BIT (extra[idx]);
  2332. ++idx;
  2333. }
  2334. }
  2335. #endif
  2336. had_char_class = false;
  2337. }
  2338. else
  2339. {
  2340. c1++;
  2341. while (c1--)
  2342. PATUNFETCH;
  2343. SET_LIST_BIT ('[');
  2344. SET_LIST_BIT ('.');
  2345. range_start = '.';
  2346. had_char_class = false;
  2347. }
  2348. }
  2349. else
  2350. {
  2351. had_char_class = false;
  2352. SET_LIST_BIT (c);
  2353. range_start = c;
  2354. }
  2355. }
  2356. /* Discard any (non)matching list bytes that are all 0 at the
  2357. end of the map. Decrease the map-length byte too. */
  2358. while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
  2359. b[-1]--;
  2360. b += b[-1];
  2361. }
  2362. break;
  2363. case '(':
  2364. if (syntax & RE_NO_BK_PARENS)
  2365. goto handle_open;
  2366. else
  2367. goto normal_char;
  2368. case ')':
  2369. if (syntax & RE_NO_BK_PARENS)
  2370. goto handle_close;
  2371. else
  2372. goto normal_char;
  2373. case '\n':
  2374. if (syntax & RE_NEWLINE_ALT)
  2375. goto handle_alt;
  2376. else
  2377. goto normal_char;
  2378. case '|':
  2379. if (syntax & RE_NO_BK_VBAR)
  2380. goto handle_alt;
  2381. else
  2382. goto normal_char;
  2383. case '{':
  2384. if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
  2385. goto handle_interval;
  2386. else
  2387. goto normal_char;
  2388. case '\\':
  2389. if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
  2390. /* Do not translate the character after the \, so that we can
  2391. distinguish, e.g., \B from \b, even if we normally would
  2392. translate, e.g., B to b. */
  2393. PATFETCH_RAW (c);
  2394. switch (c)
  2395. {
  2396. case '(':
  2397. if (syntax & RE_NO_BK_PARENS)
  2398. goto normal_backslash;
  2399. handle_open:
  2400. bufp->re_nsub++;
  2401. regnum++;
  2402. if (COMPILE_STACK_FULL)
  2403. {
  2404. RETALLOC (compile_stack.stack, compile_stack.size << 1,
  2405. compile_stack_elt_t);
  2406. if (compile_stack.stack == NULL) return REG_ESPACE;
  2407. compile_stack.size <<= 1;
  2408. }
  2409. /* These are the values to restore when we hit end of this
  2410. group. They are all relative offsets, so that if the
  2411. whole pattern moves because of realloc, they will still
  2412. be valid. */
  2413. COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
  2414. COMPILE_STACK_TOP.fixup_alt_jump
  2415. = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
  2416. COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
  2417. COMPILE_STACK_TOP.regnum = regnum;
  2418. /* We will eventually replace the 0 with the number of
  2419. groups inner to this one. But do not push a
  2420. start_memory for groups beyond the last one we can
  2421. represent in the compiled pattern. */
  2422. if (regnum <= MAX_REGNUM)
  2423. {
  2424. COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
  2425. BUF_PUSH_3 (start_memory, regnum, 0);
  2426. }
  2427. compile_stack.avail++;
  2428. fixup_alt_jump = 0;
  2429. laststart = 0;
  2430. begalt = b;
  2431. /* If we've reached MAX_REGNUM groups, then this open
  2432. won't actually generate any code, so we'll have to
  2433. clear pending_exact explicitly. */
  2434. pending_exact = 0;
  2435. break;
  2436. case ')':
  2437. if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
  2438. if (COMPILE_STACK_EMPTY)
  2439. {
  2440. if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  2441. goto normal_backslash;
  2442. else
  2443. FREE_STACK_RETURN (REG_ERPAREN);
  2444. }
  2445. handle_close:
  2446. if (fixup_alt_jump)
  2447. { /* Push a dummy failure point at the end of the
  2448. alternative for a possible future
  2449. `pop_failure_jump' to pop. See comments at
  2450. `push_dummy_failure' in `re_match_2'. */
  2451. BUF_PUSH (push_dummy_failure);
  2452. /* We allocated space for this jump when we assigned
  2453. to `fixup_alt_jump', in the `handle_alt' case below. */
  2454. STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
  2455. }
  2456. /* See similar code for backslashed left paren above. */
  2457. if (COMPILE_STACK_EMPTY)
  2458. {
  2459. if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  2460. goto normal_char;
  2461. else
  2462. FREE_STACK_RETURN (REG_ERPAREN);
  2463. }
  2464. /* Since we just checked for an empty stack above, this
  2465. ``can't happen''. */
  2466. assert (compile_stack.avail != 0);
  2467. {
  2468. /* We don't just want to restore into `regnum', because
  2469. later groups should continue to be numbered higher,
  2470. as in `(ab)c(de)' -- the second group is #2. */
  2471. regnum_t this_group_regnum;
  2472. compile_stack.avail--;
  2473. begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
  2474. fixup_alt_jump
  2475. = COMPILE_STACK_TOP.fixup_alt_jump
  2476. ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
  2477. : 0;
  2478. laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
  2479. this_group_regnum = COMPILE_STACK_TOP.regnum;
  2480. /* If we've reached MAX_REGNUM groups, then this open
  2481. won't actually generate any code, so we'll have to
  2482. clear pending_exact explicitly. */
  2483. pending_exact = 0;
  2484. /* We're at the end of the group, so now we know how many
  2485. groups were inside this one. */
  2486. if (this_group_regnum <= MAX_REGNUM)
  2487. {
  2488. unsigned char *inner_group_loc
  2489. = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
  2490. *inner_group_loc = regnum - this_group_regnum;
  2491. BUF_PUSH_3 (stop_memory, this_group_regnum,
  2492. regnum - this_group_regnum);
  2493. }
  2494. }
  2495. break;
  2496. case '|': /* `\|'. */
  2497. if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
  2498. goto normal_backslash;
  2499. handle_alt:
  2500. if (syntax & RE_LIMITED_OPS)
  2501. goto normal_char;
  2502. /* Insert before the previous alternative a jump which
  2503. jumps to this alternative if the former fails. */
  2504. GET_BUFFER_SPACE (3);
  2505. INSERT_JUMP (on_failure_jump, begalt, b + 6);
  2506. pending_exact = 0;
  2507. b += 3;
  2508. /* The alternative before this one has a jump after it
  2509. which gets executed if it gets matched. Adjust that
  2510. jump so it will jump to this alternative's analogous
  2511. jump (put in below, which in turn will jump to the next
  2512. (if any) alternative's such jump, etc.). The last such
  2513. jump jumps to the correct final destination. A picture:
  2514. _____ _____
  2515. | | | |
  2516. | v | v
  2517. a | b | c
  2518. If we are at `b', then fixup_alt_jump right now points to a
  2519. three-byte space after `a'. We'll put in the jump, set
  2520. fixup_alt_jump to right after `b', and leave behind three
  2521. bytes which we'll fill in when we get to after `c'. */
  2522. if (fixup_alt_jump)
  2523. STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  2524. /* Mark and leave space for a jump after this alternative,
  2525. to be filled in later either by next alternative or
  2526. when know we're at the end of a series of alternatives. */
  2527. fixup_alt_jump = b;
  2528. GET_BUFFER_SPACE (3);
  2529. b += 3;
  2530. laststart = 0;
  2531. begalt = b;
  2532. break;
  2533. case '{':
  2534. /* If \{ is a literal. */
  2535. if (!(syntax & RE_INTERVALS)
  2536. /* If we're at `\{' and it's not the open-interval
  2537. operator. */
  2538. || (syntax & RE_NO_BK_BRACES))
  2539. goto normal_backslash;
  2540. handle_interval:
  2541. {
  2542. /* If got here, then the syntax allows intervals. */
  2543. /* At least (most) this many matches must be made. */
  2544. int lower_bound = -1, upper_bound = -1;
  2545. beg_interval = p - 1;
  2546. if (p == pend)
  2547. {
  2548. if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  2549. goto unfetch_interval;
  2550. else
  2551. FREE_STACK_RETURN (REG_EBRACE);
  2552. }
  2553. GET_UNSIGNED_NUMBER (lower_bound);
  2554. if (c == ',')
  2555. {
  2556. GET_UNSIGNED_NUMBER (upper_bound);
  2557. if ((!(syntax & RE_NO_BK_BRACES) && c != '\\')
  2558. || ((syntax & RE_NO_BK_BRACES) && c != '}'))
  2559. FREE_STACK_RETURN (REG_BADBR);
  2560. if (upper_bound < 0)
  2561. upper_bound = RE_DUP_MAX;
  2562. }
  2563. else
  2564. /* Interval such as `{1}' => match exactly once. */
  2565. upper_bound = lower_bound;
  2566. if (lower_bound < 0 || upper_bound > RE_DUP_MAX
  2567. || lower_bound > upper_bound)
  2568. {
  2569. if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  2570. goto unfetch_interval;
  2571. else
  2572. FREE_STACK_RETURN (REG_BADBR);
  2573. }
  2574. if (!(syntax & RE_NO_BK_BRACES))
  2575. {
  2576. if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
  2577. PATFETCH (c);
  2578. }
  2579. if (c != '}')
  2580. {
  2581. if (!(syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  2582. goto unfetch_interval;
  2583. else
  2584. FREE_STACK_RETURN (REG_BADBR);
  2585. }
  2586. /* We just parsed a valid interval. */
  2587. /* If it's invalid to have no preceding re. */
  2588. if (!laststart)
  2589. {
  2590. if (syntax & RE_CONTEXT_INVALID_OPS)
  2591. FREE_STACK_RETURN (REG_BADRPT);
  2592. else if (syntax & RE_CONTEXT_INDEP_OPS)
  2593. laststart = b;
  2594. else
  2595. goto unfetch_interval;
  2596. }
  2597. /* If the upper bound is zero, don't want to succeed at
  2598. all; jump from `laststart' to `b + 3', which will be
  2599. the end of the buffer after we insert the jump. */
  2600. if (upper_bound == 0)
  2601. {
  2602. GET_BUFFER_SPACE (3);
  2603. INSERT_JUMP (jump, laststart, b + 3);
  2604. b += 3;
  2605. }
  2606. /* Otherwise, we have a nontrivial interval. When
  2607. we're all done, the pattern will look like:
  2608. set_number_at <jump count> <upper bound>
  2609. set_number_at <succeed_n count> <lower bound>
  2610. succeed_n <after jump addr> <succeed_n count>
  2611. <body of loop>
  2612. jump_n <succeed_n addr> <jump count>
  2613. (The upper bound and `jump_n' are omitted if
  2614. `upper_bound' is 1, though.) */
  2615. else
  2616. { /* If the upper bound is > 1, we need to insert
  2617. more at the end of the loop. */
  2618. unsigned nbytes = 10 + (upper_bound > 1) * 10;
  2619. GET_BUFFER_SPACE (nbytes);
  2620. /* Initialize lower bound of the `succeed_n', even
  2621. though it will be set during matching by its
  2622. attendant `set_number_at' (inserted next),
  2623. because `re_compile_fastmap' needs to know.
  2624. Jump to the `jump_n' we might insert below. */
  2625. INSERT_JUMP2 (succeed_n, laststart,
  2626. b + 5 + (upper_bound > 1) * 5,
  2627. lower_bound);
  2628. b += 5;
  2629. /* Code to initialize the lower bound. Insert
  2630. before the `succeed_n'. The `5' is the last two
  2631. bytes of this `set_number_at', plus 3 bytes of
  2632. the following `succeed_n'. */
  2633. insert_op2 (set_number_at, laststart, 5, lower_bound, b);
  2634. b += 5;
  2635. if (upper_bound > 1)
  2636. { /* More than one repetition is allowed, so
  2637. append a backward jump to the `succeed_n'
  2638. that starts this interval.
  2639. When we've reached this during matching,
  2640. we'll have matched the interval once, so
  2641. jump back only `upper_bound - 1' times. */
  2642. STORE_JUMP2 (jump_n, b, laststart + 5,
  2643. upper_bound - 1);
  2644. b += 5;
  2645. /* The location we want to set is the second
  2646. parameter of the `jump_n'; that is `b-2' as
  2647. an absolute address. `laststart' will be
  2648. the `set_number_at' we're about to insert;
  2649. `laststart+3' the number to set, the source
  2650. for the relative address. But we are
  2651. inserting into the middle of the pattern --
  2652. so everything is getting moved up by 5.
  2653. Conclusion: (b - 2) - (laststart + 3) + 5,
  2654. i.e., b - laststart.
  2655. We insert this at the beginning of the loop
  2656. so that if we fail during matching, we'll
  2657. reinitialize the bounds. */
  2658. insert_op2 (set_number_at, laststart, b - laststart,
  2659. upper_bound - 1, b);
  2660. b += 5;
  2661. }
  2662. }
  2663. pending_exact = 0;
  2664. beg_interval = NULL;
  2665. }
  2666. break;
  2667. unfetch_interval:
  2668. /* If an invalid interval, match the characters as literals. */
  2669. assert (beg_interval);
  2670. p = beg_interval;
  2671. beg_interval = NULL;
  2672. /* normal_char and normal_backslash need `c'. */
  2673. PATFETCH (c);
  2674. if (!(syntax & RE_NO_BK_BRACES))
  2675. {
  2676. if (p > pattern && p[-1] == '\\')
  2677. goto normal_backslash;
  2678. }
  2679. goto normal_char;
  2680. #ifdef emacs
  2681. /* There is no way to specify the before_dot and after_dot
  2682. operators. rms says this is ok. --karl */
  2683. case '=':
  2684. BUF_PUSH (at_dot);
  2685. break;
  2686. case 's':
  2687. laststart = b;
  2688. PATFETCH (c);
  2689. BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
  2690. break;
  2691. case 'S':
  2692. laststart = b;
  2693. PATFETCH (c);
  2694. BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
  2695. break;
  2696. #endif /* emacs */
  2697. case 'w':
  2698. if (syntax & RE_NO_GNU_OPS)
  2699. goto normal_char;
  2700. laststart = b;
  2701. BUF_PUSH (wordchar);
  2702. break;
  2703. case 'W':
  2704. if (syntax & RE_NO_GNU_OPS)
  2705. goto normal_char;
  2706. laststart = b;
  2707. BUF_PUSH (notwordchar);
  2708. break;
  2709. case '<':
  2710. if (syntax & RE_NO_GNU_OPS)
  2711. goto normal_char;
  2712. BUF_PUSH (wordbeg);
  2713. break;
  2714. case '>':
  2715. if (syntax & RE_NO_GNU_OPS)
  2716. goto normal_char;
  2717. BUF_PUSH (wordend);
  2718. break;
  2719. case 'b':
  2720. if (syntax & RE_NO_GNU_OPS)
  2721. goto normal_char;
  2722. BUF_PUSH (wordbound);
  2723. break;
  2724. case 'B':
  2725. if (syntax & RE_NO_GNU_OPS)
  2726. goto normal_char;
  2727. BUF_PUSH (notwordbound);
  2728. break;
  2729. case '`':
  2730. if (syntax & RE_NO_GNU_OPS)
  2731. goto normal_char;
  2732. BUF_PUSH (begbuf);
  2733. break;
  2734. case '\'':
  2735. if (syntax & RE_NO_GNU_OPS)
  2736. goto normal_char;
  2737. BUF_PUSH (endbuf);
  2738. break;
  2739. case '1': case '2': case '3': case '4': case '5':
  2740. case '6': case '7': case '8': case '9':
  2741. if (syntax & RE_NO_BK_REFS)
  2742. goto normal_char;
  2743. c1 = c - '0';
  2744. if (c1 > regnum)
  2745. FREE_STACK_RETURN (REG_ESUBREG);
  2746. /* Can't back reference to a subexpression if inside of it. */
  2747. if (group_in_compile_stack (compile_stack, (regnum_t) c1))
  2748. goto normal_char;
  2749. laststart = b;
  2750. BUF_PUSH_2 (duplicate, c1);
  2751. break;
  2752. case '+':
  2753. case '?':
  2754. if (syntax & RE_BK_PLUS_QM)
  2755. goto handle_plus;
  2756. else
  2757. goto normal_backslash;
  2758. default:
  2759. normal_backslash:
  2760. /* You might think it would be useful for \ to mean
  2761. not to translate; but if we don't translate it
  2762. it will never match anything. */
  2763. c = TRANSLATE (c);
  2764. goto normal_char;
  2765. }
  2766. break;
  2767. default:
  2768. /* Expects the character in `c'. */
  2769. normal_char:
  2770. /* If no exactn currently being built. */
  2771. if (!pending_exact
  2772. /* If last exactn not at current position. */
  2773. || pending_exact + *pending_exact + 1 != b
  2774. /* We have only one byte following the exactn for the count. */
  2775. || *pending_exact == (1 << BYTEWIDTH) - 1
  2776. /* If followed by a repetition operator. */
  2777. || *p == '*' || *p == '^'
  2778. || ((syntax & RE_BK_PLUS_QM)
  2779. ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  2780. : (*p == '+' || *p == '?'))
  2781. || ((syntax & RE_INTERVALS)
  2782. && ((syntax & RE_NO_BK_BRACES)
  2783. ? *p == '{'
  2784. : (p[0] == '\\' && p[1] == '{'))))
  2785. {
  2786. /* Start building a new exactn. */
  2787. laststart = b;
  2788. BUF_PUSH_2 (exactn, 0);
  2789. pending_exact = b - 1;
  2790. }
  2791. BUF_PUSH (c);
  2792. (*pending_exact)++;
  2793. break;
  2794. } /* switch (c) */
  2795. } /* while p != pend */
  2796. /* Through the pattern now. */
  2797. if (fixup_alt_jump)
  2798. STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  2799. if (!COMPILE_STACK_EMPTY)
  2800. FREE_STACK_RETURN (REG_EPAREN);
  2801. /* If we don't want backtracking, force success
  2802. the first time we reach the end of the compiled pattern. */
  2803. if (syntax & RE_NO_POSIX_BACKTRACKING)
  2804. BUF_PUSH (succeed);
  2805. free (compile_stack.stack);
  2806. /* We have succeeded; set the length of the buffer. */
  2807. bufp->used = b - bufp->buffer;
  2808. #ifdef DEBUG
  2809. if (debug)
  2810. {
  2811. DEBUG_PRINT1 ("\nCompiled pattern: \n");
  2812. print_compiled_pattern (bufp);
  2813. }
  2814. #endif /* DEBUG */
  2815. #ifndef MATCH_MAY_ALLOCATE
  2816. /* Initialize the failure stack to the largest possible stack. This
  2817. isn't necessary unless we're trying to avoid calling alloca in
  2818. the search and match routines. */
  2819. {
  2820. int num_regs = bufp->re_nsub + 1;
  2821. /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
  2822. is strictly greater than re_max_failures, the largest possible stack
  2823. is 2 * re_max_failures failure points. */
  2824. if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
  2825. {
  2826. fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
  2827. # ifdef emacs
  2828. if (! fail_stack.stack)
  2829. fail_stack.stack
  2830. = (fail_stack_elt_t *) xmalloc (fail_stack.size
  2831. * sizeof (fail_stack_elt_t));
  2832. else
  2833. fail_stack.stack
  2834. = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
  2835. (fail_stack.size
  2836. * sizeof (fail_stack_elt_t)));
  2837. # else /* not emacs */
  2838. if (! fail_stack.stack)
  2839. fail_stack.stack
  2840. = (fail_stack_elt_t *) malloc (fail_stack.size
  2841. * sizeof (fail_stack_elt_t));
  2842. else
  2843. fail_stack.stack
  2844. = (fail_stack_elt_t *) realloc (fail_stack.stack,
  2845. (fail_stack.size
  2846. * sizeof (fail_stack_elt_t)));
  2847. # endif /* not emacs */
  2848. }
  2849. regex_grow_registers (num_regs);
  2850. }
  2851. #endif /* not MATCH_MAY_ALLOCATE */
  2852. return REG_NOERROR;
  2853. } /* regex_compile */
  2854. /* Subroutines for `regex_compile'. */
  2855. /* Store OP at LOC followed by two-byte integer parameter ARG. */
  2856. static void
  2857. store_op1 (op, loc, arg)
  2858. re_opcode_t op;
  2859. unsigned char *loc;
  2860. int arg;
  2861. {
  2862. *loc = (unsigned char) op;
  2863. STORE_NUMBER (loc + 1, arg);
  2864. }
  2865. /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
  2866. static void
  2867. store_op2 (op, loc, arg1, arg2)
  2868. re_opcode_t op;
  2869. unsigned char *loc;
  2870. int arg1, arg2;
  2871. {
  2872. *loc = (unsigned char) op;
  2873. STORE_NUMBER (loc + 1, arg1);
  2874. STORE_NUMBER (loc + 3, arg2);
  2875. }
  2876. /* Copy the bytes from LOC to END to open up three bytes of space at LOC
  2877. for OP followed by two-byte integer parameter ARG. */
  2878. static void
  2879. insert_op1 (op, loc, arg, end)
  2880. re_opcode_t op;
  2881. unsigned char *loc;
  2882. int arg;
  2883. unsigned char *end;
  2884. {
  2885. register unsigned char *pfrom = end;
  2886. register unsigned char *pto = end + 3;
  2887. while (pfrom != loc)
  2888. *--pto = *--pfrom;
  2889. store_op1 (op, loc, arg);
  2890. }
  2891. /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
  2892. static void
  2893. insert_op2 (op, loc, arg1, arg2, end)
  2894. re_opcode_t op;
  2895. unsigned char *loc;
  2896. int arg1, arg2;
  2897. unsigned char *end;
  2898. {
  2899. register unsigned char *pfrom = end;
  2900. register unsigned char *pto = end + 5;
  2901. while (pfrom != loc)
  2902. *--pto = *--pfrom;
  2903. store_op2 (op, loc, arg1, arg2);
  2904. }
  2905. /* P points to just after a ^ in PATTERN. Return true if that ^ comes
  2906. after an alternative or a begin-subexpression. We assume there is at
  2907. least one character before the ^. */
  2908. static boolean
  2909. at_begline_loc_p (pattern, p, syntax)
  2910. const char *pattern, *p;
  2911. reg_syntax_t syntax;
  2912. {
  2913. const char *prev = p - 2;
  2914. boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
  2915. return
  2916. /* After a subexpression? */
  2917. (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
  2918. /* After an alternative? */
  2919. || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
  2920. }
  2921. /* The dual of at_begline_loc_p. This one is for $. We assume there is
  2922. at least one character after the $, i.e., `P < PEND'. */
  2923. static boolean
  2924. at_endline_loc_p (p, pend, syntax)
  2925. const char *p, *pend;
  2926. reg_syntax_t syntax;
  2927. {
  2928. const char *next = p;
  2929. boolean next_backslash = *next == '\\';
  2930. const char *next_next = p + 1 < pend ? p + 1 : 0;
  2931. return
  2932. /* Before a subexpression? */
  2933. (syntax & RE_NO_BK_PARENS ? *next == ')'
  2934. : next_backslash && next_next && *next_next == ')')
  2935. /* Before an alternative? */
  2936. || (syntax & RE_NO_BK_VBAR ? *next == '|'
  2937. : next_backslash && next_next && *next_next == '|');
  2938. }
  2939. /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
  2940. false if it's not. */
  2941. static boolean
  2942. group_in_compile_stack (compile_stack, regnum)
  2943. compile_stack_type compile_stack;
  2944. regnum_t regnum;
  2945. {
  2946. int this_element;
  2947. for (this_element = compile_stack.avail - 1;
  2948. this_element >= 0;
  2949. this_element--)
  2950. if (compile_stack.stack[this_element].regnum == regnum)
  2951. return true;
  2952. return false;
  2953. }
  2954. /* Read the ending character of a range (in a bracket expression) from the
  2955. uncompiled pattern *P_PTR (which ends at PEND). We assume the
  2956. starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
  2957. Then we set the translation of all bits between the starting and
  2958. ending characters (inclusive) in the compiled pattern B.
  2959. Return an error code.
  2960. We use these short variable names so we can use the same macros as
  2961. `regex_compile' itself. */
  2962. static reg_errcode_t
  2963. compile_range (range_start_char, p_ptr, pend, translate, syntax, b)
  2964. unsigned int range_start_char;
  2965. const char **p_ptr, *pend;
  2966. RE_TRANSLATE_TYPE translate;
  2967. reg_syntax_t syntax;
  2968. unsigned char *b;
  2969. {
  2970. unsigned this_char;
  2971. const char *p = *p_ptr;
  2972. reg_errcode_t ret;
  2973. #if _LIBC
  2974. const unsigned char *collseq;
  2975. unsigned int start_colseq;
  2976. unsigned int end_colseq;
  2977. #else
  2978. unsigned end_char;
  2979. #endif
  2980. if (p == pend)
  2981. return REG_ERANGE;
  2982. /* Have to increment the pointer into the pattern string, so the
  2983. caller isn't still at the ending character. */
  2984. (*p_ptr)++;
  2985. /* Report an error if the range is empty and the syntax prohibits this. */
  2986. ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
  2987. #if _LIBC
  2988. collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
  2989. _NL_COLLATE_COLLSEQMB);
  2990. start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
  2991. end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
  2992. for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
  2993. {
  2994. unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
  2995. if (start_colseq <= this_colseq && this_colseq <= end_colseq)
  2996. {
  2997. SET_LIST_BIT (TRANSLATE (this_char));
  2998. ret = REG_NOERROR;
  2999. }
  3000. }
  3001. #else
  3002. /* Here we see why `this_char' has to be larger than an `unsigned
  3003. char' -- we would otherwise go into an infinite loop, since all
  3004. characters <= 0xff. */
  3005. range_start_char = TRANSLATE (range_start_char);
  3006. end_char = TRANSLATE (p[0]);
  3007. for (this_char = range_start_char; this_char <= end_char; ++this_char)
  3008. {
  3009. SET_LIST_BIT (TRANSLATE (this_char));
  3010. ret = REG_NOERROR;
  3011. }
  3012. #endif
  3013. return ret;
  3014. }
  3015. /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
  3016. BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
  3017. characters can start a string that matches the pattern. This fastmap
  3018. is used by re_search to skip quickly over impossible starting points.
  3019. The caller must supply the address of a (1 << BYTEWIDTH)-byte data
  3020. area as BUFP->fastmap.
  3021. We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
  3022. the pattern buffer.
  3023. Returns 0 if we succeed, -2 if an internal error. */
  3024. int
  3025. re_compile_fastmap (bufp)
  3026. struct re_pattern_buffer *bufp;
  3027. {
  3028. int j, k;
  3029. #ifdef MATCH_MAY_ALLOCATE
  3030. fail_stack_type fail_stack;
  3031. #endif
  3032. #ifndef REGEX_MALLOC
  3033. char *destination;
  3034. #endif
  3035. register char *fastmap = bufp->fastmap;
  3036. unsigned char *pattern = bufp->buffer;
  3037. unsigned char *p = pattern;
  3038. register unsigned char *pend = pattern + bufp->used;
  3039. #ifdef REL_ALLOC
  3040. /* This holds the pointer to the failure stack, when
  3041. it is allocated relocatably. */
  3042. fail_stack_elt_t *failure_stack_ptr;
  3043. #endif
  3044. /* Assume that each path through the pattern can be null until
  3045. proven otherwise. We set this false at the bottom of switch
  3046. statement, to which we get only if a particular path doesn't
  3047. match the empty string. */
  3048. boolean path_can_be_null = true;
  3049. /* We aren't doing a `succeed_n' to begin with. */
  3050. boolean succeed_n_p = false;
  3051. assert (fastmap != NULL && p != NULL);
  3052. INIT_FAIL_STACK ();
  3053. bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
  3054. bufp->fastmap_accurate = 1; /* It will be when we're done. */
  3055. bufp->can_be_null = 0;
  3056. while (1)
  3057. {
  3058. if (p == pend || *p == succeed)
  3059. {
  3060. /* We have reached the (effective) end of pattern. */
  3061. if (!FAIL_STACK_EMPTY ())
  3062. {
  3063. bufp->can_be_null |= path_can_be_null;
  3064. /* Reset for next path. */
  3065. path_can_be_null = true;
  3066. p = fail_stack.stack[--fail_stack.avail].pointer;
  3067. continue;
  3068. }
  3069. else
  3070. break;
  3071. }
  3072. /* We should never be about to go beyond the end of the pattern. */
  3073. assert (p < pend);
  3074. switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
  3075. {
  3076. /* I guess the idea here is to simply not bother with a fastmap
  3077. if a backreference is used, since it's too hard to figure out
  3078. the fastmap for the corresponding group. Setting
  3079. `can_be_null' stops `re_search_2' from using the fastmap, so
  3080. that is all we do. */
  3081. case duplicate:
  3082. bufp->can_be_null = 1;
  3083. goto done;
  3084. /* Following are the cases which match a character. These end
  3085. with `break'. */
  3086. case exactn:
  3087. fastmap[p[1]] = 1;
  3088. break;
  3089. case charset:
  3090. for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  3091. if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  3092. fastmap[j] = 1;
  3093. break;
  3094. case charset_not:
  3095. /* Chars beyond end of map must be allowed. */
  3096. for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  3097. fastmap[j] = 1;
  3098. for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  3099. if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  3100. fastmap[j] = 1;
  3101. break;
  3102. case wordchar:
  3103. for (j = 0; j < (1 << BYTEWIDTH); j++)
  3104. if (SYNTAX (j) == Sword)
  3105. fastmap[j] = 1;
  3106. break;
  3107. case notwordchar:
  3108. for (j = 0; j < (1 << BYTEWIDTH); j++)
  3109. if (SYNTAX (j) != Sword)
  3110. fastmap[j] = 1;
  3111. break;
  3112. case anychar:
  3113. {
  3114. int fastmap_newline = fastmap['\n'];
  3115. /* `.' matches anything ... */
  3116. for (j = 0; j < (1 << BYTEWIDTH); j++)
  3117. fastmap[j] = 1;
  3118. /* ... except perhaps newline. */
  3119. if (!(bufp->syntax & RE_DOT_NEWLINE))
  3120. fastmap['\n'] = fastmap_newline;
  3121. /* Return if we have already set `can_be_null'; if we have,
  3122. then the fastmap is irrelevant. Something's wrong here. */
  3123. else if (bufp->can_be_null)
  3124. goto done;
  3125. /* Otherwise, have to check alternative paths. */
  3126. break;
  3127. }
  3128. #ifdef emacs
  3129. case syntaxspec:
  3130. k = *p++;
  3131. for (j = 0; j < (1 << BYTEWIDTH); j++)
  3132. if (SYNTAX (j) == (enum syntaxcode) k)
  3133. fastmap[j] = 1;
  3134. break;
  3135. case notsyntaxspec:
  3136. k = *p++;
  3137. for (j = 0; j < (1 << BYTEWIDTH); j++)
  3138. if (SYNTAX (j) != (enum syntaxcode) k)
  3139. fastmap[j] = 1;
  3140. break;
  3141. /* All cases after this match the empty string. These end with
  3142. `continue'. */
  3143. case before_dot:
  3144. case at_dot:
  3145. case after_dot:
  3146. continue;
  3147. #endif /* emacs */
  3148. case no_op:
  3149. case begline:
  3150. case endline:
  3151. case begbuf:
  3152. case endbuf:
  3153. case wordbound:
  3154. case notwordbound:
  3155. case wordbeg:
  3156. case wordend:
  3157. case push_dummy_failure:
  3158. continue;
  3159. case jump_n:
  3160. case pop_failure_jump:
  3161. case maybe_pop_jump:
  3162. case jump:
  3163. case jump_past_alt:
  3164. case dummy_failure_jump:
  3165. EXTRACT_NUMBER_AND_INCR (j, p);
  3166. p += j;
  3167. if (j > 0)
  3168. continue;
  3169. /* Jump backward implies we just went through the body of a
  3170. loop and matched nothing. Opcode jumped to should be
  3171. `on_failure_jump' or `succeed_n'. Just treat it like an
  3172. ordinary jump. For a * loop, it has pushed its failure
  3173. point already; if so, discard that as redundant. */
  3174. if ((re_opcode_t) *p != on_failure_jump
  3175. && (re_opcode_t) *p != succeed_n)
  3176. continue;
  3177. p++;
  3178. EXTRACT_NUMBER_AND_INCR (j, p);
  3179. p += j;
  3180. /* If what's on the stack is where we are now, pop it. */
  3181. if (!FAIL_STACK_EMPTY ()
  3182. && fail_stack.stack[fail_stack.avail - 1].pointer == p)
  3183. fail_stack.avail--;
  3184. continue;
  3185. case on_failure_jump:
  3186. case on_failure_keep_string_jump:
  3187. handle_on_failure_jump:
  3188. EXTRACT_NUMBER_AND_INCR (j, p);
  3189. /* For some patterns, e.g., `(a?)?', `p+j' here points to the
  3190. end of the pattern. We don't want to push such a point,
  3191. since when we restore it above, entering the switch will
  3192. increment `p' past the end of the pattern. We don't need
  3193. to push such a point since we obviously won't find any more
  3194. fastmap entries beyond `pend'. Such a pattern can match
  3195. the null string, though. */
  3196. if (p + j < pend)
  3197. {
  3198. if (!PUSH_PATTERN_OP (p + j, fail_stack))
  3199. {
  3200. RESET_FAIL_STACK ();
  3201. return -2;
  3202. }
  3203. }
  3204. else
  3205. bufp->can_be_null = 1;
  3206. if (succeed_n_p)
  3207. {
  3208. EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
  3209. succeed_n_p = false;
  3210. }
  3211. continue;
  3212. case succeed_n:
  3213. /* Get to the number of times to succeed. */
  3214. p += 2;
  3215. /* Increment p past the n for when k != 0. */
  3216. EXTRACT_NUMBER_AND_INCR (k, p);
  3217. if (k == 0)
  3218. {
  3219. p -= 4;
  3220. succeed_n_p = true; /* Spaghetti code alert. */
  3221. goto handle_on_failure_jump;
  3222. }
  3223. continue;
  3224. case set_number_at:
  3225. p += 4;
  3226. continue;
  3227. case start_memory:
  3228. case stop_memory:
  3229. p += 2;
  3230. continue;
  3231. default:
  3232. abort (); /* We have listed all the cases. */
  3233. } /* switch *p++ */
  3234. /* Getting here means we have found the possible starting
  3235. characters for one path of the pattern -- and that the empty
  3236. string does not match. We need not follow this path further.
  3237. Instead, look at the next alternative (remembered on the
  3238. stack), or quit if no more. The test at the top of the loop
  3239. does these things. */
  3240. path_can_be_null = false;
  3241. p = pend;
  3242. } /* while p */
  3243. /* Set `can_be_null' for the last path (also the first path, if the
  3244. pattern is empty). */
  3245. bufp->can_be_null |= path_can_be_null;
  3246. done:
  3247. RESET_FAIL_STACK ();
  3248. return 0;
  3249. } /* re_compile_fastmap */
  3250. #ifdef _LIBC
  3251. weak_alias (__re_compile_fastmap, re_compile_fastmap)
  3252. #endif
  3253. /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
  3254. ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
  3255. this memory for recording register information. STARTS and ENDS
  3256. must be allocated using the malloc library routine, and must each
  3257. be at least NUM_REGS * sizeof (regoff_t) bytes long.
  3258. If NUM_REGS == 0, then subsequent matches should allocate their own
  3259. register data.
  3260. Unless this function is called, the first search or match using
  3261. PATTERN_BUFFER will allocate its own register data, without
  3262. freeing the old data. */
  3263. void
  3264. re_set_registers (bufp, regs, num_regs, starts, ends)
  3265. struct re_pattern_buffer *bufp;
  3266. struct re_registers *regs;
  3267. unsigned num_regs;
  3268. regoff_t *starts, *ends;
  3269. {
  3270. if (num_regs)
  3271. {
  3272. bufp->regs_allocated = REGS_REALLOCATE;
  3273. regs->num_regs = num_regs;
  3274. regs->start = starts;
  3275. regs->end = ends;
  3276. }
  3277. else
  3278. {
  3279. bufp->regs_allocated = REGS_UNALLOCATED;
  3280. regs->num_regs = 0;
  3281. regs->start = regs->end = (regoff_t *) 0;
  3282. }
  3283. }
  3284. #ifdef _LIBC
  3285. weak_alias (__re_set_registers, re_set_registers)
  3286. #endif
  3287. /* Searching routines. */
  3288. /* Like re_search_2, below, but only one string is specified, and
  3289. doesn't let you say where to stop matching. */
  3290. int
  3291. re_search (bufp, string, size, startpos, range, regs)
  3292. struct re_pattern_buffer *bufp;
  3293. const char *string;
  3294. int size, startpos, range;
  3295. struct re_registers *regs;
  3296. {
  3297. return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
  3298. regs, size);
  3299. }
  3300. #ifdef _LIBC
  3301. weak_alias (__re_search, re_search)
  3302. #endif
  3303. /* Using the compiled pattern in BUFP->buffer, first tries to match the
  3304. virtual concatenation of STRING1 and STRING2, starting first at index
  3305. STARTPOS, then at STARTPOS + 1, and so on.
  3306. STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
  3307. RANGE is how far to scan while trying to match. RANGE = 0 means try
  3308. only at STARTPOS; in general, the last start tried is STARTPOS +
  3309. RANGE.
  3310. In REGS, return the indices of the virtual concatenation of STRING1
  3311. and STRING2 that matched the entire BUFP->buffer and its contained
  3312. subexpressions.
  3313. Do not consider matching one past the index STOP in the virtual
  3314. concatenation of STRING1 and STRING2.
  3315. We return either the position in the strings at which the match was
  3316. found, -1 if no match, or -2 if error (such as failure
  3317. stack overflow). */
  3318. int
  3319. re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
  3320. struct re_pattern_buffer *bufp;
  3321. const char *string1, *string2;
  3322. int size1, size2;
  3323. int startpos;
  3324. int range;
  3325. struct re_registers *regs;
  3326. int stop;
  3327. {
  3328. int val;
  3329. register char *fastmap = bufp->fastmap;
  3330. register RE_TRANSLATE_TYPE translate = bufp->translate;
  3331. int total_size = size1 + size2;
  3332. int endpos = startpos + range;
  3333. /* Check for out-of-range STARTPOS. */
  3334. if (startpos < 0 || startpos > total_size)
  3335. return -1;
  3336. /* Fix up RANGE if it might eventually take us outside
  3337. the virtual concatenation of STRING1 and STRING2.
  3338. Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
  3339. if (endpos < 0)
  3340. range = 0 - startpos;
  3341. else if (endpos > total_size)
  3342. range = total_size - startpos;
  3343. /* If the search isn't to be a backwards one, don't waste time in a
  3344. search for a pattern that must be anchored. */
  3345. if (bufp->used > 0 && range > 0
  3346. && ((re_opcode_t) bufp->buffer[0] == begbuf
  3347. /* `begline' is like `begbuf' if it cannot match at newlines. */
  3348. || ((re_opcode_t) bufp->buffer[0] == begline
  3349. && !bufp->newline_anchor)))
  3350. {
  3351. if (startpos > 0)
  3352. return -1;
  3353. else
  3354. range = 1;
  3355. }
  3356. #ifdef emacs
  3357. /* In a forward search for something that starts with \=.
  3358. don't keep searching past point. */
  3359. if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
  3360. {
  3361. range = PT - startpos;
  3362. if (range <= 0)
  3363. return -1;
  3364. }
  3365. #endif /* emacs */
  3366. /* Update the fastmap now if not correct already. */
  3367. if (fastmap && !bufp->fastmap_accurate)
  3368. if (re_compile_fastmap (bufp) == -2)
  3369. return -2;
  3370. /* Loop through the string, looking for a place to start matching. */
  3371. for (;;)
  3372. {
  3373. /* If a fastmap is supplied, skip quickly over characters that
  3374. cannot be the start of a match. If the pattern can match the
  3375. null string, however, we don't need to skip characters; we want
  3376. the first null string. */
  3377. if (fastmap && startpos < total_size && !bufp->can_be_null)
  3378. {
  3379. if (range > 0) /* Searching forwards. */
  3380. {
  3381. register const char *d;
  3382. register int lim = 0;
  3383. int irange = range;
  3384. if (startpos < size1 && startpos + range >= size1)
  3385. lim = range - (size1 - startpos);
  3386. d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
  3387. /* Written out as an if-else to avoid testing `translate'
  3388. inside the loop. */
  3389. if (translate)
  3390. while (range > lim
  3391. && !fastmap[(unsigned char)
  3392. translate[(unsigned char) *d++]])
  3393. range--;
  3394. else
  3395. while (range > lim && !fastmap[(unsigned char) *d++])
  3396. range--;
  3397. startpos += irange - range;
  3398. }
  3399. else /* Searching backwards. */
  3400. {
  3401. register char c = (size1 == 0 || startpos >= size1
  3402. ? string2[startpos - size1]
  3403. : string1[startpos]);
  3404. if (!fastmap[(unsigned char) TRANSLATE (c)])
  3405. goto advance;
  3406. }
  3407. }
  3408. /* If can't match the null string, and that's all we have left, fail. */
  3409. if (range >= 0 && startpos == total_size && fastmap
  3410. && !bufp->can_be_null)
  3411. return -1;
  3412. val = re_match_2_internal (bufp, string1, size1, string2, size2,
  3413. startpos, regs, stop);
  3414. #ifndef REGEX_MALLOC
  3415. # ifdef C_ALLOCA
  3416. alloca (0);
  3417. # endif
  3418. #endif
  3419. if (val >= 0)
  3420. return startpos;
  3421. if (val == -2)
  3422. return -2;
  3423. advance:
  3424. if (!range)
  3425. break;
  3426. else if (range > 0)
  3427. {
  3428. range--;
  3429. startpos++;
  3430. }
  3431. else
  3432. {
  3433. range++;
  3434. startpos--;
  3435. }
  3436. }
  3437. return -1;
  3438. } /* re_search_2 */
  3439. #ifdef _LIBC
  3440. weak_alias (__re_search_2, re_search_2)
  3441. #endif
  3442. /* This converts PTR, a pointer into one of the search strings `string1'
  3443. and `string2' into an offset from the beginning of that string. */
  3444. #define POINTER_TO_OFFSET(ptr) \
  3445. (FIRST_STRING_P (ptr) \
  3446. ? ((regoff_t) ((ptr) - string1)) \
  3447. : ((regoff_t) ((ptr) - string2 + size1)))
  3448. /* Macros for dealing with the split strings in re_match_2. */
  3449. #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
  3450. /* Call before fetching a character with *d. This switches over to
  3451. string2 if necessary. */
  3452. #define PREFETCH() \
  3453. while (d == dend) \
  3454. { \
  3455. /* End of string2 => fail. */ \
  3456. if (dend == end_match_2) \
  3457. goto fail; \
  3458. /* End of string1 => advance to string2. */ \
  3459. d = string2; \
  3460. dend = end_match_2; \
  3461. }
  3462. /* Test if at very beginning or at very end of the virtual concatenation
  3463. of `string1' and `string2'. If only one string, it's `string2'. */
  3464. #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
  3465. #define AT_STRINGS_END(d) ((d) == end2)
  3466. /* Test if D points to a character which is word-constituent. We have
  3467. two special cases to check for: if past the end of string1, look at
  3468. the first character in string2; and if before the beginning of
  3469. string2, look at the last character in string1. */
  3470. #define WORDCHAR_P(d) \
  3471. (SYNTAX ((d) == end1 ? *string2 \
  3472. : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
  3473. == Sword)
  3474. /* Disabled due to a compiler bug -- see comment at case wordbound */
  3475. #if 0
  3476. /* Test if the character before D and the one at D differ with respect
  3477. to being word-constituent. */
  3478. #define AT_WORD_BOUNDARY(d) \
  3479. (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
  3480. || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
  3481. #endif
  3482. /* Free everything we malloc. */
  3483. #ifdef MATCH_MAY_ALLOCATE
  3484. # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
  3485. # define FREE_VARIABLES() \
  3486. do { \
  3487. REGEX_FREE_STACK (fail_stack.stack); \
  3488. FREE_VAR (regstart); \
  3489. FREE_VAR (regend); \
  3490. FREE_VAR (old_regstart); \
  3491. FREE_VAR (old_regend); \
  3492. FREE_VAR (best_regstart); \
  3493. FREE_VAR (best_regend); \
  3494. FREE_VAR (reg_info); \
  3495. FREE_VAR (reg_dummy); \
  3496. FREE_VAR (reg_info_dummy); \
  3497. } while (0)
  3498. #else
  3499. # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
  3500. #endif /* not MATCH_MAY_ALLOCATE */
  3501. /* These values must meet several constraints. They must not be valid
  3502. register values; since we have a limit of 255 registers (because
  3503. we use only one byte in the pattern for the register number), we can
  3504. use numbers larger than 255. They must differ by 1, because of
  3505. NUM_FAILURE_ITEMS above. And the value for the lowest register must
  3506. be larger than the value for the highest register, so we do not try
  3507. to actually save any registers when none are active. */
  3508. #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
  3509. #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
  3510. /* Matching routines. */
  3511. #ifndef emacs /* Emacs never uses this. */
  3512. /* re_match is like re_match_2 except it takes only a single string. */
  3513. int
  3514. re_match (bufp, string, size, pos, regs)
  3515. struct re_pattern_buffer *bufp;
  3516. const char *string;
  3517. int size, pos;
  3518. struct re_registers *regs;
  3519. {
  3520. int result = re_match_2_internal (bufp, NULL, 0, string, size,
  3521. pos, regs, size);
  3522. # ifndef REGEX_MALLOC
  3523. # ifdef C_ALLOCA
  3524. alloca (0);
  3525. # endif
  3526. # endif
  3527. return result;
  3528. }
  3529. # ifdef _LIBC
  3530. weak_alias (__re_match, re_match)
  3531. # endif
  3532. #endif /* not emacs */
  3533. static boolean group_match_null_string_p _RE_ARGS ((unsigned char **p,
  3534. unsigned char *end,
  3535. register_info_type *reg_info));
  3536. static boolean alt_match_null_string_p _RE_ARGS ((unsigned char *p,
  3537. unsigned char *end,
  3538. register_info_type *reg_info));
  3539. static boolean common_op_match_null_string_p _RE_ARGS ((unsigned char **p,
  3540. unsigned char *end,
  3541. register_info_type *reg_info));
  3542. static int bcmp_translate _RE_ARGS ((const char *s1, const char *s2,
  3543. int len, char *translate));
  3544. /* re_match_2 matches the compiled pattern in BUFP against the
  3545. the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
  3546. and SIZE2, respectively). We start matching at POS, and stop
  3547. matching at STOP.
  3548. If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
  3549. store offsets for the substring each group matched in REGS. See the
  3550. documentation for exactly how many groups we fill.
  3551. We return -1 if no match, -2 if an internal error (such as the
  3552. failure stack overflowing). Otherwise, we return the length of the
  3553. matched substring. */
  3554. int
  3555. re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
  3556. struct re_pattern_buffer *bufp;
  3557. const char *string1, *string2;
  3558. int size1, size2;
  3559. int pos;
  3560. struct re_registers *regs;
  3561. int stop;
  3562. {
  3563. int result = re_match_2_internal (bufp, string1, size1, string2, size2,
  3564. pos, regs, stop);
  3565. #ifndef REGEX_MALLOC
  3566. # ifdef C_ALLOCA
  3567. alloca (0);
  3568. # endif
  3569. #endif
  3570. return result;
  3571. }
  3572. #ifdef _LIBC
  3573. weak_alias (__re_match_2, re_match_2)
  3574. #endif
  3575. /* This is a separate function so that we can force an alloca cleanup
  3576. afterwards. */
  3577. static int
  3578. re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
  3579. struct re_pattern_buffer *bufp;
  3580. const char *string1, *string2;
  3581. int size1, size2;
  3582. int pos;
  3583. struct re_registers *regs;
  3584. int stop;
  3585. {
  3586. /* General temporaries. */
  3587. int mcnt;
  3588. unsigned char *p1;
  3589. /* Just past the end of the corresponding string. */
  3590. const char *end1, *end2;
  3591. /* Pointers into string1 and string2, just past the last characters in
  3592. each to consider matching. */
  3593. const char *end_match_1, *end_match_2;
  3594. /* Where we are in the data, and the end of the current string. */
  3595. const char *d, *dend;
  3596. /* Where we are in the pattern, and the end of the pattern. */
  3597. unsigned char *p = bufp->buffer;
  3598. register unsigned char *pend = p + bufp->used;
  3599. /* Mark the opcode just after a start_memory, so we can test for an
  3600. empty subpattern when we get to the stop_memory. */
  3601. unsigned char *just_past_start_mem = 0;
  3602. /* We use this to map every character in the string. */
  3603. RE_TRANSLATE_TYPE translate = bufp->translate;
  3604. /* Failure point stack. Each place that can handle a failure further
  3605. down the line pushes a failure point on this stack. It consists of
  3606. restart, regend, and reg_info for all registers corresponding to
  3607. the subexpressions we're currently inside, plus the number of such
  3608. registers, and, finally, two char *'s. The first char * is where
  3609. to resume scanning the pattern; the second one is where to resume
  3610. scanning the strings. If the latter is zero, the failure point is
  3611. a ``dummy''; if a failure happens and the failure point is a dummy,
  3612. it gets discarded and the next next one is tried. */
  3613. #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
  3614. fail_stack_type fail_stack;
  3615. #endif
  3616. #ifdef DEBUG
  3617. static unsigned failure_id;
  3618. unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
  3619. #endif
  3620. #ifdef REL_ALLOC
  3621. /* This holds the pointer to the failure stack, when
  3622. it is allocated relocatably. */
  3623. fail_stack_elt_t *failure_stack_ptr;
  3624. #endif
  3625. /* We fill all the registers internally, independent of what we
  3626. return, for use in backreferences. The number here includes
  3627. an element for register zero. */
  3628. size_t num_regs = bufp->re_nsub + 1;
  3629. /* The currently active registers. */
  3630. active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3631. active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3632. /* Information on the contents of registers. These are pointers into
  3633. the input strings; they record just what was matched (on this
  3634. attempt) by a subexpression part of the pattern, that is, the
  3635. regnum-th regstart pointer points to where in the pattern we began
  3636. matching and the regnum-th regend points to right after where we
  3637. stopped matching the regnum-th subexpression. (The zeroth register
  3638. keeps track of what the whole pattern matches.) */
  3639. #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
  3640. const char **regstart, **regend;
  3641. #endif
  3642. /* If a group that's operated upon by a repetition operator fails to
  3643. match anything, then the register for its start will need to be
  3644. restored because it will have been set to wherever in the string we
  3645. are when we last see its open-group operator. Similarly for a
  3646. register's end. */
  3647. #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
  3648. const char **old_regstart, **old_regend;
  3649. #endif
  3650. /* The is_active field of reg_info helps us keep track of which (possibly
  3651. nested) subexpressions we are currently in. The matched_something
  3652. field of reg_info[reg_num] helps us tell whether or not we have
  3653. matched any of the pattern so far this time through the reg_num-th
  3654. subexpression. These two fields get reset each time through any
  3655. loop their register is in. */
  3656. #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
  3657. register_info_type *reg_info;
  3658. #endif
  3659. /* The following record the register info as found in the above
  3660. variables when we find a match better than any we've seen before.
  3661. This happens as we backtrack through the failure points, which in
  3662. turn happens only if we have not yet matched the entire string. */
  3663. unsigned best_regs_set = false;
  3664. #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
  3665. const char **best_regstart, **best_regend;
  3666. #endif
  3667. /* Logically, this is `best_regend[0]'. But we don't want to have to
  3668. allocate space for that if we're not allocating space for anything
  3669. else (see below). Also, we never need info about register 0 for
  3670. any of the other register vectors, and it seems rather a kludge to
  3671. treat `best_regend' differently than the rest. So we keep track of
  3672. the end of the best match so far in a separate variable. We
  3673. initialize this to NULL so that when we backtrack the first time
  3674. and need to test it, it's not garbage. */
  3675. const char *match_end = NULL;
  3676. /* This helps SET_REGS_MATCHED avoid doing redundant work. */
  3677. int set_regs_matched_done = 0;
  3678. /* Used when we pop values we don't care about. */
  3679. #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
  3680. const char **reg_dummy;
  3681. register_info_type *reg_info_dummy;
  3682. #endif
  3683. #ifdef DEBUG
  3684. /* Counts the total number of registers pushed. */
  3685. unsigned num_regs_pushed = 0;
  3686. #endif
  3687. DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
  3688. INIT_FAIL_STACK ();
  3689. #ifdef MATCH_MAY_ALLOCATE
  3690. /* Do not bother to initialize all the register variables if there are
  3691. no groups in the pattern, as it takes a fair amount of time. If
  3692. there are groups, we include space for register 0 (the whole
  3693. pattern), even though we never use it, since it simplifies the
  3694. array indexing. We should fix this. */
  3695. if (bufp->re_nsub)
  3696. {
  3697. regstart = REGEX_TALLOC (num_regs, const char *);
  3698. regend = REGEX_TALLOC (num_regs, const char *);
  3699. old_regstart = REGEX_TALLOC (num_regs, const char *);
  3700. old_regend = REGEX_TALLOC (num_regs, const char *);
  3701. best_regstart = REGEX_TALLOC (num_regs, const char *);
  3702. best_regend = REGEX_TALLOC (num_regs, const char *);
  3703. reg_info = REGEX_TALLOC (num_regs, register_info_type);
  3704. reg_dummy = REGEX_TALLOC (num_regs, const char *);
  3705. reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
  3706. if (!(regstart && regend && old_regstart && old_regend && reg_info
  3707. && best_regstart && best_regend && reg_dummy && reg_info_dummy))
  3708. {
  3709. FREE_VARIABLES ();
  3710. return -2;
  3711. }
  3712. }
  3713. else
  3714. {
  3715. /* We must initialize all our variables to NULL, so that
  3716. `FREE_VARIABLES' doesn't try to free them. */
  3717. regstart = regend = old_regstart = old_regend = best_regstart
  3718. = best_regend = reg_dummy = NULL;
  3719. reg_info = reg_info_dummy = (register_info_type *) NULL;
  3720. }
  3721. #endif /* MATCH_MAY_ALLOCATE */
  3722. /* The starting position is bogus. */
  3723. if (pos < 0 || pos > size1 + size2)
  3724. {
  3725. FREE_VARIABLES ();
  3726. return -1;
  3727. }
  3728. /* Initialize subexpression text positions to -1 to mark ones that no
  3729. start_memory/stop_memory has been seen for. Also initialize the
  3730. register information struct. */
  3731. for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
  3732. {
  3733. regstart[mcnt] = regend[mcnt]
  3734. = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
  3735. REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
  3736. IS_ACTIVE (reg_info[mcnt]) = 0;
  3737. MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  3738. EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  3739. }
  3740. /* We move `string1' into `string2' if the latter's empty -- but not if
  3741. `string1' is null. */
  3742. if (size2 == 0 && string1 != NULL)
  3743. {
  3744. string2 = string1;
  3745. size2 = size1;
  3746. string1 = 0;
  3747. size1 = 0;
  3748. }
  3749. end1 = string1 + size1;
  3750. end2 = string2 + size2;
  3751. /* Compute where to stop matching, within the two strings. */
  3752. if (stop <= size1)
  3753. {
  3754. end_match_1 = string1 + stop;
  3755. end_match_2 = string2;
  3756. }
  3757. else
  3758. {
  3759. end_match_1 = end1;
  3760. end_match_2 = string2 + stop - size1;
  3761. }
  3762. /* `p' scans through the pattern as `d' scans through the data.
  3763. `dend' is the end of the input string that `d' points within. `d'
  3764. is advanced into the following input string whenever necessary, but
  3765. this happens before fetching; therefore, at the beginning of the
  3766. loop, `d' can be pointing at the end of a string, but it cannot
  3767. equal `string2'. */
  3768. if (size1 > 0 && pos <= size1)
  3769. {
  3770. d = string1 + pos;
  3771. dend = end_match_1;
  3772. }
  3773. else
  3774. {
  3775. d = string2 + pos - size1;
  3776. dend = end_match_2;
  3777. }
  3778. DEBUG_PRINT1 ("The compiled pattern is:\n");
  3779. DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
  3780. DEBUG_PRINT1 ("The string to match is: `");
  3781. DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
  3782. DEBUG_PRINT1 ("'\n");
  3783. /* This loops over pattern commands. It exits by returning from the
  3784. function if the match is complete, or it drops through if the match
  3785. fails at this starting point in the input data. */
  3786. for (;;)
  3787. {
  3788. #ifdef _LIBC
  3789. DEBUG_PRINT2 ("\n%p: ", p);
  3790. #else
  3791. DEBUG_PRINT2 ("\n0x%x: ", p);
  3792. #endif
  3793. if (p == pend)
  3794. { /* End of pattern means we might have succeeded. */
  3795. DEBUG_PRINT1 ("end of pattern ... ");
  3796. /* If we haven't matched the entire string, and we want the
  3797. longest match, try backtracking. */
  3798. if (d != end_match_2)
  3799. {
  3800. /* 1 if this match ends in the same string (string1 or string2)
  3801. as the best previous match. */
  3802. boolean same_str_p = (FIRST_STRING_P (match_end)
  3803. == MATCHING_IN_FIRST_STRING);
  3804. /* 1 if this match is the best seen so far. */
  3805. boolean best_match_p;
  3806. /* AIX compiler got confused when this was combined
  3807. with the previous declaration. */
  3808. if (same_str_p)
  3809. best_match_p = d > match_end;
  3810. else
  3811. best_match_p = !MATCHING_IN_FIRST_STRING;
  3812. DEBUG_PRINT1 ("backtracking.\n");
  3813. if (!FAIL_STACK_EMPTY ())
  3814. { /* More failure points to try. */
  3815. /* If exceeds best match so far, save it. */
  3816. if (!best_regs_set || best_match_p)
  3817. {
  3818. best_regs_set = true;
  3819. match_end = d;
  3820. DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
  3821. for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
  3822. {
  3823. best_regstart[mcnt] = regstart[mcnt];
  3824. best_regend[mcnt] = regend[mcnt];
  3825. }
  3826. }
  3827. goto fail;
  3828. }
  3829. /* If no failure points, don't restore garbage. And if
  3830. last match is real best match, don't restore second
  3831. best one. */
  3832. else if (best_regs_set && !best_match_p)
  3833. {
  3834. restore_best_regs:
  3835. /* Restore best match. It may happen that `dend ==
  3836. end_match_1' while the restored d is in string2.
  3837. For example, the pattern `x.*y.*z' against the
  3838. strings `x-' and `y-z-', if the two strings are
  3839. not consecutive in memory. */
  3840. DEBUG_PRINT1 ("Restoring best registers.\n");
  3841. d = match_end;
  3842. dend = ((d >= string1 && d <= end1)
  3843. ? end_match_1 : end_match_2);
  3844. for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
  3845. {
  3846. regstart[mcnt] = best_regstart[mcnt];
  3847. regend[mcnt] = best_regend[mcnt];
  3848. }
  3849. }
  3850. } /* d != end_match_2 */
  3851. succeed_label:
  3852. DEBUG_PRINT1 ("Accepting match.\n");
  3853. /* If caller wants register contents data back, do it. */
  3854. if (regs && !bufp->no_sub)
  3855. {
  3856. /* Have the register data arrays been allocated? */
  3857. if (bufp->regs_allocated == REGS_UNALLOCATED)
  3858. { /* No. So allocate them with malloc. We need one
  3859. extra element beyond `num_regs' for the `-1' marker
  3860. GNU code uses. */
  3861. regs->num_regs = MAX (RE_NREGS, num_regs + 1);
  3862. regs->start = TALLOC (regs->num_regs, regoff_t);
  3863. regs->end = TALLOC (regs->num_regs, regoff_t);
  3864. if (regs->start == NULL || regs->end == NULL)
  3865. {
  3866. FREE_VARIABLES ();
  3867. return -2;
  3868. }
  3869. bufp->regs_allocated = REGS_REALLOCATE;
  3870. }
  3871. else if (bufp->regs_allocated == REGS_REALLOCATE)
  3872. { /* Yes. If we need more elements than were already
  3873. allocated, reallocate them. If we need fewer, just
  3874. leave it alone. */
  3875. if (regs->num_regs < num_regs + 1)
  3876. {
  3877. regs->num_regs = num_regs + 1;
  3878. RETALLOC (regs->start, regs->num_regs, regoff_t);
  3879. RETALLOC (regs->end, regs->num_regs, regoff_t);
  3880. if (regs->start == NULL || regs->end == NULL)
  3881. {
  3882. FREE_VARIABLES ();
  3883. return -2;
  3884. }
  3885. }
  3886. }
  3887. else
  3888. {
  3889. /* These braces fend off a "empty body in an else-statement"
  3890. warning under GCC when assert expands to nothing. */
  3891. assert (bufp->regs_allocated == REGS_FIXED);
  3892. }
  3893. /* Convert the pointer data in `regstart' and `regend' to
  3894. indices. Register zero has to be set differently,
  3895. since we haven't kept track of any info for it. */
  3896. if (regs->num_regs > 0)
  3897. {
  3898. regs->start[0] = pos;
  3899. regs->end[0] = (MATCHING_IN_FIRST_STRING
  3900. ? ((regoff_t) (d - string1))
  3901. : ((regoff_t) (d - string2 + size1)));
  3902. }
  3903. /* Go through the first `min (num_regs, regs->num_regs)'
  3904. registers, since that is all we initialized. */
  3905. for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
  3906. mcnt++)
  3907. {
  3908. if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
  3909. regs->start[mcnt] = regs->end[mcnt] = -1;
  3910. else
  3911. {
  3912. regs->start[mcnt]
  3913. = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
  3914. regs->end[mcnt]
  3915. = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
  3916. }
  3917. }
  3918. /* If the regs structure we return has more elements than
  3919. were in the pattern, set the extra elements to -1. If
  3920. we (re)allocated the registers, this is the case,
  3921. because we always allocate enough to have at least one
  3922. -1 at the end. */
  3923. for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
  3924. regs->start[mcnt] = regs->end[mcnt] = -1;
  3925. } /* regs && !bufp->no_sub */
  3926. DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
  3927. nfailure_points_pushed, nfailure_points_popped,
  3928. nfailure_points_pushed - nfailure_points_popped);
  3929. DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
  3930. mcnt = d - pos - (MATCHING_IN_FIRST_STRING
  3931. ? string1
  3932. : string2 - size1);
  3933. DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
  3934. FREE_VARIABLES ();
  3935. return mcnt;
  3936. }
  3937. /* Otherwise match next pattern command. */
  3938. switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
  3939. {
  3940. /* Ignore these. Used to ignore the n of succeed_n's which
  3941. currently have n == 0. */
  3942. case no_op:
  3943. DEBUG_PRINT1 ("EXECUTING no_op.\n");
  3944. break;
  3945. case succeed:
  3946. DEBUG_PRINT1 ("EXECUTING succeed.\n");
  3947. goto succeed_label;
  3948. /* Match the next n pattern characters exactly. The following
  3949. byte in the pattern defines n, and the n bytes after that
  3950. are the characters to match. */
  3951. case exactn:
  3952. mcnt = *p++;
  3953. DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
  3954. /* This is written out as an if-else so we don't waste time
  3955. testing `translate' inside the loop. */
  3956. if (translate)
  3957. {
  3958. do
  3959. {
  3960. PREFETCH ();
  3961. if ((unsigned char) translate[(unsigned char) *d++]
  3962. != (unsigned char) *p++)
  3963. goto fail;
  3964. }
  3965. while (--mcnt);
  3966. }
  3967. else
  3968. {
  3969. do
  3970. {
  3971. PREFETCH ();
  3972. if (*d++ != (char) *p++) goto fail;
  3973. }
  3974. while (--mcnt);
  3975. }
  3976. SET_REGS_MATCHED ();
  3977. break;
  3978. /* Match any character except possibly a newline or a null. */
  3979. case anychar:
  3980. DEBUG_PRINT1 ("EXECUTING anychar.\n");
  3981. PREFETCH ();
  3982. if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
  3983. || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
  3984. goto fail;
  3985. SET_REGS_MATCHED ();
  3986. DEBUG_PRINT2 (" Matched `%d'.\n", *d);
  3987. d++;
  3988. break;
  3989. case charset:
  3990. case charset_not:
  3991. {
  3992. register unsigned char c;
  3993. boolean not = (re_opcode_t) *(p - 1) == charset_not;
  3994. DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
  3995. PREFETCH ();
  3996. c = TRANSLATE (*d); /* The character to match. */
  3997. /* Cast to `unsigned' instead of `unsigned char' in case the
  3998. bit list is a full 32 bytes long. */
  3999. if (c < (unsigned) (*p * BYTEWIDTH)
  4000. && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  4001. not = !not;
  4002. p += 1 + *p;
  4003. if (!not) goto fail;
  4004. SET_REGS_MATCHED ();
  4005. d++;
  4006. break;
  4007. }
  4008. /* The beginning of a group is represented by start_memory.
  4009. The arguments are the register number in the next byte, and the
  4010. number of groups inner to this one in the next. The text
  4011. matched within the group is recorded (in the internal
  4012. registers data structure) under the register number. */
  4013. case start_memory:
  4014. DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
  4015. /* Find out if this group can match the empty string. */
  4016. p1 = p; /* To send to group_match_null_string_p. */
  4017. if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
  4018. REG_MATCH_NULL_STRING_P (reg_info[*p])
  4019. = group_match_null_string_p (&p1, pend, reg_info);
  4020. /* Save the position in the string where we were the last time
  4021. we were at this open-group operator in case the group is
  4022. operated upon by a repetition operator, e.g., with `(a*)*b'
  4023. against `ab'; then we want to ignore where we are now in
  4024. the string in case this attempt to match fails. */
  4025. old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  4026. ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
  4027. : regstart[*p];
  4028. DEBUG_PRINT2 (" old_regstart: %d\n",
  4029. POINTER_TO_OFFSET (old_regstart[*p]));
  4030. regstart[*p] = d;
  4031. DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
  4032. IS_ACTIVE (reg_info[*p]) = 1;
  4033. MATCHED_SOMETHING (reg_info[*p]) = 0;
  4034. /* Clear this whenever we change the register activity status. */
  4035. set_regs_matched_done = 0;
  4036. /* This is the new highest active register. */
  4037. highest_active_reg = *p;
  4038. /* If nothing was active before, this is the new lowest active
  4039. register. */
  4040. if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  4041. lowest_active_reg = *p;
  4042. /* Move past the register number and inner group count. */
  4043. p += 2;
  4044. just_past_start_mem = p;
  4045. break;
  4046. /* The stop_memory opcode represents the end of a group. Its
  4047. arguments are the same as start_memory's: the register
  4048. number, and the number of inner groups. */
  4049. case stop_memory:
  4050. DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
  4051. /* We need to save the string position the last time we were at
  4052. this close-group operator in case the group is operated
  4053. upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
  4054. against `aba'; then we want to ignore where we are now in
  4055. the string in case this attempt to match fails. */
  4056. old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  4057. ? REG_UNSET (regend[*p]) ? d : regend[*p]
  4058. : regend[*p];
  4059. DEBUG_PRINT2 (" old_regend: %d\n",
  4060. POINTER_TO_OFFSET (old_regend[*p]));
  4061. regend[*p] = d;
  4062. DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
  4063. /* This register isn't active anymore. */
  4064. IS_ACTIVE (reg_info[*p]) = 0;
  4065. /* Clear this whenever we change the register activity status. */
  4066. set_regs_matched_done = 0;
  4067. /* If this was the only register active, nothing is active
  4068. anymore. */
  4069. if (lowest_active_reg == highest_active_reg)
  4070. {
  4071. lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  4072. highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  4073. }
  4074. else
  4075. { /* We must scan for the new highest active register, since
  4076. it isn't necessarily one less than now: consider
  4077. (a(b)c(d(e)f)g). When group 3 ends, after the f), the
  4078. new highest active register is 1. */
  4079. unsigned char r = *p - 1;
  4080. while (r > 0 && !IS_ACTIVE (reg_info[r]))
  4081. r--;
  4082. /* If we end up at register zero, that means that we saved
  4083. the registers as the result of an `on_failure_jump', not
  4084. a `start_memory', and we jumped to past the innermost
  4085. `stop_memory'. For example, in ((.)*) we save
  4086. registers 1 and 2 as a result of the *, but when we pop
  4087. back to the second ), we are at the stop_memory 1.
  4088. Thus, nothing is active. */
  4089. if (r == 0)
  4090. {
  4091. lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  4092. highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  4093. }
  4094. else
  4095. highest_active_reg = r;
  4096. }
  4097. /* If just failed to match something this time around with a
  4098. group that's operated on by a repetition operator, try to
  4099. force exit from the ``loop'', and restore the register
  4100. information for this group that we had before trying this
  4101. last match. */
  4102. if ((!MATCHED_SOMETHING (reg_info[*p])
  4103. || just_past_start_mem == p - 1)
  4104. && (p + 2) < pend)
  4105. {
  4106. boolean is_a_jump_n = false;
  4107. p1 = p + 2;
  4108. mcnt = 0;
  4109. switch ((re_opcode_t) *p1++)
  4110. {
  4111. case jump_n:
  4112. is_a_jump_n = true;
  4113. case pop_failure_jump:
  4114. case maybe_pop_jump:
  4115. case jump:
  4116. case dummy_failure_jump:
  4117. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4118. if (is_a_jump_n)
  4119. p1 += 2;
  4120. break;
  4121. default:
  4122. /* do nothing */ ;
  4123. }
  4124. p1 += mcnt;
  4125. /* If the next operation is a jump backwards in the pattern
  4126. to an on_failure_jump right before the start_memory
  4127. corresponding to this stop_memory, exit from the loop
  4128. by forcing a failure after pushing on the stack the
  4129. on_failure_jump's jump in the pattern, and d. */
  4130. if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
  4131. && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
  4132. {
  4133. /* If this group ever matched anything, then restore
  4134. what its registers were before trying this last
  4135. failed match, e.g., with `(a*)*b' against `ab' for
  4136. regstart[1], and, e.g., with `((a*)*(b*)*)*'
  4137. against `aba' for regend[3].
  4138. Also restore the registers for inner groups for,
  4139. e.g., `((a*)(b*))*' against `aba' (register 3 would
  4140. otherwise get trashed). */
  4141. if (EVER_MATCHED_SOMETHING (reg_info[*p]))
  4142. {
  4143. unsigned r;
  4144. EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
  4145. /* Restore this and inner groups' (if any) registers. */
  4146. for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
  4147. r++)
  4148. {
  4149. regstart[r] = old_regstart[r];
  4150. /* xx why this test? */
  4151. if (old_regend[r] >= regstart[r])
  4152. regend[r] = old_regend[r];
  4153. }
  4154. }
  4155. p1++;
  4156. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4157. PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
  4158. goto fail;
  4159. }
  4160. }
  4161. /* Move past the register number and the inner group count. */
  4162. p += 2;
  4163. break;
  4164. /* \<digit> has been turned into a `duplicate' command which is
  4165. followed by the numeric value of <digit> as the register number. */
  4166. case duplicate:
  4167. {
  4168. register const char *d2, *dend2;
  4169. int regno = *p++; /* Get which register to match against. */
  4170. DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
  4171. /* Can't back reference a group which we've never matched. */
  4172. if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
  4173. goto fail;
  4174. /* Where in input to try to start matching. */
  4175. d2 = regstart[regno];
  4176. /* Where to stop matching; if both the place to start and
  4177. the place to stop matching are in the same string, then
  4178. set to the place to stop, otherwise, for now have to use
  4179. the end of the first string. */
  4180. dend2 = ((FIRST_STRING_P (regstart[regno])
  4181. == FIRST_STRING_P (regend[regno]))
  4182. ? regend[regno] : end_match_1);
  4183. for (;;)
  4184. {
  4185. /* If necessary, advance to next segment in register
  4186. contents. */
  4187. while (d2 == dend2)
  4188. {
  4189. if (dend2 == end_match_2) break;
  4190. if (dend2 == regend[regno]) break;
  4191. /* End of string1 => advance to string2. */
  4192. d2 = string2;
  4193. dend2 = regend[regno];
  4194. }
  4195. /* At end of register contents => success */
  4196. if (d2 == dend2) break;
  4197. /* If necessary, advance to next segment in data. */
  4198. PREFETCH ();
  4199. /* How many characters left in this segment to match. */
  4200. mcnt = dend - d;
  4201. /* Want how many consecutive characters we can match in
  4202. one shot, so, if necessary, adjust the count. */
  4203. if (mcnt > dend2 - d2)
  4204. mcnt = dend2 - d2;
  4205. /* Compare that many; failure if mismatch, else move
  4206. past them. */
  4207. if (translate
  4208. ? bcmp_translate (d, d2, mcnt, translate)
  4209. : memcmp (d, d2, mcnt))
  4210. goto fail;
  4211. d += mcnt, d2 += mcnt;
  4212. /* Do this because we've match some characters. */
  4213. SET_REGS_MATCHED ();
  4214. }
  4215. }
  4216. break;
  4217. /* begline matches the empty string at the beginning of the string
  4218. (unless `not_bol' is set in `bufp'), and, if
  4219. `newline_anchor' is set, after newlines. */
  4220. case begline:
  4221. DEBUG_PRINT1 ("EXECUTING begline.\n");
  4222. if (AT_STRINGS_BEG (d))
  4223. {
  4224. if (!bufp->not_bol) break;
  4225. }
  4226. else if (d[-1] == '\n' && bufp->newline_anchor)
  4227. {
  4228. break;
  4229. }
  4230. /* In all other cases, we fail. */
  4231. goto fail;
  4232. /* endline is the dual of begline. */
  4233. case endline:
  4234. DEBUG_PRINT1 ("EXECUTING endline.\n");
  4235. if (AT_STRINGS_END (d))
  4236. {
  4237. if (!bufp->not_eol) break;
  4238. }
  4239. /* We have to ``prefetch'' the next character. */
  4240. else if ((d == end1 ? *string2 : *d) == '\n'
  4241. && bufp->newline_anchor)
  4242. {
  4243. break;
  4244. }
  4245. goto fail;
  4246. /* Match at the very beginning of the data. */
  4247. case begbuf:
  4248. DEBUG_PRINT1 ("EXECUTING begbuf.\n");
  4249. if (AT_STRINGS_BEG (d))
  4250. break;
  4251. goto fail;
  4252. /* Match at the very end of the data. */
  4253. case endbuf:
  4254. DEBUG_PRINT1 ("EXECUTING endbuf.\n");
  4255. if (AT_STRINGS_END (d))
  4256. break;
  4257. goto fail;
  4258. /* on_failure_keep_string_jump is used to optimize `.*\n'. It
  4259. pushes NULL as the value for the string on the stack. Then
  4260. `pop_failure_point' will keep the current value for the
  4261. string, instead of restoring it. To see why, consider
  4262. matching `foo\nbar' against `.*\n'. The .* matches the foo;
  4263. then the . fails against the \n. But the next thing we want
  4264. to do is match the \n against the \n; if we restored the
  4265. string value, we would be back at the foo.
  4266. Because this is used only in specific cases, we don't need to
  4267. check all the things that `on_failure_jump' does, to make
  4268. sure the right things get saved on the stack. Hence we don't
  4269. share its code. The only reason to push anything on the
  4270. stack at all is that otherwise we would have to change
  4271. `anychar's code to do something besides goto fail in this
  4272. case; that seems worse than this. */
  4273. case on_failure_keep_string_jump:
  4274. DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
  4275. EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4276. #ifdef _LIBC
  4277. DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
  4278. #else
  4279. DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
  4280. #endif
  4281. PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
  4282. break;
  4283. /* Uses of on_failure_jump:
  4284. Each alternative starts with an on_failure_jump that points
  4285. to the beginning of the next alternative. Each alternative
  4286. except the last ends with a jump that in effect jumps past
  4287. the rest of the alternatives. (They really jump to the
  4288. ending jump of the following alternative, because tensioning
  4289. these jumps is a hassle.)
  4290. Repeats start with an on_failure_jump that points past both
  4291. the repetition text and either the following jump or
  4292. pop_failure_jump back to this on_failure_jump. */
  4293. case on_failure_jump:
  4294. on_failure:
  4295. DEBUG_PRINT1 ("EXECUTING on_failure_jump");
  4296. EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4297. #ifdef _LIBC
  4298. DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
  4299. #else
  4300. DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
  4301. #endif
  4302. /* If this on_failure_jump comes right before a group (i.e.,
  4303. the original * applied to a group), save the information
  4304. for that group and all inner ones, so that if we fail back
  4305. to this point, the group's information will be correct.
  4306. For example, in \(a*\)*\1, we need the preceding group,
  4307. and in \(zz\(a*\)b*\)\2, we need the inner group. */
  4308. /* We can't use `p' to check ahead because we push
  4309. a failure point to `p + mcnt' after we do this. */
  4310. p1 = p;
  4311. /* We need to skip no_op's before we look for the
  4312. start_memory in case this on_failure_jump is happening as
  4313. the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
  4314. against aba. */
  4315. while (p1 < pend && (re_opcode_t) *p1 == no_op)
  4316. p1++;
  4317. if (p1 < pend && (re_opcode_t) *p1 == start_memory)
  4318. {
  4319. /* We have a new highest active register now. This will
  4320. get reset at the start_memory we are about to get to,
  4321. but we will have saved all the registers relevant to
  4322. this repetition op, as described above. */
  4323. highest_active_reg = *(p1 + 1) + *(p1 + 2);
  4324. if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  4325. lowest_active_reg = *(p1 + 1);
  4326. }
  4327. DEBUG_PRINT1 (":\n");
  4328. PUSH_FAILURE_POINT (p + mcnt, d, -2);
  4329. break;
  4330. /* A smart repeat ends with `maybe_pop_jump'.
  4331. We change it to either `pop_failure_jump' or `jump'. */
  4332. case maybe_pop_jump:
  4333. EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4334. DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
  4335. {
  4336. register unsigned char *p2 = p;
  4337. /* Compare the beginning of the repeat with what in the
  4338. pattern follows its end. If we can establish that there
  4339. is nothing that they would both match, i.e., that we
  4340. would have to backtrack because of (as in, e.g., `a*a')
  4341. then we can change to pop_failure_jump, because we'll
  4342. never have to backtrack.
  4343. This is not true in the case of alternatives: in
  4344. `(a|ab)*' we do need to backtrack to the `ab' alternative
  4345. (e.g., if the string was `ab'). But instead of trying to
  4346. detect that here, the alternative has put on a dummy
  4347. failure point which is what we will end up popping. */
  4348. /* Skip over open/close-group commands.
  4349. If what follows this loop is a ...+ construct,
  4350. look at what begins its body, since we will have to
  4351. match at least one of that. */
  4352. while (1)
  4353. {
  4354. if (p2 + 2 < pend
  4355. && ((re_opcode_t) *p2 == stop_memory
  4356. || (re_opcode_t) *p2 == start_memory))
  4357. p2 += 3;
  4358. else if (p2 + 6 < pend
  4359. && (re_opcode_t) *p2 == dummy_failure_jump)
  4360. p2 += 6;
  4361. else
  4362. break;
  4363. }
  4364. p1 = p + mcnt;
  4365. /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
  4366. to the `maybe_finalize_jump' of this case. Examine what
  4367. follows. */
  4368. /* If we're at the end of the pattern, we can change. */
  4369. if (p2 == pend)
  4370. {
  4371. /* Consider what happens when matching ":\(.*\)"
  4372. against ":/". I don't really understand this code
  4373. yet. */
  4374. p[-3] = (unsigned char) pop_failure_jump;
  4375. DEBUG_PRINT1
  4376. (" End of pattern: change to `pop_failure_jump'.\n");
  4377. }
  4378. else if ((re_opcode_t) *p2 == exactn
  4379. || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
  4380. {
  4381. register unsigned char c
  4382. = *p2 == (unsigned char) endline ? '\n' : p2[2];
  4383. if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
  4384. {
  4385. p[-3] = (unsigned char) pop_failure_jump;
  4386. DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
  4387. c, p1[5]);
  4388. }
  4389. else if ((re_opcode_t) p1[3] == charset
  4390. || (re_opcode_t) p1[3] == charset_not)
  4391. {
  4392. int not = (re_opcode_t) p1[3] == charset_not;
  4393. if (c < (unsigned char) (p1[4] * BYTEWIDTH)
  4394. && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  4395. not = !not;
  4396. /* `not' is equal to 1 if c would match, which means
  4397. that we can't change to pop_failure_jump. */
  4398. if (!not)
  4399. {
  4400. p[-3] = (unsigned char) pop_failure_jump;
  4401. DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
  4402. }
  4403. }
  4404. }
  4405. else if ((re_opcode_t) *p2 == charset)
  4406. {
  4407. /* We win if the first character of the loop is not part
  4408. of the charset. */
  4409. if ((re_opcode_t) p1[3] == exactn
  4410. && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
  4411. && (p2[2 + p1[5] / BYTEWIDTH]
  4412. & (1 << (p1[5] % BYTEWIDTH)))))
  4413. {
  4414. p[-3] = (unsigned char) pop_failure_jump;
  4415. DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
  4416. }
  4417. else if ((re_opcode_t) p1[3] == charset_not)
  4418. {
  4419. int idx;
  4420. /* We win if the charset_not inside the loop
  4421. lists every character listed in the charset after. */
  4422. for (idx = 0; idx < (int) p2[1]; idx++)
  4423. if (! (p2[2 + idx] == 0
  4424. || (idx < (int) p1[4]
  4425. && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
  4426. break;
  4427. if (idx == p2[1])
  4428. {
  4429. p[-3] = (unsigned char) pop_failure_jump;
  4430. DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
  4431. }
  4432. }
  4433. else if ((re_opcode_t) p1[3] == charset)
  4434. {
  4435. int idx;
  4436. /* We win if the charset inside the loop
  4437. has no overlap with the one after the loop. */
  4438. for (idx = 0;
  4439. idx < (int) p2[1] && idx < (int) p1[4];
  4440. idx++)
  4441. if ((p2[2 + idx] & p1[5 + idx]) != 0)
  4442. break;
  4443. if (idx == p2[1] || idx == p1[4])
  4444. {
  4445. p[-3] = (unsigned char) pop_failure_jump;
  4446. DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
  4447. }
  4448. }
  4449. }
  4450. }
  4451. p -= 2; /* Point at relative address again. */
  4452. if ((re_opcode_t) p[-1] != pop_failure_jump)
  4453. {
  4454. p[-1] = (unsigned char) jump;
  4455. DEBUG_PRINT1 (" Match => jump.\n");
  4456. goto unconditional_jump;
  4457. }
  4458. /* Note fall through. */
  4459. /* The end of a simple repeat has a pop_failure_jump back to
  4460. its matching on_failure_jump, where the latter will push a
  4461. failure point. The pop_failure_jump takes off failure
  4462. points put on by this pop_failure_jump's matching
  4463. on_failure_jump; we got through the pattern to here from the
  4464. matching on_failure_jump, so didn't fail. */
  4465. case pop_failure_jump:
  4466. {
  4467. /* We need to pass separate storage for the lowest and
  4468. highest registers, even though we don't care about the
  4469. actual values. Otherwise, we will restore only one
  4470. register from the stack, since lowest will == highest in
  4471. `pop_failure_point'. */
  4472. active_reg_t dummy_low_reg, dummy_high_reg;
  4473. unsigned char *pdummy;
  4474. const char *sdummy;
  4475. DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
  4476. POP_FAILURE_POINT (sdummy, pdummy,
  4477. dummy_low_reg, dummy_high_reg,
  4478. reg_dummy, reg_dummy, reg_info_dummy);
  4479. }
  4480. /* Note fall through. */
  4481. unconditional_jump:
  4482. #ifdef _LIBC
  4483. DEBUG_PRINT2 ("\n%p: ", p);
  4484. #else
  4485. DEBUG_PRINT2 ("\n0x%x: ", p);
  4486. #endif
  4487. /* Note fall through. */
  4488. /* Unconditionally jump (without popping any failure points). */
  4489. case jump:
  4490. EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
  4491. DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
  4492. p += mcnt; /* Do the jump. */
  4493. #ifdef _LIBC
  4494. DEBUG_PRINT2 ("(to %p).\n", p);
  4495. #else
  4496. DEBUG_PRINT2 ("(to 0x%x).\n", p);
  4497. #endif
  4498. break;
  4499. /* We need this opcode so we can detect where alternatives end
  4500. in `group_match_null_string_p' et al. */
  4501. case jump_past_alt:
  4502. DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
  4503. goto unconditional_jump;
  4504. /* Normally, the on_failure_jump pushes a failure point, which
  4505. then gets popped at pop_failure_jump. We will end up at
  4506. pop_failure_jump, also, and with a pattern of, say, `a+', we
  4507. are skipping over the on_failure_jump, so we have to push
  4508. something meaningless for pop_failure_jump to pop. */
  4509. case dummy_failure_jump:
  4510. DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
  4511. /* It doesn't matter what we push for the string here. What
  4512. the code at `fail' tests is the value for the pattern. */
  4513. PUSH_FAILURE_POINT (NULL, NULL, -2);
  4514. goto unconditional_jump;
  4515. /* At the end of an alternative, we need to push a dummy failure
  4516. point in case we are followed by a `pop_failure_jump', because
  4517. we don't want the failure point for the alternative to be
  4518. popped. For example, matching `(a|ab)*' against `aab'
  4519. requires that we match the `ab' alternative. */
  4520. case push_dummy_failure:
  4521. DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
  4522. /* See comments just above at `dummy_failure_jump' about the
  4523. two zeroes. */
  4524. PUSH_FAILURE_POINT (NULL, NULL, -2);
  4525. break;
  4526. /* Have to succeed matching what follows at least n times.
  4527. After that, handle like `on_failure_jump'. */
  4528. case succeed_n:
  4529. EXTRACT_NUMBER (mcnt, p + 2);
  4530. DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
  4531. assert (mcnt >= 0);
  4532. /* Originally, this is how many times we HAVE to succeed. */
  4533. if (mcnt > 0)
  4534. {
  4535. mcnt--;
  4536. p += 2;
  4537. STORE_NUMBER_AND_INCR (p, mcnt);
  4538. #ifdef _LIBC
  4539. DEBUG_PRINT3 (" Setting %p to %d.\n", p - 2, mcnt);
  4540. #else
  4541. DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p - 2, mcnt);
  4542. #endif
  4543. }
  4544. else if (mcnt == 0)
  4545. {
  4546. #ifdef _LIBC
  4547. DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
  4548. #else
  4549. DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2);
  4550. #endif
  4551. p[2] = (unsigned char) no_op;
  4552. p[3] = (unsigned char) no_op;
  4553. goto on_failure;
  4554. }
  4555. break;
  4556. case jump_n:
  4557. EXTRACT_NUMBER (mcnt, p + 2);
  4558. DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
  4559. /* Originally, this is how many times we CAN jump. */
  4560. if (mcnt)
  4561. {
  4562. mcnt--;
  4563. STORE_NUMBER (p + 2, mcnt);
  4564. #ifdef _LIBC
  4565. DEBUG_PRINT3 (" Setting %p to %d.\n", p + 2, mcnt);
  4566. #else
  4567. DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p + 2, mcnt);
  4568. #endif
  4569. goto unconditional_jump;
  4570. }
  4571. /* If don't have to jump any more, skip over the rest of command. */
  4572. else
  4573. p += 4;
  4574. break;
  4575. case set_number_at:
  4576. {
  4577. DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
  4578. EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4579. p1 = p + mcnt;
  4580. EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4581. #ifdef _LIBC
  4582. DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
  4583. #else
  4584. DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt);
  4585. #endif
  4586. STORE_NUMBER (p1, mcnt);
  4587. break;
  4588. }
  4589. #if 0
  4590. /* The DEC Alpha C compiler 3.x generates incorrect code for the
  4591. test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
  4592. AT_WORD_BOUNDARY, so this code is disabled. Expanding the
  4593. macro and introducing temporary variables works around the bug. */
  4594. case wordbound:
  4595. DEBUG_PRINT1 ("EXECUTING wordbound.\n");
  4596. if (AT_WORD_BOUNDARY (d))
  4597. break;
  4598. goto fail;
  4599. case notwordbound:
  4600. DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
  4601. if (AT_WORD_BOUNDARY (d))
  4602. goto fail;
  4603. break;
  4604. #else
  4605. case wordbound:
  4606. {
  4607. boolean prevchar, thischar;
  4608. DEBUG_PRINT1 ("EXECUTING wordbound.\n");
  4609. if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
  4610. break;
  4611. prevchar = WORDCHAR_P (d - 1);
  4612. thischar = WORDCHAR_P (d);
  4613. if (prevchar != thischar)
  4614. break;
  4615. goto fail;
  4616. }
  4617. case notwordbound:
  4618. {
  4619. boolean prevchar, thischar;
  4620. DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
  4621. if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
  4622. goto fail;
  4623. prevchar = WORDCHAR_P (d - 1);
  4624. thischar = WORDCHAR_P (d);
  4625. if (prevchar != thischar)
  4626. goto fail;
  4627. break;
  4628. }
  4629. #endif
  4630. case wordbeg:
  4631. DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
  4632. if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
  4633. break;
  4634. goto fail;
  4635. case wordend:
  4636. DEBUG_PRINT1 ("EXECUTING wordend.\n");
  4637. if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
  4638. && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
  4639. break;
  4640. goto fail;
  4641. #ifdef emacs
  4642. case before_dot:
  4643. DEBUG_PRINT1 ("EXECUTING before_dot.\n");
  4644. if (PTR_CHAR_POS ((unsigned char *) d) >= point)
  4645. goto fail;
  4646. break;
  4647. case at_dot:
  4648. DEBUG_PRINT1 ("EXECUTING at_dot.\n");
  4649. if (PTR_CHAR_POS ((unsigned char *) d) != point)
  4650. goto fail;
  4651. break;
  4652. case after_dot:
  4653. DEBUG_PRINT1 ("EXECUTING after_dot.\n");
  4654. if (PTR_CHAR_POS ((unsigned char *) d) <= point)
  4655. goto fail;
  4656. break;
  4657. case syntaxspec:
  4658. DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
  4659. mcnt = *p++;
  4660. goto matchsyntax;
  4661. case wordchar:
  4662. DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
  4663. mcnt = (int) Sword;
  4664. matchsyntax:
  4665. PREFETCH ();
  4666. /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
  4667. d++;
  4668. if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
  4669. goto fail;
  4670. SET_REGS_MATCHED ();
  4671. break;
  4672. case notsyntaxspec:
  4673. DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
  4674. mcnt = *p++;
  4675. goto matchnotsyntax;
  4676. case notwordchar:
  4677. DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
  4678. mcnt = (int) Sword;
  4679. matchnotsyntax:
  4680. PREFETCH ();
  4681. /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
  4682. d++;
  4683. if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
  4684. goto fail;
  4685. SET_REGS_MATCHED ();
  4686. break;
  4687. #else /* not emacs */
  4688. case wordchar:
  4689. DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
  4690. PREFETCH ();
  4691. if (!WORDCHAR_P (d))
  4692. goto fail;
  4693. SET_REGS_MATCHED ();
  4694. d++;
  4695. break;
  4696. case notwordchar:
  4697. DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
  4698. PREFETCH ();
  4699. if (WORDCHAR_P (d))
  4700. goto fail;
  4701. SET_REGS_MATCHED ();
  4702. d++;
  4703. break;
  4704. #endif /* not emacs */
  4705. default:
  4706. abort ();
  4707. }
  4708. continue; /* Successfully executed one pattern command; keep going. */
  4709. /* We goto here if a matching operation fails. */
  4710. fail:
  4711. if (!FAIL_STACK_EMPTY ())
  4712. { /* A restart point is known. Restore to that state. */
  4713. DEBUG_PRINT1 ("\nFAIL:\n");
  4714. POP_FAILURE_POINT (d, p,
  4715. lowest_active_reg, highest_active_reg,
  4716. regstart, regend, reg_info);
  4717. /* If this failure point is a dummy, try the next one. */
  4718. if (!p)
  4719. goto fail;
  4720. /* If we failed to the end of the pattern, don't examine *p. */
  4721. assert (p <= pend);
  4722. if (p < pend)
  4723. {
  4724. boolean is_a_jump_n = false;
  4725. /* If failed to a backwards jump that's part of a repetition
  4726. loop, need to pop this failure point and use the next one. */
  4727. switch ((re_opcode_t) *p)
  4728. {
  4729. case jump_n:
  4730. is_a_jump_n = true;
  4731. case maybe_pop_jump:
  4732. case pop_failure_jump:
  4733. case jump:
  4734. p1 = p + 1;
  4735. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4736. p1 += mcnt;
  4737. if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
  4738. || (!is_a_jump_n
  4739. && (re_opcode_t) *p1 == on_failure_jump))
  4740. goto fail;
  4741. break;
  4742. default:
  4743. /* do nothing */ ;
  4744. }
  4745. }
  4746. if (d >= string1 && d <= end1)
  4747. dend = end_match_1;
  4748. }
  4749. else
  4750. break; /* Matching at this starting point really fails. */
  4751. } /* for (;;) */
  4752. if (best_regs_set)
  4753. goto restore_best_regs;
  4754. FREE_VARIABLES ();
  4755. return -1; /* Failure to match. */
  4756. } /* re_match_2 */
  4757. /* Subroutine definitions for re_match_2. */
  4758. /* We are passed P pointing to a register number after a start_memory.
  4759. Return true if the pattern up to the corresponding stop_memory can
  4760. match the empty string, and false otherwise.
  4761. If we find the matching stop_memory, sets P to point to one past its number.
  4762. Otherwise, sets P to an undefined byte less than or equal to END.
  4763. We don't handle duplicates properly (yet). */
  4764. static boolean
  4765. group_match_null_string_p (p, end, reg_info)
  4766. unsigned char **p, *end;
  4767. register_info_type *reg_info;
  4768. {
  4769. int mcnt;
  4770. /* Point to after the args to the start_memory. */
  4771. unsigned char *p1 = *p + 2;
  4772. while (p1 < end)
  4773. {
  4774. /* Skip over opcodes that can match nothing, and return true or
  4775. false, as appropriate, when we get to one that can't, or to the
  4776. matching stop_memory. */
  4777. switch ((re_opcode_t) *p1)
  4778. {
  4779. /* Could be either a loop or a series of alternatives. */
  4780. case on_failure_jump:
  4781. p1++;
  4782. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4783. /* If the next operation is not a jump backwards in the
  4784. pattern. */
  4785. if (mcnt >= 0)
  4786. {
  4787. /* Go through the on_failure_jumps of the alternatives,
  4788. seeing if any of the alternatives cannot match nothing.
  4789. The last alternative starts with only a jump,
  4790. whereas the rest start with on_failure_jump and end
  4791. with a jump, e.g., here is the pattern for `a|b|c':
  4792. /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
  4793. /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
  4794. /exactn/1/c
  4795. So, we have to first go through the first (n-1)
  4796. alternatives and then deal with the last one separately. */
  4797. /* Deal with the first (n-1) alternatives, which start
  4798. with an on_failure_jump (see above) that jumps to right
  4799. past a jump_past_alt. */
  4800. while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
  4801. {
  4802. /* `mcnt' holds how many bytes long the alternative
  4803. is, including the ending `jump_past_alt' and
  4804. its number. */
  4805. if (!alt_match_null_string_p (p1, p1 + mcnt - 3,
  4806. reg_info))
  4807. return false;
  4808. /* Move to right after this alternative, including the
  4809. jump_past_alt. */
  4810. p1 += mcnt;
  4811. /* Break if it's the beginning of an n-th alternative
  4812. that doesn't begin with an on_failure_jump. */
  4813. if ((re_opcode_t) *p1 != on_failure_jump)
  4814. break;
  4815. /* Still have to check that it's not an n-th
  4816. alternative that starts with an on_failure_jump. */
  4817. p1++;
  4818. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4819. if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
  4820. {
  4821. /* Get to the beginning of the n-th alternative. */
  4822. p1 -= 3;
  4823. break;
  4824. }
  4825. }
  4826. /* Deal with the last alternative: go back and get number
  4827. of the `jump_past_alt' just before it. `mcnt' contains
  4828. the length of the alternative. */
  4829. EXTRACT_NUMBER (mcnt, p1 - 2);
  4830. if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
  4831. return false;
  4832. p1 += mcnt; /* Get past the n-th alternative. */
  4833. } /* if mcnt > 0 */
  4834. break;
  4835. case stop_memory:
  4836. assert (p1[1] == **p);
  4837. *p = p1 + 2;
  4838. return true;
  4839. default:
  4840. if (!common_op_match_null_string_p (&p1, end, reg_info))
  4841. return false;
  4842. }
  4843. } /* while p1 < end */
  4844. return false;
  4845. } /* group_match_null_string_p */
  4846. /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
  4847. It expects P to be the first byte of a single alternative and END one
  4848. byte past the last. The alternative can contain groups. */
  4849. static boolean
  4850. alt_match_null_string_p (p, end, reg_info)
  4851. unsigned char *p, *end;
  4852. register_info_type *reg_info;
  4853. {
  4854. int mcnt;
  4855. unsigned char *p1 = p;
  4856. while (p1 < end)
  4857. {
  4858. /* Skip over opcodes that can match nothing, and break when we get
  4859. to one that can't. */
  4860. switch ((re_opcode_t) *p1)
  4861. {
  4862. /* It's a loop. */
  4863. case on_failure_jump:
  4864. p1++;
  4865. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4866. p1 += mcnt;
  4867. break;
  4868. default:
  4869. if (!common_op_match_null_string_p (&p1, end, reg_info))
  4870. return false;
  4871. }
  4872. } /* while p1 < end */
  4873. return true;
  4874. } /* alt_match_null_string_p */
  4875. /* Deals with the ops common to group_match_null_string_p and
  4876. alt_match_null_string_p.
  4877. Sets P to one after the op and its arguments, if any. */
  4878. static boolean
  4879. common_op_match_null_string_p (p, end, reg_info)
  4880. unsigned char **p, *end;
  4881. register_info_type *reg_info;
  4882. {
  4883. int mcnt;
  4884. boolean ret;
  4885. int reg_no;
  4886. unsigned char *p1 = *p;
  4887. switch ((re_opcode_t) *p1++)
  4888. {
  4889. case no_op:
  4890. case begline:
  4891. case endline:
  4892. case begbuf:
  4893. case endbuf:
  4894. case wordbeg:
  4895. case wordend:
  4896. case wordbound:
  4897. case notwordbound:
  4898. #ifdef emacs
  4899. case before_dot:
  4900. case at_dot:
  4901. case after_dot:
  4902. #endif
  4903. break;
  4904. case start_memory:
  4905. reg_no = *p1;
  4906. assert (reg_no > 0 && reg_no <= MAX_REGNUM);
  4907. ret = group_match_null_string_p (&p1, end, reg_info);
  4908. /* Have to set this here in case we're checking a group which
  4909. contains a group and a back reference to it. */
  4910. if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
  4911. REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
  4912. if (!ret)
  4913. return false;
  4914. break;
  4915. /* If this is an optimized succeed_n for zero times, make the jump. */
  4916. case jump:
  4917. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4918. if (mcnt >= 0)
  4919. p1 += mcnt;
  4920. else
  4921. return false;
  4922. break;
  4923. case succeed_n:
  4924. /* Get to the number of times to succeed. */
  4925. p1 += 2;
  4926. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4927. if (mcnt == 0)
  4928. {
  4929. p1 -= 4;
  4930. EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4931. p1 += mcnt;
  4932. }
  4933. else
  4934. return false;
  4935. break;
  4936. case duplicate:
  4937. if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
  4938. return false;
  4939. break;
  4940. case set_number_at:
  4941. p1 += 4;
  4942. default:
  4943. /* All other opcodes mean we cannot match the empty string. */
  4944. return false;
  4945. }
  4946. *p = p1;
  4947. return true;
  4948. } /* common_op_match_null_string_p */
  4949. /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
  4950. bytes; nonzero otherwise. */
  4951. static int
  4952. bcmp_translate (s1, s2, len, translate)
  4953. const char *s1, *s2;
  4954. register int len;
  4955. RE_TRANSLATE_TYPE translate;
  4956. {
  4957. register const unsigned char *p1 = (const unsigned char *) s1;
  4958. register const unsigned char *p2 = (const unsigned char *) s2;
  4959. while (len)
  4960. {
  4961. if (translate[*p1++] != translate[*p2++]) return 1;
  4962. len--;
  4963. }
  4964. return 0;
  4965. }
  4966. /* Entry points for GNU code. */
  4967. /* re_compile_pattern is the GNU regular expression compiler: it
  4968. compiles PATTERN (of length SIZE) and puts the result in BUFP.
  4969. Returns 0 if the pattern was valid, otherwise an error string.
  4970. Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  4971. are set in BUFP on entry.
  4972. We call regex_compile to do the actual compilation. */
  4973. const char *
  4974. re_compile_pattern (pattern, length, bufp)
  4975. const char *pattern;
  4976. size_t length;
  4977. struct re_pattern_buffer *bufp;
  4978. {
  4979. reg_errcode_t ret;
  4980. /* GNU code is written to assume at least RE_NREGS registers will be set
  4981. (and at least one extra will be -1). */
  4982. bufp->regs_allocated = REGS_UNALLOCATED;
  4983. /* And GNU code determines whether or not to get register information
  4984. by passing null for the REGS argument to re_match, etc., not by
  4985. setting no_sub. */
  4986. bufp->no_sub = 0;
  4987. /* Match anchors at newline. */
  4988. bufp->newline_anchor = 1;
  4989. ret = regex_compile (pattern, length, re_syntax_options, bufp);
  4990. if (!ret)
  4991. return NULL;
  4992. return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
  4993. }
  4994. #ifdef _LIBC
  4995. weak_alias (__re_compile_pattern, re_compile_pattern)
  4996. #endif
  4997. /* Entry points compatible with 4.2 BSD regex library. We don't define
  4998. them unless specifically requested. */
  4999. #if defined _REGEX_RE_COMP || defined _LIBC
  5000. /* BSD has one and only one pattern buffer. */
  5001. static struct re_pattern_buffer re_comp_buf;
  5002. char *
  5003. #ifdef _LIBC
  5004. /* Make these definitions weak in libc, so POSIX programs can redefine
  5005. these names if they don't use our functions, and still use
  5006. regcomp/regexec below without link errors. */
  5007. weak_function
  5008. #endif
  5009. re_comp (s)
  5010. const char *s;
  5011. {
  5012. reg_errcode_t ret;
  5013. if (!s)
  5014. {
  5015. if (!re_comp_buf.buffer)
  5016. return gettext ("No previous regular expression");
  5017. return 0;
  5018. }
  5019. if (!re_comp_buf.buffer)
  5020. {
  5021. re_comp_buf.buffer = (unsigned char *) malloc (200);
  5022. if (re_comp_buf.buffer == NULL)
  5023. return (char *) gettext (re_error_msgid
  5024. + re_error_msgid_idx[(int) REG_ESPACE]);
  5025. re_comp_buf.allocated = 200;
  5026. re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
  5027. if (re_comp_buf.fastmap == NULL)
  5028. return (char *) gettext (re_error_msgid
  5029. + re_error_msgid_idx[(int) REG_ESPACE]);
  5030. }
  5031. /* Since `re_exec' always passes NULL for the `regs' argument, we
  5032. don't need to initialize the pattern buffer fields which affect it. */
  5033. /* Match anchors at newlines. */
  5034. re_comp_buf.newline_anchor = 1;
  5035. ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
  5036. if (!ret)
  5037. return NULL;
  5038. /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
  5039. return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
  5040. }
  5041. int
  5042. #ifdef _LIBC
  5043. weak_function
  5044. #endif
  5045. re_exec (s)
  5046. const char *s;
  5047. {
  5048. const int len = strlen (s);
  5049. return
  5050. 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
  5051. }
  5052. #endif /* _REGEX_RE_COMP */
  5053. /* POSIX.2 functions. Don't define these for Emacs. */
  5054. #ifndef emacs
  5055. /* regcomp takes a regular expression as a string and compiles it.
  5056. PREG is a regex_t *. We do not expect any fields to be initialized,
  5057. since POSIX says we shouldn't. Thus, we set
  5058. `buffer' to the compiled pattern;
  5059. `used' to the length of the compiled pattern;
  5060. `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  5061. REG_EXTENDED bit in CFLAGS is set; otherwise, to
  5062. RE_SYNTAX_POSIX_BASIC;
  5063. `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  5064. `fastmap' to an allocated space for the fastmap;
  5065. `fastmap_accurate' to zero;
  5066. `re_nsub' to the number of subexpressions in PATTERN.
  5067. PATTERN is the address of the pattern string.
  5068. CFLAGS is a series of bits which affect compilation.
  5069. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  5070. use POSIX basic syntax.
  5071. If REG_NEWLINE is set, then . and [^...] don't match newline.
  5072. Also, regexec will try a match beginning after every newline.
  5073. If REG_ICASE is set, then we considers upper- and lowercase
  5074. versions of letters to be equivalent when matching.
  5075. If REG_NOSUB is set, then when PREG is passed to regexec, that
  5076. routine will report only success or failure, and nothing about the
  5077. registers.
  5078. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
  5079. the return codes and their meanings.) */
  5080. int
  5081. regcomp (preg, pattern, cflags)
  5082. regex_t *preg;
  5083. const char *pattern;
  5084. int cflags;
  5085. {
  5086. reg_errcode_t ret;
  5087. reg_syntax_t syntax
  5088. = (cflags & REG_EXTENDED) ?
  5089. RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
  5090. /* regex_compile will allocate the space for the compiled pattern. */
  5091. preg->buffer = 0;
  5092. preg->allocated = 0;
  5093. preg->used = 0;
  5094. /* Try to allocate space for the fastmap. */
  5095. preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
  5096. if (cflags & REG_ICASE)
  5097. {
  5098. unsigned i;
  5099. preg->translate
  5100. = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
  5101. * sizeof (*(RE_TRANSLATE_TYPE)0));
  5102. if (preg->translate == NULL)
  5103. return (int) REG_ESPACE;
  5104. /* Map uppercase characters to corresponding lowercase ones. */
  5105. for (i = 0; i < CHAR_SET_SIZE; i++)
  5106. preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
  5107. }
  5108. else
  5109. preg->translate = NULL;
  5110. /* If REG_NEWLINE is set, newlines are treated differently. */
  5111. if (cflags & REG_NEWLINE)
  5112. { /* REG_NEWLINE implies neither . nor [^...] match newline. */
  5113. syntax &= ~RE_DOT_NEWLINE;
  5114. syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  5115. /* It also changes the matching behavior. */
  5116. preg->newline_anchor = 1;
  5117. }
  5118. else
  5119. preg->newline_anchor = 0;
  5120. preg->no_sub = !!(cflags & REG_NOSUB);
  5121. /* POSIX says a null character in the pattern terminates it, so we
  5122. can use strlen here in compiling the pattern. */
  5123. ret = regex_compile (pattern, strlen (pattern), syntax, preg);
  5124. /* POSIX doesn't distinguish between an unmatched open-group and an
  5125. unmatched close-group: both are REG_EPAREN. */
  5126. if (ret == REG_ERPAREN) ret = REG_EPAREN;
  5127. if (ret == REG_NOERROR && preg->fastmap)
  5128. {
  5129. /* Compute the fastmap now, since regexec cannot modify the pattern
  5130. buffer. */
  5131. if (re_compile_fastmap (preg) == -2)
  5132. {
  5133. /* Some error occurred while computing the fastmap, just forget
  5134. about it. */
  5135. free (preg->fastmap);
  5136. preg->fastmap = NULL;
  5137. }
  5138. }
  5139. return (int) ret;
  5140. }
  5141. #ifdef _LIBC
  5142. weak_alias (__regcomp, regcomp)
  5143. #endif
  5144. /* regexec searches for a given pattern, specified by PREG, in the
  5145. string STRING.
  5146. If NMATCH is zero or REG_NOSUB was set in the cflags argument to
  5147. `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
  5148. least NMATCH elements, and we set them to the offsets of the
  5149. corresponding matched substrings.
  5150. EFLAGS specifies `execution flags' which affect matching: if
  5151. REG_NOTBOL is set, then ^ does not match at the beginning of the
  5152. string; if REG_NOTEOL is set, then $ does not match at the end.
  5153. We return 0 if we find a match and REG_NOMATCH if not. */
  5154. int
  5155. regexec (preg, string, nmatch, pmatch, eflags)
  5156. const regex_t *preg;
  5157. const char *string;
  5158. size_t nmatch;
  5159. regmatch_t pmatch[];
  5160. int eflags;
  5161. {
  5162. int ret;
  5163. struct re_registers regs;
  5164. regex_t private_preg;
  5165. int len = strlen (string);
  5166. boolean want_reg_info = !preg->no_sub && nmatch > 0;
  5167. private_preg = *preg;
  5168. private_preg.not_bol = !!(eflags & REG_NOTBOL);
  5169. private_preg.not_eol = !!(eflags & REG_NOTEOL);
  5170. /* The user has told us exactly how many registers to return
  5171. information about, via `nmatch'. We have to pass that on to the
  5172. matching routines. */
  5173. private_preg.regs_allocated = REGS_FIXED;
  5174. if (want_reg_info)
  5175. {
  5176. regs.num_regs = nmatch;
  5177. regs.start = TALLOC (nmatch * 2, regoff_t);
  5178. if (regs.start == NULL)
  5179. return (int) REG_NOMATCH;
  5180. regs.end = regs.start + nmatch;
  5181. }
  5182. /* Perform the searching operation. */
  5183. ret = re_search (&private_preg, string, len,
  5184. /* start: */ 0, /* range: */ len,
  5185. want_reg_info ? &regs : (struct re_registers *) 0);
  5186. /* Copy the register information to the POSIX structure. */
  5187. if (want_reg_info)
  5188. {
  5189. if (ret >= 0)
  5190. {
  5191. unsigned r;
  5192. for (r = 0; r < nmatch; r++)
  5193. {
  5194. pmatch[r].rm_so = regs.start[r];
  5195. pmatch[r].rm_eo = regs.end[r];
  5196. }
  5197. }
  5198. /* If we needed the temporary register info, free the space now. */
  5199. free (regs.start);
  5200. }
  5201. /* We want zero return to mean success, unlike `re_search'. */
  5202. return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
  5203. }
  5204. #ifdef _LIBC
  5205. weak_alias (__regexec, regexec)
  5206. #endif
  5207. /* Returns a message corresponding to an error code, ERRCODE, returned
  5208. from either regcomp or regexec. We don't use PREG here. */
  5209. size_t
  5210. regerror (errcode, preg, errbuf, errbuf_size)
  5211. int errcode;
  5212. const regex_t *preg;
  5213. char *errbuf;
  5214. size_t errbuf_size;
  5215. {
  5216. const char *msg;
  5217. size_t msg_size;
  5218. if (errcode < 0
  5219. || errcode >= (int) (sizeof (re_error_msgid_idx)
  5220. / sizeof (re_error_msgid_idx[0])))
  5221. /* Only error codes returned by the rest of the code should be passed
  5222. to this routine. If we are given anything else, or if other regex
  5223. code generates an invalid error code, then the program has a bug.
  5224. Dump core so we can fix it. */
  5225. abort ();
  5226. msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
  5227. msg_size = strlen (msg) + 1; /* Includes the null. */
  5228. if (errbuf_size != 0)
  5229. {
  5230. if (msg_size > errbuf_size)
  5231. {
  5232. #if defined HAVE_MEMPCPY || defined _LIBC
  5233. *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
  5234. #else
  5235. memcpy (errbuf, msg, errbuf_size - 1);
  5236. errbuf[errbuf_size - 1] = 0;
  5237. #endif
  5238. }
  5239. else
  5240. memcpy (errbuf, msg, msg_size);
  5241. }
  5242. return msg_size;
  5243. }
  5244. #ifdef _LIBC
  5245. weak_alias (__regerror, regerror)
  5246. #endif
  5247. /* Free dynamically allocated space used by PREG. */
  5248. void
  5249. regfree (preg)
  5250. regex_t *preg;
  5251. {
  5252. if (preg->buffer != NULL)
  5253. free (preg->buffer);
  5254. preg->buffer = NULL;
  5255. preg->allocated = 0;
  5256. preg->used = 0;
  5257. if (preg->fastmap != NULL)
  5258. free (preg->fastmap);
  5259. preg->fastmap = NULL;
  5260. preg->fastmap_accurate = 0;
  5261. if (preg->translate != NULL)
  5262. free (preg->translate);
  5263. preg->translate = NULL;
  5264. }
  5265. #ifdef _LIBC
  5266. weak_alias (__regfree, regfree)
  5267. #endif
  5268. #endif /* not emacs */
  5269. #else /* !defined(USE_LIB_REGEX) */
  5270. char regex_d1[] = "d"; char *regex_d2 = regex_d1;
  5271. #endif /* defined(USE_LIB_REGEX) */