1 /** \ingroup rpmrc rpmio
15 #define isblank(_c) ((_c) == ' ' || (_c) == '\t')
17 #define iseol(_c) ((_c) == '\n' || (_c) == '\r')
19 #define STREQ(_t, _f, _fn) ((_fn) == (sizeof(_t)-1) && rstreqn((_t), (_f), (_fn)))
21 #define MACROBUFSIZ (BUFSIZ * 2)
23 #include <rpm/rpmio.h>
24 #include <rpm/rpmstring.h>
25 #include <rpm/rpmfileutil.h>
26 #include <rpm/rpmurl.h>
27 #include <rpm/rpmlog.h>
28 #include <rpm/rpmmacro.h>
32 #include "rpmio/rpmlua.h"
37 /*! The structure used to store a macro. */
38 struct rpmMacroEntry_s {
39 struct rpmMacroEntry_s *prev;/*!< Macro entry stack. */
40 char *name; /*!< Macro name. */
41 char *opts; /*!< Macro parameters (a la getopt) */
42 char *body; /*!< Macro body. */
43 int used; /*!< No. of expansions. */
44 int level; /*!< Scoping level. */
47 /*! The structure used to store the set of macros in a context. */
48 struct rpmMacroContext_s {
49 rpmMacroEntry *macroTable; /*!< Macro entry table for context. */
50 int macrosAllocated;/*!< No. of allocated macros. */
51 int firstFree; /*!< No. of macros. */
55 static struct rpmMacroContext_s rpmGlobalMacroContext_s;
56 rpmMacroContext rpmGlobalMacroContext = &rpmGlobalMacroContext_s;
58 static struct rpmMacroContext_s rpmCLIMacroContext_s;
59 rpmMacroContext rpmCLIMacroContext = &rpmCLIMacroContext_s;
62 * Macro expansion state.
64 typedef struct MacroBuf_s {
65 char * buf; /*!< Expansion buffer. */
66 size_t tpos; /*!< Current position in expansion buffer */
67 size_t nb; /*!< No. bytes remaining in expansion buffer. */
68 int depth; /*!< Current expansion depth. */
69 int macro_trace; /*!< Pre-print macro to expand? */
70 int expand_trace; /*!< Post-print macro expansion? */
74 #define _MAX_MACRO_DEPTH 16
75 static int max_macro_depth = _MAX_MACRO_DEPTH;
77 #define _PRINT_MACRO_TRACE 0
78 static int print_macro_trace = _PRINT_MACRO_TRACE;
80 #define _PRINT_EXPAND_TRACE 0
81 static int print_expand_trace = _PRINT_EXPAND_TRACE;
83 #define MACRO_CHUNK_SIZE 16
86 static int expandMacro(MacroBuf mb, const char *src, size_t slen);
88 /* =============================================================== */
91 * Compare macro entries by name (qsort/bsearch).
92 * @param ap 1st macro entry
93 * @param bp 2nd macro entry
94 * @return result of comparison
97 compareMacroName(const void * ap, const void * bp)
99 rpmMacroEntry ame = *((const rpmMacroEntry *)ap);
100 rpmMacroEntry bme = *((const rpmMacroEntry *)bp);
102 if (ame == NULL && bme == NULL)
108 return strcmp(ame->name, bme->name);
112 * Enlarge macro table.
113 * @param mc macro context
116 expandMacroTable(rpmMacroContext mc)
118 if (mc->macroTable == NULL) {
119 mc->macrosAllocated = MACRO_CHUNK_SIZE;
120 mc->macroTable = (rpmMacroEntry *)
121 xmalloc(sizeof(*(mc->macroTable)) * mc->macrosAllocated);
124 mc->macrosAllocated += MACRO_CHUNK_SIZE;
125 mc->macroTable = (rpmMacroEntry *)
126 xrealloc(mc->macroTable, sizeof(*(mc->macroTable)) *
127 mc->macrosAllocated);
129 memset(&mc->macroTable[mc->firstFree], 0, MACRO_CHUNK_SIZE * sizeof(*(mc->macroTable)));
133 * Sort entries in macro table.
134 * @param mc macro context
137 sortMacroTable(rpmMacroContext mc)
141 if (mc == NULL || mc->macroTable == NULL)
144 qsort(mc->macroTable, mc->firstFree, sizeof(*(mc->macroTable)),
147 /* Empty pointers are now at end of table. Reset first free index. */
148 for (i = 0; i < mc->firstFree; i++) {
149 if (mc->macroTable[i] != NULL)
157 rpmDumpMacroTable(rpmMacroContext mc, FILE * fp)
162 if (mc == NULL) mc = rpmGlobalMacroContext;
163 if (fp == NULL) fp = stderr;
165 fprintf(fp, "========================\n");
166 if (mc->macroTable != NULL) {
168 for (i = 0; i < mc->firstFree; i++) {
170 if ((me = mc->macroTable[i]) == NULL) {
171 /* XXX this should never happen */
175 fprintf(fp, "%3d%c %s", me->level,
176 (me->used > 0 ? '=' : ':'), me->name);
177 if (me->opts && *me->opts)
178 fprintf(fp, "(%s)", me->opts);
179 if (me->body && *me->body)
180 fprintf(fp, "\t%s", me->body);
185 fprintf(fp, _("======================== active %d empty %d\n"),
190 * Find entry in macro table.
191 * @param mc macro context
192 * @param name macro name
193 * @param namelen no. of bytes
194 * @return address of slot in macro table with name (or NULL)
196 static rpmMacroEntry *
197 findEntry(rpmMacroContext mc, const char * name, size_t namelen)
199 rpmMacroEntry key, *ret;
200 struct rpmMacroEntry_s keybuf;
201 char namebuf[namelen+1];
202 const char *mname = name;
204 if (mc == NULL) mc = rpmGlobalMacroContext;
205 if (mc->macroTable == NULL || mc->firstFree == 0)
209 strncpy(namebuf, name, namelen);
210 namebuf[namelen] = '\0';
215 memset(key, 0, sizeof(*key));
216 key->name = (char *)mname;
217 ret = (rpmMacroEntry *) bsearch(&key, mc->macroTable, mc->firstFree,
218 sizeof(*(mc->macroTable)), compareMacroName);
219 /* XXX TODO: find 1st empty slot and return that */
223 /* =============================================================== */
226 * fgets(3) analogue that reads \ continuations. Last newline always trimmed.
227 * @param buf input buffer
228 * @param size inbut buffer size (bytes)
229 * @param fd file handle
230 * @return buffer, or NULL on end-of-file
233 rdcl(char * buf, size_t size, FILE *f)
235 char *q = buf - 1; /* initialize just before buffer. */
243 *(++q) = '\0'; /* terminate and move forward. */
244 if (fgets(q, size, f) == NULL) /* read next line. */
247 nread += nb; /* trim trailing \r and \n */
248 for (q += nb - 1; nb > 0 && iseol(*q); q--)
250 for (; p <= q; p++) {
260 case '{': p++, bc++; break;
261 case '(': p++, pc++; break;
262 case '%': p++; break;
265 case '{': if (bc > 0) bc++; break;
266 case '}': if (bc > 0) bc--; break;
267 case '(': if (pc > 0) pc++; break;
268 case ')': if (pc > 0) pc--; break;
271 if (nb == 0 || (*q != '\\' && !bc && !pc) || *(q+1) == '\0') {
272 *(++q) = '\0'; /* trim trailing \r, \n */
275 q++; p++; nb++; /* copy newline too */
277 if (*q == '\r') /* XXX avoid \r madness */
280 return (nread > 0 ? buf : NULL);
284 * Return text between pl and matching pr characters.
285 * @param p start of text
286 * @param pl left char, i.e. '[', '(', '{', etc.
287 * @param pr right char, i.e. ']', ')', '}', etc.
288 * @return address of last char before pr (or NULL)
291 matchchar(const char * p, char pl, char pr)
296 while ((c = *p++) != '\0') {
297 if (c == '\\') { /* Ignore escaped chars */
302 if (--lvl <= 0) return --p;
306 return (const char *)NULL;
310 * Pre-print macro expression to be expanded.
311 * @param mb macro expansion state
312 * @param s current expansion string
313 * @param se end of string
316 printMacro(MacroBuf mb, const char * s, const char * se)
319 const char *ellipsis;
322 if (s >= se) { /* XXX just in case */
323 fprintf(stderr, _("%3d>%*s(empty)"), mb->depth,
324 (2 * mb->depth + 1), "");
331 /* Print only to first end-of-line (or end-of-string). */
332 for (senl = se; *senl && !iseol(*senl); senl++)
335 /* Limit trailing non-trace output */
336 choplen = 61 - (2 * mb->depth);
337 if ((senl - s) > choplen) {
343 /* Substitute caret at end-of-macro position */
344 fprintf(stderr, "%3d>%*s%%%.*s^", mb->depth,
345 (2 * mb->depth + 1), "", (int)(se - s), s);
346 if (se[1] != '\0' && (senl - (se+1)) > 0)
347 fprintf(stderr, "%-.*s%s", (int)(senl - (se+1)), se+1, ellipsis);
348 fprintf(stderr, "\n");
352 * Post-print expanded macro expression.
353 * @param mb macro expansion state
354 * @param t current expansion string result
355 * @param te end of string
358 printExpansion(MacroBuf mb, const char * t, const char * te)
360 const char *ellipsis;
364 rpmlog(RPMLOG_DEBUG, _("%3d<%*s(empty)\n"), mb->depth, (2 * mb->depth + 1), "");
368 /* Shorten output which contains newlines */
369 while (te > t && iseol(te[-1]))
375 /* Skip to last line of expansion */
376 while ((tenl = strchr(t, '\n')) && tenl < te)
379 /* Limit expand output */
380 choplen = 61 - (2 * mb->depth);
381 if ((te - t) > choplen) {
387 rpmlog(RPMLOG_DEBUG,"%3d<%*s", mb->depth, (2 * mb->depth + 1), "");
389 rpmlog(RPMLOG_DEBUG, "%.*s%s", (int)(te - t), t, ellipsis);
390 rpmlog(RPMLOG_DEBUG, "\n");
393 #define SKIPBLANK(_s, _c) \
394 while (((_c) = *(_s)) && isblank(_c)) \
397 #define SKIPNONBLANK(_s, _c) \
398 while (((_c) = *(_s)) && !(isblank(_c) || iseol(_c))) \
401 #define COPYNAME(_ne, _s, _c) \
402 { SKIPBLANK(_s,_c); \
403 while(((_c) = *(_s)) && (risalnum(_c) || (_c) == '_')) \
404 *(_ne)++ = *(_s)++; \
408 #define COPYOPTS(_oe, _s, _c) \
410 while(((_c) = *(_s)) && (_c) != ')') \
411 *(_oe)++ = *(_s)++; \
416 * Macro-expand string src, return result in dynamically allocated buffer.
417 * @param mb macro expansion state
418 * @param src string to expand
419 * @param slen input string length (or 0 for strlen())
420 * @retval target pointer to expanded string (malloced)
421 * @return result of expansion
424 expandThis(MacroBuf mb, const char * src, size_t slen, char **target)
426 struct MacroBuf_s umb;
429 /* Copy other state from "parent", but we want a buffer of our own */
432 rc = expandMacro(&umb, src, slen);
438 static void mbAppend(MacroBuf mb, char c)
441 mb->buf = xrealloc(mb->buf, mb->tpos + MACROBUFSIZ + 1);
442 mb->nb += MACROBUFSIZ;
444 mb->buf[mb->tpos++] = c;
445 mb->buf[mb->tpos] = '\0';
449 static void mbAppendStr(MacroBuf mb, const char *str)
451 size_t len = strlen(str);
453 mb->buf = xrealloc(mb->buf, mb->tpos + mb->nb + MACROBUFSIZ + len + 1);
454 mb->nb += MACROBUFSIZ + len;
456 memcpy(mb->buf+mb->tpos, str, len + 1);
461 * Expand output of shell command into target buffer.
462 * @param mb macro expansion state
463 * @param cmd shell command
464 * @param clen no. bytes in shell command
465 * @return result of expansion
468 doShellEscape(MacroBuf mb, const char * cmd, size_t clen)
475 rc = expandThis(mb, cmd, clen, &buf);
479 if ((shf = popen(buf, "r")) == NULL) {
483 while((c = fgetc(shf)) != EOF) {
488 /* XXX delete trailing \r \n */
489 while (iseol(mb->buf[mb->tpos-1])) {
490 mb->buf[mb->tpos--] = '\0';
500 * Parse (and execute) new macro definition.
501 * @param mb macro expansion state
502 * @param se macro definition to parse
503 * @param level macro recursion level
504 * @param expandbody should body be expanded?
505 * @return address to continue parsing
508 doDefine(MacroBuf mb, const char * se, int level, int expandbody)
511 size_t blen = MACROBUFSIZ;
512 char *buf = xmalloc(blen);
513 char *n = buf, *ne = n;
515 char *b, *be, *ebody = NULL;
522 /* Copy opts (if present) */
531 /* Copy body, skipping over escaped newlines */
534 if (c == '{') { /* XXX permit silent {...} grouping */
535 if ((se = matchchar(s, c, '}')) == NULL) {
537 _("Macro %%%s has unterminated body\n"), n);
538 se = s; /* XXX W2DO? */
541 s++; /* XXX skip { */
542 strncpy(b, s, (se - s));
545 se++; /* XXX skip } */
546 s = se; /* move scan forward */
547 } else { /* otherwise free-field */
549 while (*s && (bc || pc || !iseol(*s))) {
559 case '{': *be++ = *s++; bc++; break;
560 case '(': *be++ = *s++; pc++; break;
561 case '%': *be++ = *s++; break;
564 case '{': if (bc > 0) bc++; break;
565 case '}': if (bc > 0) bc--; break;
566 case '(': if (pc > 0) pc++; break;
567 case ')': if (pc > 0) pc--; break;
575 _("Macro %%%s has unterminated body\n"), n);
576 se = s; /* XXX W2DO? */
580 /* Trim trailing blanks/newlines */
581 while (--be >= b && (c = *be) && (isblank(c) || iseol(c)))
583 *(++be) = '\0'; /* one too far */
586 /* Move scan over body */
591 /* Names must start with alphabetic or _ and be at least 3 chars */
592 if (!((c = *n) && (risalpha(c) || c == '_') && (ne - n) > 2)) {
594 _("Macro %%%s has illegal name (%%define)\n"), n);
598 /* Options must be terminated with ')' */
599 if (o && oc != ')') {
600 rpmlog(RPMLOG_ERR, _("Macro %%%s has unterminated opts\n"), n);
605 rpmlog(RPMLOG_ERR, _("Macro %%%s has empty body\n"), n);
610 if (expandThis(mb, b, 0, &ebody)) {
611 rpmlog(RPMLOG_ERR, _("Macro %%%s failed to expand\n"), n);
617 addMacro(mb->mc, n, o, b, (level - 1));
626 * Parse (and execute) macro undefinition.
627 * @param mc macro context
628 * @param se macro name to undefine
629 * @return address to continue parsing
632 doUndefine(rpmMacroContext mc, const char * se)
635 char *buf = xmalloc(MACROBUFSIZ);
636 char *n = buf, *ne = n;
641 /* Move scan over body */
646 /* Names must start with alphabetic or _ and be at least 3 chars */
647 if (!((c = *n) && (risalpha(c) || c == '_') && (ne - n) > 2)) {
649 _("Macro %%%s has illegal name (%%undefine)\n"), n);
661 * Push new macro definition onto macro entry stack.
662 * @param mep address of macro entry slot
663 * @param n macro name
664 * @param o macro parameters (NULL if none)
665 * @param b macro body (NULL becomes "")
666 * @param level macro recursion level
669 pushMacro(rpmMacroEntry * mep,
670 const char * n, const char * o,
671 const char * b, int level)
673 rpmMacroEntry prev = (mep && *mep ? *mep : NULL);
674 rpmMacroEntry me = (rpmMacroEntry) xmalloc(sizeof(*me));
677 me->name = (prev ? prev->name : xstrdup(n));
678 me->opts = (o ? xstrdup(o) : NULL);
679 me->body = xstrdup(b ? b : "");
689 * Pop macro definition from macro entry stack.
690 * @param mep address of macro entry slot
693 popMacro(rpmMacroEntry * mep)
696 rpmMacroEntry me = *mep;
698 /* restore previous definition of the macro */
701 /* name is shared between entries, only free if last of its kind */
702 if (me->prev == NULL)
707 memset(me, 0, sizeof(*me)); /* trash and burn */
713 * Free parsed arguments for parameterized macro.
714 * @param mb macro expansion state
717 freeArgs(MacroBuf mb)
719 rpmMacroContext mc = mb->mc;
723 if (mc == NULL || mc->macroTable == NULL)
726 /* Delete dynamic macro definitions */
727 for (i = 0; i < mc->firstFree; i++) {
728 rpmMacroEntry *mep, me;
730 mep = &mc->macroTable[i];
733 if (me == NULL) /* XXX this should never happen */
735 if (me->level < mb->depth)
737 if (strlen(me->name) == 1 && strchr("#*0", *me->name)) {
738 if (*me->name == '*' && me->used > 0)
739 skiptest = 1; /* XXX skip test for %# %* %0 */
740 } else if (!skiptest && me->used <= 0) {
743 _("Macro %%%s (%s) was not used below level %d\n"),
744 me->name, me->body, me->level);
752 /* If any deleted macros, sort macro table */
758 * Parse arguments (to next new line) for parameterized macro.
759 * @todo Use popt rather than getopt to parse args.
760 * @param mb macro expansion state
761 * @param me macro entry slot
762 * @param se arguments to parse
763 * @param lastc stop parsing at lastc
764 * @return address to continue parsing
767 grabArgs(MacroBuf mb, const rpmMacroEntry me, const char * se,
776 /* Copy macro name as argv[0] */
777 argvAdd(&argv, me->name);
778 addMacro(mb->mc, "0", NULL, me->name, mb->depth);
781 * Make a copy of se up to lastc string that we can pass to argvSplit().
782 * Append the results to main argv.
785 char *s = xcalloc((lastc-se)+1, sizeof(*s));
786 memcpy(s, se, (lastc-se));
788 argvSplit(&av, s, " \t");
789 argvAppend(&argv, av);
796 * The macro %* analoguous to the shell's $* means "Pass all non-macro
797 * parameters." Consequently, there needs to be a macro that means "Pass all
798 * (including macro parameters) options". This is useful for verifying
799 * parameters during expansion and yet transparently passing all parameters
800 * through for higher level processing (e.g. %description and/or %setup).
801 * This is the (potential) justification for %{**} ...
803 args = argvJoin(argv + 1, " ");
804 addMacro(mb->mc, "**", NULL, args, mb->depth);
808 * POSIX states optind must be 1 before any call but glibc uses 0
809 * to (re)initialize getopt structures, eww.
818 argc = argvCount(argv);
820 /* Define option macros. */
821 while((c = getopt(argc, argv, opts)) != -1)
823 char *name = NULL, *body = NULL;
824 if (c == '?' || strchr(opts, c) == NULL) {
825 rpmlog(RPMLOG_ERR, _("Unknown option %c in %s(%s)\n"),
826 (char)optopt, me->name, opts);
830 rasprintf(&name, "-%c", c);
832 rasprintf(&body, "-%c %s", c, optarg);
834 rasprintf(&body, "-%c", c);
836 addMacro(mb->mc, name, NULL, body, mb->depth);
841 rasprintf(&name, "-%c*", c);
842 addMacro(mb->mc, name, NULL, optarg, mb->depth);
847 /* Add argument count (remaining non-option items) as macro. */
849 rasprintf(&ac, "%d", (argc - optind));
850 addMacro(mb->mc, "#", NULL, ac, mb->depth);
854 /* Add macro for each argument */
856 for (c = optind; c < argc; c++) {
858 rasprintf(&name, "%d", (c - optind + 1));
859 addMacro(mb->mc, name, NULL, argv[c], mb->depth);
864 /* Add concatenated unexpanded arguments as yet another macro. */
865 args = argvJoin(argv + optind, " ");
866 addMacro(mb->mc, "*", NULL, args ? args : "", mb->depth);
871 return *lastc ? lastc + 1 : lastc;
875 * Perform macro message output
876 * @param mb macro expansion state
877 * @param waserror use rpmlog()?
878 * @param msg message to ouput
879 * @param msglen no. of bytes in message
882 doOutput(MacroBuf mb, int waserror, const char * msg, size_t msglen)
886 (void) expandThis(mb, msg, msglen, &buf);
888 rpmlog(RPMLOG_ERR, "%s\n", buf);
890 fprintf(stderr, "%s", buf);
895 * Execute macro primitives.
896 * @param mb macro expansion state
897 * @param negate should logic be inverted?
898 * @param f beginning of field f
899 * @param fn length of field f
900 * @param g beginning of field g
901 * @param gn length of field g
904 doFoo(MacroBuf mb, int negate, const char * f, size_t fn,
905 const char * g, size_t gn)
912 (void) expandThis(mb, g, gn, &buf);
914 buf = xmalloc(MACROBUFSIZ + fn + gn);
917 if (STREQ("basename", f, fn)) {
918 if ((b = strrchr(buf, '/')) == NULL)
922 } else if (STREQ("dirname", f, fn)) {
923 if ((b = strrchr(buf, '/')) != NULL)
926 } else if (STREQ("suffix", f, fn)) {
927 if ((b = strrchr(buf, '.')) != NULL)
929 } else if (STREQ("expand", f, fn)) {
931 } else if (STREQ("verbose", f, fn)) {
933 b = (rpmIsVerbose() ? NULL : buf);
935 b = (rpmIsVerbose() ? buf : NULL);
936 } else if (STREQ("url2path", f, fn) || STREQ("u2p", f, fn)) {
937 (void)urlPath(buf, (const char **)&b);
938 if (*b == '\0') b = "/";
939 } else if (STREQ("uncompress", f, fn)) {
940 rpmCompressedMagic compressed = COMPRESSED_OTHER;
941 for (b = buf; (c = *b) && isblank(c);)
943 for (be = b; (c = *be) && !isblank(c);)
946 (void) rpmFileIsCompressed(b, &compressed);
950 sprintf(be, "%%__cat %s", b);
952 case COMPRESSED_OTHER:
953 sprintf(be, "%%__gzip -dc %s", b);
955 case COMPRESSED_BZIP2:
956 sprintf(be, "%%__bzip2 -dc %s", b);
959 sprintf(be, "%%__unzip %s", b);
961 case COMPRESSED_LZMA:
963 sprintf(be, "%%__xz -dc %s", b);
965 case COMPRESSED_LZIP:
966 sprintf(be, "%%__lzip -dc %s", b);
968 case COMPRESSED_LRZIP:
969 sprintf(be, "%%__lrzip -dqo- %s", b);
971 case COMPRESSED_7ZIP:
972 sprintf(be, "%%__7zip x %s", b);
976 } else if (STREQ("getenv", f, fn)) {
978 } else if (STREQ("getconfdir", f, fn)) {
979 sprintf(buf, "%s", rpmConfigDir());
981 } else if (STREQ("S", f, fn)) {
982 for (b = buf; (c = *b) && risdigit(c);)
984 if (!c) { /* digit index */
986 sprintf(b, "%%SOURCE%s", buf);
989 } else if (STREQ("P", f, fn)) {
990 for (b = buf; (c = *b) && risdigit(c);)
992 if (!c) { /* digit index */
994 sprintf(b, "%%PATCH%s", buf);
997 } else if (STREQ("F", f, fn)) {
998 b = buf + strlen(buf) + 1;
999 sprintf(b, "file%s.file", buf);
1003 (void) expandMacro(mb, b, 0);
1009 * The main macro recursion loop.
1010 * @param mb macro expansion state
1011 * @param src string to expand
1012 * @return 0 on success, 1 on failure
1015 expandMacro(MacroBuf mb, const char *src, size_t slen)
1019 const char *s = src, *se;
1022 size_t fn, gn, tpos;
1028 char *source = NULL;
1030 /* Handle non-terminated substrings by creating a terminated copy */
1033 source = xmalloc(slen + 1);
1034 strncpy(source, src, slen);
1035 source[slen] = '\0';
1038 if (mb->buf == NULL) {
1039 size_t blen = MACROBUFSIZ + strlen(s);
1040 mb->buf = xcalloc(blen + 1, sizeof(*mb->buf));
1044 tpos = mb->tpos; /* save expansion pointer for printExpand */
1046 if (++mb->depth > max_macro_depth) {
1048 _("Too many levels of recursion in macro expansion. It is likely caused by recursive macro declaration.\n"));
1050 mb->expand_trace = 1;
1055 while (rc == 0 && (c = *s) != '\0') {
1057 /* Copy text until next macro */
1060 if (*s) { /* Ensure not end-of-string. */
1063 s++; /* skip first % in %% */
1071 /* Expand next macro */
1074 if (mb->depth > 1) /* XXX full expansion for outermost level */
1075 tpos = mb->tpos; /* save expansion pointer for printExpand */
1080 default: /* %name substitution */
1081 while (strchr("!?", *s) != NULL) {
1084 negate = ((negate + 1) % 2);
1094 while((c = *se) && (risalnum(c) || c == '_'))
1096 /* Recognize non-alnum macros too */
1100 if (*se == '*') se++;
1109 /* For "%name " macros ... */
1110 if ((c = *fe) && isblank(c))
1111 if ((lastc = strchr(fe,'\n')) == NULL)
1112 lastc = strchr(fe, '\0');
1114 case '(': /* %(...) shell escape */
1115 if ((se = matchchar(s, c, ')')) == NULL) {
1117 _("Unterminated %c: %s\n"), (char)c, s);
1121 if (mb->macro_trace)
1122 printMacro(mb, s, se+1);
1125 rc = doShellEscape(mb, s, (se - s));
1131 case '{': /* %{...}/%{...:...} substitution */
1132 if ((se = matchchar(s, c, '}')) == NULL) {
1134 _("Unterminated %c: %s\n"), (char)c, s);
1138 f = s+1;/* skip { */
1140 while (strchr("!?", *f) != NULL) {
1143 negate = ((negate + 1) % 2);
1150 for (fe = f; (c = *fe) && !strchr(" :}", c);)
1166 /* XXX Everything below expects fe > f */
1169 if ((fe - f) <= 0) {
1170 /* XXX Process % in unknown context */
1171 c = '%'; /* XXX only need to save % */
1175 _("A %% is followed by an unparseable macro\n"));
1181 if (mb->macro_trace)
1182 printMacro(mb, s, se);
1184 /* Expand builtin macros */
1185 if (STREQ("global", f, fn)) {
1186 s = doDefine(mb, se, RMIL_GLOBAL, 1);
1189 if (STREQ("define", f, fn)) {
1190 s = doDefine(mb, se, mb->depth, 0);
1193 if (STREQ("undefine", f, fn)) {
1194 s = doUndefine(mb->mc, se);
1198 if (STREQ("echo", f, fn) ||
1199 STREQ("warn", f, fn) ||
1200 STREQ("error", f, fn)) {
1202 if (STREQ("error", f, fn))
1204 if (g != NULL && g < ge)
1205 doOutput(mb, waserror, g, gn);
1207 doOutput(mb, waserror, f, fn);
1212 if (STREQ("trace", f, fn)) {
1213 /* XXX TODO restore expand_trace/macro_trace to 0 on return */
1214 mb->expand_trace = mb->macro_trace = (negate ? 0 : mb->depth);
1215 if (mb->depth == 1) {
1216 print_macro_trace = mb->macro_trace;
1217 print_expand_trace = mb->expand_trace;
1223 if (STREQ("dump", f, fn)) {
1224 rpmDumpMacroTable(mb->mc, NULL);
1232 if (STREQ("lua", f, fn)) {
1233 rpmlua lua = NULL; /* Global state. */
1234 const char *ls = s+sizeof("{lua:")-1;
1235 const char *lse = se-sizeof("}")+1;
1236 char *scriptbuf = (char *)xmalloc((lse-ls)+1);
1238 memcpy(scriptbuf, ls, lse-ls);
1239 scriptbuf[lse-ls] = '\0';
1240 rpmluaPushPrintBuffer(lua);
1241 if (rpmluaRunScript(lua, scriptbuf, NULL) == -1)
1243 printbuf = rpmluaPopPrintBuffer(lua);
1245 mbAppendStr(mb, printbuf);
1254 /* XXX necessary but clunky */
1255 if (STREQ("basename", f, fn) ||
1256 STREQ("dirname", f, fn) ||
1257 STREQ("suffix", f, fn) ||
1258 STREQ("expand", f, fn) ||
1259 STREQ("verbose", f, fn) ||
1260 STREQ("uncompress", f, fn) ||
1261 STREQ("url2path", f, fn) ||
1262 STREQ("u2p", f, fn) ||
1263 STREQ("getenv", f, fn) ||
1264 STREQ("getconfdir", f, fn) ||
1265 STREQ("S", f, fn) ||
1266 STREQ("P", f, fn) ||
1267 STREQ("F", f, fn)) {
1268 /* FIX: verbose may be set */
1269 doFoo(mb, negate, f, fn, g, gn);
1274 /* Expand defined macros */
1275 mep = findEntry(mb->mc, f, fn);
1276 me = (mep ? *mep : NULL);
1278 /* XXX Special processing for flags */
1281 me->used++; /* Mark macro as used */
1282 if ((me == NULL && !negate) || /* Without -f, skip %{-f...} */
1283 (me != NULL && negate)) { /* With -f, skip %{!-f...} */
1288 if (g && g < ge) { /* Expand X in %{-f:X} */
1289 rc = expandMacro(mb, g, gn);
1291 if (me && me->body && *me->body) {/* Expand %{-f}/%{-f*} */
1292 rc = expandMacro(mb, me->body, 0);
1298 /* XXX Special processing for macro existence */
1300 if ((me == NULL && !negate) || /* Without -f, skip %{?f...} */
1301 (me != NULL && negate)) { /* With -f, skip %{!?f...} */
1305 if (g && g < ge) { /* Expand X in %{?f:X} */
1306 rc = expandMacro(mb, g, gn);
1308 if (me && me->body && *me->body) { /* Expand %{?f}/%{?f*} */
1309 rc = expandMacro(mb, me->body, 0);
1315 if (me == NULL) { /* leave unknown %... as is */
1316 /* XXX hack to permit non-overloaded %foo to be passed */
1317 c = '%'; /* XXX only need to save % */
1322 /* Setup args for "%name " macros with opts */
1323 if (me && me->opts != NULL) {
1324 if (lastc != NULL) {
1325 se = grabArgs(mb, me, fe, lastc);
1327 addMacro(mb->mc, "**", NULL, "", mb->depth);
1328 addMacro(mb->mc, "*", NULL, "", mb->depth);
1329 addMacro(mb->mc, "#", NULL, "0", mb->depth);
1330 addMacro(mb->mc, "0", NULL, me->name, mb->depth);
1334 /* Recursively expand body of macro */
1335 if (me->body && *me->body) {
1336 rc = expandMacro(mb, me->body, 0);
1338 me->used++; /* Mark macro as used */
1341 /* Free args for "%name " macros with opts */
1342 if (me->opts != NULL)
1348 mb->buf[mb->tpos] = '\0';
1350 if (rc != 0 || mb->expand_trace)
1351 printExpansion(mb, mb->buf+tpos, mb->buf+mb->tpos);
1357 /* =============================================================== */
1359 static int doExpandMacros(rpmMacroContext mc, const char *src, char **target)
1361 MacroBuf mb = xcalloc(1, sizeof(*mb));
1364 if (mc == NULL) mc = rpmGlobalMacroContext;
1368 mb->macro_trace = print_macro_trace;
1369 mb->expand_trace = print_expand_trace;
1372 rc = expandMacro(mb, src, 0);
1374 mb->buf[mb->tpos] = '\0'; /* XXX just in case */
1375 /* expanded output is usually much less than alloced buffer, downsize */
1376 *target = xrealloc(mb->buf, mb->tpos + 1);
1382 int expandMacros(void * spec, rpmMacroContext mc, char * sbuf, size_t slen)
1384 char *target = NULL;
1385 int rc = doExpandMacros(mc, sbuf, &target);
1386 rstrlcpy(sbuf, target, slen);
1392 addMacro(rpmMacroContext mc,
1393 const char * n, const char * o, const char * b, int level)
1395 rpmMacroEntry * mep;
1397 if (mc == NULL) mc = rpmGlobalMacroContext;
1399 /* If new name, expand macro table */
1400 if ((mep = findEntry(mc, n, 0)) == NULL) {
1401 if (mc->firstFree == mc->macrosAllocated)
1402 expandMacroTable(mc);
1403 if (mc->macroTable != NULL)
1404 mep = mc->macroTable + mc->firstFree++;
1408 /* Push macro over previous definition */
1409 pushMacro(mep, n, o, b, level);
1411 /* If new name, sort macro table */
1412 if ((*mep)->prev == NULL)
1418 delMacro(rpmMacroContext mc, const char * n)
1420 rpmMacroEntry * mep;
1422 if (mc == NULL) mc = rpmGlobalMacroContext;
1423 /* If name exists, pop entry */
1424 if ((mep = findEntry(mc, n, 0)) != NULL) {
1426 /* If deleted name, sort macro table */
1433 rpmDefineMacro(rpmMacroContext mc, const char * macro, int level)
1435 MacroBuf mb = xcalloc(1, sizeof(*mb));
1437 /* XXX just enough to get by */
1438 mb->mc = (mc ? mc : rpmGlobalMacroContext);
1439 (void) doDefine(mb, macro, level, 0);
1445 rpmLoadMacros(rpmMacroContext mc, int level)
1448 if (mc == NULL || mc == rpmGlobalMacroContext)
1451 if (mc->macroTable != NULL) {
1453 for (i = 0; i < mc->firstFree; i++) {
1454 rpmMacroEntry *mep, me;
1455 mep = &mc->macroTable[i];
1458 if (me == NULL) /* XXX this should never happen */
1460 addMacro(NULL, me->name, me->opts, me->body, (level - 1));
1466 rpmLoadMacroFile(rpmMacroContext mc, const char * fn)
1468 FILE *fd = fopen(fn, "r");
1469 size_t blen = MACROBUFSIZ;
1470 char *buf = xmalloc(blen);
1476 /* XXX Assume new fangled macro expansion */
1477 max_macro_depth = 16;
1480 while(rdcl(buf, blen, fd) != NULL) {
1489 rc = rpmDefineMacro(mc, n, RMIL_MACROFILES);
1499 rpmInitMacros(rpmMacroContext mc, const char * macrofiles)
1501 ARGV_t pattern, globs = NULL;
1503 if (macrofiles == NULL)
1506 argvSplit(&globs, macrofiles, ":");
1507 for (pattern = globs; *pattern; pattern++) {
1508 ARGV_t path, files = NULL;
1510 /* Glob expand the macro file path element, expanding ~ to $HOME. */
1511 if (rpmGlob(*pattern, NULL, &files) != 0) {
1515 /* Read macros from each file. */
1516 for (path = files; *path; path++) {
1517 if (rpmFileHasSuffix(*path, ".rpmnew") ||
1518 rpmFileHasSuffix(*path, ".rpmsave") ||
1519 rpmFileHasSuffix(*path, ".rpmorig")) {
1522 (void) rpmLoadMacroFile(mc, *path);
1528 /* Reload cmdline macros */
1529 rpmLoadMacros(rpmCLIMacroContext, RMIL_CMDLINE);
1533 rpmFreeMacros(rpmMacroContext mc)
1536 if (mc == NULL) mc = rpmGlobalMacroContext;
1538 if (mc->macroTable != NULL) {
1539 for (int i = 0; i < mc->firstFree; i++) {
1540 while (mc->macroTable[i] != NULL) {
1541 popMacro(&mc->macroTable[i]);
1544 free(mc->macroTable);
1546 memset(mc, 0, sizeof(*mc));
1550 rpmExpand(const char *arg, ...)
1553 char *buf = NULL, *ret = NULL;
1563 /* precalculate unexpanded size */
1565 for (s = arg; s != NULL; s = va_arg(ap, const char *))
1569 buf = xmalloc(blen + 1);
1573 for (pe = buf, s = arg; s != NULL; s = va_arg(ap, const char *))
1577 (void) doExpandMacros(NULL, buf, &ret);
1585 rpmExpandNumeric(const char *arg)
1593 val = rpmExpand(arg, NULL);
1594 if (!(val && *val != '%'))
1596 else if (*val == 'Y' || *val == 'y')
1598 else if (*val == 'N' || *val == 'n')
1602 rc = strtol(val, &end, 0);
1603 if (!(end && *end == '\0'))