PageRenderTime 28ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/freebsd/usr.bin/m4/gnum4.c

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