unstack - fix ipcvecs
[minix.git] / commands / ash / expand.c
blob74309c4c93b4b8d1ef7f4c967780cf5b7bdfc5a0
1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Kenneth Almquist.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)expand.c 8.5 (Berkeley) 5/15/95";
36 #endif
37 #endif /* not lint */
38 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD: src/bin/sh/expand.c,v 1.46 2004/04/06 20:06:51 markm Exp $");
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <errno.h>
46 #include <dirent.h>
47 #include <unistd.h>
48 #include <pwd.h>
49 #include <stdlib.h>
50 #include <limits.h>
51 #include <stdio.h>
52 #include <string.h>
55 * Routines to expand arguments to commands. We have to deal with
56 * backquotes, shell variables, and file metacharacters.
59 #include "shell.h"
60 #include "main.h"
61 #include "nodes.h"
62 #include "eval.h"
63 #include "expand.h"
64 #include "syntax.h"
65 #include "parser.h"
66 #include "jobs.h"
67 #include "options.h"
68 #include "var.h"
69 #include "input.h"
70 #include "output.h"
71 #include "memalloc.h"
72 #include "error.h"
73 #include "mystring.h"
74 #include "arith.h"
75 #include "show.h"
78 * Structure specifying which parts of the string should be searched
79 * for IFS characters.
82 struct ifsregion {
83 struct ifsregion *next; /* next region in list */
84 int begoff; /* offset of start of region */
85 int endoff; /* offset of end of region */
86 int nulonly; /* search for nul bytes only */
90 STATIC char *expdest; /* output of current string */
91 STATIC struct nodelist *argbackq; /* list of back quote expressions */
92 STATIC struct ifsregion ifsfirst; /* first struct in list of ifs regions */
93 STATIC struct ifsregion *ifslastp; /* last struct in list */
94 STATIC struct arglist exparg; /* holds expanded arg list */
96 STATIC void argstr(char *, int);
97 STATIC char *exptilde(char *, int);
98 STATIC void expbackq(union node *, int, int);
99 STATIC int subevalvar(char *, char *, int, int, int, int);
100 STATIC char *evalvar(char *, int);
101 STATIC int varisset(char *, int);
102 STATIC void varvalue(char *, int, int);
103 STATIC void recordregion(int, int, int);
104 STATIC void removerecordregions(int);
105 STATIC void ifsbreakup(char *, struct arglist *);
106 STATIC void expandmeta(struct strlist *, int);
107 STATIC void expmeta(char *, char *);
108 STATIC void addfname(char *);
109 STATIC struct strlist *expsort(struct strlist *);
110 STATIC struct strlist *msort(struct strlist *, int);
111 STATIC int pmatch(char *, char *, int);
112 STATIC char *cvtnum(int, char *);
113 STATIC int collate_range_cmp(int, int);
114 STATIC void expari(int);
116 STATIC int
117 collate_range_cmp(int c1, int c2)
119 static char s1[2], s2[2];
121 s1[0] = c1;
122 s2[0] = c2;
123 return (strcoll(s1, s2));
127 * Expand shell variables and backquotes inside a here document.
128 * union node *arg the document
129 * int fd; where to write the expanded version
132 void
133 expandhere(union node *arg, int fd)
135 herefd = fd;
136 expandarg(arg, (struct arglist *)NULL, 0);
137 xwrite(fd, stackblock(), expdest - stackblock());
142 * Perform variable substitution and command substitution on an argument,
143 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
144 * perform splitting and file name expansion. When arglist is NULL, perform
145 * here document expansion.
148 void
149 expandarg(union node *arg, struct arglist *arglist, int flag)
151 struct strlist *sp;
152 char *p;
154 argbackq = arg->narg.backquote;
155 STARTSTACKSTR(expdest);
156 ifsfirst.next = NULL;
157 ifslastp = NULL;
158 argstr(arg->narg.text, flag);
159 if (arglist == NULL) {
160 return; /* here document expanded */
162 STPUTC('\0', expdest);
163 p = grabstackstr(expdest);
164 exparg.lastp = &exparg.list;
166 * TODO - EXP_REDIR
168 if (flag & EXP_FULL) {
169 ifsbreakup(p, &exparg);
170 *exparg.lastp = NULL;
171 exparg.lastp = &exparg.list;
172 expandmeta(exparg.list, flag);
173 } else {
174 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
175 rmescapes(p);
176 sp = (struct strlist *)stalloc(sizeof (struct strlist));
177 sp->text = p;
178 *exparg.lastp = sp;
179 exparg.lastp = &sp->next;
181 while (ifsfirst.next != NULL) {
182 struct ifsregion *ifsp;
183 INTOFF;
184 ifsp = ifsfirst.next->next;
185 ckfree(ifsfirst.next);
186 ifsfirst.next = ifsp;
187 INTON;
189 *exparg.lastp = NULL;
190 if (exparg.list) {
191 *arglist->lastp = exparg.list;
192 arglist->lastp = exparg.lastp;
199 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
200 * characters to allow for further processing. Otherwise treat
201 * $@ like $* since no splitting will be performed.
204 STATIC void
205 argstr(char *p, int flag)
207 char c;
208 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR); /* do CTLESC */
209 int firsteq = 1;
211 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
212 p = exptilde(p, flag);
213 for (;;) {
214 switch (c = *p++) {
215 case '\0':
216 case CTLENDVAR: /* ??? */
217 goto breakloop;
218 case CTLQUOTEMARK:
219 /* "$@" syntax adherence hack */
220 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
221 break;
222 if ((flag & EXP_FULL) != 0)
223 STPUTC(c, expdest);
224 break;
225 case CTLESC:
226 if (quotes)
227 STPUTC(c, expdest);
228 c = *p++;
229 STPUTC(c, expdest);
230 break;
231 case CTLVAR:
232 p = evalvar(p, flag);
233 break;
234 case CTLBACKQ:
235 case CTLBACKQ|CTLQUOTE:
236 expbackq(argbackq->n, c & CTLQUOTE, flag);
237 argbackq = argbackq->next;
238 break;
239 case CTLENDARI:
240 expari(flag);
241 break;
242 case ':':
243 case '=':
245 * sort of a hack - expand tildes in variable
246 * assignments (after the first '=' and after ':'s).
248 STPUTC(c, expdest);
249 if (flag & EXP_VARTILDE && *p == '~') {
250 if (c == '=') {
251 if (firsteq)
252 firsteq = 0;
253 else
254 break;
256 p = exptilde(p, flag);
258 break;
259 default:
260 STPUTC(c, expdest);
263 breakloop:;
266 STATIC char *
267 exptilde(char *p, int flag)
269 char c, *startp = p;
270 struct passwd *pw;
271 char *home;
272 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
274 while ((c = *p) != '\0') {
275 switch(c) {
276 case CTLESC:
277 return (startp);
278 case CTLQUOTEMARK:
279 return (startp);
280 case ':':
281 if (flag & EXP_VARTILDE)
282 goto done;
283 break;
284 case '/':
285 goto done;
287 p++;
289 done:
290 *p = '\0';
291 if (*(startp+1) == '\0') {
292 if ((home = lookupvar("HOME")) == NULL)
293 goto lose;
294 } else {
295 if ((pw = getpwnam(startp+1)) == NULL)
296 goto lose;
297 home = pw->pw_dir;
299 if (*home == '\0')
300 goto lose;
301 *p = c;
302 while ((c = *home++) != '\0') {
303 if (quotes && SQSYNTAX[(int)c] == CCTL)
304 STPUTC(CTLESC, expdest);
305 STPUTC(c, expdest);
307 return (p);
308 lose:
309 *p = c;
310 return (startp);
314 STATIC void
315 removerecordregions(int endoff)
317 if (ifslastp == NULL)
318 return;
320 if (ifsfirst.endoff > endoff) {
321 while (ifsfirst.next != NULL) {
322 struct ifsregion *ifsp;
323 INTOFF;
324 ifsp = ifsfirst.next->next;
325 ckfree(ifsfirst.next);
326 ifsfirst.next = ifsp;
327 INTON;
329 if (ifsfirst.begoff > endoff)
330 ifslastp = NULL;
331 else {
332 ifslastp = &ifsfirst;
333 ifsfirst.endoff = endoff;
335 return;
338 ifslastp = &ifsfirst;
339 while (ifslastp->next && ifslastp->next->begoff < endoff)
340 ifslastp=ifslastp->next;
341 while (ifslastp->next != NULL) {
342 struct ifsregion *ifsp;
343 INTOFF;
344 ifsp = ifslastp->next->next;
345 ckfree(ifslastp->next);
346 ifslastp->next = ifsp;
347 INTON;
349 if (ifslastp->endoff > endoff)
350 ifslastp->endoff = endoff;
354 * Expand arithmetic expression. Backup to start of expression,
355 * evaluate, place result in (backed up) result, adjust string position.
357 STATIC void
358 expari(int flag)
360 char *p, *start;
361 int result;
362 int begoff;
363 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
364 int quoted;
368 * This routine is slightly over-complicated for
369 * efficiency. First we make sure there is
370 * enough space for the result, which may be bigger
371 * than the expression if we add exponentiation. Next we
372 * scan backwards looking for the start of arithmetic. If the
373 * next previous character is a CTLESC character, then we
374 * have to rescan starting from the beginning since CTLESC
375 * characters have to be processed left to right.
377 #if INT_MAX / 1000000000 >= 10 || INT_MIN / 1000000000 <= -10
378 #error "integers with more than 10 digits are not supported"
379 #endif
380 CHECKSTRSPACE(12 - 2, expdest);
381 USTPUTC('\0', expdest);
382 start = stackblock();
383 p = expdest - 2;
384 while (p >= start && *p != CTLARI)
385 --p;
386 if (p < start || *p != CTLARI)
387 error("missing CTLARI (shouldn't happen)");
388 if (p > start && *(p - 1) == CTLESC)
389 for (p = start; *p != CTLARI; p++)
390 if (*p == CTLESC)
391 p++;
393 if (p[1] == '"')
394 quoted=1;
395 else
396 quoted=0;
397 begoff = p - start;
398 removerecordregions(begoff);
399 if (quotes)
400 rmescapes(p+2);
401 result = arith(p+2);
402 fmtstr(p, 12, "%d", result);
403 while (*p++)
405 if (quoted == 0)
406 recordregion(begoff, p - 1 - start, 0);
407 result = expdest - p + 1;
408 STADJUST(-result, expdest);
413 * Expand stuff in backwards quotes.
416 STATIC void
417 expbackq(union node *cmd, int quoted, int flag)
419 struct backcmd in;
420 int i;
421 char buf[128];
422 char *p;
423 char *dest = expdest;
424 struct ifsregion saveifs, *savelastp;
425 struct nodelist *saveargbackq;
426 char lastc;
427 int startloc = dest - stackblock();
428 char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
429 int saveherefd;
430 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
431 int nnl;
433 INTOFF;
434 saveifs = ifsfirst;
435 savelastp = ifslastp;
436 saveargbackq = argbackq;
437 saveherefd = herefd;
438 herefd = -1;
439 p = grabstackstr(dest);
440 evalbackcmd(cmd, &in);
441 ungrabstackstr(p, dest);
442 ifsfirst = saveifs;
443 ifslastp = savelastp;
444 argbackq = saveargbackq;
445 herefd = saveherefd;
447 p = in.buf;
448 lastc = '\0';
449 nnl = 0;
450 /* Don't copy trailing newlines */
451 for (;;) {
452 if (--in.nleft < 0) {
453 if (in.fd < 0)
454 break;
455 while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR);
456 TRACE(("expbackq: read returns %d\n", i));
457 if (i <= 0)
458 break;
459 p = buf;
460 in.nleft = i - 1;
462 lastc = *p++;
463 if (lastc != '\0') {
464 if (quotes && syntax[(int)lastc] == CCTL)
465 STPUTC(CTLESC, dest);
466 if (lastc == '\n') {
467 nnl++;
468 } else {
469 while (nnl > 0) {
470 nnl--;
471 STPUTC('\n', dest);
473 STPUTC(lastc, dest);
478 if (in.fd >= 0)
479 close(in.fd);
480 if (in.buf)
481 ckfree(in.buf);
482 if (in.jp)
483 exitstatus = waitforjob(in.jp, (int *)NULL);
484 if (quoted == 0)
485 recordregion(startloc, dest - stackblock(), 0);
486 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
487 (dest - stackblock()) - startloc,
488 (dest - stackblock()) - startloc,
489 stackblock() + startloc));
490 expdest = dest;
491 INTON;
496 STATIC int
497 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
498 int varflags)
500 char *startp;
501 char *loc = NULL;
502 char *q;
503 int c = 0;
504 int saveherefd = herefd;
505 struct nodelist *saveargbackq = argbackq;
506 int amount;
508 herefd = -1;
509 argstr(p, 0);
510 STACKSTRNUL(expdest);
511 herefd = saveherefd;
512 argbackq = saveargbackq;
513 startp = stackblock() + startloc;
514 if (str == NULL)
515 str = stackblock() + strloc;
517 switch (subtype) {
518 case VSASSIGN:
519 setvar(str, startp, 0);
520 amount = startp - expdest;
521 STADJUST(amount, expdest);
522 varflags &= ~VSNUL;
523 if (c != 0)
524 *loc = c;
525 return 1;
527 case VSQUESTION:
528 if (*p != CTLENDVAR) {
529 outfmt(&errout, "%s\n", startp);
530 error((char *)NULL);
532 error("%.*s: parameter %snot set", (int)(p - str - 1),
533 str, (varflags & VSNUL) ? "null or "
534 : nullstr);
535 return 0;
537 case VSTRIMLEFT:
538 for (loc = startp; loc < str; loc++) {
539 c = *loc;
540 *loc = '\0';
541 if (patmatch(str, startp, varflags & VSQUOTE)) {
542 *loc = c;
543 goto recordleft;
545 *loc = c;
546 if ((varflags & VSQUOTE) && *loc == CTLESC)
547 loc++;
549 return 0;
551 case VSTRIMLEFTMAX:
552 for (loc = str - 1; loc >= startp;) {
553 c = *loc;
554 *loc = '\0';
555 if (patmatch(str, startp, varflags & VSQUOTE)) {
556 *loc = c;
557 goto recordleft;
559 *loc = c;
560 loc--;
561 if ((varflags & VSQUOTE) && loc > startp &&
562 *(loc - 1) == CTLESC) {
563 for (q = startp; q < loc; q++)
564 if (*q == CTLESC)
565 q++;
566 if (q > loc)
567 loc--;
570 return 0;
572 case VSTRIMRIGHT:
573 for (loc = str - 1; loc >= startp;) {
574 if (patmatch(str, loc, varflags & VSQUOTE)) {
575 amount = loc - expdest;
576 STADJUST(amount, expdest);
577 return 1;
579 loc--;
580 if ((varflags & VSQUOTE) && loc > startp &&
581 *(loc - 1) == CTLESC) {
582 for (q = startp; q < loc; q++)
583 if (*q == CTLESC)
584 q++;
585 if (q > loc)
586 loc--;
589 return 0;
591 case VSTRIMRIGHTMAX:
592 for (loc = startp; loc < str - 1; loc++) {
593 if (patmatch(str, loc, varflags & VSQUOTE)) {
594 amount = loc - expdest;
595 STADJUST(amount, expdest);
596 return 1;
598 if ((varflags & VSQUOTE) && *loc == CTLESC)
599 loc++;
601 return 0;
604 default:
605 abort();
608 recordleft:
609 amount = ((str - 1) - (loc - startp)) - expdest;
610 STADJUST(amount, expdest);
611 while (loc != str - 1)
612 *startp++ = *loc++;
613 return 1;
618 * Expand a variable, and return a pointer to the next character in the
619 * input string.
622 STATIC char *
623 evalvar(char *p, int flag)
625 int subtype;
626 int varflags;
627 char *var;
628 char *val;
629 int patloc;
630 int c;
631 int set;
632 int special;
633 int startloc;
634 int varlen;
635 int easy;
636 int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
638 varflags = *p++;
639 subtype = varflags & VSTYPE;
640 var = p;
641 special = 0;
642 if (! is_name(*p))
643 special = 1;
644 p = strchr(p, '=') + 1;
645 again: /* jump here after setting a variable with ${var=text} */
646 if (special) {
647 set = varisset(var, varflags & VSNUL);
648 val = NULL;
649 } else {
650 val = bltinlookup(var, 1);
651 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
652 val = NULL;
653 set = 0;
654 } else
655 set = 1;
657 varlen = 0;
658 startloc = expdest - stackblock();
659 if (!set && uflag) {
660 switch (subtype) {
661 case VSNORMAL:
662 case VSTRIMLEFT:
663 case VSTRIMLEFTMAX:
664 case VSTRIMRIGHT:
665 case VSTRIMRIGHTMAX:
666 case VSLENGTH:
667 error("%.*s: parameter not set", (int)(p - var - 1),
668 var);
671 if (set && subtype != VSPLUS) {
672 /* insert the value of the variable */
673 if (special) {
674 varvalue(var, varflags & VSQUOTE, flag & EXP_FULL);
675 if (subtype == VSLENGTH) {
676 varlen = expdest - stackblock() - startloc;
677 STADJUST(-varlen, expdest);
679 } else {
680 char const *syntax = (varflags & VSQUOTE) ? DQSYNTAX
681 : BASESYNTAX;
683 if (subtype == VSLENGTH) {
684 for (;*val; val++)
685 varlen++;
687 else {
688 while (*val) {
689 if (quotes &&
690 syntax[(int)*val] == CCTL)
691 STPUTC(CTLESC, expdest);
692 STPUTC(*val++, expdest);
699 if (subtype == VSPLUS)
700 set = ! set;
702 easy = ((varflags & VSQUOTE) == 0 ||
703 (*var == '@' && shellparam.nparam != 1));
706 switch (subtype) {
707 case VSLENGTH:
708 expdest = cvtnum(varlen, expdest);
709 goto record;
711 case VSNORMAL:
712 if (!easy)
713 break;
714 record:
715 recordregion(startloc, expdest - stackblock(),
716 varflags & VSQUOTE);
717 break;
719 case VSPLUS:
720 case VSMINUS:
721 if (!set) {
722 argstr(p, flag);
723 break;
725 if (easy)
726 goto record;
727 break;
729 case VSTRIMLEFT:
730 case VSTRIMLEFTMAX:
731 case VSTRIMRIGHT:
732 case VSTRIMRIGHTMAX:
733 if (!set)
734 break;
736 * Terminate the string and start recording the pattern
737 * right after it
739 STPUTC('\0', expdest);
740 patloc = expdest - stackblock();
741 if (subevalvar(p, NULL, patloc, subtype,
742 startloc, varflags) == 0) {
743 int amount = (expdest - stackblock() - patloc) + 1;
744 STADJUST(-amount, expdest);
746 /* Remove any recorded regions beyond start of variable */
747 removerecordregions(startloc);
748 goto record;
750 case VSASSIGN:
751 case VSQUESTION:
752 if (!set) {
753 if (subevalvar(p, var, 0, subtype, startloc, varflags)) {
754 varflags &= ~VSNUL;
756 * Remove any recorded regions beyond
757 * start of variable
759 removerecordregions(startloc);
760 goto again;
762 break;
764 if (easy)
765 goto record;
766 break;
768 default:
769 abort();
772 if (subtype != VSNORMAL) { /* skip to end of alternative */
773 int nesting = 1;
774 for (;;) {
775 if ((c = *p++) == CTLESC)
776 p++;
777 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
778 if (set)
779 argbackq = argbackq->next;
780 } else if (c == CTLVAR) {
781 if ((*p++ & VSTYPE) != VSNORMAL)
782 nesting++;
783 } else if (c == CTLENDVAR) {
784 if (--nesting == 0)
785 break;
789 return p;
795 * Test whether a specialized variable is set.
798 STATIC int
799 varisset(char *name, int nulok)
802 if (*name == '!')
803 return backgndpid != -1;
804 else if (*name == '@' || *name == '*') {
805 if (*shellparam.p == NULL)
806 return 0;
808 if (nulok) {
809 char **av;
811 for (av = shellparam.p; *av; av++)
812 if (**av != '\0')
813 return 1;
814 return 0;
816 } else if (is_digit(*name)) {
817 char *ap;
818 int num = atoi(name);
820 if (num > shellparam.nparam)
821 return 0;
823 if (num == 0)
824 ap = arg0;
825 else
826 ap = shellparam.p[num - 1];
828 if (nulok && (ap == NULL || *ap == '\0'))
829 return 0;
831 return 1;
837 * Add the value of a specialized variable to the stack string.
840 STATIC void
841 varvalue(char *name, int quoted, int allow_split)
843 int num;
844 char *p;
845 int i;
846 extern int oexitstatus;
847 char sep;
848 char **ap;
849 char const *syntax;
851 #define STRTODEST(p) \
852 do {\
853 if (allow_split) { \
854 syntax = quoted? DQSYNTAX : BASESYNTAX; \
855 while (*p) { \
856 if (syntax[(int)*p] == CCTL) \
857 STPUTC(CTLESC, expdest); \
858 STPUTC(*p++, expdest); \
860 } else \
861 while (*p) \
862 STPUTC(*p++, expdest); \
863 } while (0)
866 switch (*name) {
867 case '$':
868 num = rootpid;
869 goto numvar;
870 case '?':
871 num = oexitstatus;
872 goto numvar;
873 case '#':
874 num = shellparam.nparam;
875 goto numvar;
876 case '!':
877 num = backgndpid;
878 numvar:
879 expdest = cvtnum(num, expdest);
880 break;
881 case '-':
882 for (i = 0 ; i < NOPTS ; i++) {
883 if (optlist[i].val)
884 STPUTC(optlist[i].letter, expdest);
886 break;
887 case '@':
888 if (allow_split && quoted) {
889 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
890 STRTODEST(p);
891 if (*ap)
892 STPUTC('\0', expdest);
894 break;
896 /* FALLTHROUGH */
897 case '*':
898 if (ifsset() != 0)
899 sep = ifsval()[0];
900 else
901 sep = ' ';
902 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
903 STRTODEST(p);
904 if (*ap && sep)
905 STPUTC(sep, expdest);
907 break;
908 case '0':
909 p = arg0;
910 STRTODEST(p);
911 break;
912 default:
913 if (is_digit(*name)) {
914 num = atoi(name);
915 if (num > 0 && num <= shellparam.nparam) {
916 p = shellparam.p[num - 1];
917 STRTODEST(p);
920 break;
927 * Record the the fact that we have to scan this region of the
928 * string for IFS characters.
931 STATIC void
932 recordregion(int start, int end, int nulonly)
934 struct ifsregion *ifsp;
936 if (ifslastp == NULL) {
937 ifsp = &ifsfirst;
938 } else {
939 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
940 ifslastp->next = ifsp;
942 ifslastp = ifsp;
943 ifslastp->next = NULL;
944 ifslastp->begoff = start;
945 ifslastp->endoff = end;
946 ifslastp->nulonly = nulonly;
952 * Break the argument string into pieces based upon IFS and add the
953 * strings to the argument list. The regions of the string to be
954 * searched for IFS characters have been stored by recordregion.
956 STATIC void
957 ifsbreakup(char *string, struct arglist *arglist)
959 struct ifsregion *ifsp;
960 struct strlist *sp;
961 char *start;
962 char *p;
963 char *q;
964 char *ifs;
965 int ifsspc;
966 int nulonly;
969 start = string;
970 ifsspc = 0;
971 nulonly = 0;
972 if (ifslastp != NULL) {
973 ifsp = &ifsfirst;
974 do {
975 p = string + ifsp->begoff;
976 nulonly = ifsp->nulonly;
977 ifs = nulonly ? nullstr :
978 ( ifsset() ? ifsval() : " \t\n" );
979 ifsspc = 0;
980 while (p < string + ifsp->endoff) {
981 q = p;
982 if (*p == CTLESC)
983 p++;
984 if (strchr(ifs, *p)) {
985 if (!nulonly)
986 ifsspc = (strchr(" \t\n", *p) != NULL);
987 /* Ignore IFS whitespace at start */
988 if (q == start && ifsspc) {
989 p++;
990 start = p;
991 continue;
993 *q = '\0';
994 sp = (struct strlist *)stalloc(sizeof *sp);
995 sp->text = start;
996 *arglist->lastp = sp;
997 arglist->lastp = &sp->next;
998 p++;
999 if (!nulonly) {
1000 for (;;) {
1001 if (p >= string + ifsp->endoff) {
1002 break;
1004 q = p;
1005 if (*p == CTLESC)
1006 p++;
1007 if (strchr(ifs, *p) == NULL ) {
1008 p = q;
1009 break;
1010 } else if (strchr(" \t\n",*p) == NULL) {
1011 if (ifsspc) {
1012 p++;
1013 ifsspc = 0;
1014 } else {
1015 p = q;
1016 break;
1018 } else
1019 p++;
1022 start = p;
1023 } else
1024 p++;
1026 } while ((ifsp = ifsp->next) != NULL);
1027 if (*start || (!ifsspc && start > string &&
1028 (nulonly || 1))) {
1029 sp = (struct strlist *)stalloc(sizeof *sp);
1030 sp->text = start;
1031 *arglist->lastp = sp;
1032 arglist->lastp = &sp->next;
1034 } else {
1035 sp = (struct strlist *)stalloc(sizeof *sp);
1036 sp->text = start;
1037 *arglist->lastp = sp;
1038 arglist->lastp = &sp->next;
1045 * Expand shell metacharacters. At this point, the only control characters
1046 * should be escapes. The results are stored in the list exparg.
1049 STATIC char *expdir;
1052 STATIC void
1053 expandmeta(struct strlist *str, int flag __unused)
1055 char *p;
1056 struct strlist **savelastp;
1057 struct strlist *sp;
1058 char c;
1059 /* TODO - EXP_REDIR */
1061 while (str) {
1062 if (fflag)
1063 goto nometa;
1064 p = str->text;
1065 for (;;) { /* fast check for meta chars */
1066 if ((c = *p++) == '\0')
1067 goto nometa;
1068 if (c == '*' || c == '?' || c == '[' || c == '!')
1069 break;
1071 savelastp = exparg.lastp;
1072 INTOFF;
1073 if (expdir == NULL) {
1074 int i = strlen(str->text);
1075 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
1078 expmeta(expdir, str->text);
1079 ckfree(expdir);
1080 expdir = NULL;
1081 INTON;
1082 if (exparg.lastp == savelastp) {
1084 * no matches
1086 nometa:
1087 *exparg.lastp = str;
1088 rmescapes(str->text);
1089 exparg.lastp = &str->next;
1090 } else {
1091 *exparg.lastp = NULL;
1092 *savelastp = sp = expsort(*savelastp);
1093 while (sp->next != NULL)
1094 sp = sp->next;
1095 exparg.lastp = &sp->next;
1097 str = str->next;
1103 * Do metacharacter (i.e. *, ?, [...]) expansion.
1106 STATIC void
1107 expmeta(char *enddir, char *name)
1109 char *p;
1110 char *q;
1111 char *start;
1112 char *endname;
1113 int metaflag;
1114 struct stat statb;
1115 DIR *dirp;
1116 struct dirent *dp;
1117 int atend;
1118 int matchdot;
1120 metaflag = 0;
1121 start = name;
1122 for (p = name ; ; p++) {
1123 if (*p == '*' || *p == '?')
1124 metaflag = 1;
1125 else if (*p == '[') {
1126 q = p + 1;
1127 if (*q == '!' || *q == '^')
1128 q++;
1129 for (;;) {
1130 while (*q == CTLQUOTEMARK)
1131 q++;
1132 if (*q == CTLESC)
1133 q++;
1134 if (*q == '/' || *q == '\0')
1135 break;
1136 if (*++q == ']') {
1137 metaflag = 1;
1138 break;
1141 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
1142 metaflag = 1;
1143 } else if (*p == '\0')
1144 break;
1145 else if (*p == CTLQUOTEMARK)
1146 continue;
1147 else if (*p == CTLESC)
1148 p++;
1149 if (*p == '/') {
1150 if (metaflag)
1151 break;
1152 start = p + 1;
1155 if (metaflag == 0) { /* we've reached the end of the file name */
1156 if (enddir != expdir)
1157 metaflag++;
1158 for (p = name ; ; p++) {
1159 if (*p == CTLQUOTEMARK)
1160 continue;
1161 if (*p == CTLESC)
1162 p++;
1163 *enddir++ = *p;
1164 if (*p == '\0')
1165 break;
1167 if (metaflag == 0 || stat(expdir, &statb) >= 0)
1168 addfname(expdir);
1169 return;
1171 endname = p;
1172 if (start != name) {
1173 p = name;
1174 while (p < start) {
1175 while (*p == CTLQUOTEMARK)
1176 p++;
1177 if (*p == CTLESC)
1178 p++;
1179 *enddir++ = *p++;
1182 if (enddir == expdir) {
1183 p = ".";
1184 } else if (enddir == expdir + 1 && *expdir == '/') {
1185 p = "/";
1186 } else {
1187 p = expdir;
1188 enddir[-1] = '\0';
1190 if ((dirp = opendir(p)) == NULL)
1191 return;
1192 if (enddir != expdir)
1193 enddir[-1] = '/';
1194 if (*endname == 0) {
1195 atend = 1;
1196 } else {
1197 atend = 0;
1198 *endname++ = '\0';
1200 matchdot = 0;
1201 p = start;
1202 while (*p == CTLQUOTEMARK)
1203 p++;
1204 if (*p == CTLESC)
1205 p++;
1206 if (*p == '.')
1207 matchdot++;
1208 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
1209 if (dp->d_name[0] == '.' && ! matchdot)
1210 continue;
1211 if (patmatch(start, dp->d_name, 0)) {
1212 if (atend) {
1213 scopy(dp->d_name, enddir);
1214 addfname(expdir);
1215 } else {
1216 char *q;
1217 for (p = enddir, q = dp->d_name;
1218 (*p++ = *q++) != '\0';)
1219 continue;
1220 p[-1] = '/';
1221 expmeta(p, endname);
1225 closedir(dirp);
1226 if (! atend)
1227 endname[-1] = '/';
1232 * Add a file name to the list.
1235 STATIC void
1236 addfname(char *name)
1238 char *p;
1239 struct strlist *sp;
1241 p = stalloc(strlen(name) + 1);
1242 scopy(name, p);
1243 sp = (struct strlist *)stalloc(sizeof *sp);
1244 sp->text = p;
1245 *exparg.lastp = sp;
1246 exparg.lastp = &sp->next;
1251 * Sort the results of file name expansion. It calculates the number of
1252 * strings to sort and then calls msort (short for merge sort) to do the
1253 * work.
1256 STATIC struct strlist *
1257 expsort(struct strlist *str)
1259 int len;
1260 struct strlist *sp;
1262 len = 0;
1263 for (sp = str ; sp ; sp = sp->next)
1264 len++;
1265 return msort(str, len);
1269 STATIC struct strlist *
1270 msort(struct strlist *list, int len)
1272 struct strlist *p, *q = NULL;
1273 struct strlist **lpp;
1274 int half;
1275 int n;
1277 if (len <= 1)
1278 return list;
1279 half = len >> 1;
1280 p = list;
1281 for (n = half ; --n >= 0 ; ) {
1282 q = p;
1283 p = p->next;
1285 q->next = NULL; /* terminate first half of list */
1286 q = msort(list, half); /* sort first half of list */
1287 p = msort(p, len - half); /* sort second half */
1288 lpp = &list;
1289 for (;;) {
1290 if (strcmp(p->text, q->text) < 0) {
1291 *lpp = p;
1292 lpp = &p->next;
1293 if ((p = *lpp) == NULL) {
1294 *lpp = q;
1295 break;
1297 } else {
1298 *lpp = q;
1299 lpp = &q->next;
1300 if ((q = *lpp) == NULL) {
1301 *lpp = p;
1302 break;
1306 return list;
1312 * Returns true if the pattern matches the string.
1316 patmatch(char *pattern, char *string, int squoted)
1318 #ifdef notdef
1319 if (pattern[0] == '!' && pattern[1] == '!')
1320 return 1 - pmatch(pattern + 2, string);
1321 else
1322 #endif
1323 return pmatch(pattern, string, squoted);
1327 STATIC int
1328 pmatch(char *pattern, char *string, int squoted)
1330 char *p, *q;
1331 char c;
1333 p = pattern;
1334 q = string;
1335 for (;;) {
1336 switch (c = *p++) {
1337 case '\0':
1338 goto breakloop;
1339 case CTLESC:
1340 if (squoted && *q == CTLESC)
1341 q++;
1342 if (*q++ != *p++)
1343 return 0;
1344 break;
1345 case CTLQUOTEMARK:
1346 continue;
1347 case '?':
1348 if (squoted && *q == CTLESC)
1349 q++;
1350 if (*q++ == '\0')
1351 return 0;
1352 break;
1353 case '*':
1354 c = *p;
1355 while (c == CTLQUOTEMARK || c == '*')
1356 c = *++p;
1357 if (c != CTLESC && c != CTLQUOTEMARK &&
1358 c != '?' && c != '*' && c != '[') {
1359 while (*q != c) {
1360 if (squoted && *q == CTLESC &&
1361 q[1] == c)
1362 break;
1363 if (*q == '\0')
1364 return 0;
1365 if (squoted && *q == CTLESC)
1366 q++;
1367 q++;
1370 do {
1371 if (pmatch(p, q, squoted))
1372 return 1;
1373 if (squoted && *q == CTLESC)
1374 q++;
1375 } while (*q++ != '\0');
1376 return 0;
1377 case '[': {
1378 char *endp;
1379 int invert, found;
1380 char chr;
1382 endp = p;
1383 if (*endp == '!' || *endp == '^')
1384 endp++;
1385 for (;;) {
1386 while (*endp == CTLQUOTEMARK)
1387 endp++;
1388 if (*endp == '\0')
1389 goto dft; /* no matching ] */
1390 if (*endp == CTLESC)
1391 endp++;
1392 if (*++endp == ']')
1393 break;
1395 invert = 0;
1396 if (*p == '!' || *p == '^') {
1397 invert++;
1398 p++;
1400 found = 0;
1401 chr = *q++;
1402 if (squoted && chr == CTLESC)
1403 chr = *q++;
1404 if (chr == '\0')
1405 return 0;
1406 c = *p++;
1407 do {
1408 if (c == CTLQUOTEMARK)
1409 continue;
1410 if (c == CTLESC)
1411 c = *p++;
1412 if (*p == '-' && p[1] != ']') {
1413 p++;
1414 while (*p == CTLQUOTEMARK)
1415 p++;
1416 if (*p == CTLESC)
1417 p++;
1418 if ( collate_range_cmp(chr, c) >= 0
1419 && collate_range_cmp(chr, *p) <= 0
1421 found = 1;
1422 p++;
1423 } else {
1424 if (chr == c)
1425 found = 1;
1427 } while ((c = *p++) != ']');
1428 if (found == invert)
1429 return 0;
1430 break;
1432 dft: default:
1433 if (squoted && *q == CTLESC)
1434 q++;
1435 if (*q++ != c)
1436 return 0;
1437 break;
1440 breakloop:
1441 if (*q != '\0')
1442 return 0;
1443 return 1;
1449 * Remove any CTLESC characters from a string.
1452 void
1453 rmescapes(char *str)
1455 char *p, *q;
1457 p = str;
1458 while (*p != CTLESC && *p != CTLQUOTEMARK) {
1459 if (*p++ == '\0')
1460 return;
1462 q = p;
1463 while (*p) {
1464 if (*p == CTLQUOTEMARK) {
1465 p++;
1466 continue;
1468 if (*p == CTLESC)
1469 p++;
1470 *q++ = *p++;
1472 *q = '\0';
1478 * See if a pattern matches in a case statement.
1482 casematch(union node *pattern, char *val)
1484 struct stackmark smark;
1485 int result;
1486 char *p;
1488 setstackmark(&smark);
1489 argbackq = pattern->narg.backquote;
1490 STARTSTACKSTR(expdest);
1491 ifslastp = NULL;
1492 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
1493 STPUTC('\0', expdest);
1494 p = grabstackstr(expdest);
1495 result = patmatch(p, val, 0);
1496 popstackmark(&smark);
1497 return result;
1501 * Our own itoa().
1504 STATIC char *
1505 cvtnum(int num, char *buf)
1507 char temp[32];
1508 int neg = num < 0;
1509 char *p = temp + 31;
1511 temp[31] = '\0';
1513 do {
1514 *--p = num % 10 + '0';
1515 } while ((num /= 10) != 0);
1517 if (neg)
1518 *--p = '-';
1520 while (*p)
1521 STPUTC(*p++, buf);
1522 return buf;
1526 * Do most of the work for wordexp(3).
1530 wordexpcmd(int argc, char **argv)
1532 size_t len;
1533 int i;
1535 out1fmt("%08x", argc - 1);
1536 for (i = 1, len = 0; i < argc; i++)
1537 len += strlen(argv[i]);
1538 out1fmt("%08x", (int)len);
1539 for (i = 1; i < argc; i++) {
1540 out1str(argv[i]);
1541 out1c('\0');
1543 return (0);
1547 * $PchId: expand.c,v 1.6 2006/04/10 14:52:06 philip Exp $