PageRenderTime 65ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/usr.bin/make/var.c

https://bitbucket.org/evzijst/freebsd
C | 2603 lines | 1532 code | 287 blank | 784 comment | 478 complexity | d93940ca441bd5eff0ec6f14291d1711 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, AGPL-1.0, LGPL-2.1, GPL-2.0, BSD-2-Clause, 0BSD, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. /*-
  2. * Copyright (c) 2002 Juli Mallett.
  3. * Copyright (c) 1988, 1989, 1990, 1993
  4. * The Regents of the University of California. All rights reserved.
  5. * Copyright (c) 1989 by Berkeley Softworks
  6. * All rights reserved.
  7. *
  8. * This code is derived from software contributed to Berkeley by
  9. * Adam de Boor.
  10. *
  11. * Redistribution and use in source and binary forms, with or without
  12. * modification, are permitted provided that the following conditions
  13. * are met:
  14. * 1. Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * 3. All advertising materials mentioning features or use of this software
  20. * must display the following acknowledgement:
  21. * This product includes software developed by the University of
  22. * California, Berkeley and its contributors.
  23. * 4. Neither the name of the University nor the names of its contributors
  24. * may be used to endorse or promote products derived from this software
  25. * without specific prior written permission.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  28. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  29. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  30. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  31. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  32. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  33. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  34. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  35. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  36. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  37. * SUCH DAMAGE.
  38. *
  39. * @(#)var.c 8.3 (Berkeley) 3/19/94
  40. */
  41. #include <sys/cdefs.h>
  42. __FBSDID("$FreeBSD$");
  43. /**
  44. * var.c --
  45. * Variable-handling functions
  46. *
  47. * Interface:
  48. * Var_Set Set the value of a variable in the given
  49. * context. The variable is created if it doesn't
  50. * yet exist. The value and variable name need not
  51. * be preserved.
  52. *
  53. * Var_Append Append more characters to an existing variable
  54. * in the given context. The variable needn't
  55. * exist already -- it will be created if it doesn't.
  56. * A space is placed between the old value and the
  57. * new one.
  58. *
  59. * Var_Exists See if a variable exists.
  60. *
  61. * Var_Value Return the value of a variable in a context or
  62. * NULL if the variable is undefined.
  63. *
  64. * Var_Subst Substitute named variable, or all variables if
  65. * NULL in a string using
  66. * the given context as the top-most one. If the
  67. * third argument is non-zero, Parse_Error is
  68. * called if any variables are undefined.
  69. *
  70. * Var_Parse Parse a variable expansion from a string and
  71. * return the result and the number of characters
  72. * consumed.
  73. *
  74. * Var_Delete Delete a variable in a context.
  75. *
  76. * Var_Init Initialize this module.
  77. *
  78. * Debugging:
  79. * Var_Dump Print out all variables defined in the given
  80. * context.
  81. *
  82. * XXX: There's a lot of duplication in these functions.
  83. */
  84. #include <ctype.h>
  85. #include <stdlib.h>
  86. #include <string.h>
  87. #include <sys/types.h>
  88. #include <regex.h>
  89. #include "buf.h"
  90. #include "config.h"
  91. #include "globals.h"
  92. #include "GNode.h"
  93. #include "job.h"
  94. #include "lst.h"
  95. #include "parse.h"
  96. #include "str.h"
  97. #include "targ.h"
  98. #include "util.h"
  99. #include "var.h"
  100. /**
  101. *
  102. */
  103. typedef struct VarParser {
  104. const char *const input; /* pointer to input string */
  105. const char *ptr; /* current parser pos in input str */
  106. GNode *ctxt;
  107. Boolean err;
  108. Boolean execute;
  109. } VarParser;
  110. typedef struct Var {
  111. char *name; /* the variable's name */
  112. struct Buffer *val; /* its value */
  113. int flags; /* miscellaneous status flags */
  114. #define VAR_IN_USE 1 /* Variable's value currently being used.
  115. * Used to avoid recursion */
  116. #define VAR_JUNK 4 /* Variable is a junk variable that
  117. * should be destroyed when done with
  118. * it. Used by Var_Parse for undefined,
  119. * modified variables */
  120. #define VAR_TO_ENV 8 /* Place variable in environment */
  121. } Var;
  122. typedef struct {
  123. struct Buffer *lhs; /* String to match */
  124. struct Buffer *rhs; /* Replacement string (w/ &'s removed) */
  125. regex_t re;
  126. int nsub;
  127. regmatch_t *matches;
  128. int flags;
  129. #define VAR_SUB_GLOBAL 0x01 /* Apply substitution globally */
  130. #define VAR_SUB_ONE 0x02 /* Apply substitution to one word */
  131. #define VAR_SUB_MATCHED 0x04 /* There was a match */
  132. #define VAR_MATCH_START 0x08 /* Match at start of word */
  133. #define VAR_MATCH_END 0x10 /* Match at end of word */
  134. } VarPattern;
  135. typedef Boolean VarModifyProc(const char *, Boolean, struct Buffer *, void *);
  136. static char *VarParse(VarParser *, Boolean *);
  137. /*
  138. * This is a harmless return value for Var_Parse that can be used by Var_Subst
  139. * to determine if there was an error in parsing -- easier than returning
  140. * a flag, as things outside this module don't give a hoot.
  141. */
  142. char var_Error[] = "";
  143. /*
  144. * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
  145. * set false. Why not just use a constant? Well, gcc likes to condense
  146. * identical string instances...
  147. */
  148. static char varNoError[] = "";
  149. /*
  150. * Internally, variables are contained in four different contexts.
  151. * 1) the environment. They may not be changed. If an environment
  152. * variable is appended-to, the result is placed in the global
  153. * context.
  154. * 2) the global context. Variables set in the Makefile are located in
  155. * the global context. It is the penultimate context searched when
  156. * substituting.
  157. * 3) the command-line context. All variables set on the command line
  158. * are placed in this context. They are UNALTERABLE once placed here.
  159. * 4) the local context. Each target has associated with it a context
  160. * list. On this list are located the structures describing such
  161. * local variables as $(@) and $(*)
  162. * The four contexts are searched in the reverse order from which they are
  163. * listed.
  164. */
  165. static GNode *VAR_ENV; /* variables from the environment */
  166. GNode *VAR_GLOBAL; /* variables from the makefile */
  167. GNode *VAR_CMD; /* variables defined on the command-line */
  168. Boolean oldVars; /* variable substitution style */
  169. Boolean checkEnvFirst; /* -e flag */
  170. #define OPEN_PAREN '('
  171. #define CLOSE_PAREN ')'
  172. #define OPEN_BRACE '{'
  173. #define CLOSE_BRACE '}'
  174. /**
  175. * Create a Var object.
  176. *
  177. * Params:
  178. * name Name of variable (copied).
  179. * value Value of variable (copied) or NULL.
  180. * flags Flags set on variable.
  181. *
  182. * Returns:
  183. * New variable.
  184. */
  185. static Var *
  186. VarCreate(const char name[], const char value[], int flags)
  187. {
  188. Var *v;
  189. v = emalloc(sizeof(Var));
  190. v->name = estrdup(name);
  191. v->val = Buf_Init(0);
  192. v->flags = flags;
  193. if (value != NULL) {
  194. Buf_Append(v->val, value);
  195. }
  196. return (v);
  197. }
  198. /**
  199. * Destroy a Var object.
  200. *
  201. * Params:
  202. * v Object to destroy.
  203. * f True if internal buffer in Buffer object is to be removed.
  204. */
  205. static void
  206. VarDestroy(Var *v, Boolean f)
  207. {
  208. Buf_Destroy(v->val, f);
  209. free(v->name);
  210. free(v);
  211. }
  212. /**
  213. * Remove the tail of the given word and place the result in the given
  214. * buffer.
  215. *
  216. * Results:
  217. * TRUE if characters were added to the buffer (a space needs to be
  218. * added to the buffer before the next word).
  219. *
  220. * Side Effects:
  221. * The trimmed word is added to the buffer.
  222. */
  223. static Boolean
  224. VarHead(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
  225. {
  226. char *slash;
  227. slash = strrchr(word, '/');
  228. if (slash != NULL) {
  229. if (addSpace) {
  230. Buf_AddByte(buf, (Byte)' ');
  231. }
  232. Buf_AppendRange(buf, word, slash);
  233. } else {
  234. /*
  235. * If no directory part, give . (q.v. the POSIX standard)
  236. */
  237. if (addSpace) {
  238. Buf_Append(buf, " .");
  239. } else {
  240. Buf_AddByte(buf, (Byte)'.');
  241. }
  242. }
  243. return (TRUE);
  244. }
  245. /**
  246. * Remove the head of the given word and place the result in the given
  247. * buffer.
  248. *
  249. * Results:
  250. * TRUE if characters were added to the buffer (a space needs to be
  251. * added to the buffer before the next word).
  252. *
  253. * Side Effects:
  254. * The trimmed word is added to the buffer.
  255. */
  256. static Boolean
  257. VarTail(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
  258. {
  259. const char *slash;
  260. if (addSpace) {
  261. Buf_AddByte (buf, (Byte)' ');
  262. }
  263. slash = strrchr(word, '/');
  264. if (slash != NULL) {
  265. slash++;
  266. Buf_Append(buf, slash);
  267. } else {
  268. Buf_Append(buf, word);
  269. }
  270. return (TRUE);
  271. }
  272. /**
  273. * Place the suffix of the given word in the given buffer.
  274. *
  275. * Results:
  276. * TRUE if characters were added to the buffer (a space needs to be
  277. * added to the buffer before the next word).
  278. *
  279. * Side Effects:
  280. * The suffix from the word is placed in the buffer.
  281. */
  282. static Boolean
  283. VarSuffix(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
  284. {
  285. const char *dot;
  286. dot = strrchr(word, '.');
  287. if (dot != NULL) {
  288. if (addSpace) {
  289. Buf_AddByte(buf, (Byte)' ');
  290. }
  291. dot++;
  292. Buf_Append(buf, dot);
  293. addSpace = TRUE;
  294. }
  295. return (addSpace);
  296. }
  297. /**
  298. * Remove the suffix of the given word and place the result in the
  299. * buffer.
  300. *
  301. * Results:
  302. * TRUE if characters were added to the buffer (a space needs to be
  303. * added to the buffer before the next word).
  304. *
  305. * Side Effects:
  306. * The trimmed word is added to the buffer.
  307. */
  308. static Boolean
  309. VarRoot(const char *word, Boolean addSpace, Buffer *buf, void *dummy __unused)
  310. {
  311. char *dot;
  312. if (addSpace) {
  313. Buf_AddByte(buf, (Byte)' ');
  314. }
  315. dot = strrchr(word, '.');
  316. if (dot != NULL) {
  317. Buf_AppendRange(buf, word, dot);
  318. } else {
  319. Buf_Append(buf, word);
  320. }
  321. return (TRUE);
  322. }
  323. /**
  324. * Place the word in the buffer if it matches the given pattern.
  325. * Callback function for VarModify to implement the :M modifier.
  326. * A space will be added if requested. A pattern is supplied
  327. * which the word must match.
  328. *
  329. * Results:
  330. * TRUE if a space should be placed in the buffer before the next
  331. * word.
  332. *
  333. * Side Effects:
  334. * The word may be copied to the buffer.
  335. */
  336. static Boolean
  337. VarMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
  338. {
  339. if (Str_Match(word, pattern)) {
  340. if (addSpace) {
  341. Buf_AddByte(buf, (Byte)' ');
  342. }
  343. addSpace = TRUE;
  344. Buf_Append(buf, word);
  345. }
  346. return (addSpace);
  347. }
  348. #ifdef SYSVVARSUB
  349. /**
  350. * Place the word in the buffer if it matches the given pattern.
  351. * Callback function for VarModify to implement the System V %
  352. * modifiers. A space is added if requested.
  353. *
  354. * Results:
  355. * TRUE if a space should be placed in the buffer before the next
  356. * word.
  357. *
  358. * Side Effects:
  359. * The word may be copied to the buffer.
  360. */
  361. static Boolean
  362. VarSYSVMatch(const char *word, Boolean addSpace, Buffer *buf, void *patp)
  363. {
  364. int len;
  365. const char *ptr;
  366. VarPattern *pat = (VarPattern *)patp;
  367. if (addSpace)
  368. Buf_AddByte(buf, (Byte)' ');
  369. addSpace = TRUE;
  370. if ((ptr = Str_SYSVMatch(word, Buf_Data(pat->lhs), &len)) != NULL)
  371. Str_SYSVSubst(buf, Buf_Data(pat->rhs), ptr, len);
  372. else
  373. Buf_Append(buf, word);
  374. return (addSpace);
  375. }
  376. #endif
  377. /**
  378. * Place the word in the buffer if it doesn't match the given pattern.
  379. * Callback function for VarModify to implement the :N modifier. A
  380. * space is added if requested.
  381. *
  382. * Results:
  383. * TRUE if a space should be placed in the buffer before the next
  384. * word.
  385. *
  386. * Side Effects:
  387. * The word may be copied to the buffer.
  388. */
  389. static Boolean
  390. VarNoMatch(const char *word, Boolean addSpace, Buffer *buf, void *pattern)
  391. {
  392. if (!Str_Match(word, pattern)) {
  393. if (addSpace) {
  394. Buf_AddByte(buf, (Byte)' ');
  395. }
  396. addSpace = TRUE;
  397. Buf_Append(buf, word);
  398. }
  399. return (addSpace);
  400. }
  401. /**
  402. * Perform a string-substitution on the given word, placing the
  403. * result in the passed buffer. A space is added if requested.
  404. *
  405. * Results:
  406. * TRUE if a space is needed before more characters are added.
  407. */
  408. static Boolean
  409. VarSubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
  410. {
  411. size_t wordLen; /* Length of word */
  412. const char *cp; /* General pointer */
  413. VarPattern *pattern = patternp;
  414. wordLen = strlen(word);
  415. if (1) { /* substitute in each word of the variable */
  416. /*
  417. * Break substitution down into simple anchored cases
  418. * and if none of them fits, perform the general substitution
  419. * case.
  420. */
  421. if ((pattern->flags & VAR_MATCH_START) &&
  422. (strncmp(word, Buf_Data(pattern->lhs),
  423. Buf_Size(pattern->lhs)) == 0)) {
  424. /*
  425. * Anchored at start and beginning of word matches
  426. * pattern.
  427. */
  428. if ((pattern->flags & VAR_MATCH_END) &&
  429. (wordLen == Buf_Size(pattern->lhs))) {
  430. /*
  431. * Also anchored at end and matches to the end
  432. * (word is same length as pattern) add space
  433. * and rhs only if rhs is non-null.
  434. */
  435. if (Buf_Size(pattern->rhs) != 0) {
  436. if (addSpace) {
  437. Buf_AddByte(buf, (Byte)' ');
  438. }
  439. addSpace = TRUE;
  440. Buf_AppendBuf(buf, pattern->rhs);
  441. }
  442. } else if (pattern->flags & VAR_MATCH_END) {
  443. /*
  444. * Doesn't match to end -- copy word wholesale
  445. */
  446. goto nosub;
  447. } else {
  448. /*
  449. * Matches at start but need to copy in
  450. * trailing characters.
  451. */
  452. if ((Buf_Size(pattern->rhs) + wordLen -
  453. Buf_Size(pattern->lhs)) != 0) {
  454. if (addSpace) {
  455. Buf_AddByte(buf, (Byte)' ');
  456. }
  457. addSpace = TRUE;
  458. }
  459. Buf_AppendBuf(buf, pattern->rhs);
  460. Buf_AddBytes(buf, wordLen -
  461. Buf_Size(pattern->lhs),
  462. (word + Buf_Size(pattern->lhs)));
  463. }
  464. } else if (pattern->flags & VAR_MATCH_START) {
  465. /*
  466. * Had to match at start of word and didn't -- copy
  467. * whole word.
  468. */
  469. goto nosub;
  470. } else if (pattern->flags & VAR_MATCH_END) {
  471. /*
  472. * Anchored at end, Find only place match could occur
  473. * (leftLen characters from the end of the word) and
  474. * see if it does. Note that because the $ will be
  475. * left at the end of the lhs, we have to use strncmp.
  476. */
  477. cp = word + (wordLen - Buf_Size(pattern->lhs));
  478. if ((cp >= word) && (strncmp(cp, Buf_Data(pattern->lhs),
  479. Buf_Size(pattern->lhs)) == 0)) {
  480. /*
  481. * Match found. If we will place characters in
  482. * the buffer, add a space before hand as
  483. * indicated by addSpace, then stuff in the
  484. * initial, unmatched part of the word followed
  485. * by the right-hand-side.
  486. */
  487. if ((cp - word) + Buf_Size(pattern->rhs) != 0) {
  488. if (addSpace) {
  489. Buf_AddByte(buf, (Byte)' ');
  490. }
  491. addSpace = TRUE;
  492. }
  493. Buf_AppendRange(buf, word, cp);
  494. Buf_AppendBuf(buf, pattern->rhs);
  495. } else {
  496. /*
  497. * Had to match at end and didn't. Copy entire
  498. * word.
  499. */
  500. goto nosub;
  501. }
  502. } else {
  503. /*
  504. * Pattern is unanchored: search for the pattern in the
  505. * word using strstr(3), copying unmatched portions and
  506. * the right-hand-side for each match found, handling
  507. * non-global substitutions correctly, etc. When the
  508. * loop is done, any remaining part of the word (word
  509. * and wordLen are adjusted accordingly through the
  510. * loop) is copied straight into the buffer.
  511. * addSpace is set FALSE as soon as a space is added
  512. * to the buffer.
  513. */
  514. Boolean done;
  515. size_t origSize;
  516. done = FALSE;
  517. origSize = Buf_Size(buf);
  518. while (!done) {
  519. cp = strstr(word, Buf_Data(pattern->lhs));
  520. if (cp != NULL) {
  521. if (addSpace && (((cp - word) +
  522. Buf_Size(pattern->rhs)) != 0)) {
  523. Buf_AddByte(buf, (Byte)' ');
  524. addSpace = FALSE;
  525. }
  526. Buf_AppendRange(buf, word, cp);
  527. Buf_AppendBuf(buf, pattern->rhs);
  528. wordLen -= (cp - word) +
  529. Buf_Size(pattern->lhs);
  530. word = cp + Buf_Size(pattern->lhs);
  531. if (wordLen == 0 || (pattern->flags &
  532. VAR_SUB_GLOBAL) == 0) {
  533. done = TRUE;
  534. }
  535. } else {
  536. done = TRUE;
  537. }
  538. }
  539. if (wordLen != 0) {
  540. if (addSpace) {
  541. Buf_AddByte(buf, (Byte)' ');
  542. }
  543. Buf_AddBytes(buf, wordLen, (const Byte *)word);
  544. }
  545. /*
  546. * If added characters to the buffer, need to add a
  547. * space before we add any more. If we didn't add any,
  548. * just return the previous value of addSpace.
  549. */
  550. return ((Buf_Size(buf) != origSize) || addSpace);
  551. }
  552. /*
  553. * Common code for anchored substitutions:
  554. * addSpace was set TRUE if characters were added to the buffer.
  555. */
  556. return (addSpace);
  557. }
  558. nosub:
  559. if (addSpace) {
  560. Buf_AddByte(buf, (Byte)' ');
  561. }
  562. Buf_AddBytes(buf, wordLen, (const Byte *)word);
  563. return (TRUE);
  564. }
  565. /**
  566. * Print the error caused by a regcomp or regexec call.
  567. *
  568. * Side Effects:
  569. * An error gets printed.
  570. */
  571. static void
  572. VarREError(int err, regex_t *pat, const char *str)
  573. {
  574. char *errbuf;
  575. int errlen;
  576. errlen = regerror(err, pat, 0, 0);
  577. errbuf = emalloc(errlen);
  578. regerror(err, pat, errbuf, errlen);
  579. Error("%s: %s", str, errbuf);
  580. free(errbuf);
  581. }
  582. /**
  583. * Perform a regex substitution on the given word, placing the
  584. * result in the passed buffer. A space is added if requested.
  585. *
  586. * Results:
  587. * TRUE if a space is needed before more characters are added.
  588. */
  589. static Boolean
  590. VarRESubstitute(const char *word, Boolean addSpace, Buffer *buf, void *patternp)
  591. {
  592. VarPattern *pat;
  593. int xrv;
  594. const char *wp;
  595. char *rp;
  596. int added;
  597. int flags = 0;
  598. #define MAYBE_ADD_SPACE() \
  599. if (addSpace && !added) \
  600. Buf_AddByte(buf, (Byte)' '); \
  601. added = 1
  602. added = 0;
  603. wp = word;
  604. pat = patternp;
  605. if ((pat->flags & (VAR_SUB_ONE | VAR_SUB_MATCHED)) ==
  606. (VAR_SUB_ONE | VAR_SUB_MATCHED)) {
  607. xrv = REG_NOMATCH;
  608. } else {
  609. tryagain:
  610. xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
  611. }
  612. switch (xrv) {
  613. case 0:
  614. pat->flags |= VAR_SUB_MATCHED;
  615. if (pat->matches[0].rm_so > 0) {
  616. MAYBE_ADD_SPACE();
  617. Buf_AddBytes(buf, pat->matches[0].rm_so,
  618. (const Byte *)wp);
  619. }
  620. for (rp = Buf_Data(pat->rhs); *rp; rp++) {
  621. if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
  622. MAYBE_ADD_SPACE();
  623. Buf_AddByte(buf, (Byte)rp[1]);
  624. rp++;
  625. } else if ((*rp == '&') ||
  626. ((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
  627. int n;
  628. const char *subbuf;
  629. int sublen;
  630. char errstr[3];
  631. if (*rp == '&') {
  632. n = 0;
  633. errstr[0] = '&';
  634. errstr[1] = '\0';
  635. } else {
  636. n = rp[1] - '0';
  637. errstr[0] = '\\';
  638. errstr[1] = rp[1];
  639. errstr[2] = '\0';
  640. rp++;
  641. }
  642. if (n > pat->nsub) {
  643. Error("No subexpression %s",
  644. &errstr[0]);
  645. subbuf = "";
  646. sublen = 0;
  647. } else if ((pat->matches[n].rm_so == -1) &&
  648. (pat->matches[n].rm_eo == -1)) {
  649. Error("No match for subexpression %s",
  650. &errstr[0]);
  651. subbuf = "";
  652. sublen = 0;
  653. } else {
  654. subbuf = wp + pat->matches[n].rm_so;
  655. sublen = pat->matches[n].rm_eo -
  656. pat->matches[n].rm_so;
  657. }
  658. if (sublen > 0) {
  659. MAYBE_ADD_SPACE();
  660. Buf_AddBytes(buf, sublen,
  661. (const Byte *)subbuf);
  662. }
  663. } else {
  664. MAYBE_ADD_SPACE();
  665. Buf_AddByte(buf, (Byte)*rp);
  666. }
  667. }
  668. wp += pat->matches[0].rm_eo;
  669. if (pat->flags & VAR_SUB_GLOBAL) {
  670. flags |= REG_NOTBOL;
  671. if (pat->matches[0].rm_so == 0 &&
  672. pat->matches[0].rm_eo == 0) {
  673. MAYBE_ADD_SPACE();
  674. Buf_AddByte(buf, (Byte)*wp);
  675. wp++;
  676. }
  677. if (*wp)
  678. goto tryagain;
  679. }
  680. if (*wp) {
  681. MAYBE_ADD_SPACE();
  682. Buf_Append(buf, wp);
  683. }
  684. break;
  685. default:
  686. VarREError(xrv, &pat->re, "Unexpected regex error");
  687. /* fall through */
  688. case REG_NOMATCH:
  689. if (*wp) {
  690. MAYBE_ADD_SPACE();
  691. Buf_Append(buf, wp);
  692. }
  693. break;
  694. }
  695. return (addSpace || added);
  696. }
  697. /**
  698. * Find a variable in a variable list.
  699. */
  700. static Var *
  701. VarLookup(Lst *vlist, const char *name)
  702. {
  703. LstNode *ln;
  704. LST_FOREACH(ln, vlist)
  705. if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0)
  706. return (Lst_Datum(ln));
  707. return (NULL);
  708. }
  709. /**
  710. * Expand a variable name's embedded variables in the given context.
  711. *
  712. * Results:
  713. * The contents of name, possibly expanded.
  714. */
  715. static char *
  716. VarPossiblyExpand(const char *name, GNode *ctxt)
  717. {
  718. Buffer *buf;
  719. if (strchr(name, '$') != NULL) {
  720. buf = Var_Subst(name, ctxt, 0);
  721. return (Buf_Peel(buf));
  722. } else {
  723. return estrdup(name);
  724. }
  725. }
  726. /**
  727. * If the variable name begins with a '.', it could very well be
  728. * one of the local ones. We check the name against all the local
  729. * variables and substitute the short version in for 'name' if it
  730. * matches one of them.
  731. */
  732. static const char *
  733. VarLocal(const char name[])
  734. {
  735. if (name[0] == '.') {
  736. switch (name[1]) {
  737. case 'A':
  738. if (!strcmp(name, ".ALLSRC"))
  739. return (ALLSRC);
  740. if (!strcmp(name, ".ARCHIVE"))
  741. return (ARCHIVE);
  742. break;
  743. case 'I':
  744. if (!strcmp(name, ".IMPSRC"))
  745. return (IMPSRC);
  746. break;
  747. case 'M':
  748. if (!strcmp(name, ".MEMBER"))
  749. return (MEMBER);
  750. break;
  751. case 'O':
  752. if (!strcmp(name, ".OODATE"))
  753. return (OODATE);
  754. break;
  755. case 'P':
  756. if (!strcmp(name, ".PREFIX"))
  757. return (PREFIX);
  758. break;
  759. case 'T':
  760. if (!strcmp(name, ".TARGET"))
  761. return (TARGET);
  762. break;
  763. default:
  764. break;
  765. }
  766. }
  767. return (name);
  768. }
  769. /**
  770. * Find the given variable in the given context and the enviornment.
  771. *
  772. * Results:
  773. * A pointer to the structure describing the desired variable or
  774. * NULL if the variable does not exist.
  775. */
  776. static Var *
  777. VarFindEnv(const char name[], GNode *ctxt)
  778. {
  779. Var *var;
  780. name = VarLocal(name);
  781. if ((var = VarLookup(&ctxt->context, name)) != NULL)
  782. return (var);
  783. if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
  784. return (var);
  785. return (NULL);
  786. }
  787. /**
  788. * Look for the variable in the given context.
  789. */
  790. static Var *
  791. VarFindOnly(const char name[], GNode *ctxt)
  792. {
  793. Var *var;
  794. name = VarLocal(name);
  795. if ((var = VarLookup(&ctxt->context, name)) != NULL)
  796. return (var);
  797. return (NULL);
  798. }
  799. /**
  800. * Look for the variable in all contexts.
  801. */
  802. static Var *
  803. VarFindAny(const char name[], GNode *ctxt)
  804. {
  805. Boolean localCheckEnvFirst;
  806. LstNode *ln;
  807. Var *var;
  808. name = VarLocal(name);
  809. /*
  810. * Note whether this is one of the specific variables we were told
  811. * through the -E flag to use environment-variable-override for.
  812. */
  813. localCheckEnvFirst = FALSE;
  814. LST_FOREACH(ln, &envFirstVars) {
  815. if (strcmp(Lst_Datum(ln), name) == 0) {
  816. localCheckEnvFirst = TRUE;
  817. break;
  818. }
  819. }
  820. /*
  821. * First look for the variable in the given context. If it's not there,
  822. * look for it in VAR_CMD, VAR_GLOBAL and the environment,
  823. * in that order, depending on the FIND_* flags in 'flags'
  824. */
  825. if ((var = VarLookup(&ctxt->context, name)) != NULL)
  826. return (var);
  827. /* not there - try command line context */
  828. if (ctxt != VAR_CMD) {
  829. if ((var = VarLookup(&VAR_CMD->context, name)) != NULL)
  830. return (var);
  831. }
  832. /* not there - try global context, but only if not -e/-E */
  833. if (ctxt != VAR_GLOBAL && (!checkEnvFirst && !localCheckEnvFirst)) {
  834. if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
  835. return (var);
  836. }
  837. if ((var = VarLookup(&VAR_ENV->context, name)) != NULL)
  838. return (var);
  839. /* deferred check for the environment (in case of -e/-E) */
  840. if ((ctxt != VAR_GLOBAL) && (checkEnvFirst || localCheckEnvFirst)) {
  841. if ((var = VarLookup(&VAR_GLOBAL->context, name)) != NULL)
  842. return (var);
  843. }
  844. return (NULL);
  845. }
  846. /**
  847. * Add a new variable of name name and value val to the given context.
  848. *
  849. * Side Effects:
  850. * The new variable is placed at the front of the given context
  851. * The name and val arguments are duplicated so they may
  852. * safely be freed.
  853. */
  854. static Var *
  855. VarAdd(const char *name, const char *val, GNode *ctxt)
  856. {
  857. Var *v;
  858. Lst_AtFront(&ctxt->context, v = VarCreate(name, val, 0));
  859. DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, name, val));
  860. return (v);
  861. }
  862. /**
  863. * Remove a variable from a context.
  864. *
  865. * Side Effects:
  866. * The Var structure is removed and freed.
  867. */
  868. void
  869. Var_Delete(const char *name, GNode *ctxt)
  870. {
  871. LstNode *ln;
  872. DEBUGF(VAR, ("%s:delete %s\n", ctxt->name, name));
  873. LST_FOREACH(ln, &ctxt->context) {
  874. if (strcmp(((const Var *)Lst_Datum(ln))->name, name) == 0) {
  875. VarDestroy(Lst_Datum(ln), TRUE);
  876. Lst_Remove(&ctxt->context, ln);
  877. break;
  878. }
  879. }
  880. }
  881. /**
  882. * Set the variable name to the value val in the given context.
  883. *
  884. * Side Effects:
  885. * If the variable doesn't yet exist, a new record is created for it.
  886. * Else the old value is freed and the new one stuck in its place
  887. *
  888. * Notes:
  889. * The variable is searched for only in its context before being
  890. * created in that context. I.e. if the context is VAR_GLOBAL,
  891. * only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
  892. * VAR_CMD->context is searched. This is done to avoid the literally
  893. * thousands of unnecessary strcmp's that used to be done to
  894. * set, say, $(@) or $(<).
  895. */
  896. void
  897. Var_Set(const char *name, const char *val, GNode *ctxt)
  898. {
  899. Var *v;
  900. char *n;
  901. /*
  902. * We only look for a variable in the given context since anything
  903. * set here will override anything in a lower context, so there's not
  904. * much point in searching them all just to save a bit of memory...
  905. */
  906. n = VarPossiblyExpand(name, ctxt);
  907. v = VarFindOnly(n, ctxt);
  908. if (v == NULL) {
  909. v = VarAdd(n, val, ctxt);
  910. } else {
  911. Buf_Clear(v->val);
  912. Buf_Append(v->val, val);
  913. DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, val));
  914. }
  915. if (ctxt == VAR_CMD || (v->flags & VAR_TO_ENV)) {
  916. /*
  917. * Any variables given on the command line
  918. * are automatically exported to the
  919. * environment (as per POSIX standard)
  920. */
  921. setenv(n, val, 1);
  922. }
  923. free(n);
  924. }
  925. /**
  926. * Set the a global name variable to the value.
  927. */
  928. void
  929. Var_SetGlobal(const char name[], const char value[])
  930. {
  931. Var_Set(name, value, VAR_GLOBAL);
  932. }
  933. /**
  934. * Set the VAR_TO_ENV flag on a variable
  935. */
  936. void
  937. Var_SetEnv(const char *name, GNode *ctxt)
  938. {
  939. Var *v;
  940. v = VarFindOnly(name, VAR_CMD);
  941. if (v != NULL) {
  942. /*
  943. * Do not allow .EXPORT: to be set on variables
  944. * from the comand line or MAKEFLAGS.
  945. */
  946. Error(
  947. "Warning: Did not set .EXPORTVAR: on %s because it "
  948. "is from the comand line or MAKEFLAGS", name);
  949. return;
  950. }
  951. v = VarFindAny(name, ctxt);
  952. if (v == NULL) {
  953. Lst_AtFront(&VAR_ENV->context,
  954. VarCreate(name, NULL, VAR_TO_ENV));
  955. setenv(name, "", 1);
  956. Error("Warning: .EXPORTVAR: set on undefined variable %s", name);
  957. } else {
  958. if ((v->flags & VAR_TO_ENV) == 0) {
  959. v->flags |= VAR_TO_ENV;
  960. setenv(v->name, Buf_Data(v->val), 1);
  961. }
  962. }
  963. }
  964. /**
  965. * The variable of the given name has the given value appended to it in
  966. * the given context.
  967. *
  968. * Side Effects:
  969. * If the variable doesn't exist, it is created. Else the strings
  970. * are concatenated (with a space in between).
  971. *
  972. * Notes:
  973. * Only if the variable is being sought in the global context is the
  974. * environment searched.
  975. * XXX: Knows its calling circumstances in that if called with ctxt
  976. * an actual target, it will only search that context since only
  977. * a local variable could be being appended to. This is actually
  978. * a big win and must be tolerated.
  979. */
  980. void
  981. Var_Append(const char *name, const char *val, GNode *ctxt)
  982. {
  983. Var *v;
  984. char *n;
  985. n = VarPossiblyExpand(name, ctxt);
  986. if (ctxt == VAR_GLOBAL) {
  987. v = VarFindEnv(n, ctxt);
  988. } else {
  989. v = VarFindOnly(n, ctxt);
  990. }
  991. if (v == NULL) {
  992. VarAdd(n, val, ctxt);
  993. } else {
  994. Buf_AddByte(v->val, (Byte)' ');
  995. Buf_Append(v->val, val);
  996. DEBUGF(VAR, ("%s:%s = %s\n", ctxt->name, n, Buf_Data(v->val)));
  997. }
  998. free(n);
  999. }
  1000. /**
  1001. * See if the given variable exists.
  1002. *
  1003. * Results:
  1004. * TRUE if it does, FALSE if it doesn't
  1005. */
  1006. Boolean
  1007. Var_Exists(const char *name, GNode *ctxt)
  1008. {
  1009. Var *v;
  1010. char *n;
  1011. n = VarPossiblyExpand(name, ctxt);
  1012. v = VarFindAny(n, ctxt);
  1013. if (v == NULL) {
  1014. free(n);
  1015. return (FALSE);
  1016. } else {
  1017. free(n);
  1018. return (TRUE);
  1019. }
  1020. }
  1021. /**
  1022. * Return the value of the named variable in the given context
  1023. *
  1024. * Results:
  1025. * The value if the variable exists, NULL if it doesn't.
  1026. */
  1027. const char *
  1028. Var_Value(const char name[], GNode *ctxt)
  1029. {
  1030. Var *v;
  1031. char *n;
  1032. n = VarPossiblyExpand(name, ctxt);
  1033. v = VarFindAny(n, ctxt);
  1034. free(n);
  1035. if (v == NULL) {
  1036. return (NULL);
  1037. } else {
  1038. return (Buf_Data(v->val));
  1039. }
  1040. }
  1041. /**
  1042. * Modify each of the words of the passed string using the given
  1043. * function. Used to implement all modifiers.
  1044. *
  1045. * Results:
  1046. * A string of all the words modified appropriately.
  1047. *
  1048. * Side Effects:
  1049. * Uses brk_string() so it invalidates any previous call to
  1050. * brk_string().
  1051. */
  1052. static char *
  1053. VarModify(const char *str, VarModifyProc *modProc, void *datum)
  1054. {
  1055. ArgArray aa;
  1056. Buffer *buf; /* Buffer for the new string */
  1057. int i;
  1058. Boolean addSpace; /*
  1059. * TRUE if need to add a space to
  1060. * the buffer before adding the
  1061. * trimmed word
  1062. */
  1063. brk_string(&aa, str, FALSE);
  1064. addSpace = FALSE;
  1065. buf = Buf_Init(0);
  1066. for (i = 1; i < aa.argc; i++)
  1067. addSpace = (*modProc)(aa.argv[i], addSpace, buf, datum);
  1068. ArgArray_Done(&aa);
  1069. return (Buf_Peel(buf));
  1070. }
  1071. /**
  1072. * Sort the words in the string.
  1073. *
  1074. * Input:
  1075. * str String whose words should be sorted
  1076. * cmp A comparison function to control the ordering
  1077. *
  1078. * Results:
  1079. * A string containing the words sorted
  1080. */
  1081. static char *
  1082. VarSortWords(const char *str, int (*cmp)(const void *, const void *))
  1083. {
  1084. ArgArray aa;
  1085. Buffer *buf;
  1086. int i;
  1087. brk_string(&aa, str, FALSE);
  1088. qsort(aa.argv + 1, aa.argc - 1, sizeof(char *), cmp);
  1089. buf = Buf_Init(0);
  1090. for (i = 1; i < aa.argc; i++) {
  1091. Buf_Append(buf, aa.argv[i]);
  1092. Buf_AddByte(buf, (Byte)((i < aa.argc - 1) ? ' ' : '\0'));
  1093. }
  1094. ArgArray_Done(&aa);
  1095. return (Buf_Peel(buf));
  1096. }
  1097. static int
  1098. SortIncreasing(const void *l, const void *r)
  1099. {
  1100. return (strcmp(*(const char* const*)l, *(const char* const*)r));
  1101. }
  1102. /**
  1103. * Remove adjacent duplicate words.
  1104. *
  1105. * Results:
  1106. * A string containing the resulting words.
  1107. */
  1108. static char *
  1109. VarUniq(const char *str)
  1110. {
  1111. ArgArray aa;
  1112. Buffer *buf; /* Buffer for new string */
  1113. int i, j;
  1114. buf = Buf_Init(0);
  1115. brk_string(&aa, str, FALSE);
  1116. if (aa.argc > 2) {
  1117. for (j = 1, i = 2; i < aa.argc; i++) {
  1118. if (strcmp(aa.argv[i], aa.argv[j]) != 0 && (++j != i))
  1119. aa.argv[j] = aa.argv[i];
  1120. }
  1121. aa.argc = j + 1;
  1122. }
  1123. for (i = 1; i < aa.argc; i++) {
  1124. Buf_AddBytes(buf, strlen(aa.argv[i]), (Byte *)aa.argv[i]);
  1125. if (i != aa.argc - 1)
  1126. Buf_AddByte(buf, ' ');
  1127. }
  1128. Buf_AddByte(buf, '\0');
  1129. ArgArray_Done(&aa);
  1130. return (Buf_Peel(buf));
  1131. }
  1132. /**
  1133. * Pass through the tstr looking for 1) escaped delimiters,
  1134. * '$'s and backslashes (place the escaped character in
  1135. * uninterpreted) and 2) unescaped $'s that aren't before
  1136. * the delimiter (expand the variable substitution).
  1137. * Return the expanded string or NULL if the delimiter was missing
  1138. * If pattern is specified, handle escaped ampersands, and replace
  1139. * unescaped ampersands with the lhs of the pattern.
  1140. *
  1141. * Results:
  1142. * A string of all the words modified appropriately.
  1143. * If length is specified, return the string length of the buffer
  1144. * If flags is specified and the last character of the pattern is a
  1145. * $ set the VAR_MATCH_END bit of flags.
  1146. */
  1147. static Buffer *
  1148. VarGetPattern(VarParser *vp, int delim, int *flags, VarPattern *patt)
  1149. {
  1150. Buffer *buf;
  1151. buf = Buf_Init(0);
  1152. /*
  1153. * Skim through until the matching delimiter is found; pick up
  1154. * variable substitutions on the way. Also allow backslashes to quote
  1155. * the delimiter, $, and \, but don't touch other backslashes.
  1156. */
  1157. while (*vp->ptr != '\0') {
  1158. if (*vp->ptr == delim) {
  1159. return (buf);
  1160. } else if ((vp->ptr[0] == '\\') &&
  1161. ((vp->ptr[1] == delim) ||
  1162. (vp->ptr[1] == '\\') ||
  1163. (vp->ptr[1] == '$') ||
  1164. (vp->ptr[1] == '&' && patt != NULL))) {
  1165. vp->ptr++; /* consume backslash */
  1166. Buf_AddByte(buf, (Byte)vp->ptr[0]);
  1167. vp->ptr++;
  1168. } else if (vp->ptr[0] == '$') {
  1169. if (vp->ptr[1] == delim) {
  1170. if (flags == NULL) {
  1171. Buf_AddByte(buf, (Byte)vp->ptr[0]);
  1172. vp->ptr++;
  1173. } else {
  1174. /*
  1175. * Unescaped $ at end of patt =>
  1176. * anchor patt at end.
  1177. */
  1178. *flags |= VAR_MATCH_END;
  1179. vp->ptr++;
  1180. }
  1181. } else {
  1182. VarParser subvp = {
  1183. vp->ptr,
  1184. vp->ptr,
  1185. vp->ctxt,
  1186. vp->err,
  1187. vp->execute
  1188. };
  1189. char *rval;
  1190. Boolean rfree;
  1191. /*
  1192. * If unescaped dollar sign not
  1193. * before the delimiter, assume it's
  1194. * a variable substitution and
  1195. * recurse.
  1196. */
  1197. rval = VarParse(&subvp, &rfree);
  1198. Buf_Append(buf, rval);
  1199. if (rfree)
  1200. free(rval);
  1201. vp->ptr = subvp.ptr;
  1202. }
  1203. } else if (vp->ptr[0] == '&' && patt != NULL) {
  1204. Buf_AppendBuf(buf, patt->lhs);
  1205. vp->ptr++;
  1206. } else {
  1207. Buf_AddByte(buf, (Byte)vp->ptr[0]);
  1208. vp->ptr++;
  1209. }
  1210. }
  1211. Buf_Destroy(buf, TRUE);
  1212. return (NULL);
  1213. }
  1214. /**
  1215. * Make sure this variable is fully expanded.
  1216. */
  1217. static char *
  1218. VarExpand(Var *v, VarParser *vp)
  1219. {
  1220. char *value;
  1221. char *result;
  1222. if (v->flags & VAR_IN_USE) {
  1223. Fatal("Variable %s is recursive.", v->name);
  1224. /* NOTREACHED */
  1225. }
  1226. v->flags |= VAR_IN_USE;
  1227. /*
  1228. * Before doing any modification, we have to make sure the
  1229. * value has been fully expanded. If it looks like recursion
  1230. * might be necessary (there's a dollar sign somewhere in the
  1231. * variable's value) we just call Var_Subst to do any other
  1232. * substitutions that are necessary. Note that the value
  1233. * returned by Var_Subst will have been
  1234. * dynamically-allocated, so it will need freeing when we
  1235. * return.
  1236. */
  1237. value = Buf_Data(v->val);
  1238. if (strchr(value, '$') == NULL) {
  1239. result = strdup(value);
  1240. } else {
  1241. Buffer *buf;
  1242. buf = Var_Subst(value, vp->ctxt, vp->err);
  1243. result = Buf_Peel(buf);
  1244. }
  1245. v->flags &= ~VAR_IN_USE;
  1246. return (result);
  1247. }
  1248. /**
  1249. * Select only those words in value that match the modifier.
  1250. */
  1251. static char *
  1252. modifier_M(VarParser *vp, const char value[], char endc)
  1253. {
  1254. char *patt;
  1255. char *ptr;
  1256. char *newValue;
  1257. char modifier;
  1258. modifier = vp->ptr[0];
  1259. vp->ptr++; /* consume 'M' or 'N' */
  1260. /*
  1261. * Compress the \:'s out of the pattern, so allocate enough
  1262. * room to hold the uncompressed pattern and compress the
  1263. * pattern into that space.
  1264. */
  1265. patt = estrdup(vp->ptr);
  1266. ptr = patt;
  1267. while (vp->ptr[0] != '\0') {
  1268. if (vp->ptr[0] == endc || vp->ptr[0] == ':') {
  1269. break;
  1270. }
  1271. if (vp->ptr[0] == '\\' &&
  1272. (vp->ptr[1] == endc || vp->ptr[1] == ':')) {
  1273. vp->ptr++; /* consume backslash */
  1274. }
  1275. *ptr = vp->ptr[0];
  1276. ptr++;
  1277. vp->ptr++;
  1278. }
  1279. *ptr = '\0';
  1280. if (modifier == 'M') {
  1281. newValue = VarModify(value, VarMatch, patt);
  1282. } else {
  1283. newValue = VarModify(value, VarNoMatch, patt);
  1284. }
  1285. free(patt);
  1286. return (newValue);
  1287. }
  1288. /**
  1289. * Substitute the replacement string for the pattern. The substitution
  1290. * is applied to each word in value.
  1291. */
  1292. static char *
  1293. modifier_S(VarParser *vp, const char value[], Var *v)
  1294. {
  1295. VarPattern patt;
  1296. char delim;
  1297. char *newValue;
  1298. patt.flags = 0;
  1299. vp->ptr++; /* consume 'S' */
  1300. delim = *vp->ptr; /* used to find end of pattern */
  1301. vp->ptr++; /* consume 1st delim */
  1302. /*
  1303. * If pattern begins with '^', it is anchored to the start of the
  1304. * word -- skip over it and flag pattern.
  1305. */
  1306. if (*vp->ptr == '^') {
  1307. patt.flags |= VAR_MATCH_START;
  1308. vp->ptr++;
  1309. }
  1310. patt.lhs = VarGetPattern(vp, delim, &patt.flags, NULL);
  1311. if (patt.lhs == NULL) {
  1312. /*
  1313. * LHS didn't end with the delim, complain and exit.
  1314. */
  1315. Fatal("Unclosed substitution for %s (%c missing)",
  1316. v->name, delim);
  1317. }
  1318. vp->ptr++; /* consume 2nd delim */
  1319. patt.rhs = VarGetPattern(vp, delim, NULL, &patt);
  1320. if (patt.rhs == NULL) {
  1321. /*
  1322. * RHS didn't end with the delim, complain and exit.
  1323. */
  1324. Fatal("Unclosed substitution for %s (%c missing)",
  1325. v->name, delim);
  1326. }
  1327. vp->ptr++; /* consume last delim */
  1328. /*
  1329. * Check for global substitution. If 'g' after the final delimiter,
  1330. * substitution is global and is marked that way.
  1331. */
  1332. if (vp->ptr[0] == 'g') {
  1333. patt.flags |= VAR_SUB_GLOBAL;
  1334. vp->ptr++;
  1335. }
  1336. /*
  1337. * Global substitution of the empty string causes an infinite number
  1338. * of matches, unless anchored by '^' (start of string) or '$' (end
  1339. * of string). Catch the infinite substitution here. Note that flags
  1340. * can only contain the 3 bits we're interested in so we don't have
  1341. * to mask unrelated bits. We can test for equality.
  1342. */
  1343. if (Buf_Size(patt.lhs) == 0 && patt.flags == VAR_SUB_GLOBAL)
  1344. Fatal("Global substitution of the empty string");
  1345. newValue = VarModify(value, VarSubstitute, &patt);
  1346. /*
  1347. * Free the two strings.
  1348. */
  1349. free(patt.lhs);
  1350. free(patt.rhs);
  1351. return (newValue);
  1352. }
  1353. static char *
  1354. modifier_C(VarParser *vp, char value[], Var *v)
  1355. {
  1356. VarPattern patt;
  1357. char delim;
  1358. int error;
  1359. char *newValue;
  1360. patt.flags = 0;
  1361. vp->ptr++; /* consume 'C' */
  1362. delim = *vp->ptr; /* delimiter between sections */
  1363. vp->ptr++; /* consume 1st delim */
  1364. patt.lhs = VarGetPattern(vp, delim, NULL, NULL);
  1365. if (patt.lhs == NULL) {
  1366. Fatal("Unclosed substitution for %s (%c missing)",
  1367. v->name, delim);
  1368. }
  1369. vp->ptr++; /* consume 2st delim */
  1370. patt.rhs = VarGetPattern(vp, delim, NULL, NULL);
  1371. if (patt.rhs == NULL) {
  1372. Fatal("Unclosed substitution for %s (%c missing)",
  1373. v->name, delim);
  1374. }
  1375. vp->ptr++; /* consume last delim */
  1376. switch (*vp->ptr) {
  1377. case 'g':
  1378. patt.flags |= VAR_SUB_GLOBAL;
  1379. vp->ptr++; /* consume 'g' */
  1380. break;
  1381. case '1':
  1382. patt.flags |= VAR_SUB_ONE;
  1383. vp->ptr++; /* consume '1' */
  1384. break;
  1385. default:
  1386. break;
  1387. }
  1388. error = regcomp(&patt.re, Buf_Data(patt.lhs), REG_EXTENDED);
  1389. if (error) {
  1390. VarREError(error, &patt.re, "RE substitution error");
  1391. free(patt.rhs);
  1392. free(patt.lhs);
  1393. return (var_Error);
  1394. }
  1395. patt.nsub = patt.re.re_nsub + 1;
  1396. if (patt.nsub < 1)
  1397. patt.nsub = 1;
  1398. if (patt.nsub > 10)
  1399. patt.nsub = 10;
  1400. patt.matches = emalloc(patt.nsub * sizeof(regmatch_t));
  1401. newValue = VarModify(value, VarRESubstitute, &patt);
  1402. regfree(&patt.re);
  1403. free(patt.matches);
  1404. free(patt.rhs);
  1405. free(patt.lhs);
  1406. return (newValue);
  1407. }
  1408. static char *
  1409. sysVvarsub(VarParser *vp, char startc, Var *v, const char value[])
  1410. {
  1411. #ifdef SYSVVARSUB
  1412. /*
  1413. * This can either be a bogus modifier or a System-V substitution
  1414. * command.
  1415. */
  1416. char endc;
  1417. VarPattern patt;
  1418. Boolean eqFound;
  1419. int cnt;
  1420. char *newStr;
  1421. const char *cp;
  1422. endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
  1423. patt.flags = 0;
  1424. /*
  1425. * First we make a pass through the string trying to verify it is a
  1426. * SYSV-make-style translation: it must be: <string1>=<string2>)
  1427. */
  1428. eqFound = FALSE;
  1429. cp = vp->ptr;
  1430. cnt = 1;
  1431. while (*cp != '\0' && cnt) {
  1432. if (*cp == '=') {
  1433. eqFound = TRUE;
  1434. /* continue looking for endc */
  1435. } else if (*cp == endc)
  1436. cnt--;
  1437. else if (*cp == startc)
  1438. cnt++;
  1439. if (cnt)
  1440. cp++;
  1441. }
  1442. if (*cp == endc && eqFound) {
  1443. /*
  1444. * Now we break this sucker into the lhs and rhs.
  1445. */
  1446. patt.lhs = VarGetPattern(vp, '=', &patt.flags, NULL);
  1447. if (patt.lhs == NULL) {
  1448. Fatal("Unclosed substitution for %s (%c missing)",
  1449. v->name, '=');
  1450. }
  1451. vp->ptr++; /* consume '=' */
  1452. patt.rhs = VarGetPattern(vp, endc, NULL, &patt);
  1453. if (patt.rhs == NULL) {
  1454. Fatal("Unclosed substitution for %s (%c missing)",
  1455. v->name, endc);
  1456. }
  1457. /*
  1458. * SYSV modifications happen through the whole string. Note
  1459. * the pattern is anchored at the end.
  1460. */
  1461. newStr = VarModify(value, VarSYSVMatch, &patt);
  1462. free(patt.lhs);
  1463. free(patt.rhs);
  1464. } else
  1465. #endif
  1466. {
  1467. Error("Unknown modifier '%c'\n", *vp->ptr);
  1468. vp->ptr++;
  1469. while (*vp->ptr != '\0') {
  1470. if (*vp->ptr == endc && *vp->ptr == ':') {
  1471. break;
  1472. }
  1473. vp->ptr++;
  1474. }
  1475. newStr = var_Error;
  1476. }
  1477. return (newStr);
  1478. }
  1479. /**
  1480. * Quote shell meta-characters in the string
  1481. *
  1482. * Results:
  1483. * The quoted string
  1484. */
  1485. static char *
  1486. Var_Quote(const char *str)
  1487. {
  1488. Buffer *buf;
  1489. /* This should cover most shells :-( */
  1490. static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
  1491. buf = Buf_Init(MAKE_BSIZE);
  1492. for (; *str; str++) {
  1493. if (strchr(meta, *str) != NULL)
  1494. Buf_AddByte(buf, (Byte)'\\');
  1495. Buf_AddByte(buf, (Byte)*str);
  1496. }
  1497. return (Buf_Peel(buf));
  1498. }
  1499. /*
  1500. * Now we need to apply any modifiers the user wants applied.
  1501. * These are:
  1502. * :M<pattern>
  1503. * words which match the given <pattern>.
  1504. * <pattern> is of the standard file
  1505. * wildcarding form.
  1506. * :N<pattern>
  1507. * words which do not match the given <pattern>
  1508. * <pattern> is of the standard file
  1509. * wildcarding form.
  1510. * :S<d><pat1><d><pat2><d>[g]
  1511. * Substitute <pat2> for <pat1> in the value
  1512. * :C<d><pat1><d><pat2><d>[g]
  1513. * Substitute <pat2> for regex <pat1> in the value
  1514. * :H Substitute the head of each word
  1515. * :T Substitute the tail of each word
  1516. * :E Substitute the extension (minus '.') of
  1517. * each word
  1518. * :R Substitute the root of each word
  1519. * (pathname minus the suffix).
  1520. * :lhs=rhs
  1521. * Like :S, but the rhs goes to the end of
  1522. * the invocation.
  1523. * :U Converts variable to upper-case.
  1524. * :L Converts variable to lower-case.
  1525. * :O ("Order") Alphabeticaly sort words in variable.
  1526. * :u ("uniq") Remove adjacent duplicate words.
  1527. */
  1528. static char *
  1529. ParseModifier(VarParser *vp, char startc, Var *v, Boolean *freeResult)
  1530. {
  1531. char *value;
  1532. char endc;
  1533. value = VarExpand(v, vp);
  1534. *freeResult = TRUE;
  1535. endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
  1536. vp->ptr++; /* consume first colon */
  1537. while (*vp->ptr != '\0') {
  1538. char *newStr; /* New value to return */
  1539. if (*vp->ptr == endc) {
  1540. return (value);
  1541. }
  1542. DEBUGF(VAR, ("Applying :%c to \"%s\"\n", *vp->ptr, value));
  1543. switch (*vp->ptr) {
  1544. case 'N':
  1545. case 'M':
  1546. newStr = modifier_M(vp, value, endc);
  1547. break;
  1548. case 'S':
  1549. newStr = modifier_S(vp, value, v);
  1550. break;
  1551. case 'C':
  1552. newStr = modifier_C(vp, value, v);
  1553. break;
  1554. default:
  1555. if (vp->ptr[1] != endc && vp->ptr[1] != ':') {
  1556. #ifdef SUNSHCMD
  1557. if ((vp->ptr[0] == 's') &&
  1558. (vp->ptr[1] == 'h') &&
  1559. (vp->ptr[2] == endc || vp->ptr[2] == ':')) {
  1560. const char *error;
  1561. if (vp->execute) {
  1562. newStr = Buf_Peel(
  1563. Cmd_Exec(value, &error));
  1564. } else {
  1565. newStr = estrdup("");
  1566. }
  1567. if (error)
  1568. Error(error, value);
  1569. vp->ptr += 2;
  1570. } else
  1571. #endif
  1572. {
  1573. newStr = sysVvarsub(vp, startc, v, value);
  1574. }
  1575. break;
  1576. }
  1577. switch (vp->ptr[0]) {
  1578. case 'L':
  1579. {
  1580. const char *cp;
  1581. Buffer *buf;
  1582. buf = Buf_Init(MAKE_BSIZE);
  1583. for (cp = value; *cp; cp++)
  1584. Buf_AddByte(buf, (Byte)tolower(*cp));
  1585. newStr = Buf_Peel(buf);
  1586. vp->ptr++;
  1587. break;
  1588. }
  1589. case 'O':
  1590. newStr = VarSortWords(value, SortIncreasing);
  1591. vp->ptr++;
  1592. break;
  1593. case 'Q':
  1594. newStr = Var_Quote(value);
  1595. vp->ptr++;
  1596. break;
  1597. case 'T':
  1598. newStr = VarModify(value, VarTail, NULL);
  1599. vp->ptr++;
  1600. break;
  1601. case 'U':
  1602. {
  1603. const char *cp;
  1604. Buffer *buf;
  1605. buf = Buf_Init(MAKE_BSIZE);
  1606. for (cp = value; *cp; cp++)
  1607. Buf_AddByte(buf, (Byte)toupper(*cp));
  1608. newStr = Buf_Peel(buf);
  1609. vp->ptr++;
  1610. break;
  1611. }
  1612. case 'H':
  1613. newStr = VarModify(value, VarHead, NULL);
  1614. vp->ptr++;
  1615. break;
  1616. case 'E':
  1617. newStr = VarModify(value, VarSuffix, NULL);
  1618. vp->ptr++;
  1619. break;
  1620. case 'R':
  1621. newStr = VarModify(value, VarRoot, NULL);
  1622. vp->ptr++;
  1623. break;
  1624. case 'u':
  1625. newStr = VarUniq(value);
  1626. vp->ptr++;
  1627. break;
  1628. default:
  1629. newStr = sysVvarsub(vp, startc, v, value);
  1630. break;
  1631. }
  1632. break;
  1633. }
  1634. DEBUGF(VAR, ("Result is \"%s\"\n", newStr));
  1635. if (*freeResult) {
  1636. free(value);
  1637. }
  1638. value = newStr;
  1639. *freeResult = (value == var_Error) ? FALSE : TRUE;
  1640. if (vp->ptr[0] == ':') {
  1641. vp->ptr++; /* consume colon */
  1642. }
  1643. }
  1644. return (value);
  1645. }
  1646. static char *
  1647. ParseRestModifier(VarParser *vp, char startc, Buffer *buf, Boolean *freeResult)
  1648. {
  1649. const char *vname;
  1650. size_t vlen;
  1651. Var *v;
  1652. char *value;
  1653. vname = Buf_GetAll(buf, &vlen);
  1654. v = VarFindAny(vname, vp->ctxt);
  1655. if (v != NULL) {
  1656. value = ParseModifier(vp, startc, v, freeResult);
  1657. return (value);
  1658. }
  1659. if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
  1660. size_t consumed;
  1661. /*
  1662. * Still need to get to the end of the variable
  1663. * specification, so kludge up a Var structure for the
  1664. * modifications
  1665. */
  1666. v = VarCreate(vname, NULL, VAR_JUNK);
  1667. value = ParseModifier(vp, startc, v, freeResult);
  1668. if (*freeResult) {
  1669. free(value);
  1670. }
  1671. VarDestroy(v, TRUE);
  1672. consumed = vp->ptr - vp->input + 1;
  1673. /*
  1674. * If substituting a local variable in a non-local context,
  1675. * assume it's for dynamic source stuff. We have to handle
  1676. * this specially and return the longhand for the variable
  1677. * with the dollar sign escaped so it makes it back to the
  1678. * caller. Only four of the local variables are treated
  1679. * specially as they are the only four that will be set when
  1680. * dynamic sources are expanded.
  1681. */
  1682. if (vlen == 1 ||
  1683. (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
  1684. if (strchr("!%*@", vname[0]) != NULL) {
  1685. value = emalloc(consumed + 1);
  1686. strncpy(value, vp->input, consumed);
  1687. value[consumed] = '\0';
  1688. *freeResult = TRUE;
  1689. return (value);
  1690. }
  1691. }
  1692. if (vlen > 2 &&
  1693. vname[0] == '.' &&
  1694. isupper((unsigned char)vname[1])) {
  1695. if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
  1696. (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
  1697. (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
  1698. (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
  1699. value = emalloc(consumed + 1);
  1700. strncpy(value, vp->input, consumed);
  1701. value[consumed] = '\0';
  1702. *freeResult = TRUE;
  1703. return (value);
  1704. }
  1705. }
  1706. *freeResult = FALSE;
  1707. return (vp->err ? var_Error : varNoError);
  1708. } else {
  1709. /*
  1710. * Check for D and F forms of local variables since we're in
  1711. * a local context and the name is the right length.
  1712. */
  1713. if (vlen == 2 &&
  1714. (vname[1] == 'F' || vname[1] == 'D') &&
  1715. (strchr("!%*<>@", vname[0]) != NULL)) {
  1716. char name[2];
  1717. name[0] = vname[0];
  1718. name[1] = '\0';
  1719. v = VarFindOnly(name, vp->ctxt);
  1720. if (v != NULL) {
  1721. value = ParseModifier(vp, startc, v, freeResult);
  1722. return (value);
  1723. }
  1724. }
  1725. /*
  1726. * Still need to get to the end of the variable
  1727. * specification, so kludge up a Var structure for the
  1728. * modifications
  1729. */
  1730. v = VarCreate(vname, NULL, VAR_JUNK);
  1731. value = ParseModifier(vp, startc, v, freeResult);
  1732. if (*freeResult) {
  1733. free(value);
  1734. }
  1735. VarDestroy(v, TRUE);
  1736. *freeResult = FALSE;
  1737. return (vp->err ? var_Error : varNoError);
  1738. }
  1739. }
  1740. static char *
  1741. ParseRestEnd(VarParser *vp, Buffer *buf, Boolean *freeResult)
  1742. {
  1743. const char *vname;
  1744. size_t vlen;
  1745. Var *v;
  1746. char *value;
  1747. vname = Buf_GetAll(buf, &vlen);
  1748. v = VarFindAny(vname, vp->ctxt);
  1749. if (v != NULL) {
  1750. value = VarExpand(v, vp);
  1751. *freeResult = TRUE;
  1752. return (value);
  1753. }
  1754. if ((vp->ctxt == VAR_CMD) || (vp->ctxt == VAR_GLOBAL)) {
  1755. size_t consumed = vp->ptr - vp->input + 1;
  1756. /*
  1757. * If substituting a local variable in a non-local context,
  1758. * assume it's for dynamic source stuff. We have to handle
  1759. * this specially and return the longhand for the variable
  1760. * with the dollar sign escaped so it makes it back to the
  1761. * caller. Only four of the local variables are treated
  1762. * specially as they are the only four that will be set when
  1763. * dynamic sources are expanded.
  1764. */
  1765. if (vlen == 1 ||
  1766. (vlen == 2 && (vname[1] == 'F' || vname[1] == 'D'))) {
  1767. if (strchr("!%*@", vname[0]) != NULL) {
  1768. value = emalloc(consumed + 1);
  1769. strncpy(value, vp->input, consumed);
  1770. value[consumed] = '\0';
  1771. *freeResult = TRUE;
  1772. return (value);
  1773. }
  1774. }
  1775. if (vlen > 2 &&
  1776. vname[0] == '.' &&
  1777. isupper((unsigned char)vname[1])) {
  1778. if ((strncmp(vname, ".TARGET", vlen - 1) == 0) ||
  1779. (strncmp(vname, ".ARCHIVE", vlen - 1) == 0) ||
  1780. (strncmp(vname, ".PREFIX", vlen - 1) == 0) ||
  1781. (strncmp(vname, ".MEMBER", vlen - 1) == 0)) {
  1782. value = emalloc(consumed + 1);
  1783. strncpy(value, vp->input, consumed);
  1784. value[consumed] = '\0';
  1785. *freeResult = TRUE;
  1786. return (value);
  1787. }
  1788. }
  1789. } else {
  1790. /*
  1791. * Check for D and F forms of local variables since we're in
  1792. * a local context and the name is the right length.
  1793. */
  1794. if (vlen == 2 &&
  1795. (vname[1] == 'F' || vname[1] == 'D') &&
  1796. (strchr("!%*<>@", vname[0]) != NULL)) {
  1797. char name[2];
  1798. name[0] = vname[0];
  1799. name[1] = '\0';
  1800. v = VarFindOnly(name, vp->ctxt);
  1801. if (v != NULL) {
  1802. char *val;
  1803. /*
  1804. * No need for nested expansion or anything,
  1805. * as we're the only one who sets these
  1806. * things and we sure don't put nested
  1807. * invocations in them...
  1808. */
  1809. val = Buf_Data(v->val);
  1810. if (vname[1] == 'D') {
  1811. val = VarModify(val, VarHead, NULL);
  1812. } else {
  1813. val = VarModify(val, VarTail, NULL);
  1814. }
  1815. *freeResult = TRUE;
  1816. return (val);
  1817. }
  1818. }
  1819. }
  1820. *freeResult = FALSE;
  1821. return (vp->err ? var_Error : varNoError);
  1822. }
  1823. /**
  1824. * Parse a multi letter variable name, and return it's value.
  1825. */
  1826. static char *
  1827. VarParseLong(VarParser *vp, Boolean *freeResult)
  1828. {
  1829. Buffer *buf;
  1830. char startc;
  1831. char endc;
  1832. char *value;
  1833. buf = Buf_Init(MAKE_BSIZE);
  1834. startc = vp->ptr[0];
  1835. vp->ptr++; /* consume opening paren or brace */
  1836. endc = (startc == OPEN_PAREN) ? CLOSE_PAREN : CLOSE_BRACE;
  1837. /*
  1838. * Process characters until we reach an end character or a colon,
  1839. * replacing embedded variables as we go.
  1840. */
  1841. while (*vp->ptr != '\0') {
  1842. if (*vp->ptr == endc) {
  1843. value = ParseRestEnd(vp, buf, freeResult);
  1844. vp->ptr++; /* consume closing paren or brace */
  1845. Buf_Destroy(buf, TRUE);
  1846. return (value);
  1847. } else if (*vp->ptr == ':') {
  1848. value = ParseRestModifier(vp, startc, buf, freeResult);
  1849. vp->ptr++; /* consume closing paren or brace */
  1850. Buf_Destroy(buf, TRUE);
  1851. return (value);
  1852. } else if (*vp->ptr == '$') {
  1853. VarParser subvp = {
  1854. vp->ptr,
  1855. vp->ptr,
  1856. vp->ctxt,
  1857. vp->err,
  1858. vp->execute
  1859. };
  1860. char *rval;
  1861. Boolean rfree;
  1862. rval = VarParse(&subvp, &rfree);
  1863. if (rval == var_Error) {
  1864. Fatal("Error expanding embedded variable.");
  1865. }
  1866. Buf_Append(buf, rval);
  1867. if (rfree)
  1868. free(rval);
  1869. vp->ptr = subvp.ptr;
  1870. } else {
  1871. Buf_AddByte(buf, (Byte)*vp->ptr);
  1872. vp->ptr++;
  1873. }
  1874. }
  1875. /* If we did not find the end character, return var_Error */
  1876. Buf_Destroy(buf, TRUE);
  1877. *freeResult = FALSE;
  1878. return (var_Error);
  1879. }
  1880. /**
  1881. * Parse a single letter variable name, and return it's value.
  1882. */
  1883. static char *
  1884. VarParseShort(VarParser *vp, Boolean *freeResult)
  1885. {
  1886. char vname[2];
  1887. Var *v;
  1888. char *value;
  1889. vname[0] = vp->ptr[0];
  1890. vname[1] = '\0';
  1891. vp->ptr++; /* consume single letter */
  1892. v = VarFindAny(vname, vp->ctxt);
  1893. if (v != NULL) {
  1894. value = VarExpand(v, vp);
  1895. *freeResult = TRUE;
  1896. return (v

Large files files are truncated, but you can click here to view the full file