1 /* $Header: /src/pub/tcsh/sh.dol.c,v 3.45 2000/11/19 20:50:43 christos Exp $ */
3 * sh.dol.c: Variable substitutions
6 * Copyright (c) 1980, 1991 The Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 RCSID("$Id: sh.dol.c,v 3.45 2000/11/19 20:50:43 christos Exp $")
46 * These routines perform variable substitution and quoting via ' and ".
47 * To this point these constructs have been preserved in the divided
48 * input words. Here we expand variables and turn quoting via ' and " into
49 * QUOTE bits on characters (which prevent further interpretation).
50 * If the `:q' modifier was applied during history expansion, then
51 * some QUOTEing may have occurred already, so we dont "trim()" here.
54 static int Dpeekc, Dpeekrd; /* Peeks for DgetC and Dreadc */
55 static Char *Dcp, **Dvp; /* Input vector for Dreadc */
59 #define unDgetC(c) Dpeekc = c
61 #define QUOTES (_QF|_QB|_ESC) /* \ ' " ` */
64 * The following variables give the information about the current
65 * $ expansion, recording the current word position, the remaining
66 * words within this expansion, the count of remaining words, and the
67 * information about any : modifier which is being applied.
69 #define MAXWLEN (BUFSIZE - 4)
71 #define MAXMOD MAXWLEN /* This cannot overflow */
73 static Char *dolp; /* Remaining chars from this word */
74 static Char **dolnxt; /* Further words */
75 static int dolcnt; /* Count of further words */
77 static Char dolmod; /* : modifier character */
79 static Char dolmod[MAXMOD]; /* : modifier character */
80 static int dolnmod; /* Number of modifiers */
82 static int dolmcnt; /* :gx -> 10000, else 1 */
83 static int dolwcnt; /* :ax -> 10000, else 1 */
85 static void Dfix2 __P((Char **));
86 static Char *Dpack __P((Char *, Char *));
87 static int Dword __P((void));
88 static void dolerror __P((Char *));
89 static int DgetC __P((int));
90 static void Dgetdol __P((void));
91 static void fixDolMod __P((void));
92 static void setDolp __P((Char *));
93 static void unDredc __P((int));
94 static int Dredc __P((void));
95 static void Dtestq __P((int));
98 * Fix up the $ expansions and quotations in the
99 * argument list to command t.
103 register struct command *t;
110 /* Note that t_dcom isn't trimmed thus !...:q's aren't lost */
111 for (pp = t->t_dcom; (p = *pp++) != NULL;) {
114 if (Ismbyte1(*p) && *(p + 1))
118 if (cmap(*p, _DOL | QUOTES)) { /* $, \, ', ", ` */
119 Dfix2(t->t_dcom); /* found one */
130 * $ substitute one word, for i/o redirection
144 setname(short2str(cp));
145 stderror(ERR_NAME | ERR_AMBIG);
147 cp = Strsave(gargv[0]);
148 blkfree(gargv), gargv = 0;
153 * Subroutine to do actual fixing after state initialization.
159 ginit(); /* Initialize glob's area pointers */
161 Dcp = STRNULL; /* Setup input vector for Dreadc */
163 unDredc(0); /* Clear out any old peeks (at error) */
165 dolcnt = 0; /* Clear out residual $ expands (...) */
171 * Pack up more characters in this word
178 register int i = MAXWLEN - (int) (wp - wbuf);
179 #if defined(DSPMBYTE)
181 #endif /* DSPMBYTE */
185 #if defined(DSPMBYTE)
186 if (mbytepos == 1 && Ismbyte1(c)) {
187 /* An MB1 byte that may be followed by a MB2 byte */
191 /* check if MB1 byte followed by an MB2 byte */
192 if (mbytepos == 2 && Ismbyte2(c)) {
193 /* MB1 + MB2 make the character */
194 mbytepos = 1; /* reset */
197 mbytepos = 1; /* reset */
198 /* wasn't followed, so the two bytes make two characters */
200 #endif /* DSPMBYTE */
220 if (cmap(c, _SP | _NL | _QF | _QB)) { /* sp \t\n'"` */
228 #if defined(DSPMBYTE)
230 #endif /* DSPMBYTE */
232 stderror(ERR_WTOOLONG);
238 * Get a word. This routine is analogous to the routine
239 * word() in sh.lex.c for the main lexical input. One difference
240 * here is that we don't get a newline to terminate our expansion.
241 * Rather, DgetC will return a DEOF when we hit the end-of-input.
248 register Char *wp = wbuf;
249 register int i = MAXWLEN;
250 register bool dolflg;
251 bool sofar = 0, done = 0;
261 /* finish this word and catch the code above the next time */
276 /* We preserve ` quotations which are done yet later */
277 *wp++ = (Char) c, --i;
282 * Note that DgetC never returns a QUOTES character from an
283 * expansion, so only true input quotes will get us here or out.
286 dolflg = c1 == '"' ? DODOL : 0;
291 if (c == '\n' || c == DEOF)
292 stderror(ERR_UNMATCHED, c1);
293 if ((c & (QUOTE | TRIM)) == ('\n' | QUOTE)) {
294 if ((wp[-1] & TRIM) == '\\')
299 stderror(ERR_WTOOLONG);
304 * Leave any `s alone for later. Other chars are all
305 * quoted, thus `...` can tell it was within "...".
307 *wp++ = c == '`' ? '`' : c | QUOTE;
311 /* Prevent all further interpretation */
316 /* Leave all text alone for later */
325 *wp++ = '`' /* i--; eliminated */;
327 if ((wp = Dpack(wbuf, wp)) == NULL)
332 * Avoid a nasty message from the RTU 4.1A & RTU 5.0 compiler concerning
333 * the "overuse of registers". According to the compiler release notes,
334 * incorrect code may be produced unless the offending expression is
335 * rewritten. Therefore, we can't just ignore it, DAS DEC-90.
338 i -= (int) (wp - wbuf);
339 #else /* !masscomp */
340 i = MAXWLEN - (int) (wp - wbuf);
341 #endif /* masscomp */
347 c = DgetC(0); /* No $ subst! */
348 if (c == '\n' || c == DEOF) {
361 if ((wp = Dpack(wbuf, wp)) == NULL)
366 * Avoid a nasty message from the RTU 4.1A & RTU 5.0 compiler concerning
367 * the "overuse of registers". According to the compiler release notes,
368 * incorrect code may be produced unless the offending expression is
369 * rewritten. Therefore, we can't just ignore it, DAS DEC-90.
372 i -= (int) (wp - wbuf);
373 #else /* !masscomp */
374 i = MAXWLEN - (int) (wp - wbuf);
375 #endif /* masscomp */
380 /* Really NOTREACHED */
386 * Get a character, performing $ substitution unless flag is 0.
387 * Any QUOTES character which is returned from a $ expansion is
388 * QUOTEd so that it will not be recognized above.
397 if ((c = Dpeekc) != 0) {
402 c = *lap++ & (QUOTE | TRIM);
413 if ((c = *dolp++ & (QUOTE | TRIM)) != 0)
428 if (c == '$' && flag) {
435 static Char *nulvec[] = { NULL };
436 static struct varent nulargv = {nulvec, STRargv, VAR_READWRITE,
437 { NULL, NULL, NULL }, 0 };
443 setname(short2str(s));
444 stderror(ERR_NAME | ERR_RANGE);
448 * Handle the multitudinous $ expansion forms.
455 register struct varent *vp = NULL;
456 Char name[4 * MAXVARLEN + 1];
458 int subscr = 0, lwb = 1, upb = 0;
459 bool dimen = 0, bitset = 0, length = 0;
462 static Char *dolbang = NULL;
465 dolmod = dolmcnt = dolwcnt = 0;
467 dolnmod = dolmcnt = dolwcnt = 0;
471 c = DgetC(0); /* sc is { to take } later */
472 if ((c & TRIM) == '#')
473 dimen++, c = DgetC(0); /* $# takes dimension */
475 bitset++, c = DgetC(0); /* $? tests existence */
477 length++, c = DgetC(0); /* $% returns length in chars */
481 if (dimen || bitset || length)
482 stderror(ERR_SYNTAX);
485 xfree((ptr_t) dolbang);
486 setDolp(dolbang = putn(backpid));
491 if (dimen || bitset || length)
492 stderror(ERR_SYNTAX);
497 /* Coherent compiler doesn't allow case-labels that are not
498 constant-expressions */
501 #else /* !SHORT_STRINGS */
504 #else /* !COHERENT */
508 stderror(ERR_NOTALLOWED, "$?<");
510 stderror(ERR_NOTALLOWED, "$#<");
512 stderror(ERR_NOTALLOWED, "$%<");
515 sigmask_t omask = sigsetmask(sigblock(0) & ~sigmask(SIGINT));
517 (void) sigrelse(SIGINT);
519 for (np = wbuf; force_read(OLDSTD, &tnp, 1) == 1; np++) {
520 *np = (unsigned char) tnp;
521 if (np >= &wbuf[BUFSIZE - 1])
522 stderror(ERR_LTOOLONG);
528 (void) sigsetmask(omask);
530 (void) sighold(SIGINT);
536 * KLUDGE: dolmod is set here because it will cause setDolp to call
537 * domod and thus to copy wbuf. Otherwise setDolp would use it
538 * directly. If we saved it ourselves, no one would know when to free
539 * it. The actual function of the 'q' causes filename expansion not to
540 * be done on the interpolated value.
543 * If we do that, then other modifiers don't work.
544 * in addition, let the user specify :q if wanted
547 /*old*/ dolmod = 'q';
548 /*new*/ dolmod[dolnmod++] = 'q';
557 (void) Strcpy(name, STRargv);
559 subscr = -1; /* Prevent eating [...] */
564 np = dimen ? STRargv : (bitset ? STRstatus : NULL);
567 (void) Strcpy(name, np);
569 subscr = -1; /* Prevent eating [...] */
574 stderror(ERR_SYNTAX);
581 stderror(ERR_NOTALLOWED, "$#<num>");
584 subscr = subscr * 10 + c - '0';
586 } while (Isdigit(c));
589 dolerror(vp->v_name);
594 dolp = dolzero ? STR1 : STR0;
598 stderror(ERR_DOLZERO);
601 length = Strlen(ffile);
614 stderror(ERR_NOTALLOWED, "$?<num>");
616 stderror(ERR_NOTALLOWED, "$%<num>");
626 np = dimen ? STRargv : (bitset ? STRstatus : NULL);
629 (void) Strcpy(name, np);
631 subscr = -1; /* Prevent eating [...] */
636 stderror(ERR_VARALNUM);
643 if (np >= &name[MAXVARLEN])
644 stderror(ERR_VARTOOLONG);
651 dolp = (vp || getenv(short2str(name))) ? STR1 : STR0;
655 np = str2short(getenv(short2str(name)));
665 upb = blklen(vp->vec);
666 if (dimen == 0 && subscr == 0 && c == '[') {
669 c = DgetC(DODOL); /* Allow $ expand within [ ] */
672 if (c == '\n' || c == DEOF)
674 if (np >= &name[sizeof(name) / sizeof(Char) - 2])
675 stderror(ERR_VARTOOLONG);
679 if (dolp || dolcnt) /* $ exp must end before ] */
680 stderror(ERR_EXPORD);
682 stderror(ERR_SYNTAX);
686 for (i = 0; Isdigit(*np); i = i * 10 + *np++ - '0')
688 if ((i < 0 || i > upb) && !any("-*", *np)) {
689 dolerror(vp->v_name);
694 upb = lwb, np = STRstar;
699 stderror(ERR_MISSING, '-');
701 register int i = upb;
707 i = i * 10 + *np++ - '0';
708 if (i < 0 || i > upb) {
709 dolerror(vp->v_name);
720 dolerror(vp->v_name);
726 stderror(ERR_SYNTAX);
738 Char *cp = putn(upb - lwb + 1);
740 /* this is a kludge. It prevents Dgetdol() from */
741 /* pushing erroneous ${#<error> values into the labuf. */
747 stderror(ERR_MISSING, '}');
758 for (i = lwb - 1, length = 0; i < upb; i++)
759 length += Strlen(vp->vec[i]);
761 /* We don't want that, since we can always compute it by adding $#xxx */
762 length += i - 1; /* Add the number of spaces in */
771 dolnxt = &vp->vec[lwb - 1];
772 dolcnt = upb - lwb + 1;
778 stderror(ERR_MISSING, '}');
792 c = DgetC(0), dolmcnt = 1, dolwcnt = 1;
793 if (c == 'g' || c == 'a') {
800 if ((c == 'g' && dolmcnt != 10000) ||
801 (c == 'a' && dolwcnt != 10000)) {
809 if (c == 's') { /* [eichin:19910926.0755EST] */
811 int delim = DgetC(0);
812 dolmod[dolnmod++] = (Char) c;
813 dolmod[dolnmod++] = (Char) delim;
815 if (!delim || letter(delim)
816 || Isdigit(delim) || any(" \t\n", delim)) {
817 seterror(ERR_BADSUBST);
820 while ((c = DgetC(0)) != (-1)) {
821 dolmod[dolnmod++] = (Char) c;
822 if(c == delim) delimcnt--;
826 seterror(ERR_BADSUBST);
831 if (!any("luhtrqxes", c))
832 stderror(ERR_BADMOD, c);
834 dolmod[dolnmod++] = (Char) c;
842 while ((c = DgetC(0)) == ':');
860 if (dolmod == 0 || dolmcnt == 0) {
862 if (dolnmod == 0 || dolmcnt == 0) {
868 dp = domod(cp, dolmod);
870 dp = cp = Strsave(cp);
871 for (i = 0; i < dolnmod; i++) {
872 /* handle s// [eichin:19910926.0510EST] */
873 if(dolmod[i] == 's') {
875 Char *lhsub, *rhsub, *np;
876 size_t lhlen = 0, rhlen = 0;
880 if (!delim || letter(delim)
881 || Isdigit(delim) || any(" \t\n", delim)) {
882 seterror(ERR_BADSUBST);
885 lhsub = &dolmod[++i];
886 while(dolmod[i] != delim && dolmod[++i]) {
890 rhsub = &dolmod[++i];
891 while(dolmod[i] != delim && dolmod[++i]) {
899 dp = Strstr(cp, lhsub);
901 np = (Char *) xmalloc((size_t)
902 ((Strlen(cp) + 1 - lhlen + rhlen) *
904 (void) Strncpy(np, cp, (size_t) (dp - cp));
905 (void) Strcpy(np + (dp - cp), rhsub);
906 (void) Strcpy(np + (dp - cp) + rhlen, dp + lhlen);
912 /* should this do a seterror? */
916 while (dolwcnt == 10000);
918 * restore dolmod for additional words
920 dolmod[i] = rhsub[-1] = (Char) delim;
931 if ((dp = domod(cp, dolmod[i])) != NULL) {
933 if (Strcmp(cp, dp) == 0) {
946 while (dolwcnt == 10000);
988 if ((c = Dpeekrd) != 0) {
992 if (Dcp && (c = *Dcp++))
993 return (c & (QUOTE | TRIM));
1007 if (cmap(c, QUOTES))
1012 * Form a shell temporary file (in unit 0) from the words
1013 * of the shell input up to EOF or a line the same as "term".
1014 * Unit 0 should have been closed before this call.
1022 Char obuf[BUFSIZE], lbuf[BUFSIZE], mbuf[BUFSIZE];
1023 int ocnt, lcnt, mcnt;
1024 register Char *lbp, *obp, *mbp;
1028 #ifndef WINNT_NATIVE
1032 #endif /* WINNT_NATIVE */
1033 tmp = short2str(shtemp);
1036 if (creat(tmp, 0600) < 0)
1037 stderror(ERR_SYSTEM, tmp, strerror(errno));
1041 # define O_TEMPORARY 0
1046 if (open(tmp, O_RDWR|O_CREAT|O_EXCL|O_TEMPORARY) == -1) {
1048 #ifndef WINNT_NATIVE
1049 if (errno == EEXIST) {
1050 if (unlink(tmp) == -1) {
1051 (void) gettimeofday(&tv, NULL);
1052 shtemp = Strspl(STRtmpsh, putn((((int)tv.tv_sec) ^
1053 ((int)tv.tv_usec) ^ ((int)getpid())) & 0x00ffffff));
1057 #endif /* WINNT_NATIVE */
1060 stderror(ERR_SYSTEM, tmp, strerror(errno));
1062 (void) unlink(tmp); /* 0 0 inode! */
1074 #endif /* WINNT_NATIVE */
1082 c = readc(1); /* 1 -> Want EOF returns */
1083 if (c < 0 || c == '\n')
1085 if ((c &= TRIM) != 0) {
1089 stderror(ERR_NAME | ERR_OVERFLOW);
1096 * Check for EOF or compare to terminator -- before expansion
1098 if (c < 0 || eq(lbuf, term)) {
1099 (void) write(0, short2str(obuf), (size_t) (BUFSIZE - ocnt));
1100 (void) lseek(0, (off_t) 0, L_SET);
1106 * If term was quoted or -n just pass it on
1108 if (quoted || noexec) {
1111 for (lbp = lbuf; (c = *lbp++) != 0;) {
1114 (void) write(0, short2str(obuf), BUFSIZE);
1123 * Term wasn't quoted so variable and then command expand the input
1134 if ((c &= TRIM) == 0)
1136 /* \ quotes \ $ ` here */
1139 if (!any("$\\`", c))
1140 unDgetC(c | QUOTE), c = '\\';
1147 stderror(ERR_NAME | ERR_OVERFLOW);
1153 * If any ` in line do command substitution
1156 if (Strchr(mbp, '`') != NULL) {
1158 * 1 arg to dobackp causes substitution to be literal. Words are
1159 * broken only at newlines so that all blanks and tabs are
1160 * preserved. Blank lines (null words) are not discarded.
1162 vp = dobackp(mbuf, 1);
1165 /* Setup trivial vector similar to return of dobackp */
1166 Dv[0] = mbp, Dv[1] = NULL, vp = Dv;
1169 * Resurrect the words from the command substitution each separated by
1170 * a newline. Note that the last newline of a command substitution
1171 * will have been discarded, but we put a newline after the last word
1172 * because this represents the newline after the last input line!
1175 for (mbp = *vp; *mbp; mbp++) {
1176 *obp++ = *mbp & TRIM;
1178 (void) write(0, short2str(obuf), BUFSIZE);
1185 (void) write(0, short2str(obuf), BUFSIZE);
1191 blkfree(pargv), pargv = 0;