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);
251 #define INTON __inton()
252 #define FORCEINTON forceinton()
255 #define CLEAR_PENDING_INT intpending = 0
256 #define int_pending() intpending
259 typedef void *pointer;
262 #define NULL (void *)0
265 static pointer stalloc(int);
266 static void stunalloc(pointer);
267 static void ungrabstackstr(char *, char *);
268 static char *growstackstr(void);
269 static char *makestrspace(size_t newlen);
270 static char *sstrdup(const char *);
273 * Parse trees for commands are allocated in lifo order, so we use a stack
274 * to make this more efficient, and also to avoid all sorts of exception
275 * handling code to handle interrupts in the middle of a parse.
277 * The size 504 was chosen because the Ultrix malloc handles that size
281 #define MINSIZE 504 /* minimum size of a block */
285 struct stack_block *prev;
289 static struct stack_block stackbase;
290 static struct stack_block *stackp = &stackbase;
291 static struct stackmark *markp;
292 static char *stacknxt = stackbase.space;
293 static int stacknleft = MINSIZE;
296 #define equal(s1, s2) (strcmp(s1, s2) == 0)
298 #define stackblock() stacknxt
299 #define stackblocksize() stacknleft
300 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
302 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
303 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
304 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
307 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
308 #define STUNPUTC(p) (++sstrnleft, --p)
309 #define STTOPC(p) p[-1]
310 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
311 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
316 #define TRACE(param) trace param
317 typedef union node unode;
318 static void trace(const char *, ...);
319 static void trargs(char **);
320 static void showtree(unode *);
321 static void trputc(int);
322 static void trputs(const char *);
323 static void opentrace(void);
358 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
359 #define EXP_TILDE 0x2 /* do normal tilde expansion */
360 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
361 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
362 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
363 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
368 static char optet_vals[NOPTS];
370 static const char *const optlist[NOPTS] = {
389 #define optent_name(optent) (optent+1)
390 #define optent_letter(optent) optent[0]
391 #define optent_val(optent) optet_vals[optent]
393 #define eflag optent_val(0)
394 #define fflag optent_val(1)
395 #define Iflag optent_val(2)
396 #define iflag optent_val(3)
397 #define mflag optent_val(4)
398 #define nflag optent_val(5)
399 #define sflag optent_val(6)
400 #define xflag optent_val(7)
401 #define vflag optent_val(8)
402 #define Vflag optent_val(9)
403 #define Eflag optent_val(10)
404 #define Cflag optent_val(11)
405 #define aflag optent_val(12)
406 #define bflag optent_val(13)
407 #define uflag optent_val(14)
408 #define qflag optent_val(15)
411 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
429 union node *redirect;
436 struct nodelist *cmdlist;
443 union node *redirect;
451 union node *elsepart;
482 struct nodelist *backquote;
520 struct nbinary nbinary;
523 struct nredir nredir;
527 struct nclist nclist;
537 struct nodelist *next;
541 struct backcmd { /* result of evalbackcmd */
542 int fd; /* file descriptor to read from */
543 char *buf; /* buffer */
544 int nleft; /* number of chars in buffer */
545 struct job *jp; /* job structure for command */
553 const struct builtincmd *cmd;
558 struct strlist *next;
564 struct strlist *list;
565 struct strlist **lastp;
569 struct strpush *prev; /* preceding string on stack */
572 #ifdef CONFIG_ASH_ALIAS
573 struct alias *ap; /* if push was associated with an alias */
575 char *string; /* remember the string since it may change */
579 struct parsefile *prev; /* preceding file on stack */
580 int linno; /* current line */
581 int fd; /* file descriptor (or -1 if string) */
582 int nleft; /* number of chars left in this line */
583 int lleft; /* number of chars left in this buffer */
584 char *nextc; /* next char in buffer */
585 char *buf; /* input buffer */
586 struct strpush *strpush; /* for pushing strings at this level */
587 struct strpush basestrpush; /* so pushing one is fast */
591 struct stack_block *stackp;
594 struct stackmark *marknext;
598 int nparam; /* # of positional parameters (without $0) */
599 unsigned char malloc; /* if parameter list dynamically allocated */
600 char **p; /* parameter list */
601 int optind; /* next parameter to be processed by getopts */
602 int optoff; /* used by getopts */
606 * When commands are first encountered, they are entered in a hash table.
607 * This ensures that a full path search will not have to be done for them
608 * on each invocation.
610 * We should investigate converting to a linear search, even though that
611 * would make the command name "hash" a misnomer.
613 #define CMDTABLESIZE 31 /* should be prime */
614 #define ARB 1 /* actual size determined at run time */
619 struct tblentry *next; /* next entry in hash chain */
620 union param param; /* definition of builtin function */
621 short cmdtype; /* index identifying command */
622 char rehash; /* if set, cd done since entry created */
623 char cmdname[ARB]; /* name of command */
627 static struct tblentry *cmdtable[CMDTABLESIZE];
628 static int builtinloc = -1; /* index in path of %builtin, or -1 */
629 static int exerrno = 0; /* Last exec error */
632 static void tryexec(char *, char **, char **);
633 static void printentry(struct tblentry *, int);
634 static void clearcmdentry(int);
635 static struct tblentry *cmdlookup(const char *, int);
636 static void delete_cmd_entry(void);
637 static int path_change(const char *, int *);
640 static void flushall(void);
641 static void out2fmt(const char *, ...)
642 __attribute__ ((__format__(__printf__, 1, 2)));
643 static int xwrite(int, const char *, int);
645 static inline void outstr(const char *p, FILE * file)
649 static void out1str(const char *p)
653 static void out2str(const char *p)
658 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
659 #define out2c(c) putc((c), stderr)
661 static void out2c(int c)
668 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
669 #define USE_SIT_FUNCTION
672 /* number syntax index */
673 #define BASESYNTAX 0 /* not in quotes */
674 #define DQSYNTAX 1 /* in double quotes */
675 #define SQSYNTAX 2 /* in single quotes */
676 #define ARISYNTAX 3 /* in arithmetic */
678 static const char S_I_T[][4] = {
679 /* 0 */ {CSPCL, CIGN, CIGN, CIGN},
681 /* 1 */ {CSPCL, CWORD, CWORD, CWORD},
683 /* 2 */ {CNL, CNL, CNL, CNL},
685 /* 3 */ {CWORD, CCTL, CCTL, CWORD},
687 /* 4 */ {CDQUOTE, CENDQUOTE, CWORD, CDQUOTE},
689 /* 5 */ {CVAR, CVAR, CWORD, CVAR},
691 /* 6 */ {CSQUOTE, CWORD, CENDQUOTE, CSQUOTE},
693 /* 7 */ {CSPCL, CWORD, CWORD, CLP},
695 /* 8 */ {CSPCL, CWORD, CWORD, CRP},
697 /* 9 */ {CBACK, CBACK, CCTL, CBACK},
699 /* 10 */ {CBQUOTE, CBQUOTE, CWORD, CBQUOTE},
701 /* 11 */ {CENDVAR, CENDVAR, CWORD, CENDVAR},
703 #ifndef USE_SIT_FUNCTION
704 /* 12 */ {CENDFILE, CENDFILE, CENDFILE, CENDFILE},
706 /* 13 */ {CWORD, CWORD, CWORD, CWORD},
708 /* 14 */ {CCTL, CCTL, CCTL, CCTL}
713 #ifdef USE_SIT_FUNCTION
715 #define U_C(c) ((unsigned char)(c))
717 static int SIT(int c, int syntax)
719 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
720 static const char syntax_index_table[] = {
721 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
722 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
723 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
729 if (c == PEOF) /* 2^8+2 */
731 if (c == PEOA) /* 2^8+1 */
733 else if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
736 s = strchr(spec_symbls, c);
739 indx = syntax_index_table[(s - spec_symbls)];
741 return S_I_T[indx][syntax];
744 #else /* USE_SIT_FUNCTION */
746 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
748 #define CSPCL_CIGN_CIGN_CIGN 0
749 #define CSPCL_CWORD_CWORD_CWORD 1
750 #define CNL_CNL_CNL_CNL 2
751 #define CWORD_CCTL_CCTL_CWORD 3
752 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
753 #define CVAR_CVAR_CWORD_CVAR 5
754 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
755 #define CSPCL_CWORD_CWORD_CLP 7
756 #define CSPCL_CWORD_CWORD_CRP 8
757 #define CBACK_CBACK_CCTL_CBACK 9
758 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
759 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
760 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
761 #define CWORD_CWORD_CWORD_CWORD 13
762 #define CCTL_CCTL_CCTL_CCTL 14
764 static const char syntax_index_table[258] = {
765 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
766 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
767 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
768 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
769 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL,
771 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
772 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
773 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
774 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
775 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
776 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
777 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL,
779 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
780 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
781 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
782 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
783 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
784 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
785 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
786 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
787 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
788 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
789 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
790 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
791 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
792 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
793 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
794 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
795 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
796 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
797 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
798 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
799 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
800 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
801 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
802 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
803 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
804 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
805 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
806 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
807 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
808 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
809 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
810 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
811 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
812 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
813 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
814 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
815 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
816 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
817 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
818 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
819 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
820 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
821 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
822 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
823 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
824 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
825 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
826 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
827 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
828 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
829 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
830 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
831 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
832 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
833 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
834 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
835 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
836 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
837 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
838 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
839 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
840 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
841 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
842 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
843 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
844 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
845 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
846 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
847 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
848 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
849 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
850 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
851 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
852 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
853 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
854 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
855 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
856 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
857 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
858 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
859 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
860 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
861 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
862 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
863 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
864 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
865 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
866 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
867 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
868 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
869 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
870 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
871 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
872 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
873 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
874 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
875 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
876 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
877 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
878 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
879 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
880 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
881 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
882 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
883 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
884 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
885 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
886 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
887 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
888 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
889 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
890 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
891 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
892 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
893 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
894 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
895 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
896 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
897 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
898 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
899 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
900 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
901 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
902 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
903 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
904 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
905 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
906 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
907 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
908 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
909 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
910 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
911 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
912 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
913 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
914 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
915 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
916 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
917 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
918 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
919 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
920 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
921 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
922 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
923 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
924 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
925 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
926 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
927 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
928 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
929 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
930 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
931 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
932 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
933 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
934 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
935 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
936 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
937 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
938 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
939 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
940 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
941 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
942 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
943 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
944 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
945 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
946 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
947 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
948 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
949 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
950 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
951 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
952 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
953 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
954 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
955 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
956 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
957 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
958 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
959 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
960 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
961 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
962 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
963 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
964 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
965 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
966 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
967 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
968 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
969 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
970 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
971 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
972 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
973 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
974 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
975 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
976 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
977 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
978 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
979 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
980 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
981 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
982 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
983 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
984 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
985 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
986 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
987 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
988 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
989 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
990 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
991 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
992 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
993 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
994 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
995 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
996 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
997 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
998 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
999 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1004 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1005 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1023 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1024 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1025 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1028 #endif /* USE_SIT_FUNCTION */
1031 /* first char is indicating which tokens mark the end of a list */
1032 static const char *const tokname_array[] = {
1047 #define KWDOFFSET 14
1048 /* the following are keywords */
1067 static const char *tokname(int tok)
1069 static char buf[16];
1073 sprintf(buf + (tok >= TSEMI), "%s%c",
1074 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
1078 static int plinno = 1; /* input line number */
1080 static int parselleft; /* copy of parsefile->lleft */
1082 static struct parsefile basepf; /* top level input file */
1083 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1084 static struct parsefile *parsefile = &basepf; /* current input file */
1087 * NEOF is returned by parsecmd when it encounters an end of file. It
1088 * must be distinct from NULL, so we use the address of a variable that
1089 * happens to be handy.
1092 static int tokpushback; /* last token pushed back */
1094 #define NEOF ((union node *)&tokpushback)
1095 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1098 static void error(const char *, ...) __attribute__ ((__noreturn__));
1099 static void exerror(int, const char *, ...) __attribute__ ((__noreturn__));
1100 static void shellexec(char **, char **, const char *, int)
1101 __attribute__ ((noreturn));
1102 static void exitshell(int) __attribute__ ((noreturn));
1104 static int goodname(const char *);
1105 static void ignoresig(int);
1106 static void onsig(int);
1107 static void dotrap(void);
1108 static int decode_signal(const char *, int);
1110 static void shprocvar(void);
1111 static void deletefuncs(void);
1112 static void setparam(char **);
1113 static void freeparam(volatile struct shparam *);
1115 static void find_command(const char *, struct cmdentry *, int, const char *);
1117 static inline void hashcd(void);
1119 /* reasons for skipping commands (see comment on breakcmd routine) */
1125 /* values of cmdtype */
1126 #define CMDUNKNOWN -1 /* no entry in table for command */
1127 #define CMDNORMAL 0 /* command is an executable program */
1128 #define CMDBUILTIN 1 /* command is a shell builtin */
1129 #define CMDFUNCTION 2 /* command is a shell function */
1131 #define DO_ERR 1 /* find_command prints errors */
1132 #define DO_ABS 2 /* find_command checks absolute paths */
1133 #define DO_NOFUN 4 /* find_command ignores functions */
1134 #define DO_BRUTE 8 /* find_command ignores hash table */
1141 #define VEXPORT 0x01 /* variable is exported */
1142 #define VREADONLY 0x02 /* variable cannot be modified */
1143 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1144 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1145 #define VSTACK 0x10 /* text is allocated on the stack */
1146 #define VUNSET 0x20 /* the variable is not set */
1147 #define VNOFUNC 0x40 /* don't call the callback function */
1151 struct var *next; /* next entry in hash list */
1152 int flags; /* flags are defined above */
1153 char *text; /* name=value */
1154 void (*func) (const char *);
1155 /* function to be called when */
1156 /* the variable gets set/unset */
1160 struct localvar *next; /* next local variable in list */
1161 struct var *vp; /* the variable that was made local */
1162 int flags; /* saved flags */
1163 char *text; /* saved text */
1167 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1168 #define rmescapes(p) _rmescapes((p), 0)
1169 static char *_rmescapes(char *, int);
1171 static void rmescapes(char *);
1174 static int casematch(union node *, const char *);
1175 static void clearredir(void);
1176 static void popstring(void);
1177 static void readcmdfile(const char *);
1179 static int number(const char *);
1180 static int is_number(const char *, int *num);
1181 static char *single_quote(const char *);
1182 static int nextopt(const char *);
1184 static void redirect(union node *, int);
1185 static void popredir(void);
1186 static int dup_as_newfd(int, int);
1188 static void changepath(const char *newval);
1189 static void getoptsreset(const char *value);
1192 static int parsenleft; /* copy of parsefile->nleft */
1193 static char *parsenextc; /* copy of parsefile->nextc */
1194 static int rootpid; /* pid of main shell */
1195 static int rootshell; /* true if we aren't a child of the main shell */
1197 static const char spcstr[] = " ";
1198 static const char snlfmt[] = "%s\n";
1200 static int sstrnleft;
1201 static int herefd = -1;
1203 static struct localvar *localvars;
1205 static struct var vifs;
1206 static struct var vmail;
1207 static struct var vmpath;
1208 static struct var vpath;
1209 static struct var vps1;
1210 static struct var vps2;
1211 static struct var voptind;
1213 #ifdef CONFIG_LOCALE_SUPPORT
1214 static struct var vlc_all;
1215 static struct var vlc_ctype;
1222 void (*func) (const char *);
1225 static const char defpathvar[] =
1226 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1227 #define defpath (defpathvar + 5)
1230 static const char defifsvar[] = "IFS= \t\n";
1232 #define defifs (defifsvar + 4)
1234 static const char defifs[] = " \t\n";
1237 static const struct varinit varinit[] = {
1239 {&vifs, VSTRFIXED | VTEXTFIXED, defifsvar,
1241 {&vifs, VSTRFIXED | VTEXTFIXED | VUNSET, "IFS=",
1244 {&vmail, VSTRFIXED | VTEXTFIXED | VUNSET, "MAIL=",
1246 {&vmpath, VSTRFIXED | VTEXTFIXED | VUNSET, "MAILPATH=",
1248 {&vpath, VSTRFIXED | VTEXTFIXED, defpathvar,
1250 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1251 {&vps1, VSTRFIXED | VTEXTFIXED, "PS1=\\w \\$ ",
1253 #endif /* else vps1 depends on uid */
1254 {&vps2, VSTRFIXED | VTEXTFIXED, "PS2=> ",
1256 {&voptind, VSTRFIXED | VTEXTFIXED, "OPTIND=1",
1258 #ifdef CONFIG_LOCALE_SUPPORT
1259 {&vlc_all, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=",
1261 {&vlc_ctype, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=",
1270 static struct var *vartab[VTABSIZE];
1273 * The following macros access the values of the above variables.
1274 * They have to skip over the name. They return the null string
1275 * for unset variables.
1278 #define ifsval() (vifs.text + 4)
1279 #define ifsset() ((vifs.flags & VUNSET) == 0)
1280 #define mailval() (vmail.text + 5)
1281 #define mpathval() (vmpath.text + 9)
1282 #define pathval() (vpath.text + 5)
1283 #define ps1val() (vps1.text + 4)
1284 #define ps2val() (vps2.text + 4)
1285 #define optindval() (voptind.text + 7)
1287 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1289 static void initvar(void);
1290 static void setvar(const char *, const char *, int);
1291 static void setvareq(char *, int);
1292 static void listsetvar(struct strlist *);
1293 static const char *lookupvar(const char *);
1294 static const char *bltinlookup(const char *);
1295 static char **environment(void);
1296 static int showvarscmd(int, char **);
1297 static void mklocal(char *);
1298 static void poplocalvars(void);
1299 static int unsetvar(const char *);
1300 static int varequal(const char *, const char *);
1303 static char *arg0; /* value of $0 */
1304 static struct shparam shellparam; /* current positional parameters */
1305 static char **argptr; /* argument list for builtin commands */
1306 static char *optionarg; /* set by nextopt (like getopt) */
1307 static char *optptr; /* used by nextopt */
1308 static char *minusc; /* argument to -c option */
1311 #ifdef CONFIG_ASH_ALIAS
1313 #define ALIASINUSE 1
1325 static struct alias *atab[ATABSIZE];
1327 static void setalias(char *, char *);
1328 static struct alias **hashalias(const char *);
1329 static struct alias *freealias(struct alias *);
1330 static struct alias **__lookupalias(const char *);
1332 static void setalias(char *name, char *val)
1334 struct alias *ap, **app;
1336 app = __lookupalias(name);
1340 if (!(ap->flag & ALIASINUSE)) {
1343 ap->val = xstrdup(val);
1344 ap->flag &= ~ALIASDEAD;
1347 ap = xmalloc(sizeof(struct alias));
1348 ap->name = xstrdup(name);
1349 ap->val = xstrdup(val);
1357 static int unalias(char *name)
1361 app = __lookupalias(name);
1365 *app = freealias(*app);
1373 static void rmaliases(void)
1375 struct alias *ap, **app;
1379 for (i = 0; i < ATABSIZE; i++) {
1381 for (ap = *app; ap; ap = *app) {
1382 *app = freealias(*app);
1391 static void printalias(const struct alias *ap)
1395 p = single_quote(ap->val);
1396 printf("alias %s=%s\n", ap->name, p);
1402 * TODO - sort output
1404 static int aliascmd(int argc, char **argv)
1413 for (i = 0; i < ATABSIZE; i++)
1414 for (ap = atab[i]; ap; ap = ap->next) {
1419 while ((n = *++argv) != NULL) {
1420 if ((v = strchr(n + 1, '=')) == NULL) { /* n+1: funny ksh stuff */
1421 if ((ap = *__lookupalias(n)) == NULL) {
1422 out2fmt("%s: %s not found\n", "alias", n);
1435 static int unaliascmd(int argc, char **argv)
1439 while ((i = nextopt("a")) != '\0') {
1445 for (i = 0; *argptr; argptr++) {
1446 if (unalias(*argptr)) {
1447 out2fmt("%s: %s not found\n", "unalias", *argptr);
1455 static struct alias **hashalias(const char *p)
1457 unsigned int hashval;
1462 return &atab[hashval % ATABSIZE];
1465 static struct alias *freealias(struct alias *ap)
1469 if (ap->flag & ALIASINUSE) {
1470 ap->flag |= ALIASDEAD;
1482 static struct alias **__lookupalias(const char *name)
1484 struct alias **app = hashalias(name);
1486 for (; *app; app = &(*app)->next) {
1487 if (equal(name, (*app)->name)) {
1496 #ifdef CONFIG_ASH_MATH_SUPPORT
1497 /* The generated file arith.c has been replaced with a custom hand
1498 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1499 * This is now part of libbb, so that it can be used by all the shells
1501 static void expari(int);
1504 static char *trap[NSIG]; /* trap handler commands */
1505 static char sigmode[NSIG - 1]; /* current value of signal */
1506 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1507 static int pendingsigs; /* indicates some signal received */
1510 * This file was generated by the mkbuiltins program.
1513 #ifdef CONFIG_ASH_JOB_CONTROL
1514 static int bgcmd(int, char **);
1515 static int fgcmd(int, char **);
1516 static int killcmd(int, char **);
1518 static int bltincmd(int, char **);
1519 static int cdcmd(int, char **);
1520 static int breakcmd(int, char **);
1522 #ifdef CONFIG_ASH_CMDCMD
1523 static int commandcmd(int, char **);
1525 static int dotcmd(int, char **);
1526 static int evalcmd(int, char **);
1527 static int execcmd(int, char **);
1528 static int exitcmd(int, char **);
1529 static int exportcmd(int, char **);
1530 static int histcmd(int, char **);
1531 static int hashcmd(int, char **);
1532 static int helpcmd(int, char **);
1533 static int jobscmd(int, char **);
1534 static int localcmd(int, char **);
1535 static int pwdcmd(int, char **);
1536 static int readcmd(int, char **);
1537 static int returncmd(int, char **);
1538 static int setcmd(int, char **);
1539 static int setvarcmd(int, char **);
1540 static int shiftcmd(int, char **);
1541 static int trapcmd(int, char **);
1542 static int umaskcmd(int, char **);
1544 #ifdef CONFIG_ASH_ALIAS
1545 static int aliascmd(int, char **);
1546 static int unaliascmd(int, char **);
1548 static int unsetcmd(int, char **);
1549 static int waitcmd(int, char **);
1550 static int ulimitcmd(int, char **);
1551 static int timescmd(int, char **);
1553 #ifdef CONFIG_ASH_MATH_SUPPORT
1554 static int letcmd(int, char **);
1556 static int typecmd(int, char **);
1558 #ifdef CONFIG_ASH_GETOPTS
1559 static int getoptscmd(int, char **);
1563 static int true_main(int, char **);
1565 #ifndef CONFIG_FALSE
1566 static int false_main(int, char **);
1569 static void setpwd(const char *, int);
1572 #define BUILTIN_NOSPEC "0"
1573 #define BUILTIN_SPECIAL "1"
1574 #define BUILTIN_REGULAR "2"
1575 #define BUILTIN_ASSIGN "4"
1576 #define BUILTIN_SPEC_ASSG "5"
1577 #define BUILTIN_REG_ASSG "6"
1579 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1580 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1581 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1585 int (*const builtinfunc) (int, char **);
1586 /* unsigned flags; */
1590 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1591 * the binary search in find_builtin() will stop working. If you value
1592 * your kneecaps, you'll be sure to *make sure* that any changes made
1593 * to this array result in the listing remaining in ascii order. You
1596 static const struct builtincmd builtincmds[] = {
1597 {BUILTIN_SPECIAL ".", dotcmd}, /* first, see declare DOTCMD */
1598 {BUILTIN_SPECIAL ":", true_main},
1599 #ifdef CONFIG_ASH_ALIAS
1600 {BUILTIN_REG_ASSG "alias", aliascmd},
1602 #ifdef CONFIG_ASH_JOB_CONTROL
1603 {BUILTIN_REGULAR "bg", bgcmd},
1605 {BUILTIN_SPECIAL "break", breakcmd},
1606 {BUILTIN_SPECIAL "builtin", bltincmd},
1607 {BUILTIN_REGULAR "cd", cdcmd},
1608 {BUILTIN_NOSPEC "chdir", cdcmd},
1609 #ifdef CONFIG_ASH_CMDCMD
1610 {BUILTIN_REGULAR "command", commandcmd},
1612 {BUILTIN_SPECIAL "continue", breakcmd},
1613 {BUILTIN_SPECIAL "eval", evalcmd},
1614 {BUILTIN_SPECIAL "exec", execcmd},
1615 {BUILTIN_SPECIAL "exit", exitcmd},
1616 {BUILTIN_SPEC_ASSG "export", exportcmd},
1617 {BUILTIN_REGULAR "false", false_main},
1618 {BUILTIN_REGULAR "fc", histcmd},
1619 #ifdef CONFIG_ASH_JOB_CONTROL
1620 {BUILTIN_REGULAR "fg", fgcmd},
1622 #ifdef CONFIG_ASH_GETOPTS
1623 {BUILTIN_REGULAR "getopts", getoptscmd},
1625 {BUILTIN_NOSPEC "hash", hashcmd},
1626 {BUILTIN_NOSPEC "help", helpcmd},
1627 {BUILTIN_REGULAR "jobs", jobscmd},
1628 #ifdef CONFIG_ASH_JOB_CONTROL
1629 {BUILTIN_REGULAR "kill", killcmd},
1631 #ifdef CONFIG_ASH_MATH_SUPPORT
1632 {BUILTIN_REGULAR "let", letcmd},
1634 {BUILTIN_ASSIGN "local", localcmd},
1635 {BUILTIN_NOSPEC "pwd", pwdcmd},
1636 {BUILTIN_REGULAR "read", readcmd},
1637 {BUILTIN_SPEC_ASSG "readonly", exportcmd},
1638 {BUILTIN_SPECIAL "return", returncmd},
1639 {BUILTIN_SPECIAL "set", setcmd},
1640 {BUILTIN_NOSPEC "setvar", setvarcmd},
1641 {BUILTIN_SPECIAL "shift", shiftcmd},
1642 {BUILTIN_SPECIAL "times", timescmd},
1643 {BUILTIN_SPECIAL "trap", trapcmd},
1644 {BUILTIN_REGULAR "true", true_main},
1645 {BUILTIN_NOSPEC "type", typecmd},
1646 {BUILTIN_NOSPEC "ulimit", ulimitcmd},
1647 {BUILTIN_REGULAR "umask", umaskcmd},
1648 #ifdef CONFIG_ASH_ALIAS
1649 {BUILTIN_REGULAR "unalias", unaliascmd},
1651 {BUILTIN_SPECIAL "unset", unsetcmd},
1652 {BUILTIN_REGULAR "wait", waitcmd},
1655 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1657 #define DOTCMD &builtincmds[0]
1658 static struct builtincmd *BLTINCMD;
1659 static struct builtincmd *EXECCMD;
1660 static struct builtincmd *EVALCMD;
1663 #define CONFIG_ASH_JOB_CONTROLTOPPED 1 /* all procs are stopped */
1664 #define JOBDONE 2 /* all procs are completed */
1667 * A job structure contains information about a job. A job is either a
1668 * single process or a set of processes contained in a pipeline. In the
1669 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1674 pid_t pid; /* process id */
1675 int status; /* status flags (defined above) */
1676 char *cmd; /* text of command being run */
1680 static int job_warning; /* user was warned about stopped jobs */
1682 #ifdef CONFIG_ASH_JOB_CONTROL
1683 static void setjobctl(int enable);
1685 #define setjobctl(on) /* do nothing */
1690 struct procstat ps0; /* status of process */
1691 struct procstat *ps; /* status or processes when more than one */
1692 short nprocs; /* number of processes */
1693 short pgrp; /* process group of this job */
1694 char state; /* true if job is finished */
1695 char used; /* true if this entry is in used */
1696 char changed; /* true if status has changed */
1697 #ifdef CONFIG_ASH_JOB_CONTROL
1698 char jobctl; /* job running under job control */
1702 static struct job *jobtab; /* array of jobs */
1703 static int njobs; /* size of array */
1704 static int backgndpid = -1; /* pid of last background process */
1706 #ifdef CONFIG_ASH_JOB_CONTROL
1707 static int initialpgrp; /* pgrp of shell on invocation */
1708 static int curjob; /* current job */
1711 static int intreceived;
1713 static struct job *makejob(const union node *, int);
1714 static int forkshell(struct job *, const union node *, int);
1715 static int waitforjob(struct job *);
1717 static int docd(char *, int);
1718 static void getpwd(void);
1720 static char *padvance(const char **, const char *);
1722 static char nullstr[1]; /* zero length string */
1723 static char *curdir = nullstr; /* current working directory */
1725 static int cdcmd(int argc, char **argv)
1734 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1735 error("HOME not set");
1738 if (dest[0] == '-' && dest[1] == '\0') {
1739 dest = bltinlookup("OLDPWD");
1740 if (!dest || !*dest) {
1749 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1751 while ((p = padvance(&path, dest)) != NULL) {
1752 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1757 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1759 print = strcmp(p, dest);
1761 if (docd(p, print) >= 0)
1766 error("can't cd to %s", dest);
1772 * Actually do the chdir. In an interactive shell, print the
1773 * directory name if "print" is nonzero.
1776 static int docd(char *dest, int print)
1778 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1780 if (chdir(dest) < 0) {
1786 * Update curdir (the name of the current directory) in response to a
1787 * cd command. We also call hashcd to let the routines in exec.c know
1788 * that the current directory has changed.
1790 /* If dest is NULL, we don't know the current directory */
1791 if (dest == NULL || curdir == nullstr)
1803 static int pwdcmd(int argc, char **argv)
1809 /* Ask system the current directory */
1810 static void getpwd(void)
1812 curdir = xgetcwd(0);
1817 static void setpwd(const char *val, int setold)
1822 setvar("OLDPWD", curdir, VEXPORT);
1825 if (curdir != nullstr) {
1826 if (val != NULL && *val != '/')
1827 val = cated = concat_path_file(curdir, val);
1833 curdir = simplify_path(val);
1836 setvar("PWD", curdir, VEXPORT);
1840 * Errors and exceptions.
1844 * Code to handle exceptions in C.
1848 * We enclose jmp_buf in a structure so that we can declare pointers to
1849 * jump locations. The global variable handler contains the location to
1850 * jump to when an exception occurs, and the global variable exception
1851 * contains a code identifying the exeception. To implement nested
1852 * exception handlers, the user should save the value of handler on entry
1853 * to an inner scope, set handler to point to a jmploc structure for the
1854 * inner scope, and restore handler on exit from the scope.
1862 #define EXINT 0 /* SIGINT received */
1863 #define EXERROR 1 /* a generic error */
1864 #define EXSHELLPROC 2 /* execute a shell procedure */
1865 #define EXEXEC 3 /* command execution failed */
1867 static struct jmploc *handler;
1868 static int exception;
1870 static void exverror(int, const char *, va_list)
1871 __attribute__ ((__noreturn__));
1874 * Called to raise an exception. Since C doesn't include exceptions, we
1875 * just do a longjmp to the exception handler. The type of exception is
1876 * stored in the global variable "exception".
1879 static void exraise(int) __attribute__ ((__noreturn__));
1881 static void exraise(int e)
1884 if (handler == NULL)
1889 longjmp(handler->loc, 1);
1894 * Called from trap.c when a SIGINT is received. (If the user specifies
1895 * that SIGINT is to be trapped or ignored using the trap builtin, then
1896 * this routine is not called.) Suppressint is nonzero when interrupts
1897 * are held using the INTOFF macro. The call to _exit is necessary because
1898 * there is a short period after a fork before the signal handlers are
1899 * set to the appropriate value for the child. (The test for iflag is
1900 * just defensive programming.)
1903 static void onint(void)
1912 sigemptyset(&mysigset);
1913 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1914 if (rootshell && iflag)
1917 signal(SIGINT, SIG_DFL);
1924 static char *commandname; /* currently executing command */
1927 * Exverror is called to raise the error exception. If the first argument
1928 * is not NULL then error prints an error message using printf style
1929 * formatting. It then raises the error exception.
1931 static void exverror(int cond, const char *msg, va_list ap)
1938 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1940 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1944 out2fmt("%s: ", commandname);
1945 vfprintf(stderr, msg, ap);
1953 static void error(const char *msg, ...)
1958 exverror(EXERROR, msg, ap);
1964 static void exerror(int cond, const char *msg, ...)
1969 exverror(cond, msg, ap);
1977 * Table of error messages.
1981 short errcode; /* error number */
1982 short action; /* operation which encountered the error */
1986 * Types of operations (passed to the errmsg routine).
1989 #define E_OPEN 01 /* opening a file */
1990 #define E_CREAT 02 /* creating a file */
1991 #define E_EXEC 04 /* executing a program */
1993 #define ALL (E_OPEN|E_CREAT|E_EXEC)
1995 static const struct errname errormsg[] = {
2049 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2052 * Return a string describing an error. The returned string may be a
2053 * pointer to a static buffer that will be overwritten on the next call.
2054 * Action describes the operation that got the error.
2057 static const char *errmsg(int e, int action)
2059 struct errname const *ep;
2060 static char buf[12];
2062 for (ep = errormsg; ep < errormsg + ERRNAME_SIZE; ep++) {
2063 if (ep->errcode == e && (ep->action & action) != 0)
2067 snprintf(buf, sizeof buf, "error %d", e);
2072 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
2073 static void __inton()
2075 if (--suppressint == 0 && intpending) {
2079 static void forceinton(void)
2087 /* flags in argument to evaltree */
2088 #define EV_EXIT 01 /* exit after evaluating tree */
2089 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2090 #define EV_BACKCMD 04 /* command executing within back quotes */
2092 static int evalskip; /* set if we are skipping commands */
2093 static int skipcount; /* number of levels to skip */
2094 static int loopnest; /* current loop nesting level */
2095 static int funcnest; /* depth of function calls */
2098 static struct strlist *cmdenviron; /* environment for builtin command */
2099 static int exitstatus; /* exit status of last command */
2100 static int oexitstatus; /* saved exit status */
2102 static void evalsubshell(const union node *, int);
2103 static void expredir(union node *);
2104 static void eprintlist(struct strlist *);
2106 static union node *parsecmd(int);
2109 * Called to reset things after an exception.
2113 * The eval commmand.
2115 static void evalstring(char *, int);
2117 static int evalcmd(int argc, char **argv)
2126 STARTSTACKSTR(concat);
2130 STPUTC(*p++, concat);
2131 if ((p = *ap++) == NULL)
2133 STPUTC(' ', concat);
2135 STPUTC('\0', concat);
2136 p = grabstackstr(concat);
2138 evalstring(p, EV_TESTED);
2144 * Execute a command or commands contained in a string.
2147 static void evaltree(union node *, int);
2148 static void setinputstring(char *);
2149 static void popfile(void);
2150 static void setstackmark(struct stackmark *mark);
2151 static void popstackmark(struct stackmark *mark);
2154 static void evalstring(char *s, int flag)
2157 struct stackmark smark;
2159 setstackmark(&smark);
2161 while ((n = parsecmd(0)) != NEOF) {
2163 popstackmark(&smark);
2166 popstackmark(&smark);
2169 static struct builtincmd *find_builtin(const char *);
2170 static void expandarg(union node *, struct arglist *, int);
2171 static void calcsize(const union node *);
2172 static union node *copynode(const union node *);
2175 * Make a copy of a parse tree.
2178 static int funcblocksize; /* size of structures in function */
2179 static int funcstringsize; /* size of strings in node */
2180 static pointer funcblock; /* block to allocate function from */
2181 static char *funcstring; /* block to allocate strings from */
2184 static inline union node *copyfunc(union node *n)
2191 funcblock = xmalloc(funcblocksize + funcstringsize);
2192 funcstring = (char *) funcblock + funcblocksize;
2197 * Add a new command entry, replacing any existing command entry for
2201 static inline void addcmdentry(char *name, struct cmdentry *entry)
2203 struct tblentry *cmdp;
2206 cmdp = cmdlookup(name, 1);
2207 if (cmdp->cmdtype == CMDFUNCTION) {
2208 free(cmdp->param.func);
2210 cmdp->cmdtype = entry->cmdtype;
2211 cmdp->param = entry->u;
2215 static inline void evalloop(const union node *n, int flags)
2222 evaltree(n->nbinary.ch1, EV_TESTED);
2224 skipping:if (evalskip == SKIPCONT && --skipcount <= 0) {
2228 if (evalskip == SKIPBREAK && --skipcount <= 0)
2232 if (n->type == NWHILE) {
2233 if (exitstatus != 0)
2236 if (exitstatus == 0)
2239 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2240 status = exitstatus;
2245 exitstatus = status;
2248 static void evalfor(const union node *n, int flags)
2250 struct arglist arglist;
2253 struct stackmark smark;
2255 setstackmark(&smark);
2256 arglist.lastp = &arglist.list;
2257 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
2258 oexitstatus = exitstatus;
2259 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2263 *arglist.lastp = NULL;
2267 for (sp = arglist.list; sp; sp = sp->next) {
2268 setvar(n->nfor.var, sp->text, 0);
2269 evaltree(n->nfor.body, flags & EV_TESTED);
2271 if (evalskip == SKIPCONT && --skipcount <= 0) {
2275 if (evalskip == SKIPBREAK && --skipcount <= 0)
2282 popstackmark(&smark);
2285 static inline void evalcase(const union node *n, int flags)
2289 struct arglist arglist;
2290 struct stackmark smark;
2292 setstackmark(&smark);
2293 arglist.lastp = &arglist.list;
2294 oexitstatus = exitstatus;
2295 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2296 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
2297 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
2298 if (casematch(patp, arglist.list->text)) {
2299 if (evalskip == 0) {
2300 evaltree(cp->nclist.body, flags);
2307 popstackmark(&smark);
2311 * Evaluate a pipeline. All the processes in the pipeline are children
2312 * of the process creating the pipeline. (This differs from some versions
2313 * of the shell, which make the last process in a pipeline the parent
2317 static inline void evalpipe(union node *n)
2320 struct nodelist *lp;
2325 TRACE(("evalpipe(0x%lx) called\n", (long) n));
2327 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
2330 jp = makejob(n, pipelen);
2332 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
2334 * Search for a command. This is called before we fork so that the
2335 * location of the command will be available in the parent as well as
2336 * the child. The check for "goodname" is an overly conservative
2337 * check that the name will not be subject to expansion.
2340 struct cmdentry entry;
2341 union node *lpn = lp->n;
2343 if (lpn->type == NCMD && lpn->ncmd.args
2344 && goodname(lpn->ncmd.args->narg.text))
2345 find_command(lpn->ncmd.args->narg.text, &entry, 0, pathval());
2349 if (pipe(pip) < 0) {
2351 error("Pipe call failed");
2354 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2358 dup_as_newfd(prevfd, 0);
2370 dup_as_newfd(pip[1], 1);
2374 evaltree(lp->n, EV_EXIT);
2382 if (n->npipe.backgnd == 0) {
2384 exitstatus = waitforjob(jp);
2385 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2390 static int isassignment(const char *word)
2392 if (!is_name(*word)) {
2397 } while (is_in_name(*word));
2398 return *word == '=';
2402 static void evalcommand(union node *cmd, int flags)
2404 struct stackmark smark;
2406 struct arglist arglist;
2407 struct arglist varlist;
2413 struct cmdentry cmdentry;
2415 char *volatile savecmdname;
2416 volatile struct shparam saveparam;
2417 struct localvar *volatile savelocalvars;
2421 const struct builtincmd *firstbltin;
2422 struct jmploc *volatile savehandler;
2423 struct jmploc jmploc;
2426 /* Avoid longjmp clobbering */
2433 /* First expand the arguments. */
2434 TRACE(("evalcommand(0x%lx, %d) called\n", (long) cmd, flags));
2435 setstackmark(&smark);
2436 arglist.lastp = &arglist.list;
2437 varlist.lastp = &varlist.list;
2439 oexitstatus = exitstatus;
2442 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2443 expandarg(argp, &varlist, EXP_VARTILDE);
2445 for (argp = cmd->ncmd.args; argp && !arglist.list; argp = argp->narg.next) {
2446 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2449 struct builtincmd *bcmd;
2452 bcmd = find_builtin(arglist.list->text);
2453 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2454 for (; argp; argp = argp->narg.next) {
2455 if (pseudovarflag && isassignment(argp->narg.text)) {
2456 expandarg(argp, &arglist, EXP_VARTILDE);
2459 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2462 *arglist.lastp = NULL;
2463 *varlist.lastp = NULL;
2464 expredir(cmd->ncmd.redirect);
2466 for (sp = arglist.list; sp; sp = sp->next)
2468 argv = stalloc(sizeof(char *) * (argc + 1));
2470 for (sp = arglist.list; sp; sp = sp->next) {
2471 TRACE(("evalcommand arg: %s\n", sp->text));
2476 if (iflag && funcnest == 0 && argc > 0)
2480 /* Print the command if xflag is set. */
2483 eprintlist(varlist.list);
2484 eprintlist(arglist.list);
2488 /* Now locate the command. */
2490 cmdentry.cmdtype = CMDBUILTIN;
2491 firstbltin = cmdentry.u.cmd = BLTINCMD;
2493 const char *oldpath;
2494 int findflag = DO_ERR;
2498 * Modify the command lookup path, if a PATH= assignment
2501 for (sp = varlist.list; sp; sp = sp->next)
2502 if (varequal(sp->text, defpathvar)) {
2503 path = sp->text + 5;
2504 findflag |= DO_BRUTE;
2507 oldfindflag = findflag;
2510 find_command(argv[0], &cmdentry, findflag, path);
2511 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2515 /* implement bltin and command here */
2516 if (cmdentry.cmdtype != CMDBUILTIN) {
2520 firstbltin = cmdentry.u.cmd;
2522 if (cmdentry.u.cmd == BLTINCMD) {
2524 struct builtincmd *bcmd;
2529 if (!(bcmd = find_builtin(*argv))) {
2530 out2fmt("%s: not found\n", *argv);
2534 cmdentry.u.cmd = bcmd;
2535 if (bcmd != BLTINCMD)
2539 if (cmdentry.u.cmd == find_builtin("command")) {
2544 if (*argv[0] == '-') {
2545 if (!equal(argv[0], "-p")) {
2555 findflag |= DO_BRUTE;
2558 findflag = oldfindflag;
2560 findflag |= DO_NOFUN;
2568 /* Fork off a child process if necessary. */
2569 if (cmd->ncmd.backgnd
2570 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2572 jp = makejob(cmd, 1);
2573 mode = cmd->ncmd.backgnd;
2574 if (forkshell(jp, cmd, mode) != 0)
2575 goto parent; /* at end of routine */
2579 /* This is the child process if a fork occurred. */
2580 /* Execute the command. */
2581 if (cmdentry.cmdtype == CMDFUNCTION) {
2583 trputs("Shell function: ");
2586 exitstatus = oexitstatus;
2587 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2588 saveparam = shellparam;
2589 shellparam.malloc = 0;
2590 shellparam.nparam = argc - 1;
2591 shellparam.p = argv + 1;
2593 savelocalvars = localvars;
2596 if (setjmp(jmploc.loc)) {
2597 if (exception == EXSHELLPROC) {
2598 freeparam((volatile struct shparam *)
2601 saveparam.optind = shellparam.optind;
2602 saveparam.optoff = shellparam.optoff;
2603 freeparam(&shellparam);
2604 shellparam = saveparam;
2607 localvars = savelocalvars;
2608 handler = savehandler;
2609 longjmp(handler->loc, 1);
2611 savehandler = handler;
2613 for (sp = varlist.list; sp; sp = sp->next)
2616 evaltree(cmdentry.u.func, flags & EV_TESTED);
2620 localvars = savelocalvars;
2621 saveparam.optind = shellparam.optind;
2622 saveparam.optoff = shellparam.optoff;
2623 freeparam(&shellparam);
2624 shellparam = saveparam;
2625 handler = savehandler;
2628 if (evalskip == SKIPFUNC) {
2632 if (flags & EV_EXIT)
2633 exitshell(exitstatus);
2634 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2636 trputs("builtin command: ");
2639 mode = (cmdentry.u.cmd == EXECCMD) ? 0 : REDIR_PUSH;
2640 redirect(cmd->ncmd.redirect, mode);
2641 savecmdname = commandname;
2642 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2643 listsetvar(varlist.list);
2645 cmdenviron = varlist.list;
2648 if (setjmp(jmploc.loc)) {
2650 exitstatus = (e == EXINT) ? SIGINT + 128 : 2;
2653 savehandler = handler;
2655 commandname = argv[0];
2657 optptr = NULL; /* initialize nextopt */
2658 exitstatus = (*cmdentry.u.cmd->builtinfunc) (argc, argv);
2662 if (e != EXSHELLPROC) {
2663 commandname = savecmdname;
2664 if (flags & EV_EXIT)
2665 exitshell(exitstatus);
2667 handler = savehandler;
2669 if ((e != EXERROR && e != EXEXEC)
2670 || cmdentry.u.cmd == BLTINCMD
2671 || cmdentry.u.cmd == DOTCMD
2672 || cmdentry.u.cmd == EVALCMD || cmdentry.u.cmd == EXECCMD)
2676 if (cmdentry.u.cmd != EXECCMD)
2680 trputs("normal command: ");
2683 redirect(cmd->ncmd.redirect, 0);
2685 for (sp = varlist.list; sp; sp = sp->next)
2686 setvareq(sp->text, VEXPORT | VSTACK);
2687 envp = environment();
2688 shellexec(argv, envp, path, cmdentry.u.index);
2692 parent: /* parent process gets here (if we forked) */
2693 if (mode == 0) { /* argument to fork */
2695 exitstatus = waitforjob(jp);
2701 setvar("_", lastarg, 0);
2702 popstackmark(&smark);
2706 * Evaluate a parse tree. The value is left in the global variable
2709 static void evaltree(union node *n, int flags)
2714 TRACE(("evaltree(NULL) called\n"));
2717 TRACE(("evaltree(0x%lx: %d) called\n", (long) n, n->type));
2720 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2723 evaltree(n->nbinary.ch2, flags);
2726 evaltree(n->nbinary.ch1, EV_TESTED);
2727 if (evalskip || exitstatus != 0)
2729 evaltree(n->nbinary.ch2, flags);
2732 evaltree(n->nbinary.ch1, EV_TESTED);
2733 if (evalskip || exitstatus == 0)
2735 evaltree(n->nbinary.ch2, flags);
2738 expredir(n->nredir.redirect);
2739 redirect(n->nredir.redirect, REDIR_PUSH);
2740 evaltree(n->nredir.n, flags);
2744 evalsubshell(n, flags);
2747 evalsubshell(n, flags);
2750 evaltree(n->nif.test, EV_TESTED);
2753 if (exitstatus == 0)
2754 evaltree(n->nif.ifpart, flags);
2755 else if (n->nif.elsepart)
2756 evaltree(n->nif.elsepart, flags);
2772 struct builtincmd *bcmd;
2773 struct cmdentry entry;
2775 if ((bcmd = find_builtin(n->narg.text)) && IS_BUILTIN_SPECIAL(bcmd)
2777 out2fmt("%s is a special built-in\n", n->narg.text);
2781 entry.cmdtype = CMDFUNCTION;
2782 entry.u.func = copyfunc(n->narg.next);
2783 addcmdentry(n->narg.text, &entry);
2788 evaltree(n->nnot.com, EV_TESTED);
2789 exitstatus = !exitstatus;
2797 evalcommand(n, flags);
2802 printf("Node type = %d\n", n->type);
2809 if (flags & EV_EXIT ||
2810 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2812 exitshell(exitstatus);
2816 * Kick off a subshell to evaluate a tree.
2819 static void evalsubshell(const union node *n, int flags)
2822 int backgnd = (n->type == NBACKGND);
2824 expredir(n->nredir.redirect);
2826 if (forkshell(jp, n, backgnd) == 0) {
2828 flags &= ~EV_TESTED;
2829 redirect(n->nredir.redirect, 0);
2830 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2834 exitstatus = waitforjob(jp);
2840 * Compute the names of the files in a redirection list.
2843 static void fixredir(union node *n, const char *text, int err);
2845 static void expredir(union node *n)
2849 for (redir = n; redir; redir = redir->nfile.next) {
2852 fn.lastp = &fn.list;
2853 oexitstatus = exitstatus;
2854 switch (redir->type) {
2860 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2861 redir->nfile.expfname = fn.list->text;
2865 if (redir->ndup.vname) {
2866 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2867 fixredir(redir, fn.list->text, 1);
2876 * Execute a command inside back quotes. If it's a builtin command, we
2877 * want to save its output in a block obtained from malloc. Otherwise
2878 * we fork off a subprocess and get the output of the command via a pipe.
2879 * Should be called with interrupts off.
2882 static void evalbackcmd(union node *n, struct backcmd *result)
2886 struct stackmark smark; /* unnecessary */
2888 setstackmark(&smark);
2899 error("Pipe call failed");
2901 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2906 dup_as_newfd(pip[1], 1);
2910 evaltree(n, EV_EXIT);
2913 result->fd = pip[0];
2916 popstackmark(&smark);
2917 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2918 result->fd, result->buf, result->nleft, result->jp));
2923 * Execute a simple command.
2928 * Builtin commands. Builtin commands whose functions are closely
2929 * tied to evaluation are implemented here.
2933 * No command given, or a bltin command with no arguments. Set the
2934 * specified variables.
2937 int bltincmd(int argc, char **argv)
2940 * Preserve exitstatus of a previous possible redirection
2948 * Handle break and continue commands. Break, continue, and return are
2949 * all handled by setting the evalskip flag. The evaluation routines
2950 * above all check this flag, and if it is set they start skipping
2951 * commands rather than executing them. The variable skipcount is
2952 * the number of loops to break/continue, or the number of function
2953 * levels to return. (The latter is always 1.) It should probably
2954 * be an error to break out of more loops than exist, but it isn't
2955 * in the standard shell so we don't make it one here.
2958 static int breakcmd(int argc, char **argv)
2960 int n = argc > 1 ? number(argv[1]) : 1;
2963 error("Illegal number: %s", argv[1]);
2967 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
2975 * The return command.
2978 static int returncmd(int argc, char **argv)
2980 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
2983 evalskip = SKIPFUNC;
2987 /* Do what ksh does; skip the rest of the file */
2988 evalskip = SKIPFILE;
2995 #ifndef CONFIG_FALSE
2996 static int false_main(int argc, char **argv)
3003 static int true_main(int argc, char **argv)
3010 * Controls whether the shell is interactive or not.
3013 static void setsignal(int signo);
3015 #ifdef CONFIG_ASH_MAIL
3016 static void chkmail(int silent);
3019 static void setinteractive(int on)
3021 static int is_interactive;
3022 static int do_banner = 0;
3024 if (on == is_interactive)
3029 #ifdef CONFIG_ASH_MAIL
3032 is_interactive = on;
3033 if (do_banner == 0 && is_interactive) {
3034 /* Looks like they want an interactive shell */
3035 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3036 printf("\n\n" BB_BANNER " Built-in shell (ash)\n");
3037 printf("Enter 'help' for a list of built-in commands.\n\n");
3043 static void optschanged(void)
3045 setinteractive(iflag);
3050 static int execcmd(int argc, char **argv)
3055 iflag = 0; /* exit on error */
3058 for (sp = cmdenviron; sp; sp = sp->next)
3059 setvareq(sp->text, VEXPORT | VSTACK);
3060 shellexec(argv + 1, environment(), pathval(), 0);
3065 static void eprintlist(struct strlist *sp)
3067 for (; sp; sp = sp->next) {
3068 out2fmt(" %s", sp->text);
3073 * Exec a program. Never returns. If you change this routine, you may
3074 * have to change the find_command routine as well.
3077 static const char *pathopt; /* set by padvance */
3079 static void shellexec(char **argv, char **envp, const char *path, int idx)
3084 if (strchr(argv[0], '/') != NULL) {
3085 tryexec(argv[0], argv, envp);
3089 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3090 if (--idx < 0 && pathopt == NULL) {
3091 tryexec(cmdname, argv, envp);
3092 if (errno != ENOENT && errno != ENOTDIR)
3099 /* Map to POSIX errors */
3111 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3116 * Clear traps on a fork.
3118 static void clear_traps(void)
3122 for (tp = trap; tp < &trap[NSIG]; tp++) {
3123 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3128 setsignal(tp - trap);
3135 static void initshellproc(void)
3138 #ifdef CONFIG_ASH_ALIAS
3157 #ifdef CONFIG_ASH_JOB_CONTROL
3162 /* from options.c: */
3166 for (i = 0; i < NOPTS; i++)
3182 for (sm = sigmode; sm < sigmode + NSIG - 1; sm++) {
3194 static int preadbuffer(void);
3195 static void pushfile(void);
3198 * Read a character from the script, returning PEOF on end of file.
3199 * Nul characters in the input are silently discarded.
3202 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
3203 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3204 static int pgetc(void)
3206 return pgetc_macro();
3209 static int pgetc_macro(void)
3211 return --parsenleft >= 0 ? *parsenextc++ : preadbuffer();
3214 static inline int pgetc(void)
3216 return pgetc_macro();
3222 * Undo the last call to pgetc. Only one character may be pushed back.
3223 * PEOF may be pushed back.
3226 static void pungetc(void)
3233 static void popfile(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.
3257 static void popallfiles(void)
3259 while (parsefile != &basepf)
3264 * Close the file(s) that the shell is reading commands from. Called
3265 * after a fork is done.
3268 static void closescript(void)
3271 if (parsefile->fd > 0) {
3272 close(parsefile->fd);
3279 * Like setinputfile, but takes an open file descriptor. Call this with
3283 static void setinputfd(int fd, int push)
3285 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3291 while (parsefile->strpush)
3295 if (parsefile->buf == NULL)
3296 parsefile->buf = xmalloc(BUFSIZ);
3297 parselleft = parsenleft = 0;
3303 * Set the input to take input from a file. If push is set, push the
3304 * old input onto the stack first.
3307 static void setinputfile(const char *fname, int push)
3313 if ((fd = open(fname, O_RDONLY)) < 0)
3314 error("Can't open %s", fname);
3316 myfileno2 = dup_as_newfd(fd, 10);
3319 error("Out of file descriptors");
3322 setinputfd(fd, push);
3327 static void tryexec(char *cmd, char **argv, char **envp)
3331 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3333 char **argv_l = argv;
3336 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3337 name = get_last_path_component(name);
3340 for (argc_l = 0; *argv_l != NULL; argv_l++, argc_l++)
3343 for (argc_l = 0; *argv_l != NULL; argv_l++, argc_l++)
3345 run_applet_by_name(name, argc_l, argv);
3347 execve(cmd, argv, envp);
3352 setinputfile(cmd, 0);
3353 commandname = arg0 = xstrdup(argv[0]);
3355 exraise(EXSHELLPROC);
3360 static char *commandtext(const union node *);
3363 * Do a path search. The variable path (passed by reference) should be
3364 * set to the start of the path before the first call; padvance will update
3365 * this value as it proceeds. Successive calls to padvance will return
3366 * the possible path expansions in sequence. If an option (indicated by
3367 * a percent sign) appears in the path entry then the global variable
3368 * pathopt will be set to point to it; otherwise pathopt will be set to
3372 static const char *pathopt;
3374 static void growstackblock(void);
3377 static char *padvance(const char **path, const char *name)
3387 for (p = start; *p && *p != ':' && *p != '%'; p++);
3388 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3389 while (stackblocksize() < len)
3393 memcpy(q, start, p - start);
3401 while (*p && *p != ':')
3408 return stalloc(len);
3412 * Wrapper around strcmp for qsort/bsearch/...
3414 static int pstrcmp(const void *a, const void *b)
3416 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3420 * Find a keyword is in a sorted array.
3423 static const char *const *findkwd(const char *s)
3425 return bsearch(s, tokname_array + KWDOFFSET,
3426 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
3427 sizeof(const char *), pstrcmp);
3431 /*** Command hashing code ***/
3434 static int hashcmd(int argc, char **argv)
3436 struct tblentry **pp;
3437 struct tblentry *cmdp;
3440 struct cmdentry entry;
3443 #ifdef CONFIG_ASH_ALIAS
3444 const struct alias *ap;
3448 while ((c = nextopt("rvV")) != '\0') {
3452 } else if (c == 'v' || c == 'V') {
3456 if (*argptr == NULL) {
3457 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3458 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3459 if (cmdp->cmdtype != CMDBUILTIN) {
3460 printentry(cmdp, verbose);
3467 while ((name = *argptr++) != NULL) {
3468 if ((cmdp = cmdlookup(name, 0)) != NULL
3469 && (cmdp->cmdtype == CMDNORMAL
3470 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3472 #ifdef CONFIG_ASH_ALIAS
3473 /* Then look at the aliases */
3474 if ((ap = *__lookupalias(name)) != NULL) {
3476 printf("%s is an alias for %s\n", name, ap->val);
3482 /* First look at the keywords */
3483 if (findkwd(name) != 0) {
3485 printf("%s is a shell keyword\n", name);
3491 find_command(name, &entry, DO_ERR, pathval());
3492 if (entry.cmdtype == CMDUNKNOWN)
3495 cmdp = cmdlookup(name, 0);
3497 printentry(cmdp, verbose == 'v');
3504 static void printentry(struct tblentry *cmdp, int verbose)
3510 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3511 if (cmdp->cmdtype == CMDNORMAL) {
3512 idx = cmdp->param.index;
3515 name = padvance(&path, cmdp->cmdname);
3517 } while (--idx >= 0);
3520 } else if (cmdp->cmdtype == CMDBUILTIN) {
3522 out1str("a shell builtin");
3523 } else if (cmdp->cmdtype == CMDFUNCTION) {
3526 out1str("a function\n");
3527 name = commandtext(cmdp->param.func);
3528 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3534 error("internal error: cmdtype %d", cmdp->cmdtype);
3537 puts(cmdp->rehash ? "*" : nullstr);
3542 /*** List the available builtins ***/
3545 static int helpcmd(int argc, char **argv)
3549 printf("\nBuilt-in commands:\n-------------------\n");
3550 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
3551 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3552 builtincmds[i].name + 1);
3558 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3560 extern const struct BB_applet applets[];
3561 extern const size_t NUM_APPLETS;
3563 for (i = 0; i < NUM_APPLETS; i++) {
3565 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
3574 return EXIT_SUCCESS;
3578 * Resolve a command name. If you change this routine, you may have to
3579 * change the shellexec routine as well.
3582 static int prefix(const char *, const char *);
3585 find_command(const char *name, struct cmdentry *entry, int act,
3588 struct tblentry *cmdp;
3598 struct builtincmd *bcmd;
3600 /* If name contains a slash, don't use the hash table */
3601 if (strchr(name, '/') != NULL) {
3603 while (stat(name, &statb) < 0) {
3604 if (errno != ENOENT && errno != ENOTDIR)
3606 entry->cmdtype = CMDUNKNOWN;
3607 entry->u.index = -1;
3610 entry->cmdtype = CMDNORMAL;
3611 entry->u.index = -1;
3614 entry->cmdtype = CMDNORMAL;
3620 if (act & DO_BRUTE) {
3621 firstchange = path_change(path, &bltin);
3627 /* If name is in the table, and not invalidated by cd, we're done */
3628 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3629 if (cmdp->cmdtype == CMDFUNCTION) {
3630 if (act & DO_NOFUN) {
3635 } else if (act & DO_BRUTE) {
3636 if ((cmdp->cmdtype == CMDNORMAL &&
3637 cmdp->param.index >= firstchange) ||
3638 (cmdp->cmdtype == CMDBUILTIN &&
3639 ((builtinloc < 0 && bltin >= 0) ?
3640 bltin : builtinloc) >= firstchange)) {
3641 /* need to recompute the entry */
3650 bcmd = find_builtin(name);
3651 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3654 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3657 } else if (act & DO_BRUTE) {
3658 if (firstchange == 0) {
3663 /* If %builtin not in path, check for builtin next */
3664 if (regular || (bltin < 0 && bcmd)) {
3667 entry->cmdtype = CMDBUILTIN;
3668 entry->u.cmd = bcmd;
3672 cmdp = cmdlookup(name, 1);
3673 cmdp->cmdtype = CMDBUILTIN;
3674 cmdp->param.cmd = bcmd;
3679 /* We have to search path. */
3680 prev = -1; /* where to start */
3681 if (cmdp && cmdp->rehash) { /* doing a rehash */
3682 if (cmdp->cmdtype == CMDBUILTIN)
3685 prev = cmdp->param.index;
3691 while ((fullname = padvance(&path, name)) != NULL) {
3692 stunalloc(fullname);
3694 if (idx >= firstchange) {
3698 if (prefix("builtin", pathopt)) {
3699 if ((bcmd = find_builtin(name))) {
3703 } else if (!(act & DO_NOFUN) && prefix("func", pathopt)) {
3706 continue; /* ignore unimplemented options */
3709 /* if rehash, don't redo absolute path names */
3710 if (fullname[0] == '/' && idx <= prev && idx < firstchange) {
3713 TRACE(("searchexec \"%s\": no change\n", name));
3716 while (stat(fullname, &statb) < 0) {
3717 if (errno != ENOENT && errno != ENOTDIR)
3721 e = EACCES; /* if we fail, this will be the error */
3722 if (!S_ISREG(statb.st_mode))
3724 if (pathopt) { /* this is a %func directory */
3725 stalloc(strlen(fullname) + 1);
3726 readcmdfile(fullname);
3727 if ((cmdp = cmdlookup(name, 0)) == NULL
3728 || cmdp->cmdtype != CMDFUNCTION)
3729 error("%s not defined in %s", name, fullname);
3730 stunalloc(fullname);
3733 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3734 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3735 be a function and we're being called with DO_NOFUN */
3737 entry->cmdtype = CMDNORMAL;
3738 entry->u.index = idx;
3742 cmdp = cmdlookup(name, 1);
3743 cmdp->cmdtype = CMDNORMAL;
3744 cmdp->param.index = idx;
3749 /* We failed. If there was an entry for this command, delete it */
3750 if (cmdp && updatetbl)
3753 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3754 entry->cmdtype = CMDUNKNOWN;
3759 entry->cmdtype = cmdp->cmdtype;
3760 entry->u = cmdp->param;
3766 * Search the table of builtin commands.
3769 static int bstrcmp(const void *name, const void *b)
3771 return strcmp((const char *) name, (*(const char *const *) b) + 1);
3774 static struct builtincmd *find_builtin(const char *name)
3776 struct builtincmd *bp;
3778 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3785 * Called when a cd is done. Marks all commands so the next time they
3786 * are executed they will be rehashed.
3789 static inline void hashcd(void)
3791 struct tblentry **pp;
3792 struct tblentry *cmdp;
3794 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3795 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3796 if (cmdp->cmdtype == CMDNORMAL
3797 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3806 * Called before PATH is changed. The argument is the new value of PATH;
3807 * pathval() still returns the old value at this point. Called with
3811 static void changepath(const char *newval)
3816 firstchange = path_change(newval, &bltin);
3817 if (builtinloc < 0 && bltin >= 0)
3818 builtinloc = bltin; /* zap builtins */
3819 clearcmdentry(firstchange);
3821 /* Ensure that getenv("PATH") stays current */
3822 setenv("PATH", newval, 1);
3827 * Clear out command entries. The argument specifies the first entry in
3828 * PATH which has changed.
3831 static void clearcmdentry(int firstchange)
3833 struct tblentry **tblp;
3834 struct tblentry **pp;
3835 struct tblentry *cmdp;
3838 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
3840 while ((cmdp = *pp) != NULL) {
3841 if ((cmdp->cmdtype == CMDNORMAL &&
3842 cmdp->param.index >= firstchange)
3843 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= firstchange)) {
3856 * Delete all functions.
3859 static void deletefuncs(void)
3861 struct tblentry **tblp;
3862 struct tblentry **pp;
3863 struct tblentry *cmdp;
3866 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
3868 while ((cmdp = *pp) != NULL) {
3869 if (cmdp->cmdtype == CMDFUNCTION) {
3871 free(cmdp->param.func);
3884 * Locate a command in the command hash table. If "add" is nonzero,
3885 * add the command to the table if it is not already present. The
3886 * variable "lastcmdentry" is set to point to the address of the link
3887 * pointing to the entry, so that delete_cmd_entry can delete the
3891 static struct tblentry **lastcmdentry;
3893 static struct tblentry *cmdlookup(const char *name, int add)
3897 struct tblentry *cmdp;
3898 struct tblentry **pp;
3905 pp = &cmdtable[hashval % CMDTABLESIZE];
3906 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3907 if (equal(cmdp->cmdname, name))
3911 if (add && cmdp == NULL) {
3913 cmdp = *pp = xmalloc(sizeof(struct tblentry) - ARB
3914 + strlen(name) + 1);
3916 cmdp->cmdtype = CMDUNKNOWN;
3918 strcpy(cmdp->cmdname, name);
3926 * Delete the command entry returned on the last lookup.
3929 static void delete_cmd_entry()
3931 struct tblentry *cmdp;
3934 cmdp = *lastcmdentry;
3935 *lastcmdentry = cmdp->next;
3944 static const unsigned char nodesize[26] = {
3945 ALIGN(sizeof(struct nbinary)),
3946 ALIGN(sizeof(struct ncmd)),
3947 ALIGN(sizeof(struct npipe)),
3948 ALIGN(sizeof(struct nredir)),
3949 ALIGN(sizeof(struct nredir)),
3950 ALIGN(sizeof(struct nredir)),
3951 ALIGN(sizeof(struct nbinary)),
3952 ALIGN(sizeof(struct nbinary)),
3953 ALIGN(sizeof(struct nif)),
3954 ALIGN(sizeof(struct nbinary)),
3955 ALIGN(sizeof(struct nbinary)),
3956 ALIGN(sizeof(struct nfor)),
3957 ALIGN(sizeof(struct ncase)),
3958 ALIGN(sizeof(struct nclist)),
3959 ALIGN(sizeof(struct narg)),
3960 ALIGN(sizeof(struct narg)),
3961 ALIGN(sizeof(struct nfile)),
3962 ALIGN(sizeof(struct nfile)),
3963 ALIGN(sizeof(struct nfile)),
3964 ALIGN(sizeof(struct nfile)),
3965 ALIGN(sizeof(struct nfile)),
3966 ALIGN(sizeof(struct ndup)),
3967 ALIGN(sizeof(struct ndup)),
3968 ALIGN(sizeof(struct nhere)),
3969 ALIGN(sizeof(struct nhere)),
3970 ALIGN(sizeof(struct nnot)),
3976 * Delete a function if it exists.
3979 static void unsetfunc(char *name)
3981 struct tblentry *cmdp;
3983 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
3984 free(cmdp->param.func);
3991 * Locate and print what a word is...
3994 static int typecmd(int argc, char **argv)
4002 for (i = 1; i < argc; i++) {
4003 argv_a[0] = argv[i];
4006 err |= hashcmd(argc, argv);
4011 #ifdef CONFIG_ASH_CMDCMD
4012 static int commandcmd(int argc, char **argv)
4015 int default_path = 0;
4016 int verify_only = 0;
4017 int verbose_verify_only = 0;
4019 while ((c = nextopt("pvV")) != '\0')
4028 verbose_verify_only = 1;
4032 if (default_path + verify_only + verbose_verify_only > 1 || !*argptr) {
4033 out2str("command [-p] command [arg ...]\n"
4034 "command {-v|-V} command\n");
4038 if (verify_only || verbose_verify_only) {
4042 argv_a[0] = *argptr;
4044 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4045 return hashcmd(argc, argv);
4052 static int path_change(const char *newval, int *bltin)
4054 const char *old, *new;
4060 firstchange = 9999; /* assume no change */
4066 if ((*old == '\0' && *new == ':')
4067 || (*old == ':' && *new == '\0'))
4069 old = new; /* ignore subsequent differences */
4073 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4080 if (builtinloc >= 0 && *bltin < 0)
4086 * Routines to expand arguments to commands. We have to deal with
4087 * backquotes, shell variables, and file metacharacters.
4092 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4093 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4096 * Structure specifying which parts of the string should be searched
4097 * for IFS characters.
4101 struct ifsregion *next; /* next region in list */
4102 int begoff; /* offset of start of region */
4103 int endoff; /* offset of end of region */
4104 int nulonly; /* search for nul bytes only */
4108 static char *expdest; /* output of current string */
4109 static struct nodelist *argbackq; /* list of back quote expressions */
4110 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4111 static struct ifsregion *ifslastp; /* last struct in list */
4112 static struct arglist exparg; /* holds expanded arg list */
4114 static void argstr(char *, int);
4115 static char *exptilde(char *, int);
4116 static void expbackq(union node *, int, int);
4117 static int subevalvar(char *, char *, int, int, int, int, int);
4118 static int varisset(char *, int);
4119 static void strtodest(const char *, int, int);
4120 static inline void varvalue(char *, int, int);
4121 static void recordregion(int, int, int);
4122 static void removerecordregions(int);
4123 static void ifsbreakup(char *, struct arglist *);
4124 static void ifsfree(void);
4125 static void expandmeta(struct strlist *, int);
4127 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4128 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4129 #if !defined(GLOB_BROKEN)
4130 static inline void addglob(const glob_t *);
4133 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4134 static void expmeta(char *, char *);
4136 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4137 static struct strlist *expsort(struct strlist *);
4138 static struct strlist *msort(struct strlist *, int);
4140 static int patmatch(char *, char *, int);
4142 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4143 static int patmatch2(char *, char *, int);
4145 static int pmatch(char *, char *, int);
4147 #define patmatch2 patmatch
4149 static char *cvtnum(int, char *);
4152 * Expand shell variables and backquotes inside a here document.
4155 /* arg: the document, fd: where to write the expanded version */
4156 static inline void expandhere(union node *arg, int fd)
4159 expandarg(arg, (struct arglist *) NULL, 0);
4160 xwrite(fd, stackblock(), expdest - stackblock());
4165 * Perform variable substitution and command substitution on an argument,
4166 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4167 * perform splitting and file name expansion. When arglist is NULL, perform
4168 * here document expansion.
4171 static void expandarg(union node *arg, struct arglist *arglist, int flag)
4176 argbackq = arg->narg.backquote;
4177 STARTSTACKSTR(expdest);
4178 ifsfirst.next = NULL;
4180 argstr(arg->narg.text, flag);
4181 if (arglist == NULL) {
4182 return; /* here document expanded */
4184 STPUTC('\0', expdest);
4185 p = grabstackstr(expdest);
4186 exparg.lastp = &exparg.list;
4190 if (flag & EXP_FULL) {
4191 ifsbreakup(p, &exparg);
4192 *exparg.lastp = NULL;
4193 exparg.lastp = &exparg.list;
4194 expandmeta(exparg.list, flag);
4196 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4198 sp = (struct strlist *) stalloc(sizeof(struct strlist));
4201 exparg.lastp = &sp->next;
4204 *exparg.lastp = NULL;
4206 *arglist->lastp = exparg.list;
4207 arglist->lastp = exparg.lastp;
4213 * Expand a variable, and return a pointer to the next character in the
4217 static inline char *evalvar(char *p, int flag)
4230 int quotes = flag & (EXP_FULL | EXP_CASE);
4233 subtype = varflags & VSTYPE;
4238 p = strchr(p, '=') + 1;
4239 again: /* jump here after setting a variable with ${var=text} */
4241 set = varisset(var, varflags & VSNUL);
4244 val = lookupvar(var);
4245 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4252 startloc = expdest - stackblock();
4253 if (set && subtype != VSPLUS) {
4254 /* insert the value of the variable */
4256 varvalue(var, varflags & VSQUOTE, flag);
4257 if (subtype == VSLENGTH) {
4258 varlen = expdest - stackblock() - startloc;
4259 STADJUST(-varlen, expdest);
4262 if (subtype == VSLENGTH) {
4263 varlen = strlen(val);
4266 varflags & VSQUOTE ? DQSYNTAX : BASESYNTAX, quotes);
4271 if (subtype == VSPLUS)
4274 easy = ((varflags & VSQUOTE) == 0 ||
4275 (*var == '@' && shellparam.nparam != 1));
4280 expdest = cvtnum(varlen, expdest);
4287 recordregion(startloc, expdest - stackblock(), varflags & VSQUOTE);
4303 case VSTRIMRIGHTMAX:
4307 * Terminate the string and start recording the pattern
4310 STPUTC('\0', expdest);
4311 patloc = expdest - stackblock();
4312 if (subevalvar(p, NULL, patloc, subtype,
4313 startloc, varflags, quotes) == 0) {
4314 int amount = (expdest - stackblock() - patloc) + 1;
4316 STADJUST(-amount, expdest);
4318 /* Remove any recorded regions beyond start of variable */
4319 removerecordregions(startloc);
4325 if (subevalvar(p, var, 0, subtype, startloc, varflags, quotes)) {
4328 * Remove any recorded regions beyond
4331 removerecordregions(startloc);
4346 if (subtype != VSNORMAL) { /* skip to end of alternative */
4350 if ((c = *p++) == CTLESC)
4352 else if (c == CTLBACKQ || c == (CTLBACKQ | CTLQUOTE)) {
4354 argbackq = argbackq->next;
4355 } else if (c == CTLVAR) {
4356 if ((*p++ & VSTYPE) != VSNORMAL)
4358 } else if (c == CTLENDVAR) {
4369 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4370 * characters to allow for further processing. Otherwise treat
4371 * $@ like $* since no splitting will be performed.
4374 static void argstr(char *p, int flag)
4377 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4380 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4381 p = exptilde(p, flag);
4385 case CTLENDVAR: /* ??? */
4388 /* "$@" syntax adherence hack */
4389 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4391 if ((flag & EXP_FULL) != 0)
4401 p = evalvar(p, flag);
4404 case CTLBACKQ | CTLQUOTE:
4405 expbackq(argbackq->n, c & CTLQUOTE, flag);
4406 argbackq = argbackq->next;
4408 #ifdef CONFIG_ASH_MATH_SUPPORT
4416 * sort of a hack - expand tildes in variable
4417 * assignments (after the first '=' and after ':'s).
4420 if (flag & EXP_VARTILDE && *p == '~') {
4427 p = exptilde(p, flag);
4437 static char *exptilde(char *p, int flag)
4439 char c, *startp = p;
4442 int quotes = flag & (EXP_FULL | EXP_CASE);
4444 while ((c = *p) != '\0') {
4451 if (flag & EXP_VARTILDE)
4461 if (*(startp + 1) == '\0') {
4462 if ((home = lookupvar("HOME")) == NULL)
4465 if ((pw = getpwnam(startp + 1)) == NULL)
4472 strtodest(home, SQSYNTAX, quotes);
4480 static void removerecordregions(int endoff)
4482 if (ifslastp == NULL)
4485 if (ifsfirst.endoff > endoff) {
4486 while (ifsfirst.next != NULL) {
4487 struct ifsregion *ifsp;
4490 ifsp = ifsfirst.next->next;
4491 free(ifsfirst.next);
4492 ifsfirst.next = ifsp;
4495 if (ifsfirst.begoff > endoff)
4498 ifslastp = &ifsfirst;
4499 ifsfirst.endoff = endoff;
4504 ifslastp = &ifsfirst;
4505 while (ifslastp->next && ifslastp->next->begoff < endoff)
4506 ifslastp = ifslastp->next;
4507 while (ifslastp->next != NULL) {
4508 struct ifsregion *ifsp;
4511 ifsp = ifslastp->next->next;
4512 free(ifslastp->next);
4513 ifslastp->next = ifsp;
4516 if (ifslastp->endoff > endoff)
4517 ifslastp->endoff = endoff;
4521 #ifdef CONFIG_ASH_MATH_SUPPORT
4523 * Expand arithmetic expression. Backup to start of expression,
4524 * evaluate, place result in (backed up) result, adjust string position.
4526 static void expari(int flag)
4532 int quotes = flag & (EXP_FULL | EXP_CASE);
4538 * This routine is slightly over-complicated for
4539 * efficiency. First we make sure there is
4540 * enough space for the result, which may be bigger
4541 * than the expression if we add exponentation. Next we
4542 * scan backwards looking for the start of arithmetic. If the
4543 * next previous character is a CTLESC character, then we
4544 * have to rescan starting from the beginning since CTLESC
4545 * characters have to be processed left to right.
4547 CHECKSTRSPACE(10, expdest);
4548 USTPUTC('\0', expdest);
4549 start = stackblock();
4551 while (*p != CTLARI && p >= start)
4554 error("missing CTLARI (shouldn't happen)");
4555 if (p > start && *(p - 1) == CTLESC)
4556 for (p = start; *p != CTLARI; p++)
4565 removerecordregions(begoff);
4568 result = arith(p + 2, &errcode);
4571 error("divide by zero");
4573 error("syntax error: \"%s\"\n", p + 2);
4575 snprintf(p, 12, "%d", result);
4580 recordregion(begoff, p - 1 - start, 0);
4581 result = expdest - p + 1;
4582 STADJUST(-result, expdest);
4587 * Expand stuff in backwards quotes.
4590 static void expbackq(union node *cmd, int quoted, int flag)
4592 volatile struct backcmd in;
4596 char *dest = expdest;
4597 volatile struct ifsregion saveifs;
4598 struct ifsregion *volatile savelastp;
4599 struct nodelist *volatile saveargbackq;
4601 int startloc = dest - stackblock();
4602 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4603 volatile int saveherefd;
4604 int quotes = flag & (EXP_FULL | EXP_CASE);
4605 struct jmploc jmploc;
4606 struct jmploc *volatile savehandler;
4610 /* Avoid longjmp clobbering */
4621 savelastp = ifslastp;
4622 saveargbackq = argbackq;
4623 saveherefd = herefd;
4625 if ((ex = setjmp(jmploc.loc))) {
4628 savehandler = handler;
4631 p = grabstackstr(dest);
4632 evalbackcmd(cmd, (struct backcmd *) &in);
4633 ungrabstackstr(p, dest);
4637 ifslastp = savelastp;
4638 argbackq = saveargbackq;
4639 herefd = saveherefd;
4647 if (--in.nleft < 0) {
4650 i = safe_read(in.fd, buf, sizeof buf);
4651 TRACE(("expbackq: read returns %d\n", i));
4658 if (lastc != '\0') {
4659 if (quotes && SIT(lastc, syntax) == CCTL)
4660 STPUTC(CTLESC, dest);
4661 STPUTC(lastc, dest);
4665 /* Eat all trailing newlines */
4666 for (; dest > stackblock() && dest[-1] == '\n';)
4674 exitstatus = waitforjob(in.jp);
4675 handler = savehandler;
4677 longjmp(handler->loc, 1);
4680 recordregion(startloc, dest - stackblock(), 0);
4681 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4682 (dest - stackblock()) - startloc,
4683 (dest - stackblock()) - startloc, stackblock() + startloc));
4689 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
4690 int varflags, int quotes)
4696 int saveherefd = herefd;
4697 struct nodelist *saveargbackq = argbackq;
4701 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4702 STACKSTRNUL(expdest);
4703 herefd = saveherefd;
4704 argbackq = saveargbackq;
4705 startp = stackblock() + startloc;
4707 str = stackblock() + strloc;
4711 setvar(str, startp, 0);
4712 amount = startp - expdest;
4713 STADJUST(amount, expdest);
4720 if (*p != CTLENDVAR) {
4721 out2fmt(snlfmt, startp);
4722 error((char *) NULL);
4724 error("%.*s: parameter %snot set", p - str - 1,
4725 str, (varflags & VSNUL) ? "null or " : nullstr);
4729 for (loc = startp; loc < str; loc++) {
4732 if (patmatch2(str, startp, quotes))
4735 if (quotes && *loc == CTLESC)
4741 for (loc = str - 1; loc >= startp;) {
4744 if (patmatch2(str, startp, quotes))
4748 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4749 for (q = startp; q < loc; q++)
4759 for (loc = str - 1; loc >= startp;) {
4760 if (patmatch2(str, loc, quotes))
4763 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4764 for (q = startp; q < loc; q++)
4773 case VSTRIMRIGHTMAX:
4774 for (loc = startp; loc < str - 1; loc++) {
4775 if (patmatch2(str, loc, quotes))
4777 if (quotes && *loc == CTLESC)
4790 amount = ((str - 1) - (loc - startp)) - expdest;
4791 STADJUST(amount, expdest);
4792 while (loc != str - 1)
4797 amount = loc - expdest;
4798 STADJUST(amount, expdest);
4799 STPUTC('\0', expdest);
4800 STADJUST(-1, expdest);
4806 * Test whether a specialized variable is set.
4809 static int varisset(char *name, int nulok)
4812 return backgndpid != -1;
4813 else if (*name == '@' || *name == '*') {
4814 if (*shellparam.p == NULL)
4820 for (av = shellparam.p; *av; av++)
4825 } else if (is_digit(*name)) {
4827 int num = atoi(name);
4829 if (num > shellparam.nparam)
4835 ap = shellparam.p[num - 1];
4837 if (nulok && (ap == NULL || *ap == '\0'))
4844 * Put a string on the stack.
4847 static void strtodest(const char *p, int syntax, int quotes)
4850 if (quotes && SIT(*p, syntax) == CCTL)
4851 STPUTC(CTLESC, expdest);
4852 STPUTC(*p++, expdest);
4857 * Add the value of a specialized variable to the stack string.
4860 static inline void varvalue(char *name, int quoted, int flags)
4869 int allow_split = flags & EXP_FULL;
4870 int quotes = flags & (EXP_FULL | EXP_CASE);
4872 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4881 num = shellparam.nparam;
4886 expdest = cvtnum(num, expdest);
4889 for (i = 0; i < NOPTS; i++) {
4891 STPUTC(optent_letter(optlist[i]), expdest);
4895 if (allow_split && quoted) {
4896 sep = 1 << CHAR_BIT;
4901 sep = ifsset()? ifsval()[0] : ' ';
4903 sepq = SIT(sep, syntax) == CCTL;
4906 for (ap = shellparam.p; (p = *ap++) != NULL;) {
4907 strtodest(p, syntax, quotes);
4910 STPUTC(CTLESC, expdest);
4911 STPUTC(sep, expdest);
4916 strtodest(arg0, syntax, quotes);
4920 if (num > 0 && num <= shellparam.nparam) {
4921 strtodest(shellparam.p[num - 1], syntax, quotes);
4929 * Record the fact that we have to scan this region of the
4930 * string for IFS characters.
4933 static void recordregion(int start, int end, int nulonly)
4935 struct ifsregion *ifsp;
4937 if (ifslastp == NULL) {
4941 ifsp = (struct ifsregion *) xmalloc(sizeof(struct ifsregion));
4943 ifslastp->next = ifsp;
4947 ifslastp->begoff = start;
4948 ifslastp->endoff = end;
4949 ifslastp->nulonly = nulonly;
4955 * Break the argument string into pieces based upon IFS and add the
4956 * strings to the argument list. The regions of the string to be
4957 * searched for IFS characters have been stored by recordregion.
4959 static void ifsbreakup(char *string, struct arglist *arglist)
4961 struct ifsregion *ifsp;
4966 const char *ifs, *realifs;
4974 realifs = ifsset()? ifsval() : defifs;
4975 if (ifslastp != NULL) {
4978 p = string + ifsp->begoff;
4979 nulonly = ifsp->nulonly;
4980 ifs = nulonly ? nullstr : realifs;
4982 while (p < string + ifsp->endoff) {
4986 if (strchr(ifs, *p)) {
4988 ifsspc = (strchr(defifs, *p) != NULL);
4989 /* Ignore IFS whitespace at start */
4990 if (q == start && ifsspc) {
4996 sp = (struct strlist *) stalloc(sizeof *sp);
4998 *arglist->lastp = sp;
4999 arglist->lastp = &sp->next;
5003 if (p >= string + ifsp->endoff) {
5009 if (strchr(ifs, *p) == NULL) {
5012 } else if (strchr(defifs, *p) == NULL) {
5028 } while ((ifsp = ifsp->next) != NULL);
5029 if (!(*start || (!ifsspc && start > string && nulonly))) {
5034 sp = (struct strlist *) stalloc(sizeof *sp);
5036 *arglist->lastp = sp;
5037 arglist->lastp = &sp->next;
5040 static void ifsfree(void)
5042 while (ifsfirst.next != NULL) {
5043 struct ifsregion *ifsp;
5046 ifsp = ifsfirst.next->next;
5047 free(ifsfirst.next);
5048 ifsfirst.next = ifsp;
5052 ifsfirst.next = NULL;
5056 * Add a file name to the list.
5059 static void addfname(const char *name)
5063 sp = (struct strlist *) stalloc(sizeof *sp);
5064 sp->text = sstrdup(name);
5066 exparg.lastp = &sp->next;
5070 * Expand shell metacharacters. At this point, the only control characters
5071 * should be escapes. The results are stored in the list exparg.
5074 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5075 static void expandmeta(struct strlist *str, int flag)
5080 /* TODO - EXP_REDIR */
5085 p = preglob(str->text);
5087 switch (glob(p, 0, 0, &pglob)) {
5089 if (pglob.gl_pathv[1] == 0 && !strcmp(p, pglob.gl_pathv[0]))
5100 *exparg.lastp = str;
5101 rmescapes(str->text);
5102 exparg.lastp = &str->next;
5104 default: /* GLOB_NOSPACE */
5105 error("Out of space");
5113 * Add the result of glob(3) to the list.
5116 static inline void addglob(const glob_t * pglob)
5118 char **p = pglob->gl_pathv;
5126 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5127 static char *expdir;
5130 static void expandmeta(struct strlist *str, int flag)
5133 struct strlist **savelastp;
5137 /* TODO - EXP_REDIR */
5143 for (;;) { /* fast check for meta chars */
5144 if ((c = *p++) == '\0')
5146 if (c == '*' || c == '?' || c == '[' || c == '!')
5149 savelastp = exparg.lastp;
5151 if (expdir == NULL) {
5152 int i = strlen(str->text);
5154 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5157 expmeta(expdir, str->text);
5161 if (exparg.lastp == savelastp) {
5166 *exparg.lastp = str;
5167 rmescapes(str->text);
5168 exparg.lastp = &str->next;
5170 *exparg.lastp = NULL;
5171 *savelastp = sp = expsort(*savelastp);
5172 while (sp->next != NULL)
5174 exparg.lastp = &sp->next;
5182 * Do metacharacter (i.e. *, ?, [...]) expansion.
5185 static void expmeta(char *enddir, char *name)
5201 for (p = name;; p++) {
5202 if (*p == '*' || *p == '?')
5204 else if (*p == '[') {
5209 while (*q == CTLQUOTEMARK)
5213 if (*q == '/' || *q == '\0')
5220 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5222 } else if (*p == '\0')
5224 else if (*p == CTLQUOTEMARK)
5226 else if (*p == CTLESC)
5234 if (metaflag == 0) { /* we've reached the end of the file name */
5235 if (enddir != expdir)
5237 for (p = name;; p++) {
5238 if (*p == CTLQUOTEMARK)
5246 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5251 if (start != name) {
5254 while (*p == CTLQUOTEMARK)
5261 if (enddir == expdir) {
5263 } else if (enddir == expdir + 1 && *expdir == '/') {
5269 if ((dirp = opendir(cp)) == NULL)
5271 if (enddir != expdir)
5273 if (*endname == 0) {
5281 while (*p == CTLQUOTEMARK)
5287 while (!int_pending() && (dp = readdir(dirp)) != NULL) {
5288 if (dp->d_name[0] == '.' && !matchdot)
5290 if (patmatch(start, dp->d_name, 0)) {
5292 strcpy(enddir, dp->d_name);
5295 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
5298 expmeta(p, endname);
5306 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5310 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5312 * Sort the results of file name expansion. It calculates the number of
5313 * strings to sort and then calls msort (short for merge sort) to do the
5317 static struct strlist *expsort(struct strlist *str)
5323 for (sp = str; sp; sp = sp->next)
5325 return msort(str, len);
5329 static struct strlist *msort(struct strlist *list, int len)
5331 struct strlist *p, *q = NULL;
5332 struct strlist **lpp;
5340 for (n = half; --n >= 0;) {
5344 q->next = NULL; /* terminate first half of list */
5345 q = msort(list, half); /* sort first half of list */
5346 p = msort(p, len - half); /* sort second half */
5349 if (strcmp(p->text, q->text) < 0) {
5352 if ((p = *lpp) == NULL) {
5359 if ((q = *lpp) == NULL) {
5372 * Returns true if the pattern matches the string.
5375 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5376 /* squoted: string might have quote chars */
5377 static int patmatch(char *pattern, char *string, int squoted)
5382 p = preglob(pattern);
5383 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5385 return !fnmatch(p, q, 0);
5389 static int patmatch2(char *pattern, char *string, int squoted)
5395 p = grabstackstr(expdest);
5396 res = patmatch(pattern, string, squoted);
5397 ungrabstackstr(p, expdest);
5401 static int patmatch(char *pattern, char *string, int squoted)
5403 return pmatch(pattern, string, squoted);
5407 static int pmatch(char *pattern, char *string, int squoted)
5419 if (squoted && *q == CTLESC)
5427 if (squoted && *q == CTLESC)
5434 while (c == CTLQUOTEMARK || c == '*')
5436 if (c != CTLESC && c != CTLQUOTEMARK &&
5437 c != '?' && c != '*' && c != '[') {
5439 if (squoted && *q == CTLESC && q[1] == c)
5443 if (squoted && *q == CTLESC)
5449 if (pmatch(p, q, squoted))
5451 if (squoted && *q == CTLESC)
5453 } while (*q++ != '\0');
5464 while (*endp == CTLQUOTEMARK)
5467 goto dft; /* no matching ] */
5468 if (*endp == CTLESC)
5480 if (squoted && chr == CTLESC)
5486 if (c == CTLQUOTEMARK)
5490 if (*p == '-' && p[1] != ']') {
5492 while (*p == CTLQUOTEMARK)
5496 if (chr >= c && chr <= *p)
5503 } while ((c = *p++) != ']');
5504 if (found == invert)
5509 if (squoted && *q == CTLESC)
5526 * Remove any CTLESC characters from a string.
5529 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5530 static char *_rmescapes(char *str, int flag)
5533 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5535 p = strpbrk(str, qchars);
5541 if (flag & RMESCAPE_ALLOC) {
5542 size_t len = p - str;
5544 q = r = stalloc(strlen(p) + len + 1);
5546 memcpy(q, str, len);
5551 if (*p == CTLQUOTEMARK) {
5557 if (flag & RMESCAPE_GLOB && *p != '/') {
5567 static void rmescapes(char *str)
5572 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5578 if (*p == CTLQUOTEMARK) {
5593 * See if a pattern matches in a case statement.
5596 static int casematch(union node *pattern, const char *val)
5598 struct stackmark smark;
5602 setstackmark(&smark);
5603 argbackq = pattern->narg.backquote;
5604 STARTSTACKSTR(expdest);
5606 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5607 STPUTC('\0', expdest);
5608 p = grabstackstr(expdest);
5609 result = patmatch(p, (char *) val, 0);
5610 popstackmark(&smark);
5618 static char *cvtnum(int num, char *buf)
5622 CHECKSTRSPACE(32, buf);
5623 len = sprintf(buf, "%d", num);
5629 * Editline and history functions (and glue).
5631 static int histcmd(int argc, char **argv)
5633 error("not compiled with history support");
5639 struct redirtab *next;
5640 short renamed[10]; /* Current ash support only 0-9 descriptors */
5641 /* char on arm (and others) can't be negative */
5644 static struct redirtab *redirlist;
5646 extern char **environ;
5651 * Initialization code.
5654 static void init(void)
5665 basepf.nextc = basepf.buf = basebuf;
5674 for (envp = environ; *envp; envp++) {
5675 if (strchr(*envp, '=')) {
5676 setvareq(*envp, VEXPORT | VTEXTFIXED);
5680 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5681 setvar("PPID", ppid, 0);
5688 * This routine is called when an error or an interrupt occurs in an
5689 * interactive shell and control is returned to the main command loop.
5692 /* 1 == check for aliases, 2 == also check for assignments */
5693 static int checkalias; /* also used in no alias mode for check assignments */
5695 static void reset(void)
5707 if (exception != EXSHELLPROC)
5708 parselleft = parsenleft = 0; /* clear input buffer */
5712 /* from parser.c: */
5730 * This file implements the input routines used by the parser.
5733 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5734 static const char *cmdedit_prompt;
5735 static inline void putprompt(const char *s)
5740 static inline void putprompt(const char *s)
5746 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5751 * Same as pgetc(), but ignores PEOA.
5754 #ifdef CONFIG_ASH_ALIAS
5755 static int pgetc2(void)
5761 } while (c == PEOA);
5765 static inline int pgetc2(void)
5767 return pgetc_macro();
5772 * Read a line from the script.
5775 static inline char *pfgets(char *line, int len)
5781 while (--nleft > 0) {
5796 static inline int preadfd(void)
5799 char *buf = parsefile->buf;
5804 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5806 if (!iflag || parsefile->fd)
5807 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5809 nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
5813 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5817 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5818 int flags = fcntl(0, F_GETFL, 0);
5820 if (flags >= 0 && flags & O_NONBLOCK) {
5821 flags &= ~O_NONBLOCK;
5822 if (fcntl(0, F_SETFL, flags) >= 0) {
5823 out2str("sh: turning off NDELAY mode\n");
5832 static void popstring(void)
5834 struct strpush *sp = parsefile->strpush;
5837 #ifdef CONFIG_ASH_ALIAS
5839 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5844 if (sp->string != sp->ap->val) {
5848 sp->ap->flag &= ~ALIASINUSE;
5849 if (sp->ap->flag & ALIASDEAD) {
5850 unalias(sp->ap->name);
5854 parsenextc = sp->prevstring;
5855 parsenleft = sp->prevnleft;
5856 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5857 parsefile->strpush = sp->prev;
5858 if (sp != &(parsefile->basestrpush))
5865 * Refill the input buffer and return the next input character:
5867 * 1) If a string was pushed back on the input, pop it;
5868 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5869 * from a string so we can't refill the buffer, return EOF.
5870 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5871 * 4) Process input up to the next newline, deleting nul characters.
5874 static int preadbuffer(void)
5880 while (parsefile->strpush) {
5881 #ifdef CONFIG_ASH_ALIAS
5882 if (parsenleft == -1 && parsefile->strpush->ap &&
5883 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5888 if (--parsenleft >= 0)
5889 return (*parsenextc++);
5891 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5896 if (parselleft <= 0) {
5897 if ((parselleft = preadfd()) <= 0) {
5898 parselleft = parsenleft = EOF_NLEFT;
5905 /* delete nul characters */
5906 for (more = 1; more;) {
5914 parsenleft = q - parsenextc;
5915 more = 0; /* Stop processing here */
5921 if (--parselleft <= 0 && more) {
5922 parsenleft = q - parsenextc - 1;
5933 out2str(parsenextc);
5938 return *parsenextc++;
5943 * Push a string back onto the input at this current parsefile level.
5944 * We handle aliases this way.
5946 static void pushstring(char *s, int len, void *ap)
5951 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
5952 if (parsefile->strpush) {
5953 sp = xmalloc(sizeof(struct strpush));
5954 sp->prev = parsefile->strpush;
5955 parsefile->strpush = sp;
5957 sp = parsefile->strpush = &(parsefile->basestrpush);
5958 sp->prevstring = parsenextc;
5959 sp->prevnleft = parsenleft;
5960 #ifdef CONFIG_ASH_ALIAS
5961 sp->ap = (struct alias *) ap;
5963 ((struct alias *) ap)->flag |= ALIASINUSE;
5974 * Like setinputfile, but takes input from a string.
5977 static void setinputstring(char *string)
5981 parsenextc = string;
5982 parsenleft = strlen(string);
5983 parsefile->buf = NULL;
5991 * To handle the "." command, a stack of input files is used. Pushfile
5992 * adds a new entry to the stack and popfile restores the previous level.
5995 static void pushfile(void)
5997 struct parsefile *pf;
5999 parsefile->nleft = parsenleft;
6000 parsefile->lleft = parselleft;
6001 parsefile->nextc = parsenextc;
6002 parsefile->linno = plinno;
6003 pf = (struct parsefile *) xmalloc(sizeof(struct parsefile));
6004 pf->prev = parsefile;
6007 pf->basestrpush.prev = NULL;
6011 #ifdef CONFIG_ASH_JOB_CONTROL
6012 static void restartjob(struct job *);
6014 static void freejob(struct job *);
6015 static struct job *getjob(const char *);
6016 static int dowait(int, struct job *);
6017 static void waitonint(int);
6021 * We keep track of whether or not fd0 has been redirected. This is for
6022 * background commands, where we want to redirect fd0 to /dev/null only
6023 * if it hasn't already been redirected.
6025 static int fd0_redirected = 0;
6027 /* Return true if fd 0 has already been redirected at least once. */
6028 static inline int fd0_redirected_p(void)
6030 return fd0_redirected != 0;
6033 static void dupredirect(const union node *, int, int fd1dup);
6035 #ifdef CONFIG_ASH_JOB_CONTROL
6037 * Turn job control on and off.
6039 * Note: This code assumes that the third arg to ioctl is a character
6040 * pointer, which is true on Berkeley systems but not System V. Since
6041 * System V doesn't have job control yet, this isn't a problem now.
6046 static void setjobctl(int enable)
6048 #ifdef OLD_TTY_DRIVER
6052 if (enable == jobctl || rootshell == 0)
6055 do { /* while we are in the background */
6056 #ifdef OLD_TTY_DRIVER
6057 if (ioctl(2, TIOCGPGRP, (char *) &initialpgrp) < 0) {
6059 initialpgrp = tcgetpgrp(2);
6060 if (initialpgrp < 0) {
6062 out2str("sh: can't access tty; job control turned off\n");
6066 if (initialpgrp == -1)
6067 initialpgrp = getpgrp();
6068 else if (initialpgrp != getpgrp()) {
6069 killpg(initialpgrp, SIGTTIN);
6073 #ifdef OLD_TTY_DRIVER
6074 if (ioctl(2, TIOCGETD, (char *) &ldisc) < 0 || ldisc != NTTYDISC) {
6076 ("sh: need new tty driver to run job control; job control turned off\n");
6084 setpgid(0, rootpid);
6085 #ifdef OLD_TTY_DRIVER
6086 ioctl(2, TIOCSPGRP, (char *) &rootpid);
6088 tcsetpgrp(2, rootpid);
6090 } else { /* turning job control off */
6091 setpgid(0, initialpgrp);
6092 #ifdef OLD_TTY_DRIVER
6093 ioctl(2, TIOCSPGRP, (char *) &initialpgrp);
6095 tcsetpgrp(2, initialpgrp);
6106 #ifdef CONFIG_ASH_JOB_CONTROL
6107 static int killcmd(int argc, char **argv)
6118 ("Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6119 "kill -l [exitstatus]");
6122 if (*argv[1] == '-') {
6123 signo = decode_signal(argv[1] + 1, 1);
6127 while ((c = nextopt("ls:")) != '\0')
6133 signo = decode_signal(optionarg, 1);
6135 error("invalid signal number or name: %s", optionarg);
6140 error("nextopt returned character code 0%o", c);
6147 if (!list && signo < 0)
6150 if ((signo < 0 || !*argptr) ^ list) {
6159 for (i = 1; i < NSIG; i++) {
6160 name = u_signal_names(0, &i, 1);
6166 name = u_signal_names(*argptr, &signo, -1);
6170 error("invalid signal number or exit status: %s", *argptr);
6175 if (**argptr == '%') {
6176 jp = getjob(*argptr);
6177 if (jp->jobctl == 0)
6178 error("job %s not created under job control", *argptr);
6179 pid = -jp->ps[0].pid;
6181 pid = atoi(*argptr);
6182 if (kill(pid, signo) != 0)
6183 error("%s: %m", *argptr);
6184 } while (*++argptr);
6189 static int fgcmd(int argc, char **argv)
6195 jp = getjob(argv[1]);
6196 if (jp->jobctl == 0)
6197 error("job not created under job control");
6198 pgrp = jp->ps[0].pid;
6199 #ifdef OLD_TTY_DRIVER
6200 ioctl(2, TIOCSPGRP, (char *) &pgrp);
6205 status = waitforjob(jp);
6210 static int bgcmd(int argc, char **argv)
6215 jp = getjob(*++argv);
6216 if (jp->jobctl == 0)
6217 error("job not created under job control");
6219 } while (--argc > 1);
6224 static void restartjob(struct job *jp)
6226 struct procstat *ps;
6229 if (jp->state == JOBDONE)
6232 killpg(jp->ps[0].pid, SIGCONT);
6233 for (ps = jp->ps, i = jp->nprocs; --i >= 0; ps++) {
6234 if (WIFSTOPPED(ps->status)) {
6243 static void showjobs(int change);
6246 static int jobscmd(int argc, char **argv)
6254 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6255 * statuses have changed since the last call to showjobs.
6257 * If the shell is interrupted in the process of creating a job, the
6258 * result may be a job structure containing zero processes. Such structures
6259 * will be freed here.
6262 static void showjobs(int change)
6268 struct procstat *ps;
6272 TRACE(("showjobs(%d) called\n", change));
6273 while (dowait(0, (struct job *) NULL) > 0);
6274 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6277 if (jp->nprocs == 0) {
6281 if (change && !jp->changed)
6283 procno = jp->nprocs;
6284 for (ps = jp->ps;; ps++) { /* for each process */
6286 snprintf(s, 64, "[%d] %ld ", jobno, (long) ps->pid);
6288 snprintf(s, 64, " %ld ", (long) ps->pid);
6292 if (ps->status == -1) {
6293 /* don't print anything */
6294 } else if (WIFEXITED(ps->status)) {
6295 snprintf(s, 64, "Exit %d", WEXITSTATUS(ps->status));
6297 #ifdef CONFIG_ASH_JOB_CONTROL
6298 if (WIFSTOPPED(ps->status))
6299 i = WSTOPSIG(ps->status);
6300 else /* WIFSIGNALED(ps->status) */
6302 i = WTERMSIG(ps->status);
6303 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6304 strcpy(s, sys_siglist[i & 0x7F]);
6306 snprintf(s, 64, "Signal %d", i & 0x7F);
6307 if (WCOREDUMP(ps->status))
6308 strcat(s, " (core dumped)");
6312 printf("%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ', ps->cmd);
6317 if (jp->state == JOBDONE) {
6325 * Mark a job structure as unused.
6328 static void freejob(struct job *jp)
6330 const struct procstat *ps;
6334 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
6335 if (ps->cmd != nullstr)
6338 if (jp->ps != &jp->ps0)
6341 #ifdef CONFIG_ASH_JOB_CONTROL
6342 if (curjob == jp - jobtab + 1)
6350 static int waitcmd(int argc, char **argv)
6358 job = getjob(*++argv);
6362 for (;;) { /* loop until process terminated or stopped */
6365 status = job->ps[job->nprocs - 1].status;
6371 if (WIFEXITED(status))
6372 retval = WEXITSTATUS(status);
6373 #ifdef CONFIG_ASH_JOB_CONTROL
6374 else if (WIFSTOPPED(status))
6375 retval = WSTOPSIG(status) + 128;
6378 /* XXX: limits number of signals */
6379 retval = WTERMSIG(status) + 128;
6384 for (jp = jobtab;; jp++) {
6385 if (jp >= jobtab + njobs) { /* no running procs */
6388 if (jp->used && jp->state == 0)
6392 if (dowait(2, 0) < 0 && errno == EINTR) {
6401 * Convert a job name to a job structure.
6404 static struct job *getjob(const char *name)
6412 #ifdef CONFIG_ASH_JOB_CONTROL
6414 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6415 error("No current job");
6416 return &jobtab[jobno - 1];
6418 error("No current job");
6420 } else if (name[0] == '%') {
6421 if (is_digit(name[1])) {
6422 jobno = number(name + 1);
6423 if (jobno > 0 && jobno <= njobs && jobtab[jobno - 1].used != 0)
6424 return &jobtab[jobno - 1];
6425 #ifdef CONFIG_ASH_JOB_CONTROL
6426 } else if (name[1] == '%' && name[2] == '\0') {
6430 struct job *found = NULL;
6432 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6433 if (jp->used && jp->nprocs > 0
6434 && prefix(name + 1, jp->ps[0].cmd)) {
6436 error("%s: ambiguous", name);
6443 } else if (is_number(name, &pid)) {
6444 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6445 if (jp->used && jp->nprocs > 0
6446 && jp->ps[jp->nprocs - 1].pid == pid)
6450 error("No such job: %s", name);
6457 * Return a new job structure,
6460 static struct job *makejob(const union node *node, int nprocs)
6465 for (i = njobs, jp = jobtab;; jp++) {
6469 jobtab = xmalloc(4 * sizeof jobtab[0]);
6471 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6472 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6473 /* Relocate `ps' pointers */
6474 for (i = 0; i < njobs; i++)
6475 if (jp[i].ps == &jobtab[i].ps0)
6476 jp[i].ps = &jp[i].ps0;
6480 jp = jobtab + njobs;
6481 for (i = 4; --i >= 0; jobtab[njobs++].used = 0);
6493 #ifdef CONFIG_ASH_JOB_CONTROL
6494 jp->jobctl = jobctl;
6497 jp->ps = xmalloc(nprocs * sizeof(struct procstat));
6502 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long) node, nprocs,
6509 * Fork of a subshell. If we are doing job control, give the subshell its
6510 * own process group. Jp is a job structure that the job is to be added to.
6511 * N is the command that will be evaluated by the child. Both jp and n may
6512 * be NULL. The mode parameter can be one of the following:
6513 * FORK_FG - Fork off a foreground process.
6514 * FORK_BG - Fork off a background process.
6515 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6516 * process group even if job control is on.
6518 * When job control is turned off, background processes have their standard
6519 * input redirected to /dev/null (except for the second and later processes
6525 static int forkshell(struct job *jp, const union node *n, int mode)
6529 #ifdef CONFIG_ASH_JOB_CONTROL
6532 const char *devnull = _PATH_DEVNULL;
6533 const char *nullerr = "Can't open %s";
6535 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long) n,
6538 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6544 TRACE(("Fork failed, errno=%d\n", errno));
6546 error("Cannot fork");
6553 TRACE(("Child shell %d\n", getpid()));
6554 wasroot = rootshell;
6559 #ifdef CONFIG_ASH_JOB_CONTROL
6560 jobctl = 0; /* do job control only in root shell */
6561 if (wasroot && mode != FORK_NOJOB && mflag) {
6562 if (jp == NULL || jp->nprocs == 0)
6565 pgrp = jp->ps[0].pid;
6567 if (mode == FORK_FG) {
6568 /*** this causes superfluous TIOCSPGRPS ***/
6569 #ifdef OLD_TTY_DRIVER
6570 if (ioctl(2, TIOCSPGRP, (char *) &pgrp) < 0)
6571 error("TIOCSPGRP failed, errno=%d", errno);
6573 if (tcsetpgrp(2, pgrp) < 0)
6574 error("tcsetpgrp failed, errno=%d", errno);
6579 } else if (mode == FORK_BG) {
6581 if (mode == FORK_BG) {
6585 if ((jp == NULL || jp->nprocs == 0) && !fd0_redirected_p()) {
6587 if (open(devnull, O_RDONLY) != 0)
6588 error(nullerr, devnull);
6591 for (i = njobs, p = jobtab; --i >= 0; p++)
6594 if (wasroot && iflag) {
6601 #ifdef CONFIG_ASH_JOB_CONTROL
6602 if (rootshell && mode != FORK_NOJOB && mflag) {
6603 if (jp == NULL || jp->nprocs == 0)
6606 pgrp = jp->ps[0].pid;
6610 if (mode == FORK_BG)
6611 backgndpid = pid; /* set $! */
6613 struct procstat *ps = &jp->ps[jp->nprocs++];
6618 if (iflag && rootshell && n)
6619 ps->cmd = commandtext(n);
6622 TRACE(("In parent shell: child = %d\n", pid));
6629 * Wait for job to finish.
6631 * Under job control we have the problem that while a child process is
6632 * running interrupts generated by the user are sent to the child but not
6633 * to the shell. This means that an infinite loop started by an inter-
6634 * active user may be hard to kill. With job control turned off, an
6635 * interactive user may place an interactive program inside a loop. If
6636 * the interactive program catches interrupts, the user doesn't want
6637 * these interrupts to also abort the loop. The approach we take here
6638 * is to have the shell ignore interrupt signals while waiting for a
6639 * forground process to terminate, and then send itself an interrupt
6640 * signal if the child process was terminated by an interrupt signal.
6641 * Unfortunately, some programs want to do a bit of cleanup and then
6642 * exit on interrupt; unless these processes terminate themselves by
6643 * sending a signal to themselves (instead of calling exit) they will
6644 * confuse this approach.
6647 static int waitforjob(struct job *jp)
6649 #ifdef CONFIG_ASH_JOB_CONTROL
6650 int mypgrp = getpgrp();
6654 struct sigaction act, oact;
6658 #ifdef CONFIG_ASH_JOB_CONTROL
6663 sigaction(SIGINT, 0, &act);
6664 act.sa_handler = waitonint;
6665 sigaction(SIGINT, &act, &oact);
6667 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6668 while (jp->state == 0) {
6671 #ifdef CONFIG_ASH_JOB_CONTROL
6676 sigaction(SIGINT, &oact, 0);
6678 kill(getpid(), SIGINT);
6680 #ifdef CONFIG_ASH_JOB_CONTROL
6682 #ifdef OLD_TTY_DRIVER
6683 if (ioctl(2, TIOCSPGRP, (char *) &mypgrp) < 0)
6684 error("TIOCSPGRP failed, errno=%d\n", errno);
6686 if (tcsetpgrp(2, mypgrp) < 0)
6687 error("tcsetpgrp failed, errno=%d\n", errno);
6690 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED)
6691 curjob = jp - jobtab + 1;
6693 status = jp->ps[jp->nprocs - 1].status;
6694 /* convert to 8 bits */
6695 if (WIFEXITED(status))
6696 st = WEXITSTATUS(status);
6697 #ifdef CONFIG_ASH_JOB_CONTROL
6698 else if (WIFSTOPPED(status))
6699 st = WSTOPSIG(status) + 128;
6702 st = WTERMSIG(status) + 128;
6703 #ifdef CONFIG_ASH_JOB_CONTROL
6706 * This is truly gross.
6707 * If we're doing job control, then we did a TIOCSPGRP which
6708 * caused us (the shell) to no longer be in the controlling
6709 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6710 * intuit from the subprocess exit status whether a SIGINT
6711 * occured, and if so interrupt ourselves. Yuck. - mycroft
6713 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6716 if (jp->state == JOBDONE)
6726 * Wait for a process to terminate.
6730 * Do a wait system call. If job control is compiled in, we accept
6731 * stopped processes. If block is zero, we return a value of zero
6732 * rather than blocking.
6734 * System V doesn't have a non-blocking wait system call. It does
6735 * have a SIGCLD signal that is sent to a process when one of it's
6736 * children dies. The obvious way to use SIGCLD would be to install
6737 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6738 * was received, and have waitproc bump another counter when it got
6739 * the status of a process. Waitproc would then know that a wait
6740 * system call would not block if the two counters were different.
6741 * This approach doesn't work because if a process has children that
6742 * have not been waited for, System V will send it a SIGCLD when it
6743 * installs a signal handler for SIGCLD. What this means is that when
6744 * a child exits, the shell will be sent SIGCLD signals continuously
6745 * until is runs out of stack space, unless it does a wait call before
6746 * restoring the signal handler. The code below takes advantage of
6747 * this (mis)feature by installing a signal handler for SIGCLD and
6748 * then checking to see whether it was called. If there are any
6749 * children to be waited for, it will be.
6753 static inline int waitproc(int block, int *status)
6758 #ifdef CONFIG_ASH_JOB_CONTROL
6764 return wait3(status, flags, (struct rusage *) NULL);
6767 static int dowait(int block, struct job *job)
6771 struct procstat *sp;
6773 struct job *thisjob;
6779 TRACE(("dowait(%d) called\n", block));
6781 pid = waitproc(block, &status);
6782 TRACE(("wait returns %d, status=%d\n", pid, status));
6783 } while (!(block & 2) && pid == -1 && errno == EINTR);
6788 for (jp = jobtab; jp < jobtab + njobs; jp++) {
6792 for (sp = jp->ps; sp < jp->ps + jp->nprocs; sp++) {
6795 if (sp->pid == pid) {
6796 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
6797 pid, sp->status, status));
6798 sp->status = status;
6801 if (sp->status == -1)
6803 else if (WIFSTOPPED(sp->status))
6806 if (stopped) { /* stopped or done */
6807 int state = done ? JOBDONE : CONFIG_ASH_JOB_CONTROLTOPPED;
6809 if (jp->state != state) {
6810 TRACE(("Job %d: changing state from %d to %d\n",
6811 jp - jobtab + 1, jp->state, state));
6813 #ifdef CONFIG_ASH_JOB_CONTROL
6814 if (done && curjob == jp - jobtab + 1)
6815 curjob = 0; /* no current job */
6822 if (!rootshell || !iflag || (job && thisjob == job)) {
6823 core = WCOREDUMP(status);
6824 #ifdef CONFIG_ASH_JOB_CONTROL
6825 if (WIFSTOPPED(status))
6826 sig = WSTOPSIG(status);
6829 if (WIFEXITED(status))
6832 sig = WTERMSIG(status);
6834 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6836 out2fmt("%d: ", pid);
6837 #ifdef CONFIG_ASH_JOB_CONTROL
6838 if (sig == SIGTSTP && rootshell && iflag)
6839 out2fmt("%%%ld ", (long) (job - jobtab + 1));
6841 if (sig < NSIG && sys_siglist[sig])
6842 out2str(sys_siglist[sig]);
6844 out2fmt("Signal %d", sig);
6846 out2str(" - core dumped");
6849 TRACE(("Not printing status: status=%d, sig=%d\n", status, sig));
6852 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell,
6855 thisjob->changed = 1;
6864 * return 1 if there are stopped jobs, otherwise 0
6866 static int stoppedjobs(void)
6873 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6876 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED) {
6877 out2str("You have stopped jobs.\n");
6887 * Return a string identifying a command (to be printed by the
6891 static char *cmdnextc;
6892 static int cmdnleft;
6894 #define MAXCMDTEXT 200
6896 static void cmdputs(const char *s)
6907 while ((c = *p++) != '\0') {
6910 else if (c == CTLVAR) {
6915 } else if (c == '=' && subtype != 0) {
6916 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
6918 } else if (c == CTLENDVAR) {
6920 } else if (c == CTLBACKQ || c == CTLBACKQ + CTLQUOTE)
6921 cmdnleft++; /* ignore it */
6924 if (--cmdnleft <= 0) {
6934 #define CMDTXT_TABLE
6937 * To collect a lot of redundant code in cmdtxt() case statements, we
6938 * implement a mini language here. Each type of node struct has an
6939 * associated instruction sequence that operates on its members via
6940 * their offsets. The instruction are pack in unsigned chars with
6941 * format IIDDDDDE where the bits are
6942 * I : part of the instruction opcode, which are
6943 * 00 : member is a pointer to another node -- process it recursively
6944 * 40 : member is a pointer to a char string -- output it
6945 * 80 : output the string whose index is stored in the data field
6946 * CC : flag signaling that this case needs external processing
6947 * D : data - either the (shifted) index of a fixed string to output or
6948 * the actual offset of the member to operate on in the struct
6949 * (since we assume bit 0 is set, the offset is not shifted)
6950 * E : flag signaling end of instruction sequence
6952 * WARNING: In order to handle larger offsets for 64bit archs, this code
6953 * assumes that no offset can be an odd number and stores the
6954 * end-of-instructions flag in bit 0.
6957 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
6958 #define CMDTXT_CHARPTR 0x40
6959 #define CMDTXT_STRING 0x80
6960 #define CMDTXT_SPECIAL 0xC0
6961 #define CMDTXT_OFFSETMASK 0x3E
6963 static const char *const cmdtxt_strings[] = {
6964 /* 0 1 2 3 4 5 6 7 */
6965 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
6966 /* 8 9 10 11 12 13 */
6967 "while ", "; do ", "; done", "until ", "for ", " in ...",
6969 "case ", "???", "() ...", "<<..."
6972 static const char *const redir_strings[] = {
6973 ">", "<", "<>", ">>", ">|", ">&", "<&"
6976 static const unsigned char cmdtxt_ops[] = {
6977 #define CMDTXT_NSEMI 0
6978 offsetof(union node, nbinary.ch1),
6980 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6981 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
6982 #define CMDTXT_NPIPE (CMDTXT_NCMD)
6983 #define CMDTXT_NCASE (CMDTXT_NCMD)
6984 #define CMDTXT_NTO (CMDTXT_NCMD)
6985 #define CMDTXT_NFROM (CMDTXT_NCMD)
6986 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
6987 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
6988 #define CMDTXT_NTOOV (CMDTXT_NCMD)
6989 #define CMDTXT_NTOFD (CMDTXT_NCMD)
6990 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
6992 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
6993 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
6994 offsetof(union node, nredir.n) | CMDTXT_NOMORE,
6995 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
6996 (1 * 2) | CMDTXT_STRING,
6997 offsetof(union node, nredir.n),
6998 (2 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6999 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7000 offsetof(union node, nbinary.ch1),
7001 (3 * 2) | CMDTXT_STRING,
7002 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
7003 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7004 offsetof(union node, nbinary.ch1),
7005 (4 * 2) | CMDTXT_STRING,
7006 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
7007 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7008 (5 * 2) | CMDTXT_STRING,
7009 offsetof(union node, nif.test),
7010 (6 * 2) | CMDTXT_STRING,
7011 offsetof(union node, nif.ifpart),
7012 (7 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7013 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7014 (8 * 2) | CMDTXT_STRING,
7015 offsetof(union node, nbinary.ch1),
7016 (9 * 2) | CMDTXT_STRING,
7017 offsetof(union node, nbinary.ch2),
7018 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7019 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7020 (11 * 2) | CMDTXT_STRING,
7021 offsetof(union node, nbinary.ch1),
7022 (9 * 2) | CMDTXT_STRING,
7023 offsetof(union node, nbinary.ch2),
7024 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7025 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7026 (12 * 2) | CMDTXT_STRING,
7027 offsetof(union node, nfor.var) | CMDTXT_CHARPTR,
7028 (13 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7029 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7030 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7031 (15 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7032 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7033 offsetof(union node, narg.text) | CMDTXT_CHARPTR,
7034 (16 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7035 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7036 offsetof(union node, narg.text) | CMDTXT_CHARPTR | CMDTXT_NOMORE,
7037 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7038 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7039 (17 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
7042 #if CMDTXT_NXHERE != 36
7043 #error CMDTXT_NXHERE
7046 static const unsigned char cmdtxt_ops_index[26] = {
7075 static void cmdtxt(const union node *n)
7082 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7083 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7085 if (*p & CMDTXT_STRING) { /* output fixed string */
7086 cmdputs(cmdtxt_strings
7087 [((int) (*p & CMDTXT_OFFSETMASK) >> 1)]);
7089 const char *pf = ((const char *) n)
7090 + ((int) (*p & CMDTXT_OFFSETMASK));
7092 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7093 cmdputs(*((const char **) pf));
7094 } else { /* output field */
7095 cmdtxt(*((const union node **) pf));
7098 } while (!(*p++ & CMDTXT_NOMORE));
7099 } else if (n->type == NCMD) {
7102 for (np = n->ncmd.args; np; np = np->narg.next) {
7107 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
7111 } else if (n->type == NPIPE) {
7112 struct nodelist *lp;
7114 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7119 } else if (n->type == NCASE) {
7120 cmdputs(cmdtxt_strings[14]);
7121 cmdputs(n->ncase.expr->narg.text);
7122 cmdputs(cmdtxt_strings[13]);
7124 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7125 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7130 assert((n->type >= NTO) && (n->type <= NFROMFD));
7133 p = redir_strings[n->type - NTO];
7134 if (n->nfile.fd != ('>' == *p)) {
7135 s[0] = n->nfile.fd + '0';
7140 if (n->type >= NTOFD) {
7141 s[0] = n->ndup.dupfd + '0';
7145 cmdtxt(n->nfile.fname);
7149 #else /* CMDTXT_TABLE */
7150 static void cmdtxt(const union node *n)
7153 struct nodelist *lp;
7162 cmdtxt(n->nbinary.ch1);
7164 cmdtxt(n->nbinary.ch2);
7167 cmdtxt(n->nbinary.ch1);
7169 cmdtxt(n->nbinary.ch2);
7172 cmdtxt(n->nbinary.ch1);
7174 cmdtxt(n->nbinary.ch2);
7177 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7185 cmdtxt(n->nredir.n);
7190 cmdtxt(n->nredir.n);
7194 cmdtxt(n->nif.test);
7196 cmdtxt(n->nif.ifpart);
7205 cmdtxt(n->nbinary.ch1);
7207 cmdtxt(n->nbinary.ch2);
7212 cmdputs(n->nfor.var);
7217 cmdputs(n->ncase.expr->narg.text);
7221 cmdputs(n->narg.text);
7225 for (np = n->ncmd.args; np; np = np->narg.next) {
7230 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
7236 cmdputs(n->narg.text);
7267 if (n->nfile.fd != i) {
7268 s[0] = n->nfile.fd + '0';
7273 if (n->type == NTOFD || n->type == NFROMFD) {
7274 s[0] = n->ndup.dupfd + '0';
7278 cmdtxt(n->nfile.fname);
7290 #endif /* CMDTXT_TABLE */
7292 static char *commandtext(const union node *n)
7296 cmdnextc = name = xmalloc(MAXCMDTEXT);
7297 cmdnleft = MAXCMDTEXT - 4;
7304 static void waitonint(int sig)
7309 #ifdef CONFIG_ASH_MAIL
7312 * Routines to check for mail.
7316 #define MAXMBOXES 10
7319 static int nmboxes; /* number of mailboxes */
7320 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7325 * Print appropriate message(s) if mail has arrived. If the argument is
7326 * nozero, then the value of MAIL has changed, so we just update the
7330 static void chkmail(int silent)
7336 struct stackmark smark;
7343 setstackmark(&smark);
7344 mpath = mpathset()? mpathval() : mailval();
7345 for (i = 0; i < nmboxes; i++) {
7346 p = padvance(&mpath, nullstr);
7351 for (q = p; *q; q++);
7356 q[-1] = '\0'; /* delete trailing '/' */
7357 if (stat(p, &statb) < 0)
7359 if (statb.st_size > mailtime[i] && !silent) {
7360 out2fmt(snlfmt, pathopt ? pathopt : "you have mail");
7362 mailtime[i] = statb.st_size;
7365 popstackmark(&smark);
7368 #endif /* CONFIG_ASH_MAIL */
7373 static short profile_buf[16384];
7377 static int isloginsh = 0;
7379 static void read_profile(const char *);
7380 static void cmdloop(int);
7381 static void options(int);
7382 static void setoption(int, int);
7383 static void procargs(int, char **);
7387 * Main routine. We initialize things, parse the arguments, execute
7388 * profiles if we're a login shell, and then call cmdloop to execute
7389 * commands. The setjmp call sets up the location to jump to when an
7390 * exception occurs. When an exception occurs the variable "state"
7391 * is used to figure out how far we had gotten.
7394 int ash_main(int argc, char **argv)
7396 struct jmploc jmploc;
7397 struct stackmark smark;
7401 BLTINCMD = find_builtin("builtin");
7402 EXECCMD = find_builtin("exec");
7403 EVALCMD = find_builtin("eval");
7405 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7411 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7413 #if defined(linux) || defined(__GNU__)
7414 signal(SIGCHLD, SIG_DFL);
7417 if (setjmp(jmploc.loc)) {
7420 * When a shell procedure is executed, we raise the
7421 * exception EXSHELLPROC to clean up before executing
7422 * the shell procedure.
7424 if (exception == EXSHELLPROC) {
7430 if (exception == EXEXEC) {
7431 exitstatus = exerrno;
7432 } else if (exception == EXERROR) {
7435 if (state == 0 || iflag == 0 || !rootshell)
7436 exitshell(exitstatus);
7439 if (exception == EXINT) {
7442 popstackmark(&smark);
7443 FORCEINTON; /* enable interrupts */
7446 else if (state == 2)
7448 else if (state == 3)
7456 trputs("Shell args: ");
7462 setstackmark(&smark);
7463 procargs(argc, argv);
7464 if (argv[0] && argv[0][0] == '-')
7468 read_profile("/etc/profile");
7471 read_profile(".profile");
7476 if (getuid() == geteuid() && getgid() == getegid()) {
7478 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7480 read_profile(shinit);
7487 if (sflag == 0 || minusc) {
7488 static const char sigs[] = {
7489 SIGINT, SIGQUIT, SIGHUP,
7496 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7499 for (i = 0; i < SIGSSIZE; i++)
7504 evalstring(minusc, 0);
7506 if (sflag || minusc == NULL) {
7507 state4: /* XXX ??? - why isn't this before the "if" statement */
7513 exitshell(exitstatus);
7519 * Read and execute commands. "Top" is nonzero for the top level command
7520 * loop; it turns on prompting if the shell is interactive.
7523 static void cmdloop(int top)
7526 struct stackmark smark;
7530 TRACE(("cmdloop(%d) called\n", top));
7531 setstackmark(&smark);
7539 #ifdef CONFIG_ASH_MAIL
7544 n = parsecmd(inter);
7545 /* showtree(n); DEBUG */
7547 if (!top || numeof >= 50)
7549 if (!stoppedjobs()) {
7552 out2str("\nUse \"exit\" to leave shell.\n");
7555 } else if (n != NULL && nflag == 0) {
7556 job_warning = (job_warning == 2) ? 1 : 0;
7560 popstackmark(&smark);
7561 setstackmark(&smark);
7562 if (evalskip == SKIPFILE) {
7567 popstackmark(&smark);
7573 * Read /etc/profile or .profile. Return on error.
7576 static void read_profile(const char *name)
7583 if ((fd = open(name, O_RDONLY)) >= 0)
7588 /* -q turns off -x and -v just when executing init files */
7589 /* Note: Might do a little redundant work, but reduces code size. */
7604 * Read a file containing shell functions.
7607 static void readcmdfile(const char *name)
7612 if ((fd = open(name, O_RDONLY)) >= 0)
7615 error("Can't open %s", name);
7624 * Take commands from a file. To be compatable we should do a path
7625 * search for the file, which is necessary to find sub-commands.
7628 static inline char *find_dot_file(char *mybasename)
7631 const char *path = pathval();
7634 /* don't try this for absolute or relative paths */
7635 if (strchr(mybasename, '/'))
7638 while ((fullname = padvance(&path, mybasename)) != NULL) {
7639 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7641 * Don't bother freeing here, since it will
7642 * be freed by the caller.
7646 stunalloc(fullname);
7649 /* not found in the PATH */
7650 error("%s: not found", mybasename);
7654 static int dotcmd(int argc, char **argv)
7657 volatile struct shparam saveparam;
7661 for (sp = cmdenviron; sp; sp = sp->next)
7662 setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
7664 if (argc >= 2) { /* That's what SVR2 does */
7666 struct stackmark smark;
7668 setstackmark(&smark);
7669 fullname = find_dot_file(argv[1]);
7672 saveparam = shellparam;
7673 shellparam.malloc = 0;
7674 shellparam.nparam = argc - 2;
7675 shellparam.p = argv + 2;
7678 setinputfile(fullname, 1);
7679 commandname = fullname;
7684 freeparam(&shellparam);
7685 shellparam = saveparam;
7688 popstackmark(&smark);
7694 static int exitcmd(int argc, char **argv)
7699 exitstatus = number(argv[1]);
7701 exitstatus = oexitstatus;
7702 exitshell(exitstatus);
7706 static pointer stalloc(int nbytes)
7710 nbytes = ALIGN(nbytes);
7711 if (nbytes > stacknleft) {
7713 struct stack_block *sp;
7716 if (blocksize < MINSIZE)
7717 blocksize = MINSIZE;
7719 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7721 stacknxt = sp->space;
7722 stacknleft = blocksize;
7728 stacknleft -= nbytes;
7733 static void stunalloc(pointer p)
7736 if (p == NULL) { /*DEBUG */
7737 write(2, "stunalloc\n", 10);
7741 if (!(stacknxt >= (char *) p && (char *) p >= stackp->space)) {
7744 stacknleft += stacknxt - (char *) p;
7749 static void setstackmark(struct stackmark *mark)
7751 mark->stackp = stackp;
7752 mark->stacknxt = stacknxt;
7753 mark->stacknleft = stacknleft;
7754 mark->marknext = markp;
7759 static void popstackmark(struct stackmark *mark)
7761 struct stack_block *sp;
7764 markp = mark->marknext;
7765 while (stackp != mark->stackp) {
7770 stacknxt = mark->stacknxt;
7771 stacknleft = mark->stacknleft;
7777 * When the parser reads in a string, it wants to stick the string on the
7778 * stack and only adjust the stack pointer when it knows how big the
7779 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7780 * of space on top of the stack and stackblocklen returns the length of
7781 * this block. Growstackblock will grow this space by at least one byte,
7782 * possibly moving it (like realloc). Grabstackblock actually allocates the
7783 * part of the block that has been used.
7786 static void growstackblock(void)
7789 int newlen = ALIGN(stacknleft * 2 + 100);
7790 char *oldspace = stacknxt;
7791 int oldlen = stacknleft;
7792 struct stack_block *sp;
7793 struct stack_block *oldstackp;
7795 if (stacknxt == stackp->space && stackp != &stackbase) {
7800 sp = xrealloc((pointer) sp,
7801 sizeof(struct stack_block) - MINSIZE + newlen);
7804 stacknxt = sp->space;
7805 stacknleft = newlen;
7807 /* Stack marks pointing to the start of the old block
7808 * must be relocated to point to the new block
7810 struct stackmark *xmark;
7813 while (xmark != NULL && xmark->stackp == oldstackp) {
7814 xmark->stackp = stackp;
7815 xmark->stacknxt = stacknxt;
7816 xmark->stacknleft = stacknleft;
7817 xmark = xmark->marknext;
7822 p = stalloc(newlen);
7823 memcpy(p, oldspace, oldlen);
7824 stacknxt = p; /* free the space */
7825 stacknleft += newlen; /* we just allocated */
7831 static inline void grabstackblock(int len)
7841 * The following routines are somewhat easier to use that the above.
7842 * The user declares a variable of type STACKSTR, which may be declared
7843 * to be a register. The macro STARTSTACKSTR initializes things. Then
7844 * the user uses the macro STPUTC to add characters to the string. In
7845 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7846 * grown as necessary. When the user is done, she can just leave the
7847 * string there and refer to it using stackblock(). Or she can allocate
7848 * the space for it using grabstackstr(). If it is necessary to allow
7849 * someone else to use the stack temporarily and then continue to grow
7850 * the string, the user should use grabstack to allocate the space, and
7851 * then call ungrabstr(p) to return to the previous mode of operation.
7853 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7854 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7855 * is space for at least one character.
7859 static char *growstackstr(void)
7861 int len = stackblocksize();
7863 if (herefd >= 0 && len >= 1024) {
7864 xwrite(herefd, stackblock(), len);
7865 sstrnleft = len - 1;
7866 return stackblock();
7869 sstrnleft = stackblocksize() - len - 1;
7870 return stackblock() + len;
7875 * Called from CHECKSTRSPACE.
7878 static char *makestrspace(size_t newlen)
7880 int len = stackblocksize() - sstrnleft;
7884 sstrnleft = stackblocksize() - len;
7885 } while (sstrnleft < newlen);
7886 return stackblock() + len;
7891 static void ungrabstackstr(char *s, char *p)
7893 stacknleft += stacknxt - s;
7895 sstrnleft = stacknleft - (p - s);
7899 * Miscelaneous builtins.
7905 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
7906 typedef long rlim_t;
7912 * The read builtin. The -e option causes backslashes to escape the
7913 * following character.
7915 * This uses unbuffered input, which may be avoidable in some cases.
7918 static int readcmd(int argc, char **argv)
7933 while ((i = nextopt("p:r")) != '\0') {
7939 if (prompt && isatty(0)) {
7940 out2str(prompt); /* read without cmdedit */
7943 if (*(ap = argptr) == NULL)
7945 if ((ifs = bltinlookup("IFS")) == NULL)
7952 if (read(0, &c, 1) != 1) {
7964 if (!rflag && c == '\\') {
7970 if (startword && *ifs == ' ' && strchr(ifs, c)) {
7974 if (backslash && c == '\\') {
7975 if (read(0, &c, 1) != 1) {
7980 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
7982 setvar(*ap, stackblock(), 0);
7991 /* Remove trailing blanks */
7992 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
7994 setvar(*ap, stackblock(), 0);
7995 while (*++ap != NULL)
7996 setvar(*ap, nullstr, 0);
8002 static int umaskcmd(int argc, char **argv)
8004 static const char permuser[3] = "ugo";
8005 static const char permmode[3] = "rwx";
8006 static const short int permmask[] = {
8007 S_IRUSR, S_IWUSR, S_IXUSR,
8008 S_IRGRP, S_IWGRP, S_IXGRP,
8009 S_IROTH, S_IWOTH, S_IXOTH
8015 int symbolic_mode = 0;
8017 while (nextopt("S") != '\0') {
8026 if ((ap = *argptr) == NULL) {
8027 if (symbolic_mode) {
8031 for (i = 0; i < 3; i++) {
8036 for (j = 0; j < 3; j++) {
8037 if ((mask & permmask[3 * i + j]) == 0) {
8046 printf("%.4o\n", mask);
8049 if (is_digit((unsigned char) *ap)) {
8052 if (*ap >= '8' || *ap < '0')
8053 error("Illegal number: %s", argv[1]);
8054 mask = (mask << 3) + (*ap - '0');
8055 } while (*++ap != '\0');
8058 mask = ~mask & 0777;
8059 if (!parse_mode(ap, &mask)) {
8060 error("Illegal mode: %s", ap);
8062 umask(~mask & 0777);
8071 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8072 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8073 * ash by J.T. Conklin.
8081 short factor; /* multiply by to get rlim_{cur,max} values */
8084 static const struct limits limits[] = {
8086 {"time(seconds)", RLIMIT_CPU, 1},
8089 {"file(blocks)", RLIMIT_FSIZE, 512},
8092 {"data(kbytes)", RLIMIT_DATA, 1024},
8095 {"stack(kbytes)", RLIMIT_STACK, 1024},
8098 {"coredump(blocks)", RLIMIT_CORE, 512},
8101 {"memory(kbytes)", RLIMIT_RSS, 1024},
8103 #ifdef RLIMIT_MEMLOCK
8104 {"locked memory(kbytes)", RLIMIT_MEMLOCK, 1024},
8107 {"process(processes)", RLIMIT_NPROC, 1},
8109 #ifdef RLIMIT_NOFILE
8110 {"nofiles(descriptors)", RLIMIT_NOFILE, 1},
8113 {"vmemory(kbytes)", RLIMIT_VMEM, 1024},
8116 {"swap(kbytes)", RLIMIT_SWAP, 1024},
8121 static int ulimitcmd(int argc, char **argv)
8123 static const char unlimited_string[] = "unlimited";
8126 enum { SOFT = 0x1, HARD = 0x2 } how = SOFT | HARD;
8127 const struct limits *l;
8130 struct rlimit limit;
8134 while ((optc = nextopt("HSa"
8153 #ifdef RLIMIT_MEMLOCK
8159 #ifdef RLIMIT_NOFILE
8171 } else if (optc == 'S') {
8173 } else if (optc == 'a') {
8180 for (l = limits; l->name; l++) {
8181 if (l->name[0] == what)
8183 if (l->name[1] == 'w' && what == 'w')
8187 set = *argptr ? 1 : 0;
8191 if (all || argptr[1])
8192 error("too many arguments");
8193 if (strcmp(p, unlimited_string) == 0)
8194 val = RLIM_INFINITY;
8198 while ((c = *p++) >= '0' && c <= '9') {
8199 val = (val * 10) + (long) (c - '0');
8200 if (val < (rlim_t) 0)
8204 error("bad number");
8210 for (l = limits; l->name; l++) {
8211 printf("%-20s ", l->name);
8212 getrlimit(l->cmd, &limit);
8215 val = limit.rlim_cur;
8216 else if (how & HARD)
8217 val = limit.rlim_max;
8219 if (val == RLIM_INFINITY)
8220 puts(unlimited_string);
8223 printf("%lld\n", (long long) val);
8236 getrlimit(l->cmd, &limit);
8238 limit.rlim_max = val;
8240 limit.rlim_cur = val;
8241 if (setrlimit(l->cmd, &limit) < 0)
8242 error("error setting limit (%m)");
8247 * prefix -- see if pfx is a prefix of string.
8250 static int prefix(char const *pfx, char const *string)
8253 if (*pfx++ != *string++)
8260 * Return true if s is a string of digits, and save munber in intptr
8264 static int is_number(const char *p, int *intptr)
8272 ret += digit_val(*p);
8274 } while (*p != '\0');
8281 * Convert a string of digits to an integer, printing an error message on
8285 static int number(const char *s)
8289 if (!is_number(s, &i))
8290 error("Illegal number: %s", s);
8295 * Produce a possibly single quoted string suitable as input to the shell.
8296 * The return string is allocated on the stack.
8299 static char *single_quote(const char *s)
8307 size_t len1, len1p, len2, len2p;
8309 len1 = strcspn(s, "'");
8310 len2 = strspn(s + len1, "'");
8312 len1p = len1 ? len1 + 2 : len1;
8313 len2p = len2 + ((len2 < 2) ? len2 : 2);
8315 CHECKSTRSPACE(len1p + len2p + 1, p);
8320 memcpy(p + 1, s, len1);
8328 memcpy(q + 1, s, len2);
8331 } else if (len2 == 1) {
8337 STADJUST(len1p + len2p, p);
8342 return grabstackstr(p);
8346 * Like strdup but works with the ash stack.
8349 static char *sstrdup(const char *p)
8351 size_t len = strlen(p) + 1;
8353 return memcpy(stalloc(len), p, len);
8358 * Routine for dealing with parsed shell commands.
8362 static void sizenodelist(const struct nodelist *);
8363 static struct nodelist *copynodelist(const struct nodelist *);
8364 static char *nodexstrdup(const char *);
8366 #define CALCSIZE_TABLE
8367 #define COPYNODE_TABLE
8368 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8370 * To collect a lot of redundant code in case statements for copynode()
8371 * and calcsize(), we implement a mini language here. Each type of node
8372 * struct has an associated instruction sequence that operates on its
8373 * members via their offsets. The instruction are pack in unsigned chars
8374 * with format IIDDDDDE where the bits are
8375 * I : part of the instruction opcode, which are
8376 * 00 : member is a pointer to another node
8377 * 40 : member is an integer
8378 * 80 : member is a pointer to a nodelist
8379 * CC : member is a pointer to a char string
8380 * D : data - the actual offset of the member to operate on in the struct
8381 * (since we assume bit 0 is set, it is not shifted)
8382 * E : flag signaling end of instruction sequence
8384 * WARNING: In order to handle larger offsets for 64bit archs, this code
8385 * assumes that no offset can be an odd number and stores the
8386 * end-of-instructions flag in bit 0.
8389 #define NODE_INTEGER 0x40
8390 #define NODE_NODELIST 0x80
8391 #define NODE_CHARPTR 0xC0
8392 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned) */
8393 #define NODE_MBRMASK 0xC0
8394 #define NODE_OFFSETMASK 0x3E
8396 static const unsigned char copynode_ops[35] = {
8397 #define COPYNODE_OPS0 0
8398 offsetof(union node, nbinary.ch2),
8399 offsetof(union node, nbinary.ch1) | NODE_NOMORE,
8400 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8401 offsetof(union node, ncmd.redirect),
8402 offsetof(union node, ncmd.args),
8403 offsetof(union node, ncmd.assign),
8404 offsetof(union node, ncmd.backgnd) | NODE_INTEGER | NODE_NOMORE,
8405 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8406 offsetof(union node, npipe.cmdlist) | NODE_NODELIST,
8407 offsetof(union node, npipe.backgnd) | NODE_INTEGER | NODE_NOMORE,
8408 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8409 offsetof(union node, nredir.redirect),
8410 offsetof(union node, nredir.n) | NODE_NOMORE,
8411 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8412 offsetof(union node, nif.elsepart),
8413 offsetof(union node, nif.ifpart),
8414 offsetof(union node, nif.test) | NODE_NOMORE,
8415 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8416 offsetof(union node, nfor.var) | NODE_CHARPTR,
8417 offsetof(union node, nfor.body),
8418 offsetof(union node, nfor.args) | NODE_NOMORE,
8419 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8420 offsetof(union node, ncase.cases),
8421 offsetof(union node, ncase.expr) | NODE_NOMORE,
8422 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8423 offsetof(union node, nclist.body),
8424 offsetof(union node, nclist.pattern),
8425 offsetof(union node, nclist.next) | NODE_NOMORE,
8426 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8427 offsetof(union node, narg.backquote) | NODE_NODELIST,
8428 offsetof(union node, narg.text) | NODE_CHARPTR,
8429 offsetof(union node, narg.next) | NODE_NOMORE,
8430 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8431 offsetof(union node, nfile.fname),
8432 offsetof(union node, nfile.fd) | NODE_INTEGER,
8433 offsetof(union node, nfile.next) | NODE_NOMORE,
8434 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8435 offsetof(union node, ndup.vname),
8436 offsetof(union node, ndup.dupfd) | NODE_INTEGER,
8437 offsetof(union node, ndup.fd) | NODE_INTEGER,
8438 offsetof(union node, ndup.next) | NODE_NOMORE,
8439 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8440 offsetof(union node, nhere.doc),
8441 offsetof(union node, nhere.fd) | NODE_INTEGER,
8442 offsetof(union node, nhere.next) | NODE_NOMORE,
8443 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8444 offsetof(union node, nnot.com) | NODE_NOMORE,
8447 #if COPYNODE_OPS12 != 34
8448 #error COPYNODE_OPS12 is incorrect
8451 static const unsigned char copynode_ops_index[26] = {
8452 COPYNODE_OPS0, /* NSEMI */
8453 COPYNODE_OPS1, /* NCMD */
8454 COPYNODE_OPS2, /* NPIPE */
8455 COPYNODE_OPS3, /* NREDIR */
8456 COPYNODE_OPS3, /* NBACKGND */
8457 COPYNODE_OPS3, /* NSUBSHELL */
8458 COPYNODE_OPS0, /* NAND */
8459 COPYNODE_OPS0, /* NOR */
8460 COPYNODE_OPS4, /* NIF */
8461 COPYNODE_OPS0, /* NWHILE */
8462 COPYNODE_OPS0, /* NUNTIL */
8463 COPYNODE_OPS5, /* NFOR */
8464 COPYNODE_OPS6, /* NCASE */
8465 COPYNODE_OPS7, /* NCLIST */
8466 COPYNODE_OPS8, /* NDEFUN */
8467 COPYNODE_OPS8, /* NARG */
8468 COPYNODE_OPS9, /* NTO */
8469 COPYNODE_OPS9, /* NFROM */
8470 COPYNODE_OPS9, /* NFROMTO */
8471 COPYNODE_OPS9, /* NAPPEND */
8472 COPYNODE_OPS9, /* NTOOV */
8473 COPYNODE_OPS10, /* NTOFD */
8474 COPYNODE_OPS10, /* NFROMFD */
8475 COPYNODE_OPS11, /* NHERE */
8476 COPYNODE_OPS11, /* NXHERE */
8477 COPYNODE_OPS12, /* NNOT */
8480 #if NODE_CHARPTR != NODE_MBRMASK
8481 #error NODE_CHARPTR != NODE_MBRMASK!!!
8483 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8485 #ifdef COPYNODE_TABLE
8486 static union node *copynode(const union node *n)
8489 const unsigned char *p;
8495 new->type = n->type;
8496 funcblock = (char *) funcblock + (int) nodesize[n->type];
8497 p = copynode_ops + (int) copynode_ops_index[n->type];
8499 char *nn = ((char *) new) + ((int) (*p & NODE_OFFSETMASK));
8500 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8502 if (!(*p & NODE_MBRMASK)) { /* standard node */
8503 *((union node **) nn) = copynode(*((const union node **) no));
8504 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8505 *((const char **) nn) = nodexstrdup(*((const char **) no));
8506 } else if (*p & NODE_NODELIST) { /* nodelist */
8507 *((struct nodelist **) nn)
8508 = copynodelist(*((const struct nodelist **) no));
8509 } else { /* integer */
8510 *((int *) nn) = *((int *) no);
8512 } while (!(*p++ & NODE_NOMORE));
8515 #else /* COPYNODE_TABLE */
8516 static union node *copynode(const union node *n)
8523 funcblock = (char *) funcblock + nodesize[n->type];
8530 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8531 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8534 new->ncmd.redirect = copynode(n->ncmd.redirect);
8535 new->ncmd.args = copynode(n->ncmd.args);
8536 new->ncmd.assign = copynode(n->ncmd.assign);
8537 new->ncmd.backgnd = n->ncmd.backgnd;
8540 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8541 new->npipe.backgnd = n->npipe.backgnd;
8546 new->nredir.redirect = copynode(n->nredir.redirect);
8547 new->nredir.n = copynode(n->nredir.n);
8550 new->nif.elsepart = copynode(n->nif.elsepart);
8551 new->nif.ifpart = copynode(n->nif.ifpart);
8552 new->nif.test = copynode(n->nif.test);
8555 new->nfor.var = nodexstrdup(n->nfor.var);
8556 new->nfor.body = copynode(n->nfor.body);
8557 new->nfor.args = copynode(n->nfor.args);
8560 new->ncase.cases = copynode(n->ncase.cases);
8561 new->ncase.expr = copynode(n->ncase.expr);
8564 new->nclist.body = copynode(n->nclist.body);
8565 new->nclist.pattern = copynode(n->nclist.pattern);
8566 new->nclist.next = copynode(n->nclist.next);
8570 new->narg.backquote = copynodelist(n->narg.backquote);
8571 new->narg.text = nodexstrdup(n->narg.text);
8572 new->narg.next = copynode(n->narg.next);
8579 new->nfile.fname = copynode(n->nfile.fname);
8580 new->nfile.fd = n->nfile.fd;
8581 new->nfile.next = copynode(n->nfile.next);
8585 new->ndup.vname = copynode(n->ndup.vname);
8586 new->ndup.dupfd = n->ndup.dupfd;
8587 new->ndup.fd = n->ndup.fd;
8588 new->ndup.next = copynode(n->ndup.next);
8592 new->nhere.doc = copynode(n->nhere.doc);
8593 new->nhere.fd = n->nhere.fd;
8594 new->nhere.next = copynode(n->nhere.next);
8597 new->nnot.com = copynode(n->nnot.com);
8600 new->type = n->type;
8603 #endif /* COPYNODE_TABLE */
8605 #ifdef CALCSIZE_TABLE
8606 static void calcsize(const union node *n)
8608 const unsigned char *p;
8612 funcblocksize += (int) nodesize[n->type];
8614 p = copynode_ops + (int) copynode_ops_index[n->type];
8616 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8618 if (!(*p & NODE_MBRMASK)) { /* standard node */
8619 calcsize(*((const union node **) no));
8620 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8621 funcstringsize += strlen(*((const char **) no)) + 1;
8622 } else if (*p & NODE_NODELIST) { /* nodelist */
8623 sizenodelist(*((const struct nodelist **) no));
8624 } /* else integer -- ignore */
8625 } while (!(*p++ & NODE_NOMORE));
8627 #else /* CALCSIZE_TABLE */
8628 static void calcsize(const union node *n)
8632 funcblocksize += nodesize[n->type];
8639 calcsize(n->nbinary.ch2);
8640 calcsize(n->nbinary.ch1);
8643 calcsize(n->ncmd.redirect);
8644 calcsize(n->ncmd.args);
8645 calcsize(n->ncmd.assign);
8648 sizenodelist(n->npipe.cmdlist);
8653 calcsize(n->nredir.redirect);
8654 calcsize(n->nredir.n);
8657 calcsize(n->nif.elsepart);
8658 calcsize(n->nif.ifpart);
8659 calcsize(n->nif.test);
8662 funcstringsize += strlen(n->nfor.var) + 1;
8663 calcsize(n->nfor.body);
8664 calcsize(n->nfor.args);
8667 calcsize(n->ncase.cases);
8668 calcsize(n->ncase.expr);
8671 calcsize(n->nclist.body);
8672 calcsize(n->nclist.pattern);
8673 calcsize(n->nclist.next);
8677 sizenodelist(n->narg.backquote);
8678 funcstringsize += strlen(n->narg.text) + 1;
8679 calcsize(n->narg.next);
8686 calcsize(n->nfile.fname);
8687 calcsize(n->nfile.next);
8691 calcsize(n->ndup.vname);
8692 calcsize(n->ndup.next);
8696 calcsize(n->nhere.doc);
8697 calcsize(n->nhere.next);
8700 calcsize(n->nnot.com);
8704 #endif /* CALCSIZE_TABLE */
8706 static void sizenodelist(const struct nodelist *lp)
8709 funcblocksize += ALIGN(sizeof(struct nodelist));
8716 static struct nodelist *copynodelist(const struct nodelist *lp)
8718 struct nodelist *start;
8719 struct nodelist **lpp;
8724 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8725 (*lpp)->n = copynode(lp->n);
8727 lpp = &(*lpp)->next;
8734 static char *nodexstrdup(const char *s)
8737 char *q = funcstring;
8738 char *rtn = funcstring;
8740 while ((*q++ = *p++) != '\0')
8746 #ifdef CONFIG_ASH_GETOPTS
8747 static int getopts(char *, char *, char **, int *, int *);
8751 * Process the shell command line arguments.
8754 static void procargs(int argc, char **argv)
8761 for (i = 0; i < NOPTS; i++)
8764 if (*argptr == NULL && minusc == NULL)
8766 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8770 for (i = 0; i < NOPTS; i++)
8771 if (optent_val(i) == 2)
8774 if (sflag == 0 && minusc == NULL) {
8775 commandname = argv[0];
8777 setinputfile(arg0, 0);
8780 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8781 if (argptr && minusc && *argptr)
8784 shellparam.p = argptr;
8785 shellparam.optind = 1;
8786 shellparam.optoff = -1;
8787 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8789 shellparam.nparam++;
8798 * Process shell options. The global variable argptr contains a pointer
8799 * to the argument list; we advance it past the options.
8802 static inline void minus_o(const char *name, int val)
8807 out1str("Current option settings\n");
8808 for (i = 0; i < NOPTS; i++)
8809 printf("%-16s%s\n", optent_name(optlist[i]),
8810 optent_val(i) ? "on" : "off");
8812 for (i = 0; i < NOPTS; i++)
8813 if (equal(name, optent_name(optlist[i]))) {
8814 setoption(optent_letter(optlist[i]), val);
8817 error("Illegal option -o %s", name);
8822 static void options(int cmdline)
8830 while ((p = *argptr) != NULL) {
8832 if ((c = *p++) == '-') {
8834 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8836 /* "-" means turn off -x and -v */
8839 /* "--" means reset params */
8840 else if (*argptr == NULL)
8843 break; /* "-" or "--" terminates options */
8845 } else if (c == '+') {
8851 while ((c = *p++) != '\0') {
8852 if (c == 'c' && cmdline) {
8855 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8859 if (q == NULL || minusc != NULL)
8860 error("Bad -c option");
8865 } else if (c == 'o') {
8866 minus_o(*argptr, val);
8869 } else if (cmdline && (c == '-')) { /* long options */
8870 if (strcmp(p, "login") == 0)
8881 static void setoption(int flag, int val)
8885 for (i = 0; i < NOPTS; i++)
8886 if (optent_letter(optlist[i]) == flag) {
8887 optent_val(i) = val;
8889 /* #%$ hack for ksh semantics */
8892 else if (flag == 'E')
8897 error("Illegal option -%c", flag);
8904 * Set the shell parameters.
8907 static void setparam(char **argv)
8913 for (nparam = 0; argv[nparam]; nparam++);
8914 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
8916 *ap++ = xstrdup(*argv++);
8919 freeparam(&shellparam);
8920 shellparam.malloc = 1;
8921 shellparam.nparam = nparam;
8922 shellparam.p = newparam;
8923 shellparam.optind = 1;
8924 shellparam.optoff = -1;
8929 * Free the list of positional parameters.
8932 static void freeparam(volatile struct shparam *param)
8936 if (param->malloc) {
8937 for (ap = param->p; *ap; ap++)
8946 * The shift builtin command.
8949 static int shiftcmd(int argc, char **argv)
8956 n = number(argv[1]);
8957 if (n > shellparam.nparam)
8958 error("can't shift that many");
8960 shellparam.nparam -= n;
8961 for (ap1 = shellparam.p; --n >= 0; ap1++) {
8962 if (shellparam.malloc)
8966 while ((*ap2++ = *ap1++) != NULL);
8967 shellparam.optind = 1;
8968 shellparam.optoff = -1;
8976 * The set command builtin.
8979 static int setcmd(int argc, char **argv)
8982 return showvarscmd(argc, argv);
8986 if (*argptr != NULL) {
8994 static void getoptsreset(const char *value)
8996 shellparam.optind = number(value);
8997 shellparam.optoff = -1;
9000 #ifdef CONFIG_LOCALE_SUPPORT
9001 static void change_lc_all(const char *value)
9003 if (value != 0 && *value != 0)
9004 setlocale(LC_ALL, value);
9007 static void change_lc_ctype(const char *value)
9009 if (value != 0 && *value != 0)
9010 setlocale(LC_CTYPE, value);
9015 #ifdef CONFIG_ASH_GETOPTS
9017 * The getopts builtin. Shellparam.optnext points to the next argument
9018 * to be processed. Shellparam.optptr points to the next character to
9019 * be processed in the current argument. If shellparam.optnext is NULL,
9020 * then it's the first time getopts has been called.
9023 static int getoptscmd(int argc, char **argv)
9028 error("Usage: getopts optstring var [arg]");
9029 else if (argc == 3) {
9030 optbase = shellparam.p;
9031 if (shellparam.optind > shellparam.nparam + 1) {
9032 shellparam.optind = 1;
9033 shellparam.optoff = -1;
9037 if (shellparam.optind > argc - 2) {
9038 shellparam.optind = 1;
9039 shellparam.optoff = -1;
9043 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9044 &shellparam.optoff);
9048 * Safe version of setvar, returns 1 on success 0 on failure.
9051 static int setvarsafe(const char *name, const char *val, int flags)
9053 struct jmploc jmploc;
9054 struct jmploc *volatile savehandler = handler;
9061 if (setjmp(jmploc.loc))
9065 setvar(name, val, flags);
9067 handler = savehandler;
9072 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind,
9080 char **optnext = optfirst + *myoptind - 1;
9082 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9083 strlen(*(optnext - 1)) < *optoff)
9086 p = *(optnext - 1) + *optoff;
9087 if (p == NULL || *p == '\0') {
9088 /* Current word is done, advance */
9089 if (optnext == NULL)
9092 if (p == NULL || *p != '-' || *++p == '\0') {
9094 *myoptind = optnext - optfirst + 1;
9100 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9105 for (q = optstr; *q != c;) {
9107 if (optstr[0] == ':') {
9110 err |= setvarsafe("OPTARG", s, 0);
9112 out2fmt("Illegal option -%c\n", c);
9113 (void) unsetvar("OPTARG");
9123 if (*p == '\0' && (p = *optnext) == NULL) {
9124 if (optstr[0] == ':') {
9127 err |= setvarsafe("OPTARG", s, 0);
9130 out2fmt("No arg for -%c option\n", c);
9131 (void) unsetvar("OPTARG");
9139 setvarsafe("OPTARG", p, 0);
9142 setvarsafe("OPTARG", "", 0);
9143 *myoptind = optnext - optfirst + 1;
9150 *optoff = p ? p - *(optnext - 1) : -1;
9151 snprintf(s, sizeof(s), "%d", *myoptind);
9152 err |= setvarsafe("OPTIND", s, VNOFUNC);
9155 err |= setvarsafe(optvar, s, 0);
9166 * XXX - should get rid of. have all builtins use getopt(3). the
9167 * library getopt must have the BSD extension static variable "optreset"
9168 * otherwise it can't be used within the shell safely.
9170 * Standard option processing (a la getopt) for builtin routines. The
9171 * only argument that is passed to nextopt is the option string; the
9172 * other arguments are unnecessary. It return the character, or '\0' on
9176 static int nextopt(const char *optstring)
9182 if ((p = optptr) == NULL || *p == '\0') {
9184 if (p == NULL || *p != '-' || *++p == '\0')
9187 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9191 for (q = optstring; *q != c;) {
9193 error("Illegal option -%c", c);
9198 if (*p == '\0' && (p = *argptr++) == NULL)
9199 error("No arg for -%c option", c);
9207 static void flushall()
9215 static void out2fmt(const char *fmt, ...)
9220 vfprintf(stderr, fmt, ap);
9225 * Version of write which resumes after a signal is caught.
9228 static int xwrite(int fd, const char *buf, int nbytes)
9237 i = write(fd, buf, n);
9243 } else if (i == 0) {
9246 } else if (errno != EINTR) {
9254 * Shell command parser.
9257 #define EOFMARKLEN 79
9262 struct heredoc *next; /* next here document in list */
9263 union node *here; /* redirection node */
9264 char *eofmark; /* string indicating end of input */
9265 int striptabs; /* if set, strip leading tabs */
9268 static struct heredoc *heredoclist; /* list of here documents to read */
9269 static int parsebackquote; /* nonzero if we are inside backquotes */
9270 static int doprompt; /* if set, prompt the user */
9271 static int needprompt; /* true if interactive and at start of line */
9272 static int lasttoken; /* last token read */
9274 static char *wordtext; /* text of last word returned by readtoken */
9276 static struct nodelist *backquotelist;
9277 static union node *redirnode;
9278 static struct heredoc *heredoc;
9279 static int quoteflag; /* set if (part of) last token was quoted */
9280 static int startlinno; /* line # where last token started */
9283 static union node *list(int);
9284 static union node *andor(void);
9285 static union node *pipeline(void);
9286 static union node *command(void);
9287 static union node *simplecmd(union node **rpp, union node *redir);
9288 static void parsefname(void);
9289 static void parseheredoc(void);
9290 static char peektoken(void);
9291 static int readtoken(void);
9292 static int xxreadtoken(void);
9293 static int readtoken1(int, int, const char *, int);
9294 static int noexpand(char *);
9295 static void synexpect(int) __attribute__ ((noreturn));
9296 static void synerror(const char *) __attribute__ ((noreturn));
9297 static void setprompt(int);
9301 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9302 * valid parse tree indicating a blank line.)
9305 static union node *parsecmd(int interact)
9310 doprompt = interact;
9326 static union node *list(int nlflag)
9328 union node *n1, *n2, *n3;
9332 if (nlflag == 0 && peektoken())
9338 if (tok == TBACKGND) {
9339 if (n2->type == NCMD || n2->type == NPIPE) {
9340 n2->ncmd.backgnd = 1;
9341 } else if (n2->type == NREDIR) {
9342 n2->type = NBACKGND;
9344 n3 = (union node *) stalloc(sizeof(struct nredir));
9345 n3->type = NBACKGND;
9347 n3->nredir.redirect = NULL;
9354 n3 = (union node *) stalloc(sizeof(struct nbinary));
9356 n3->nbinary.ch1 = n1;
9357 n3->nbinary.ch2 = n2;
9381 pungetc(); /* push back EOF on input */
9394 static union node *andor()
9396 union node *n1, *n2, *n3;
9402 if ((t = readtoken()) == TAND) {
9404 } else if (t == TOR) {
9412 n3 = (union node *) stalloc(sizeof(struct nbinary));
9414 n3->nbinary.ch1 = n1;
9415 n3->nbinary.ch2 = n2;
9422 static union node *pipeline()
9424 union node *n1, *n2, *pipenode;
9425 struct nodelist *lp, *prev;
9429 TRACE(("pipeline: entered\n"));
9430 if (readtoken() == TNOT) {
9436 if (readtoken() == TPIPE) {
9437 pipenode = (union node *) stalloc(sizeof(struct npipe));
9438 pipenode->type = NPIPE;
9439 pipenode->npipe.backgnd = 0;
9440 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9441 pipenode->npipe.cmdlist = lp;
9445 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9449 } while (readtoken() == TPIPE);
9455 n2 = (union node *) stalloc(sizeof(struct nnot));
9465 static union node *command(void)
9467 union node *n1, *n2;
9468 union node *ap, **app;
9469 union node *cp, **cpp;
9470 union node *redir, **rpp;
9477 /* Check for redirection which may precede command */
9478 while (readtoken() == TREDIR) {
9479 *rpp = n2 = redirnode;
9480 rpp = &n2->nfile.next;
9485 switch (readtoken()) {
9487 n1 = (union node *) stalloc(sizeof(struct nif));
9489 n1->nif.test = list(0);
9490 if (readtoken() != TTHEN)
9492 n1->nif.ifpart = list(0);
9494 while (readtoken() == TELIF) {
9495 n2->nif.elsepart = (union node *) stalloc(sizeof(struct nif));
9496 n2 = n2->nif.elsepart;
9498 n2->nif.test = list(0);
9499 if (readtoken() != TTHEN)
9501 n2->nif.ifpart = list(0);
9503 if (lasttoken == TELSE)
9504 n2->nif.elsepart = list(0);
9506 n2->nif.elsepart = NULL;
9509 if (readtoken() != TFI)
9516 n1 = (union node *) stalloc(sizeof(struct nbinary));
9517 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9518 n1->nbinary.ch1 = list(0);
9519 if ((got = readtoken()) != TDO) {
9520 TRACE(("expecting DO got %s %s\n", tokname(got),
9521 got == TWORD ? wordtext : ""));
9524 n1->nbinary.ch2 = list(0);
9525 if (readtoken() != TDONE)
9531 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
9532 synerror("Bad for loop variable");
9533 n1 = (union node *) stalloc(sizeof(struct nfor));
9535 n1->nfor.var = wordtext;
9537 if (readtoken() == TIN) {
9539 while (readtoken() == TWORD) {
9540 n2 = (union node *) stalloc(sizeof(struct narg));
9542 n2->narg.text = wordtext;
9543 n2->narg.backquote = backquotelist;
9545 app = &n2->narg.next;
9549 if (lasttoken != TNL && lasttoken != TSEMI)
9552 static char argvars[5] = { CTLVAR, VSNORMAL | VSQUOTE,
9555 n2 = (union node *) stalloc(sizeof(struct narg));
9557 n2->narg.text = argvars;
9558 n2->narg.backquote = NULL;
9559 n2->narg.next = NULL;
9562 * Newline or semicolon here is optional (but note
9563 * that the original Bourne shell only allowed NL).
9565 if (lasttoken != TNL && lasttoken != TSEMI)
9569 if (readtoken() != TDO)
9571 n1->nfor.body = list(0);
9572 if (readtoken() != TDONE)
9577 n1 = (union node *) stalloc(sizeof(struct ncase));
9579 if (readtoken() != TWORD)
9581 n1->ncase.expr = n2 = (union node *) stalloc(sizeof(struct narg));
9583 n2->narg.text = wordtext;
9584 n2->narg.backquote = backquotelist;
9585 n2->narg.next = NULL;
9588 } while (readtoken() == TNL);
9589 if (lasttoken != TIN)
9590 synerror("expecting \"in\"");
9591 cpp = &n1->ncase.cases;
9592 checkkwd = 2, readtoken();
9594 if (lasttoken == TLP)
9596 *cpp = cp = (union node *) stalloc(sizeof(struct nclist));
9598 app = &cp->nclist.pattern;
9600 *app = ap = (union node *) stalloc(sizeof(struct narg));
9602 ap->narg.text = wordtext;
9603 ap->narg.backquote = backquotelist;
9604 if (checkkwd = 2, readtoken() != TPIPE)
9606 app = &ap->narg.next;
9609 ap->narg.next = NULL;
9610 if (lasttoken != TRP)
9612 cp->nclist.body = list(0);
9615 if ((t = readtoken()) != TESAC) {
9617 synexpect(TENDCASE);
9619 checkkwd = 2, readtoken();
9621 cpp = &cp->nclist.next;
9622 } while (lasttoken != TESAC);
9627 n1 = (union node *) stalloc(sizeof(struct nredir));
9628 n1->type = NSUBSHELL;
9629 n1->nredir.n = list(0);
9630 n1->nredir.redirect = NULL;
9631 if (readtoken() != TRP)
9637 if (readtoken() != TEND)
9641 /* Handle an empty command like other simple commands. */
9650 * An empty command before a ; doesn't make much sense, and
9651 * should certainly be disallowed in the case of `if ;'.
9657 n1 = simplecmd(rpp, redir);
9664 /* Now check for redirection which may follow command */
9665 while (readtoken() == TREDIR) {
9666 *rpp = n2 = redirnode;
9667 rpp = &n2->nfile.next;
9673 if (n1->type != NSUBSHELL) {
9674 n2 = (union node *) stalloc(sizeof(struct nredir));
9679 n1->nredir.redirect = redir;
9686 static union node *simplecmd(union node **rpp, union node *redir)
9688 union node *args, **app;
9689 union node *n = NULL;
9690 union node *vars, **vpp;
9691 union node **orig_rpp;
9698 /* If we don't have any redirections already, then we must reset
9699 rpp to be the address of the local redir variable. */
9702 /* We save the incoming value, because we need this for shell
9703 functions. There can not be a redirect or an argument between
9704 the function name and the open parenthesis. */
9709 switch (readtoken()) {
9712 n = (union node *) stalloc(sizeof(struct narg));
9714 n->narg.text = wordtext;
9715 n->narg.backquote = backquotelist;
9716 if (lasttoken == TWORD) {
9718 app = &n->narg.next;
9721 vpp = &n->narg.next;
9725 *rpp = n = redirnode;
9726 rpp = &n->nfile.next;
9727 parsefname(); /* read name of redirection file */
9730 if (args && app == &args->narg.next && !vars && rpp == orig_rpp) {
9731 /* We have a function */
9732 if (readtoken() != TRP)
9736 n->narg.next = command();
9749 n = (union node *) stalloc(sizeof(struct ncmd));
9751 n->ncmd.backgnd = 0;
9752 n->ncmd.args = args;
9753 n->ncmd.assign = vars;
9754 n->ncmd.redirect = redir;
9758 static union node *makename(void)
9762 n = (union node *) stalloc(sizeof(struct narg));
9764 n->narg.next = NULL;
9765 n->narg.text = wordtext;
9766 n->narg.backquote = backquotelist;
9770 static void fixredir(union node *n, const char *text, int err)
9772 TRACE(("Fix redir %s %d\n", text, err));
9774 n->ndup.vname = NULL;
9776 if (is_digit(text[0]) && text[1] == '\0')
9777 n->ndup.dupfd = digit_val(text[0]);
9778 else if (text[0] == '-' && text[1] == '\0')
9783 synerror("Bad fd number");
9785 n->ndup.vname = makename();
9790 static void parsefname(void)
9792 union node *n = redirnode;
9794 if (readtoken() != TWORD)
9796 if (n->type == NHERE) {
9797 struct heredoc *here = heredoc;
9803 TRACE(("Here document %d\n", n->type));
9804 if (here->striptabs) {
9805 while (*wordtext == '\t')
9808 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0
9810 synerror("Illegal eof marker for << redirection");
9811 rmescapes(wordtext);
9812 here->eofmark = wordtext;
9814 if (heredoclist == NULL)
9817 for (p = heredoclist; p->next; p = p->next);
9820 } else if (n->type == NTOFD || n->type == NFROMFD) {
9821 fixredir(n, wordtext, 0);
9823 n->nfile.fname = makename();
9829 * Input any here documents.
9832 static void parseheredoc()
9834 struct heredoc *here;
9837 while (heredoclist) {
9839 heredoclist = here->next;
9844 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
9845 here->eofmark, here->striptabs);
9846 n = (union node *) stalloc(sizeof(struct narg));
9847 n->narg.type = NARG;
9848 n->narg.next = NULL;
9849 n->narg.text = wordtext;
9850 n->narg.backquote = backquotelist;
9851 here->here->nhere.doc = n;
9855 static char peektoken()
9861 return tokname_array[t][0];
9864 static int readtoken()
9868 int savecheckalias = checkalias;
9870 #ifdef CONFIG_ASH_ALIAS
9871 int savecheckkwd = checkkwd;
9876 int alreadyseen = tokpushback;
9879 #ifdef CONFIG_ASH_ALIAS
9885 checkalias = savecheckalias;
9891 if (checkkwd == 2) {
9900 * check for keywords
9902 if (t == TWORD && !quoteflag) {
9903 const char *const *pp;
9905 if ((pp = findkwd(wordtext))) {
9906 lasttoken = t = pp - tokname_array;
9907 TRACE(("keyword %s recognized\n", tokname(t)));
9918 } else if (checkalias == 2 && isassignment(wordtext)) {
9919 lasttoken = t = TASSIGN;
9920 } else if (checkalias) {
9921 #ifdef CONFIG_ASH_ALIAS
9922 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL
9923 && !(ap->flag & ALIASINUSE)) {
9925 pushstring(ap->val, strlen(ap->val), ap);
9927 checkkwd = savecheckkwd;
9936 TRACE(("token %s %s\n", tokname(t), t == TWORD
9937 || t == TASSIGN ? wordtext : ""));
9939 TRACE(("reread token %s %s\n", tokname(t), t == TWORD
9940 || t == TASSIGN ? wordtext : ""));
9947 * Read the next input token.
9948 * If the token is a word, we set backquotelist to the list of cmds in
9949 * backquotes. We set quoteflag to true if any part of the word was
9951 * If the token is TREDIR, then we set redirnode to a structure containing
9953 * In all cases, the variable startlinno is set to the number of the line
9954 * on which the token starts.
9956 * [Change comment: here documents and internal procedures]
9957 * [Readtoken shouldn't have any arguments. Perhaps we should make the
9958 * word parsing code into a separate routine. In this case, readtoken
9959 * doesn't need to have any internal procedures, but parseword does.
9960 * We could also make parseoperator in essence the main routine, and
9961 * have parseword (readtoken1?) handle both words and redirection.]
9964 #define NEW_xxreadtoken
9965 #ifdef NEW_xxreadtoken
9967 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
9968 static const char xxreadtoken_tokens[] = {
9969 TNL, TLP, TRP, /* only single occurrence allowed */
9970 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
9971 TEOF, /* corresponds to trailing nul */
9972 TAND, TOR, TENDCASE, /* if double occurrence */
9975 #define xxreadtoken_doubles \
9976 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
9977 #define xxreadtoken_singles \
9978 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
9980 static int xxreadtoken()
9992 startlinno = plinno;
9993 for (;;) { /* until token or start of word found */
9996 if ((c != ' ') && (c != '\t')
9997 #ifdef CONFIG_ASH_ALIAS
10002 while ((c = pgetc()) != '\n' && c != PEOF);
10004 } else if (c == '\\') {
10005 if (pgetc() != '\n') {
10009 startlinno = ++plinno;
10010 setprompt(doprompt ? 2 : 0);
10013 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10018 needprompt = doprompt;
10021 p = strchr(xxreadtoken_chars, c);
10024 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10027 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10028 if (pgetc() == *p) { /* double occurrence? */
10029 p += xxreadtoken_doubles + 1;
10036 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10044 #define RETURN(token) return lasttoken = token
10046 static int xxreadtoken()
10058 startlinno = plinno;
10059 for (;;) { /* until token or start of word found */
10064 #ifdef CONFIG_ASH_ALIAS
10069 while ((c = pgetc()) != '\n' && c != PEOF);
10073 if (pgetc() == '\n') {
10074 startlinno = ++plinno;
10085 needprompt = doprompt;
10090 if (pgetc() == '&')
10095 if (pgetc() == '|')
10100 if (pgetc() == ';')
10113 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10119 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10120 * is not NULL, read a here document. In the latter case, eofmark is the
10121 * word which marks the end of the document and striptabs is true if
10122 * leading tabs should be stripped from the document. The argument firstc
10123 * is the first character of the input token or document.
10125 * Because C does not have internal subroutines, I have simulated them
10126 * using goto's to implement the subroutine linkage. The following macros
10127 * will run code that appears at the end of readtoken1.
10130 #define CHECKEND() {goto checkend; checkend_return:;}
10131 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10132 #define PARSESUB() {goto parsesub; parsesub_return:;}
10133 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10134 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10135 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10138 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10143 char line[EOFMARKLEN + 1];
10144 struct nodelist *bqlist;
10147 int varnest; /* levels of variables expansion */
10148 int arinest; /* levels of arithmetic expansion */
10149 int parenlevel; /* levels of parens in arithmetic */
10150 int dqvarnest; /* levels of variables expansion within double quotes */
10152 int prevsyntax; /* syntax before arithmetic */
10155 /* Avoid longjmp clobbering */
10161 (void) &parenlevel;
10164 (void) &prevsyntax;
10168 startlinno = plinno;
10170 if (syntax == DQSYNTAX)
10179 STARTSTACKSTR(out);
10180 loop:{ /* for each line, until end of word */
10181 CHECKEND(); /* set c to PEOF if at end of here document */
10182 for (;;) { /* until end of line or end of word */
10183 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10184 switch (SIT(c, syntax)) {
10185 case CNL: /* '\n' */
10186 if (syntax == BASESYNTAX)
10187 goto endword; /* exit outer loop */
10195 goto loop; /* continue outer loop */
10200 if ((eofmark == NULL || dblquote) && dqvarnest == 0)
10201 USTPUTC(CTLESC, out);
10204 case CBACK: /* backslash */
10207 USTPUTC('\\', out);
10209 } else if (c == '\n') {
10215 if (dblquote && c != '\\' && c != '`' && c != '$'
10216 && (c != '"' || eofmark != NULL))
10217 USTPUTC('\\', out);
10218 if (SIT(c, SQSYNTAX) == CCTL)
10219 USTPUTC(CTLESC, out);
10220 else if (eofmark == NULL)
10221 USTPUTC(CTLQUOTEMARK, out);
10227 if (eofmark == NULL)
10228 USTPUTC(CTLQUOTEMARK, out);
10232 if (eofmark == NULL)
10233 USTPUTC(CTLQUOTEMARK, out);
10238 if (eofmark != NULL && arinest == 0 && varnest == 0) {
10242 syntax = ARISYNTAX;
10244 } else if (eofmark == NULL && dqvarnest == 0) {
10245 syntax = BASESYNTAX;
10251 case CVAR: /* '$' */
10252 PARSESUB(); /* parse substitution */
10254 case CENDVAR: /* '}' */
10257 if (dqvarnest > 0) {
10260 USTPUTC(CTLENDVAR, out);
10265 #ifdef CONFIG_ASH_MATH_SUPPORT
10266 case CLP: /* '(' in arithmetic */
10270 case CRP: /* ')' in arithmetic */
10271 if (parenlevel > 0) {
10275 if (pgetc() == ')') {
10276 if (--arinest == 0) {
10277 USTPUTC(CTLENDARI, out);
10278 syntax = prevsyntax;
10279 if (syntax == DQSYNTAX)
10287 * unbalanced parens
10288 * (don't 2nd guess - no error)
10296 case CBQUOTE: /* '`' */
10300 goto endword; /* exit outer loop */
10305 goto endword; /* exit outer loop */
10306 #ifdef CONFIG_ASH_ALIAS
10316 if (syntax == ARISYNTAX)
10317 synerror("Missing '))'");
10318 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10319 synerror("Unterminated quoted string");
10320 if (varnest != 0) {
10321 startlinno = plinno;
10322 synerror("Missing '}'");
10324 USTPUTC('\0', out);
10325 len = out - stackblock();
10326 out = stackblock();
10327 if (eofmark == NULL) {
10328 if ((c == '>' || c == '<')
10329 && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) {
10331 return lasttoken = TREDIR;
10336 quoteflag = quotef;
10337 backquotelist = bqlist;
10338 grabstackblock(len);
10340 return lasttoken = TWORD;
10341 /* end of readtoken routine */
10346 * Check to see whether we are at the end of the here document. When this
10347 * is called, c is set to the first character of the next input line. If
10348 * we are at the end of the here document, this routine sets the c to PEOF.
10353 #ifdef CONFIG_ASH_ALIAS
10359 while (c == '\t') {
10363 if (c == *eofmark) {
10364 if (pfgets(line, sizeof line) != NULL) {
10368 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10369 if (*p == '\n' && *q == '\0') {
10372 needprompt = doprompt;
10374 pushstring(line, strlen(line), NULL);
10379 goto checkend_return;
10384 * Parse a redirection operator. The variable "out" points to a string
10385 * specifying the fd to be redirected. The variable "c" contains the
10386 * first character of the redirection operator.
10393 np = (union node *) stalloc(sizeof(struct nfile));
10398 np->type = NAPPEND;
10407 } else { /* c == '<' */
10409 switch (c = pgetc()) {
10411 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10412 np = (union node *) stalloc(sizeof(struct nhere));
10416 heredoc = (struct heredoc *) stalloc(sizeof(struct heredoc));
10417 heredoc->here = np;
10418 if ((c = pgetc()) == '-') {
10419 heredoc->striptabs = 1;
10421 heredoc->striptabs = 0;
10427 np->type = NFROMFD;
10431 np->type = NFROMTO;
10441 np->nfile.fd = digit_val(fd);
10443 goto parseredir_return;
10448 * Parse a substitution. At this point, we have read the dollar sign
10449 * and nothing else.
10457 static const char types[] = "}-+?=";
10461 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10465 } else if (c == '(') { /* $(command) or $((arith)) */
10466 if (pgetc() == '(') {
10473 USTPUTC(CTLVAR, out);
10474 typeloc = out - stackblock();
10475 USTPUTC(VSNORMAL, out);
10476 subtype = VSNORMAL;
10480 if ((c = pgetc()) == '}')
10483 subtype = VSLENGTH;
10487 if (c > PEOA && is_name(c)) {
10491 } while (c > PEOA && is_in_name(c));
10492 } else if (is_digit(c)) {
10496 } while (is_digit(c));
10497 } else if (is_special(c)) {
10501 badsub:synerror("Bad substitution");
10505 if (subtype == 0) {
10510 /*FALLTHROUGH*/ default:
10511 p = strchr(types, c);
10514 subtype = p - types + VSNORMAL;
10521 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
10533 if (dblquote || arinest)
10535 *(stackblock() + typeloc) = subtype | flags;
10536 if (subtype != VSNORMAL) {
10543 goto parsesub_return;
10548 * Called to parse command substitutions. Newstyle is set if the command
10549 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10550 * list of commands (passed by reference), and savelen is the number of
10551 * characters on the top of the stack which must be preserved.
10555 struct nodelist **nlpp;
10558 char *volatile str;
10559 struct jmploc jmploc;
10560 struct jmploc *volatile savehandler;
10565 (void) &saveprompt;
10568 savepbq = parsebackquote;
10569 if (setjmp(jmploc.loc)) {
10571 parsebackquote = 0;
10572 handler = savehandler;
10573 longjmp(handler->loc, 1);
10577 savelen = out - stackblock();
10579 str = xmalloc(savelen);
10580 memcpy(str, stackblock(), savelen);
10582 savehandler = handler;
10586 /* We must read until the closing backquote, giving special
10587 treatment to some slashes, and then push the string and
10588 reread it as input, interpreting it normally. */
10595 STARTSTACKSTR(pout);
10601 switch (pc = pgetc()) {
10606 if ((pc = pgetc()) == '\n') {
10613 * If eating a newline, avoid putting
10614 * the newline into the new character
10615 * stream (via the STPUTC after the
10620 if (pc != '\\' && pc != '`' && pc != '$'
10621 && (!dblquote || pc != '"'))
10622 STPUTC('\\', pout);
10629 #ifdef CONFIG_ASH_ALIAS
10632 startlinno = plinno;
10633 synerror("EOF in backquote substitution");
10637 needprompt = doprompt;
10646 STPUTC('\0', pout);
10647 psavelen = pout - stackblock();
10648 if (psavelen > 0) {
10649 pstr = grabstackstr(pout);
10650 setinputstring(pstr);
10655 nlpp = &(*nlpp)->next;
10656 *nlpp = (struct nodelist *) stalloc(sizeof(struct nodelist));
10657 (*nlpp)->next = NULL;
10658 parsebackquote = oldstyle;
10661 saveprompt = doprompt;
10668 doprompt = saveprompt;
10670 if (readtoken() != TRP)
10677 * Start reading from old file again, ignoring any pushed back
10678 * tokens left from the backquote parsing
10683 while (stackblocksize() <= savelen)
10685 STARTSTACKSTR(out);
10687 memcpy(out, str, savelen);
10688 STADJUST(savelen, out);
10694 parsebackquote = savepbq;
10695 handler = savehandler;
10696 if (arinest || dblquote)
10697 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10699 USTPUTC(CTLBACKQ, out);
10701 goto parsebackq_oldreturn;
10703 goto parsebackq_newreturn;
10707 * Parse an arithmetic expansion (indicate start of one and set state)
10711 if (++arinest == 1) {
10712 prevsyntax = syntax;
10713 syntax = ARISYNTAX;
10714 USTPUTC(CTLARI, out);
10721 * we collapse embedded arithmetic expansion to
10722 * parenthesis, which should be equivalent
10726 goto parsearith_return;
10729 } /* end of readtoken */
10733 * Returns true if the text contains nothing to expand (no dollar signs
10737 static int noexpand(char *text)
10743 while ((c = *p++) != '\0') {
10744 if (c == CTLQUOTEMARK)
10748 else if (SIT(c, BASESYNTAX) == CCTL)
10756 * Return true if the argument is a legal variable name (a letter or
10757 * underscore followed by zero or more letters, underscores, and digits).
10760 static int goodname(const char *name)
10768 if (!is_in_name(*p))
10776 * Called when an unexpected token is read during the parse. The argument
10777 * is the token that is expected, or -1 if more than one type of token can
10778 * occur at this point.
10781 static void synexpect(int token)
10786 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10788 sprintf(msg + l, " (expecting %s)", tokname(token));
10794 static void synerror(const char *msg)
10797 out2fmt("%s: %d: ", commandname, startlinno);
10798 out2fmt("Syntax error: %s\n", msg);
10799 error((char *) NULL);
10805 * called by editline -- any expansions to the prompt
10806 * should be added here.
10808 static void setprompt(int whichprompt)
10812 switch (whichprompt) {
10827 * Code for dealing with input/output redirection.
10830 #define EMPTY -2 /* marks an unused slot in redirtab */
10832 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10834 # define PIPESIZE PIPE_BUF
10839 * Open a file in noclobber mode.
10840 * The code was copied from bash.
10842 static inline int noclobberopen(const char *fname)
10845 struct stat finfo, finfo2;
10848 * If the file exists and is a regular file, return an error
10851 r = stat(fname, &finfo);
10852 if (r == 0 && S_ISREG(finfo.st_mode)) {
10858 * If the file was not present (r != 0), make sure we open it
10859 * exclusively so that if it is created before we open it, our open
10860 * will fail. Make sure that we do not truncate an existing file.
10861 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10862 * file was not a regular file, we leave O_EXCL off.
10865 return open(fname, O_WRONLY | O_CREAT | O_EXCL, 0666);
10866 fd = open(fname, O_WRONLY | O_CREAT, 0666);
10868 /* If the open failed, return the file descriptor right away. */
10873 * OK, the open succeeded, but the file may have been changed from a
10874 * non-regular file to a regular file between the stat and the open.
10875 * We are assuming that the O_EXCL open handles the case where FILENAME
10876 * did not exist and is symlinked to an existing file between the stat
10881 * If we can open it and fstat the file descriptor, and neither check
10882 * revealed that it was a regular file, and the file has not been
10883 * replaced, return the file descriptor.
10885 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10886 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10889 /* The file has been replaced. badness. */
10896 * Handle here documents. Normally we fork off a process to write the
10897 * data to a pipe. If the document is short, we can stuff the data in
10898 * the pipe without forking.
10901 static inline int openhere(const union node *redir)
10907 error("Pipe call failed");
10908 if (redir->type == NHERE) {
10909 len = strlen(redir->nhere.doc->narg.text);
10910 if (len <= PIPESIZE) {
10911 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10915 if (forkshell((struct job *) NULL, (union node *) NULL, FORK_NOJOB) == 0) {
10917 signal(SIGINT, SIG_IGN);
10918 signal(SIGQUIT, SIG_IGN);
10919 signal(SIGHUP, SIG_IGN);
10921 signal(SIGTSTP, SIG_IGN);
10923 signal(SIGPIPE, SIG_DFL);
10924 if (redir->type == NHERE)
10925 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10927 expandhere(redir->nhere.doc, pip[1]);
10936 static inline int openredirect(const union node *redir)
10941 switch (redir->nfile.type) {
10943 fname = redir->nfile.expfname;
10944 if ((f = open(fname, O_RDONLY)) < 0)
10948 fname = redir->nfile.expfname;
10949 if ((f = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0)
10953 /* Take care of noclobber mode. */
10955 fname = redir->nfile.expfname;
10956 if ((f = noclobberopen(fname)) < 0)
10961 fname = redir->nfile.expfname;
10963 if ((f = open(fname, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
10966 if ((f = creat(fname, 0666)) < 0)
10971 fname = redir->nfile.expfname;
10973 if ((f = open(fname, O_WRONLY | O_CREAT | O_APPEND, 0666)) < 0)
10976 if ((f = open(fname, O_WRONLY)) < 0 && (f = creat(fname, 0666)) < 0)
10978 lseek(f, (off_t) 0, 2);
10985 /* Fall through to eliminate warning. */
10992 f = openhere(redir);
10998 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11000 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11005 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11006 * old file descriptors are stashed away so that the redirection can be
11007 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11008 * standard output, and the standard error if it becomes a duplicate of
11012 static void redirect(union node *redir, int flags)
11015 struct redirtab *sv = NULL;
11020 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11022 if (flags & REDIR_PUSH) {
11023 sv = xmalloc(sizeof(struct redirtab));
11024 for (i = 0; i < 10; i++)
11025 sv->renamed[i] = EMPTY;
11026 sv->next = redirlist;
11029 for (n = redir; n; n = n->nfile.next) {
11032 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11033 n->ndup.dupfd == fd)
11034 continue; /* redirect from/to same file descriptor */
11037 newfd = openredirect(n);
11038 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11041 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11045 dupredirect(n, newfd, fd1dup);
11055 error("%d: %m", fd);
11061 if (flags & REDIR_PUSH) {
11062 sv->renamed[fd] = i;
11065 } else if (fd != newfd) {
11071 dupredirect(n, newfd, fd1dup);
11077 static void dupredirect(const union node *redir, int f, int fd1dup)
11079 int fd = redir->nfile.fd;
11083 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11084 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11085 if (redir->ndup.dupfd != 1 || fd1dup != 1)
11086 dup_as_newfd(redir->ndup.dupfd, fd);
11092 dup_as_newfd(f, fd);
11101 * Undo the effects of the last redirection.
11104 static void popredir(void)
11106 struct redirtab *rp = redirlist;
11110 for (i = 0; i < 10; i++) {
11111 if (rp->renamed[i] != EMPTY) {
11115 if (rp->renamed[i] >= 0) {
11116 dup_as_newfd(rp->renamed[i], i);
11117 close(rp->renamed[i]);
11121 redirlist = rp->next;
11127 * Discard all saved file descriptors.
11130 static void clearredir(void)
11132 struct redirtab *rp;
11135 for (rp = redirlist; rp; rp = rp->next) {
11136 for (i = 0; i < 10; i++) {
11137 if (rp->renamed[i] >= 0) {
11138 close(rp->renamed[i]);
11140 rp->renamed[i] = EMPTY;
11147 * Copy a file descriptor to be >= to. Returns -1
11148 * if the source file descriptor is closed, EMPTY if there are no unused
11149 * file descriptors left.
11152 static int dup_as_newfd(int from, int to)
11156 newfd = fcntl(from, F_DUPFD, to);
11158 if (errno == EMFILE)
11161 error("%d: %m", from);
11170 static void shtree(union node *, int, char *, FILE *);
11171 static void shcmd(union node *, FILE *);
11172 static void sharg(union node *, FILE *);
11173 static void indent(int, char *, FILE *);
11174 static void trstring(char *);
11177 static void showtree(n)
11180 trputs("showtree called\n");
11181 shtree(n, 1, NULL, stdout);
11185 static void shtree(union node *n, int ind, char *pfx, FILE * fp)
11187 struct nodelist *lp;
11193 indent(ind, pfx, fp);
11204 shtree(n->nbinary.ch1, ind, NULL, fp);
11207 shtree(n->nbinary.ch2, ind, NULL, fp);
11215 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
11220 if (n->npipe.backgnd)
11226 fprintf(fp, "<node type %d>", n->type);
11235 static void shcmd(union node *cmd, FILE * fp)
11243 for (np = cmd->ncmd.args; np; np = np->narg.next) {
11249 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
11255 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11256 s = redir_strings[np->nfile.type - NTO];
11262 switch (np->nfile.type) {
11297 if (np->nfile.fd != dftfd)
11298 fprintf(fp, "%d", np->nfile.fd);
11300 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11301 fprintf(fp, "%d", np->ndup.dupfd);
11303 sharg(np->nfile.fname, fp);
11309 static void sharg(union node *arg, FILE * fp)
11312 struct nodelist *bqlist;
11315 if (arg->type != NARG) {
11316 printf("<node type %d>\n", arg->type);
11320 bqlist = arg->narg.backquote;
11321 for (p = arg->narg.text; *p; p++) {
11330 if (subtype == VSLENGTH)
11336 if (subtype & VSNUL)
11339 switch (subtype & VSTYPE) {
11358 case VSTRIMLEFTMAX:
11365 case VSTRIMRIGHTMAX:
11372 printf("<subtype %d>", subtype);
11379 case CTLBACKQ | CTLQUOTE:
11382 shtree(bqlist->n, -1, NULL, fp);
11393 static void indent(int amount, char *pfx, FILE * fp)
11397 for (i = 0; i < amount; i++) {
11398 if (pfx && i == amount - 1)
11408 static int debug = 1;
11410 static int debug = 0;
11414 static void trputc(int c)
11416 if (tracefile == NULL)
11418 putc(c, tracefile);
11423 static void trace(const char *fmt, ...)
11428 if (tracefile != NULL) {
11429 (void) vfprintf(tracefile, fmt, va);
11430 if (strchr(fmt, '\n'))
11431 (void) fflush(tracefile);
11437 static void trputs(const char *s)
11439 if (tracefile == NULL)
11441 fputs(s, tracefile);
11442 if (strchr(s, '\n'))
11447 static void trstring(char *s)
11452 if (tracefile == NULL)
11454 putc('"', tracefile);
11455 for (p = s; *p; p++) {
11478 case CTLVAR + CTLQUOTE:
11484 case CTLBACKQ + CTLQUOTE:
11487 backslash:putc('\\', tracefile);
11488 putc(c, tracefile);
11491 if (*p >= ' ' && *p <= '~')
11492 putc(*p, tracefile);
11494 putc('\\', tracefile);
11495 putc(*p >> 6 & 03, tracefile);
11496 putc(*p >> 3 & 07, tracefile);
11497 putc(*p & 07, tracefile);
11502 putc('"', tracefile);
11506 static void trargs(char **ap)
11508 if (tracefile == NULL)
11513 putc(' ', tracefile);
11515 putc('\n', tracefile);
11521 static void opentrace()
11531 #ifdef not_this_way
11535 if ((p = getenv("HOME")) == NULL) {
11536 if (geteuid() == 0)
11542 strcat(s, "/trace");
11545 strcpy(s, "./trace");
11546 #endif /* not_this_way */
11547 if ((tracefile = wfopen(s, "a")) == NULL)
11550 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11551 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11553 fputs("\nTracing started.\n", tracefile);
11560 * The trap builtin.
11563 static int trapcmd(int argc, char **argv)
11570 for (signo = 0; signo < NSIG; signo++) {
11571 if (trap[signo] != NULL) {
11575 p = single_quote(trap[signo]);
11576 sn = sys_siglist[signo];
11578 sn = u_signal_names(0, &signo, 0);
11581 printf("trap -- %s %s\n", p, sn);
11593 if ((signo = decode_signal(*ap, 0)) < 0)
11594 error("%s: bad trap", *ap);
11597 if (action[0] == '-' && action[1] == '\0')
11600 action = xstrdup(action);
11603 trap[signo] = action;
11618 * Set the signal handler for the specified signal. The routine figures
11619 * out what it should be set to.
11622 static void setsignal(int signo)
11626 struct sigaction act;
11628 if ((t = trap[signo]) == NULL)
11630 else if (*t != '\0')
11634 if (rootshell && action == S_DFL) {
11637 if (iflag || minusc || sflag == 0)
11653 #ifdef CONFIG_ASH_JOB_CONTROL
11663 t = &sigmode[signo - 1];
11666 * current setting unknown
11668 if (sigaction(signo, 0, &act) == -1) {
11670 * Pretend it worked; maybe we should give a warning
11671 * here, but other shells don't. We don't alter
11672 * sigmode, so that we retry every time.
11676 if (act.sa_handler == SIG_IGN) {
11677 if (mflag && (signo == SIGTSTP ||
11678 signo == SIGTTIN || signo == SIGTTOU)) {
11679 *t = S_IGN; /* don't hard ignore these */
11683 *t = S_RESET; /* force to be set */
11686 if (*t == S_HARD_IGN || *t == action)
11688 act.sa_handler = ((action == S_CATCH) ? onsig
11689 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11692 sigemptyset(&act.sa_mask);
11693 sigaction(signo, &act, 0);
11700 static void ignoresig(int signo)
11702 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11703 signal(signo, SIG_IGN);
11705 sigmode[signo - 1] = S_HARD_IGN;
11713 static void onsig(int signo)
11715 if (signo == SIGINT && trap[SIGINT] == NULL) {
11719 gotsig[signo - 1] = 1;
11725 * Called to execute a trap. Perhaps we should avoid entering new trap
11726 * handlers while we are executing a trap handler.
11729 static void dotrap(void)
11735 for (i = 1;; i++) {
11742 savestatus = exitstatus;
11743 evalstring(trap[i], 0);
11744 exitstatus = savestatus;
11751 * Called to exit the shell.
11754 static void exitshell(int status)
11756 struct jmploc loc1, loc2;
11759 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11760 if (setjmp(loc1.loc)) {
11763 if (setjmp(loc2.loc)) {
11767 if ((p = trap[0]) != NULL && *p != '\0') {
11771 l1:handler = &loc2; /* probably unnecessary */
11773 #ifdef CONFIG_ASH_JOB_CONTROL
11780 static int decode_signal(const char *string, int minsig)
11783 const char *name = u_signal_names(string, &signo, minsig);
11785 return name ? signo : -1;
11788 static struct var **hashvar(const char *);
11789 static void showvars(const char *, int, int);
11790 static struct var **findvar(struct var **, const char *);
11793 * Initialize the varable symbol tables and import the environment
11797 * This routine initializes the builtin variables. It is called when the
11798 * shell is initialized and again when a shell procedure is spawned.
11801 static void initvar()
11803 const struct varinit *ip;
11807 for (ip = varinit; (vp = ip->var) != NULL; ip++) {
11808 if ((vp->flags & VEXPORT) == 0) {
11809 vpp = hashvar(ip->text);
11812 vp->text = xstrdup(ip->text);
11813 vp->flags = ip->flags;
11814 vp->func = ip->func;
11817 #if !defined(CONFIG_FEATURE_COMMAND_EDITING) || !defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
11819 * PS1 depends on uid
11821 if ((vps1.flags & VEXPORT) == 0) {
11822 vpp = hashvar("PS1=$");
11825 vps1.text = xstrdup(geteuid()? "PS1=$ " : "PS1=# ");
11826 vps1.flags = VSTRFIXED | VTEXTFIXED;
11832 * Set the value of a variable. The flags argument is ored with the
11833 * flags of the variable. If val is NULL, the variable is unset.
11836 static void setvar(const char *name, const char *val, int flags)
11851 if (!is_in_name(*p)) {
11852 if (*p == '\0' || *p == '=')
11858 namelen = p - name;
11860 error("%.*s: bad variable name", namelen, name);
11861 len = namelen + 2; /* 2 is space for '=' and '\0' */
11865 len += vallen = strlen(val);
11868 nameeq = xmalloc(len);
11869 memcpy(nameeq, name, namelen);
11870 nameeq[namelen] = '=';
11872 memcpy(nameeq + namelen + 1, val, vallen + 1);
11874 nameeq[namelen + 1] = '\0';
11876 setvareq(nameeq, flags);
11883 * Same as setvar except that the variable and value are passed in
11884 * the first argument as name=value. Since the first argument will
11885 * be actually stored in the table, it should not be a string that
11889 static void setvareq(char *s, int flags)
11891 struct var *vp, **vpp;
11894 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11895 if ((vp = *findvar(vpp, s))) {
11896 if (vp->flags & VREADONLY) {
11897 size_t len = strchr(s, '=') - s;
11899 error("%.*s: is read only", len, s);
11903 if (vp->func && (flags & VNOFUNC) == 0)
11904 (*vp->func) (strchr(s, '=') + 1);
11906 if ((vp->flags & (VTEXTFIXED | VSTACK)) == 0)
11909 vp->flags &= ~(VTEXTFIXED | VSTACK | VUNSET);
11910 vp->flags |= flags;
11913 #ifdef CONFIG_ASH_MAIL
11915 * We could roll this to a function, to handle it as
11916 * a regular variable function callback, but why bother?
11918 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
11925 vp = xmalloc(sizeof(*vp));
11936 * Process a linked list of variable assignments.
11939 static void listsetvar(struct strlist *mylist)
11941 struct strlist *lp;
11944 for (lp = mylist; lp; lp = lp->next) {
11945 setvareq(xstrdup(lp->text), 0);
11953 * Find the value of a variable. Returns NULL if not set.
11956 static const char *lookupvar(const char *name)
11960 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
11961 return strchr(v->text, '=') + 1;
11969 * Search the environment of a builtin command.
11972 static const char *bltinlookup(const char *name)
11974 const struct strlist *sp;
11976 for (sp = cmdenviron; sp; sp = sp->next) {
11977 if (varequal(sp->text, name))
11978 return strchr(sp->text, '=') + 1;
11980 return lookupvar(name);
11986 * Generate a list of exported variables. This routine is used to construct
11987 * the third argument to execve when executing a program.
11990 static char **environment()
11999 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12000 for (vp = *vpp; vp; vp = vp->next)
12001 if (vp->flags & VEXPORT)
12004 ep = env = stalloc((nenv + 1) * sizeof *env);
12005 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12006 for (vp = *vpp; vp; vp = vp->next)
12007 if (vp->flags & VEXPORT)
12016 * Called when a shell procedure is invoked to clear out nonexported
12017 * variables. It is also necessary to reallocate variables of with
12018 * VSTACK set since these are currently allocated on the stack.
12021 static void shprocvar(void)
12024 struct var *vp, **prev;
12026 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12027 for (prev = vpp; (vp = *prev) != NULL;) {
12028 if ((vp->flags & VEXPORT) == 0) {
12030 if ((vp->flags & VTEXTFIXED) == 0)
12032 if ((vp->flags & VSTRFIXED) == 0)
12035 if (vp->flags & VSTACK) {
12036 vp->text = xstrdup(vp->text);
12037 vp->flags &= ~VSTACK;
12049 * Command to list all variables which are set. Currently this command
12050 * is invoked from the set command when the set command is called without
12054 static int showvarscmd(int argc, char **argv)
12056 showvars(nullstr, VUNSET, VUNSET);
12063 * The export and readonly commands.
12066 static int exportcmd(int argc, char **argv)
12071 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
12074 listsetvar(cmdenviron);
12075 pflag = (nextopt("p") == 'p');
12076 if (argc > 1 && !pflag) {
12077 while ((name = *argptr++) != NULL) {
12078 if ((p = strchr(name, '=')) != NULL) {
12081 if ((vp = *findvar(hashvar(name), name))) {
12086 setvar(name, p, flag);
12090 showvars(argv[0], flag, 0);
12097 * The "local" command.
12100 /* funcnest nonzero if we are currently evaluating a function */
12102 static int localcmd(int argc, char **argv)
12107 error("Not in a function");
12108 while ((name = *argptr++) != NULL) {
12116 * Make a variable a local variable. When a variable is made local, it's
12117 * value and flags are saved in a localvar structure. The saved values
12118 * will be restored when the shell function returns. We handle the name
12119 * "-" as a special case.
12122 static void mklocal(char *name)
12124 struct localvar *lvp;
12129 lvp = xmalloc(sizeof(struct localvar));
12130 if (name[0] == '-' && name[1] == '\0') {
12133 p = xmalloc(sizeof optet_vals);
12134 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12137 vpp = hashvar(name);
12138 vp = *findvar(vpp, name);
12140 if (strchr(name, '='))
12141 setvareq(xstrdup(name), VSTRFIXED);
12143 setvar(name, NULL, VSTRFIXED);
12144 vp = *vpp; /* the new variable */
12146 lvp->flags = VUNSET;
12148 lvp->text = vp->text;
12149 lvp->flags = vp->flags;
12150 vp->flags |= VSTRFIXED | VTEXTFIXED;
12151 if (strchr(name, '='))
12152 setvareq(xstrdup(name), 0);
12156 lvp->next = localvars;
12163 * Called after a function returns.
12166 static void poplocalvars()
12168 struct localvar *lvp;
12171 while ((lvp = localvars) != NULL) {
12172 localvars = lvp->next;
12174 if (vp == NULL) { /* $- saved */
12175 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12177 } else if ((lvp->flags & (VUNSET | VSTRFIXED)) == VUNSET) {
12178 (void) unsetvar(vp->text);
12180 if ((vp->flags & VTEXTFIXED) == 0)
12182 vp->flags = lvp->flags;
12183 vp->text = lvp->text;
12190 static int setvarcmd(int argc, char **argv)
12193 return unsetcmd(argc, argv);
12194 else if (argc == 3)
12195 setvar(argv[1], argv[2], 0);
12197 error("List assignment not implemented");
12203 * The unset builtin command. We unset the function before we unset the
12204 * variable to allow a function to be unset when there is a readonly variable
12205 * with the same name.
12208 static int unsetcmd(int argc, char **argv)
12216 while ((i = nextopt("vf")) != '\0') {
12222 if (flg_func == 0 && flg_var == 0)
12225 for (ap = argptr; *ap; ap++) {
12229 ret |= unsetvar(*ap);
12236 * Unset the specified variable.
12239 static int unsetvar(const char *s)
12244 vpp = findvar(hashvar(s), s);
12247 if (vp->flags & VREADONLY)
12250 if (*(strchr(vp->text, '=') + 1) != '\0')
12251 setvar(s, nullstr, 0);
12252 vp->flags &= ~VEXPORT;
12253 vp->flags |= VUNSET;
12254 if ((vp->flags & VSTRFIXED) == 0) {
12255 if ((vp->flags & VTEXTFIXED) == 0)
12270 * Find the appropriate entry in the hash table from the name.
12273 static struct var **hashvar(const char *p)
12275 unsigned int hashval;
12277 hashval = ((unsigned char) *p) << 4;
12278 while (*p && *p != '=')
12279 hashval += (unsigned char) *p++;
12280 return &vartab[hashval % VTABSIZE];
12286 * Returns true if the two strings specify the same varable. The first
12287 * variable name is terminated by '='; the second may be terminated by
12288 * either '=' or '\0'.
12291 static int varequal(const char *p, const char *q)
12293 while (*p == *q++) {
12297 if (*p == '=' && *(q - 1) == '\0')
12302 static void showvars(const char *myprefix, int mask, int xor)
12306 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12308 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12309 for (vp = *vpp; vp; vp = vp->next) {
12310 if ((vp->flags & mask) ^ xor) {
12314 p = strchr(vp->text, '=') + 1;
12315 len = p - vp->text;
12316 p = single_quote(p);
12318 printf("%s%s%.*s%s\n", myprefix, sep, len, vp->text, p);
12325 static struct var **findvar(struct var **vpp, const char *name)
12327 for (; *vpp; vpp = &(*vpp)->next) {
12328 if (varequal((*vpp)->text, name)) {
12336 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12337 * This file contains code for the times builtin.
12338 * $Id: ash.c,v 1.57 2002/08/22 18:30:15 bug1 Exp $
12340 static int timescmd(int argc, char **argv)
12343 long int clk_tck = sysconf(_SC_CLK_TCK);
12346 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12347 (int) (buf.tms_utime / clk_tck / 60),
12348 ((double) buf.tms_utime) / clk_tck,
12349 (int) (buf.tms_stime / clk_tck / 60),
12350 ((double) buf.tms_stime) / clk_tck,
12351 (int) (buf.tms_cutime / clk_tck / 60),
12352 ((double) buf.tms_cutime) / clk_tck,
12353 (int) (buf.tms_cstime / clk_tck / 60),
12354 ((double) buf.tms_cstime) / clk_tck);
12358 #ifdef CONFIG_ASH_MATH_SUPPORT
12359 /* The let builtin. */
12360 int letcmd(int argc, char **argv)
12366 char *tmp, *expression, p[13];
12368 expression = strchr(argv[1], '=');
12370 /* Cannot use 'error()' here, or the return code
12371 * will be incorrect */
12372 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12375 *expression = '\0';
12376 tmp = ++expression;
12377 result = arith(tmp, &errcode);
12379 /* Cannot use 'error()' here, or the return code
12380 * will be incorrect */
12381 out2fmt("sh: let: ");
12383 out2fmt("divide by zero");
12385 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12388 snprintf(p, 12, "%ld", result);
12389 setvar(argv[1], xstrdup(p), 0);
12390 } else if (argc >= 3)
12391 synerror("invalid operand");
12399 * Copyright (c) 1989, 1991, 1993, 1994
12400 * The Regents of the University of California. All rights reserved.
12402 * This code is derived from software contributed to Berkeley by
12403 * Kenneth Almquist.
12405 * Redistribution and use in source and binary forms, with or without
12406 * modification, are permitted provided that the following conditions
12408 * 1. Redistributions of source code must retain the above copyright
12409 * notice, this list of conditions and the following disclaimer.
12410 * 2. Redistributions in binary form must reproduce the above copyright
12411 * notice, this list of conditions and the following disclaimer in the
12412 * documentation and/or other materials provided with the distribution.
12414 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12415 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12417 * 4. Neither the name of the University nor the names of its contributors
12418 * may be used to endorse or promote products derived from this software
12419 * without specific prior written permission.
12421 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12422 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12423 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12424 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12425 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12426 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12427 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12428 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12429 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12430 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF