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
88 #if defined(__uClinux__)
89 #error "Do not even bother, ash will not run on uClinux"
93 * This file was generated by the mksyntax program.
97 #define CWORD 0 /* character is nothing special */
98 #define CNL 1 /* newline character */
99 #define CBACK 2 /* a backslash character */
100 #define CSQUOTE 3 /* single quote */
101 #define CDQUOTE 4 /* double quote */
102 #define CENDQUOTE 5 /* a terminating quote */
103 #define CBQUOTE 6 /* backwards single quote */
104 #define CVAR 7 /* a dollar sign */
105 #define CENDVAR 8 /* a '}' character */
106 #define CLP 9 /* a left paren in arithmetic */
107 #define CRP 10 /* a right paren in arithmetic */
108 #define CENDFILE 11 /* end of file */
109 #define CCTL 12 /* like CWORD, except it must be escaped */
110 #define CSPCL 13 /* these terminate a word */
111 #define CIGN 14 /* character should be ignored */
131 #define TENDBQUOTE 13
151 /* control characters in argument strings */
152 #define CTLESC '\201'
153 #define CTLVAR '\202'
154 #define CTLENDVAR '\203'
155 #define CTLBACKQ '\204'
156 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
157 /* CTLBACKQ | CTLQUOTE == '\205' */
158 #define CTLARI '\206'
159 #define CTLENDARI '\207'
160 #define CTLQUOTEMARK '\210'
163 #define is_digit(c) ((c)>='0' && (c)<='9')
164 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
165 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
168 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
169 * (assuming ascii char codes, as the original implementation did)
171 #define is_special(c) \
172 ( (((unsigned int)c) - 33 < 32) \
173 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
175 #define digit_val(c) ((c) - '0')
178 #define S_DFL 1 /* default signal handling (SIG_DFL) */
179 #define S_CATCH 2 /* signal is caught */
180 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
181 #define S_HARD_IGN 4 /* signal is ignored permenantly */
182 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
185 /* variable substitution byte (follows CTLVAR) */
186 #define VSTYPE 0x0f /* type of variable substitution */
187 #define VSNUL 0x10 /* colon--treat the empty string as unset */
188 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
190 /* values of VSTYPE field */
191 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
192 #define VSMINUS 0x2 /* ${var-text} */
193 #define VSPLUS 0x3 /* ${var+text} */
194 #define VSQUESTION 0x4 /* ${var?message} */
195 #define VSASSIGN 0x5 /* ${var=text} */
196 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
197 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
198 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
199 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
200 #define VSLENGTH 0xa /* ${#var} */
202 /* flags passed to redirect */
203 #define REDIR_PUSH 01 /* save previous values of file descriptors */
204 #define REDIR_BACKQ 02 /* save the command output to pipe */
207 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
208 * so we use _setjmp instead.
212 #define setjmp(jmploc) _setjmp(jmploc)
213 #define longjmp(jmploc, val) _longjmp(jmploc, val)
217 * Most machines require the value returned from malloc to be aligned
218 * in some way. The following macro will get this right on many machines.
227 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
230 #ifdef CONFIG_LOCALE_SUPPORT
232 static void change_lc_all(const char *value);
233 static void change_lc_ctype(const char *value);
237 * These macros allow the user to suspend the handling of interrupt signals
238 * over a period of time. This is similar to SIGHOLD to or sigblock, but
239 * much more efficient and portable. (But hacking the kernel is so much
240 * more fun than worrying about efficiency and portability. :-))
243 static void onint(void);
244 static volatile int suppressint;
245 static volatile int intpending;
247 #define INTOFF suppressint++
248 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
249 #define INTON { if (--suppressint == 0 && intpending) onint(); }
250 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
252 static void __inton(void);
253 static void forceinton(void);
255 #define INTON __inton()
256 #define FORCEINTON forceinton()
259 #define CLEAR_PENDING_INT intpending = 0
260 #define int_pending() intpending
263 typedef void *pointer;
266 #define NULL (void *)0
269 static pointer stalloc(int);
270 static void stunalloc(pointer);
271 static void ungrabstackstr(char *, char *);
272 static char *growstackstr(void);
273 static char *makestrspace(size_t newlen);
276 * Parse trees for commands are allocated in lifo order, so we use a stack
277 * to make this more efficient, and also to avoid all sorts of exception
278 * handling code to handle interrupts in the middle of a parse.
280 * The size 504 was chosen because the Ultrix malloc handles that size
284 #define MINSIZE 504 /* minimum size of a block */
288 struct stack_block *prev;
292 static struct stack_block stackbase;
293 static struct stack_block *stackp = &stackbase;
294 static struct stackmark *markp;
295 static char *stacknxt = stackbase.space;
296 static int stacknleft = MINSIZE;
299 #define equal(s1, s2) (strcmp(s1, s2) == 0)
301 #define stackblock() stacknxt
302 #define stackblocksize() stacknleft
303 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
305 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
306 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
307 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
310 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
311 #define STUNPUTC(p) (++sstrnleft, --p)
312 #define STTOPC(p) p[-1]
313 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
314 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
318 #define TRACE(param) trace param
319 typedef union node unode;
320 static void trace(const char *, ...);
321 static void trargs(char **);
322 static void showtree(unode *);
323 static void trputc(int);
324 static void trputs(const char *);
325 static void opentrace(void);
360 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
361 #define EXP_TILDE 0x2 /* do normal tilde expansion */
362 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
363 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
364 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
365 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
370 static char optet_vals[NOPTS];
372 static const char *const optlist[NOPTS] = {
391 #define optent_name(optent) (optent+1)
392 #define optent_letter(optent) optent[0]
393 #define optent_val(optent) optet_vals[optent]
395 #define eflag optent_val(0)
396 #define fflag optent_val(1)
397 #define Iflag optent_val(2)
398 #define iflag optent_val(3)
399 #define mflag optent_val(4)
400 #define nflag optent_val(5)
401 #define sflag optent_val(6)
402 #define xflag optent_val(7)
403 #define vflag optent_val(8)
404 #define Vflag optent_val(9)
405 #define Eflag optent_val(10)
406 #define Cflag optent_val(11)
407 #define aflag optent_val(12)
408 #define bflag optent_val(13)
409 #define uflag optent_val(14)
410 #define qflag optent_val(15)
413 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
431 union node *redirect;
438 struct nodelist *cmdlist;
445 union node *redirect;
453 union node *elsepart;
484 struct nodelist *backquote;
522 struct nbinary nbinary;
525 struct nredir nredir;
529 struct nclist nclist;
539 struct nodelist *next;
543 struct backcmd { /* result of evalbackcmd */
544 int fd; /* file descriptor to read from */
545 char *buf; /* buffer */
546 int nleft; /* number of chars in buffer */
547 struct job *jp; /* job structure for command */
555 const struct builtincmd *cmd;
560 struct strlist *next;
566 struct strlist *list;
567 struct strlist **lastp;
571 struct strpush *prev; /* preceding string on stack */
574 #ifdef CONFIG_ASH_ALIAS
575 struct alias *ap; /* if push was associated with an alias */
577 char *string; /* remember the string since it may change */
581 struct parsefile *prev; /* preceding file on stack */
582 int linno; /* current line */
583 int fd; /* file descriptor (or -1 if string) */
584 int nleft; /* number of chars left in this line */
585 int lleft; /* number of chars left in this buffer */
586 char *nextc; /* next char in buffer */
587 char *buf; /* input buffer */
588 struct strpush *strpush; /* for pushing strings at this level */
589 struct strpush basestrpush; /* so pushing one is fast */
593 struct stack_block *stackp;
596 struct stackmark *marknext;
600 int nparam; /* # of positional parameters (without $0) */
601 unsigned char malloc; /* if parameter list dynamically allocated */
602 char **p; /* parameter list */
603 int optind; /* next parameter to be processed by getopts */
604 int optoff; /* used by getopts */
608 * When commands are first encountered, they are entered in a hash table.
609 * This ensures that a full path search will not have to be done for them
610 * on each invocation.
612 * We should investigate converting to a linear search, even though that
613 * would make the command name "hash" a misnomer.
615 #define CMDTABLESIZE 31 /* should be prime */
616 #define ARB 1 /* actual size determined at run time */
621 struct tblentry *next; /* next entry in hash chain */
622 union param param; /* definition of builtin function */
623 short cmdtype; /* index identifying command */
624 char rehash; /* if set, cd done since entry created */
625 char cmdname[ARB]; /* name of command */
629 static struct tblentry *cmdtable[CMDTABLESIZE];
630 static int builtinloc = -1; /* index in path of %builtin, or -1 */
631 static int exerrno = 0; /* Last exec error */
634 static void tryexec(char *, char **, char **);
635 static void printentry(struct tblentry *, int);
636 static void clearcmdentry(int);
637 static struct tblentry *cmdlookup(const char *, int);
638 static void delete_cmd_entry(void);
639 static int path_change(const char *, int *);
642 static void flushall(void);
643 static void out2fmt(const char *, ...)
644 __attribute__ ((__format__(__printf__, 1, 2)));
645 static int xwrite(int, const char *, int);
647 static inline void outstr(const char *p, FILE * file)
651 static void out1str(const char *p)
655 static void out2str(const char *p)
660 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
661 #define out2c(c) putc((c), stderr)
663 static void out2c(int c)
670 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
671 #define USE_SIT_FUNCTION
674 /* number syntax index */
675 #define BASESYNTAX 0 /* not in quotes */
676 #define DQSYNTAX 1 /* in double quotes */
677 #define SQSYNTAX 2 /* in single quotes */
678 #define ARISYNTAX 3 /* in arithmetic */
680 static const char S_I_T[][4] = {
681 {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
682 {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
683 {CNL, CNL, CNL, CNL}, /* 2, \n */
684 {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
685 {CDQUOTE, CENDQUOTE, CWORD, CDQUOTE}, /* 4, '"' */
686 {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
687 {CSQUOTE, CWORD, CENDQUOTE, CSQUOTE}, /* 6, "'" */
688 {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
689 {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
690 {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
691 {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
692 {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
693 #ifndef USE_SIT_FUNCTION
694 {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
695 {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
696 {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
700 #ifdef USE_SIT_FUNCTION
702 #define U_C(c) ((unsigned char)(c))
704 static int SIT(int c, int syntax)
706 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
707 static const char syntax_index_table[] = {
708 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
709 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
710 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
716 if (c == PEOF) /* 2^8+2 */
718 if (c == PEOA) /* 2^8+1 */
720 else if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
723 s = strchr(spec_symbls, c);
726 indx = syntax_index_table[(s - spec_symbls)];
728 return S_I_T[indx][syntax];
731 #else /* USE_SIT_FUNCTION */
733 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
735 #define CSPCL_CIGN_CIGN_CIGN 0
736 #define CSPCL_CWORD_CWORD_CWORD 1
737 #define CNL_CNL_CNL_CNL 2
738 #define CWORD_CCTL_CCTL_CWORD 3
739 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
740 #define CVAR_CVAR_CWORD_CVAR 5
741 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
742 #define CSPCL_CWORD_CWORD_CLP 7
743 #define CSPCL_CWORD_CWORD_CRP 8
744 #define CBACK_CBACK_CCTL_CBACK 9
745 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
746 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
747 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
748 #define CWORD_CWORD_CWORD_CWORD 13
749 #define CCTL_CCTL_CCTL_CCTL 14
751 static const char syntax_index_table[258] = {
752 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
753 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
754 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
755 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
756 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL,
758 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
759 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
760 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
761 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
762 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
763 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
764 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL,
766 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
767 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
768 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
769 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
770 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
771 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
772 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
773 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
774 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
775 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
776 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
777 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
778 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
779 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
780 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
781 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
782 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
783 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
784 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
785 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
786 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
787 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
788 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
789 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
790 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
791 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
792 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
793 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
794 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
795 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
796 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
797 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
798 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
799 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
800 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
801 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
802 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
803 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
804 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
805 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
806 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
807 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
808 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
809 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
810 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
811 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
812 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
813 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
814 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
815 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
816 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
817 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
818 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
819 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
820 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
821 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
822 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
823 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
824 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
825 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
826 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
827 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
828 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
829 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
830 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
831 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
832 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
833 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
834 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
835 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
836 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
837 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
838 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
839 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
840 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
841 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
842 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
843 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
844 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
845 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
846 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
847 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
848 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
849 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
850 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
851 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
852 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
853 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
854 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
855 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
856 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
857 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
858 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
859 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
860 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
861 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
862 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
863 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
864 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
865 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
866 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
867 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
868 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
869 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
870 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
871 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
872 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
873 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
874 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
875 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
876 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
877 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
878 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
879 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
880 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
881 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
882 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
883 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
884 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
885 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
886 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
887 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
888 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
889 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
890 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
891 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
892 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
893 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
894 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
895 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
896 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
897 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
898 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
899 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
900 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
901 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
902 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
903 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
904 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
905 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
906 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
907 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
908 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
909 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
910 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
911 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
912 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
913 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
914 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
915 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
916 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
917 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
918 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
919 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
920 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
921 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
922 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
923 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
924 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
925 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
926 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
927 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
928 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
929 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
930 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
931 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
932 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
933 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
934 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
935 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
936 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
937 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
938 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
939 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
940 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
941 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
942 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
943 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
944 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
945 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
946 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
947 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
948 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
949 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
950 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
951 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
952 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
953 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
954 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
955 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
956 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
957 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
958 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
959 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
960 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
961 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
962 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
963 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
964 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
965 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
966 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
967 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
968 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
969 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
970 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
971 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
972 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
973 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
974 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
975 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
976 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
977 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
978 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
979 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
980 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
981 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
982 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
983 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
984 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
985 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
986 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
987 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
988 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
989 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
990 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
991 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
992 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
993 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
994 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
995 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
996 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
997 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
998 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
999 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1004 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1005 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1010 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1011 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1012 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1015 #endif /* USE_SIT_FUNCTION */
1018 /* first char is indicating which tokens mark the end of a list */
1019 static const char *const tokname_array[] = {
1034 #define KWDOFFSET 14
1035 /* the following are keywords */
1054 static const char *tokname(int tok)
1056 static char buf[16];
1060 sprintf(buf + (tok >= TSEMI), "%s%c",
1061 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
1065 static int plinno = 1; /* input line number */
1067 static int parselleft; /* copy of parsefile->lleft */
1069 static struct parsefile basepf; /* top level input file */
1070 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1071 static struct parsefile *parsefile = &basepf; /* current input file */
1074 * NEOF is returned by parsecmd when it encounters an end of file. It
1075 * must be distinct from NULL, so we use the address of a variable that
1076 * happens to be handy.
1079 static int tokpushback; /* last token pushed back */
1081 #define NEOF ((union node *)&tokpushback)
1082 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1085 static void error(const char *, ...) __attribute__ ((__noreturn__));
1086 static void exerror(int, const char *, ...) __attribute__ ((__noreturn__));
1087 static void shellexec(char **, char **, const char *, int)
1088 __attribute__ ((noreturn));
1089 static void exitshell(int) __attribute__ ((noreturn));
1091 static int goodname(const char *);
1092 static void ignoresig(int);
1093 static void onsig(int);
1094 static void dotrap(void);
1095 static int decode_signal(const char *, int);
1097 static void setparam(char **);
1098 static void freeparam(volatile struct shparam *);
1100 /* reasons for skipping commands (see comment on breakcmd routine) */
1106 /* values of cmdtype */
1107 #define CMDUNKNOWN -1 /* no entry in table for command */
1108 #define CMDNORMAL 0 /* command is an executable program */
1109 #define CMDBUILTIN 1 /* command is a shell builtin */
1110 #define CMDFUNCTION 2 /* command is a shell function */
1112 #define DO_ERR 1 /* find_command prints errors */
1113 #define DO_ABS 2 /* find_command checks absolute paths */
1114 #define DO_NOFUN 4 /* find_command ignores functions */
1115 #define DO_BRUTE 8 /* find_command ignores hash table */
1122 #define VEXPORT 0x01 /* variable is exported */
1123 #define VREADONLY 0x02 /* variable cannot be modified */
1124 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1125 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1126 #define VSTACK 0x10 /* text is allocated on the stack */
1127 #define VUNSET 0x20 /* the variable is not set */
1128 #define VNOFUNC 0x40 /* don't call the callback function */
1132 struct var *next; /* next entry in hash list */
1133 int flags; /* flags are defined above */
1134 char *text; /* name=value */
1135 void (*func) (const char *);
1136 /* function to be called when */
1137 /* the variable gets set/unset */
1141 struct localvar *next; /* next local variable in list */
1142 struct var *vp; /* the variable that was made local */
1143 int flags; /* saved flags */
1144 char *text; /* saved text */
1148 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1149 #define rmescapes(p) _rmescapes((p), 0)
1150 static char *_rmescapes(char *, int);
1152 static void rmescapes(char *);
1155 static int casematch(union node *, const char *);
1156 static void clearredir(void);
1157 static void popstring(void);
1158 static void readcmdfile(const char *);
1160 static int number(const char *);
1161 static int is_number(const char *, int *num);
1162 static char *single_quote(const char *);
1163 static int nextopt(const char *);
1165 static void redirect(union node *, int);
1166 static void popredir(void);
1167 static int dup_as_newfd(int, int);
1169 static void changepath(const char *newval);
1170 static void getoptsreset(const char *value);
1173 static int parsenleft; /* copy of parsefile->nleft */
1174 static char *parsenextc; /* copy of parsefile->nextc */
1175 static int rootpid; /* pid of main shell */
1176 static int rootshell; /* true if we aren't a child of the main shell */
1178 static const char spcstr[] = " ";
1179 static const char snlfmt[] = "%s\n";
1181 static int sstrnleft;
1182 static int herefd = -1;
1184 static struct localvar *localvars;
1186 static struct var vifs;
1187 static struct var vmail;
1188 static struct var vmpath;
1189 static struct var vpath;
1190 static struct var vps1;
1191 static struct var vps2;
1192 static struct var voptind;
1194 #ifdef CONFIG_LOCALE_SUPPORT
1195 static struct var vlc_all;
1196 static struct var vlc_ctype;
1203 void (*func) (const char *);
1206 static const char defpathvar[] =
1207 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1208 #define defpath (defpathvar + 5)
1211 static const char defifsvar[] = "IFS= \t\n";
1213 #define defifs (defifsvar + 4)
1215 static const char defifs[] = " \t\n";
1218 static const struct varinit varinit[] = {
1220 {&vifs, VSTRFIXED | VTEXTFIXED, defifsvar,
1222 {&vifs, VSTRFIXED | VTEXTFIXED | VUNSET, "IFS=",
1225 {&vmail, VSTRFIXED | VTEXTFIXED | VUNSET, "MAIL=",
1227 {&vmpath, VSTRFIXED | VTEXTFIXED | VUNSET, "MAILPATH=",
1229 {&vpath, VSTRFIXED | VTEXTFIXED, defpathvar,
1231 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1232 {&vps1, VSTRFIXED | VTEXTFIXED, "PS1=\\w \\$ ",
1234 #endif /* else vps1 depends on uid */
1235 {&vps2, VSTRFIXED | VTEXTFIXED, "PS2=> ",
1237 {&voptind, VSTRFIXED | VTEXTFIXED, "OPTIND=1",
1239 #ifdef CONFIG_LOCALE_SUPPORT
1240 {&vlc_all, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=",
1242 {&vlc_ctype, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=",
1251 static struct var *vartab[VTABSIZE];
1254 * The following macros access the values of the above variables.
1255 * They have to skip over the name. They return the null string
1256 * for unset variables.
1259 #define ifsval() (vifs.text + 4)
1260 #define ifsset() ((vifs.flags & VUNSET) == 0)
1261 #define mailval() (vmail.text + 5)
1262 #define mpathval() (vmpath.text + 9)
1263 #define pathval() (vpath.text + 5)
1264 #define ps1val() (vps1.text + 4)
1265 #define ps2val() (vps2.text + 4)
1266 #define optindval() (voptind.text + 7)
1268 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1270 static void initvar(void);
1271 static void setvar(const char *, const char *, int);
1272 static void setvareq(char *, int);
1273 static void listsetvar(struct strlist *);
1274 static const char *lookupvar(const char *);
1275 static const char *bltinlookup(const char *);
1276 static char **environment(void);
1277 static int showvarscmd(int, char **);
1278 static void mklocal(char *);
1279 static void poplocalvars(void);
1280 static int unsetvar(const char *);
1281 static int varequal(const char *, const char *);
1284 static char *arg0; /* value of $0 */
1285 static struct shparam shellparam; /* current positional parameters */
1286 static char **argptr; /* argument list for builtin commands */
1287 static char *optionarg; /* set by nextopt (like getopt) */
1288 static char *optptr; /* used by nextopt */
1289 static char *minusc; /* argument to -c option */
1292 #ifdef CONFIG_ASH_ALIAS
1294 #define ALIASINUSE 1
1306 static struct alias *atab[ATABSIZE];
1308 static void setalias(char *, char *);
1309 static struct alias **hashalias(const char *);
1310 static struct alias *freealias(struct alias *);
1311 static struct alias **__lookupalias(const char *);
1313 static void setalias(char *name, char *val)
1315 struct alias *ap, **app;
1317 app = __lookupalias(name);
1321 if (!(ap->flag & ALIASINUSE)) {
1324 ap->val = xstrdup(val);
1325 ap->flag &= ~ALIASDEAD;
1328 ap = xmalloc(sizeof(struct alias));
1329 ap->name = xstrdup(name);
1330 ap->val = xstrdup(val);
1338 static int unalias(char *name)
1342 app = __lookupalias(name);
1346 *app = freealias(*app);
1354 static void rmaliases(void)
1356 struct alias *ap, **app;
1360 for (i = 0; i < ATABSIZE; i++) {
1362 for (ap = *app; ap; ap = *app) {
1363 *app = freealias(*app);
1372 static void printalias(const struct alias *ap)
1376 p = single_quote(ap->val);
1377 printf("alias %s=%s\n", ap->name, p);
1383 * TODO - sort output
1385 static int aliascmd(int argc, char **argv)
1394 for (i = 0; i < ATABSIZE; i++)
1395 for (ap = atab[i]; ap; ap = ap->next) {
1400 while ((n = *++argv) != NULL) {
1401 if ((v = strchr(n + 1, '=')) == NULL) { /* n+1: funny ksh stuff */
1402 if ((ap = *__lookupalias(n)) == NULL) {
1403 out2fmt("%s: %s not found\n", "alias", n);
1416 static int unaliascmd(int argc, char **argv)
1420 while ((i = nextopt("a")) != '\0') {
1426 for (i = 0; *argptr; argptr++) {
1427 if (unalias(*argptr)) {
1428 out2fmt("%s: %s not found\n", "unalias", *argptr);
1436 static struct alias **hashalias(const char *p)
1438 unsigned int hashval;
1443 return &atab[hashval % ATABSIZE];
1446 static struct alias *freealias(struct alias *ap)
1450 if (ap->flag & ALIASINUSE) {
1451 ap->flag |= ALIASDEAD;
1463 static struct alias **__lookupalias(const char *name)
1465 struct alias **app = hashalias(name);
1467 for (; *app; app = &(*app)->next) {
1468 if (equal(name, (*app)->name)) {
1477 #ifdef CONFIG_ASH_MATH_SUPPORT
1478 /* The generated file arith.c has been replaced with a custom hand
1479 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1480 * This is now part of libbb, so that it can be used by all the shells
1482 static void expari(int);
1485 static char *trap[NSIG]; /* trap handler commands */
1486 static char sigmode[NSIG - 1]; /* current value of signal */
1487 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1488 static int pendingsigs; /* indicates some signal received */
1491 * This file was generated by the mkbuiltins program.
1494 #ifdef CONFIG_ASH_JOB_CONTROL
1495 static int bgcmd(int, char **);
1496 static int fgcmd(int, char **);
1497 static int killcmd(int, char **);
1499 static int bltincmd(int, char **);
1500 static int cdcmd(int, char **);
1501 static int breakcmd(int, char **);
1503 #ifdef CONFIG_ASH_CMDCMD
1504 static int commandcmd(int, char **);
1506 static int dotcmd(int, char **);
1507 static int evalcmd(int, char **);
1508 static int execcmd(int, char **);
1509 static int exitcmd(int, char **);
1510 static int exportcmd(int, char **);
1511 static int histcmd(int, char **);
1512 static int hashcmd(int, char **);
1513 static int helpcmd(int, char **);
1514 static int jobscmd(int, char **);
1515 static int localcmd(int, char **);
1516 static int pwdcmd(int, char **);
1517 static int readcmd(int, char **);
1518 static int returncmd(int, char **);
1519 static int setcmd(int, char **);
1520 static int setvarcmd(int, char **);
1521 static int shiftcmd(int, char **);
1522 static int trapcmd(int, char **);
1523 static int umaskcmd(int, char **);
1525 #ifdef CONFIG_ASH_ALIAS
1526 static int aliascmd(int, char **);
1527 static int unaliascmd(int, char **);
1529 static int unsetcmd(int, char **);
1530 static int waitcmd(int, char **);
1531 static int ulimitcmd(int, char **);
1532 static int timescmd(int, char **);
1534 #ifdef CONFIG_ASH_MATH_SUPPORT
1535 static int letcmd(int, char **);
1537 static int typecmd(int, char **);
1539 #ifdef CONFIG_ASH_GETOPTS
1540 static int getoptscmd(int, char **);
1544 static int true_main(int, char **);
1546 #ifndef CONFIG_FALSE
1547 static int false_main(int, char **);
1550 static void setpwd(const char *, int);
1553 #define BUILTIN_NOSPEC "0"
1554 #define BUILTIN_SPECIAL "1"
1555 #define BUILTIN_REGULAR "2"
1556 #define BUILTIN_ASSIGN "4"
1557 #define BUILTIN_SPEC_ASSG "5"
1558 #define BUILTIN_REG_ASSG "6"
1560 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1561 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1562 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1566 int (*const builtinfunc) (int, char **);
1571 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1572 * the binary search in find_builtin() will stop working. If you value
1573 * your kneecaps, you'll be sure to *make sure* that any changes made
1574 * to this array result in the listing remaining in ascii order. You
1577 static const struct builtincmd builtincmds[] = {
1578 {BUILTIN_SPECIAL ".", dotcmd}, /* first, see declare DOTCMD */
1579 {BUILTIN_SPECIAL ":", true_main},
1580 #ifdef CONFIG_ASH_ALIAS
1581 {BUILTIN_REG_ASSG "alias", aliascmd},
1583 #ifdef CONFIG_ASH_JOB_CONTROL
1584 {BUILTIN_REGULAR "bg", bgcmd},
1586 {BUILTIN_SPECIAL "break", breakcmd},
1587 {BUILTIN_SPECIAL "builtin", bltincmd},
1588 {BUILTIN_REGULAR "cd", cdcmd},
1589 {BUILTIN_NOSPEC "chdir", cdcmd},
1590 #ifdef CONFIG_ASH_CMDCMD
1591 {BUILTIN_REGULAR "command", commandcmd},
1593 {BUILTIN_SPECIAL "continue", breakcmd},
1594 {BUILTIN_SPECIAL "eval", evalcmd},
1595 {BUILTIN_SPECIAL "exec", execcmd},
1596 {BUILTIN_SPECIAL "exit", exitcmd},
1597 {BUILTIN_SPEC_ASSG "export", exportcmd},
1598 {BUILTIN_REGULAR "false", false_main},
1599 {BUILTIN_REGULAR "fc", histcmd},
1600 #ifdef CONFIG_ASH_JOB_CONTROL
1601 {BUILTIN_REGULAR "fg", fgcmd},
1603 #ifdef CONFIG_ASH_GETOPTS
1604 {BUILTIN_REGULAR "getopts", getoptscmd},
1606 {BUILTIN_NOSPEC "hash", hashcmd},
1607 {BUILTIN_NOSPEC "help", helpcmd},
1608 {BUILTIN_REGULAR "jobs", jobscmd},
1609 #ifdef CONFIG_ASH_JOB_CONTROL
1610 {BUILTIN_REGULAR "kill", killcmd},
1612 #ifdef CONFIG_ASH_MATH_SUPPORT
1613 {BUILTIN_REGULAR "let", letcmd},
1615 {BUILTIN_ASSIGN "local", localcmd},
1616 {BUILTIN_NOSPEC "pwd", pwdcmd},
1617 {BUILTIN_REGULAR "read", readcmd},
1618 {BUILTIN_SPEC_ASSG "readonly", exportcmd},
1619 {BUILTIN_SPECIAL "return", returncmd},
1620 {BUILTIN_SPECIAL "set", setcmd},
1621 {BUILTIN_NOSPEC "setvar", setvarcmd},
1622 {BUILTIN_SPECIAL "shift", shiftcmd},
1623 {BUILTIN_SPECIAL "times", timescmd},
1624 {BUILTIN_SPECIAL "trap", trapcmd},
1625 {BUILTIN_REGULAR "true", true_main},
1626 {BUILTIN_NOSPEC "type", typecmd},
1627 {BUILTIN_NOSPEC "ulimit", ulimitcmd},
1628 {BUILTIN_REGULAR "umask", umaskcmd},
1629 #ifdef CONFIG_ASH_ALIAS
1630 {BUILTIN_REGULAR "unalias", unaliascmd},
1632 {BUILTIN_SPECIAL "unset", unsetcmd},
1633 {BUILTIN_REGULAR "wait", waitcmd},
1636 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1638 #define DOTCMD &builtincmds[0]
1639 static struct builtincmd *BLTINCMD;
1640 static struct builtincmd *EXECCMD;
1641 static struct builtincmd *EVALCMD;
1644 #define JOBSTOPPED 1 /* all procs are stopped */
1645 #define JOBDONE 2 /* all procs are completed */
1648 * A job structure contains information about a job. A job is either a
1649 * single process or a set of processes contained in a pipeline. In the
1650 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1655 pid_t pid; /* process id */
1656 int status; /* status flags (defined above) */
1657 char *cmd; /* text of command being run */
1661 static int job_warning; /* user was warned about stopped jobs */
1663 #ifdef CONFIG_ASH_JOB_CONTROL
1664 static void setjobctl(int enable);
1666 #define setjobctl(on) /* do nothing */
1671 struct procstat ps0; /* status of process */
1672 struct procstat *ps; /* status or processes when more than one */
1673 short nprocs; /* number of processes */
1674 short pgrp; /* process group of this job */
1675 char state; /* true if job is finished */
1676 char used; /* true if this entry is in used */
1677 char changed; /* true if status has changed */
1678 #ifdef CONFIG_ASH_JOB_CONTROL
1679 char jobctl; /* job running under job control */
1683 static struct job *jobtab; /* array of jobs */
1684 static int njobs; /* size of array */
1685 static int backgndpid = -1; /* pid of last background process */
1687 #ifdef CONFIG_ASH_JOB_CONTROL
1688 static int initialpgrp; /* pgrp of shell on invocation */
1689 static int curjob; /* current job */
1693 static struct job *makejob(const union node *, int);
1694 static int forkshell(struct job *, const union node *, int);
1695 static int waitforjob(struct job *);
1697 static int docd(char *, int);
1698 static void getpwd(void);
1700 static char *padvance(const char **, const char *);
1702 static char nullstr[1]; /* zero length string */
1703 static char *curdir = nullstr; /* current working directory */
1705 static int cdcmd(int argc, char **argv)
1714 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1715 error("HOME not set");
1718 if (dest[0] == '-' && dest[1] == '\0') {
1719 dest = bltinlookup("OLDPWD");
1720 if (!dest || !*dest) {
1729 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1731 while ((p = padvance(&path, dest)) != NULL) {
1732 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1737 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1739 print = strcmp(p, dest);
1741 if (docd(p, print) >= 0)
1746 error("can't cd to %s", dest);
1752 * Update curdir (the name of the current directory) in response to a
1753 * cd command. We also call hashcd to let the routines in exec.c know
1754 * that the current directory has changed.
1757 static void hashcd(void);
1759 static inline void updatepwd(const char *dir)
1761 hashcd(); /* update command hash table */
1764 * If our argument is NULL, we don't know the current directory
1766 if (dir == NULL || curdir == nullstr) {
1774 * Actually do the chdir. In an interactive shell, print the
1775 * directory name if "print" is nonzero.
1778 static int docd(char *dest, int print)
1780 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1782 if (chdir(dest) < 0) {
1794 static int pwdcmd(int argc, char **argv)
1800 /* Ask system the current directory */
1801 static void getpwd(void)
1803 curdir = xgetcwd(0);
1808 static void setpwd(const char *val, int setold)
1813 setvar("OLDPWD", curdir, VEXPORT);
1816 if (curdir != nullstr) {
1817 if (val != NULL && *val != '/')
1818 val = cated = concat_path_file(curdir, val);
1824 curdir = simplify_path(val);
1827 setvar("PWD", curdir, VEXPORT);
1831 * Errors and exceptions.
1835 * Code to handle exceptions in C.
1839 * We enclose jmp_buf in a structure so that we can declare pointers to
1840 * jump locations. The global variable handler contains the location to
1841 * jump to when an exception occurs, and the global variable exception
1842 * contains a code identifying the exeception. To implement nested
1843 * exception handlers, the user should save the value of handler on entry
1844 * to an inner scope, set handler to point to a jmploc structure for the
1845 * inner scope, and restore handler on exit from the scope.
1853 #define EXINT 0 /* SIGINT received */
1854 #define EXERROR 1 /* a generic error */
1855 #define EXSHELLPROC 2 /* execute a shell procedure */
1856 #define EXEXEC 3 /* command execution failed */
1857 #define EXREDIR 4 /* redirection error */
1859 static struct jmploc *handler;
1860 static int exception;
1862 static void exverror(int, const char *, va_list)
1863 __attribute__ ((__noreturn__));
1866 * Called to raise an exception. Since C doesn't include exceptions, we
1867 * just do a longjmp to the exception handler. The type of exception is
1868 * stored in the global variable "exception".
1871 static void exraise(int) __attribute__ ((__noreturn__));
1873 static void exraise(int e)
1876 if (handler == NULL)
1881 longjmp(handler->loc, 1);
1886 * Called from trap.c when a SIGINT is received. (If the user specifies
1887 * that SIGINT is to be trapped or ignored using the trap builtin, then
1888 * this routine is not called.) Suppressint is nonzero when interrupts
1889 * are held using the INTOFF macro. The call to _exit is necessary because
1890 * there is a short period after a fork before the signal handlers are
1891 * set to the appropriate value for the child. (The test for iflag is
1892 * just defensive programming.)
1895 static void onint(void)
1904 sigemptyset(&mysigset);
1905 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1906 if (!(rootshell && iflag)) {
1907 signal(SIGINT, SIG_DFL);
1915 static char *commandname; /* currently executing command */
1918 * Exverror is called to raise the error exception. If the first argument
1919 * is not NULL then error prints an error message using printf style
1920 * formatting. It then raises the error exception.
1922 static void exverror(int cond, const char *msg, va_list ap)
1929 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1931 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1935 out2fmt("%s: ", commandname);
1936 vfprintf(stderr, msg, ap);
1944 static void error(const char *msg, ...)
1949 exverror(EXERROR, msg, ap);
1955 static void exerror(int cond, const char *msg, ...)
1960 exverror(cond, msg, ap);
1968 * Table of error messages.
1972 short errcode; /* error number */
1973 short action; /* operation which encountered the error */
1977 * Types of operations (passed to the errmsg routine).
1980 #define E_OPEN 01 /* opening a file */
1981 #define E_CREAT 02 /* creating a file */
1982 #define E_EXEC 04 /* executing a program */
1984 #define ALL (E_OPEN|E_CREAT|E_EXEC)
1986 static const struct errname errormsg[] = {
2040 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2043 * Return a string describing an error. The returned string may be a
2044 * pointer to a static buffer that will be overwritten on the next call.
2045 * Action describes the operation that got the error.
2048 static const char *errmsg(int e, int action)
2050 struct errname const *ep;
2051 static char buf[12];
2053 for (ep = errormsg; ep < errormsg + ERRNAME_SIZE; ep++) {
2054 if (ep->errcode == e && (ep->action & action) != 0)
2058 snprintf(buf, sizeof buf, "error %d", e);
2063 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
2064 static void __inton()
2066 if (--suppressint == 0 && intpending) {
2070 static void forceinton(void)
2078 /* flags in argument to evaltree */
2079 #define EV_EXIT 01 /* exit after evaluating tree */
2080 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2081 #define EV_BACKCMD 04 /* command executing within back quotes */
2083 static int evalskip; /* set if we are skipping commands */
2084 static int skipcount; /* number of levels to skip */
2085 static int loopnest; /* current loop nesting level */
2086 static int funcnest; /* depth of function calls */
2089 static struct strlist *cmdenviron; /* environment for builtin command */
2090 static int exitstatus; /* exit status of last command */
2091 static int oexitstatus; /* saved exit status */
2093 static void evalsubshell(const union node *, int);
2094 static void expredir(union node *);
2095 static void prehash(union node *);
2096 static void eprintlist(struct strlist *);
2098 static union node *parsecmd(int);
2101 * Called to reset things after an exception.
2105 * The eval commmand.
2107 static void evalstring(char *, int);
2109 static int evalcmd(int argc, char **argv)
2118 STARTSTACKSTR(concat);
2122 STPUTC(*p++, concat);
2123 if ((p = *ap++) == NULL)
2125 STPUTC(' ', concat);
2127 STPUTC('\0', concat);
2128 p = grabstackstr(concat);
2130 evalstring(p, EV_TESTED);
2136 * Execute a command or commands contained in a string.
2139 static void evaltree(union node *, int);
2140 static void setinputstring(char *);
2141 static void popfile(void);
2142 static void setstackmark(struct stackmark *mark);
2143 static void popstackmark(struct stackmark *mark);
2146 static void evalstring(char *s, int flag)
2149 struct stackmark smark;
2151 setstackmark(&smark);
2153 while ((n = parsecmd(0)) != NEOF) {
2155 popstackmark(&smark);
2158 popstackmark(&smark);
2161 static struct builtincmd *find_builtin(const char *);
2162 static void expandarg(union node *, struct arglist *, int);
2163 static void calcsize(const union node *);
2164 static union node *copynode(const union node *);
2167 * Make a copy of a parse tree.
2170 static int funcblocksize; /* size of structures in function */
2171 static int funcstringsize; /* size of strings in node */
2172 static pointer funcblock; /* block to allocate function from */
2173 static char *funcstring; /* block to allocate strings from */
2176 static inline union node *copyfunc(union node *n)
2183 funcblock = xmalloc(funcblocksize + funcstringsize);
2184 funcstring = (char *) funcblock + funcblocksize;
2189 * Add a new command entry, replacing any existing command entry for
2193 static inline void addcmdentry(char *name, struct cmdentry *entry)
2195 struct tblentry *cmdp;
2198 cmdp = cmdlookup(name, 1);
2199 if (cmdp->cmdtype == CMDFUNCTION) {
2200 free(cmdp->param.func);
2202 cmdp->cmdtype = entry->cmdtype;
2203 cmdp->param = entry->u;
2207 static inline void evalloop(const union node *n, int flags)
2215 evaltree(n->nbinary.ch1, EV_TESTED);
2217 skipping:if (evalskip == SKIPCONT && --skipcount <= 0) {
2221 if (evalskip == SKIPBREAK && --skipcount <= 0)
2225 if (n->type == NWHILE) {
2226 if (exitstatus != 0)
2229 if (exitstatus == 0)
2232 evaltree(n->nbinary.ch2, flags);
2233 status = exitstatus;
2238 exitstatus = status;
2241 static void evalfor(const union node *n, int flags)
2243 struct arglist arglist;
2246 struct stackmark smark;
2248 setstackmark(&smark);
2249 arglist.lastp = &arglist.list;
2250 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
2251 oexitstatus = exitstatus;
2252 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2256 *arglist.lastp = NULL;
2261 for (sp = arglist.list; sp; sp = sp->next) {
2262 setvar(n->nfor.var, sp->text, 0);
2263 evaltree(n->nfor.body, flags);
2265 if (evalskip == SKIPCONT && --skipcount <= 0) {
2269 if (evalskip == SKIPBREAK && --skipcount <= 0)
2276 popstackmark(&smark);
2279 static inline void evalcase(const union node *n, int flags)
2283 struct arglist arglist;
2284 struct stackmark smark;
2286 setstackmark(&smark);
2287 arglist.lastp = &arglist.list;
2288 oexitstatus = exitstatus;
2289 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2290 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
2291 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
2292 if (casematch(patp, arglist.list->text)) {
2293 if (evalskip == 0) {
2294 evaltree(cp->nclist.body, flags);
2301 popstackmark(&smark);
2305 * Evaluate a pipeline. All the processes in the pipeline are children
2306 * of the process creating the pipeline. (This differs from some versions
2307 * of the shell, which make the last process in a pipeline the parent
2311 static inline void evalpipe(union node *n, int flags)
2314 struct nodelist *lp;
2319 TRACE(("evalpipe(0x%lx) called\n", (long) n));
2321 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
2325 jp = makejob(n, pipelen);
2327 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
2331 if (pipe(pip) < 0) {
2333 error("Pipe call failed");
2336 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2349 evaltree(lp->n, flags);
2356 if (n->npipe.backgnd == 0) {
2357 exitstatus = waitforjob(jp);
2358 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2363 static void find_command(const char *, struct cmdentry *, int, const char *);
2365 static int isassignment(const char *word)
2367 if (!is_name(*word)) {
2372 } while (is_in_name(*word));
2373 return *word == '=';
2377 static void evalcommand(union node *cmd, int flags)
2379 struct stackmark smark;
2381 struct arglist arglist;
2382 struct arglist varlist;
2388 struct cmdentry cmdentry;
2390 char *volatile savecmdname;
2391 volatile struct shparam saveparam;
2392 struct localvar *volatile savelocalvars;
2397 struct jmploc *volatile savehandler;
2398 struct jmploc jmploc;
2401 /* Avoid longjmp clobbering */
2409 /* First expand the arguments. */
2410 TRACE(("evalcommand(0x%lx, %d) called\n", (long) cmd, flags));
2411 setstackmark(&smark);
2412 arglist.lastp = &arglist.list;
2413 varlist.lastp = &varlist.list;
2415 oexitstatus = exitstatus;
2418 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2419 expandarg(argp, &varlist, EXP_VARTILDE);
2421 for (argp = cmd->ncmd.args; argp && !arglist.list; argp = argp->narg.next) {
2422 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2425 struct builtincmd *bcmd;
2428 bcmd = find_builtin(arglist.list->text);
2429 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2430 for (; argp; argp = argp->narg.next) {
2431 if (pseudovarflag && isassignment(argp->narg.text)) {
2432 expandarg(argp, &arglist, EXP_VARTILDE);
2435 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2438 *arglist.lastp = NULL;
2439 *varlist.lastp = NULL;
2440 expredir(cmd->ncmd.redirect);
2442 for (sp = arglist.list; sp; sp = sp->next)
2444 argv = stalloc(sizeof(char *) * (argc + 1));
2446 for (sp = arglist.list; sp; sp = sp->next) {
2447 TRACE(("evalcommand arg: %s\n", sp->text));
2452 if (iflag && funcnest == 0 && argc > 0)
2456 /* Print the command if xflag is set. */
2459 eprintlist(varlist.list);
2460 eprintlist(arglist.list);
2464 /* Now locate the command. */
2466 cmdentry.cmdtype = CMDBUILTIN;
2467 cmdentry.u.cmd = BLTINCMD;
2470 const char *oldpath;
2471 int findflag = DO_ERR;
2475 * Modify the command lookup path, if a PATH= assignment
2478 for (sp = varlist.list; sp; sp = sp->next)
2479 if (varequal(sp->text, defpathvar)) {
2480 path = sp->text + 5;
2481 findflag |= DO_BRUTE;
2484 oldfindflag = findflag;
2487 find_command(argv[0], &cmdentry, findflag, path);
2488 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2492 /* implement bltin and command here */
2493 if (cmdentry.cmdtype != CMDBUILTIN) {
2496 if (spclbltin < 0) {
2497 spclbltin = !!(IS_BUILTIN_SPECIAL(cmdentry.u.cmd)) * 2;
2499 if (cmdentry.u.cmd == BLTINCMD) {
2501 struct builtincmd *bcmd;
2506 if (!(bcmd = find_builtin(*argv))) {
2507 out2fmt("%s: not found\n", *argv);
2511 cmdentry.u.cmd = bcmd;
2512 if (bcmd != BLTINCMD)
2516 if (cmdentry.u.cmd == find_builtin("command")) {
2521 if (*argv[0] == '-') {
2522 if (!equal(argv[0], "-p")) {
2532 findflag |= DO_BRUTE;
2535 findflag = oldfindflag;
2537 findflag |= DO_NOFUN;
2545 /* Fork off a child process if necessary. */
2546 if (cmd->ncmd.backgnd
2547 || (cmdentry.cmdtype == CMDNORMAL && (!(flags & EV_EXIT) || trap[0]))
2550 jp = makejob(cmd, 1);
2551 mode = cmd->ncmd.backgnd;
2552 if (forkshell(jp, cmd, mode) != 0)
2553 goto parent; /* at end of routine */
2560 /* This is the child process if a fork occurred. */
2561 /* Execute the command. */
2562 if (cmdentry.cmdtype == CMDFUNCTION) {
2564 trputs("Shell function: ");
2567 exitstatus = oexitstatus;
2568 saveparam = shellparam;
2569 shellparam.malloc = 0;
2570 shellparam.nparam = argc - 1;
2571 shellparam.p = argv + 1;
2573 savelocalvars = localvars;
2576 if (setjmp(jmploc.loc)) {
2577 if (exception == EXREDIR) {
2581 saveparam.optind = shellparam.optind;
2582 saveparam.optoff = shellparam.optoff;
2583 freeparam(&shellparam);
2584 shellparam = saveparam;
2586 localvars = savelocalvars;
2587 handler = savehandler;
2588 longjmp(handler->loc, 1);
2590 savehandler = handler;
2592 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2593 listsetvar(varlist.list);
2595 evaltree(cmdentry.u.func, flags & EV_TESTED);
2600 localvars = savelocalvars;
2601 saveparam.optind = shellparam.optind;
2602 saveparam.optoff = shellparam.optoff;
2603 freeparam(&shellparam);
2604 shellparam = saveparam;
2605 handler = savehandler;
2608 if (evalskip == SKIPFUNC) {
2612 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2616 trputs("builtin command: ");
2619 redir = (cmdentry.u.cmd == EXECCMD) ? 0 : REDIR_PUSH;
2620 savecmdname = commandname;
2622 listsetvar(varlist.list);
2624 cmdenviron = varlist.list;
2627 if (setjmp(jmploc.loc)) {
2629 exitstatus = (e == EXINT) ? SIGINT + 128 : 2;
2632 savehandler = handler;
2634 redirect(cmd->ncmd.redirect, redir);
2635 commandname = argv[0];
2637 optptr = NULL; /* initialize nextopt */
2638 exitstatus = (*cmdentry.u.cmd->builtinfunc) (argc, argv);
2642 commandname = savecmdname;
2643 handler = savehandler;
2645 if (e == EXINT || spclbltin & 2) {
2651 if (cmdentry.u.cmd != EXECCMD)
2655 trputs("normal command: ");
2658 redirect(cmd->ncmd.redirect, 0);
2660 for (sp = varlist.list; sp; sp = sp->next)
2661 setvareq(sp->text, VEXPORT | VSTACK);
2662 envp = environment();
2663 shellexec(argv, envp, path, cmdentry.u.index);
2665 if (flags & EV_EXIT)
2666 exitshell(exitstatus);
2669 parent: /* parent process gets here (if we forked) */
2670 if (mode == 0) { /* argument to fork */
2671 exitstatus = waitforjob(jp);
2677 setvar("_", lastarg, 0);
2678 popstackmark(&smark);
2682 * Evaluate a parse tree. The value is left in the global variable
2685 static void evaltree(union node *n, int flags)
2690 TRACE(("evaltree(NULL) called\n"));
2693 TRACE(("evaltree(0x%lx: %d) called\n", (long) n, n->type));
2696 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2699 evaltree(n->nbinary.ch2, flags);
2702 evaltree(n->nbinary.ch1, EV_TESTED);
2703 if (evalskip || exitstatus != 0)
2705 evaltree(n->nbinary.ch2, flags);
2708 evaltree(n->nbinary.ch1, EV_TESTED);
2709 if (evalskip || exitstatus == 0)
2711 evaltree(n->nbinary.ch2, flags);
2714 expredir(n->nredir.redirect);
2715 redirect(n->nredir.redirect, REDIR_PUSH);
2716 evaltree(n->nredir.n, flags);
2720 evalsubshell(n, flags);
2723 evalsubshell(n, flags);
2726 evaltree(n->nif.test, EV_TESTED);
2729 if (exitstatus == 0)
2730 evaltree(n->nif.ifpart, flags);
2731 else if (n->nif.elsepart)
2732 evaltree(n->nif.elsepart, flags);
2748 struct builtincmd *bcmd;
2749 struct cmdentry entry;
2751 if ((bcmd = find_builtin(n->narg.text)) && IS_BUILTIN_SPECIAL(bcmd)
2753 out2fmt("%s is a special built-in\n", n->narg.text);
2757 entry.cmdtype = CMDFUNCTION;
2758 entry.u.func = copyfunc(n->narg.next);
2759 addcmdentry(n->narg.text, &entry);
2764 evaltree(n->nnot.com, EV_TESTED);
2765 exitstatus = !exitstatus;
2773 evalcommand(n, flags);
2778 printf("Node type = %d\n", n->type);
2785 if (flags & EV_EXIT ||
2786 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2788 exitshell(exitstatus);
2792 * Kick off a subshell to evaluate a tree.
2795 static void evalsubshell(const union node *n, int flags)
2798 int backgnd = (n->type == NBACKGND);
2800 expredir(n->nredir.redirect);
2801 if (!backgnd && flags & EV_EXIT && !trap[0])
2805 if (forkshell(jp, n, backgnd) == 0) {
2809 flags &= ~EV_TESTED;
2811 redirect(n->nredir.redirect, 0);
2812 evaltree(n->nredir.n, flags); /* never returns */
2815 exitstatus = waitforjob(jp);
2821 * Compute the names of the files in a redirection list.
2824 static void fixredir(union node *n, const char *text, int err);
2826 static void expredir(union node *n)
2830 for (redir = n; redir; redir = redir->nfile.next) {
2833 fn.lastp = &fn.list;
2834 oexitstatus = exitstatus;
2835 switch (redir->type) {
2841 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2842 redir->nfile.expfname = fn.list->text;
2846 if (redir->ndup.vname) {
2847 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2848 fixredir(redir, fn.list->text, 1);
2857 * Execute a command inside back quotes. If it's a builtin command, we
2858 * want to save its output in a block obtained from malloc. Otherwise
2859 * we fork off a subprocess and get the output of the command via a pipe.
2860 * Should be called with interrupts off.
2863 static void evalbackcmd(union node *n, struct backcmd *result)
2867 struct stackmark smark; /* unnecessary */
2869 setstackmark(&smark);
2880 error("Pipe call failed");
2882 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2887 dup_as_newfd(pip[1], 1);
2891 evaltree(n, EV_EXIT);
2894 result->fd = pip[0];
2897 popstackmark(&smark);
2898 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2899 result->fd, result->buf, result->nleft, result->jp));
2904 * Execute a simple command.
2908 * Search for a command. This is called before we fork so that the
2909 * location of the command will be available in the parent as well as
2910 * the child. The check for "goodname" is an overly conservative
2911 * check that the name will not be subject to expansion.
2914 static void prehash(union node *n)
2916 struct cmdentry entry;
2918 if (n->type == NCMD && n->ncmd.args)
2919 if (goodname(n->ncmd.args->narg.text))
2920 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
2925 * Builtin commands. Builtin commands whose functions are closely
2926 * tied to evaluation are implemented here.
2930 * No command given, or a bltin command with no arguments. Set the
2931 * specified variables.
2934 int bltincmd(int argc, char **argv)
2937 * Preserve exitstatus of a previous possible redirection
2945 * Handle break and continue commands. Break, continue, and return are
2946 * all handled by setting the evalskip flag. The evaluation routines
2947 * above all check this flag, and if it is set they start skipping
2948 * commands rather than executing them. The variable skipcount is
2949 * the number of loops to break/continue, or the number of function
2950 * levels to return. (The latter is always 1.) It should probably
2951 * be an error to break out of more loops than exist, but it isn't
2952 * in the standard shell so we don't make it one here.
2955 static int breakcmd(int argc, char **argv)
2957 int n = argc > 1 ? number(argv[1]) : 1;
2960 error("Illegal number: %s", argv[1]);
2964 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
2972 * The return command.
2975 static int returncmd(int argc, char **argv)
2977 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
2980 evalskip = SKIPFUNC;
2984 /* Do what ksh does; skip the rest of the file */
2985 evalskip = SKIPFILE;
2992 #ifndef CONFIG_FALSE
2993 static int false_main(int argc, char **argv)
3000 static int true_main(int argc, char **argv)
3007 * Controls whether the shell is interactive or not.
3010 static void setsignal(int signo);
3012 #ifdef CONFIG_ASH_MAIL
3013 static void chkmail(int silent);
3016 static void setinteractive(int on)
3018 static int is_interactive;
3019 static int do_banner = 0;
3021 if (on == is_interactive)
3026 #ifdef CONFIG_ASH_MAIL
3029 is_interactive = on;
3030 if (do_banner == 0 && is_interactive) {
3031 /* Looks like they want an interactive shell */
3032 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3033 printf("\n\n" BB_BANNER " Built-in shell (ash)\n");
3034 printf("Enter 'help' for a list of built-in commands.\n\n");
3040 static void optschanged(void)
3042 setinteractive(iflag);
3047 static int execcmd(int argc, char **argv)
3052 iflag = 0; /* exit on error */
3055 for (sp = cmdenviron; sp; sp = sp->next)
3056 setvareq(sp->text, VEXPORT | VSTACK);
3057 shellexec(argv + 1, environment(), pathval(), 0);
3062 static void eprintlist(struct strlist *sp)
3064 for (; sp; sp = sp->next) {
3065 out2fmt(" %s", sp->text);
3070 * Exec a program. Never returns. If you change this routine, you may
3071 * have to change the find_command routine as well.
3074 static const char *pathopt; /* set by padvance */
3076 static void shellexec(char **argv, char **envp, const char *path, int idx)
3081 if (strchr(argv[0], '/') != NULL
3082 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3083 || find_applet_by_name(argv[0])
3087 tryexec(argv[0], argv, envp);
3091 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3092 if (--idx < 0 && pathopt == NULL) {
3093 tryexec(cmdname, argv, envp);
3094 if (errno != ENOENT && errno != ENOTDIR)
3101 /* Map to POSIX errors */
3113 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3118 * Clear traps on a fork.
3120 static void clear_traps(void)
3124 for (tp = trap; tp < &trap[NSIG]; tp++) {
3125 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3130 setsignal(tp - trap);
3137 static int preadbuffer(void);
3138 static void pushfile(void);
3141 * Read a character from the script, returning PEOF on end of file.
3142 * Nul characters in the input are silently discarded.
3145 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
3146 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3147 static int pgetc(void)
3149 return pgetc_macro();
3152 static int pgetc_macro(void)
3154 return --parsenleft >= 0 ? *parsenextc++ : preadbuffer();
3157 static inline int pgetc(void)
3159 return pgetc_macro();
3165 * Undo the last call to pgetc. Only one character may be pushed back.
3166 * PEOF may be pushed back.
3169 static void pungetc(void)
3176 static void popfile(void)
3178 struct parsefile *pf = parsefile;
3186 parsefile = pf->prev;
3188 parsenleft = parsefile->nleft;
3189 parselleft = parsefile->lleft;
3190 parsenextc = parsefile->nextc;
3191 plinno = parsefile->linno;
3197 * Return to top level.
3200 static void popallfiles(void)
3202 while (parsefile != &basepf)
3207 * Close the file(s) that the shell is reading commands from. Called
3208 * after a fork is done.
3211 static void closescript(void)
3214 if (parsefile->fd > 0) {
3215 close(parsefile->fd);
3222 * Like setinputfile, but takes an open file descriptor. Call this with
3226 static void setinputfd(int fd, int push)
3228 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3234 while (parsefile->strpush)
3238 if (parsefile->buf == NULL)
3239 parsefile->buf = xmalloc(BUFSIZ);
3240 parselleft = parsenleft = 0;
3246 * Set the input to take input from a file. If push is set, push the
3247 * old input onto the stack first.
3250 static void setinputfile(const char *fname, int push)
3256 if ((fd = open(fname, O_RDONLY)) < 0)
3257 error("Can't open %s", fname);
3259 myfileno2 = dup_as_newfd(fd, 10);
3262 error("Out of file descriptors");
3265 setinputfd(fd, push);
3270 static void tryexec(char *cmd, char **argv, char **envp)
3274 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3276 char **argv_l = argv;
3279 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3280 name = get_last_path_component(name);
3283 for (argc_l = 0; *argv_l != NULL; argv_l++, argc_l++)
3286 for (argc_l = 0; *argv_l != NULL; argv_l++, argc_l++)
3288 run_applet_by_name(name, argc_l, argv);
3291 execve(cmd, argv, envp);
3294 } else if (errno == ENOEXEC) {
3298 for (ap = argv; *ap; ap++);
3299 ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
3300 *ap++ = cmd = "/bin/sh";
3301 while ((*ap++ = *argv++));
3307 static char *commandtext(const union node *);
3310 * Do a path search. The variable path (passed by reference) should be
3311 * set to the start of the path before the first call; padvance will update
3312 * this value as it proceeds. Successive calls to padvance will return
3313 * the possible path expansions in sequence. If an option (indicated by
3314 * a percent sign) appears in the path entry then the global variable
3315 * pathopt will be set to point to it; otherwise pathopt will be set to
3319 static const char *pathopt;
3321 static void growstackblock(void);
3324 static char *padvance(const char **path, const char *name)
3334 for (p = start; *p && *p != ':' && *p != '%'; p++);
3335 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3336 while (stackblocksize() < len)
3340 memcpy(q, start, p - start);
3348 while (*p && *p != ':')
3355 return stalloc(len);
3359 * Wrapper around strcmp for qsort/bsearch/...
3361 static int pstrcmp(const void *a, const void *b)
3363 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3367 * Find a keyword is in a sorted array.
3370 static const char *const *findkwd(const char *s)
3372 return bsearch(s, tokname_array + KWDOFFSET,
3373 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
3374 sizeof(const char *), pstrcmp);
3378 /*** Command hashing code ***/
3380 static int hashcmd(int argc, char **argv)
3382 struct tblentry **pp;
3383 struct tblentry *cmdp;
3386 struct cmdentry entry;
3389 #ifdef CONFIG_ASH_ALIAS
3390 const struct alias *ap;
3394 while ((c = nextopt("rvV")) != '\0') {
3398 } else if (c == 'v' || c == 'V') {
3402 if (*argptr == NULL) {
3403 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3404 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3405 if (cmdp->cmdtype != CMDBUILTIN) {
3406 printentry(cmdp, verbose);
3413 while ((name = *argptr++) != NULL) {
3414 if ((cmdp = cmdlookup(name, 0)) != NULL
3415 && (cmdp->cmdtype == CMDNORMAL
3416 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3418 #ifdef CONFIG_ASH_ALIAS
3419 /* Then look at the aliases */
3420 if ((ap = *__lookupalias(name)) != NULL) {
3422 printf("%s is an alias for %s\n", name, ap->val);
3428 /* First look at the keywords */
3429 if (findkwd(name) != 0) {
3431 printf("%s is a shell keyword\n", name);
3437 find_command(name, &entry, DO_ERR, pathval());
3438 if (entry.cmdtype == CMDUNKNOWN)
3441 cmdp = cmdlookup(name, 0);
3443 printentry(cmdp, verbose == 'v');
3450 static void printentry(struct tblentry *cmdp, int verbose)
3456 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3457 if (cmdp->cmdtype == CMDNORMAL) {
3458 idx = cmdp->param.index;
3461 name = padvance(&path, cmdp->cmdname);
3463 } while (--idx >= 0);
3466 } else if (cmdp->cmdtype == CMDBUILTIN) {
3468 out1str("a shell builtin");
3469 } else if (cmdp->cmdtype == CMDFUNCTION) {
3472 out1str("a function\n");
3473 name = commandtext(cmdp->param.func);
3474 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3480 error("internal error: cmdtype %d", cmdp->cmdtype);
3483 puts(cmdp->rehash ? "*" : nullstr);
3488 /*** List the available builtins ***/
3491 static int helpcmd(int argc, char **argv)
3495 printf("\nBuilt-in commands:\n-------------------\n");
3496 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
3497 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3498 builtincmds[i].name + 1);
3504 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3506 extern const struct BB_applet applets[];
3507 extern const size_t NUM_APPLETS;
3509 for (i = 0; i < NUM_APPLETS; i++) {
3511 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
3520 return EXIT_SUCCESS;
3524 * Resolve a command name. If you change this routine, you may have to
3525 * change the shellexec routine as well.
3528 static int prefix(const char *, const char *);
3531 find_command(const char *name, struct cmdentry *entry, int act,
3534 struct tblentry *cmdp;
3544 struct builtincmd *bcmd;
3546 /* If name contains a slash, don't use the hash table */
3547 if (strchr(name, '/') != NULL) {
3549 while (stat(name, &statb) < 0) {
3550 if (errno != ENOENT && errno != ENOTDIR)
3552 entry->cmdtype = CMDUNKNOWN;
3553 entry->u.index = -1;
3556 entry->cmdtype = CMDNORMAL;
3557 entry->u.index = -1;
3560 entry->cmdtype = CMDNORMAL;
3565 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3566 if (find_applet_by_name(name)) {
3567 entry->cmdtype = CMDNORMAL;
3568 entry->u.index = -1;
3574 if (act & DO_BRUTE) {
3575 firstchange = path_change(path, &bltin);
3581 /* If name is in the table, and not invalidated by cd, we're done */
3582 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3583 if (cmdp->cmdtype == CMDFUNCTION) {
3584 if (act & DO_NOFUN) {
3589 } else if (act & DO_BRUTE) {
3590 if ((cmdp->cmdtype == CMDNORMAL &&
3591 cmdp->param.index >= firstchange) ||
3592 (cmdp->cmdtype == CMDBUILTIN &&
3593 ((builtinloc < 0 && bltin >= 0) ?
3594 bltin : builtinloc) >= firstchange)) {
3595 /* need to recompute the entry */
3604 bcmd = find_builtin(name);
3605 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3608 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3611 } else if (act & DO_BRUTE) {
3612 if (firstchange == 0) {
3617 /* If %builtin not in path, check for builtin next */
3618 if (regular || (bltin < 0 && bcmd)) {
3621 entry->cmdtype = CMDBUILTIN;
3622 entry->u.cmd = bcmd;
3626 cmdp = cmdlookup(name, 1);
3627 cmdp->cmdtype = CMDBUILTIN;
3628 cmdp->param.cmd = bcmd;
3633 /* We have to search path. */
3634 prev = -1; /* where to start */
3635 if (cmdp && cmdp->rehash) { /* doing a rehash */
3636 if (cmdp->cmdtype == CMDBUILTIN)
3639 prev = cmdp->param.index;
3645 while ((fullname = padvance(&path, name)) != NULL) {
3646 stunalloc(fullname);
3648 if (idx >= firstchange) {
3652 if (prefix("builtin", pathopt)) {
3653 if ((bcmd = find_builtin(name))) {
3657 } else if (!(act & DO_NOFUN) && prefix("func", pathopt)) {
3660 continue; /* ignore unimplemented options */
3663 /* if rehash, don't redo absolute path names */
3664 if (fullname[0] == '/' && idx <= prev && idx < firstchange) {
3667 TRACE(("searchexec \"%s\": no change\n", name));
3670 while (stat(fullname, &statb) < 0) {
3671 if (errno != ENOENT && errno != ENOTDIR)
3675 e = EACCES; /* if we fail, this will be the error */
3676 if (!S_ISREG(statb.st_mode))
3678 if (pathopt) { /* this is a %func directory */
3679 stalloc(strlen(fullname) + 1);
3680 readcmdfile(fullname);
3681 if ((cmdp = cmdlookup(name, 0)) == NULL
3682 || cmdp->cmdtype != CMDFUNCTION)
3683 error("%s not defined in %s", name, fullname);
3684 stunalloc(fullname);
3687 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3688 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3689 be a function and we're being called with DO_NOFUN */
3691 entry->cmdtype = CMDNORMAL;
3692 entry->u.index = idx;
3696 cmdp = cmdlookup(name, 1);
3697 cmdp->cmdtype = CMDNORMAL;
3698 cmdp->param.index = idx;
3703 /* We failed. If there was an entry for this command, delete it */
3704 if (cmdp && updatetbl)
3707 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3708 entry->cmdtype = CMDUNKNOWN;
3713 entry->cmdtype = cmdp->cmdtype;
3714 entry->u = cmdp->param;
3720 * Search the table of builtin commands.
3723 static struct builtincmd *find_builtin(const char *name)
3725 struct builtincmd *bp;
3727 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3734 * Called when a cd is done. Marks all commands so the next time they
3735 * are executed they will be rehashed.
3738 static void hashcd(void)
3740 struct tblentry **pp;
3741 struct tblentry *cmdp;
3743 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3744 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3745 if (cmdp->cmdtype == CMDNORMAL
3746 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3755 * Called before PATH is changed. The argument is the new value of PATH;
3756 * pathval() still returns the old value at this point. Called with
3760 static void changepath(const char *newval)
3765 firstchange = path_change(newval, &bltin);
3766 if (builtinloc < 0 && bltin >= 0)
3767 builtinloc = bltin; /* zap builtins */
3768 clearcmdentry(firstchange);
3770 /* Ensure that getenv("PATH") stays current */
3771 setenv("PATH", newval, 1);
3776 * Clear out command entries. The argument specifies the first entry in
3777 * PATH which has changed.
3780 static void clearcmdentry(int firstchange)
3782 struct tblentry **tblp;
3783 struct tblentry **pp;
3784 struct tblentry *cmdp;
3787 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
3789 while ((cmdp = *pp) != NULL) {
3790 if ((cmdp->cmdtype == CMDNORMAL &&
3791 cmdp->param.index >= firstchange)
3792 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= firstchange)) {
3805 * Locate a command in the command hash table. If "add" is nonzero,
3806 * add the command to the table if it is not already present. The
3807 * variable "lastcmdentry" is set to point to the address of the link
3808 * pointing to the entry, so that delete_cmd_entry can delete the
3812 static struct tblentry **lastcmdentry;
3814 static struct tblentry *cmdlookup(const char *name, int add)
3818 struct tblentry *cmdp;
3819 struct tblentry **pp;
3826 pp = &cmdtable[hashval % CMDTABLESIZE];
3827 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3828 if (equal(cmdp->cmdname, name))
3832 if (add && cmdp == NULL) {
3834 cmdp = *pp = xmalloc(sizeof(struct tblentry) - ARB
3835 + strlen(name) + 1);
3837 cmdp->cmdtype = CMDUNKNOWN;
3839 strcpy(cmdp->cmdname, name);
3847 * Delete the command entry returned on the last lookup.
3850 static void delete_cmd_entry(void)
3852 struct tblentry *cmdp;
3855 cmdp = *lastcmdentry;
3856 *lastcmdentry = cmdp->next;
3865 static const unsigned char nodesize[26] = {
3866 ALIGN(sizeof(struct nbinary)),
3867 ALIGN(sizeof(struct ncmd)),
3868 ALIGN(sizeof(struct npipe)),
3869 ALIGN(sizeof(struct nredir)),
3870 ALIGN(sizeof(struct nredir)),
3871 ALIGN(sizeof(struct nredir)),
3872 ALIGN(sizeof(struct nbinary)),
3873 ALIGN(sizeof(struct nbinary)),
3874 ALIGN(sizeof(struct nif)),
3875 ALIGN(sizeof(struct nbinary)),
3876 ALIGN(sizeof(struct nbinary)),
3877 ALIGN(sizeof(struct nfor)),
3878 ALIGN(sizeof(struct ncase)),
3879 ALIGN(sizeof(struct nclist)),
3880 ALIGN(sizeof(struct narg)),
3881 ALIGN(sizeof(struct narg)),
3882 ALIGN(sizeof(struct nfile)),
3883 ALIGN(sizeof(struct nfile)),
3884 ALIGN(sizeof(struct nfile)),
3885 ALIGN(sizeof(struct nfile)),
3886 ALIGN(sizeof(struct nfile)),
3887 ALIGN(sizeof(struct ndup)),
3888 ALIGN(sizeof(struct ndup)),
3889 ALIGN(sizeof(struct nhere)),
3890 ALIGN(sizeof(struct nhere)),
3891 ALIGN(sizeof(struct nnot)),
3897 * Delete a function if it exists.
3900 static void unsetfunc(char *name)
3902 struct tblentry *cmdp;
3904 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
3905 free(cmdp->param.func);
3912 * Locate and print what a word is...
3915 static int typecmd(int argc, char **argv)
3923 for (i = 1; i < argc; i++) {
3924 argv_a[0] = argv[i];
3927 err |= hashcmd(argc, argv);
3932 #ifdef CONFIG_ASH_CMDCMD
3933 static int commandcmd(int argc, char **argv)
3936 int default_path = 0;
3937 int verify_only = 0;
3938 int verbose_verify_only = 0;
3940 while ((c = nextopt("pvV")) != '\0')
3949 verbose_verify_only = 1;
3953 if (default_path + verify_only + verbose_verify_only > 1 || !*argptr) {
3954 out2str("command [-p] command [arg ...]\n"
3955 "command {-v|-V} command\n");
3959 if (verify_only || verbose_verify_only) {
3963 argv_a[0] = *argptr;
3965 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
3966 return hashcmd(argc, argv);
3973 static int path_change(const char *newval, int *bltin)
3975 const char *old, *new;
3981 firstchange = 9999; /* assume no change */
3987 if ((*old == '\0' && *new == ':')
3988 || (*old == ':' && *new == '\0'))
3990 old = new; /* ignore subsequent differences */
3994 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4001 if (builtinloc >= 0 && *bltin < 0)
4007 * Routines to expand arguments to commands. We have to deal with
4008 * backquotes, shell variables, and file metacharacters.
4013 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4014 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4017 * Structure specifying which parts of the string should be searched
4018 * for IFS characters.
4022 struct ifsregion *next; /* next region in list */
4023 int begoff; /* offset of start of region */
4024 int endoff; /* offset of end of region */
4025 int nulonly; /* search for nul bytes only */
4029 static char *expdest; /* output of current string */
4030 static struct nodelist *argbackq; /* list of back quote expressions */
4031 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4032 static struct ifsregion *ifslastp; /* last struct in list */
4033 static struct arglist exparg; /* holds expanded arg list */
4035 static void argstr(char *, int);
4036 static char *exptilde(char *, int);
4037 static void expbackq(union node *, int, int);
4038 static int subevalvar(char *, char *, int, int, int, int, int);
4039 static int varisset(char *, int);
4040 static void strtodest(const char *, int, int);
4041 static void varvalue(char *, int, int);
4042 static void recordregion(int, int, int);
4043 static void removerecordregions(int);
4044 static void ifsbreakup(char *, struct arglist *);
4045 static void ifsfree(void);
4046 static void expandmeta(struct strlist *, int);
4048 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4049 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4050 #if !defined(GLOB_BROKEN)
4051 static void addglob(const glob_t *);
4054 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4055 static void expmeta(char *, char *);
4057 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4058 static struct strlist *expsort(struct strlist *);
4059 static struct strlist *msort(struct strlist *, int);
4061 static int patmatch(char *, char *, int);
4063 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4064 static int patmatch2(char *, char *, int);
4066 static int pmatch(char *, char *, int);
4068 #define patmatch2 patmatch
4070 static char *cvtnum(int, char *);
4073 * Expand shell variables and backquotes inside a here document.
4076 /* arg: the document, fd: where to write the expanded version */
4077 static inline void expandhere(union node *arg, int fd)
4080 expandarg(arg, (struct arglist *) NULL, 0);
4081 xwrite(fd, stackblock(), expdest - stackblock());
4086 * Perform variable substitution and command substitution on an argument,
4087 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4088 * perform splitting and file name expansion. When arglist is NULL, perform
4089 * here document expansion.
4092 static void expandarg(union node *arg, struct arglist *arglist, int flag)
4097 argbackq = arg->narg.backquote;
4098 STARTSTACKSTR(expdest);
4099 ifsfirst.next = NULL;
4101 argstr(arg->narg.text, flag);
4102 if (arglist == NULL) {
4103 return; /* here document expanded */
4105 STPUTC('\0', expdest);
4106 p = grabstackstr(expdest);
4107 exparg.lastp = &exparg.list;
4111 if (flag & EXP_FULL) {
4112 ifsbreakup(p, &exparg);
4113 *exparg.lastp = NULL;
4114 exparg.lastp = &exparg.list;
4115 expandmeta(exparg.list, flag);
4117 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4119 sp = (struct strlist *) stalloc(sizeof(struct strlist));
4122 exparg.lastp = &sp->next;
4125 *exparg.lastp = NULL;
4127 *arglist->lastp = exparg.list;
4128 arglist->lastp = exparg.lastp;
4134 * Expand a variable, and return a pointer to the next character in the
4138 static inline char *evalvar(char *p, int flag)
4151 int quotes = flag & (EXP_FULL | EXP_CASE);
4154 subtype = varflags & VSTYPE;
4159 p = strchr(p, '=') + 1;
4160 again: /* jump here after setting a variable with ${var=text} */
4162 set = varisset(var, varflags & VSNUL);
4165 val = lookupvar(var);
4166 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4173 startloc = expdest - stackblock();
4174 if (set && subtype != VSPLUS) {
4175 /* insert the value of the variable */
4177 varvalue(var, varflags & VSQUOTE, flag);
4178 if (subtype == VSLENGTH) {
4179 varlen = expdest - stackblock() - startloc;
4180 STADJUST(-varlen, expdest);
4183 if (subtype == VSLENGTH) {
4184 varlen = strlen(val);
4187 varflags & VSQUOTE ? DQSYNTAX : BASESYNTAX, quotes);
4192 if (subtype == VSPLUS)
4195 easy = ((varflags & VSQUOTE) == 0 ||
4196 (*var == '@' && shellparam.nparam != 1));
4201 expdest = cvtnum(varlen, expdest);
4208 recordregion(startloc, expdest - stackblock(), varflags & VSQUOTE);
4224 case VSTRIMRIGHTMAX:
4228 * Terminate the string and start recording the pattern
4231 STPUTC('\0', expdest);
4232 patloc = expdest - stackblock();
4233 if (subevalvar(p, NULL, patloc, subtype,
4234 startloc, varflags, quotes) == 0) {
4235 int amount = (expdest - stackblock() - patloc) + 1;
4237 STADJUST(-amount, expdest);
4239 /* Remove any recorded regions beyond start of variable */
4240 removerecordregions(startloc);
4246 if (subevalvar(p, var, 0, subtype, startloc, varflags, quotes)) {
4249 * Remove any recorded regions beyond
4252 removerecordregions(startloc);
4267 if (subtype != VSNORMAL) { /* skip to end of alternative */
4271 if ((c = *p++) == CTLESC)
4273 else if (c == CTLBACKQ || c == (CTLBACKQ | CTLQUOTE)) {
4275 argbackq = argbackq->next;
4276 } else if (c == CTLVAR) {
4277 if ((*p++ & VSTYPE) != VSNORMAL)
4279 } else if (c == CTLENDVAR) {
4290 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4291 * characters to allow for further processing. Otherwise treat
4292 * $@ like $* since no splitting will be performed.
4295 static void argstr(char *p, int flag)
4298 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4301 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4302 p = exptilde(p, flag);
4306 case CTLENDVAR: /* ??? */
4309 /* "$@" syntax adherence hack */
4310 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4312 if ((flag & EXP_FULL) != 0)
4322 p = evalvar(p, flag);
4325 case CTLBACKQ | CTLQUOTE:
4326 expbackq(argbackq->n, c & CTLQUOTE, flag);
4327 argbackq = argbackq->next;
4329 #ifdef CONFIG_ASH_MATH_SUPPORT
4337 * sort of a hack - expand tildes in variable
4338 * assignments (after the first '=' and after ':'s).
4341 if (flag & EXP_VARTILDE && *p == '~') {
4348 p = exptilde(p, flag);
4357 static char *exptilde(char *p, int flag)
4359 char c, *startp = p;
4362 int quotes = flag & (EXP_FULL | EXP_CASE);
4364 while ((c = *p) != '\0') {
4371 if (flag & EXP_VARTILDE)
4381 if (*(startp + 1) == '\0') {
4382 if ((home = lookupvar("HOME")) == NULL)
4385 if ((pw = getpwnam(startp + 1)) == NULL)
4392 strtodest(home, SQSYNTAX, quotes);
4400 static void removerecordregions(int endoff)
4402 if (ifslastp == NULL)
4405 if (ifsfirst.endoff > endoff) {
4406 while (ifsfirst.next != NULL) {
4407 struct ifsregion *ifsp;
4410 ifsp = ifsfirst.next->next;
4411 free(ifsfirst.next);
4412 ifsfirst.next = ifsp;
4415 if (ifsfirst.begoff > endoff)
4418 ifslastp = &ifsfirst;
4419 ifsfirst.endoff = endoff;
4424 ifslastp = &ifsfirst;
4425 while (ifslastp->next && ifslastp->next->begoff < endoff)
4426 ifslastp = ifslastp->next;
4427 while (ifslastp->next != NULL) {
4428 struct ifsregion *ifsp;
4431 ifsp = ifslastp->next->next;
4432 free(ifslastp->next);
4433 ifslastp->next = ifsp;
4436 if (ifslastp->endoff > endoff)
4437 ifslastp->endoff = endoff;
4441 #ifdef CONFIG_ASH_MATH_SUPPORT
4443 * Expand arithmetic expression. Backup to start of expression,
4444 * evaluate, place result in (backed up) result, adjust string position.
4446 static void expari(int flag)
4452 int quotes = flag & (EXP_FULL | EXP_CASE);
4458 * This routine is slightly over-complicated for
4459 * efficiency. First we make sure there is
4460 * enough space for the result, which may be bigger
4461 * than the expression if we add exponentation. Next we
4462 * scan backwards looking for the start of arithmetic. If the
4463 * next previous character is a CTLESC character, then we
4464 * have to rescan starting from the beginning since CTLESC
4465 * characters have to be processed left to right.
4467 CHECKSTRSPACE(10, expdest);
4468 USTPUTC('\0', expdest);
4469 start = stackblock();
4471 while (*p != CTLARI && p >= start)
4474 error("missing CTLARI (shouldn't happen)");
4475 if (p > start && *(p - 1) == CTLESC)
4476 for (p = start; *p != CTLARI; p++)
4485 removerecordregions(begoff);
4488 result = arith(p + 2, &errcode);
4491 error("divide by zero");
4493 error("syntax error: \"%s\"\n", p + 2);
4495 snprintf(p, 12, "%d", result);
4499 recordregion(begoff, p - 1 - start, 0);
4500 result = expdest - p + 1;
4501 STADJUST(-result, expdest);
4506 * Expand stuff in backwards quotes.
4509 static void expbackq(union node *cmd, int quoted, int flag)
4511 volatile struct backcmd in;
4515 char *dest = expdest;
4516 volatile struct ifsregion saveifs;
4517 struct ifsregion *volatile savelastp;
4518 struct nodelist *volatile saveargbackq;
4520 int startloc = dest - stackblock();
4521 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4522 volatile int saveherefd;
4523 int quotes = flag & (EXP_FULL | EXP_CASE);
4524 struct jmploc jmploc;
4525 struct jmploc *volatile savehandler;
4529 /* Avoid longjmp clobbering */
4540 savelastp = ifslastp;
4541 saveargbackq = argbackq;
4542 saveherefd = herefd;
4544 if ((ex = setjmp(jmploc.loc))) {
4547 savehandler = handler;
4550 p = grabstackstr(dest);
4551 evalbackcmd(cmd, (struct backcmd *) &in);
4552 ungrabstackstr(p, dest);
4556 ifslastp = savelastp;
4557 argbackq = saveargbackq;
4558 herefd = saveherefd;
4566 if (--in.nleft < 0) {
4569 i = safe_read(in.fd, buf, sizeof buf);
4570 TRACE(("expbackq: read returns %d\n", i));
4577 if (lastc != '\0') {
4578 if (quotes && SIT(lastc, syntax) == CCTL)
4579 STPUTC(CTLESC, dest);
4580 STPUTC(lastc, dest);
4584 /* Eat all trailing newlines */
4585 for (; dest > stackblock() && dest[-1] == '\n';)
4593 exitstatus = waitforjob(in.jp);
4594 handler = savehandler;
4596 longjmp(handler->loc, 1);
4599 recordregion(startloc, dest - stackblock(), 0);
4600 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4601 (dest - stackblock()) - startloc,
4602 (dest - stackblock()) - startloc, stackblock() + startloc));
4608 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
4609 int varflags, int quotes)
4615 int saveherefd = herefd;
4616 struct nodelist *saveargbackq = argbackq;
4620 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4621 STACKSTRNUL(expdest);
4622 herefd = saveherefd;
4623 argbackq = saveargbackq;
4624 startp = stackblock() + startloc;
4626 str = stackblock() + strloc;
4630 setvar(str, startp, 0);
4631 amount = startp - expdest;
4632 STADJUST(amount, expdest);
4639 if (*p != CTLENDVAR) {
4640 out2fmt(snlfmt, startp);
4641 error((char *) NULL);
4643 error("%.*s: parameter %snot set", p - str - 1,
4644 str, (varflags & VSNUL) ? "null or " : nullstr);
4648 for (loc = startp; loc < str; loc++) {
4651 if (patmatch2(str, startp, quotes))
4654 if (quotes && *loc == CTLESC)
4660 for (loc = str - 1; loc >= startp;) {
4663 if (patmatch2(str, startp, quotes))
4667 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4668 for (q = startp; q < loc; q++)
4678 for (loc = str - 1; loc >= startp;) {
4679 if (patmatch2(str, loc, quotes))
4682 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4683 for (q = startp; q < loc; q++)
4692 case VSTRIMRIGHTMAX:
4693 for (loc = startp; loc < str - 1; loc++) {
4694 if (patmatch2(str, loc, quotes))
4696 if (quotes && *loc == CTLESC)
4709 amount = ((str - 1) - (loc - startp)) - expdest;
4710 STADJUST(amount, expdest);
4711 while (loc != str - 1)
4716 amount = loc - expdest;
4717 STADJUST(amount, expdest);
4718 STPUTC('\0', expdest);
4719 STADJUST(-1, expdest);
4725 * Test whether a specialized variable is set.
4728 static int varisset(char *name, int nulok)
4731 return backgndpid != -1;
4732 else if (*name == '@' || *name == '*') {
4733 if (*shellparam.p == NULL)
4739 for (av = shellparam.p; *av; av++)
4744 } else if (is_digit(*name)) {
4746 int num = atoi(name);
4748 if (num > shellparam.nparam)
4754 ap = shellparam.p[num - 1];
4756 if (nulok && (ap == NULL || *ap == '\0'))
4763 * Put a string on the stack.
4766 static void strtodest(const char *p, int syntax, int quotes)
4769 if (quotes && SIT(*p, syntax) == CCTL)
4770 STPUTC(CTLESC, expdest);
4771 STPUTC(*p++, expdest);
4776 * Add the value of a specialized variable to the stack string.
4779 static void varvalue(char *name, int quoted, int flags)
4788 int allow_split = flags & EXP_FULL;
4789 int quotes = flags & (EXP_FULL | EXP_CASE);
4791 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4800 num = shellparam.nparam;
4805 expdest = cvtnum(num, expdest);
4808 for (i = 0; i < NOPTS; i++) {
4810 STPUTC(optent_letter(optlist[i]), expdest);
4814 if (allow_split && quoted) {
4815 sep = 1 << CHAR_BIT;
4820 sep = ifsset()? ifsval()[0] : ' ';
4822 sepq = SIT(sep, syntax) == CCTL;
4825 for (ap = shellparam.p; (p = *ap++) != NULL;) {
4826 strtodest(p, syntax, quotes);
4829 STPUTC(CTLESC, expdest);
4830 STPUTC(sep, expdest);
4835 strtodest(arg0, syntax, quotes);
4839 if (num > 0 && num <= shellparam.nparam) {
4840 strtodest(shellparam.p[num - 1], syntax, quotes);
4848 * Record the fact that we have to scan this region of the
4849 * string for IFS characters.
4852 static void recordregion(int start, int end, int nulonly)
4854 struct ifsregion *ifsp;
4856 if (ifslastp == NULL) {
4860 ifsp = (struct ifsregion *) xmalloc(sizeof(struct ifsregion));
4862 ifslastp->next = ifsp;
4866 ifslastp->begoff = start;
4867 ifslastp->endoff = end;
4868 ifslastp->nulonly = nulonly;
4874 * Break the argument string into pieces based upon IFS and add the
4875 * strings to the argument list. The regions of the string to be
4876 * searched for IFS characters have been stored by recordregion.
4878 static void ifsbreakup(char *string, struct arglist *arglist)
4880 struct ifsregion *ifsp;
4885 const char *ifs, *realifs;
4893 realifs = ifsset()? ifsval() : defifs;
4894 if (ifslastp != NULL) {
4897 p = string + ifsp->begoff;
4898 nulonly = ifsp->nulonly;
4899 ifs = nulonly ? nullstr : realifs;
4901 while (p < string + ifsp->endoff) {
4905 if (strchr(ifs, *p)) {
4907 ifsspc = (strchr(defifs, *p) != NULL);
4908 /* Ignore IFS whitespace at start */
4909 if (q == start && ifsspc) {
4915 sp = (struct strlist *) stalloc(sizeof *sp);
4917 *arglist->lastp = sp;
4918 arglist->lastp = &sp->next;
4922 if (p >= string + ifsp->endoff) {
4928 if (strchr(ifs, *p) == NULL) {
4931 } else if (strchr(defifs, *p) == NULL) {
4947 } while ((ifsp = ifsp->next) != NULL);
4948 if (!(*start || (!ifsspc && start > string && nulonly))) {
4953 sp = (struct strlist *) stalloc(sizeof *sp);
4955 *arglist->lastp = sp;
4956 arglist->lastp = &sp->next;
4959 static void ifsfree(void)
4961 while (ifsfirst.next != NULL) {
4962 struct ifsregion *ifsp;
4965 ifsp = ifsfirst.next->next;
4966 free(ifsfirst.next);
4967 ifsfirst.next = ifsp;
4971 ifsfirst.next = NULL;
4975 * Add a file name to the list.
4978 static void addfname(const char *name)
4981 size_t len = strlen(name) + 1;
4983 sp = (struct strlist *) stalloc(sizeof *sp);
4984 sp->text = memcpy(stalloc(len), name, len);
4986 exparg.lastp = &sp->next;
4990 * Expand shell metacharacters. At this point, the only control characters
4991 * should be escapes. The results are stored in the list exparg.
4994 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
4995 static void expandmeta(struct strlist *str, int flag)
5000 /* TODO - EXP_REDIR */
5005 p = preglob(str->text);
5007 switch (glob(p, 0, 0, &pglob)) {
5009 if (pglob.gl_pathv[1] == 0 && !strcmp(p, pglob.gl_pathv[0]))
5020 *exparg.lastp = str;
5021 rmescapes(str->text);
5022 exparg.lastp = &str->next;
5024 default: /* GLOB_NOSPACE */
5025 error("Out of space");
5033 * Add the result of glob(3) to the list.
5036 static void addglob(const glob_t * pglob)
5038 char **p = pglob->gl_pathv;
5046 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5047 static char *expdir;
5050 static void expandmeta(struct strlist *str, int flag)
5053 struct strlist **savelastp;
5057 /* TODO - EXP_REDIR */
5063 for (;;) { /* fast check for meta chars */
5064 if ((c = *p++) == '\0')
5066 if (c == '*' || c == '?' || c == '[' || c == '!')
5069 savelastp = exparg.lastp;
5071 if (expdir == NULL) {
5072 int i = strlen(str->text);
5074 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5077 expmeta(expdir, str->text);
5081 if (exparg.lastp == savelastp) {
5086 *exparg.lastp = str;
5087 rmescapes(str->text);
5088 exparg.lastp = &str->next;
5090 *exparg.lastp = NULL;
5091 *savelastp = sp = expsort(*savelastp);
5092 while (sp->next != NULL)
5094 exparg.lastp = &sp->next;
5102 * Do metacharacter (i.e. *, ?, [...]) expansion.
5105 static void expmeta(char *enddir, char *name)
5121 for (p = name;; p++) {
5122 if (*p == '*' || *p == '?')
5124 else if (*p == '[') {
5129 while (*q == CTLQUOTEMARK)
5133 if (*q == '/' || *q == '\0')
5140 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5142 } else if (*p == '\0')
5144 else if (*p == CTLQUOTEMARK)
5146 else if (*p == CTLESC)
5154 if (metaflag == 0) { /* we've reached the end of the file name */
5155 if (enddir != expdir)
5157 for (p = name;; p++) {
5158 if (*p == CTLQUOTEMARK)
5166 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5171 if (start != name) {
5174 while (*p == CTLQUOTEMARK)
5181 if (enddir == expdir) {
5183 } else if (enddir == expdir + 1 && *expdir == '/') {
5189 if ((dirp = opendir(cp)) == NULL)
5191 if (enddir != expdir)
5193 if (*endname == 0) {
5201 while (*p == CTLQUOTEMARK)
5207 while (!int_pending() && (dp = readdir(dirp)) != NULL) {
5208 if (dp->d_name[0] == '.' && !matchdot)
5210 if (patmatch(start, dp->d_name, 0)) {
5212 strcpy(enddir, dp->d_name);
5215 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
5218 expmeta(p, endname);
5226 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5230 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5232 * Sort the results of file name expansion. It calculates the number of
5233 * strings to sort and then calls msort (short for merge sort) to do the
5237 static struct strlist *expsort(struct strlist *str)
5243 for (sp = str; sp; sp = sp->next)
5245 return msort(str, len);
5249 static struct strlist *msort(struct strlist *list, int len)
5251 struct strlist *p, *q = NULL;
5252 struct strlist **lpp;
5260 for (n = half; --n >= 0;) {
5264 q->next = NULL; /* terminate first half of list */
5265 q = msort(list, half); /* sort first half of list */
5266 p = msort(p, len - half); /* sort second half */
5269 if (strcmp(p->text, q->text) < 0) {
5272 if ((p = *lpp) == NULL) {
5279 if ((q = *lpp) == NULL) {
5292 * Returns true if the pattern matches the string.
5295 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5296 /* squoted: string might have quote chars */
5297 static int patmatch(char *pattern, char *string, int squoted)
5302 p = preglob(pattern);
5303 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5305 return !fnmatch(p, q, 0);
5309 static int patmatch2(char *pattern, char *string, int squoted)
5315 p = grabstackstr(expdest);
5316 res = patmatch(pattern, string, squoted);
5317 ungrabstackstr(p, expdest);
5321 static int patmatch(char *pattern, char *string, int squoted)
5323 return pmatch(pattern, string, squoted);
5327 static int pmatch(char *pattern, char *string, int squoted)
5339 if (squoted && *q == CTLESC)
5347 if (squoted && *q == CTLESC)
5354 while (c == CTLQUOTEMARK || c == '*')
5356 if (c != CTLESC && c != CTLQUOTEMARK &&
5357 c != '?' && c != '*' && c != '[') {
5359 if (squoted && *q == CTLESC && q[1] == c)
5363 if (squoted && *q == CTLESC)
5369 if (pmatch(p, q, squoted))
5371 if (squoted && *q == CTLESC)
5373 } while (*q++ != '\0');
5384 while (*endp == CTLQUOTEMARK)
5387 goto dft; /* no matching ] */
5388 if (*endp == CTLESC)
5400 if (squoted && chr == CTLESC)
5406 if (c == CTLQUOTEMARK)
5410 if (*p == '-' && p[1] != ']') {
5412 while (*p == CTLQUOTEMARK)
5416 if (chr >= c && chr <= *p)
5423 } while ((c = *p++) != ']');
5424 if (found == invert)
5429 if (squoted && *q == CTLESC)
5446 * Remove any CTLESC characters from a string.
5449 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5450 static char *_rmescapes(char *str, int flag)
5453 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5455 p = strpbrk(str, qchars);
5461 if (flag & RMESCAPE_ALLOC) {
5462 size_t len = p - str;
5464 q = r = stalloc(strlen(p) + len + 1);
5466 memcpy(q, str, len);
5471 if (*p == CTLQUOTEMARK) {
5477 if (flag & RMESCAPE_GLOB && *p != '/') {
5487 static void rmescapes(char *str)
5492 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5498 if (*p == CTLQUOTEMARK) {
5513 * See if a pattern matches in a case statement.
5516 static int casematch(union node *pattern, const char *val)
5518 struct stackmark smark;
5522 setstackmark(&smark);
5523 argbackq = pattern->narg.backquote;
5524 STARTSTACKSTR(expdest);
5526 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5527 STPUTC('\0', expdest);
5528 p = grabstackstr(expdest);
5529 result = patmatch(p, (char *) val, 0);
5530 popstackmark(&smark);
5538 static char *cvtnum(int num, char *buf)
5542 CHECKSTRSPACE(32, buf);
5543 len = sprintf(buf, "%d", num);
5549 * Editline and history functions (and glue).
5551 static int histcmd(int argc, char **argv)
5553 error("not compiled with history support");
5559 struct redirtab *next;
5560 short renamed[10]; /* Current ash support only 0-9 descriptors */
5561 /* char on arm (and others) can't be negative */
5564 static struct redirtab *redirlist;
5566 extern char **environ;
5571 * Initialization code.
5574 static void init(void)
5585 basepf.nextc = basepf.buf = basebuf;
5594 for (envp = environ; *envp; envp++) {
5595 if (strchr(*envp, '=')) {
5596 setvareq(*envp, VEXPORT | VTEXTFIXED);
5600 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5601 setvar("PPID", ppid, 0);
5608 * This routine is called when an error or an interrupt occurs in an
5609 * interactive shell and control is returned to the main command loop.
5612 /* 1 == check for aliases, 2 == also check for assignments */
5613 static int checkalias; /* also used in no alias mode for check assignments */
5615 static void reset(void)
5627 parselleft = parsenleft = 0; /* clear input buffer */
5631 /* from parser.c: */
5649 * This file implements the input routines used by the parser.
5652 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5653 static const char *cmdedit_prompt;
5654 static inline void putprompt(const char *s)
5659 static inline void putprompt(const char *s)
5665 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5670 * Same as pgetc(), but ignores PEOA.
5673 #ifdef CONFIG_ASH_ALIAS
5674 static int pgetc2(void)
5680 } while (c == PEOA);
5684 static inline int pgetc2(void)
5686 return pgetc_macro();
5691 * Read a line from the script.
5694 static inline char *pfgets(char *line, int len)
5700 while (--nleft > 0) {
5715 static inline int preadfd(void)
5718 char *buf = parsefile->buf;
5723 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5725 if (!iflag || parsefile->fd)
5726 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5728 nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
5732 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5736 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5737 int flags = fcntl(0, F_GETFL, 0);
5739 if (flags >= 0 && flags & O_NONBLOCK) {
5740 flags &= ~O_NONBLOCK;
5741 if (fcntl(0, F_SETFL, flags) >= 0) {
5742 out2str("sh: turning off NDELAY mode\n");
5751 static void popstring(void)
5753 struct strpush *sp = parsefile->strpush;
5756 #ifdef CONFIG_ASH_ALIAS
5758 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5763 if (sp->string != sp->ap->val) {
5767 sp->ap->flag &= ~ALIASINUSE;
5768 if (sp->ap->flag & ALIASDEAD) {
5769 unalias(sp->ap->name);
5773 parsenextc = sp->prevstring;
5774 parsenleft = sp->prevnleft;
5775 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5776 parsefile->strpush = sp->prev;
5777 if (sp != &(parsefile->basestrpush))
5784 * Refill the input buffer and return the next input character:
5786 * 1) If a string was pushed back on the input, pop it;
5787 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5788 * from a string so we can't refill the buffer, return EOF.
5789 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5790 * 4) Process input up to the next newline, deleting nul characters.
5793 static int preadbuffer(void)
5799 while (parsefile->strpush) {
5800 #ifdef CONFIG_ASH_ALIAS
5801 if (parsenleft == -1 && parsefile->strpush->ap &&
5802 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5807 if (--parsenleft >= 0)
5808 return (*parsenextc++);
5810 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5815 if (parselleft <= 0) {
5816 if ((parselleft = preadfd()) <= 0) {
5817 parselleft = parsenleft = EOF_NLEFT;
5824 /* delete nul characters */
5825 for (more = 1; more;) {
5833 parsenleft = q - parsenextc;
5834 more = 0; /* Stop processing here */
5840 if (--parselleft <= 0 && more) {
5841 parsenleft = q - parsenextc - 1;
5852 out2str(parsenextc);
5857 return *parsenextc++;
5862 * Push a string back onto the input at this current parsefile level.
5863 * We handle aliases this way.
5865 static void pushstring(char *s, int len, void *ap)
5870 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
5871 if (parsefile->strpush) {
5872 sp = xmalloc(sizeof(struct strpush));
5873 sp->prev = parsefile->strpush;
5874 parsefile->strpush = sp;
5876 sp = parsefile->strpush = &(parsefile->basestrpush);
5877 sp->prevstring = parsenextc;
5878 sp->prevnleft = parsenleft;
5879 #ifdef CONFIG_ASH_ALIAS
5880 sp->ap = (struct alias *) ap;
5882 ((struct alias *) ap)->flag |= ALIASINUSE;
5893 * Like setinputfile, but takes input from a string.
5896 static void setinputstring(char *string)
5900 parsenextc = string;
5901 parsenleft = strlen(string);
5902 parsefile->buf = NULL;
5910 * To handle the "." command, a stack of input files is used. Pushfile
5911 * adds a new entry to the stack and popfile restores the previous level.
5914 static void pushfile(void)
5916 struct parsefile *pf;
5918 parsefile->nleft = parsenleft;
5919 parsefile->lleft = parselleft;
5920 parsefile->nextc = parsenextc;
5921 parsefile->linno = plinno;
5922 pf = (struct parsefile *) xmalloc(sizeof(struct parsefile));
5923 pf->prev = parsefile;
5926 pf->basestrpush.prev = NULL;
5930 #ifdef CONFIG_ASH_JOB_CONTROL
5931 static void restartjob(struct job *);
5933 static void freejob(struct job *);
5934 static struct job *getjob(const char *);
5935 static int dowait(int, struct job *);
5939 * We keep track of whether or not fd0 has been redirected. This is for
5940 * background commands, where we want to redirect fd0 to /dev/null only
5941 * if it hasn't already been redirected.
5943 static int fd0_redirected = 0;
5945 /* Return true if fd 0 has already been redirected at least once. */
5946 static inline int fd0_redirected_p(void)
5948 return fd0_redirected != 0;
5951 static void dupredirect(const union node *, int, int fd1dup);
5953 #ifdef CONFIG_ASH_JOB_CONTROL
5955 * Turn job control on and off.
5957 * Note: This code assumes that the third arg to ioctl is a character
5958 * pointer, which is true on Berkeley systems but not System V. Since
5959 * System V doesn't have job control yet, this isn't a problem now.
5964 static void setjobctl(int enable)
5966 if (enable == jobctl || rootshell == 0)
5969 do { /* while we are in the background */
5970 initialpgrp = tcgetpgrp(2);
5971 if (initialpgrp < 0) {
5972 out2str("sh: can't access tty; job control turned off\n");
5976 if (initialpgrp == -1)
5977 initialpgrp = getpgrp();
5978 else if (initialpgrp != getpgrp()) {
5979 killpg(initialpgrp, SIGTTIN);
5986 setpgid(0, rootpid);
5987 tcsetpgrp(2, rootpid);
5988 } else { /* turning job control off */
5989 setpgid(0, initialpgrp);
5990 tcsetpgrp(2, initialpgrp);
6000 #ifdef CONFIG_ASH_JOB_CONTROL
6001 static int killcmd(int argc, char **argv)
6012 ("Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6013 "kill -l [exitstatus]");
6016 if (*argv[1] == '-') {
6017 signo = decode_signal(argv[1] + 1, 1);
6021 while ((c = nextopt("ls:")) != '\0')
6027 signo = decode_signal(optionarg, 1);
6029 error("invalid signal number or name: %s", optionarg);
6034 error("nextopt returned character code 0%o", c);
6041 if (!list && signo < 0)
6044 if ((signo < 0 || !*argptr) ^ list) {
6053 for (i = 1; i < NSIG; i++) {
6054 name = u_signal_names(0, &i, 1);
6060 name = u_signal_names(*argptr, &signo, -1);
6064 error("invalid signal number or exit status: %s", *argptr);
6069 if (**argptr == '%') {
6070 jp = getjob(*argptr);
6071 if (jp->jobctl == 0)
6072 error("job %s not created under job control", *argptr);
6073 pid = -jp->ps[0].pid;
6075 pid = atoi(*argptr);
6076 if (kill(pid, signo) != 0)
6077 error("%s: %m", *argptr);
6078 } while (*++argptr);
6083 static int fgcmd(int argc, char **argv)
6089 jp = getjob(argv[1]);
6090 if (jp->jobctl == 0)
6091 error("job not created under job control");
6092 pgrp = jp->ps[0].pid;
6093 ioctl(2, TIOCSPGRP, (char *) &pgrp);
6095 status = waitforjob(jp);
6100 static int bgcmd(int argc, char **argv)
6105 jp = getjob(*++argv);
6106 if (jp->jobctl == 0)
6107 error("job not created under job control");
6109 } while (--argc > 1);
6114 static void restartjob(struct job *jp)
6116 struct procstat *ps;
6119 if (jp->state == JOBDONE)
6122 killpg(jp->ps[0].pid, SIGCONT);
6123 for (ps = jp->ps, i = jp->nprocs; --i >= 0; ps++) {
6124 if (WIFSTOPPED(ps->status)) {
6133 static void showjobs(int change);
6136 static int jobscmd(int argc, char **argv)
6144 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6145 * statuses have changed since the last call to showjobs.
6147 * If the shell is interrupted in the process of creating a job, the
6148 * result may be a job structure containing zero processes. Such structures
6149 * will be freed here.
6152 static void showjobs(int change)
6158 struct procstat *ps;
6162 TRACE(("showjobs(%d) called\n", change));
6163 while (dowait(0, (struct job *) NULL) > 0);
6164 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6167 if (jp->nprocs == 0) {
6171 if (change && !jp->changed)
6173 procno = jp->nprocs;
6174 for (ps = jp->ps;; ps++) { /* for each process */
6176 snprintf(s, 64, "[%d] %ld ", jobno, (long) ps->pid);
6178 snprintf(s, 64, " %ld ", (long) ps->pid);
6182 if (ps->status == -1) {
6183 /* don't print anything */
6184 } else if (WIFEXITED(ps->status)) {
6185 snprintf(s, 64, "Exit %d", WEXITSTATUS(ps->status));
6187 #ifdef CONFIG_ASH_JOB_CONTROL
6188 if (WIFSTOPPED(ps->status))
6189 i = WSTOPSIG(ps->status);
6190 else /* WIFSIGNALED(ps->status) */
6192 i = WTERMSIG(ps->status);
6193 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6194 strcpy(s, sys_siglist[i & 0x7F]);
6196 snprintf(s, 64, "Signal %d", i & 0x7F);
6197 if (WCOREDUMP(ps->status))
6198 strcat(s, " (core dumped)");
6202 printf("%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ', ps->cmd);
6207 if (jp->state == JOBDONE) {
6215 * Mark a job structure as unused.
6218 static void freejob(struct job *jp)
6220 const struct procstat *ps;
6224 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
6225 if (ps->cmd != nullstr)
6228 if (jp->ps != &jp->ps0)
6231 #ifdef CONFIG_ASH_JOB_CONTROL
6232 if (curjob == jp - jobtab + 1)
6240 static int waitcmd(int argc, char **argv)
6248 job = getjob(*++argv);
6252 for (;;) { /* loop until process terminated or stopped */
6255 status = job->ps[job->nprocs - 1].status;
6261 if (WIFEXITED(status))
6262 retval = WEXITSTATUS(status);
6263 #ifdef CONFIG_ASH_JOB_CONTROL
6264 else if (WIFSTOPPED(status))
6265 retval = WSTOPSIG(status) + 128;
6268 /* XXX: limits number of signals */
6269 retval = WTERMSIG(status) + 128;
6274 for (jp = jobtab;; jp++) {
6275 if (jp >= jobtab + njobs) { /* no running procs */
6278 if (jp->used && jp->state == 0)
6282 if (dowait(2, 0) < 0 && errno == EINTR) {
6291 * Convert a job name to a job structure.
6294 static struct job *getjob(const char *name)
6302 #ifdef CONFIG_ASH_JOB_CONTROL
6304 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6305 error("No current job");
6306 return &jobtab[jobno - 1];
6308 error("No current job");
6310 } else if (name[0] == '%') {
6311 if (is_digit(name[1])) {
6312 jobno = number(name + 1);
6313 if (jobno > 0 && jobno <= njobs && jobtab[jobno - 1].used != 0)
6314 return &jobtab[jobno - 1];
6315 #ifdef CONFIG_ASH_JOB_CONTROL
6316 } else if (name[1] == '%' && name[2] == '\0') {
6320 struct job *found = NULL;
6322 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6323 if (jp->used && jp->nprocs > 0
6324 && prefix(name + 1, jp->ps[0].cmd)) {
6326 error("%s: ambiguous", name);
6333 } else if (is_number(name, &pid)) {
6334 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6335 if (jp->used && jp->nprocs > 0
6336 && jp->ps[jp->nprocs - 1].pid == pid)
6340 error("No such job: %s", name);
6347 * Return a new job structure,
6350 static struct job *makejob(const union node *node, int nprocs)
6355 for (i = njobs, jp = jobtab;; jp++) {
6359 jobtab = xmalloc(4 * sizeof jobtab[0]);
6361 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6362 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6363 /* Relocate `ps' pointers */
6364 for (i = 0; i < njobs; i++)
6365 if (jp[i].ps == &jobtab[i].ps0)
6366 jp[i].ps = &jp[i].ps0;
6370 jp = jobtab + njobs;
6371 for (i = 4; --i >= 0; jobtab[njobs++].used = 0);
6383 #ifdef CONFIG_ASH_JOB_CONTROL
6384 jp->jobctl = jobctl;
6387 jp->ps = xmalloc(nprocs * sizeof(struct procstat));
6392 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long) node, nprocs,
6399 * Fork of a subshell. If we are doing job control, give the subshell its
6400 * own process group. Jp is a job structure that the job is to be added to.
6401 * N is the command that will be evaluated by the child. Both jp and n may
6402 * be NULL. The mode parameter can be one of the following:
6403 * FORK_FG - Fork off a foreground process.
6404 * FORK_BG - Fork off a background process.
6405 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6406 * process group even if job control is on.
6408 * When job control is turned off, background processes have their standard
6409 * input redirected to /dev/null (except for the second and later processes
6415 static int forkshell(struct job *jp, const union node *n, int mode)
6419 #ifdef CONFIG_ASH_JOB_CONTROL
6422 const char *devnull = _PATH_DEVNULL;
6423 const char *nullerr = "Can't open %s";
6425 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long) n,
6430 TRACE(("Fork failed, errno=%d\n", errno));
6432 error("Cannot fork");
6439 TRACE(("Child shell %d\n", getpid()));
6440 wasroot = rootshell;
6445 #ifdef CONFIG_ASH_JOB_CONTROL
6446 jobctl = 0; /* do job control only in root shell */
6447 if (wasroot && mode != FORK_NOJOB && mflag) {
6448 if (jp == NULL || jp->nprocs == 0)
6451 pgrp = jp->ps[0].pid;
6453 if (mode == FORK_FG) {
6454 /*** this causes superfluous TIOCSPGRPS ***/
6455 if (tcsetpgrp(2, pgrp) < 0)
6456 error("tcsetpgrp failed, errno=%d", errno);
6460 } else if (mode == FORK_BG) {
6462 if (mode == FORK_BG) {
6466 if ((jp == NULL || jp->nprocs == 0) && !fd0_redirected_p()) {
6468 if (open(devnull, O_RDONLY) != 0)
6469 error(nullerr, devnull);
6472 for (i = njobs, p = jobtab; --i >= 0; p++)
6475 if (wasroot && iflag) {
6482 #ifdef CONFIG_ASH_JOB_CONTROL
6483 if (rootshell && mode != FORK_NOJOB && mflag) {
6484 if (jp == NULL || jp->nprocs == 0)
6487 pgrp = jp->ps[0].pid;
6491 if (mode == FORK_BG)
6492 backgndpid = pid; /* set $! */
6494 struct procstat *ps = &jp->ps[jp->nprocs++];
6499 if (iflag && rootshell && n)
6500 ps->cmd = commandtext(n);
6503 TRACE(("In parent shell: child = %d\n", pid));
6510 * Wait for job to finish.
6512 * Under job control we have the problem that while a child process is
6513 * running interrupts generated by the user are sent to the child but not
6514 * to the shell. This means that an infinite loop started by an inter-
6515 * active user may be hard to kill. With job control turned off, an
6516 * interactive user may place an interactive program inside a loop. If
6517 * the interactive program catches interrupts, the user doesn't want
6518 * these interrupts to also abort the loop. The approach we take here
6519 * is to have the shell ignore interrupt signals while waiting for a
6520 * forground process to terminate, and then send itself an interrupt
6521 * signal if the child process was terminated by an interrupt signal.
6522 * Unfortunately, some programs want to do a bit of cleanup and then
6523 * exit on interrupt; unless these processes terminate themselves by
6524 * sending a signal to themselves (instead of calling exit) they will
6525 * confuse this approach.
6528 static int waitforjob(struct job *jp)
6530 #ifdef CONFIG_ASH_JOB_CONTROL
6531 int mypgrp = getpgrp();
6537 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6538 while (jp->state == 0) {
6541 #ifdef CONFIG_ASH_JOB_CONTROL
6543 if (tcsetpgrp(2, mypgrp) < 0)
6544 error("tcsetpgrp failed, errno=%d\n", errno);
6546 if (jp->state == JOBSTOPPED)
6547 curjob = jp - jobtab + 1;
6549 status = jp->ps[jp->nprocs - 1].status;
6550 /* convert to 8 bits */
6551 if (WIFEXITED(status))
6552 st = WEXITSTATUS(status);
6553 #ifdef CONFIG_ASH_JOB_CONTROL
6554 else if (WIFSTOPPED(status))
6555 st = WSTOPSIG(status) + 128;
6558 st = WTERMSIG(status) + 128;
6559 #ifdef CONFIG_ASH_JOB_CONTROL
6562 * This is truly gross.
6563 * If we're doing job control, then we did a TIOCSPGRP which
6564 * caused us (the shell) to no longer be in the controlling
6565 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6566 * intuit from the subprocess exit status whether a SIGINT
6567 * occured, and if so interrupt ourselves. Yuck. - mycroft
6569 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6572 if (jp->state == JOBDONE)
6582 * Wait for a process to terminate.
6586 * Do a wait system call. If job control is compiled in, we accept
6587 * stopped processes. If block is zero, we return a value of zero
6588 * rather than blocking.
6590 * System V doesn't have a non-blocking wait system call. It does
6591 * have a SIGCLD signal that is sent to a process when one of it's
6592 * children dies. The obvious way to use SIGCLD would be to install
6593 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6594 * was received, and have waitproc bump another counter when it got
6595 * the status of a process. Waitproc would then know that a wait
6596 * system call would not block if the two counters were different.
6597 * This approach doesn't work because if a process has children that
6598 * have not been waited for, System V will send it a SIGCLD when it
6599 * installs a signal handler for SIGCLD. What this means is that when
6600 * a child exits, the shell will be sent SIGCLD signals continuously
6601 * until is runs out of stack space, unless it does a wait call before
6602 * restoring the signal handler. The code below takes advantage of
6603 * this (mis)feature by installing a signal handler for SIGCLD and
6604 * then checking to see whether it was called. If there are any
6605 * children to be waited for, it will be.
6609 static inline int waitproc(int block, int *status)
6614 #ifdef CONFIG_ASH_JOB_CONTROL
6620 return wait3(status, flags, (struct rusage *) NULL);
6623 static int dowait(int block, struct job *job)
6627 struct procstat *sp;
6629 struct job *thisjob;
6635 TRACE(("dowait(%d) called\n", block));
6637 pid = waitproc(block, &status);
6638 TRACE(("wait returns %d, status=%d\n", pid, status));
6639 } while (!(block & 2) && pid == -1 && errno == EINTR);
6644 for (jp = jobtab; jp < jobtab + njobs; jp++) {
6648 for (sp = jp->ps; sp < jp->ps + jp->nprocs; sp++) {
6651 if (sp->pid == pid) {
6652 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
6653 pid, sp->status, status));
6654 sp->status = status;
6657 if (sp->status == -1)
6659 else if (WIFSTOPPED(sp->status))
6662 if (stopped) { /* stopped or done */
6663 int state = done ? JOBDONE : JOBSTOPPED;
6665 if (jp->state != state) {
6666 TRACE(("Job %d: changing state from %d to %d\n",
6667 jp - jobtab + 1, jp->state, state));
6669 #ifdef CONFIG_ASH_JOB_CONTROL
6670 if (done && curjob == jp - jobtab + 1)
6671 curjob = 0; /* no current job */
6678 if (!rootshell || !iflag || (job && thisjob == job)) {
6679 core = WCOREDUMP(status);
6680 #ifdef CONFIG_ASH_JOB_CONTROL
6681 if (WIFSTOPPED(status))
6682 sig = WSTOPSIG(status);
6685 if (WIFEXITED(status))
6688 sig = WTERMSIG(status);
6690 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6692 out2fmt("%d: ", pid);
6693 #ifdef CONFIG_ASH_JOB_CONTROL
6694 if (sig == SIGTSTP && rootshell && iflag)
6695 out2fmt("%%%ld ", (long) (job - jobtab + 1));
6697 if (sig < NSIG && sys_siglist[sig])
6698 out2str(sys_siglist[sig]);
6700 out2fmt("Signal %d", sig);
6702 out2str(" - core dumped");
6705 TRACE(("Not printing status: status=%d, sig=%d\n", status, sig));
6708 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell,
6711 thisjob->changed = 1;
6720 * return 1 if there are stopped jobs, otherwise 0
6722 static int stoppedjobs(void)
6729 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6732 if (jp->state == JOBSTOPPED) {
6733 out2str("You have stopped jobs.\n");
6743 * Return a string identifying a command (to be printed by the
6747 static char *cmdnextc;
6748 static int cmdnleft;
6750 #define MAXCMDTEXT 200
6752 static void cmdputs(const char *s)
6763 while ((c = *p++) != '\0') {
6766 else if (c == CTLVAR) {
6771 } else if (c == '=' && subtype != 0) {
6772 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
6774 } else if (c == CTLENDVAR) {
6776 } else if (c == CTLBACKQ || c == CTLBACKQ + CTLQUOTE)
6777 cmdnleft++; /* ignore it */
6780 if (--cmdnleft <= 0) {
6790 #define CMDTXT_TABLE
6793 * To collect a lot of redundant code in cmdtxt() case statements, we
6794 * implement a mini language here. Each type of node struct has an
6795 * associated instruction sequence that operates on its members via
6796 * their offsets. The instruction are pack in unsigned chars with
6797 * format IIDDDDDE where the bits are
6798 * I : part of the instruction opcode, which are
6799 * 00 : member is a pointer to another node -- process it recursively
6800 * 40 : member is a pointer to a char string -- output it
6801 * 80 : output the string whose index is stored in the data field
6802 * CC : flag signaling that this case needs external processing
6803 * D : data - either the (shifted) index of a fixed string to output or
6804 * the actual offset of the member to operate on in the struct
6805 * (since we assume bit 0 is set, the offset is not shifted)
6806 * E : flag signaling end of instruction sequence
6808 * WARNING: In order to handle larger offsets for 64bit archs, this code
6809 * assumes that no offset can be an odd number and stores the
6810 * end-of-instructions flag in bit 0.
6813 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
6814 #define CMDTXT_CHARPTR 0x40
6815 #define CMDTXT_STRING 0x80
6816 #define CMDTXT_SPECIAL 0xC0
6817 #define CMDTXT_OFFSETMASK 0x3E
6819 static const char *const cmdtxt_strings[] = {
6820 /* 0 1 2 3 4 5 6 7 */
6821 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
6822 /* 8 9 10 11 12 13 */
6823 "while ", "; do ", "; done", "until ", "for ", " in ...",
6825 "case ", "???", "() ...", "<<..."
6828 static const char *const redir_strings[] = {
6829 ">", "<", "<>", ">>", ">|", ">&", "<&"
6832 static const unsigned char cmdtxt_ops[] = {
6833 #define CMDTXT_NSEMI 0
6834 offsetof(union node, nbinary.ch1),
6836 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6837 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
6838 #define CMDTXT_NPIPE (CMDTXT_NCMD)
6839 #define CMDTXT_NCASE (CMDTXT_NCMD)
6840 #define CMDTXT_NTO (CMDTXT_NCMD)
6841 #define CMDTXT_NFROM (CMDTXT_NCMD)
6842 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
6843 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
6844 #define CMDTXT_NTOOV (CMDTXT_NCMD)
6845 #define CMDTXT_NTOFD (CMDTXT_NCMD)
6846 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
6848 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
6849 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
6850 offsetof(union node, nredir.n) | CMDTXT_NOMORE,
6851 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
6852 (1 * 2) | CMDTXT_STRING,
6853 offsetof(union node, nredir.n),
6854 (2 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6855 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
6856 offsetof(union node, nbinary.ch1),
6857 (3 * 2) | CMDTXT_STRING,
6858 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6859 #define CMDTXT_NOR (CMDTXT_NAND + 3)
6860 offsetof(union node, nbinary.ch1),
6861 (4 * 2) | CMDTXT_STRING,
6862 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6863 #define CMDTXT_NIF (CMDTXT_NOR + 3)
6864 (5 * 2) | CMDTXT_STRING,
6865 offsetof(union node, nif.test),
6866 (6 * 2) | CMDTXT_STRING,
6867 offsetof(union node, nif.ifpart),
6868 (7 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6869 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
6870 (8 * 2) | CMDTXT_STRING,
6871 offsetof(union node, nbinary.ch1),
6872 (9 * 2) | CMDTXT_STRING,
6873 offsetof(union node, nbinary.ch2),
6874 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6875 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
6876 (11 * 2) | CMDTXT_STRING,
6877 offsetof(union node, nbinary.ch1),
6878 (9 * 2) | CMDTXT_STRING,
6879 offsetof(union node, nbinary.ch2),
6880 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6881 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
6882 (12 * 2) | CMDTXT_STRING,
6883 offsetof(union node, nfor.var) | CMDTXT_CHARPTR,
6884 (13 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6885 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
6886 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
6887 (15 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6888 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
6889 offsetof(union node, narg.text) | CMDTXT_CHARPTR,
6890 (16 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6891 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
6892 offsetof(union node, narg.text) | CMDTXT_CHARPTR | CMDTXT_NOMORE,
6893 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
6894 #define CMDTXT_NXHERE (CMDTXT_NHERE)
6895 (17 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6898 #if CMDTXT_NXHERE != 36
6899 #error CMDTXT_NXHERE
6902 static const unsigned char cmdtxt_ops_index[26] = {
6931 static void cmdtxt(const union node *n)
6938 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
6939 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
6941 if (*p & CMDTXT_STRING) { /* output fixed string */
6942 cmdputs(cmdtxt_strings
6943 [((int) (*p & CMDTXT_OFFSETMASK) >> 1)]);
6945 const char *pf = ((const char *) n)
6946 + ((int) (*p & CMDTXT_OFFSETMASK));
6948 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
6949 cmdputs(*((const char **) pf));
6950 } else { /* output field */
6951 cmdtxt(*((const union node **) pf));
6954 } while (!(*p++ & CMDTXT_NOMORE));
6955 } else if (n->type == NCMD) {
6958 for (np = n->ncmd.args; np; np = np->narg.next) {
6963 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
6967 } else if (n->type == NPIPE) {
6968 struct nodelist *lp;
6970 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
6975 } else if (n->type == NCASE) {
6976 cmdputs(cmdtxt_strings[14]);
6977 cmdputs(n->ncase.expr->narg.text);
6978 cmdputs(cmdtxt_strings[13]);
6980 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
6981 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
6986 assert((n->type >= NTO) && (n->type <= NFROMFD));
6989 p = redir_strings[n->type - NTO];
6990 if (n->nfile.fd != ('>' == *p)) {
6991 s[0] = n->nfile.fd + '0';
6996 if (n->type >= NTOFD) {
6997 s[0] = n->ndup.dupfd + '0';
7001 cmdtxt(n->nfile.fname);
7005 #else /* CMDTXT_TABLE */
7006 static void cmdtxt(const union node *n)
7009 struct nodelist *lp;
7018 cmdtxt(n->nbinary.ch1);
7020 cmdtxt(n->nbinary.ch2);
7023 cmdtxt(n->nbinary.ch1);
7025 cmdtxt(n->nbinary.ch2);
7028 cmdtxt(n->nbinary.ch1);
7030 cmdtxt(n->nbinary.ch2);
7033 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7041 cmdtxt(n->nredir.n);
7046 cmdtxt(n->nredir.n);
7050 cmdtxt(n->nif.test);
7052 cmdtxt(n->nif.ifpart);
7061 cmdtxt(n->nbinary.ch1);
7063 cmdtxt(n->nbinary.ch2);
7068 cmdputs(n->nfor.var);
7073 cmdputs(n->ncase.expr->narg.text);
7077 cmdputs(n->narg.text);
7081 for (np = n->ncmd.args; np; np = np->narg.next) {
7086 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
7092 cmdputs(n->narg.text);
7123 if (n->nfile.fd != i) {
7124 s[0] = n->nfile.fd + '0';
7129 if (n->type == NTOFD || n->type == NFROMFD) {
7130 s[0] = n->ndup.dupfd + '0';
7134 cmdtxt(n->nfile.fname);
7146 #endif /* CMDTXT_TABLE */
7148 static char *commandtext(const union node *n)
7152 cmdnextc = name = xmalloc(MAXCMDTEXT);
7153 cmdnleft = MAXCMDTEXT - 4;
7160 #ifdef CONFIG_ASH_MAIL
7163 * Routines to check for mail.
7167 #define MAXMBOXES 10
7170 static int nmboxes; /* number of mailboxes */
7171 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7176 * Print appropriate message(s) if mail has arrived. If the argument is
7177 * nozero, then the value of MAIL has changed, so we just update the
7181 static void chkmail(int silent)
7187 struct stackmark smark;
7194 setstackmark(&smark);
7195 mpath = mpathset()? mpathval() : mailval();
7196 for (i = 0; i < nmboxes; i++) {
7197 p = padvance(&mpath, nullstr);
7202 for (q = p; *q; q++);
7207 q[-1] = '\0'; /* delete trailing '/' */
7208 if (stat(p, &statb) < 0)
7210 if (statb.st_size > mailtime[i] && !silent) {
7211 out2fmt(snlfmt, pathopt ? pathopt : "you have mail");
7213 mailtime[i] = statb.st_size;
7216 popstackmark(&smark);
7219 #endif /* CONFIG_ASH_MAIL */
7224 static short profile_buf[16384];
7228 static int isloginsh = 0;
7230 static void read_profile(const char *);
7231 static void cmdloop(int);
7232 static void options(int);
7233 static void setoption(int, int);
7234 static void procargs(int, char **);
7238 * Main routine. We initialize things, parse the arguments, execute
7239 * profiles if we're a login shell, and then call cmdloop to execute
7240 * commands. The setjmp call sets up the location to jump to when an
7241 * exception occurs. When an exception occurs the variable "state"
7242 * is used to figure out how far we had gotten.
7245 int ash_main(int argc, char **argv)
7247 struct jmploc jmploc;
7248 struct stackmark smark;
7252 BLTINCMD = find_builtin("builtin");
7253 EXECCMD = find_builtin("exec");
7254 EVALCMD = find_builtin("eval");
7256 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7262 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7264 #if defined(linux) || defined(__GNU__)
7265 signal(SIGCHLD, SIG_DFL);
7268 if (setjmp(jmploc.loc)) {
7271 * When a shell procedure is executed, we raise the
7272 * exception EXSHELLPROC to clean up before executing
7273 * the shell procedure.
7275 if (exception == EXSHELLPROC) {
7281 if (exception == EXEXEC) {
7282 exitstatus = exerrno;
7283 } else if (exception == EXERROR) {
7286 if (state == 0 || iflag == 0 || !rootshell)
7287 exitshell(exitstatus);
7290 if (exception == EXINT) {
7293 popstackmark(&smark);
7294 FORCEINTON; /* enable interrupts */
7297 else if (state == 2)
7299 else if (state == 3)
7307 trputs("Shell args: ");
7313 setstackmark(&smark);
7314 procargs(argc, argv);
7315 if (argv[0] && argv[0][0] == '-')
7319 read_profile("/etc/profile");
7322 read_profile(".profile");
7327 if (getuid() == geteuid() && getgid() == getegid()) {
7329 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7331 read_profile(shinit);
7338 if (sflag == 0 || minusc) {
7339 static const char sigs[] = {
7340 SIGINT, SIGQUIT, SIGHUP,
7347 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])))
7350 for (i = 0; i < SIGSSIZE; i++)
7355 evalstring(minusc, 0);
7357 if (sflag || minusc == NULL) {
7358 state4: /* XXX ??? - why isn't this before the "if" statement */
7364 exitshell(exitstatus);
7370 * Read and execute commands. "Top" is nonzero for the top level command
7371 * loop; it turns on prompting if the shell is interactive.
7374 static void cmdloop(int top)
7377 struct stackmark smark;
7381 TRACE(("cmdloop(%d) called\n", top));
7382 setstackmark(&smark);
7390 #ifdef CONFIG_ASH_MAIL
7395 n = parsecmd(inter);
7396 /* showtree(n); DEBUG */
7398 if (!top || numeof >= 50)
7400 if (!stoppedjobs()) {
7403 out2str("\nUse \"exit\" to leave shell.\n");
7406 } else if (n != NULL && nflag == 0) {
7407 job_warning = (job_warning == 2) ? 1 : 0;
7411 popstackmark(&smark);
7412 setstackmark(&smark);
7413 if (evalskip == SKIPFILE) {
7418 popstackmark(&smark);
7424 * Read /etc/profile or .profile. Return on error.
7427 static void read_profile(const char *name)
7434 if ((fd = open(name, O_RDONLY)) >= 0)
7439 /* -q turns off -x and -v just when executing init files */
7440 /* Note: Might do a little redundant work, but reduces code size. */
7455 * Read a file containing shell functions.
7458 static void readcmdfile(const char *name)
7463 if ((fd = open(name, O_RDONLY)) >= 0)
7466 error("Can't open %s", name);
7475 * Take commands from a file. To be compatable we should do a path
7476 * search for the file, which is necessary to find sub-commands.
7479 static inline char *find_dot_file(char *mybasename)
7482 const char *path = pathval();
7485 /* don't try this for absolute or relative paths */
7486 if (strchr(mybasename, '/'))
7489 while ((fullname = padvance(&path, mybasename)) != NULL) {
7490 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7492 * Don't bother freeing here, since it will
7493 * be freed by the caller.
7497 stunalloc(fullname);
7500 /* not found in the PATH */
7501 error("%s: not found", mybasename);
7505 static int dotcmd(int argc, char **argv)
7508 volatile struct shparam saveparam;
7512 for (sp = cmdenviron; sp; sp = sp->next)
7513 setvareq(xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
7515 if (argc >= 2) { /* That's what SVR2 does */
7517 struct stackmark smark;
7519 setstackmark(&smark);
7520 fullname = find_dot_file(argv[1]);
7523 saveparam = shellparam;
7524 shellparam.malloc = 0;
7525 shellparam.nparam = argc - 2;
7526 shellparam.p = argv + 2;
7529 setinputfile(fullname, 1);
7530 commandname = fullname;
7535 freeparam(&shellparam);
7536 shellparam = saveparam;
7539 popstackmark(&smark);
7545 static int exitcmd(int argc, char **argv)
7550 exitstatus = number(argv[1]);
7552 exitstatus = oexitstatus;
7553 exitshell(exitstatus);
7557 static pointer stalloc(int nbytes)
7561 nbytes = ALIGN(nbytes);
7562 if (nbytes > stacknleft) {
7564 struct stack_block *sp;
7567 if (blocksize < MINSIZE)
7568 blocksize = MINSIZE;
7570 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7572 stacknxt = sp->space;
7573 stacknleft = blocksize;
7579 stacknleft -= nbytes;
7584 static void stunalloc(pointer p)
7587 if (p == NULL) { /*DEBUG */
7588 write(2, "stunalloc\n", 10);
7592 if (!(stacknxt >= (char *) p && (char *) p >= stackp->space)) {
7595 stacknleft += stacknxt - (char *) p;
7600 static void setstackmark(struct stackmark *mark)
7602 mark->stackp = stackp;
7603 mark->stacknxt = stacknxt;
7604 mark->stacknleft = stacknleft;
7605 mark->marknext = markp;
7610 static void popstackmark(struct stackmark *mark)
7612 struct stack_block *sp;
7615 markp = mark->marknext;
7616 while (stackp != mark->stackp) {
7621 stacknxt = mark->stacknxt;
7622 stacknleft = mark->stacknleft;
7628 * When the parser reads in a string, it wants to stick the string on the
7629 * stack and only adjust the stack pointer when it knows how big the
7630 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7631 * of space on top of the stack and stackblocklen returns the length of
7632 * this block. Growstackblock will grow this space by at least one byte,
7633 * possibly moving it (like realloc). Grabstackblock actually allocates the
7634 * part of the block that has been used.
7637 static void growstackblock(void)
7640 int newlen = ALIGN(stacknleft * 2 + 100);
7641 char *oldspace = stacknxt;
7642 int oldlen = stacknleft;
7643 struct stack_block *sp;
7644 struct stack_block *oldstackp;
7646 if (stacknxt == stackp->space && stackp != &stackbase) {
7651 sp = xrealloc((pointer) sp,
7652 sizeof(struct stack_block) - MINSIZE + newlen);
7655 stacknxt = sp->space;
7656 stacknleft = newlen;
7658 /* Stack marks pointing to the start of the old block
7659 * must be relocated to point to the new block
7661 struct stackmark *xmark;
7664 while (xmark != NULL && xmark->stackp == oldstackp) {
7665 xmark->stackp = stackp;
7666 xmark->stacknxt = stacknxt;
7667 xmark->stacknleft = stacknleft;
7668 xmark = xmark->marknext;
7673 p = stalloc(newlen);
7674 memcpy(p, oldspace, oldlen);
7675 stacknxt = p; /* free the space */
7676 stacknleft += newlen; /* we just allocated */
7682 static inline void grabstackblock(int len)
7692 * The following routines are somewhat easier to use that the above.
7693 * The user declares a variable of type STACKSTR, which may be declared
7694 * to be a register. The macro STARTSTACKSTR initializes things. Then
7695 * the user uses the macro STPUTC to add characters to the string. In
7696 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7697 * grown as necessary. When the user is done, she can just leave the
7698 * string there and refer to it using stackblock(). Or she can allocate
7699 * the space for it using grabstackstr(). If it is necessary to allow
7700 * someone else to use the stack temporarily and then continue to grow
7701 * the string, the user should use grabstack to allocate the space, and
7702 * then call ungrabstr(p) to return to the previous mode of operation.
7704 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7705 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7706 * is space for at least one character.
7710 static char *growstackstr(void)
7712 int len = stackblocksize();
7714 if (herefd >= 0 && len >= 1024) {
7715 xwrite(herefd, stackblock(), len);
7716 sstrnleft = len - 1;
7717 return stackblock();
7720 sstrnleft = stackblocksize() - len - 1;
7721 return stackblock() + len;
7726 * Called from CHECKSTRSPACE.
7729 static char *makestrspace(size_t newlen)
7731 int len = stackblocksize() - sstrnleft;
7735 sstrnleft = stackblocksize() - len;
7736 } while (sstrnleft < newlen);
7737 return stackblock() + len;
7742 static void ungrabstackstr(char *s, char *p)
7744 stacknleft += stacknxt - s;
7746 sstrnleft = stacknleft - (p - s);
7750 * Miscelaneous builtins.
7756 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
7757 typedef long rlim_t;
7763 * The read builtin. The -e option causes backslashes to escape the
7764 * following character.
7766 * This uses unbuffered input, which may be avoidable in some cases.
7769 static int readcmd(int argc, char **argv)
7784 while ((i = nextopt("p:r")) != '\0') {
7790 if (prompt && isatty(0)) {
7791 out2str(prompt); /* read without cmdedit */
7794 if (*(ap = argptr) == NULL)
7796 if ((ifs = bltinlookup("IFS")) == NULL)
7803 if (read(0, &c, 1) != 1) {
7815 if (!rflag && c == '\\') {
7821 if (startword && *ifs == ' ' && strchr(ifs, c)) {
7825 if (backslash && c == '\\') {
7826 if (read(0, &c, 1) != 1) {
7831 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
7833 setvar(*ap, stackblock(), 0);
7842 /* Remove trailing blanks */
7843 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
7845 setvar(*ap, stackblock(), 0);
7846 while (*++ap != NULL)
7847 setvar(*ap, nullstr, 0);
7853 static int umaskcmd(int argc, char **argv)
7855 static const char permuser[3] = "ugo";
7856 static const char permmode[3] = "rwx";
7857 static const short int permmask[] = {
7858 S_IRUSR, S_IWUSR, S_IXUSR,
7859 S_IRGRP, S_IWGRP, S_IXGRP,
7860 S_IROTH, S_IWOTH, S_IXOTH
7866 int symbolic_mode = 0;
7868 while (nextopt("S") != '\0') {
7877 if ((ap = *argptr) == NULL) {
7878 if (symbolic_mode) {
7882 for (i = 0; i < 3; i++) {
7887 for (j = 0; j < 3; j++) {
7888 if ((mask & permmask[3 * i + j]) == 0) {
7897 printf("%.4o\n", mask);
7900 if (is_digit((unsigned char) *ap)) {
7903 if (*ap >= '8' || *ap < '0')
7904 error("Illegal number: %s", argv[1]);
7905 mask = (mask << 3) + (*ap - '0');
7906 } while (*++ap != '\0');
7909 mask = ~mask & 0777;
7910 if (!parse_mode(ap, &mask)) {
7911 error("Illegal mode: %s", ap);
7913 umask(~mask & 0777);
7922 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
7923 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
7924 * ash by J.T. Conklin.
7932 short factor; /* multiply by to get rlim_{cur,max} values */
7935 static const struct limits limits[] = {
7937 {"time(seconds)", RLIMIT_CPU, 1},
7940 {"file(blocks)", RLIMIT_FSIZE, 512},
7943 {"data(kbytes)", RLIMIT_DATA, 1024},
7946 {"stack(kbytes)", RLIMIT_STACK, 1024},
7949 {"coredump(blocks)", RLIMIT_CORE, 512},
7952 {"memory(kbytes)", RLIMIT_RSS, 1024},
7954 #ifdef RLIMIT_MEMLOCK
7955 {"locked memory(kbytes)", RLIMIT_MEMLOCK, 1024},
7958 {"process(processes)", RLIMIT_NPROC, 1},
7960 #ifdef RLIMIT_NOFILE
7961 {"nofiles(descriptors)", RLIMIT_NOFILE, 1},
7964 {"vmemory(kbytes)", RLIMIT_VMEM, 1024},
7967 {"swap(kbytes)", RLIMIT_SWAP, 1024},
7972 static int ulimitcmd(int argc, char **argv)
7974 static const char unlimited_string[] = "unlimited";
7977 enum { SOFT = 0x1, HARD = 0x2 } how = SOFT | HARD;
7978 const struct limits *l;
7981 struct rlimit limit;
7985 while ((optc = nextopt("HSa"
8004 #ifdef RLIMIT_MEMLOCK
8010 #ifdef RLIMIT_NOFILE
8022 } else if (optc == 'S') {
8024 } else if (optc == 'a') {
8031 for (l = limits; l->name; l++) {
8032 if (l->name[0] == what)
8034 if (l->name[1] == 'w' && what == 'w')
8038 set = *argptr ? 1 : 0;
8042 if (all || argptr[1])
8043 error("too many arguments");
8044 if (strcmp(p, unlimited_string) == 0)
8045 val = RLIM_INFINITY;
8049 while ((c = *p++) >= '0' && c <= '9') {
8050 val = (val * 10) + (long) (c - '0');
8051 if (val < (rlim_t) 0)
8055 error("bad number");
8061 for (l = limits; l->name; l++) {
8062 printf("%-20s ", l->name);
8063 getrlimit(l->cmd, &limit);
8066 val = limit.rlim_cur;
8067 else if (how & HARD)
8068 val = limit.rlim_max;
8070 if (val == RLIM_INFINITY)
8071 puts(unlimited_string);
8074 printf("%lld\n", (long long) val);
8087 getrlimit(l->cmd, &limit);
8089 limit.rlim_max = val;
8091 limit.rlim_cur = val;
8092 if (setrlimit(l->cmd, &limit) < 0)
8093 error("error setting limit (%m)");
8098 * prefix -- see if pfx is a prefix of string.
8101 static int prefix(char const *pfx, char const *string)
8104 if (*pfx++ != *string++)
8111 * Return true if s is a string of digits, and save munber in intptr
8115 static int is_number(const char *p, int *intptr)
8123 ret += digit_val(*p);
8125 } while (*p != '\0');
8132 * Convert a string of digits to an integer, printing an error message on
8136 static int number(const char *s)
8140 if (!is_number(s, &i))
8141 error("Illegal number: %s", s);
8146 * Produce a possibly single quoted string suitable as input to the shell.
8147 * The return string is allocated on the stack.
8150 static char *single_quote(const char *s)
8158 size_t len1, len1p, len2, len2p;
8160 len1 = strcspn(s, "'");
8161 len2 = strspn(s + len1, "'");
8163 len1p = len1 ? len1 + 2 : len1;
8164 len2p = len2 + ((len2 < 2) ? len2 : 2);
8166 CHECKSTRSPACE(len1p + len2p + 1, p);
8171 memcpy(p + 1, s, len1);
8179 memcpy(q + 1, s, len2);
8182 } else if (len2 == 1) {
8188 STADJUST(len1p + len2p, p);
8193 return grabstackstr(p);
8197 * Routine for dealing with parsed shell commands.
8201 static void sizenodelist(const struct nodelist *);
8202 static struct nodelist *copynodelist(const struct nodelist *);
8203 static char *nodesavestr(const char *);
8205 #define CALCSIZE_TABLE
8206 #define COPYNODE_TABLE
8207 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8209 * To collect a lot of redundant code in case statements for copynode()
8210 * and calcsize(), we implement a mini language here. Each type of node
8211 * struct has an associated instruction sequence that operates on its
8212 * members via their offsets. The instruction are pack in unsigned chars
8213 * with format IIDDDDDE where the bits are
8214 * I : part of the instruction opcode, which are
8215 * 00 : member is a pointer to another node
8216 * 40 : member is an integer
8217 * 80 : member is a pointer to a nodelist
8218 * CC : member is a pointer to a char string
8219 * D : data - the actual offset of the member to operate on in the struct
8220 * (since we assume bit 0 is set, it is not shifted)
8221 * E : flag signaling end of instruction sequence
8223 * WARNING: In order to handle larger offsets for 64bit archs, this code
8224 * assumes that no offset can be an odd number and stores the
8225 * end-of-instructions flag in bit 0.
8228 #define NODE_INTEGER 0x40
8229 #define NODE_NODELIST 0x80
8230 #define NODE_CHARPTR 0xC0
8231 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned) */
8232 #define NODE_MBRMASK 0xC0
8233 #define NODE_OFFSETMASK 0x3E
8235 static const unsigned char copynode_ops[35] = {
8236 #define COPYNODE_OPS0 0
8237 offsetof(union node, nbinary.ch2),
8238 offsetof(union node, nbinary.ch1) | NODE_NOMORE,
8239 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8240 offsetof(union node, ncmd.redirect),
8241 offsetof(union node, ncmd.args),
8242 offsetof(union node, ncmd.assign),
8243 offsetof(union node, ncmd.backgnd) | NODE_INTEGER | NODE_NOMORE,
8244 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8245 offsetof(union node, npipe.cmdlist) | NODE_NODELIST,
8246 offsetof(union node, npipe.backgnd) | NODE_INTEGER | NODE_NOMORE,
8247 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8248 offsetof(union node, nredir.redirect),
8249 offsetof(union node, nredir.n) | NODE_NOMORE,
8250 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8251 offsetof(union node, nif.elsepart),
8252 offsetof(union node, nif.ifpart),
8253 offsetof(union node, nif.test) | NODE_NOMORE,
8254 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8255 offsetof(union node, nfor.var) | NODE_CHARPTR,
8256 offsetof(union node, nfor.body),
8257 offsetof(union node, nfor.args) | NODE_NOMORE,
8258 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8259 offsetof(union node, ncase.cases),
8260 offsetof(union node, ncase.expr) | NODE_NOMORE,
8261 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8262 offsetof(union node, nclist.body),
8263 offsetof(union node, nclist.pattern),
8264 offsetof(union node, nclist.next) | NODE_NOMORE,
8265 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8266 offsetof(union node, narg.backquote) | NODE_NODELIST,
8267 offsetof(union node, narg.text) | NODE_CHARPTR,
8268 offsetof(union node, narg.next) | NODE_NOMORE,
8269 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8270 offsetof(union node, nfile.fname),
8271 offsetof(union node, nfile.fd) | NODE_INTEGER,
8272 offsetof(union node, nfile.next) | NODE_NOMORE,
8273 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8274 offsetof(union node, ndup.vname),
8275 offsetof(union node, ndup.dupfd) | NODE_INTEGER,
8276 offsetof(union node, ndup.fd) | NODE_INTEGER,
8277 offsetof(union node, ndup.next) | NODE_NOMORE,
8278 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8279 offsetof(union node, nhere.doc),
8280 offsetof(union node, nhere.fd) | NODE_INTEGER,
8281 offsetof(union node, nhere.next) | NODE_NOMORE,
8282 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8283 offsetof(union node, nnot.com) | NODE_NOMORE,
8286 #if COPYNODE_OPS12 != 34
8287 #error COPYNODE_OPS12 is incorrect
8290 static const unsigned char copynode_ops_index[26] = {
8291 COPYNODE_OPS0, /* NSEMI */
8292 COPYNODE_OPS1, /* NCMD */
8293 COPYNODE_OPS2, /* NPIPE */
8294 COPYNODE_OPS3, /* NREDIR */
8295 COPYNODE_OPS3, /* NBACKGND */
8296 COPYNODE_OPS3, /* NSUBSHELL */
8297 COPYNODE_OPS0, /* NAND */
8298 COPYNODE_OPS0, /* NOR */
8299 COPYNODE_OPS4, /* NIF */
8300 COPYNODE_OPS0, /* NWHILE */
8301 COPYNODE_OPS0, /* NUNTIL */
8302 COPYNODE_OPS5, /* NFOR */
8303 COPYNODE_OPS6, /* NCASE */
8304 COPYNODE_OPS7, /* NCLIST */
8305 COPYNODE_OPS8, /* NDEFUN */
8306 COPYNODE_OPS8, /* NARG */
8307 COPYNODE_OPS9, /* NTO */
8308 COPYNODE_OPS9, /* NFROM */
8309 COPYNODE_OPS9, /* NFROMTO */
8310 COPYNODE_OPS9, /* NAPPEND */
8311 COPYNODE_OPS9, /* NTOOV */
8312 COPYNODE_OPS10, /* NTOFD */
8313 COPYNODE_OPS10, /* NFROMFD */
8314 COPYNODE_OPS11, /* NHERE */
8315 COPYNODE_OPS11, /* NXHERE */
8316 COPYNODE_OPS12, /* NNOT */
8319 #if NODE_CHARPTR != NODE_MBRMASK
8320 #error NODE_CHARPTR != NODE_MBRMASK!!!
8322 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8324 #ifdef COPYNODE_TABLE
8325 static union node *copynode(const union node *n)
8328 const unsigned char *p;
8334 new->type = n->type;
8335 funcblock = (char *) funcblock + (int) nodesize[n->type];
8336 p = copynode_ops + (int) copynode_ops_index[n->type];
8338 char *nn = ((char *) new) + ((int) (*p & NODE_OFFSETMASK));
8339 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8341 if (!(*p & NODE_MBRMASK)) { /* standard node */
8342 *((union node **) nn) = copynode(*((const union node **) no));
8343 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8344 *((const char **) nn) = nodesavestr(*((const char **) no));
8345 } else if (*p & NODE_NODELIST) { /* nodelist */
8346 *((struct nodelist **) nn)
8347 = copynodelist(*((const struct nodelist **) no));
8348 } else { /* integer */
8349 *((int *) nn) = *((int *) no);
8351 } while (!(*p++ & NODE_NOMORE));
8354 #else /* COPYNODE_TABLE */
8355 static union node *copynode(const union node *n)
8362 funcblock = (char *) funcblock + nodesize[n->type];
8369 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8370 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8373 new->ncmd.redirect = copynode(n->ncmd.redirect);
8374 new->ncmd.args = copynode(n->ncmd.args);
8375 new->ncmd.assign = copynode(n->ncmd.assign);
8376 new->ncmd.backgnd = n->ncmd.backgnd;
8379 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8380 new->npipe.backgnd = n->npipe.backgnd;
8385 new->nredir.redirect = copynode(n->nredir.redirect);
8386 new->nredir.n = copynode(n->nredir.n);
8389 new->nif.elsepart = copynode(n->nif.elsepart);
8390 new->nif.ifpart = copynode(n->nif.ifpart);
8391 new->nif.test = copynode(n->nif.test);
8394 new->nfor.var = nodesavestr(n->nfor.var);
8395 new->nfor.body = copynode(n->nfor.body);
8396 new->nfor.args = copynode(n->nfor.args);
8399 new->ncase.cases = copynode(n->ncase.cases);
8400 new->ncase.expr = copynode(n->ncase.expr);
8403 new->nclist.body = copynode(n->nclist.body);
8404 new->nclist.pattern = copynode(n->nclist.pattern);
8405 new->nclist.next = copynode(n->nclist.next);
8409 new->narg.backquote = copynodelist(n->narg.backquote);
8410 new->narg.text = nodesavestr(n->narg.text);
8411 new->narg.next = copynode(n->narg.next);
8418 new->nfile.fname = copynode(n->nfile.fname);
8419 new->nfile.fd = n->nfile.fd;
8420 new->nfile.next = copynode(n->nfile.next);
8424 new->ndup.vname = copynode(n->ndup.vname);
8425 new->ndup.dupfd = n->ndup.dupfd;
8426 new->ndup.fd = n->ndup.fd;
8427 new->ndup.next = copynode(n->ndup.next);
8431 new->nhere.doc = copynode(n->nhere.doc);
8432 new->nhere.fd = n->nhere.fd;
8433 new->nhere.next = copynode(n->nhere.next);
8436 new->nnot.com = copynode(n->nnot.com);
8439 new->type = n->type;
8442 #endif /* COPYNODE_TABLE */
8444 #ifdef CALCSIZE_TABLE
8445 static void calcsize(const union node *n)
8447 const unsigned char *p;
8451 funcblocksize += (int) nodesize[n->type];
8453 p = copynode_ops + (int) copynode_ops_index[n->type];
8455 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8457 if (!(*p & NODE_MBRMASK)) { /* standard node */
8458 calcsize(*((const union node **) no));
8459 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8460 funcstringsize += strlen(*((const char **) no)) + 1;
8461 } else if (*p & NODE_NODELIST) { /* nodelist */
8462 sizenodelist(*((const struct nodelist **) no));
8463 } /* else integer -- ignore */
8464 } while (!(*p++ & NODE_NOMORE));
8466 #else /* CALCSIZE_TABLE */
8467 static void calcsize(const union node *n)
8471 funcblocksize += nodesize[n->type];
8478 calcsize(n->nbinary.ch2);
8479 calcsize(n->nbinary.ch1);
8482 calcsize(n->ncmd.redirect);
8483 calcsize(n->ncmd.args);
8484 calcsize(n->ncmd.assign);
8487 sizenodelist(n->npipe.cmdlist);
8492 calcsize(n->nredir.redirect);
8493 calcsize(n->nredir.n);
8496 calcsize(n->nif.elsepart);
8497 calcsize(n->nif.ifpart);
8498 calcsize(n->nif.test);
8501 funcstringsize += strlen(n->nfor.var) + 1;
8502 calcsize(n->nfor.body);
8503 calcsize(n->nfor.args);
8506 calcsize(n->ncase.cases);
8507 calcsize(n->ncase.expr);
8510 calcsize(n->nclist.body);
8511 calcsize(n->nclist.pattern);
8512 calcsize(n->nclist.next);
8516 sizenodelist(n->narg.backquote);
8517 funcstringsize += strlen(n->narg.text) + 1;
8518 calcsize(n->narg.next);
8525 calcsize(n->nfile.fname);
8526 calcsize(n->nfile.next);
8530 calcsize(n->ndup.vname);
8531 calcsize(n->ndup.next);
8535 calcsize(n->nhere.doc);
8536 calcsize(n->nhere.next);
8539 calcsize(n->nnot.com);
8543 #endif /* CALCSIZE_TABLE */
8545 static void sizenodelist(const struct nodelist *lp)
8548 funcblocksize += ALIGN(sizeof(struct nodelist));
8555 static struct nodelist *copynodelist(const struct nodelist *lp)
8557 struct nodelist *start;
8558 struct nodelist **lpp;
8563 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8564 (*lpp)->n = copynode(lp->n);
8566 lpp = &(*lpp)->next;
8573 static char *nodesavestr(const char *s)
8576 char *q = funcstring;
8577 char *rtn = funcstring;
8579 while ((*q++ = *p++) != '\0')
8585 #ifdef CONFIG_ASH_GETOPTS
8586 static int getopts(char *, char *, char **, int *, int *);
8590 * Process the shell command line arguments.
8593 static void procargs(int argc, char **argv)
8600 for (i = 0; i < NOPTS; i++)
8603 if (*argptr == NULL && minusc == NULL)
8605 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8609 for (i = 0; i < NOPTS; i++)
8610 if (optent_val(i) == 2)
8613 if (sflag == 0 && minusc == NULL) {
8614 commandname = argv[0];
8616 setinputfile(arg0, 0);
8619 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8620 if (argptr && minusc && *argptr)
8623 shellparam.p = argptr;
8624 shellparam.optind = 1;
8625 shellparam.optoff = -1;
8626 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8628 shellparam.nparam++;
8637 * Process shell options. The global variable argptr contains a pointer
8638 * to the argument list; we advance it past the options.
8641 static inline void minus_o(const char *name, int val)
8646 out1str("Current option settings\n");
8647 for (i = 0; i < NOPTS; i++)
8648 printf("%-16s%s\n", optent_name(optlist[i]),
8649 optent_val(i) ? "on" : "off");
8651 for (i = 0; i < NOPTS; i++)
8652 if (equal(name, optent_name(optlist[i]))) {
8653 setoption(optent_letter(optlist[i]), val);
8656 error("Illegal option -o %s", name);
8661 static void options(int cmdline)
8669 while ((p = *argptr) != NULL) {
8671 if ((c = *p++) == '-') {
8673 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8675 /* "-" means turn off -x and -v */
8678 /* "--" means reset params */
8679 else if (*argptr == NULL)
8682 break; /* "-" or "--" terminates options */
8684 } else if (c == '+') {
8690 while ((c = *p++) != '\0') {
8691 if (c == 'c' && cmdline) {
8694 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8698 if (q == NULL || minusc != NULL)
8699 error("Bad -c option");
8704 } else if (c == 'o') {
8705 minus_o(*argptr, val);
8708 } else if (cmdline && (c == '-')) { // long options
8709 if (strcmp(p, "login") == 0)
8720 static void setoption(int flag, int val)
8724 for (i = 0; i < NOPTS; i++)
8725 if (optent_letter(optlist[i]) == flag) {
8726 optent_val(i) = val;
8728 /* #%$ hack for ksh semantics */
8731 else if (flag == 'E')
8736 error("Illegal option -%c", flag);
8743 * Set the shell parameters.
8746 static void setparam(char **argv)
8752 for (nparam = 0; argv[nparam]; nparam++);
8753 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
8755 *ap++ = xstrdup(*argv++);
8758 freeparam(&shellparam);
8759 shellparam.malloc = 1;
8760 shellparam.nparam = nparam;
8761 shellparam.p = newparam;
8762 shellparam.optind = 1;
8763 shellparam.optoff = -1;
8768 * Free the list of positional parameters.
8771 static void freeparam(volatile struct shparam *param)
8775 if (param->malloc) {
8776 for (ap = param->p; *ap; ap++)
8785 * The shift builtin command.
8788 static int shiftcmd(int argc, char **argv)
8795 n = number(argv[1]);
8796 if (n > shellparam.nparam)
8797 error("can't shift that many");
8799 shellparam.nparam -= n;
8800 for (ap1 = shellparam.p; --n >= 0; ap1++) {
8801 if (shellparam.malloc)
8805 while ((*ap2++ = *ap1++) != NULL);
8806 shellparam.optind = 1;
8807 shellparam.optoff = -1;
8815 * The set command builtin.
8818 static int setcmd(int argc, char **argv)
8821 return showvarscmd(argc, argv);
8825 if (*argptr != NULL) {
8833 static void getoptsreset(const char *value)
8835 shellparam.optind = number(value);
8836 shellparam.optoff = -1;
8839 #ifdef CONFIG_LOCALE_SUPPORT
8840 static void change_lc_all(const char *value)
8842 if (value != 0 && *value != 0)
8843 setlocale(LC_ALL, value);
8846 static void change_lc_ctype(const char *value)
8848 if (value != 0 && *value != 0)
8849 setlocale(LC_CTYPE, value);
8854 #ifdef CONFIG_ASH_GETOPTS
8856 * The getopts builtin. Shellparam.optnext points to the next argument
8857 * to be processed. Shellparam.optptr points to the next character to
8858 * be processed in the current argument. If shellparam.optnext is NULL,
8859 * then it's the first time getopts has been called.
8862 static int getoptscmd(int argc, char **argv)
8867 error("Usage: getopts optstring var [arg]");
8868 else if (argc == 3) {
8869 optbase = shellparam.p;
8870 if (shellparam.optind > shellparam.nparam + 1) {
8871 shellparam.optind = 1;
8872 shellparam.optoff = -1;
8876 if (shellparam.optind > argc - 2) {
8877 shellparam.optind = 1;
8878 shellparam.optoff = -1;
8882 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
8883 &shellparam.optoff);
8887 * Safe version of setvar, returns 1 on success 0 on failure.
8890 static int setvarsafe(const char *name, const char *val, int flags)
8892 struct jmploc jmploc;
8893 struct jmploc *volatile savehandler = handler;
8900 if (setjmp(jmploc.loc))
8904 setvar(name, val, flags);
8906 handler = savehandler;
8911 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind,
8919 char **optnext = optfirst + *myoptind - 1;
8921 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
8922 strlen(*(optnext - 1)) < *optoff)
8925 p = *(optnext - 1) + *optoff;
8926 if (p == NULL || *p == '\0') {
8927 /* Current word is done, advance */
8928 if (optnext == NULL)
8931 if (p == NULL || *p != '-' || *++p == '\0') {
8933 *myoptind = optnext - optfirst + 1;
8939 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
8944 for (q = optstr; *q != c;) {
8946 if (optstr[0] == ':') {
8949 err |= setvarsafe("OPTARG", s, 0);
8951 out2fmt("Illegal option -%c\n", c);
8952 (void) unsetvar("OPTARG");
8962 if (*p == '\0' && (p = *optnext) == NULL) {
8963 if (optstr[0] == ':') {
8966 err |= setvarsafe("OPTARG", s, 0);
8969 out2fmt("No arg for -%c option\n", c);
8970 (void) unsetvar("OPTARG");
8978 setvarsafe("OPTARG", p, 0);
8981 setvarsafe("OPTARG", "", 0);
8982 *myoptind = optnext - optfirst + 1;
8989 *optoff = p ? p - *(optnext - 1) : -1;
8990 snprintf(s, sizeof(s), "%d", *myoptind);
8991 err |= setvarsafe("OPTIND", s, VNOFUNC);
8994 err |= setvarsafe(optvar, s, 0);
9005 * XXX - should get rid of. have all builtins use getopt(3). the
9006 * library getopt must have the BSD extension static variable "optreset"
9007 * otherwise it can't be used within the shell safely.
9009 * Standard option processing (a la getopt) for builtin routines. The
9010 * only argument that is passed to nextopt is the option string; the
9011 * other arguments are unnecessary. It return the character, or '\0' on
9015 static int nextopt(const char *optstring)
9021 if ((p = optptr) == NULL || *p == '\0') {
9023 if (p == NULL || *p != '-' || *++p == '\0')
9026 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9030 for (q = optstring; *q != c;) {
9032 error("Illegal option -%c", c);
9037 if (*p == '\0' && (p = *argptr++) == NULL)
9038 error("No arg for -%c option", c);
9046 static void flushall()
9054 static void out2fmt(const char *fmt, ...)
9059 vfprintf(stderr, fmt, ap);
9064 * Version of write which resumes after a signal is caught.
9067 static int xwrite(int fd, const char *buf, int nbytes)
9076 i = write(fd, buf, n);
9082 } else if (i == 0) {
9085 } else if (errno != EINTR) {
9093 * Shell command parser.
9096 #define EOFMARKLEN 79
9101 struct heredoc *next; /* next here document in list */
9102 union node *here; /* redirection node */
9103 char *eofmark; /* string indicating end of input */
9104 int striptabs; /* if set, strip leading tabs */
9107 static struct heredoc *heredoclist; /* list of here documents to read */
9108 static int parsebackquote; /* nonzero if we are inside backquotes */
9109 static int doprompt; /* if set, prompt the user */
9110 static int needprompt; /* true if interactive and at start of line */
9111 static int lasttoken; /* last token read */
9113 static char *wordtext; /* text of last word returned by readtoken */
9115 static struct nodelist *backquotelist;
9116 static union node *redirnode;
9117 static struct heredoc *heredoc;
9118 static int quoteflag; /* set if (part of) last token was quoted */
9119 static int startlinno; /* line # where last token started */
9122 static union node *list(int);
9123 static union node *andor(void);
9124 static union node *pipeline(void);
9125 static union node *command(void);
9126 static union node *simplecmd(union node **rpp, union node *redir);
9127 static void parsefname(void);
9128 static void parseheredoc(void);
9129 static char peektoken(void);
9130 static int readtoken(void);
9131 static int xxreadtoken(void);
9132 static int readtoken1(int, int, const char *, int);
9133 static int noexpand(char *);
9134 static void synexpect(int) __attribute__ ((noreturn));
9135 static void synerror(const char *) __attribute__ ((noreturn));
9136 static void setprompt(int);
9140 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9141 * valid parse tree indicating a blank line.)
9144 static union node *parsecmd(int interact)
9149 doprompt = interact;
9165 static union node *list(int nlflag)
9167 union node *n1, *n2, *n3;
9171 if (nlflag == 0 && peektoken())
9177 if (tok == TBACKGND) {
9178 if (n2->type == NCMD || n2->type == NPIPE) {
9179 n2->ncmd.backgnd = 1;
9180 } else if (n2->type == NREDIR) {
9181 n2->type = NBACKGND;
9183 n3 = (union node *) stalloc(sizeof(struct nredir));
9184 n3->type = NBACKGND;
9186 n3->nredir.redirect = NULL;
9193 n3 = (union node *) stalloc(sizeof(struct nbinary));
9195 n3->nbinary.ch1 = n1;
9196 n3->nbinary.ch2 = n2;
9220 pungetc(); /* push back EOF on input */
9233 static union node *andor()
9235 union node *n1, *n2, *n3;
9241 if ((t = readtoken()) == TAND) {
9243 } else if (t == TOR) {
9251 n3 = (union node *) stalloc(sizeof(struct nbinary));
9253 n3->nbinary.ch1 = n1;
9254 n3->nbinary.ch2 = n2;
9261 static union node *pipeline()
9263 union node *n1, *n2, *pipenode;
9264 struct nodelist *lp, *prev;
9268 TRACE(("pipeline: entered\n"));
9269 if (readtoken() == TNOT) {
9275 if (readtoken() == TPIPE) {
9276 pipenode = (union node *) stalloc(sizeof(struct npipe));
9277 pipenode->type = NPIPE;
9278 pipenode->npipe.backgnd = 0;
9279 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9280 pipenode->npipe.cmdlist = lp;
9284 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9288 } while (readtoken() == TPIPE);
9294 n2 = (union node *) stalloc(sizeof(struct nnot));
9304 static union node *command(void)
9306 union node *n1, *n2;
9307 union node *ap, **app;
9308 union node *cp, **cpp;
9309 union node *redir, **rpp;
9316 /* Check for redirection which may precede command */
9317 while (readtoken() == TREDIR) {
9318 *rpp = n2 = redirnode;
9319 rpp = &n2->nfile.next;
9324 switch (readtoken()) {
9326 n1 = (union node *) stalloc(sizeof(struct nif));
9328 n1->nif.test = list(0);
9329 if (readtoken() != TTHEN)
9331 n1->nif.ifpart = list(0);
9333 while (readtoken() == TELIF) {
9334 n2->nif.elsepart = (union node *) stalloc(sizeof(struct nif));
9335 n2 = n2->nif.elsepart;
9337 n2->nif.test = list(0);
9338 if (readtoken() != TTHEN)
9340 n2->nif.ifpart = list(0);
9342 if (lasttoken == TELSE)
9343 n2->nif.elsepart = list(0);
9345 n2->nif.elsepart = NULL;
9348 if (readtoken() != TFI)
9355 n1 = (union node *) stalloc(sizeof(struct nbinary));
9356 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9357 n1->nbinary.ch1 = list(0);
9358 if ((got = readtoken()) != TDO) {
9359 TRACE(("expecting DO got %s %s\n", tokname(got),
9360 got == TWORD ? wordtext : ""));
9363 n1->nbinary.ch2 = list(0);
9364 if (readtoken() != TDONE)
9370 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
9371 synerror("Bad for loop variable");
9372 n1 = (union node *) stalloc(sizeof(struct nfor));
9374 n1->nfor.var = wordtext;
9376 if (readtoken() == TIN) {
9378 while (readtoken() == TWORD) {
9379 n2 = (union node *) stalloc(sizeof(struct narg));
9381 n2->narg.text = wordtext;
9382 n2->narg.backquote = backquotelist;
9384 app = &n2->narg.next;
9388 if (lasttoken != TNL && lasttoken != TSEMI)
9391 static char argvars[5] = { CTLVAR, VSNORMAL | VSQUOTE,
9394 n2 = (union node *) stalloc(sizeof(struct narg));
9396 n2->narg.text = argvars;
9397 n2->narg.backquote = NULL;
9398 n2->narg.next = NULL;
9401 * Newline or semicolon here is optional (but note
9402 * that the original Bourne shell only allowed NL).
9404 if (lasttoken != TNL && lasttoken != TSEMI)
9408 if (readtoken() != TDO)
9410 n1->nfor.body = list(0);
9411 if (readtoken() != TDONE)
9416 n1 = (union node *) stalloc(sizeof(struct ncase));
9418 if (readtoken() != TWORD)
9420 n1->ncase.expr = n2 = (union node *) stalloc(sizeof(struct narg));
9422 n2->narg.text = wordtext;
9423 n2->narg.backquote = backquotelist;
9424 n2->narg.next = NULL;
9427 } while (readtoken() == TNL);
9428 if (lasttoken != TIN)
9429 synerror("expecting \"in\"");
9430 cpp = &n1->ncase.cases;
9431 checkkwd = 2, readtoken();
9433 if (lasttoken == TLP)
9435 *cpp = cp = (union node *) stalloc(sizeof(struct nclist));
9437 app = &cp->nclist.pattern;
9439 *app = ap = (union node *) stalloc(sizeof(struct narg));
9441 ap->narg.text = wordtext;
9442 ap->narg.backquote = backquotelist;
9443 if (checkkwd = 2, readtoken() != TPIPE)
9445 app = &ap->narg.next;
9448 ap->narg.next = NULL;
9449 if (lasttoken != TRP)
9451 cp->nclist.body = list(0);
9454 if ((t = readtoken()) != TESAC) {
9456 synexpect(TENDCASE);
9458 checkkwd = 2, readtoken();
9460 cpp = &cp->nclist.next;
9461 } while (lasttoken != TESAC);
9466 n1 = (union node *) stalloc(sizeof(struct nredir));
9467 n1->type = NSUBSHELL;
9468 n1->nredir.n = list(0);
9469 n1->nredir.redirect = NULL;
9470 if (readtoken() != TRP)
9476 if (readtoken() != TEND)
9480 /* Handle an empty command like other simple commands. */
9489 * An empty command before a ; doesn't make much sense, and
9490 * should certainly be disallowed in the case of `if ;'.
9496 n1 = simplecmd(rpp, redir);
9503 /* Now check for redirection which may follow command */
9504 while (readtoken() == TREDIR) {
9505 *rpp = n2 = redirnode;
9506 rpp = &n2->nfile.next;
9512 if (n1->type != NSUBSHELL) {
9513 n2 = (union node *) stalloc(sizeof(struct nredir));
9518 n1->nredir.redirect = redir;
9525 static union node *simplecmd(union node **rpp, union node *redir)
9527 union node *args, **app;
9528 union node *n = NULL;
9529 union node *vars, **vpp;
9530 union node **orig_rpp;
9537 /* If we don't have any redirections already, then we must reset
9538 rpp to be the address of the local redir variable. */
9541 /* We save the incoming value, because we need this for shell
9542 functions. There can not be a redirect or an argument between
9543 the function name and the open parenthesis. */
9548 switch (readtoken()) {
9551 n = (union node *) stalloc(sizeof(struct narg));
9553 n->narg.text = wordtext;
9554 n->narg.backquote = backquotelist;
9555 if (lasttoken == TWORD) {
9557 app = &n->narg.next;
9560 vpp = &n->narg.next;
9564 *rpp = n = redirnode;
9565 rpp = &n->nfile.next;
9566 parsefname(); /* read name of redirection file */
9569 if (args && app == &args->narg.next && !vars && rpp == orig_rpp) {
9570 /* We have a function */
9571 if (readtoken() != TRP)
9575 n->narg.next = command();
9588 n = (union node *) stalloc(sizeof(struct ncmd));
9590 n->ncmd.backgnd = 0;
9591 n->ncmd.args = args;
9592 n->ncmd.assign = vars;
9593 n->ncmd.redirect = redir;
9597 static union node *makename(void)
9601 n = (union node *) stalloc(sizeof(struct narg));
9603 n->narg.next = NULL;
9604 n->narg.text = wordtext;
9605 n->narg.backquote = backquotelist;
9609 static void fixredir(union node *n, const char *text, int err)
9611 TRACE(("Fix redir %s %d\n", text, err));
9613 n->ndup.vname = NULL;
9615 if (is_digit(text[0]) && text[1] == '\0')
9616 n->ndup.dupfd = digit_val(text[0]);
9617 else if (text[0] == '-' && text[1] == '\0')
9622 synerror("Bad fd number");
9624 n->ndup.vname = makename();
9629 static void parsefname(void)
9631 union node *n = redirnode;
9633 if (readtoken() != TWORD)
9635 if (n->type == NHERE) {
9636 struct heredoc *here = heredoc;
9642 TRACE(("Here document %d\n", n->type));
9643 if (here->striptabs) {
9644 while (*wordtext == '\t')
9647 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0
9649 synerror("Illegal eof marker for << redirection");
9650 rmescapes(wordtext);
9651 here->eofmark = wordtext;
9653 if (heredoclist == NULL)
9656 for (p = heredoclist; p->next; p = p->next);
9659 } else if (n->type == NTOFD || n->type == NFROMFD) {
9660 fixredir(n, wordtext, 0);
9662 n->nfile.fname = makename();
9668 * Input any here documents.
9671 static void parseheredoc()
9673 struct heredoc *here;
9676 while (heredoclist) {
9678 heredoclist = here->next;
9683 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
9684 here->eofmark, here->striptabs);
9685 n = (union node *) stalloc(sizeof(struct narg));
9686 n->narg.type = NARG;
9687 n->narg.next = NULL;
9688 n->narg.text = wordtext;
9689 n->narg.backquote = backquotelist;
9690 here->here->nhere.doc = n;
9694 static char peektoken()
9700 return tokname_array[t][0];
9703 static int readtoken()
9707 int savecheckalias = checkalias;
9709 #ifdef CONFIG_ASH_ALIAS
9710 int savecheckkwd = checkkwd;
9715 int alreadyseen = tokpushback;
9718 #ifdef CONFIG_ASH_ALIAS
9724 checkalias = savecheckalias;
9730 if (checkkwd == 2) {
9739 * check for keywords
9741 if (t == TWORD && !quoteflag) {
9742 const char *const *pp;
9744 if ((pp = findkwd(wordtext))) {
9745 lasttoken = t = pp - tokname_array;
9746 TRACE(("keyword %s recognized\n", tokname(t)));
9757 } else if (checkalias == 2 && isassignment(wordtext)) {
9758 lasttoken = t = TASSIGN;
9759 } else if (checkalias) {
9760 #ifdef CONFIG_ASH_ALIAS
9761 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL
9762 && !(ap->flag & ALIASINUSE)) {
9764 pushstring(ap->val, strlen(ap->val), ap);
9766 checkkwd = savecheckkwd;
9775 TRACE(("token %s %s\n", tokname(t), t == TWORD
9776 || t == TASSIGN ? wordtext : ""));
9778 TRACE(("reread token %s %s\n", tokname(t), t == TWORD
9779 || t == TASSIGN ? wordtext : ""));
9786 * Read the next input token.
9787 * If the token is a word, we set backquotelist to the list of cmds in
9788 * backquotes. We set quoteflag to true if any part of the word was
9790 * If the token is TREDIR, then we set redirnode to a structure containing
9792 * In all cases, the variable startlinno is set to the number of the line
9793 * on which the token starts.
9795 * [Change comment: here documents and internal procedures]
9796 * [Readtoken shouldn't have any arguments. Perhaps we should make the
9797 * word parsing code into a separate routine. In this case, readtoken
9798 * doesn't need to have any internal procedures, but parseword does.
9799 * We could also make parseoperator in essence the main routine, and
9800 * have parseword (readtoken1?) handle both words and redirection.]
9803 #define NEW_xxreadtoken
9804 #ifdef NEW_xxreadtoken
9806 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
9807 static const char xxreadtoken_tokens[] = {
9808 TNL, TLP, TRP, /* only single occurrence allowed */
9809 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
9810 TEOF, /* corresponds to trailing nul */
9811 TAND, TOR, TENDCASE, /* if double occurrence */
9814 #define xxreadtoken_doubles \
9815 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
9816 #define xxreadtoken_singles \
9817 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
9819 static int xxreadtoken()
9831 startlinno = plinno;
9832 for (;;) { /* until token or start of word found */
9835 if ((c != ' ') && (c != '\t')
9836 #ifdef CONFIG_ASH_ALIAS
9841 while ((c = pgetc()) != '\n' && c != PEOF);
9843 } else if (c == '\\') {
9844 if (pgetc() != '\n') {
9848 startlinno = ++plinno;
9849 setprompt(doprompt ? 2 : 0);
9852 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
9857 needprompt = doprompt;
9860 p = strchr(xxreadtoken_chars, c);
9863 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
9866 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
9867 if (pgetc() == *p) { /* double occurrence? */
9868 p += xxreadtoken_doubles + 1;
9875 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
9883 #define RETURN(token) return lasttoken = token
9885 static int xxreadtoken()
9897 startlinno = plinno;
9898 for (;;) { /* until token or start of word found */
9903 #ifdef CONFIG_ASH_ALIAS
9908 while ((c = pgetc()) != '\n' && c != PEOF);
9912 if (pgetc() == '\n') {
9913 startlinno = ++plinno;
9924 needprompt = doprompt;
9952 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
9958 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
9959 * is not NULL, read a here document. In the latter case, eofmark is the
9960 * word which marks the end of the document and striptabs is true if
9961 * leading tabs should be stripped from the document. The argument firstc
9962 * is the first character of the input token or document.
9964 * Because C does not have internal subroutines, I have simulated them
9965 * using goto's to implement the subroutine linkage. The following macros
9966 * will run code that appears at the end of readtoken1.
9969 #define CHECKEND() {goto checkend; checkend_return:;}
9970 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
9971 #define PARSESUB() {goto parsesub; parsesub_return:;}
9972 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
9973 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
9974 #define PARSEARITH() {goto parsearith; parsearith_return:;}
9977 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
9982 char line[EOFMARKLEN + 1];
9983 struct nodelist *bqlist;
9986 int varnest; /* levels of variables expansion */
9987 int arinest; /* levels of arithmetic expansion */
9988 int parenlevel; /* levels of parens in arithmetic */
9989 int dqvarnest; /* levels of variables expansion within double quotes */
9991 int prevsyntax; /* syntax before arithmetic */
9994 /* Avoid longjmp clobbering */
10000 (void) &parenlevel;
10003 (void) &prevsyntax;
10007 startlinno = plinno;
10009 if (syntax == DQSYNTAX)
10018 STARTSTACKSTR(out);
10019 loop:{ /* for each line, until end of word */
10020 CHECKEND(); /* set c to PEOF if at end of here document */
10021 for (;;) { /* until end of line or end of word */
10022 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10023 switch (SIT(c, syntax)) {
10024 case CNL: /* '\n' */
10025 if (syntax == BASESYNTAX)
10026 goto endword; /* exit outer loop */
10034 goto loop; /* continue outer loop */
10039 if ((eofmark == NULL || dblquote) && dqvarnest == 0)
10040 USTPUTC(CTLESC, out);
10043 case CBACK: /* backslash */
10046 USTPUTC('\\', out);
10048 } else if (c == '\n') {
10054 if (dblquote && c != '\\' && c != '`' && c != '$'
10055 && (c != '"' || eofmark != NULL))
10056 USTPUTC('\\', out);
10057 if (SIT(c, SQSYNTAX) == CCTL)
10058 USTPUTC(CTLESC, out);
10059 else if (eofmark == NULL)
10060 USTPUTC(CTLQUOTEMARK, out);
10066 if (eofmark == NULL)
10067 USTPUTC(CTLQUOTEMARK, out);
10071 if (eofmark == NULL)
10072 USTPUTC(CTLQUOTEMARK, out);
10077 if (eofmark != NULL && arinest == 0 && varnest == 0) {
10081 syntax = ARISYNTAX;
10083 } else if (eofmark == NULL && dqvarnest == 0) {
10084 syntax = BASESYNTAX;
10090 case CVAR: /* '$' */
10091 PARSESUB(); /* parse substitution */
10093 case CENDVAR: /* '}' */
10096 if (dqvarnest > 0) {
10099 USTPUTC(CTLENDVAR, out);
10104 #ifdef CONFIG_ASH_MATH_SUPPORT
10105 case CLP: /* '(' in arithmetic */
10109 case CRP: /* ')' in arithmetic */
10110 if (parenlevel > 0) {
10114 if (pgetc() == ')') {
10115 if (--arinest == 0) {
10116 USTPUTC(CTLENDARI, out);
10117 syntax = prevsyntax;
10118 if (syntax == DQSYNTAX)
10126 * unbalanced parens
10127 * (don't 2nd guess - no error)
10135 case CBQUOTE: /* '`' */
10139 goto endword; /* exit outer loop */
10144 goto endword; /* exit outer loop */
10145 #ifdef CONFIG_ASH_ALIAS
10155 if (syntax == ARISYNTAX)
10156 synerror("Missing '))'");
10157 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10158 synerror("Unterminated quoted string");
10159 if (varnest != 0) {
10160 startlinno = plinno;
10161 synerror("Missing '}'");
10163 USTPUTC('\0', out);
10164 len = out - stackblock();
10165 out = stackblock();
10166 if (eofmark == NULL) {
10167 if ((c == '>' || c == '<')
10168 && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) {
10170 return lasttoken = TREDIR;
10175 quoteflag = quotef;
10176 backquotelist = bqlist;
10177 grabstackblock(len);
10179 return lasttoken = TWORD;
10180 /* end of readtoken routine */
10185 * Check to see whether we are at the end of the here document. When this
10186 * is called, c is set to the first character of the next input line. If
10187 * we are at the end of the here document, this routine sets the c to PEOF.
10192 #ifdef CONFIG_ASH_ALIAS
10198 while (c == '\t') {
10202 if (c == *eofmark) {
10203 if (pfgets(line, sizeof line) != NULL) {
10207 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10208 if (*p == '\n' && *q == '\0') {
10211 needprompt = doprompt;
10213 pushstring(line, strlen(line), NULL);
10218 goto checkend_return;
10223 * Parse a redirection operator. The variable "out" points to a string
10224 * specifying the fd to be redirected. The variable "c" contains the
10225 * first character of the redirection operator.
10232 np = (union node *) stalloc(sizeof(struct nfile));
10237 np->type = NAPPEND;
10246 } else { /* c == '<' */
10248 switch (c = pgetc()) {
10250 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10251 np = (union node *) stalloc(sizeof(struct nhere));
10255 heredoc = (struct heredoc *) stalloc(sizeof(struct heredoc));
10256 heredoc->here = np;
10257 if ((c = pgetc()) == '-') {
10258 heredoc->striptabs = 1;
10260 heredoc->striptabs = 0;
10266 np->type = NFROMFD;
10270 np->type = NFROMTO;
10280 np->nfile.fd = digit_val(fd);
10282 goto parseredir_return;
10287 * Parse a substitution. At this point, we have read the dollar sign
10288 * and nothing else.
10296 static const char types[] = "}-+?=";
10300 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10304 } else if (c == '(') { /* $(command) or $((arith)) */
10305 if (pgetc() == '(') {
10312 USTPUTC(CTLVAR, out);
10313 typeloc = out - stackblock();
10314 USTPUTC(VSNORMAL, out);
10315 subtype = VSNORMAL;
10319 if ((c = pgetc()) == '}')
10322 subtype = VSLENGTH;
10326 if (c > PEOA && is_name(c)) {
10330 } while (c > PEOA && is_in_name(c));
10331 } else if (is_digit(c)) {
10335 } while (is_digit(c));
10336 } else if (is_special(c)) {
10340 badsub:synerror("Bad substitution");
10344 if (subtype == 0) {
10349 /*FALLTHROUGH*/ default:
10350 p = strchr(types, c);
10353 subtype = p - types + VSNORMAL;
10360 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
10372 if (dblquote || arinest)
10374 *(stackblock() + typeloc) = subtype | flags;
10375 if (subtype != VSNORMAL) {
10382 goto parsesub_return;
10387 * Called to parse command substitutions. Newstyle is set if the command
10388 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10389 * list of commands (passed by reference), and savelen is the number of
10390 * characters on the top of the stack which must be preserved.
10394 struct nodelist **nlpp;
10397 char *volatile str;
10398 struct jmploc jmploc;
10399 struct jmploc *volatile savehandler;
10404 (void) &saveprompt;
10407 savepbq = parsebackquote;
10408 if (setjmp(jmploc.loc)) {
10410 parsebackquote = 0;
10411 handler = savehandler;
10412 longjmp(handler->loc, 1);
10416 savelen = out - stackblock();
10418 str = xmalloc(savelen);
10419 memcpy(str, stackblock(), savelen);
10421 savehandler = handler;
10425 /* We must read until the closing backquote, giving special
10426 treatment to some slashes, and then push the string and
10427 reread it as input, interpreting it normally. */
10434 STARTSTACKSTR(pout);
10440 switch (pc = pgetc()) {
10445 if ((pc = pgetc()) == '\n') {
10452 * If eating a newline, avoid putting
10453 * the newline into the new character
10454 * stream (via the STPUTC after the
10459 if (pc != '\\' && pc != '`' && pc != '$'
10460 && (!dblquote || pc != '"'))
10461 STPUTC('\\', pout);
10468 #ifdef CONFIG_ASH_ALIAS
10471 startlinno = plinno;
10472 synerror("EOF in backquote substitution");
10476 needprompt = doprompt;
10485 STPUTC('\0', pout);
10486 psavelen = pout - stackblock();
10487 if (psavelen > 0) {
10488 pstr = grabstackstr(pout);
10489 setinputstring(pstr);
10494 nlpp = &(*nlpp)->next;
10495 *nlpp = (struct nodelist *) stalloc(sizeof(struct nodelist));
10496 (*nlpp)->next = NULL;
10497 parsebackquote = oldstyle;
10500 saveprompt = doprompt;
10507 doprompt = saveprompt;
10509 if (readtoken() != TRP)
10516 * Start reading from old file again, ignoring any pushed back
10517 * tokens left from the backquote parsing
10522 while (stackblocksize() <= savelen)
10524 STARTSTACKSTR(out);
10526 memcpy(out, str, savelen);
10527 STADJUST(savelen, out);
10533 parsebackquote = savepbq;
10534 handler = savehandler;
10535 if (arinest || dblquote)
10536 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10538 USTPUTC(CTLBACKQ, out);
10540 goto parsebackq_oldreturn;
10542 goto parsebackq_newreturn;
10546 * Parse an arithmetic expansion (indicate start of one and set state)
10550 if (++arinest == 1) {
10551 prevsyntax = syntax;
10552 syntax = ARISYNTAX;
10553 USTPUTC(CTLARI, out);
10560 * we collapse embedded arithmetic expansion to
10561 * parenthesis, which should be equivalent
10565 goto parsearith_return;
10568 } /* end of readtoken */
10572 * Returns true if the text contains nothing to expand (no dollar signs
10576 static int noexpand(char *text)
10582 while ((c = *p++) != '\0') {
10583 if (c == CTLQUOTEMARK)
10587 else if (SIT(c, BASESYNTAX) == CCTL)
10595 * Return true if the argument is a legal variable name (a letter or
10596 * underscore followed by zero or more letters, underscores, and digits).
10599 static int goodname(const char *name)
10607 if (!is_in_name(*p))
10615 * Called when an unexpected token is read during the parse. The argument
10616 * is the token that is expected, or -1 if more than one type of token can
10617 * occur at this point.
10620 static void synexpect(int token)
10625 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10627 sprintf(msg + l, " (expecting %s)", tokname(token));
10633 static void synerror(const char *msg)
10636 out2fmt("%s: %d: ", commandname, startlinno);
10637 out2fmt("Syntax error: %s\n", msg);
10638 error((char *) NULL);
10644 * called by editline -- any expansions to the prompt
10645 * should be added here.
10647 static void setprompt(int whichprompt)
10651 switch (whichprompt) {
10666 * Code for dealing with input/output redirection.
10669 #define EMPTY -2 /* marks an unused slot in redirtab */
10671 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10673 # define PIPESIZE PIPE_BUF
10678 * Open a file in noclobber mode.
10679 * The code was copied from bash.
10681 static inline int noclobberopen(const char *fname)
10684 struct stat finfo, finfo2;
10687 * If the file exists and is a regular file, return an error
10690 r = stat(fname, &finfo);
10691 if (r == 0 && S_ISREG(finfo.st_mode)) {
10697 * If the file was not present (r != 0), make sure we open it
10698 * exclusively so that if it is created before we open it, our open
10699 * will fail. Make sure that we do not truncate an existing file.
10700 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10701 * file was not a regular file, we leave O_EXCL off.
10704 return open(fname, O_WRONLY | O_CREAT | O_EXCL, 0666);
10705 fd = open(fname, O_WRONLY | O_CREAT, 0666);
10707 /* If the open failed, return the file descriptor right away. */
10712 * OK, the open succeeded, but the file may have been changed from a
10713 * non-regular file to a regular file between the stat and the open.
10714 * We are assuming that the O_EXCL open handles the case where FILENAME
10715 * did not exist and is symlinked to an existing file between the stat
10720 * If we can open it and fstat the file descriptor, and neither check
10721 * revealed that it was a regular file, and the file has not been
10722 * replaced, return the file descriptor.
10724 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10725 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10728 /* The file has been replaced. badness. */
10735 * Handle here documents. Normally we fork off a process to write the
10736 * data to a pipe. If the document is short, we can stuff the data in
10737 * the pipe without forking.
10740 static inline int openhere(const union node *redir)
10746 error("Pipe call failed");
10747 if (redir->type == NHERE) {
10748 len = strlen(redir->nhere.doc->narg.text);
10749 if (len <= PIPESIZE) {
10750 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10754 if (forkshell((struct job *) NULL, (union node *) NULL, FORK_NOJOB) == 0) {
10756 signal(SIGINT, SIG_IGN);
10757 signal(SIGQUIT, SIG_IGN);
10758 signal(SIGHUP, SIG_IGN);
10760 signal(SIGTSTP, SIG_IGN);
10762 signal(SIGPIPE, SIG_DFL);
10763 if (redir->type == NHERE)
10764 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10766 expandhere(redir->nhere.doc, pip[1]);
10775 static inline int openredirect(const union node *redir)
10780 switch (redir->nfile.type) {
10782 fname = redir->nfile.expfname;
10783 if ((f = open(fname, O_RDONLY)) < 0)
10787 fname = redir->nfile.expfname;
10788 if ((f = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0)
10792 /* Take care of noclobber mode. */
10794 fname = redir->nfile.expfname;
10795 if ((f = noclobberopen(fname)) < 0)
10800 fname = redir->nfile.expfname;
10802 if ((f = open(fname, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
10805 if ((f = creat(fname, 0666)) < 0)
10810 fname = redir->nfile.expfname;
10812 if ((f = open(fname, O_WRONLY | O_CREAT | O_APPEND, 0666)) < 0)
10815 if ((f = open(fname, O_WRONLY)) < 0 && (f = creat(fname, 0666)) < 0)
10817 lseek(f, (off_t) 0, 2);
10824 /* Fall through to eliminate warning. */
10831 f = openhere(redir);
10837 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
10839 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
10844 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
10845 * old file descriptors are stashed away so that the redirection can be
10846 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
10847 * standard output, and the standard error if it becomes a duplicate of
10851 static void redirect(union node *redir, int flags)
10854 struct redirtab *sv = NULL;
10859 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
10861 TRACE(("redirect(%s) called\n",
10862 flags & REDIR_PUSH ? "REDIR_PUSH" : "NO_REDIR_PUSH"));
10863 if (flags & REDIR_PUSH) {
10864 sv = xmalloc(sizeof(struct redirtab));
10865 for (i = 0; i < 10; i++)
10866 sv->renamed[i] = EMPTY;
10867 sv->next = redirlist;
10870 for (n = redir; n; n = n->nfile.next) {
10873 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
10874 n->ndup.dupfd == fd)
10875 continue; /* redirect from/to same file descriptor */
10878 newfd = openredirect(n);
10879 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
10883 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
10887 dupredirect(n, newfd, fd1dup);
10897 error("%d: %m", fd);
10903 if (flags & REDIR_PUSH) {
10904 sv->renamed[fd] = i;
10907 } else if (fd != newfd) {
10913 dupredirect(n, newfd, fd1dup);
10919 static void dupredirect(const union node *redir, int f, int fd1dup)
10921 int fd = redir->nfile.fd;
10925 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
10926 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
10927 if (redir->ndup.dupfd != 1 || fd1dup != 1)
10928 dup_as_newfd(redir->ndup.dupfd, fd);
10934 dup_as_newfd(f, fd);
10943 * Undo the effects of the last redirection.
10946 static void popredir(void)
10948 struct redirtab *rp = redirlist;
10952 for (i = 0; i < 10; i++) {
10953 if (rp->renamed[i] != EMPTY) {
10957 if (rp->renamed[i] >= 0) {
10958 dup_as_newfd(rp->renamed[i], i);
10959 close(rp->renamed[i]);
10963 redirlist = rp->next;
10969 * Discard all saved file descriptors.
10972 static void clearredir(void)
10974 struct redirtab *rp;
10977 for (rp = redirlist; rp; rp = rp->next) {
10978 for (i = 0; i < 10; i++) {
10979 if (rp->renamed[i] >= 0) {
10980 close(rp->renamed[i]);
10982 rp->renamed[i] = EMPTY;
10989 * Copy a file descriptor to be >= to. Returns -1
10990 * if the source file descriptor is closed, EMPTY if there are no unused
10991 * file descriptors left.
10994 static int dup_as_newfd(int from, int to)
10998 newfd = fcntl(from, F_DUPFD, to);
11000 if (errno == EMFILE)
11003 error("%d: %m", from);
11013 static void shtree(union node *, int, char *, FILE *);
11014 static void shcmd(union node *, FILE *);
11015 static void sharg(union node *, FILE *);
11016 static void indent(int, char *, FILE *);
11017 static void trstring(char *);
11021 static void showtree(node * n)
11023 trputs("showtree called\n");
11024 shtree(n, 1, NULL, stdout);
11028 static void shtree(union node *n, int ind, char *pfx, FILE * fp)
11030 struct nodelist *lp;
11036 indent(ind, pfx, fp);
11047 shtree(n->nbinary.ch1, ind, NULL, fp);
11050 shtree(n->nbinary.ch2, ind, NULL, fp);
11058 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
11063 if (n->npipe.backgnd)
11069 fprintf(fp, "<node type %d>", n->type);
11077 static void shcmd(union node *cmd, FILE * fp)
11085 for (np = cmd->ncmd.args; np; np = np->narg.next) {
11091 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
11097 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11098 s = redir_strings[np->nfile.type - NTO];
11104 switch (np->nfile.type) {
11139 if (np->nfile.fd != dftfd)
11140 fprintf(fp, "%d", np->nfile.fd);
11142 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11143 fprintf(fp, "%d", np->ndup.dupfd);
11145 sharg(np->nfile.fname, fp);
11152 static void sharg(union node *arg, FILE * fp)
11155 struct nodelist *bqlist;
11158 if (arg->type != NARG) {
11159 printf("<node type %d>\n", arg->type);
11163 bqlist = arg->narg.backquote;
11164 for (p = arg->narg.text; *p; p++) {
11173 if (subtype == VSLENGTH)
11179 if (subtype & VSNUL)
11182 switch (subtype & VSTYPE) {
11201 case VSTRIMLEFTMAX:
11208 case VSTRIMRIGHTMAX:
11215 printf("<subtype %d>", subtype);
11222 case CTLBACKQ | CTLQUOTE:
11225 shtree(bqlist->n, -1, NULL, fp);
11236 static void indent(int amount, char *pfx, FILE * fp)
11240 for (i = 0; i < amount; i++) {
11241 if (pfx && i == amount - 1)
11250 static int debug = 1;
11252 static int debug = 0;
11256 static void trputc(int c)
11258 if (tracefile == NULL)
11260 putc(c, tracefile);
11265 static void trace(const char *fmt, ...)
11270 if (tracefile != NULL) {
11271 (void) vfprintf(tracefile, fmt, va);
11272 if (strchr(fmt, '\n'))
11273 (void) fflush(tracefile);
11279 static void trputs(const char *s)
11281 if (tracefile == NULL)
11283 fputs(s, tracefile);
11284 if (strchr(s, '\n'))
11289 static void trstring(char *s)
11294 if (tracefile == NULL)
11296 putc('"', tracefile);
11297 for (p = s; *p; p++) {
11320 case CTLVAR + CTLQUOTE:
11326 case CTLBACKQ + CTLQUOTE:
11329 backslash:putc('\\', tracefile);
11330 putc(c, tracefile);
11333 if (*p >= ' ' && *p <= '~')
11334 putc(*p, tracefile);
11336 putc('\\', tracefile);
11337 putc(*p >> 6 & 03, tracefile);
11338 putc(*p >> 3 & 07, tracefile);
11339 putc(*p & 07, tracefile);
11344 putc('"', tracefile);
11348 static void trargs(char **ap)
11350 if (tracefile == NULL)
11355 putc(' ', tracefile);
11357 putc('\n', tracefile);
11363 static void opentrace()
11373 #ifdef not_this_way
11377 if ((p = getenv("HOME")) == NULL) {
11378 if (geteuid() == 0)
11384 strcat(s, "/trace");
11387 strcpy(s, "./trace");
11388 #endif /* not_this_way */
11389 if ((tracefile = wfopen(s, "a")) == NULL)
11392 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11393 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11395 fputs("\nTracing started.\n", tracefile);
11402 * The trap builtin.
11405 static int trapcmd(int argc, char **argv)
11412 for (signo = 0; signo < NSIG; signo++) {
11413 if (trap[signo] != NULL) {
11417 p = single_quote(trap[signo]);
11418 sn = sys_siglist[signo];
11420 sn = u_signal_names(0, &signo, 0);
11423 printf("trap -- %s %s\n", p, sn);
11435 if ((signo = decode_signal(*ap, 0)) < 0)
11436 error("%s: bad trap", *ap);
11439 if (action[0] == '-' && action[1] == '\0')
11442 action = xstrdup(action);
11445 trap[signo] = action;
11456 * Set the signal handler for the specified signal. The routine figures
11457 * out what it should be set to.
11460 static void setsignal(int signo)
11464 struct sigaction act;
11466 if ((t = trap[signo]) == NULL)
11468 else if (*t != '\0')
11472 if (rootshell && action == S_DFL) {
11475 if (iflag || minusc || sflag == 0)
11491 #ifdef CONFIG_ASH_JOB_CONTROL
11501 t = &sigmode[signo - 1];
11504 * current setting unknown
11506 if (sigaction(signo, 0, &act) == -1) {
11508 * Pretend it worked; maybe we should give a warning
11509 * here, but other shells don't. We don't alter
11510 * sigmode, so that we retry every time.
11514 if (act.sa_handler == SIG_IGN) {
11515 if (mflag && (signo == SIGTSTP ||
11516 signo == SIGTTIN || signo == SIGTTOU)) {
11517 *t = S_IGN; /* don't hard ignore these */
11521 *t = S_RESET; /* force to be set */
11524 if (*t == S_HARD_IGN || *t == action)
11526 act.sa_handler = ((action == S_CATCH) ? onsig
11527 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11530 sigemptyset(&act.sa_mask);
11531 sigaction(signo, &act, 0);
11538 static void ignoresig(int signo)
11540 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11541 signal(signo, SIG_IGN);
11543 sigmode[signo - 1] = S_HARD_IGN;
11551 static void onsig(int signo)
11553 if (signo == SIGINT && trap[SIGINT] == NULL) {
11557 gotsig[signo - 1] = 1;
11563 * Called to execute a trap. Perhaps we should avoid entering new trap
11564 * handlers while we are executing a trap handler.
11567 static void dotrap(void)
11573 for (i = 1;; i++) {
11580 savestatus = exitstatus;
11581 evalstring(trap[i], 0);
11582 exitstatus = savestatus;
11589 * Called to exit the shell.
11592 static void exitshell(int status)
11594 struct jmploc loc1, loc2;
11597 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11598 if (setjmp(loc1.loc)) {
11601 if (setjmp(loc2.loc)) {
11605 if ((p = trap[0]) != NULL && *p != '\0') {
11609 l1:handler = &loc2; /* probably unnecessary */
11611 #ifdef CONFIG_ASH_JOB_CONTROL
11618 static int decode_signal(const char *string, int minsig)
11621 const char *name = u_signal_names(string, &signo, minsig);
11623 return name ? signo : -1;
11626 static struct var **hashvar(const char *);
11627 static void showvars(const char *, int, int);
11628 static struct var **findvar(struct var **, const char *);
11631 * Initialize the varable symbol tables and import the environment
11635 * This routine initializes the builtin variables. It is called when the
11636 * shell is initialized and again when a shell procedure is spawned.
11639 static void initvar()
11641 const struct varinit *ip;
11645 for (ip = varinit; (vp = ip->var) != NULL; ip++) {
11646 if ((vp->flags & VEXPORT) == 0) {
11647 vpp = hashvar(ip->text);
11650 vp->text = xstrdup(ip->text);
11651 vp->flags = ip->flags;
11652 vp->func = ip->func;
11655 #if !defined(CONFIG_FEATURE_COMMAND_EDITING) || !defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
11657 * PS1 depends on uid
11659 if ((vps1.flags & VEXPORT) == 0) {
11660 vpp = hashvar("PS1=$ ");
11663 vps1.text = xstrdup(geteuid()? "PS1=$ " : "PS1=# ");
11664 vps1.flags = VSTRFIXED | VTEXTFIXED;
11670 * Set the value of a variable. The flags argument is ored with the
11671 * flags of the variable. If val is NULL, the variable is unset.
11674 static void setvar(const char *name, const char *val, int flags)
11689 if (!is_in_name(*p)) {
11690 if (*p == '\0' || *p == '=')
11696 namelen = p - name;
11698 error("%.*s: bad variable name", namelen, name);
11699 len = namelen + 2; /* 2 is space for '=' and '\0' */
11703 len += vallen = strlen(val);
11706 nameeq = xmalloc(len);
11707 memcpy(nameeq, name, namelen);
11708 nameeq[namelen] = '=';
11710 memcpy(nameeq + namelen + 1, val, vallen + 1);
11712 nameeq[namelen + 1] = '\0';
11714 setvareq(nameeq, flags);
11721 * Same as setvar except that the variable and value are passed in
11722 * the first argument as name=value. Since the first argument will
11723 * be actually stored in the table, it should not be a string that
11727 static void setvareq(char *s, int flags)
11729 struct var *vp, **vpp;
11732 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11733 if ((vp = *findvar(vpp, s))) {
11734 if (vp->flags & VREADONLY) {
11735 size_t len = strchr(s, '=') - s;
11737 error("%.*s: is read only", len, s);
11741 if (vp->func && (flags & VNOFUNC) == 0)
11742 (*vp->func) (strchr(s, '=') + 1);
11744 if ((vp->flags & (VTEXTFIXED | VSTACK)) == 0)
11747 vp->flags &= ~(VTEXTFIXED | VSTACK | VUNSET);
11748 vp->flags |= flags;
11751 #ifdef CONFIG_ASH_MAIL
11753 * We could roll this to a function, to handle it as
11754 * a regular variable function callback, but why bother?
11756 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
11763 vp = xmalloc(sizeof(*vp));
11774 * Process a linked list of variable assignments.
11777 static void listsetvar(struct strlist *mylist)
11779 struct strlist *lp;
11782 for (lp = mylist; lp; lp = lp->next) {
11783 setvareq(xstrdup(lp->text), 0);
11791 * Find the value of a variable. Returns NULL if not set.
11794 static const char *lookupvar(const char *name)
11798 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
11799 return strchr(v->text, '=') + 1;
11807 * Search the environment of a builtin command.
11810 static const char *bltinlookup(const char *name)
11812 const struct strlist *sp;
11814 for (sp = cmdenviron; sp; sp = sp->next) {
11815 if (varequal(sp->text, name))
11816 return strchr(sp->text, '=') + 1;
11818 return lookupvar(name);
11824 * Generate a list of exported variables. This routine is used to construct
11825 * the third argument to execve when executing a program.
11828 static char **environment()
11837 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
11838 for (vp = *vpp; vp; vp = vp->next)
11839 if (vp->flags & VEXPORT)
11842 ep = env = stalloc((nenv + 1) * sizeof *env);
11843 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
11844 for (vp = *vpp; vp; vp = vp->next)
11845 if (vp->flags & VEXPORT)
11854 * Command to list all variables which are set. Currently this command
11855 * is invoked from the set command when the set command is called without
11859 static int showvarscmd(int argc, char **argv)
11861 showvars(nullstr, VUNSET, VUNSET);
11868 * The export and readonly commands.
11871 static int exportcmd(int argc, char **argv)
11876 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
11879 listsetvar(cmdenviron);
11880 pflag = (nextopt("p") == 'p');
11881 if (argc > 1 && !pflag) {
11882 while ((name = *argptr++) != NULL) {
11883 if ((p = strchr(name, '=')) != NULL) {
11886 if ((vp = *findvar(hashvar(name), name))) {
11891 setvar(name, p, flag);
11895 showvars(argv[0], flag, 0);
11902 * The "local" command.
11905 /* funcnest nonzero if we are currently evaluating a function */
11907 static int localcmd(int argc, char **argv)
11912 error("Not in a function");
11913 while ((name = *argptr++) != NULL) {
11921 * Make a variable a local variable. When a variable is made local, it's
11922 * value and flags are saved in a localvar structure. The saved values
11923 * will be restored when the shell function returns. We handle the name
11924 * "-" as a special case.
11927 static void mklocal(char *name)
11929 struct localvar *lvp;
11934 lvp = xmalloc(sizeof(struct localvar));
11935 if (name[0] == '-' && name[1] == '\0') {
11938 p = xmalloc(sizeof optet_vals);
11939 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
11942 vpp = hashvar(name);
11943 vp = *findvar(vpp, name);
11945 if (strchr(name, '='))
11946 setvareq(xstrdup(name), VSTRFIXED);
11948 setvar(name, NULL, VSTRFIXED);
11949 vp = *vpp; /* the new variable */
11951 lvp->flags = VUNSET;
11953 lvp->text = vp->text;
11954 lvp->flags = vp->flags;
11955 vp->flags |= VSTRFIXED | VTEXTFIXED;
11956 if (strchr(name, '='))
11957 setvareq(xstrdup(name), 0);
11961 lvp->next = localvars;
11968 * Called after a function returns.
11971 static void poplocalvars()
11973 struct localvar *lvp;
11976 while ((lvp = localvars) != NULL) {
11977 localvars = lvp->next;
11979 if (vp == NULL) { /* $- saved */
11980 memcpy(optet_vals, lvp->text, sizeof optet_vals);
11982 } else if ((lvp->flags & (VUNSET | VSTRFIXED)) == VUNSET) {
11983 (void) unsetvar(vp->text);
11985 if ((vp->flags & VTEXTFIXED) == 0)
11987 vp->flags = lvp->flags;
11988 vp->text = lvp->text;
11995 static int setvarcmd(int argc, char **argv)
11998 return unsetcmd(argc, argv);
11999 else if (argc == 3)
12000 setvar(argv[1], argv[2], 0);
12002 error("List assignment not implemented");
12008 * The unset builtin command. We unset the function before we unset the
12009 * variable to allow a function to be unset when there is a readonly variable
12010 * with the same name.
12013 static int unsetcmd(int argc, char **argv)
12021 while ((i = nextopt("vf")) != '\0') {
12027 if (flg_func == 0 && flg_var == 0)
12030 for (ap = argptr; *ap; ap++) {
12034 ret |= unsetvar(*ap);
12041 * Unset the specified variable.
12044 static int unsetvar(const char *s)
12049 vpp = findvar(hashvar(s), s);
12052 if (vp->flags & VREADONLY)
12055 if (*(strchr(vp->text, '=') + 1) != '\0')
12056 setvar(s, nullstr, 0);
12057 vp->flags &= ~VEXPORT;
12058 vp->flags |= VUNSET;
12059 if ((vp->flags & VSTRFIXED) == 0) {
12060 if ((vp->flags & VTEXTFIXED) == 0)
12075 * Find the appropriate entry in the hash table from the name.
12078 static struct var **hashvar(const char *p)
12080 unsigned int hashval;
12082 hashval = ((unsigned char) *p) << 4;
12083 while (*p && *p != '=')
12084 hashval += (unsigned char) *p++;
12085 return &vartab[hashval % VTABSIZE];
12091 * Returns true if the two strings specify the same varable. The first
12092 * variable name is terminated by '='; the second may be terminated by
12093 * either '=' or '\0'.
12096 static int varequal(const char *p, const char *q)
12098 while (*p == *q++) {
12102 if (*p == '=' && *(q - 1) == '\0')
12107 static void showvars(const char *myprefix, int mask, int xor)
12111 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12113 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12114 for (vp = *vpp; vp; vp = vp->next) {
12115 if ((vp->flags & mask) ^ xor) {
12119 p = strchr(vp->text, '=') + 1;
12120 len = p - vp->text;
12121 p = single_quote(p);
12123 printf("%s%s%.*s%s\n", myprefix, sep, len, vp->text, p);
12130 static struct var **findvar(struct var **vpp, const char *name)
12132 for (; *vpp; vpp = &(*vpp)->next) {
12133 if (varequal((*vpp)->text, name)) {
12141 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12142 * This file contains code for the times builtin.
12144 static int timescmd(int argc, char **argv)
12147 long int clk_tck = sysconf(_SC_CLK_TCK);
12150 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12151 (int) (buf.tms_utime / clk_tck / 60),
12152 ((double) buf.tms_utime) / clk_tck,
12153 (int) (buf.tms_stime / clk_tck / 60),
12154 ((double) buf.tms_stime) / clk_tck,
12155 (int) (buf.tms_cutime / clk_tck / 60),
12156 ((double) buf.tms_cutime) / clk_tck,
12157 (int) (buf.tms_cstime / clk_tck / 60),
12158 ((double) buf.tms_cstime) / clk_tck);
12162 #ifdef CONFIG_ASH_MATH_SUPPORT
12163 /* The let builtin. */
12164 int letcmd(int argc, char **argv)
12170 char *tmp, *expression, p[13];
12172 expression = strchr(argv[1], '=');
12174 /* Cannot use 'error()' here, or the return code
12175 * will be incorrect */
12176 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12179 *expression = '\0';
12180 tmp = ++expression;
12181 result = arith(tmp, &errcode);
12183 /* Cannot use 'error()' here, or the return code
12184 * will be incorrect */
12185 out2fmt("sh: let: ");
12187 out2fmt("divide by zero");
12189 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12192 snprintf(p, 12, "%ld", result);
12193 setvar(argv[1], xstrdup(p), 0);
12194 } else if (argc >= 3)
12195 synerror("invalid operand");
12203 * Copyright (c) 1989, 1991, 1993, 1994
12204 * The Regents of the University of California. All rights reserved.
12206 * This code is derived from software contributed to Berkeley by
12207 * Kenneth Almquist.
12209 * Redistribution and use in source and binary forms, with or without
12210 * modification, are permitted provided that the following conditions
12212 * 1. Redistributions of source code must retain the above copyright
12213 * notice, this list of conditions and the following disclaimer.
12214 * 2. Redistributions in binary form must reproduce the above copyright
12215 * notice, this list of conditions and the following disclaimer in the
12216 * documentation and/or other materials provided with the distribution.
12218 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12219 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12221 * 4. Neither the name of the University nor the names of its contributors
12222 * may be used to endorse or promote products derived from this software
12223 * without specific prior written permission.
12225 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12226 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12227 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12228 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12229 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12230 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12231 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12232 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12233 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12234 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF