PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/usr.bin/m4/gnum4.c

https://bitbucket.org/kmv/aeriebsd-src
C | 662 lines | 533 code | 66 blank | 63 comment | 148 complexity | c143a26d6d92e91b13673840b01c6357 MD5 | raw file
  1. /*
  2. * Copyright (c) 1999 Marc Espie
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  14. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  17. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. * SUCH DAMAGE.
  24. */
  25. /*
  26. * functions needed to support gnu-m4 extensions, including a fake freezing
  27. */
  28. #include <sys/param.h>
  29. #include <sys/types.h>
  30. #include <sys/wait.h>
  31. #include <ctype.h>
  32. #include <err.h>
  33. #include <paths.h>
  34. #include <regex.h>
  35. #include <stddef.h>
  36. #include <stdlib.h>
  37. #include <stdio.h>
  38. #include <string.h>
  39. #include <errno.h>
  40. #include <unistd.h>
  41. #include "mdef.h"
  42. #include "stdd.h"
  43. #include "extern.h"
  44. int mimic_gnu = 0;
  45. /*
  46. * Support for include path search
  47. * First search in the current directory.
  48. * If not found, and the path is not absolute, include path kicks in.
  49. * First, -I options, in the order found on the command line.
  50. * Then M4PATH env variable
  51. */
  52. struct path_entry {
  53. char *name;
  54. struct path_entry *next;
  55. } *first, *last;
  56. static struct path_entry *new_path_entry(const char *);
  57. static void ensure_m4path(void);
  58. static struct input_file *dopath(struct input_file *, const char *);
  59. static struct path_entry *
  60. new_path_entry(const char *dirname)
  61. {
  62. struct path_entry *n;
  63. n = malloc(sizeof(struct path_entry));
  64. if (!n)
  65. errx(1, "out of memory");
  66. n->name = strdup(dirname);
  67. if (!n->name)
  68. errx(1, "out of memory");
  69. n->next = 0;
  70. return n;
  71. }
  72. void
  73. addtoincludepath(const char *dirname)
  74. {
  75. struct path_entry *n;
  76. n = new_path_entry(dirname);
  77. if (last) {
  78. last->next = n;
  79. last = n;
  80. }
  81. else
  82. last = first = n;
  83. }
  84. static void
  85. ensure_m4path()
  86. {
  87. static int envpathdone = 0;
  88. char *envpath;
  89. char *sweep;
  90. char *path;
  91. if (envpathdone)
  92. return;
  93. envpathdone = TRUE;
  94. envpath = getenv("M4PATH");
  95. if (!envpath)
  96. return;
  97. /* for portability: getenv result is read-only */
  98. envpath = strdup(envpath);
  99. if (!envpath)
  100. errx(1, "out of memory");
  101. for (sweep = envpath;
  102. (path = strsep(&sweep, ":")) != NULL;)
  103. addtoincludepath(path);
  104. free(envpath);
  105. }
  106. static
  107. struct input_file *
  108. dopath(struct input_file *i, const char *filename)
  109. {
  110. char path[MAXPATHLEN];
  111. struct path_entry *pe;
  112. FILE *f;
  113. for (pe = first; pe; pe = pe->next) {
  114. snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
  115. if ((f = fopen(path, "r")) != 0) {
  116. set_input(i, f, path);
  117. return i;
  118. }
  119. }
  120. return NULL;
  121. }
  122. struct input_file *
  123. fopen_trypath(struct input_file *i, const char *filename)
  124. {
  125. FILE *f;
  126. f = fopen(filename, "r");
  127. if (f != NULL) {
  128. set_input(i, f, filename);
  129. return i;
  130. }
  131. if (filename[0] == '/')
  132. return NULL;
  133. ensure_m4path();
  134. return dopath(i, filename);
  135. }
  136. void
  137. doindir(const char *argv[], int argc)
  138. {
  139. ndptr n;
  140. struct macro_definition *p;
  141. n = lookup(argv[2]);
  142. if (n == NULL || (p = macro_getdef(n)) == NULL)
  143. m4errx(1, "indir: undefined macro %s.", argv[2]);
  144. argv[1] = p->defn;
  145. eval(argv+1, argc-1, p->type, is_traced(n));
  146. }
  147. void
  148. dobuiltin(const char *argv[], int argc)
  149. {
  150. ndptr p;
  151. argv[1] = NULL;
  152. p = macro_getbuiltin(argv[2]);
  153. if (p != NULL)
  154. eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
  155. else
  156. m4errx(1, "unknown builtin %s.", argv[2]);
  157. }
  158. /* We need some temporary buffer space, as pb pushes BACK and substitution
  159. * proceeds forward... */
  160. static char *buffer;
  161. static size_t bufsize = 0;
  162. static size_t current = 0;
  163. static void addchars(const char *, size_t);
  164. static void addchar(int);
  165. static char *twiddle(const char *);
  166. static char *getstring(void);
  167. static void exit_regerror(int, regex_t *);
  168. static void do_subst(const char *, regex_t *, const char *, regmatch_t *);
  169. static void do_regexpindex(const char *, regex_t *, regmatch_t *);
  170. static void do_regexp(const char *, regex_t *, const char *, regmatch_t *);
  171. static void add_sub(int, const char *, regex_t *, regmatch_t *);
  172. static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
  173. #define addconstantstring(s) addchars((s), sizeof(s)-1)
  174. static void
  175. addchars(const char *c, size_t n)
  176. {
  177. if (n == 0)
  178. return;
  179. while (current + n > bufsize) {
  180. if (bufsize == 0)
  181. bufsize = 1024;
  182. else
  183. bufsize *= 2;
  184. buffer = xrealloc(buffer, bufsize, NULL);
  185. }
  186. memcpy(buffer+current, c, n);
  187. current += n;
  188. }
  189. static void
  190. addchar(int c)
  191. {
  192. if (current +1 > bufsize) {
  193. if (bufsize == 0)
  194. bufsize = 1024;
  195. else
  196. bufsize *= 2;
  197. buffer = xrealloc(buffer, bufsize, NULL);
  198. }
  199. buffer[current++] = c;
  200. }
  201. static char *
  202. getstring()
  203. {
  204. addchar('\0');
  205. current = 0;
  206. return buffer;
  207. }
  208. static void
  209. exit_regerror(int er, regex_t *re)
  210. {
  211. size_t errlen;
  212. char *errbuf;
  213. errlen = regerror(er, re, NULL, 0);
  214. errbuf = xalloc(errlen,
  215. "malloc in regerror: %lu", (unsigned long)errlen);
  216. regerror(er, re, errbuf, errlen);
  217. m4errx(1, "regular expression error: %s.", errbuf);
  218. }
  219. static void
  220. add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
  221. {
  222. if (n > re->re_nsub)
  223. warnx("No subexpression %d", n);
  224. /* Subexpressions that did not match are
  225. * not an error. */
  226. else if (pm[n].rm_so != -1 &&
  227. pm[n].rm_eo != -1) {
  228. addchars(string + pm[n].rm_so,
  229. pm[n].rm_eo - pm[n].rm_so);
  230. }
  231. }
  232. /* Add replacement string to the output buffer, recognizing special
  233. * constructs and replacing them with substrings of the original string.
  234. */
  235. static void
  236. add_replace(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
  237. {
  238. const char *p;
  239. for (p = replace; *p != '\0'; p++) {
  240. if (*p == '&' && !mimic_gnu) {
  241. add_sub(0, string, re, pm);
  242. continue;
  243. }
  244. if (*p == '\\') {
  245. if (p[1] == '\\') {
  246. addchar(p[1]);
  247. p++;
  248. continue;
  249. }
  250. if (p[1] == '&') {
  251. if (mimic_gnu)
  252. add_sub(0, string, re, pm);
  253. else
  254. addchar(p[1]);
  255. p++;
  256. continue;
  257. }
  258. if (isdigit(p[1])) {
  259. add_sub(*(++p) - '0', string, re, pm);
  260. continue;
  261. }
  262. }
  263. addchar(*p);
  264. }
  265. }
  266. static void
  267. do_subst(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
  268. {
  269. int error;
  270. int flags = 0;
  271. const char *last_match = NULL;
  272. while ((error = regexec(re, string, re->re_nsub+1, pm, flags)) == 0) {
  273. if (pm[0].rm_eo != 0) {
  274. if (string[pm[0].rm_eo-1] == '\n')
  275. flags = 0;
  276. else
  277. flags = REG_NOTBOL;
  278. }
  279. /* NULL length matches are special... We use the `vi-mode'
  280. * rule: don't allow a NULL-match at the last match
  281. * position.
  282. */
  283. if (pm[0].rm_so == pm[0].rm_eo &&
  284. string + pm[0].rm_so == last_match) {
  285. if (*string == '\0')
  286. return;
  287. addchar(*string);
  288. if (*string++ == '\n')
  289. flags = 0;
  290. else
  291. flags = REG_NOTBOL;
  292. continue;
  293. }
  294. last_match = string + pm[0].rm_so;
  295. addchars(string, pm[0].rm_so);
  296. add_replace(string, re, replace, pm);
  297. string += pm[0].rm_eo;
  298. }
  299. if (error != REG_NOMATCH)
  300. exit_regerror(error, re);
  301. pbstr(string);
  302. }
  303. static void
  304. do_regexp(const char *string, regex_t *re, const char *replace, regmatch_t *pm)
  305. {
  306. int error;
  307. switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
  308. case 0:
  309. add_replace(string, re, replace, pm);
  310. pbstr(getstring());
  311. break;
  312. case REG_NOMATCH:
  313. break;
  314. default:
  315. exit_regerror(error, re);
  316. }
  317. }
  318. static void
  319. do_regexpindex(const char *string, regex_t *re, regmatch_t *pm)
  320. {
  321. int error;
  322. switch(error = regexec(re, string, re->re_nsub+1, pm, 0)) {
  323. case 0:
  324. pbunsigned(pm[0].rm_so);
  325. break;
  326. case REG_NOMATCH:
  327. pbnum(-1);
  328. break;
  329. default:
  330. exit_regerror(error, re);
  331. }
  332. }
  333. /* In Gnu m4 mode, parentheses for backmatch don't work like POSIX 1003.2
  334. * says. So we twiddle with the regexp before passing it to regcomp.
  335. */
  336. static char *
  337. twiddle(const char *p)
  338. {
  339. /* + at start of regexp is a normal character for Gnu m4 */
  340. if (*p == '^') {
  341. addchar(*p);
  342. p++;
  343. }
  344. if (*p == '+') {
  345. addchar('\\');
  346. }
  347. /* This could use strcspn for speed... */
  348. while (*p != '\0') {
  349. if (*p == '\\') {
  350. switch(p[1]) {
  351. case '(':
  352. case ')':
  353. case '|':
  354. addchar(p[1]);
  355. break;
  356. case 'w':
  357. addconstantstring("[_a-zA-Z0-9]");
  358. break;
  359. case 'W':
  360. addconstantstring("[^_a-zA-Z0-9]");
  361. break;
  362. case '<':
  363. addconstantstring("[[:<:]]");
  364. break;
  365. case '>':
  366. addconstantstring("[[:>:]]");
  367. break;
  368. default:
  369. addchars(p, 2);
  370. break;
  371. }
  372. p+=2;
  373. continue;
  374. }
  375. if (*p == '(' || *p == ')' || *p == '|')
  376. addchar('\\');
  377. addchar(*p);
  378. p++;
  379. }
  380. return getstring();
  381. }
  382. /* patsubst(string, regexp, opt replacement) */
  383. /* argv[2]: string
  384. * argv[3]: regexp
  385. * argv[4]: opt rep
  386. */
  387. void
  388. dopatsubst(const char *argv[], int argc)
  389. {
  390. if (argc <= 3) {
  391. warnx("Too few arguments to patsubst");
  392. return;
  393. }
  394. /* special case: empty regexp */
  395. if (argv[3][0] == '\0') {
  396. const char *s;
  397. size_t len;
  398. if (argc > 4 && argv[4])
  399. len = strlen(argv[4]);
  400. else
  401. len = 0;
  402. for (s = argv[2]; *s != '\0'; s++) {
  403. addchars(argv[4], len);
  404. addchar(*s);
  405. }
  406. } else {
  407. int error;
  408. regex_t re;
  409. regmatch_t *pmatch;
  410. int mode = REG_EXTENDED;
  411. size_t l = strlen(argv[3]);
  412. if (!mimic_gnu ||
  413. (argv[3][0] == '^') ||
  414. (l > 0 && argv[3][l-1] == '$'))
  415. mode |= REG_NEWLINE;
  416. error = regcomp(&re, mimic_gnu ? twiddle(argv[3]) : argv[3],
  417. mode);
  418. if (error != 0)
  419. exit_regerror(error, &re);
  420. pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1), NULL);
  421. do_subst(argv[2], &re,
  422. argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
  423. free(pmatch);
  424. regfree(&re);
  425. }
  426. pbstr(getstring());
  427. }
  428. void
  429. doregexp(const char *argv[], int argc)
  430. {
  431. int error;
  432. regex_t re;
  433. regmatch_t *pmatch;
  434. if (argc <= 3) {
  435. warnx("Too few arguments to regexp");
  436. return;
  437. }
  438. /* special gnu case */
  439. if (argv[3][0] == '\0' && mimic_gnu) {
  440. if (argc == 4 || argv[4] == NULL)
  441. return;
  442. else
  443. pbstr(argv[4]);
  444. }
  445. error = regcomp(&re, mimic_gnu ? twiddle(argv[3]) : argv[3],
  446. REG_EXTENDED);
  447. if (error != 0)
  448. exit_regerror(error, &re);
  449. pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1), NULL);
  450. if (argc == 4 || argv[4] == NULL)
  451. do_regexpindex(argv[2], &re, pmatch);
  452. else
  453. do_regexp(argv[2], &re, argv[4], pmatch);
  454. free(pmatch);
  455. regfree(&re);
  456. }
  457. void
  458. doformat(const char *argv[], int argc)
  459. {
  460. const char *format = argv[2];
  461. int pos = 3;
  462. int left_padded;
  463. long width;
  464. size_t l;
  465. const char *thisarg;
  466. char temp[2];
  467. long extra;
  468. while (*format != 0) {
  469. if (*format != '%') {
  470. addchar(*format++);
  471. continue;
  472. }
  473. format++;
  474. if (*format == '%') {
  475. addchar(*format++);
  476. continue;
  477. }
  478. if (*format == 0) {
  479. addchar('%');
  480. break;
  481. }
  482. if (*format == '*') {
  483. format++;
  484. if (pos >= argc)
  485. m4errx(1,
  486. "Format with too many format specifiers.");
  487. width = strtol(argv[pos++], NULL, 10);
  488. } else {
  489. width = strtol(format, (char **)&format, 10);
  490. }
  491. if (width < 0) {
  492. left_padded = 1;
  493. width = -width;
  494. } else {
  495. left_padded = 0;
  496. }
  497. if (*format == '.') {
  498. format++;
  499. if (*format == '*') {
  500. format++;
  501. if (pos >= argc)
  502. m4errx(1,
  503. "Format with too many format specifiers.");
  504. extra = strtol(argv[pos++], NULL, 10);
  505. } else {
  506. extra = strtol(format, (char **)&format, 10);
  507. }
  508. } else {
  509. extra = LONG_MAX;
  510. }
  511. if (pos >= argc)
  512. m4errx(1, "Format with too many format specifiers.");
  513. switch(*format) {
  514. case 's':
  515. thisarg = argv[pos++];
  516. break;
  517. case 'c':
  518. temp[0] = strtoul(argv[pos++], NULL, 10);
  519. temp[1] = 0;
  520. thisarg = temp;
  521. break;
  522. default:
  523. m4errx(1, "Unsupported format specification: %s.",
  524. argv[2]);
  525. }
  526. format++;
  527. l = strlen(thisarg);
  528. if (l > extra)
  529. l = extra;
  530. if (!left_padded) {
  531. while (l < width--)
  532. addchar(' ');
  533. }
  534. addchars(thisarg, l);
  535. if (left_padded) {
  536. while (l < width--)
  537. addchar(' ');
  538. }
  539. }
  540. pbstr(getstring());
  541. }
  542. void
  543. doesyscmd(const char *cmd)
  544. {
  545. int p[2];
  546. pid_t pid, cpid;
  547. char *argv[4];
  548. int cc;
  549. int status;
  550. /* Follow gnu m4 documentation: first flush buffers. */
  551. fflush(NULL);
  552. argv[0] = "sh";
  553. argv[1] = "-c";
  554. argv[2] = (char *)cmd;
  555. argv[3] = NULL;
  556. /* Just set up standard output, share stderr and stdin with m4 */
  557. if (pipe(p) == -1)
  558. err(1, "bad pipe");
  559. switch(cpid = fork()) {
  560. case -1:
  561. err(1, "bad fork");
  562. /* NOTREACHED */
  563. case 0:
  564. (void) close(p[0]);
  565. (void) dup2(p[1], 1);
  566. (void) close(p[1]);
  567. execv(_PATH_BSHELL, argv);
  568. exit(1);
  569. default:
  570. /* Read result in two stages, since m4's buffer is
  571. * pushback-only. */
  572. (void) close(p[1]);
  573. do {
  574. char result[BUFSIZE];
  575. cc = read(p[0], result, sizeof result);
  576. if (cc > 0)
  577. addchars(result, cc);
  578. } while (cc > 0 || (cc == -1 && errno == EINTR));
  579. (void) close(p[0]);
  580. while ((pid = wait(&status)) != cpid && pid >= 0)
  581. continue;
  582. pbstr(getstring());
  583. }
  584. }
  585. void
  586. getdivfile(const char *name)
  587. {
  588. FILE *f;
  589. int c;
  590. f = fopen(name, "r");
  591. if (!f)
  592. return;
  593. while ((c = getc(f))!= EOF)
  594. putc(c, active);
  595. (void) fclose(f);
  596. }