1 /* $Header: /src/pub/tcsh/sh.dol.c,v 3.50 2002/06/25 19:02:11 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. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 RCSID("$Id: sh.dol.c,v 3.50 2002/06/25 19:02:11 christos Exp $")
42 * These routines perform variable substitution and quoting via ' and ".
43 * To this point these constructs have been preserved in the divided
44 * input words. Here we expand variables and turn quoting via ' and " into
45 * QUOTE bits on characters (which prevent further interpretation).
46 * If the `:q' modifier was applied during history expansion, then
47 * some QUOTEing may have occurred already, so we dont "trim()" here.
50 static int Dpeekc, Dpeekrd; /* Peeks for DgetC and Dreadc */
51 static Char *Dcp, **Dvp; /* Input vector for Dreadc */
55 #define unDgetC(c) Dpeekc = c
57 #define QUOTES (_QF|_QB|_ESC) /* \ ' " ` */
60 * The following variables give the information about the current
61 * $ expansion, recording the current word position, the remaining
62 * words within this expansion, the count of remaining words, and the
63 * information about any : modifier which is being applied.
65 #define MAXWLEN (BUFSIZE - 4)
67 #define MAXMOD MAXWLEN /* This cannot overflow */
69 static Char *dolp; /* Remaining chars from this word */
70 static Char **dolnxt; /* Further words */
71 static int dolcnt; /* Count of further words */
73 static Char dolmod; /* : modifier character */
75 static Char dolmod[MAXMOD]; /* : modifier character */
76 static int dolnmod; /* Number of modifiers */
78 static int dolmcnt; /* :gx -> 10000, else 1 */
79 static int dolwcnt; /* :ax -> 10000, else 1 */
81 static void Dfix2 __P((Char **));
82 static Char *Dpack __P((Char *, Char *));
83 static int Dword __P((void));
84 static void dolerror __P((Char *));
85 static int DgetC __P((int));
86 static void Dgetdol __P((void));
87 static void fixDolMod __P((void));
88 static void setDolp __P((Char *));
89 static void unDredc __P((int));
90 static int Dredc __P((void));
91 static void Dtestq __P((int));
94 * Fix up the $ expansions and quotations in the
95 * argument list to command t.
99 register struct command *t;
106 /* Note that t_dcom isn't trimmed thus !...:q's aren't lost */
107 for (pp = t->t_dcom; (p = *pp++) != NULL;) {
110 if (Ismbyte1(*p) && *(p + 1))
113 #endif /* DSPMBYTE */
114 if (cmap(*p, _DOL | QUOTES)) { /* $, \, ', ", ` */
115 Dfix2(t->t_dcom); /* found one */
126 * $ substitute one word, for i/o redirection
140 setname(short2str(cp));
141 stderror(ERR_NAME | ERR_AMBIG);
143 cp = Strsave(gargv[0]);
144 blkfree(gargv), gargv = 0;
149 * Subroutine to do actual fixing after state initialization.
155 ginit(); /* Initialize glob's area pointers */
157 Dcp = STRNULL; /* Setup input vector for Dreadc */
159 unDredc(0); /* Clear out any old peeks (at error) */
161 dolcnt = 0; /* Clear out residual $ expands (...) */
167 * Pack up more characters in this word
174 register int i = MAXWLEN - (int) (wp - wbuf);
175 #if defined(DSPMBYTE)
177 #endif /* DSPMBYTE */
181 #if defined(DSPMBYTE)
182 if (mbytepos == 1 && Ismbyte1(c)) {
183 /* An MB1 byte that may be followed by a MB2 byte */
187 /* check if MB1 byte followed by an MB2 byte */
188 if (mbytepos == 2 && Ismbyte2(c)) {
189 /* MB1 + MB2 make the character */
190 mbytepos = 1; /* reset */
193 mbytepos = 1; /* reset */
194 /* wasn't followed, so the two bytes make two characters */
196 #endif /* DSPMBYTE */
216 if (cmap(c, _SP | _NL | _QF | _QB)) { /* sp \t\n'"` */
224 #if defined(DSPMBYTE)
226 #endif /* DSPMBYTE */
228 stderror(ERR_WTOOLONG);
234 * Get a word. This routine is analogous to the routine
235 * word() in sh.lex.c for the main lexical input. One difference
236 * here is that we don't get a newline to terminate our expansion.
237 * Rather, DgetC will return a DEOF when we hit the end-of-input.
244 register Char *wp = wbuf;
245 register int i = MAXWLEN;
246 register bool dolflg;
247 bool sofar = 0, done = 0;
257 /* finish this word and catch the code above the next time */
272 /* We preserve ` quotations which are done yet later */
273 *wp++ = (Char) c, --i;
278 * Note that DgetC never returns a QUOTES character from an
279 * expansion, so only true input quotes will get us here or out.
282 dolflg = c1 == '"' ? DODOL : 0;
287 if (c == '\n' || c == DEOF)
288 stderror(ERR_UNMATCHED, c1);
289 if ((c & (QUOTE | TRIM)) == ('\n' | QUOTE)) {
290 if ((wp[-1] & TRIM) == '\\')
295 stderror(ERR_WTOOLONG);
300 * Leave any `s alone for later. Other chars are all
301 * quoted, thus `...` can tell it was within "...".
303 *wp++ = c == '`' ? '`' : c | QUOTE;
307 /* Prevent all further interpretation */
312 /* Leave all text alone for later */
321 *wp++ = '`' /* i--; eliminated */;
323 if ((wp = Dpack(wbuf, wp)) == NULL)
328 * Avoid a nasty message from the RTU 4.1A & RTU 5.0 compiler concerning
329 * the "overuse of registers". According to the compiler release notes,
330 * incorrect code may be produced unless the offending expression is
331 * rewritten. Therefore, we can't just ignore it, DAS DEC-90.
334 i -= (int) (wp - wbuf);
335 #else /* !masscomp */
336 i = MAXWLEN - (int) (wp - wbuf);
337 #endif /* masscomp */
343 c = DgetC(0); /* No $ subst! */
344 if (c == '\n' || c == DEOF) {
357 if ((wp = Dpack(wbuf, wp)) == NULL)
362 * Avoid a nasty message from the RTU 4.1A & RTU 5.0 compiler concerning
363 * the "overuse of registers". According to the compiler release notes,
364 * incorrect code may be produced unless the offending expression is
365 * rewritten. Therefore, we can't just ignore it, DAS DEC-90.
368 i -= (int) (wp - wbuf);
369 #else /* !masscomp */
370 i = MAXWLEN - (int) (wp - wbuf);
371 #endif /* masscomp */
376 /* Really NOTREACHED */
382 * Get a character, performing $ substitution unless flag is 0.
383 * Any QUOTES character which is returned from a $ expansion is
384 * QUOTEd so that it will not be recognized above.
393 if ((c = Dpeekc) != 0) {
398 c = *lap++ & (QUOTE | TRIM);
409 if ((c = *dolp++ & (QUOTE | TRIM)) != 0)
424 if (c == '$' && flag) {
431 static Char *nulvec[] = { NULL };
432 static struct varent nulargv = {nulvec, STRargv, VAR_READWRITE,
433 { NULL, NULL, NULL }, 0 };
439 setname(short2str(s));
440 stderror(ERR_NAME | ERR_RANGE);
444 * Handle the multitudinous $ expansion forms.
451 register struct varent *vp = NULL;
452 Char name[4 * MAXVARLEN + 1];
454 int subscr = 0, lwb = 1, upb = 0;
455 bool dimen = 0, bitset = 0, length = 0;
458 static Char *dolbang = NULL;
461 dolmod = dolmcnt = dolwcnt = 0;
463 dolnmod = dolmcnt = dolwcnt = 0;
467 c = DgetC(0); /* sc is { to take } later */
468 if ((c & TRIM) == '#')
469 dimen++, c = DgetC(0); /* $# takes dimension */
471 bitset++, c = DgetC(0); /* $? tests existence */
473 length++, c = DgetC(0); /* $% returns length in chars */
477 if (dimen || bitset || length)
478 stderror(ERR_SYNTAX);
481 xfree((ptr_t) dolbang);
482 setDolp(dolbang = putn(backpid));
487 if (dimen || bitset || length)
488 stderror(ERR_SYNTAX);
493 /* Coherent compiler doesn't allow case-labels that are not
494 constant-expressions */
497 #else /* !SHORT_STRINGS */
500 #else /* !COHERENT */
504 stderror(ERR_NOTALLOWED, "$?<");
506 stderror(ERR_NOTALLOWED, "$#<");
508 stderror(ERR_NOTALLOWED, "$%<");
511 sigmask_t omask = sigsetmask(sigblock(0) & ~sigmask(SIGINT));
513 (void) sigrelse(SIGINT);
515 for (np = wbuf; force_read(OLDSTD, &tnp, 1) == 1; np++) {
516 *np = (unsigned char) tnp;
517 if (np >= &wbuf[BUFSIZE - 1])
518 stderror(ERR_LTOOLONG);
524 (void) sigsetmask(omask);
526 (void) sighold(SIGINT);
532 * KLUDGE: dolmod is set here because it will cause setDolp to call
533 * domod and thus to copy wbuf. Otherwise setDolp would use it
534 * directly. If we saved it ourselves, no one would know when to free
535 * it. The actual function of the 'q' causes filename expansion not to
536 * be done on the interpolated value.
539 * If we do that, then other modifiers don't work.
540 * in addition, let the user specify :q if wanted
543 /*old*/ dolmod = 'q';
544 /*new*/ dolmod[dolnmod++] = 'q';
553 (void) Strcpy(name, STRargv);
555 subscr = -1; /* Prevent eating [...] */
560 np = dimen ? STRargv : (bitset ? STRstatus : NULL);
563 (void) Strcpy(name, np);
565 subscr = -1; /* Prevent eating [...] */
570 stderror(ERR_SYNTAX);
577 stderror(ERR_NOTALLOWED, "$#<num>");
580 subscr = subscr * 10 + c - '0';
582 } while (Isdigit(c));
588 dolp = dolzero ? STR1 : STR0;
592 stderror(ERR_DOLZERO);
595 length = Strlen(ffile);
608 stderror(ERR_NOTALLOWED, "$?<num>");
610 stderror(ERR_NOTALLOWED, "$%<num>");
620 np = dimen ? STRargv : (bitset ? STRstatus : NULL);
623 (void) Strcpy(name, np);
625 subscr = -1; /* Prevent eating [...] */
630 stderror(ERR_VARALNUM);
637 if (np >= &name[MAXVARLEN])
638 stderror(ERR_VARTOOLONG);
645 dolp = (vp || getenv(short2str(name))) ? STR1 : STR0;
648 if (vp == NULL || vp->vec == NULL) {
649 np = str2short(getenv(short2str(name)));
659 upb = blklen(vp->vec);
660 if (dimen == 0 && subscr == 0 && c == '[') {
663 c = DgetC(DODOL); /* Allow $ expand within [ ] */
666 if (c == '\n' || c == DEOF)
668 if (np >= &name[sizeof(name) / sizeof(Char) - 2])
669 stderror(ERR_VARTOOLONG);
673 if (dolp || dolcnt) /* $ exp must end before ] */
674 stderror(ERR_EXPORD);
676 stderror(ERR_SYNTAX);
680 for (i = 0; Isdigit(*np); i = i * 10 + *np++ - '0')
682 if ((i < 0 || i > upb) && !any("-*", *np)) {
683 dolerror(vp->v_name);
688 upb = lwb, np = STRstar;
693 stderror(ERR_MISSING, '-');
695 register int i = upb;
701 i = i * 10 + *np++ - '0';
702 if (i < 0 || i > upb) {
703 dolerror(vp->v_name);
714 dolerror(vp->v_name);
720 stderror(ERR_SYNTAX);
732 Char *cp = putn(upb - lwb + 1);
734 /* this is a kludge. It prevents Dgetdol() from */
735 /* pushing erroneous ${#<error> values into the labuf. */
741 stderror(ERR_MISSING, '}');
752 for (i = lwb - 1, length = 0; i < upb; i++)
753 length += Strlen(vp->vec[i]);
755 /* We don't want that, since we can always compute it by adding $#xxx */
756 length += i - 1; /* Add the number of spaces in */
765 dolnxt = &vp->vec[lwb - 1];
766 dolcnt = upb - lwb + 1;
772 stderror(ERR_MISSING, '}');
786 c = DgetC(0), dolmcnt = 1, dolwcnt = 1;
787 if (c == 'g' || c == 'a') {
794 if ((c == 'g' && dolmcnt != 10000) ||
795 (c == 'a' && dolwcnt != 10000)) {
803 if (c == 's') { /* [eichin:19910926.0755EST] */
805 int delim = DgetC(0);
806 dolmod[dolnmod++] = (Char) c;
807 dolmod[dolnmod++] = (Char) delim;
809 if (!delim || letter(delim)
810 || Isdigit(delim) || any(" \t\n", delim)) {
811 seterror(ERR_BADSUBST);
814 while ((c = DgetC(0)) != (-1)) {
815 dolmod[dolnmod++] = (Char) c;
816 if(c == delim) delimcnt--;
820 seterror(ERR_BADSUBST);
825 if (!any("luhtrqxes", c))
826 stderror(ERR_BADMOD, c);
828 dolmod[dolnmod++] = (Char) c;
836 while ((c = DgetC(0)) == ':');
854 if (dolmod == 0 || dolmcnt == 0) {
856 if (dolnmod == 0 || dolmcnt == 0) {
862 dp = domod(cp, dolmod);
864 dp = cp = Strsave(cp);
865 for (i = 0; i < dolnmod; i++) {
866 /* handle s// [eichin:19910926.0510EST] */
867 if(dolmod[i] == 's') {
869 Char *lhsub, *rhsub, *np;
870 size_t lhlen = 0, rhlen = 0;
874 if (!delim || letter(delim)
875 || Isdigit(delim) || any(" \t\n", delim)) {
876 seterror(ERR_BADSUBST);
879 lhsub = &dolmod[++i];
880 while(dolmod[i] != delim && dolmod[++i]) {
884 rhsub = &dolmod[++i];
885 while(dolmod[i] != delim && dolmod[++i]) {
893 dp = Strstr(cp, lhsub);
895 np = (Char *) xmalloc((size_t)
896 ((Strlen(cp) + 1 - lhlen + rhlen) *
898 (void) Strncpy(np, cp, (size_t) (dp - cp));
899 (void) Strcpy(np + (dp - cp), rhsub);
900 (void) Strcpy(np + (dp - cp) + rhlen, dp + lhlen);
906 /* should this do a seterror? */
910 while (dolwcnt == 10000);
912 * restore dolmod for additional words
914 dolmod[i] = rhsub[-1] = (Char) delim;
925 if ((dp = domod(cp, dolmod[i])) != NULL) {
927 if (Strcmp(cp, dp) == 0) {
940 while (dolwcnt == 10000);
982 if ((c = Dpeekrd) != 0) {
986 if (Dcp && (c = *Dcp++))
987 return (c & (QUOTE | TRIM));
1001 if (cmap(c, QUOTES))
1006 * Form a shell temporary file (in unit 0) from the words
1007 * of the shell input up to EOF or a line the same as "term".
1008 * Unit 0 should have been closed before this call.
1016 Char obuf[BUFSIZE], lbuf[BUFSIZE], mbuf[BUFSIZE];
1017 int ocnt, lcnt, mcnt;
1018 register Char *lbp, *obp, *mbp;
1022 #ifndef WINNT_NATIVE
1026 #endif /* WINNT_NATIVE */
1027 tmp = short2str(shtemp);
1030 if (creat(tmp, 0600) < 0)
1031 stderror(ERR_SYSTEM, tmp, strerror(errno));
1035 # define O_TEMPORARY 0
1040 if (open(tmp, O_RDWR|O_CREAT|O_EXCL|O_TEMPORARY, 0600) == -1) {
1042 #ifndef WINNT_NATIVE
1043 if (errno == EEXIST) {
1044 if (unlink(tmp) == -1) {
1045 (void) gettimeofday(&tv, NULL);
1046 shtemp = Strspl(STRtmpsh, putn((((int)tv.tv_sec) ^
1047 ((int)tv.tv_usec) ^ ((int)getpid())) & 0x00ffffff));
1051 #endif /* WINNT_NATIVE */
1054 stderror(ERR_SYSTEM, tmp, strerror(errno));
1056 (void) unlink(tmp); /* 0 0 inode! */
1068 #endif /* WINNT_NATIVE */
1076 c = readc(1); /* 1 -> Want EOF returns */
1077 if (c < 0 || c == '\n')
1079 if ((c &= TRIM) != 0) {
1083 stderror(ERR_NAME | ERR_OVERFLOW);
1090 * Check for EOF or compare to terminator -- before expansion
1092 if (c < 0 || eq(lbuf, term)) {
1093 (void) write(0, short2str(obuf), (size_t) (BUFSIZE - ocnt));
1094 (void) lseek(0, (off_t) 0, L_SET);
1100 * If term was quoted or -n just pass it on
1102 if (quoted || noexec) {
1105 for (lbp = lbuf; (c = *lbp++) != 0;) {
1108 (void) write(0, short2str(obuf), BUFSIZE);
1117 * Term wasn't quoted so variable and then command expand the input
1128 if ((c &= TRIM) == 0)
1130 /* \ quotes \ $ ` here */
1133 if (!any("$\\`", c))
1134 unDgetC(c | QUOTE), c = '\\';
1141 stderror(ERR_NAME | ERR_OVERFLOW);
1147 * If any ` in line do command substitution
1150 if (Strchr(mbp, '`') != NULL) {
1152 * 1 arg to dobackp causes substitution to be literal. Words are
1153 * broken only at newlines so that all blanks and tabs are
1154 * preserved. Blank lines (null words) are not discarded.
1156 vp = dobackp(mbuf, 1);
1159 /* Setup trivial vector similar to return of dobackp */
1160 Dv[0] = mbp, Dv[1] = NULL, vp = Dv;
1163 * Resurrect the words from the command substitution each separated by
1164 * a newline. Note that the last newline of a command substitution
1165 * will have been discarded, but we put a newline after the last word
1166 * because this represents the newline after the last input line!
1169 for (mbp = *vp; *mbp; mbp++) {
1170 *obp++ = *mbp & TRIM;
1172 (void) write(0, short2str(obuf), BUFSIZE);
1179 (void) write(0, short2str(obuf), BUFSIZE);
1185 blkfree(pargv), pargv = 0;