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 <andersen@codepoet.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;
1199 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1200 static struct var vhistfile;
1207 void (*func) (const char *);
1210 static const char defpathvar[] =
1211 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1212 #define defpath (defpathvar + 5)
1215 static const char defifsvar[] = "IFS= \t\n";
1217 #define defifs (defifsvar + 4)
1219 static const char defifs[] = " \t\n";
1222 static const struct varinit varinit[] = {
1224 {&vifs, VSTRFIXED | VTEXTFIXED, defifsvar,
1226 {&vifs, VSTRFIXED | VTEXTFIXED | VUNSET, "IFS=",
1229 {&vmail, VSTRFIXED | VTEXTFIXED | VUNSET, "MAIL=",
1231 {&vmpath, VSTRFIXED | VTEXTFIXED | VUNSET, "MAILPATH=",
1233 {&vpath, VSTRFIXED | VTEXTFIXED, defpathvar,
1235 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1236 {&vps1, VSTRFIXED | VTEXTFIXED, "PS1=\\w \\$ ",
1238 #endif /* else vps1 depends on uid */
1239 {&vps2, VSTRFIXED | VTEXTFIXED, "PS2=> ",
1241 {&voptind, VSTRFIXED | VTEXTFIXED, "OPTIND=1",
1243 #ifdef CONFIG_LOCALE_SUPPORT
1244 {&vlc_all, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=",
1246 {&vlc_ctype, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=",
1249 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1250 {&vhistfile, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE=",
1259 static struct var *vartab[VTABSIZE];
1262 * The following macros access the values of the above variables.
1263 * They have to skip over the name. They return the null string
1264 * for unset variables.
1267 #define ifsval() (vifs.text + 4)
1268 #define ifsset() ((vifs.flags & VUNSET) == 0)
1269 #define mailval() (vmail.text + 5)
1270 #define mpathval() (vmpath.text + 9)
1271 #define pathval() (vpath.text + 5)
1272 #define ps1val() (vps1.text + 4)
1273 #define ps2val() (vps2.text + 4)
1274 #define optindval() (voptind.text + 7)
1276 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1278 static void initvar(void);
1279 static void setvar(const char *, const char *, int);
1280 static void setvareq(char *, int);
1281 static void listsetvar(struct strlist *);
1282 static const char *lookupvar(const char *);
1283 static const char *bltinlookup(const char *);
1284 static char **environment(void);
1285 static int showvarscmd(int, char **);
1286 static void mklocal(char *);
1287 static void poplocalvars(void);
1288 static int unsetvar(const char *);
1289 static int varequal(const char *, const char *);
1292 static char *arg0; /* value of $0 */
1293 static struct shparam shellparam; /* current positional parameters */
1294 static char **argptr; /* argument list for builtin commands */
1295 static char *optionarg; /* set by nextopt (like getopt) */
1296 static char *optptr; /* used by nextopt */
1297 static char *minusc; /* argument to -c option */
1300 #ifdef CONFIG_ASH_ALIAS
1302 #define ALIASINUSE 1
1314 static struct alias *atab[ATABSIZE];
1316 static void setalias(char *, char *);
1317 static struct alias **hashalias(const char *);
1318 static struct alias *freealias(struct alias *);
1319 static struct alias **__lookupalias(const char *);
1321 static void setalias(char *name, char *val)
1323 struct alias *ap, **app;
1325 app = __lookupalias(name);
1329 if (!(ap->flag & ALIASINUSE)) {
1332 ap->val = bb_xstrdup(val);
1333 ap->flag &= ~ALIASDEAD;
1336 ap = xmalloc(sizeof(struct alias));
1337 ap->name = bb_xstrdup(name);
1338 ap->val = bb_xstrdup(val);
1346 static int unalias(char *name)
1350 app = __lookupalias(name);
1354 *app = freealias(*app);
1362 static void rmaliases(void)
1364 struct alias *ap, **app;
1368 for (i = 0; i < ATABSIZE; i++) {
1370 for (ap = *app; ap; ap = *app) {
1371 *app = freealias(*app);
1380 static void printalias(const struct alias *ap)
1384 p = single_quote(ap->val);
1385 printf("alias %s=%s\n", ap->name, p);
1391 * TODO - sort output
1393 static int aliascmd(int argc, char **argv)
1402 for (i = 0; i < ATABSIZE; i++)
1403 for (ap = atab[i]; ap; ap = ap->next) {
1408 while ((n = *++argv) != NULL) {
1409 if ((v = strchr(n + 1, '=')) == NULL) { /* n+1: funny ksh stuff */
1410 if ((ap = *__lookupalias(n)) == NULL) {
1411 out2fmt("%s: %s not found\n", "alias", n);
1424 static int unaliascmd(int argc, char **argv)
1428 while ((i = nextopt("a")) != '\0') {
1434 for (i = 0; *argptr; argptr++) {
1435 if (unalias(*argptr)) {
1436 out2fmt("%s: %s not found\n", "unalias", *argptr);
1444 static struct alias **hashalias(const char *p)
1446 unsigned int hashval;
1451 return &atab[hashval % ATABSIZE];
1454 static struct alias *freealias(struct alias *ap)
1458 if (ap->flag & ALIASINUSE) {
1459 ap->flag |= ALIASDEAD;
1471 static struct alias **__lookupalias(const char *name)
1473 struct alias **app = hashalias(name);
1475 for (; *app; app = &(*app)->next) {
1476 if (equal(name, (*app)->name)) {
1485 #ifdef CONFIG_ASH_MATH_SUPPORT
1486 /* The generated file arith.c has been replaced with a custom hand
1487 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1488 * This is now part of libbb, so that it can be used by all the shells
1490 static void expari(int);
1493 static char *trap[NSIG]; /* trap handler commands */
1494 static char sigmode[NSIG - 1]; /* current value of signal */
1495 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1496 static int pendingsigs; /* indicates some signal received */
1499 * This file was generated by the mkbuiltins program.
1502 #ifdef CONFIG_ASH_JOB_CONTROL
1503 static int bgcmd(int, char **);
1504 static int fgcmd(int, char **);
1505 static int killcmd(int, char **);
1507 static int bltincmd(int, char **);
1508 static int cdcmd(int, char **);
1509 static int breakcmd(int, char **);
1511 #ifdef CONFIG_ASH_CMDCMD
1512 static int commandcmd(int, char **);
1514 static int dotcmd(int, char **);
1515 static int evalcmd(int, char **);
1516 static int execcmd(int, char **);
1517 static int exitcmd(int, char **);
1518 static int exportcmd(int, char **);
1519 static int histcmd(int, char **);
1520 static int hashcmd(int, char **);
1521 static int helpcmd(int, char **);
1522 static int jobscmd(int, char **);
1523 static int localcmd(int, char **);
1524 static int pwdcmd(int, char **);
1525 static int readcmd(int, char **);
1526 static int returncmd(int, char **);
1527 static int setcmd(int, char **);
1528 static int setvarcmd(int, char **);
1529 static int shiftcmd(int, char **);
1530 static int trapcmd(int, char **);
1531 static int umaskcmd(int, char **);
1533 #ifdef CONFIG_ASH_ALIAS
1534 static int aliascmd(int, char **);
1535 static int unaliascmd(int, char **);
1537 static int unsetcmd(int, char **);
1538 static int waitcmd(int, char **);
1539 static int ulimitcmd(int, char **);
1540 static int timescmd(int, char **);
1542 #ifdef CONFIG_ASH_MATH_SUPPORT
1543 static int letcmd(int, char **);
1545 static int typecmd(int, char **);
1547 #ifdef CONFIG_ASH_GETOPTS
1548 static int getoptscmd(int, char **);
1552 static int true_main(int, char **);
1554 #ifndef CONFIG_FALSE
1555 static int false_main(int, char **);
1558 static void setpwd(const char *, int);
1561 #define BUILTIN_NOSPEC "0"
1562 #define BUILTIN_SPECIAL "1"
1563 #define BUILTIN_REGULAR "2"
1564 #define BUILTIN_ASSIGN "4"
1565 #define BUILTIN_SPEC_ASSG "5"
1566 #define BUILTIN_REG_ASSG "6"
1568 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1569 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1570 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1574 int (*const builtinfunc) (int, char **);
1579 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1580 * the binary search in find_builtin() will stop working. If you value
1581 * your kneecaps, you'll be sure to *make sure* that any changes made
1582 * to this array result in the listing remaining in ascii order. You
1585 static const struct builtincmd builtincmds[] = {
1586 {BUILTIN_SPECIAL ".", dotcmd}, /* first, see declare DOTCMD */
1587 {BUILTIN_SPECIAL ":", true_main},
1588 #ifdef CONFIG_ASH_ALIAS
1589 {BUILTIN_REG_ASSG "alias", aliascmd},
1591 #ifdef CONFIG_ASH_JOB_CONTROL
1592 {BUILTIN_REGULAR "bg", bgcmd},
1594 {BUILTIN_SPECIAL "break", breakcmd},
1595 {BUILTIN_SPECIAL "builtin", bltincmd},
1596 {BUILTIN_REGULAR "cd", cdcmd},
1597 {BUILTIN_NOSPEC "chdir", cdcmd},
1598 #ifdef CONFIG_ASH_CMDCMD
1599 {BUILTIN_REGULAR "command", commandcmd},
1601 {BUILTIN_SPECIAL "continue", breakcmd},
1602 {BUILTIN_SPECIAL "eval", evalcmd},
1603 {BUILTIN_SPECIAL "exec", execcmd},
1604 {BUILTIN_SPECIAL "exit", exitcmd},
1605 {BUILTIN_SPEC_ASSG "export", exportcmd},
1606 {BUILTIN_REGULAR "false", false_main},
1607 {BUILTIN_REGULAR "fc", histcmd},
1608 #ifdef CONFIG_ASH_JOB_CONTROL
1609 {BUILTIN_REGULAR "fg", fgcmd},
1611 #ifdef CONFIG_ASH_GETOPTS
1612 {BUILTIN_REGULAR "getopts", getoptscmd},
1614 {BUILTIN_NOSPEC "hash", hashcmd},
1615 {BUILTIN_NOSPEC "help", helpcmd},
1616 {BUILTIN_REGULAR "jobs", jobscmd},
1617 #ifdef CONFIG_ASH_JOB_CONTROL
1618 {BUILTIN_REGULAR "kill", killcmd},
1620 #ifdef CONFIG_ASH_MATH_SUPPORT
1621 {BUILTIN_REGULAR "let", letcmd},
1623 {BUILTIN_ASSIGN "local", localcmd},
1624 {BUILTIN_NOSPEC "pwd", pwdcmd},
1625 {BUILTIN_REGULAR "read", readcmd},
1626 {BUILTIN_SPEC_ASSG "readonly", exportcmd},
1627 {BUILTIN_SPECIAL "return", returncmd},
1628 {BUILTIN_SPECIAL "set", setcmd},
1629 {BUILTIN_NOSPEC "setvar", setvarcmd},
1630 {BUILTIN_SPECIAL "shift", shiftcmd},
1631 {BUILTIN_SPECIAL "times", timescmd},
1632 {BUILTIN_SPECIAL "trap", trapcmd},
1633 {BUILTIN_REGULAR "true", true_main},
1634 {BUILTIN_NOSPEC "type", typecmd},
1635 {BUILTIN_NOSPEC "ulimit", ulimitcmd},
1636 {BUILTIN_REGULAR "umask", umaskcmd},
1637 #ifdef CONFIG_ASH_ALIAS
1638 {BUILTIN_REGULAR "unalias", unaliascmd},
1640 {BUILTIN_SPECIAL "unset", unsetcmd},
1641 {BUILTIN_REGULAR "wait", waitcmd},
1644 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1646 #define DOTCMD &builtincmds[0]
1647 static struct builtincmd *BLTINCMD;
1648 static struct builtincmd *EXECCMD;
1649 static struct builtincmd *EVALCMD;
1652 #define JOBSTOPPED 1 /* all procs are stopped */
1653 #define JOBDONE 2 /* all procs are completed */
1656 * A job structure contains information about a job. A job is either a
1657 * single process or a set of processes contained in a pipeline. In the
1658 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1663 pid_t pid; /* process id */
1664 int status; /* status flags (defined above) */
1665 char *cmd; /* text of command being run */
1669 static int job_warning; /* user was warned about stopped jobs */
1671 #ifdef CONFIG_ASH_JOB_CONTROL
1672 static void setjobctl(int enable);
1674 #define setjobctl(on) /* do nothing */
1679 struct procstat ps0; /* status of process */
1680 struct procstat *ps; /* status or processes when more than one */
1681 short nprocs; /* number of processes */
1682 short pgrp; /* process group of this job */
1683 char state; /* true if job is finished */
1684 char used; /* true if this entry is in used */
1685 char changed; /* true if status has changed */
1686 #ifdef CONFIG_ASH_JOB_CONTROL
1687 char jobctl; /* job running under job control */
1691 static struct job *jobtab; /* array of jobs */
1692 static int njobs; /* size of array */
1693 static int backgndpid = -1; /* pid of last background process */
1695 #ifdef CONFIG_ASH_JOB_CONTROL
1696 static int initialpgrp; /* pgrp of shell on invocation */
1697 static int curjob; /* current job */
1701 static struct job *makejob(const union node *, int);
1702 static int forkshell(struct job *, const union node *, int);
1703 static int waitforjob(struct job *);
1705 static int docd(char *, int);
1706 static void getpwd(void);
1708 static char *padvance(const char **, const char *);
1710 static char nullstr[1]; /* zero length string */
1711 static char *curdir = nullstr; /* current working directory */
1713 static int cdcmd(int argc, char **argv)
1722 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1723 error("HOME not set");
1726 if (dest[0] == '-' && dest[1] == '\0') {
1727 dest = bltinlookup("OLDPWD");
1728 if (!dest || !*dest) {
1737 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1739 while ((p = padvance(&path, dest)) != NULL) {
1740 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1745 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1747 print = strcmp(p, dest);
1749 if (docd(p, print) >= 0)
1754 error("can't cd to %s", dest);
1760 * Update curdir (the name of the current directory) in response to a
1761 * cd command. We also call hashcd to let the routines in exec.c know
1762 * that the current directory has changed.
1765 static void hashcd(void);
1767 static inline void updatepwd(const char *dir)
1769 hashcd(); /* update command hash table */
1772 * If our argument is NULL, we don't know the current directory
1774 if (dir == NULL || curdir == nullstr) {
1782 * Actually do the chdir. In an interactive shell, print the
1783 * directory name if "print" is nonzero.
1786 static int docd(char *dest, int print)
1788 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1790 if (chdir(dest) < 0) {
1802 static int pwdcmd(int argc, char **argv)
1808 /* Ask system the current directory */
1809 static void getpwd(void)
1811 curdir = xgetcwd(0);
1816 static void setpwd(const char *val, int setold)
1821 setvar("OLDPWD", curdir, VEXPORT);
1824 if (curdir != nullstr) {
1825 if (val != NULL && *val != '/')
1826 val = cated = concat_path_file(curdir, val);
1832 curdir = bb_simplify_path(val);
1836 setvar("PWD", curdir, VEXPORT);
1840 * Errors and exceptions.
1844 * Code to handle exceptions in C.
1848 * We enclose jmp_buf in a structure so that we can declare pointers to
1849 * jump locations. The global variable handler contains the location to
1850 * jump to when an exception occurs, and the global variable exception
1851 * contains a code identifying the exeception. To implement nested
1852 * exception handlers, the user should save the value of handler on entry
1853 * to an inner scope, set handler to point to a jmploc structure for the
1854 * inner scope, and restore handler on exit from the scope.
1862 #define EXINT 0 /* SIGINT received */
1863 #define EXERROR 1 /* a generic error */
1864 #define EXSHELLPROC 2 /* execute a shell procedure */
1865 #define EXEXEC 3 /* command execution failed */
1866 #define EXREDIR 4 /* redirection error */
1868 static struct jmploc *handler;
1869 static int exception;
1871 static void exverror(int, const char *, va_list)
1872 __attribute__ ((__noreturn__));
1875 * Called to raise an exception. Since C doesn't include exceptions, we
1876 * just do a longjmp to the exception handler. The type of exception is
1877 * stored in the global variable "exception".
1880 static void exraise(int) __attribute__ ((__noreturn__));
1882 static void exraise(int e)
1885 if (handler == NULL)
1890 longjmp(handler->loc, 1);
1895 * Called from trap.c when a SIGINT is received. (If the user specifies
1896 * that SIGINT is to be trapped or ignored using the trap builtin, then
1897 * this routine is not called.) Suppressint is nonzero when interrupts
1898 * are held using the INTOFF macro. The call to _exit is necessary because
1899 * there is a short period after a fork before the signal handlers are
1900 * set to the appropriate value for the child. (The test for iflag is
1901 * just defensive programming.)
1904 static void onint(void)
1913 sigemptyset(&mysigset);
1914 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1915 if (!(rootshell && iflag)) {
1916 signal(SIGINT, SIG_DFL);
1924 static char *commandname; /* currently executing command */
1927 * Exverror is called to raise the error exception. If the first argument
1928 * is not NULL then error prints an error message using printf style
1929 * formatting. It then raises the error exception.
1931 static void exverror(int cond, const char *msg, va_list ap)
1938 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1940 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1944 out2fmt("%s: ", commandname);
1945 vfprintf(stderr, msg, ap);
1953 static void error(const char *msg, ...)
1958 exverror(EXERROR, msg, ap);
1964 static void exerror(int cond, const char *msg, ...)
1969 exverror(cond, msg, ap);
1977 * Table of error messages.
1981 short errcode; /* error number */
1982 short action; /* operation which encountered the error */
1986 * Types of operations (passed to the errmsg routine).
1989 #define E_OPEN 01 /* opening a file */
1990 #define E_CREAT 02 /* creating a file */
1991 #define E_EXEC 04 /* executing a program */
1993 #define ALL (E_OPEN|E_CREAT|E_EXEC)
1995 static const struct errname errormsg[] = {
2049 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2052 * Return a string describing an error. The returned string may be a
2053 * pointer to a static buffer that will be overwritten on the next call.
2054 * Action describes the operation that got the error.
2057 static const char *errmsg(int e, int action)
2059 struct errname const *ep;
2060 static char buf[12];
2062 for (ep = errormsg; ep < errormsg + ERRNAME_SIZE; ep++) {
2063 if (ep->errcode == e && (ep->action & action) != 0)
2067 snprintf(buf, sizeof buf, "error %d", e);
2072 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
2073 static void __inton()
2075 if (--suppressint == 0 && intpending) {
2079 static void forceinton(void)
2087 /* flags in argument to evaltree */
2088 #define EV_EXIT 01 /* exit after evaluating tree */
2089 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2090 #define EV_BACKCMD 04 /* command executing within back quotes */
2092 static int evalskip; /* set if we are skipping commands */
2093 static int skipcount; /* number of levels to skip */
2094 static int loopnest; /* current loop nesting level */
2095 static int funcnest; /* depth of function calls */
2098 static struct strlist *cmdenviron; /* environment for builtin command */
2099 static int exitstatus; /* exit status of last command */
2100 static int oexitstatus; /* saved exit status */
2102 static void evalsubshell(const union node *, int);
2103 static void expredir(union node *);
2104 static void prehash(union node *);
2105 static void eprintlist(struct strlist *);
2107 static union node *parsecmd(int);
2110 * Called to reset things after an exception.
2114 * The eval commmand.
2116 static void evalstring(char *, int);
2118 static int evalcmd(int argc, char **argv)
2127 STARTSTACKSTR(concat);
2131 STPUTC(*p++, concat);
2132 if ((p = *ap++) == NULL)
2134 STPUTC(' ', concat);
2136 STPUTC('\0', concat);
2137 p = grabstackstr(concat);
2139 evalstring(p, EV_TESTED);
2145 * Execute a command or commands contained in a string.
2148 static void evaltree(union node *, int);
2149 static void setinputstring(char *);
2150 static void popfile(void);
2151 static void setstackmark(struct stackmark *mark);
2152 static void popstackmark(struct stackmark *mark);
2155 static void evalstring(char *s, int flag)
2158 struct stackmark smark;
2160 setstackmark(&smark);
2162 while ((n = parsecmd(0)) != NEOF) {
2164 popstackmark(&smark);
2167 popstackmark(&smark);
2170 static struct builtincmd *find_builtin(const char *);
2171 static void expandarg(union node *, struct arglist *, int);
2172 static void calcsize(const union node *);
2173 static union node *copynode(const union node *);
2176 * Make a copy of a parse tree.
2179 static int funcblocksize; /* size of structures in function */
2180 static int funcstringsize; /* size of strings in node */
2181 static pointer funcblock; /* block to allocate function from */
2182 static char *funcstring; /* block to allocate strings from */
2185 static inline union node *copyfunc(union node *n)
2192 funcblock = xmalloc(funcblocksize + funcstringsize);
2193 funcstring = (char *) funcblock + funcblocksize;
2198 * Add a new command entry, replacing any existing command entry for
2202 static inline void addcmdentry(char *name, struct cmdentry *entry)
2204 struct tblentry *cmdp;
2207 cmdp = cmdlookup(name, 1);
2208 if (cmdp->cmdtype == CMDFUNCTION) {
2209 free(cmdp->param.func);
2211 cmdp->cmdtype = entry->cmdtype;
2212 cmdp->param = entry->u;
2216 static inline void evalloop(const union node *n, int flags)
2224 evaltree(n->nbinary.ch1, EV_TESTED);
2226 skipping:if (evalskip == SKIPCONT && --skipcount <= 0) {
2230 if (evalskip == SKIPBREAK && --skipcount <= 0)
2234 if (n->type == NWHILE) {
2235 if (exitstatus != 0)
2238 if (exitstatus == 0)
2241 evaltree(n->nbinary.ch2, flags);
2242 status = exitstatus;
2247 exitstatus = status;
2250 static void evalfor(const union node *n, int flags)
2252 struct arglist arglist;
2255 struct stackmark smark;
2257 setstackmark(&smark);
2258 arglist.lastp = &arglist.list;
2259 for (argp = n->nfor.args; argp; argp = argp->narg.next) {
2260 oexitstatus = exitstatus;
2261 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2265 *arglist.lastp = NULL;
2270 for (sp = arglist.list; sp; sp = sp->next) {
2271 setvar(n->nfor.var, sp->text, 0);
2272 evaltree(n->nfor.body, flags);
2274 if (evalskip == SKIPCONT && --skipcount <= 0) {
2278 if (evalskip == SKIPBREAK && --skipcount <= 0)
2285 popstackmark(&smark);
2288 static inline void evalcase(const union node *n, int flags)
2292 struct arglist arglist;
2293 struct stackmark smark;
2295 setstackmark(&smark);
2296 arglist.lastp = &arglist.list;
2297 oexitstatus = exitstatus;
2298 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2299 for (cp = n->ncase.cases; cp && evalskip == 0; cp = cp->nclist.next) {
2300 for (patp = cp->nclist.pattern; patp; patp = patp->narg.next) {
2301 if (casematch(patp, arglist.list->text)) {
2302 if (evalskip == 0) {
2303 evaltree(cp->nclist.body, flags);
2310 popstackmark(&smark);
2314 * Evaluate a pipeline. All the processes in the pipeline are children
2315 * of the process creating the pipeline. (This differs from some versions
2316 * of the shell, which make the last process in a pipeline the parent
2320 static inline void evalpipe(union node *n, int flags)
2323 struct nodelist *lp;
2328 TRACE(("evalpipe(0x%lx) called\n", (long) n));
2330 for (lp = n->npipe.cmdlist; lp; lp = lp->next)
2334 jp = makejob(n, pipelen);
2336 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
2340 if (pipe(pip) < 0) {
2342 error("Pipe call failed");
2345 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2358 evaltree(lp->n, flags);
2365 if (n->npipe.backgnd == 0) {
2366 exitstatus = waitforjob(jp);
2367 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2372 static void find_command(const char *, struct cmdentry *, int, const char *);
2374 static int isassignment(const char *word)
2376 if (!is_name(*word)) {
2381 } while (is_in_name(*word));
2382 return *word == '=';
2386 static void evalcommand(union node *cmd, int flags)
2388 struct stackmark smark;
2390 struct arglist arglist;
2391 struct arglist varlist;
2397 struct cmdentry cmdentry;
2399 char *volatile savecmdname;
2400 volatile struct shparam saveparam;
2401 struct localvar *volatile savelocalvars;
2406 struct jmploc *volatile savehandler;
2407 struct jmploc jmploc;
2410 /* Avoid longjmp clobbering */
2418 /* First expand the arguments. */
2419 TRACE(("evalcommand(0x%lx, %d) called\n", (long) cmd, flags));
2420 setstackmark(&smark);
2421 arglist.lastp = &arglist.list;
2422 varlist.lastp = &varlist.list;
2424 oexitstatus = exitstatus;
2427 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2428 expandarg(argp, &varlist, EXP_VARTILDE);
2430 for (argp = cmd->ncmd.args; argp && !arglist.list; argp = argp->narg.next) {
2431 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2434 struct builtincmd *bcmd;
2437 bcmd = find_builtin(arglist.list->text);
2438 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2439 for (; argp; argp = argp->narg.next) {
2440 if (pseudovarflag && isassignment(argp->narg.text)) {
2441 expandarg(argp, &arglist, EXP_VARTILDE);
2444 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2447 *arglist.lastp = NULL;
2448 *varlist.lastp = NULL;
2449 expredir(cmd->ncmd.redirect);
2451 for (sp = arglist.list; sp; sp = sp->next)
2453 argv = stalloc(sizeof(char *) * (argc + 1));
2455 for (sp = arglist.list; sp; sp = sp->next) {
2456 TRACE(("evalcommand arg: %s\n", sp->text));
2461 if (iflag && funcnest == 0 && argc > 0)
2465 /* Print the command if xflag is set. */
2468 eprintlist(varlist.list);
2469 eprintlist(arglist.list);
2473 /* Now locate the command. */
2475 cmdentry.cmdtype = CMDBUILTIN;
2476 cmdentry.u.cmd = BLTINCMD;
2479 const char *oldpath;
2480 int findflag = DO_ERR;
2484 * Modify the command lookup path, if a PATH= assignment
2487 for (sp = varlist.list; sp; sp = sp->next)
2488 if (varequal(sp->text, defpathvar)) {
2489 path = sp->text + 5;
2490 findflag |= DO_BRUTE;
2493 oldfindflag = findflag;
2496 find_command(argv[0], &cmdentry, findflag, path);
2497 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2501 /* implement bltin and command here */
2502 if (cmdentry.cmdtype != CMDBUILTIN) {
2505 if (spclbltin < 0) {
2506 spclbltin = !!(IS_BUILTIN_SPECIAL(cmdentry.u.cmd)) * 2;
2508 if (cmdentry.u.cmd == BLTINCMD) {
2510 struct builtincmd *bcmd;
2515 if (!(bcmd = find_builtin(*argv))) {
2516 out2fmt("%s: not found\n", *argv);
2520 cmdentry.u.cmd = bcmd;
2521 if (bcmd != BLTINCMD)
2525 if (cmdentry.u.cmd == find_builtin("command")) {
2530 if (*argv[0] == '-') {
2531 if (!equal(argv[0], "-p")) {
2541 findflag |= DO_BRUTE;
2544 findflag = oldfindflag;
2546 findflag |= DO_NOFUN;
2554 /* Fork off a child process if necessary. */
2555 if (cmd->ncmd.backgnd
2556 || (cmdentry.cmdtype == CMDNORMAL && (!(flags & EV_EXIT) || trap[0]))
2559 jp = makejob(cmd, 1);
2560 mode = cmd->ncmd.backgnd;
2561 if (forkshell(jp, cmd, mode) != 0)
2562 goto parent; /* at end of routine */
2569 /* This is the child process if a fork occurred. */
2570 /* Execute the command. */
2571 if (cmdentry.cmdtype == CMDFUNCTION) {
2573 trputs("Shell function: ");
2576 exitstatus = oexitstatus;
2577 saveparam = shellparam;
2578 shellparam.malloc = 0;
2579 shellparam.nparam = argc - 1;
2580 shellparam.p = argv + 1;
2582 savelocalvars = localvars;
2585 if (setjmp(jmploc.loc)) {
2586 if (exception == EXREDIR) {
2590 saveparam.optind = shellparam.optind;
2591 saveparam.optoff = shellparam.optoff;
2592 freeparam(&shellparam);
2593 shellparam = saveparam;
2595 localvars = savelocalvars;
2596 handler = savehandler;
2597 longjmp(handler->loc, 1);
2599 savehandler = handler;
2601 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2602 listsetvar(varlist.list);
2604 evaltree(cmdentry.u.func, flags & EV_TESTED);
2609 localvars = savelocalvars;
2610 saveparam.optind = shellparam.optind;
2611 saveparam.optoff = shellparam.optoff;
2612 freeparam(&shellparam);
2613 shellparam = saveparam;
2614 handler = savehandler;
2617 if (evalskip == SKIPFUNC) {
2621 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2625 trputs("builtin command: ");
2628 redir = (cmdentry.u.cmd == EXECCMD) ? 0 : REDIR_PUSH;
2629 savecmdname = commandname;
2631 listsetvar(varlist.list);
2633 cmdenviron = varlist.list;
2636 if (setjmp(jmploc.loc)) {
2638 exitstatus = (e == EXINT) ? SIGINT + 128 : 2;
2641 savehandler = handler;
2643 redirect(cmd->ncmd.redirect, redir);
2644 commandname = argv[0];
2646 optptr = NULL; /* initialize nextopt */
2647 exitstatus = (*cmdentry.u.cmd->builtinfunc) (argc, argv);
2651 commandname = savecmdname;
2652 handler = savehandler;
2654 if (e == EXINT || spclbltin & 2) {
2660 if (cmdentry.u.cmd != EXECCMD)
2664 trputs("normal command: ");
2667 redirect(cmd->ncmd.redirect, 0);
2669 for (sp = varlist.list; sp; sp = sp->next)
2670 setvareq(sp->text, VEXPORT | VSTACK);
2671 envp = environment();
2672 shellexec(argv, envp, path, cmdentry.u.index);
2674 if (flags & EV_EXIT)
2675 exitshell(exitstatus);
2678 parent: /* parent process gets here (if we forked) */
2679 if (mode == 0) { /* argument to fork */
2680 exitstatus = waitforjob(jp);
2686 setvar("_", lastarg, 0);
2687 popstackmark(&smark);
2691 * Evaluate a parse tree. The value is left in the global variable
2694 static void evaltree(union node *n, int flags)
2699 TRACE(("evaltree(NULL) called\n"));
2702 TRACE(("evaltree(0x%lx: %d) called\n", (long) n, n->type));
2705 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2708 evaltree(n->nbinary.ch2, flags);
2711 evaltree(n->nbinary.ch1, EV_TESTED);
2712 if (evalskip || exitstatus != 0)
2714 evaltree(n->nbinary.ch2, flags);
2717 evaltree(n->nbinary.ch1, EV_TESTED);
2718 if (evalskip || exitstatus == 0)
2720 evaltree(n->nbinary.ch2, flags);
2723 expredir(n->nredir.redirect);
2724 redirect(n->nredir.redirect, REDIR_PUSH);
2725 evaltree(n->nredir.n, flags);
2729 evalsubshell(n, flags);
2732 evalsubshell(n, flags);
2735 evaltree(n->nif.test, EV_TESTED);
2738 if (exitstatus == 0)
2739 evaltree(n->nif.ifpart, flags);
2740 else if (n->nif.elsepart)
2741 evaltree(n->nif.elsepart, flags);
2757 struct builtincmd *bcmd;
2758 struct cmdentry entry;
2760 if ((bcmd = find_builtin(n->narg.text)) && IS_BUILTIN_SPECIAL(bcmd)
2762 out2fmt("%s is a special built-in\n", n->narg.text);
2766 entry.cmdtype = CMDFUNCTION;
2767 entry.u.func = copyfunc(n->narg.next);
2768 addcmdentry(n->narg.text, &entry);
2773 evaltree(n->nnot.com, EV_TESTED);
2774 exitstatus = !exitstatus;
2782 evalcommand(n, flags);
2787 printf("Node type = %d\n", n->type);
2794 if (flags & EV_EXIT ||
2795 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2797 exitshell(exitstatus);
2801 * Kick off a subshell to evaluate a tree.
2804 static void evalsubshell(const union node *n, int flags)
2807 int backgnd = (n->type == NBACKGND);
2809 expredir(n->nredir.redirect);
2810 if (!backgnd && flags & EV_EXIT && !trap[0])
2814 if (forkshell(jp, n, backgnd) == 0) {
2818 flags &= ~EV_TESTED;
2820 redirect(n->nredir.redirect, 0);
2821 evaltree(n->nredir.n, flags); /* never returns */
2824 exitstatus = waitforjob(jp);
2830 * Compute the names of the files in a redirection list.
2833 static void fixredir(union node *n, const char *text, int err);
2835 static void expredir(union node *n)
2839 for (redir = n; redir; redir = redir->nfile.next) {
2842 fn.lastp = &fn.list;
2843 oexitstatus = exitstatus;
2844 switch (redir->type) {
2850 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2851 redir->nfile.expfname = fn.list->text;
2855 if (redir->ndup.vname) {
2856 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2857 fixredir(redir, fn.list->text, 1);
2866 * Execute a command inside back quotes. If it's a builtin command, we
2867 * want to save its output in a block obtained from malloc. Otherwise
2868 * we fork off a subprocess and get the output of the command via a pipe.
2869 * Should be called with interrupts off.
2872 static void evalbackcmd(union node *n, struct backcmd *result)
2876 struct stackmark smark; /* unnecessary */
2878 setstackmark(&smark);
2889 error("Pipe call failed");
2891 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2896 dup_as_newfd(pip[1], 1);
2900 evaltree(n, EV_EXIT);
2903 result->fd = pip[0];
2906 popstackmark(&smark);
2907 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2908 result->fd, result->buf, result->nleft, result->jp));
2913 * Execute a simple command.
2917 * Search for a command. This is called before we fork so that the
2918 * location of the command will be available in the parent as well as
2919 * the child. The check for "goodname" is an overly conservative
2920 * check that the name will not be subject to expansion.
2923 static void prehash(union node *n)
2925 struct cmdentry entry;
2927 if (n->type == NCMD && n->ncmd.args)
2928 if (goodname(n->ncmd.args->narg.text))
2929 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
2934 * Builtin commands. Builtin commands whose functions are closely
2935 * tied to evaluation are implemented here.
2939 * No command given, or a bltin command with no arguments. Set the
2940 * specified variables.
2943 int bltincmd(int argc, char **argv)
2946 * Preserve exitstatus of a previous possible redirection
2954 * Handle break and continue commands. Break, continue, and return are
2955 * all handled by setting the evalskip flag. The evaluation routines
2956 * above all check this flag, and if it is set they start skipping
2957 * commands rather than executing them. The variable skipcount is
2958 * the number of loops to break/continue, or the number of function
2959 * levels to return. (The latter is always 1.) It should probably
2960 * be an error to break out of more loops than exist, but it isn't
2961 * in the standard shell so we don't make it one here.
2964 static int breakcmd(int argc, char **argv)
2966 int n = argc > 1 ? number(argv[1]) : 1;
2969 error("Illegal number: %s", argv[1]);
2973 evalskip = (**argv == 'c') ? SKIPCONT : SKIPBREAK;
2981 * The return command.
2984 static int returncmd(int argc, char **argv)
2986 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
2989 evalskip = SKIPFUNC;
2993 /* Do what ksh does; skip the rest of the file */
2994 evalskip = SKIPFILE;
3001 #ifndef CONFIG_FALSE
3002 static int false_main(int argc, char **argv)
3009 static int true_main(int argc, char **argv)
3016 * Controls whether the shell is interactive or not.
3019 static void setsignal(int signo);
3021 #ifdef CONFIG_ASH_MAIL
3022 static void chkmail(int silent);
3025 static void setinteractive(int on)
3027 static int is_interactive;
3028 static int do_banner = 0;
3030 if (on == is_interactive)
3035 #ifdef CONFIG_ASH_MAIL
3038 is_interactive = on;
3039 if (do_banner == 0 && is_interactive) {
3040 /* Looks like they want an interactive shell */
3041 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3042 printf("\n\n" BB_BANNER " Built-in shell (ash)\n");
3043 printf("Enter 'help' for a list of built-in commands.\n\n");
3049 static void optschanged(void)
3051 setinteractive(iflag);
3056 static int execcmd(int argc, char **argv)
3061 iflag = 0; /* exit on error */
3064 for (sp = cmdenviron; sp; sp = sp->next)
3065 setvareq(sp->text, VEXPORT | VSTACK);
3066 shellexec(argv + 1, environment(), pathval(), 0);
3071 static void eprintlist(struct strlist *sp)
3073 for (; sp; sp = sp->next) {
3074 out2fmt(" %s", sp->text);
3079 * Exec a program. Never returns. If you change this routine, you may
3080 * have to change the find_command routine as well.
3083 static const char *pathopt; /* set by padvance */
3085 static void shellexec(char **argv, char **envp, const char *path, int idx)
3090 if (strchr(argv[0], '/') != NULL
3091 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3092 || find_applet_by_name(argv[0])
3096 tryexec(argv[0], argv, envp);
3100 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3101 if (--idx < 0 && pathopt == NULL) {
3102 tryexec(cmdname, argv, envp);
3103 if (errno != ENOENT && errno != ENOTDIR)
3110 /* Map to POSIX errors */
3122 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3127 * Clear traps on a fork.
3129 static void clear_traps(void)
3133 for (tp = trap; tp < &trap[NSIG]; tp++) {
3134 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3139 setsignal(tp - trap);
3146 static int preadbuffer(void);
3147 static void pushfile(void);
3150 * Read a character from the script, returning PEOF on end of file.
3151 * Nul characters in the input are silently discarded.
3154 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
3155 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3156 static int pgetc(void)
3158 return pgetc_macro();
3161 static int pgetc_macro(void)
3163 return --parsenleft >= 0 ? *parsenextc++ : preadbuffer();
3166 static inline int pgetc(void)
3168 return pgetc_macro();
3174 * Undo the last call to pgetc. Only one character may be pushed back.
3175 * PEOF may be pushed back.
3178 static void pungetc(void)
3185 static void popfile(void)
3187 struct parsefile *pf = parsefile;
3195 parsefile = pf->prev;
3197 parsenleft = parsefile->nleft;
3198 parselleft = parsefile->lleft;
3199 parsenextc = parsefile->nextc;
3200 plinno = parsefile->linno;
3206 * Return to top level.
3209 static void popallfiles(void)
3211 while (parsefile != &basepf)
3216 * Close the file(s) that the shell is reading commands from. Called
3217 * after a fork is done.
3220 static void closescript(void)
3223 if (parsefile->fd > 0) {
3224 close(parsefile->fd);
3231 * Like setinputfile, but takes an open file descriptor. Call this with
3235 static void setinputfd(int fd, int push)
3237 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3243 while (parsefile->strpush)
3247 if (parsefile->buf == NULL)
3248 parsefile->buf = xmalloc(BUFSIZ);
3249 parselleft = parsenleft = 0;
3255 * Set the input to take input from a file. If push is set, push the
3256 * old input onto the stack first.
3259 static void setinputfile(const char *fname, int push)
3265 if ((fd = open(fname, O_RDONLY)) < 0)
3266 error("Can't open %s", fname);
3268 myfileno2 = dup_as_newfd(fd, 10);
3271 error("Out of file descriptors");
3274 setinputfd(fd, push);
3279 static void tryexec(char *cmd, char **argv, char **envp)
3283 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3287 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3288 name = bb_get_last_path_component(name);
3289 if(find_applet_by_name(name) != NULL)
3292 if(strchr(name, '/') == NULL && find_applet_by_name(name) != NULL) {
3301 if(strcmp(name, "busybox")) {
3302 for (ap = argv; *ap; ap++);
3303 ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
3304 *ap++ = cmd = "/bin/busybox";
3305 while ((*ap++ = *argv++));
3309 cmd = "/bin/busybox";
3314 execve(cmd, argv, envp);
3317 } else if (errno == ENOEXEC) {
3321 for (ap = argv; *ap; ap++);
3322 ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
3323 *ap++ = cmd = "/bin/sh";
3324 while ((*ap++ = *argv++));
3330 static char *commandtext(const union node *);
3333 * Do a path search. The variable path (passed by reference) should be
3334 * set to the start of the path before the first call; padvance will update
3335 * this value as it proceeds. Successive calls to padvance will return
3336 * the possible path expansions in sequence. If an option (indicated by
3337 * a percent sign) appears in the path entry then the global variable
3338 * pathopt will be set to point to it; otherwise pathopt will be set to
3342 static const char *pathopt;
3344 static void growstackblock(void);
3347 static char *padvance(const char **path, const char *name)
3357 for (p = start; *p && *p != ':' && *p != '%'; p++);
3358 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3359 while (stackblocksize() < len)
3363 memcpy(q, start, p - start);
3371 while (*p && *p != ':')
3378 return stalloc(len);
3382 * Wrapper around strcmp for qsort/bsearch/...
3384 static int pstrcmp(const void *a, const void *b)
3386 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3390 * Find a keyword is in a sorted array.
3393 static const char *const *findkwd(const char *s)
3395 return bsearch(s, tokname_array + KWDOFFSET,
3396 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
3397 sizeof(const char *), pstrcmp);
3401 /*** Command hashing code ***/
3403 static int hashcmd(int argc, char **argv)
3405 struct tblentry **pp;
3406 struct tblentry *cmdp;
3409 struct cmdentry entry;
3412 #ifdef CONFIG_ASH_ALIAS
3413 const struct alias *ap;
3417 while ((c = nextopt("rvV")) != '\0') {
3421 } else if (c == 'v' || c == 'V') {
3425 if (*argptr == NULL) {
3426 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3427 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3428 if (cmdp->cmdtype != CMDBUILTIN) {
3429 printentry(cmdp, verbose);
3436 while ((name = *argptr++) != NULL) {
3437 if ((cmdp = cmdlookup(name, 0)) != NULL
3438 && (cmdp->cmdtype == CMDNORMAL
3439 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3441 #ifdef CONFIG_ASH_ALIAS
3442 /* Then look at the aliases */
3443 if ((ap = *__lookupalias(name)) != NULL) {
3445 printf("%s is an alias for %s\n", name, ap->val);
3451 /* First look at the keywords */
3452 if (findkwd(name) != 0) {
3454 printf("%s is a shell keyword\n", name);
3460 find_command(name, &entry, DO_ERR, pathval());
3461 if (entry.cmdtype == CMDUNKNOWN)
3464 cmdp = cmdlookup(name, 0);
3466 printentry(cmdp, verbose == 'v');
3473 static void printentry(struct tblentry *cmdp, int verbose)
3479 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3480 if (cmdp->cmdtype == CMDNORMAL) {
3481 idx = cmdp->param.index;
3484 name = padvance(&path, cmdp->cmdname);
3486 } while (--idx >= 0);
3489 } else if (cmdp->cmdtype == CMDBUILTIN) {
3491 out1str("a shell builtin");
3492 } else if (cmdp->cmdtype == CMDFUNCTION) {
3495 out1str("a function\n");
3496 name = commandtext(cmdp->param.func);
3497 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3503 error("internal error: cmdtype %d", cmdp->cmdtype);
3506 puts(cmdp->rehash ? "*" : nullstr);
3511 /*** List the available builtins ***/
3514 static int helpcmd(int argc, char **argv)
3518 printf("\nBuilt-in commands:\n-------------------\n");
3519 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
3520 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3521 builtincmds[i].name + 1);
3527 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3529 extern const struct BB_applet applets[];
3530 extern const size_t NUM_APPLETS;
3532 for (i = 0; i < NUM_APPLETS; i++) {
3534 col += printf("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
3543 return EXIT_SUCCESS;
3547 * Resolve a command name. If you change this routine, you may have to
3548 * change the shellexec routine as well.
3551 static int prefix(const char *, const char *);
3554 find_command(const char *name, struct cmdentry *entry, int act,
3557 struct tblentry *cmdp;
3567 struct builtincmd *bcmd;
3569 /* If name contains a slash, don't use the hash table */
3570 if (strchr(name, '/') != NULL) {
3572 while (stat(name, &statb) < 0) {
3573 if (errno != ENOENT && errno != ENOTDIR)
3575 entry->cmdtype = CMDUNKNOWN;
3576 entry->u.index = -1;
3579 entry->cmdtype = CMDNORMAL;
3580 entry->u.index = -1;
3583 entry->cmdtype = CMDNORMAL;
3588 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3589 if (find_applet_by_name(name)) {
3590 entry->cmdtype = CMDNORMAL;
3591 entry->u.index = -1;
3597 if (act & DO_BRUTE) {
3598 firstchange = path_change(path, &bltin);
3604 /* If name is in the table, and not invalidated by cd, we're done */
3605 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3606 if (cmdp->cmdtype == CMDFUNCTION) {
3607 if (act & DO_NOFUN) {
3612 } else if (act & DO_BRUTE) {
3613 if ((cmdp->cmdtype == CMDNORMAL &&
3614 cmdp->param.index >= firstchange) ||
3615 (cmdp->cmdtype == CMDBUILTIN &&
3616 ((builtinloc < 0 && bltin >= 0) ?
3617 bltin : builtinloc) >= firstchange)) {
3618 /* need to recompute the entry */
3627 bcmd = find_builtin(name);
3628 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3631 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3634 } else if (act & DO_BRUTE) {
3635 if (firstchange == 0) {
3640 /* If %builtin not in path, check for builtin next */
3641 if (regular || (bltin < 0 && bcmd)) {
3644 entry->cmdtype = CMDBUILTIN;
3645 entry->u.cmd = bcmd;
3649 cmdp = cmdlookup(name, 1);
3650 cmdp->cmdtype = CMDBUILTIN;
3651 cmdp->param.cmd = bcmd;
3656 /* We have to search path. */
3657 prev = -1; /* where to start */
3658 if (cmdp && cmdp->rehash) { /* doing a rehash */
3659 if (cmdp->cmdtype == CMDBUILTIN)
3662 prev = cmdp->param.index;
3668 while ((fullname = padvance(&path, name)) != NULL) {
3669 stunalloc(fullname);
3671 if (idx >= firstchange) {
3675 if (prefix("builtin", pathopt)) {
3676 if ((bcmd = find_builtin(name))) {
3680 } else if (!(act & DO_NOFUN) && prefix("func", pathopt)) {
3683 continue; /* ignore unimplemented options */
3686 /* if rehash, don't redo absolute path names */
3687 if (fullname[0] == '/' && idx <= prev && idx < firstchange) {
3690 TRACE(("searchexec \"%s\": no change\n", name));
3693 while (stat(fullname, &statb) < 0) {
3694 if (errno != ENOENT && errno != ENOTDIR)
3698 e = EACCES; /* if we fail, this will be the error */
3699 if (!S_ISREG(statb.st_mode))
3701 if (pathopt) { /* this is a %func directory */
3702 stalloc(strlen(fullname) + 1);
3703 readcmdfile(fullname);
3704 if ((cmdp = cmdlookup(name, 0)) == NULL
3705 || cmdp->cmdtype != CMDFUNCTION)
3706 error("%s not defined in %s", name, fullname);
3707 stunalloc(fullname);
3710 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3711 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3712 be a function and we're being called with DO_NOFUN */
3714 entry->cmdtype = CMDNORMAL;
3715 entry->u.index = idx;
3719 cmdp = cmdlookup(name, 1);
3720 cmdp->cmdtype = CMDNORMAL;
3721 cmdp->param.index = idx;
3726 /* We failed. If there was an entry for this command, delete it */
3727 if (cmdp && updatetbl)
3730 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3731 entry->cmdtype = CMDUNKNOWN;
3736 entry->cmdtype = cmdp->cmdtype;
3737 entry->u = cmdp->param;
3743 * Search the table of builtin commands.
3746 static struct builtincmd *find_builtin(const char *name)
3748 struct builtincmd *bp;
3750 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3757 * Called when a cd is done. Marks all commands so the next time they
3758 * are executed they will be rehashed.
3761 static void hashcd(void)
3763 struct tblentry **pp;
3764 struct tblentry *cmdp;
3766 for (pp = cmdtable; pp < &cmdtable[CMDTABLESIZE]; pp++) {
3767 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3768 if (cmdp->cmdtype == CMDNORMAL
3769 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3778 * Called before PATH is changed. The argument is the new value of PATH;
3779 * pathval() still returns the old value at this point. Called with
3783 static void changepath(const char *newval)
3788 firstchange = path_change(newval, &bltin);
3789 if (builtinloc < 0 && bltin >= 0)
3790 builtinloc = bltin; /* zap builtins */
3791 clearcmdentry(firstchange);
3793 /* Ensure that getenv("PATH") stays current */
3794 setenv("PATH", newval, 1);
3799 * Clear out command entries. The argument specifies the first entry in
3800 * PATH which has changed.
3803 static void clearcmdentry(int firstchange)
3805 struct tblentry **tblp;
3806 struct tblentry **pp;
3807 struct tblentry *cmdp;
3810 for (tblp = cmdtable; tblp < &cmdtable[CMDTABLESIZE]; tblp++) {
3812 while ((cmdp = *pp) != NULL) {
3813 if ((cmdp->cmdtype == CMDNORMAL &&
3814 cmdp->param.index >= firstchange)
3815 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= firstchange)) {
3828 * Locate a command in the command hash table. If "add" is nonzero,
3829 * add the command to the table if it is not already present. The
3830 * variable "lastcmdentry" is set to point to the address of the link
3831 * pointing to the entry, so that delete_cmd_entry can delete the
3835 static struct tblentry **lastcmdentry;
3837 static struct tblentry *cmdlookup(const char *name, int add)
3841 struct tblentry *cmdp;
3842 struct tblentry **pp;
3849 pp = &cmdtable[hashval % CMDTABLESIZE];
3850 for (cmdp = *pp; cmdp; cmdp = cmdp->next) {
3851 if (equal(cmdp->cmdname, name))
3855 if (add && cmdp == NULL) {
3857 cmdp = *pp = xmalloc(sizeof(struct tblentry) - ARB
3858 + strlen(name) + 1);
3860 cmdp->cmdtype = CMDUNKNOWN;
3862 strcpy(cmdp->cmdname, name);
3870 * Delete the command entry returned on the last lookup.
3873 static void delete_cmd_entry(void)
3875 struct tblentry *cmdp;
3878 cmdp = *lastcmdentry;
3879 *lastcmdentry = cmdp->next;
3888 static const unsigned char nodesize[26] = {
3889 ALIGN(sizeof(struct nbinary)),
3890 ALIGN(sizeof(struct ncmd)),
3891 ALIGN(sizeof(struct npipe)),
3892 ALIGN(sizeof(struct nredir)),
3893 ALIGN(sizeof(struct nredir)),
3894 ALIGN(sizeof(struct nredir)),
3895 ALIGN(sizeof(struct nbinary)),
3896 ALIGN(sizeof(struct nbinary)),
3897 ALIGN(sizeof(struct nif)),
3898 ALIGN(sizeof(struct nbinary)),
3899 ALIGN(sizeof(struct nbinary)),
3900 ALIGN(sizeof(struct nfor)),
3901 ALIGN(sizeof(struct ncase)),
3902 ALIGN(sizeof(struct nclist)),
3903 ALIGN(sizeof(struct narg)),
3904 ALIGN(sizeof(struct narg)),
3905 ALIGN(sizeof(struct nfile)),
3906 ALIGN(sizeof(struct nfile)),
3907 ALIGN(sizeof(struct nfile)),
3908 ALIGN(sizeof(struct nfile)),
3909 ALIGN(sizeof(struct nfile)),
3910 ALIGN(sizeof(struct ndup)),
3911 ALIGN(sizeof(struct ndup)),
3912 ALIGN(sizeof(struct nhere)),
3913 ALIGN(sizeof(struct nhere)),
3914 ALIGN(sizeof(struct nnot)),
3920 * Delete a function if it exists.
3923 static void unsetfunc(char *name)
3925 struct tblentry *cmdp;
3927 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
3928 free(cmdp->param.func);
3935 * Locate and print what a word is...
3938 static int typecmd(int argc, char **argv)
3946 for (i = 1; i < argc; i++) {
3947 argv_a[0] = argv[i];
3950 err |= hashcmd(2, argv);
3955 #ifdef CONFIG_ASH_CMDCMD
3956 static int commandcmd(int argc, char **argv)
3959 int default_path = 0;
3960 int verify_only = 0;
3961 int verbose_verify_only = 0;
3963 while ((c = nextopt("pvV")) != '\0')
3972 verbose_verify_only = 1;
3976 if (default_path + verify_only + verbose_verify_only > 1 || !*argptr) {
3977 out2str("command [-p] command [arg ...]\n"
3978 "command {-v|-V} command\n");
3982 if (verify_only || verbose_verify_only) {
3986 argv_a[0] = *argptr;
3988 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
3989 return hashcmd(argc, argv);
3996 static int path_change(const char *newval, int *bltin)
3998 const char *old, *new;
4004 firstchange = 9999; /* assume no change */
4010 if ((*old == '\0' && *new == ':')
4011 || (*old == ':' && *new == '\0'))
4013 old = new; /* ignore subsequent differences */
4017 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4024 if (builtinloc >= 0 && *bltin < 0)
4030 * Routines to expand arguments to commands. We have to deal with
4031 * backquotes, shell variables, and file metacharacters.
4036 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4037 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4040 * Structure specifying which parts of the string should be searched
4041 * for IFS characters.
4045 struct ifsregion *next; /* next region in list */
4046 int begoff; /* offset of start of region */
4047 int endoff; /* offset of end of region */
4048 int nulonly; /* search for nul bytes only */
4052 static char *expdest; /* output of current string */
4053 static struct nodelist *argbackq; /* list of back quote expressions */
4054 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4055 static struct ifsregion *ifslastp; /* last struct in list */
4056 static struct arglist exparg; /* holds expanded arg list */
4058 static void argstr(char *, int);
4059 static char *exptilde(char *, int);
4060 static void expbackq(union node *, int, int);
4061 static int subevalvar(char *, char *, int, int, int, int, int);
4062 static int varisset(char *, int);
4063 static void strtodest(const char *, int, int);
4064 static void varvalue(char *, int, int);
4065 static void recordregion(int, int, int);
4066 static void removerecordregions(int);
4067 static void ifsbreakup(char *, struct arglist *);
4068 static void ifsfree(void);
4069 static void expandmeta(struct strlist *, int);
4071 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4072 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4073 #if !defined(GLOB_BROKEN)
4074 static void addglob(const glob_t *);
4077 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4078 static void expmeta(char *, char *);
4080 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4081 static struct strlist *expsort(struct strlist *);
4082 static struct strlist *msort(struct strlist *, int);
4084 static int patmatch(char *, char *, int);
4086 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4087 static int patmatch2(char *, char *, int);
4089 static int pmatch(char *, char *, int);
4091 #define patmatch2 patmatch
4093 static char *cvtnum(int, char *);
4096 * Expand shell variables and backquotes inside a here document.
4099 /* arg: the document, fd: where to write the expanded version */
4100 static inline void expandhere(union node *arg, int fd)
4103 expandarg(arg, (struct arglist *) NULL, 0);
4104 xwrite(fd, stackblock(), expdest - stackblock());
4109 * Perform variable substitution and command substitution on an argument,
4110 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4111 * perform splitting and file name expansion. When arglist is NULL, perform
4112 * here document expansion.
4115 static void expandarg(union node *arg, struct arglist *arglist, int flag)
4120 argbackq = arg->narg.backquote;
4121 STARTSTACKSTR(expdest);
4122 ifsfirst.next = NULL;
4124 argstr(arg->narg.text, flag);
4125 if (arglist == NULL) {
4126 return; /* here document expanded */
4128 STPUTC('\0', expdest);
4129 p = grabstackstr(expdest);
4130 exparg.lastp = &exparg.list;
4134 if (flag & EXP_FULL) {
4135 ifsbreakup(p, &exparg);
4136 *exparg.lastp = NULL;
4137 exparg.lastp = &exparg.list;
4138 expandmeta(exparg.list, flag);
4140 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4142 sp = (struct strlist *) stalloc(sizeof(struct strlist));
4145 exparg.lastp = &sp->next;
4148 *exparg.lastp = NULL;
4150 *arglist->lastp = exparg.list;
4151 arglist->lastp = exparg.lastp;
4157 * Expand a variable, and return a pointer to the next character in the
4161 static inline char *evalvar(char *p, int flag)
4174 int quotes = flag & (EXP_FULL | EXP_CASE);
4177 subtype = varflags & VSTYPE;
4182 p = strchr(p, '=') + 1;
4183 again: /* jump here after setting a variable with ${var=text} */
4185 set = varisset(var, varflags & VSNUL);
4188 val = lookupvar(var);
4189 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4196 startloc = expdest - stackblock();
4197 if (set && subtype != VSPLUS) {
4198 /* insert the value of the variable */
4200 varvalue(var, varflags & VSQUOTE, flag);
4201 if (subtype == VSLENGTH) {
4202 varlen = expdest - stackblock() - startloc;
4203 STADJUST(-varlen, expdest);
4206 if (subtype == VSLENGTH) {
4207 varlen = strlen(val);
4210 varflags & VSQUOTE ? DQSYNTAX : BASESYNTAX, quotes);
4215 if (subtype == VSPLUS)
4218 easy = ((varflags & VSQUOTE) == 0 ||
4219 (*var == '@' && shellparam.nparam != 1));
4224 expdest = cvtnum(varlen, expdest);
4231 recordregion(startloc, expdest - stackblock(), varflags & VSQUOTE);
4247 case VSTRIMRIGHTMAX:
4251 * Terminate the string and start recording the pattern
4254 STPUTC('\0', expdest);
4255 patloc = expdest - stackblock();
4256 if (subevalvar(p, NULL, patloc, subtype,
4257 startloc, varflags, quotes) == 0) {
4258 int amount = (expdest - stackblock() - patloc) + 1;
4260 STADJUST(-amount, expdest);
4262 /* Remove any recorded regions beyond start of variable */
4263 removerecordregions(startloc);
4269 if (subevalvar(p, var, 0, subtype, startloc, varflags, quotes)) {
4272 * Remove any recorded regions beyond
4275 removerecordregions(startloc);
4290 if (subtype != VSNORMAL) { /* skip to end of alternative */
4294 if ((c = *p++) == CTLESC)
4296 else if (c == CTLBACKQ || c == (CTLBACKQ | CTLQUOTE)) {
4298 argbackq = argbackq->next;
4299 } else if (c == CTLVAR) {
4300 if ((*p++ & VSTYPE) != VSNORMAL)
4302 } else if (c == CTLENDVAR) {
4313 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4314 * characters to allow for further processing. Otherwise treat
4315 * $@ like $* since no splitting will be performed.
4318 static void argstr(char *p, int flag)
4321 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4324 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4325 p = exptilde(p, flag);
4329 case CTLENDVAR: /* ??? */
4332 /* "$@" syntax adherence hack */
4333 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4335 if ((flag & EXP_FULL) != 0)
4345 p = evalvar(p, flag);
4348 case CTLBACKQ | CTLQUOTE:
4349 expbackq(argbackq->n, c & CTLQUOTE, flag);
4350 argbackq = argbackq->next;
4352 #ifdef CONFIG_ASH_MATH_SUPPORT
4360 * sort of a hack - expand tildes in variable
4361 * assignments (after the first '=' and after ':'s).
4364 if (flag & EXP_VARTILDE && *p == '~') {
4371 p = exptilde(p, flag);
4380 static char *exptilde(char *p, int flag)
4382 char c, *startp = p;
4385 int quotes = flag & (EXP_FULL | EXP_CASE);
4387 while ((c = *p) != '\0') {
4394 if (flag & EXP_VARTILDE)
4404 if (*(startp + 1) == '\0') {
4405 if ((home = lookupvar("HOME")) == NULL)
4408 if ((pw = getpwnam(startp + 1)) == NULL)
4415 strtodest(home, SQSYNTAX, quotes);
4423 static void removerecordregions(int endoff)
4425 if (ifslastp == NULL)
4428 if (ifsfirst.endoff > endoff) {
4429 while (ifsfirst.next != NULL) {
4430 struct ifsregion *ifsp;
4433 ifsp = ifsfirst.next->next;
4434 free(ifsfirst.next);
4435 ifsfirst.next = ifsp;
4438 if (ifsfirst.begoff > endoff)
4441 ifslastp = &ifsfirst;
4442 ifsfirst.endoff = endoff;
4447 ifslastp = &ifsfirst;
4448 while (ifslastp->next && ifslastp->next->begoff < endoff)
4449 ifslastp = ifslastp->next;
4450 while (ifslastp->next != NULL) {
4451 struct ifsregion *ifsp;
4454 ifsp = ifslastp->next->next;
4455 free(ifslastp->next);
4456 ifslastp->next = ifsp;
4459 if (ifslastp->endoff > endoff)
4460 ifslastp->endoff = endoff;
4464 #ifdef CONFIG_ASH_MATH_SUPPORT
4466 * Expand arithmetic expression. Backup to start of expression,
4467 * evaluate, place result in (backed up) result, adjust string position.
4469 static void expari(int flag)
4475 int quotes = flag & (EXP_FULL | EXP_CASE);
4481 * This routine is slightly over-complicated for
4482 * efficiency. First we make sure there is
4483 * enough space for the result, which may be bigger
4484 * than the expression if we add exponentation. Next we
4485 * scan backwards looking for the start of arithmetic. If the
4486 * next previous character is a CTLESC character, then we
4487 * have to rescan starting from the beginning since CTLESC
4488 * characters have to be processed left to right.
4490 CHECKSTRSPACE(10, expdest);
4491 USTPUTC('\0', expdest);
4492 start = stackblock();
4494 while (*p != CTLARI && p >= start)
4497 error("missing CTLARI (shouldn't happen)");
4498 if (p > start && *(p - 1) == CTLESC)
4499 for (p = start; *p != CTLARI; p++)
4508 removerecordregions(begoff);
4511 result = arith(p + 2, &errcode);
4514 error("divide by zero");
4516 error("syntax error: \"%s\"\n", p + 2);
4518 snprintf(p, 12, "%d", result);
4522 recordregion(begoff, p - 1 - start, 0);
4523 result = expdest - p + 1;
4524 STADJUST(-result, expdest);
4529 * Expand stuff in backwards quotes.
4532 static void expbackq(union node *cmd, int quoted, int flag)
4534 volatile struct backcmd in;
4538 char *dest = expdest;
4539 volatile struct ifsregion saveifs;
4540 struct ifsregion *volatile savelastp;
4541 struct nodelist *volatile saveargbackq;
4543 int startloc = dest - stackblock();
4544 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4545 volatile int saveherefd;
4546 int quotes = flag & (EXP_FULL | EXP_CASE);
4547 struct jmploc jmploc;
4548 struct jmploc *volatile savehandler;
4552 /* Avoid longjmp clobbering */
4563 savelastp = ifslastp;
4564 saveargbackq = argbackq;
4565 saveherefd = herefd;
4567 if ((ex = setjmp(jmploc.loc))) {
4570 savehandler = handler;
4573 p = grabstackstr(dest);
4574 evalbackcmd(cmd, (struct backcmd *) &in);
4575 ungrabstackstr(p, dest);
4579 ifslastp = savelastp;
4580 argbackq = saveargbackq;
4581 herefd = saveherefd;
4589 if (--in.nleft < 0) {
4592 i = safe_read(in.fd, buf, sizeof buf);
4593 TRACE(("expbackq: read returns %d\n", i));
4600 if (lastc != '\0') {
4601 if (quotes && SIT(lastc, syntax) == CCTL)
4602 STPUTC(CTLESC, dest);
4603 STPUTC(lastc, dest);
4607 /* Eat all trailing newlines */
4608 for (; dest > stackblock() && dest[-1] == '\n';)
4616 exitstatus = waitforjob(in.jp);
4617 handler = savehandler;
4619 longjmp(handler->loc, 1);
4622 recordregion(startloc, dest - stackblock(), 0);
4623 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4624 (dest - stackblock()) - startloc,
4625 (dest - stackblock()) - startloc, stackblock() + startloc));
4631 subevalvar(char *p, char *str, int strloc, int subtype, int startloc,
4632 int varflags, int quotes)
4638 int saveherefd = herefd;
4639 struct nodelist *saveargbackq = argbackq;
4643 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4644 STACKSTRNUL(expdest);
4645 herefd = saveherefd;
4646 argbackq = saveargbackq;
4647 startp = stackblock() + startloc;
4649 str = stackblock() + strloc;
4653 setvar(str, startp, 0);
4654 amount = startp - expdest;
4655 STADJUST(amount, expdest);
4662 if (*p != CTLENDVAR) {
4663 out2fmt(snlfmt, startp);
4664 error((char *) NULL);
4666 error("%.*s: parameter %snot set", p - str - 1,
4667 str, (varflags & VSNUL) ? "null or " : nullstr);
4671 for (loc = startp; loc < str; loc++) {
4674 if (patmatch2(str, startp, quotes))
4677 if (quotes && *loc == CTLESC)
4683 for (loc = str - 1; loc >= startp;) {
4686 if (patmatch2(str, startp, quotes))
4690 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4691 for (q = startp; q < loc; q++)
4701 for (loc = str - 1; loc >= startp;) {
4702 if (patmatch2(str, loc, quotes))
4705 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4706 for (q = startp; q < loc; q++)
4715 case VSTRIMRIGHTMAX:
4716 for (loc = startp; loc < str - 1; loc++) {
4717 if (patmatch2(str, loc, quotes))
4719 if (quotes && *loc == CTLESC)
4732 amount = ((str - 1) - (loc - startp)) - expdest;
4733 STADJUST(amount, expdest);
4734 while (loc != str - 1)
4739 amount = loc - expdest;
4740 STADJUST(amount, expdest);
4741 STPUTC('\0', expdest);
4742 STADJUST(-1, expdest);
4748 * Test whether a specialized variable is set.
4751 static int varisset(char *name, int nulok)
4754 return backgndpid != -1;
4755 else if (*name == '@' || *name == '*') {
4756 if (*shellparam.p == NULL)
4762 for (av = shellparam.p; *av; av++)
4767 } else if (is_digit(*name)) {
4769 int num = atoi(name);
4771 if (num > shellparam.nparam)
4777 ap = shellparam.p[num - 1];
4779 if (nulok && (ap == NULL || *ap == '\0'))
4786 * Put a string on the stack.
4789 static void strtodest(const char *p, int syntax, int quotes)
4792 if (quotes && SIT(*p, syntax) == CCTL)
4793 STPUTC(CTLESC, expdest);
4794 STPUTC(*p++, expdest);
4799 * Add the value of a specialized variable to the stack string.
4802 static void varvalue(char *name, int quoted, int flags)
4811 int allow_split = flags & EXP_FULL;
4812 int quotes = flags & (EXP_FULL | EXP_CASE);
4814 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4823 num = shellparam.nparam;
4828 expdest = cvtnum(num, expdest);
4831 for (i = 0; i < NOPTS; i++) {
4833 STPUTC(optent_letter(optlist[i]), expdest);
4837 if (allow_split && quoted) {
4838 sep = 1 << CHAR_BIT;
4843 sep = ifsset()? ifsval()[0] : ' ';
4845 sepq = SIT(sep, syntax) == CCTL;
4848 for (ap = shellparam.p; (p = *ap++) != NULL;) {
4849 strtodest(p, syntax, quotes);
4852 STPUTC(CTLESC, expdest);
4853 STPUTC(sep, expdest);
4858 strtodest(arg0, syntax, quotes);
4862 if (num > 0 && num <= shellparam.nparam) {
4863 strtodest(shellparam.p[num - 1], syntax, quotes);
4871 * Record the fact that we have to scan this region of the
4872 * string for IFS characters.
4875 static void recordregion(int start, int end, int nulonly)
4877 struct ifsregion *ifsp;
4879 if (ifslastp == NULL) {
4883 ifsp = (struct ifsregion *) xmalloc(sizeof(struct ifsregion));
4885 ifslastp->next = ifsp;
4889 ifslastp->begoff = start;
4890 ifslastp->endoff = end;
4891 ifslastp->nulonly = nulonly;
4897 * Break the argument string into pieces based upon IFS and add the
4898 * strings to the argument list. The regions of the string to be
4899 * searched for IFS characters have been stored by recordregion.
4901 static void ifsbreakup(char *string, struct arglist *arglist)
4903 struct ifsregion *ifsp;
4908 const char *ifs, *realifs;
4916 realifs = ifsset()? ifsval() : defifs;
4917 if (ifslastp != NULL) {
4920 p = string + ifsp->begoff;
4921 nulonly = ifsp->nulonly;
4922 ifs = nulonly ? nullstr : realifs;
4924 while (p < string + ifsp->endoff) {
4928 if (strchr(ifs, *p)) {
4930 ifsspc = (strchr(defifs, *p) != NULL);
4931 /* Ignore IFS whitespace at start */
4932 if (q == start && ifsspc) {
4938 sp = (struct strlist *) stalloc(sizeof *sp);
4940 *arglist->lastp = sp;
4941 arglist->lastp = &sp->next;
4945 if (p >= string + ifsp->endoff) {
4951 if (strchr(ifs, *p) == NULL) {
4954 } else if (strchr(defifs, *p) == NULL) {
4970 } while ((ifsp = ifsp->next) != NULL);
4971 if (!(*start || (!ifsspc && start > string && nulonly))) {
4976 sp = (struct strlist *) stalloc(sizeof *sp);
4978 *arglist->lastp = sp;
4979 arglist->lastp = &sp->next;
4982 static void ifsfree(void)
4984 while (ifsfirst.next != NULL) {
4985 struct ifsregion *ifsp;
4988 ifsp = ifsfirst.next->next;
4989 free(ifsfirst.next);
4990 ifsfirst.next = ifsp;
4994 ifsfirst.next = NULL;
4998 * Add a file name to the list.
5001 static void addfname(const char *name)
5004 size_t len = strlen(name) + 1;
5006 sp = (struct strlist *) stalloc(sizeof *sp);
5007 sp->text = memcpy(stalloc(len), name, len);
5009 exparg.lastp = &sp->next;
5013 * Expand shell metacharacters. At this point, the only control characters
5014 * should be escapes. The results are stored in the list exparg.
5017 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5018 static void expandmeta(struct strlist *str, int flag)
5023 /* TODO - EXP_REDIR */
5028 p = preglob(str->text);
5030 switch (glob(p, 0, 0, &pglob)) {
5032 if (pglob.gl_pathv[1] == 0 && !strcmp(p, pglob.gl_pathv[0]))
5043 *exparg.lastp = str;
5044 rmescapes(str->text);
5045 exparg.lastp = &str->next;
5047 default: /* GLOB_NOSPACE */
5048 error("Out of space");
5056 * Add the result of glob(3) to the list.
5059 static void addglob(const glob_t * pglob)
5061 char **p = pglob->gl_pathv;
5069 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5070 static char *expdir;
5073 static void expandmeta(struct strlist *str, int flag)
5076 struct strlist **savelastp;
5080 /* TODO - EXP_REDIR */
5086 for (;;) { /* fast check for meta chars */
5087 if ((c = *p++) == '\0')
5089 if (c == '*' || c == '?' || c == '[' || c == '!')
5092 savelastp = exparg.lastp;
5094 if (expdir == NULL) {
5095 int i = strlen(str->text);
5097 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5100 expmeta(expdir, str->text);
5104 if (exparg.lastp == savelastp) {
5109 *exparg.lastp = str;
5110 rmescapes(str->text);
5111 exparg.lastp = &str->next;
5113 *exparg.lastp = NULL;
5114 *savelastp = sp = expsort(*savelastp);
5115 while (sp->next != NULL)
5117 exparg.lastp = &sp->next;
5125 * Do metacharacter (i.e. *, ?, [...]) expansion.
5128 static void expmeta(char *enddir, char *name)
5144 for (p = name;; p++) {
5145 if (*p == '*' || *p == '?')
5147 else if (*p == '[') {
5152 while (*q == CTLQUOTEMARK)
5156 if (*q == '/' || *q == '\0')
5163 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5165 } else if (*p == '\0')
5167 else if (*p == CTLQUOTEMARK)
5169 else if (*p == CTLESC)
5177 if (metaflag == 0) { /* we've reached the end of the file name */
5178 if (enddir != expdir)
5180 for (p = name;; p++) {
5181 if (*p == CTLQUOTEMARK)
5189 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5194 if (start != name) {
5197 while (*p == CTLQUOTEMARK)
5204 if (enddir == expdir) {
5206 } else if (enddir == expdir + 1 && *expdir == '/') {
5212 if ((dirp = opendir(cp)) == NULL)
5214 if (enddir != expdir)
5216 if (*endname == 0) {
5224 while (*p == CTLQUOTEMARK)
5230 while (!int_pending() && (dp = readdir(dirp)) != NULL) {
5231 if (dp->d_name[0] == '.' && !matchdot)
5233 if (patmatch(start, dp->d_name, 0)) {
5235 strcpy(enddir, dp->d_name);
5238 for (p = enddir, cp = dp->d_name; (*p++ = *cp++) != '\0';)
5241 expmeta(p, endname);
5249 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5253 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5255 * Sort the results of file name expansion. It calculates the number of
5256 * strings to sort and then calls msort (short for merge sort) to do the
5260 static struct strlist *expsort(struct strlist *str)
5266 for (sp = str; sp; sp = sp->next)
5268 return msort(str, len);
5272 static struct strlist *msort(struct strlist *list, int len)
5274 struct strlist *p, *q = NULL;
5275 struct strlist **lpp;
5283 for (n = half; --n >= 0;) {
5287 q->next = NULL; /* terminate first half of list */
5288 q = msort(list, half); /* sort first half of list */
5289 p = msort(p, len - half); /* sort second half */
5292 if (strcmp(p->text, q->text) < 0) {
5295 if ((p = *lpp) == NULL) {
5302 if ((q = *lpp) == NULL) {
5315 * Returns true if the pattern matches the string.
5318 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5319 /* squoted: string might have quote chars */
5320 static int patmatch(char *pattern, char *string, int squoted)
5325 p = preglob(pattern);
5326 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5328 return !fnmatch(p, q, 0);
5332 static int patmatch2(char *pattern, char *string, int squoted)
5338 p = grabstackstr(expdest);
5339 res = patmatch(pattern, string, squoted);
5340 ungrabstackstr(p, expdest);
5344 static int patmatch(char *pattern, char *string, int squoted)
5346 return pmatch(pattern, string, squoted);
5350 static int pmatch(char *pattern, char *string, int squoted)
5362 if (squoted && *q == CTLESC)
5370 if (squoted && *q == CTLESC)
5377 while (c == CTLQUOTEMARK || c == '*')
5379 if (c != CTLESC && c != CTLQUOTEMARK &&
5380 c != '?' && c != '*' && c != '[') {
5382 if (squoted && *q == CTLESC && q[1] == c)
5386 if (squoted && *q == CTLESC)
5392 if (pmatch(p, q, squoted))
5394 if (squoted && *q == CTLESC)
5396 } while (*q++ != '\0');
5407 while (*endp == CTLQUOTEMARK)
5410 goto dft; /* no matching ] */
5411 if (*endp == CTLESC)
5423 if (squoted && chr == CTLESC)
5429 if (c == CTLQUOTEMARK)
5433 if (*p == '-' && p[1] != ']') {
5435 while (*p == CTLQUOTEMARK)
5439 if (chr >= c && chr <= *p)
5446 } while ((c = *p++) != ']');
5447 if (found == invert)
5452 if (squoted && *q == CTLESC)
5469 * Remove any CTLESC characters from a string.
5472 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5473 static char *_rmescapes(char *str, int flag)
5476 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5478 p = strpbrk(str, qchars);
5484 if (flag & RMESCAPE_ALLOC) {
5485 size_t len = p - str;
5487 q = r = stalloc(strlen(p) + len + 1);
5489 memcpy(q, str, len);
5494 if (*p == CTLQUOTEMARK) {
5500 if (flag & RMESCAPE_GLOB && *p != '/') {
5510 static void rmescapes(char *str)
5515 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5521 if (*p == CTLQUOTEMARK) {
5536 * See if a pattern matches in a case statement.
5539 static int casematch(union node *pattern, const char *val)
5541 struct stackmark smark;
5545 setstackmark(&smark);
5546 argbackq = pattern->narg.backquote;
5547 STARTSTACKSTR(expdest);
5549 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5550 STPUTC('\0', expdest);
5551 p = grabstackstr(expdest);
5552 result = patmatch(p, (char *) val, 0);
5553 popstackmark(&smark);
5561 static char *cvtnum(int num, char *buf)
5565 CHECKSTRSPACE(32, buf);
5566 len = sprintf(buf, "%d", num);
5572 * Editline and history functions (and glue).
5574 static int histcmd(int argc, char **argv)
5576 error("not compiled with history support");
5582 struct redirtab *next;
5583 short renamed[10]; /* Current ash support only 0-9 descriptors */
5584 /* char on arm (and others) can't be negative */
5587 static struct redirtab *redirlist;
5589 extern char **environ;
5594 * Initialization code.
5597 static void init(void)
5608 basepf.nextc = basepf.buf = basebuf;
5617 for (envp = environ; *envp; envp++) {
5618 if (strchr(*envp, '=')) {
5619 setvareq(*envp, VEXPORT | VTEXTFIXED);
5623 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5624 setvar("PPID", ppid, 0);
5631 * This routine is called when an error or an interrupt occurs in an
5632 * interactive shell and control is returned to the main command loop.
5635 /* 1 == check for aliases, 2 == also check for assignments */
5636 static int checkalias; /* also used in no alias mode for check assignments */
5638 static void reset(void)
5650 parselleft = parsenleft = 0; /* clear input buffer */
5654 /* from parser.c: */
5672 * This file implements the input routines used by the parser.
5675 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5676 static const char *cmdedit_prompt;
5677 static inline void putprompt(const char *s)
5682 static inline void putprompt(const char *s)
5688 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5693 * Same as pgetc(), but ignores PEOA.
5696 #ifdef CONFIG_ASH_ALIAS
5697 static int pgetc2(void)
5703 } while (c == PEOA);
5707 static inline int pgetc2(void)
5709 return pgetc_macro();
5714 * Read a line from the script.
5717 static inline char *pfgets(char *line, int len)
5723 while (--nleft > 0) {
5738 static inline int preadfd(void)
5741 char *buf = parsefile->buf;
5746 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5748 if (!iflag || parsefile->fd)
5749 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5751 nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
5755 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5759 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5760 int flags = fcntl(0, F_GETFL, 0);
5762 if (flags >= 0 && flags & O_NONBLOCK) {
5763 flags &= ~O_NONBLOCK;
5764 if (fcntl(0, F_SETFL, flags) >= 0) {
5765 out2str("sh: turning off NDELAY mode\n");
5774 static void popstring(void)
5776 struct strpush *sp = parsefile->strpush;
5779 #ifdef CONFIG_ASH_ALIAS
5781 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5786 if (sp->string != sp->ap->val) {
5790 sp->ap->flag &= ~ALIASINUSE;
5791 if (sp->ap->flag & ALIASDEAD) {
5792 unalias(sp->ap->name);
5796 parsenextc = sp->prevstring;
5797 parsenleft = sp->prevnleft;
5798 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5799 parsefile->strpush = sp->prev;
5800 if (sp != &(parsefile->basestrpush))
5807 * Refill the input buffer and return the next input character:
5809 * 1) If a string was pushed back on the input, pop it;
5810 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5811 * from a string so we can't refill the buffer, return EOF.
5812 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5813 * 4) Process input up to the next newline, deleting nul characters.
5816 static int preadbuffer(void)
5822 while (parsefile->strpush) {
5823 #ifdef CONFIG_ASH_ALIAS
5824 if (parsenleft == -1 && parsefile->strpush->ap &&
5825 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5830 if (--parsenleft >= 0)
5831 return (*parsenextc++);
5833 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5838 if (parselleft <= 0) {
5839 if ((parselleft = preadfd()) <= 0) {
5840 parselleft = parsenleft = EOF_NLEFT;
5847 /* delete nul characters */
5848 for (more = 1; more;) {
5856 parsenleft = q - parsenextc;
5857 more = 0; /* Stop processing here */
5863 if (--parselleft <= 0 && more) {
5864 parsenleft = q - parsenextc - 1;
5875 out2str(parsenextc);
5880 return *parsenextc++;
5885 * Push a string back onto the input at this current parsefile level.
5886 * We handle aliases this way.
5888 static void pushstring(char *s, int len, void *ap)
5893 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
5894 if (parsefile->strpush) {
5895 sp = xmalloc(sizeof(struct strpush));
5896 sp->prev = parsefile->strpush;
5897 parsefile->strpush = sp;
5899 sp = parsefile->strpush = &(parsefile->basestrpush);
5900 sp->prevstring = parsenextc;
5901 sp->prevnleft = parsenleft;
5902 #ifdef CONFIG_ASH_ALIAS
5903 sp->ap = (struct alias *) ap;
5905 ((struct alias *) ap)->flag |= ALIASINUSE;
5916 * Like setinputfile, but takes input from a string.
5919 static void setinputstring(char *string)
5923 parsenextc = string;
5924 parsenleft = strlen(string);
5925 parsefile->buf = NULL;
5933 * To handle the "." command, a stack of input files is used. Pushfile
5934 * adds a new entry to the stack and popfile restores the previous level.
5937 static void pushfile(void)
5939 struct parsefile *pf;
5941 parsefile->nleft = parsenleft;
5942 parsefile->lleft = parselleft;
5943 parsefile->nextc = parsenextc;
5944 parsefile->linno = plinno;
5945 pf = (struct parsefile *) xmalloc(sizeof(struct parsefile));
5946 pf->prev = parsefile;
5949 pf->basestrpush.prev = NULL;
5953 #ifdef CONFIG_ASH_JOB_CONTROL
5954 static void restartjob(struct job *);
5956 static void freejob(struct job *);
5957 static struct job *getjob(const char *);
5958 static int dowait(int, struct job *);
5962 * We keep track of whether or not fd0 has been redirected. This is for
5963 * background commands, where we want to redirect fd0 to /dev/null only
5964 * if it hasn't already been redirected.
5966 static int fd0_redirected = 0;
5968 /* Return true if fd 0 has already been redirected at least once. */
5969 static inline int fd0_redirected_p(void)
5971 return fd0_redirected != 0;
5974 static void dupredirect(const union node *, int, int fd1dup);
5976 #ifdef CONFIG_ASH_JOB_CONTROL
5978 * Turn job control on and off.
5980 * Note: This code assumes that the third arg to ioctl is a character
5981 * pointer, which is true on Berkeley systems but not System V. Since
5982 * System V doesn't have job control yet, this isn't a problem now.
5987 static void setjobctl(int enable)
5989 if (enable == jobctl || rootshell == 0)
5992 do { /* while we are in the background */
5993 initialpgrp = tcgetpgrp(2);
5994 if (initialpgrp < 0) {
5995 out2str("sh: can't access tty; job control turned off\n");
5999 if (initialpgrp == getpgrp())
6006 setpgid(0, rootpid);
6007 tcsetpgrp(2, rootpid);
6008 } else { /* turning job control off */
6009 setpgid(0, initialpgrp);
6010 tcsetpgrp(2, initialpgrp);
6020 #ifdef CONFIG_ASH_JOB_CONTROL
6021 static int killcmd(int argc, char **argv)
6032 ("Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6033 "kill -l [exitstatus]");
6036 if (*argv[1] == '-') {
6037 signo = decode_signal(argv[1] + 1, 1);
6041 while ((c = nextopt("ls:")) != '\0')
6047 signo = decode_signal(optionarg, 1);
6049 error("invalid signal number or name: %s", optionarg);
6054 error("nextopt returned character code 0%o", c);
6061 if (!list && signo < 0)
6064 if ((signo < 0 || !*argptr) ^ list) {
6073 for (i = 1; i < NSIG; i++) {
6074 name = u_signal_names(0, &i, 1);
6080 name = u_signal_names(*argptr, &signo, -1);
6084 error("invalid signal number or exit status: %s", *argptr);
6089 if (**argptr == '%') {
6090 jp = getjob(*argptr);
6091 if (jp->jobctl == 0)
6092 error("job %s not created under job control", *argptr);
6093 pid = -jp->ps[0].pid;
6095 pid = atoi(*argptr);
6096 if (kill(pid, signo) != 0)
6097 error("%s: %m", *argptr);
6098 } while (*++argptr);
6103 static int fgcmd(int argc, char **argv)
6109 jp = getjob(argv[1]);
6110 if (jp->jobctl == 0)
6111 error("job not created under job control");
6112 pgrp = jp->ps[0].pid;
6113 ioctl(2, TIOCSPGRP, (char *) &pgrp);
6115 status = waitforjob(jp);
6120 static int bgcmd(int argc, char **argv)
6125 jp = getjob(*++argv);
6126 if (jp->jobctl == 0)
6127 error("job not created under job control");
6129 } while (--argc > 1);
6134 static void restartjob(struct job *jp)
6136 struct procstat *ps;
6139 if (jp->state == JOBDONE)
6142 killpg(jp->ps[0].pid, SIGCONT);
6143 for (ps = jp->ps, i = jp->nprocs; --i >= 0; ps++) {
6144 if (WIFSTOPPED(ps->status)) {
6153 static void showjobs(int change);
6156 static int jobscmd(int argc, char **argv)
6164 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6165 * statuses have changed since the last call to showjobs.
6167 * If the shell is interrupted in the process of creating a job, the
6168 * result may be a job structure containing zero processes. Such structures
6169 * will be freed here.
6172 static void showjobs(int change)
6178 struct procstat *ps;
6182 TRACE(("showjobs(%d) called\n", change));
6183 while (dowait(0, (struct job *) NULL) > 0);
6184 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6187 if (jp->nprocs == 0) {
6191 if (change && !jp->changed)
6193 procno = jp->nprocs;
6194 for (ps = jp->ps;; ps++) { /* for each process */
6196 snprintf(s, 64, "[%d] %ld ", jobno, (long) ps->pid);
6198 snprintf(s, 64, " %ld ", (long) ps->pid);
6202 if (ps->status == -1) {
6203 /* don't print anything */
6204 } else if (WIFEXITED(ps->status)) {
6205 snprintf(s, 64, "Exit %d", WEXITSTATUS(ps->status));
6207 #ifdef CONFIG_ASH_JOB_CONTROL
6208 if (WIFSTOPPED(ps->status))
6209 i = WSTOPSIG(ps->status);
6210 else /* WIFSIGNALED(ps->status) */
6212 i = WTERMSIG(ps->status);
6213 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6214 strcpy(s, sys_siglist[i & 0x7F]);
6216 snprintf(s, 64, "Signal %d", i & 0x7F);
6217 if (WCOREDUMP(ps->status))
6218 strcat(s, " (core dumped)");
6222 printf("%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ', ps->cmd);
6227 if (jp->state == JOBDONE) {
6235 * Mark a job structure as unused.
6238 static void freejob(struct job *jp)
6240 const struct procstat *ps;
6244 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
6245 if (ps->cmd != nullstr)
6248 if (jp->ps != &jp->ps0)
6251 #ifdef CONFIG_ASH_JOB_CONTROL
6252 if (curjob == jp - jobtab + 1)
6260 static int waitcmd(int argc, char **argv)
6268 job = getjob(*++argv);
6272 for (;;) { /* loop until process terminated or stopped */
6275 status = job->ps[job->nprocs - 1].status;
6281 if (WIFEXITED(status))
6282 retval = WEXITSTATUS(status);
6283 #ifdef CONFIG_ASH_JOB_CONTROL
6284 else if (WIFSTOPPED(status))
6285 retval = WSTOPSIG(status) + 128;
6288 /* XXX: limits number of signals */
6289 retval = WTERMSIG(status) + 128;
6294 for (jp = jobtab;; jp++) {
6295 if (jp >= jobtab + njobs) { /* no running procs */
6298 if (jp->used && jp->state == 0)
6302 if (dowait(2, 0) < 0 && errno == EINTR) {
6311 * Convert a job name to a job structure.
6314 static struct job *getjob(const char *name)
6322 #ifdef CONFIG_ASH_JOB_CONTROL
6324 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6325 error("No current job");
6326 return &jobtab[jobno - 1];
6328 error("No current job");
6330 } else if (name[0] == '%') {
6331 if (is_digit(name[1])) {
6332 jobno = number(name + 1);
6333 if (jobno > 0 && jobno <= njobs && jobtab[jobno - 1].used != 0)
6334 return &jobtab[jobno - 1];
6335 #ifdef CONFIG_ASH_JOB_CONTROL
6336 } else if (name[1] == '%' && name[2] == '\0') {
6340 struct job *found = NULL;
6342 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6343 if (jp->used && jp->nprocs > 0
6344 && prefix(name + 1, jp->ps[0].cmd)) {
6346 error("%s: ambiguous", name);
6353 } else if (is_number(name, &pid)) {
6354 for (jp = jobtab, i = njobs; --i >= 0; jp++) {
6355 if (jp->used && jp->nprocs > 0
6356 && jp->ps[jp->nprocs - 1].pid == pid)
6360 error("No such job: %s", name);
6367 * Return a new job structure,
6370 static struct job *makejob(const union node *node, int nprocs)
6375 for (i = njobs, jp = jobtab;; jp++) {
6379 jobtab = xmalloc(4 * sizeof jobtab[0]);
6381 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6382 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6383 /* Relocate `ps' pointers */
6384 for (i = 0; i < njobs; i++)
6385 if (jp[i].ps == &jobtab[i].ps0)
6386 jp[i].ps = &jp[i].ps0;
6390 jp = jobtab + njobs;
6391 for (i = 4; --i >= 0; jobtab[njobs++].used = 0);
6403 #ifdef CONFIG_ASH_JOB_CONTROL
6404 jp->jobctl = jobctl;
6407 jp->ps = xmalloc(nprocs * sizeof(struct procstat));
6412 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long) node, nprocs,
6419 * Fork of a subshell. If we are doing job control, give the subshell its
6420 * own process group. Jp is a job structure that the job is to be added to.
6421 * N is the command that will be evaluated by the child. Both jp and n may
6422 * be NULL. The mode parameter can be one of the following:
6423 * FORK_FG - Fork off a foreground process.
6424 * FORK_BG - Fork off a background process.
6425 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6426 * process group even if job control is on.
6428 * When job control is turned off, background processes have their standard
6429 * input redirected to /dev/null (except for the second and later processes
6435 static int forkshell(struct job *jp, const union node *n, int mode)
6439 #ifdef CONFIG_ASH_JOB_CONTROL
6442 const char *devnull = _PATH_DEVNULL;
6443 const char *nullerr = "Can't open %s";
6445 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long) n,
6450 TRACE(("Fork failed, errno=%d\n", errno));
6452 error("Cannot fork");
6459 TRACE(("Child shell %d\n", getpid()));
6460 wasroot = rootshell;
6465 #ifdef CONFIG_ASH_JOB_CONTROL
6466 jobctl = 0; /* do job control only in root shell */
6467 if (wasroot && mode != FORK_NOJOB && mflag) {
6468 if (jp == NULL || jp->nprocs == 0)
6471 pgrp = jp->ps[0].pid;
6473 if (mode == FORK_FG) {
6474 /*** this causes superfluous TIOCSPGRPS ***/
6475 if (tcsetpgrp(2, pgrp) < 0)
6476 error("tcsetpgrp failed, errno=%d", errno);
6480 } else if (mode == FORK_BG) {
6482 if (mode == FORK_BG) {
6486 if ((jp == NULL || jp->nprocs == 0) && !fd0_redirected_p()) {
6488 if (open(devnull, O_RDONLY) != 0)
6489 error(nullerr, devnull);
6492 for (i = njobs, p = jobtab; --i >= 0; p++)
6495 if (wasroot && iflag) {
6502 #ifdef CONFIG_ASH_JOB_CONTROL
6503 if (rootshell && mode != FORK_NOJOB && mflag) {
6504 if (jp == NULL || jp->nprocs == 0)
6507 pgrp = jp->ps[0].pid;
6511 if (mode == FORK_BG)
6512 backgndpid = pid; /* set $! */
6514 struct procstat *ps = &jp->ps[jp->nprocs++];
6519 if (iflag && rootshell && n)
6520 ps->cmd = commandtext(n);
6523 TRACE(("In parent shell: child = %d\n", pid));
6530 * Wait for job to finish.
6532 * Under job control we have the problem that while a child process is
6533 * running interrupts generated by the user are sent to the child but not
6534 * to the shell. This means that an infinite loop started by an inter-
6535 * active user may be hard to kill. With job control turned off, an
6536 * interactive user may place an interactive program inside a loop. If
6537 * the interactive program catches interrupts, the user doesn't want
6538 * these interrupts to also abort the loop. The approach we take here
6539 * is to have the shell ignore interrupt signals while waiting for a
6540 * forground process to terminate, and then send itself an interrupt
6541 * signal if the child process was terminated by an interrupt signal.
6542 * Unfortunately, some programs want to do a bit of cleanup and then
6543 * exit on interrupt; unless these processes terminate themselves by
6544 * sending a signal to themselves (instead of calling exit) they will
6545 * confuse this approach.
6548 static int waitforjob(struct job *jp)
6550 #ifdef CONFIG_ASH_JOB_CONTROL
6551 int mypgrp = getpgrp();
6557 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6558 while (jp->state == 0) {
6561 #ifdef CONFIG_ASH_JOB_CONTROL
6563 if (tcsetpgrp(2, mypgrp) < 0)
6564 error("tcsetpgrp failed, errno=%d\n", errno);
6566 if (jp->state == JOBSTOPPED)
6567 curjob = jp - jobtab + 1;
6569 status = jp->ps[jp->nprocs - 1].status;
6570 /* convert to 8 bits */
6571 if (WIFEXITED(status))
6572 st = WEXITSTATUS(status);
6573 #ifdef CONFIG_ASH_JOB_CONTROL
6574 else if (WIFSTOPPED(status))
6575 st = WSTOPSIG(status) + 128;
6578 st = WTERMSIG(status) + 128;
6579 #ifdef CONFIG_ASH_JOB_CONTROL
6582 * This is truly gross.
6583 * If we're doing job control, then we did a TIOCSPGRP which
6584 * caused us (the shell) to no longer be in the controlling
6585 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6586 * intuit from the subprocess exit status whether a SIGINT
6587 * occured, and if so interrupt ourselves. Yuck. - mycroft
6589 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6592 if (jp->state == JOBDONE)
6602 * Wait for a process to terminate.
6606 * Do a wait system call. If job control is compiled in, we accept
6607 * stopped processes. If block is zero, we return a value of zero
6608 * rather than blocking.
6610 * System V doesn't have a non-blocking wait system call. It does
6611 * have a SIGCLD signal that is sent to a process when one of it's
6612 * children dies. The obvious way to use SIGCLD would be to install
6613 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6614 * was received, and have waitproc bump another counter when it got
6615 * the status of a process. Waitproc would then know that a wait
6616 * system call would not block if the two counters were different.
6617 * This approach doesn't work because if a process has children that
6618 * have not been waited for, System V will send it a SIGCLD when it
6619 * installs a signal handler for SIGCLD. What this means is that when
6620 * a child exits, the shell will be sent SIGCLD signals continuously
6621 * until is runs out of stack space, unless it does a wait call before
6622 * restoring the signal handler. The code below takes advantage of
6623 * this (mis)feature by installing a signal handler for SIGCLD and
6624 * then checking to see whether it was called. If there are any
6625 * children to be waited for, it will be.
6629 static inline int waitproc(int block, int *status)
6634 #ifdef CONFIG_ASH_JOB_CONTROL
6640 return wait3(status, flags, (struct rusage *) NULL);
6643 static int dowait(int block, struct job *job)
6647 struct procstat *sp;
6649 struct job *thisjob;
6655 TRACE(("dowait(%d) called\n", block));
6657 pid = waitproc(block, &status);
6658 TRACE(("wait returns %d, status=%d\n", pid, status));
6659 } while (!(block & 2) && pid == -1 && errno == EINTR);
6664 for (jp = jobtab; jp < jobtab + njobs; jp++) {
6668 for (sp = jp->ps; sp < jp->ps + jp->nprocs; sp++) {
6671 if (sp->pid == pid) {
6672 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
6673 pid, sp->status, status));
6674 sp->status = status;
6677 if (sp->status == -1)
6679 else if (WIFSTOPPED(sp->status))
6682 if (stopped) { /* stopped or done */
6683 int state = done ? JOBDONE : JOBSTOPPED;
6685 if (jp->state != state) {
6686 TRACE(("Job %d: changing state from %d to %d\n",
6687 jp - jobtab + 1, jp->state, state));
6689 #ifdef CONFIG_ASH_JOB_CONTROL
6690 if (done && curjob == jp - jobtab + 1)
6691 curjob = 0; /* no current job */
6698 if (!rootshell || !iflag || (job && thisjob == job)) {
6699 core = WCOREDUMP(status);
6700 #ifdef CONFIG_ASH_JOB_CONTROL
6701 if (WIFSTOPPED(status))
6702 sig = WSTOPSIG(status);
6705 if (WIFEXITED(status))
6708 sig = WTERMSIG(status);
6710 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6712 out2fmt("%d: ", pid);
6713 #ifdef CONFIG_ASH_JOB_CONTROL
6714 if (sig == SIGTSTP && rootshell && iflag)
6715 out2fmt("%%%ld ", (long) (job - jobtab + 1));
6717 if (sig < NSIG && sys_siglist[sig])
6718 out2str(sys_siglist[sig]);
6720 out2fmt("Signal %d", sig);
6722 out2str(" - core dumped");
6725 TRACE(("Not printing status: status=%d, sig=%d\n", status, sig));
6728 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell,
6731 thisjob->changed = 1;
6740 * return 1 if there are stopped jobs, otherwise 0
6742 static int stoppedjobs(void)
6749 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6752 if (jp->state == JOBSTOPPED) {
6753 out2str("You have stopped jobs.\n");
6763 * Return a string identifying a command (to be printed by the
6767 static char *cmdnextc;
6768 static int cmdnleft;
6770 #define MAXCMDTEXT 200
6772 static void cmdputs(const char *s)
6783 while ((c = *p++) != '\0') {
6786 else if (c == CTLVAR) {
6791 } else if (c == '=' && subtype != 0) {
6792 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
6794 } else if (c == CTLENDVAR) {
6796 } else if (c == CTLBACKQ || c == CTLBACKQ + CTLQUOTE)
6797 cmdnleft++; /* ignore it */
6800 if (--cmdnleft <= 0) {
6810 #define CMDTXT_TABLE
6813 * To collect a lot of redundant code in cmdtxt() case statements, we
6814 * implement a mini language here. Each type of node struct has an
6815 * associated instruction sequence that operates on its members via
6816 * their offsets. The instruction are pack in unsigned chars with
6817 * format IIDDDDDE where the bits are
6818 * I : part of the instruction opcode, which are
6819 * 00 : member is a pointer to another node -- process it recursively
6820 * 40 : member is a pointer to a char string -- output it
6821 * 80 : output the string whose index is stored in the data field
6822 * CC : flag signaling that this case needs external processing
6823 * D : data - either the (shifted) index of a fixed string to output or
6824 * the actual offset of the member to operate on in the struct
6825 * (since we assume bit 0 is set, the offset is not shifted)
6826 * E : flag signaling end of instruction sequence
6828 * WARNING: In order to handle larger offsets for 64bit archs, this code
6829 * assumes that no offset can be an odd number and stores the
6830 * end-of-instructions flag in bit 0.
6833 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
6834 #define CMDTXT_CHARPTR 0x40
6835 #define CMDTXT_STRING 0x80
6836 #define CMDTXT_SPECIAL 0xC0
6837 #define CMDTXT_OFFSETMASK 0x3E
6839 static const char *const cmdtxt_strings[] = {
6840 /* 0 1 2 3 4 5 6 7 */
6841 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
6842 /* 8 9 10 11 12 13 */
6843 "while ", "; do ", "; done", "until ", "for ", " in ...",
6845 "case ", "???", "() ...", "<<..."
6848 static const char *const redir_strings[] = {
6849 ">", "<", "<>", ">>", ">|", ">&", "<&"
6852 static const unsigned char cmdtxt_ops[] = {
6853 #define CMDTXT_NSEMI 0
6854 offsetof(union node, nbinary.ch1),
6856 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6857 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
6858 #define CMDTXT_NPIPE (CMDTXT_NCMD)
6859 #define CMDTXT_NCASE (CMDTXT_NCMD)
6860 #define CMDTXT_NTO (CMDTXT_NCMD)
6861 #define CMDTXT_NFROM (CMDTXT_NCMD)
6862 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
6863 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
6864 #define CMDTXT_NTOOV (CMDTXT_NCMD)
6865 #define CMDTXT_NTOFD (CMDTXT_NCMD)
6866 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
6868 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
6869 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
6870 offsetof(union node, nredir.n) | CMDTXT_NOMORE,
6871 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
6872 (1 * 2) | CMDTXT_STRING,
6873 offsetof(union node, nredir.n),
6874 (2 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6875 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
6876 offsetof(union node, nbinary.ch1),
6877 (3 * 2) | CMDTXT_STRING,
6878 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6879 #define CMDTXT_NOR (CMDTXT_NAND + 3)
6880 offsetof(union node, nbinary.ch1),
6881 (4 * 2) | CMDTXT_STRING,
6882 offsetof(union node, nbinary.ch2) | CMDTXT_NOMORE,
6883 #define CMDTXT_NIF (CMDTXT_NOR + 3)
6884 (5 * 2) | CMDTXT_STRING,
6885 offsetof(union node, nif.test),
6886 (6 * 2) | CMDTXT_STRING,
6887 offsetof(union node, nif.ifpart),
6888 (7 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6889 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
6890 (8 * 2) | CMDTXT_STRING,
6891 offsetof(union node, nbinary.ch1),
6892 (9 * 2) | CMDTXT_STRING,
6893 offsetof(union node, nbinary.ch2),
6894 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6895 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
6896 (11 * 2) | CMDTXT_STRING,
6897 offsetof(union node, nbinary.ch1),
6898 (9 * 2) | CMDTXT_STRING,
6899 offsetof(union node, nbinary.ch2),
6900 (10 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6901 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
6902 (12 * 2) | CMDTXT_STRING,
6903 offsetof(union node, nfor.var) | CMDTXT_CHARPTR,
6904 (13 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6905 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
6906 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
6907 (15 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6908 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
6909 offsetof(union node, narg.text) | CMDTXT_CHARPTR,
6910 (16 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6911 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
6912 offsetof(union node, narg.text) | CMDTXT_CHARPTR | CMDTXT_NOMORE,
6913 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
6914 #define CMDTXT_NXHERE (CMDTXT_NHERE)
6915 (17 * 2) | CMDTXT_STRING | CMDTXT_NOMORE,
6918 #if CMDTXT_NXHERE != 36
6919 #error CMDTXT_NXHERE
6922 static const unsigned char cmdtxt_ops_index[26] = {
6951 static void cmdtxt(const union node *n)
6958 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
6959 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
6961 if (*p & CMDTXT_STRING) { /* output fixed string */
6962 cmdputs(cmdtxt_strings
6963 [((int) (*p & CMDTXT_OFFSETMASK) >> 1)]);
6965 const char *pf = ((const char *) n)
6966 + ((int) (*p & CMDTXT_OFFSETMASK));
6968 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
6969 cmdputs(*((const char **) pf));
6970 } else { /* output field */
6971 cmdtxt(*((const union node **) pf));
6974 } while (!(*p++ & CMDTXT_NOMORE));
6975 } else if (n->type == NCMD) {
6978 for (np = n->ncmd.args; np; np = np->narg.next) {
6983 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
6987 } else if (n->type == NPIPE) {
6988 struct nodelist *lp;
6990 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
6995 } else if (n->type == NCASE) {
6996 cmdputs(cmdtxt_strings[14]);
6997 cmdputs(n->ncase.expr->narg.text);
6998 cmdputs(cmdtxt_strings[13]);
7000 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7001 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7006 assert((n->type >= NTO) && (n->type <= NFROMFD));
7009 p = redir_strings[n->type - NTO];
7010 if (n->nfile.fd != ('>' == *p)) {
7011 s[0] = n->nfile.fd + '0';
7016 if (n->type >= NTOFD) {
7017 s[0] = n->ndup.dupfd + '0';
7021 cmdtxt(n->nfile.fname);
7025 #else /* CMDTXT_TABLE */
7026 static void cmdtxt(const union node *n)
7029 struct nodelist *lp;
7038 cmdtxt(n->nbinary.ch1);
7040 cmdtxt(n->nbinary.ch2);
7043 cmdtxt(n->nbinary.ch1);
7045 cmdtxt(n->nbinary.ch2);
7048 cmdtxt(n->nbinary.ch1);
7050 cmdtxt(n->nbinary.ch2);
7053 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
7061 cmdtxt(n->nredir.n);
7066 cmdtxt(n->nredir.n);
7070 cmdtxt(n->nif.test);
7072 cmdtxt(n->nif.ifpart);
7081 cmdtxt(n->nbinary.ch1);
7083 cmdtxt(n->nbinary.ch2);
7088 cmdputs(n->nfor.var);
7093 cmdputs(n->ncase.expr->narg.text);
7097 cmdputs(n->narg.text);
7101 for (np = n->ncmd.args; np; np = np->narg.next) {
7106 for (np = n->ncmd.redirect; np; np = np->nfile.next) {
7112 cmdputs(n->narg.text);
7143 if (n->nfile.fd != i) {
7144 s[0] = n->nfile.fd + '0';
7149 if (n->type == NTOFD || n->type == NFROMFD) {
7150 s[0] = n->ndup.dupfd + '0';
7154 cmdtxt(n->nfile.fname);
7166 #endif /* CMDTXT_TABLE */
7168 static char *commandtext(const union node *n)
7172 cmdnextc = name = xmalloc(MAXCMDTEXT);
7173 cmdnleft = MAXCMDTEXT - 4;
7180 #ifdef CONFIG_ASH_MAIL
7183 * Routines to check for mail.
7187 #define MAXMBOXES 10
7190 static int nmboxes; /* number of mailboxes */
7191 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7196 * Print appropriate message(s) if mail has arrived. If the argument is
7197 * nozero, then the value of MAIL has changed, so we just update the
7201 static void chkmail(int silent)
7207 struct stackmark smark;
7214 setstackmark(&smark);
7215 mpath = mpathset()? mpathval() : mailval();
7216 for (i = 0; i < nmboxes; i++) {
7217 p = padvance(&mpath, nullstr);
7222 for (q = p; *q; q++);
7227 q[-1] = '\0'; /* delete trailing '/' */
7228 if (stat(p, &statb) < 0)
7230 if (statb.st_size > mailtime[i] && !silent) {
7231 out2fmt(snlfmt, pathopt ? pathopt : "you have mail");
7233 mailtime[i] = statb.st_size;
7236 popstackmark(&smark);
7239 #endif /* CONFIG_ASH_MAIL */
7244 static short profile_buf[16384];
7248 static int isloginsh = 0;
7250 static void read_profile(const char *);
7251 static void cmdloop(int);
7252 static void options(int);
7253 static void setoption(int, int);
7254 static void procargs(int, char **);
7258 * Main routine. We initialize things, parse the arguments, execute
7259 * profiles if we're a login shell, and then call cmdloop to execute
7260 * commands. The setjmp call sets up the location to jump to when an
7261 * exception occurs. When an exception occurs the variable "state"
7262 * is used to figure out how far we had gotten.
7265 int ash_main(int argc, char **argv)
7267 struct jmploc jmploc;
7268 struct stackmark smark;
7272 BLTINCMD = find_builtin("builtin");
7273 EXECCMD = find_builtin("exec");
7274 EVALCMD = find_builtin("eval");
7276 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7282 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7284 #if defined(linux) || defined(__GNU__)
7285 signal(SIGCHLD, SIG_DFL);
7288 if (setjmp(jmploc.loc)) {
7291 * When a shell procedure is executed, we raise the
7292 * exception EXSHELLPROC to clean up before executing
7293 * the shell procedure.
7295 if (exception == EXSHELLPROC) {
7301 if (exception == EXEXEC) {
7302 exitstatus = exerrno;
7303 } else if (exception == EXERROR) {
7306 if (state == 0 || iflag == 0 || !rootshell)
7307 exitshell(exitstatus);
7310 if (exception == EXINT) {
7313 popstackmark(&smark);
7314 FORCEINTON; /* enable interrupts */
7317 else if (state == 2)
7319 else if (state == 3)
7327 trputs("Shell args: ");
7333 setstackmark(&smark);
7334 procargs(argc, argv);
7335 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7337 const char *hp = lookupvar("HISTFILE");
7340 hp = lookupvar("HOME");
7342 char *defhp = concat_path_file(hp, ".ash_history");
7343 setvar("HISTFILE", defhp, 0);
7349 if (argv[0] && argv[0][0] == '-')
7353 read_profile("/etc/profile");
7356 read_profile(".profile");
7361 if (getuid() == geteuid() && getgid() == getegid()) {
7363 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7365 read_profile(shinit);
7372 if (sflag == 0 || minusc) {
7373 static const char sigs[] = {
7374 SIGINT, SIGQUIT, SIGHUP,
7381 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])))
7384 for (i = 0; i < SIGSSIZE; i++)
7389 evalstring(minusc, 0);
7391 if (sflag || minusc == NULL) {
7392 state4: /* XXX ??? - why isn't this before the "if" statement */
7393 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7395 const char *hp = lookupvar("HISTFILE");
7398 load_history ( hp );
7406 exitshell(exitstatus);
7412 * Read and execute commands. "Top" is nonzero for the top level command
7413 * loop; it turns on prompting if the shell is interactive.
7416 static void cmdloop(int top)
7419 struct stackmark smark;
7423 TRACE(("cmdloop(%d) called\n", top));
7424 setstackmark(&smark);
7432 #ifdef CONFIG_ASH_MAIL
7437 n = parsecmd(inter);
7438 /* showtree(n); DEBUG */
7440 if (!top || numeof >= 50)
7442 if (!stoppedjobs()) {
7445 out2str("\nUse \"exit\" to leave shell.\n");
7448 } else if (n != NULL && nflag == 0) {
7449 job_warning = (job_warning == 2) ? 1 : 0;
7453 popstackmark(&smark);
7454 setstackmark(&smark);
7455 if (evalskip == SKIPFILE) {
7460 popstackmark(&smark);
7466 * Read /etc/profile or .profile. Return on error.
7469 static void read_profile(const char *name)
7476 if ((fd = open(name, O_RDONLY)) >= 0)
7481 /* -q turns off -x and -v just when executing init files */
7482 /* Note: Might do a little redundant work, but reduces code size. */
7497 * Read a file containing shell functions.
7500 static void readcmdfile(const char *name)
7505 if ((fd = open(name, O_RDONLY)) >= 0)
7508 error("Can't open %s", name);
7517 * Take commands from a file. To be compatable we should do a path
7518 * search for the file, which is necessary to find sub-commands.
7521 static inline char *find_dot_file(char *mybasename)
7524 const char *path = pathval();
7527 /* don't try this for absolute or relative paths */
7528 if (strchr(mybasename, '/'))
7531 while ((fullname = padvance(&path, mybasename)) != NULL) {
7532 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7534 * Don't bother freeing here, since it will
7535 * be freed by the caller.
7539 stunalloc(fullname);
7542 /* not found in the PATH */
7543 error("%s: not found", mybasename);
7547 static int dotcmd(int argc, char **argv)
7550 volatile struct shparam saveparam;
7554 for (sp = cmdenviron; sp; sp = sp->next)
7555 setvareq(bb_xstrdup(sp->text), VSTRFIXED | VTEXTFIXED);
7557 if (argc >= 2) { /* That's what SVR2 does */
7559 struct stackmark smark;
7561 setstackmark(&smark);
7562 fullname = find_dot_file(argv[1]);
7565 saveparam = shellparam;
7566 shellparam.malloc = 0;
7567 shellparam.nparam = argc - 2;
7568 shellparam.p = argv + 2;
7571 setinputfile(fullname, 1);
7572 commandname = fullname;
7577 freeparam(&shellparam);
7578 shellparam = saveparam;
7581 popstackmark(&smark);
7587 static int exitcmd(int argc, char **argv)
7593 exitstatus = number(argv[1]);
7595 exitstatus = oexitstatus;
7596 exitshell(exitstatus);
7600 static pointer stalloc(int nbytes)
7604 nbytes = ALIGN(nbytes);
7605 if (nbytes > stacknleft) {
7607 struct stack_block *sp;
7610 if (blocksize < MINSIZE)
7611 blocksize = MINSIZE;
7613 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7615 stacknxt = sp->space;
7616 stacknleft = blocksize;
7622 stacknleft -= nbytes;
7627 static void stunalloc(pointer p)
7630 if (p == NULL) { /*DEBUG */
7631 write(2, "stunalloc\n", 10);
7635 if (!(stacknxt >= (char *) p && (char *) p >= stackp->space)) {
7638 stacknleft += stacknxt - (char *) p;
7643 static void setstackmark(struct stackmark *mark)
7645 mark->stackp = stackp;
7646 mark->stacknxt = stacknxt;
7647 mark->stacknleft = stacknleft;
7648 mark->marknext = markp;
7653 static void popstackmark(struct stackmark *mark)
7655 struct stack_block *sp;
7658 markp = mark->marknext;
7659 while (stackp != mark->stackp) {
7664 stacknxt = mark->stacknxt;
7665 stacknleft = mark->stacknleft;
7671 * When the parser reads in a string, it wants to stick the string on the
7672 * stack and only adjust the stack pointer when it knows how big the
7673 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7674 * of space on top of the stack and stackblocklen returns the length of
7675 * this block. Growstackblock will grow this space by at least one byte,
7676 * possibly moving it (like realloc). Grabstackblock actually allocates the
7677 * part of the block that has been used.
7680 static void growstackblock(void)
7683 int newlen = ALIGN(stacknleft * 2 + 100);
7684 char *oldspace = stacknxt;
7685 int oldlen = stacknleft;
7686 struct stack_block *sp;
7687 struct stack_block *oldstackp;
7689 if (stacknxt == stackp->space && stackp != &stackbase) {
7694 sp = xrealloc((pointer) sp,
7695 sizeof(struct stack_block) - MINSIZE + newlen);
7698 stacknxt = sp->space;
7699 stacknleft = newlen;
7701 /* Stack marks pointing to the start of the old block
7702 * must be relocated to point to the new block
7704 struct stackmark *xmark;
7707 while (xmark != NULL && xmark->stackp == oldstackp) {
7708 xmark->stackp = stackp;
7709 xmark->stacknxt = stacknxt;
7710 xmark->stacknleft = stacknleft;
7711 xmark = xmark->marknext;
7716 p = stalloc(newlen);
7717 memcpy(p, oldspace, oldlen);
7718 stacknxt = p; /* free the space */
7719 stacknleft += newlen; /* we just allocated */
7725 static inline void grabstackblock(int len)
7735 * The following routines are somewhat easier to use that the above.
7736 * The user declares a variable of type STACKSTR, which may be declared
7737 * to be a register. The macro STARTSTACKSTR initializes things. Then
7738 * the user uses the macro STPUTC to add characters to the string. In
7739 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7740 * grown as necessary. When the user is done, she can just leave the
7741 * string there and refer to it using stackblock(). Or she can allocate
7742 * the space for it using grabstackstr(). If it is necessary to allow
7743 * someone else to use the stack temporarily and then continue to grow
7744 * the string, the user should use grabstack to allocate the space, and
7745 * then call ungrabstr(p) to return to the previous mode of operation.
7747 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7748 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7749 * is space for at least one character.
7753 static char *growstackstr(void)
7755 int len = stackblocksize();
7757 if (herefd >= 0 && len >= 1024) {
7758 xwrite(herefd, stackblock(), len);
7759 sstrnleft = len - 1;
7760 return stackblock();
7763 sstrnleft = stackblocksize() - len - 1;
7764 return stackblock() + len;
7769 * Called from CHECKSTRSPACE.
7772 static char *makestrspace(size_t newlen)
7774 int len = stackblocksize() - sstrnleft;
7778 sstrnleft = stackblocksize() - len;
7779 } while (sstrnleft < newlen);
7780 return stackblock() + len;
7785 static void ungrabstackstr(char *s, char *p)
7787 stacknleft += stacknxt - s;
7789 sstrnleft = stacknleft - (p - s);
7793 * Miscelaneous builtins.
7799 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
7800 typedef long rlim_t;
7806 * The read builtin. The -e option causes backslashes to escape the
7807 * following character.
7809 * This uses unbuffered input, which may be avoidable in some cases.
7812 static int readcmd(int argc, char **argv)
7827 while ((i = nextopt("p:r")) != '\0') {
7833 if (prompt && isatty(0)) {
7834 out2str(prompt); /* read without cmdedit */
7837 if (*(ap = argptr) == NULL)
7839 if ((ifs = bltinlookup("IFS")) == NULL)
7846 if (read(0, &c, 1) != 1) {
7858 if (!rflag && c == '\\') {
7864 if (startword && *ifs == ' ' && strchr(ifs, c)) {
7868 if (backslash && c == '\\') {
7869 if (read(0, &c, 1) != 1) {
7874 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
7876 setvar(*ap, stackblock(), 0);
7885 /* Remove trailing blanks */
7886 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
7888 setvar(*ap, stackblock(), 0);
7889 while (*++ap != NULL)
7890 setvar(*ap, nullstr, 0);
7896 static int umaskcmd(int argc, char **argv)
7898 static const char permuser[3] = "ugo";
7899 static const char permmode[3] = "rwx";
7900 static const short int permmask[] = {
7901 S_IRUSR, S_IWUSR, S_IXUSR,
7902 S_IRGRP, S_IWGRP, S_IXGRP,
7903 S_IROTH, S_IWOTH, S_IXOTH
7909 int symbolic_mode = 0;
7911 while (nextopt("S") != '\0') {
7920 if ((ap = *argptr) == NULL) {
7921 if (symbolic_mode) {
7925 for (i = 0; i < 3; i++) {
7930 for (j = 0; j < 3; j++) {
7931 if ((mask & permmask[3 * i + j]) == 0) {
7940 printf("%.4o\n", mask);
7943 if (is_digit((unsigned char) *ap)) {
7946 if (*ap >= '8' || *ap < '0')
7947 error("Illegal number: %s", argv[1]);
7948 mask = (mask << 3) + (*ap - '0');
7949 } while (*++ap != '\0');
7952 mask = ~mask & 0777;
7953 if (!bb_parse_mode(ap, &mask)) {
7954 error("Illegal mode: %s", ap);
7956 umask(~mask & 0777);
7965 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
7966 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
7967 * ash by J.T. Conklin.
7975 short factor; /* multiply by to get rlim_{cur,max} values */
7978 static const struct limits limits[] = {
7980 {"time(seconds)", RLIMIT_CPU, 1},
7983 {"file(blocks)", RLIMIT_FSIZE, 512},
7986 {"data(kbytes)", RLIMIT_DATA, 1024},
7989 {"stack(kbytes)", RLIMIT_STACK, 1024},
7992 {"coredump(blocks)", RLIMIT_CORE, 512},
7995 {"memory(kbytes)", RLIMIT_RSS, 1024},
7997 #ifdef RLIMIT_MEMLOCK
7998 {"locked memory(kbytes)", RLIMIT_MEMLOCK, 1024},
8001 {"process(processes)", RLIMIT_NPROC, 1},
8003 #ifdef RLIMIT_NOFILE
8004 {"nofiles(descriptors)", RLIMIT_NOFILE, 1},
8007 {"vmemory(kbytes)", RLIMIT_VMEM, 1024},
8010 {"swap(kbytes)", RLIMIT_SWAP, 1024},
8015 static int ulimitcmd(int argc, char **argv)
8017 static const char unlimited_string[] = "unlimited";
8020 enum { SOFT = 0x1, HARD = 0x2 } how = SOFT | HARD;
8021 const struct limits *l;
8024 struct rlimit limit;
8028 while ((optc = nextopt("HSa"
8047 #ifdef RLIMIT_MEMLOCK
8053 #ifdef RLIMIT_NOFILE
8065 } else if (optc == 'S') {
8067 } else if (optc == 'a') {
8074 for (l = limits; l->name; l++) {
8075 if (l->name[0] == what)
8077 if (l->name[1] == 'w' && what == 'w')
8081 set = *argptr ? 1 : 0;
8085 if (all || argptr[1])
8086 error("too many arguments");
8087 if (strcmp(p, unlimited_string) == 0)
8088 val = RLIM_INFINITY;
8092 while ((c = *p++) >= '0' && c <= '9') {
8093 val = (val * 10) + (long) (c - '0');
8094 if (val < (rlim_t) 0)
8098 error("bad number");
8104 for (l = limits; l->name; l++) {
8105 printf("%-20s ", l->name);
8106 getrlimit(l->cmd, &limit);
8109 val = limit.rlim_cur;
8110 else if (how & HARD)
8111 val = limit.rlim_max;
8113 if (val == RLIM_INFINITY)
8114 puts(unlimited_string);
8117 printf("%lld\n", (long long) val);
8130 getrlimit(l->cmd, &limit);
8132 limit.rlim_max = val;
8134 limit.rlim_cur = val;
8135 if (setrlimit(l->cmd, &limit) < 0)
8136 error("error setting limit (%m)");
8141 * prefix -- see if pfx is a prefix of string.
8144 static int prefix(char const *pfx, char const *string)
8147 if (*pfx++ != *string++)
8154 * Return true if s is a string of digits, and save munber in intptr
8158 static int is_number(const char *p, int *intptr)
8166 ret += digit_val(*p);
8168 } while (*p != '\0');
8175 * Convert a string of digits to an integer, printing an error message on
8179 static int number(const char *s)
8183 if (!is_number(s, &i))
8184 error("Illegal number: %s", s);
8189 * Produce a possibly single quoted string suitable as input to the shell.
8190 * The return string is allocated on the stack.
8193 static char *single_quote(const char *s)
8201 size_t len1, len1p, len2, len2p;
8203 len1 = strcspn(s, "'");
8204 len2 = strspn(s + len1, "'");
8206 len1p = len1 ? len1 + 2 : len1;
8207 len2p = len2 + ((len2 < 2) ? len2 : 2);
8209 CHECKSTRSPACE(len1p + len2p + 1, p);
8214 memcpy(p + 1, s, len1);
8222 memcpy(q + 1, s, len2);
8225 } else if (len2 == 1) {
8231 STADJUST(len1p + len2p, p);
8236 return grabstackstr(p);
8240 * Routine for dealing with parsed shell commands.
8244 static void sizenodelist(const struct nodelist *);
8245 static struct nodelist *copynodelist(const struct nodelist *);
8246 static char *nodesavestr(const char *);
8248 #define CALCSIZE_TABLE
8249 #define COPYNODE_TABLE
8250 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8252 * To collect a lot of redundant code in case statements for copynode()
8253 * and calcsize(), we implement a mini language here. Each type of node
8254 * struct has an associated instruction sequence that operates on its
8255 * members via their offsets. The instruction are pack in unsigned chars
8256 * with format IIDDDDDE where the bits are
8257 * I : part of the instruction opcode, which are
8258 * 00 : member is a pointer to another node
8259 * 40 : member is an integer
8260 * 80 : member is a pointer to a nodelist
8261 * CC : member is a pointer to a char string
8262 * D : data - the actual offset of the member to operate on in the struct
8263 * (since we assume bit 0 is set, it is not shifted)
8264 * E : flag signaling end of instruction sequence
8266 * WARNING: In order to handle larger offsets for 64bit archs, this code
8267 * assumes that no offset can be an odd number and stores the
8268 * end-of-instructions flag in bit 0.
8271 #define NODE_INTEGER 0x40
8272 #define NODE_NODELIST 0x80
8273 #define NODE_CHARPTR 0xC0
8274 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned) */
8275 #define NODE_MBRMASK 0xC0
8276 #define NODE_OFFSETMASK 0x3E
8278 static const unsigned char copynode_ops[35] = {
8279 #define COPYNODE_OPS0 0
8280 offsetof(union node, nbinary.ch2),
8281 offsetof(union node, nbinary.ch1) | NODE_NOMORE,
8282 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8283 offsetof(union node, ncmd.redirect),
8284 offsetof(union node, ncmd.args),
8285 offsetof(union node, ncmd.assign),
8286 offsetof(union node, ncmd.backgnd) | NODE_INTEGER | NODE_NOMORE,
8287 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8288 offsetof(union node, npipe.cmdlist) | NODE_NODELIST,
8289 offsetof(union node, npipe.backgnd) | NODE_INTEGER | NODE_NOMORE,
8290 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8291 offsetof(union node, nredir.redirect),
8292 offsetof(union node, nredir.n) | NODE_NOMORE,
8293 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8294 offsetof(union node, nif.elsepart),
8295 offsetof(union node, nif.ifpart),
8296 offsetof(union node, nif.test) | NODE_NOMORE,
8297 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8298 offsetof(union node, nfor.var) | NODE_CHARPTR,
8299 offsetof(union node, nfor.body),
8300 offsetof(union node, nfor.args) | NODE_NOMORE,
8301 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8302 offsetof(union node, ncase.cases),
8303 offsetof(union node, ncase.expr) | NODE_NOMORE,
8304 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8305 offsetof(union node, nclist.body),
8306 offsetof(union node, nclist.pattern),
8307 offsetof(union node, nclist.next) | NODE_NOMORE,
8308 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8309 offsetof(union node, narg.backquote) | NODE_NODELIST,
8310 offsetof(union node, narg.text) | NODE_CHARPTR,
8311 offsetof(union node, narg.next) | NODE_NOMORE,
8312 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8313 offsetof(union node, nfile.fname),
8314 offsetof(union node, nfile.fd) | NODE_INTEGER,
8315 offsetof(union node, nfile.next) | NODE_NOMORE,
8316 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8317 offsetof(union node, ndup.vname),
8318 offsetof(union node, ndup.dupfd) | NODE_INTEGER,
8319 offsetof(union node, ndup.fd) | NODE_INTEGER,
8320 offsetof(union node, ndup.next) | NODE_NOMORE,
8321 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8322 offsetof(union node, nhere.doc),
8323 offsetof(union node, nhere.fd) | NODE_INTEGER,
8324 offsetof(union node, nhere.next) | NODE_NOMORE,
8325 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8326 offsetof(union node, nnot.com) | NODE_NOMORE,
8329 #if COPYNODE_OPS12 != 34
8330 #error COPYNODE_OPS12 is incorrect
8333 static const unsigned char copynode_ops_index[26] = {
8334 COPYNODE_OPS0, /* NSEMI */
8335 COPYNODE_OPS1, /* NCMD */
8336 COPYNODE_OPS2, /* NPIPE */
8337 COPYNODE_OPS3, /* NREDIR */
8338 COPYNODE_OPS3, /* NBACKGND */
8339 COPYNODE_OPS3, /* NSUBSHELL */
8340 COPYNODE_OPS0, /* NAND */
8341 COPYNODE_OPS0, /* NOR */
8342 COPYNODE_OPS4, /* NIF */
8343 COPYNODE_OPS0, /* NWHILE */
8344 COPYNODE_OPS0, /* NUNTIL */
8345 COPYNODE_OPS5, /* NFOR */
8346 COPYNODE_OPS6, /* NCASE */
8347 COPYNODE_OPS7, /* NCLIST */
8348 COPYNODE_OPS8, /* NDEFUN */
8349 COPYNODE_OPS8, /* NARG */
8350 COPYNODE_OPS9, /* NTO */
8351 COPYNODE_OPS9, /* NFROM */
8352 COPYNODE_OPS9, /* NFROMTO */
8353 COPYNODE_OPS9, /* NAPPEND */
8354 COPYNODE_OPS9, /* NTOOV */
8355 COPYNODE_OPS10, /* NTOFD */
8356 COPYNODE_OPS10, /* NFROMFD */
8357 COPYNODE_OPS11, /* NHERE */
8358 COPYNODE_OPS11, /* NXHERE */
8359 COPYNODE_OPS12, /* NNOT */
8362 #if NODE_CHARPTR != NODE_MBRMASK
8363 #error NODE_CHARPTR != NODE_MBRMASK!!!
8365 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8367 #ifdef COPYNODE_TABLE
8368 static union node *copynode(const union node *n)
8371 const unsigned char *p;
8377 new->type = n->type;
8378 funcblock = (char *) funcblock + (int) nodesize[n->type];
8379 p = copynode_ops + (int) copynode_ops_index[n->type];
8381 char *nn = ((char *) new) + ((int) (*p & NODE_OFFSETMASK));
8382 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8384 if (!(*p & NODE_MBRMASK)) { /* standard node */
8385 *((union node **) nn) = copynode(*((const union node **) no));
8386 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8387 *((const char **) nn) = nodesavestr(*((const char **) no));
8388 } else if (*p & NODE_NODELIST) { /* nodelist */
8389 *((struct nodelist **) nn)
8390 = copynodelist(*((const struct nodelist **) no));
8391 } else { /* integer */
8392 *((int *) nn) = *((int *) no);
8394 } while (!(*p++ & NODE_NOMORE));
8397 #else /* COPYNODE_TABLE */
8398 static union node *copynode(const union node *n)
8405 funcblock = (char *) funcblock + nodesize[n->type];
8412 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8413 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8416 new->ncmd.redirect = copynode(n->ncmd.redirect);
8417 new->ncmd.args = copynode(n->ncmd.args);
8418 new->ncmd.assign = copynode(n->ncmd.assign);
8419 new->ncmd.backgnd = n->ncmd.backgnd;
8422 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8423 new->npipe.backgnd = n->npipe.backgnd;
8428 new->nredir.redirect = copynode(n->nredir.redirect);
8429 new->nredir.n = copynode(n->nredir.n);
8432 new->nif.elsepart = copynode(n->nif.elsepart);
8433 new->nif.ifpart = copynode(n->nif.ifpart);
8434 new->nif.test = copynode(n->nif.test);
8437 new->nfor.var = nodesavestr(n->nfor.var);
8438 new->nfor.body = copynode(n->nfor.body);
8439 new->nfor.args = copynode(n->nfor.args);
8442 new->ncase.cases = copynode(n->ncase.cases);
8443 new->ncase.expr = copynode(n->ncase.expr);
8446 new->nclist.body = copynode(n->nclist.body);
8447 new->nclist.pattern = copynode(n->nclist.pattern);
8448 new->nclist.next = copynode(n->nclist.next);
8452 new->narg.backquote = copynodelist(n->narg.backquote);
8453 new->narg.text = nodesavestr(n->narg.text);
8454 new->narg.next = copynode(n->narg.next);
8461 new->nfile.fname = copynode(n->nfile.fname);
8462 new->nfile.fd = n->nfile.fd;
8463 new->nfile.next = copynode(n->nfile.next);
8467 new->ndup.vname = copynode(n->ndup.vname);
8468 new->ndup.dupfd = n->ndup.dupfd;
8469 new->ndup.fd = n->ndup.fd;
8470 new->ndup.next = copynode(n->ndup.next);
8474 new->nhere.doc = copynode(n->nhere.doc);
8475 new->nhere.fd = n->nhere.fd;
8476 new->nhere.next = copynode(n->nhere.next);
8479 new->nnot.com = copynode(n->nnot.com);
8482 new->type = n->type;
8485 #endif /* COPYNODE_TABLE */
8487 #ifdef CALCSIZE_TABLE
8488 static void calcsize(const union node *n)
8490 const unsigned char *p;
8494 funcblocksize += (int) nodesize[n->type];
8496 p = copynode_ops + (int) copynode_ops_index[n->type];
8498 const char *no = ((const char *) n) + ((int) (*p & NODE_OFFSETMASK));
8500 if (!(*p & NODE_MBRMASK)) { /* standard node */
8501 calcsize(*((const union node **) no));
8502 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8503 funcstringsize += strlen(*((const char **) no)) + 1;
8504 } else if (*p & NODE_NODELIST) { /* nodelist */
8505 sizenodelist(*((const struct nodelist **) no));
8506 } /* else integer -- ignore */
8507 } while (!(*p++ & NODE_NOMORE));
8509 #else /* CALCSIZE_TABLE */
8510 static void calcsize(const union node *n)
8514 funcblocksize += nodesize[n->type];
8521 calcsize(n->nbinary.ch2);
8522 calcsize(n->nbinary.ch1);
8525 calcsize(n->ncmd.redirect);
8526 calcsize(n->ncmd.args);
8527 calcsize(n->ncmd.assign);
8530 sizenodelist(n->npipe.cmdlist);
8535 calcsize(n->nredir.redirect);
8536 calcsize(n->nredir.n);
8539 calcsize(n->nif.elsepart);
8540 calcsize(n->nif.ifpart);
8541 calcsize(n->nif.test);
8544 funcstringsize += strlen(n->nfor.var) + 1;
8545 calcsize(n->nfor.body);
8546 calcsize(n->nfor.args);
8549 calcsize(n->ncase.cases);
8550 calcsize(n->ncase.expr);
8553 calcsize(n->nclist.body);
8554 calcsize(n->nclist.pattern);
8555 calcsize(n->nclist.next);
8559 sizenodelist(n->narg.backquote);
8560 funcstringsize += strlen(n->narg.text) + 1;
8561 calcsize(n->narg.next);
8568 calcsize(n->nfile.fname);
8569 calcsize(n->nfile.next);
8573 calcsize(n->ndup.vname);
8574 calcsize(n->ndup.next);
8578 calcsize(n->nhere.doc);
8579 calcsize(n->nhere.next);
8582 calcsize(n->nnot.com);
8586 #endif /* CALCSIZE_TABLE */
8588 static void sizenodelist(const struct nodelist *lp)
8591 funcblocksize += ALIGN(sizeof(struct nodelist));
8598 static struct nodelist *copynodelist(const struct nodelist *lp)
8600 struct nodelist *start;
8601 struct nodelist **lpp;
8606 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8607 (*lpp)->n = copynode(lp->n);
8609 lpp = &(*lpp)->next;
8616 static char *nodesavestr(const char *s)
8619 char *q = funcstring;
8620 char *rtn = funcstring;
8622 while ((*q++ = *p++) != '\0')
8628 #ifdef CONFIG_ASH_GETOPTS
8629 static int getopts(char *, char *, char **, int *, int *);
8633 * Process the shell command line arguments.
8636 static void procargs(int argc, char **argv)
8643 for (i = 0; i < NOPTS; i++)
8646 if (*argptr == NULL && minusc == NULL)
8648 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8652 for (i = 0; i < NOPTS; i++)
8653 if (optent_val(i) == 2)
8656 if (sflag == 0 && minusc == NULL) {
8657 commandname = argv[0];
8659 setinputfile(arg0, 0);
8662 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8663 if (argptr && minusc && *argptr)
8666 shellparam.p = argptr;
8667 shellparam.optind = 1;
8668 shellparam.optoff = -1;
8669 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8671 shellparam.nparam++;
8680 * Process shell options. The global variable argptr contains a pointer
8681 * to the argument list; we advance it past the options.
8684 static inline void minus_o(const char *name, int val)
8689 out1str("Current option settings\n");
8690 for (i = 0; i < NOPTS; i++)
8691 printf("%-16s%s\n", optent_name(optlist[i]),
8692 optent_val(i) ? "on" : "off");
8694 for (i = 0; i < NOPTS; i++)
8695 if (equal(name, optent_name(optlist[i]))) {
8696 setoption(optent_letter(optlist[i]), val);
8699 error("Illegal option -o %s", name);
8704 static void options(int cmdline)
8712 while ((p = *argptr) != NULL) {
8714 if ((c = *p++) == '-') {
8716 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8718 /* "-" means turn off -x and -v */
8721 /* "--" means reset params */
8722 else if (*argptr == NULL)
8725 break; /* "-" or "--" terminates options */
8727 } else if (c == '+') {
8733 while ((c = *p++) != '\0') {
8734 if (c == 'c' && cmdline) {
8737 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8741 if (q == NULL || minusc != NULL)
8742 error("Bad -c option");
8747 } else if (c == 'o') {
8748 minus_o(*argptr, val);
8751 } else if (cmdline && (c == '-')) { // long options
8752 if (strcmp(p, "login") == 0)
8763 static void setoption(int flag, int val)
8767 for (i = 0; i < NOPTS; i++)
8768 if (optent_letter(optlist[i]) == flag) {
8769 optent_val(i) = val;
8771 /* #%$ hack for ksh semantics */
8774 else if (flag == 'E')
8779 error("Illegal option -%c", flag);
8786 * Set the shell parameters.
8789 static void setparam(char **argv)
8795 for (nparam = 0; argv[nparam]; nparam++);
8796 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
8798 *ap++ = bb_xstrdup(*argv++);
8801 freeparam(&shellparam);
8802 shellparam.malloc = 1;
8803 shellparam.nparam = nparam;
8804 shellparam.p = newparam;
8805 shellparam.optind = 1;
8806 shellparam.optoff = -1;
8811 * Free the list of positional parameters.
8814 static void freeparam(volatile struct shparam *param)
8818 if (param->malloc) {
8819 for (ap = param->p; *ap; ap++)
8828 * The shift builtin command.
8831 static int shiftcmd(int argc, char **argv)
8838 n = number(argv[1]);
8839 if (n > shellparam.nparam)
8840 error("can't shift that many");
8842 shellparam.nparam -= n;
8843 for (ap1 = shellparam.p; --n >= 0; ap1++) {
8844 if (shellparam.malloc)
8848 while ((*ap2++ = *ap1++) != NULL);
8849 shellparam.optind = 1;
8850 shellparam.optoff = -1;
8858 * The set command builtin.
8861 static int setcmd(int argc, char **argv)
8864 return showvarscmd(argc, argv);
8868 if (*argptr != NULL) {
8876 static void getoptsreset(const char *value)
8878 shellparam.optind = number(value);
8879 shellparam.optoff = -1;
8882 #ifdef CONFIG_LOCALE_SUPPORT
8883 static void change_lc_all(const char *value)
8885 if (value != 0 && *value != 0)
8886 setlocale(LC_ALL, value);
8889 static void change_lc_ctype(const char *value)
8891 if (value != 0 && *value != 0)
8892 setlocale(LC_CTYPE, value);
8897 #ifdef CONFIG_ASH_GETOPTS
8899 * The getopts builtin. Shellparam.optnext points to the next argument
8900 * to be processed. Shellparam.optptr points to the next character to
8901 * be processed in the current argument. If shellparam.optnext is NULL,
8902 * then it's the first time getopts has been called.
8905 static int getoptscmd(int argc, char **argv)
8910 error("Usage: getopts optstring var [arg]");
8911 else if (argc == 3) {
8912 optbase = shellparam.p;
8913 if (shellparam.optind > shellparam.nparam + 1) {
8914 shellparam.optind = 1;
8915 shellparam.optoff = -1;
8919 if (shellparam.optind > argc - 2) {
8920 shellparam.optind = 1;
8921 shellparam.optoff = -1;
8925 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
8926 &shellparam.optoff);
8930 * Safe version of setvar, returns 1 on success 0 on failure.
8933 static int setvarsafe(const char *name, const char *val, int flags)
8935 struct jmploc jmploc;
8936 struct jmploc *volatile savehandler = handler;
8943 if (setjmp(jmploc.loc))
8947 setvar(name, val, flags);
8949 handler = savehandler;
8954 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind,
8962 char **optnext = optfirst + *myoptind - 1;
8964 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
8965 strlen(*(optnext - 1)) < *optoff)
8968 p = *(optnext - 1) + *optoff;
8969 if (p == NULL || *p == '\0') {
8970 /* Current word is done, advance */
8971 if (optnext == NULL)
8974 if (p == NULL || *p != '-' || *++p == '\0') {
8976 *myoptind = optnext - optfirst + 1;
8982 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
8987 for (q = optstr; *q != c;) {
8989 if (optstr[0] == ':') {
8992 err |= setvarsafe("OPTARG", s, 0);
8994 out2fmt("Illegal option -%c\n", c);
8995 (void) unsetvar("OPTARG");
9005 if (*p == '\0' && (p = *optnext) == NULL) {
9006 if (optstr[0] == ':') {
9009 err |= setvarsafe("OPTARG", s, 0);
9012 out2fmt("No arg for -%c option\n", c);
9013 (void) unsetvar("OPTARG");
9021 setvarsafe("OPTARG", p, 0);
9024 setvarsafe("OPTARG", "", 0);
9025 *myoptind = optnext - optfirst + 1;
9032 *optoff = p ? p - *(optnext - 1) : -1;
9033 snprintf(s, sizeof(s), "%d", *myoptind);
9034 err |= setvarsafe("OPTIND", s, VNOFUNC);
9037 err |= setvarsafe(optvar, s, 0);
9048 * XXX - should get rid of. have all builtins use getopt(3). the
9049 * library getopt must have the BSD extension static variable "optreset"
9050 * otherwise it can't be used within the shell safely.
9052 * Standard option processing (a la getopt) for builtin routines. The
9053 * only argument that is passed to nextopt is the option string; the
9054 * other arguments are unnecessary. It return the character, or '\0' on
9058 static int nextopt(const char *optstring)
9064 if ((p = optptr) == NULL || *p == '\0') {
9066 if (p == NULL || *p != '-' || *++p == '\0')
9069 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9073 for (q = optstring; *q != c;) {
9075 error("Illegal option -%c", c);
9080 if (*p == '\0' && (p = *argptr++) == NULL)
9081 error("No arg for -%c option", c);
9089 static void flushall()
9097 static void out2fmt(const char *fmt, ...)
9102 vfprintf(stderr, fmt, ap);
9107 * Version of write which resumes after a signal is caught.
9110 static int xwrite(int fd, const char *buf, int nbytes)
9119 i = write(fd, buf, n);
9125 } else if (i == 0) {
9128 } else if (errno != EINTR) {
9136 * Shell command parser.
9139 #define EOFMARKLEN 79
9144 struct heredoc *next; /* next here document in list */
9145 union node *here; /* redirection node */
9146 char *eofmark; /* string indicating end of input */
9147 int striptabs; /* if set, strip leading tabs */
9150 static struct heredoc *heredoclist; /* list of here documents to read */
9151 static int parsebackquote; /* nonzero if we are inside backquotes */
9152 static int doprompt; /* if set, prompt the user */
9153 static int needprompt; /* true if interactive and at start of line */
9154 static int lasttoken; /* last token read */
9156 static char *wordtext; /* text of last word returned by readtoken */
9158 static struct nodelist *backquotelist;
9159 static union node *redirnode;
9160 static struct heredoc *heredoc;
9161 static int quoteflag; /* set if (part of) last token was quoted */
9162 static int startlinno; /* line # where last token started */
9165 static union node *list(int);
9166 static union node *andor(void);
9167 static union node *pipeline(void);
9168 static union node *command(void);
9169 static union node *simplecmd(union node **rpp, union node *redir);
9170 static void parsefname(void);
9171 static void parseheredoc(void);
9172 static char peektoken(void);
9173 static int readtoken(void);
9174 static int xxreadtoken(void);
9175 static int readtoken1(int, int, const char *, int);
9176 static int noexpand(char *);
9177 static void synexpect(int) __attribute__ ((noreturn));
9178 static void synerror(const char *) __attribute__ ((noreturn));
9179 static void setprompt(int);
9183 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9184 * valid parse tree indicating a blank line.)
9187 static union node *parsecmd(int interact)
9192 doprompt = interact;
9208 static union node *list(int nlflag)
9210 union node *n1, *n2, *n3;
9214 if (nlflag == 0 && peektoken())
9220 if (tok == TBACKGND) {
9221 if (n2->type == NCMD || n2->type == NPIPE) {
9222 n2->ncmd.backgnd = 1;
9223 } else if (n2->type == NREDIR) {
9224 n2->type = NBACKGND;
9226 n3 = (union node *) stalloc(sizeof(struct nredir));
9227 n3->type = NBACKGND;
9229 n3->nredir.redirect = NULL;
9236 n3 = (union node *) stalloc(sizeof(struct nbinary));
9238 n3->nbinary.ch1 = n1;
9239 n3->nbinary.ch2 = n2;
9263 pungetc(); /* push back EOF on input */
9276 static union node *andor()
9278 union node *n1, *n2, *n3;
9284 if ((t = readtoken()) == TAND) {
9286 } else if (t == TOR) {
9294 n3 = (union node *) stalloc(sizeof(struct nbinary));
9296 n3->nbinary.ch1 = n1;
9297 n3->nbinary.ch2 = n2;
9304 static union node *pipeline()
9306 union node *n1, *n2, *pipenode;
9307 struct nodelist *lp, *prev;
9311 TRACE(("pipeline: entered\n"));
9312 if (readtoken() == TNOT) {
9318 if (readtoken() == TPIPE) {
9319 pipenode = (union node *) stalloc(sizeof(struct npipe));
9320 pipenode->type = NPIPE;
9321 pipenode->npipe.backgnd = 0;
9322 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9323 pipenode->npipe.cmdlist = lp;
9327 lp = (struct nodelist *) stalloc(sizeof(struct nodelist));
9331 } while (readtoken() == TPIPE);
9337 n2 = (union node *) stalloc(sizeof(struct nnot));
9347 static union node *command(void)
9349 union node *n1, *n2;
9350 union node *ap, **app;
9351 union node *cp, **cpp;
9352 union node *redir, **rpp;
9359 /* Check for redirection which may precede command */
9360 while (readtoken() == TREDIR) {
9361 *rpp = n2 = redirnode;
9362 rpp = &n2->nfile.next;
9367 switch (readtoken()) {
9369 n1 = (union node *) stalloc(sizeof(struct nif));
9371 n1->nif.test = list(0);
9372 if (readtoken() != TTHEN)
9374 n1->nif.ifpart = list(0);
9376 while (readtoken() == TELIF) {
9377 n2->nif.elsepart = (union node *) stalloc(sizeof(struct nif));
9378 n2 = n2->nif.elsepart;
9380 n2->nif.test = list(0);
9381 if (readtoken() != TTHEN)
9383 n2->nif.ifpart = list(0);
9385 if (lasttoken == TELSE)
9386 n2->nif.elsepart = list(0);
9388 n2->nif.elsepart = NULL;
9391 if (readtoken() != TFI)
9398 n1 = (union node *) stalloc(sizeof(struct nbinary));
9399 n1->type = (lasttoken == TWHILE) ? NWHILE : NUNTIL;
9400 n1->nbinary.ch1 = list(0);
9401 if ((got = readtoken()) != TDO) {
9402 TRACE(("expecting DO got %s %s\n", tokname(got),
9403 got == TWORD ? wordtext : ""));
9406 n1->nbinary.ch2 = list(0);
9407 if (readtoken() != TDONE)
9413 if (readtoken() != TWORD || quoteflag || !goodname(wordtext))
9414 synerror("Bad for loop variable");
9415 n1 = (union node *) stalloc(sizeof(struct nfor));
9417 n1->nfor.var = wordtext;
9419 if (readtoken() == TIN) {
9421 while (readtoken() == TWORD) {
9422 n2 = (union node *) stalloc(sizeof(struct narg));
9424 n2->narg.text = wordtext;
9425 n2->narg.backquote = backquotelist;
9427 app = &n2->narg.next;
9431 if (lasttoken != TNL && lasttoken != TSEMI)
9434 static char argvars[5] = { CTLVAR, VSNORMAL | VSQUOTE,
9437 n2 = (union node *) stalloc(sizeof(struct narg));
9439 n2->narg.text = argvars;
9440 n2->narg.backquote = NULL;
9441 n2->narg.next = NULL;
9444 * Newline or semicolon here is optional (but note
9445 * that the original Bourne shell only allowed NL).
9447 if (lasttoken != TNL && lasttoken != TSEMI)
9451 if (readtoken() != TDO)
9453 n1->nfor.body = list(0);
9454 if (readtoken() != TDONE)
9459 n1 = (union node *) stalloc(sizeof(struct ncase));
9461 if (readtoken() != TWORD)
9463 n1->ncase.expr = n2 = (union node *) stalloc(sizeof(struct narg));
9465 n2->narg.text = wordtext;
9466 n2->narg.backquote = backquotelist;
9467 n2->narg.next = NULL;
9470 } while (readtoken() == TNL);
9471 if (lasttoken != TIN)
9472 synerror("expecting \"in\"");
9473 cpp = &n1->ncase.cases;
9474 checkkwd = 2, readtoken();
9476 if (lasttoken == TLP)
9478 *cpp = cp = (union node *) stalloc(sizeof(struct nclist));
9480 app = &cp->nclist.pattern;
9482 *app = ap = (union node *) stalloc(sizeof(struct narg));
9484 ap->narg.text = wordtext;
9485 ap->narg.backquote = backquotelist;
9486 if (checkkwd = 2, readtoken() != TPIPE)
9488 app = &ap->narg.next;
9491 ap->narg.next = NULL;
9492 if (lasttoken != TRP)
9494 cp->nclist.body = list(0);
9497 if ((t = readtoken()) != TESAC) {
9499 synexpect(TENDCASE);
9501 checkkwd = 2, readtoken();
9503 cpp = &cp->nclist.next;
9504 } while (lasttoken != TESAC);
9509 n1 = (union node *) stalloc(sizeof(struct nredir));
9510 n1->type = NSUBSHELL;
9511 n1->nredir.n = list(0);
9512 n1->nredir.redirect = NULL;
9513 if (readtoken() != TRP)
9519 if (readtoken() != TEND)
9523 /* Handle an empty command like other simple commands. */
9532 * An empty command before a ; doesn't make much sense, and
9533 * should certainly be disallowed in the case of `if ;'.
9539 n1 = simplecmd(rpp, redir);
9546 /* Now check for redirection which may follow command */
9547 while (readtoken() == TREDIR) {
9548 *rpp = n2 = redirnode;
9549 rpp = &n2->nfile.next;
9555 if (n1->type != NSUBSHELL) {
9556 n2 = (union node *) stalloc(sizeof(struct nredir));
9561 n1->nredir.redirect = redir;
9568 static union node *simplecmd(union node **rpp, union node *redir)
9570 union node *args, **app;
9571 union node *n = NULL;
9572 union node *vars, **vpp;
9573 union node **orig_rpp;
9580 /* If we don't have any redirections already, then we must reset
9581 rpp to be the address of the local redir variable. */
9584 /* We save the incoming value, because we need this for shell
9585 functions. There can not be a redirect or an argument between
9586 the function name and the open parenthesis. */
9591 switch (readtoken()) {
9594 n = (union node *) stalloc(sizeof(struct narg));
9596 n->narg.text = wordtext;
9597 n->narg.backquote = backquotelist;
9598 if (lasttoken == TWORD) {
9600 app = &n->narg.next;
9603 vpp = &n->narg.next;
9607 *rpp = n = redirnode;
9608 rpp = &n->nfile.next;
9609 parsefname(); /* read name of redirection file */
9612 if (args && app == &args->narg.next && !vars && rpp == orig_rpp) {
9613 /* We have a function */
9614 if (readtoken() != TRP)
9618 n->narg.next = command();
9631 n = (union node *) stalloc(sizeof(struct ncmd));
9633 n->ncmd.backgnd = 0;
9634 n->ncmd.args = args;
9635 n->ncmd.assign = vars;
9636 n->ncmd.redirect = redir;
9640 static union node *makename(void)
9644 n = (union node *) stalloc(sizeof(struct narg));
9646 n->narg.next = NULL;
9647 n->narg.text = wordtext;
9648 n->narg.backquote = backquotelist;
9652 static void fixredir(union node *n, const char *text, int err)
9654 TRACE(("Fix redir %s %d\n", text, err));
9656 n->ndup.vname = NULL;
9658 if (is_digit(text[0]) && text[1] == '\0')
9659 n->ndup.dupfd = digit_val(text[0]);
9660 else if (text[0] == '-' && text[1] == '\0')
9665 synerror("Bad fd number");
9667 n->ndup.vname = makename();
9672 static void parsefname(void)
9674 union node *n = redirnode;
9676 if (readtoken() != TWORD)
9678 if (n->type == NHERE) {
9679 struct heredoc *here = heredoc;
9685 TRACE(("Here document %d\n", n->type));
9686 if (here->striptabs) {
9687 while (*wordtext == '\t')
9690 if (!noexpand(wordtext) || (i = strlen(wordtext)) == 0
9692 synerror("Illegal eof marker for << redirection");
9693 rmescapes(wordtext);
9694 here->eofmark = wordtext;
9696 if (heredoclist == NULL)
9699 for (p = heredoclist; p->next; p = p->next);
9702 } else if (n->type == NTOFD || n->type == NFROMFD) {
9703 fixredir(n, wordtext, 0);
9705 n->nfile.fname = makename();
9711 * Input any here documents.
9714 static void parseheredoc()
9716 struct heredoc *here;
9719 while (heredoclist) {
9721 heredoclist = here->next;
9726 readtoken1(pgetc(), here->here->type == NHERE ? SQSYNTAX : DQSYNTAX,
9727 here->eofmark, here->striptabs);
9728 n = (union node *) stalloc(sizeof(struct narg));
9729 n->narg.type = NARG;
9730 n->narg.next = NULL;
9731 n->narg.text = wordtext;
9732 n->narg.backquote = backquotelist;
9733 here->here->nhere.doc = n;
9737 static char peektoken()
9743 return tokname_array[t][0];
9746 static int readtoken()
9750 int savecheckalias = checkalias;
9752 #ifdef CONFIG_ASH_ALIAS
9753 int savecheckkwd = checkkwd;
9758 int alreadyseen = tokpushback;
9761 #ifdef CONFIG_ASH_ALIAS
9767 checkalias = savecheckalias;
9773 if (checkkwd == 2) {
9782 * check for keywords
9784 if (t == TWORD && !quoteflag) {
9785 const char *const *pp;
9787 if ((pp = findkwd(wordtext))) {
9788 lasttoken = t = pp - tokname_array;
9789 TRACE(("keyword %s recognized\n", tokname(t)));
9800 } else if (checkalias == 2 && isassignment(wordtext)) {
9801 lasttoken = t = TASSIGN;
9802 } else if (checkalias) {
9803 #ifdef CONFIG_ASH_ALIAS
9804 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL
9805 && !(ap->flag & ALIASINUSE)) {
9807 pushstring(ap->val, strlen(ap->val), ap);
9809 checkkwd = savecheckkwd;
9818 TRACE(("token %s %s\n", tokname(t), t == TWORD
9819 || t == TASSIGN ? wordtext : ""));
9821 TRACE(("reread token %s %s\n", tokname(t), t == TWORD
9822 || t == TASSIGN ? wordtext : ""));
9829 * Read the next input token.
9830 * If the token is a word, we set backquotelist to the list of cmds in
9831 * backquotes. We set quoteflag to true if any part of the word was
9833 * If the token is TREDIR, then we set redirnode to a structure containing
9835 * In all cases, the variable startlinno is set to the number of the line
9836 * on which the token starts.
9838 * [Change comment: here documents and internal procedures]
9839 * [Readtoken shouldn't have any arguments. Perhaps we should make the
9840 * word parsing code into a separate routine. In this case, readtoken
9841 * doesn't need to have any internal procedures, but parseword does.
9842 * We could also make parseoperator in essence the main routine, and
9843 * have parseword (readtoken1?) handle both words and redirection.]
9846 #define NEW_xxreadtoken
9847 #ifdef NEW_xxreadtoken
9849 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
9850 static const char xxreadtoken_tokens[] = {
9851 TNL, TLP, TRP, /* only single occurrence allowed */
9852 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
9853 TEOF, /* corresponds to trailing nul */
9854 TAND, TOR, TENDCASE, /* if double occurrence */
9857 #define xxreadtoken_doubles \
9858 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
9859 #define xxreadtoken_singles \
9860 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
9862 static int xxreadtoken()
9874 startlinno = plinno;
9875 for (;;) { /* until token or start of word found */
9878 if ((c != ' ') && (c != '\t')
9879 #ifdef CONFIG_ASH_ALIAS
9884 while ((c = pgetc()) != '\n' && c != PEOF);
9886 } else if (c == '\\') {
9887 if (pgetc() != '\n') {
9891 startlinno = ++plinno;
9892 setprompt(doprompt ? 2 : 0);
9895 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
9900 needprompt = doprompt;
9903 p = strchr(xxreadtoken_chars, c);
9906 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
9909 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
9910 if (pgetc() == *p) { /* double occurrence? */
9911 p += xxreadtoken_doubles + 1;
9918 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
9926 #define RETURN(token) return lasttoken = token
9928 static int xxreadtoken()
9940 startlinno = plinno;
9941 for (;;) { /* until token or start of word found */
9946 #ifdef CONFIG_ASH_ALIAS
9951 while ((c = pgetc()) != '\n' && c != PEOF);
9955 if (pgetc() == '\n') {
9956 startlinno = ++plinno;
9967 needprompt = doprompt;
9995 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10001 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10002 * is not NULL, read a here document. In the latter case, eofmark is the
10003 * word which marks the end of the document and striptabs is true if
10004 * leading tabs should be stripped from the document. The argument firstc
10005 * is the first character of the input token or document.
10007 * Because C does not have internal subroutines, I have simulated them
10008 * using goto's to implement the subroutine linkage. The following macros
10009 * will run code that appears at the end of readtoken1.
10012 #define CHECKEND() {goto checkend; checkend_return:;}
10013 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10014 #define PARSESUB() {goto parsesub; parsesub_return:;}
10015 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10016 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10017 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10020 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10025 char line[EOFMARKLEN + 1];
10026 struct nodelist *bqlist;
10029 int varnest; /* levels of variables expansion */
10030 int arinest; /* levels of arithmetic expansion */
10031 int parenlevel; /* levels of parens in arithmetic */
10032 int dqvarnest; /* levels of variables expansion within double quotes */
10034 int prevsyntax; /* syntax before arithmetic */
10037 /* Avoid longjmp clobbering */
10043 (void) &parenlevel;
10046 (void) &prevsyntax;
10050 startlinno = plinno;
10052 if (syntax == DQSYNTAX)
10061 STARTSTACKSTR(out);
10062 loop:{ /* for each line, until end of word */
10063 CHECKEND(); /* set c to PEOF if at end of here document */
10064 for (;;) { /* until end of line or end of word */
10065 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10066 switch (SIT(c, syntax)) {
10067 case CNL: /* '\n' */
10068 if (syntax == BASESYNTAX)
10069 goto endword; /* exit outer loop */
10077 goto loop; /* continue outer loop */
10082 if ((eofmark == NULL || dblquote) && dqvarnest == 0)
10083 USTPUTC(CTLESC, out);
10086 case CBACK: /* backslash */
10089 USTPUTC('\\', out);
10091 } else if (c == '\n') {
10097 if (dblquote && c != '\\' && c != '`' && c != '$'
10098 && (c != '"' || eofmark != NULL))
10099 USTPUTC('\\', out);
10100 if (SIT(c, SQSYNTAX) == CCTL)
10101 USTPUTC(CTLESC, out);
10102 else if (eofmark == NULL)
10103 USTPUTC(CTLQUOTEMARK, out);
10109 if (eofmark == NULL)
10110 USTPUTC(CTLQUOTEMARK, out);
10114 if (eofmark == NULL)
10115 USTPUTC(CTLQUOTEMARK, out);
10120 if (eofmark != NULL && arinest == 0 && varnest == 0) {
10124 syntax = ARISYNTAX;
10126 } else if (eofmark == NULL && dqvarnest == 0) {
10127 syntax = BASESYNTAX;
10133 case CVAR: /* '$' */
10134 PARSESUB(); /* parse substitution */
10136 case CENDVAR: /* '}' */
10139 if (dqvarnest > 0) {
10142 USTPUTC(CTLENDVAR, out);
10147 #ifdef CONFIG_ASH_MATH_SUPPORT
10148 case CLP: /* '(' in arithmetic */
10152 case CRP: /* ')' in arithmetic */
10153 if (parenlevel > 0) {
10157 if (pgetc() == ')') {
10158 if (--arinest == 0) {
10159 USTPUTC(CTLENDARI, out);
10160 syntax = prevsyntax;
10161 if (syntax == DQSYNTAX)
10169 * unbalanced parens
10170 * (don't 2nd guess - no error)
10178 case CBQUOTE: /* '`' */
10182 goto endword; /* exit outer loop */
10187 goto endword; /* exit outer loop */
10188 #ifdef CONFIG_ASH_ALIAS
10198 if (syntax == ARISYNTAX)
10199 synerror("Missing '))'");
10200 if (syntax != BASESYNTAX && !parsebackquote && eofmark == NULL)
10201 synerror("Unterminated quoted string");
10202 if (varnest != 0) {
10203 startlinno = plinno;
10204 synerror("Missing '}'");
10206 USTPUTC('\0', out);
10207 len = out - stackblock();
10208 out = stackblock();
10209 if (eofmark == NULL) {
10210 if ((c == '>' || c == '<')
10211 && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) {
10213 return lasttoken = TREDIR;
10218 quoteflag = quotef;
10219 backquotelist = bqlist;
10220 grabstackblock(len);
10222 return lasttoken = TWORD;
10223 /* end of readtoken routine */
10228 * Check to see whether we are at the end of the here document. When this
10229 * is called, c is set to the first character of the next input line. If
10230 * we are at the end of the here document, this routine sets the c to PEOF.
10235 #ifdef CONFIG_ASH_ALIAS
10241 while (c == '\t') {
10245 if (c == *eofmark) {
10246 if (pfgets(line, sizeof line) != NULL) {
10250 for (q = eofmark + 1; *q && *p == *q; p++, q++);
10251 if (*p == '\n' && *q == '\0') {
10254 needprompt = doprompt;
10256 pushstring(line, strlen(line), NULL);
10261 goto checkend_return;
10266 * Parse a redirection operator. The variable "out" points to a string
10267 * specifying the fd to be redirected. The variable "c" contains the
10268 * first character of the redirection operator.
10275 np = (union node *) stalloc(sizeof(struct nfile));
10280 np->type = NAPPEND;
10289 } else { /* c == '<' */
10291 switch (c = pgetc()) {
10293 if (sizeof(struct nfile) != sizeof(struct nhere)) {
10294 np = (union node *) stalloc(sizeof(struct nhere));
10298 heredoc = (struct heredoc *) stalloc(sizeof(struct heredoc));
10299 heredoc->here = np;
10300 if ((c = pgetc()) == '-') {
10301 heredoc->striptabs = 1;
10303 heredoc->striptabs = 0;
10309 np->type = NFROMFD;
10313 np->type = NFROMTO;
10323 np->nfile.fd = digit_val(fd);
10325 goto parseredir_return;
10330 * Parse a substitution. At this point, we have read the dollar sign
10331 * and nothing else.
10339 static const char types[] = "}-+?=";
10343 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10347 } else if (c == '(') { /* $(command) or $((arith)) */
10348 if (pgetc() == '(') {
10355 USTPUTC(CTLVAR, out);
10356 typeloc = out - stackblock();
10357 USTPUTC(VSNORMAL, out);
10358 subtype = VSNORMAL;
10362 if ((c = pgetc()) == '}')
10365 subtype = VSLENGTH;
10369 if (c > PEOA && is_name(c)) {
10373 } while (c > PEOA && is_in_name(c));
10374 } else if (is_digit(c)) {
10378 } while (is_digit(c));
10379 } else if (is_special(c)) {
10383 badsub:synerror("Bad substitution");
10387 if (subtype == 0) {
10392 /*FALLTHROUGH*/ default:
10393 p = strchr(types, c);
10396 subtype = p - types + VSNORMAL;
10403 subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT;
10415 if (dblquote || arinest)
10417 *(stackblock() + typeloc) = subtype | flags;
10418 if (subtype != VSNORMAL) {
10425 goto parsesub_return;
10430 * Called to parse command substitutions. Newstyle is set if the command
10431 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10432 * list of commands (passed by reference), and savelen is the number of
10433 * characters on the top of the stack which must be preserved.
10437 struct nodelist **nlpp;
10440 char *volatile str;
10441 struct jmploc jmploc;
10442 struct jmploc *volatile savehandler;
10447 (void) &saveprompt;
10450 savepbq = parsebackquote;
10451 if (setjmp(jmploc.loc)) {
10453 parsebackquote = 0;
10454 handler = savehandler;
10455 longjmp(handler->loc, 1);
10459 savelen = out - stackblock();
10461 str = xmalloc(savelen);
10462 memcpy(str, stackblock(), savelen);
10464 savehandler = handler;
10468 /* We must read until the closing backquote, giving special
10469 treatment to some slashes, and then push the string and
10470 reread it as input, interpreting it normally. */
10477 STARTSTACKSTR(pout);
10483 switch (pc = pgetc()) {
10488 if ((pc = pgetc()) == '\n') {
10495 * If eating a newline, avoid putting
10496 * the newline into the new character
10497 * stream (via the STPUTC after the
10502 if (pc != '\\' && pc != '`' && pc != '$'
10503 && (!dblquote || pc != '"'))
10504 STPUTC('\\', pout);
10511 #ifdef CONFIG_ASH_ALIAS
10514 startlinno = plinno;
10515 synerror("EOF in backquote substitution");
10519 needprompt = doprompt;
10528 STPUTC('\0', pout);
10529 psavelen = pout - stackblock();
10530 if (psavelen > 0) {
10531 pstr = grabstackstr(pout);
10532 setinputstring(pstr);
10537 nlpp = &(*nlpp)->next;
10538 *nlpp = (struct nodelist *) stalloc(sizeof(struct nodelist));
10539 (*nlpp)->next = NULL;
10540 parsebackquote = oldstyle;
10543 saveprompt = doprompt;
10550 doprompt = saveprompt;
10552 if (readtoken() != TRP)
10559 * Start reading from old file again, ignoring any pushed back
10560 * tokens left from the backquote parsing
10565 while (stackblocksize() <= savelen)
10567 STARTSTACKSTR(out);
10569 memcpy(out, str, savelen);
10570 STADJUST(savelen, out);
10576 parsebackquote = savepbq;
10577 handler = savehandler;
10578 if (arinest || dblquote)
10579 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10581 USTPUTC(CTLBACKQ, out);
10583 goto parsebackq_oldreturn;
10585 goto parsebackq_newreturn;
10589 * Parse an arithmetic expansion (indicate start of one and set state)
10593 if (++arinest == 1) {
10594 prevsyntax = syntax;
10595 syntax = ARISYNTAX;
10596 USTPUTC(CTLARI, out);
10603 * we collapse embedded arithmetic expansion to
10604 * parenthesis, which should be equivalent
10608 goto parsearith_return;
10611 } /* end of readtoken */
10615 * Returns true if the text contains nothing to expand (no dollar signs
10619 static int noexpand(char *text)
10625 while ((c = *p++) != '\0') {
10626 if (c == CTLQUOTEMARK)
10630 else if (SIT(c, BASESYNTAX) == CCTL)
10638 * Return true if the argument is a legal variable name (a letter or
10639 * underscore followed by zero or more letters, underscores, and digits).
10642 static int goodname(const char *name)
10650 if (!is_in_name(*p))
10658 * Called when an unexpected token is read during the parse. The argument
10659 * is the token that is expected, or -1 if more than one type of token can
10660 * occur at this point.
10663 static void synexpect(int token)
10668 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10670 sprintf(msg + l, " (expecting %s)", tokname(token));
10676 static void synerror(const char *msg)
10679 out2fmt("%s: %d: ", commandname, startlinno);
10680 out2fmt("Syntax error: %s\n", msg);
10681 error((char *) NULL);
10687 * called by editline -- any expansions to the prompt
10688 * should be added here.
10690 static void setprompt(int whichprompt)
10694 switch (whichprompt) {
10709 * Code for dealing with input/output redirection.
10712 #define EMPTY -2 /* marks an unused slot in redirtab */
10714 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10716 # define PIPESIZE PIPE_BUF
10721 * Open a file in noclobber mode.
10722 * The code was copied from bash.
10724 static inline int noclobberopen(const char *fname)
10727 struct stat finfo, finfo2;
10730 * If the file exists and is a regular file, return an error
10733 r = stat(fname, &finfo);
10734 if (r == 0 && S_ISREG(finfo.st_mode)) {
10740 * If the file was not present (r != 0), make sure we open it
10741 * exclusively so that if it is created before we open it, our open
10742 * will fail. Make sure that we do not truncate an existing file.
10743 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10744 * file was not a regular file, we leave O_EXCL off.
10747 return open(fname, O_WRONLY | O_CREAT | O_EXCL, 0666);
10748 fd = open(fname, O_WRONLY | O_CREAT, 0666);
10750 /* If the open failed, return the file descriptor right away. */
10755 * OK, the open succeeded, but the file may have been changed from a
10756 * non-regular file to a regular file between the stat and the open.
10757 * We are assuming that the O_EXCL open handles the case where FILENAME
10758 * did not exist and is symlinked to an existing file between the stat
10763 * If we can open it and fstat the file descriptor, and neither check
10764 * revealed that it was a regular file, and the file has not been
10765 * replaced, return the file descriptor.
10767 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10768 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10771 /* The file has been replaced. badness. */
10778 * Handle here documents. Normally we fork off a process to write the
10779 * data to a pipe. If the document is short, we can stuff the data in
10780 * the pipe without forking.
10783 static inline int openhere(const union node *redir)
10789 error("Pipe call failed");
10790 if (redir->type == NHERE) {
10791 len = strlen(redir->nhere.doc->narg.text);
10792 if (len <= PIPESIZE) {
10793 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10797 if (forkshell((struct job *) NULL, (union node *) NULL, FORK_NOJOB) == 0) {
10799 signal(SIGINT, SIG_IGN);
10800 signal(SIGQUIT, SIG_IGN);
10801 signal(SIGHUP, SIG_IGN);
10803 signal(SIGTSTP, SIG_IGN);
10805 signal(SIGPIPE, SIG_DFL);
10806 if (redir->type == NHERE)
10807 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10809 expandhere(redir->nhere.doc, pip[1]);
10818 static inline int openredirect(const union node *redir)
10823 switch (redir->nfile.type) {
10825 fname = redir->nfile.expfname;
10826 if ((f = open(fname, O_RDONLY)) < 0)
10830 fname = redir->nfile.expfname;
10831 if ((f = open(fname, O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0)
10835 /* Take care of noclobber mode. */
10837 fname = redir->nfile.expfname;
10838 if ((f = noclobberopen(fname)) < 0)
10843 fname = redir->nfile.expfname;
10845 if ((f = open(fname, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0)
10848 if ((f = creat(fname, 0666)) < 0)
10853 fname = redir->nfile.expfname;
10855 if ((f = open(fname, O_WRONLY | O_CREAT | O_APPEND, 0666)) < 0)
10858 if ((f = open(fname, O_WRONLY)) < 0 && (f = creat(fname, 0666)) < 0)
10860 lseek(f, (off_t) 0, 2);
10867 /* Fall through to eliminate warning. */
10874 f = openhere(redir);
10880 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
10882 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
10887 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
10888 * old file descriptors are stashed away so that the redirection can be
10889 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
10890 * standard output, and the standard error if it becomes a duplicate of
10894 static void redirect(union node *redir, int flags)
10897 struct redirtab *sv = NULL;
10902 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
10904 TRACE(("redirect(%s) called\n",
10905 flags & REDIR_PUSH ? "REDIR_PUSH" : "NO_REDIR_PUSH"));
10906 if (flags & REDIR_PUSH) {
10907 sv = xmalloc(sizeof(struct redirtab));
10908 for (i = 0; i < 10; i++)
10909 sv->renamed[i] = EMPTY;
10910 sv->next = redirlist;
10913 for (n = redir; n; n = n->nfile.next) {
10916 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
10917 n->ndup.dupfd == fd)
10918 continue; /* redirect from/to same file descriptor */
10921 newfd = openredirect(n);
10922 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
10926 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
10930 dupredirect(n, newfd, fd1dup);
10940 error("%d: %m", fd);
10946 if (flags & REDIR_PUSH) {
10947 sv->renamed[fd] = i;
10950 } else if (fd != newfd) {
10956 dupredirect(n, newfd, fd1dup);
10962 static void dupredirect(const union node *redir, int f, int fd1dup)
10964 int fd = redir->nfile.fd;
10968 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
10969 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
10970 if (redir->ndup.dupfd != 1 || fd1dup != 1)
10971 dup_as_newfd(redir->ndup.dupfd, fd);
10977 dup_as_newfd(f, fd);
10986 * Undo the effects of the last redirection.
10989 static void popredir(void)
10991 struct redirtab *rp = redirlist;
10995 for (i = 0; i < 10; i++) {
10996 if (rp->renamed[i] != EMPTY) {
11000 if (rp->renamed[i] >= 0) {
11001 dup_as_newfd(rp->renamed[i], i);
11002 close(rp->renamed[i]);
11006 redirlist = rp->next;
11012 * Discard all saved file descriptors.
11015 static void clearredir(void)
11017 struct redirtab *rp;
11020 for (rp = redirlist; rp; rp = rp->next) {
11021 for (i = 0; i < 10; i++) {
11022 if (rp->renamed[i] >= 0) {
11023 close(rp->renamed[i]);
11025 rp->renamed[i] = EMPTY;
11032 * Copy a file descriptor to be >= to. Returns -1
11033 * if the source file descriptor is closed, EMPTY if there are no unused
11034 * file descriptors left.
11037 static int dup_as_newfd(int from, int to)
11041 newfd = fcntl(from, F_DUPFD, to);
11043 if (errno == EMFILE)
11046 error("%d: %m", from);
11056 static void shtree(union node *, int, char *, FILE *);
11057 static void shcmd(union node *, FILE *);
11058 static void sharg(union node *, FILE *);
11059 static void indent(int, char *, FILE *);
11060 static void trstring(char *);
11064 static void showtree(node * n)
11066 trputs("showtree called\n");
11067 shtree(n, 1, NULL, stdout);
11071 static void shtree(union node *n, int ind, char *pfx, FILE * fp)
11073 struct nodelist *lp;
11079 indent(ind, pfx, fp);
11090 shtree(n->nbinary.ch1, ind, NULL, fp);
11093 shtree(n->nbinary.ch2, ind, NULL, fp);
11101 for (lp = n->npipe.cmdlist; lp; lp = lp->next) {
11106 if (n->npipe.backgnd)
11112 fprintf(fp, "<node type %d>", n->type);
11120 static void shcmd(union node *cmd, FILE * fp)
11128 for (np = cmd->ncmd.args; np; np = np->narg.next) {
11134 for (np = cmd->ncmd.redirect; np; np = np->nfile.next) {
11140 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11141 s = redir_strings[np->nfile.type - NTO];
11147 switch (np->nfile.type) {
11182 if (np->nfile.fd != dftfd)
11183 fprintf(fp, "%d", np->nfile.fd);
11185 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11186 fprintf(fp, "%d", np->ndup.dupfd);
11188 sharg(np->nfile.fname, fp);
11195 static void sharg(union node *arg, FILE * fp)
11198 struct nodelist *bqlist;
11201 if (arg->type != NARG) {
11202 printf("<node type %d>\n", arg->type);
11206 bqlist = arg->narg.backquote;
11207 for (p = arg->narg.text; *p; p++) {
11216 if (subtype == VSLENGTH)
11222 if (subtype & VSNUL)
11225 switch (subtype & VSTYPE) {
11244 case VSTRIMLEFTMAX:
11251 case VSTRIMRIGHTMAX:
11258 printf("<subtype %d>", subtype);
11265 case CTLBACKQ | CTLQUOTE:
11268 shtree(bqlist->n, -1, NULL, fp);
11279 static void indent(int amount, char *pfx, FILE * fp)
11283 for (i = 0; i < amount; i++) {
11284 if (pfx && i == amount - 1)
11293 static int debug = 1;
11295 static int debug = 0;
11299 static void trputc(int c)
11301 if (tracefile == NULL)
11303 putc(c, tracefile);
11308 static void trace(const char *fmt, ...)
11313 if (tracefile != NULL) {
11314 (void) vfprintf(tracefile, fmt, va);
11315 if (strchr(fmt, '\n'))
11316 (void) fflush(tracefile);
11322 static void trputs(const char *s)
11324 if (tracefile == NULL)
11326 fputs(s, tracefile);
11327 if (strchr(s, '\n'))
11332 static void trstring(char *s)
11337 if (tracefile == NULL)
11339 putc('"', tracefile);
11340 for (p = s; *p; p++) {
11363 case CTLVAR + CTLQUOTE:
11369 case CTLBACKQ + CTLQUOTE:
11372 backslash:putc('\\', tracefile);
11373 putc(c, tracefile);
11376 if (*p >= ' ' && *p <= '~')
11377 putc(*p, tracefile);
11379 putc('\\', tracefile);
11380 putc(*p >> 6 & 03, tracefile);
11381 putc(*p >> 3 & 07, tracefile);
11382 putc(*p & 07, tracefile);
11387 putc('"', tracefile);
11391 static void trargs(char **ap)
11393 if (tracefile == NULL)
11398 putc(' ', tracefile);
11400 putc('\n', tracefile);
11406 static void opentrace()
11416 #ifdef not_this_way
11420 if ((p = getenv("HOME")) == NULL) {
11421 if (geteuid() == 0)
11427 strcat(s, "/trace");
11430 strcpy(s, "./trace");
11431 #endif /* not_this_way */
11432 if ((tracefile = bb_wfopen(s, "a")) == NULL)
11435 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11436 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11438 fputs("\nTracing started.\n", tracefile);
11445 * The trap builtin.
11448 static int trapcmd(int argc, char **argv)
11455 for (signo = 0; signo < NSIG; signo++) {
11456 if (trap[signo] != NULL) {
11460 p = single_quote(trap[signo]);
11461 sn = sys_siglist[signo];
11463 sn = u_signal_names(0, &signo, 0);
11466 printf("trap -- %s %s\n", p, sn);
11478 if ((signo = decode_signal(*ap, 0)) < 0)
11479 error("%s: bad trap", *ap);
11482 if (action[0] == '-' && action[1] == '\0')
11485 action = bb_xstrdup(action);
11488 trap[signo] = action;
11499 * Set the signal handler for the specified signal. The routine figures
11500 * out what it should be set to.
11503 static void setsignal(int signo)
11507 struct sigaction act;
11509 if ((t = trap[signo]) == NULL)
11511 else if (*t != '\0')
11515 if (rootshell && action == S_DFL) {
11518 if (iflag || minusc || sflag == 0)
11534 #ifdef CONFIG_ASH_JOB_CONTROL
11544 t = &sigmode[signo - 1];
11547 * current setting unknown
11549 if (sigaction(signo, 0, &act) == -1) {
11551 * Pretend it worked; maybe we should give a warning
11552 * here, but other shells don't. We don't alter
11553 * sigmode, so that we retry every time.
11557 if (act.sa_handler == SIG_IGN) {
11558 if (mflag && (signo == SIGTSTP ||
11559 signo == SIGTTIN || signo == SIGTTOU)) {
11560 *t = S_IGN; /* don't hard ignore these */
11564 *t = S_RESET; /* force to be set */
11567 if (*t == S_HARD_IGN || *t == action)
11569 act.sa_handler = ((action == S_CATCH) ? onsig
11570 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11573 sigemptyset(&act.sa_mask);
11574 sigaction(signo, &act, 0);
11581 static void ignoresig(int signo)
11583 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11584 signal(signo, SIG_IGN);
11586 sigmode[signo - 1] = S_HARD_IGN;
11594 static void onsig(int signo)
11596 if (signo == SIGINT && trap[SIGINT] == NULL) {
11600 gotsig[signo - 1] = 1;
11606 * Called to execute a trap. Perhaps we should avoid entering new trap
11607 * handlers while we are executing a trap handler.
11610 static void dotrap(void)
11616 for (i = 1;; i++) {
11623 savestatus = exitstatus;
11624 evalstring(trap[i], 0);
11625 exitstatus = savestatus;
11632 * Called to exit the shell.
11635 static void exitshell(int status)
11637 struct jmploc loc1, loc2;
11640 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11641 if (setjmp(loc1.loc)) {
11644 if (setjmp(loc2.loc)) {
11648 if ((p = trap[0]) != NULL && *p != '\0') {
11653 handler = &loc2; /* probably unnecessary */
11655 #ifdef CONFIG_ASH_JOB_CONTROL
11658 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
11659 if (iflag && rootshell) {
11660 const char *hp = lookupvar("HISTFILE");
11663 save_history ( hp );
11671 static int decode_signal(const char *string, int minsig)
11674 const char *name = u_signal_names(string, &signo, minsig);
11676 return name ? signo : -1;
11679 static struct var **hashvar(const char *);
11680 static void showvars(const char *, int, int);
11681 static struct var **findvar(struct var **, const char *);
11684 * Initialize the varable symbol tables and import the environment
11688 * This routine initializes the builtin variables. It is called when the
11689 * shell is initialized and again when a shell procedure is spawned.
11692 static void initvar()
11694 const struct varinit *ip;
11698 for (ip = varinit; (vp = ip->var) != NULL; ip++) {
11699 if ((vp->flags & VEXPORT) == 0) {
11700 vpp = hashvar(ip->text);
11703 vp->text = bb_xstrdup(ip->text);
11704 vp->flags = ip->flags;
11705 vp->func = ip->func;
11708 #if !defined(CONFIG_FEATURE_COMMAND_EDITING) || !defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
11710 * PS1 depends on uid
11712 if ((vps1.flags & VEXPORT) == 0) {
11713 vpp = hashvar("PS1=$ ");
11716 vps1.text = bb_xstrdup(geteuid()? "PS1=$ " : "PS1=# ");
11717 vps1.flags = VSTRFIXED | VTEXTFIXED;
11723 * Set the value of a variable. The flags argument is ored with the
11724 * flags of the variable. If val is NULL, the variable is unset.
11727 static void setvar(const char *name, const char *val, int flags)
11742 if (!is_in_name(*p)) {
11743 if (*p == '\0' || *p == '=')
11749 namelen = p - name;
11751 error("%.*s: bad variable name", namelen, name);
11752 len = namelen + 2; /* 2 is space for '=' and '\0' */
11756 len += vallen = strlen(val);
11759 nameeq = xmalloc(len);
11760 memcpy(nameeq, name, namelen);
11761 nameeq[namelen] = '=';
11763 memcpy(nameeq + namelen + 1, val, vallen + 1);
11765 nameeq[namelen + 1] = '\0';
11767 setvareq(nameeq, flags);
11774 * Same as setvar except that the variable and value are passed in
11775 * the first argument as name=value. Since the first argument will
11776 * be actually stored in the table, it should not be a string that
11780 static void setvareq(char *s, int flags)
11782 struct var *vp, **vpp;
11785 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11786 if ((vp = *findvar(vpp, s))) {
11787 if (vp->flags & VREADONLY) {
11788 size_t len = strchr(s, '=') - s;
11790 error("%.*s: is read only", len, s);
11794 if (vp->func && (flags & VNOFUNC) == 0)
11795 (*vp->func) (strchr(s, '=') + 1);
11797 if ((vp->flags & (VTEXTFIXED | VSTACK)) == 0)
11800 vp->flags &= ~(VTEXTFIXED | VSTACK | VUNSET);
11801 vp->flags |= flags;
11804 #ifdef CONFIG_ASH_MAIL
11806 * We could roll this to a function, to handle it as
11807 * a regular variable function callback, but why bother?
11809 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
11816 vp = xmalloc(sizeof(*vp));
11827 * Process a linked list of variable assignments.
11830 static void listsetvar(struct strlist *mylist)
11832 struct strlist *lp;
11835 for (lp = mylist; lp; lp = lp->next) {
11836 setvareq(bb_xstrdup(lp->text), 0);
11844 * Find the value of a variable. Returns NULL if not set.
11847 static const char *lookupvar(const char *name)
11851 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
11852 return strchr(v->text, '=') + 1;
11860 * Search the environment of a builtin command.
11863 static const char *bltinlookup(const char *name)
11865 const struct strlist *sp;
11867 for (sp = cmdenviron; sp; sp = sp->next) {
11868 if (varequal(sp->text, name))
11869 return strchr(sp->text, '=') + 1;
11871 return lookupvar(name);
11877 * Generate a list of exported variables. This routine is used to construct
11878 * the third argument to execve when executing a program.
11881 static char **environment()
11890 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
11891 for (vp = *vpp; vp; vp = vp->next)
11892 if (vp->flags & VEXPORT)
11895 ep = env = stalloc((nenv + 1) * sizeof *env);
11896 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
11897 for (vp = *vpp; vp; vp = vp->next)
11898 if (vp->flags & VEXPORT)
11907 * Command to list all variables which are set. Currently this command
11908 * is invoked from the set command when the set command is called without
11912 static int showvarscmd(int argc, char **argv)
11914 showvars(nullstr, VUNSET, VUNSET);
11921 * The export and readonly commands.
11924 static int exportcmd(int argc, char **argv)
11929 int flag = argv[0][0] == 'r' ? VREADONLY : VEXPORT;
11932 listsetvar(cmdenviron);
11933 pflag = (nextopt("p") == 'p');
11934 if (argc > 1 && !pflag) {
11935 while ((name = *argptr++) != NULL) {
11936 if ((p = strchr(name, '=')) != NULL) {
11939 if ((vp = *findvar(hashvar(name), name))) {
11944 setvar(name, p, flag);
11948 showvars(argv[0], flag, 0);
11955 * The "local" command.
11958 /* funcnest nonzero if we are currently evaluating a function */
11960 static int localcmd(int argc, char **argv)
11965 error("Not in a function");
11966 while ((name = *argptr++) != NULL) {
11974 * Make a variable a local variable. When a variable is made local, it's
11975 * value and flags are saved in a localvar structure. The saved values
11976 * will be restored when the shell function returns. We handle the name
11977 * "-" as a special case.
11980 static void mklocal(char *name)
11982 struct localvar *lvp;
11987 lvp = xmalloc(sizeof(struct localvar));
11988 if (name[0] == '-' && name[1] == '\0') {
11991 p = xmalloc(sizeof optet_vals);
11992 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
11995 vpp = hashvar(name);
11996 vp = *findvar(vpp, name);
11998 if (strchr(name, '='))
11999 setvareq(bb_xstrdup(name), VSTRFIXED);
12001 setvar(name, NULL, VSTRFIXED);
12002 vp = *vpp; /* the new variable */
12004 lvp->flags = VUNSET;
12006 lvp->text = vp->text;
12007 lvp->flags = vp->flags;
12008 vp->flags |= VSTRFIXED | VTEXTFIXED;
12009 if (strchr(name, '='))
12010 setvareq(bb_xstrdup(name), 0);
12014 lvp->next = localvars;
12021 * Called after a function returns.
12024 static void poplocalvars()
12026 struct localvar *lvp;
12029 while ((lvp = localvars) != NULL) {
12030 localvars = lvp->next;
12032 if (vp == NULL) { /* $- saved */
12033 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12035 } else if ((lvp->flags & (VUNSET | VSTRFIXED)) == VUNSET) {
12036 (void) unsetvar(vp->text);
12038 if ((vp->flags & VTEXTFIXED) == 0)
12040 vp->flags = lvp->flags;
12041 vp->text = lvp->text;
12048 static int setvarcmd(int argc, char **argv)
12051 return unsetcmd(argc, argv);
12052 else if (argc == 3)
12053 setvar(argv[1], argv[2], 0);
12055 error("List assignment not implemented");
12061 * The unset builtin command. We unset the function before we unset the
12062 * variable to allow a function to be unset when there is a readonly variable
12063 * with the same name.
12066 static int unsetcmd(int argc, char **argv)
12074 while ((i = nextopt("vf")) != '\0') {
12080 if (flg_func == 0 && flg_var == 0)
12083 for (ap = argptr; *ap; ap++) {
12087 ret |= unsetvar(*ap);
12094 * Unset the specified variable.
12097 static int unsetvar(const char *s)
12102 vpp = findvar(hashvar(s), s);
12105 if (vp->flags & VREADONLY)
12108 if (*(strchr(vp->text, '=') + 1) != '\0')
12109 setvar(s, nullstr, 0);
12110 vp->flags &= ~VEXPORT;
12111 vp->flags |= VUNSET;
12112 if ((vp->flags & VSTRFIXED) == 0) {
12113 if ((vp->flags & VTEXTFIXED) == 0)
12128 * Find the appropriate entry in the hash table from the name.
12131 static struct var **hashvar(const char *p)
12133 unsigned int hashval;
12135 hashval = ((unsigned char) *p) << 4;
12136 while (*p && *p != '=')
12137 hashval += (unsigned char) *p++;
12138 return &vartab[hashval % VTABSIZE];
12144 * Returns true if the two strings specify the same varable. The first
12145 * variable name is terminated by '='; the second may be terminated by
12146 * either '=' or '\0'.
12149 static int varequal(const char *p, const char *q)
12151 while (*p == *q++) {
12155 if (*p == '=' && *(q - 1) == '\0')
12160 static void showvars(const char *myprefix, int mask, int xor)
12164 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12166 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
12167 for (vp = *vpp; vp; vp = vp->next) {
12168 if ((vp->flags & mask) ^ xor) {
12172 p = strchr(vp->text, '=') + 1;
12173 len = p - vp->text;
12174 p = single_quote(p);
12176 printf("%s%s%.*s%s\n", myprefix, sep, len, vp->text, p);
12183 static struct var **findvar(struct var **vpp, const char *name)
12185 for (; *vpp; vpp = &(*vpp)->next) {
12186 if (varequal((*vpp)->text, name)) {
12194 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12195 * This file contains code for the times builtin.
12197 static int timescmd(int argc, char **argv)
12200 long int clk_tck = sysconf(_SC_CLK_TCK);
12203 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12204 (int) (buf.tms_utime / clk_tck / 60),
12205 ((double) buf.tms_utime) / clk_tck,
12206 (int) (buf.tms_stime / clk_tck / 60),
12207 ((double) buf.tms_stime) / clk_tck,
12208 (int) (buf.tms_cutime / clk_tck / 60),
12209 ((double) buf.tms_cutime) / clk_tck,
12210 (int) (buf.tms_cstime / clk_tck / 60),
12211 ((double) buf.tms_cstime) / clk_tck);
12215 #ifdef CONFIG_ASH_MATH_SUPPORT
12216 /* The let builtin. */
12217 int letcmd(int argc, char **argv)
12223 char *tmp, *expression, p[13];
12225 expression = strchr(argv[1], '=');
12227 /* Cannot use 'error()' here, or the return code
12228 * will be incorrect */
12229 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12232 *expression = '\0';
12233 tmp = ++expression;
12234 result = arith(tmp, &errcode);
12236 /* Cannot use 'error()' here, or the return code
12237 * will be incorrect */
12238 out2fmt("sh: let: ");
12240 out2fmt("divide by zero");
12242 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12245 snprintf(p, 12, "%ld", result);
12246 setvar(argv[1], bb_xstrdup(p), 0);
12247 } else if (argc >= 3)
12248 synerror("invalid operand");
12256 * Copyright (c) 1989, 1991, 1993, 1994
12257 * The Regents of the University of California. All rights reserved.
12259 * This code is derived from software contributed to Berkeley by
12260 * Kenneth Almquist.
12262 * Redistribution and use in source and binary forms, with or without
12263 * modification, are permitted provided that the following conditions
12265 * 1. Redistributions of source code must retain the above copyright
12266 * notice, this list of conditions and the following disclaimer.
12267 * 2. Redistributions in binary form must reproduce the above copyright
12268 * notice, this list of conditions and the following disclaimer in the
12269 * documentation and/or other materials provided with the distribution.
12271 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12272 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12274 * 4. Neither the name of the University nor the names of its contributors
12275 * may be used to endorse or promote products derived from this software
12276 * without specific prior written permission.
12278 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12279 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12280 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12281 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12282 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12283 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12284 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12285 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12286 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12287 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF