1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * This version of ash is adapted from the source in Debian's ash 0.3.8-5
28 * Modified by Erik Andersen <andersee@debian.org> and
29 * Vladimir Oleynik <dzo@simtreas.ru> to be used in busybox
32 * Original copyright notice is retained at the end of this file.
36 /* Enable this to compile in extra debugging noise. When debugging is
37 * on, debugging info will be written to $HOME/trace and a quit signal
38 * will generate a core dump. */
41 /* These are here to work with glibc -- Don't change these... */
63 #include <sys/cdefs.h>
64 #include <sys/ioctl.h>
65 #include <sys/param.h>
66 #include <sys/resource.h>
68 #include <sys/times.h>
69 #include <sys/types.h>
75 #if !defined(FNMATCH_BROKEN)
78 #if !defined(GLOB_BROKEN)
82 #ifdef CONFIG_ASH_JOB_CONTROL
89 * This file was generated by the mksyntax program.
93 #define CWORD 0 /* character is nothing special */
94 #define CNL 1 /* newline character */
95 #define CBACK 2 /* a backslash character */
96 #define CSQUOTE 3 /* single quote */
97 #define CDQUOTE 4 /* double quote */
98 #define CENDQUOTE 5 /* a terminating quote */
99 #define CBQUOTE 6 /* backwards single quote */
100 #define CVAR 7 /* a dollar sign */
101 #define CENDVAR 8 /* a '}' character */
102 #define CLP 9 /* a left paren in arithmetic */
103 #define CRP 10 /* a right paren in arithmetic */
104 #define CENDFILE 11 /* end of file */
105 #define CCTL 12 /* like CWORD, except it must be escaped */
106 #define CSPCL 13 /* these terminate a word */
107 #define CIGN 14 /* character should be ignored */
127 #define TENDBQUOTE 13
147 /* control characters in argument strings */
148 #define CTLESC '\201'
149 #define CTLVAR '\202'
150 #define CTLENDVAR '\203'
151 #define CTLBACKQ '\204'
152 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
153 /* CTLBACKQ | CTLQUOTE == '\205' */
154 #define CTLARI '\206'
155 #define CTLENDARI '\207'
156 #define CTLQUOTEMARK '\210'
159 #define is_digit(c) ((c)>='0' && (c)<='9')
160 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
161 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
164 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
165 * (assuming ascii char codes, as the original implementation did)
167 #define is_special(c) \
168 ( (((unsigned int)c) - 33 < 32) \
169 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
171 #define digit_val(c) ((c) - '0')
174 #define S_DFL 1 /* default signal handling (SIG_DFL) */
175 #define S_CATCH 2 /* signal is caught */
176 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
177 #define S_HARD_IGN 4 /* signal is ignored permenantly */
178 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
181 /* variable substitution byte (follows CTLVAR) */
182 #define VSTYPE 0x0f /* type of variable substitution */
183 #define VSNUL 0x10 /* colon--treat the empty string as unset */
184 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
186 /* values of VSTYPE field */
187 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
188 #define VSMINUS 0x2 /* ${var-text} */
189 #define VSPLUS 0x3 /* ${var+text} */
190 #define VSQUESTION 0x4 /* ${var?message} */
191 #define VSASSIGN 0x5 /* ${var=text} */
192 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
193 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
194 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
195 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
196 #define VSLENGTH 0xa /* ${#var} */
198 /* flags passed to redirect */
199 #define REDIR_PUSH 01 /* save previous values of file descriptors */
200 #define REDIR_BACKQ 02 /* save the command output to pipe */
203 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
204 * so we use _setjmp instead.
208 #define setjmp(jmploc) _setjmp(jmploc)
209 #define longjmp(jmploc, val) _longjmp(jmploc, val)
213 * Most machines require the value returned from malloc to be aligned
214 * in some way. The following macro will get this right on many machines.
223 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
226 #ifdef CONFIG_LOCALE_SUPPORT
228 static void change_lc_all(const char *value);
229 static void change_lc_ctype(const char *value);
233 * These macros allow the user to suspend the handling of interrupt signals
234 * over a period of time. This is similar to SIGHOLD to or sigblock, but
235 * much more efficient and portable. (But hacking the kernel is so much
236 * more fun than worrying about efficiency and portability. :-))
239 static void onint (void);
240 static volatile int suppressint;
241 static volatile int intpending;
243 #define INTOFF suppressint++
244 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
245 #define INTON { if (--suppressint == 0 && intpending) onint(); }
246 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
248 static void __inton (void);
249 static void forceinton (void);
250 #define INTON __inton()
251 #define FORCEINTON forceinton()
254 #define CLEAR_PENDING_INT intpending = 0
255 #define int_pending() intpending
258 typedef void *pointer;
260 #define NULL (void *)0
263 static pointer stalloc (int);
264 static void stunalloc (pointer);
265 static void ungrabstackstr (char *, char *);
266 static char * growstackstr(void);
267 static char * makestrspace(size_t newlen);
268 static char *sstrdup (const char *);
271 * Parse trees for commands are allocated in lifo order, so we use a stack
272 * to make this more efficient, and also to avoid all sorts of exception
273 * handling code to handle interrupts in the middle of a parse.
275 * The size 504 was chosen because the Ultrix malloc handles that size
279 #define MINSIZE 504 /* minimum size of a block */
283 struct stack_block *prev;
287 static struct stack_block stackbase;
288 static struct stack_block *stackp = &stackbase;
289 static struct stackmark *markp;
290 static char *stacknxt = stackbase.space;
291 static int stacknleft = MINSIZE;
294 #define equal(s1, s2) (strcmp(s1, s2) == 0)
296 #define stackblock() stacknxt
297 #define stackblocksize() stacknleft
298 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
300 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
301 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
302 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
305 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
306 #define STUNPUTC(p) (++sstrnleft, --p)
307 #define STTOPC(p) p[-1]
308 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
309 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
314 #define TRACE(param) trace param
315 typedef union node unode;
316 static void trace (const char *, ...);
317 static void trargs (char **);
318 static void showtree (unode *);
319 static void trputc (int);
320 static void trputs (const char *);
321 static void opentrace (void);
356 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
357 #define EXP_TILDE 0x2 /* do normal tilde expansion */
358 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
359 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
360 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
361 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
366 static char optet_vals[NOPTS];
368 static const char * const optlist[NOPTS] = {
387 #define optent_name(optent) (optent+1)
388 #define optent_letter(optent) optent[0]
389 #define optent_val(optent) optet_vals[optent]
391 #define eflag optent_val(0)
392 #define fflag optent_val(1)
393 #define Iflag optent_val(2)
394 #define iflag optent_val(3)
395 #define mflag optent_val(4)
396 #define nflag optent_val(5)
397 #define sflag optent_val(6)
398 #define xflag optent_val(7)
399 #define vflag optent_val(8)
400 #define Vflag optent_val(9)
401 #define Eflag optent_val(10)
402 #define Cflag optent_val(11)
403 #define aflag optent_val(12)
404 #define bflag optent_val(13)
405 #define uflag optent_val(14)
406 #define qflag optent_val(15)
409 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
427 union node *redirect;
434 struct nodelist *cmdlist;
441 union node *redirect;
449 union node *elsepart;
480 struct nodelist *backquote;
518 struct nbinary nbinary;
521 struct nredir nredir;
525 struct nclist nclist;
535 struct nodelist *next;
539 struct backcmd { /* result of evalbackcmd */
540 int fd; /* file descriptor to read from */
541 char *buf; /* buffer */
542 int nleft; /* number of chars in buffer */
543 struct job *jp; /* job structure for command */
551 const struct builtincmd *cmd;
556 struct strlist *next;
562 struct strlist *list;
563 struct strlist **lastp;
567 struct strpush *prev; /* preceding string on stack */
570 #ifdef CONFIG_ASH_ALIAS
571 struct alias *ap; /* if push was associated with an alias */
573 char *string; /* remember the string since it may change */
577 struct parsefile *prev; /* preceding file on stack */
578 int linno; /* current line */
579 int fd; /* file descriptor (or -1 if string) */
580 int nleft; /* number of chars left in this line */
581 int lleft; /* number of chars left in this buffer */
582 char *nextc; /* next char in buffer */
583 char *buf; /* input buffer */
584 struct strpush *strpush; /* for pushing strings at this level */
585 struct strpush basestrpush; /* so pushing one is fast */
589 struct stack_block *stackp;
592 struct stackmark *marknext;
596 int nparam; /* # of positional parameters (without $0) */
597 unsigned char malloc; /* if parameter list dynamically allocated */
598 char **p; /* parameter list */
599 int optind; /* next parameter to be processed by getopts */
600 int optoff; /* used by getopts */
604 * When commands are first encountered, they are entered in a hash table.
605 * This ensures that a full path search will not have to be done for them
606 * on each invocation.
608 * We should investigate converting to a linear search, even though that
609 * would make the command name "hash" a misnomer.
611 #define CMDTABLESIZE 31 /* should be prime */
612 #define ARB 1 /* actual size determined at run time */
617 struct tblentry *next; /* next entry in hash chain */
618 union param param; /* definition of builtin function */
619 short cmdtype; /* index identifying command */
620 char rehash; /* if set, cd done since entry created */
621 char cmdname[ARB]; /* name of command */
625 static struct tblentry *cmdtable[CMDTABLESIZE];
626 static int builtinloc = -1; /* index in path of %builtin, or -1 */
627 static int exerrno = 0; /* Last exec error */
630 static void tryexec (char *, char **, char **);
631 static void printentry (struct tblentry *, int);
632 static void clearcmdentry (int);
633 static struct tblentry *cmdlookup (const char *, int);
634 static void delete_cmd_entry (void);
635 static int path_change (const char *, int *);
638 static void flushall (void);
639 static void out2fmt (const char *, ...)
640 __attribute__((__format__(__printf__,1,2)));
641 static int xwrite (int, const char *, int);
643 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
644 static void out1str(const char *p) { outstr(p, stdout); }
645 static void out2str(const char *p) { outstr(p, stderr); }
647 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
648 #define out2c(c) putc((c), stderr)
650 static void out2c(int c) { putc(c, stderr); }
654 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
655 #define USE_SIT_FUNCTION
658 /* number syntax index */
659 #define BASESYNTAX 0 /* not in quotes */
660 #define DQSYNTAX 1 /* in double quotes */
661 #define SQSYNTAX 2 /* in single quotes */
662 #define ARISYNTAX 3 /* in arithmetic */
664 static const char S_I_T[][4] = {
665 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
666 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
667 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
668 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
669 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
670 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
671 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
672 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
673 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
674 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
675 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
676 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
677 #ifndef USE_SIT_FUNCTION
678 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
679 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
680 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
684 #ifdef USE_SIT_FUNCTION
686 #define U_C(c) ((unsigned char)(c))
688 static int SIT(int c, int syntax)
690 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
691 static const char syntax_index_table [] = {
692 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
693 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
694 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
699 if(c==PEOF) /* 2^8+2 */
701 if(c==PEOA) /* 2^8+1 */
703 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
706 s = strchr(spec_symbls, c);
709 indx = syntax_index_table[(s-spec_symbls)];
711 return S_I_T[indx][syntax];
714 #else /* USE_SIT_FUNCTION */
716 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
718 #define CSPCL_CIGN_CIGN_CIGN 0
719 #define CSPCL_CWORD_CWORD_CWORD 1
720 #define CNL_CNL_CNL_CNL 2
721 #define CWORD_CCTL_CCTL_CWORD 3
722 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
723 #define CVAR_CVAR_CWORD_CVAR 5
724 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
725 #define CSPCL_CWORD_CWORD_CLP 7
726 #define CSPCL_CWORD_CWORD_CRP 8
727 #define CBACK_CBACK_CCTL_CBACK 9
728 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
729 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
730 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
731 #define CWORD_CWORD_CWORD_CWORD 13
732 #define CCTL_CCTL_CCTL_CCTL 14
734 static const char syntax_index_table[258] = {
735 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
736 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
737 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
738 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
739 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
740 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
741 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
742 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
743 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
744 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
745 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
746 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
747 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
748 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
749 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
750 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
751 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
752 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
753 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
754 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
755 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
756 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
757 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
758 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
759 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
760 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
761 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
762 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
763 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
764 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
765 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
766 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
767 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
768 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
769 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
770 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
771 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
772 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
773 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
774 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
775 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
776 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
777 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
778 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
779 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
780 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
781 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
782 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
783 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
784 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
785 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
786 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
787 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
788 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
789 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
790 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
791 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
792 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
793 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
794 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
795 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
796 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
797 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
798 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
799 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
800 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
801 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
802 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
803 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
804 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
805 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
806 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
807 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
808 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
809 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
810 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
811 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
812 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
813 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
814 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
815 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
816 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
817 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
818 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
819 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
820 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
821 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
822 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
823 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
824 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
825 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
826 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
827 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
828 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
829 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
830 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
831 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
832 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
833 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
834 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
835 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
836 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
837 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
838 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
839 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
840 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
841 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
842 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
843 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
844 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
845 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
846 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
847 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
848 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
849 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
850 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
851 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
852 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
853 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
854 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
855 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
856 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
857 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
858 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
859 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
860 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
861 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
862 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
863 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
864 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
865 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
866 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
867 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
868 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
869 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
870 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
871 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
872 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
873 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
874 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
875 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
876 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
877 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
878 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
879 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
880 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
881 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
882 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
883 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
884 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
885 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
886 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
887 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
888 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
889 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
890 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
891 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
892 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
893 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
894 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
895 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
896 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
897 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
898 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
899 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
900 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
901 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
902 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
903 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
904 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
905 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
906 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
907 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
908 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
909 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
910 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
911 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
912 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
913 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
914 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
915 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
916 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
917 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
918 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
919 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
920 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
921 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
922 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
923 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
924 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
925 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
926 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
927 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
928 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
929 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
930 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
931 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
932 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
933 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
934 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
935 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
936 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
937 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
938 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
939 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
940 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
941 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
942 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
943 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
944 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
945 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
946 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
947 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
948 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
949 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
950 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
951 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
952 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
953 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
954 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
955 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
956 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
957 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
958 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
959 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
960 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
961 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
962 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
963 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
964 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
965 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
966 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
967 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
968 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
969 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
970 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
971 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
972 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
973 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
974 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
975 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
976 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
977 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
978 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
979 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
980 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
981 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
982 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
983 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
984 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
985 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
986 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
987 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
988 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
989 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
990 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
991 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
992 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
993 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
996 #endif /* USE_SIT_FUNCTION */
999 /* first char is indicating which tokens mark the end of a list */
1000 static const char *const tokname_array[] = {
1015 #define KWDOFFSET 14
1016 /* the following are keywords */
1035 static const char *tokname(int tok)
1037 static char buf[16];
1041 sprintf(buf+(tok>=TSEMI), "%s%c",
1042 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1046 static int plinno = 1; /* input line number */
1048 static int parselleft; /* copy of parsefile->lleft */
1050 static struct parsefile basepf; /* top level input file */
1051 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1052 static struct parsefile *parsefile = &basepf; /* current input file */
1055 * NEOF is returned by parsecmd when it encounters an end of file. It
1056 * must be distinct from NULL, so we use the address of a variable that
1057 * happens to be handy.
1060 static int tokpushback; /* last token pushed back */
1061 #define NEOF ((union node *)&tokpushback)
1062 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1065 static void error (const char *, ...) __attribute__((__noreturn__));
1066 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1067 static void shellexec (char **, char **, const char *, int)
1068 __attribute__((noreturn));
1069 static void exitshell (int) __attribute__((noreturn));
1071 static int goodname(const char *);
1072 static void ignoresig (int);
1073 static void onsig (int);
1074 static void dotrap (void);
1075 static int decode_signal (const char *, int);
1077 static void shprocvar(void);
1078 static void deletefuncs(void);
1079 static void setparam (char **);
1080 static void freeparam (volatile struct shparam *);
1082 static void find_command (const char *, struct cmdentry *, int, const char *);
1084 static inline void hashcd (void);
1086 /* reasons for skipping commands (see comment on breakcmd routine) */
1092 /* values of cmdtype */
1093 #define CMDUNKNOWN -1 /* no entry in table for command */
1094 #define CMDNORMAL 0 /* command is an executable program */
1095 #define CMDBUILTIN 1 /* command is a shell builtin */
1096 #define CMDFUNCTION 2 /* command is a shell function */
1098 #define DO_ERR 1 /* find_command prints errors */
1099 #define DO_ABS 2 /* find_command checks absolute paths */
1100 #define DO_NOFUN 4 /* find_command ignores functions */
1101 #define DO_BRUTE 8 /* find_command ignores hash table */
1108 #define VEXPORT 0x01 /* variable is exported */
1109 #define VREADONLY 0x02 /* variable cannot be modified */
1110 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1111 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1112 #define VSTACK 0x10 /* text is allocated on the stack */
1113 #define VUNSET 0x20 /* the variable is not set */
1114 #define VNOFUNC 0x40 /* don't call the callback function */
1118 struct var *next; /* next entry in hash list */
1119 int flags; /* flags are defined above */
1120 char *text; /* name=value */
1121 void (*func) (const char *);
1122 /* function to be called when */
1123 /* the variable gets set/unset */
1127 struct localvar *next; /* next local variable in list */
1128 struct var *vp; /* the variable that was made local */
1129 int flags; /* saved flags */
1130 char *text; /* saved text */
1134 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1135 #define rmescapes(p) _rmescapes((p), 0)
1136 static char *_rmescapes (char *, int);
1138 static void rmescapes (char *);
1141 static int casematch (union node *, const char *);
1142 static void clearredir(void);
1143 static void popstring(void);
1144 static void readcmdfile (const char *);
1146 static int number (const char *);
1147 static int is_number (const char *, int *num);
1148 static char *single_quote (const char *);
1149 static int nextopt (const char *);
1151 static void redirect (union node *, int);
1152 static void popredir (void);
1153 static int dup_as_newfd (int, int);
1155 static void changepath(const char *newval);
1156 static void getoptsreset(const char *value);
1159 static int parsenleft; /* copy of parsefile->nleft */
1160 static char *parsenextc; /* copy of parsefile->nextc */
1161 static int rootpid; /* pid of main shell */
1162 static int rootshell; /* true if we aren't a child of the main shell */
1164 static const char spcstr[] = " ";
1165 static const char snlfmt[] = "%s\n";
1167 static int sstrnleft;
1168 static int herefd = -1;
1170 static struct localvar *localvars;
1172 static struct var vifs;
1173 static struct var vmail;
1174 static struct var vmpath;
1175 static struct var vpath;
1176 static struct var vps1;
1177 static struct var vps2;
1178 static struct var voptind;
1179 #ifdef CONFIG_LOCALE_SUPPORT
1180 static struct var vlc_all;
1181 static struct var vlc_ctype;
1188 void (*func) (const char *);
1191 static const char defpathvar[] =
1192 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1193 #define defpath (defpathvar + 5)
1196 static const char defifsvar[] = "IFS= \t\n";
1197 #define defifs (defifsvar + 4)
1199 static const char defifs[] = " \t\n";
1202 static const struct varinit varinit[] = {
1204 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1206 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1209 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1211 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1213 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1215 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1216 { &vps1, VSTRFIXED|VTEXTFIXED, "PS1=\\w \\$ ",
1218 #endif /* else vps1 depends on uid */
1219 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1221 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1223 #ifdef CONFIG_LOCALE_SUPPORT
1224 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1226 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1235 static struct var *vartab[VTABSIZE];
1238 * The following macros access the values of the above variables.
1239 * They have to skip over the name. They return the null string
1240 * for unset variables.
1243 #define ifsval() (vifs.text + 4)
1244 #define ifsset() ((vifs.flags & VUNSET) == 0)
1245 #define mailval() (vmail.text + 5)
1246 #define mpathval() (vmpath.text + 9)
1247 #define pathval() (vpath.text + 5)
1248 #define ps1val() (vps1.text + 4)
1249 #define ps2val() (vps2.text + 4)
1250 #define optindval() (voptind.text + 7)
1252 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1254 static void initvar (void);
1255 static void setvar (const char *, const char *, int);
1256 static void setvareq (char *, int);
1257 static void listsetvar (struct strlist *);
1258 static const char *lookupvar (const char *);
1259 static const char *bltinlookup (const char *);
1260 static char **environment (void);
1261 static int showvarscmd (int, char **);
1262 static void mklocal (char *);
1263 static void poplocalvars (void);
1264 static int unsetvar (const char *);
1265 static int varequal (const char *, const char *);
1268 static char *arg0; /* value of $0 */
1269 static struct shparam shellparam; /* current positional parameters */
1270 static char **argptr; /* argument list for builtin commands */
1271 static char *optionarg; /* set by nextopt (like getopt) */
1272 static char *optptr; /* used by nextopt */
1273 static char *minusc; /* argument to -c option */
1276 #ifdef CONFIG_ASH_ALIAS
1278 #define ALIASINUSE 1
1290 static struct alias *atab[ATABSIZE];
1292 static void setalias (char *, char *);
1293 static struct alias **hashalias (const char *);
1294 static struct alias *freealias (struct alias *);
1295 static struct alias **__lookupalias (const char *);
1298 setalias(char *name, char *val)
1300 struct alias *ap, **app;
1302 app = __lookupalias(name);
1306 if (!(ap->flag & ALIASINUSE)) {
1309 ap->val = xstrdup(val);
1310 ap->flag &= ~ALIASDEAD;
1313 ap = xmalloc(sizeof (struct alias));
1314 ap->name = xstrdup(name);
1315 ap->val = xstrdup(val);
1328 app = __lookupalias(name);
1332 *app = freealias(*app);
1343 struct alias *ap, **app;
1347 for (i = 0; i < ATABSIZE; i++) {
1349 for (ap = *app; ap; ap = *app) {
1350 *app = freealias(*app);
1360 printalias(const struct alias *ap) {
1363 p = single_quote(ap->val);
1364 printf("alias %s=%s\n", ap->name, p);
1370 * TODO - sort output
1373 aliascmd(int argc, char **argv)
1382 for (i = 0; i < ATABSIZE; i++)
1383 for (ap = atab[i]; ap; ap = ap->next) {
1388 while ((n = *++argv) != NULL) {
1389 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1390 if ((ap = *__lookupalias(n)) == NULL) {
1391 out2fmt("%s: %s not found\n", "alias", n);
1406 unaliascmd(int argc, char **argv)
1410 while ((i = nextopt("a")) != '\0') {
1416 for (i = 0; *argptr; argptr++) {
1417 if (unalias(*argptr)) {
1418 out2fmt("%s: %s not found\n", "unalias", *argptr);
1426 static struct alias **
1427 hashalias(const char *p)
1429 unsigned int hashval;
1434 return &atab[hashval % ATABSIZE];
1437 static struct alias *
1438 freealias(struct alias *ap)
1442 if (ap->flag & ALIASINUSE) {
1443 ap->flag |= ALIASDEAD;
1455 static struct alias **
1456 __lookupalias(const char *name)
1458 struct alias **app = hashalias(name);
1460 for (; *app; app = &(*app)->next) {
1461 if (equal(name, (*app)->name)) {
1470 #ifdef CONFIG_ASH_MATH_SUPPORT
1471 /* The generated file arith.c has been replaced with a custom hand
1472 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1473 * This is now part of libbb, so that it can be used by all the shells
1475 static void expari (int);
1478 static char *trap[NSIG]; /* trap handler commands */
1479 static char sigmode[NSIG - 1]; /* current value of signal */
1480 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1481 static int pendingsigs; /* indicates some signal received */
1484 * This file was generated by the mkbuiltins program.
1487 #ifdef CONFIG_ASH_JOB_CONTROL
1488 static int bgcmd (int, char **);
1489 static int fgcmd (int, char **);
1490 static int killcmd (int, char **);
1492 static int bltincmd (int, char **);
1493 static int cdcmd (int, char **);
1494 static int breakcmd (int, char **);
1495 #ifdef CONFIG_ASH_CMDCMD
1496 static int commandcmd (int, char **);
1498 static int dotcmd (int, char **);
1499 static int evalcmd (int, char **);
1500 static int execcmd (int, char **);
1501 static int exitcmd (int, char **);
1502 static int exportcmd (int, char **);
1503 static int histcmd (int, char **);
1504 static int hashcmd (int, char **);
1505 static int helpcmd (int, char **);
1506 static int jobscmd (int, char **);
1507 static int localcmd (int, char **);
1508 static int pwdcmd (int, char **);
1509 static int readcmd (int, char **);
1510 static int returncmd (int, char **);
1511 static int setcmd (int, char **);
1512 static int setvarcmd (int, char **);
1513 static int shiftcmd (int, char **);
1514 static int trapcmd (int, char **);
1515 static int umaskcmd (int, char **);
1516 #ifdef CONFIG_ASH_ALIAS
1517 static int aliascmd (int, char **);
1518 static int unaliascmd (int, char **);
1520 static int unsetcmd (int, char **);
1521 static int waitcmd (int, char **);
1522 static int ulimitcmd (int, char **);
1523 static int timescmd (int, char **);
1524 #ifdef CONFIG_ASH_MATH_SUPPORT
1525 static int letcmd (int, char **);
1527 static int typecmd (int, char **);
1528 #ifdef CONFIG_ASH_GETOPTS
1529 static int getoptscmd (int, char **);
1533 static int true_main (int, char **);
1535 #ifndef CONFIG_FALSE
1536 static int false_main (int, char **);
1539 static void setpwd (const char *, int);
1542 #define BUILTIN_NOSPEC "0"
1543 #define BUILTIN_SPECIAL "1"
1544 #define BUILTIN_REGULAR "2"
1545 #define BUILTIN_ASSIGN "4"
1546 #define BUILTIN_SPEC_ASSG "5"
1547 #define BUILTIN_REG_ASSG "6"
1549 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1550 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1551 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1555 int (*const builtinfunc) (int, char **);
1560 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1561 * the binary search in find_builtin() will stop working. If you value
1562 * your kneecaps, you'll be sure to *make sure* that any changes made
1563 * to this array result in the listing remaining in ascii order. You
1566 static const struct builtincmd builtincmds[] = {
1567 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1568 { BUILTIN_SPECIAL ":", true_main },
1569 #ifdef CONFIG_ASH_ALIAS
1570 { BUILTIN_REG_ASSG "alias", aliascmd },
1572 #ifdef CONFIG_ASH_JOB_CONTROL
1573 { BUILTIN_REGULAR "bg", bgcmd },
1575 { BUILTIN_SPECIAL "break", breakcmd },
1576 { BUILTIN_SPECIAL "builtin", bltincmd },
1577 { BUILTIN_REGULAR "cd", cdcmd },
1578 { BUILTIN_NOSPEC "chdir", cdcmd },
1579 #ifdef CONFIG_ASH_CMDCMD
1580 { BUILTIN_REGULAR "command", commandcmd },
1582 { BUILTIN_SPECIAL "continue", breakcmd },
1583 { BUILTIN_SPECIAL "eval", evalcmd },
1584 { BUILTIN_SPECIAL "exec", execcmd },
1585 { BUILTIN_SPECIAL "exit", exitcmd },
1586 { BUILTIN_SPEC_ASSG "export", exportcmd },
1587 { BUILTIN_REGULAR "false", false_main },
1588 { BUILTIN_REGULAR "fc", histcmd },
1589 #ifdef CONFIG_ASH_JOB_CONTROL
1590 { BUILTIN_REGULAR "fg", fgcmd },
1592 #ifdef CONFIG_ASH_GETOPTS
1593 { BUILTIN_REGULAR "getopts", getoptscmd },
1595 { BUILTIN_NOSPEC "hash", hashcmd },
1596 { BUILTIN_NOSPEC "help", helpcmd },
1597 { BUILTIN_REGULAR "jobs", jobscmd },
1598 #ifdef CONFIG_ASH_JOB_CONTROL
1599 { BUILTIN_REGULAR "kill", killcmd },
1601 #ifdef CONFIG_ASH_MATH_SUPPORT
1602 { BUILTIN_REGULAR "let", letcmd },
1604 { BUILTIN_ASSIGN "local", localcmd },
1605 { BUILTIN_NOSPEC "pwd", pwdcmd },
1606 { BUILTIN_REGULAR "read", readcmd },
1607 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1608 { BUILTIN_SPECIAL "return", returncmd },
1609 { BUILTIN_SPECIAL "set", setcmd },
1610 { BUILTIN_NOSPEC "setvar", setvarcmd },
1611 { BUILTIN_SPECIAL "shift", shiftcmd },
1612 { BUILTIN_SPECIAL "times", timescmd },
1613 { BUILTIN_SPECIAL "trap", trapcmd },
1614 { BUILTIN_REGULAR "true", true_main },
1615 { BUILTIN_NOSPEC "type", typecmd },
1616 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1617 { BUILTIN_REGULAR "umask", umaskcmd },
1618 #ifdef CONFIG_ASH_ALIAS
1619 { BUILTIN_REGULAR "unalias", unaliascmd },
1621 { BUILTIN_SPECIAL "unset", unsetcmd },
1622 { BUILTIN_REGULAR "wait", waitcmd },
1624 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1626 #define DOTCMD &builtincmds[0]
1627 static struct builtincmd *BLTINCMD;
1628 static struct builtincmd *EXECCMD;
1629 static struct builtincmd *EVALCMD;
1632 #define CONFIG_ASH_JOB_CONTROLTOPPED 1 /* all procs are stopped */
1633 #define JOBDONE 2 /* all procs are completed */
1636 * A job structure contains information about a job. A job is either a
1637 * single process or a set of processes contained in a pipeline. In the
1638 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1643 pid_t pid; /* process id */
1644 int status; /* status flags (defined above) */
1645 char *cmd; /* text of command being run */
1649 static int job_warning; /* user was warned about stopped jobs */
1651 #ifdef CONFIG_ASH_JOB_CONTROL
1652 static void setjobctl(int enable);
1654 #define setjobctl(on) /* do nothing */
1659 struct procstat ps0; /* status of process */
1660 struct procstat *ps; /* status or processes when more than one */
1661 short nprocs; /* number of processes */
1662 short pgrp; /* process group of this job */
1663 char state; /* true if job is finished */
1664 char used; /* true if this entry is in used */
1665 char changed; /* true if status has changed */
1666 #ifdef CONFIG_ASH_JOB_CONTROL
1667 char jobctl; /* job running under job control */
1671 static struct job *jobtab; /* array of jobs */
1672 static int njobs; /* size of array */
1673 static int backgndpid = -1; /* pid of last background process */
1674 #ifdef CONFIG_ASH_JOB_CONTROL
1675 static int initialpgrp; /* pgrp of shell on invocation */
1676 static int curjob; /* current job */
1679 static int intreceived;
1681 static struct job *makejob (const union node *, int);
1682 static int forkshell (struct job *, const union node *, int);
1683 static int waitforjob (struct job *);
1685 static int docd (char *, int);
1686 static void getpwd (void);
1688 static char *padvance (const char **, const char *);
1690 static char nullstr[1]; /* zero length string */
1691 static char *curdir = nullstr; /* current working directory */
1694 cdcmd(int argc, char **argv)
1703 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1704 error("HOME not set");
1707 if (dest[0] == '-' && dest[1] == '\0') {
1708 dest = bltinlookup("OLDPWD");
1709 if (!dest || !*dest) {
1718 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1720 while ((p = padvance(&path, dest)) != NULL) {
1721 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1726 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1728 print = strcmp(p, dest);
1730 if (docd(p, print) >= 0)
1735 error("can't cd to %s", dest);
1741 * Actually do the chdir. In an interactive shell, print the
1742 * directory name if "print" is nonzero.
1746 docd(char *dest, int print)
1748 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1750 if (chdir(dest) < 0) {
1756 * Update curdir (the name of the current directory) in response to a
1757 * cd command. We also call hashcd to let the routines in exec.c know
1758 * that the current directory has changed.
1760 /* If dest is NULL, we don't know the current directory */
1761 if (dest == NULL || curdir == nullstr)
1774 pwdcmd(int argc, char **argv)
1780 /* Ask system the current directory */
1784 curdir = xgetcwd(0);
1790 setpwd(const char *val, int setold)
1795 setvar("OLDPWD", curdir, VEXPORT);
1798 if (curdir != nullstr) {
1799 if(val!=NULL && *val != '/')
1800 val = cated = concat_path_file(curdir, val);
1806 curdir = simplify_path(val);
1809 setvar("PWD", curdir, VEXPORT);
1813 * Errors and exceptions.
1817 * Code to handle exceptions in C.
1821 * We enclose jmp_buf in a structure so that we can declare pointers to
1822 * jump locations. The global variable handler contains the location to
1823 * jump to when an exception occurs, and the global variable exception
1824 * contains a code identifying the exeception. To implement nested
1825 * exception handlers, the user should save the value of handler on entry
1826 * to an inner scope, set handler to point to a jmploc structure for the
1827 * inner scope, and restore handler on exit from the scope.
1835 #define EXINT 0 /* SIGINT received */
1836 #define EXERROR 1 /* a generic error */
1837 #define EXSHELLPROC 2 /* execute a shell procedure */
1838 #define EXEXEC 3 /* command execution failed */
1840 static struct jmploc *handler;
1841 static int exception;
1843 static void exverror (int, const char *, va_list)
1844 __attribute__((__noreturn__));
1847 * Called to raise an exception. Since C doesn't include exceptions, we
1848 * just do a longjmp to the exception handler. The type of exception is
1849 * stored in the global variable "exception".
1852 static void exraise (int) __attribute__((__noreturn__));
1858 if (handler == NULL)
1863 longjmp(handler->loc, 1);
1868 * Called from trap.c when a SIGINT is received. (If the user specifies
1869 * that SIGINT is to be trapped or ignored using the trap builtin, then
1870 * this routine is not called.) Suppressint is nonzero when interrupts
1871 * are held using the INTOFF macro. The call to _exit is necessary because
1872 * there is a short period after a fork before the signal handlers are
1873 * set to the appropriate value for the child. (The test for iflag is
1874 * just defensive programming.)
1886 sigemptyset(&mysigset);
1887 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1888 if (rootshell && iflag)
1891 signal(SIGINT, SIG_DFL);
1898 static char *commandname; /* currently executing command */
1901 * Exverror is called to raise the error exception. If the first argument
1902 * is not NULL then error prints an error message using printf style
1903 * formatting. It then raises the error exception.
1906 exverror(int cond, const char *msg, va_list ap)
1913 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1915 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1919 out2fmt("%s: ", commandname);
1920 vfprintf(stderr, msg, ap);
1929 error(const char *msg, ...)
1933 exverror(EXERROR, msg, ap);
1940 exerror(int cond, const char *msg, ...)
1944 exverror(cond, msg, ap);
1952 * Table of error messages.
1956 short errcode; /* error number */
1957 short action; /* operation which encountered the error */
1961 * Types of operations (passed to the errmsg routine).
1964 #define E_OPEN 01 /* opening a file */
1965 #define E_CREAT 02 /* creating a file */
1966 #define E_EXEC 04 /* executing a program */
1968 #define ALL (E_OPEN|E_CREAT|E_EXEC)
1970 static const struct errname errormsg[] = {
1975 { ENOENT, E_CREAT },
1977 { ENOTDIR, E_OPEN },
1978 { ENOTDIR, E_CREAT },
1979 { ENOTDIR, E_EXEC },
1981 { EEXIST, E_CREAT },
2020 { ELIBACC, E_EXEC },
2024 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2027 * Return a string describing an error. The returned string may be a
2028 * pointer to a static buffer that will be overwritten on the next call.
2029 * Action describes the operation that got the error.
2033 errmsg(int e, int action)
2035 struct errname const *ep;
2036 static char buf[12];
2038 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2039 if (ep->errcode == e && (ep->action & action) != 0)
2043 snprintf(buf, sizeof buf, "error %d", e);
2048 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
2051 if (--suppressint == 0 && intpending) {
2055 static void forceinton (void) {
2062 /* flags in argument to evaltree */
2063 #define EV_EXIT 01 /* exit after evaluating tree */
2064 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2065 #define EV_BACKCMD 04 /* command executing within back quotes */
2067 static int evalskip; /* set if we are skipping commands */
2068 static int skipcount; /* number of levels to skip */
2069 static int loopnest; /* current loop nesting level */
2070 static int funcnest; /* depth of function calls */
2073 static struct strlist *cmdenviron; /* environment for builtin command */
2074 static int exitstatus; /* exit status of last command */
2075 static int oexitstatus; /* saved exit status */
2077 static void evalsubshell (const union node *, int);
2078 static void expredir (union node *);
2079 static void eprintlist (struct strlist *);
2081 static union node *parsecmd(int);
2083 * Called to reset things after an exception.
2087 * The eval commmand.
2089 static void evalstring (char *, int);
2092 evalcmd(int argc, char **argv)
2101 STARTSTACKSTR(concat);
2105 STPUTC(*p++, concat);
2106 if ((p = *ap++) == NULL)
2108 STPUTC(' ', concat);
2110 STPUTC('\0', concat);
2111 p = grabstackstr(concat);
2113 evalstring(p, EV_TESTED);
2119 * Execute a command or commands contained in a string.
2122 static void evaltree (union node *, int);
2123 static void setinputstring (char *);
2124 static void popfile (void);
2125 static void setstackmark(struct stackmark *mark);
2126 static void popstackmark(struct stackmark *mark);
2130 evalstring(char *s, int flag)
2133 struct stackmark smark;
2135 setstackmark(&smark);
2137 while ((n = parsecmd(0)) != NEOF) {
2139 popstackmark(&smark);
2142 popstackmark(&smark);
2145 static struct builtincmd *find_builtin (const char *);
2146 static void expandarg (union node *, struct arglist *, int);
2147 static void calcsize (const union node *);
2148 static union node *copynode (const union node *);
2151 * Make a copy of a parse tree.
2154 static int funcblocksize; /* size of structures in function */
2155 static int funcstringsize; /* size of strings in node */
2156 static pointer funcblock; /* block to allocate function from */
2157 static char *funcstring; /* block to allocate strings from */
2160 static inline union node *
2161 copyfunc(union node *n)
2168 funcblock = xmalloc(funcblocksize + funcstringsize);
2169 funcstring = (char *) funcblock + funcblocksize;
2174 * Add a new command entry, replacing any existing command entry for
2179 addcmdentry(char *name, struct cmdentry *entry)
2181 struct tblentry *cmdp;
2184 cmdp = cmdlookup(name, 1);
2185 if (cmdp->cmdtype == CMDFUNCTION) {
2186 free(cmdp->param.func);
2188 cmdp->cmdtype = entry->cmdtype;
2189 cmdp->param = entry->u;
2194 evalloop(const union node *n, int flags)
2201 evaltree(n->nbinary.ch1, EV_TESTED);
2203 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2207 if (evalskip == SKIPBREAK && --skipcount <= 0)
2211 if (n->type == NWHILE) {
2212 if (exitstatus != 0)
2215 if (exitstatus == 0)
2218 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2219 status = exitstatus;
2224 exitstatus = status;
2228 evalfor(const union node *n, int flags)
2230 struct arglist arglist;
2233 struct stackmark smark;
2235 setstackmark(&smark);
2236 arglist.lastp = &arglist.list;
2237 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2238 oexitstatus = exitstatus;
2239 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2243 *arglist.lastp = NULL;
2247 for (sp = arglist.list ; sp ; sp = sp->next) {
2248 setvar(n->nfor.var, sp->text, 0);
2249 evaltree(n->nfor.body, flags & EV_TESTED);
2251 if (evalskip == SKIPCONT && --skipcount <= 0) {
2255 if (evalskip == SKIPBREAK && --skipcount <= 0)
2262 popstackmark(&smark);
2266 evalcase(const union node *n, int flags)
2270 struct arglist arglist;
2271 struct stackmark smark;
2273 setstackmark(&smark);
2274 arglist.lastp = &arglist.list;
2275 oexitstatus = exitstatus;
2276 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2277 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2278 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2279 if (casematch(patp, arglist.list->text)) {
2280 if (evalskip == 0) {
2281 evaltree(cp->nclist.body, flags);
2288 popstackmark(&smark);
2292 * Evaluate a pipeline. All the processes in the pipeline are children
2293 * of the process creating the pipeline. (This differs from some versions
2294 * of the shell, which make the last process in a pipeline the parent
2298 static inline void evalpipe(union node *n)
2301 struct nodelist *lp;
2306 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2308 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2311 jp = makejob(n, pipelen);
2313 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2315 * Search for a command. This is called before we fork so that the
2316 * location of the command will be available in the parent as well as
2317 * the child. The check for "goodname" is an overly conservative
2318 * check that the name will not be subject to expansion.
2321 struct cmdentry entry;
2322 union node *lpn = lp->n;
2323 if (lpn->type == NCMD && lpn->ncmd.args && goodname(lpn->ncmd.args->narg.text))
2324 find_command(lpn->ncmd.args->narg.text, &entry, 0, pathval());
2328 if (pipe(pip) < 0) {
2330 error("Pipe call failed");
2333 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2337 dup_as_newfd(prevfd, 0);
2349 dup_as_newfd(pip[1], 1);
2353 evaltree(lp->n, EV_EXIT);
2361 if (n->npipe.backgnd == 0) {
2363 exitstatus = waitforjob(jp);
2364 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2370 isassignment(const char *word) {
2371 if (!is_name(*word)) {
2376 } while (is_in_name(*word));
2377 return *word == '=';
2382 evalcommand(union node *cmd, int flags)
2384 struct stackmark smark;
2386 struct arglist arglist;
2387 struct arglist varlist;
2393 struct cmdentry cmdentry;
2395 char *volatile savecmdname;
2396 volatile struct shparam saveparam;
2397 struct localvar *volatile savelocalvars;
2401 const struct builtincmd *firstbltin;
2402 struct jmploc *volatile savehandler;
2403 struct jmploc jmploc;
2405 /* Avoid longjmp clobbering */
2412 /* First expand the arguments. */
2413 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2414 setstackmark(&smark);
2415 arglist.lastp = &arglist.list;
2416 varlist.lastp = &varlist.list;
2418 oexitstatus = exitstatus;
2421 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2422 expandarg(argp, &varlist, EXP_VARTILDE);
2425 argp = cmd->ncmd.args; argp && !arglist.list;
2426 argp = argp->narg.next
2428 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2431 struct builtincmd *bcmd;
2433 bcmd = find_builtin(arglist.list->text);
2434 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2435 for (; argp; argp = argp->narg.next) {
2436 if (pseudovarflag && isassignment(argp->narg.text)) {
2437 expandarg(argp, &arglist, EXP_VARTILDE);
2440 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2443 *arglist.lastp = NULL;
2444 *varlist.lastp = NULL;
2445 expredir(cmd->ncmd.redirect);
2447 for (sp = arglist.list ; sp ; sp = sp->next)
2449 argv = stalloc(sizeof (char *) * (argc + 1));
2451 for (sp = arglist.list ; sp ; sp = sp->next) {
2452 TRACE(("evalcommand arg: %s\n", sp->text));
2457 if (iflag && funcnest == 0 && argc > 0)
2461 /* Print the command if xflag is set. */
2464 eprintlist(varlist.list);
2465 eprintlist(arglist.list);
2469 /* Now locate the command. */
2471 cmdentry.cmdtype = CMDBUILTIN;
2472 firstbltin = cmdentry.u.cmd = BLTINCMD;
2474 const char *oldpath;
2475 int findflag = DO_ERR;
2479 * Modify the command lookup path, if a PATH= assignment
2482 for (sp = varlist.list ; sp ; sp = sp->next)
2483 if (varequal(sp->text, defpathvar)) {
2484 path = sp->text + 5;
2485 findflag |= DO_BRUTE;
2488 oldfindflag = findflag;
2491 find_command(argv[0], &cmdentry, findflag, path);
2492 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2496 /* implement bltin and command here */
2497 if (cmdentry.cmdtype != CMDBUILTIN) {
2501 firstbltin = cmdentry.u.cmd;
2503 if (cmdentry.u.cmd == BLTINCMD) {
2505 struct builtincmd *bcmd;
2510 if (!(bcmd = find_builtin(*argv))) {
2511 out2fmt("%s: not found\n", *argv);
2515 cmdentry.u.cmd = bcmd;
2516 if (bcmd != BLTINCMD)
2520 if (cmdentry.u.cmd == find_builtin("command")) {
2525 if (*argv[0] == '-') {
2526 if (!equal(argv[0], "-p")) {
2536 findflag |= DO_BRUTE;
2539 findflag = oldfindflag;
2541 findflag |= DO_NOFUN;
2549 /* Fork off a child process if necessary. */
2550 if (cmd->ncmd.backgnd
2551 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2553 jp = makejob(cmd, 1);
2554 mode = cmd->ncmd.backgnd;
2555 if (forkshell(jp, cmd, mode) != 0)
2556 goto parent; /* at end of routine */
2560 /* This is the child process if a fork occurred. */
2561 /* Execute the command. */
2562 if (cmdentry.cmdtype == CMDFUNCTION) {
2564 trputs("Shell function: "); trargs(argv);
2566 exitstatus = oexitstatus;
2567 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2568 saveparam = shellparam;
2569 shellparam.malloc = 0;
2570 shellparam.nparam = argc - 1;
2571 shellparam.p = argv + 1;
2573 savelocalvars = localvars;
2576 if (setjmp(jmploc.loc)) {
2577 if (exception == EXSHELLPROC) {
2578 freeparam((volatile struct shparam *)
2581 saveparam.optind = shellparam.optind;
2582 saveparam.optoff = shellparam.optoff;
2583 freeparam(&shellparam);
2584 shellparam = saveparam;
2587 localvars = savelocalvars;
2588 handler = savehandler;
2589 longjmp(handler->loc, 1);
2591 savehandler = handler;
2593 for (sp = varlist.list ; sp ; sp = sp->next)
2596 evaltree(cmdentry.u.func, flags & EV_TESTED);
2600 localvars = savelocalvars;
2601 saveparam.optind = shellparam.optind;
2602 saveparam.optoff = shellparam.optoff;
2603 freeparam(&shellparam);
2604 shellparam = saveparam;
2605 handler = savehandler;
2608 if (evalskip == SKIPFUNC) {
2612 if (flags & EV_EXIT)
2613 exitshell(exitstatus);
2614 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2616 trputs("builtin command: "); trargs(argv);
2618 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2619 redirect(cmd->ncmd.redirect, mode);
2620 savecmdname = commandname;
2621 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2622 listsetvar(varlist.list);
2624 cmdenviron = varlist.list;
2627 if (setjmp(jmploc.loc)) {
2629 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2632 savehandler = handler;
2634 commandname = argv[0];
2636 optptr = NULL; /* initialize nextopt */
2637 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2641 if (e != EXSHELLPROC) {
2642 commandname = savecmdname;
2643 if (flags & EV_EXIT)
2644 exitshell(exitstatus);
2646 handler = savehandler;
2648 if ((e != EXERROR && e != EXEXEC)
2649 || cmdentry.u.cmd == BLTINCMD
2650 || cmdentry.u.cmd == DOTCMD
2651 || cmdentry.u.cmd == EVALCMD
2652 || cmdentry.u.cmd == EXECCMD)
2656 if (cmdentry.u.cmd != EXECCMD)
2660 trputs("normal command: "); trargs(argv);
2662 redirect(cmd->ncmd.redirect, 0);
2664 for (sp = varlist.list ; sp ; sp = sp->next)
2665 setvareq(sp->text, VEXPORT|VSTACK);
2666 envp = environment();
2667 shellexec(argv, envp, path, cmdentry.u.index);
2671 parent: /* parent process gets here (if we forked) */
2672 if (mode == 0) { /* argument to fork */
2674 exitstatus = waitforjob(jp);
2680 setvar("_", lastarg, 0);
2681 popstackmark(&smark);
2685 * Evaluate a parse tree. The value is left in the global variable
2689 evaltree(union node *n, int flags)
2693 TRACE(("evaltree(NULL) called\n"));
2696 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2699 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2702 evaltree(n->nbinary.ch2, flags);
2705 evaltree(n->nbinary.ch1, EV_TESTED);
2706 if (evalskip || exitstatus != 0)
2708 evaltree(n->nbinary.ch2, flags);
2711 evaltree(n->nbinary.ch1, EV_TESTED);
2712 if (evalskip || exitstatus == 0)
2714 evaltree(n->nbinary.ch2, flags);
2717 expredir(n->nredir.redirect);
2718 redirect(n->nredir.redirect, REDIR_PUSH);
2719 evaltree(n->nredir.n, flags);
2723 evalsubshell(n, flags);
2726 evalsubshell(n, flags);
2729 evaltree(n->nif.test, EV_TESTED);
2732 if (exitstatus == 0)
2733 evaltree(n->nif.ifpart, flags);
2734 else if (n->nif.elsepart)
2735 evaltree(n->nif.elsepart, flags);
2751 struct builtincmd *bcmd;
2752 struct cmdentry entry;
2754 (bcmd = find_builtin(n->narg.text)) &&
2755 IS_BUILTIN_SPECIAL(bcmd)
2757 out2fmt("%s is a special built-in\n", n->narg.text);
2761 entry.cmdtype = CMDFUNCTION;
2762 entry.u.func = copyfunc(n->narg.next);
2763 addcmdentry(n->narg.text, &entry);
2768 evaltree(n->nnot.com, EV_TESTED);
2769 exitstatus = !exitstatus;
2777 evalcommand(n, flags);
2782 printf("Node type = %d\n", n->type);
2791 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2793 exitshell(exitstatus);
2797 * Kick off a subshell to evaluate a tree.
2801 evalsubshell(const union node *n, int flags)
2804 int backgnd = (n->type == NBACKGND);
2806 expredir(n->nredir.redirect);
2808 if (forkshell(jp, n, backgnd) == 0) {
2810 flags &=~ EV_TESTED;
2811 redirect(n->nredir.redirect, 0);
2812 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2816 exitstatus = waitforjob(jp);
2822 * Compute the names of the files in a redirection list.
2825 static void fixredir(union node *n, const char *text, int err);
2828 expredir(union node *n)
2832 for (redir = n ; redir ; redir = redir->nfile.next) {
2834 fn.lastp = &fn.list;
2835 oexitstatus = exitstatus;
2836 switch (redir->type) {
2842 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2843 redir->nfile.expfname = fn.list->text;
2847 if (redir->ndup.vname) {
2848 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2849 fixredir(redir, fn.list->text, 1);
2858 * Execute a command inside back quotes. If it's a builtin command, we
2859 * want to save its output in a block obtained from malloc. Otherwise
2860 * we fork off a subprocess and get the output of the command via a pipe.
2861 * Should be called with interrupts off.
2865 evalbackcmd(union node *n, struct backcmd *result)
2869 struct stackmark smark; /* unnecessary */
2871 setstackmark(&smark);
2882 error("Pipe call failed");
2884 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2889 dup_as_newfd(pip[1], 1);
2893 evaltree(n, EV_EXIT);
2896 result->fd = pip[0];
2899 popstackmark(&smark);
2900 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2901 result->fd, result->buf, result->nleft, result->jp));
2906 * Execute a simple command.
2911 * Builtin commands. Builtin commands whose functions are closely
2912 * tied to evaluation are implemented here.
2916 * No command given, or a bltin command with no arguments. Set the
2917 * specified variables.
2921 bltincmd(int argc, char **argv)
2924 * Preserve exitstatus of a previous possible redirection
2932 * Handle break and continue commands. Break, continue, and return are
2933 * all handled by setting the evalskip flag. The evaluation routines
2934 * above all check this flag, and if it is set they start skipping
2935 * commands rather than executing them. The variable skipcount is
2936 * the number of loops to break/continue, or the number of function
2937 * levels to return. (The latter is always 1.) It should probably
2938 * be an error to break out of more loops than exist, but it isn't
2939 * in the standard shell so we don't make it one here.
2943 breakcmd(int argc, char **argv)
2945 int n = argc > 1 ? number(argv[1]) : 1;
2948 error("Illegal number: %s", argv[1]);
2952 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
2960 * The return command.
2964 returncmd(int argc, char **argv)
2966 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
2969 evalskip = SKIPFUNC;
2974 /* Do what ksh does; skip the rest of the file */
2975 evalskip = SKIPFILE;
2982 #ifndef CONFIG_FALSE
2984 false_main(int argc, char **argv)
2992 true_main(int argc, char **argv)
2999 * Controls whether the shell is interactive or not.
3002 static void setsignal(int signo);
3004 #ifdef CONFIG_ASH_MAIL
3005 static void chkmail(int silent);
3009 setinteractive(int on)
3011 static int is_interactive;
3012 static int do_banner=0;
3014 if (on == is_interactive)
3019 #ifdef CONFIG_ASH_MAIL
3022 is_interactive = on;
3023 if (do_banner==0 && is_interactive) {
3024 /* Looks like they want an interactive shell */
3025 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3026 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3027 printf( "Enter 'help' for a list of built-in commands.\n\n");
3036 setinteractive(iflag);
3042 execcmd(int argc, char **argv)
3047 iflag = 0; /* exit on error */
3050 for (sp = cmdenviron; sp ; sp = sp->next)
3051 setvareq(sp->text, VEXPORT|VSTACK);
3052 shellexec(argv + 1, environment(), pathval(), 0);
3058 eprintlist(struct strlist *sp)
3060 for (; sp; sp = sp->next) {
3061 out2fmt(" %s",sp->text);
3066 * Exec a program. Never returns. If you change this routine, you may
3067 * have to change the find_command routine as well.
3070 static const char *pathopt; /* set by padvance */
3073 shellexec(char **argv, char **envp, const char *path, int idx)
3078 if (strchr(argv[0], '/') != NULL) {
3079 tryexec(argv[0], argv, envp);
3083 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3084 if (--idx < 0 && pathopt == NULL) {
3085 tryexec(cmdname, argv, envp);
3086 if (errno != ENOENT && errno != ENOTDIR)
3093 /* Map to POSIX errors */
3105 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3110 * Clear traps on a fork.
3117 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3118 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3123 setsignal(tp - trap);
3134 #ifdef CONFIG_ASH_ALIAS
3153 #ifdef CONFIG_ASH_JOB_CONTROL
3158 /* from options.c: */
3162 for (i = 0; i < NOPTS; i++)
3178 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3190 static int preadbuffer(void);
3191 static void pushfile (void);
3194 * Read a character from the script, returning PEOF on end of file.
3195 * Nul characters in the input are silently discarded.
3198 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
3199 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3203 return pgetc_macro();
3209 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3215 return pgetc_macro();
3221 * Undo the last call to pgetc. Only one character may be pushed back.
3222 * PEOF may be pushed back.
3225 static void pungetc(void)
3235 struct parsefile *pf = parsefile;
3243 parsefile = pf->prev;
3245 parsenleft = parsefile->nleft;
3246 parselleft = parsefile->lleft;
3247 parsenextc = parsefile->nextc;
3248 plinno = parsefile->linno;
3254 * Return to top level.
3260 while (parsefile != &basepf)
3265 * Close the file(s) that the shell is reading commands from. Called
3266 * after a fork is done.
3269 static void closescript(void)
3272 if (parsefile->fd > 0) {
3273 close(parsefile->fd);
3280 * Like setinputfile, but takes an open file descriptor. Call this with
3284 static void setinputfd(int fd, int push)
3286 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3292 while (parsefile->strpush)
3296 if (parsefile->buf == NULL)
3297 parsefile->buf = xmalloc(BUFSIZ);
3298 parselleft = parsenleft = 0;
3304 * Set the input to take input from a file. If push is set, push the
3305 * old input onto the stack first.
3309 setinputfile(const char *fname, int push)
3315 if ((fd = open(fname, O_RDONLY)) < 0)
3316 error("Can't open %s", fname);
3318 myfileno2 = dup_as_newfd(fd, 10);
3321 error("Out of file descriptors");
3324 setinputfd(fd, push);
3330 tryexec(char *cmd, char **argv, char **envp)
3334 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3338 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3339 name = get_last_path_component(name);
3342 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3345 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3347 run_applet_by_name(name, argc_l, argv);
3349 execve(cmd, argv, envp);
3354 setinputfile(cmd, 0);
3355 commandname = arg0 = xstrdup(argv[0]);
3357 exraise(EXSHELLPROC);
3362 static char *commandtext (const union node *);
3365 * Do a path search. The variable path (passed by reference) should be
3366 * set to the start of the path before the first call; padvance will update
3367 * this value as it proceeds. Successive calls to padvance will return
3368 * the possible path expansions in sequence. If an option (indicated by
3369 * a percent sign) appears in the path entry then the global variable
3370 * pathopt will be set to point to it; otherwise pathopt will be set to
3374 static const char *pathopt;
3376 static void growstackblock(void);
3380 padvance(const char **path, const char *name)
3390 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3391 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3392 while (stackblocksize() < len)
3396 memcpy(q, start, p - start);
3404 while (*p && *p != ':') p++;
3410 return stalloc(len);
3414 * Wrapper around strcmp for qsort/bsearch/...
3417 pstrcmp(const void *a, const void *b)
3419 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3423 * Find a keyword is in a sorted array.
3426 static const char *const *
3427 findkwd(const char *s)
3429 return bsearch(s, tokname_array + KWDOFFSET,
3430 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3431 sizeof(const char *), pstrcmp);
3435 /*** Command hashing code ***/
3439 hashcmd(int argc, char **argv)
3441 struct tblentry **pp;
3442 struct tblentry *cmdp;
3445 struct cmdentry entry;
3447 #ifdef CONFIG_ASH_ALIAS
3448 const struct alias *ap;
3452 while ((c = nextopt("rvV")) != '\0') {
3456 } else if (c == 'v' || c == 'V') {
3460 if (*argptr == NULL) {
3461 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3462 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3463 if (cmdp->cmdtype != CMDBUILTIN) {
3464 printentry(cmdp, verbose);
3471 while ((name = *argptr++) != NULL) {
3472 if ((cmdp = cmdlookup(name, 0)) != NULL
3473 && (cmdp->cmdtype == CMDNORMAL
3474 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3476 #ifdef CONFIG_ASH_ALIAS
3477 /* Then look at the aliases */
3478 if ((ap = *__lookupalias(name)) != NULL) {
3480 printf("%s is an alias for %s\n", name, ap->val);
3486 /* First look at the keywords */
3487 if (findkwd(name)!=0) {
3489 printf("%s is a shell keyword\n", name);
3495 find_command(name, &entry, DO_ERR, pathval());
3496 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3498 cmdp = cmdlookup(name, 0);
3499 if (cmdp) printentry(cmdp, verbose=='v');
3507 printentry(struct tblentry *cmdp, int verbose)
3513 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3514 if (cmdp->cmdtype == CMDNORMAL) {
3515 idx = cmdp->param.index;
3518 name = padvance(&path, cmdp->cmdname);
3520 } while (--idx >= 0);
3523 } else if (cmdp->cmdtype == CMDBUILTIN) {
3525 out1str("a shell builtin");
3526 } else if (cmdp->cmdtype == CMDFUNCTION) {
3529 out1str("a function\n");
3530 name = commandtext(cmdp->param.func);
3531 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3537 error("internal error: cmdtype %d", cmdp->cmdtype);
3540 puts(cmdp->rehash ? "*" : nullstr);
3545 /*** List the available builtins ***/
3548 static int helpcmd(int argc, char** argv)
3552 printf("\nBuilt-in commands:\n-------------------\n");
3553 for (col=0, i=0; i < NUMBUILTINS; i++) {
3554 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3555 builtincmds[i].name+1);
3561 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3563 extern const struct BB_applet applets[];
3564 extern const size_t NUM_APPLETS;
3566 for (i=0; i < NUM_APPLETS; i++) {
3568 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3578 return EXIT_SUCCESS;
3582 * Resolve a command name. If you change this routine, you may have to
3583 * change the shellexec routine as well.
3586 static int prefix (const char *, const char *);
3589 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3591 struct tblentry *cmdp;
3601 struct builtincmd *bcmd;
3603 /* If name contains a slash, don't use the hash table */
3604 if (strchr(name, '/') != NULL) {
3606 while (stat(name, &statb) < 0) {
3607 if (errno != ENOENT && errno != ENOTDIR)
3609 entry->cmdtype = CMDUNKNOWN;
3610 entry->u.index = -1;
3613 entry->cmdtype = CMDNORMAL;
3614 entry->u.index = -1;
3617 entry->cmdtype = CMDNORMAL;
3623 if (act & DO_BRUTE) {
3624 firstchange = path_change(path, &bltin);
3630 /* If name is in the table, and not invalidated by cd, we're done */
3631 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3632 if (cmdp->cmdtype == CMDFUNCTION) {
3633 if (act & DO_NOFUN) {
3638 } else if (act & DO_BRUTE) {
3639 if ((cmdp->cmdtype == CMDNORMAL &&
3640 cmdp->param.index >= firstchange) ||
3641 (cmdp->cmdtype == CMDBUILTIN &&
3642 ((builtinloc < 0 && bltin >= 0) ?
3643 bltin : builtinloc) >= firstchange)) {
3644 /* need to recompute the entry */
3653 bcmd = find_builtin(name);
3654 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3657 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3660 } else if (act & DO_BRUTE) {
3661 if (firstchange == 0) {
3666 /* If %builtin not in path, check for builtin next */
3667 if (regular || (bltin < 0 && bcmd)) {
3670 entry->cmdtype = CMDBUILTIN;
3671 entry->u.cmd = bcmd;
3675 cmdp = cmdlookup(name, 1);
3676 cmdp->cmdtype = CMDBUILTIN;
3677 cmdp->param.cmd = bcmd;
3682 /* We have to search path. */
3683 prev = -1; /* where to start */
3684 if (cmdp && cmdp->rehash) { /* doing a rehash */
3685 if (cmdp->cmdtype == CMDBUILTIN)
3688 prev = cmdp->param.index;
3694 while ((fullname = padvance(&path, name)) != NULL) {
3695 stunalloc(fullname);
3697 if (idx >= firstchange) {
3701 if (prefix("builtin", pathopt)) {
3702 if ((bcmd = find_builtin(name))) {
3706 } else if (!(act & DO_NOFUN) &&
3707 prefix("func", pathopt)) {
3710 continue; /* ignore unimplemented options */
3713 /* if rehash, don't redo absolute path names */
3714 if (fullname[0] == '/' && idx <= prev &&
3715 idx < firstchange) {
3718 TRACE(("searchexec \"%s\": no change\n", name));
3721 while (stat(fullname, &statb) < 0) {
3722 if (errno != ENOENT && errno != ENOTDIR)
3726 e = EACCES; /* if we fail, this will be the error */
3727 if (!S_ISREG(statb.st_mode))
3729 if (pathopt) { /* this is a %func directory */
3730 stalloc(strlen(fullname) + 1);
3731 readcmdfile(fullname);
3732 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3733 error("%s not defined in %s", name, fullname);
3734 stunalloc(fullname);
3737 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3738 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3739 be a function and we're being called with DO_NOFUN */
3741 entry->cmdtype = CMDNORMAL;
3742 entry->u.index = idx;
3746 cmdp = cmdlookup(name, 1);
3747 cmdp->cmdtype = CMDNORMAL;
3748 cmdp->param.index = idx;
3753 /* We failed. If there was an entry for this command, delete it */
3754 if (cmdp && updatetbl)
3757 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3758 entry->cmdtype = CMDUNKNOWN;
3763 entry->cmdtype = cmdp->cmdtype;
3764 entry->u = cmdp->param;
3770 * Search the table of builtin commands.
3774 bstrcmp(const void *name, const void *b)
3776 return strcmp((const char *)name, (*(const char *const *) b)+1);
3779 static struct builtincmd *
3780 find_builtin(const char *name)
3782 struct builtincmd *bp;
3784 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3792 * Called when a cd is done. Marks all commands so the next time they
3793 * are executed they will be rehashed.
3799 struct tblentry **pp;
3800 struct tblentry *cmdp;
3802 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3803 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3804 if (cmdp->cmdtype == CMDNORMAL
3805 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3814 * Called before PATH is changed. The argument is the new value of PATH;
3815 * pathval() still returns the old value at this point. Called with
3820 changepath(const char *newval)
3825 firstchange = path_change(newval, &bltin);
3826 if (builtinloc < 0 && bltin >= 0)
3827 builtinloc = bltin; /* zap builtins */
3828 clearcmdentry(firstchange);
3830 /* Ensure that getenv("PATH") stays current */
3831 setenv("PATH", newval, 1);
3836 * Clear out command entries. The argument specifies the first entry in
3837 * PATH which has changed.
3841 clearcmdentry(int firstchange)
3843 struct tblentry **tblp;
3844 struct tblentry **pp;
3845 struct tblentry *cmdp;
3848 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3850 while ((cmdp = *pp) != NULL) {
3851 if ((cmdp->cmdtype == CMDNORMAL &&
3852 cmdp->param.index >= firstchange)
3853 || (cmdp->cmdtype == CMDBUILTIN &&
3854 builtinloc >= firstchange)) {
3867 * Delete all functions.
3873 struct tblentry **tblp;
3874 struct tblentry **pp;
3875 struct tblentry *cmdp;
3878 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3880 while ((cmdp = *pp) != NULL) {
3881 if (cmdp->cmdtype == CMDFUNCTION) {
3883 free(cmdp->param.func);
3896 * Locate a command in the command hash table. If "add" is nonzero,
3897 * add the command to the table if it is not already present. The
3898 * variable "lastcmdentry" is set to point to the address of the link
3899 * pointing to the entry, so that delete_cmd_entry can delete the
3903 static struct tblentry **lastcmdentry;
3905 static struct tblentry *
3906 cmdlookup(const char *name, int add)
3910 struct tblentry *cmdp;
3911 struct tblentry **pp;
3918 pp = &cmdtable[hashval % CMDTABLESIZE];
3919 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3920 if (equal(cmdp->cmdname, name))
3924 if (add && cmdp == NULL) {
3926 cmdp = *pp = xmalloc(sizeof (struct tblentry) - ARB
3927 + strlen(name) + 1);
3929 cmdp->cmdtype = CMDUNKNOWN;
3931 strcpy(cmdp->cmdname, name);
3939 * Delete the command entry returned on the last lookup.
3945 struct tblentry *cmdp;
3948 cmdp = *lastcmdentry;
3949 *lastcmdentry = cmdp->next;
3958 static const unsigned char nodesize[26] = {
3959 ALIGN(sizeof (struct nbinary)),
3960 ALIGN(sizeof (struct ncmd)),
3961 ALIGN(sizeof (struct npipe)),
3962 ALIGN(sizeof (struct nredir)),
3963 ALIGN(sizeof (struct nredir)),
3964 ALIGN(sizeof (struct nredir)),
3965 ALIGN(sizeof (struct nbinary)),
3966 ALIGN(sizeof (struct nbinary)),
3967 ALIGN(sizeof (struct nif)),
3968 ALIGN(sizeof (struct nbinary)),
3969 ALIGN(sizeof (struct nbinary)),
3970 ALIGN(sizeof (struct nfor)),
3971 ALIGN(sizeof (struct ncase)),
3972 ALIGN(sizeof (struct nclist)),
3973 ALIGN(sizeof (struct narg)),
3974 ALIGN(sizeof (struct narg)),
3975 ALIGN(sizeof (struct nfile)),
3976 ALIGN(sizeof (struct nfile)),
3977 ALIGN(sizeof (struct nfile)),
3978 ALIGN(sizeof (struct nfile)),
3979 ALIGN(sizeof (struct nfile)),
3980 ALIGN(sizeof (struct ndup)),
3981 ALIGN(sizeof (struct ndup)),
3982 ALIGN(sizeof (struct nhere)),
3983 ALIGN(sizeof (struct nhere)),
3984 ALIGN(sizeof (struct nnot)),
3990 * Delete a function if it exists.
3994 unsetfunc(char *name)
3996 struct tblentry *cmdp;
3998 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
3999 free(cmdp->param.func);
4006 * Locate and print what a word is...
4010 typecmd(int argc, char **argv)
4018 for (i = 1; i < argc; i++) {
4019 argv_a[0] = argv[i];
4022 err |= hashcmd(argc, argv);
4027 #ifdef CONFIG_ASH_CMDCMD
4029 commandcmd(int argc, char **argv)
4032 int default_path = 0;
4033 int verify_only = 0;
4034 int verbose_verify_only = 0;
4036 while ((c = nextopt("pvV")) != '\0')
4045 verbose_verify_only = 1;
4049 if (default_path + verify_only + verbose_verify_only > 1 ||
4052 "command [-p] command [arg ...]\n"
4053 "command {-v|-V} command\n");
4057 if (verify_only || verbose_verify_only) {
4061 argv_a[0] = *argptr;
4063 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4064 return hashcmd(argc, argv);
4072 path_change(const char *newval, int *bltin)
4074 const char *old, *new;
4080 firstchange = 9999; /* assume no change */
4086 if ((*old == '\0' && *new == ':')
4087 || (*old == ':' && *new == '\0'))
4089 old = new; /* ignore subsequent differences */
4093 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4100 if (builtinloc >= 0 && *bltin < 0)
4105 * Routines to expand arguments to commands. We have to deal with
4106 * backquotes, shell variables, and file metacharacters.
4111 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4112 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4115 * Structure specifying which parts of the string should be searched
4116 * for IFS characters.
4120 struct ifsregion *next; /* next region in list */
4121 int begoff; /* offset of start of region */
4122 int endoff; /* offset of end of region */
4123 int nulonly; /* search for nul bytes only */
4127 static char *expdest; /* output of current string */
4128 static struct nodelist *argbackq; /* list of back quote expressions */
4129 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4130 static struct ifsregion *ifslastp; /* last struct in list */
4131 static struct arglist exparg; /* holds expanded arg list */
4133 static void argstr (char *, int);
4134 static char *exptilde (char *, int);
4135 static void expbackq (union node *, int, int);
4136 static int subevalvar (char *, char *, int, int, int, int, int);
4137 static int varisset (char *, int);
4138 static void strtodest (const char *, int, int);
4139 static inline void varvalue (char *, int, int);
4140 static void recordregion (int, int, int);
4141 static void removerecordregions (int);
4142 static void ifsbreakup (char *, struct arglist *);
4143 static void ifsfree (void);
4144 static void expandmeta (struct strlist *, int);
4145 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4146 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4147 #if !defined(GLOB_BROKEN)
4148 static inline void addglob (const glob_t *);
4151 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4152 static void expmeta (char *, char *);
4154 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4155 static struct strlist *expsort (struct strlist *);
4156 static struct strlist *msort (struct strlist *, int);
4158 static int patmatch (char *, char *, int);
4159 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4160 static int patmatch2 (char *, char *, int);
4162 static int pmatch (char *, char *, int);
4163 #define patmatch2 patmatch
4165 static char *cvtnum (int, char *);
4168 * Expand shell variables and backquotes inside a here document.
4171 /* arg: the document, fd: where to write the expanded version */
4173 expandhere(union node *arg, int fd)
4176 expandarg(arg, (struct arglist *)NULL, 0);
4177 xwrite(fd, stackblock(), expdest - stackblock());
4182 * Perform variable substitution and command substitution on an argument,
4183 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4184 * perform splitting and file name expansion. When arglist is NULL, perform
4185 * here document expansion.
4189 expandarg(union node *arg, struct arglist *arglist, int flag)
4194 argbackq = arg->narg.backquote;
4195 STARTSTACKSTR(expdest);
4196 ifsfirst.next = NULL;
4198 argstr(arg->narg.text, flag);
4199 if (arglist == NULL) {
4200 return; /* here document expanded */
4202 STPUTC('\0', expdest);
4203 p = grabstackstr(expdest);
4204 exparg.lastp = &exparg.list;
4208 if (flag & EXP_FULL) {
4209 ifsbreakup(p, &exparg);
4210 *exparg.lastp = NULL;
4211 exparg.lastp = &exparg.list;
4212 expandmeta(exparg.list, flag);
4214 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4216 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4219 exparg.lastp = &sp->next;
4222 *exparg.lastp = NULL;
4224 *arglist->lastp = exparg.list;
4225 arglist->lastp = exparg.lastp;
4231 * Expand a variable, and return a pointer to the next character in the
4235 static inline char * evalvar(char *p, int flag)
4248 int quotes = flag & (EXP_FULL | EXP_CASE);
4251 subtype = varflags & VSTYPE;
4256 p = strchr(p, '=') + 1;
4257 again: /* jump here after setting a variable with ${var=text} */
4259 set = varisset(var, varflags & VSNUL);
4262 val = lookupvar(var);
4263 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4270 startloc = expdest - stackblock();
4271 if (set && subtype != VSPLUS) {
4272 /* insert the value of the variable */
4274 varvalue(var, varflags & VSQUOTE, flag);
4275 if (subtype == VSLENGTH) {
4276 varlen = expdest - stackblock() - startloc;
4277 STADJUST(-varlen, expdest);
4280 if (subtype == VSLENGTH) {
4281 varlen = strlen(val);
4285 varflags & VSQUOTE ?
4286 DQSYNTAX : BASESYNTAX,
4293 if (subtype == VSPLUS)
4296 easy = ((varflags & VSQUOTE) == 0 ||
4297 (*var == '@' && shellparam.nparam != 1));
4302 expdest = cvtnum(varlen, expdest);
4309 recordregion(startloc, expdest - stackblock(),
4310 varflags & VSQUOTE);
4326 case VSTRIMRIGHTMAX:
4330 * Terminate the string and start recording the pattern
4333 STPUTC('\0', expdest);
4334 patloc = expdest - stackblock();
4335 if (subevalvar(p, NULL, patloc, subtype,
4336 startloc, varflags, quotes) == 0) {
4337 int amount = (expdest - stackblock() - patloc) + 1;
4338 STADJUST(-amount, expdest);
4340 /* Remove any recorded regions beyond start of variable */
4341 removerecordregions(startloc);
4347 if (subevalvar(p, var, 0, subtype, startloc,
4348 varflags, quotes)) {
4351 * Remove any recorded regions beyond
4354 removerecordregions(startloc);
4369 if (subtype != VSNORMAL) { /* skip to end of alternative */
4372 if ((c = *p++) == CTLESC)
4374 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4376 argbackq = argbackq->next;
4377 } else if (c == CTLVAR) {
4378 if ((*p++ & VSTYPE) != VSNORMAL)
4380 } else if (c == CTLENDVAR) {
4391 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4392 * characters to allow for further processing. Otherwise treat
4393 * $@ like $* since no splitting will be performed.
4397 argstr(char *p, int flag)
4400 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4403 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4404 p = exptilde(p, flag);
4408 case CTLENDVAR: /* ??? */
4411 /* "$@" syntax adherence hack */
4412 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4414 if ((flag & EXP_FULL) != 0)
4424 p = evalvar(p, flag);
4427 case CTLBACKQ|CTLQUOTE:
4428 expbackq(argbackq->n, c & CTLQUOTE, flag);
4429 argbackq = argbackq->next;
4431 #ifdef CONFIG_ASH_MATH_SUPPORT
4439 * sort of a hack - expand tildes in variable
4440 * assignments (after the first '=' and after ':'s).
4443 if (flag & EXP_VARTILDE && *p == '~') {
4450 p = exptilde(p, flag);
4461 exptilde(char *p, int flag)
4463 char c, *startp = p;
4466 int quotes = flag & (EXP_FULL | EXP_CASE);
4468 while ((c = *p) != '\0') {
4475 if (flag & EXP_VARTILDE)
4485 if (*(startp+1) == '\0') {
4486 if ((home = lookupvar("HOME")) == NULL)
4489 if ((pw = getpwnam(startp+1)) == NULL)
4496 strtodest(home, SQSYNTAX, quotes);
4505 removerecordregions(int endoff)
4507 if (ifslastp == NULL)
4510 if (ifsfirst.endoff > endoff) {
4511 while (ifsfirst.next != NULL) {
4512 struct ifsregion *ifsp;
4514 ifsp = ifsfirst.next->next;
4515 free(ifsfirst.next);
4516 ifsfirst.next = ifsp;
4519 if (ifsfirst.begoff > endoff)
4522 ifslastp = &ifsfirst;
4523 ifsfirst.endoff = endoff;
4528 ifslastp = &ifsfirst;
4529 while (ifslastp->next && ifslastp->next->begoff < endoff)
4530 ifslastp=ifslastp->next;
4531 while (ifslastp->next != NULL) {
4532 struct ifsregion *ifsp;
4534 ifsp = ifslastp->next->next;
4535 free(ifslastp->next);
4536 ifslastp->next = ifsp;
4539 if (ifslastp->endoff > endoff)
4540 ifslastp->endoff = endoff;
4544 #ifdef CONFIG_ASH_MATH_SUPPORT
4546 * Expand arithmetic expression. Backup to start of expression,
4547 * evaluate, place result in (backed up) result, adjust string position.
4556 int quotes = flag & (EXP_FULL | EXP_CASE);
4562 * This routine is slightly over-complicated for
4563 * efficiency. First we make sure there is
4564 * enough space for the result, which may be bigger
4565 * than the expression if we add exponentation. Next we
4566 * scan backwards looking for the start of arithmetic. If the
4567 * next previous character is a CTLESC character, then we
4568 * have to rescan starting from the beginning since CTLESC
4569 * characters have to be processed left to right.
4571 CHECKSTRSPACE(10, expdest);
4572 USTPUTC('\0', expdest);
4573 start = stackblock();
4575 while (*p != CTLARI && p >= start)
4578 error("missing CTLARI (shouldn't happen)");
4579 if (p > start && *(p-1) == CTLESC)
4580 for (p = start; *p != CTLARI; p++)
4589 removerecordregions(begoff);
4592 result = arith(p+2, &errcode);
4595 error("divide by zero");
4597 error("syntax error: \"%s\"\n", p+2);
4599 snprintf(p, 12, "%d", result);
4605 recordregion(begoff, p - 1 - start, 0);
4606 result = expdest - p + 1;
4607 STADJUST(-result, expdest);
4612 * Expand stuff in backwards quotes.
4616 expbackq(union node *cmd, int quoted, int flag)
4618 volatile struct backcmd in;
4622 char *dest = expdest;
4623 volatile struct ifsregion saveifs;
4624 struct ifsregion *volatile savelastp;
4625 struct nodelist *volatile saveargbackq;
4627 int startloc = dest - stackblock();
4628 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4629 volatile int saveherefd;
4630 int quotes = flag & (EXP_FULL | EXP_CASE);
4631 struct jmploc jmploc;
4632 struct jmploc *volatile savehandler;
4636 /* Avoid longjmp clobbering */
4647 savelastp = ifslastp;
4648 saveargbackq = argbackq;
4649 saveherefd = herefd;
4651 if ((ex = setjmp(jmploc.loc))) {
4654 savehandler = handler;
4657 p = grabstackstr(dest);
4658 evalbackcmd(cmd, (struct backcmd *) &in);
4659 ungrabstackstr(p, dest);
4663 ifslastp = savelastp;
4664 argbackq = saveargbackq;
4665 herefd = saveherefd;
4673 if (--in.nleft < 0) {
4676 i = safe_read(in.fd, buf, sizeof buf);
4677 TRACE(("expbackq: read returns %d\n", i));
4684 if (lastc != '\0') {
4685 if (quotes && SIT(lastc, syntax) == CCTL)
4686 STPUTC(CTLESC, dest);
4687 STPUTC(lastc, dest);
4691 /* Eat all trailing newlines */
4692 for (; dest > stackblock() && dest[-1] == '\n';)
4700 exitstatus = waitforjob(in.jp);
4701 handler = savehandler;
4703 longjmp(handler->loc, 1);
4706 recordregion(startloc, dest - stackblock(), 0);
4707 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4708 (dest - stackblock()) - startloc,
4709 (dest - stackblock()) - startloc,
4710 stackblock() + startloc));
4716 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
4722 int saveherefd = herefd;
4723 struct nodelist *saveargbackq = argbackq;
4727 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4728 STACKSTRNUL(expdest);
4729 herefd = saveherefd;
4730 argbackq = saveargbackq;
4731 startp = stackblock() + startloc;
4733 str = stackblock() + strloc;
4737 setvar(str, startp, 0);
4738 amount = startp - expdest;
4739 STADJUST(amount, expdest);
4746 if (*p != CTLENDVAR) {
4747 out2fmt(snlfmt, startp);
4748 error((char *)NULL);
4750 error("%.*s: parameter %snot set", p - str - 1,
4751 str, (varflags & VSNUL) ? "null or "
4756 for (loc = startp; loc < str; loc++) {
4759 if (patmatch2(str, startp, quotes))
4762 if (quotes && *loc == CTLESC)
4768 for (loc = str - 1; loc >= startp;) {
4771 if (patmatch2(str, startp, quotes))
4775 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4776 for (q = startp; q < loc; q++)
4786 for (loc = str - 1; loc >= startp;) {
4787 if (patmatch2(str, loc, quotes))
4790 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4791 for (q = startp; q < loc; q++)
4800 case VSTRIMRIGHTMAX:
4801 for (loc = startp; loc < str - 1; loc++) {
4802 if (patmatch2(str, loc, quotes))
4804 if (quotes && *loc == CTLESC)
4817 amount = ((str - 1) - (loc - startp)) - expdest;
4818 STADJUST(amount, expdest);
4819 while (loc != str - 1)
4824 amount = loc - expdest;
4825 STADJUST(amount, expdest);
4826 STPUTC('\0', expdest);
4827 STADJUST(-1, expdest);
4833 * Test whether a specialized variable is set.
4837 varisset(char *name, int nulok)
4840 return backgndpid != -1;
4841 else if (*name == '@' || *name == '*') {
4842 if (*shellparam.p == NULL)
4848 for (av = shellparam.p; *av; av++)
4853 } else if (is_digit(*name)) {
4855 int num = atoi(name);
4857 if (num > shellparam.nparam)
4863 ap = shellparam.p[num - 1];
4865 if (nulok && (ap == NULL || *ap == '\0'))
4872 * Put a string on the stack.
4876 strtodest(const char *p, int syntax, int quotes)
4879 if (quotes && SIT(*p,syntax) == CCTL)
4880 STPUTC(CTLESC, expdest);
4881 STPUTC(*p++, expdest);
4886 * Add the value of a specialized variable to the stack string.
4890 varvalue(char *name, int quoted, int flags)
4899 int allow_split = flags & EXP_FULL;
4900 int quotes = flags & (EXP_FULL | EXP_CASE);
4902 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4911 num = shellparam.nparam;
4916 expdest = cvtnum(num, expdest);
4919 for (i = 0 ; i < NOPTS ; i++) {
4921 STPUTC(optent_letter(optlist[i]), expdest);
4925 if (allow_split && quoted) {
4926 sep = 1 << CHAR_BIT;
4931 sep = ifsset() ? ifsval()[0] : ' ';
4933 sepq = SIT(sep,syntax) == CCTL;
4936 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
4937 strtodest(p, syntax, quotes);
4940 STPUTC(CTLESC, expdest);
4941 STPUTC(sep, expdest);
4946 strtodest(arg0, syntax, quotes);
4950 if (num > 0 && num <= shellparam.nparam) {
4951 strtodest(shellparam.p[num - 1], syntax, quotes);
4959 * Record the fact that we have to scan this region of the
4960 * string for IFS characters.
4964 recordregion(int start, int end, int nulonly)
4966 struct ifsregion *ifsp;
4968 if (ifslastp == NULL) {
4972 ifsp = (struct ifsregion *)xmalloc(sizeof (struct ifsregion));
4974 ifslastp->next = ifsp;
4978 ifslastp->begoff = start;
4979 ifslastp->endoff = end;
4980 ifslastp->nulonly = nulonly;
4986 * Break the argument string into pieces based upon IFS and add the
4987 * strings to the argument list. The regions of the string to be
4988 * searched for IFS characters have been stored by recordregion.
4991 ifsbreakup(char *string, struct arglist *arglist)
4993 struct ifsregion *ifsp;
4998 const char *ifs, *realifs;
5006 realifs = ifsset() ? ifsval() : defifs;
5007 if (ifslastp != NULL) {
5010 p = string + ifsp->begoff;
5011 nulonly = ifsp->nulonly;
5012 ifs = nulonly ? nullstr : realifs;
5014 while (p < string + ifsp->endoff) {
5018 if (strchr(ifs, *p)) {
5020 ifsspc = (strchr(defifs, *p) != NULL);
5021 /* Ignore IFS whitespace at start */
5022 if (q == start && ifsspc) {
5028 sp = (struct strlist *)stalloc(sizeof *sp);
5030 *arglist->lastp = sp;
5031 arglist->lastp = &sp->next;
5035 if (p >= string + ifsp->endoff) {
5041 if (strchr(ifs, *p) == NULL ) {
5044 } else if (strchr(defifs, *p) == NULL) {
5060 } while ((ifsp = ifsp->next) != NULL);
5061 if (!(*start || (!ifsspc && start > string && nulonly))) {
5066 sp = (struct strlist *)stalloc(sizeof *sp);
5068 *arglist->lastp = sp;
5069 arglist->lastp = &sp->next;
5075 while (ifsfirst.next != NULL) {
5076 struct ifsregion *ifsp;
5078 ifsp = ifsfirst.next->next;
5079 free(ifsfirst.next);
5080 ifsfirst.next = ifsp;
5084 ifsfirst.next = NULL;
5088 * Add a file name to the list.
5092 addfname(const char *name)
5096 sp = (struct strlist *)stalloc(sizeof *sp);
5097 sp->text = sstrdup(name);
5099 exparg.lastp = &sp->next;
5103 * Expand shell metacharacters. At this point, the only control characters
5104 * should be escapes. The results are stored in the list exparg.
5107 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5109 expandmeta(struct strlist *str, int flag)
5113 /* TODO - EXP_REDIR */
5118 p = preglob(str->text);
5120 switch (glob(p, 0, 0, &pglob)) {
5122 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5133 *exparg.lastp = str;
5134 rmescapes(str->text);
5135 exparg.lastp = &str->next;
5137 default: /* GLOB_NOSPACE */
5138 error("Out of space");
5146 * Add the result of glob(3) to the list.
5150 addglob(const glob_t *pglob)
5152 char **p = pglob->gl_pathv;
5160 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5161 static char *expdir;
5165 expandmeta(struct strlist *str, int flag)
5168 struct strlist **savelastp;
5171 /* TODO - EXP_REDIR */
5177 for (;;) { /* fast check for meta chars */
5178 if ((c = *p++) == '\0')
5180 if (c == '*' || c == '?' || c == '[' || c == '!')
5183 savelastp = exparg.lastp;
5185 if (expdir == NULL) {
5186 int i = strlen(str->text);
5187 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5190 expmeta(expdir, str->text);
5194 if (exparg.lastp == savelastp) {
5199 *exparg.lastp = str;
5200 rmescapes(str->text);
5201 exparg.lastp = &str->next;
5203 *exparg.lastp = NULL;
5204 *savelastp = sp = expsort(*savelastp);
5205 while (sp->next != NULL)
5207 exparg.lastp = &sp->next;
5215 * Do metacharacter (i.e. *, ?, [...]) expansion.
5219 expmeta(char *enddir, char *name)
5235 for (p = name ; ; p++) {
5236 if (*p == '*' || *p == '?')
5238 else if (*p == '[') {
5243 while (*q == CTLQUOTEMARK)
5247 if (*q == '/' || *q == '\0')
5254 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5256 } else if (*p == '\0')
5258 else if (*p == CTLQUOTEMARK)
5260 else if (*p == CTLESC)
5268 if (metaflag == 0) { /* we've reached the end of the file name */
5269 if (enddir != expdir)
5271 for (p = name ; ; p++) {
5272 if (*p == CTLQUOTEMARK)
5280 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5285 if (start != name) {
5288 while (*p == CTLQUOTEMARK)
5295 if (enddir == expdir) {
5297 } else if (enddir == expdir + 1 && *expdir == '/') {
5303 if ((dirp = opendir(cp)) == NULL)
5305 if (enddir != expdir)
5307 if (*endname == 0) {
5315 while (*p == CTLQUOTEMARK)
5321 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5322 if (dp->d_name[0] == '.' && ! matchdot)
5324 if (patmatch(start, dp->d_name, 0)) {
5326 strcpy(enddir, dp->d_name);
5329 for (p = enddir, cp = dp->d_name;
5330 (*p++ = *cp++) != '\0';)
5333 expmeta(p, endname);
5341 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5345 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5347 * Sort the results of file name expansion. It calculates the number of
5348 * strings to sort and then calls msort (short for merge sort) to do the
5352 static struct strlist *
5353 expsort(struct strlist *str)
5359 for (sp = str ; sp ; sp = sp->next)
5361 return msort(str, len);
5365 static struct strlist *
5366 msort(struct strlist *list, int len)
5368 struct strlist *p, *q = NULL;
5369 struct strlist **lpp;
5377 for (n = half ; --n >= 0 ; ) {
5381 q->next = NULL; /* terminate first half of list */
5382 q = msort(list, half); /* sort first half of list */
5383 p = msort(p, len - half); /* sort second half */
5386 if (strcmp(p->text, q->text) < 0) {
5389 if ((p = *lpp) == NULL) {
5396 if ((q = *lpp) == NULL) {
5409 * Returns true if the pattern matches the string.
5412 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5413 /* squoted: string might have quote chars */
5415 patmatch(char *pattern, char *string, int squoted)
5420 p = preglob(pattern);
5421 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5423 return !fnmatch(p, q, 0);
5428 patmatch2(char *pattern, char *string, int squoted)
5434 p = grabstackstr(expdest);
5435 res = patmatch(pattern, string, squoted);
5436 ungrabstackstr(p, expdest);
5441 patmatch(char *pattern, char *string, int squoted) {
5442 return pmatch(pattern, string, squoted);
5447 pmatch(char *pattern, char *string, int squoted)
5459 if (squoted && *q == CTLESC)
5467 if (squoted && *q == CTLESC)
5474 while (c == CTLQUOTEMARK || c == '*')
5476 if (c != CTLESC && c != CTLQUOTEMARK &&
5477 c != '?' && c != '*' && c != '[') {
5479 if (squoted && *q == CTLESC &&
5484 if (squoted && *q == CTLESC)
5490 if (pmatch(p, q, squoted))
5492 if (squoted && *q == CTLESC)
5494 } while (*q++ != '\0');
5505 while (*endp == CTLQUOTEMARK)
5508 goto dft; /* no matching ] */
5509 if (*endp == CTLESC)
5521 if (squoted && chr == CTLESC)
5527 if (c == CTLQUOTEMARK)
5531 if (*p == '-' && p[1] != ']') {
5533 while (*p == CTLQUOTEMARK)
5537 if (chr >= c && chr <= *p)
5544 } while ((c = *p++) != ']');
5545 if (found == invert)
5550 if (squoted && *q == CTLESC)
5567 * Remove any CTLESC characters from a string.
5570 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5572 _rmescapes(char *str, int flag)
5575 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5577 p = strpbrk(str, qchars);
5583 if (flag & RMESCAPE_ALLOC) {
5584 size_t len = p - str;
5585 q = r = stalloc(strlen(p) + len + 1);
5587 memcpy(q, str, len);
5592 if (*p == CTLQUOTEMARK) {
5598 if (flag & RMESCAPE_GLOB && *p != '/') {
5609 rmescapes(char *str)
5614 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5620 if (*p == CTLQUOTEMARK) {
5635 * See if a pattern matches in a case statement.
5639 casematch(union node *pattern, const char *val)
5641 struct stackmark smark;
5645 setstackmark(&smark);
5646 argbackq = pattern->narg.backquote;
5647 STARTSTACKSTR(expdest);
5649 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5650 STPUTC('\0', expdest);
5651 p = grabstackstr(expdest);
5652 result = patmatch(p, (char *)val, 0);
5653 popstackmark(&smark);
5662 cvtnum(int num, char *buf)
5666 CHECKSTRSPACE(32, buf);
5667 len = sprintf(buf, "%d", num);
5672 * Editline and history functions (and glue).
5674 static int histcmd(int argc, char **argv)
5676 error("not compiled with history support");
5682 struct redirtab *next;
5683 short renamed[10]; /* Current ash support only 0-9 descriptors */
5684 /* char on arm (and others) can't be negative */
5687 static struct redirtab *redirlist;
5689 extern char **environ;
5694 * Initialization code.
5708 basepf.nextc = basepf.buf = basebuf;
5717 for (envp = environ ; *envp ; envp++) {
5718 if (strchr(*envp, '=')) {
5719 setvareq(*envp, VEXPORT|VTEXTFIXED);
5723 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5724 setvar("PPID", ppid, 0);
5731 * This routine is called when an error or an interrupt occurs in an
5732 * interactive shell and control is returned to the main command loop.
5735 /* 1 == check for aliases, 2 == also check for assignments */
5736 static int checkalias; /* also used in no alias mode for check assignments */
5750 if (exception != EXSHELLPROC)
5751 parselleft = parsenleft = 0; /* clear input buffer */
5755 /* from parser.c: */
5773 * This file implements the input routines used by the parser.
5776 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5777 static const char * cmdedit_prompt;
5778 static inline void putprompt(const char *s) {
5782 static inline void putprompt(const char *s) {
5787 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5792 * Same as pgetc(), but ignores PEOA.
5795 #ifdef CONFIG_ASH_ALIAS
5802 } while (c == PEOA);
5806 static inline int pgetc2(void) { return pgetc_macro(); }
5810 * Read a line from the script.
5813 static inline char *
5814 pfgets(char *line, int len)
5820 while (--nleft > 0) {
5839 char *buf = parsefile->buf;
5843 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5845 if (!iflag || parsefile->fd)
5846 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5848 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5852 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5856 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5857 int flags = fcntl(0, F_GETFL, 0);
5858 if (flags >= 0 && flags & O_NONBLOCK) {
5859 flags &=~ O_NONBLOCK;
5860 if (fcntl(0, F_SETFL, flags) >= 0) {
5861 out2str("sh: turning off NDELAY mode\n");
5873 struct strpush *sp = parsefile->strpush;
5876 #ifdef CONFIG_ASH_ALIAS
5878 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5883 if (sp->string != sp->ap->val) {
5887 sp->ap->flag &= ~ALIASINUSE;
5888 if (sp->ap->flag & ALIASDEAD) {
5889 unalias(sp->ap->name);
5893 parsenextc = sp->prevstring;
5894 parsenleft = sp->prevnleft;
5895 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5896 parsefile->strpush = sp->prev;
5897 if (sp != &(parsefile->basestrpush))
5904 * Refill the input buffer and return the next input character:
5906 * 1) If a string was pushed back on the input, pop it;
5907 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5908 * from a string so we can't refill the buffer, return EOF.
5909 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5910 * 4) Process input up to the next newline, deleting nul characters.
5920 while (parsefile->strpush) {
5921 #ifdef CONFIG_ASH_ALIAS
5922 if (parsenleft == -1 && parsefile->strpush->ap &&
5923 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5928 if (--parsenleft >= 0)
5929 return (*parsenextc++);
5931 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5936 if (parselleft <= 0) {
5937 if ((parselleft = preadfd()) <= 0) {
5938 parselleft = parsenleft = EOF_NLEFT;
5945 /* delete nul characters */
5946 for (more = 1; more;) {
5954 parsenleft = q - parsenextc;
5955 more = 0; /* Stop processing here */
5961 if (--parselleft <= 0 && more) {
5962 parsenleft = q - parsenextc - 1;
5973 out2str(parsenextc);
5978 return *parsenextc++;
5983 * Push a string back onto the input at this current parsefile level.
5984 * We handle aliases this way.
5987 pushstring(char *s, int len, void *ap)
5992 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
5993 if (parsefile->strpush) {
5994 sp = xmalloc(sizeof (struct strpush));
5995 sp->prev = parsefile->strpush;
5996 parsefile->strpush = sp;
5998 sp = parsefile->strpush = &(parsefile->basestrpush);
5999 sp->prevstring = parsenextc;
6000 sp->prevnleft = parsenleft;
6001 #ifdef CONFIG_ASH_ALIAS
6002 sp->ap = (struct alias *)ap;
6004 ((struct alias *)ap)->flag |= ALIASINUSE;
6015 * Like setinputfile, but takes input from a string.
6019 setinputstring(char *string)
6023 parsenextc = string;
6024 parsenleft = strlen(string);
6025 parsefile->buf = NULL;
6033 * To handle the "." command, a stack of input files is used. Pushfile
6034 * adds a new entry to the stack and popfile restores the previous level.
6040 struct parsefile *pf;
6042 parsefile->nleft = parsenleft;
6043 parsefile->lleft = parselleft;
6044 parsefile->nextc = parsenextc;
6045 parsefile->linno = plinno;
6046 pf = (struct parsefile *)xmalloc(sizeof (struct parsefile));
6047 pf->prev = parsefile;
6050 pf->basestrpush.prev = NULL;
6054 #ifdef CONFIG_ASH_JOB_CONTROL
6055 static void restartjob (struct job *);
6057 static void freejob (struct job *);
6058 static struct job *getjob (const char *);
6059 static int dowait (int, struct job *);
6060 static void waitonint(int);
6064 * We keep track of whether or not fd0 has been redirected. This is for
6065 * background commands, where we want to redirect fd0 to /dev/null only
6066 * if it hasn't already been redirected.
6068 static int fd0_redirected = 0;
6070 /* Return true if fd 0 has already been redirected at least once. */
6072 fd0_redirected_p (void)
6074 return fd0_redirected != 0;
6077 static void dupredirect (const union node *, int, int fd1dup);
6079 #ifdef CONFIG_ASH_JOB_CONTROL
6081 * Turn job control on and off.
6083 * Note: This code assumes that the third arg to ioctl is a character
6084 * pointer, which is true on Berkeley systems but not System V. Since
6085 * System V doesn't have job control yet, this isn't a problem now.
6090 static void setjobctl(int enable)
6092 #ifdef OLD_TTY_DRIVER
6096 if (enable == jobctl || rootshell == 0)
6099 do { /* while we are in the background */
6100 #ifdef OLD_TTY_DRIVER
6101 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6103 initialpgrp = tcgetpgrp(2);
6104 if (initialpgrp < 0) {
6106 out2str("sh: can't access tty; job control turned off\n");
6110 if (initialpgrp == -1)
6111 initialpgrp = getpgrp();
6112 else if (initialpgrp != getpgrp()) {
6113 killpg(initialpgrp, SIGTTIN);
6117 #ifdef OLD_TTY_DRIVER
6118 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6119 out2str("sh: need new tty driver to run job control; job control turned off\n");
6127 setpgid(0, rootpid);
6128 #ifdef OLD_TTY_DRIVER
6129 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6131 tcsetpgrp(2, rootpid);
6133 } else { /* turning job control off */
6134 setpgid(0, initialpgrp);
6135 #ifdef OLD_TTY_DRIVER
6136 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6138 tcsetpgrp(2, initialpgrp);
6149 #ifdef CONFIG_ASH_JOB_CONTROL
6151 killcmd(int argc, char **argv)
6162 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6163 "kill -l [exitstatus]"
6167 if (*argv[1] == '-') {
6168 signo = decode_signal(argv[1] + 1, 1);
6172 while ((c = nextopt("ls:")) != '\0')
6178 signo = decode_signal(optionarg, 1);
6181 "invalid signal number or name: %s",
6189 "nextopt returned character code 0%o", c);
6196 if (!list && signo < 0)
6199 if ((signo < 0 || !*argptr) ^ list) {
6208 for (i = 1; i < NSIG; i++) {
6209 name = u_signal_names(0, &i, 1);
6215 name = u_signal_names(*argptr, &signo, -1);
6219 error("invalid signal number or exit status: %s",
6225 if (**argptr == '%') {
6226 jp = getjob(*argptr);
6227 if (jp->jobctl == 0)
6228 error("job %s not created under job control",
6230 pid = -jp->ps[0].pid;
6232 pid = atoi(*argptr);
6233 if (kill(pid, signo) != 0)
6234 error("%s: %m", *argptr);
6235 } while (*++argptr);
6241 fgcmd(int argc, char **argv)
6247 jp = getjob(argv[1]);
6248 if (jp->jobctl == 0)
6249 error("job not created under job control");
6250 pgrp = jp->ps[0].pid;
6251 #ifdef OLD_TTY_DRIVER
6252 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6257 status = waitforjob(jp);
6263 bgcmd(int argc, char **argv)
6268 jp = getjob(*++argv);
6269 if (jp->jobctl == 0)
6270 error("job not created under job control");
6272 } while (--argc > 1);
6278 restartjob(struct job *jp)
6280 struct procstat *ps;
6283 if (jp->state == JOBDONE)
6286 killpg(jp->ps[0].pid, SIGCONT);
6287 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6288 if (WIFSTOPPED(ps->status)) {
6297 static void showjobs(int change);
6301 jobscmd(int argc, char **argv)
6309 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6310 * statuses have changed since the last call to showjobs.
6312 * If the shell is interrupted in the process of creating a job, the
6313 * result may be a job structure containing zero processes. Such structures
6314 * will be freed here.
6318 showjobs(int change)
6324 struct procstat *ps;
6328 TRACE(("showjobs(%d) called\n", change));
6329 while (dowait(0, (struct job *)NULL) > 0);
6330 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6333 if (jp->nprocs == 0) {
6337 if (change && ! jp->changed)
6339 procno = jp->nprocs;
6340 for (ps = jp->ps ; ; ps++) { /* for each process */
6342 snprintf(s, 64, "[%d] %ld ", jobno,
6345 snprintf(s, 64, " %ld ",
6350 if (ps->status == -1) {
6351 /* don't print anything */
6352 } else if (WIFEXITED(ps->status)) {
6353 snprintf(s, 64, "Exit %d",
6354 WEXITSTATUS(ps->status));
6356 #ifdef CONFIG_ASH_JOB_CONTROL
6357 if (WIFSTOPPED(ps->status))
6358 i = WSTOPSIG(ps->status);
6359 else /* WIFSIGNALED(ps->status) */
6361 i = WTERMSIG(ps->status);
6362 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6363 strcpy(s, sys_siglist[i & 0x7F]);
6365 snprintf(s, 64, "Signal %d", i & 0x7F);
6366 if (WCOREDUMP(ps->status))
6367 strcat(s, " (core dumped)");
6372 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6379 if (jp->state == JOBDONE) {
6387 * Mark a job structure as unused.
6391 freejob(struct job *jp)
6393 const struct procstat *ps;
6397 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6398 if (ps->cmd != nullstr)
6401 if (jp->ps != &jp->ps0)
6404 #ifdef CONFIG_ASH_JOB_CONTROL
6405 if (curjob == jp - jobtab + 1)
6414 waitcmd(int argc, char **argv)
6422 job = getjob(*++argv);
6426 for (;;) { /* loop until process terminated or stopped */
6429 status = job->ps[job->nprocs - 1].status;
6435 if (WIFEXITED(status))
6436 retval = WEXITSTATUS(status);
6437 #ifdef CONFIG_ASH_JOB_CONTROL
6438 else if (WIFSTOPPED(status))
6439 retval = WSTOPSIG(status) + 128;
6442 /* XXX: limits number of signals */
6443 retval = WTERMSIG(status) + 128;
6448 for (jp = jobtab ; ; jp++) {
6449 if (jp >= jobtab + njobs) { /* no running procs */
6452 if (jp->used && jp->state == 0)
6456 if (dowait(2, 0) < 0 && errno == EINTR) {
6465 * Convert a job name to a job structure.
6469 getjob(const char *name)
6477 #ifdef CONFIG_ASH_JOB_CONTROL
6479 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6480 error("No current job");
6481 return &jobtab[jobno - 1];
6483 error("No current job");
6485 } else if (name[0] == '%') {
6486 if (is_digit(name[1])) {
6487 jobno = number(name + 1);
6488 if (jobno > 0 && jobno <= njobs
6489 && jobtab[jobno - 1].used != 0)
6490 return &jobtab[jobno - 1];
6491 #ifdef CONFIG_ASH_JOB_CONTROL
6492 } else if (name[1] == '%' && name[2] == '\0') {
6496 struct job *found = NULL;
6497 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6498 if (jp->used && jp->nprocs > 0
6499 && prefix(name + 1, jp->ps[0].cmd)) {
6501 error("%s: ambiguous", name);
6508 } else if (is_number(name, &pid)) {
6509 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6510 if (jp->used && jp->nprocs > 0
6511 && jp->ps[jp->nprocs - 1].pid == pid)
6515 error("No such job: %s", name);
6522 * Return a new job structure,
6526 makejob(const union node *node, int nprocs)
6531 for (i = njobs, jp = jobtab ; ; jp++) {
6535 jobtab = xmalloc(4 * sizeof jobtab[0]);
6537 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6538 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6539 /* Relocate `ps' pointers */
6540 for (i = 0; i < njobs; i++)
6541 if (jp[i].ps == &jobtab[i].ps0)
6542 jp[i].ps = &jp[i].ps0;
6546 jp = jobtab + njobs;
6547 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6559 #ifdef CONFIG_ASH_JOB_CONTROL
6560 jp->jobctl = jobctl;
6563 jp->ps = xmalloc(nprocs * sizeof (struct procstat));
6568 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6575 * Fork of a subshell. If we are doing job control, give the subshell its
6576 * own process group. Jp is a job structure that the job is to be added to.
6577 * N is the command that will be evaluated by the child. Both jp and n may
6578 * be NULL. The mode parameter can be one of the following:
6579 * FORK_FG - Fork off a foreground process.
6580 * FORK_BG - Fork off a background process.
6581 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6582 * process group even if job control is on.
6584 * When job control is turned off, background processes have their standard
6585 * input redirected to /dev/null (except for the second and later processes
6592 forkshell(struct job *jp, const union node *n, int mode)
6595 #ifdef CONFIG_ASH_JOB_CONTROL
6598 const char *devnull = _PATH_DEVNULL;
6599 const char *nullerr = "Can't open %s";
6601 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6604 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6610 TRACE(("Fork failed, errno=%d\n", errno));
6612 error("Cannot fork");
6619 TRACE(("Child shell %d\n", getpid()));
6620 wasroot = rootshell;
6625 #ifdef CONFIG_ASH_JOB_CONTROL
6626 jobctl = 0; /* do job control only in root shell */
6627 if (wasroot && mode != FORK_NOJOB && mflag) {
6628 if (jp == NULL || jp->nprocs == 0)
6631 pgrp = jp->ps[0].pid;
6633 if (mode == FORK_FG) {
6634 /*** this causes superfluous TIOCSPGRPS ***/
6635 #ifdef OLD_TTY_DRIVER
6636 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6637 error("TIOCSPGRP failed, errno=%d", errno);
6639 if (tcsetpgrp(2, pgrp) < 0)
6640 error("tcsetpgrp failed, errno=%d", errno);
6645 } else if (mode == FORK_BG) {
6647 if (mode == FORK_BG) {
6651 if ((jp == NULL || jp->nprocs == 0) &&
6652 ! fd0_redirected_p ()) {
6654 if (open(devnull, O_RDONLY) != 0)
6655 error(nullerr, devnull);
6658 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6661 if (wasroot && iflag) {
6668 #ifdef CONFIG_ASH_JOB_CONTROL
6669 if (rootshell && mode != FORK_NOJOB && mflag) {
6670 if (jp == NULL || jp->nprocs == 0)
6673 pgrp = jp->ps[0].pid;
6677 if (mode == FORK_BG)
6678 backgndpid = pid; /* set $! */
6680 struct procstat *ps = &jp->ps[jp->nprocs++];
6684 if (iflag && rootshell && n)
6685 ps->cmd = commandtext(n);
6688 TRACE(("In parent shell: child = %d\n", pid));
6695 * Wait for job to finish.
6697 * Under job control we have the problem that while a child process is
6698 * running interrupts generated by the user are sent to the child but not
6699 * to the shell. This means that an infinite loop started by an inter-
6700 * active user may be hard to kill. With job control turned off, an
6701 * interactive user may place an interactive program inside a loop. If
6702 * the interactive program catches interrupts, the user doesn't want
6703 * these interrupts to also abort the loop. The approach we take here
6704 * is to have the shell ignore interrupt signals while waiting for a
6705 * forground process to terminate, and then send itself an interrupt
6706 * signal if the child process was terminated by an interrupt signal.
6707 * Unfortunately, some programs want to do a bit of cleanup and then
6708 * exit on interrupt; unless these processes terminate themselves by
6709 * sending a signal to themselves (instead of calling exit) they will
6710 * confuse this approach.
6714 waitforjob(struct job *jp)
6716 #ifdef CONFIG_ASH_JOB_CONTROL
6717 int mypgrp = getpgrp();
6721 struct sigaction act, oact;
6725 #ifdef CONFIG_ASH_JOB_CONTROL
6730 sigaction(SIGINT, 0, &act);
6731 act.sa_handler = waitonint;
6732 sigaction(SIGINT, &act, &oact);
6734 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6735 while (jp->state == 0) {
6738 #ifdef CONFIG_ASH_JOB_CONTROL
6743 sigaction(SIGINT, &oact, 0);
6744 if (intreceived) kill(getpid(), SIGINT);
6746 #ifdef CONFIG_ASH_JOB_CONTROL
6748 #ifdef OLD_TTY_DRIVER
6749 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6750 error("TIOCSPGRP failed, errno=%d\n", errno);
6752 if (tcsetpgrp(2, mypgrp) < 0)
6753 error("tcsetpgrp failed, errno=%d\n", errno);
6756 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED)
6757 curjob = jp - jobtab + 1;
6759 status = jp->ps[jp->nprocs - 1].status;
6760 /* convert to 8 bits */
6761 if (WIFEXITED(status))
6762 st = WEXITSTATUS(status);
6763 #ifdef CONFIG_ASH_JOB_CONTROL
6764 else if (WIFSTOPPED(status))
6765 st = WSTOPSIG(status) + 128;
6768 st = WTERMSIG(status) + 128;
6769 #ifdef CONFIG_ASH_JOB_CONTROL
6772 * This is truly gross.
6773 * If we're doing job control, then we did a TIOCSPGRP which
6774 * caused us (the shell) to no longer be in the controlling
6775 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6776 * intuit from the subprocess exit status whether a SIGINT
6777 * occured, and if so interrupt ourselves. Yuck. - mycroft
6779 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6782 if (jp->state == JOBDONE)
6793 * Wait for a process to terminate.
6797 * Do a wait system call. If job control is compiled in, we accept
6798 * stopped processes. If block is zero, we return a value of zero
6799 * rather than blocking.
6801 * System V doesn't have a non-blocking wait system call. It does
6802 * have a SIGCLD signal that is sent to a process when one of it's
6803 * children dies. The obvious way to use SIGCLD would be to install
6804 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6805 * was received, and have waitproc bump another counter when it got
6806 * the status of a process. Waitproc would then know that a wait
6807 * system call would not block if the two counters were different.
6808 * This approach doesn't work because if a process has children that
6809 * have not been waited for, System V will send it a SIGCLD when it
6810 * installs a signal handler for SIGCLD. What this means is that when
6811 * a child exits, the shell will be sent SIGCLD signals continuously
6812 * until is runs out of stack space, unless it does a wait call before
6813 * restoring the signal handler. The code below takes advantage of
6814 * this (mis)feature by installing a signal handler for SIGCLD and
6815 * then checking to see whether it was called. If there are any
6816 * children to be waited for, it will be.
6821 waitproc(int block, int *status)
6826 #ifdef CONFIG_ASH_JOB_CONTROL
6832 return wait3(status, flags, (struct rusage *)NULL);
6836 dowait(int block, struct job *job)
6840 struct procstat *sp;
6842 struct job *thisjob;
6848 TRACE(("dowait(%d) called\n", block));
6850 pid = waitproc(block, &status);
6851 TRACE(("wait returns %d, status=%d\n", pid, status));
6852 } while (!(block & 2) && pid == -1 && errno == EINTR);
6857 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
6861 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
6864 if (sp->pid == pid) {
6865 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
6866 sp->status = status;
6869 if (sp->status == -1)
6871 else if (WIFSTOPPED(sp->status))
6874 if (stopped) { /* stopped or done */
6875 int state = done? JOBDONE : CONFIG_ASH_JOB_CONTROLTOPPED;
6876 if (jp->state != state) {
6877 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
6879 #ifdef CONFIG_ASH_JOB_CONTROL
6880 if (done && curjob == jp - jobtab + 1)
6881 curjob = 0; /* no current job */
6888 if (! rootshell || ! iflag || (job && thisjob == job)) {
6889 core = WCOREDUMP(status);
6890 #ifdef CONFIG_ASH_JOB_CONTROL
6891 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
6894 if (WIFEXITED(status)) sig = 0;
6895 else sig = WTERMSIG(status);
6897 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6899 out2fmt("%d: ", pid);
6900 #ifdef CONFIG_ASH_JOB_CONTROL
6901 if (sig == SIGTSTP && rootshell && iflag)
6903 (long)(job - jobtab + 1));
6905 if (sig < NSIG && sys_siglist[sig])
6906 out2str(sys_siglist[sig]);
6908 out2fmt("Signal %d", sig);
6910 out2str(" - core dumped");
6913 TRACE(("Not printing status: status=%d, sig=%d\n",
6917 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
6919 thisjob->changed = 1;
6928 * return 1 if there are stopped jobs, otherwise 0
6938 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6941 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED) {
6942 out2str("You have stopped jobs.\n");
6952 * Return a string identifying a command (to be printed by the
6956 static char *cmdnextc;
6957 static int cmdnleft;
6958 #define MAXCMDTEXT 200
6961 cmdputs(const char *s)
6972 while ((c = *p++) != '\0') {
6975 else if (c == CTLVAR) {
6980 } else if (c == '=' && subtype != 0) {
6981 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
6983 } else if (c == CTLENDVAR) {
6985 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
6986 cmdnleft++; /* ignore it */
6989 if (--cmdnleft <= 0) {
6999 #define CMDTXT_TABLE
7002 * To collect a lot of redundant code in cmdtxt() case statements, we
7003 * implement a mini language here. Each type of node struct has an
7004 * associated instruction sequence that operates on its members via
7005 * their offsets. The instruction are pack in unsigned chars with
7006 * format IIDDDDDE where the bits are
7007 * I : part of the instruction opcode, which are
7008 * 00 : member is a pointer to another node -- process it recursively
7009 * 40 : member is a pointer to a char string -- output it
7010 * 80 : output the string whose index is stored in the data field
7011 * CC : flag signaling that this case needs external processing
7012 * D : data - either the (shifted) index of a fixed string to output or
7013 * the actual offset of the member to operate on in the struct
7014 * (since we assume bit 0 is set, the offset is not shifted)
7015 * E : flag signaling end of instruction sequence
7017 * WARNING: In order to handle larger offsets for 64bit archs, this code
7018 * assumes that no offset can be an odd number and stores the
7019 * end-of-instructions flag in bit 0.
7022 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7023 #define CMDTXT_CHARPTR 0x40
7024 #define CMDTXT_STRING 0x80
7025 #define CMDTXT_SPECIAL 0xC0
7026 #define CMDTXT_OFFSETMASK 0x3E
7028 static const char * const cmdtxt_strings[] = {
7029 /* 0 1 2 3 4 5 6 7 */
7030 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7031 /* 8 9 10 11 12 13 */
7032 "while ", "; do ", "; done", "until ", "for ", " in ...",
7034 "case ", "???", "() ...", "<<..."
7037 static const char * const redir_strings[] = {
7038 ">", "<", "<>", ">>", ">|", ">&", "<&"
7041 static const unsigned char cmdtxt_ops[] = {
7042 #define CMDTXT_NSEMI 0
7043 offsetof(union node, nbinary.ch1),
7045 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7046 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7047 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7048 #define CMDTXT_NCASE (CMDTXT_NCMD)
7049 #define CMDTXT_NTO (CMDTXT_NCMD)
7050 #define CMDTXT_NFROM (CMDTXT_NCMD)
7051 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7052 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7053 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7054 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7055 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7057 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7058 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7059 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7060 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7061 (1*2)|CMDTXT_STRING,
7062 offsetof(union node, nredir.n),
7063 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7064 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7065 offsetof(union node, nbinary.ch1),
7066 (3*2)|CMDTXT_STRING,
7067 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7068 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7069 offsetof(union node, nbinary.ch1),
7070 (4*2)|CMDTXT_STRING,
7071 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7072 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7073 (5*2)|CMDTXT_STRING,
7074 offsetof(union node, nif.test),
7075 (6*2)|CMDTXT_STRING,
7076 offsetof(union node, nif.ifpart),
7077 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7078 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7079 (8*2)|CMDTXT_STRING,
7080 offsetof(union node, nbinary.ch1),
7081 (9*2)|CMDTXT_STRING,
7082 offsetof(union node, nbinary.ch2),
7083 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7084 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7085 (11*2)|CMDTXT_STRING,
7086 offsetof(union node, nbinary.ch1),
7087 (9*2)|CMDTXT_STRING,
7088 offsetof(union node, nbinary.ch2),
7089 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7090 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7091 (12*2)|CMDTXT_STRING,
7092 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7093 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7094 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7095 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7096 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7097 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7098 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7099 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7100 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7101 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7102 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7103 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7104 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7107 #if CMDTXT_NXHERE != 36
7108 #error CMDTXT_NXHERE
7111 static const unsigned char cmdtxt_ops_index[26] = {
7141 cmdtxt(const union node *n)
7148 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7149 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7151 if (*p & CMDTXT_STRING) { /* output fixed string */
7152 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7154 const char *pf = ((const char *) n)
7155 + ((int)(*p & CMDTXT_OFFSETMASK));
7156 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7157 cmdputs(*((const char **) pf));
7158 } else { /* output field */
7159 cmdtxt(*((const union node **) pf));
7162 } while (!(*p++ & CMDTXT_NOMORE));
7163 } else if (n->type == NCMD) {
7165 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7170 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7174 } else if (n->type == NPIPE) {
7175 struct nodelist *lp;
7176 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7181 } else if (n->type == NCASE) {
7182 cmdputs(cmdtxt_strings[14]);
7183 cmdputs(n->ncase.expr->narg.text);
7184 cmdputs(cmdtxt_strings[13]);
7186 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7187 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7192 assert((n->type >= NTO) && (n->type <= NFROMFD));
7195 p = redir_strings[n->type - NTO];
7196 if (n->nfile.fd != ('>' == *p)) {
7197 s[0] = n->nfile.fd + '0';
7202 if (n->type >= NTOFD) {
7203 s[0] = n->ndup.dupfd + '0';
7207 cmdtxt(n->nfile.fname);
7211 #else /* CMDTXT_TABLE */
7213 cmdtxt(const union node *n)
7216 struct nodelist *lp;
7225 cmdtxt(n->nbinary.ch1);
7227 cmdtxt(n->nbinary.ch2);
7230 cmdtxt(n->nbinary.ch1);
7232 cmdtxt(n->nbinary.ch2);
7235 cmdtxt(n->nbinary.ch1);
7237 cmdtxt(n->nbinary.ch2);
7240 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7248 cmdtxt(n->nredir.n);
7253 cmdtxt(n->nredir.n);
7257 cmdtxt(n->nif.test);
7259 cmdtxt(n->nif.ifpart);
7268 cmdtxt(n->nbinary.ch1);
7270 cmdtxt(n->nbinary.ch2);
7275 cmdputs(n->nfor.var);
7280 cmdputs(n->ncase.expr->narg.text);
7284 cmdputs(n->narg.text);
7288 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7293 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7299 cmdputs(n->narg.text);
7302 p = ">"; i = 1; goto redir;
7304 p = ">>"; i = 1; goto redir;
7306 p = ">&"; i = 1; goto redir;
7308 p = ">|"; i = 1; goto redir;
7310 p = "<"; i = 0; goto redir;
7312 p = "<&"; i = 0; goto redir;
7314 p = "<>"; i = 0; goto redir;
7316 if (n->nfile.fd != i) {
7317 s[0] = n->nfile.fd + '0';
7322 if (n->type == NTOFD || n->type == NFROMFD) {
7323 s[0] = n->ndup.dupfd + '0';
7327 cmdtxt(n->nfile.fname);
7339 #endif /* CMDTXT_TABLE */
7342 commandtext(const union node *n)
7346 cmdnextc = name = xmalloc(MAXCMDTEXT);
7347 cmdnleft = MAXCMDTEXT - 4;
7354 static void waitonint(int sig) {
7358 #ifdef CONFIG_ASH_MAIL
7361 * Routines to check for mail.
7365 #define MAXMBOXES 10
7368 static int nmboxes; /* number of mailboxes */
7369 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7374 * Print appropriate message(s) if mail has arrived. If the argument is
7375 * nozero, then the value of MAIL has changed, so we just update the
7386 struct stackmark smark;
7393 setstackmark(&smark);
7394 mpath = mpathset()? mpathval() : mailval();
7395 for (i = 0 ; i < nmboxes ; i++) {
7396 p = padvance(&mpath, nullstr);
7401 for (q = p ; *q ; q++);
7406 q[-1] = '\0'; /* delete trailing '/' */
7407 if (stat(p, &statb) < 0)
7409 if (statb.st_size > mailtime[i] && ! silent) {
7411 pathopt? pathopt : "you have mail");
7413 mailtime[i] = statb.st_size;
7416 popstackmark(&smark);
7419 #endif /* CONFIG_ASH_MAIL */
7424 static short profile_buf[16384];
7428 static int isloginsh = 0;
7430 static void read_profile (const char *);
7431 static void cmdloop (int);
7432 static void options (int);
7433 static void setoption (int, int);
7434 static void procargs (int, char **);
7438 * Main routine. We initialize things, parse the arguments, execute
7439 * profiles if we're a login shell, and then call cmdloop to execute
7440 * commands. The setjmp call sets up the location to jump to when an
7441 * exception occurs. When an exception occurs the variable "state"
7442 * is used to figure out how far we had gotten.
7446 ash_main(int argc, char **argv)
7448 struct jmploc jmploc;
7449 struct stackmark smark;
7453 BLTINCMD = find_builtin("builtin");
7454 EXECCMD = find_builtin("exec");
7455 EVALCMD = find_builtin("eval");
7457 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7463 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7465 #if defined(linux) || defined(__GNU__)
7466 signal(SIGCHLD, SIG_DFL);
7469 if (setjmp(jmploc.loc)) {
7472 * When a shell procedure is executed, we raise the
7473 * exception EXSHELLPROC to clean up before executing
7474 * the shell procedure.
7476 if (exception == EXSHELLPROC) {
7482 if (exception == EXEXEC) {
7483 exitstatus = exerrno;
7484 } else if (exception == EXERROR) {
7487 if (state == 0 || iflag == 0 || ! rootshell)
7488 exitshell(exitstatus);
7491 if (exception == EXINT) {
7494 popstackmark(&smark);
7495 FORCEINTON; /* enable interrupts */
7498 else if (state == 2)
7500 else if (state == 3)
7508 trputs("Shell args: "); trargs(argv);
7513 setstackmark(&smark);
7514 procargs(argc, argv);
7515 if (argv[0] && argv[0][0] == '-')
7519 read_profile("/etc/profile");
7522 read_profile(".profile");
7527 if (getuid() == geteuid() && getgid() == getegid()) {
7529 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7531 read_profile(shinit);
7538 if (sflag == 0 || minusc) {
7539 static const char sigs[] = {
7540 SIGINT, SIGQUIT, SIGHUP,
7546 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7549 for (i = 0; i < SIGSSIZE; i++)
7554 evalstring(minusc, 0);
7556 if (sflag || minusc == NULL) {
7557 state4: /* XXX ??? - why isn't this before the "if" statement */
7563 exitshell(exitstatus);
7569 * Read and execute commands. "Top" is nonzero for the top level command
7570 * loop; it turns on prompting if the shell is interactive.
7577 struct stackmark smark;
7581 TRACE(("cmdloop(%d) called\n", top));
7582 setstackmark(&smark);
7590 #ifdef CONFIG_ASH_MAIL
7595 n = parsecmd(inter);
7596 /* showtree(n); DEBUG */
7598 if (!top || numeof >= 50)
7600 if (!stoppedjobs()) {
7603 out2str("\nUse \"exit\" to leave shell.\n");
7606 } else if (n != NULL && nflag == 0) {
7607 job_warning = (job_warning == 2) ? 1 : 0;
7611 popstackmark(&smark);
7612 setstackmark(&smark);
7613 if (evalskip == SKIPFILE) {
7618 popstackmark(&smark);
7624 * Read /etc/profile or .profile. Return on error.
7628 read_profile(const char *name)
7635 if ((fd = open(name, O_RDONLY)) >= 0)
7640 /* -q turns off -x and -v just when executing init files */
7641 /* Note: Might do a little redundant work, but reduces code size. */
7656 * Read a file containing shell functions.
7660 readcmdfile(const char *name)
7665 if ((fd = open(name, O_RDONLY)) >= 0)
7668 error("Can't open %s", name);
7677 * Take commands from a file. To be compatable we should do a path
7678 * search for the file, which is necessary to find sub-commands.
7681 static inline char *
7682 find_dot_file(char *mybasename)
7685 const char *path = pathval();
7688 /* don't try this for absolute or relative paths */
7689 if (strchr(mybasename, '/'))
7692 while ((fullname = padvance(&path, mybasename)) != NULL) {
7693 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7695 * Don't bother freeing here, since it will
7696 * be freed by the caller.
7700 stunalloc(fullname);
7703 /* not found in the PATH */
7704 error("%s: not found", mybasename);
7709 dotcmd(int argc, char **argv)
7712 volatile struct shparam saveparam;
7715 for (sp = cmdenviron; sp ; sp = sp->next)
7716 setvareq(xstrdup(sp->text), VSTRFIXED|VTEXTFIXED);
7718 if (argc >= 2) { /* That's what SVR2 does */
7720 struct stackmark smark;
7722 setstackmark(&smark);
7723 fullname = find_dot_file(argv[1]);
7726 saveparam = shellparam;
7727 shellparam.malloc = 0;
7728 shellparam.nparam = argc - 2;
7729 shellparam.p = argv + 2;
7732 setinputfile(fullname, 1);
7733 commandname = fullname;
7738 freeparam(&shellparam);
7739 shellparam = saveparam;
7742 popstackmark(&smark);
7749 exitcmd(int argc, char **argv)
7754 exitstatus = number(argv[1]);
7756 exitstatus = oexitstatus;
7757 exitshell(exitstatus);
7766 nbytes = ALIGN(nbytes);
7767 if (nbytes > stacknleft) {
7769 struct stack_block *sp;
7772 if (blocksize < MINSIZE)
7773 blocksize = MINSIZE;
7775 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7777 stacknxt = sp->space;
7778 stacknleft = blocksize;
7784 stacknleft -= nbytes;
7790 stunalloc(pointer p)
7793 if (p == NULL) { /*DEBUG */
7794 write(2, "stunalloc\n", 10);
7798 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7801 stacknleft += stacknxt - (char *)p;
7807 setstackmark(struct stackmark *mark)
7809 mark->stackp = stackp;
7810 mark->stacknxt = stacknxt;
7811 mark->stacknleft = stacknleft;
7812 mark->marknext = markp;
7818 popstackmark(struct stackmark *mark)
7820 struct stack_block *sp;
7823 markp = mark->marknext;
7824 while (stackp != mark->stackp) {
7829 stacknxt = mark->stacknxt;
7830 stacknleft = mark->stacknleft;
7836 * When the parser reads in a string, it wants to stick the string on the
7837 * stack and only adjust the stack pointer when it knows how big the
7838 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7839 * of space on top of the stack and stackblocklen returns the length of
7840 * this block. Growstackblock will grow this space by at least one byte,
7841 * possibly moving it (like realloc). Grabstackblock actually allocates the
7842 * part of the block that has been used.
7846 growstackblock(void) {
7848 int newlen = ALIGN(stacknleft * 2 + 100);
7849 char *oldspace = stacknxt;
7850 int oldlen = stacknleft;
7851 struct stack_block *sp;
7852 struct stack_block *oldstackp;
7854 if (stacknxt == stackp->space && stackp != &stackbase) {
7859 sp = xrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
7862 stacknxt = sp->space;
7863 stacknleft = newlen;
7865 /* Stack marks pointing to the start of the old block
7866 * must be relocated to point to the new block
7868 struct stackmark *xmark;
7870 while (xmark != NULL && xmark->stackp == oldstackp) {
7871 xmark->stackp = stackp;
7872 xmark->stacknxt = stacknxt;
7873 xmark->stacknleft = stacknleft;
7874 xmark = xmark->marknext;
7879 p = stalloc(newlen);
7880 memcpy(p, oldspace, oldlen);
7881 stacknxt = p; /* free the space */
7882 stacknleft += newlen; /* we just allocated */
7889 grabstackblock(int len)
7899 * The following routines are somewhat easier to use that the above.
7900 * The user declares a variable of type STACKSTR, which may be declared
7901 * to be a register. The macro STARTSTACKSTR initializes things. Then
7902 * the user uses the macro STPUTC to add characters to the string. In
7903 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7904 * grown as necessary. When the user is done, she can just leave the
7905 * string there and refer to it using stackblock(). Or she can allocate
7906 * the space for it using grabstackstr(). If it is necessary to allow
7907 * someone else to use the stack temporarily and then continue to grow
7908 * the string, the user should use grabstack to allocate the space, and
7909 * then call ungrabstr(p) to return to the previous mode of operation.
7911 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7912 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7913 * is space for at least one character.
7918 growstackstr(void) {
7919 int len = stackblocksize();
7920 if (herefd >= 0 && len >= 1024) {
7921 xwrite(herefd, stackblock(), len);
7922 sstrnleft = len - 1;
7923 return stackblock();
7926 sstrnleft = stackblocksize() - len - 1;
7927 return stackblock() + len;
7932 * Called from CHECKSTRSPACE.
7936 makestrspace(size_t newlen) {
7937 int len = stackblocksize() - sstrnleft;
7940 sstrnleft = stackblocksize() - len;
7941 } while (sstrnleft < newlen);
7942 return stackblock() + len;
7948 ungrabstackstr(char *s, char *p)
7950 stacknleft += stacknxt - s;
7952 sstrnleft = stacknleft - (p - s);
7955 * Miscelaneous builtins.
7961 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
7962 typedef long rlim_t;
7968 * The read builtin. The -e option causes backslashes to escape the
7969 * following character.
7971 * This uses unbuffered input, which may be avoidable in some cases.
7975 readcmd(int argc, char **argv)
7990 while ((i = nextopt("p:r")) != '\0') {
7996 if (prompt && isatty(0)) {
7997 out2str(prompt); /* read without cmdedit */
8000 if (*(ap = argptr) == NULL)
8002 if ((ifs = bltinlookup("IFS")) == NULL)
8009 if (read(0, &c, 1) != 1) {
8021 if (!rflag && c == '\\') {
8027 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8031 if (backslash && c == '\\') {
8032 if (read(0, &c, 1) != 1) {
8037 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8039 setvar(*ap, stackblock(), 0);
8048 /* Remove trailing blanks */
8049 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8051 setvar(*ap, stackblock(), 0);
8052 while (*++ap != NULL)
8053 setvar(*ap, nullstr, 0);
8060 umaskcmd(int argc, char **argv)
8062 static const char permuser[3] = "ugo";
8063 static const char permmode[3] = "rwx";
8064 static const short int permmask[] = {
8065 S_IRUSR, S_IWUSR, S_IXUSR,
8066 S_IRGRP, S_IWGRP, S_IXGRP,
8067 S_IROTH, S_IWOTH, S_IXOTH
8073 int symbolic_mode = 0;
8075 while (nextopt("S") != '\0') {
8084 if ((ap = *argptr) == NULL) {
8085 if (symbolic_mode) {
8088 for (i=0 ; i<3 ; i++) {
8092 for (j=0 ; j<3 ; j++) {
8093 if ((mask & permmask[3*i+j]) == 0) {
8102 printf("%.4o\n", mask);
8105 if (is_digit((unsigned char)*ap)) {
8108 if (*ap >= '8' || *ap < '0')
8109 error("Illegal number: %s", argv[1]);
8110 mask = (mask << 3) + (*ap - '0');
8111 } while (*++ap != '\0');
8114 mask = ~mask & 0777;
8115 if (! parse_mode(ap, &mask)) {
8116 error("Illegal mode: %s", ap);
8118 umask(~mask & 0777);
8127 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8128 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8129 * ash by J.T. Conklin.
8137 short factor; /* multiply by to get rlim_{cur,max} values */
8140 static const struct limits limits[] = {
8142 { "time(seconds)", RLIMIT_CPU, 1 },
8145 { "file(blocks)", RLIMIT_FSIZE, 512 },
8148 { "data(kbytes)", RLIMIT_DATA, 1024 },
8151 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8154 { "coredump(blocks)", RLIMIT_CORE, 512 },
8157 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8159 #ifdef RLIMIT_MEMLOCK
8160 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8163 { "process(processes)", RLIMIT_NPROC, 1 },
8165 #ifdef RLIMIT_NOFILE
8166 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8169 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8172 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8178 ulimitcmd(int argc, char **argv)
8180 static const char unlimited_string[] = "unlimited";
8183 enum { SOFT = 0x1, HARD = 0x2 }
8185 const struct limits *l;
8188 struct rlimit limit;
8192 while ((optc = nextopt("HSa"
8211 #ifdef RLIMIT_MEMLOCK
8217 #ifdef RLIMIT_NOFILE
8229 } else if (optc == 'S') {
8231 } else if (optc == 'a') {
8238 for (l = limits; l->name; l++) {
8239 if(l->name[0] == what)
8241 if(l->name[1]=='w' && what=='w')
8245 set = *argptr ? 1 : 0;
8249 if (all || argptr[1])
8250 error("too many arguments");
8251 if (strcmp(p, unlimited_string) == 0)
8252 val = RLIM_INFINITY;
8256 while ((c = *p++) >= '0' && c <= '9')
8258 val = (val * 10) + (long)(c - '0');
8259 if (val < (rlim_t) 0)
8263 error("bad number");
8269 for (l = limits; l->name; l++) {
8270 printf("%-20s ", l->name);
8271 getrlimit(l->cmd, &limit);
8274 val = limit.rlim_cur;
8275 else if (how & HARD)
8276 val = limit.rlim_max;
8278 if (val == RLIM_INFINITY)
8279 puts(unlimited_string);
8283 printf("%lld\n", (long long) val);
8296 getrlimit(l->cmd, &limit);
8298 limit.rlim_max = val;
8300 limit.rlim_cur = val;
8301 if (setrlimit(l->cmd, &limit) < 0)
8302 error("error setting limit (%m)");
8306 * prefix -- see if pfx is a prefix of string.
8310 prefix(char const *pfx, char const *string)
8313 if (*pfx++ != *string++)
8320 * Return true if s is a string of digits, and save munber in intptr
8325 is_number(const char *p, int *intptr)
8333 ret += digit_val(*p);
8335 } while (*p != '\0');
8342 * Convert a string of digits to an integer, printing an error message on
8347 number(const char *s)
8350 if (! is_number(s, &i))
8351 error("Illegal number: %s", s);
8356 * Produce a possibly single quoted string suitable as input to the shell.
8357 * The return string is allocated on the stack.
8361 single_quote(const char *s)
8369 size_t len1, len1p, len2, len2p;
8371 len1 = strcspn(s, "'");
8372 len2 = strspn(s + len1, "'");
8374 len1p = len1 ? len1 + 2 : len1;
8375 len2p = len2 + ((len2 < 2) ? len2 : 2);
8377 CHECKSTRSPACE(len1p + len2p + 1, p);
8382 memcpy(p + 1, s, len1);
8390 memcpy(q + 1, s, len2);
8393 } else if (len2 == 1) {
8399 STADJUST(len1p + len2p, p);
8404 return grabstackstr(p);
8408 * Like strdup but works with the ash stack.
8412 sstrdup(const char *p)
8414 size_t len = strlen(p) + 1;
8415 return memcpy(stalloc(len), p, len);
8420 * Routine for dealing with parsed shell commands.
8424 static void sizenodelist (const struct nodelist *);
8425 static struct nodelist *copynodelist (const struct nodelist *);
8426 static char *nodexstrdup (const char *);
8428 #define CALCSIZE_TABLE
8429 #define COPYNODE_TABLE
8430 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8432 * To collect a lot of redundant code in case statements for copynode()
8433 * and calcsize(), we implement a mini language here. Each type of node
8434 * struct has an associated instruction sequence that operates on its
8435 * members via their offsets. The instruction are pack in unsigned chars
8436 * with format IIDDDDDE where the bits are
8437 * I : part of the instruction opcode, which are
8438 * 00 : member is a pointer to another node
8439 * 40 : member is an integer
8440 * 80 : member is a pointer to a nodelist
8441 * CC : member is a pointer to a char string
8442 * D : data - the actual offset of the member to operate on in the struct
8443 * (since we assume bit 0 is set, it is not shifted)
8444 * E : flag signaling end of instruction sequence
8446 * WARNING: In order to handle larger offsets for 64bit archs, this code
8447 * assumes that no offset can be an odd number and stores the
8448 * end-of-instructions flag in bit 0.
8451 #define NODE_INTEGER 0x40
8452 #define NODE_NODELIST 0x80
8453 #define NODE_CHARPTR 0xC0
8454 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8455 #define NODE_MBRMASK 0xC0
8456 #define NODE_OFFSETMASK 0x3E
8458 static const unsigned char copynode_ops[35] = {
8459 #define COPYNODE_OPS0 0
8460 offsetof(union node, nbinary.ch2),
8461 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8462 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8463 offsetof(union node, ncmd.redirect),
8464 offsetof(union node, ncmd.args),
8465 offsetof(union node, ncmd.assign),
8466 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8467 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8468 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8469 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8470 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8471 offsetof(union node, nredir.redirect),
8472 offsetof(union node, nredir.n)|NODE_NOMORE,
8473 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8474 offsetof(union node, nif.elsepart),
8475 offsetof(union node, nif.ifpart),
8476 offsetof(union node, nif.test)|NODE_NOMORE,
8477 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8478 offsetof(union node, nfor.var)|NODE_CHARPTR,
8479 offsetof(union node, nfor.body),
8480 offsetof(union node, nfor.args)|NODE_NOMORE,
8481 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8482 offsetof(union node, ncase.cases),
8483 offsetof(union node, ncase.expr)|NODE_NOMORE,
8484 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8485 offsetof(union node, nclist.body),
8486 offsetof(union node, nclist.pattern),
8487 offsetof(union node, nclist.next)|NODE_NOMORE,
8488 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8489 offsetof(union node, narg.backquote)|NODE_NODELIST,
8490 offsetof(union node, narg.text)|NODE_CHARPTR,
8491 offsetof(union node, narg.next)|NODE_NOMORE,
8492 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8493 offsetof(union node, nfile.fname),
8494 offsetof(union node, nfile.fd)|NODE_INTEGER,
8495 offsetof(union node, nfile.next)|NODE_NOMORE,
8496 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8497 offsetof(union node, ndup.vname),
8498 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8499 offsetof(union node, ndup.fd)|NODE_INTEGER,
8500 offsetof(union node, ndup.next)|NODE_NOMORE,
8501 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8502 offsetof(union node, nhere.doc),
8503 offsetof(union node, nhere.fd)|NODE_INTEGER,
8504 offsetof(union node, nhere.next)|NODE_NOMORE,
8505 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8506 offsetof(union node, nnot.com)|NODE_NOMORE,
8509 #if COPYNODE_OPS12 != 34
8510 #error COPYNODE_OPS12 is incorrect
8513 static const unsigned char copynode_ops_index[26] = {
8514 COPYNODE_OPS0, /* NSEMI */
8515 COPYNODE_OPS1, /* NCMD */
8516 COPYNODE_OPS2, /* NPIPE */
8517 COPYNODE_OPS3, /* NREDIR */
8518 COPYNODE_OPS3, /* NBACKGND */
8519 COPYNODE_OPS3, /* NSUBSHELL */
8520 COPYNODE_OPS0, /* NAND */
8521 COPYNODE_OPS0, /* NOR */
8522 COPYNODE_OPS4, /* NIF */
8523 COPYNODE_OPS0, /* NWHILE */
8524 COPYNODE_OPS0, /* NUNTIL */
8525 COPYNODE_OPS5, /* NFOR */
8526 COPYNODE_OPS6, /* NCASE */
8527 COPYNODE_OPS7, /* NCLIST */
8528 COPYNODE_OPS8, /* NDEFUN */
8529 COPYNODE_OPS8, /* NARG */
8530 COPYNODE_OPS9, /* NTO */
8531 COPYNODE_OPS9, /* NFROM */
8532 COPYNODE_OPS9, /* NFROMTO */
8533 COPYNODE_OPS9, /* NAPPEND */
8534 COPYNODE_OPS9, /* NTOOV */
8535 COPYNODE_OPS10, /* NTOFD */
8536 COPYNODE_OPS10, /* NFROMFD */
8537 COPYNODE_OPS11, /* NHERE */
8538 COPYNODE_OPS11, /* NXHERE */
8539 COPYNODE_OPS12, /* NNOT */
8542 #if NODE_CHARPTR != NODE_MBRMASK
8543 #error NODE_CHARPTR != NODE_MBRMASK!!!
8545 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8547 #ifdef COPYNODE_TABLE
8549 copynode(const union node *n)
8552 const unsigned char *p;
8558 new->type = n->type;
8559 funcblock = (char *) funcblock + (int) nodesize[n->type];
8560 p = copynode_ops + (int) copynode_ops_index[n->type];
8562 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8563 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8565 if (!(*p & NODE_MBRMASK)) { /* standard node */
8566 *((union node **)nn) = copynode(*((const union node **) no));
8567 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8568 *((const char **)nn) = nodexstrdup(*((const char **)no));
8569 } else if (*p & NODE_NODELIST) { /* nodelist */
8570 *((struct nodelist **)nn)
8571 = copynodelist(*((const struct nodelist **) no));
8572 } else { /* integer */
8573 *((int *) nn) = *((int *) no);
8575 } while (!(*p++ & NODE_NOMORE));
8578 #else /* COPYNODE_TABLE */
8580 copynode(const union node *n)
8587 funcblock = (char *) funcblock + nodesize[n->type];
8594 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8595 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8598 new->ncmd.redirect = copynode(n->ncmd.redirect);
8599 new->ncmd.args = copynode(n->ncmd.args);
8600 new->ncmd.assign = copynode(n->ncmd.assign);
8601 new->ncmd.backgnd = n->ncmd.backgnd;
8604 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8605 new->npipe.backgnd = n->npipe.backgnd;
8610 new->nredir.redirect = copynode(n->nredir.redirect);
8611 new->nredir.n = copynode(n->nredir.n);
8614 new->nif.elsepart = copynode(n->nif.elsepart);
8615 new->nif.ifpart = copynode(n->nif.ifpart);
8616 new->nif.test = copynode(n->nif.test);
8619 new->nfor.var = nodexstrdup(n->nfor.var);
8620 new->nfor.body = copynode(n->nfor.body);
8621 new->nfor.args = copynode(n->nfor.args);
8624 new->ncase.cases = copynode(n->ncase.cases);
8625 new->ncase.expr = copynode(n->ncase.expr);
8628 new->nclist.body = copynode(n->nclist.body);
8629 new->nclist.pattern = copynode(n->nclist.pattern);
8630 new->nclist.next = copynode(n->nclist.next);
8634 new->narg.backquote = copynodelist(n->narg.backquote);
8635 new->narg.text = nodexstrdup(n->narg.text);
8636 new->narg.next = copynode(n->narg.next);
8643 new->nfile.fname = copynode(n->nfile.fname);
8644 new->nfile.fd = n->nfile.fd;
8645 new->nfile.next = copynode(n->nfile.next);
8649 new->ndup.vname = copynode(n->ndup.vname);
8650 new->ndup.dupfd = n->ndup.dupfd;
8651 new->ndup.fd = n->ndup.fd;
8652 new->ndup.next = copynode(n->ndup.next);
8656 new->nhere.doc = copynode(n->nhere.doc);
8657 new->nhere.fd = n->nhere.fd;
8658 new->nhere.next = copynode(n->nhere.next);
8661 new->nnot.com = copynode(n->nnot.com);
8664 new->type = n->type;
8667 #endif /* COPYNODE_TABLE */
8669 #ifdef CALCSIZE_TABLE
8671 calcsize(const union node *n)
8673 const unsigned char *p;
8677 funcblocksize += (int) nodesize[n->type];
8679 p = copynode_ops + (int) copynode_ops_index[n->type];
8681 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8683 if (!(*p & NODE_MBRMASK)) { /* standard node */
8684 calcsize(*((const union node **) no));
8685 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8686 funcstringsize += strlen(*((const char **)no)) + 1;
8687 } else if (*p & NODE_NODELIST) { /* nodelist */
8688 sizenodelist(*((const struct nodelist **) no));
8689 } /* else integer -- ignore */
8690 } while (!(*p++ & NODE_NOMORE));
8692 #else /* CALCSIZE_TABLE */
8694 calcsize(const union node *n)
8698 funcblocksize += nodesize[n->type];
8705 calcsize(n->nbinary.ch2);
8706 calcsize(n->nbinary.ch1);
8709 calcsize(n->ncmd.redirect);
8710 calcsize(n->ncmd.args);
8711 calcsize(n->ncmd.assign);
8714 sizenodelist(n->npipe.cmdlist);
8719 calcsize(n->nredir.redirect);
8720 calcsize(n->nredir.n);
8723 calcsize(n->nif.elsepart);
8724 calcsize(n->nif.ifpart);
8725 calcsize(n->nif.test);
8728 funcstringsize += strlen(n->nfor.var) + 1;
8729 calcsize(n->nfor.body);
8730 calcsize(n->nfor.args);
8733 calcsize(n->ncase.cases);
8734 calcsize(n->ncase.expr);
8737 calcsize(n->nclist.body);
8738 calcsize(n->nclist.pattern);
8739 calcsize(n->nclist.next);
8743 sizenodelist(n->narg.backquote);
8744 funcstringsize += strlen(n->narg.text) + 1;
8745 calcsize(n->narg.next);
8752 calcsize(n->nfile.fname);
8753 calcsize(n->nfile.next);
8757 calcsize(n->ndup.vname);
8758 calcsize(n->ndup.next);
8762 calcsize(n->nhere.doc);
8763 calcsize(n->nhere.next);
8766 calcsize(n->nnot.com);
8770 #endif /* CALCSIZE_TABLE */
8773 sizenodelist(const struct nodelist *lp)
8776 funcblocksize += ALIGN(sizeof(struct nodelist));
8783 static struct nodelist *
8784 copynodelist(const struct nodelist *lp)
8786 struct nodelist *start;
8787 struct nodelist **lpp;
8792 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8793 (*lpp)->n = copynode(lp->n);
8795 lpp = &(*lpp)->next;
8803 nodexstrdup(const char *s)
8806 char *q = funcstring;
8807 char *rtn = funcstring;
8809 while ((*q++ = *p++) != '\0')
8815 #ifdef CONFIG_ASH_GETOPTS
8816 static int getopts (char *, char *, char **, int *, int *);
8820 * Process the shell command line arguments.
8824 procargs(int argc, char **argv)
8831 for (i = 0; i < NOPTS; i++)
8834 if (*argptr == NULL && minusc == NULL)
8836 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8840 for (i = 0; i < NOPTS; i++)
8841 if (optent_val(i) == 2)
8844 if (sflag == 0 && minusc == NULL) {
8845 commandname = argv[0];
8847 setinputfile(arg0, 0);
8850 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8851 if (argptr && minusc && *argptr)
8854 shellparam.p = argptr;
8855 shellparam.optind = 1;
8856 shellparam.optoff = -1;
8857 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8859 shellparam.nparam++;
8868 * Process shell options. The global variable argptr contains a pointer
8869 * to the argument list; we advance it past the options.
8873 minus_o(const char *name, int val)
8878 out1str("Current option settings\n");
8879 for (i = 0; i < NOPTS; i++)
8880 printf("%-16s%s\n", optent_name(optlist[i]),
8881 optent_val(i) ? "on" : "off");
8883 for (i = 0; i < NOPTS; i++)
8884 if (equal(name, optent_name(optlist[i]))) {
8885 setoption(optent_letter(optlist[i]), val);
8888 error("Illegal option -o %s", name);
8894 options(int cmdline)
8902 while ((p = *argptr) != NULL) {
8904 if ((c = *p++) == '-') {
8906 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8908 /* "-" means turn off -x and -v */
8911 /* "--" means reset params */
8912 else if (*argptr == NULL)
8915 break; /* "-" or "--" terminates options */
8917 } else if (c == '+') {
8923 while ((c = *p++) != '\0') {
8924 if (c == 'c' && cmdline) {
8926 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8930 if (q == NULL || minusc != NULL)
8931 error("Bad -c option");
8936 } else if (c == 'o') {
8937 minus_o(*argptr, val);
8940 } else if (cmdline && (c == '-')) { // long options
8941 if ( strcmp ( p, "login" ) == 0 )
8953 setoption(int flag, int val)
8957 for (i = 0; i < NOPTS; i++)
8958 if (optent_letter(optlist[i]) == flag) {
8959 optent_val(i) = val;
8961 /* #%$ hack for ksh semantics */
8964 else if (flag == 'E')
8969 error("Illegal option -%c", flag);
8976 * Set the shell parameters.
8980 setparam(char **argv)
8986 for (nparam = 0 ; argv[nparam] ; nparam++);
8987 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
8989 *ap++ = xstrdup(*argv++);
8992 freeparam(&shellparam);
8993 shellparam.malloc = 1;
8994 shellparam.nparam = nparam;
8995 shellparam.p = newparam;
8996 shellparam.optind = 1;
8997 shellparam.optoff = -1;
9002 * Free the list of positional parameters.
9006 freeparam(volatile struct shparam *param)
9010 if (param->malloc) {
9011 for (ap = param->p ; *ap ; ap++)
9020 * The shift builtin command.
9024 shiftcmd(int argc, char **argv)
9031 n = number(argv[1]);
9032 if (n > shellparam.nparam)
9033 error("can't shift that many");
9035 shellparam.nparam -= n;
9036 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9037 if (shellparam.malloc)
9041 while ((*ap2++ = *ap1++) != NULL);
9042 shellparam.optind = 1;
9043 shellparam.optoff = -1;
9051 * The set command builtin.
9055 setcmd(int argc, char **argv)
9058 return showvarscmd(argc, argv);
9062 if (*argptr != NULL) {
9071 getoptsreset(const char *value)
9073 shellparam.optind = number(value);
9074 shellparam.optoff = -1;
9077 #ifdef CONFIG_LOCALE_SUPPORT
9078 static void change_lc_all(const char *value)
9080 if(value != 0 && *value != 0)
9081 setlocale(LC_ALL, value);
9084 static void change_lc_ctype(const char *value)
9086 if(value != 0 && *value != 0)
9087 setlocale(LC_CTYPE, value);
9092 #ifdef CONFIG_ASH_GETOPTS
9094 * The getopts builtin. Shellparam.optnext points to the next argument
9095 * to be processed. Shellparam.optptr points to the next character to
9096 * be processed in the current argument. If shellparam.optnext is NULL,
9097 * then it's the first time getopts has been called.
9101 getoptscmd(int argc, char **argv)
9106 error("Usage: getopts optstring var [arg]");
9107 else if (argc == 3) {
9108 optbase = shellparam.p;
9109 if (shellparam.optind > shellparam.nparam + 1) {
9110 shellparam.optind = 1;
9111 shellparam.optoff = -1;
9116 if (shellparam.optind > argc - 2) {
9117 shellparam.optind = 1;
9118 shellparam.optoff = -1;
9122 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9123 &shellparam.optoff);
9127 * Safe version of setvar, returns 1 on success 0 on failure.
9131 setvarsafe(const char *name, const char *val, int flags)
9133 struct jmploc jmploc;
9134 struct jmploc *volatile savehandler = handler;
9140 if (setjmp(jmploc.loc))
9144 setvar(name, val, flags);
9146 handler = savehandler;
9151 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind, int *optoff)
9158 char **optnext = optfirst + *myoptind - 1;
9160 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9161 strlen(*(optnext - 1)) < *optoff)
9164 p = *(optnext - 1) + *optoff;
9165 if (p == NULL || *p == '\0') {
9166 /* Current word is done, advance */
9167 if (optnext == NULL)
9170 if (p == NULL || *p != '-' || *++p == '\0') {
9172 *myoptind = optnext - optfirst + 1;
9178 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9183 for (q = optstr; *q != c; ) {
9185 if (optstr[0] == ':') {
9188 err |= setvarsafe("OPTARG", s, 0);
9191 out2fmt("Illegal option -%c\n", c);
9192 (void) unsetvar("OPTARG");
9202 if (*p == '\0' && (p = *optnext) == NULL) {
9203 if (optstr[0] == ':') {
9206 err |= setvarsafe("OPTARG", s, 0);
9210 out2fmt("No arg for -%c option\n", c);
9211 (void) unsetvar("OPTARG");
9219 setvarsafe("OPTARG", p, 0);
9223 setvarsafe("OPTARG", "", 0);
9224 *myoptind = optnext - optfirst + 1;
9231 *optoff = p ? p - *(optnext - 1) : -1;
9232 snprintf(s, sizeof(s), "%d", *myoptind);
9233 err |= setvarsafe("OPTIND", s, VNOFUNC);
9236 err |= setvarsafe(optvar, s, 0);
9247 * XXX - should get rid of. have all builtins use getopt(3). the
9248 * library getopt must have the BSD extension static variable "optreset"
9249 * otherwise it can't be used within the shell safely.
9251 * Standard option processing (a la getopt) for builtin routines. The
9252 * only argument that is passed to nextopt is the option string; the
9253 * other arguments are unnecessary. It return the character, or '\0' on
9258 nextopt(const char *optstring)
9264 if ((p = optptr) == NULL || *p == '\0') {
9266 if (p == NULL || *p != '-' || *++p == '\0')
9269 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9273 for (q = optstring ; *q != c ; ) {
9275 error("Illegal option -%c", c);
9280 if (*p == '\0' && (p = *argptr++) == NULL)
9281 error("No arg for -%c option", c);
9298 out2fmt(const char *fmt, ...)
9302 vfprintf(stderr, fmt, ap);
9307 * Version of write which resumes after a signal is caught.
9311 xwrite(int fd, const char *buf, int nbytes)
9320 i = write(fd, buf, n);
9326 } else if (i == 0) {
9329 } else if (errno != EINTR) {
9337 * Shell command parser.
9340 #define EOFMARKLEN 79
9345 struct heredoc *next; /* next here document in list */
9346 union node *here; /* redirection node */
9347 char *eofmark; /* string indicating end of input */
9348 int striptabs; /* if set, strip leading tabs */
9351 static struct heredoc *heredoclist; /* list of here documents to read */
9352 static int parsebackquote; /* nonzero if we are inside backquotes */
9353 static int doprompt; /* if set, prompt the user */
9354 static int needprompt; /* true if interactive and at start of line */
9355 static int lasttoken; /* last token read */
9357 static char *wordtext; /* text of last word returned by readtoken */
9359 static struct nodelist *backquotelist;
9360 static union node *redirnode;
9361 static struct heredoc *heredoc;
9362 static int quoteflag; /* set if (part of) last token was quoted */
9363 static int startlinno; /* line # where last token started */
9366 static union node *list (int);
9367 static union node *andor (void);
9368 static union node *pipeline (void);
9369 static union node *command (void);
9370 static union node *simplecmd(union node **rpp, union node *redir);
9371 static void parsefname (void);
9372 static void parseheredoc (void);
9373 static char peektoken (void);
9374 static int readtoken (void);
9375 static int xxreadtoken (void);
9376 static int readtoken1 (int, int, const char *, int);
9377 static int noexpand (char *);
9378 static void synexpect (int) __attribute__((noreturn));
9379 static void synerror (const char *) __attribute__((noreturn));
9380 static void setprompt (int);
9384 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9385 * valid parse tree indicating a blank line.)
9389 parsecmd(int interact)
9394 doprompt = interact;
9413 union node *n1, *n2, *n3;
9417 if (nlflag == 0 && peektoken())
9423 if (tok == TBACKGND) {
9424 if (n2->type == NCMD || n2->type == NPIPE) {
9425 n2->ncmd.backgnd = 1;
9426 } else if (n2->type == NREDIR) {
9427 n2->type = NBACKGND;
9429 n3 = (union node *)stalloc(sizeof (struct nredir));
9430 n3->type = NBACKGND;
9432 n3->nredir.redirect = NULL;
9440 n3 = (union node *)stalloc(sizeof (struct nbinary));
9442 n3->nbinary.ch1 = n1;
9443 n3->nbinary.ch2 = n2;
9467 pungetc(); /* push back EOF on input */
9482 union node *n1, *n2, *n3;
9488 if ((t = readtoken()) == TAND) {
9490 } else if (t == TOR) {
9498 n3 = (union node *)stalloc(sizeof (struct nbinary));
9500 n3->nbinary.ch1 = n1;
9501 n3->nbinary.ch2 = n2;
9510 union node *n1, *n2, *pipenode;
9511 struct nodelist *lp, *prev;
9515 TRACE(("pipeline: entered\n"));
9516 if (readtoken() == TNOT) {
9522 if (readtoken() == TPIPE) {
9523 pipenode = (union node *)stalloc(sizeof (struct npipe));
9524 pipenode->type = NPIPE;
9525 pipenode->npipe.backgnd = 0;
9526 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9527 pipenode->npipe.cmdlist = lp;
9531 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9535 } while (readtoken() == TPIPE);
9541 n2 = (union node *)stalloc(sizeof (struct nnot));
9553 union node *n1, *n2;
9554 union node *ap, **app;
9555 union node *cp, **cpp;
9556 union node *redir, **rpp;
9563 /* Check for redirection which may precede command */
9564 while (readtoken() == TREDIR) {
9565 *rpp = n2 = redirnode;
9566 rpp = &n2->nfile.next;
9571 switch (readtoken()) {
9573 n1 = (union node *)stalloc(sizeof (struct nif));
9575 n1->nif.test = list(0);
9576 if (readtoken() != TTHEN)
9578 n1->nif.ifpart = list(0);
9580 while (readtoken() == TELIF) {
9581 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9582 n2 = n2->nif.elsepart;
9584 n2->nif.test = list(0);
9585 if (readtoken() != TTHEN)
9587 n2->nif.ifpart = list(0);
9589 if (lasttoken == TELSE)
9590 n2->nif.elsepart = list(0);
9592 n2->nif.elsepart = NULL;
9595 if (readtoken() != TFI)
9602 n1 = (union node *)stalloc(sizeof (struct nbinary));
9603 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9604 n1->nbinary.ch1 = list(0);
9605 if ((got=readtoken()) != TDO) {
9606 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9609 n1->nbinary.ch2 = list(0);
9610 if (readtoken() != TDONE)
9616 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9617 synerror("Bad for loop variable");
9618 n1 = (union node *)stalloc(sizeof (struct nfor));
9620 n1->nfor.var = wordtext;
9622 if (readtoken() == TIN) {
9624 while (readtoken() == TWORD) {
9625 n2 = (union node *)stalloc(sizeof (struct narg));
9627 n2->narg.text = wordtext;
9628 n2->narg.backquote = backquotelist;
9630 app = &n2->narg.next;
9634 if (lasttoken != TNL && lasttoken != TSEMI)
9637 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9639 n2 = (union node *)stalloc(sizeof (struct narg));
9641 n2->narg.text = argvars;
9642 n2->narg.backquote = NULL;
9643 n2->narg.next = NULL;
9646 * Newline or semicolon here is optional (but note
9647 * that the original Bourne shell only allowed NL).
9649 if (lasttoken != TNL && lasttoken != TSEMI)
9653 if (readtoken() != TDO)
9655 n1->nfor.body = list(0);
9656 if (readtoken() != TDONE)
9661 n1 = (union node *)stalloc(sizeof (struct ncase));
9663 if (readtoken() != TWORD)
9665 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9667 n2->narg.text = wordtext;
9668 n2->narg.backquote = backquotelist;
9669 n2->narg.next = NULL;
9672 } while (readtoken() == TNL);
9673 if (lasttoken != TIN)
9674 synerror("expecting \"in\"");
9675 cpp = &n1->ncase.cases;
9676 checkkwd = 2, readtoken();
9678 if (lasttoken == TLP)
9680 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9682 app = &cp->nclist.pattern;
9684 *app = ap = (union node *)stalloc(sizeof (struct narg));
9686 ap->narg.text = wordtext;
9687 ap->narg.backquote = backquotelist;
9688 if (checkkwd = 2, readtoken() != TPIPE)
9690 app = &ap->narg.next;
9693 ap->narg.next = NULL;
9694 if (lasttoken != TRP)
9696 cp->nclist.body = list(0);
9699 if ((t = readtoken()) != TESAC) {
9701 synexpect(TENDCASE);
9703 checkkwd = 2, readtoken();
9705 cpp = &cp->nclist.next;
9706 } while(lasttoken != TESAC);
9711 n1 = (union node *)stalloc(sizeof (struct nredir));
9712 n1->type = NSUBSHELL;
9713 n1->nredir.n = list(0);
9714 n1->nredir.redirect = NULL;
9715 if (readtoken() != TRP)
9721 if (readtoken() != TEND)
9725 /* Handle an empty command like other simple commands. */
9734 * An empty command before a ; doesn't make much sense, and
9735 * should certainly be disallowed in the case of `if ;'.
9741 n1 = simplecmd(rpp, redir);
9748 /* Now check for redirection which may follow command */
9749 while (readtoken() == TREDIR) {
9750 *rpp = n2 = redirnode;
9751 rpp = &n2->nfile.next;
9757 if (n1->type != NSUBSHELL) {
9758 n2 = (union node *)stalloc(sizeof (struct nredir));
9763 n1->nredir.redirect = redir;
9771 simplecmd(union node **rpp, union node *redir) {
9772 union node *args, **app;
9773 union node *n = NULL;
9774 union node *vars, **vpp;
9775 union node **orig_rpp;
9782 /* If we don't have any redirections already, then we must reset
9783 rpp to be the address of the local redir variable. */
9786 /* We save the incoming value, because we need this for shell
9787 functions. There can not be a redirect or an argument between
9788 the function name and the open parenthesis. */
9793 switch (readtoken()) {
9796 n = (union node *)stalloc(sizeof (struct narg));
9798 n->narg.text = wordtext;
9799 n->narg.backquote = backquotelist;
9800 if (lasttoken == TWORD) {
9802 app = &n->narg.next;
9805 vpp = &n->narg.next;
9809 *rpp = n = redirnode;
9810 rpp = &n->nfile.next;
9811 parsefname(); /* read name of redirection file */
9815 args && app == &args->narg.next &&
9816 !vars && rpp == orig_rpp
9818 /* We have a function */
9819 if (readtoken() != TRP)
9823 n->narg.next = command();
9836 n = (union node *)stalloc(sizeof (struct ncmd));
9838 n->ncmd.backgnd = 0;
9839 n->ncmd.args = args;
9840 n->ncmd.assign = vars;
9841 n->ncmd.redirect = redir;
9849 n = (union node *)stalloc(sizeof (struct narg));
9851 n->narg.next = NULL;
9852 n->narg.text = wordtext;
9853 n->narg.backquote = backquotelist;
9857 static void fixredir(union node *n, const char *text, int err)
9859 TRACE(("Fix redir %s %d\n", text, err));
9861 n->ndup.vname = NULL;
9863 if (is_digit(text[0]) && text[1] == '\0')
9864 n->ndup.dupfd = digit_val(text[0]);
9865 else if (text[0] == '-' && text[1] == '\0')
9870 synerror("Bad fd number");
9872 n->ndup.vname = makename();
9879 union node *n = redirnode;
9881 if (readtoken() != TWORD)
9883 if (n->type == NHERE) {
9884 struct heredoc *here = heredoc;
9890 TRACE(("Here document %d\n", n->type));
9891 if (here->striptabs) {
9892 while (*wordtext == '\t')
9895 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9896 synerror("Illegal eof marker for << redirection");
9897 rmescapes(wordtext);
9898 here->eofmark = wordtext;
9900 if (heredoclist == NULL)
9903 for (p = heredoclist ; p->next ; p = p->next);
9906 } else if (n->type == NTOFD || n->type == NFROMFD) {
9907 fixredir(n, wordtext, 0);
9909 n->nfile.fname = makename();
9915 * Input any here documents.
9920 struct heredoc *here;
9923 while (heredoclist) {
9925 heredoclist = here->next;
9930 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9931 here->eofmark, here->striptabs);
9932 n = (union node *)stalloc(sizeof (struct narg));
9933 n->narg.type = NARG;
9934 n->narg.next = NULL;
9935 n->narg.text = wordtext;
9936 n->narg.backquote = backquotelist;
9937 here->here->nhere.doc = n;
9947 return tokname_array[t][0];
9954 int savecheckalias = checkalias;
9955 #ifdef CONFIG_ASH_ALIAS
9956 int savecheckkwd = checkkwd;
9961 int alreadyseen = tokpushback;
9964 #ifdef CONFIG_ASH_ALIAS
9970 checkalias = savecheckalias;
9976 if (checkkwd == 2) {
9985 * check for keywords
9987 if (t == TWORD && !quoteflag)
9989 const char *const *pp;
9991 if ((pp = findkwd(wordtext))) {
9992 lasttoken = t = pp - tokname_array;
9993 TRACE(("keyword %s recognized\n", tokname(t)));
10004 } else if (checkalias == 2 && isassignment(wordtext)) {
10005 lasttoken = t = TASSIGN;
10006 } else if (checkalias) {
10007 #ifdef CONFIG_ASH_ALIAS
10008 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10010 pushstring(ap->val, strlen(ap->val), ap);
10012 checkkwd = savecheckkwd;
10021 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10023 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10030 * Read the next input token.
10031 * If the token is a word, we set backquotelist to the list of cmds in
10032 * backquotes. We set quoteflag to true if any part of the word was
10034 * If the token is TREDIR, then we set redirnode to a structure containing
10036 * In all cases, the variable startlinno is set to the number of the line
10037 * on which the token starts.
10039 * [Change comment: here documents and internal procedures]
10040 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10041 * word parsing code into a separate routine. In this case, readtoken
10042 * doesn't need to have any internal procedures, but parseword does.
10043 * We could also make parseoperator in essence the main routine, and
10044 * have parseword (readtoken1?) handle both words and redirection.]
10047 #define NEW_xxreadtoken
10048 #ifdef NEW_xxreadtoken
10050 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10051 static const char xxreadtoken_tokens[] = {
10052 TNL, TLP, TRP, /* only single occurrence allowed */
10053 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10054 TEOF, /* corresponds to trailing nul */
10055 TAND, TOR, TENDCASE, /* if double occurrence */
10058 #define xxreadtoken_doubles \
10059 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10060 #define xxreadtoken_singles \
10061 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10075 startlinno = plinno;
10076 for (;;) { /* until token or start of word found */
10079 if ((c!=' ') && (c!='\t')
10080 #ifdef CONFIG_ASH_ALIAS
10085 while ((c = pgetc()) != '\n' && c != PEOF);
10087 } else if (c=='\\') {
10088 if (pgetc() != '\n') {
10092 startlinno = ++plinno;
10093 setprompt(doprompt ? 2 : 0);
10096 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10101 needprompt = doprompt;
10104 p = strchr(xxreadtoken_chars, c);
10107 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10110 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10111 if (pgetc() == *p) { /* double occurrence? */
10112 p += xxreadtoken_doubles + 1;
10119 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10127 #define RETURN(token) return lasttoken = token
10141 startlinno = plinno;
10142 for (;;) { /* until token or start of word found */
10145 case ' ': case '\t':
10146 #ifdef CONFIG_ASH_ALIAS
10151 while ((c = pgetc()) != '\n' && c != PEOF);
10155 if (pgetc() == '\n') {
10156 startlinno = ++plinno;
10167 needprompt = doprompt;
10172 if (pgetc() == '&')
10177 if (pgetc() == '|')
10182 if (pgetc() == ';')
10195 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10201 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10202 * is not NULL, read a here document. In the latter case, eofmark is the
10203 * word which marks the end of the document and striptabs is true if
10204 * leading tabs should be stripped from the document. The argument firstc
10205 * is the first character of the input token or document.
10207 * Because C does not have internal subroutines, I have simulated them
10208 * using goto's to implement the subroutine linkage. The following macros
10209 * will run code that appears at the end of readtoken1.
10212 #define CHECKEND() {goto checkend; checkend_return:;}
10213 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10214 #define PARSESUB() {goto parsesub; parsesub_return:;}
10215 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10216 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10217 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10220 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10225 char line[EOFMARKLEN + 1];
10226 struct nodelist *bqlist;
10229 int varnest; /* levels of variables expansion */
10230 int arinest; /* levels of arithmetic expansion */
10231 int parenlevel; /* levels of parens in arithmetic */
10232 int dqvarnest; /* levels of variables expansion within double quotes */
10234 int prevsyntax; /* syntax before arithmetic */
10236 /* Avoid longjmp clobbering */
10242 (void) &parenlevel;
10245 (void) &prevsyntax;
10249 startlinno = plinno;
10251 if (syntax == DQSYNTAX)
10260 STARTSTACKSTR(out);
10261 loop: { /* for each line, until end of word */
10262 CHECKEND(); /* set c to PEOF if at end of here document */
10263 for (;;) { /* until end of line or end of word */
10264 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10265 switch(SIT(c,syntax)) {
10266 case CNL: /* '\n' */
10267 if (syntax == BASESYNTAX)
10268 goto endword; /* exit outer loop */
10276 goto loop; /* continue outer loop */
10281 if ((eofmark == NULL || dblquote) &&
10283 USTPUTC(CTLESC, out);
10286 case CBACK: /* backslash */
10289 USTPUTC('\\', out);
10291 } else if (c == '\n') {
10297 if (dblquote && c != '\\' && c != '`' && c != '$'
10298 && (c != '"' || eofmark != NULL))
10299 USTPUTC('\\', out);
10300 if (SIT(c,SQSYNTAX) == CCTL)
10301 USTPUTC(CTLESC, out);
10302 else if (eofmark == NULL)
10303 USTPUTC(CTLQUOTEMARK, out);
10309 if (eofmark == NULL)
10310 USTPUTC(CTLQUOTEMARK, out);
10314 if (eofmark == NULL)
10315 USTPUTC(CTLQUOTEMARK, out);
10320 if (eofmark != NULL && arinest == 0 &&
10325 syntax = ARISYNTAX;
10327 } else if (eofmark == NULL &&
10329 syntax = BASESYNTAX;
10335 case CVAR: /* '$' */
10336 PARSESUB(); /* parse substitution */
10338 case CENDVAR: /* '}' */
10341 if (dqvarnest > 0) {
10344 USTPUTC(CTLENDVAR, out);
10349 #ifdef CONFIG_ASH_MATH_SUPPORT
10350 case CLP: /* '(' in arithmetic */
10354 case CRP: /* ')' in arithmetic */
10355 if (parenlevel > 0) {
10359 if (pgetc() == ')') {
10360 if (--arinest == 0) {
10361 USTPUTC(CTLENDARI, out);
10362 syntax = prevsyntax;
10363 if (syntax == DQSYNTAX)
10371 * unbalanced parens
10372 * (don't 2nd guess - no error)
10380 case CBQUOTE: /* '`' */
10384 goto endword; /* exit outer loop */
10389 goto endword; /* exit outer loop */
10390 #ifdef CONFIG_ASH_ALIAS
10400 if (syntax == ARISYNTAX)
10401 synerror("Missing '))'");
10402 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10403 synerror("Unterminated quoted string");
10404 if (varnest != 0) {
10405 startlinno = plinno;
10406 synerror("Missing '}'");
10408 USTPUTC('\0', out);
10409 len = out - stackblock();
10410 out = stackblock();
10411 if (eofmark == NULL) {
10412 if ((c == '>' || c == '<')
10415 && (*out == '\0' || is_digit(*out))) {
10417 return lasttoken = TREDIR;
10422 quoteflag = quotef;
10423 backquotelist = bqlist;
10424 grabstackblock(len);
10426 return lasttoken = TWORD;
10427 /* end of readtoken routine */
10432 * Check to see whether we are at the end of the here document. When this
10433 * is called, c is set to the first character of the next input line. If
10434 * we are at the end of the here document, this routine sets the c to PEOF.
10439 #ifdef CONFIG_ASH_ALIAS
10445 while (c == '\t') {
10449 if (c == *eofmark) {
10450 if (pfgets(line, sizeof line) != NULL) {
10454 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10455 if (*p == '\n' && *q == '\0') {
10458 needprompt = doprompt;
10460 pushstring(line, strlen(line), NULL);
10465 goto checkend_return;
10470 * Parse a redirection operator. The variable "out" points to a string
10471 * specifying the fd to be redirected. The variable "c" contains the
10472 * first character of the redirection operator.
10479 np = (union node *)stalloc(sizeof (struct nfile));
10484 np->type = NAPPEND;
10493 } else { /* c == '<' */
10495 switch (c = pgetc()) {
10497 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10498 np = (union node *)stalloc(sizeof (struct nhere));
10502 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10503 heredoc->here = np;
10504 if ((c = pgetc()) == '-') {
10505 heredoc->striptabs = 1;
10507 heredoc->striptabs = 0;
10513 np->type = NFROMFD;
10517 np->type = NFROMTO;
10527 np->nfile.fd = digit_val(fd);
10529 goto parseredir_return;
10534 * Parse a substitution. At this point, we have read the dollar sign
10535 * and nothing else.
10543 static const char types[] = "}-+?=";
10548 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10552 } else if (c == '(') { /* $(command) or $((arith)) */
10553 if (pgetc() == '(') {
10560 USTPUTC(CTLVAR, out);
10561 typeloc = out - stackblock();
10562 USTPUTC(VSNORMAL, out);
10563 subtype = VSNORMAL;
10567 if ((c = pgetc()) == '}')
10570 subtype = VSLENGTH;
10575 if (c > PEOA && is_name(c)) {
10579 } while (c > PEOA && is_in_name(c));
10580 } else if (is_digit(c)) {
10584 } while (is_digit(c));
10586 else if (is_special(c)) {
10591 badsub: synerror("Bad substitution");
10595 if (subtype == 0) {
10602 p = strchr(types, c);
10605 subtype = p - types + VSNORMAL;
10611 subtype = c == '#' ? VSTRIMLEFT :
10624 if (dblquote || arinest)
10626 *(stackblock() + typeloc) = subtype | flags;
10627 if (subtype != VSNORMAL) {
10634 goto parsesub_return;
10639 * Called to parse command substitutions. Newstyle is set if the command
10640 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10641 * list of commands (passed by reference), and savelen is the number of
10642 * characters on the top of the stack which must be preserved.
10646 struct nodelist **nlpp;
10649 char *volatile str;
10650 struct jmploc jmploc;
10651 struct jmploc *volatile savehandler;
10655 (void) &saveprompt;
10658 savepbq = parsebackquote;
10659 if (setjmp(jmploc.loc)) {
10661 parsebackquote = 0;
10662 handler = savehandler;
10663 longjmp(handler->loc, 1);
10667 savelen = out - stackblock();
10669 str = xmalloc(savelen);
10670 memcpy(str, stackblock(), savelen);
10672 savehandler = handler;
10676 /* We must read until the closing backquote, giving special
10677 treatment to some slashes, and then push the string and
10678 reread it as input, interpreting it normally. */
10685 STARTSTACKSTR(pout);
10691 switch (pc = pgetc()) {
10696 if ((pc = pgetc()) == '\n') {
10703 * If eating a newline, avoid putting
10704 * the newline into the new character
10705 * stream (via the STPUTC after the
10710 if (pc != '\\' && pc != '`' && pc != '$'
10711 && (!dblquote || pc != '"'))
10712 STPUTC('\\', pout);
10719 #ifdef CONFIG_ASH_ALIAS
10722 startlinno = plinno;
10723 synerror("EOF in backquote substitution");
10727 needprompt = doprompt;
10736 STPUTC('\0', pout);
10737 psavelen = pout - stackblock();
10738 if (psavelen > 0) {
10739 pstr = grabstackstr(pout);
10740 setinputstring(pstr);
10745 nlpp = &(*nlpp)->next;
10746 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10747 (*nlpp)->next = NULL;
10748 parsebackquote = oldstyle;
10751 saveprompt = doprompt;
10758 doprompt = saveprompt;
10760 if (readtoken() != TRP)
10767 * Start reading from old file again, ignoring any pushed back
10768 * tokens left from the backquote parsing
10773 while (stackblocksize() <= savelen)
10775 STARTSTACKSTR(out);
10777 memcpy(out, str, savelen);
10778 STADJUST(savelen, out);
10784 parsebackquote = savepbq;
10785 handler = savehandler;
10786 if (arinest || dblquote)
10787 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10789 USTPUTC(CTLBACKQ, out);
10791 goto parsebackq_oldreturn;
10793 goto parsebackq_newreturn;
10797 * Parse an arithmetic expansion (indicate start of one and set state)
10801 if (++arinest == 1) {
10802 prevsyntax = syntax;
10803 syntax = ARISYNTAX;
10804 USTPUTC(CTLARI, out);
10811 * we collapse embedded arithmetic expansion to
10812 * parenthesis, which should be equivalent
10816 goto parsearith_return;
10819 } /* end of readtoken */
10823 * Returns true if the text contains nothing to expand (no dollar signs
10828 noexpand(char *text)
10834 while ((c = *p++) != '\0') {
10835 if (c == CTLQUOTEMARK)
10839 else if (SIT(c,BASESYNTAX) == CCTL)
10847 * Return true if the argument is a legal variable name (a letter or
10848 * underscore followed by zero or more letters, underscores, and digits).
10852 goodname(const char *name)
10860 if (! is_in_name(*p))
10868 * Called when an unexpected token is read during the parse. The argument
10869 * is the token that is expected, or -1 if more than one type of token can
10870 * occur at this point.
10874 synexpect(int token)
10879 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10881 sprintf(msg+l, " (expecting %s)", tokname(token));
10888 synerror(const char *msg)
10891 out2fmt("%s: %d: ", commandname, startlinno);
10892 out2fmt("Syntax error: %s\n", msg);
10893 error((char *)NULL);
10899 * called by editline -- any expansions to the prompt
10900 * should be added here.
10903 setprompt(int whichprompt)
10906 switch (whichprompt) {
10921 * Code for dealing with input/output redirection.
10924 #define EMPTY -2 /* marks an unused slot in redirtab */
10926 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10928 # define PIPESIZE PIPE_BUF
10933 * Open a file in noclobber mode.
10934 * The code was copied from bash.
10937 noclobberopen(const char *fname)
10940 struct stat finfo, finfo2;
10943 * If the file exists and is a regular file, return an error
10946 r = stat(fname, &finfo);
10947 if (r == 0 && S_ISREG(finfo.st_mode)) {
10953 * If the file was not present (r != 0), make sure we open it
10954 * exclusively so that if it is created before we open it, our open
10955 * will fail. Make sure that we do not truncate an existing file.
10956 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10957 * file was not a regular file, we leave O_EXCL off.
10960 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
10961 fd = open(fname, O_WRONLY|O_CREAT, 0666);
10963 /* If the open failed, return the file descriptor right away. */
10968 * OK, the open succeeded, but the file may have been changed from a
10969 * non-regular file to a regular file between the stat and the open.
10970 * We are assuming that the O_EXCL open handles the case where FILENAME
10971 * did not exist and is symlinked to an existing file between the stat
10976 * If we can open it and fstat the file descriptor, and neither check
10977 * revealed that it was a regular file, and the file has not been
10978 * replaced, return the file descriptor.
10980 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10981 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10984 /* The file has been replaced. badness. */
10991 * Handle here documents. Normally we fork off a process to write the
10992 * data to a pipe. If the document is short, we can stuff the data in
10993 * the pipe without forking.
10997 openhere(const union node *redir)
11003 error("Pipe call failed");
11004 if (redir->type == NHERE) {
11005 len = strlen(redir->nhere.doc->narg.text);
11006 if (len <= PIPESIZE) {
11007 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11011 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11013 signal(SIGINT, SIG_IGN);
11014 signal(SIGQUIT, SIG_IGN);
11015 signal(SIGHUP, SIG_IGN);
11017 signal(SIGTSTP, SIG_IGN);
11019 signal(SIGPIPE, SIG_DFL);
11020 if (redir->type == NHERE)
11021 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11023 expandhere(redir->nhere.doc, pip[1]);
11033 openredirect(const union node *redir)
11038 switch (redir->nfile.type) {
11040 fname = redir->nfile.expfname;
11041 if ((f = open(fname, O_RDONLY)) < 0)
11045 fname = redir->nfile.expfname;
11046 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11050 /* Take care of noclobber mode. */
11052 fname = redir->nfile.expfname;
11053 if ((f = noclobberopen(fname)) < 0)
11058 fname = redir->nfile.expfname;
11060 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11063 if ((f = creat(fname, 0666)) < 0)
11068 fname = redir->nfile.expfname;
11070 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11073 if ((f = open(fname, O_WRONLY)) < 0
11074 && (f = creat(fname, 0666)) < 0)
11076 lseek(f, (off_t)0, 2);
11083 /* Fall through to eliminate warning. */
11090 f = openhere(redir);
11096 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11098 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11103 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11104 * old file descriptors are stashed away so that the redirection can be
11105 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11106 * standard output, and the standard error if it becomes a duplicate of
11111 redirect(union node *redir, int flags)
11114 struct redirtab *sv = NULL;
11119 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11121 if (flags & REDIR_PUSH) {
11122 sv = xmalloc(sizeof (struct redirtab));
11123 for (i = 0 ; i < 10 ; i++)
11124 sv->renamed[i] = EMPTY;
11125 sv->next = redirlist;
11128 for (n = redir ; n ; n = n->nfile.next) {
11131 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11132 n->ndup.dupfd == fd)
11133 continue; /* redirect from/to same file descriptor */
11136 newfd = openredirect(n);
11137 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11140 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11144 dupredirect(n, newfd, fd1dup);
11154 error("%d: %m", fd);
11160 if (flags & REDIR_PUSH) {
11161 sv->renamed[fd] = i;
11164 } else if (fd != newfd) {
11170 dupredirect(n, newfd, fd1dup);
11177 dupredirect(const union node *redir, int f, int fd1dup)
11179 int fd = redir->nfile.fd;
11183 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11184 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11185 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11186 dup_as_newfd(redir->ndup.dupfd, fd);
11192 dup_as_newfd(f, fd);
11201 * Undo the effects of the last redirection.
11207 struct redirtab *rp = redirlist;
11211 for (i = 0 ; i < 10 ; i++) {
11212 if (rp->renamed[i] != EMPTY) {
11216 if (rp->renamed[i] >= 0) {
11217 dup_as_newfd(rp->renamed[i], i);
11218 close(rp->renamed[i]);
11222 redirlist = rp->next;
11228 * Discard all saved file descriptors.
11233 struct redirtab *rp;
11236 for (rp = redirlist ; rp ; rp = rp->next) {
11237 for (i = 0 ; i < 10 ; i++) {
11238 if (rp->renamed[i] >= 0) {
11239 close(rp->renamed[i]);
11241 rp->renamed[i] = EMPTY;
11248 * Copy a file descriptor to be >= to. Returns -1
11249 * if the source file descriptor is closed, EMPTY if there are no unused
11250 * file descriptors left.
11254 dup_as_newfd(int from, int to)
11258 newfd = fcntl(from, F_DUPFD, to);
11260 if (errno == EMFILE)
11263 error("%d: %m", from);
11272 static void shtree (union node *, int, char *, FILE*);
11273 static void shcmd (union node *, FILE *);
11274 static void sharg (union node *, FILE *);
11275 static void indent (int, char *, FILE *);
11276 static void trstring (char *);
11283 trputs("showtree called\n");
11284 shtree(n, 1, NULL, stdout);
11289 shtree(union node *n, int ind, char *pfx, FILE *fp)
11291 struct nodelist *lp;
11297 indent(ind, pfx, fp);
11308 shtree(n->nbinary.ch1, ind, NULL, fp);
11311 shtree(n->nbinary.ch2, ind, NULL, fp);
11319 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11324 if (n->npipe.backgnd)
11330 fprintf(fp, "<node type %d>", n->type);
11340 shcmd(union node *cmd, FILE *fp)
11348 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11354 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11360 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11361 s = redir_strings[np->nfile.type - NTO];
11367 switch (np->nfile.type) {
11368 case NTO: s = ">"; dftfd = 1; break;
11369 case NAPPEND: s = ">>"; dftfd = 1; break;
11370 case NTOFD: s = ">&"; dftfd = 1; break;
11371 case NTOOV: s = ">|"; dftfd = 1; break;
11372 case NFROM: s = "<"; dftfd = 0; break;
11373 case NFROMFD: s = "<&"; dftfd = 0; break;
11374 case NFROMTO: s = "<>"; dftfd = 0; break;
11375 default: s = "*error*"; dftfd = 0; break;
11378 if (np->nfile.fd != dftfd)
11379 fprintf(fp, "%d", np->nfile.fd);
11381 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11382 fprintf(fp, "%d", np->ndup.dupfd);
11384 sharg(np->nfile.fname, fp);
11391 sharg(union node *arg, FILE *fp)
11394 struct nodelist *bqlist;
11397 if (arg->type != NARG) {
11398 printf("<node type %d>\n", arg->type);
11402 bqlist = arg->narg.backquote;
11403 for (p = arg->narg.text ; *p ; p++) {
11412 if (subtype == VSLENGTH)
11418 if (subtype & VSNUL)
11421 switch (subtype & VSTYPE) {
11440 case VSTRIMLEFTMAX:
11447 case VSTRIMRIGHTMAX:
11454 printf("<subtype %d>", subtype);
11461 case CTLBACKQ|CTLQUOTE:
11464 shtree(bqlist->n, -1, NULL, fp);
11476 indent(int amount, char *pfx, FILE *fp)
11480 for (i = 0 ; i < amount ; i++) {
11481 if (pfx && i == amount - 1)
11491 static int debug = 1;
11493 static int debug = 0;
11500 if (tracefile == NULL)
11502 putc(c, tracefile);
11508 trace(const char *fmt, ...)
11512 if (tracefile != NULL) {
11513 (void) vfprintf(tracefile, fmt, va);
11514 if (strchr(fmt, '\n'))
11515 (void) fflush(tracefile);
11522 trputs(const char *s)
11524 if (tracefile == NULL)
11526 fputs(s, tracefile);
11527 if (strchr(s, '\n'))
11538 if (tracefile == NULL)
11540 putc('"', tracefile);
11541 for (p = s ; *p ; p++) {
11543 case '\n': c = 'n'; goto backslash;
11544 case '\t': c = 't'; goto backslash;
11545 case '\r': c = 'r'; goto backslash;
11546 case '"': c = '"'; goto backslash;
11547 case '\\': c = '\\'; goto backslash;
11548 case CTLESC: c = 'e'; goto backslash;
11549 case CTLVAR: c = 'v'; goto backslash;
11550 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11551 case CTLBACKQ: c = 'q'; goto backslash;
11552 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11553 backslash: putc('\\', tracefile);
11554 putc(c, tracefile);
11557 if (*p >= ' ' && *p <= '~')
11558 putc(*p, tracefile);
11560 putc('\\', tracefile);
11561 putc(*p >> 6 & 03, tracefile);
11562 putc(*p >> 3 & 07, tracefile);
11563 putc(*p & 07, tracefile);
11568 putc('"', tracefile);
11575 if (tracefile == NULL)
11580 putc(' ', tracefile);
11582 putc('\n', tracefile);
11598 #ifdef not_this_way
11601 if ((p = getenv("HOME")) == NULL) {
11602 if (geteuid() == 0)
11608 strcat(s, "/trace");
11611 strcpy(s, "./trace");
11612 #endif /* not_this_way */
11613 if ((tracefile = wfopen(s, "a")) == NULL)
11616 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11617 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11619 fputs("\nTracing started.\n", tracefile);
11626 * The trap builtin.
11630 trapcmd(int argc, char **argv)
11637 for (signo = 0 ; signo < NSIG ; signo++) {
11638 if (trap[signo] != NULL) {
11642 p = single_quote(trap[signo]);
11643 sn = sys_siglist[signo];
11645 sn = u_signal_names(0, &signo, 0);
11648 printf("trap -- %s %s\n", p, sn);
11660 if ((signo = decode_signal(*ap, 0)) < 0)
11661 error("%s: bad trap", *ap);
11664 if (action[0] == '-' && action[1] == '\0')
11667 action = xstrdup(action);
11670 trap[signo] = action;
11685 * Set the signal handler for the specified signal. The routine figures
11686 * out what it should be set to.
11690 setsignal(int signo)
11694 struct sigaction act;
11696 if ((t = trap[signo]) == NULL)
11698 else if (*t != '\0')
11702 if (rootshell && action == S_DFL) {
11705 if (iflag || minusc || sflag == 0)
11721 #ifdef CONFIG_ASH_JOB_CONTROL
11731 t = &sigmode[signo - 1];
11734 * current setting unknown
11736 if (sigaction(signo, 0, &act) == -1) {
11738 * Pretend it worked; maybe we should give a warning
11739 * here, but other shells don't. We don't alter
11740 * sigmode, so that we retry every time.
11744 if (act.sa_handler == SIG_IGN) {
11745 if (mflag && (signo == SIGTSTP ||
11746 signo == SIGTTIN || signo == SIGTTOU)) {
11747 *t = S_IGN; /* don't hard ignore these */
11751 *t = S_RESET; /* force to be set */
11754 if (*t == S_HARD_IGN || *t == action)
11756 act.sa_handler = ((action == S_CATCH) ? onsig
11757 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11760 sigemptyset(&act.sa_mask);
11761 sigaction(signo, &act, 0);
11769 ignoresig(int signo)
11771 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11772 signal(signo, SIG_IGN);
11774 sigmode[signo - 1] = S_HARD_IGN;
11785 if (signo == SIGINT && trap[SIGINT] == NULL) {
11789 gotsig[signo - 1] = 1;
11795 * Called to execute a trap. Perhaps we should avoid entering new trap
11796 * handlers while we are executing a trap handler.
11806 for (i = 1 ; ; i++) {
11813 savestatus=exitstatus;
11814 evalstring(trap[i], 0);
11815 exitstatus=savestatus;
11822 * Called to exit the shell.
11826 exitshell(int status)
11828 struct jmploc loc1, loc2;
11831 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11832 if (setjmp(loc1.loc)) {
11835 if (setjmp(loc2.loc)) {
11839 if ((p = trap[0]) != NULL && *p != '\0') {
11843 l1: handler = &loc2; /* probably unnecessary */
11845 #ifdef CONFIG_ASH_JOB_CONTROL
11852 static int decode_signal(const char *string, int minsig)
11855 const char *name = u_signal_names(string, &signo, minsig);
11857 return name ? signo : -1;
11860 static struct var **hashvar (const char *);
11861 static void showvars (const char *, int, int);
11862 static struct var **findvar (struct var **, const char *);
11865 * Initialize the varable symbol tables and import the environment
11869 * This routine initializes the builtin variables. It is called when the
11870 * shell is initialized and again when a shell procedure is spawned.
11875 const struct varinit *ip;
11879 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
11880 if ((vp->flags & VEXPORT) == 0) {
11881 vpp = hashvar(ip->text);
11884 vp->text = xstrdup(ip->text);
11885 vp->flags = ip->flags;
11886 vp->func = ip->func;
11889 #if !defined(CONFIG_FEATURE_COMMAND_EDITING) || !defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
11891 * PS1 depends on uid
11893 if ((vps1.flags & VEXPORT) == 0) {
11894 vpp = hashvar("PS1=$");
11897 vps1.text = xstrdup(geteuid() ? "PS1=$ " : "PS1=# ");
11898 vps1.flags = VSTRFIXED|VTEXTFIXED;
11904 * Set the value of a variable. The flags argument is ored with the
11905 * flags of the variable. If val is NULL, the variable is unset.
11909 setvar(const char *name, const char *val, int flags)
11924 if (! is_in_name(*p)) {
11925 if (*p == '\0' || *p == '=')
11931 namelen = p - name;
11933 error("%.*s: bad variable name", namelen, name);
11934 len = namelen + 2; /* 2 is space for '=' and '\0' */
11938 len += vallen = strlen(val);
11941 nameeq = xmalloc(len);
11942 memcpy(nameeq, name, namelen);
11943 nameeq[namelen] = '=';
11945 memcpy(nameeq + namelen + 1, val, vallen + 1);
11947 nameeq[namelen + 1] = '\0';
11949 setvareq(nameeq, flags);
11956 * Same as setvar except that the variable and value are passed in
11957 * the first argument as name=value. Since the first argument will
11958 * be actually stored in the table, it should not be a string that
11963 setvareq(char *s, int flags)
11965 struct var *vp, **vpp;
11968 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11969 if ((vp = *findvar(vpp, s))) {
11970 if (vp->flags & VREADONLY) {
11971 size_t len = strchr(s, '=') - s;
11972 error("%.*s: is read only", len, s);
11976 if (vp->func && (flags & VNOFUNC) == 0)
11977 (*vp->func)(strchr(s, '=') + 1);
11979 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
11982 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
11983 vp->flags |= flags;
11986 #ifdef CONFIG_ASH_MAIL
11988 * We could roll this to a function, to handle it as
11989 * a regular variable function callback, but why bother?
11991 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
11998 vp = xmalloc(sizeof (*vp));
12009 * Process a linked list of variable assignments.
12013 listsetvar(struct strlist *mylist)
12015 struct strlist *lp;
12018 for (lp = mylist ; lp ; lp = lp->next) {
12019 setvareq(xstrdup(lp->text), 0);
12027 * Find the value of a variable. Returns NULL if not set.
12030 static const char *
12031 lookupvar(const char *name)
12035 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12036 return strchr(v->text, '=') + 1;
12044 * Search the environment of a builtin command.
12047 static const char *
12048 bltinlookup(const char *name)
12050 const struct strlist *sp;
12052 for (sp = cmdenviron ; sp ; sp = sp->next) {
12053 if (varequal(sp->text, name))
12054 return strchr(sp->text, '=') + 1;
12056 return lookupvar(name);
12062 * Generate a list of exported variables. This routine is used to construct
12063 * the third argument to execve when executing a program.
12075 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12076 for (vp = *vpp ; vp ; vp = vp->next)
12077 if (vp->flags & VEXPORT)
12080 ep = env = stalloc((nenv + 1) * sizeof *env);
12081 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12082 for (vp = *vpp ; vp ; vp = vp->next)
12083 if (vp->flags & VEXPORT)
12092 * Called when a shell procedure is invoked to clear out nonexported
12093 * variables. It is also necessary to reallocate variables of with
12094 * VSTACK set since these are currently allocated on the stack.
12100 struct var *vp, **prev;
12102 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12103 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12104 if ((vp->flags & VEXPORT) == 0) {
12106 if ((vp->flags & VTEXTFIXED) == 0)
12108 if ((vp->flags & VSTRFIXED) == 0)
12111 if (vp->flags & VSTACK) {
12112 vp->text = xstrdup(vp->text);
12113 vp->flags &=~ VSTACK;
12125 * Command to list all variables which are set. Currently this command
12126 * is invoked from the set command when the set command is called without
12131 showvarscmd(int argc, char **argv)
12133 showvars(nullstr, VUNSET, VUNSET);
12140 * The export and readonly commands.
12144 exportcmd(int argc, char **argv)
12149 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12152 listsetvar(cmdenviron);
12153 pflag = (nextopt("p") == 'p');
12154 if (argc > 1 && !pflag) {
12155 while ((name = *argptr++) != NULL) {
12156 if ((p = strchr(name, '=')) != NULL) {
12159 if ((vp = *findvar(hashvar(name), name))) {
12164 setvar(name, p, flag);
12168 showvars(argv[0], flag, 0);
12175 * The "local" command.
12178 /* funcnest nonzero if we are currently evaluating a function */
12181 localcmd(int argc, char **argv)
12186 error("Not in a function");
12187 while ((name = *argptr++) != NULL) {
12195 * Make a variable a local variable. When a variable is made local, it's
12196 * value and flags are saved in a localvar structure. The saved values
12197 * will be restored when the shell function returns. We handle the name
12198 * "-" as a special case.
12202 mklocal(char *name)
12204 struct localvar *lvp;
12209 lvp = xmalloc(sizeof (struct localvar));
12210 if (name[0] == '-' && name[1] == '\0') {
12212 p = xmalloc(sizeof optet_vals);
12213 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12216 vpp = hashvar(name);
12217 vp = *findvar(vpp, name);
12219 if (strchr(name, '='))
12220 setvareq(xstrdup(name), VSTRFIXED);
12222 setvar(name, NULL, VSTRFIXED);
12223 vp = *vpp; /* the new variable */
12225 lvp->flags = VUNSET;
12227 lvp->text = vp->text;
12228 lvp->flags = vp->flags;
12229 vp->flags |= VSTRFIXED|VTEXTFIXED;
12230 if (strchr(name, '='))
12231 setvareq(xstrdup(name), 0);
12235 lvp->next = localvars;
12242 * Called after a function returns.
12247 struct localvar *lvp;
12250 while ((lvp = localvars) != NULL) {
12251 localvars = lvp->next;
12253 if (vp == NULL) { /* $- saved */
12254 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12256 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12257 (void)unsetvar(vp->text);
12259 if ((vp->flags & VTEXTFIXED) == 0)
12261 vp->flags = lvp->flags;
12262 vp->text = lvp->text;
12270 setvarcmd(int argc, char **argv)
12273 return unsetcmd(argc, argv);
12274 else if (argc == 3)
12275 setvar(argv[1], argv[2], 0);
12277 error("List assignment not implemented");
12283 * The unset builtin command. We unset the function before we unset the
12284 * variable to allow a function to be unset when there is a readonly variable
12285 * with the same name.
12289 unsetcmd(int argc, char **argv)
12297 while ((i = nextopt("vf")) != '\0') {
12303 if (flg_func == 0 && flg_var == 0)
12306 for (ap = argptr; *ap ; ap++) {
12310 ret |= unsetvar(*ap);
12317 * Unset the specified variable.
12321 unsetvar(const char *s)
12326 vpp = findvar(hashvar(s), s);
12329 if (vp->flags & VREADONLY)
12332 if (*(strchr(vp->text, '=') + 1) != '\0')
12333 setvar(s, nullstr, 0);
12334 vp->flags &= ~VEXPORT;
12335 vp->flags |= VUNSET;
12336 if ((vp->flags & VSTRFIXED) == 0) {
12337 if ((vp->flags & VTEXTFIXED) == 0)
12352 * Find the appropriate entry in the hash table from the name.
12355 static struct var **
12356 hashvar(const char *p)
12358 unsigned int hashval;
12360 hashval = ((unsigned char) *p) << 4;
12361 while (*p && *p != '=')
12362 hashval += (unsigned char) *p++;
12363 return &vartab[hashval % VTABSIZE];
12369 * Returns true if the two strings specify the same varable. The first
12370 * variable name is terminated by '='; the second may be terminated by
12371 * either '=' or '\0'.
12375 varequal(const char *p, const char *q)
12377 while (*p == *q++) {
12381 if (*p == '=' && *(q - 1) == '\0')
12387 showvars(const char *myprefix, int mask, int xor)
12391 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12393 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12394 for (vp = *vpp ; vp ; vp = vp->next) {
12395 if ((vp->flags & mask) ^ xor) {
12399 p = strchr(vp->text, '=') + 1;
12400 len = p - vp->text;
12401 p = single_quote(p);
12403 printf("%s%s%.*s%s\n", myprefix, sep, len,
12411 static struct var **
12412 findvar(struct var **vpp, const char *name)
12414 for (; *vpp; vpp = &(*vpp)->next) {
12415 if (varequal((*vpp)->text, name)) {
12423 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12424 * This file contains code for the times builtin.
12425 * $Id: ash.c,v 1.56 2002/08/02 06:39:47 aaronl Exp $
12427 static int timescmd (int argc, char **argv)
12430 long int clk_tck = sysconf(_SC_CLK_TCK);
12433 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12434 (int) (buf.tms_utime / clk_tck / 60),
12435 ((double) buf.tms_utime) / clk_tck,
12436 (int) (buf.tms_stime / clk_tck / 60),
12437 ((double) buf.tms_stime) / clk_tck,
12438 (int) (buf.tms_cutime / clk_tck / 60),
12439 ((double) buf.tms_cutime) / clk_tck,
12440 (int) (buf.tms_cstime / clk_tck / 60),
12441 ((double) buf.tms_cstime) / clk_tck);
12445 #ifdef CONFIG_ASH_MATH_SUPPORT
12446 /* The let builtin. */
12447 int letcmd(int argc, char **argv)
12452 char *tmp, *expression, p[13];
12453 expression = strchr(argv[1], '=');
12455 /* Cannot use 'error()' here, or the return code
12456 * will be incorrect */
12457 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12460 *expression = '\0';
12461 tmp = ++expression;
12462 result = arith(tmp, &errcode);
12464 /* Cannot use 'error()' here, or the return code
12465 * will be incorrect */
12466 out2fmt("sh: let: ");
12468 out2fmt("divide by zero");
12470 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12473 snprintf(p, 12, "%ld", result);
12474 setvar(argv[1], xstrdup(p), 0);
12475 } else if (argc >= 3)
12476 synerror("invalid operand");
12484 * Copyright (c) 1989, 1991, 1993, 1994
12485 * The Regents of the University of California. All rights reserved.
12487 * This code is derived from software contributed to Berkeley by
12488 * Kenneth Almquist.
12490 * Redistribution and use in source and binary forms, with or without
12491 * modification, are permitted provided that the following conditions
12493 * 1. Redistributions of source code must retain the above copyright
12494 * notice, this list of conditions and the following disclaimer.
12495 * 2. Redistributions in binary form must reproduce the above copyright
12496 * notice, this list of conditions and the following disclaimer in the
12497 * documentation and/or other materials provided with the distribution.
12499 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12500 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12502 * 4. Neither the name of the University nor the names of its contributors
12503 * may be used to endorse or promote products derived from this software
12504 * without specific prior written permission.
12506 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12507 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12508 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12509 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12510 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12511 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12512 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12513 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12514 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12515 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF