1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * This version of ash is adapted from the source in Debian's ash 0.3.8-5
28 * Modified by Erik Andersen <andersee@debian.org> and
29 * Vladimir Oleynik <dzo@simtreas.ru> to be used in busybox
32 * Original copyright notice is retained at the end of this file.
36 /* Enable this to compile in extra debugging noise. When debugging is
37 * on, debugging info will be written to $HOME/trace and a quit signal
38 * will generate a core dump. */
41 /* These are here to work with glibc -- Don't change these... */
63 #include <sys/cdefs.h>
64 #include <sys/ioctl.h>
65 #include <sys/param.h>
66 #include <sys/resource.h>
68 #include <sys/times.h>
69 #include <sys/types.h>
75 #if !defined(FNMATCH_BROKEN)
78 #if !defined(GLOB_BROKEN)
82 #ifdef CONFIG_ASH_JOB_CONTROL
89 * This file was generated by the mksyntax program.
93 #define CWORD 0 /* character is nothing special */
94 #define CNL 1 /* newline character */
95 #define CBACK 2 /* a backslash character */
96 #define CSQUOTE 3 /* single quote */
97 #define CDQUOTE 4 /* double quote */
98 #define CENDQUOTE 5 /* a terminating quote */
99 #define CBQUOTE 6 /* backwards single quote */
100 #define CVAR 7 /* a dollar sign */
101 #define CENDVAR 8 /* a '}' character */
102 #define CLP 9 /* a left paren in arithmetic */
103 #define CRP 10 /* a right paren in arithmetic */
104 #define CENDFILE 11 /* end of file */
105 #define CCTL 12 /* like CWORD, except it must be escaped */
106 #define CSPCL 13 /* these terminate a word */
107 #define CIGN 14 /* character should be ignored */
127 #define TENDBQUOTE 13
147 /* control characters in argument strings */
148 #define CTLESC '\201'
149 #define CTLVAR '\202'
150 #define CTLENDVAR '\203'
151 #define CTLBACKQ '\204'
152 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
153 /* CTLBACKQ | CTLQUOTE == '\205' */
154 #define CTLARI '\206'
155 #define CTLENDARI '\207'
156 #define CTLQUOTEMARK '\210'
159 #define is_digit(c) ((c)>='0' && (c)<='9')
160 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
161 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
164 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
165 * (assuming ascii char codes, as the original implementation did)
167 #define is_special(c) \
168 ( (((unsigned int)c) - 33 < 32) \
169 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
171 #define digit_val(c) ((c) - '0')
174 #define S_DFL 1 /* default signal handling (SIG_DFL) */
175 #define S_CATCH 2 /* signal is caught */
176 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
177 #define S_HARD_IGN 4 /* signal is ignored permenantly */
178 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
181 /* variable substitution byte (follows CTLVAR) */
182 #define VSTYPE 0x0f /* type of variable substitution */
183 #define VSNUL 0x10 /* colon--treat the empty string as unset */
184 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
186 /* values of VSTYPE field */
187 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
188 #define VSMINUS 0x2 /* ${var-text} */
189 #define VSPLUS 0x3 /* ${var+text} */
190 #define VSQUESTION 0x4 /* ${var?message} */
191 #define VSASSIGN 0x5 /* ${var=text} */
192 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
193 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
194 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
195 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
196 #define VSLENGTH 0xa /* ${#var} */
198 /* flags passed to redirect */
199 #define REDIR_PUSH 01 /* save previous values of file descriptors */
200 #define REDIR_BACKQ 02 /* save the command output to pipe */
203 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
204 * so we use _setjmp instead.
208 #define setjmp(jmploc) _setjmp(jmploc)
209 #define longjmp(jmploc, val) _longjmp(jmploc, val)
213 * Most machines require the value returned from malloc to be aligned
214 * in some way. The following macro will get this right on many machines.
223 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
226 #ifdef CONFIG_LOCALE_SUPPORT
228 static void change_lc_all(const char *value);
229 static void change_lc_ctype(const char *value);
233 * These macros allow the user to suspend the handling of interrupt signals
234 * over a period of time. This is similar to SIGHOLD to or sigblock, but
235 * much more efficient and portable. (But hacking the kernel is so much
236 * more fun than worrying about efficiency and portability. :-))
239 static void onint (void);
240 static volatile int suppressint;
241 static volatile int intpending;
243 #define INTOFF suppressint++
244 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
245 #define INTON { if (--suppressint == 0 && intpending) onint(); }
246 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
248 static void __inton (void);
249 static void forceinton (void);
250 #define INTON __inton()
251 #define FORCEINTON forceinton()
254 #define CLEAR_PENDING_INT intpending = 0
255 #define int_pending() intpending
258 typedef void *pointer;
260 #define NULL (void *)0
263 static pointer stalloc (int);
264 static void stunalloc (pointer);
265 static void ungrabstackstr (char *, char *);
266 static char * growstackstr(void);
267 static char * makestrspace(size_t newlen);
268 static char *sstrdup (const char *);
271 * Parse trees for commands are allocated in lifo order, so we use a stack
272 * to make this more efficient, and also to avoid all sorts of exception
273 * handling code to handle interrupts in the middle of a parse.
275 * The size 504 was chosen because the Ultrix malloc handles that size
279 #define MINSIZE 504 /* minimum size of a block */
283 struct stack_block *prev;
287 static struct stack_block stackbase;
288 static struct stack_block *stackp = &stackbase;
289 static struct stackmark *markp;
290 static char *stacknxt = stackbase.space;
291 static int stacknleft = MINSIZE;
294 #define equal(s1, s2) (strcmp(s1, s2) == 0)
296 #define stackblock() stacknxt
297 #define stackblocksize() stacknleft
298 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
300 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
301 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
302 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
305 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
306 #define STUNPUTC(p) (++sstrnleft, --p)
307 #define STTOPC(p) p[-1]
308 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
309 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
311 #define ckfree(p) free((pointer)(p))
315 #define TRACE(param) trace param
316 typedef union node unode;
317 static void trace (const char *, ...);
318 static void trargs (char **);
319 static void showtree (unode *);
320 static void trputc (int);
321 static void trputs (const char *);
322 static void opentrace (void);
357 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
358 #define EXP_TILDE 0x2 /* do normal tilde expansion */
359 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
360 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
361 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
362 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
367 static char optet_vals[NOPTS];
369 static const char * const optlist[NOPTS] = {
388 #define optent_name(optent) (optent+1)
389 #define optent_letter(optent) optent[0]
390 #define optent_val(optent) optet_vals[optent]
392 #define eflag optent_val(0)
393 #define fflag optent_val(1)
394 #define Iflag optent_val(2)
395 #define iflag optent_val(3)
396 #define mflag optent_val(4)
397 #define nflag optent_val(5)
398 #define sflag optent_val(6)
399 #define xflag optent_val(7)
400 #define vflag optent_val(8)
401 #define Vflag optent_val(9)
402 #define Eflag optent_val(10)
403 #define Cflag optent_val(11)
404 #define aflag optent_val(12)
405 #define bflag optent_val(13)
406 #define uflag optent_val(14)
407 #define qflag optent_val(15)
410 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
428 union node *redirect;
435 struct nodelist *cmdlist;
442 union node *redirect;
450 union node *elsepart;
481 struct nodelist *backquote;
519 struct nbinary nbinary;
522 struct nredir nredir;
526 struct nclist nclist;
536 struct nodelist *next;
540 struct backcmd { /* result of evalbackcmd */
541 int fd; /* file descriptor to read from */
542 char *buf; /* buffer */
543 int nleft; /* number of chars in buffer */
544 struct job *jp; /* job structure for command */
552 const struct builtincmd *cmd;
557 struct strlist *next;
563 struct strlist *list;
564 struct strlist **lastp;
568 struct strpush *prev; /* preceding string on stack */
571 #ifdef CONFIG_ASH_ALIAS
572 struct alias *ap; /* if push was associated with an alias */
574 char *string; /* remember the string since it may change */
578 struct parsefile *prev; /* preceding file on stack */
579 int linno; /* current line */
580 int fd; /* file descriptor (or -1 if string) */
581 int nleft; /* number of chars left in this line */
582 int lleft; /* number of chars left in this buffer */
583 char *nextc; /* next char in buffer */
584 char *buf; /* input buffer */
585 struct strpush *strpush; /* for pushing strings at this level */
586 struct strpush basestrpush; /* so pushing one is fast */
590 struct stack_block *stackp;
593 struct stackmark *marknext;
597 int nparam; /* # of positional parameters (without $0) */
598 unsigned char malloc; /* if parameter list dynamically allocated */
599 char **p; /* parameter list */
600 int optind; /* next parameter to be processed by getopts */
601 int optoff; /* used by getopts */
605 * When commands are first encountered, they are entered in a hash table.
606 * This ensures that a full path search will not have to be done for them
607 * on each invocation.
609 * We should investigate converting to a linear search, even though that
610 * would make the command name "hash" a misnomer.
612 #define CMDTABLESIZE 31 /* should be prime */
613 #define ARB 1 /* actual size determined at run time */
618 struct tblentry *next; /* next entry in hash chain */
619 union param param; /* definition of builtin function */
620 short cmdtype; /* index identifying command */
621 char rehash; /* if set, cd done since entry created */
622 char cmdname[ARB]; /* name of command */
626 static struct tblentry *cmdtable[CMDTABLESIZE];
627 static int builtinloc = -1; /* index in path of %builtin, or -1 */
628 static int exerrno = 0; /* Last exec error */
631 static void tryexec (char *, char **, char **);
632 static void printentry (struct tblentry *, int);
633 static void clearcmdentry (int);
634 static struct tblentry *cmdlookup (const char *, int);
635 static void delete_cmd_entry (void);
636 static int path_change (const char *, int *);
639 static void flushall (void);
640 static void out2fmt (const char *, ...)
641 __attribute__((__format__(__printf__,1,2)));
642 static int xwrite (int, const char *, int);
644 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
645 static void out1str(const char *p) { outstr(p, stdout); }
646 static void out2str(const char *p) { outstr(p, stderr); }
648 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
649 #define out2c(c) putc((c), stderr)
651 static void out2c(int c) { putc(c, stderr); }
655 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
656 #define USE_SIT_FUNCTION
659 /* number syntax index */
660 #define BASESYNTAX 0 /* not in quotes */
661 #define DQSYNTAX 1 /* in double quotes */
662 #define SQSYNTAX 2 /* in single quotes */
663 #define ARISYNTAX 3 /* in arithmetic */
665 static const char S_I_T[][4] = {
666 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
667 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
668 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
669 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
670 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
671 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
672 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
673 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
674 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
675 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
676 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
677 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
678 #ifndef USE_SIT_FUNCTION
679 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
680 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
681 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
685 #ifdef USE_SIT_FUNCTION
687 #define U_C(c) ((unsigned char)(c))
689 static int SIT(int c, int syntax)
691 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
692 static const char syntax_index_table [] = {
693 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
694 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
695 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
700 if(c==PEOF) /* 2^8+2 */
702 if(c==PEOA) /* 2^8+1 */
704 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
707 s = strchr(spec_symbls, c);
710 indx = syntax_index_table[(s-spec_symbls)];
712 return S_I_T[indx][syntax];
715 #else /* USE_SIT_FUNCTION */
717 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
719 #define CSPCL_CIGN_CIGN_CIGN 0
720 #define CSPCL_CWORD_CWORD_CWORD 1
721 #define CNL_CNL_CNL_CNL 2
722 #define CWORD_CCTL_CCTL_CWORD 3
723 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
724 #define CVAR_CVAR_CWORD_CVAR 5
725 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
726 #define CSPCL_CWORD_CWORD_CLP 7
727 #define CSPCL_CWORD_CWORD_CRP 8
728 #define CBACK_CBACK_CCTL_CBACK 9
729 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
730 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
731 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
732 #define CWORD_CWORD_CWORD_CWORD 13
733 #define CCTL_CCTL_CCTL_CCTL 14
735 static const char syntax_index_table[258] = {
736 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
737 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
738 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
739 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
740 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
741 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
742 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
743 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
744 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
745 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
746 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
747 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
748 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
749 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
750 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
751 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
752 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
753 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
754 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
755 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
756 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
757 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
758 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
759 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
760 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
761 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
762 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
763 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
764 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
765 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
766 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
767 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
768 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
769 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
770 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
771 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
772 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
773 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
774 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
775 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
776 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
777 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
778 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
779 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
780 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
781 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
782 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
783 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
784 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
785 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
786 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
787 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
788 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
789 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
790 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
791 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
792 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
793 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
794 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
795 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
796 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
797 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
798 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
799 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
800 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
801 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
802 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
803 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
804 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
805 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
806 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
807 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
808 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
809 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
810 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
811 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
812 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
813 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
814 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
815 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
816 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
817 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
818 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
819 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
820 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
821 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
822 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
823 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
824 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
825 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
826 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
827 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
828 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
829 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
830 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
831 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
832 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
833 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
834 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
835 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
836 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
837 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
838 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
839 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
840 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
841 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
842 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
843 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
844 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
845 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
846 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
847 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
848 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
849 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
850 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
851 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
852 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
853 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
854 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
855 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
856 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
857 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
858 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
859 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
860 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
861 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
862 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
863 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
864 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
865 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
866 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
867 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
868 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
869 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
870 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
871 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
872 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
873 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
874 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
875 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
876 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
877 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
878 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
879 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
880 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
881 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
882 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
883 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
884 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
885 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
886 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
887 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
888 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
889 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
890 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
891 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
892 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
893 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
894 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
895 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
896 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
897 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
898 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
899 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
900 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
901 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
902 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
903 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
904 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
905 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
906 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
907 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
908 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
909 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
910 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
911 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
912 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
913 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
914 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
915 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
916 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
917 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
918 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
919 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
920 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
921 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
922 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
923 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
924 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
925 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
926 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
927 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
928 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
929 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
930 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
931 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
932 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
933 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
934 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
935 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
936 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
937 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
938 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
939 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
940 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
941 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
942 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
943 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
944 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
945 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
946 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
947 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
948 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
949 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
950 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
951 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
952 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
953 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
954 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
955 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
956 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
957 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
958 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
959 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
960 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
961 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
962 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
963 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
964 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
965 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
966 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
967 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
968 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
969 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
970 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
971 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
972 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
973 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
974 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
975 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
976 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
977 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
978 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
979 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
980 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
981 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
982 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
983 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
984 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
985 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
986 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
987 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
988 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
989 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
990 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
991 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
992 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
993 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
994 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
997 #endif /* USE_SIT_FUNCTION */
1000 /* first char is indicating which tokens mark the end of a list */
1001 static const char *const tokname_array[] = {
1016 #define KWDOFFSET 14
1017 /* the following are keywords */
1036 static const char *tokname(int tok)
1038 static char buf[16];
1042 sprintf(buf+(tok>=TSEMI), "%s%c",
1043 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1047 static int plinno = 1; /* input line number */
1049 static int parselleft; /* copy of parsefile->lleft */
1051 static struct parsefile basepf; /* top level input file */
1052 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1053 static struct parsefile *parsefile = &basepf; /* current input file */
1056 * NEOF is returned by parsecmd when it encounters an end of file. It
1057 * must be distinct from NULL, so we use the address of a variable that
1058 * happens to be handy.
1061 static int tokpushback; /* last token pushed back */
1062 #define NEOF ((union node *)&tokpushback)
1063 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1066 static void error (const char *, ...) __attribute__((__noreturn__));
1067 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1068 static void shellexec (char **, char **, const char *, int)
1069 __attribute__((noreturn));
1070 static void exitshell (int) __attribute__((noreturn));
1072 static int goodname(const char *);
1073 static void ignoresig (int);
1074 static void onsig (int);
1075 static void dotrap (void);
1076 static int decode_signal (const char *, int);
1078 static void shprocvar(void);
1079 static void deletefuncs(void);
1080 static void setparam (char **);
1081 static void freeparam (volatile struct shparam *);
1083 static void find_command (const char *, struct cmdentry *, int, const char *);
1085 static inline void hashcd (void);
1087 /* reasons for skipping commands (see comment on breakcmd routine) */
1093 /* values of cmdtype */
1094 #define CMDUNKNOWN -1 /* no entry in table for command */
1095 #define CMDNORMAL 0 /* command is an executable program */
1096 #define CMDBUILTIN 1 /* command is a shell builtin */
1097 #define CMDFUNCTION 2 /* command is a shell function */
1099 #define DO_ERR 1 /* find_command prints errors */
1100 #define DO_ABS 2 /* find_command checks absolute paths */
1101 #define DO_NOFUN 4 /* find_command ignores functions */
1102 #define DO_BRUTE 8 /* find_command ignores hash table */
1109 #define VEXPORT 0x01 /* variable is exported */
1110 #define VREADONLY 0x02 /* variable cannot be modified */
1111 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1112 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1113 #define VSTACK 0x10 /* text is allocated on the stack */
1114 #define VUNSET 0x20 /* the variable is not set */
1115 #define VNOFUNC 0x40 /* don't call the callback function */
1119 struct var *next; /* next entry in hash list */
1120 int flags; /* flags are defined above */
1121 char *text; /* name=value */
1122 void (*func) (const char *);
1123 /* function to be called when */
1124 /* the variable gets set/unset */
1128 struct localvar *next; /* next local variable in list */
1129 struct var *vp; /* the variable that was made local */
1130 int flags; /* saved flags */
1131 char *text; /* saved text */
1135 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1136 #define rmescapes(p) _rmescapes((p), 0)
1137 static char *_rmescapes (char *, int);
1139 static void rmescapes (char *);
1142 static int casematch (union node *, const char *);
1143 static void clearredir(void);
1144 static void popstring(void);
1145 static void readcmdfile (const char *);
1147 static int number (const char *);
1148 static int is_number (const char *, int *num);
1149 static char *single_quote (const char *);
1150 static int nextopt (const char *);
1152 static void redirect (union node *, int);
1153 static void popredir (void);
1154 static int dup_as_newfd (int, int);
1156 static void changepath(const char *newval);
1157 static void getoptsreset(const char *value);
1160 static int parsenleft; /* copy of parsefile->nleft */
1161 static char *parsenextc; /* copy of parsefile->nextc */
1162 static int rootpid; /* pid of main shell */
1163 static int rootshell; /* true if we aren't a child of the main shell */
1165 static const char spcstr[] = " ";
1166 static const char snlfmt[] = "%s\n";
1168 static int sstrnleft;
1169 static int herefd = -1;
1171 static struct localvar *localvars;
1173 static struct var vifs;
1174 static struct var vmail;
1175 static struct var vmpath;
1176 static struct var vpath;
1177 static struct var vps1;
1178 static struct var vps2;
1179 static struct var voptind;
1180 #ifdef CONFIG_LOCALE_SUPPORT
1181 static struct var vlc_all;
1182 static struct var vlc_ctype;
1189 void (*func) (const char *);
1192 static const char defpathvar[] =
1193 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1194 #define defpath (defpathvar + 5)
1197 static const char defifsvar[] = "IFS= \t\n";
1198 #define defifs (defifsvar + 4)
1200 static const char defifs[] = " \t\n";
1203 static const struct varinit varinit[] = {
1205 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1207 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1210 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1212 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1214 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1216 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1217 { &vps1, VSTRFIXED|VTEXTFIXED, "PS1=\\w \\$ ",
1219 #endif /* else vps1 depends on uid */
1220 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1222 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1224 #ifdef CONFIG_LOCALE_SUPPORT
1225 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1227 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1236 static struct var *vartab[VTABSIZE];
1239 * The following macros access the values of the above variables.
1240 * They have to skip over the name. They return the null string
1241 * for unset variables.
1244 #define ifsval() (vifs.text + 4)
1245 #define ifsset() ((vifs.flags & VUNSET) == 0)
1246 #define mailval() (vmail.text + 5)
1247 #define mpathval() (vmpath.text + 9)
1248 #define pathval() (vpath.text + 5)
1249 #define ps1val() (vps1.text + 4)
1250 #define ps2val() (vps2.text + 4)
1251 #define optindval() (voptind.text + 7)
1253 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1255 static void initvar (void);
1256 static void setvar (const char *, const char *, int);
1257 static void setvareq (char *, int);
1258 static void listsetvar (struct strlist *);
1259 static const char *lookupvar (const char *);
1260 static const char *bltinlookup (const char *);
1261 static char **environment (void);
1262 static int showvarscmd (int, char **);
1263 static void mklocal (char *);
1264 static void poplocalvars (void);
1265 static int unsetvar (const char *);
1266 static int varequal (const char *, const char *);
1269 static char *arg0; /* value of $0 */
1270 static struct shparam shellparam; /* current positional parameters */
1271 static char **argptr; /* argument list for builtin commands */
1272 static char *optionarg; /* set by nextopt (like getopt) */
1273 static char *optptr; /* used by nextopt */
1274 static char *minusc; /* argument to -c option */
1277 #ifdef CONFIG_ASH_ALIAS
1279 #define ALIASINUSE 1
1291 static struct alias *atab[ATABSIZE];
1293 static void setalias (char *, char *);
1294 static struct alias **hashalias (const char *);
1295 static struct alias *freealias (struct alias *);
1296 static struct alias **__lookupalias (const char *);
1299 setalias(char *name, char *val)
1301 struct alias *ap, **app;
1303 app = __lookupalias(name);
1307 if (!(ap->flag & ALIASINUSE)) {
1310 ap->val = xstrdup(val);
1311 ap->flag &= ~ALIASDEAD;
1314 ap = xmalloc(sizeof (struct alias));
1315 ap->name = xstrdup(name);
1316 ap->val = xstrdup(val);
1329 app = __lookupalias(name);
1333 *app = freealias(*app);
1344 struct alias *ap, **app;
1348 for (i = 0; i < ATABSIZE; i++) {
1350 for (ap = *app; ap; ap = *app) {
1351 *app = freealias(*app);
1361 printalias(const struct alias *ap) {
1364 p = single_quote(ap->val);
1365 printf("alias %s=%s\n", ap->name, p);
1371 * TODO - sort output
1374 aliascmd(int argc, char **argv)
1383 for (i = 0; i < ATABSIZE; i++)
1384 for (ap = atab[i]; ap; ap = ap->next) {
1389 while ((n = *++argv) != NULL) {
1390 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1391 if ((ap = *__lookupalias(n)) == NULL) {
1392 out2fmt("%s: %s not found\n", "alias", n);
1407 unaliascmd(int argc, char **argv)
1411 while ((i = nextopt("a")) != '\0') {
1417 for (i = 0; *argptr; argptr++) {
1418 if (unalias(*argptr)) {
1419 out2fmt("%s: %s not found\n", "unalias", *argptr);
1427 static struct alias **
1428 hashalias(const char *p)
1430 unsigned int hashval;
1435 return &atab[hashval % ATABSIZE];
1438 static struct alias *
1439 freealias(struct alias *ap)
1443 if (ap->flag & ALIASINUSE) {
1444 ap->flag |= ALIASDEAD;
1456 static struct alias **
1457 __lookupalias(const char *name)
1459 struct alias **app = hashalias(name);
1461 for (; *app; app = &(*app)->next) {
1462 if (equal(name, (*app)->name)) {
1471 #ifdef CONFIG_ASH_MATH_SUPPORT
1472 /* The generated file arith.c has been replaced with a custom hand
1473 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1474 * This is now part of libbb, so that it can be used by all the shells
1476 static void expari (int);
1479 static char *trap[NSIG]; /* trap handler commands */
1480 static char sigmode[NSIG - 1]; /* current value of signal */
1481 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1482 static int pendingsigs; /* indicates some signal received */
1485 * This file was generated by the mkbuiltins program.
1488 #ifdef CONFIG_ASH_JOB_CONTROL
1489 static int bgcmd (int, char **);
1490 static int fgcmd (int, char **);
1491 static int killcmd (int, char **);
1493 static int bltincmd (int, char **);
1494 static int cdcmd (int, char **);
1495 static int breakcmd (int, char **);
1496 #ifdef CONFIG_ASH_CMDCMD
1497 static int commandcmd (int, char **);
1499 static int dotcmd (int, char **);
1500 static int evalcmd (int, char **);
1501 static int execcmd (int, char **);
1502 static int exitcmd (int, char **);
1503 static int exportcmd (int, char **);
1504 static int histcmd (int, char **);
1505 static int hashcmd (int, char **);
1506 static int helpcmd (int, char **);
1507 static int jobscmd (int, char **);
1508 static int localcmd (int, char **);
1509 static int pwdcmd (int, char **);
1510 static int readcmd (int, char **);
1511 static int returncmd (int, char **);
1512 static int setcmd (int, char **);
1513 static int setvarcmd (int, char **);
1514 static int shiftcmd (int, char **);
1515 static int trapcmd (int, char **);
1516 static int umaskcmd (int, char **);
1517 #ifdef CONFIG_ASH_ALIAS
1518 static int aliascmd (int, char **);
1519 static int unaliascmd (int, char **);
1521 static int unsetcmd (int, char **);
1522 static int waitcmd (int, char **);
1523 static int ulimitcmd (int, char **);
1524 static int timescmd (int, char **);
1525 #ifdef CONFIG_ASH_MATH_SUPPORT
1526 static int letcmd (int, char **);
1528 static int typecmd (int, char **);
1529 #ifdef CONFIG_ASH_GETOPTS
1530 static int getoptscmd (int, char **);
1534 static int true_main (int, char **);
1536 #ifndef CONFIG_FALSE
1537 static int false_main (int, char **);
1540 static void setpwd (const char *, int);
1543 #define BUILTIN_NOSPEC "0"
1544 #define BUILTIN_SPECIAL "1"
1545 #define BUILTIN_REGULAR "2"
1546 #define BUILTIN_ASSIGN "4"
1547 #define BUILTIN_SPEC_ASSG "5"
1548 #define BUILTIN_REG_ASSG "6"
1550 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1551 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1552 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1556 int (*const builtinfunc) (int, char **);
1561 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1562 * the binary search in find_builtin() will stop working. If you value
1563 * your kneecaps, you'll be sure to *make sure* that any changes made
1564 * to this array result in the listing remaining in ascii order. You
1567 static const struct builtincmd builtincmds[] = {
1568 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1569 { BUILTIN_SPECIAL ":", true_main },
1570 #ifdef CONFIG_ASH_ALIAS
1571 { BUILTIN_REG_ASSG "alias", aliascmd },
1573 #ifdef CONFIG_ASH_JOB_CONTROL
1574 { BUILTIN_REGULAR "bg", bgcmd },
1576 { BUILTIN_SPECIAL "break", breakcmd },
1577 { BUILTIN_SPECIAL "builtin", bltincmd },
1578 { BUILTIN_REGULAR "cd", cdcmd },
1579 { BUILTIN_NOSPEC "chdir", cdcmd },
1580 #ifdef CONFIG_ASH_CMDCMD
1581 { BUILTIN_REGULAR "command", commandcmd },
1583 { BUILTIN_SPECIAL "continue", breakcmd },
1584 { BUILTIN_SPECIAL "eval", evalcmd },
1585 { BUILTIN_SPECIAL "exec", execcmd },
1586 { BUILTIN_SPECIAL "exit", exitcmd },
1587 { BUILTIN_SPEC_ASSG "export", exportcmd },
1588 { BUILTIN_REGULAR "false", false_main },
1589 { BUILTIN_REGULAR "fc", histcmd },
1590 #ifdef CONFIG_ASH_JOB_CONTROL
1591 { BUILTIN_REGULAR "fg", fgcmd },
1593 #ifdef CONFIG_ASH_GETOPTS
1594 { BUILTIN_REGULAR "getopts", getoptscmd },
1596 { BUILTIN_NOSPEC "hash", hashcmd },
1597 { BUILTIN_NOSPEC "help", helpcmd },
1598 { BUILTIN_REGULAR "jobs", jobscmd },
1599 #ifdef CONFIG_ASH_JOB_CONTROL
1600 { BUILTIN_REGULAR "kill", killcmd },
1602 #ifdef CONFIG_ASH_MATH_SUPPORT
1603 { BUILTIN_REGULAR "let", letcmd },
1605 { BUILTIN_ASSIGN "local", localcmd },
1606 { BUILTIN_NOSPEC "pwd", pwdcmd },
1607 { BUILTIN_REGULAR "read", readcmd },
1608 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1609 { BUILTIN_SPECIAL "return", returncmd },
1610 { BUILTIN_SPECIAL "set", setcmd },
1611 { BUILTIN_NOSPEC "setvar", setvarcmd },
1612 { BUILTIN_SPECIAL "shift", shiftcmd },
1613 { BUILTIN_SPECIAL "times", timescmd },
1614 { BUILTIN_SPECIAL "trap", trapcmd },
1615 { BUILTIN_REGULAR "true", true_main },
1616 { BUILTIN_NOSPEC "type", typecmd },
1617 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1618 { BUILTIN_REGULAR "umask", umaskcmd },
1619 #ifdef CONFIG_ASH_ALIAS
1620 { BUILTIN_REGULAR "unalias", unaliascmd },
1622 { BUILTIN_SPECIAL "unset", unsetcmd },
1623 { BUILTIN_REGULAR "wait", waitcmd },
1625 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1627 #define DOTCMD &builtincmds[0]
1628 static struct builtincmd *BLTINCMD;
1629 static struct builtincmd *EXECCMD;
1630 static struct builtincmd *EVALCMD;
1633 #define CONFIG_ASH_JOB_CONTROLTOPPED 1 /* all procs are stopped */
1634 #define JOBDONE 2 /* all procs are completed */
1637 * A job structure contains information about a job. A job is either a
1638 * single process or a set of processes contained in a pipeline. In the
1639 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1644 pid_t pid; /* process id */
1645 int status; /* status flags (defined above) */
1646 char *cmd; /* text of command being run */
1650 static int job_warning; /* user was warned about stopped jobs */
1652 #ifdef CONFIG_ASH_JOB_CONTROL
1653 static void setjobctl(int enable);
1655 #define setjobctl(on) /* do nothing */
1660 struct procstat ps0; /* status of process */
1661 struct procstat *ps; /* status or processes when more than one */
1662 short nprocs; /* number of processes */
1663 short pgrp; /* process group of this job */
1664 char state; /* true if job is finished */
1665 char used; /* true if this entry is in used */
1666 char changed; /* true if status has changed */
1667 #ifdef CONFIG_ASH_JOB_CONTROL
1668 char jobctl; /* job running under job control */
1672 static struct job *jobtab; /* array of jobs */
1673 static int njobs; /* size of array */
1674 static int backgndpid = -1; /* pid of last background process */
1675 #ifdef CONFIG_ASH_JOB_CONTROL
1676 static int initialpgrp; /* pgrp of shell on invocation */
1677 static int curjob; /* current job */
1680 static int intreceived;
1682 static struct job *makejob (const union node *, int);
1683 static int forkshell (struct job *, const union node *, int);
1684 static int waitforjob (struct job *);
1686 static int docd (char *, int);
1687 static void getpwd (void);
1689 static char *padvance (const char **, const char *);
1691 static char nullstr[1]; /* zero length string */
1692 static char *curdir = nullstr; /* current working directory */
1695 cdcmd(int argc, char **argv)
1704 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1705 error("HOME not set");
1708 if (dest[0] == '-' && dest[1] == '\0') {
1709 dest = bltinlookup("OLDPWD");
1710 if (!dest || !*dest) {
1719 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1721 while ((p = padvance(&path, dest)) != NULL) {
1722 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1727 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1729 print = strcmp(p, dest);
1731 if (docd(p, print) >= 0)
1736 error("can't cd to %s", dest);
1742 * Actually do the chdir. In an interactive shell, print the
1743 * directory name if "print" is nonzero.
1747 docd(char *dest, int print)
1749 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1751 if (chdir(dest) < 0) {
1757 * Update curdir (the name of the current directory) in response to a
1758 * cd command. We also call hashcd to let the routines in exec.c know
1759 * that the current directory has changed.
1761 /* If dest is NULL, we don't know the current directory */
1762 if (dest == NULL || curdir == nullstr)
1775 pwdcmd(int argc, char **argv)
1781 /* Ask system the current directory */
1785 curdir = xgetcwd(0);
1791 setpwd(const char *val, int setold)
1796 setvar("OLDPWD", curdir, VEXPORT);
1799 if (curdir != nullstr) {
1800 if(val!=NULL && *val != '/')
1801 val = cated = concat_path_file(curdir, val);
1807 curdir = simplify_path(val);
1810 setvar("PWD", curdir, VEXPORT);
1814 * Errors and exceptions.
1818 * Code to handle exceptions in C.
1822 * We enclose jmp_buf in a structure so that we can declare pointers to
1823 * jump locations. The global variable handler contains the location to
1824 * jump to when an exception occurs, and the global variable exception
1825 * contains a code identifying the exeception. To implement nested
1826 * exception handlers, the user should save the value of handler on entry
1827 * to an inner scope, set handler to point to a jmploc structure for the
1828 * inner scope, and restore handler on exit from the scope.
1836 #define EXINT 0 /* SIGINT received */
1837 #define EXERROR 1 /* a generic error */
1838 #define EXSHELLPROC 2 /* execute a shell procedure */
1839 #define EXEXEC 3 /* command execution failed */
1841 static struct jmploc *handler;
1842 static int exception;
1844 static void exverror (int, const char *, va_list)
1845 __attribute__((__noreturn__));
1848 * Called to raise an exception. Since C doesn't include exceptions, we
1849 * just do a longjmp to the exception handler. The type of exception is
1850 * stored in the global variable "exception".
1853 static void exraise (int) __attribute__((__noreturn__));
1859 if (handler == NULL)
1864 longjmp(handler->loc, 1);
1869 * Called from trap.c when a SIGINT is received. (If the user specifies
1870 * that SIGINT is to be trapped or ignored using the trap builtin, then
1871 * this routine is not called.) Suppressint is nonzero when interrupts
1872 * are held using the INTOFF macro. The call to _exit is necessary because
1873 * there is a short period after a fork before the signal handlers are
1874 * set to the appropriate value for the child. (The test for iflag is
1875 * just defensive programming.)
1887 sigemptyset(&mysigset);
1888 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1889 if (rootshell && iflag)
1892 signal(SIGINT, SIG_DFL);
1899 static char *commandname; /* currently executing command */
1902 * Exverror is called to raise the error exception. If the first argument
1903 * is not NULL then error prints an error message using printf style
1904 * formatting. It then raises the error exception.
1907 exverror(int cond, const char *msg, va_list ap)
1914 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1916 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1920 out2fmt("%s: ", commandname);
1921 vfprintf(stderr, msg, ap);
1930 error(const char *msg, ...)
1934 exverror(EXERROR, msg, ap);
1941 exerror(int cond, const char *msg, ...)
1945 exverror(cond, msg, ap);
1953 * Table of error messages.
1957 short errcode; /* error number */
1958 short action; /* operation which encountered the error */
1962 * Types of operations (passed to the errmsg routine).
1965 #define E_OPEN 01 /* opening a file */
1966 #define E_CREAT 02 /* creating a file */
1967 #define E_EXEC 04 /* executing a program */
1969 #define ALL (E_OPEN|E_CREAT|E_EXEC)
1971 static const struct errname errormsg[] = {
1976 { ENOENT, E_CREAT },
1978 { ENOTDIR, E_OPEN },
1979 { ENOTDIR, E_CREAT },
1980 { ENOTDIR, E_EXEC },
1982 { EEXIST, E_CREAT },
2021 { ELIBACC, E_EXEC },
2025 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2028 * Return a string describing an error. The returned string may be a
2029 * pointer to a static buffer that will be overwritten on the next call.
2030 * Action describes the operation that got the error.
2034 errmsg(int e, int action)
2036 struct errname const *ep;
2037 static char buf[12];
2039 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2040 if (ep->errcode == e && (ep->action & action) != 0)
2044 snprintf(buf, sizeof buf, "error %d", e);
2049 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
2052 if (--suppressint == 0 && intpending) {
2056 static void forceinton (void) {
2063 /* flags in argument to evaltree */
2064 #define EV_EXIT 01 /* exit after evaluating tree */
2065 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2066 #define EV_BACKCMD 04 /* command executing within back quotes */
2068 static int evalskip; /* set if we are skipping commands */
2069 static int skipcount; /* number of levels to skip */
2070 static int loopnest; /* current loop nesting level */
2071 static int funcnest; /* depth of function calls */
2074 static struct strlist *cmdenviron; /* environment for builtin command */
2075 static int exitstatus; /* exit status of last command */
2076 static int oexitstatus; /* saved exit status */
2078 static void evalsubshell (const union node *, int);
2079 static void expredir (union node *);
2080 static void eprintlist (struct strlist *);
2082 static union node *parsecmd(int);
2084 * Called to reset things after an exception.
2088 * The eval commmand.
2090 static void evalstring (char *, int);
2093 evalcmd(int argc, char **argv)
2102 STARTSTACKSTR(concat);
2106 STPUTC(*p++, concat);
2107 if ((p = *ap++) == NULL)
2109 STPUTC(' ', concat);
2111 STPUTC('\0', concat);
2112 p = grabstackstr(concat);
2114 evalstring(p, EV_TESTED);
2120 * Execute a command or commands contained in a string.
2123 static void evaltree (union node *, int);
2124 static void setinputstring (char *);
2125 static void popfile (void);
2126 static void setstackmark(struct stackmark *mark);
2127 static void popstackmark(struct stackmark *mark);
2131 evalstring(char *s, int flag)
2134 struct stackmark smark;
2136 setstackmark(&smark);
2138 while ((n = parsecmd(0)) != NEOF) {
2140 popstackmark(&smark);
2143 popstackmark(&smark);
2146 static struct builtincmd *find_builtin (const char *);
2147 static void expandarg (union node *, struct arglist *, int);
2148 static void calcsize (const union node *);
2149 static union node *copynode (const union node *);
2152 * Make a copy of a parse tree.
2155 static int funcblocksize; /* size of structures in function */
2156 static int funcstringsize; /* size of strings in node */
2157 static pointer funcblock; /* block to allocate function from */
2158 static char *funcstring; /* block to allocate strings from */
2161 static inline union node *
2162 copyfunc(union node *n)
2169 funcblock = xmalloc(funcblocksize + funcstringsize);
2170 funcstring = (char *) funcblock + funcblocksize;
2175 * Free a parse tree.
2179 freefunc(union node *n)
2187 * Add a new command entry, replacing any existing command entry for
2192 addcmdentry(char *name, struct cmdentry *entry)
2194 struct tblentry *cmdp;
2197 cmdp = cmdlookup(name, 1);
2198 if (cmdp->cmdtype == CMDFUNCTION) {
2199 freefunc(cmdp->param.func);
2201 cmdp->cmdtype = entry->cmdtype;
2202 cmdp->param = entry->u;
2207 evalloop(const union node *n, int flags)
2214 evaltree(n->nbinary.ch1, EV_TESTED);
2216 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2220 if (evalskip == SKIPBREAK && --skipcount <= 0)
2224 if (n->type == NWHILE) {
2225 if (exitstatus != 0)
2228 if (exitstatus == 0)
2231 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2232 status = exitstatus;
2237 exitstatus = status;
2241 evalfor(const union node *n, int flags)
2243 struct arglist arglist;
2246 struct stackmark smark;
2248 setstackmark(&smark);
2249 arglist.lastp = &arglist.list;
2250 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2251 oexitstatus = exitstatus;
2252 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2256 *arglist.lastp = NULL;
2260 for (sp = arglist.list ; sp ; sp = sp->next) {
2261 setvar(n->nfor.var, sp->text, 0);
2262 evaltree(n->nfor.body, flags & EV_TESTED);
2264 if (evalskip == SKIPCONT && --skipcount <= 0) {
2268 if (evalskip == SKIPBREAK && --skipcount <= 0)
2275 popstackmark(&smark);
2279 evalcase(const union node *n, int flags)
2283 struct arglist arglist;
2284 struct stackmark smark;
2286 setstackmark(&smark);
2287 arglist.lastp = &arglist.list;
2288 oexitstatus = exitstatus;
2289 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2290 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2291 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2292 if (casematch(patp, arglist.list->text)) {
2293 if (evalskip == 0) {
2294 evaltree(cp->nclist.body, flags);
2301 popstackmark(&smark);
2305 * Evaluate a pipeline. All the processes in the pipeline are children
2306 * of the process creating the pipeline. (This differs from some versions
2307 * of the shell, which make the last process in a pipeline the parent
2311 static inline void evalpipe(union node *n)
2314 struct nodelist *lp;
2319 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2321 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2324 jp = makejob(n, pipelen);
2326 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2328 * Search for a command. This is called before we fork so that the
2329 * location of the command will be available in the parent as well as
2330 * the child. The check for "goodname" is an overly conservative
2331 * check that the name will not be subject to expansion.
2334 struct cmdentry entry;
2335 union node *lpn = lp->n;
2336 if (lpn->type == NCMD && lpn->ncmd.args && goodname(lpn->ncmd.args->narg.text))
2337 find_command(lpn->ncmd.args->narg.text, &entry, 0, pathval());
2341 if (pipe(pip) < 0) {
2343 error("Pipe call failed");
2346 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2350 dup_as_newfd(prevfd, 0);
2362 dup_as_newfd(pip[1], 1);
2366 evaltree(lp->n, EV_EXIT);
2374 if (n->npipe.backgnd == 0) {
2376 exitstatus = waitforjob(jp);
2377 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2383 isassignment(const char *word) {
2384 if (!is_name(*word)) {
2389 } while (is_in_name(*word));
2390 return *word == '=';
2395 evalcommand(union node *cmd, int flags)
2397 struct stackmark smark;
2399 struct arglist arglist;
2400 struct arglist varlist;
2406 struct cmdentry cmdentry;
2408 char *volatile savecmdname;
2409 volatile struct shparam saveparam;
2410 struct localvar *volatile savelocalvars;
2414 const struct builtincmd *firstbltin;
2415 struct jmploc *volatile savehandler;
2416 struct jmploc jmploc;
2418 /* Avoid longjmp clobbering */
2425 /* First expand the arguments. */
2426 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2427 setstackmark(&smark);
2428 arglist.lastp = &arglist.list;
2429 varlist.lastp = &varlist.list;
2431 oexitstatus = exitstatus;
2434 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2435 expandarg(argp, &varlist, EXP_VARTILDE);
2438 argp = cmd->ncmd.args; argp && !arglist.list;
2439 argp = argp->narg.next
2441 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2444 struct builtincmd *bcmd;
2446 bcmd = find_builtin(arglist.list->text);
2447 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2448 for (; argp; argp = argp->narg.next) {
2449 if (pseudovarflag && isassignment(argp->narg.text)) {
2450 expandarg(argp, &arglist, EXP_VARTILDE);
2453 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2456 *arglist.lastp = NULL;
2457 *varlist.lastp = NULL;
2458 expredir(cmd->ncmd.redirect);
2460 for (sp = arglist.list ; sp ; sp = sp->next)
2462 argv = stalloc(sizeof (char *) * (argc + 1));
2464 for (sp = arglist.list ; sp ; sp = sp->next) {
2465 TRACE(("evalcommand arg: %s\n", sp->text));
2470 if (iflag && funcnest == 0 && argc > 0)
2474 /* Print the command if xflag is set. */
2477 eprintlist(varlist.list);
2478 eprintlist(arglist.list);
2482 /* Now locate the command. */
2484 cmdentry.cmdtype = CMDBUILTIN;
2485 firstbltin = cmdentry.u.cmd = BLTINCMD;
2487 const char *oldpath;
2488 int findflag = DO_ERR;
2492 * Modify the command lookup path, if a PATH= assignment
2495 for (sp = varlist.list ; sp ; sp = sp->next)
2496 if (varequal(sp->text, defpathvar)) {
2497 path = sp->text + 5;
2498 findflag |= DO_BRUTE;
2501 oldfindflag = findflag;
2504 find_command(argv[0], &cmdentry, findflag, path);
2505 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2509 /* implement bltin and command here */
2510 if (cmdentry.cmdtype != CMDBUILTIN) {
2514 firstbltin = cmdentry.u.cmd;
2516 if (cmdentry.u.cmd == BLTINCMD) {
2518 struct builtincmd *bcmd;
2523 if (!(bcmd = find_builtin(*argv))) {
2524 out2fmt("%s: not found\n", *argv);
2528 cmdentry.u.cmd = bcmd;
2529 if (bcmd != BLTINCMD)
2533 if (cmdentry.u.cmd == find_builtin("command")) {
2538 if (*argv[0] == '-') {
2539 if (!equal(argv[0], "-p")) {
2549 findflag |= DO_BRUTE;
2552 findflag = oldfindflag;
2554 findflag |= DO_NOFUN;
2562 /* Fork off a child process if necessary. */
2563 if (cmd->ncmd.backgnd
2564 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2566 jp = makejob(cmd, 1);
2567 mode = cmd->ncmd.backgnd;
2568 if (forkshell(jp, cmd, mode) != 0)
2569 goto parent; /* at end of routine */
2573 /* This is the child process if a fork occurred. */
2574 /* Execute the command. */
2575 if (cmdentry.cmdtype == CMDFUNCTION) {
2577 trputs("Shell function: "); trargs(argv);
2579 exitstatus = oexitstatus;
2580 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2581 saveparam = shellparam;
2582 shellparam.malloc = 0;
2583 shellparam.nparam = argc - 1;
2584 shellparam.p = argv + 1;
2586 savelocalvars = localvars;
2589 if (setjmp(jmploc.loc)) {
2590 if (exception == EXSHELLPROC) {
2591 freeparam((volatile struct shparam *)
2594 saveparam.optind = shellparam.optind;
2595 saveparam.optoff = shellparam.optoff;
2596 freeparam(&shellparam);
2597 shellparam = saveparam;
2600 localvars = savelocalvars;
2601 handler = savehandler;
2602 longjmp(handler->loc, 1);
2604 savehandler = handler;
2606 for (sp = varlist.list ; sp ; sp = sp->next)
2609 evaltree(cmdentry.u.func, flags & EV_TESTED);
2613 localvars = savelocalvars;
2614 saveparam.optind = shellparam.optind;
2615 saveparam.optoff = shellparam.optoff;
2616 freeparam(&shellparam);
2617 shellparam = saveparam;
2618 handler = savehandler;
2621 if (evalskip == SKIPFUNC) {
2625 if (flags & EV_EXIT)
2626 exitshell(exitstatus);
2627 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2629 trputs("builtin command: "); trargs(argv);
2631 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2632 redirect(cmd->ncmd.redirect, mode);
2633 savecmdname = commandname;
2634 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2635 listsetvar(varlist.list);
2637 cmdenviron = varlist.list;
2640 if (setjmp(jmploc.loc)) {
2642 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2645 savehandler = handler;
2647 commandname = argv[0];
2649 optptr = NULL; /* initialize nextopt */
2650 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2654 if (e != EXSHELLPROC) {
2655 commandname = savecmdname;
2656 if (flags & EV_EXIT)
2657 exitshell(exitstatus);
2659 handler = savehandler;
2661 if ((e != EXERROR && e != EXEXEC)
2662 || cmdentry.u.cmd == BLTINCMD
2663 || cmdentry.u.cmd == DOTCMD
2664 || cmdentry.u.cmd == EVALCMD
2665 || cmdentry.u.cmd == EXECCMD)
2669 if (cmdentry.u.cmd != EXECCMD)
2673 trputs("normal command: "); trargs(argv);
2675 redirect(cmd->ncmd.redirect, 0);
2677 for (sp = varlist.list ; sp ; sp = sp->next)
2678 setvareq(sp->text, VEXPORT|VSTACK);
2679 envp = environment();
2680 shellexec(argv, envp, path, cmdentry.u.index);
2684 parent: /* parent process gets here (if we forked) */
2685 if (mode == 0) { /* argument to fork */
2687 exitstatus = waitforjob(jp);
2693 setvar("_", lastarg, 0);
2694 popstackmark(&smark);
2698 * Evaluate a parse tree. The value is left in the global variable
2702 evaltree(union node *n, int flags)
2706 TRACE(("evaltree(NULL) called\n"));
2709 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2712 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2715 evaltree(n->nbinary.ch2, flags);
2718 evaltree(n->nbinary.ch1, EV_TESTED);
2719 if (evalskip || exitstatus != 0)
2721 evaltree(n->nbinary.ch2, flags);
2724 evaltree(n->nbinary.ch1, EV_TESTED);
2725 if (evalskip || exitstatus == 0)
2727 evaltree(n->nbinary.ch2, flags);
2730 expredir(n->nredir.redirect);
2731 redirect(n->nredir.redirect, REDIR_PUSH);
2732 evaltree(n->nredir.n, flags);
2736 evalsubshell(n, flags);
2739 evalsubshell(n, flags);
2742 evaltree(n->nif.test, EV_TESTED);
2745 if (exitstatus == 0)
2746 evaltree(n->nif.ifpart, flags);
2747 else if (n->nif.elsepart)
2748 evaltree(n->nif.elsepart, flags);
2764 struct builtincmd *bcmd;
2765 struct cmdentry entry;
2767 (bcmd = find_builtin(n->narg.text)) &&
2768 IS_BUILTIN_SPECIAL(bcmd)
2770 out2fmt("%s is a special built-in\n", n->narg.text);
2774 entry.cmdtype = CMDFUNCTION;
2775 entry.u.func = copyfunc(n->narg.next);
2776 addcmdentry(n->narg.text, &entry);
2781 evaltree(n->nnot.com, EV_TESTED);
2782 exitstatus = !exitstatus;
2790 evalcommand(n, flags);
2795 printf("Node type = %d\n", n->type);
2804 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2806 exitshell(exitstatus);
2810 * Kick off a subshell to evaluate a tree.
2814 evalsubshell(const union node *n, int flags)
2817 int backgnd = (n->type == NBACKGND);
2819 expredir(n->nredir.redirect);
2821 if (forkshell(jp, n, backgnd) == 0) {
2823 flags &=~ EV_TESTED;
2824 redirect(n->nredir.redirect, 0);
2825 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2829 exitstatus = waitforjob(jp);
2835 * Compute the names of the files in a redirection list.
2838 static void fixredir(union node *n, const char *text, int err);
2841 expredir(union node *n)
2845 for (redir = n ; redir ; redir = redir->nfile.next) {
2847 fn.lastp = &fn.list;
2848 oexitstatus = exitstatus;
2849 switch (redir->type) {
2855 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2856 redir->nfile.expfname = fn.list->text;
2860 if (redir->ndup.vname) {
2861 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2862 fixredir(redir, fn.list->text, 1);
2871 * Execute a command inside back quotes. If it's a builtin command, we
2872 * want to save its output in a block obtained from malloc. Otherwise
2873 * we fork off a subprocess and get the output of the command via a pipe.
2874 * Should be called with interrupts off.
2878 evalbackcmd(union node *n, struct backcmd *result)
2882 struct stackmark smark; /* unnecessary */
2884 setstackmark(&smark);
2895 error("Pipe call failed");
2897 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2902 dup_as_newfd(pip[1], 1);
2906 evaltree(n, EV_EXIT);
2909 result->fd = pip[0];
2912 popstackmark(&smark);
2913 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2914 result->fd, result->buf, result->nleft, result->jp));
2919 * Execute a simple command.
2924 * Builtin commands. Builtin commands whose functions are closely
2925 * tied to evaluation are implemented here.
2929 * No command given, or a bltin command with no arguments. Set the
2930 * specified variables.
2934 bltincmd(int argc, char **argv)
2937 * Preserve exitstatus of a previous possible redirection
2945 * Handle break and continue commands. Break, continue, and return are
2946 * all handled by setting the evalskip flag. The evaluation routines
2947 * above all check this flag, and if it is set they start skipping
2948 * commands rather than executing them. The variable skipcount is
2949 * the number of loops to break/continue, or the number of function
2950 * levels to return. (The latter is always 1.) It should probably
2951 * be an error to break out of more loops than exist, but it isn't
2952 * in the standard shell so we don't make it one here.
2956 breakcmd(int argc, char **argv)
2958 int n = argc > 1 ? number(argv[1]) : 1;
2961 error("Illegal number: %s", argv[1]);
2965 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
2973 * The return command.
2977 returncmd(int argc, char **argv)
2979 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
2982 evalskip = SKIPFUNC;
2987 /* Do what ksh does; skip the rest of the file */
2988 evalskip = SKIPFILE;
2995 #ifndef CONFIG_FALSE
2997 false_main(int argc, char **argv)
3005 true_main(int argc, char **argv)
3012 * Controls whether the shell is interactive or not.
3015 static void setsignal(int signo);
3017 #ifdef CONFIG_ASH_MAIL
3018 static void chkmail(int silent);
3022 setinteractive(int on)
3024 static int is_interactive;
3025 static int do_banner=0;
3027 if (on == is_interactive)
3032 #ifdef CONFIG_ASH_MAIL
3035 is_interactive = on;
3036 if (do_banner==0 && is_interactive) {
3037 /* Looks like they want an interactive shell */
3038 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3039 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3040 printf( "Enter 'help' for a list of built-in commands.\n\n");
3049 setinteractive(iflag);
3055 execcmd(int argc, char **argv)
3060 iflag = 0; /* exit on error */
3063 for (sp = cmdenviron; sp ; sp = sp->next)
3064 setvareq(sp->text, VEXPORT|VSTACK);
3065 shellexec(argv + 1, environment(), pathval(), 0);
3071 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 */
3086 shellexec(char **argv, char **envp, const char *path, int idx)
3091 if (strchr(argv[0], '/') != NULL) {
3092 tryexec(argv[0], argv, envp);
3096 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3097 if (--idx < 0 && pathopt == NULL) {
3098 tryexec(cmdname, argv, envp);
3099 if (errno != ENOENT && errno != ENOTDIR)
3106 /* Map to POSIX errors */
3118 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3123 * Clear traps on a fork.
3130 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3131 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3136 setsignal(tp - trap);
3147 #ifdef CONFIG_ASH_ALIAS
3166 #ifdef CONFIG_ASH_JOB_CONTROL
3171 /* from options.c: */
3175 for (i = 0; i < NOPTS; i++)
3191 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3203 static int preadbuffer(void);
3204 static void pushfile (void);
3207 * Read a character from the script, returning PEOF on end of file.
3208 * Nul characters in the input are silently discarded.
3211 #ifndef CONFIG_ASH_OPTIMIZE_FOR_SIZE
3212 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3216 return pgetc_macro();
3222 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3228 return pgetc_macro();
3234 * Undo the last call to pgetc. Only one character may be pushed back.
3235 * PEOF may be pushed back.
3238 static void pungetc(void)
3248 struct parsefile *pf = parsefile;
3257 parsefile = pf->prev;
3259 parsenleft = parsefile->nleft;
3260 parselleft = parsefile->lleft;
3261 parsenextc = parsefile->nextc;
3262 plinno = parsefile->linno;
3268 * Return to top level.
3274 while (parsefile != &basepf)
3279 * Close the file(s) that the shell is reading commands from. Called
3280 * after a fork is done.
3283 static void closescript(void)
3286 if (parsefile->fd > 0) {
3287 close(parsefile->fd);
3294 * Like setinputfile, but takes an open file descriptor. Call this with
3298 static void setinputfd(int fd, int push)
3300 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3306 while (parsefile->strpush)
3310 if (parsefile->buf == NULL)
3311 parsefile->buf = xmalloc(BUFSIZ);
3312 parselleft = parsenleft = 0;
3318 * Set the input to take input from a file. If push is set, push the
3319 * old input onto the stack first.
3323 setinputfile(const char *fname, int push)
3329 if ((fd = open(fname, O_RDONLY)) < 0)
3330 error("Can't open %s", fname);
3332 myfileno2 = dup_as_newfd(fd, 10);
3335 error("Out of file descriptors");
3338 setinputfd(fd, push);
3344 tryexec(char *cmd, char **argv, char **envp)
3348 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3352 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3353 name = get_last_path_component(name);
3356 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3359 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3361 run_applet_by_name(name, argc_l, argv);
3363 execve(cmd, argv, envp);
3368 setinputfile(cmd, 0);
3369 commandname = arg0 = xstrdup(argv[0]);
3371 exraise(EXSHELLPROC);
3376 static char *commandtext (const union node *);
3379 * Do a path search. The variable path (passed by reference) should be
3380 * set to the start of the path before the first call; padvance will update
3381 * this value as it proceeds. Successive calls to padvance will return
3382 * the possible path expansions in sequence. If an option (indicated by
3383 * a percent sign) appears in the path entry then the global variable
3384 * pathopt will be set to point to it; otherwise pathopt will be set to
3388 static const char *pathopt;
3390 static void growstackblock(void);
3394 padvance(const char **path, const char *name)
3404 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3405 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3406 while (stackblocksize() < len)
3410 memcpy(q, start, p - start);
3418 while (*p && *p != ':') p++;
3424 return stalloc(len);
3428 * Wrapper around strcmp for qsort/bsearch/...
3431 pstrcmp(const void *a, const void *b)
3433 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3437 * Find a keyword is in a sorted array.
3440 static const char *const *
3441 findkwd(const char *s)
3443 return bsearch(s, tokname_array + KWDOFFSET,
3444 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3445 sizeof(const char *), pstrcmp);
3449 /*** Command hashing code ***/
3453 hashcmd(int argc, char **argv)
3455 struct tblentry **pp;
3456 struct tblentry *cmdp;
3459 struct cmdentry entry;
3461 #ifdef CONFIG_ASH_ALIAS
3462 const struct alias *ap;
3466 while ((c = nextopt("rvV")) != '\0') {
3470 } else if (c == 'v' || c == 'V') {
3474 if (*argptr == NULL) {
3475 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3476 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3477 if (cmdp->cmdtype != CMDBUILTIN) {
3478 printentry(cmdp, verbose);
3485 while ((name = *argptr++) != NULL) {
3486 if ((cmdp = cmdlookup(name, 0)) != NULL
3487 && (cmdp->cmdtype == CMDNORMAL
3488 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3490 #ifdef CONFIG_ASH_ALIAS
3491 /* Then look at the aliases */
3492 if ((ap = *__lookupalias(name)) != NULL) {
3494 printf("%s is an alias for %s\n", name, ap->val);
3500 /* First look at the keywords */
3501 if (findkwd(name)!=0) {
3503 printf("%s is a shell keyword\n", name);
3509 find_command(name, &entry, DO_ERR, pathval());
3510 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3512 cmdp = cmdlookup(name, 0);
3513 if (cmdp) printentry(cmdp, verbose=='v');
3521 printentry(struct tblentry *cmdp, int verbose)
3527 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3528 if (cmdp->cmdtype == CMDNORMAL) {
3529 idx = cmdp->param.index;
3532 name = padvance(&path, cmdp->cmdname);
3534 } while (--idx >= 0);
3537 } else if (cmdp->cmdtype == CMDBUILTIN) {
3539 out1str("a shell builtin");
3540 } else if (cmdp->cmdtype == CMDFUNCTION) {
3543 out1str("a function\n");
3544 name = commandtext(cmdp->param.func);
3545 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3551 error("internal error: cmdtype %d", cmdp->cmdtype);
3554 puts(cmdp->rehash ? "*" : nullstr);
3559 /*** List the available builtins ***/
3562 static int helpcmd(int argc, char** argv)
3566 printf("\nBuilt-in commands:\n-------------------\n");
3567 for (col=0, i=0; i < NUMBUILTINS; i++) {
3568 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3569 builtincmds[i].name+1);
3575 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3577 extern const struct BB_applet applets[];
3578 extern const size_t NUM_APPLETS;
3580 for (i=0; i < NUM_APPLETS; i++) {
3582 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3592 return EXIT_SUCCESS;
3596 * Resolve a command name. If you change this routine, you may have to
3597 * change the shellexec routine as well.
3600 static int prefix (const char *, const char *);
3603 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3605 struct tblentry *cmdp;
3615 struct builtincmd *bcmd;
3617 /* If name contains a slash, don't use the hash table */
3618 if (strchr(name, '/') != NULL) {
3620 while (stat(name, &statb) < 0) {
3621 if (errno != ENOENT && errno != ENOTDIR)
3623 entry->cmdtype = CMDUNKNOWN;
3624 entry->u.index = -1;
3627 entry->cmdtype = CMDNORMAL;
3628 entry->u.index = -1;
3631 entry->cmdtype = CMDNORMAL;
3637 if (act & DO_BRUTE) {
3638 firstchange = path_change(path, &bltin);
3644 /* If name is in the table, and not invalidated by cd, we're done */
3645 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3646 if (cmdp->cmdtype == CMDFUNCTION) {
3647 if (act & DO_NOFUN) {
3652 } else if (act & DO_BRUTE) {
3653 if ((cmdp->cmdtype == CMDNORMAL &&
3654 cmdp->param.index >= firstchange) ||
3655 (cmdp->cmdtype == CMDBUILTIN &&
3656 ((builtinloc < 0 && bltin >= 0) ?
3657 bltin : builtinloc) >= firstchange)) {
3658 /* need to recompute the entry */
3667 bcmd = find_builtin(name);
3668 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3671 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3674 } else if (act & DO_BRUTE) {
3675 if (firstchange == 0) {
3680 /* If %builtin not in path, check for builtin next */
3681 if (regular || (bltin < 0 && bcmd)) {
3684 entry->cmdtype = CMDBUILTIN;
3685 entry->u.cmd = bcmd;
3689 cmdp = cmdlookup(name, 1);
3690 cmdp->cmdtype = CMDBUILTIN;
3691 cmdp->param.cmd = bcmd;
3696 /* We have to search path. */
3697 prev = -1; /* where to start */
3698 if (cmdp && cmdp->rehash) { /* doing a rehash */
3699 if (cmdp->cmdtype == CMDBUILTIN)
3702 prev = cmdp->param.index;
3708 while ((fullname = padvance(&path, name)) != NULL) {
3709 stunalloc(fullname);
3711 if (idx >= firstchange) {
3715 if (prefix("builtin", pathopt)) {
3716 if ((bcmd = find_builtin(name))) {
3720 } else if (!(act & DO_NOFUN) &&
3721 prefix("func", pathopt)) {
3724 continue; /* ignore unimplemented options */
3727 /* if rehash, don't redo absolute path names */
3728 if (fullname[0] == '/' && idx <= prev &&
3729 idx < firstchange) {
3732 TRACE(("searchexec \"%s\": no change\n", name));
3735 while (stat(fullname, &statb) < 0) {
3736 if (errno != ENOENT && errno != ENOTDIR)
3740 e = EACCES; /* if we fail, this will be the error */
3741 if (!S_ISREG(statb.st_mode))
3743 if (pathopt) { /* this is a %func directory */
3744 stalloc(strlen(fullname) + 1);
3745 readcmdfile(fullname);
3746 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3747 error("%s not defined in %s", name, fullname);
3748 stunalloc(fullname);
3751 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3752 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3753 be a function and we're being called with DO_NOFUN */
3755 entry->cmdtype = CMDNORMAL;
3756 entry->u.index = idx;
3760 cmdp = cmdlookup(name, 1);
3761 cmdp->cmdtype = CMDNORMAL;
3762 cmdp->param.index = idx;
3767 /* We failed. If there was an entry for this command, delete it */
3768 if (cmdp && updatetbl)
3771 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3772 entry->cmdtype = CMDUNKNOWN;
3777 entry->cmdtype = cmdp->cmdtype;
3778 entry->u = cmdp->param;
3784 * Search the table of builtin commands.
3788 bstrcmp(const void *name, const void *b)
3790 return strcmp((const char *)name, (*(const char *const *) b)+1);
3793 static struct builtincmd *
3794 find_builtin(const char *name)
3796 struct builtincmd *bp;
3798 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3806 * Called when a cd is done. Marks all commands so the next time they
3807 * are executed they will be rehashed.
3813 struct tblentry **pp;
3814 struct tblentry *cmdp;
3816 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3817 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3818 if (cmdp->cmdtype == CMDNORMAL
3819 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3828 * Called before PATH is changed. The argument is the new value of PATH;
3829 * pathval() still returns the old value at this point. Called with
3834 changepath(const char *newval)
3839 firstchange = path_change(newval, &bltin);
3840 if (builtinloc < 0 && bltin >= 0)
3841 builtinloc = bltin; /* zap builtins */
3842 clearcmdentry(firstchange);
3848 * Clear out command entries. The argument specifies the first entry in
3849 * PATH which has changed.
3853 clearcmdentry(int firstchange)
3855 struct tblentry **tblp;
3856 struct tblentry **pp;
3857 struct tblentry *cmdp;
3860 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3862 while ((cmdp = *pp) != NULL) {
3863 if ((cmdp->cmdtype == CMDNORMAL &&
3864 cmdp->param.index >= firstchange)
3865 || (cmdp->cmdtype == CMDBUILTIN &&
3866 builtinloc >= firstchange)) {
3879 * Delete all functions.
3885 struct tblentry **tblp;
3886 struct tblentry **pp;
3887 struct tblentry *cmdp;
3890 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3892 while ((cmdp = *pp) != NULL) {
3893 if (cmdp->cmdtype == CMDFUNCTION) {
3895 freefunc(cmdp->param.func);
3908 * Locate a command in the command hash table. If "add" is nonzero,
3909 * add the command to the table if it is not already present. The
3910 * variable "lastcmdentry" is set to point to the address of the link
3911 * pointing to the entry, so that delete_cmd_entry can delete the
3915 static struct tblentry **lastcmdentry;
3917 static struct tblentry *
3918 cmdlookup(const char *name, int add)
3922 struct tblentry *cmdp;
3923 struct tblentry **pp;
3930 pp = &cmdtable[hashval % CMDTABLESIZE];
3931 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3932 if (equal(cmdp->cmdname, name))
3936 if (add && cmdp == NULL) {
3938 cmdp = *pp = xmalloc(sizeof (struct tblentry) - ARB
3939 + strlen(name) + 1);
3941 cmdp->cmdtype = CMDUNKNOWN;
3943 strcpy(cmdp->cmdname, name);
3951 * Delete the command entry returned on the last lookup.
3957 struct tblentry *cmdp;
3960 cmdp = *lastcmdentry;
3961 *lastcmdentry = cmdp->next;
3970 static const unsigned char nodesize[26] = {
3971 ALIGN(sizeof (struct nbinary)),
3972 ALIGN(sizeof (struct ncmd)),
3973 ALIGN(sizeof (struct npipe)),
3974 ALIGN(sizeof (struct nredir)),
3975 ALIGN(sizeof (struct nredir)),
3976 ALIGN(sizeof (struct nredir)),
3977 ALIGN(sizeof (struct nbinary)),
3978 ALIGN(sizeof (struct nbinary)),
3979 ALIGN(sizeof (struct nif)),
3980 ALIGN(sizeof (struct nbinary)),
3981 ALIGN(sizeof (struct nbinary)),
3982 ALIGN(sizeof (struct nfor)),
3983 ALIGN(sizeof (struct ncase)),
3984 ALIGN(sizeof (struct nclist)),
3985 ALIGN(sizeof (struct narg)),
3986 ALIGN(sizeof (struct narg)),
3987 ALIGN(sizeof (struct nfile)),
3988 ALIGN(sizeof (struct nfile)),
3989 ALIGN(sizeof (struct nfile)),
3990 ALIGN(sizeof (struct nfile)),
3991 ALIGN(sizeof (struct nfile)),
3992 ALIGN(sizeof (struct ndup)),
3993 ALIGN(sizeof (struct ndup)),
3994 ALIGN(sizeof (struct nhere)),
3995 ALIGN(sizeof (struct nhere)),
3996 ALIGN(sizeof (struct nnot)),
4002 * Delete a function if it exists.
4006 unsetfunc(char *name)
4008 struct tblentry *cmdp;
4010 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4011 freefunc(cmdp->param.func);
4018 * Locate and print what a word is...
4022 typecmd(int argc, char **argv)
4030 for (i = 1; i < argc; i++) {
4031 argv_a[0] = argv[i];
4034 err |= hashcmd(argc, argv);
4039 #ifdef CONFIG_ASH_CMDCMD
4041 commandcmd(int argc, char **argv)
4044 int default_path = 0;
4045 int verify_only = 0;
4046 int verbose_verify_only = 0;
4048 while ((c = nextopt("pvV")) != '\0')
4057 verbose_verify_only = 1;
4061 if (default_path + verify_only + verbose_verify_only > 1 ||
4064 "command [-p] command [arg ...]\n"
4065 "command {-v|-V} command\n");
4069 if (verify_only || verbose_verify_only) {
4073 argv_a[0] = *argptr;
4075 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4076 return hashcmd(argc, argv);
4084 path_change(const char *newval, int *bltin)
4086 const char *old, *new;
4092 firstchange = 9999; /* assume no change */
4098 if ((*old == '\0' && *new == ':')
4099 || (*old == ':' && *new == '\0'))
4101 old = new; /* ignore subsequent differences */
4105 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4112 if (builtinloc >= 0 && *bltin < 0)
4114 /* Ensure that getenv("PATH") stays current */
4115 setenv("PATH", newval, 1);
4119 * Routines to expand arguments to commands. We have to deal with
4120 * backquotes, shell variables, and file metacharacters.
4125 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4126 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4129 * Structure specifying which parts of the string should be searched
4130 * for IFS characters.
4134 struct ifsregion *next; /* next region in list */
4135 int begoff; /* offset of start of region */
4136 int endoff; /* offset of end of region */
4137 int nulonly; /* search for nul bytes only */
4141 static char *expdest; /* output of current string */
4142 static struct nodelist *argbackq; /* list of back quote expressions */
4143 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4144 static struct ifsregion *ifslastp; /* last struct in list */
4145 static struct arglist exparg; /* holds expanded arg list */
4147 static void argstr (char *, int);
4148 static char *exptilde (char *, int);
4149 static void expbackq (union node *, int, int);
4150 static int subevalvar (char *, char *, int, int, int, int, int);
4151 static int varisset (char *, int);
4152 static void strtodest (const char *, int, int);
4153 static inline void varvalue (char *, int, int);
4154 static void recordregion (int, int, int);
4155 static void removerecordregions (int);
4156 static void ifsbreakup (char *, struct arglist *);
4157 static void ifsfree (void);
4158 static void expandmeta (struct strlist *, int);
4159 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4160 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4161 #if !defined(GLOB_BROKEN)
4162 static inline void addglob (const glob_t *);
4165 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4166 static void expmeta (char *, char *);
4168 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4169 static struct strlist *expsort (struct strlist *);
4170 static struct strlist *msort (struct strlist *, int);
4172 static int patmatch (char *, char *, int);
4173 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4174 static int patmatch2 (char *, char *, int);
4176 static int pmatch (char *, char *, int);
4177 #define patmatch2 patmatch
4179 static char *cvtnum (int, char *);
4182 * Expand shell variables and backquotes inside a here document.
4185 /* arg: the document, fd: where to write the expanded version */
4187 expandhere(union node *arg, int fd)
4190 expandarg(arg, (struct arglist *)NULL, 0);
4191 xwrite(fd, stackblock(), expdest - stackblock());
4196 * Perform variable substitution and command substitution on an argument,
4197 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4198 * perform splitting and file name expansion. When arglist is NULL, perform
4199 * here document expansion.
4203 expandarg(union node *arg, struct arglist *arglist, int flag)
4208 argbackq = arg->narg.backquote;
4209 STARTSTACKSTR(expdest);
4210 ifsfirst.next = NULL;
4212 argstr(arg->narg.text, flag);
4213 if (arglist == NULL) {
4214 return; /* here document expanded */
4216 STPUTC('\0', expdest);
4217 p = grabstackstr(expdest);
4218 exparg.lastp = &exparg.list;
4222 if (flag & EXP_FULL) {
4223 ifsbreakup(p, &exparg);
4224 *exparg.lastp = NULL;
4225 exparg.lastp = &exparg.list;
4226 expandmeta(exparg.list, flag);
4228 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4230 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4233 exparg.lastp = &sp->next;
4236 *exparg.lastp = NULL;
4238 *arglist->lastp = exparg.list;
4239 arglist->lastp = exparg.lastp;
4245 * Expand a variable, and return a pointer to the next character in the
4249 static inline char * evalvar(char *p, int flag)
4262 int quotes = flag & (EXP_FULL | EXP_CASE);
4265 subtype = varflags & VSTYPE;
4270 p = strchr(p, '=') + 1;
4271 again: /* jump here after setting a variable with ${var=text} */
4273 set = varisset(var, varflags & VSNUL);
4276 val = lookupvar(var);
4277 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4284 startloc = expdest - stackblock();
4285 if (set && subtype != VSPLUS) {
4286 /* insert the value of the variable */
4288 varvalue(var, varflags & VSQUOTE, flag);
4289 if (subtype == VSLENGTH) {
4290 varlen = expdest - stackblock() - startloc;
4291 STADJUST(-varlen, expdest);
4294 if (subtype == VSLENGTH) {
4295 varlen = strlen(val);
4299 varflags & VSQUOTE ?
4300 DQSYNTAX : BASESYNTAX,
4307 if (subtype == VSPLUS)
4310 easy = ((varflags & VSQUOTE) == 0 ||
4311 (*var == '@' && shellparam.nparam != 1));
4316 expdest = cvtnum(varlen, expdest);
4323 recordregion(startloc, expdest - stackblock(),
4324 varflags & VSQUOTE);
4340 case VSTRIMRIGHTMAX:
4344 * Terminate the string and start recording the pattern
4347 STPUTC('\0', expdest);
4348 patloc = expdest - stackblock();
4349 if (subevalvar(p, NULL, patloc, subtype,
4350 startloc, varflags, quotes) == 0) {
4351 int amount = (expdest - stackblock() - patloc) + 1;
4352 STADJUST(-amount, expdest);
4354 /* Remove any recorded regions beyond start of variable */
4355 removerecordregions(startloc);
4361 if (subevalvar(p, var, 0, subtype, startloc,
4362 varflags, quotes)) {
4365 * Remove any recorded regions beyond
4368 removerecordregions(startloc);
4383 if (subtype != VSNORMAL) { /* skip to end of alternative */
4386 if ((c = *p++) == CTLESC)
4388 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4390 argbackq = argbackq->next;
4391 } else if (c == CTLVAR) {
4392 if ((*p++ & VSTYPE) != VSNORMAL)
4394 } else if (c == CTLENDVAR) {
4405 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4406 * characters to allow for further processing. Otherwise treat
4407 * $@ like $* since no splitting will be performed.
4411 argstr(char *p, int flag)
4414 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4417 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4418 p = exptilde(p, flag);
4422 case CTLENDVAR: /* ??? */
4425 /* "$@" syntax adherence hack */
4426 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4428 if ((flag & EXP_FULL) != 0)
4438 p = evalvar(p, flag);
4441 case CTLBACKQ|CTLQUOTE:
4442 expbackq(argbackq->n, c & CTLQUOTE, flag);
4443 argbackq = argbackq->next;
4445 #ifdef CONFIG_ASH_MATH_SUPPORT
4453 * sort of a hack - expand tildes in variable
4454 * assignments (after the first '=' and after ':'s).
4457 if (flag & EXP_VARTILDE && *p == '~') {
4464 p = exptilde(p, flag);
4475 exptilde(char *p, int flag)
4477 char c, *startp = p;
4480 int quotes = flag & (EXP_FULL | EXP_CASE);
4482 while ((c = *p) != '\0') {
4489 if (flag & EXP_VARTILDE)
4499 if (*(startp+1) == '\0') {
4500 if ((home = lookupvar("HOME")) == NULL)
4503 if ((pw = getpwnam(startp+1)) == NULL)
4510 strtodest(home, SQSYNTAX, quotes);
4519 removerecordregions(int endoff)
4521 if (ifslastp == NULL)
4524 if (ifsfirst.endoff > endoff) {
4525 while (ifsfirst.next != NULL) {
4526 struct ifsregion *ifsp;
4528 ifsp = ifsfirst.next->next;
4529 ckfree(ifsfirst.next);
4530 ifsfirst.next = ifsp;
4533 if (ifsfirst.begoff > endoff)
4536 ifslastp = &ifsfirst;
4537 ifsfirst.endoff = endoff;
4542 ifslastp = &ifsfirst;
4543 while (ifslastp->next && ifslastp->next->begoff < endoff)
4544 ifslastp=ifslastp->next;
4545 while (ifslastp->next != NULL) {
4546 struct ifsregion *ifsp;
4548 ifsp = ifslastp->next->next;
4549 ckfree(ifslastp->next);
4550 ifslastp->next = ifsp;
4553 if (ifslastp->endoff > endoff)
4554 ifslastp->endoff = endoff;
4558 #ifdef CONFIG_ASH_MATH_SUPPORT
4560 * Expand arithmetic expression. Backup to start of expression,
4561 * evaluate, place result in (backed up) result, adjust string position.
4570 int quotes = flag & (EXP_FULL | EXP_CASE);
4576 * This routine is slightly over-complicated for
4577 * efficiency. First we make sure there is
4578 * enough space for the result, which may be bigger
4579 * than the expression if we add exponentation. Next we
4580 * scan backwards looking for the start of arithmetic. If the
4581 * next previous character is a CTLESC character, then we
4582 * have to rescan starting from the beginning since CTLESC
4583 * characters have to be processed left to right.
4585 CHECKSTRSPACE(10, expdest);
4586 USTPUTC('\0', expdest);
4587 start = stackblock();
4589 while (*p != CTLARI && p >= start)
4592 error("missing CTLARI (shouldn't happen)");
4593 if (p > start && *(p-1) == CTLESC)
4594 for (p = start; *p != CTLARI; p++)
4603 removerecordregions(begoff);
4606 result = arith(p+2, &errcode);
4609 error("divide by zero");
4611 error("syntax error: \"%s\"\n", p+2);
4613 snprintf(p, 12, "%d", result);
4619 recordregion(begoff, p - 1 - start, 0);
4620 result = expdest - p + 1;
4621 STADJUST(-result, expdest);
4626 * Expand stuff in backwards quotes.
4630 expbackq(union node *cmd, int quoted, int flag)
4632 volatile struct backcmd in;
4636 char *dest = expdest;
4637 volatile struct ifsregion saveifs;
4638 struct ifsregion *volatile savelastp;
4639 struct nodelist *volatile saveargbackq;
4641 int startloc = dest - stackblock();
4642 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4643 volatile int saveherefd;
4644 int quotes = flag & (EXP_FULL | EXP_CASE);
4645 struct jmploc jmploc;
4646 struct jmploc *volatile savehandler;
4650 /* Avoid longjmp clobbering */
4661 savelastp = ifslastp;
4662 saveargbackq = argbackq;
4663 saveherefd = herefd;
4665 if ((ex = setjmp(jmploc.loc))) {
4668 savehandler = handler;
4671 p = grabstackstr(dest);
4672 evalbackcmd(cmd, (struct backcmd *) &in);
4673 ungrabstackstr(p, dest);
4677 ifslastp = savelastp;
4678 argbackq = saveargbackq;
4679 herefd = saveherefd;
4687 if (--in.nleft < 0) {
4690 i = safe_read(in.fd, buf, sizeof buf);
4691 TRACE(("expbackq: read returns %d\n", i));
4698 if (lastc != '\0') {
4699 if (quotes && SIT(lastc, syntax) == CCTL)
4700 STPUTC(CTLESC, dest);
4701 STPUTC(lastc, dest);
4705 /* Eat all trailing newlines */
4706 for (; dest > stackblock() && dest[-1] == '\n';)
4715 exitstatus = waitforjob(in.jp);
4716 handler = savehandler;
4718 longjmp(handler->loc, 1);
4721 recordregion(startloc, dest - stackblock(), 0);
4722 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4723 (dest - stackblock()) - startloc,
4724 (dest - stackblock()) - startloc,
4725 stackblock() + startloc));
4731 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
4737 int saveherefd = herefd;
4738 struct nodelist *saveargbackq = argbackq;
4742 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4743 STACKSTRNUL(expdest);
4744 herefd = saveherefd;
4745 argbackq = saveargbackq;
4746 startp = stackblock() + startloc;
4748 str = stackblock() + strloc;
4752 setvar(str, startp, 0);
4753 amount = startp - expdest;
4754 STADJUST(amount, expdest);
4761 if (*p != CTLENDVAR) {
4762 out2fmt(snlfmt, startp);
4763 error((char *)NULL);
4765 error("%.*s: parameter %snot set", p - str - 1,
4766 str, (varflags & VSNUL) ? "null or "
4771 for (loc = startp; loc < str; loc++) {
4774 if (patmatch2(str, startp, quotes))
4777 if (quotes && *loc == CTLESC)
4783 for (loc = str - 1; loc >= startp;) {
4786 if (patmatch2(str, startp, quotes))
4790 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4791 for (q = startp; q < loc; q++)
4801 for (loc = str - 1; loc >= startp;) {
4802 if (patmatch2(str, loc, quotes))
4805 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4806 for (q = startp; q < loc; q++)
4815 case VSTRIMRIGHTMAX:
4816 for (loc = startp; loc < str - 1; loc++) {
4817 if (patmatch2(str, loc, quotes))
4819 if (quotes && *loc == CTLESC)
4832 amount = ((str - 1) - (loc - startp)) - expdest;
4833 STADJUST(amount, expdest);
4834 while (loc != str - 1)
4839 amount = loc - expdest;
4840 STADJUST(amount, expdest);
4841 STPUTC('\0', expdest);
4842 STADJUST(-1, expdest);
4848 * Test whether a specialized variable is set.
4852 varisset(char *name, int nulok)
4855 return backgndpid != -1;
4856 else if (*name == '@' || *name == '*') {
4857 if (*shellparam.p == NULL)
4863 for (av = shellparam.p; *av; av++)
4868 } else if (is_digit(*name)) {
4870 int num = atoi(name);
4872 if (num > shellparam.nparam)
4878 ap = shellparam.p[num - 1];
4880 if (nulok && (ap == NULL || *ap == '\0'))
4887 * Put a string on the stack.
4891 strtodest(const char *p, int syntax, int quotes)
4894 if (quotes && SIT(*p,syntax) == CCTL)
4895 STPUTC(CTLESC, expdest);
4896 STPUTC(*p++, expdest);
4901 * Add the value of a specialized variable to the stack string.
4905 varvalue(char *name, int quoted, int flags)
4914 int allow_split = flags & EXP_FULL;
4915 int quotes = flags & (EXP_FULL | EXP_CASE);
4917 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4926 num = shellparam.nparam;
4931 expdest = cvtnum(num, expdest);
4934 for (i = 0 ; i < NOPTS ; i++) {
4936 STPUTC(optent_letter(optlist[i]), expdest);
4940 if (allow_split && quoted) {
4941 sep = 1 << CHAR_BIT;
4946 sep = ifsset() ? ifsval()[0] : ' ';
4948 sepq = SIT(sep,syntax) == CCTL;
4951 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
4952 strtodest(p, syntax, quotes);
4955 STPUTC(CTLESC, expdest);
4956 STPUTC(sep, expdest);
4961 strtodest(arg0, syntax, quotes);
4965 if (num > 0 && num <= shellparam.nparam) {
4966 strtodest(shellparam.p[num - 1], syntax, quotes);
4974 * Record the fact that we have to scan this region of the
4975 * string for IFS characters.
4979 recordregion(int start, int end, int nulonly)
4981 struct ifsregion *ifsp;
4983 if (ifslastp == NULL) {
4987 ifsp = (struct ifsregion *)xmalloc(sizeof (struct ifsregion));
4989 ifslastp->next = ifsp;
4993 ifslastp->begoff = start;
4994 ifslastp->endoff = end;
4995 ifslastp->nulonly = nulonly;
5001 * Break the argument string into pieces based upon IFS and add the
5002 * strings to the argument list. The regions of the string to be
5003 * searched for IFS characters have been stored by recordregion.
5006 ifsbreakup(char *string, struct arglist *arglist)
5008 struct ifsregion *ifsp;
5013 const char *ifs, *realifs;
5021 realifs = ifsset() ? ifsval() : defifs;
5022 if (ifslastp != NULL) {
5025 p = string + ifsp->begoff;
5026 nulonly = ifsp->nulonly;
5027 ifs = nulonly ? nullstr : realifs;
5029 while (p < string + ifsp->endoff) {
5033 if (strchr(ifs, *p)) {
5035 ifsspc = (strchr(defifs, *p) != NULL);
5036 /* Ignore IFS whitespace at start */
5037 if (q == start && ifsspc) {
5043 sp = (struct strlist *)stalloc(sizeof *sp);
5045 *arglist->lastp = sp;
5046 arglist->lastp = &sp->next;
5050 if (p >= string + ifsp->endoff) {
5056 if (strchr(ifs, *p) == NULL ) {
5059 } else if (strchr(defifs, *p) == NULL) {
5075 } while ((ifsp = ifsp->next) != NULL);
5076 if (!(*start || (!ifsspc && start > string && nulonly))) {
5081 sp = (struct strlist *)stalloc(sizeof *sp);
5083 *arglist->lastp = sp;
5084 arglist->lastp = &sp->next;
5090 while (ifsfirst.next != NULL) {
5091 struct ifsregion *ifsp;
5093 ifsp = ifsfirst.next->next;
5094 ckfree(ifsfirst.next);
5095 ifsfirst.next = ifsp;
5099 ifsfirst.next = NULL;
5103 * Add a file name to the list.
5107 addfname(const char *name)
5111 sp = (struct strlist *)stalloc(sizeof *sp);
5112 sp->text = sstrdup(name);
5114 exparg.lastp = &sp->next;
5118 * Expand shell metacharacters. At this point, the only control characters
5119 * should be escapes. The results are stored in the list exparg.
5122 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5124 expandmeta(struct strlist *str, int flag)
5128 /* TODO - EXP_REDIR */
5133 p = preglob(str->text);
5135 switch (glob(p, 0, 0, &pglob)) {
5137 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5148 *exparg.lastp = str;
5149 rmescapes(str->text);
5150 exparg.lastp = &str->next;
5152 default: /* GLOB_NOSPACE */
5153 error("Out of space");
5161 * Add the result of glob(3) to the list.
5165 addglob(const glob_t *pglob)
5167 char **p = pglob->gl_pathv;
5175 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5176 static char *expdir;
5180 expandmeta(struct strlist *str, int flag)
5183 struct strlist **savelastp;
5186 /* TODO - EXP_REDIR */
5192 for (;;) { /* fast check for meta chars */
5193 if ((c = *p++) == '\0')
5195 if (c == '*' || c == '?' || c == '[' || c == '!')
5198 savelastp = exparg.lastp;
5200 if (expdir == NULL) {
5201 int i = strlen(str->text);
5202 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5205 expmeta(expdir, str->text);
5209 if (exparg.lastp == savelastp) {
5214 *exparg.lastp = str;
5215 rmescapes(str->text);
5216 exparg.lastp = &str->next;
5218 *exparg.lastp = NULL;
5219 *savelastp = sp = expsort(*savelastp);
5220 while (sp->next != NULL)
5222 exparg.lastp = &sp->next;
5230 * Do metacharacter (i.e. *, ?, [...]) expansion.
5234 expmeta(char *enddir, char *name)
5250 for (p = name ; ; p++) {
5251 if (*p == '*' || *p == '?')
5253 else if (*p == '[') {
5258 while (*q == CTLQUOTEMARK)
5262 if (*q == '/' || *q == '\0')
5269 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5271 } else if (*p == '\0')
5273 else if (*p == CTLQUOTEMARK)
5275 else if (*p == CTLESC)
5283 if (metaflag == 0) { /* we've reached the end of the file name */
5284 if (enddir != expdir)
5286 for (p = name ; ; p++) {
5287 if (*p == CTLQUOTEMARK)
5295 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5300 if (start != name) {
5303 while (*p == CTLQUOTEMARK)
5310 if (enddir == expdir) {
5312 } else if (enddir == expdir + 1 && *expdir == '/') {
5318 if ((dirp = opendir(cp)) == NULL)
5320 if (enddir != expdir)
5322 if (*endname == 0) {
5330 while (*p == CTLQUOTEMARK)
5336 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5337 if (dp->d_name[0] == '.' && ! matchdot)
5339 if (patmatch(start, dp->d_name, 0)) {
5341 strcpy(enddir, dp->d_name);
5344 for (p = enddir, cp = dp->d_name;
5345 (*p++ = *cp++) != '\0';)
5348 expmeta(p, endname);
5356 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5360 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5362 * Sort the results of file name expansion. It calculates the number of
5363 * strings to sort and then calls msort (short for merge sort) to do the
5367 static struct strlist *
5368 expsort(struct strlist *str)
5374 for (sp = str ; sp ; sp = sp->next)
5376 return msort(str, len);
5380 static struct strlist *
5381 msort(struct strlist *list, int len)
5383 struct strlist *p, *q = NULL;
5384 struct strlist **lpp;
5392 for (n = half ; --n >= 0 ; ) {
5396 q->next = NULL; /* terminate first half of list */
5397 q = msort(list, half); /* sort first half of list */
5398 p = msort(p, len - half); /* sort second half */
5401 if (strcmp(p->text, q->text) < 0) {
5404 if ((p = *lpp) == NULL) {
5411 if ((q = *lpp) == NULL) {
5424 * Returns true if the pattern matches the string.
5427 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5428 /* squoted: string might have quote chars */
5430 patmatch(char *pattern, char *string, int squoted)
5435 p = preglob(pattern);
5436 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5438 return !fnmatch(p, q, 0);
5443 patmatch2(char *pattern, char *string, int squoted)
5449 p = grabstackstr(expdest);
5450 res = patmatch(pattern, string, squoted);
5451 ungrabstackstr(p, expdest);
5456 patmatch(char *pattern, char *string, int squoted) {
5457 return pmatch(pattern, string, squoted);
5462 pmatch(char *pattern, char *string, int squoted)
5474 if (squoted && *q == CTLESC)
5482 if (squoted && *q == CTLESC)
5489 while (c == CTLQUOTEMARK || c == '*')
5491 if (c != CTLESC && c != CTLQUOTEMARK &&
5492 c != '?' && c != '*' && c != '[') {
5494 if (squoted && *q == CTLESC &&
5499 if (squoted && *q == CTLESC)
5505 if (pmatch(p, q, squoted))
5507 if (squoted && *q == CTLESC)
5509 } while (*q++ != '\0');
5520 while (*endp == CTLQUOTEMARK)
5523 goto dft; /* no matching ] */
5524 if (*endp == CTLESC)
5536 if (squoted && chr == CTLESC)
5542 if (c == CTLQUOTEMARK)
5546 if (*p == '-' && p[1] != ']') {
5548 while (*p == CTLQUOTEMARK)
5552 if (chr >= c && chr <= *p)
5559 } while ((c = *p++) != ']');
5560 if (found == invert)
5565 if (squoted && *q == CTLESC)
5582 * Remove any CTLESC characters from a string.
5585 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5587 _rmescapes(char *str, int flag)
5590 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5592 p = strpbrk(str, qchars);
5598 if (flag & RMESCAPE_ALLOC) {
5599 size_t len = p - str;
5600 q = r = stalloc(strlen(p) + len + 1);
5602 memcpy(q, str, len);
5607 if (*p == CTLQUOTEMARK) {
5613 if (flag & RMESCAPE_GLOB && *p != '/') {
5624 rmescapes(char *str)
5629 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5635 if (*p == CTLQUOTEMARK) {
5650 * See if a pattern matches in a case statement.
5654 casematch(union node *pattern, const char *val)
5656 struct stackmark smark;
5660 setstackmark(&smark);
5661 argbackq = pattern->narg.backquote;
5662 STARTSTACKSTR(expdest);
5664 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5665 STPUTC('\0', expdest);
5666 p = grabstackstr(expdest);
5667 result = patmatch(p, (char *)val, 0);
5668 popstackmark(&smark);
5677 cvtnum(int num, char *buf)
5681 CHECKSTRSPACE(32, buf);
5682 len = sprintf(buf, "%d", num);
5687 * Editline and history functions (and glue).
5689 static int histcmd(int argc, char **argv)
5691 error("not compiled with history support");
5697 struct redirtab *next;
5698 short renamed[10]; /* Current ash support only 0-9 descriptors */
5699 /* char on arm (and others) can't be negative */
5702 static struct redirtab *redirlist;
5704 extern char **environ;
5709 * Initialization code.
5723 basepf.nextc = basepf.buf = basebuf;
5732 for (envp = environ ; *envp ; envp++) {
5733 if (strchr(*envp, '=')) {
5734 setvareq(*envp, VEXPORT|VTEXTFIXED);
5738 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5739 setvar("PPID", ppid, 0);
5746 * This routine is called when an error or an interrupt occurs in an
5747 * interactive shell and control is returned to the main command loop.
5750 /* 1 == check for aliases, 2 == also check for assignments */
5751 static int checkalias; /* also used in no alias mode for check assignments */
5765 if (exception != EXSHELLPROC)
5766 parselleft = parsenleft = 0; /* clear input buffer */
5770 /* from parser.c: */
5788 * This file implements the input routines used by the parser.
5791 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5792 static const char * cmdedit_prompt;
5793 static inline void putprompt(const char *s) {
5797 static inline void putprompt(const char *s) {
5802 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5807 * Same as pgetc(), but ignores PEOA.
5810 #ifdef CONFIG_ASH_ALIAS
5817 } while (c == PEOA);
5821 static inline int pgetc2(void) { return pgetc_macro(); }
5825 * Read a line from the script.
5828 static inline char *
5829 pfgets(char *line, int len)
5835 while (--nleft > 0) {
5854 char *buf = parsefile->buf;
5858 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5860 if (!iflag || parsefile->fd)
5861 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5863 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5867 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5871 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5872 int flags = fcntl(0, F_GETFL, 0);
5873 if (flags >= 0 && flags & O_NONBLOCK) {
5874 flags &=~ O_NONBLOCK;
5875 if (fcntl(0, F_SETFL, flags) >= 0) {
5876 out2str("sh: turning off NDELAY mode\n");
5888 struct strpush *sp = parsefile->strpush;
5891 #ifdef CONFIG_ASH_ALIAS
5893 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5898 if (sp->string != sp->ap->val) {
5902 sp->ap->flag &= ~ALIASINUSE;
5903 if (sp->ap->flag & ALIASDEAD) {
5904 unalias(sp->ap->name);
5908 parsenextc = sp->prevstring;
5909 parsenleft = sp->prevnleft;
5910 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5911 parsefile->strpush = sp->prev;
5912 if (sp != &(parsefile->basestrpush))
5919 * Refill the input buffer and return the next input character:
5921 * 1) If a string was pushed back on the input, pop it;
5922 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5923 * from a string so we can't refill the buffer, return EOF.
5924 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5925 * 4) Process input up to the next newline, deleting nul characters.
5935 while (parsefile->strpush) {
5936 #ifdef CONFIG_ASH_ALIAS
5937 if (parsenleft == -1 && parsefile->strpush->ap &&
5938 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5943 if (--parsenleft >= 0)
5944 return (*parsenextc++);
5946 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5951 if (parselleft <= 0) {
5952 if ((parselleft = preadfd()) <= 0) {
5953 parselleft = parsenleft = EOF_NLEFT;
5960 /* delete nul characters */
5961 for (more = 1; more;) {
5969 parsenleft = q - parsenextc;
5970 more = 0; /* Stop processing here */
5976 if (--parselleft <= 0 && more) {
5977 parsenleft = q - parsenextc - 1;
5988 out2str(parsenextc);
5993 return *parsenextc++;
5998 * Push a string back onto the input at this current parsefile level.
5999 * We handle aliases this way.
6002 pushstring(char *s, int len, void *ap)
6007 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6008 if (parsefile->strpush) {
6009 sp = xmalloc(sizeof (struct strpush));
6010 sp->prev = parsefile->strpush;
6011 parsefile->strpush = sp;
6013 sp = parsefile->strpush = &(parsefile->basestrpush);
6014 sp->prevstring = parsenextc;
6015 sp->prevnleft = parsenleft;
6016 #ifdef CONFIG_ASH_ALIAS
6017 sp->ap = (struct alias *)ap;
6019 ((struct alias *)ap)->flag |= ALIASINUSE;
6030 * Like setinputfile, but takes input from a string.
6034 setinputstring(char *string)
6038 parsenextc = string;
6039 parsenleft = strlen(string);
6040 parsefile->buf = NULL;
6048 * To handle the "." command, a stack of input files is used. Pushfile
6049 * adds a new entry to the stack and popfile restores the previous level.
6055 struct parsefile *pf;
6057 parsefile->nleft = parsenleft;
6058 parsefile->lleft = parselleft;
6059 parsefile->nextc = parsenextc;
6060 parsefile->linno = plinno;
6061 pf = (struct parsefile *)xmalloc(sizeof (struct parsefile));
6062 pf->prev = parsefile;
6065 pf->basestrpush.prev = NULL;
6069 #ifdef CONFIG_ASH_JOB_CONTROL
6070 static void restartjob (struct job *);
6072 static void freejob (struct job *);
6073 static struct job *getjob (const char *);
6074 static int dowait (int, struct job *);
6075 static void waitonint(int);
6079 * We keep track of whether or not fd0 has been redirected. This is for
6080 * background commands, where we want to redirect fd0 to /dev/null only
6081 * if it hasn't already been redirected.
6083 static int fd0_redirected = 0;
6085 /* Return true if fd 0 has already been redirected at least once. */
6087 fd0_redirected_p (void)
6089 return fd0_redirected != 0;
6092 static void dupredirect (const union node *, int, int fd1dup);
6094 #ifdef CONFIG_ASH_JOB_CONTROL
6096 * Turn job control on and off.
6098 * Note: This code assumes that the third arg to ioctl is a character
6099 * pointer, which is true on Berkeley systems but not System V. Since
6100 * System V doesn't have job control yet, this isn't a problem now.
6105 static void setjobctl(int enable)
6107 #ifdef OLD_TTY_DRIVER
6111 if (enable == jobctl || rootshell == 0)
6114 do { /* while we are in the background */
6115 #ifdef OLD_TTY_DRIVER
6116 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6118 initialpgrp = tcgetpgrp(2);
6119 if (initialpgrp < 0) {
6121 out2str("sh: can't access tty; job control turned off\n");
6125 if (initialpgrp == -1)
6126 initialpgrp = getpgrp();
6127 else if (initialpgrp != getpgrp()) {
6128 killpg(initialpgrp, SIGTTIN);
6132 #ifdef OLD_TTY_DRIVER
6133 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6134 out2str("sh: need new tty driver to run job control; job control turned off\n");
6142 setpgid(0, rootpid);
6143 #ifdef OLD_TTY_DRIVER
6144 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6146 tcsetpgrp(2, rootpid);
6148 } else { /* turning job control off */
6149 setpgid(0, initialpgrp);
6150 #ifdef OLD_TTY_DRIVER
6151 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6153 tcsetpgrp(2, initialpgrp);
6164 #ifdef CONFIG_ASH_JOB_CONTROL
6166 killcmd(int argc, char **argv)
6177 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6178 "kill -l [exitstatus]"
6182 if (*argv[1] == '-') {
6183 signo = decode_signal(argv[1] + 1, 1);
6187 while ((c = nextopt("ls:")) != '\0')
6193 signo = decode_signal(optionarg, 1);
6196 "invalid signal number or name: %s",
6204 "nextopt returned character code 0%o", c);
6211 if (!list && signo < 0)
6214 if ((signo < 0 || !*argptr) ^ list) {
6223 for (i = 1; i < NSIG; i++) {
6224 name = u_signal_names(0, &i, 1);
6230 name = u_signal_names(*argptr, &signo, -1);
6234 error("invalid signal number or exit status: %s",
6240 if (**argptr == '%') {
6241 jp = getjob(*argptr);
6242 if (jp->jobctl == 0)
6243 error("job %s not created under job control",
6245 pid = -jp->ps[0].pid;
6247 pid = atoi(*argptr);
6248 if (kill(pid, signo) != 0)
6249 error("%s: %m", *argptr);
6250 } while (*++argptr);
6256 fgcmd(int argc, char **argv)
6262 jp = getjob(argv[1]);
6263 if (jp->jobctl == 0)
6264 error("job not created under job control");
6265 pgrp = jp->ps[0].pid;
6266 #ifdef OLD_TTY_DRIVER
6267 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6272 status = waitforjob(jp);
6278 bgcmd(int argc, char **argv)
6283 jp = getjob(*++argv);
6284 if (jp->jobctl == 0)
6285 error("job not created under job control");
6287 } while (--argc > 1);
6293 restartjob(struct job *jp)
6295 struct procstat *ps;
6298 if (jp->state == JOBDONE)
6301 killpg(jp->ps[0].pid, SIGCONT);
6302 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6303 if (WIFSTOPPED(ps->status)) {
6312 static void showjobs(int change);
6316 jobscmd(int argc, char **argv)
6324 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6325 * statuses have changed since the last call to showjobs.
6327 * If the shell is interrupted in the process of creating a job, the
6328 * result may be a job structure containing zero processes. Such structures
6329 * will be freed here.
6333 showjobs(int change)
6339 struct procstat *ps;
6343 TRACE(("showjobs(%d) called\n", change));
6344 while (dowait(0, (struct job *)NULL) > 0);
6345 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6348 if (jp->nprocs == 0) {
6352 if (change && ! jp->changed)
6354 procno = jp->nprocs;
6355 for (ps = jp->ps ; ; ps++) { /* for each process */
6357 snprintf(s, 64, "[%d] %ld ", jobno,
6360 snprintf(s, 64, " %ld ",
6365 if (ps->status == -1) {
6366 /* don't print anything */
6367 } else if (WIFEXITED(ps->status)) {
6368 snprintf(s, 64, "Exit %d",
6369 WEXITSTATUS(ps->status));
6371 #ifdef CONFIG_ASH_JOB_CONTROL
6372 if (WIFSTOPPED(ps->status))
6373 i = WSTOPSIG(ps->status);
6374 else /* WIFSIGNALED(ps->status) */
6376 i = WTERMSIG(ps->status);
6377 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6378 strcpy(s, sys_siglist[i & 0x7F]);
6380 snprintf(s, 64, "Signal %d", i & 0x7F);
6381 if (WCOREDUMP(ps->status))
6382 strcat(s, " (core dumped)");
6387 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6394 if (jp->state == JOBDONE) {
6402 * Mark a job structure as unused.
6406 freejob(struct job *jp)
6408 const struct procstat *ps;
6412 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6413 if (ps->cmd != nullstr)
6416 if (jp->ps != &jp->ps0)
6419 #ifdef CONFIG_ASH_JOB_CONTROL
6420 if (curjob == jp - jobtab + 1)
6429 waitcmd(int argc, char **argv)
6437 job = getjob(*++argv);
6441 for (;;) { /* loop until process terminated or stopped */
6444 status = job->ps[job->nprocs - 1].status;
6450 if (WIFEXITED(status))
6451 retval = WEXITSTATUS(status);
6452 #ifdef CONFIG_ASH_JOB_CONTROL
6453 else if (WIFSTOPPED(status))
6454 retval = WSTOPSIG(status) + 128;
6457 /* XXX: limits number of signals */
6458 retval = WTERMSIG(status) + 128;
6463 for (jp = jobtab ; ; jp++) {
6464 if (jp >= jobtab + njobs) { /* no running procs */
6467 if (jp->used && jp->state == 0)
6471 if (dowait(2, 0) < 0 && errno == EINTR) {
6480 * Convert a job name to a job structure.
6484 getjob(const char *name)
6492 #ifdef CONFIG_ASH_JOB_CONTROL
6494 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6495 error("No current job");
6496 return &jobtab[jobno - 1];
6498 error("No current job");
6500 } else if (name[0] == '%') {
6501 if (is_digit(name[1])) {
6502 jobno = number(name + 1);
6503 if (jobno > 0 && jobno <= njobs
6504 && jobtab[jobno - 1].used != 0)
6505 return &jobtab[jobno - 1];
6506 #ifdef CONFIG_ASH_JOB_CONTROL
6507 } else if (name[1] == '%' && name[2] == '\0') {
6511 struct job *found = NULL;
6512 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6513 if (jp->used && jp->nprocs > 0
6514 && prefix(name + 1, jp->ps[0].cmd)) {
6516 error("%s: ambiguous", name);
6523 } else if (is_number(name, &pid)) {
6524 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6525 if (jp->used && jp->nprocs > 0
6526 && jp->ps[jp->nprocs - 1].pid == pid)
6530 error("No such job: %s", name);
6537 * Return a new job structure,
6541 makejob(const union node *node, int nprocs)
6546 for (i = njobs, jp = jobtab ; ; jp++) {
6550 jobtab = xmalloc(4 * sizeof jobtab[0]);
6552 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6553 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6554 /* Relocate `ps' pointers */
6555 for (i = 0; i < njobs; i++)
6556 if (jp[i].ps == &jobtab[i].ps0)
6557 jp[i].ps = &jp[i].ps0;
6561 jp = jobtab + njobs;
6562 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6574 #ifdef CONFIG_ASH_JOB_CONTROL
6575 jp->jobctl = jobctl;
6578 jp->ps = xmalloc(nprocs * sizeof (struct procstat));
6583 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6590 * Fork of a subshell. If we are doing job control, give the subshell its
6591 * own process group. Jp is a job structure that the job is to be added to.
6592 * N is the command that will be evaluated by the child. Both jp and n may
6593 * be NULL. The mode parameter can be one of the following:
6594 * FORK_FG - Fork off a foreground process.
6595 * FORK_BG - Fork off a background process.
6596 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6597 * process group even if job control is on.
6599 * When job control is turned off, background processes have their standard
6600 * input redirected to /dev/null (except for the second and later processes
6607 forkshell(struct job *jp, const union node *n, int mode)
6610 #ifdef CONFIG_ASH_JOB_CONTROL
6613 const char *devnull = _PATH_DEVNULL;
6614 const char *nullerr = "Can't open %s";
6616 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6619 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6625 TRACE(("Fork failed, errno=%d\n", errno));
6627 error("Cannot fork");
6634 TRACE(("Child shell %d\n", getpid()));
6635 wasroot = rootshell;
6640 #ifdef CONFIG_ASH_JOB_CONTROL
6641 jobctl = 0; /* do job control only in root shell */
6642 if (wasroot && mode != FORK_NOJOB && mflag) {
6643 if (jp == NULL || jp->nprocs == 0)
6646 pgrp = jp->ps[0].pid;
6648 if (mode == FORK_FG) {
6649 /*** this causes superfluous TIOCSPGRPS ***/
6650 #ifdef OLD_TTY_DRIVER
6651 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6652 error("TIOCSPGRP failed, errno=%d", errno);
6654 if (tcsetpgrp(2, pgrp) < 0)
6655 error("tcsetpgrp failed, errno=%d", errno);
6660 } else if (mode == FORK_BG) {
6662 if (mode == FORK_BG) {
6666 if ((jp == NULL || jp->nprocs == 0) &&
6667 ! fd0_redirected_p ()) {
6669 if (open(devnull, O_RDONLY) != 0)
6670 error(nullerr, devnull);
6673 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6676 if (wasroot && iflag) {
6683 #ifdef CONFIG_ASH_JOB_CONTROL
6684 if (rootshell && mode != FORK_NOJOB && mflag) {
6685 if (jp == NULL || jp->nprocs == 0)
6688 pgrp = jp->ps[0].pid;
6692 if (mode == FORK_BG)
6693 backgndpid = pid; /* set $! */
6695 struct procstat *ps = &jp->ps[jp->nprocs++];
6699 if (iflag && rootshell && n)
6700 ps->cmd = commandtext(n);
6703 TRACE(("In parent shell: child = %d\n", pid));
6710 * Wait for job to finish.
6712 * Under job control we have the problem that while a child process is
6713 * running interrupts generated by the user are sent to the child but not
6714 * to the shell. This means that an infinite loop started by an inter-
6715 * active user may be hard to kill. With job control turned off, an
6716 * interactive user may place an interactive program inside a loop. If
6717 * the interactive program catches interrupts, the user doesn't want
6718 * these interrupts to also abort the loop. The approach we take here
6719 * is to have the shell ignore interrupt signals while waiting for a
6720 * forground process to terminate, and then send itself an interrupt
6721 * signal if the child process was terminated by an interrupt signal.
6722 * Unfortunately, some programs want to do a bit of cleanup and then
6723 * exit on interrupt; unless these processes terminate themselves by
6724 * sending a signal to themselves (instead of calling exit) they will
6725 * confuse this approach.
6729 waitforjob(struct job *jp)
6731 #ifdef CONFIG_ASH_JOB_CONTROL
6732 int mypgrp = getpgrp();
6736 struct sigaction act, oact;
6740 #ifdef CONFIG_ASH_JOB_CONTROL
6745 sigaction(SIGINT, 0, &act);
6746 act.sa_handler = waitonint;
6747 sigaction(SIGINT, &act, &oact);
6749 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6750 while (jp->state == 0) {
6753 #ifdef CONFIG_ASH_JOB_CONTROL
6758 sigaction(SIGINT, &oact, 0);
6759 if (intreceived) kill(getpid(), SIGINT);
6761 #ifdef CONFIG_ASH_JOB_CONTROL
6763 #ifdef OLD_TTY_DRIVER
6764 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6765 error("TIOCSPGRP failed, errno=%d\n", errno);
6767 if (tcsetpgrp(2, mypgrp) < 0)
6768 error("tcsetpgrp failed, errno=%d\n", errno);
6771 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED)
6772 curjob = jp - jobtab + 1;
6774 status = jp->ps[jp->nprocs - 1].status;
6775 /* convert to 8 bits */
6776 if (WIFEXITED(status))
6777 st = WEXITSTATUS(status);
6778 #ifdef CONFIG_ASH_JOB_CONTROL
6779 else if (WIFSTOPPED(status))
6780 st = WSTOPSIG(status) + 128;
6783 st = WTERMSIG(status) + 128;
6784 #ifdef CONFIG_ASH_JOB_CONTROL
6787 * This is truly gross.
6788 * If we're doing job control, then we did a TIOCSPGRP which
6789 * caused us (the shell) to no longer be in the controlling
6790 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6791 * intuit from the subprocess exit status whether a SIGINT
6792 * occured, and if so interrupt ourselves. Yuck. - mycroft
6794 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6797 if (jp->state == JOBDONE)
6808 * Wait for a process to terminate.
6812 * Do a wait system call. If job control is compiled in, we accept
6813 * stopped processes. If block is zero, we return a value of zero
6814 * rather than blocking.
6816 * System V doesn't have a non-blocking wait system call. It does
6817 * have a SIGCLD signal that is sent to a process when one of it's
6818 * children dies. The obvious way to use SIGCLD would be to install
6819 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6820 * was received, and have waitproc bump another counter when it got
6821 * the status of a process. Waitproc would then know that a wait
6822 * system call would not block if the two counters were different.
6823 * This approach doesn't work because if a process has children that
6824 * have not been waited for, System V will send it a SIGCLD when it
6825 * installs a signal handler for SIGCLD. What this means is that when
6826 * a child exits, the shell will be sent SIGCLD signals continuously
6827 * until is runs out of stack space, unless it does a wait call before
6828 * restoring the signal handler. The code below takes advantage of
6829 * this (mis)feature by installing a signal handler for SIGCLD and
6830 * then checking to see whether it was called. If there are any
6831 * children to be waited for, it will be.
6836 waitproc(int block, int *status)
6841 #ifdef CONFIG_ASH_JOB_CONTROL
6847 return wait3(status, flags, (struct rusage *)NULL);
6851 dowait(int block, struct job *job)
6855 struct procstat *sp;
6857 struct job *thisjob;
6863 TRACE(("dowait(%d) called\n", block));
6865 pid = waitproc(block, &status);
6866 TRACE(("wait returns %d, status=%d\n", pid, status));
6867 } while (!(block & 2) && pid == -1 && errno == EINTR);
6872 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
6876 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
6879 if (sp->pid == pid) {
6880 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
6881 sp->status = status;
6884 if (sp->status == -1)
6886 else if (WIFSTOPPED(sp->status))
6889 if (stopped) { /* stopped or done */
6890 int state = done? JOBDONE : CONFIG_ASH_JOB_CONTROLTOPPED;
6891 if (jp->state != state) {
6892 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
6894 #ifdef CONFIG_ASH_JOB_CONTROL
6895 if (done && curjob == jp - jobtab + 1)
6896 curjob = 0; /* no current job */
6903 if (! rootshell || ! iflag || (job && thisjob == job)) {
6904 core = WCOREDUMP(status);
6905 #ifdef CONFIG_ASH_JOB_CONTROL
6906 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
6909 if (WIFEXITED(status)) sig = 0;
6910 else sig = WTERMSIG(status);
6912 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6914 out2fmt("%d: ", pid);
6915 #ifdef CONFIG_ASH_JOB_CONTROL
6916 if (sig == SIGTSTP && rootshell && iflag)
6918 (long)(job - jobtab + 1));
6920 if (sig < NSIG && sys_siglist[sig])
6921 out2str(sys_siglist[sig]);
6923 out2fmt("Signal %d", sig);
6925 out2str(" - core dumped");
6928 TRACE(("Not printing status: status=%d, sig=%d\n",
6932 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
6934 thisjob->changed = 1;
6943 * return 1 if there are stopped jobs, otherwise 0
6953 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6956 if (jp->state == CONFIG_ASH_JOB_CONTROLTOPPED) {
6957 out2str("You have stopped jobs.\n");
6967 * Return a string identifying a command (to be printed by the
6971 static char *cmdnextc;
6972 static int cmdnleft;
6973 #define MAXCMDTEXT 200
6976 cmdputs(const char *s)
6987 while ((c = *p++) != '\0') {
6990 else if (c == CTLVAR) {
6995 } else if (c == '=' && subtype != 0) {
6996 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
6998 } else if (c == CTLENDVAR) {
7000 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7001 cmdnleft++; /* ignore it */
7004 if (--cmdnleft <= 0) {
7014 #define CMDTXT_TABLE
7017 * To collect a lot of redundant code in cmdtxt() case statements, we
7018 * implement a mini language here. Each type of node struct has an
7019 * associated instruction sequence that operates on its members via
7020 * their offsets. The instruction are pack in unsigned chars with
7021 * format IIDDDDDE where the bits are
7022 * I : part of the instruction opcode, which are
7023 * 00 : member is a pointer to another node -- process it recursively
7024 * 40 : member is a pointer to a char string -- output it
7025 * 80 : output the string whose index is stored in the data field
7026 * CC : flag signaling that this case needs external processing
7027 * D : data - either the (shifted) index of a fixed string to output or
7028 * the actual offset of the member to operate on in the struct
7029 * (since we assume bit 0 is set, the offset is not shifted)
7030 * E : flag signaling end of instruction sequence
7032 * WARNING: In order to handle larger offsets for 64bit archs, this code
7033 * assumes that no offset can be an odd number and stores the
7034 * end-of-instructions flag in bit 0.
7037 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7038 #define CMDTXT_CHARPTR 0x40
7039 #define CMDTXT_STRING 0x80
7040 #define CMDTXT_SPECIAL 0xC0
7041 #define CMDTXT_OFFSETMASK 0x3E
7043 static const char * const cmdtxt_strings[] = {
7044 /* 0 1 2 3 4 5 6 7 */
7045 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7046 /* 8 9 10 11 12 13 */
7047 "while ", "; do ", "; done", "until ", "for ", " in ...",
7049 "case ", "???", "() ...", "<<..."
7052 static const char * const redir_strings[] = {
7053 ">", "<", "<>", ">>", ">|", ">&", "<&"
7056 static const unsigned char cmdtxt_ops[] = {
7057 #define CMDTXT_NSEMI 0
7058 offsetof(union node, nbinary.ch1),
7060 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7061 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7062 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7063 #define CMDTXT_NCASE (CMDTXT_NCMD)
7064 #define CMDTXT_NTO (CMDTXT_NCMD)
7065 #define CMDTXT_NFROM (CMDTXT_NCMD)
7066 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7067 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7068 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7069 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7070 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7072 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7073 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7074 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7075 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7076 (1*2)|CMDTXT_STRING,
7077 offsetof(union node, nredir.n),
7078 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7079 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7080 offsetof(union node, nbinary.ch1),
7081 (3*2)|CMDTXT_STRING,
7082 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7083 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7084 offsetof(union node, nbinary.ch1),
7085 (4*2)|CMDTXT_STRING,
7086 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7087 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7088 (5*2)|CMDTXT_STRING,
7089 offsetof(union node, nif.test),
7090 (6*2)|CMDTXT_STRING,
7091 offsetof(union node, nif.ifpart),
7092 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7093 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7094 (8*2)|CMDTXT_STRING,
7095 offsetof(union node, nbinary.ch1),
7096 (9*2)|CMDTXT_STRING,
7097 offsetof(union node, nbinary.ch2),
7098 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7099 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7100 (11*2)|CMDTXT_STRING,
7101 offsetof(union node, nbinary.ch1),
7102 (9*2)|CMDTXT_STRING,
7103 offsetof(union node, nbinary.ch2),
7104 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7105 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7106 (12*2)|CMDTXT_STRING,
7107 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7108 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7109 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7110 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7111 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7112 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7113 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7114 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7115 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7116 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7117 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7118 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7119 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7122 #if CMDTXT_NXHERE != 36
7123 #error CMDTXT_NXHERE
7126 static const unsigned char cmdtxt_ops_index[26] = {
7156 cmdtxt(const union node *n)
7163 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7164 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7166 if (*p & CMDTXT_STRING) { /* output fixed string */
7167 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7169 const char *pf = ((const char *) n)
7170 + ((int)(*p & CMDTXT_OFFSETMASK));
7171 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7172 cmdputs(*((const char **) pf));
7173 } else { /* output field */
7174 cmdtxt(*((const union node **) pf));
7177 } while (!(*p++ & CMDTXT_NOMORE));
7178 } else if (n->type == NCMD) {
7180 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7185 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7189 } else if (n->type == NPIPE) {
7190 struct nodelist *lp;
7191 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7196 } else if (n->type == NCASE) {
7197 cmdputs(cmdtxt_strings[14]);
7198 cmdputs(n->ncase.expr->narg.text);
7199 cmdputs(cmdtxt_strings[13]);
7201 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7202 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7207 assert((n->type >= NTO) && (n->type <= NFROMFD));
7210 p = redir_strings[n->type - NTO];
7211 if (n->nfile.fd != ('>' == *p)) {
7212 s[0] = n->nfile.fd + '0';
7217 if (n->type >= NTOFD) {
7218 s[0] = n->ndup.dupfd + '0';
7222 cmdtxt(n->nfile.fname);
7226 #else /* CMDTXT_TABLE */
7228 cmdtxt(const union node *n)
7231 struct nodelist *lp;
7240 cmdtxt(n->nbinary.ch1);
7242 cmdtxt(n->nbinary.ch2);
7245 cmdtxt(n->nbinary.ch1);
7247 cmdtxt(n->nbinary.ch2);
7250 cmdtxt(n->nbinary.ch1);
7252 cmdtxt(n->nbinary.ch2);
7255 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7263 cmdtxt(n->nredir.n);
7268 cmdtxt(n->nredir.n);
7272 cmdtxt(n->nif.test);
7274 cmdtxt(n->nif.ifpart);
7283 cmdtxt(n->nbinary.ch1);
7285 cmdtxt(n->nbinary.ch2);
7290 cmdputs(n->nfor.var);
7295 cmdputs(n->ncase.expr->narg.text);
7299 cmdputs(n->narg.text);
7303 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7308 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7314 cmdputs(n->narg.text);
7317 p = ">"; i = 1; goto redir;
7319 p = ">>"; i = 1; goto redir;
7321 p = ">&"; i = 1; goto redir;
7323 p = ">|"; i = 1; goto redir;
7325 p = "<"; i = 0; goto redir;
7327 p = "<&"; i = 0; goto redir;
7329 p = "<>"; i = 0; goto redir;
7331 if (n->nfile.fd != i) {
7332 s[0] = n->nfile.fd + '0';
7337 if (n->type == NTOFD || n->type == NFROMFD) {
7338 s[0] = n->ndup.dupfd + '0';
7342 cmdtxt(n->nfile.fname);
7354 #endif /* CMDTXT_TABLE */
7357 commandtext(const union node *n)
7361 cmdnextc = name = xmalloc(MAXCMDTEXT);
7362 cmdnleft = MAXCMDTEXT - 4;
7369 static void waitonint(int sig) {
7374 #ifdef CONFIG_ASH_MAIL
7377 * Routines to check for mail.
7381 #define MAXMBOXES 10
7384 static int nmboxes; /* number of mailboxes */
7385 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7390 * Print appropriate message(s) if mail has arrived. If the argument is
7391 * nozero, then the value of MAIL has changed, so we just update the
7402 struct stackmark smark;
7409 setstackmark(&smark);
7410 mpath = mpathset()? mpathval() : mailval();
7411 for (i = 0 ; i < nmboxes ; i++) {
7412 p = padvance(&mpath, nullstr);
7417 for (q = p ; *q ; q++);
7422 q[-1] = '\0'; /* delete trailing '/' */
7423 if (stat(p, &statb) < 0)
7425 if (statb.st_size > mailtime[i] && ! silent) {
7427 pathopt? pathopt : "you have mail");
7429 mailtime[i] = statb.st_size;
7432 popstackmark(&smark);
7435 #endif /* CONFIG_ASH_MAIL */
7440 static short profile_buf[16384];
7444 static int isloginsh = 0;
7446 static void read_profile (const char *);
7447 static void cmdloop (int);
7448 static void options (int);
7449 static void setoption (int, int);
7450 static void procargs (int, char **);
7454 * Main routine. We initialize things, parse the arguments, execute
7455 * profiles if we're a login shell, and then call cmdloop to execute
7456 * commands. The setjmp call sets up the location to jump to when an
7457 * exception occurs. When an exception occurs the variable "state"
7458 * is used to figure out how far we had gotten.
7462 ash_main(int argc, char **argv)
7464 struct jmploc jmploc;
7465 struct stackmark smark;
7469 BLTINCMD = find_builtin("builtin");
7470 EXECCMD = find_builtin("exec");
7471 EVALCMD = find_builtin("eval");
7473 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7479 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7481 #if defined(linux) || defined(__GNU__)
7482 signal(SIGCHLD, SIG_DFL);
7485 if (setjmp(jmploc.loc)) {
7488 * When a shell procedure is executed, we raise the
7489 * exception EXSHELLPROC to clean up before executing
7490 * the shell procedure.
7492 if (exception == EXSHELLPROC) {
7498 if (exception == EXEXEC) {
7499 exitstatus = exerrno;
7500 } else if (exception == EXERROR) {
7503 if (state == 0 || iflag == 0 || ! rootshell)
7504 exitshell(exitstatus);
7507 if (exception == EXINT) {
7510 popstackmark(&smark);
7511 FORCEINTON; /* enable interrupts */
7514 else if (state == 2)
7516 else if (state == 3)
7524 trputs("Shell args: "); trargs(argv);
7529 setstackmark(&smark);
7530 procargs(argc, argv);
7531 if (argv[0] && argv[0][0] == '-')
7535 read_profile("/etc/profile");
7538 read_profile(".profile");
7543 if (getuid() == geteuid() && getgid() == getegid()) {
7545 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7547 read_profile(shinit);
7554 if (sflag == 0 || minusc) {
7555 static const char sigs[] = {
7556 SIGINT, SIGQUIT, SIGHUP,
7562 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7565 for (i = 0; i < SIGSSIZE; i++)
7570 evalstring(minusc, 0);
7572 if (sflag || minusc == NULL) {
7573 state4: /* XXX ??? - why isn't this before the "if" statement */
7579 exitshell(exitstatus);
7585 * Read and execute commands. "Top" is nonzero for the top level command
7586 * loop; it turns on prompting if the shell is interactive.
7593 struct stackmark smark;
7597 TRACE(("cmdloop(%d) called\n", top));
7598 setstackmark(&smark);
7606 #ifdef CONFIG_ASH_MAIL
7611 n = parsecmd(inter);
7612 /* showtree(n); DEBUG */
7614 if (!top || numeof >= 50)
7616 if (!stoppedjobs()) {
7619 out2str("\nUse \"exit\" to leave shell.\n");
7622 } else if (n != NULL && nflag == 0) {
7623 job_warning = (job_warning == 2) ? 1 : 0;
7627 popstackmark(&smark);
7628 setstackmark(&smark);
7629 if (evalskip == SKIPFILE) {
7634 popstackmark(&smark);
7640 * Read /etc/profile or .profile. Return on error.
7644 read_profile(const char *name)
7651 if ((fd = open(name, O_RDONLY)) >= 0)
7656 /* -q turns off -x and -v just when executing init files */
7657 /* Note: Might do a little redundant work, but reduces code size. */
7672 * Read a file containing shell functions.
7676 readcmdfile(const char *name)
7681 if ((fd = open(name, O_RDONLY)) >= 0)
7684 error("Can't open %s", name);
7693 * Take commands from a file. To be compatable we should do a path
7694 * search for the file, which is necessary to find sub-commands.
7697 static inline char *
7698 find_dot_file(char *mybasename)
7701 const char *path = pathval();
7704 /* don't try this for absolute or relative paths */
7705 if (strchr(mybasename, '/'))
7708 while ((fullname = padvance(&path, mybasename)) != NULL) {
7709 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7711 * Don't bother freeing here, since it will
7712 * be freed by the caller.
7716 stunalloc(fullname);
7719 /* not found in the PATH */
7720 error("%s: not found", mybasename);
7725 dotcmd(int argc, char **argv)
7728 volatile struct shparam saveparam;
7731 for (sp = cmdenviron; sp ; sp = sp->next)
7732 setvareq(xstrdup(sp->text), VSTRFIXED|VTEXTFIXED);
7734 if (argc >= 2) { /* That's what SVR2 does */
7736 struct stackmark smark;
7738 setstackmark(&smark);
7739 fullname = find_dot_file(argv[1]);
7742 saveparam = shellparam;
7743 shellparam.malloc = 0;
7744 shellparam.nparam = argc - 2;
7745 shellparam.p = argv + 2;
7748 setinputfile(fullname, 1);
7749 commandname = fullname;
7754 freeparam(&shellparam);
7755 shellparam = saveparam;
7758 popstackmark(&smark);
7765 exitcmd(int argc, char **argv)
7770 exitstatus = number(argv[1]);
7772 exitstatus = oexitstatus;
7773 exitshell(exitstatus);
7782 nbytes = ALIGN(nbytes);
7783 if (nbytes > stacknleft) {
7785 struct stack_block *sp;
7788 if (blocksize < MINSIZE)
7789 blocksize = MINSIZE;
7791 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7793 stacknxt = sp->space;
7794 stacknleft = blocksize;
7800 stacknleft -= nbytes;
7806 stunalloc(pointer p)
7809 if (p == NULL) { /*DEBUG */
7810 write(2, "stunalloc\n", 10);
7814 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7817 stacknleft += stacknxt - (char *)p;
7823 setstackmark(struct stackmark *mark)
7825 mark->stackp = stackp;
7826 mark->stacknxt = stacknxt;
7827 mark->stacknleft = stacknleft;
7828 mark->marknext = markp;
7834 popstackmark(struct stackmark *mark)
7836 struct stack_block *sp;
7839 markp = mark->marknext;
7840 while (stackp != mark->stackp) {
7845 stacknxt = mark->stacknxt;
7846 stacknleft = mark->stacknleft;
7852 * When the parser reads in a string, it wants to stick the string on the
7853 * stack and only adjust the stack pointer when it knows how big the
7854 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7855 * of space on top of the stack and stackblocklen returns the length of
7856 * this block. Growstackblock will grow this space by at least one byte,
7857 * possibly moving it (like realloc). Grabstackblock actually allocates the
7858 * part of the block that has been used.
7862 growstackblock(void) {
7864 int newlen = ALIGN(stacknleft * 2 + 100);
7865 char *oldspace = stacknxt;
7866 int oldlen = stacknleft;
7867 struct stack_block *sp;
7868 struct stack_block *oldstackp;
7870 if (stacknxt == stackp->space && stackp != &stackbase) {
7875 sp = xrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
7878 stacknxt = sp->space;
7879 stacknleft = newlen;
7881 /* Stack marks pointing to the start of the old block
7882 * must be relocated to point to the new block
7884 struct stackmark *xmark;
7886 while (xmark != NULL && xmark->stackp == oldstackp) {
7887 xmark->stackp = stackp;
7888 xmark->stacknxt = stacknxt;
7889 xmark->stacknleft = stacknleft;
7890 xmark = xmark->marknext;
7895 p = stalloc(newlen);
7896 memcpy(p, oldspace, oldlen);
7897 stacknxt = p; /* free the space */
7898 stacknleft += newlen; /* we just allocated */
7905 grabstackblock(int len)
7915 * The following routines are somewhat easier to use that the above.
7916 * The user declares a variable of type STACKSTR, which may be declared
7917 * to be a register. The macro STARTSTACKSTR initializes things. Then
7918 * the user uses the macro STPUTC to add characters to the string. In
7919 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7920 * grown as necessary. When the user is done, she can just leave the
7921 * string there and refer to it using stackblock(). Or she can allocate
7922 * the space for it using grabstackstr(). If it is necessary to allow
7923 * someone else to use the stack temporarily and then continue to grow
7924 * the string, the user should use grabstack to allocate the space, and
7925 * then call ungrabstr(p) to return to the previous mode of operation.
7927 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7928 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7929 * is space for at least one character.
7934 growstackstr(void) {
7935 int len = stackblocksize();
7936 if (herefd >= 0 && len >= 1024) {
7937 xwrite(herefd, stackblock(), len);
7938 sstrnleft = len - 1;
7939 return stackblock();
7942 sstrnleft = stackblocksize() - len - 1;
7943 return stackblock() + len;
7948 * Called from CHECKSTRSPACE.
7952 makestrspace(size_t newlen) {
7953 int len = stackblocksize() - sstrnleft;
7956 sstrnleft = stackblocksize() - len;
7957 } while (sstrnleft < newlen);
7958 return stackblock() + len;
7964 ungrabstackstr(char *s, char *p)
7966 stacknleft += stacknxt - s;
7968 sstrnleft = stacknleft - (p - s);
7971 * Miscelaneous builtins.
7977 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
7978 typedef long rlim_t;
7984 * The read builtin. The -e option causes backslashes to escape the
7985 * following character.
7987 * This uses unbuffered input, which may be avoidable in some cases.
7991 readcmd(int argc, char **argv)
8006 while ((i = nextopt("p:r")) != '\0') {
8012 if (prompt && isatty(0)) {
8013 out2str(prompt); /* read without cmdedit */
8016 if (*(ap = argptr) == NULL)
8018 if ((ifs = bltinlookup("IFS")) == NULL)
8025 if (read(0, &c, 1) != 1) {
8037 if (!rflag && c == '\\') {
8043 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8047 if (backslash && c == '\\') {
8048 if (read(0, &c, 1) != 1) {
8053 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8055 setvar(*ap, stackblock(), 0);
8064 /* Remove trailing blanks */
8065 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8067 setvar(*ap, stackblock(), 0);
8068 while (*++ap != NULL)
8069 setvar(*ap, nullstr, 0);
8076 umaskcmd(int argc, char **argv)
8078 static const char permuser[3] = "ugo";
8079 static const char permmode[3] = "rwx";
8080 static const short int permmask[] = {
8081 S_IRUSR, S_IWUSR, S_IXUSR,
8082 S_IRGRP, S_IWGRP, S_IXGRP,
8083 S_IROTH, S_IWOTH, S_IXOTH
8089 int symbolic_mode = 0;
8091 while (nextopt("S") != '\0') {
8100 if ((ap = *argptr) == NULL) {
8101 if (symbolic_mode) {
8104 for (i=0 ; i<3 ; i++) {
8108 for (j=0 ; j<3 ; j++) {
8109 if ((mask & permmask[3*i+j]) == 0) {
8118 printf("%.4o\n", mask);
8121 if (is_digit((unsigned char)*ap)) {
8124 if (*ap >= '8' || *ap < '0')
8125 error("Illegal number: %s", argv[1]);
8126 mask = (mask << 3) + (*ap - '0');
8127 } while (*++ap != '\0');
8130 mask = ~mask & 0777;
8131 if (! parse_mode(ap, &mask)) {
8132 error("Illegal mode: %s", ap);
8134 umask(~mask & 0777);
8143 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8144 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8145 * ash by J.T. Conklin.
8153 short factor; /* multiply by to get rlim_{cur,max} values */
8156 static const struct limits limits[] = {
8158 { "time(seconds)", RLIMIT_CPU, 1 },
8161 { "file(blocks)", RLIMIT_FSIZE, 512 },
8164 { "data(kbytes)", RLIMIT_DATA, 1024 },
8167 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8170 { "coredump(blocks)", RLIMIT_CORE, 512 },
8173 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8175 #ifdef RLIMIT_MEMLOCK
8176 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8179 { "process(processes)", RLIMIT_NPROC, 1 },
8181 #ifdef RLIMIT_NOFILE
8182 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8185 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8188 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8194 ulimitcmd(int argc, char **argv)
8196 static const char unlimited_string[] = "unlimited";
8199 enum { SOFT = 0x1, HARD = 0x2 }
8201 const struct limits *l;
8204 struct rlimit limit;
8208 while ((optc = nextopt("HSa"
8227 #ifdef RLIMIT_MEMLOCK
8233 #ifdef RLIMIT_NOFILE
8245 } else if (optc == 'S') {
8247 } else if (optc == 'a') {
8254 for (l = limits; l->name; l++) {
8255 if(l->name[0] == what)
8257 if(l->name[1]=='w' && what=='w')
8261 set = *argptr ? 1 : 0;
8265 if (all || argptr[1])
8266 error("too many arguments");
8267 if (strcmp(p, unlimited_string) == 0)
8268 val = RLIM_INFINITY;
8272 while ((c = *p++) >= '0' && c <= '9')
8274 val = (val * 10) + (long)(c - '0');
8275 if (val < (rlim_t) 0)
8279 error("bad number");
8285 for (l = limits; l->name; l++) {
8286 printf("%-20s ", l->name);
8287 getrlimit(l->cmd, &limit);
8290 val = limit.rlim_cur;
8291 else if (how & HARD)
8292 val = limit.rlim_max;
8294 if (val == RLIM_INFINITY)
8295 puts(unlimited_string);
8299 printf("%lld\n", (long long) val);
8312 getrlimit(l->cmd, &limit);
8314 limit.rlim_max = val;
8316 limit.rlim_cur = val;
8317 if (setrlimit(l->cmd, &limit) < 0)
8318 error("error setting limit (%m)");
8322 * prefix -- see if pfx is a prefix of string.
8326 prefix(char const *pfx, char const *string)
8329 if (*pfx++ != *string++)
8336 * Return true if s is a string of digits, and save munber in intptr
8341 is_number(const char *p, int *intptr)
8349 ret += digit_val(*p);
8351 } while (*p != '\0');
8358 * Convert a string of digits to an integer, printing an error message on
8363 number(const char *s)
8366 if (! is_number(s, &i))
8367 error("Illegal number: %s", s);
8372 * Produce a possibly single quoted string suitable as input to the shell.
8373 * The return string is allocated on the stack.
8377 single_quote(const char *s)
8385 size_t len1, len1p, len2, len2p;
8387 len1 = strcspn(s, "'");
8388 len2 = strspn(s + len1, "'");
8390 len1p = len1 ? len1 + 2 : len1;
8391 len2p = len2 + ((len2 < 2) ? len2 : 2);
8393 CHECKSTRSPACE(len1p + len2p + 1, p);
8398 memcpy(p + 1, s, len1);
8406 memcpy(q + 1, s, len2);
8409 } else if (len2 == 1) {
8415 STADJUST(len1p + len2p, p);
8420 return grabstackstr(p);
8424 * Like strdup but works with the ash stack.
8428 sstrdup(const char *p)
8430 size_t len = strlen(p) + 1;
8431 return memcpy(stalloc(len), p, len);
8436 * Routine for dealing with parsed shell commands.
8440 static void sizenodelist (const struct nodelist *);
8441 static struct nodelist *copynodelist (const struct nodelist *);
8442 static char *nodexstrdup (const char *);
8444 #define CALCSIZE_TABLE
8445 #define COPYNODE_TABLE
8446 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8448 * To collect a lot of redundant code in case statements for copynode()
8449 * and calcsize(), we implement a mini language here. Each type of node
8450 * struct has an associated instruction sequence that operates on its
8451 * members via their offsets. The instruction are pack in unsigned chars
8452 * with format IIDDDDDE where the bits are
8453 * I : part of the instruction opcode, which are
8454 * 00 : member is a pointer to another node
8455 * 40 : member is an integer
8456 * 80 : member is a pointer to a nodelist
8457 * CC : member is a pointer to a char string
8458 * D : data - the actual offset of the member to operate on in the struct
8459 * (since we assume bit 0 is set, it is not shifted)
8460 * E : flag signaling end of instruction sequence
8462 * WARNING: In order to handle larger offsets for 64bit archs, this code
8463 * assumes that no offset can be an odd number and stores the
8464 * end-of-instructions flag in bit 0.
8467 #define NODE_INTEGER 0x40
8468 #define NODE_NODELIST 0x80
8469 #define NODE_CHARPTR 0xC0
8470 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8471 #define NODE_MBRMASK 0xC0
8472 #define NODE_OFFSETMASK 0x3E
8474 static const unsigned char copynode_ops[35] = {
8475 #define COPYNODE_OPS0 0
8476 offsetof(union node, nbinary.ch2),
8477 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8478 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8479 offsetof(union node, ncmd.redirect),
8480 offsetof(union node, ncmd.args),
8481 offsetof(union node, ncmd.assign),
8482 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8483 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8484 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8485 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8486 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8487 offsetof(union node, nredir.redirect),
8488 offsetof(union node, nredir.n)|NODE_NOMORE,
8489 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8490 offsetof(union node, nif.elsepart),
8491 offsetof(union node, nif.ifpart),
8492 offsetof(union node, nif.test)|NODE_NOMORE,
8493 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8494 offsetof(union node, nfor.var)|NODE_CHARPTR,
8495 offsetof(union node, nfor.body),
8496 offsetof(union node, nfor.args)|NODE_NOMORE,
8497 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8498 offsetof(union node, ncase.cases),
8499 offsetof(union node, ncase.expr)|NODE_NOMORE,
8500 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8501 offsetof(union node, nclist.body),
8502 offsetof(union node, nclist.pattern),
8503 offsetof(union node, nclist.next)|NODE_NOMORE,
8504 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8505 offsetof(union node, narg.backquote)|NODE_NODELIST,
8506 offsetof(union node, narg.text)|NODE_CHARPTR,
8507 offsetof(union node, narg.next)|NODE_NOMORE,
8508 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8509 offsetof(union node, nfile.fname),
8510 offsetof(union node, nfile.fd)|NODE_INTEGER,
8511 offsetof(union node, nfile.next)|NODE_NOMORE,
8512 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8513 offsetof(union node, ndup.vname),
8514 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8515 offsetof(union node, ndup.fd)|NODE_INTEGER,
8516 offsetof(union node, ndup.next)|NODE_NOMORE,
8517 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8518 offsetof(union node, nhere.doc),
8519 offsetof(union node, nhere.fd)|NODE_INTEGER,
8520 offsetof(union node, nhere.next)|NODE_NOMORE,
8521 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8522 offsetof(union node, nnot.com)|NODE_NOMORE,
8525 #if COPYNODE_OPS12 != 34
8526 #error COPYNODE_OPS12 is incorrect
8529 static const unsigned char copynode_ops_index[26] = {
8530 COPYNODE_OPS0, /* NSEMI */
8531 COPYNODE_OPS1, /* NCMD */
8532 COPYNODE_OPS2, /* NPIPE */
8533 COPYNODE_OPS3, /* NREDIR */
8534 COPYNODE_OPS3, /* NBACKGND */
8535 COPYNODE_OPS3, /* NSUBSHELL */
8536 COPYNODE_OPS0, /* NAND */
8537 COPYNODE_OPS0, /* NOR */
8538 COPYNODE_OPS4, /* NIF */
8539 COPYNODE_OPS0, /* NWHILE */
8540 COPYNODE_OPS0, /* NUNTIL */
8541 COPYNODE_OPS5, /* NFOR */
8542 COPYNODE_OPS6, /* NCASE */
8543 COPYNODE_OPS7, /* NCLIST */
8544 COPYNODE_OPS8, /* NDEFUN */
8545 COPYNODE_OPS8, /* NARG */
8546 COPYNODE_OPS9, /* NTO */
8547 COPYNODE_OPS9, /* NFROM */
8548 COPYNODE_OPS9, /* NFROMTO */
8549 COPYNODE_OPS9, /* NAPPEND */
8550 COPYNODE_OPS9, /* NTOOV */
8551 COPYNODE_OPS10, /* NTOFD */
8552 COPYNODE_OPS10, /* NFROMFD */
8553 COPYNODE_OPS11, /* NHERE */
8554 COPYNODE_OPS11, /* NXHERE */
8555 COPYNODE_OPS12, /* NNOT */
8558 #if NODE_CHARPTR != NODE_MBRMASK
8559 #error NODE_CHARPTR != NODE_MBRMASK!!!
8561 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8563 #ifdef COPYNODE_TABLE
8565 copynode(const union node *n)
8568 const unsigned char *p;
8574 new->type = n->type;
8575 funcblock = (char *) funcblock + (int) nodesize[n->type];
8576 p = copynode_ops + (int) copynode_ops_index[n->type];
8578 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8579 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8581 if (!(*p & NODE_MBRMASK)) { /* standard node */
8582 *((union node **)nn) = copynode(*((const union node **) no));
8583 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8584 *((const char **)nn) = nodexstrdup(*((const char **)no));
8585 } else if (*p & NODE_NODELIST) { /* nodelist */
8586 *((struct nodelist **)nn)
8587 = copynodelist(*((const struct nodelist **) no));
8588 } else { /* integer */
8589 *((int *) nn) = *((int *) no);
8591 } while (!(*p++ & NODE_NOMORE));
8594 #else /* COPYNODE_TABLE */
8596 copynode(const union node *n)
8603 funcblock = (char *) funcblock + nodesize[n->type];
8610 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8611 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8614 new->ncmd.redirect = copynode(n->ncmd.redirect);
8615 new->ncmd.args = copynode(n->ncmd.args);
8616 new->ncmd.assign = copynode(n->ncmd.assign);
8617 new->ncmd.backgnd = n->ncmd.backgnd;
8620 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8621 new->npipe.backgnd = n->npipe.backgnd;
8626 new->nredir.redirect = copynode(n->nredir.redirect);
8627 new->nredir.n = copynode(n->nredir.n);
8630 new->nif.elsepart = copynode(n->nif.elsepart);
8631 new->nif.ifpart = copynode(n->nif.ifpart);
8632 new->nif.test = copynode(n->nif.test);
8635 new->nfor.var = nodexstrdup(n->nfor.var);
8636 new->nfor.body = copynode(n->nfor.body);
8637 new->nfor.args = copynode(n->nfor.args);
8640 new->ncase.cases = copynode(n->ncase.cases);
8641 new->ncase.expr = copynode(n->ncase.expr);
8644 new->nclist.body = copynode(n->nclist.body);
8645 new->nclist.pattern = copynode(n->nclist.pattern);
8646 new->nclist.next = copynode(n->nclist.next);
8650 new->narg.backquote = copynodelist(n->narg.backquote);
8651 new->narg.text = nodexstrdup(n->narg.text);
8652 new->narg.next = copynode(n->narg.next);
8659 new->nfile.fname = copynode(n->nfile.fname);
8660 new->nfile.fd = n->nfile.fd;
8661 new->nfile.next = copynode(n->nfile.next);
8665 new->ndup.vname = copynode(n->ndup.vname);
8666 new->ndup.dupfd = n->ndup.dupfd;
8667 new->ndup.fd = n->ndup.fd;
8668 new->ndup.next = copynode(n->ndup.next);
8672 new->nhere.doc = copynode(n->nhere.doc);
8673 new->nhere.fd = n->nhere.fd;
8674 new->nhere.next = copynode(n->nhere.next);
8677 new->nnot.com = copynode(n->nnot.com);
8680 new->type = n->type;
8683 #endif /* COPYNODE_TABLE */
8685 #ifdef CALCSIZE_TABLE
8687 calcsize(const union node *n)
8689 const unsigned char *p;
8693 funcblocksize += (int) nodesize[n->type];
8695 p = copynode_ops + (int) copynode_ops_index[n->type];
8697 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8699 if (!(*p & NODE_MBRMASK)) { /* standard node */
8700 calcsize(*((const union node **) no));
8701 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8702 funcstringsize += strlen(*((const char **)no)) + 1;
8703 } else if (*p & NODE_NODELIST) { /* nodelist */
8704 sizenodelist(*((const struct nodelist **) no));
8705 } /* else integer -- ignore */
8706 } while (!(*p++ & NODE_NOMORE));
8708 #else /* CALCSIZE_TABLE */
8710 calcsize(const union node *n)
8714 funcblocksize += nodesize[n->type];
8721 calcsize(n->nbinary.ch2);
8722 calcsize(n->nbinary.ch1);
8725 calcsize(n->ncmd.redirect);
8726 calcsize(n->ncmd.args);
8727 calcsize(n->ncmd.assign);
8730 sizenodelist(n->npipe.cmdlist);
8735 calcsize(n->nredir.redirect);
8736 calcsize(n->nredir.n);
8739 calcsize(n->nif.elsepart);
8740 calcsize(n->nif.ifpart);
8741 calcsize(n->nif.test);
8744 funcstringsize += strlen(n->nfor.var) + 1;
8745 calcsize(n->nfor.body);
8746 calcsize(n->nfor.args);
8749 calcsize(n->ncase.cases);
8750 calcsize(n->ncase.expr);
8753 calcsize(n->nclist.body);
8754 calcsize(n->nclist.pattern);
8755 calcsize(n->nclist.next);
8759 sizenodelist(n->narg.backquote);
8760 funcstringsize += strlen(n->narg.text) + 1;
8761 calcsize(n->narg.next);
8768 calcsize(n->nfile.fname);
8769 calcsize(n->nfile.next);
8773 calcsize(n->ndup.vname);
8774 calcsize(n->ndup.next);
8778 calcsize(n->nhere.doc);
8779 calcsize(n->nhere.next);
8782 calcsize(n->nnot.com);
8786 #endif /* CALCSIZE_TABLE */
8789 sizenodelist(const struct nodelist *lp)
8792 funcblocksize += ALIGN(sizeof(struct nodelist));
8799 static struct nodelist *
8800 copynodelist(const struct nodelist *lp)
8802 struct nodelist *start;
8803 struct nodelist **lpp;
8808 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8809 (*lpp)->n = copynode(lp->n);
8811 lpp = &(*lpp)->next;
8819 nodexstrdup(const char *s)
8822 char *q = funcstring;
8823 char *rtn = funcstring;
8825 while ((*q++ = *p++) != '\0')
8831 #ifdef CONFIG_ASH_GETOPTS
8832 static int getopts (char *, char *, char **, int *, int *);
8836 * Process the shell command line arguments.
8840 procargs(int argc, char **argv)
8847 for (i = 0; i < NOPTS; i++)
8850 if (*argptr == NULL && minusc == NULL)
8852 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8856 for (i = 0; i < NOPTS; i++)
8857 if (optent_val(i) == 2)
8860 if (sflag == 0 && minusc == NULL) {
8861 commandname = argv[0];
8863 setinputfile(arg0, 0);
8866 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8867 if (argptr && minusc && *argptr)
8870 shellparam.p = argptr;
8871 shellparam.optind = 1;
8872 shellparam.optoff = -1;
8873 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8875 shellparam.nparam++;
8884 * Process shell options. The global variable argptr contains a pointer
8885 * to the argument list; we advance it past the options.
8889 minus_o(const char *name, int val)
8894 out1str("Current option settings\n");
8895 for (i = 0; i < NOPTS; i++)
8896 printf("%-16s%s\n", optent_name(optlist[i]),
8897 optent_val(i) ? "on" : "off");
8899 for (i = 0; i < NOPTS; i++)
8900 if (equal(name, optent_name(optlist[i]))) {
8901 setoption(optent_letter(optlist[i]), val);
8904 error("Illegal option -o %s", name);
8910 options(int cmdline)
8918 while ((p = *argptr) != NULL) {
8920 if ((c = *p++) == '-') {
8922 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8924 /* "-" means turn off -x and -v */
8927 /* "--" means reset params */
8928 else if (*argptr == NULL)
8931 break; /* "-" or "--" terminates options */
8933 } else if (c == '+') {
8939 while ((c = *p++) != '\0') {
8940 if (c == 'c' && cmdline) {
8942 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8946 if (q == NULL || minusc != NULL)
8947 error("Bad -c option");
8952 } else if (c == 'o') {
8953 minus_o(*argptr, val);
8956 } else if (cmdline && (c == '-')) { // long options
8957 if ( strcmp ( p, "login" ) == 0 )
8969 setoption(int flag, int val)
8973 for (i = 0; i < NOPTS; i++)
8974 if (optent_letter(optlist[i]) == flag) {
8975 optent_val(i) = val;
8977 /* #%$ hack for ksh semantics */
8980 else if (flag == 'E')
8985 error("Illegal option -%c", flag);
8992 * Set the shell parameters.
8996 setparam(char **argv)
9002 for (nparam = 0 ; argv[nparam] ; nparam++);
9003 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
9005 *ap++ = xstrdup(*argv++);
9008 freeparam(&shellparam);
9009 shellparam.malloc = 1;
9010 shellparam.nparam = nparam;
9011 shellparam.p = newparam;
9012 shellparam.optind = 1;
9013 shellparam.optoff = -1;
9018 * Free the list of positional parameters.
9022 freeparam(volatile struct shparam *param)
9026 if (param->malloc) {
9027 for (ap = param->p ; *ap ; ap++)
9036 * The shift builtin command.
9040 shiftcmd(int argc, char **argv)
9047 n = number(argv[1]);
9048 if (n > shellparam.nparam)
9049 error("can't shift that many");
9051 shellparam.nparam -= n;
9052 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9053 if (shellparam.malloc)
9057 while ((*ap2++ = *ap1++) != NULL);
9058 shellparam.optind = 1;
9059 shellparam.optoff = -1;
9067 * The set command builtin.
9071 setcmd(int argc, char **argv)
9074 return showvarscmd(argc, argv);
9078 if (*argptr != NULL) {
9087 getoptsreset(const char *value)
9089 shellparam.optind = number(value);
9090 shellparam.optoff = -1;
9093 #ifdef CONFIG_LOCALE_SUPPORT
9094 static void change_lc_all(const char *value)
9096 if(value != 0 && *value != 0)
9097 setlocale(LC_ALL, value);
9100 static void change_lc_ctype(const char *value)
9102 if(value != 0 && *value != 0)
9103 setlocale(LC_CTYPE, value);
9108 #ifdef CONFIG_ASH_GETOPTS
9110 * The getopts builtin. Shellparam.optnext points to the next argument
9111 * to be processed. Shellparam.optptr points to the next character to
9112 * be processed in the current argument. If shellparam.optnext is NULL,
9113 * then it's the first time getopts has been called.
9117 getoptscmd(int argc, char **argv)
9122 error("Usage: getopts optstring var [arg]");
9123 else if (argc == 3) {
9124 optbase = shellparam.p;
9125 if (shellparam.optind > shellparam.nparam + 1) {
9126 shellparam.optind = 1;
9127 shellparam.optoff = -1;
9132 if (shellparam.optind > argc - 2) {
9133 shellparam.optind = 1;
9134 shellparam.optoff = -1;
9138 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9139 &shellparam.optoff);
9143 * Safe version of setvar, returns 1 on success 0 on failure.
9147 setvarsafe(const char *name, const char *val, int flags)
9149 struct jmploc jmploc;
9150 struct jmploc *volatile savehandler = handler;
9156 if (setjmp(jmploc.loc))
9160 setvar(name, val, flags);
9162 handler = savehandler;
9167 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind, int *optoff)
9174 char **optnext = optfirst + *myoptind - 1;
9176 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9177 strlen(*(optnext - 1)) < *optoff)
9180 p = *(optnext - 1) + *optoff;
9181 if (p == NULL || *p == '\0') {
9182 /* Current word is done, advance */
9183 if (optnext == NULL)
9186 if (p == NULL || *p != '-' || *++p == '\0') {
9188 *myoptind = optnext - optfirst + 1;
9194 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9199 for (q = optstr; *q != c; ) {
9201 if (optstr[0] == ':') {
9204 err |= setvarsafe("OPTARG", s, 0);
9207 out2fmt("Illegal option -%c\n", c);
9208 (void) unsetvar("OPTARG");
9218 if (*p == '\0' && (p = *optnext) == NULL) {
9219 if (optstr[0] == ':') {
9222 err |= setvarsafe("OPTARG", s, 0);
9226 out2fmt("No arg for -%c option\n", c);
9227 (void) unsetvar("OPTARG");
9235 setvarsafe("OPTARG", p, 0);
9239 setvarsafe("OPTARG", "", 0);
9240 *myoptind = optnext - optfirst + 1;
9247 *optoff = p ? p - *(optnext - 1) : -1;
9248 snprintf(s, sizeof(s), "%d", *myoptind);
9249 err |= setvarsafe("OPTIND", s, VNOFUNC);
9252 err |= setvarsafe(optvar, s, 0);
9263 * XXX - should get rid of. have all builtins use getopt(3). the
9264 * library getopt must have the BSD extension static variable "optreset"
9265 * otherwise it can't be used within the shell safely.
9267 * Standard option processing (a la getopt) for builtin routines. The
9268 * only argument that is passed to nextopt is the option string; the
9269 * other arguments are unnecessary. It return the character, or '\0' on
9274 nextopt(const char *optstring)
9280 if ((p = optptr) == NULL || *p == '\0') {
9282 if (p == NULL || *p != '-' || *++p == '\0')
9285 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9289 for (q = optstring ; *q != c ; ) {
9291 error("Illegal option -%c", c);
9296 if (*p == '\0' && (p = *argptr++) == NULL)
9297 error("No arg for -%c option", c);
9314 out2fmt(const char *fmt, ...)
9318 vfprintf(stderr, fmt, ap);
9323 * Version of write which resumes after a signal is caught.
9327 xwrite(int fd, const char *buf, int nbytes)
9336 i = write(fd, buf, n);
9342 } else if (i == 0) {
9345 } else if (errno != EINTR) {
9353 * Shell command parser.
9356 #define EOFMARKLEN 79
9361 struct heredoc *next; /* next here document in list */
9362 union node *here; /* redirection node */
9363 char *eofmark; /* string indicating end of input */
9364 int striptabs; /* if set, strip leading tabs */
9367 static struct heredoc *heredoclist; /* list of here documents to read */
9368 static int parsebackquote; /* nonzero if we are inside backquotes */
9369 static int doprompt; /* if set, prompt the user */
9370 static int needprompt; /* true if interactive and at start of line */
9371 static int lasttoken; /* last token read */
9373 static char *wordtext; /* text of last word returned by readtoken */
9375 static struct nodelist *backquotelist;
9376 static union node *redirnode;
9377 static struct heredoc *heredoc;
9378 static int quoteflag; /* set if (part of) last token was quoted */
9379 static int startlinno; /* line # where last token started */
9382 static union node *list (int);
9383 static union node *andor (void);
9384 static union node *pipeline (void);
9385 static union node *command (void);
9386 static union node *simplecmd(union node **rpp, union node *redir);
9387 static void parsefname (void);
9388 static void parseheredoc (void);
9389 static char peektoken (void);
9390 static int readtoken (void);
9391 static int xxreadtoken (void);
9392 static int readtoken1 (int, int, const char *, int);
9393 static int noexpand (char *);
9394 static void synexpect (int) __attribute__((noreturn));
9395 static void synerror (const char *) __attribute__((noreturn));
9396 static void setprompt (int);
9400 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9401 * valid parse tree indicating a blank line.)
9405 parsecmd(int interact)
9410 doprompt = interact;
9429 union node *n1, *n2, *n3;
9433 if (nlflag == 0 && peektoken())
9439 if (tok == TBACKGND) {
9440 if (n2->type == NCMD || n2->type == NPIPE) {
9441 n2->ncmd.backgnd = 1;
9442 } else if (n2->type == NREDIR) {
9443 n2->type = NBACKGND;
9445 n3 = (union node *)stalloc(sizeof (struct nredir));
9446 n3->type = NBACKGND;
9448 n3->nredir.redirect = NULL;
9456 n3 = (union node *)stalloc(sizeof (struct nbinary));
9458 n3->nbinary.ch1 = n1;
9459 n3->nbinary.ch2 = n2;
9483 pungetc(); /* push back EOF on input */
9498 union node *n1, *n2, *n3;
9504 if ((t = readtoken()) == TAND) {
9506 } else if (t == TOR) {
9514 n3 = (union node *)stalloc(sizeof (struct nbinary));
9516 n3->nbinary.ch1 = n1;
9517 n3->nbinary.ch2 = n2;
9526 union node *n1, *n2, *pipenode;
9527 struct nodelist *lp, *prev;
9531 TRACE(("pipeline: entered\n"));
9532 if (readtoken() == TNOT) {
9538 if (readtoken() == TPIPE) {
9539 pipenode = (union node *)stalloc(sizeof (struct npipe));
9540 pipenode->type = NPIPE;
9541 pipenode->npipe.backgnd = 0;
9542 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9543 pipenode->npipe.cmdlist = lp;
9547 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9551 } while (readtoken() == TPIPE);
9557 n2 = (union node *)stalloc(sizeof (struct nnot));
9569 union node *n1, *n2;
9570 union node *ap, **app;
9571 union node *cp, **cpp;
9572 union node *redir, **rpp;
9579 /* Check for redirection which may precede command */
9580 while (readtoken() == TREDIR) {
9581 *rpp = n2 = redirnode;
9582 rpp = &n2->nfile.next;
9587 switch (readtoken()) {
9589 n1 = (union node *)stalloc(sizeof (struct nif));
9591 n1->nif.test = list(0);
9592 if (readtoken() != TTHEN)
9594 n1->nif.ifpart = list(0);
9596 while (readtoken() == TELIF) {
9597 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9598 n2 = n2->nif.elsepart;
9600 n2->nif.test = list(0);
9601 if (readtoken() != TTHEN)
9603 n2->nif.ifpart = list(0);
9605 if (lasttoken == TELSE)
9606 n2->nif.elsepart = list(0);
9608 n2->nif.elsepart = NULL;
9611 if (readtoken() != TFI)
9618 n1 = (union node *)stalloc(sizeof (struct nbinary));
9619 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9620 n1->nbinary.ch1 = list(0);
9621 if ((got=readtoken()) != TDO) {
9622 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9625 n1->nbinary.ch2 = list(0);
9626 if (readtoken() != TDONE)
9632 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9633 synerror("Bad for loop variable");
9634 n1 = (union node *)stalloc(sizeof (struct nfor));
9636 n1->nfor.var = wordtext;
9638 if (readtoken() == TIN) {
9640 while (readtoken() == TWORD) {
9641 n2 = (union node *)stalloc(sizeof (struct narg));
9643 n2->narg.text = wordtext;
9644 n2->narg.backquote = backquotelist;
9646 app = &n2->narg.next;
9650 if (lasttoken != TNL && lasttoken != TSEMI)
9653 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9655 n2 = (union node *)stalloc(sizeof (struct narg));
9657 n2->narg.text = argvars;
9658 n2->narg.backquote = NULL;
9659 n2->narg.next = NULL;
9662 * Newline or semicolon here is optional (but note
9663 * that the original Bourne shell only allowed NL).
9665 if (lasttoken != TNL && lasttoken != TSEMI)
9669 if (readtoken() != TDO)
9671 n1->nfor.body = list(0);
9672 if (readtoken() != TDONE)
9677 n1 = (union node *)stalloc(sizeof (struct ncase));
9679 if (readtoken() != TWORD)
9681 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9683 n2->narg.text = wordtext;
9684 n2->narg.backquote = backquotelist;
9685 n2->narg.next = NULL;
9688 } while (readtoken() == TNL);
9689 if (lasttoken != TIN)
9690 synerror("expecting \"in\"");
9691 cpp = &n1->ncase.cases;
9692 checkkwd = 2, readtoken();
9694 if (lasttoken == TLP)
9696 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9698 app = &cp->nclist.pattern;
9700 *app = ap = (union node *)stalloc(sizeof (struct narg));
9702 ap->narg.text = wordtext;
9703 ap->narg.backquote = backquotelist;
9704 if (checkkwd = 2, readtoken() != TPIPE)
9706 app = &ap->narg.next;
9709 ap->narg.next = NULL;
9710 if (lasttoken != TRP)
9712 cp->nclist.body = list(0);
9715 if ((t = readtoken()) != TESAC) {
9717 synexpect(TENDCASE);
9719 checkkwd = 2, readtoken();
9721 cpp = &cp->nclist.next;
9722 } while(lasttoken != TESAC);
9727 n1 = (union node *)stalloc(sizeof (struct nredir));
9728 n1->type = NSUBSHELL;
9729 n1->nredir.n = list(0);
9730 n1->nredir.redirect = NULL;
9731 if (readtoken() != TRP)
9737 if (readtoken() != TEND)
9741 /* Handle an empty command like other simple commands. */
9750 * An empty command before a ; doesn't make much sense, and
9751 * should certainly be disallowed in the case of `if ;'.
9757 n1 = simplecmd(rpp, redir);
9764 /* Now check for redirection which may follow command */
9765 while (readtoken() == TREDIR) {
9766 *rpp = n2 = redirnode;
9767 rpp = &n2->nfile.next;
9773 if (n1->type != NSUBSHELL) {
9774 n2 = (union node *)stalloc(sizeof (struct nredir));
9779 n1->nredir.redirect = redir;
9787 simplecmd(union node **rpp, union node *redir) {
9788 union node *args, **app;
9789 union node *n = NULL;
9790 union node *vars, **vpp;
9791 union node **orig_rpp;
9798 /* If we don't have any redirections already, then we must reset
9799 rpp to be the address of the local redir variable. */
9802 /* We save the incoming value, because we need this for shell
9803 functions. There can not be a redirect or an argument between
9804 the function name and the open parenthesis. */
9809 switch (readtoken()) {
9812 n = (union node *)stalloc(sizeof (struct narg));
9814 n->narg.text = wordtext;
9815 n->narg.backquote = backquotelist;
9816 if (lasttoken == TWORD) {
9818 app = &n->narg.next;
9821 vpp = &n->narg.next;
9825 *rpp = n = redirnode;
9826 rpp = &n->nfile.next;
9827 parsefname(); /* read name of redirection file */
9831 args && app == &args->narg.next &&
9832 !vars && rpp == orig_rpp
9834 /* We have a function */
9835 if (readtoken() != TRP)
9839 n->narg.next = command();
9852 n = (union node *)stalloc(sizeof (struct ncmd));
9854 n->ncmd.backgnd = 0;
9855 n->ncmd.args = args;
9856 n->ncmd.assign = vars;
9857 n->ncmd.redirect = redir;
9865 n = (union node *)stalloc(sizeof (struct narg));
9867 n->narg.next = NULL;
9868 n->narg.text = wordtext;
9869 n->narg.backquote = backquotelist;
9873 static void fixredir(union node *n, const char *text, int err)
9875 TRACE(("Fix redir %s %d\n", text, err));
9877 n->ndup.vname = NULL;
9879 if (is_digit(text[0]) && text[1] == '\0')
9880 n->ndup.dupfd = digit_val(text[0]);
9881 else if (text[0] == '-' && text[1] == '\0')
9886 synerror("Bad fd number");
9888 n->ndup.vname = makename();
9895 union node *n = redirnode;
9897 if (readtoken() != TWORD)
9899 if (n->type == NHERE) {
9900 struct heredoc *here = heredoc;
9906 TRACE(("Here document %d\n", n->type));
9907 if (here->striptabs) {
9908 while (*wordtext == '\t')
9911 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9912 synerror("Illegal eof marker for << redirection");
9913 rmescapes(wordtext);
9914 here->eofmark = wordtext;
9916 if (heredoclist == NULL)
9919 for (p = heredoclist ; p->next ; p = p->next);
9922 } else if (n->type == NTOFD || n->type == NFROMFD) {
9923 fixredir(n, wordtext, 0);
9925 n->nfile.fname = makename();
9931 * Input any here documents.
9936 struct heredoc *here;
9939 while (heredoclist) {
9941 heredoclist = here->next;
9946 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9947 here->eofmark, here->striptabs);
9948 n = (union node *)stalloc(sizeof (struct narg));
9949 n->narg.type = NARG;
9950 n->narg.next = NULL;
9951 n->narg.text = wordtext;
9952 n->narg.backquote = backquotelist;
9953 here->here->nhere.doc = n;
9963 return tokname_array[t][0];
9970 #ifdef CONFIG_ASH_ALIAS
9971 int savecheckalias = checkalias;
9972 int savecheckkwd = checkkwd;
9977 int alreadyseen = tokpushback;
9980 #ifdef CONFIG_ASH_ALIAS
9986 #ifdef CONFIG_ASH_ALIAS
9987 checkalias = savecheckalias;
9994 if (checkkwd == 2) {
10003 * check for keywords
10005 if (t == TWORD && !quoteflag)
10007 const char *const *pp;
10009 if ((pp = findkwd(wordtext))) {
10010 lasttoken = t = pp - tokname_array;
10011 TRACE(("keyword %s recognized\n", tokname(t)));
10022 } else if (checkalias == 2 && isassignment(wordtext)) {
10023 lasttoken = t = TASSIGN;
10024 #ifdef CONFIG_ASH_ALIAS
10025 } else if (checkalias) {
10026 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10028 pushstring(ap->val, strlen(ap->val), ap);
10030 checkkwd = savecheckkwd;
10039 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10041 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10048 * Read the next input token.
10049 * If the token is a word, we set backquotelist to the list of cmds in
10050 * backquotes. We set quoteflag to true if any part of the word was
10052 * If the token is TREDIR, then we set redirnode to a structure containing
10054 * In all cases, the variable startlinno is set to the number of the line
10055 * on which the token starts.
10057 * [Change comment: here documents and internal procedures]
10058 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10059 * word parsing code into a separate routine. In this case, readtoken
10060 * doesn't need to have any internal procedures, but parseword does.
10061 * We could also make parseoperator in essence the main routine, and
10062 * have parseword (readtoken1?) handle both words and redirection.]
10065 #define NEW_xxreadtoken
10066 #ifdef NEW_xxreadtoken
10068 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10069 static const char xxreadtoken_tokens[] = {
10070 TNL, TLP, TRP, /* only single occurrence allowed */
10071 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10072 TEOF, /* corresponds to trailing nul */
10073 TAND, TOR, TENDCASE, /* if double occurrence */
10076 #define xxreadtoken_doubles \
10077 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10078 #define xxreadtoken_singles \
10079 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10093 startlinno = plinno;
10094 for (;;) { /* until token or start of word found */
10097 if ((c!=' ') && (c!='\t')
10098 #ifdef CONFIG_ASH_ALIAS
10103 while ((c = pgetc()) != '\n' && c != PEOF);
10105 } else if (c=='\\') {
10106 if (pgetc() != '\n') {
10110 startlinno = ++plinno;
10111 setprompt(doprompt ? 2 : 0);
10114 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10119 needprompt = doprompt;
10122 p = strchr(xxreadtoken_chars, c);
10125 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10128 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10129 if (pgetc() == *p) { /* double occurrence? */
10130 p += xxreadtoken_doubles + 1;
10137 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10145 #define RETURN(token) return lasttoken = token
10159 startlinno = plinno;
10160 for (;;) { /* until token or start of word found */
10163 case ' ': case '\t':
10164 #ifdef CONFIG_ASH_ALIAS
10169 while ((c = pgetc()) != '\n' && c != PEOF);
10173 if (pgetc() == '\n') {
10174 startlinno = ++plinno;
10185 needprompt = doprompt;
10190 if (pgetc() == '&')
10195 if (pgetc() == '|')
10200 if (pgetc() == ';')
10213 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10219 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10220 * is not NULL, read a here document. In the latter case, eofmark is the
10221 * word which marks the end of the document and striptabs is true if
10222 * leading tabs should be stripped from the document. The argument firstc
10223 * is the first character of the input token or document.
10225 * Because C does not have internal subroutines, I have simulated them
10226 * using goto's to implement the subroutine linkage. The following macros
10227 * will run code that appears at the end of readtoken1.
10230 #define CHECKEND() {goto checkend; checkend_return:;}
10231 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10232 #define PARSESUB() {goto parsesub; parsesub_return:;}
10233 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10234 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10235 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10238 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10243 char line[EOFMARKLEN + 1];
10244 struct nodelist *bqlist;
10247 int varnest; /* levels of variables expansion */
10248 int arinest; /* levels of arithmetic expansion */
10249 int parenlevel; /* levels of parens in arithmetic */
10250 int dqvarnest; /* levels of variables expansion within double quotes */
10252 int prevsyntax; /* syntax before arithmetic */
10254 /* Avoid longjmp clobbering */
10260 (void) &parenlevel;
10263 (void) &prevsyntax;
10267 startlinno = plinno;
10269 if (syntax == DQSYNTAX)
10278 STARTSTACKSTR(out);
10279 loop: { /* for each line, until end of word */
10280 CHECKEND(); /* set c to PEOF if at end of here document */
10281 for (;;) { /* until end of line or end of word */
10282 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10283 switch(SIT(c,syntax)) {
10284 case CNL: /* '\n' */
10285 if (syntax == BASESYNTAX)
10286 goto endword; /* exit outer loop */
10294 goto loop; /* continue outer loop */
10299 if ((eofmark == NULL || dblquote) &&
10301 USTPUTC(CTLESC, out);
10304 case CBACK: /* backslash */
10307 USTPUTC('\\', out);
10309 } else if (c == '\n') {
10315 if (dblquote && c != '\\' && c != '`' && c != '$'
10316 && (c != '"' || eofmark != NULL))
10317 USTPUTC('\\', out);
10318 if (SIT(c,SQSYNTAX) == CCTL)
10319 USTPUTC(CTLESC, out);
10320 else if (eofmark == NULL)
10321 USTPUTC(CTLQUOTEMARK, out);
10327 if (eofmark == NULL)
10328 USTPUTC(CTLQUOTEMARK, out);
10332 if (eofmark == NULL)
10333 USTPUTC(CTLQUOTEMARK, out);
10338 if (eofmark != NULL && arinest == 0 &&
10343 syntax = ARISYNTAX;
10345 } else if (eofmark == NULL &&
10347 syntax = BASESYNTAX;
10353 case CVAR: /* '$' */
10354 PARSESUB(); /* parse substitution */
10356 case CENDVAR: /* '}' */
10359 if (dqvarnest > 0) {
10362 USTPUTC(CTLENDVAR, out);
10367 #ifdef CONFIG_ASH_MATH_SUPPORT
10368 case CLP: /* '(' in arithmetic */
10372 case CRP: /* ')' in arithmetic */
10373 if (parenlevel > 0) {
10377 if (pgetc() == ')') {
10378 if (--arinest == 0) {
10379 USTPUTC(CTLENDARI, out);
10380 syntax = prevsyntax;
10381 if (syntax == DQSYNTAX)
10389 * unbalanced parens
10390 * (don't 2nd guess - no error)
10398 case CBQUOTE: /* '`' */
10402 goto endword; /* exit outer loop */
10407 goto endword; /* exit outer loop */
10408 #ifdef CONFIG_ASH_ALIAS
10418 if (syntax == ARISYNTAX)
10419 synerror("Missing '))'");
10420 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10421 synerror("Unterminated quoted string");
10422 if (varnest != 0) {
10423 startlinno = plinno;
10424 synerror("Missing '}'");
10426 USTPUTC('\0', out);
10427 len = out - stackblock();
10428 out = stackblock();
10429 if (eofmark == NULL) {
10430 if ((c == '>' || c == '<')
10433 && (*out == '\0' || is_digit(*out))) {
10435 return lasttoken = TREDIR;
10440 quoteflag = quotef;
10441 backquotelist = bqlist;
10442 grabstackblock(len);
10444 return lasttoken = TWORD;
10445 /* end of readtoken routine */
10450 * Check to see whether we are at the end of the here document. When this
10451 * is called, c is set to the first character of the next input line. If
10452 * we are at the end of the here document, this routine sets the c to PEOF.
10457 #ifdef CONFIG_ASH_ALIAS
10463 while (c == '\t') {
10467 if (c == *eofmark) {
10468 if (pfgets(line, sizeof line) != NULL) {
10472 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10473 if (*p == '\n' && *q == '\0') {
10476 needprompt = doprompt;
10478 pushstring(line, strlen(line), NULL);
10483 goto checkend_return;
10488 * Parse a redirection operator. The variable "out" points to a string
10489 * specifying the fd to be redirected. The variable "c" contains the
10490 * first character of the redirection operator.
10497 np = (union node *)stalloc(sizeof (struct nfile));
10502 np->type = NAPPEND;
10511 } else { /* c == '<' */
10513 switch (c = pgetc()) {
10515 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10516 np = (union node *)stalloc(sizeof (struct nhere));
10520 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10521 heredoc->here = np;
10522 if ((c = pgetc()) == '-') {
10523 heredoc->striptabs = 1;
10525 heredoc->striptabs = 0;
10531 np->type = NFROMFD;
10535 np->type = NFROMTO;
10545 np->nfile.fd = digit_val(fd);
10547 goto parseredir_return;
10552 * Parse a substitution. At this point, we have read the dollar sign
10553 * and nothing else.
10561 static const char types[] = "}-+?=";
10566 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10570 } else if (c == '(') { /* $(command) or $((arith)) */
10571 if (pgetc() == '(') {
10578 USTPUTC(CTLVAR, out);
10579 typeloc = out - stackblock();
10580 USTPUTC(VSNORMAL, out);
10581 subtype = VSNORMAL;
10585 if ((c = pgetc()) == '}')
10588 subtype = VSLENGTH;
10593 if (c > PEOA && is_name(c)) {
10597 } while (c > PEOA && is_in_name(c));
10598 } else if (is_digit(c)) {
10602 } while (is_digit(c));
10604 else if (is_special(c)) {
10609 badsub: synerror("Bad substitution");
10613 if (subtype == 0) {
10620 p = strchr(types, c);
10623 subtype = p - types + VSNORMAL;
10629 subtype = c == '#' ? VSTRIMLEFT :
10642 if (dblquote || arinest)
10644 *(stackblock() + typeloc) = subtype | flags;
10645 if (subtype != VSNORMAL) {
10652 goto parsesub_return;
10657 * Called to parse command substitutions. Newstyle is set if the command
10658 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10659 * list of commands (passed by reference), and savelen is the number of
10660 * characters on the top of the stack which must be preserved.
10664 struct nodelist **nlpp;
10667 char *volatile str;
10668 struct jmploc jmploc;
10669 struct jmploc *volatile savehandler;
10673 (void) &saveprompt;
10676 savepbq = parsebackquote;
10677 if (setjmp(jmploc.loc)) {
10680 parsebackquote = 0;
10681 handler = savehandler;
10682 longjmp(handler->loc, 1);
10686 savelen = out - stackblock();
10688 str = xmalloc(savelen);
10689 memcpy(str, stackblock(), savelen);
10691 savehandler = handler;
10695 /* We must read until the closing backquote, giving special
10696 treatment to some slashes, and then push the string and
10697 reread it as input, interpreting it normally. */
10704 STARTSTACKSTR(pout);
10710 switch (pc = pgetc()) {
10715 if ((pc = pgetc()) == '\n') {
10722 * If eating a newline, avoid putting
10723 * the newline into the new character
10724 * stream (via the STPUTC after the
10729 if (pc != '\\' && pc != '`' && pc != '$'
10730 && (!dblquote || pc != '"'))
10731 STPUTC('\\', pout);
10738 #ifdef CONFIG_ASH_ALIAS
10741 startlinno = plinno;
10742 synerror("EOF in backquote substitution");
10746 needprompt = doprompt;
10755 STPUTC('\0', pout);
10756 psavelen = pout - stackblock();
10757 if (psavelen > 0) {
10758 pstr = grabstackstr(pout);
10759 setinputstring(pstr);
10764 nlpp = &(*nlpp)->next;
10765 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10766 (*nlpp)->next = NULL;
10767 parsebackquote = oldstyle;
10770 saveprompt = doprompt;
10777 doprompt = saveprompt;
10779 if (readtoken() != TRP)
10786 * Start reading from old file again, ignoring any pushed back
10787 * tokens left from the backquote parsing
10792 while (stackblocksize() <= savelen)
10794 STARTSTACKSTR(out);
10796 memcpy(out, str, savelen);
10797 STADJUST(savelen, out);
10803 parsebackquote = savepbq;
10804 handler = savehandler;
10805 if (arinest || dblquote)
10806 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10808 USTPUTC(CTLBACKQ, out);
10810 goto parsebackq_oldreturn;
10812 goto parsebackq_newreturn;
10816 * Parse an arithmetic expansion (indicate start of one and set state)
10820 if (++arinest == 1) {
10821 prevsyntax = syntax;
10822 syntax = ARISYNTAX;
10823 USTPUTC(CTLARI, out);
10830 * we collapse embedded arithmetic expansion to
10831 * parenthesis, which should be equivalent
10835 goto parsearith_return;
10838 } /* end of readtoken */
10842 * Returns true if the text contains nothing to expand (no dollar signs
10847 noexpand(char *text)
10853 while ((c = *p++) != '\0') {
10854 if (c == CTLQUOTEMARK)
10858 else if (SIT(c,BASESYNTAX) == CCTL)
10866 * Return true if the argument is a legal variable name (a letter or
10867 * underscore followed by zero or more letters, underscores, and digits).
10871 goodname(const char *name)
10879 if (! is_in_name(*p))
10887 * Called when an unexpected token is read during the parse. The argument
10888 * is the token that is expected, or -1 if more than one type of token can
10889 * occur at this point.
10893 synexpect(int token)
10898 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10900 sprintf(msg+l, " (expecting %s)", tokname(token));
10907 synerror(const char *msg)
10910 out2fmt("%s: %d: ", commandname, startlinno);
10911 out2fmt("Syntax error: %s\n", msg);
10912 error((char *)NULL);
10918 * called by editline -- any expansions to the prompt
10919 * should be added here.
10922 setprompt(int whichprompt)
10925 switch (whichprompt) {
10940 * Code for dealing with input/output redirection.
10943 #define EMPTY -2 /* marks an unused slot in redirtab */
10945 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10947 # define PIPESIZE PIPE_BUF
10952 * Open a file in noclobber mode.
10953 * The code was copied from bash.
10956 noclobberopen(const char *fname)
10959 struct stat finfo, finfo2;
10962 * If the file exists and is a regular file, return an error
10965 r = stat(fname, &finfo);
10966 if (r == 0 && S_ISREG(finfo.st_mode)) {
10972 * If the file was not present (r != 0), make sure we open it
10973 * exclusively so that if it is created before we open it, our open
10974 * will fail. Make sure that we do not truncate an existing file.
10975 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10976 * file was not a regular file, we leave O_EXCL off.
10979 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
10980 fd = open(fname, O_WRONLY|O_CREAT, 0666);
10982 /* If the open failed, return the file descriptor right away. */
10987 * OK, the open succeeded, but the file may have been changed from a
10988 * non-regular file to a regular file between the stat and the open.
10989 * We are assuming that the O_EXCL open handles the case where FILENAME
10990 * did not exist and is symlinked to an existing file between the stat
10995 * If we can open it and fstat the file descriptor, and neither check
10996 * revealed that it was a regular file, and the file has not been
10997 * replaced, return the file descriptor.
10999 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11000 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11003 /* The file has been replaced. badness. */
11010 * Handle here documents. Normally we fork off a process to write the
11011 * data to a pipe. If the document is short, we can stuff the data in
11012 * the pipe without forking.
11016 openhere(const union node *redir)
11022 error("Pipe call failed");
11023 if (redir->type == NHERE) {
11024 len = strlen(redir->nhere.doc->narg.text);
11025 if (len <= PIPESIZE) {
11026 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11030 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11032 signal(SIGINT, SIG_IGN);
11033 signal(SIGQUIT, SIG_IGN);
11034 signal(SIGHUP, SIG_IGN);
11036 signal(SIGTSTP, SIG_IGN);
11038 signal(SIGPIPE, SIG_DFL);
11039 if (redir->type == NHERE)
11040 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11042 expandhere(redir->nhere.doc, pip[1]);
11052 openredirect(const union node *redir)
11057 switch (redir->nfile.type) {
11059 fname = redir->nfile.expfname;
11060 if ((f = open(fname, O_RDONLY)) < 0)
11064 fname = redir->nfile.expfname;
11065 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11069 /* Take care of noclobber mode. */
11071 fname = redir->nfile.expfname;
11072 if ((f = noclobberopen(fname)) < 0)
11077 fname = redir->nfile.expfname;
11079 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11082 if ((f = creat(fname, 0666)) < 0)
11087 fname = redir->nfile.expfname;
11089 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11092 if ((f = open(fname, O_WRONLY)) < 0
11093 && (f = creat(fname, 0666)) < 0)
11095 lseek(f, (off_t)0, 2);
11102 /* Fall through to eliminate warning. */
11109 f = openhere(redir);
11115 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11117 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11122 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11123 * old file descriptors are stashed away so that the redirection can be
11124 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11125 * standard output, and the standard error if it becomes a duplicate of
11130 redirect(union node *redir, int flags)
11133 struct redirtab *sv = NULL;
11138 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11140 if (flags & REDIR_PUSH) {
11141 sv = xmalloc(sizeof (struct redirtab));
11142 for (i = 0 ; i < 10 ; i++)
11143 sv->renamed[i] = EMPTY;
11144 sv->next = redirlist;
11147 for (n = redir ; n ; n = n->nfile.next) {
11150 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11151 n->ndup.dupfd == fd)
11152 continue; /* redirect from/to same file descriptor */
11155 newfd = openredirect(n);
11156 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11159 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11163 dupredirect(n, newfd, fd1dup);
11173 error("%d: %m", fd);
11179 if (flags & REDIR_PUSH) {
11180 sv->renamed[fd] = i;
11183 } else if (fd != newfd) {
11189 dupredirect(n, newfd, fd1dup);
11196 dupredirect(const union node *redir, int f, int fd1dup)
11198 int fd = redir->nfile.fd;
11202 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11203 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11204 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11205 dup_as_newfd(redir->ndup.dupfd, fd);
11211 dup_as_newfd(f, fd);
11220 * Undo the effects of the last redirection.
11226 struct redirtab *rp = redirlist;
11230 for (i = 0 ; i < 10 ; i++) {
11231 if (rp->renamed[i] != EMPTY) {
11235 if (rp->renamed[i] >= 0) {
11236 dup_as_newfd(rp->renamed[i], i);
11237 close(rp->renamed[i]);
11241 redirlist = rp->next;
11247 * Discard all saved file descriptors.
11252 struct redirtab *rp;
11255 for (rp = redirlist ; rp ; rp = rp->next) {
11256 for (i = 0 ; i < 10 ; i++) {
11257 if (rp->renamed[i] >= 0) {
11258 close(rp->renamed[i]);
11260 rp->renamed[i] = EMPTY;
11267 * Copy a file descriptor to be >= to. Returns -1
11268 * if the source file descriptor is closed, EMPTY if there are no unused
11269 * file descriptors left.
11273 dup_as_newfd(int from, int to)
11277 newfd = fcntl(from, F_DUPFD, to);
11279 if (errno == EMFILE)
11282 error("%d: %m", from);
11291 static void shtree (union node *, int, char *, FILE*);
11292 static void shcmd (union node *, FILE *);
11293 static void sharg (union node *, FILE *);
11294 static void indent (int, char *, FILE *);
11295 static void trstring (char *);
11302 trputs("showtree called\n");
11303 shtree(n, 1, NULL, stdout);
11308 shtree(union node *n, int ind, char *pfx, FILE *fp)
11310 struct nodelist *lp;
11316 indent(ind, pfx, fp);
11327 shtree(n->nbinary.ch1, ind, NULL, fp);
11330 shtree(n->nbinary.ch2, ind, NULL, fp);
11338 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11343 if (n->npipe.backgnd)
11349 fprintf(fp, "<node type %d>", n->type);
11359 shcmd(union node *cmd, FILE *fp)
11367 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11373 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11379 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11380 s = redir_strings[np->nfile.type - NTO];
11386 switch (np->nfile.type) {
11387 case NTO: s = ">"; dftfd = 1; break;
11388 case NAPPEND: s = ">>"; dftfd = 1; break;
11389 case NTOFD: s = ">&"; dftfd = 1; break;
11390 case NTOOV: s = ">|"; dftfd = 1; break;
11391 case NFROM: s = "<"; dftfd = 0; break;
11392 case NFROMFD: s = "<&"; dftfd = 0; break;
11393 case NFROMTO: s = "<>"; dftfd = 0; break;
11394 default: s = "*error*"; dftfd = 0; break;
11397 if (np->nfile.fd != dftfd)
11398 fprintf(fp, "%d", np->nfile.fd);
11400 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11401 fprintf(fp, "%d", np->ndup.dupfd);
11403 sharg(np->nfile.fname, fp);
11410 sharg(union node *arg, FILE *fp)
11413 struct nodelist *bqlist;
11416 if (arg->type != NARG) {
11417 printf("<node type %d>\n", arg->type);
11421 bqlist = arg->narg.backquote;
11422 for (p = arg->narg.text ; *p ; p++) {
11431 if (subtype == VSLENGTH)
11437 if (subtype & VSNUL)
11440 switch (subtype & VSTYPE) {
11459 case VSTRIMLEFTMAX:
11466 case VSTRIMRIGHTMAX:
11473 printf("<subtype %d>", subtype);
11480 case CTLBACKQ|CTLQUOTE:
11483 shtree(bqlist->n, -1, NULL, fp);
11495 indent(int amount, char *pfx, FILE *fp)
11499 for (i = 0 ; i < amount ; i++) {
11500 if (pfx && i == amount - 1)
11510 static int debug = 1;
11512 static int debug = 0;
11519 if (tracefile == NULL)
11521 putc(c, tracefile);
11527 trace(const char *fmt, ...)
11531 if (tracefile != NULL) {
11532 (void) vfprintf(tracefile, fmt, va);
11533 if (strchr(fmt, '\n'))
11534 (void) fflush(tracefile);
11541 trputs(const char *s)
11543 if (tracefile == NULL)
11545 fputs(s, tracefile);
11546 if (strchr(s, '\n'))
11557 if (tracefile == NULL)
11559 putc('"', tracefile);
11560 for (p = s ; *p ; p++) {
11562 case '\n': c = 'n'; goto backslash;
11563 case '\t': c = 't'; goto backslash;
11564 case '\r': c = 'r'; goto backslash;
11565 case '"': c = '"'; goto backslash;
11566 case '\\': c = '\\'; goto backslash;
11567 case CTLESC: c = 'e'; goto backslash;
11568 case CTLVAR: c = 'v'; goto backslash;
11569 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11570 case CTLBACKQ: c = 'q'; goto backslash;
11571 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11572 backslash: putc('\\', tracefile);
11573 putc(c, tracefile);
11576 if (*p >= ' ' && *p <= '~')
11577 putc(*p, tracefile);
11579 putc('\\', tracefile);
11580 putc(*p >> 6 & 03, tracefile);
11581 putc(*p >> 3 & 07, tracefile);
11582 putc(*p & 07, tracefile);
11587 putc('"', tracefile);
11594 if (tracefile == NULL)
11599 putc(' ', tracefile);
11601 putc('\n', tracefile);
11617 #ifdef not_this_way
11620 if ((p = getenv("HOME")) == NULL) {
11621 if (geteuid() == 0)
11627 strcat(s, "/trace");
11630 strcpy(s, "./trace");
11631 #endif /* not_this_way */
11632 if ((tracefile = wfopen(s, "a")) == NULL)
11635 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11636 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11638 fputs("\nTracing started.\n", tracefile);
11645 * The trap builtin.
11649 trapcmd(int argc, char **argv)
11656 for (signo = 0 ; signo < NSIG ; signo++) {
11657 if (trap[signo] != NULL) {
11661 p = single_quote(trap[signo]);
11662 sn = sys_siglist[signo];
11664 sn = u_signal_names(0, &signo, 0);
11667 printf("trap -- %s %s\n", p, sn);
11679 if ((signo = decode_signal(*ap, 0)) < 0)
11680 error("%s: bad trap", *ap);
11683 if (action[0] == '-' && action[1] == '\0')
11686 action = xstrdup(action);
11689 ckfree(trap[signo]);
11690 trap[signo] = action;
11705 * Set the signal handler for the specified signal. The routine figures
11706 * out what it should be set to.
11710 setsignal(int signo)
11714 struct sigaction act;
11716 if ((t = trap[signo]) == NULL)
11718 else if (*t != '\0')
11722 if (rootshell && action == S_DFL) {
11725 if (iflag || minusc || sflag == 0)
11741 #ifdef CONFIG_ASH_JOB_CONTROL
11751 t = &sigmode[signo - 1];
11754 * current setting unknown
11756 if (sigaction(signo, 0, &act) == -1) {
11758 * Pretend it worked; maybe we should give a warning
11759 * here, but other shells don't. We don't alter
11760 * sigmode, so that we retry every time.
11764 if (act.sa_handler == SIG_IGN) {
11765 if (mflag && (signo == SIGTSTP ||
11766 signo == SIGTTIN || signo == SIGTTOU)) {
11767 *t = S_IGN; /* don't hard ignore these */
11771 *t = S_RESET; /* force to be set */
11774 if (*t == S_HARD_IGN || *t == action)
11776 act.sa_handler = ((action == S_CATCH) ? onsig
11777 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11780 sigemptyset(&act.sa_mask);
11781 sigaction(signo, &act, 0);
11789 ignoresig(int signo)
11791 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11792 signal(signo, SIG_IGN);
11794 sigmode[signo - 1] = S_HARD_IGN;
11805 if (signo == SIGINT && trap[SIGINT] == NULL) {
11809 gotsig[signo - 1] = 1;
11815 * Called to execute a trap. Perhaps we should avoid entering new trap
11816 * handlers while we are executing a trap handler.
11826 for (i = 1 ; ; i++) {
11833 savestatus=exitstatus;
11834 evalstring(trap[i], 0);
11835 exitstatus=savestatus;
11842 * Called to exit the shell.
11846 exitshell(int status)
11848 struct jmploc loc1, loc2;
11851 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11852 if (setjmp(loc1.loc)) {
11855 if (setjmp(loc2.loc)) {
11859 if ((p = trap[0]) != NULL && *p != '\0') {
11863 l1: handler = &loc2; /* probably unnecessary */
11865 #ifdef CONFIG_ASH_JOB_CONTROL
11872 static int decode_signal(const char *string, int minsig)
11875 const char *name = u_signal_names(string, &signo, minsig);
11877 return name ? signo : -1;
11880 static struct var **hashvar (const char *);
11881 static void showvars (const char *, int, int);
11882 static struct var **findvar (struct var **, const char *);
11885 * Initialize the varable symbol tables and import the environment
11889 * This routine initializes the builtin variables. It is called when the
11890 * shell is initialized and again when a shell procedure is spawned.
11895 const struct varinit *ip;
11899 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
11900 if ((vp->flags & VEXPORT) == 0) {
11901 vpp = hashvar(ip->text);
11904 vp->text = xstrdup(ip->text);
11905 vp->flags = ip->flags;
11906 vp->func = ip->func;
11909 #if !defined(CONFIG_FEATURE_COMMAND_EDITING) || !defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
11911 * PS1 depends on uid
11913 if ((vps1.flags & VEXPORT) == 0) {
11914 vpp = hashvar("PS1=$");
11917 vps1.text = xstrdup(geteuid() ? "PS1=$ " : "PS1=# ");
11918 vps1.flags = VSTRFIXED|VTEXTFIXED;
11924 * Set the value of a variable. The flags argument is ored with the
11925 * flags of the variable. If val is NULL, the variable is unset.
11929 setvar(const char *name, const char *val, int flags)
11944 if (! is_in_name(*p)) {
11945 if (*p == '\0' || *p == '=')
11951 namelen = p - name;
11953 error("%.*s: bad variable name", namelen, name);
11954 len = namelen + 2; /* 2 is space for '=' and '\0' */
11958 len += vallen = strlen(val);
11961 nameeq = xmalloc(len);
11962 memcpy(nameeq, name, namelen);
11963 nameeq[namelen] = '=';
11965 memcpy(nameeq + namelen + 1, val, vallen + 1);
11967 nameeq[namelen + 1] = '\0';
11969 setvareq(nameeq, flags);
11976 * Same as setvar except that the variable and value are passed in
11977 * the first argument as name=value. Since the first argument will
11978 * be actually stored in the table, it should not be a string that
11983 setvareq(char *s, int flags)
11985 struct var *vp, **vpp;
11988 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11989 if ((vp = *findvar(vpp, s))) {
11990 if (vp->flags & VREADONLY) {
11991 size_t len = strchr(s, '=') - s;
11992 error("%.*s: is read only", len, s);
11996 if (vp->func && (flags & VNOFUNC) == 0)
11997 (*vp->func)(strchr(s, '=') + 1);
11999 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12002 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12003 vp->flags |= flags;
12006 #ifdef CONFIG_ASH_MAIL
12008 * We could roll this to a function, to handle it as
12009 * a regular variable function callback, but why bother?
12011 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12018 vp = xmalloc(sizeof (*vp));
12029 * Process a linked list of variable assignments.
12033 listsetvar(struct strlist *mylist)
12035 struct strlist *lp;
12038 for (lp = mylist ; lp ; lp = lp->next) {
12039 setvareq(xstrdup(lp->text), 0);
12047 * Find the value of a variable. Returns NULL if not set.
12050 static const char *
12051 lookupvar(const char *name)
12055 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12056 return strchr(v->text, '=') + 1;
12064 * Search the environment of a builtin command.
12067 static const char *
12068 bltinlookup(const char *name)
12070 const struct strlist *sp;
12072 for (sp = cmdenviron ; sp ; sp = sp->next) {
12073 if (varequal(sp->text, name))
12074 return strchr(sp->text, '=') + 1;
12076 return lookupvar(name);
12082 * Generate a list of exported variables. This routine is used to construct
12083 * the third argument to execve when executing a program.
12095 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12096 for (vp = *vpp ; vp ; vp = vp->next)
12097 if (vp->flags & VEXPORT)
12100 ep = env = stalloc((nenv + 1) * sizeof *env);
12101 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12102 for (vp = *vpp ; vp ; vp = vp->next)
12103 if (vp->flags & VEXPORT)
12112 * Called when a shell procedure is invoked to clear out nonexported
12113 * variables. It is also necessary to reallocate variables of with
12114 * VSTACK set since these are currently allocated on the stack.
12120 struct var *vp, **prev;
12122 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12123 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12124 if ((vp->flags & VEXPORT) == 0) {
12126 if ((vp->flags & VTEXTFIXED) == 0)
12128 if ((vp->flags & VSTRFIXED) == 0)
12131 if (vp->flags & VSTACK) {
12132 vp->text = xstrdup(vp->text);
12133 vp->flags &=~ VSTACK;
12145 * Command to list all variables which are set. Currently this command
12146 * is invoked from the set command when the set command is called without
12151 showvarscmd(int argc, char **argv)
12153 showvars(nullstr, VUNSET, VUNSET);
12160 * The export and readonly commands.
12164 exportcmd(int argc, char **argv)
12169 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12172 listsetvar(cmdenviron);
12173 pflag = (nextopt("p") == 'p');
12174 if (argc > 1 && !pflag) {
12175 while ((name = *argptr++) != NULL) {
12176 if ((p = strchr(name, '=')) != NULL) {
12179 if ((vp = *findvar(hashvar(name), name))) {
12184 setvar(name, p, flag);
12188 showvars(argv[0], flag, 0);
12195 * The "local" command.
12198 /* funcnest nonzero if we are currently evaluating a function */
12201 localcmd(int argc, char **argv)
12206 error("Not in a function");
12207 while ((name = *argptr++) != NULL) {
12215 * Make a variable a local variable. When a variable is made local, it's
12216 * value and flags are saved in a localvar structure. The saved values
12217 * will be restored when the shell function returns. We handle the name
12218 * "-" as a special case.
12222 mklocal(char *name)
12224 struct localvar *lvp;
12229 lvp = xmalloc(sizeof (struct localvar));
12230 if (name[0] == '-' && name[1] == '\0') {
12232 p = xmalloc(sizeof optet_vals);
12233 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12236 vpp = hashvar(name);
12237 vp = *findvar(vpp, name);
12239 if (strchr(name, '='))
12240 setvareq(xstrdup(name), VSTRFIXED);
12242 setvar(name, NULL, VSTRFIXED);
12243 vp = *vpp; /* the new variable */
12245 lvp->flags = VUNSET;
12247 lvp->text = vp->text;
12248 lvp->flags = vp->flags;
12249 vp->flags |= VSTRFIXED|VTEXTFIXED;
12250 if (strchr(name, '='))
12251 setvareq(xstrdup(name), 0);
12255 lvp->next = localvars;
12262 * Called after a function returns.
12267 struct localvar *lvp;
12270 while ((lvp = localvars) != NULL) {
12271 localvars = lvp->next;
12273 if (vp == NULL) { /* $- saved */
12274 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12276 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12277 (void)unsetvar(vp->text);
12279 if ((vp->flags & VTEXTFIXED) == 0)
12281 vp->flags = lvp->flags;
12282 vp->text = lvp->text;
12290 setvarcmd(int argc, char **argv)
12293 return unsetcmd(argc, argv);
12294 else if (argc == 3)
12295 setvar(argv[1], argv[2], 0);
12297 error("List assignment not implemented");
12303 * The unset builtin command. We unset the function before we unset the
12304 * variable to allow a function to be unset when there is a readonly variable
12305 * with the same name.
12309 unsetcmd(int argc, char **argv)
12317 while ((i = nextopt("vf")) != '\0') {
12323 if (flg_func == 0 && flg_var == 0)
12326 for (ap = argptr; *ap ; ap++) {
12330 ret |= unsetvar(*ap);
12337 * Unset the specified variable.
12341 unsetvar(const char *s)
12346 vpp = findvar(hashvar(s), s);
12349 if (vp->flags & VREADONLY)
12352 if (*(strchr(vp->text, '=') + 1) != '\0')
12353 setvar(s, nullstr, 0);
12354 vp->flags &= ~VEXPORT;
12355 vp->flags |= VUNSET;
12356 if ((vp->flags & VSTRFIXED) == 0) {
12357 if ((vp->flags & VTEXTFIXED) == 0)
12372 * Find the appropriate entry in the hash table from the name.
12375 static struct var **
12376 hashvar(const char *p)
12378 unsigned int hashval;
12380 hashval = ((unsigned char) *p) << 4;
12381 while (*p && *p != '=')
12382 hashval += (unsigned char) *p++;
12383 return &vartab[hashval % VTABSIZE];
12389 * Returns true if the two strings specify the same varable. The first
12390 * variable name is terminated by '='; the second may be terminated by
12391 * either '=' or '\0'.
12395 varequal(const char *p, const char *q)
12397 while (*p == *q++) {
12401 if (*p == '=' && *(q - 1) == '\0')
12407 showvars(const char *myprefix, int mask, int xor)
12411 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12413 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12414 for (vp = *vpp ; vp ; vp = vp->next) {
12415 if ((vp->flags & mask) ^ xor) {
12419 p = strchr(vp->text, '=') + 1;
12420 len = p - vp->text;
12421 p = single_quote(p);
12423 printf("%s%s%.*s%s\n", myprefix, sep, len,
12431 static struct var **
12432 findvar(struct var **vpp, const char *name)
12434 for (; *vpp; vpp = &(*vpp)->next) {
12435 if (varequal((*vpp)->text, name)) {
12443 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12444 * This file contains code for the times builtin.
12445 * $Id: ash.c,v 1.51 2002/06/04 20:10:15 sandman Exp $
12447 static int timescmd (int argc, char **argv)
12450 long int clk_tck = sysconf(_SC_CLK_TCK);
12453 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12454 (int) (buf.tms_utime / clk_tck / 60),
12455 ((double) buf.tms_utime) / clk_tck,
12456 (int) (buf.tms_stime / clk_tck / 60),
12457 ((double) buf.tms_stime) / clk_tck,
12458 (int) (buf.tms_cutime / clk_tck / 60),
12459 ((double) buf.tms_cutime) / clk_tck,
12460 (int) (buf.tms_cstime / clk_tck / 60),
12461 ((double) buf.tms_cstime) / clk_tck);
12465 #ifdef CONFIG_ASH_MATH_SUPPORT
12466 /* The let builtin. */
12467 int letcmd(int argc, char **argv)
12472 char *tmp, *expression, p[13];
12473 expression = strchr(argv[1], '=');
12475 /* Cannot use 'error()' here, or the return code
12476 * will be incorrect */
12477 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12480 *expression = '\0';
12481 tmp = ++expression;
12482 result = arith(tmp, &errcode);
12484 /* Cannot use 'error()' here, or the return code
12485 * will be incorrect */
12486 out2fmt("sh: let: ");
12488 out2fmt("divide by zero");
12490 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12493 snprintf(p, 12, "%ld", result);
12494 setvar(argv[1], xstrdup(p), 0);
12495 } else if (argc >= 3)
12496 synerror("invalid operand");
12504 * Copyright (c) 1989, 1991, 1993, 1994
12505 * The Regents of the University of California. All rights reserved.
12507 * This code is derived from software contributed to Berkeley by
12508 * Kenneth Almquist.
12510 * Redistribution and use in source and binary forms, with or without
12511 * modification, are permitted provided that the following conditions
12513 * 1. Redistributions of source code must retain the above copyright
12514 * notice, this list of conditions and the following disclaimer.
12515 * 2. Redistributions in binary form must reproduce the above copyright
12516 * notice, this list of conditions and the following disclaimer in the
12517 * documentation and/or other materials provided with the distribution.
12519 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12520 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12522 * 4. Neither the name of the University nor the names of its contributors
12523 * may be used to endorse or promote products derived from this software
12524 * without specific prior written permission.
12526 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12527 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12528 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12529 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12530 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12531 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12532 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12533 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12534 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12535 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF