Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1246 lines
36 KiB

  1. /* $Source: /u/mark/src/pax/RCS/regexp.c,v $
  2. *
  3. * $Revision: 1.2 $
  4. *
  5. * regexp.c - regular expression matching
  6. *
  7. * DESCRIPTION
  8. *
  9. * Underneath the reformatting and comment blocks which were added to
  10. * make it consistent with the rest of the code, you will find a
  11. * modified version of Henry Specer's regular expression library.
  12. * Henry's functions were modified to provide the minimal regular
  13. * expression matching, as required by P1003. Henry's code was
  14. * copyrighted, and copy of the copyright message and restrictions
  15. * are provided, verbatim, below:
  16. *
  17. * Copyright (c) 1986 by University of Toronto.
  18. * Written by Henry Spencer. Not derived from licensed software.
  19. *
  20. * Permission is granted to anyone to use this software for any
  21. * purpose on any computer system, and to redistribute it freely,
  22. * subject to the following restrictions:
  23. *
  24. * 1. The author is not responsible for the consequences of use of
  25. * this software, no matter how awful, even if they arise
  26. * from defects in it.
  27. *
  28. * 2. The origin of this software must not be misrepresented, either
  29. * by explicit claim or by omission.
  30. *
  31. * 3. Altered versions must be plainly marked as such, and must not
  32. * be misrepresented as being the original software.
  33. *
  34. * Beware that some of this code is subtly aware of the way operator
  35. * precedence is structured in regular expressions. Serious changes in
  36. * regular-expression syntax might require a total rethink.
  37. *
  38. * AUTHORS
  39. *
  40. * Mark H. Colburn, NAPS International (mark@jhereg.mn.org)
  41. * Henry Spencer, University of Torronto (henry@utzoo.edu)
  42. *
  43. * Sponsored by The USENIX Association for public distribution.
  44. *
  45. * $Log: regexp.c,v $
  46. * Revision 1.2 89/02/12 10:05:39 mark
  47. * 1.2 release fixes
  48. *
  49. * Revision 1.1 88/12/23 18:02:32 mark
  50. * Initial revision
  51. *
  52. */
  53. /* Headers */
  54. #include "pax.h"
  55. #ifndef lint
  56. static char *Ident = "$Id: regexp.c,v 1.2 89/02/12 10:05:39 mark Exp $";
  57. #endif
  58. /*
  59. * The "internal use only" fields in regexp.h are present to pass info from
  60. * compile to execute that permits the execute phase to run lots faster on
  61. * simple cases. They are:
  62. *
  63. * regstart char that must begin a match; '\0' if none obvious
  64. * reganch is the match anchored (at beginning-of-line only)?
  65. * regmust string (pointer into program) that match must include, or NULL
  66. * regmlen length of regmust string
  67. *
  68. * Regstart and reganch permit very fast decisions on suitable starting points
  69. * for a match, cutting down the work a lot. Regmust permits fast rejection
  70. * of lines that cannot possibly match. The regmust tests are costly enough
  71. * that regcomp() supplies a regmust only if the r.e. contains something
  72. * potentially expensive (at present, the only such thing detected is * or +
  73. * at the start of the r.e., which can involve a lot of backup). Regmlen is
  74. * supplied because the test in regexec() needs it and regcomp() is computing
  75. * it anyway.
  76. */
  77. /*
  78. * Structure for regexp "program". This is essentially a linear encoding
  79. * of a nondeterministic finite-state machine (aka syntax charts or
  80. * "railroad normal form" in parsing technology). Each node is an opcode
  81. * plus a "nxt" pointer, possibly plus an operand. "Nxt" pointers of
  82. * all nodes except BRANCH implement concatenation; a "nxt" pointer with
  83. * a BRANCH on both ends of it is connecting two alternatives. (Here we
  84. * have one of the subtle syntax dependencies: an individual BRANCH (as
  85. * opposed to a collection of them) is never concatenated with anything
  86. * because of operator precedence.) The operand of some types of node is
  87. * a literal string; for others, it is a node leading into a sub-FSM. In
  88. * particular, the operand of a BRANCH node is the first node of the branch.
  89. * (NB this is *not* a tree structure: the tail of the branch connects
  90. * to the thing following the set of BRANCHes.) The opcodes are:
  91. */
  92. /* definition number opnd? meaning */
  93. #define END 0 /* no End of program. */
  94. #define BOL 1 /* no Match "" at beginning of line. */
  95. #define EOL 2 /* no Match "" at end of line. */
  96. #define ANY 3 /* no Match any one character. */
  97. #define ANYOF 4 /* str Match any character in this string. */
  98. #define ANYBUT 5 /* str Match any character not in this
  99. * string. */
  100. #define BRANCH 6 /* node Match this alternative, or the
  101. * nxt... */
  102. #define BACK 7 /* no Match "", "nxt" ptr points backward. */
  103. #define EXACTLY 8 /* str Match this string. */
  104. #define NOTHING 9 /* no Match empty string. */
  105. #define STAR 10 /* node Match this (simple) thing 0 or more
  106. * times. */
  107. #define OPEN 20 /* no Mark this point in input as start of
  108. * #n. */
  109. /* OPEN+1 is number 1, etc. */
  110. #define CLOSE 30 /* no Analogous to OPEN. */
  111. /*
  112. * Opcode notes:
  113. *
  114. * BRANCH The set of branches constituting a single choice are hooked
  115. * together with their "nxt" pointers, since precedence prevents
  116. * anything being concatenated to any individual branch. The
  117. * "nxt" pointer of the last BRANCH in a choice points to the
  118. * thing following the whole choice. This is also where the
  119. * final "nxt" pointer of each individual branch points; each
  120. * branch starts with the operand node of a BRANCH node.
  121. *
  122. * BACK Normal "nxt" pointers all implicitly point forward; BACK
  123. * exists to make loop structures possible.
  124. *
  125. * STAR complex '*', are implemented as circular BRANCH structures
  126. * using BACK. Simple cases (one character per match) are
  127. * implemented with STAR for speed and to minimize recursive
  128. * plunges.
  129. *
  130. * OPEN,CLOSE ...are numbered at compile time.
  131. */
  132. /*
  133. * A node is one char of opcode followed by two chars of "nxt" pointer.
  134. * "Nxt" pointers are stored as two 8-bit pieces, high order first. The
  135. * value is a positive offset from the opcode of the node containing it.
  136. * An operand, if any, simply follows the node. (Note that much of the
  137. * code generation knows about this implicit relationship.)
  138. *
  139. * Using two bytes for the "nxt" pointer is vast overkill for most things,
  140. * but allows patterns to get big without disasters.
  141. */
  142. #define OP(p) (*(p))
  143. #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  144. #define OPERAND(p) ((p) + 3)
  145. /*
  146. * Utility definitions.
  147. */
  148. #define FAIL(m) { regerror(m); return(NULL); }
  149. #define ISMULT(c) ((c) == '*')
  150. #define META "^$.[()|*\\"
  151. #ifndef CHARBITS
  152. #define UCHARAT(p) ((int)*(unsigned char *)(p))
  153. #else
  154. #define UCHARAT(p) ((int)*(p)&CHARBITS)
  155. #endif
  156. /*
  157. * Flags to be passed up and down.
  158. */
  159. #define HASWIDTH 01 /* Known never to match null string. */
  160. #define SIMPLE 02 /* Simple enough to be STAR operand. */
  161. #define SPSTART 04 /* Starts with * */
  162. #define WORST 0 /* Worst case. */
  163. /*
  164. * Global work variables for regcomp().
  165. */
  166. static char *regparse; /* Input-scan pointer. */
  167. static int regnpar; /* () count. */
  168. static char regdummy;
  169. static char *regcode; /* Code-emit pointer; &regdummy = don't. */
  170. static long regsize; /* Code size. */
  171. /*
  172. * Forward declarations for regcomp()'s friends.
  173. */
  174. #ifndef STATIC
  175. #define STATIC static
  176. #endif
  177. STATIC char *reg(int, int *); /* Xn */
  178. STATIC char *regbranch(int *); /* Xn */
  179. STATIC char *regpiece(int *); /* Xn */
  180. STATIC char *regatom(int *); /* Xn */
  181. STATIC char *regnode(char); /* Xn */
  182. STATIC char *regnext(register char *); /* Xn */
  183. STATIC void regc(char); /* Xn */
  184. STATIC void reginsert(char, char *); /* Xn */
  185. STATIC void regtail(char *, char *); /* Xn */
  186. STATIC void regoptail(char *, char *); /* Xn */
  187. #ifdef STRCSPN
  188. STATIC size_t strcspn(const char *, const char *); /* Xn */
  189. #endif
  190. /*
  191. - regcomp - compile a regular expression into internal code
  192. *
  193. * We can't allocate space until we know how big the compiled form will be,
  194. * but we can't compile it (and thus know how big it is) until we've got a
  195. * place to put the code. So we cheat: we compile it twice, once with code
  196. * generation turned off and size counting turned on, and once "for real".
  197. * This also means that we don't allocate space until we are sure that the
  198. * thing really will compile successfully, and we never have to move the
  199. * code and thus invalidate pointers into it. (Note that it has to be in
  200. * one piece because free() must be able to free it all.)
  201. *
  202. * Beware that the optimization-preparation code in here knows about some
  203. * of the structure of the compiled regexp.
  204. */
  205. regexp *regcomp(char *exp) /* Xn */
  206. {
  207. register regexp *r;
  208. register char *scan;
  209. register char *longest;
  210. register size_t len;
  211. int flags;
  212. if (exp == (char *)NULL)
  213. FAIL("NULL argument");
  214. /* First pass: determine size, legality. */
  215. regparse = exp;
  216. regnpar = 1;
  217. regsize = 0L;
  218. regcode = &regdummy;
  219. regc(MAGIC);
  220. if (reg(0, &flags) == (char *)NULL)
  221. return ((regexp *)NULL);
  222. /* Small enough for pointer-storage convention? */
  223. if (regsize >= 32767L) /* Probably could be 65535L. */
  224. FAIL("regexp too big");
  225. /* Allocate space. */
  226. r = (regexp *) malloc(sizeof(regexp) + (unsigned) regsize);
  227. if (r == (regexp *) NULL)
  228. FAIL("out of space");
  229. /* Second pass: emit code. */
  230. regparse = exp;
  231. regnpar = 1;
  232. regcode = r->program;
  233. regc(MAGIC);
  234. if (reg(0, &flags) == NULL)
  235. return ((regexp *) NULL);
  236. /* Dig out information for optimizations. */
  237. r->regstart = '\0'; /* Worst-case defaults. */
  238. r->reganch = 0;
  239. r->regmust = NULL;
  240. r->regmlen = 0;
  241. scan = r->program + 1; /* First BRANCH. */
  242. if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
  243. scan = OPERAND(scan);
  244. /* Starting-point info. */
  245. if (OP(scan) == EXACTLY)
  246. r->regstart = *OPERAND(scan);
  247. else if (OP(scan) == BOL)
  248. r->reganch++;
  249. /*
  250. * If there's something expensive in the r.e., find the longest
  251. * literal string that must appear and make it the regmust. Resolve
  252. * ties in favor of later strings, since the regstart check works
  253. * with the beginning of the r.e. and avoiding duplication
  254. * strengthens checking. Not a strong reason, but sufficient in the
  255. * absence of others.
  256. */
  257. if (flags & SPSTART) {
  258. longest = NULL;
  259. len = 0;
  260. for (; scan != NULL; scan = regnext(scan))
  261. if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  262. longest = OPERAND(scan);
  263. len = strlen(OPERAND(scan));
  264. }
  265. r->regmust = longest;
  266. r->regmlen = len;
  267. }
  268. }
  269. return (r);
  270. }
  271. /*
  272. - reg - regular expression, i.e. main body or parenthesized thing
  273. *
  274. * Caller must absorb opening parenthesis.
  275. *
  276. * Combining parenthesis handling with the base level of regular expression
  277. * is a trifle forced, but the need to tie the tails of the branches to what
  278. * follows makes it hard to avoid.
  279. */
  280. static char *reg(int paren, int *flagp) /* Xn */
  281. {
  282. register char *ret;
  283. register char *br;
  284. register char *ender;
  285. register int parno;
  286. int flags;
  287. *flagp = HASWIDTH; /* Tentatively. */
  288. /* Make an OPEN node, if parenthesized. */
  289. #ifdef DF_TRACE_DEBUG
  290. printf("DF_TRACE_DEBUG: static char *reg() in regexp.c\n");
  291. #endif
  292. if (paren) {
  293. if (regnpar >= NSUBEXP)
  294. FAIL("too many ()");
  295. parno = regnpar;
  296. regnpar++;
  297. ret = regnode((char)(OPEN + parno));
  298. } else
  299. ret = (char *)NULL;
  300. /* Pick up the branches, linking them together. */
  301. br = regbranch(&flags);
  302. if (br == (char *)NULL)
  303. return ((char *)NULL);
  304. if (ret != (char *)NULL)
  305. regtail(ret, br); /* OPEN -> first. */
  306. else
  307. ret = br;
  308. if (!(flags & HASWIDTH))
  309. *flagp &= ~HASWIDTH;
  310. *flagp |= flags & SPSTART;
  311. while (*regparse == '|') {
  312. regparse++;
  313. br = regbranch(&flags);
  314. if (br == (char *)NULL)
  315. return ((char *)NULL);
  316. regtail(ret, br); /* BRANCH -> BRANCH. */
  317. if (!(flags & HASWIDTH))
  318. *flagp &= ~HASWIDTH;
  319. *flagp |= flags & SPSTART;
  320. }
  321. /* Make a closing node, and hook it on the end. */
  322. ender = regnode((char)((paren) ? CLOSE + parno : END));
  323. regtail(ret, ender);
  324. /* Hook the tails of the branches to the closing node. */
  325. for (br = ret; br != (char *)NULL; br = regnext(br))
  326. regoptail(br, ender);
  327. /* Check for proper termination. */
  328. if (paren && *regparse++ != ')') {
  329. FAIL("unmatched ()");
  330. } else if (!paren && *regparse != '\0') {
  331. if (*regparse == ')') {
  332. FAIL("unmatched ()");
  333. } else
  334. FAIL("junk on end");/* "Can't happen". */
  335. /* NOTREACHED */
  336. }
  337. return (ret);
  338. }
  339. /*
  340. - regbranch - one alternative of an | operator
  341. *
  342. * Implements the concatenation operator.
  343. */
  344. static char *regbranch(int *flagp) /* Xn */
  345. {
  346. register char *ret;
  347. register char *chain;
  348. register char *latest;
  349. int flags;
  350. *flagp = WORST; /* Tentatively. */
  351. #ifdef DF_TRACE_DEBUG
  352. printf("DF_TRACE_DEBUG: static char *regbranch() in regexp.c\n");
  353. #endif
  354. ret = regnode(BRANCH);
  355. chain = (char *)NULL;
  356. while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  357. latest = regpiece(&flags);
  358. if (latest == (char *)NULL)
  359. return ((char *)NULL);
  360. *flagp |= flags & HASWIDTH;
  361. if (chain == (char *)NULL) /* First piece. */
  362. *flagp |= flags & SPSTART;
  363. else
  364. regtail(chain, latest);
  365. chain = latest;
  366. }
  367. if (chain == (char *)NULL) /* Loop ran zero times. */
  368. regnode(NOTHING);
  369. return (ret);
  370. }
  371. /*
  372. - regpiece - something followed by possible [*]
  373. *
  374. * Note that the branching code sequence used for * is somewhat optimized:
  375. * they use the same NOTHING node as both the endmarker for their branch
  376. * list and the body of the last branch. It might seem that this node could
  377. * be dispensed with entirely, but the endmarker role is not redundant.
  378. */
  379. static char *regpiece(int *flagp) /* Xn */
  380. {
  381. register char *ret;
  382. register char op;
  383. int flags;
  384. ret = regatom(&flags);
  385. if (ret == (char *)NULL)
  386. return ((char *)NULL);
  387. op = *regparse;
  388. if (!ISMULT(op)) {
  389. *flagp = flags;
  390. return (ret);
  391. }
  392. if (!(flags & HASWIDTH))
  393. FAIL("* operand could be empty");
  394. *flagp = (WORST | SPSTART);
  395. if (op == '*' && (flags & SIMPLE))
  396. reginsert(STAR, ret);
  397. else if (op == '*') {
  398. /* Emit x* as (x&|), where & means "self". */
  399. reginsert(BRANCH, ret); /* Either x */
  400. regoptail(ret, regnode(BACK)); /* and loop */
  401. regoptail(ret, ret); /* back */
  402. regtail(ret, regnode(BRANCH)); /* or */
  403. regtail(ret, regnode(NOTHING)); /* null. */
  404. }
  405. regparse++;
  406. if (ISMULT(*regparse))
  407. FAIL("nested *");
  408. return (ret);
  409. }
  410. /*
  411. - regatom - the lowest level
  412. *
  413. * Optimization: gobbles an entire sequence of ordinary characters so that
  414. * it can turn them into a single node, which is smaller to store and
  415. * faster to run. Backslashed characters are exceptions, each becoming a
  416. * separate node; the code is simpler that way and it's not worth fixing.
  417. */
  418. static char *regatom(int *flagp) /* Xn */
  419. {
  420. register char *ret;
  421. int flags;
  422. *flagp = WORST; /* Tentatively. */
  423. switch (*regparse++) {
  424. case '^':
  425. ret = regnode(BOL);
  426. break;
  427. case '$':
  428. ret = regnode(EOL);
  429. break;
  430. case '.':
  431. ret = regnode(ANY);
  432. *flagp |= HASWIDTH | SIMPLE;
  433. break;
  434. case '[':{
  435. register int class;
  436. register int classend;
  437. if (*regparse == '^') { /* Complement of range. */
  438. ret = regnode(ANYBUT);
  439. regparse++;
  440. } else
  441. ret = regnode(ANYOF);
  442. if (*regparse == ']' || *regparse == '-')
  443. regc(*regparse++);
  444. while (*regparse != '\0' && *regparse != ']') {
  445. if (*regparse == '-') {
  446. regparse++;
  447. if (*regparse == ']' || *regparse == '\0')
  448. regc('-');
  449. else {
  450. class = UCHARAT(regparse - 2) + 1;
  451. classend = UCHARAT(regparse);
  452. if (class > classend + 1)
  453. FAIL("invalid [] range");
  454. for (; class <= classend; class++)
  455. regc((char)class);
  456. regparse++;
  457. }
  458. } else
  459. regc(*regparse++);
  460. }
  461. regc('\0');
  462. if (*regparse != ']')
  463. FAIL("unmatched []");
  464. regparse++;
  465. *flagp |= HASWIDTH | SIMPLE;
  466. }
  467. break;
  468. case '(':
  469. ret = reg(1, &flags);
  470. if (ret == (char *)NULL)
  471. return ((char *)NULL);
  472. *flagp |= flags & (HASWIDTH | SPSTART);
  473. break;
  474. case '\0':
  475. case '|':
  476. case ')':
  477. FAIL("internal urp"); /* Supposed to be caught earlier. */
  478. case '*':
  479. FAIL("* follows nothing");
  480. case '\\':
  481. if (*regparse == '\0')
  482. FAIL("trailing \\");
  483. ret = regnode(EXACTLY);
  484. regc(*regparse++);
  485. regc('\0');
  486. *flagp |= HASWIDTH | SIMPLE;
  487. break;
  488. default:{
  489. register uint len; /* Xn */
  490. register char ender;
  491. regparse--;
  492. len = strcspn(regparse, META);
  493. ender = *(regparse + len);
  494. if (len > 1 && ISMULT(ender))
  495. len--; /* Back off clear of * operand. */
  496. *flagp |= HASWIDTH;
  497. if (len == 1)
  498. *flagp |= SIMPLE;
  499. ret = regnode(EXACTLY);
  500. while (len > 0) {
  501. regc(*regparse++);
  502. len--;
  503. }
  504. regc('\0');
  505. }
  506. break;
  507. }
  508. return (ret);
  509. }
  510. /*
  511. - regnode - emit a node
  512. */
  513. static char *regnode(char op) /* Xn */
  514. {
  515. register char *ret;
  516. register char *ptr;
  517. ret = regcode;
  518. #ifdef DF_TRACE_DEBUG
  519. printf("DF_TRACE_DEBUG: static char *regnode() in regexp.c\n");
  520. #endif
  521. if (ret == &regdummy) {
  522. regsize += 3;
  523. return (ret);
  524. }
  525. ptr = ret;
  526. *ptr++ = op;
  527. *ptr++ = '\0'; /* Null "nxt" pointer. */
  528. *ptr++ = '\0';
  529. regcode = ptr;
  530. return (ret);
  531. }
  532. /*
  533. - regc - emit (if appropriate) a byte of code
  534. */
  535. static void regc(char b) /* Xn */
  536. {
  537. #ifdef DF_TRACE_DEBUG
  538. printf("DF_TRACE_DEBUG: static void regc() in regexp.c\n");
  539. #endif
  540. if (regcode != &regdummy)
  541. *regcode++ = b;
  542. else
  543. regsize++;
  544. }
  545. /*
  546. - reginsert - insert an operator in front of already-emitted operand
  547. *
  548. * Means relocating the operand.
  549. */
  550. static void reginsert(char op, char *opnd) /* Xn */
  551. {
  552. register char *src;
  553. register char *dst;
  554. register char *place;
  555. #ifdef DF_TRACE_DEBUG
  556. printf("DF_TRACE_DEBUG: static void reginsert() in regexp.c\n");
  557. #endif
  558. if (regcode == &regdummy) {
  559. regsize += 3;
  560. return;
  561. }
  562. src = regcode;
  563. regcode += 3;
  564. dst = regcode;
  565. while (src > opnd)
  566. *--dst = *--src;
  567. place = opnd; /* Op node, where operand used to be. */
  568. *place++ = op;
  569. *place++ = '\0';
  570. *place++ = '\0';
  571. }
  572. /*
  573. - regtail - set the next-pointer at the end of a node chain
  574. */
  575. static void regtail(char *p, char *val) /* Xn */
  576. {
  577. register char *scan;
  578. register char *temp;
  579. register int offset;
  580. if (p == &regdummy)
  581. return;
  582. /* Find last node. */
  583. scan = p;
  584. for (;;) {
  585. temp = regnext(scan);
  586. if (temp == (char *)NULL)
  587. break;
  588. scan = temp;
  589. }
  590. if (OP(scan) == BACK)
  591. offset = (int)(scan - val);
  592. else
  593. offset = (int)(val - scan);
  594. *(scan + 1) = (offset >> 8) & 0377;
  595. *(scan + 2) = offset & 0377;
  596. }
  597. /*
  598. - regoptail - regtail on operand of first argument; nop if operandless
  599. */
  600. static void regoptail(char *p, char *val) /* Xn */
  601. {
  602. /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  603. if (p == (char *)NULL || p == &regdummy || OP(p) != BRANCH)
  604. return;
  605. regtail(OPERAND(p), val);
  606. }
  607. /*
  608. * regexec and friends
  609. */
  610. /*
  611. * Global work variables for regexec().
  612. */
  613. static char *reginput; /* String-input pointer. */
  614. static char *regbol; /* Beginning of input, for ^ check. */
  615. static char **regstartp; /* Pointer to startp array. */
  616. static char **regendp; /* Ditto for endp. */
  617. /*
  618. * Forwards.
  619. */
  620. STATIC int regtry(regexp *, char *); /* Xn */
  621. STATIC int regmatch(char *); /* Xn */
  622. STATIC int regrepeat(char *); /* Xn */
  623. /* Xn */
  624. #ifdef DEBUG /* Xn */
  625. int regnarrate = 0; /* Xn */
  626. void regdump(regexp *); /* Xn */
  627. STATIC char *regprop(char *); /* Xn */
  628. #endif /* Xn */
  629. /*
  630. - regexec - match a regexp against a string
  631. */
  632. int regexec(register regexp *prog, register char *string) /* Xn */
  633. {
  634. register char *s;
  635. /* Be paranoid... */
  636. #ifdef DF_TRACE_DEBUG
  637. printf("DF_TRACE_DEBUG: int regexec() in regexp.c\n");
  638. #endif
  639. if (prog == (regexp *)NULL || string == (char *)NULL) {
  640. regerror("NULL parameter");
  641. return (0);
  642. }
  643. /* Check validity of program. */
  644. if (UCHARAT(prog->program) != MAGIC) {
  645. regerror("corrupted program");
  646. return (0);
  647. }
  648. /* If there is a "must appear" string, look for it. */
  649. if (prog->regmust != (char *)NULL) {
  650. s = string;
  651. while ((s = strchr(s, prog->regmust[0])) != (char *)NULL) {
  652. if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  653. break; /* Found it. */
  654. s++;
  655. }
  656. if (s == (char *)NULL) /* Not present. */
  657. return (0);
  658. }
  659. /* Mark beginning of line for ^ . */
  660. regbol = string;
  661. /* Simplest case: anchored match need be tried only once. */
  662. if (prog->reganch)
  663. return (regtry(prog, string));
  664. /* Messy cases: unanchored match. */
  665. s = string;
  666. if (prog->regstart != '\0')
  667. /* We know what char it must start with. */
  668. while ((s = strchr(s, prog->regstart)) != (char *)NULL) {
  669. if (regtry(prog, s))
  670. return (1);
  671. s++;
  672. } else
  673. /* We don't -- general case. */
  674. do {
  675. if (regtry(prog, s))
  676. return (1);
  677. } while (*s++ != '\0');
  678. /* Failure. */
  679. return (0);
  680. }
  681. /*
  682. - regtry - try match at specific point
  683. */
  684. static int regtry(regexp *prog, char *string)
  685. {
  686. register int i;
  687. register char **sp;
  688. register char **ep;
  689. reginput = string;
  690. regstartp = prog->startp;
  691. regendp = prog->endp;
  692. sp = prog->startp;
  693. ep = prog->endp;
  694. for (i = NSUBEXP; i > 0; i--) {
  695. *sp++ = (char *)NULL;
  696. *ep++ = (char *)NULL;
  697. }
  698. if (regmatch(prog->program + 1)) {
  699. prog->startp[0] = string;
  700. prog->endp[0] = reginput;
  701. return (1);
  702. } else
  703. return (0);
  704. }
  705. /*
  706. - regmatch - main matching routine
  707. *
  708. * Conceptually the strategy is simple: check to see whether the current
  709. * node matches, call self recursively to see whether the rest matches,
  710. * and then act accordingly. In practice we make some effort to avoid
  711. * recursion, in particular by going through "ordinary" nodes (that don't
  712. * need to know whether the rest of the match failed) by a loop instead of
  713. * by recursion.
  714. */
  715. static int regmatch(char *prog)
  716. {
  717. register char *scan; /* Current node. */
  718. char *nxt; /* nxt node. */
  719. scan = prog;
  720. #ifdef DEBUG
  721. #ifdef DF_TRACE_DEBUG
  722. printf("DF_TRACE_DEBUG: static int regmatch() in regexp.c\n");
  723. #endif
  724. if (scan != (char *)NULL && regnarrate)
  725. fprintf(stderr, "%s(\n", regprop(scan));
  726. #endif
  727. while (scan != (char *)NULL) {
  728. #ifdef DEBUG
  729. if (regnarrate)
  730. fprintf(stderr, "%s...\n", regprop(scan));
  731. #endif
  732. nxt = regnext(scan);
  733. switch (OP(scan)) {
  734. case BOL:
  735. if (reginput != regbol)
  736. return (0);
  737. break;
  738. case EOL:
  739. if (*reginput != '\0')
  740. return (0);
  741. break;
  742. case ANY:
  743. if (*reginput == '\0')
  744. return (0);
  745. reginput++;
  746. break;
  747. case EXACTLY:{
  748. register int len;
  749. register char *opnd;
  750. opnd = OPERAND(scan);
  751. /* Inline the first character, for speed. */
  752. if (*opnd != *reginput)
  753. return (0);
  754. len = strlen(opnd);
  755. if (len > 1 && strncmp(opnd, reginput, len) != 0)
  756. return (0);
  757. reginput += len;
  758. }
  759. break;
  760. case ANYOF:
  761. if (*reginput == '\0' ||
  762. strchr(OPERAND(scan), *reginput) == (char *)NULL)
  763. return (0);
  764. reginput++;
  765. break;
  766. case ANYBUT:
  767. if (*reginput == '\0' ||
  768. strchr(OPERAND(scan), *reginput) != (char *)NULL)
  769. return (0);
  770. reginput++;
  771. break;
  772. case NOTHING:
  773. break;
  774. case BACK:
  775. break;
  776. case OPEN + 1:
  777. case OPEN + 2:
  778. case OPEN + 3:
  779. case OPEN + 4:
  780. case OPEN + 5:
  781. case OPEN + 6:
  782. case OPEN + 7:
  783. case OPEN + 8:
  784. case OPEN + 9:{
  785. register int no;
  786. register char *save;
  787. no = OP(scan) - OPEN;
  788. save = reginput;
  789. if (regmatch(nxt)) {
  790. /*
  791. * Don't set startp if some later invocation of the same
  792. * parentheses already has.
  793. */
  794. if (regstartp[no] == (char *)NULL)
  795. regstartp[no] = save;
  796. return (1);
  797. } else
  798. return (0);
  799. }
  800. case CLOSE + 1:
  801. case CLOSE + 2:
  802. case CLOSE + 3:
  803. case CLOSE + 4:
  804. case CLOSE + 5:
  805. case CLOSE + 6:
  806. case CLOSE + 7:
  807. case CLOSE + 8:
  808. case CLOSE + 9:{
  809. register int no;
  810. register char *save;
  811. no = OP(scan) - CLOSE;
  812. save = reginput;
  813. if (regmatch(nxt)) {
  814. /*
  815. * Don't set endp if some later invocation of the same
  816. * parentheses already has.
  817. */
  818. if (regendp[no] == (char *)NULL)
  819. regendp[no] = save;
  820. return (1);
  821. } else
  822. return (0);
  823. }
  824. case BRANCH:{
  825. register char *save;
  826. if (OP(nxt) != BRANCH) /* No choice. */
  827. nxt = OPERAND(scan); /* Avoid recursion. */
  828. else {
  829. do {
  830. save = reginput;
  831. if (regmatch(OPERAND(scan)))
  832. return (1);
  833. reginput = save;
  834. scan = regnext(scan);
  835. } while (scan != (char *)NULL && OP(scan) == BRANCH);
  836. return (0);
  837. /* NOTREACHED */
  838. }
  839. break; /* Xn */
  840. } /* Xn */
  841. case STAR:{
  842. register char nextch;
  843. register int no;
  844. register char *save;
  845. register int minimum;
  846. /*
  847. * Lookahead to avoid useless match attempts when we know
  848. * what character comes next.
  849. */
  850. nextch = '\0';
  851. if (OP(nxt) == EXACTLY)
  852. nextch = *OPERAND(nxt);
  853. minimum = (OP(scan) == STAR) ? 0 : 1;
  854. save = reginput;
  855. no = regrepeat(OPERAND(scan));
  856. while (no >= minimum) {
  857. /* If it could work, try it. */
  858. if (nextch == '\0' || *reginput == nextch)
  859. if (regmatch(nxt))
  860. return (1);
  861. /* Couldn't or didn't -- back up. */
  862. no--;
  863. reginput = save + no;
  864. }
  865. return (0);
  866. }
  867. case END:
  868. return (1); /* Success! */
  869. default:
  870. regerror("memory corruption");
  871. return (0);
  872. }
  873. scan = nxt;
  874. }
  875. /*
  876. * We get here only if there's trouble -- normally "case END" is the
  877. * terminating point.
  878. */
  879. regerror("corrupted pointers");
  880. return (0);
  881. }
  882. /*
  883. - regrepeat - repeatedly match something simple, report how many
  884. */
  885. static int regrepeat(char *p)
  886. {
  887. register int count = 0;
  888. register char *scan;
  889. register char *opnd;
  890. scan = reginput;
  891. opnd = OPERAND(p);
  892. switch (OP(p)) {
  893. case ANY:
  894. count = strlen(scan);
  895. scan += count;
  896. break;
  897. case EXACTLY:
  898. while (*opnd == *scan) {
  899. count++;
  900. scan++;
  901. }
  902. break;
  903. case ANYOF:
  904. while (*scan != '\0' && strchr(opnd, *scan) != (char *)NULL) {
  905. count++;
  906. scan++;
  907. }
  908. break;
  909. case ANYBUT:
  910. while (*scan != '\0' && strchr(opnd, *scan) == (char *)NULL) {
  911. count++;
  912. scan++;
  913. }
  914. break;
  915. default: /* Oh dear. Called inappropriately. */
  916. regerror("internal foulup");
  917. count = 0; /* Best compromise. */
  918. break;
  919. }
  920. reginput = scan;
  921. return (count);
  922. }
  923. /*
  924. - regnext - dig the "nxt" pointer out of a node
  925. */
  926. static char *regnext(register char *p)
  927. {
  928. register int offset;
  929. if (p == &regdummy)
  930. return ((char *)NULL);
  931. offset = NEXT(p);
  932. if (offset == 0)
  933. return ((char *)NULL);
  934. if (OP(p) == BACK)
  935. return (p - offset);
  936. else
  937. return (p + offset);
  938. }
  939. #ifdef DEBUG
  940. #if 0 /* Xn */
  941. STATIC char *regprop();
  942. #endif /* Xn */
  943. /*
  944. - regdump - dump a regexp onto stdout in vaguely comprehensible form
  945. */
  946. void regdump(regexp *r)
  947. {
  948. register char *s;
  949. register char op = EXACTLY; /* Arbitrary non-END op. */
  950. register char *nxt;
  951. #if 0 /* Xn */
  952. extern char *strchr();
  953. #endif /* Xn */
  954. s = r->program + 1;
  955. while (op != END) { /* While that wasn't END last time... */
  956. op = OP(s);
  957. printf("%2d%s", s - r->program, regprop(s)); /* Where, what. */
  958. nxt = regnext(s);
  959. if (nxt == (char *)NULL) /* nxt ptr. */
  960. printf("(0)");
  961. else
  962. printf("(%d)", (s - r->program) + (nxt - s));
  963. s += 3;
  964. if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  965. /* Literal string, where present. */
  966. while (*s != '\0') {
  967. putchar(*s);
  968. s++;
  969. }
  970. s++;
  971. }
  972. putchar('\n');
  973. }
  974. /* Header fields of interest. */
  975. if (r->regstart != '\0')
  976. printf("start `%c' ", r->regstart);
  977. if (r->reganch)
  978. printf("anchored ");
  979. if (r->regmust != (char *)NULL)
  980. printf("must have \"%s\"", r->regmust);
  981. printf("\n");
  982. }
  983. /*
  984. - regprop - printable representation of opcode
  985. */
  986. static char *regprop(char *op)
  987. {
  988. register char *p;
  989. static char buf[50];
  990. strcpy(buf, ":");
  991. switch (OP(op)) {
  992. case BOL:
  993. p = "BOL";
  994. break;
  995. case EOL:
  996. p = "EOL";
  997. break;
  998. case ANY:
  999. p = "ANY";
  1000. break;
  1001. case ANYOF:
  1002. p = "ANYOF";
  1003. break;
  1004. case ANYBUT:
  1005. p = "ANYBUT";
  1006. break;
  1007. case BRANCH:
  1008. p = "BRANCH";
  1009. break;
  1010. case EXACTLY:
  1011. p = "EXACTLY";
  1012. break;
  1013. case NOTHING:
  1014. p = "NOTHING";
  1015. break;
  1016. case BACK:
  1017. p = "BACK";
  1018. break;
  1019. case END:
  1020. p = "END";
  1021. break;
  1022. case OPEN + 1:
  1023. case OPEN + 2:
  1024. case OPEN + 3:
  1025. case OPEN + 4:
  1026. case OPEN + 5:
  1027. case OPEN + 6:
  1028. case OPEN + 7:
  1029. case OPEN + 8:
  1030. case OPEN + 9:
  1031. sprintf(buf + strlen(buf), "OPEN%d", OP(op) - OPEN);
  1032. p = (char *)NULL;
  1033. break;
  1034. case CLOSE + 1:
  1035. case CLOSE + 2:
  1036. case CLOSE + 3:
  1037. case CLOSE + 4:
  1038. case CLOSE + 5:
  1039. case CLOSE + 6:
  1040. case CLOSE + 7:
  1041. case CLOSE + 8:
  1042. case CLOSE + 9:
  1043. sprintf(buf + strlen(buf), "CLOSE%d", OP(op) - CLOSE);
  1044. p = (char *)NULL;
  1045. break;
  1046. case STAR:
  1047. p = "STAR";
  1048. break;
  1049. default:
  1050. regerror("corrupted opcode");
  1051. break;
  1052. }
  1053. if (p != (char *)NULL)
  1054. strcat(buf, p);
  1055. return (buf);
  1056. }
  1057. #endif
  1058. /*
  1059. * The following is provided for those people who do not have strcspn() in
  1060. * their C libraries. They should get off their butts and do something
  1061. * about it; at least one public-domain implementation of those (highly
  1062. * useful) string routines has been published on Usenet.
  1063. */
  1064. #ifdef STRCSPN
  1065. /*
  1066. * strcspn - find length of initial segment of s1 consisting entirely
  1067. * of characters not from s2
  1068. */
  1069. static size_t strcspn(const char *s1, const char *s2) /* Xn */
  1070. {
  1071. #ifdef __STDC__ /* Xn */
  1072. register const char *scan1; /* Xn */
  1073. register const char *scan2; /* Xn */
  1074. register size_t count; /* Xn */
  1075. #else /* Xn */
  1076. register char *scan1;
  1077. register char *scan2;
  1078. register uint count; /* Xn */
  1079. #endif /* Xn */
  1080. count = 0;
  1081. for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1082. for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */
  1083. if (*scan1 == *scan2++)
  1084. return (count);
  1085. count++;
  1086. }
  1087. return (count);
  1088. }
  1089. #endif
  1090. /*
  1091. - regsub - perform substitutions after a regexp match
  1092. */
  1093. void regsub(regexp *prog, char *source, char *dest)
  1094. {
  1095. register char *src;
  1096. register char *dst;
  1097. register char c;
  1098. register int no;
  1099. register int len;
  1100. extern char *strncpy();
  1101. if (prog == (regexp *)NULL ||
  1102. source == (char *)NULL || dest == (char *)NULL) {
  1103. regerror("NULL parm to regsub");
  1104. return;
  1105. }
  1106. if (UCHARAT(prog->program) != MAGIC) {
  1107. regerror("damaged regexp fed to regsub");
  1108. return;
  1109. }
  1110. src = source;
  1111. dst = dest;
  1112. while ((c = *src++) != '\0') {
  1113. if (c == '&')
  1114. no = 0;
  1115. else if (c == '\\' && '0' <= *src && *src <= '9')
  1116. no = *src++ - '0';
  1117. else
  1118. no = -1;
  1119. if (no < 0) { /* Ordinary character. */
  1120. if (c == '\\' && (*src == '\\' || *src == '&'))
  1121. c = *src++;
  1122. *dst++ = c;
  1123. } else if (prog->startp[no] != (char *)NULL &&
  1124. prog->endp[no] != (char *)NULL) {
  1125. len = (int)(prog->endp[no] - prog->startp[no]);
  1126. strncpy(dst, prog->startp[no], len);
  1127. dst += len;
  1128. if (len != 0 && *(dst - 1) == '\0') { /* strncpy hit NUL. */
  1129. regerror("damaged match string");
  1130. return;
  1131. }
  1132. }
  1133. }
  1134. *dst++ = '\0';
  1135. }
  1136. void regerror(char *s)
  1137. {
  1138. fprintf(stderr, "regexp(3): %s", s);
  1139. exit(1);
  1140. }