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 /* These defines allow you to adjust the feature set to be compiled
37 * into the ash shell. As a rule, enabling these options will make
38 * ash get bigger... With all of these options off, ash adds about
39 * 60k to busybox on an x86 system.*/
42 /* Enable job control. This allows you to run jobs in the background,
43 * which is great when ash is being used as an interactive shell, but
44 * it completely useless for is all you are doing is running scripts.
45 * This adds about 2.5k on an x86 system. */
48 /* This enables alias support in ash. If you want to support things
49 * like "alias ls='ls -l'" with ash, enable this. This is only useful
50 * when ash is used as an intractive shell. This adds about 1.5k */
53 /* If you need ash to act as a full Posix shell, with full math
54 * support, enable this. This adds a bit over 2k an x86 system. */
55 //#undef ASH_MATH_SUPPORT
56 #define ASH_MATH_SUPPORT
58 /* Getopts is used by shell procedures to parse positional parameters.
59 * You probably want to leave this disabled, and use the busybox getopt
60 * applet if you want to do this sort of thing. There are some scripts
61 * out there that use it, so it you need it, enable. Most people will
62 * leave this disabled. This adds 1k on an x86 system. */
65 /* This allows you to override shell builtins and use whatever is on
66 * the filesystem. This is most useful when ash is acting as a
67 * standalone shell. Adds about 272 bytes. */
71 /* Optimize size vs speed as size */
72 #define ASH_OPTIMIZE_FOR_SIZE
74 /* Enable this to compile in extra debugging noise. When debugging is
75 * on, debugging info will be written to $HOME/trace and a quit signal
76 * will generate a core dump. */
79 /* These are here to work with glibc -- Don't change these... */
100 #include <sys/stat.h>
101 #include <sys/cdefs.h>
102 #include <sys/ioctl.h>
103 #include <sys/param.h>
104 #include <sys/resource.h>
105 #include <sys/time.h>
106 #include <sys/times.h>
107 #include <sys/types.h>
108 #include <sys/wait.h>
111 #if !defined(FNMATCH_BROKEN)
114 #if !defined(GLOB_BROKEN)
126 * This file was generated by the mksyntax program.
130 #define CWORD 0 /* character is nothing special */
131 #define CNL 1 /* newline character */
132 #define CBACK 2 /* a backslash character */
133 #define CSQUOTE 3 /* single quote */
134 #define CDQUOTE 4 /* double quote */
135 #define CENDQUOTE 5 /* a terminating quote */
136 #define CBQUOTE 6 /* backwards single quote */
137 #define CVAR 7 /* a dollar sign */
138 #define CENDVAR 8 /* a '}' character */
139 #define CLP 9 /* a left paren in arithmetic */
140 #define CRP 10 /* a right paren in arithmetic */
141 #define CENDFILE 11 /* end of file */
142 #define CCTL 12 /* like CWORD, except it must be escaped */
143 #define CSPCL 13 /* these terminate a word */
144 #define CIGN 14 /* character should be ignored */
164 #define TENDBQUOTE 13
184 /* control characters in argument strings */
185 #define CTLESC '\201'
186 #define CTLVAR '\202'
187 #define CTLENDVAR '\203'
188 #define CTLBACKQ '\204'
189 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
190 /* CTLBACKQ | CTLQUOTE == '\205' */
191 #define CTLARI '\206'
192 #define CTLENDARI '\207'
193 #define CTLQUOTEMARK '\210'
196 #define is_digit(c) ((c)>='0' && (c)<='9')
197 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
198 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
201 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
202 * (assuming ascii char codes, as the original implementation did)
204 #define is_special(c) \
205 ( (((unsigned int)c) - 33 < 32) \
206 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
208 #define digit_val(c) ((c) - '0')
211 #define _DIAGASSERT(x)
215 #define S_DFL 1 /* default signal handling (SIG_DFL) */
216 #define S_CATCH 2 /* signal is caught */
217 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
218 #define S_HARD_IGN 4 /* signal is ignored permenantly */
219 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
222 /* variable substitution byte (follows CTLVAR) */
223 #define VSTYPE 0x0f /* type of variable substitution */
224 #define VSNUL 0x10 /* colon--treat the empty string as unset */
225 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
227 /* values of VSTYPE field */
228 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
229 #define VSMINUS 0x2 /* ${var-text} */
230 #define VSPLUS 0x3 /* ${var+text} */
231 #define VSQUESTION 0x4 /* ${var?message} */
232 #define VSASSIGN 0x5 /* ${var=text} */
233 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
234 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
235 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
236 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
237 #define VSLENGTH 0xa /* ${#var} */
239 /* flags passed to redirect */
240 #define REDIR_PUSH 01 /* save previous values of file descriptors */
241 #define REDIR_BACKQ 02 /* save the command output to pipe */
244 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
245 * so we use _setjmp instead.
249 #define setjmp(jmploc) _setjmp(jmploc)
250 #define longjmp(jmploc, val) _longjmp(jmploc, val)
254 * Most machines require the value returned from malloc to be aligned
255 * in some way. The following macro will get this right on many machines.
264 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
267 #ifdef BB_LOCALE_SUPPORT
269 static void change_lc_all(const char *value);
270 static void change_lc_ctype(const char *value);
274 * These macros allow the user to suspend the handling of interrupt signals
275 * over a period of time. This is similar to SIGHOLD to or sigblock, but
276 * much more efficient and portable. (But hacking the kernel is so much
277 * more fun than worrying about efficiency and portability. :-))
280 static void onint (void);
281 static volatile int suppressint;
282 static volatile int intpending;
284 #define INTOFF suppressint++
285 #ifndef ASH_OPTIMIZE_FOR_SIZE
286 #define INTON { if (--suppressint == 0 && intpending) onint(); }
287 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
289 static void __inton (void);
290 static void forceinton (void);
291 #define INTON __inton()
292 #define FORCEINTON forceinton()
295 #define CLEAR_PENDING_INT intpending = 0
296 #define int_pending() intpending
299 typedef void *pointer;
301 #define NULL (void *)0
304 static inline pointer ckmalloc (int sz) { return xmalloc(sz); }
305 static inline pointer ckrealloc(void *p, int sz) { return xrealloc(p, sz); }
306 static inline char * savestr (const char *s) { return xstrdup(s); }
308 static pointer stalloc (int);
309 static void stunalloc (pointer);
310 static void ungrabstackstr (char *, char *);
311 static char * growstackstr(void);
312 static char * makestrspace(size_t newlen);
313 static char *sstrdup (const char *);
316 * Parse trees for commands are allocated in lifo order, so we use a stack
317 * to make this more efficient, and also to avoid all sorts of exception
318 * handling code to handle interrupts in the middle of a parse.
320 * The size 504 was chosen because the Ultrix malloc handles that size
324 #define MINSIZE 504 /* minimum size of a block */
328 struct stack_block *prev;
332 static struct stack_block stackbase;
333 static struct stack_block *stackp = &stackbase;
334 static struct stackmark *markp;
335 static char *stacknxt = stackbase.space;
336 static int stacknleft = MINSIZE;
339 #define equal(s1, s2) (strcmp(s1, s2) == 0)
341 #define stackblock() stacknxt
342 #define stackblocksize() stacknleft
343 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
345 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
346 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
347 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
350 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
351 #define STUNPUTC(p) (++sstrnleft, --p)
352 #define STTOPC(p) p[-1]
353 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
354 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
356 #define ckfree(p) free((pointer)(p))
360 #define TRACE(param) trace param
361 static void trace (const char *, ...);
362 static void trargs (char **);
363 static void showtree (union node *);
364 static void trputc (int);
365 static void trputs (const char *);
366 static void opentrace (void);
401 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
402 #define EXP_TILDE 0x2 /* do normal tilde expansion */
403 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
404 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
405 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
406 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
411 static char optet_vals[NOPTS];
413 static const char * const optlist[NOPTS] = {
432 #define optent_name(optent) (optent+1)
433 #define optent_letter(optent) optent[0]
434 #define optent_val(optent) optet_vals[optent]
436 #define eflag optent_val(0)
437 #define fflag optent_val(1)
438 #define Iflag optent_val(2)
439 #define iflag optent_val(3)
440 #define mflag optent_val(4)
441 #define nflag optent_val(5)
442 #define sflag optent_val(6)
443 #define xflag optent_val(7)
444 #define vflag optent_val(8)
445 #define Vflag optent_val(9)
446 #define Eflag optent_val(10)
447 #define Cflag optent_val(11)
448 #define aflag optent_val(12)
449 #define bflag optent_val(13)
450 #define uflag optent_val(14)
451 #define qflag optent_val(15)
454 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
472 union node *redirect;
479 struct nodelist *cmdlist;
486 union node *redirect;
494 union node *elsepart;
525 struct nodelist *backquote;
563 struct nbinary nbinary;
566 struct nredir nredir;
570 struct nclist nclist;
580 struct nodelist *next;
584 struct backcmd { /* result of evalbackcmd */
585 int fd; /* file descriptor to read from */
586 char *buf; /* buffer */
587 int nleft; /* number of chars in buffer */
588 struct job *jp; /* job structure for command */
596 const struct builtincmd *cmd;
601 struct strlist *next;
607 struct strlist *list;
608 struct strlist **lastp;
612 struct strpush *prev; /* preceding string on stack */
616 struct alias *ap; /* if push was associated with an alias */
618 char *string; /* remember the string since it may change */
622 struct parsefile *prev; /* preceding file on stack */
623 int linno; /* current line */
624 int fd; /* file descriptor (or -1 if string) */
625 int nleft; /* number of chars left in this line */
626 int lleft; /* number of chars left in this buffer */
627 char *nextc; /* next char in buffer */
628 char *buf; /* input buffer */
629 struct strpush *strpush; /* for pushing strings at this level */
630 struct strpush basestrpush; /* so pushing one is fast */
634 struct stack_block *stackp;
637 struct stackmark *marknext;
641 int nparam; /* # of positional parameters (without $0) */
642 unsigned char malloc; /* if parameter list dynamically allocated */
643 char **p; /* parameter list */
644 int optind; /* next parameter to be processed by getopts */
645 int optoff; /* used by getopts */
649 * When commands are first encountered, they are entered in a hash table.
650 * This ensures that a full path search will not have to be done for them
651 * on each invocation.
653 * We should investigate converting to a linear search, even though that
654 * would make the command name "hash" a misnomer.
656 #define CMDTABLESIZE 31 /* should be prime */
657 #define ARB 1 /* actual size determined at run time */
662 struct tblentry *next; /* next entry in hash chain */
663 union param param; /* definition of builtin function */
664 short cmdtype; /* index identifying command */
665 char rehash; /* if set, cd done since entry created */
666 char cmdname[ARB]; /* name of command */
670 static struct tblentry *cmdtable[CMDTABLESIZE];
671 static int builtinloc = -1; /* index in path of %builtin, or -1 */
672 static int exerrno = 0; /* Last exec error */
675 static void tryexec (char *, char **, char **);
676 static void printentry (struct tblentry *, int);
677 static void clearcmdentry (int);
678 static struct tblentry *cmdlookup (const char *, int);
679 static void delete_cmd_entry (void);
680 static int path_change (const char *, int *);
683 static void flushall (void);
684 static void out2fmt (const char *, ...)
685 __attribute__((__format__(__printf__,1,2)));
686 static int xwrite (int, const char *, int);
688 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
689 static void out1str(const char *p) { outstr(p, stdout); }
690 static void out2str(const char *p) { outstr(p, stderr); }
692 #ifndef ASH_OPTIMIZE_FOR_SIZE
693 #define out2c(c) putc((c), stderr)
695 static void out2c(int c) { putc(c, stderr); }
699 #ifdef ASH_OPTIMIZE_FOR_SIZE
700 #define USE_SIT_FUNCTION
703 /* number syntax index */
704 #define BASESYNTAX 0 /* not in quotes */
705 #define DQSYNTAX 1 /* in double quotes */
706 #define SQSYNTAX 2 /* in single quotes */
707 #define ARISYNTAX 3 /* in arithmetic */
709 static const char S_I_T[][4] = {
710 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
711 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
712 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
713 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
714 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
715 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
716 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
717 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
718 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
719 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
720 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
721 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
722 #ifndef USE_SIT_FUNCTION
723 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
724 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
725 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
729 #ifdef USE_SIT_FUNCTION
731 #define U_C(c) ((unsigned char)(c))
733 static int SIT(int c, int syntax)
735 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
736 static const char syntax_index_table [] = {
737 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
738 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
739 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
744 if(c==PEOF) /* 2^8+2 */
746 if(c==PEOA) /* 2^8+1 */
748 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
751 s = strchr(spec_symbls, c);
754 indx = syntax_index_table[(s-spec_symbls)];
756 return S_I_T[indx][syntax];
759 #else /* USE_SIT_FUNCTION */
761 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
763 #define CSPCL_CIGN_CIGN_CIGN 0
764 #define CSPCL_CWORD_CWORD_CWORD 1
765 #define CNL_CNL_CNL_CNL 2
766 #define CWORD_CCTL_CCTL_CWORD 3
767 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
768 #define CVAR_CVAR_CWORD_CVAR 5
769 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
770 #define CSPCL_CWORD_CWORD_CLP 7
771 #define CSPCL_CWORD_CWORD_CRP 8
772 #define CBACK_CBACK_CCTL_CBACK 9
773 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
774 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
775 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
776 #define CWORD_CWORD_CWORD_CWORD 13
777 #define CCTL_CCTL_CCTL_CCTL 14
779 static const char syntax_index_table[258] = {
780 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
781 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
782 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
783 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
784 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
785 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
786 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
787 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
788 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
789 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
790 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
791 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
792 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
793 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
794 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
795 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
796 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
797 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
798 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
799 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
800 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
801 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
802 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
803 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
804 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
805 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
806 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
807 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
808 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
809 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
810 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
811 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
812 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
813 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
814 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
815 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
816 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
817 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
818 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
819 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
820 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
821 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
822 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
823 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
824 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
825 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
826 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
827 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
828 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
829 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
830 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
831 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
832 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
833 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
834 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
835 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
836 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
837 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
838 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
839 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
840 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
841 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
842 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
843 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
844 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
845 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
846 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
847 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
848 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
849 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
850 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
851 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
852 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
853 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
854 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
855 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
856 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
857 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
858 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
859 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
860 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
861 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
862 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
863 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
864 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
865 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
866 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
867 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
868 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
869 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
870 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
871 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
872 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
873 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
874 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
875 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
876 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
877 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
878 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
879 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
880 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
881 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
882 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
883 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
884 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
885 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
886 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
887 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
888 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
889 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
890 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
891 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
892 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
893 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
894 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
895 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
896 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
897 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
898 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
899 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
900 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
901 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
902 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
903 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
904 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
905 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
906 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
907 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
908 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
909 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
910 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
911 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
912 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
913 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
914 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
915 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
916 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
917 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
918 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
919 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
920 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
921 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
922 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
923 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
924 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
925 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
926 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
927 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
928 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
929 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
930 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
931 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
932 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
933 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
934 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
935 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
936 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
937 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
938 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
939 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
940 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
941 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
942 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
943 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
944 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
945 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
946 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
947 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
948 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
949 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
950 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
951 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
952 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
953 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
954 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
955 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
956 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
957 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
958 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
959 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
960 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
961 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
962 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
963 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
964 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
965 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
966 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
967 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
968 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
969 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
970 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
971 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
972 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
973 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
974 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
975 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
976 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
977 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
978 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
979 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
980 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
981 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
982 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
983 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
984 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
985 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
986 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
987 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
988 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
989 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
990 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
991 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
992 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
993 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
994 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
995 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
996 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
997 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
998 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
999 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1003 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1004 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1005 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1008 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1032 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1033 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1034 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1035 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1036 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1037 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1038 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1041 #endif /* USE_SIT_FUNCTION */
1044 /* first char is indicating which tokens mark the end of a list */
1045 static const char *const tokname_array[] = {
1060 #define KWDOFFSET 14
1061 /* the following are keywords */
1080 static const char *tokname(int tok)
1082 static char buf[16];
1086 sprintf(buf+(tok>=TSEMI), "%s%c",
1087 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1091 static int plinno = 1; /* input line number */
1093 static int parselleft; /* copy of parsefile->lleft */
1095 static struct parsefile basepf; /* top level input file */
1096 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1097 static struct parsefile *parsefile = &basepf; /* current input file */
1100 * NEOF is returned by parsecmd when it encounters an end of file. It
1101 * must be distinct from NULL, so we use the address of a variable that
1102 * happens to be handy.
1105 static int tokpushback; /* last token pushed back */
1106 #define NEOF ((union node *)&tokpushback)
1107 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1110 static void error (const char *, ...) __attribute__((__noreturn__));
1111 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1112 static void shellexec (char **, char **, const char *, int)
1113 __attribute__((noreturn));
1114 static void exitshell (int) __attribute__((noreturn));
1116 static int goodname(const char *);
1117 static void ignoresig (int);
1118 static void onsig (int);
1119 static void dotrap (void);
1120 static int decode_signal (const char *, int);
1122 static void shprocvar(void);
1123 static void deletefuncs(void);
1124 static void setparam (char **);
1125 static void freeparam (volatile struct shparam *);
1127 /* reasons for skipping commands (see comment on breakcmd routine) */
1133 /* values of cmdtype */
1134 #define CMDUNKNOWN -1 /* no entry in table for command */
1135 #define CMDNORMAL 0 /* command is an executable program */
1136 #define CMDBUILTIN 1 /* command is a shell builtin */
1137 #define CMDFUNCTION 2 /* command is a shell function */
1139 #define DO_ERR 1 /* find_command prints errors */
1140 #define DO_ABS 2 /* find_command checks absolute paths */
1141 #define DO_NOFUN 4 /* find_command ignores functions */
1142 #define DO_BRUTE 8 /* find_command ignores hash table */
1149 #define VEXPORT 0x01 /* variable is exported */
1150 #define VREADONLY 0x02 /* variable cannot be modified */
1151 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1152 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1153 #define VSTACK 0x10 /* text is allocated on the stack */
1154 #define VUNSET 0x20 /* the variable is not set */
1155 #define VNOFUNC 0x40 /* don't call the callback function */
1159 struct var *next; /* next entry in hash list */
1160 int flags; /* flags are defined above */
1161 char *text; /* name=value */
1162 void (*func) (const char *);
1163 /* function to be called when */
1164 /* the variable gets set/unset */
1168 struct localvar *next; /* next local variable in list */
1169 struct var *vp; /* the variable that was made local */
1170 int flags; /* saved flags */
1171 char *text; /* saved text */
1175 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1176 #define rmescapes(p) _rmescapes((p), 0)
1177 static char *_rmescapes (char *, int);
1179 static void rmescapes (char *);
1182 static int casematch (union node *, const char *);
1183 static void clearredir(void);
1184 static void popstring(void);
1185 static void readcmdfile (const char *);
1187 static int number (const char *);
1188 static int is_number (const char *, int *num);
1189 static char *single_quote (const char *);
1190 static int nextopt (const char *);
1192 static void redirect (union node *, int);
1193 static void popredir (void);
1194 static int dup_as_newfd (int, int);
1196 static void changepath(const char *newval);
1197 static void getoptsreset(const char *value);
1200 static int parsenleft; /* copy of parsefile->nleft */
1201 static char *parsenextc; /* copy of parsefile->nextc */
1202 static int rootpid; /* pid of main shell */
1203 static int rootshell; /* true if we aren't a child of the main shell */
1205 static const char spcstr[] = " ";
1206 static const char snlfmt[] = "%s\n";
1208 static int sstrnleft;
1209 static int herefd = -1;
1211 static struct localvar *localvars;
1213 static struct var vifs;
1214 static struct var vmail;
1215 static struct var vmpath;
1216 static struct var vpath;
1217 static struct var vps1;
1218 static struct var vps2;
1219 static struct var voptind;
1220 #ifdef BB_LOCALE_SUPPORT
1221 static struct var vlc_all;
1222 static struct var vlc_ctype;
1229 void (*func) (const char *);
1232 static const char defpathvar[] =
1233 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1234 #define defpath (defpathvar + 5)
1237 static const char defifsvar[] = "IFS= \t\n";
1238 #define defifs (defifsvar + 4)
1240 static const char defifs[] = " \t\n";
1243 static const struct varinit varinit[] = {
1245 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1247 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1250 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1252 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1254 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1257 * vps1 depends on uid
1259 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1261 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1263 #ifdef BB_LOCALE_SUPPORT
1264 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1266 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1275 static struct var *vartab[VTABSIZE];
1278 * The following macros access the values of the above variables.
1279 * They have to skip over the name. They return the null string
1280 * for unset variables.
1283 #define ifsval() (vifs.text + 4)
1284 #define ifsset() ((vifs.flags & VUNSET) == 0)
1285 #define mailval() (vmail.text + 5)
1286 #define mpathval() (vmpath.text + 9)
1287 #define pathval() (vpath.text + 5)
1288 #define ps1val() (vps1.text + 4)
1289 #define ps2val() (vps2.text + 4)
1290 #define optindval() (voptind.text + 7)
1292 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1294 static void initvar (void);
1295 static void setvar (const char *, const char *, int);
1296 static void setvareq (char *, int);
1297 static void listsetvar (struct strlist *);
1298 static const char *lookupvar (const char *);
1299 static const char *bltinlookup (const char *);
1300 static char **environment (void);
1301 static int showvarscmd (int, char **);
1302 static void mklocal (char *);
1303 static void poplocalvars (void);
1304 static int unsetvar (const char *);
1305 static int varequal (const char *, const char *);
1308 static char *arg0; /* value of $0 */
1309 static struct shparam shellparam; /* current positional parameters */
1310 static char **argptr; /* argument list for builtin commands */
1311 static char *optionarg; /* set by nextopt (like getopt) */
1312 static char *optptr; /* used by nextopt */
1313 static char *minusc; /* argument to -c option */
1318 #define ALIASINUSE 1
1330 static struct alias *atab[ATABSIZE];
1332 static void setalias (char *, char *);
1333 static struct alias **hashalias (const char *);
1334 static struct alias *freealias (struct alias *);
1335 static struct alias **__lookupalias (const char *);
1341 struct alias *ap, **app;
1343 app = __lookupalias(name);
1347 if (!(ap->flag & ALIASINUSE)) {
1350 ap->val = savestr(val);
1351 ap->flag &= ~ALIASDEAD;
1354 ap = ckmalloc(sizeof (struct alias));
1355 ap->name = savestr(name);
1356 ap->val = savestr(val);
1369 app = __lookupalias(name);
1373 *app = freealias(*app);
1384 struct alias *ap, **app;
1388 for (i = 0; i < ATABSIZE; i++) {
1390 for (ap = *app; ap; ap = *app) {
1391 *app = freealias(*app);
1400 static struct alias *
1401 lookupalias(const char *name, int check)
1403 struct alias *ap = *__lookupalias(name);
1405 if (check && ap && (ap->flag & ALIASINUSE))
1411 printalias(const struct alias *ap) {
1414 p = single_quote(ap->val);
1415 printf("alias %s=%s\n", ap->name, p);
1421 * TODO - sort output
1424 aliascmd(int argc, char **argv)
1433 for (i = 0; i < ATABSIZE; i++)
1434 for (ap = atab[i]; ap; ap = ap->next) {
1439 while ((n = *++argv) != NULL) {
1440 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1441 if ((ap = *__lookupalias(n)) == NULL) {
1442 out2fmt("%s: %s not found\n", "alias", n);
1457 unaliascmd(int argc, char **argv)
1461 while ((i = nextopt("a")) != '\0') {
1467 for (i = 0; *argptr; argptr++) {
1468 if (unalias(*argptr)) {
1469 out2fmt("%s: %s not found\n", "unalias", *argptr);
1477 static struct alias **
1481 unsigned int hashval;
1486 return &atab[hashval % ATABSIZE];
1489 static struct alias *
1490 freealias(struct alias *ap) {
1493 if (ap->flag & ALIASINUSE) {
1494 ap->flag |= ALIASDEAD;
1506 static struct alias **
1507 __lookupalias(const char *name) {
1508 struct alias **app = hashalias(name);
1510 for (; *app; app = &(*app)->next) {
1511 if (equal(name, (*app)->name)) {
1520 #ifdef ASH_MATH_SUPPORT
1521 /* The generated file arith.c has been replaced with a custom hand
1522 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1523 * This is now part of libbb, so that it can be used by all the shells
1525 #define ARITH_NUM 257
1526 #define ARITH_LPAREN 258
1527 #define ARITH_RPAREN 259
1528 #define ARITH_OR 260
1529 #define ARITH_AND 261
1530 #define ARITH_BOR 262
1531 #define ARITH_BXOR 263
1532 #define ARITH_BAND 264
1533 #define ARITH_EQ 265
1534 #define ARITH_NE 266
1535 #define ARITH_LT 267
1536 #define ARITH_GT 268
1537 #define ARITH_GE 269
1538 #define ARITH_LE 270
1539 #define ARITH_LSHIFT 271
1540 #define ARITH_RSHIFT 272
1541 #define ARITH_ADD 273
1542 #define ARITH_SUB 274
1543 #define ARITH_MUL 275
1544 #define ARITH_DIV 276
1545 #define ARITH_REM 277
1546 #define ARITH_UNARYMINUS 278
1547 #define ARITH_UNARYPLUS 279
1548 #define ARITH_NOT 280
1549 #define ARITH_BNOT 281
1551 static void expari (int);
1554 static char *trap[NSIG]; /* trap handler commands */
1555 static char sigmode[NSIG - 1]; /* current value of signal */
1556 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1557 static int pendingsigs; /* indicates some signal received */
1560 * This file was generated by the mkbuiltins program.
1564 static int bgcmd (int, char **);
1565 static int fgcmd (int, char **);
1566 static int killcmd (int, char **);
1568 static int bltincmd (int, char **);
1569 static int cdcmd (int, char **);
1570 static int breakcmd (int, char **);
1572 static int commandcmd (int, char **);
1574 static int dotcmd (int, char **);
1575 static int evalcmd (int, char **);
1576 static int execcmd (int, char **);
1577 static int exitcmd (int, char **);
1578 static int exportcmd (int, char **);
1579 static int histcmd (int, char **);
1580 static int hashcmd (int, char **);
1581 static int helpcmd (int, char **);
1582 static int jobscmd (int, char **);
1583 static int localcmd (int, char **);
1585 static int pwdcmd (int, char **);
1587 static int readcmd (int, char **);
1588 static int returncmd (int, char **);
1589 static int setcmd (int, char **);
1590 static int setvarcmd (int, char **);
1591 static int shiftcmd (int, char **);
1592 static int trapcmd (int, char **);
1593 static int umaskcmd (int, char **);
1595 static int aliascmd (int, char **);
1596 static int unaliascmd (int, char **);
1598 static int unsetcmd (int, char **);
1599 static int waitcmd (int, char **);
1600 static int ulimitcmd (int, char **);
1601 static int timescmd (int, char **);
1602 #ifdef ASH_MATH_SUPPORT
1603 static int letcmd (int, char **);
1605 static int typecmd (int, char **);
1607 static int getoptscmd (int, char **);
1610 #ifndef BB_TRUE_FALSE
1611 static int true_main (int, char **);
1612 static int false_main (int, char **);
1615 static void setpwd (const char *, int);
1618 #define BUILTIN_NOSPEC "0"
1619 #define BUILTIN_SPECIAL "1"
1620 #define BUILTIN_REGULAR "2"
1621 #define BUILTIN_ASSIGN "4"
1622 #define BUILTIN_SPEC_ASSG "5"
1623 #define BUILTIN_REG_ASSG "6"
1625 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1626 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1627 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1631 int (*const builtinfunc) (int, char **);
1636 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1637 * the binary search in find_builtin() will stop working. If you value
1638 * your kneecaps, you'll be sure to *make sure* that any changes made
1639 * to this array result in the listing remaining in ascii order. You
1642 static const struct builtincmd builtincmds[] = {
1643 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1644 { BUILTIN_SPECIAL ":", true_main },
1646 { BUILTIN_REG_ASSG "alias", aliascmd },
1649 { BUILTIN_REGULAR "bg", bgcmd },
1651 { BUILTIN_SPECIAL "break", breakcmd },
1652 { BUILTIN_SPECIAL "builtin", bltincmd },
1653 { BUILTIN_REGULAR "cd", cdcmd },
1654 { BUILTIN_NOSPEC "chdir", cdcmd },
1656 { BUILTIN_REGULAR "command", commandcmd },
1658 { BUILTIN_SPECIAL "continue", breakcmd },
1659 { BUILTIN_SPECIAL "eval", evalcmd },
1660 { BUILTIN_SPECIAL "exec", execcmd },
1661 { BUILTIN_SPECIAL "exit", exitcmd },
1662 { BUILTIN_SPEC_ASSG "export", exportcmd },
1663 { BUILTIN_REGULAR "false", false_main },
1664 { BUILTIN_REGULAR "fc", histcmd },
1666 { BUILTIN_REGULAR "fg", fgcmd },
1669 { BUILTIN_REGULAR "getopts", getoptscmd },
1671 { BUILTIN_NOSPEC "hash", hashcmd },
1672 { BUILTIN_NOSPEC "help", helpcmd },
1673 { BUILTIN_REGULAR "jobs", jobscmd },
1675 { BUILTIN_REGULAR "kill", killcmd },
1677 #ifdef ASH_MATH_SUPPORT
1678 { BUILTIN_REGULAR "let", letcmd },
1680 { BUILTIN_ASSIGN "local", localcmd },
1682 { BUILTIN_NOSPEC "pwd", pwdcmd },
1684 { BUILTIN_REGULAR "read", readcmd },
1685 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1686 { BUILTIN_SPECIAL "return", returncmd },
1687 { BUILTIN_SPECIAL "set", setcmd },
1688 { BUILTIN_NOSPEC "setvar", setvarcmd },
1689 { BUILTIN_SPECIAL "shift", shiftcmd },
1690 { BUILTIN_SPECIAL "times", timescmd },
1691 { BUILTIN_SPECIAL "trap", trapcmd },
1692 { BUILTIN_REGULAR "true", true_main },
1693 { BUILTIN_NOSPEC "type", typecmd },
1694 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1695 { BUILTIN_REGULAR "umask", umaskcmd },
1697 { BUILTIN_REGULAR "unalias", unaliascmd },
1699 { BUILTIN_SPECIAL "unset", unsetcmd },
1700 { BUILTIN_REGULAR "wait", waitcmd },
1702 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1704 #define DOTCMD &builtincmds[0]
1705 static struct builtincmd *BLTINCMD;
1706 static struct builtincmd *EXECCMD;
1707 static struct builtincmd *EVALCMD;
1710 #define JOBSTOPPED 1 /* all procs are stopped */
1711 #define JOBDONE 2 /* all procs are completed */
1714 * A job structure contains information about a job. A job is either a
1715 * single process or a set of processes contained in a pipeline. In the
1716 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1721 pid_t pid; /* process id */
1722 int status; /* status flags (defined above) */
1723 char *cmd; /* text of command being run */
1727 static int job_warning; /* user was warned about stopped jobs */
1730 static void setjobctl(int enable);
1732 #define setjobctl(on) /* do nothing */
1737 struct procstat ps0; /* status of process */
1738 struct procstat *ps; /* status or processes when more than one */
1739 short nprocs; /* number of processes */
1740 short pgrp; /* process group of this job */
1741 char state; /* true if job is finished */
1742 char used; /* true if this entry is in used */
1743 char changed; /* true if status has changed */
1745 char jobctl; /* job running under job control */
1749 static struct job *jobtab; /* array of jobs */
1750 static int njobs; /* size of array */
1751 static int backgndpid = -1; /* pid of last background process */
1753 static int initialpgrp; /* pgrp of shell on invocation */
1754 static int curjob; /* current job */
1757 static int intreceived;
1759 static struct job *makejob (const union node *, int);
1760 static int forkshell (struct job *, const union node *, int);
1761 static int waitforjob (struct job *);
1763 static int docd (char *, int);
1764 static char *getcomponent (void);
1765 static void updatepwd (const char *);
1766 static void getpwd (void);
1768 static char *padvance (const char **, const char *);
1770 static char nullstr[1]; /* zero length string */
1771 static char *curdir = nullstr; /* current working directory */
1772 static char *cdcomppath;
1786 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1787 error("HOME not set");
1790 if (dest[0] == '-' && dest[1] == '\0') {
1791 dest = bltinlookup("OLDPWD");
1792 if (!dest || !*dest) {
1801 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1803 while ((p = padvance(&path, dest)) != NULL) {
1804 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1809 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1811 print = strcmp(p, dest);
1813 if (docd(p, print) >= 0)
1818 error("can't cd to %s", dest);
1824 * Actually do the chdir. In an interactive shell, print the
1825 * directory name if "print" is nonzero.
1840 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1843 * Check each component of the path. If we find a symlink or
1844 * something we can't stat, clear curdir to force a getcwd()
1845 * next time we get the value of the current directory.
1848 cdcomppath = sstrdup(dest);
1855 while ((q = getcomponent()) != NULL) {
1856 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
1864 if (equal(component, ".."))
1867 if ((lstat(stackblock(), &statb) < 0)
1868 || (S_ISLNK(statb.st_mode))) {
1876 if (chdir(dest) < 0) {
1880 updatepwd(badstat ? NULL : dest);
1883 printf(snlfmt, curdir);
1889 * Get the next component of the path name pointed to by cdcomppath.
1890 * This routine overwrites the string pointed to by cdcomppath.
1898 if ((p = cdcomppath) == NULL)
1901 while (*p != '/' && *p != '\0')
1915 * Update curdir (the name of the current directory) in response to a
1916 * cd command. We also call hashcd to let the routines in exec.c know
1917 * that the current directory has changed.
1920 static void hashcd (void);
1923 updatepwd(const char *dir)
1929 hashcd(); /* update command hash table */
1932 * If our argument is NULL, we don't know the current directory
1933 * any more because we traversed a symbolic link or something
1934 * we couldn't stat().
1936 if (dir == NULL || curdir == nullstr) {
1941 cdcomppath = sstrdup(dir);
1950 while ((p = getcomponent()) != NULL) {
1951 if (equal(p, "..")) {
1952 while (new > stackblock() && (STUNPUTC(new), *new) != '/');
1953 } else if (*p != '\0' && ! equal(p, ".")) {
1959 if (new == stackblock())
1962 setpwd(stackblock(), 1);
1972 printf(snlfmt, curdir);
1978 * Find out what the current directory is. If we already know the current
1979 * directory, this routine returns immediately.
1984 curdir = xgetcwd(0);
1990 setpwd(const char *val, int setold)
1993 setvar("OLDPWD", curdir, VEXPORT);
1996 if (curdir != nullstr) {
2003 curdir = savestr(val);
2006 setvar("PWD", curdir, VEXPORT);
2010 * Errors and exceptions.
2014 * Code to handle exceptions in C.
2018 * We enclose jmp_buf in a structure so that we can declare pointers to
2019 * jump locations. The global variable handler contains the location to
2020 * jump to when an exception occurs, and the global variable exception
2021 * contains a code identifying the exeception. To implement nested
2022 * exception handlers, the user should save the value of handler on entry
2023 * to an inner scope, set handler to point to a jmploc structure for the
2024 * inner scope, and restore handler on exit from the scope.
2032 #define EXINT 0 /* SIGINT received */
2033 #define EXERROR 1 /* a generic error */
2034 #define EXSHELLPROC 2 /* execute a shell procedure */
2035 #define EXEXEC 3 /* command execution failed */
2037 static struct jmploc *handler;
2038 static int exception;
2040 static void exverror (int, const char *, va_list)
2041 __attribute__((__noreturn__));
2044 * Called to raise an exception. Since C doesn't include exceptions, we
2045 * just do a longjmp to the exception handler. The type of exception is
2046 * stored in the global variable "exception".
2049 static void exraise (int) __attribute__((__noreturn__));
2055 if (handler == NULL)
2060 longjmp(handler->loc, 1);
2065 * Called from trap.c when a SIGINT is received. (If the user specifies
2066 * that SIGINT is to be trapped or ignored using the trap builtin, then
2067 * this routine is not called.) Suppressint is nonzero when interrupts
2068 * are held using the INTOFF macro. The call to _exit is necessary because
2069 * there is a short period after a fork before the signal handlers are
2070 * set to the appropriate value for the child. (The test for iflag is
2071 * just defensive programming.)
2083 sigemptyset(&mysigset);
2084 sigprocmask(SIG_SETMASK, &mysigset, NULL);
2085 if (rootshell && iflag)
2088 signal(SIGINT, SIG_DFL);
2095 static char *commandname; /* currently executing command */
2098 * Exverror is called to raise the error exception. If the first argument
2099 * is not NULL then error prints an error message using printf style
2100 * formatting. It then raises the error exception.
2103 exverror(int cond, const char *msg, va_list ap)
2110 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
2112 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
2116 out2fmt("%s: ", commandname);
2117 vfprintf(stderr, msg, ap);
2126 error(const char *msg, ...)
2130 exverror(EXERROR, msg, ap);
2137 exerror(int cond, const char *msg, ...)
2141 exverror(cond, msg, ap);
2149 * Table of error messages.
2153 short errcode; /* error number */
2154 char action; /* operation which encountered the error */
2158 * Types of operations (passed to the errmsg routine).
2161 #define E_OPEN 01 /* opening a file */
2162 #define E_CREAT 02 /* creating a file */
2163 #define E_EXEC 04 /* executing a program */
2165 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2167 static const struct errname errormsg[] = {
2172 { ENOENT, E_CREAT },
2174 { ENOTDIR, E_OPEN },
2175 { ENOTDIR, E_CREAT },
2176 { ENOTDIR, E_EXEC },
2178 { EEXIST, E_CREAT },
2217 { ELIBACC, E_EXEC },
2221 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2224 * Return a string describing an error. The returned string may be a
2225 * pointer to a static buffer that will be overwritten on the next call.
2226 * Action describes the operation that got the error.
2230 errmsg(int e, int action)
2232 struct errname const *ep;
2233 static char buf[12];
2235 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2236 if (ep->errcode == e && (ep->action & action) != 0)
2240 snprintf(buf, sizeof buf, "error %d", e);
2245 #ifdef ASH_OPTIMIZE_FOR_SIZE
2248 if (--suppressint == 0 && intpending) {
2252 static void forceinton (void) {
2259 /* flags in argument to evaltree */
2260 #define EV_EXIT 01 /* exit after evaluating tree */
2261 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2262 #define EV_BACKCMD 04 /* command executing within back quotes */
2264 static int evalskip; /* set if we are skipping commands */
2265 static int skipcount; /* number of levels to skip */
2266 static int loopnest; /* current loop nesting level */
2267 static int funcnest; /* depth of function calls */
2270 static struct strlist *cmdenviron; /* environment for builtin command */
2271 static int exitstatus; /* exit status of last command */
2272 static int oexitstatus; /* saved exit status */
2274 static void evalsubshell (const union node *, int);
2275 static void expredir (union node *);
2276 static void prehash (union node *);
2277 static void eprintlist (struct strlist *);
2279 static union node *parsecmd(int);
2281 * Called to reset things after an exception.
2285 * The eval commmand.
2287 static void evalstring (char *, int);
2301 STARTSTACKSTR(concat);
2305 STPUTC(*p++, concat);
2306 if ((p = *ap++) == NULL)
2308 STPUTC(' ', concat);
2310 STPUTC('\0', concat);
2311 p = grabstackstr(concat);
2313 evalstring(p, EV_TESTED);
2319 * Execute a command or commands contained in a string.
2322 static void evaltree (union node *, int);
2323 static void setinputstring (char *);
2324 static void popfile (void);
2325 static void setstackmark(struct stackmark *mark);
2326 static void popstackmark(struct stackmark *mark);
2330 evalstring(char *s, int flag)
2333 struct stackmark smark;
2335 setstackmark(&smark);
2337 while ((n = parsecmd(0)) != NEOF) {
2339 popstackmark(&smark);
2342 popstackmark(&smark);
2345 static struct builtincmd *find_builtin (const char *);
2346 static void expandarg (union node *, struct arglist *, int);
2347 static void calcsize (const union node *);
2348 static union node *copynode (const union node *);
2351 * Make a copy of a parse tree.
2354 static int funcblocksize; /* size of structures in function */
2355 static int funcstringsize; /* size of strings in node */
2356 static pointer funcblock; /* block to allocate function from */
2357 static char *funcstring; /* block to allocate strings from */
2360 static inline union node *
2361 copyfunc(union node *n)
2368 funcblock = ckmalloc(funcblocksize + funcstringsize);
2369 funcstring = (char *) funcblock + funcblocksize;
2374 * Free a parse tree.
2378 freefunc(union node *n)
2386 * Add a new command entry, replacing any existing command entry for
2391 addcmdentry(char *name, struct cmdentry *entry)
2393 struct tblentry *cmdp;
2396 cmdp = cmdlookup(name, 1);
2397 if (cmdp->cmdtype == CMDFUNCTION) {
2398 freefunc(cmdp->param.func);
2400 cmdp->cmdtype = entry->cmdtype;
2401 cmdp->param = entry->u;
2406 evalloop(const union node *n, int flags)
2413 evaltree(n->nbinary.ch1, EV_TESTED);
2415 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2419 if (evalskip == SKIPBREAK && --skipcount <= 0)
2423 if (n->type == NWHILE) {
2424 if (exitstatus != 0)
2427 if (exitstatus == 0)
2430 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2431 status = exitstatus;
2436 exitstatus = status;
2440 evalfor(const union node *n, int flags)
2442 struct arglist arglist;
2445 struct stackmark smark;
2447 setstackmark(&smark);
2448 arglist.lastp = &arglist.list;
2449 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2450 oexitstatus = exitstatus;
2451 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2455 *arglist.lastp = NULL;
2459 for (sp = arglist.list ; sp ; sp = sp->next) {
2460 setvar(n->nfor.var, sp->text, 0);
2461 evaltree(n->nfor.body, flags & EV_TESTED);
2463 if (evalskip == SKIPCONT && --skipcount <= 0) {
2467 if (evalskip == SKIPBREAK && --skipcount <= 0)
2474 popstackmark(&smark);
2478 evalcase(const union node *n, int flags)
2482 struct arglist arglist;
2483 struct stackmark smark;
2485 setstackmark(&smark);
2486 arglist.lastp = &arglist.list;
2487 oexitstatus = exitstatus;
2488 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2489 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2490 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2491 if (casematch(patp, arglist.list->text)) {
2492 if (evalskip == 0) {
2493 evaltree(cp->nclist.body, flags);
2500 popstackmark(&smark);
2504 * Evaluate a pipeline. All the processes in the pipeline are children
2505 * of the process creating the pipeline. (This differs from some versions
2506 * of the shell, which make the last process in a pipeline the parent
2515 struct nodelist *lp;
2520 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2522 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2525 jp = makejob(n, pipelen);
2527 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2531 if (pipe(pip) < 0) {
2533 error("Pipe call failed");
2536 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2540 dup_as_newfd(prevfd, 0);
2552 dup_as_newfd(pip[1], 1);
2556 evaltree(lp->n, EV_EXIT);
2564 if (n->npipe.backgnd == 0) {
2566 exitstatus = waitforjob(jp);
2567 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2572 static void find_command (const char *, struct cmdentry *, int, const char *);
2575 isassignment(const char *word) {
2576 if (!is_name(*word)) {
2581 } while (is_in_name(*word));
2582 return *word == '=';
2587 evalcommand(union node *cmd, int flags)
2589 struct stackmark smark;
2591 struct arglist arglist;
2592 struct arglist varlist;
2598 struct cmdentry cmdentry;
2600 char *volatile savecmdname;
2601 volatile struct shparam saveparam;
2602 struct localvar *volatile savelocalvars;
2606 const struct builtincmd *firstbltin;
2607 struct jmploc *volatile savehandler;
2608 struct jmploc jmploc;
2610 /* Avoid longjmp clobbering */
2617 /* First expand the arguments. */
2618 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2619 setstackmark(&smark);
2620 arglist.lastp = &arglist.list;
2621 varlist.lastp = &varlist.list;
2623 oexitstatus = exitstatus;
2626 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2627 expandarg(argp, &varlist, EXP_VARTILDE);
2630 argp = cmd->ncmd.args; argp && !arglist.list;
2631 argp = argp->narg.next
2633 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2636 struct builtincmd *bcmd;
2638 bcmd = find_builtin(arglist.list->text);
2639 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2640 for (; argp; argp = argp->narg.next) {
2641 if (pseudovarflag && isassignment(argp->narg.text)) {
2642 expandarg(argp, &arglist, EXP_VARTILDE);
2645 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2648 *arglist.lastp = NULL;
2649 *varlist.lastp = NULL;
2650 expredir(cmd->ncmd.redirect);
2652 for (sp = arglist.list ; sp ; sp = sp->next)
2654 argv = stalloc(sizeof (char *) * (argc + 1));
2656 for (sp = arglist.list ; sp ; sp = sp->next) {
2657 TRACE(("evalcommand arg: %s\n", sp->text));
2662 if (iflag && funcnest == 0 && argc > 0)
2666 /* Print the command if xflag is set. */
2669 eprintlist(varlist.list);
2670 eprintlist(arglist.list);
2674 /* Now locate the command. */
2676 cmdentry.cmdtype = CMDBUILTIN;
2677 firstbltin = cmdentry.u.cmd = BLTINCMD;
2679 const char *oldpath;
2680 int findflag = DO_ERR;
2684 * Modify the command lookup path, if a PATH= assignment
2687 for (sp = varlist.list ; sp ; sp = sp->next)
2688 if (varequal(sp->text, defpathvar)) {
2689 path = sp->text + 5;
2690 findflag |= DO_BRUTE;
2693 oldfindflag = findflag;
2696 find_command(argv[0], &cmdentry, findflag, path);
2697 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2701 /* implement bltin and command here */
2702 if (cmdentry.cmdtype != CMDBUILTIN) {
2706 firstbltin = cmdentry.u.cmd;
2708 if (cmdentry.u.cmd == BLTINCMD) {
2710 struct builtincmd *bcmd;
2715 if (!(bcmd = find_builtin(*argv))) {
2716 out2fmt("%s: not found\n", *argv);
2720 cmdentry.u.cmd = bcmd;
2721 if (bcmd != BLTINCMD)
2725 if (cmdentry.u.cmd == find_builtin("command")) {
2730 if (*argv[0] == '-') {
2731 if (!equal(argv[0], "-p")) {
2741 findflag |= DO_BRUTE;
2744 findflag = oldfindflag;
2746 findflag |= DO_NOFUN;
2754 /* Fork off a child process if necessary. */
2755 if (cmd->ncmd.backgnd
2756 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2758 jp = makejob(cmd, 1);
2759 mode = cmd->ncmd.backgnd;
2760 if (forkshell(jp, cmd, mode) != 0)
2761 goto parent; /* at end of routine */
2765 /* This is the child process if a fork occurred. */
2766 /* Execute the command. */
2767 if (cmdentry.cmdtype == CMDFUNCTION) {
2769 trputs("Shell function: "); trargs(argv);
2771 exitstatus = oexitstatus;
2772 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2773 saveparam = shellparam;
2774 shellparam.malloc = 0;
2775 shellparam.nparam = argc - 1;
2776 shellparam.p = argv + 1;
2778 savelocalvars = localvars;
2781 if (setjmp(jmploc.loc)) {
2782 if (exception == EXSHELLPROC) {
2783 freeparam((volatile struct shparam *)
2786 saveparam.optind = shellparam.optind;
2787 saveparam.optoff = shellparam.optoff;
2788 freeparam(&shellparam);
2789 shellparam = saveparam;
2792 localvars = savelocalvars;
2793 handler = savehandler;
2794 longjmp(handler->loc, 1);
2796 savehandler = handler;
2798 for (sp = varlist.list ; sp ; sp = sp->next)
2801 evaltree(cmdentry.u.func, flags & EV_TESTED);
2805 localvars = savelocalvars;
2806 saveparam.optind = shellparam.optind;
2807 saveparam.optoff = shellparam.optoff;
2808 freeparam(&shellparam);
2809 shellparam = saveparam;
2810 handler = savehandler;
2813 if (evalskip == SKIPFUNC) {
2817 if (flags & EV_EXIT)
2818 exitshell(exitstatus);
2819 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2821 trputs("builtin command: "); trargs(argv);
2823 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2824 redirect(cmd->ncmd.redirect, mode);
2825 savecmdname = commandname;
2826 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2827 listsetvar(varlist.list);
2829 cmdenviron = varlist.list;
2832 if (setjmp(jmploc.loc)) {
2834 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2837 savehandler = handler;
2839 commandname = argv[0];
2841 optptr = NULL; /* initialize nextopt */
2842 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2846 if (e != EXSHELLPROC) {
2847 commandname = savecmdname;
2848 if (flags & EV_EXIT)
2849 exitshell(exitstatus);
2851 handler = savehandler;
2853 if ((e != EXERROR && e != EXEXEC)
2854 || cmdentry.u.cmd == BLTINCMD
2855 || cmdentry.u.cmd == DOTCMD
2856 || cmdentry.u.cmd == EVALCMD
2857 || cmdentry.u.cmd == EXECCMD)
2861 if (cmdentry.u.cmd != EXECCMD)
2865 trputs("normal command: "); trargs(argv);
2867 redirect(cmd->ncmd.redirect, 0);
2869 for (sp = varlist.list ; sp ; sp = sp->next)
2870 setvareq(sp->text, VEXPORT|VSTACK);
2871 envp = environment();
2872 shellexec(argv, envp, path, cmdentry.u.index);
2876 parent: /* parent process gets here (if we forked) */
2877 if (mode == 0) { /* argument to fork */
2879 exitstatus = waitforjob(jp);
2885 setvar("_", lastarg, 0);
2886 popstackmark(&smark);
2890 * Evaluate a parse tree. The value is left in the global variable
2900 TRACE(("evaltree(NULL) called\n"));
2903 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2906 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2909 evaltree(n->nbinary.ch2, flags);
2912 evaltree(n->nbinary.ch1, EV_TESTED);
2913 if (evalskip || exitstatus != 0)
2915 evaltree(n->nbinary.ch2, flags);
2918 evaltree(n->nbinary.ch1, EV_TESTED);
2919 if (evalskip || exitstatus == 0)
2921 evaltree(n->nbinary.ch2, flags);
2924 expredir(n->nredir.redirect);
2925 redirect(n->nredir.redirect, REDIR_PUSH);
2926 evaltree(n->nredir.n, flags);
2930 evalsubshell(n, flags);
2933 evalsubshell(n, flags);
2936 evaltree(n->nif.test, EV_TESTED);
2939 if (exitstatus == 0)
2940 evaltree(n->nif.ifpart, flags);
2941 else if (n->nif.elsepart)
2942 evaltree(n->nif.elsepart, flags);
2958 struct builtincmd *bcmd;
2959 struct cmdentry entry;
2961 (bcmd = find_builtin(n->narg.text)) &&
2962 IS_BUILTIN_SPECIAL(bcmd)
2964 out2fmt("%s is a special built-in\n", n->narg.text);
2968 entry.cmdtype = CMDFUNCTION;
2969 entry.u.func = copyfunc(n->narg.next);
2970 addcmdentry(n->narg.text, &entry);
2975 evaltree(n->nnot.com, EV_TESTED);
2976 exitstatus = !exitstatus;
2984 evalcommand(n, flags);
2989 printf("Node type = %d\n", n->type);
2998 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
3000 exitshell(exitstatus);
3004 * Kick off a subshell to evaluate a tree.
3008 evalsubshell(const union node *n, int flags)
3011 int backgnd = (n->type == NBACKGND);
3013 expredir(n->nredir.redirect);
3015 if (forkshell(jp, n, backgnd) == 0) {
3017 flags &=~ EV_TESTED;
3018 redirect(n->nredir.redirect, 0);
3019 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
3023 exitstatus = waitforjob(jp);
3029 * Compute the names of the files in a redirection list.
3032 static void fixredir(union node *n, const char *text, int err);
3035 expredir(union node *n)
3039 for (redir = n ; redir ; redir = redir->nfile.next) {
3041 fn.lastp = &fn.list;
3042 oexitstatus = exitstatus;
3043 switch (redir->type) {
3049 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
3050 redir->nfile.expfname = fn.list->text;
3054 if (redir->ndup.vname) {
3055 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
3056 fixredir(redir, fn.list->text, 1);
3065 * Execute a command inside back quotes. If it's a builtin command, we
3066 * want to save its output in a block obtained from malloc. Otherwise
3067 * we fork off a subprocess and get the output of the command via a pipe.
3068 * Should be called with interrupts off.
3072 evalbackcmd(union node *n, struct backcmd *result)
3076 struct stackmark smark; /* unnecessary */
3078 setstackmark(&smark);
3089 error("Pipe call failed");
3091 if (forkshell(jp, n, FORK_NOJOB) == 0) {
3096 dup_as_newfd(pip[1], 1);
3100 evaltree(n, EV_EXIT);
3103 result->fd = pip[0];
3106 popstackmark(&smark);
3107 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
3108 result->fd, result->buf, result->nleft, result->jp));
3113 * Execute a simple command.
3117 * Search for a command. This is called before we fork so that the
3118 * location of the command will be available in the parent as well as
3119 * the child. The check for "goodname" is an overly conservative
3120 * check that the name will not be subject to expansion.
3127 struct cmdentry entry;
3129 if (n->type == NCMD && n->ncmd.args)
3130 if (goodname(n->ncmd.args->narg.text))
3131 find_command(n->ncmd.args->narg.text, &entry, 0,
3137 * Builtin commands. Builtin commands whose functions are closely
3138 * tied to evaluation are implemented here.
3142 * No command given, or a bltin command with no arguments. Set the
3143 * specified variables.
3147 bltincmd(argc, argv)
3152 * Preserve exitstatus of a previous possible redirection
3160 * Handle break and continue commands. Break, continue, and return are
3161 * all handled by setting the evalskip flag. The evaluation routines
3162 * above all check this flag, and if it is set they start skipping
3163 * commands rather than executing them. The variable skipcount is
3164 * the number of loops to break/continue, or the number of function
3165 * levels to return. (The latter is always 1.) It should probably
3166 * be an error to break out of more loops than exist, but it isn't
3167 * in the standard shell so we don't make it one here.
3171 breakcmd(argc, argv)
3175 int n = argc > 1 ? number(argv[1]) : 1;
3180 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3188 * The return command.
3192 returncmd(argc, argv)
3196 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3199 evalskip = SKIPFUNC;
3204 /* Do what ksh does; skip the rest of the file */
3205 evalskip = SKIPFILE;
3212 #ifndef BB_TRUE_FALSE
3214 false_main(argc, argv)
3223 true_main(argc, argv)
3232 * Controls whether the shell is interactive or not.
3235 static void setsignal(int signo);
3236 static void chkmail(int silent);
3240 setinteractive(int on)
3242 static int is_interactive;
3243 static int do_banner=0;
3245 if (on == is_interactive)
3251 is_interactive = on;
3252 if (do_banner==0 && is_interactive) {
3253 /* Looks like they want an interactive shell */
3254 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3255 printf( "Enter 'help' for a list of built-in commands.\n\n");
3263 setinteractive(iflag);
3276 iflag = 0; /* exit on error */
3279 for (sp = cmdenviron; sp ; sp = sp->next)
3280 setvareq(sp->text, VEXPORT|VSTACK);
3281 shellexec(argv + 1, environment(), pathval(), 0);
3287 eprintlist(struct strlist *sp)
3289 for (; sp; sp = sp->next) {
3290 out2fmt(" %s",sp->text);
3295 * Exec a program. Never returns. If you change this routine, you may
3296 * have to change the find_command routine as well.
3299 static const char *pathopt; /* set by padvance */
3302 shellexec(argv, envp, path, idx)
3303 char **argv, **envp;
3310 if (strchr(argv[0], '/') != NULL) {
3311 tryexec(argv[0], argv, envp);
3315 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3316 if (--idx < 0 && pathopt == NULL) {
3317 tryexec(cmdname, argv, envp);
3318 if (errno != ENOENT && errno != ENOTDIR)
3325 /* Map to POSIX errors */
3337 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3342 * Clear traps on a fork.
3348 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3349 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3354 setsignal(tp - trap);
3362 initshellproc(void) {
3388 /* from options.c: */
3392 for (i = 0; i < NOPTS; i++)
3408 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3420 static int preadbuffer(void);
3421 static void pushfile (void);
3424 * Read a character from the script, returning PEOF on end of file.
3425 * Nul characters in the input are silently discarded.
3428 #ifndef ASH_OPTIMIZE_FOR_SIZE
3429 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3433 return pgetc_macro();
3439 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3445 return pgetc_macro();
3451 * Undo the last call to pgetc. Only one character may be pushed back.
3452 * PEOF may be pushed back.
3464 struct parsefile *pf = parsefile;
3473 parsefile = pf->prev;
3475 parsenleft = parsefile->nleft;
3476 parselleft = parsefile->lleft;
3477 parsenextc = parsefile->nextc;
3478 plinno = parsefile->linno;
3484 * Return to top level.
3489 while (parsefile != &basepf)
3494 * Close the file(s) that the shell is reading commands from. Called
3495 * after a fork is done.
3501 if (parsefile->fd > 0) {
3502 close(parsefile->fd);
3509 * Like setinputfile, but takes an open file descriptor. Call this with
3514 setinputfd(fd, push)
3517 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3523 while (parsefile->strpush)
3527 if (parsefile->buf == NULL)
3528 parsefile->buf = ckmalloc(BUFSIZ);
3529 parselleft = parsenleft = 0;
3535 * Set the input to take input from a file. If push is set, push the
3536 * old input onto the stack first.
3540 setinputfile(const char *fname, int push)
3546 if ((fd = open(fname, O_RDONLY)) < 0)
3547 error("Can't open %s", fname);
3549 myfileno2 = dup_as_newfd(fd, 10);
3552 error("Out of file descriptors");
3555 setinputfd(fd, push);
3561 tryexec(char *cmd, char **argv, char **envp)
3565 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
3569 #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
3570 name = get_last_path_component(name);
3573 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3576 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3578 run_applet_by_name(name, argc_l, argv);
3580 execve(cmd, argv, envp);
3585 setinputfile(cmd, 0);
3586 commandname = arg0 = savestr(argv[0]);
3588 exraise(EXSHELLPROC);
3593 static char *commandtext (const union node *);
3596 * Do a path search. The variable path (passed by reference) should be
3597 * set to the start of the path before the first call; padvance will update
3598 * this value as it proceeds. Successive calls to padvance will return
3599 * the possible path expansions in sequence. If an option (indicated by
3600 * a percent sign) appears in the path entry then the global variable
3601 * pathopt will be set to point to it; otherwise pathopt will be set to
3605 static const char *pathopt;
3607 static void growstackblock(void);
3611 padvance(const char **path, const char *name)
3621 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3622 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3623 while (stackblocksize() < len)
3627 memcpy(q, start, p - start);
3635 while (*p && *p != ':') p++;
3641 return stalloc(len);
3645 * Wrapper around strcmp for qsort/bsearch/...
3648 pstrcmp(const void *a, const void *b)
3650 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3654 * Find a keyword is in a sorted array.
3657 static const char *const *
3658 findkwd(const char *s)
3660 return bsearch(s, tokname_array + KWDOFFSET,
3661 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3662 sizeof(const char *), pstrcmp);
3666 /*** Command hashing code ***/
3674 struct tblentry **pp;
3675 struct tblentry *cmdp;
3678 struct cmdentry entry;
3681 const struct alias *ap;
3685 while ((c = nextopt("rvV")) != '\0') {
3689 } else if (c == 'v' || c == 'V') {
3693 if (*argptr == NULL) {
3694 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3695 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3696 if (cmdp->cmdtype != CMDBUILTIN) {
3697 printentry(cmdp, verbose);
3704 while ((name = *argptr++) != NULL) {
3705 if ((cmdp = cmdlookup(name, 0)) != NULL
3706 && (cmdp->cmdtype == CMDNORMAL
3707 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3710 /* Then look at the aliases */
3711 if ((ap = lookupalias(name, 0)) != NULL) {
3713 printf("%s is an alias for %s\n", name, ap->val);
3719 /* First look at the keywords */
3720 if (findkwd(name)!=0) {
3722 printf("%s is a shell keyword\n", name);
3724 printf(snlfmt, name);
3728 find_command(name, &entry, DO_ERR, pathval());
3729 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3731 cmdp = cmdlookup(name, 0);
3732 if (cmdp) printentry(cmdp, verbose=='v');
3740 printentry(cmdp, verbose)
3741 struct tblentry *cmdp;
3748 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3749 if (cmdp->cmdtype == CMDNORMAL) {
3750 idx = cmdp->param.index;
3753 name = padvance(&path, cmdp->cmdname);
3755 } while (--idx >= 0);
3758 } else if (cmdp->cmdtype == CMDBUILTIN) {
3760 out1str("a shell builtin");
3761 } else if (cmdp->cmdtype == CMDFUNCTION) {
3764 out1str("a function\n");
3765 name = commandtext(cmdp->param.func);
3766 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3772 error("internal error: cmdtype %d", cmdp->cmdtype);
3775 printf(snlfmt, cmdp->rehash ? "*" : nullstr);
3780 /*** List the available builtins ***/
3783 static int helpcmd(int argc, char** argv)
3787 printf("\nBuilt-in commands:\n-------------------\n");
3788 for (col=0, i=0; i < NUMBUILTINS; i++) {
3789 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3790 builtincmds[i].name+1);
3796 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
3798 extern const struct BB_applet applets[];
3799 extern const size_t NUM_APPLETS;
3801 for (i=0; i < NUM_APPLETS; i++) {
3803 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3813 return EXIT_SUCCESS;
3817 * Resolve a command name. If you change this routine, you may have to
3818 * change the shellexec routine as well.
3821 static int prefix (const char *, const char *);
3824 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3826 struct tblentry *cmdp;
3836 struct builtincmd *bcmd;
3838 /* If name contains a slash, don't use the hash table */
3839 if (strchr(name, '/') != NULL) {
3841 while (stat(name, &statb) < 0) {
3842 if (errno != ENOENT && errno != ENOTDIR)
3844 entry->cmdtype = CMDUNKNOWN;
3845 entry->u.index = -1;
3848 entry->cmdtype = CMDNORMAL;
3849 entry->u.index = -1;
3852 entry->cmdtype = CMDNORMAL;
3858 if (act & DO_BRUTE) {
3859 firstchange = path_change(path, &bltin);
3865 /* If name is in the table, and not invalidated by cd, we're done */
3866 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3867 if (cmdp->cmdtype == CMDFUNCTION) {
3868 if (act & DO_NOFUN) {
3873 } else if (act & DO_BRUTE) {
3874 if ((cmdp->cmdtype == CMDNORMAL &&
3875 cmdp->param.index >= firstchange) ||
3876 (cmdp->cmdtype == CMDBUILTIN &&
3877 ((builtinloc < 0 && bltin >= 0) ?
3878 bltin : builtinloc) >= firstchange)) {
3879 /* need to recompute the entry */
3888 bcmd = find_builtin(name);
3889 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3892 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3895 } else if (act & DO_BRUTE) {
3896 if (firstchange == 0) {
3901 /* If %builtin not in path, check for builtin next */
3902 if (regular || (bltin < 0 && bcmd)) {
3905 entry->cmdtype = CMDBUILTIN;
3906 entry->u.cmd = bcmd;
3910 cmdp = cmdlookup(name, 1);
3911 cmdp->cmdtype = CMDBUILTIN;
3912 cmdp->param.cmd = bcmd;
3917 /* We have to search path. */
3918 prev = -1; /* where to start */
3919 if (cmdp && cmdp->rehash) { /* doing a rehash */
3920 if (cmdp->cmdtype == CMDBUILTIN)
3923 prev = cmdp->param.index;
3929 while ((fullname = padvance(&path, name)) != NULL) {
3930 stunalloc(fullname);
3932 if (idx >= firstchange) {
3936 if (prefix("builtin", pathopt)) {
3937 if ((bcmd = find_builtin(name))) {
3941 } else if (!(act & DO_NOFUN) &&
3942 prefix("func", pathopt)) {
3945 continue; /* ignore unimplemented options */
3948 /* if rehash, don't redo absolute path names */
3949 if (fullname[0] == '/' && idx <= prev &&
3950 idx < firstchange) {
3953 TRACE(("searchexec \"%s\": no change\n", name));
3956 while (stat(fullname, &statb) < 0) {
3957 if (errno != ENOENT && errno != ENOTDIR)
3961 e = EACCES; /* if we fail, this will be the error */
3962 if (!S_ISREG(statb.st_mode))
3964 if (pathopt) { /* this is a %func directory */
3965 stalloc(strlen(fullname) + 1);
3966 readcmdfile(fullname);
3967 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3968 error("%s not defined in %s", name, fullname);
3969 stunalloc(fullname);
3972 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3973 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3974 be a function and we're being called with DO_NOFUN */
3976 entry->cmdtype = CMDNORMAL;
3977 entry->u.index = idx;
3981 cmdp = cmdlookup(name, 1);
3982 cmdp->cmdtype = CMDNORMAL;
3983 cmdp->param.index = idx;
3988 /* We failed. If there was an entry for this command, delete it */
3989 if (cmdp && updatetbl)
3992 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3993 entry->cmdtype = CMDUNKNOWN;
3998 entry->cmdtype = cmdp->cmdtype;
3999 entry->u = cmdp->param;
4005 * Search the table of builtin commands.
4009 bstrcmp(const void *name, const void *b)
4011 return strcmp((const char *)name, (*(const char *const *) b)+1);
4014 static struct builtincmd *
4015 find_builtin(const char *name)
4017 struct builtincmd *bp;
4019 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
4027 * Called when a cd is done. Marks all commands so the next time they
4028 * are executed they will be rehashed.
4033 struct tblentry **pp;
4034 struct tblentry *cmdp;
4036 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
4037 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4038 if (cmdp->cmdtype == CMDNORMAL
4039 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
4048 * Called before PATH is changed. The argument is the new value of PATH;
4049 * pathval() still returns the old value at this point. Called with
4054 changepath(const char *newval)
4059 firstchange = path_change(newval, &bltin);
4060 if (builtinloc < 0 && bltin >= 0)
4061 builtinloc = bltin; /* zap builtins */
4062 clearcmdentry(firstchange);
4068 * Clear out command entries. The argument specifies the first entry in
4069 * PATH which has changed.
4073 clearcmdentry(firstchange)
4076 struct tblentry **tblp;
4077 struct tblentry **pp;
4078 struct tblentry *cmdp;
4081 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4083 while ((cmdp = *pp) != NULL) {
4084 if ((cmdp->cmdtype == CMDNORMAL &&
4085 cmdp->param.index >= firstchange)
4086 || (cmdp->cmdtype == CMDBUILTIN &&
4087 builtinloc >= firstchange)) {
4100 * Delete all functions.
4105 struct tblentry **tblp;
4106 struct tblentry **pp;
4107 struct tblentry *cmdp;
4110 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4112 while ((cmdp = *pp) != NULL) {
4113 if (cmdp->cmdtype == CMDFUNCTION) {
4115 freefunc(cmdp->param.func);
4128 * Locate a command in the command hash table. If "add" is nonzero,
4129 * add the command to the table if it is not already present. The
4130 * variable "lastcmdentry" is set to point to the address of the link
4131 * pointing to the entry, so that delete_cmd_entry can delete the
4135 static struct tblentry **lastcmdentry;
4137 static struct tblentry *
4138 cmdlookup(const char *name, int add)
4142 struct tblentry *cmdp;
4143 struct tblentry **pp;
4150 pp = &cmdtable[hashval % CMDTABLESIZE];
4151 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4152 if (equal(cmdp->cmdname, name))
4156 if (add && cmdp == NULL) {
4158 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4159 + strlen(name) + 1);
4161 cmdp->cmdtype = CMDUNKNOWN;
4163 strcpy(cmdp->cmdname, name);
4171 * Delete the command entry returned on the last lookup.
4175 delete_cmd_entry() {
4176 struct tblentry *cmdp;
4179 cmdp = *lastcmdentry;
4180 *lastcmdentry = cmdp->next;
4189 static const unsigned char nodesize[26] = {
4190 ALIGN(sizeof (struct nbinary)),
4191 ALIGN(sizeof (struct ncmd)),
4192 ALIGN(sizeof (struct npipe)),
4193 ALIGN(sizeof (struct nredir)),
4194 ALIGN(sizeof (struct nredir)),
4195 ALIGN(sizeof (struct nredir)),
4196 ALIGN(sizeof (struct nbinary)),
4197 ALIGN(sizeof (struct nbinary)),
4198 ALIGN(sizeof (struct nif)),
4199 ALIGN(sizeof (struct nbinary)),
4200 ALIGN(sizeof (struct nbinary)),
4201 ALIGN(sizeof (struct nfor)),
4202 ALIGN(sizeof (struct ncase)),
4203 ALIGN(sizeof (struct nclist)),
4204 ALIGN(sizeof (struct narg)),
4205 ALIGN(sizeof (struct narg)),
4206 ALIGN(sizeof (struct nfile)),
4207 ALIGN(sizeof (struct nfile)),
4208 ALIGN(sizeof (struct nfile)),
4209 ALIGN(sizeof (struct nfile)),
4210 ALIGN(sizeof (struct nfile)),
4211 ALIGN(sizeof (struct ndup)),
4212 ALIGN(sizeof (struct ndup)),
4213 ALIGN(sizeof (struct nhere)),
4214 ALIGN(sizeof (struct nhere)),
4215 ALIGN(sizeof (struct nnot)),
4221 * Delete a function if it exists.
4225 unsetfunc(char *name)
4227 struct tblentry *cmdp;
4229 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4230 freefunc(cmdp->param.func);
4237 * Locate and print what a word is...
4241 typecmd(int argc, char **argv)
4249 for (i = 1; i < argc; i++) {
4250 argv_a[0] = argv[i];
4253 err |= hashcmd(argc, argv);
4260 commandcmd(argc, argv)
4265 int default_path = 0;
4266 int verify_only = 0;
4267 int verbose_verify_only = 0;
4269 while ((c = nextopt("pvV")) != '\0')
4278 verbose_verify_only = 1;
4282 if (default_path + verify_only + verbose_verify_only > 1 ||
4285 "command [-p] command [arg ...]\n"
4286 "command {-v|-V} command\n");
4290 if (verify_only || verbose_verify_only) {
4294 argv_a[0] = *argptr;
4296 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4297 return hashcmd(argc, argv);
4305 path_change(newval, bltin)
4309 const char *old, *new;
4315 firstchange = 9999; /* assume no change */
4321 if ((*old == '\0' && *new == ':')
4322 || (*old == ':' && *new == '\0'))
4324 old = new; /* ignore subsequent differences */
4328 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4335 if (builtinloc >= 0 && *bltin < 0)
4340 * Routines to expand arguments to commands. We have to deal with
4341 * backquotes, shell variables, and file metacharacters.
4346 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4347 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4350 * Structure specifying which parts of the string should be searched
4351 * for IFS characters.
4355 struct ifsregion *next; /* next region in list */
4356 int begoff; /* offset of start of region */
4357 int endoff; /* offset of end of region */
4358 int nulonly; /* search for nul bytes only */
4362 static char *expdest; /* output of current string */
4363 static struct nodelist *argbackq; /* list of back quote expressions */
4364 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4365 static struct ifsregion *ifslastp; /* last struct in list */
4366 static struct arglist exparg; /* holds expanded arg list */
4368 static void argstr (char *, int);
4369 static char *exptilde (char *, int);
4370 static void expbackq (union node *, int, int);
4371 static int subevalvar (char *, char *, int, int, int, int, int);
4372 static int varisset (char *, int);
4373 static void strtodest (const char *, int, int);
4374 static void varvalue (char *, int, int);
4375 static void recordregion (int, int, int);
4376 static void removerecordregions (int);
4377 static void ifsbreakup (char *, struct arglist *);
4378 static void ifsfree (void);
4379 static void expandmeta (struct strlist *, int);
4380 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4381 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4382 #if !defined(GLOB_BROKEN)
4383 static void addglob (const glob_t *);
4386 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4387 static void expmeta (char *, char *);
4389 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4390 static struct strlist *expsort (struct strlist *);
4391 static struct strlist *msort (struct strlist *, int);
4393 static int patmatch (char *, char *, int);
4394 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4395 static int patmatch2 (char *, char *, int);
4397 static int pmatch (char *, char *, int);
4398 #define patmatch2 patmatch
4400 static char *cvtnum (int, char *);
4403 * Expand shell variables and backquotes inside a here document.
4406 /* arg: the document, fd: where to write the expanded version */
4408 expandhere(union node *arg, int fd)
4411 expandarg(arg, (struct arglist *)NULL, 0);
4412 xwrite(fd, stackblock(), expdest - stackblock());
4417 * Perform variable substitution and command substitution on an argument,
4418 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4419 * perform splitting and file name expansion. When arglist is NULL, perform
4420 * here document expansion.
4424 expandarg(arg, arglist, flag)
4426 struct arglist *arglist;
4432 argbackq = arg->narg.backquote;
4433 STARTSTACKSTR(expdest);
4434 ifsfirst.next = NULL;
4436 argstr(arg->narg.text, flag);
4437 if (arglist == NULL) {
4438 return; /* here document expanded */
4440 STPUTC('\0', expdest);
4441 p = grabstackstr(expdest);
4442 exparg.lastp = &exparg.list;
4446 if (flag & EXP_FULL) {
4447 ifsbreakup(p, &exparg);
4448 *exparg.lastp = NULL;
4449 exparg.lastp = &exparg.list;
4450 expandmeta(exparg.list, flag);
4452 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4454 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4457 exparg.lastp = &sp->next;
4460 *exparg.lastp = NULL;
4462 *arglist->lastp = exparg.list;
4463 arglist->lastp = exparg.lastp;
4469 * Expand a variable, and return a pointer to the next character in the
4473 static inline char *
4489 int quotes = flag & (EXP_FULL | EXP_CASE);
4492 subtype = varflags & VSTYPE;
4497 p = strchr(p, '=') + 1;
4498 again: /* jump here after setting a variable with ${var=text} */
4500 set = varisset(var, varflags & VSNUL);
4503 val = lookupvar(var);
4504 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4511 startloc = expdest - stackblock();
4512 if (set && subtype != VSPLUS) {
4513 /* insert the value of the variable */
4515 varvalue(var, varflags & VSQUOTE, flag);
4516 if (subtype == VSLENGTH) {
4517 varlen = expdest - stackblock() - startloc;
4518 STADJUST(-varlen, expdest);
4521 if (subtype == VSLENGTH) {
4522 varlen = strlen(val);
4526 varflags & VSQUOTE ?
4527 DQSYNTAX : BASESYNTAX,
4534 if (subtype == VSPLUS)
4537 easy = ((varflags & VSQUOTE) == 0 ||
4538 (*var == '@' && shellparam.nparam != 1));
4543 expdest = cvtnum(varlen, expdest);
4550 recordregion(startloc, expdest - stackblock(),
4551 varflags & VSQUOTE);
4567 case VSTRIMRIGHTMAX:
4571 * Terminate the string and start recording the pattern
4574 STPUTC('\0', expdest);
4575 patloc = expdest - stackblock();
4576 if (subevalvar(p, NULL, patloc, subtype,
4577 startloc, varflags, quotes) == 0) {
4578 int amount = (expdest - stackblock() - patloc) + 1;
4579 STADJUST(-amount, expdest);
4581 /* Remove any recorded regions beyond start of variable */
4582 removerecordregions(startloc);
4588 if (subevalvar(p, var, 0, subtype, startloc,
4589 varflags, quotes)) {
4592 * Remove any recorded regions beyond
4595 removerecordregions(startloc);
4610 if (subtype != VSNORMAL) { /* skip to end of alternative */
4613 if ((c = *p++) == CTLESC)
4615 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4617 argbackq = argbackq->next;
4618 } else if (c == CTLVAR) {
4619 if ((*p++ & VSTYPE) != VSNORMAL)
4621 } else if (c == CTLENDVAR) {
4632 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4633 * characters to allow for further processing. Otherwise treat
4634 * $@ like $* since no splitting will be performed.
4643 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4646 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4647 p = exptilde(p, flag);
4651 case CTLENDVAR: /* ??? */
4654 /* "$@" syntax adherence hack */
4655 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4657 if ((flag & EXP_FULL) != 0)
4667 p = evalvar(p, flag);
4670 case CTLBACKQ|CTLQUOTE:
4671 expbackq(argbackq->n, c & CTLQUOTE, flag);
4672 argbackq = argbackq->next;
4674 #ifdef ASH_MATH_SUPPORT
4682 * sort of a hack - expand tildes in variable
4683 * assignments (after the first '=' and after ':'s).
4686 if (flag & EXP_VARTILDE && *p == '~') {
4693 p = exptilde(p, flag);
4709 char c, *startp = p;
4712 int quotes = flag & (EXP_FULL | EXP_CASE);
4714 while ((c = *p) != '\0') {
4721 if (flag & EXP_VARTILDE)
4731 if (*(startp+1) == '\0') {
4732 if ((home = lookupvar("HOME")) == NULL)
4735 if ((pw = getpwnam(startp+1)) == NULL)
4742 strtodest(home, SQSYNTAX, quotes);
4751 removerecordregions(int endoff)
4753 if (ifslastp == NULL)
4756 if (ifsfirst.endoff > endoff) {
4757 while (ifsfirst.next != NULL) {
4758 struct ifsregion *ifsp;
4760 ifsp = ifsfirst.next->next;
4761 ckfree(ifsfirst.next);
4762 ifsfirst.next = ifsp;
4765 if (ifsfirst.begoff > endoff)
4768 ifslastp = &ifsfirst;
4769 ifsfirst.endoff = endoff;
4774 ifslastp = &ifsfirst;
4775 while (ifslastp->next && ifslastp->next->begoff < endoff)
4776 ifslastp=ifslastp->next;
4777 while (ifslastp->next != NULL) {
4778 struct ifsregion *ifsp;
4780 ifsp = ifslastp->next->next;
4781 ckfree(ifslastp->next);
4782 ifslastp->next = ifsp;
4785 if (ifslastp->endoff > endoff)
4786 ifslastp->endoff = endoff;
4790 #ifdef ASH_MATH_SUPPORT
4792 * Expand arithmetic expression. Backup to start of expression,
4793 * evaluate, place result in (backed up) result, adjust string position.
4802 int quotes = flag & (EXP_FULL | EXP_CASE);
4808 * This routine is slightly over-complicated for
4809 * efficiency. First we make sure there is
4810 * enough space for the result, which may be bigger
4811 * than the expression if we add exponentation. Next we
4812 * scan backwards looking for the start of arithmetic. If the
4813 * next previous character is a CTLESC character, then we
4814 * have to rescan starting from the beginning since CTLESC
4815 * characters have to be processed left to right.
4817 CHECKSTRSPACE(10, expdest);
4818 USTPUTC('\0', expdest);
4819 start = stackblock();
4821 while (*p != CTLARI && p >= start)
4824 error("missing CTLARI (shouldn't happen)");
4825 if (p > start && *(p-1) == CTLESC)
4826 for (p = start; *p != CTLARI; p++)
4835 removerecordregions(begoff);
4838 result = arith(p+2, &errcode);
4841 error("divide by zero");
4843 error("syntax error: \"%s\"\n", p+2);
4845 snprintf(p, 12, "%d", result);
4851 recordregion(begoff, p - 1 - start, 0);
4852 result = expdest - p + 1;
4853 STADJUST(-result, expdest);
4858 * Expand stuff in backwards quotes.
4862 expbackq(cmd, quoted, flag)
4867 volatile struct backcmd in;
4871 char *dest = expdest;
4872 volatile struct ifsregion saveifs;
4873 struct ifsregion *volatile savelastp;
4874 struct nodelist *volatile saveargbackq;
4876 int startloc = dest - stackblock();
4877 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4878 volatile int saveherefd;
4879 int quotes = flag & (EXP_FULL | EXP_CASE);
4880 struct jmploc jmploc;
4881 struct jmploc *volatile savehandler;
4885 /* Avoid longjmp clobbering */
4896 savelastp = ifslastp;
4897 saveargbackq = argbackq;
4898 saveherefd = herefd;
4900 if ((ex = setjmp(jmploc.loc))) {
4903 savehandler = handler;
4906 p = grabstackstr(dest);
4907 evalbackcmd(cmd, (struct backcmd *) &in);
4908 ungrabstackstr(p, dest);
4912 ifslastp = savelastp;
4913 argbackq = saveargbackq;
4914 herefd = saveherefd;
4922 if (--in.nleft < 0) {
4925 i = safe_read(in.fd, buf, sizeof buf);
4926 TRACE(("expbackq: read returns %d\n", i));
4933 if (lastc != '\0') {
4934 if (quotes && SIT(lastc, syntax) == CCTL)
4935 STPUTC(CTLESC, dest);
4936 STPUTC(lastc, dest);
4940 /* Eat all trailing newlines */
4941 for (; dest > stackblock() && dest[-1] == '\n';)
4950 exitstatus = waitforjob(in.jp);
4951 handler = savehandler;
4953 longjmp(handler->loc, 1);
4956 recordregion(startloc, dest - stackblock(), 0);
4957 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4958 (dest - stackblock()) - startloc,
4959 (dest - stackblock()) - startloc,
4960 stackblock() + startloc));
4966 subevalvar(p, str, strloc, subtype, startloc, varflags, quotes)
4979 int saveherefd = herefd;
4980 struct nodelist *saveargbackq = argbackq;
4984 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4985 STACKSTRNUL(expdest);
4986 herefd = saveherefd;
4987 argbackq = saveargbackq;
4988 startp = stackblock() + startloc;
4990 str = stackblock() + strloc;
4994 setvar(str, startp, 0);
4995 amount = startp - expdest;
4996 STADJUST(amount, expdest);
5003 if (*p != CTLENDVAR) {
5004 out2fmt(snlfmt, startp);
5005 error((char *)NULL);
5007 error("%.*s: parameter %snot set", p - str - 1,
5008 str, (varflags & VSNUL) ? "null or "
5013 for (loc = startp; loc < str; loc++) {
5016 if (patmatch2(str, startp, quotes))
5019 if (quotes && *loc == CTLESC)
5025 for (loc = str - 1; loc >= startp;) {
5028 if (patmatch2(str, startp, quotes))
5032 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
5033 for (q = startp; q < loc; q++)
5043 for (loc = str - 1; loc >= startp;) {
5044 if (patmatch2(str, loc, quotes))
5047 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
5048 for (q = startp; q < loc; q++)
5057 case VSTRIMRIGHTMAX:
5058 for (loc = startp; loc < str - 1; loc++) {
5059 if (patmatch2(str, loc, quotes))
5061 if (quotes && *loc == CTLESC)
5074 amount = ((str - 1) - (loc - startp)) - expdest;
5075 STADJUST(amount, expdest);
5076 while (loc != str - 1)
5081 amount = loc - expdest;
5082 STADJUST(amount, expdest);
5083 STPUTC('\0', expdest);
5084 STADJUST(-1, expdest);
5090 * Test whether a specialized variable is set.
5094 varisset(name, nulok)
5099 return backgndpid != -1;
5100 else if (*name == '@' || *name == '*') {
5101 if (*shellparam.p == NULL)
5107 for (av = shellparam.p; *av; av++)
5112 } else if (is_digit(*name)) {
5114 int num = atoi(name);
5116 if (num > shellparam.nparam)
5122 ap = shellparam.p[num - 1];
5124 if (nulok && (ap == NULL || *ap == '\0'))
5131 * Put a string on the stack.
5135 strtodest(const char *p, int syntax, int quotes)
5138 if (quotes && SIT(*p,syntax) == CCTL)
5139 STPUTC(CTLESC, expdest);
5140 STPUTC(*p++, expdest);
5145 * Add the value of a specialized variable to the stack string.
5149 varvalue(char *name, int quoted, int flags)
5158 int allow_split = flags & EXP_FULL;
5159 int quotes = flags & (EXP_FULL | EXP_CASE);
5161 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5170 num = shellparam.nparam;
5175 expdest = cvtnum(num, expdest);
5178 for (i = 0 ; i < NOPTS ; i++) {
5180 STPUTC(optent_letter(optlist[i]), expdest);
5184 if (allow_split && quoted) {
5185 sep = 1 << CHAR_BIT;
5190 sep = ifsset() ? ifsval()[0] : ' ';
5192 sepq = SIT(sep,syntax) == CCTL;
5195 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
5196 strtodest(p, syntax, quotes);
5199 STPUTC(CTLESC, expdest);
5200 STPUTC(sep, expdest);
5205 strtodest(arg0, syntax, quotes);
5209 if (num > 0 && num <= shellparam.nparam) {
5210 strtodest(shellparam.p[num - 1], syntax, quotes);
5218 * Record the fact that we have to scan this region of the
5219 * string for IFS characters.
5223 recordregion(start, end, nulonly)
5228 struct ifsregion *ifsp;
5230 if (ifslastp == NULL) {
5234 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5236 ifslastp->next = ifsp;
5240 ifslastp->begoff = start;
5241 ifslastp->endoff = end;
5242 ifslastp->nulonly = nulonly;
5248 * Break the argument string into pieces based upon IFS and add the
5249 * strings to the argument list. The regions of the string to be
5250 * searched for IFS characters have been stored by recordregion.
5253 ifsbreakup(string, arglist)
5255 struct arglist *arglist;
5257 struct ifsregion *ifsp;
5262 const char *ifs, *realifs;
5270 realifs = ifsset() ? ifsval() : defifs;
5271 if (ifslastp != NULL) {
5274 p = string + ifsp->begoff;
5275 nulonly = ifsp->nulonly;
5276 ifs = nulonly ? nullstr : realifs;
5278 while (p < string + ifsp->endoff) {
5282 if (strchr(ifs, *p)) {
5284 ifsspc = (strchr(defifs, *p) != NULL);
5285 /* Ignore IFS whitespace at start */
5286 if (q == start && ifsspc) {
5292 sp = (struct strlist *)stalloc(sizeof *sp);
5294 *arglist->lastp = sp;
5295 arglist->lastp = &sp->next;
5299 if (p >= string + ifsp->endoff) {
5305 if (strchr(ifs, *p) == NULL ) {
5308 } else if (strchr(defifs, *p) == NULL) {
5324 } while ((ifsp = ifsp->next) != NULL);
5325 if (!(*start || (!ifsspc && start > string && nulonly))) {
5330 sp = (struct strlist *)stalloc(sizeof *sp);
5332 *arglist->lastp = sp;
5333 arglist->lastp = &sp->next;
5339 while (ifsfirst.next != NULL) {
5340 struct ifsregion *ifsp;
5342 ifsp = ifsfirst.next->next;
5343 ckfree(ifsfirst.next);
5344 ifsfirst.next = ifsp;
5348 ifsfirst.next = NULL;
5352 * Add a file name to the list.
5356 addfname(const char *name)
5362 sp = (struct strlist *)stalloc(sizeof *sp);
5365 exparg.lastp = &sp->next;
5369 * Expand shell metacharacters. At this point, the only control characters
5370 * should be escapes. The results are stored in the list exparg.
5373 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5375 expandmeta(str, flag)
5376 struct strlist *str;
5381 /* TODO - EXP_REDIR */
5386 p = preglob(str->text);
5388 switch (glob(p, 0, 0, &pglob)) {
5390 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5401 *exparg.lastp = str;
5402 rmescapes(str->text);
5403 exparg.lastp = &str->next;
5405 default: /* GLOB_NOSPACE */
5406 error("Out of space");
5414 * Add the result of glob(3) to the list.
5419 const glob_t *pglob;
5421 char **p = pglob->gl_pathv;
5429 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5430 static char *expdir;
5434 expandmeta(str, flag)
5435 struct strlist *str;
5439 struct strlist **savelastp;
5442 /* TODO - EXP_REDIR */
5448 for (;;) { /* fast check for meta chars */
5449 if ((c = *p++) == '\0')
5451 if (c == '*' || c == '?' || c == '[' || c == '!')
5454 savelastp = exparg.lastp;
5456 if (expdir == NULL) {
5457 int i = strlen(str->text);
5458 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5461 expmeta(expdir, str->text);
5465 if (exparg.lastp == savelastp) {
5470 *exparg.lastp = str;
5471 rmescapes(str->text);
5472 exparg.lastp = &str->next;
5474 *exparg.lastp = NULL;
5475 *savelastp = sp = expsort(*savelastp);
5476 while (sp->next != NULL)
5478 exparg.lastp = &sp->next;
5486 * Do metacharacter (i.e. *, ?, [...]) expansion.
5490 expmeta(enddir, name)
5508 for (p = name ; ; p++) {
5509 if (*p == '*' || *p == '?')
5511 else if (*p == '[') {
5516 while (*q == CTLQUOTEMARK)
5520 if (*q == '/' || *q == '\0')
5527 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5529 } else if (*p == '\0')
5531 else if (*p == CTLQUOTEMARK)
5533 else if (*p == CTLESC)
5541 if (metaflag == 0) { /* we've reached the end of the file name */
5542 if (enddir != expdir)
5544 for (p = name ; ; p++) {
5545 if (*p == CTLQUOTEMARK)
5553 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5558 if (start != name) {
5561 while (*p == CTLQUOTEMARK)
5568 if (enddir == expdir) {
5570 } else if (enddir == expdir + 1 && *expdir == '/') {
5576 if ((dirp = opendir(cp)) == NULL)
5578 if (enddir != expdir)
5580 if (*endname == 0) {
5588 while (*p == CTLQUOTEMARK)
5594 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5595 if (dp->d_name[0] == '.' && ! matchdot)
5597 if (patmatch(start, dp->d_name, 0)) {
5599 strcpy(enddir, dp->d_name);
5602 for (p = enddir, cp = dp->d_name;
5603 (*p++ = *cp++) != '\0';)
5606 expmeta(p, endname);
5614 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5618 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5620 * Sort the results of file name expansion. It calculates the number of
5621 * strings to sort and then calls msort (short for merge sort) to do the
5625 static struct strlist *
5627 struct strlist *str;
5633 for (sp = str ; sp ; sp = sp->next)
5635 return msort(str, len);
5639 static struct strlist *
5641 struct strlist *list;
5644 struct strlist *p, *q = NULL;
5645 struct strlist **lpp;
5653 for (n = half ; --n >= 0 ; ) {
5657 q->next = NULL; /* terminate first half of list */
5658 q = msort(list, half); /* sort first half of list */
5659 p = msort(p, len - half); /* sort second half */
5662 if (strcmp(p->text, q->text) < 0) {
5665 if ((p = *lpp) == NULL) {
5672 if ((q = *lpp) == NULL) {
5685 * Returns true if the pattern matches the string.
5688 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5689 /* squoted: string might have quote chars */
5691 patmatch(char *pattern, char *string, int squoted)
5696 p = preglob(pattern);
5697 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5699 return !fnmatch(p, q, 0);
5704 patmatch2(char *pattern, char *string, int squoted)
5710 p = grabstackstr(expdest);
5711 res = patmatch(pattern, string, squoted);
5712 ungrabstackstr(p, expdest);
5717 patmatch(char *pattern, char *string, int squoted) {
5718 return pmatch(pattern, string, squoted);
5723 pmatch(char *pattern, char *string, int squoted)
5735 if (squoted && *q == CTLESC)
5743 if (squoted && *q == CTLESC)
5750 while (c == CTLQUOTEMARK || c == '*')
5752 if (c != CTLESC && c != CTLQUOTEMARK &&
5753 c != '?' && c != '*' && c != '[') {
5755 if (squoted && *q == CTLESC &&
5760 if (squoted && *q == CTLESC)
5766 if (pmatch(p, q, squoted))
5768 if (squoted && *q == CTLESC)
5770 } while (*q++ != '\0');
5781 while (*endp == CTLQUOTEMARK)
5784 goto dft; /* no matching ] */
5785 if (*endp == CTLESC)
5797 if (squoted && chr == CTLESC)
5803 if (c == CTLQUOTEMARK)
5807 if (*p == '-' && p[1] != ']') {
5809 while (*p == CTLQUOTEMARK)
5813 if (chr >= c && chr <= *p)
5820 } while ((c = *p++) != ']');
5821 if (found == invert)
5826 if (squoted && *q == CTLESC)
5843 * Remove any CTLESC characters from a string.
5846 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5848 _rmescapes(char *str, int flag)
5851 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5853 p = strpbrk(str, qchars);
5859 if (flag & RMESCAPE_ALLOC) {
5860 size_t len = p - str;
5861 q = r = stalloc(strlen(p) + len + 1);
5863 memcpy(q, str, len);
5868 if (*p == CTLQUOTEMARK) {
5874 if (flag & RMESCAPE_GLOB && *p != '/') {
5891 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5897 if (*p == CTLQUOTEMARK) {
5912 * See if a pattern matches in a case statement.
5916 casematch(union node *pattern, const char *val)
5918 struct stackmark smark;
5922 setstackmark(&smark);
5923 argbackq = pattern->narg.backquote;
5924 STARTSTACKSTR(expdest);
5926 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5927 STPUTC('\0', expdest);
5928 p = grabstackstr(expdest);
5929 result = patmatch(p, (char *)val, 0);
5930 popstackmark(&smark);
5945 CHECKSTRSPACE(32, buf);
5946 len = sprintf(buf, "%d", num);
5951 * Editline and history functions (and glue).
5953 static int histcmd(argc, argv)
5957 error("not compiled with history support");
5963 struct redirtab *next;
5964 short renamed[10]; /* Current ash support only 0-9 descriptors */
5965 /* char on arm (and others) can't be negative */
5968 static struct redirtab *redirlist;
5970 extern char **environ;
5975 * Initialization code.
5988 basepf.nextc = basepf.buf = basebuf;
5997 for (envp = environ ; *envp ; envp++) {
5998 if (strchr(*envp, '=')) {
5999 setvareq(*envp, VEXPORT|VTEXTFIXED);
6003 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
6004 setvar("PPID", ppid, 0);
6011 * This routine is called when an error or an interrupt occurs in an
6012 * interactive shell and control is returned to the main command loop.
6015 /* 1 == check for aliases, 2 == also check for assignments */
6016 static int checkalias; /* also used in no alias mode for check assignments */
6030 if (exception != EXSHELLPROC)
6031 parselleft = parsenleft = 0; /* clear input buffer */
6035 /* from parser.c: */
6053 * This file implements the input routines used by the parser.
6056 #ifdef BB_FEATURE_COMMAND_EDITING
6057 static const char * cmdedit_prompt;
6058 static inline void putprompt(const char *s) {
6062 static inline void putprompt(const char *s) {
6067 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
6072 * Same as pgetc(), but ignores PEOA.
6082 } while (c == PEOA);
6086 static inline int pgetc2() { return pgetc_macro(); }
6090 * Read a line from the script.
6093 static inline char *
6094 pfgets(char *line, int len)
6100 while (--nleft > 0) {
6119 char *buf = parsefile->buf;
6123 #ifdef BB_FEATURE_COMMAND_EDITING
6125 if (!iflag || parsefile->fd)
6126 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6128 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
6132 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6136 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6137 int flags = fcntl(0, F_GETFL, 0);
6138 if (flags >= 0 && flags & O_NONBLOCK) {
6139 flags &=~ O_NONBLOCK;
6140 if (fcntl(0, F_SETFL, flags) >= 0) {
6141 out2str("sh: turning off NDELAY mode\n");
6153 struct strpush *sp = parsefile->strpush;
6158 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6163 if (sp->string != sp->ap->val) {
6167 sp->ap->flag &= ~ALIASINUSE;
6168 if (sp->ap->flag & ALIASDEAD) {
6169 unalias(sp->ap->name);
6173 parsenextc = sp->prevstring;
6174 parsenleft = sp->prevnleft;
6175 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6176 parsefile->strpush = sp->prev;
6177 if (sp != &(parsefile->basestrpush))
6184 * Refill the input buffer and return the next input character:
6186 * 1) If a string was pushed back on the input, pop it;
6187 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6188 * from a string so we can't refill the buffer, return EOF.
6189 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6190 * 4) Process input up to the next newline, deleting nul characters.
6200 while (parsefile->strpush) {
6202 if (parsenleft == -1 && parsefile->strpush->ap &&
6203 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6208 if (--parsenleft >= 0)
6209 return (*parsenextc++);
6211 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6216 if (parselleft <= 0) {
6217 if ((parselleft = preadfd()) <= 0) {
6218 parselleft = parsenleft = EOF_NLEFT;
6225 /* delete nul characters */
6226 for (more = 1; more;) {
6234 parsenleft = q - parsenextc;
6235 more = 0; /* Stop processing here */
6241 if (--parselleft <= 0 && more) {
6242 parsenleft = q - parsenextc - 1;
6253 out2str(parsenextc);
6258 return *parsenextc++;
6263 * Push a string back onto the input at this current parsefile level.
6264 * We handle aliases this way.
6267 pushstring(char *s, int len, void *ap)
6272 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6273 if (parsefile->strpush) {
6274 sp = ckmalloc(sizeof (struct strpush));
6275 sp->prev = parsefile->strpush;
6276 parsefile->strpush = sp;
6278 sp = parsefile->strpush = &(parsefile->basestrpush);
6279 sp->prevstring = parsenextc;
6280 sp->prevnleft = parsenleft;
6282 sp->ap = (struct alias *)ap;
6284 ((struct alias *)ap)->flag |= ALIASINUSE;
6295 * Like setinputfile, but takes input from a string.
6299 setinputstring(char *string)
6303 parsenextc = string;
6304 parsenleft = strlen(string);
6305 parsefile->buf = NULL;
6313 * To handle the "." command, a stack of input files is used. Pushfile
6314 * adds a new entry to the stack and popfile restores the previous level.
6319 struct parsefile *pf;
6321 parsefile->nleft = parsenleft;
6322 parsefile->lleft = parselleft;
6323 parsefile->nextc = parsenextc;
6324 parsefile->linno = plinno;
6325 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6326 pf->prev = parsefile;
6329 pf->basestrpush.prev = NULL;
6334 static void restartjob (struct job *);
6336 static void freejob (struct job *);
6337 static struct job *getjob (const char *);
6338 static int dowait (int, struct job *);
6339 static void waitonint(int);
6343 * We keep track of whether or not fd0 has been redirected. This is for
6344 * background commands, where we want to redirect fd0 to /dev/null only
6345 * if it hasn't already been redirected.
6347 static int fd0_redirected = 0;
6349 /* Return true if fd 0 has already been redirected at least once. */
6351 fd0_redirected_p () {
6352 return fd0_redirected != 0;
6355 static void dupredirect (const union node *, int, int fd1dup);
6359 * Turn job control on and off.
6361 * Note: This code assumes that the third arg to ioctl is a character
6362 * pointer, which is true on Berkeley systems but not System V. Since
6363 * System V doesn't have job control yet, this isn't a problem now.
6368 static void setjobctl(int enable)
6370 #ifdef OLD_TTY_DRIVER
6374 if (enable == jobctl || rootshell == 0)
6377 do { /* while we are in the background */
6378 #ifdef OLD_TTY_DRIVER
6379 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6381 initialpgrp = tcgetpgrp(2);
6382 if (initialpgrp < 0) {
6384 out2str("sh: can't access tty; job control turned off\n");
6388 if (initialpgrp == -1)
6389 initialpgrp = getpgrp();
6390 else if (initialpgrp != getpgrp()) {
6391 killpg(initialpgrp, SIGTTIN);
6395 #ifdef OLD_TTY_DRIVER
6396 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6397 out2str("sh: need new tty driver to run job control; job control turned off\n");
6405 setpgid(0, rootpid);
6406 #ifdef OLD_TTY_DRIVER
6407 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6409 tcsetpgrp(2, rootpid);
6411 } else { /* turning job control off */
6412 setpgid(0, initialpgrp);
6413 #ifdef OLD_TTY_DRIVER
6414 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6416 tcsetpgrp(2, initialpgrp);
6442 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6443 "kill -l [exitstatus]"
6447 if (*argv[1] == '-') {
6448 signo = decode_signal(argv[1] + 1, 1);
6452 while ((c = nextopt("ls:")) != '\0')
6458 signo = decode_signal(optionarg, 1);
6461 "invalid signal number or name: %s",
6469 "nextopt returned character code 0%o", c);
6476 if (!list && signo < 0)
6479 if ((signo < 0 || !*argptr) ^ list) {
6488 for (i = 1; i < NSIG; i++) {
6489 name = u_signal_names(0, &i, 1);
6491 printf(snlfmt, name);
6495 name = u_signal_names(*argptr, &signo, -1);
6497 printf(snlfmt, name);
6499 error("invalid signal number or exit status: %s",
6505 if (**argptr == '%') {
6506 jp = getjob(*argptr);
6507 if (jp->jobctl == 0)
6508 error("job %s not created under job control",
6510 pid = -jp->ps[0].pid;
6512 pid = atoi(*argptr);
6513 if (kill(pid, signo) != 0)
6514 error("%s: %m", *argptr);
6515 } while (*++argptr);
6529 jp = getjob(argv[1]);
6530 if (jp->jobctl == 0)
6531 error("job not created under job control");
6532 pgrp = jp->ps[0].pid;
6533 #ifdef OLD_TTY_DRIVER
6534 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6540 status = waitforjob(jp);
6554 jp = getjob(*++argv);
6555 if (jp->jobctl == 0)
6556 error("job not created under job control");
6558 } while (--argc > 1);
6567 struct procstat *ps;
6570 if (jp->state == JOBDONE)
6573 killpg(jp->ps[0].pid, SIGCONT);
6574 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6575 if (WIFSTOPPED(ps->status)) {
6584 static void showjobs(int change);
6598 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6599 * statuses have changed since the last call to showjobs.
6601 * If the shell is interrupted in the process of creating a job, the
6602 * result may be a job structure containing zero processes. Such structures
6603 * will be freed here.
6614 struct procstat *ps;
6618 TRACE(("showjobs(%d) called\n", change));
6619 while (dowait(0, (struct job *)NULL) > 0);
6620 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6623 if (jp->nprocs == 0) {
6627 if (change && ! jp->changed)
6629 procno = jp->nprocs;
6630 for (ps = jp->ps ; ; ps++) { /* for each process */
6632 snprintf(s, 64, "[%d] %ld ", jobno,
6635 snprintf(s, 64, " %ld ",
6640 if (ps->status == -1) {
6641 /* don't print anything */
6642 } else if (WIFEXITED(ps->status)) {
6643 snprintf(s, 64, "Exit %d",
6644 WEXITSTATUS(ps->status));
6647 if (WIFSTOPPED(ps->status))
6648 i = WSTOPSIG(ps->status);
6649 else /* WIFSIGNALED(ps->status) */
6651 i = WTERMSIG(ps->status);
6652 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6653 strcpy(s, sys_siglist[i & 0x7F]);
6655 snprintf(s, 64, "Signal %d", i & 0x7F);
6656 if (WCOREDUMP(ps->status))
6657 strcat(s, " (core dumped)");
6662 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6669 if (jp->state == JOBDONE) {
6677 * Mark a job structure as unused.
6681 freejob(struct job *jp)
6683 const struct procstat *ps;
6687 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6688 if (ps->cmd != nullstr)
6691 if (jp->ps != &jp->ps0)
6695 if (curjob == jp - jobtab + 1)
6714 job = getjob(*++argv);
6718 for (;;) { /* loop until process terminated or stopped */
6721 status = job->ps[job->nprocs - 1].status;
6727 if (WIFEXITED(status))
6728 retval = WEXITSTATUS(status);
6730 else if (WIFSTOPPED(status))
6731 retval = WSTOPSIG(status) + 128;
6734 /* XXX: limits number of signals */
6735 retval = WTERMSIG(status) + 128;
6740 for (jp = jobtab ; ; jp++) {
6741 if (jp >= jobtab + njobs) { /* no running procs */
6744 if (jp->used && jp->state == 0)
6748 if (dowait(2, 0) < 0 && errno == EINTR) {
6757 * Convert a job name to a job structure.
6761 getjob(const char *name)
6771 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6772 error("No current job");
6773 return &jobtab[jobno - 1];
6775 error("No current job");
6777 } else if (name[0] == '%') {
6778 if (is_digit(name[1])) {
6779 jobno = number(name + 1);
6780 if (jobno > 0 && jobno <= njobs
6781 && jobtab[jobno - 1].used != 0)
6782 return &jobtab[jobno - 1];
6784 } else if (name[1] == '%' && name[2] == '\0') {
6788 struct job *found = NULL;
6789 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6790 if (jp->used && jp->nprocs > 0
6791 && prefix(name + 1, jp->ps[0].cmd)) {
6793 error("%s: ambiguous", name);
6800 } else if (is_number(name, &pid)) {
6801 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6802 if (jp->used && jp->nprocs > 0
6803 && jp->ps[jp->nprocs - 1].pid == pid)
6807 error("No such job: %s", name);
6814 * Return a new job structure,
6818 makejob(const union node *node, int nprocs)
6823 for (i = njobs, jp = jobtab ; ; jp++) {
6827 jobtab = ckmalloc(4 * sizeof jobtab[0]);
6829 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
6830 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6831 /* Relocate `ps' pointers */
6832 for (i = 0; i < njobs; i++)
6833 if (jp[i].ps == &jobtab[i].ps0)
6834 jp[i].ps = &jp[i].ps0;
6838 jp = jobtab + njobs;
6839 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6852 jp->jobctl = jobctl;
6855 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6860 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6867 * Fork of a subshell. If we are doing job control, give the subshell its
6868 * own process group. Jp is a job structure that the job is to be added to.
6869 * N is the command that will be evaluated by the child. Both jp and n may
6870 * be NULL. The mode parameter can be one of the following:
6871 * FORK_FG - Fork off a foreground process.
6872 * FORK_BG - Fork off a background process.
6873 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6874 * process group even if job control is on.
6876 * When job control is turned off, background processes have their standard
6877 * input redirected to /dev/null (except for the second and later processes
6884 forkshell(struct job *jp, const union node *n, int mode)
6890 const char *devnull = _PATH_DEVNULL;
6891 const char *nullerr = "Can't open %s";
6893 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6898 TRACE(("Fork failed, errno=%d\n", errno));
6900 error("Cannot fork");
6907 TRACE(("Child shell %d\n", getpid()));
6908 wasroot = rootshell;
6914 jobctl = 0; /* do job control only in root shell */
6915 if (wasroot && mode != FORK_NOJOB && mflag) {
6916 if (jp == NULL || jp->nprocs == 0)
6919 pgrp = jp->ps[0].pid;
6921 if (mode == FORK_FG) {
6922 /*** this causes superfluous TIOCSPGRPS ***/
6923 #ifdef OLD_TTY_DRIVER
6924 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6925 error("TIOCSPGRP failed, errno=%d", errno);
6927 if (tcsetpgrp(2, pgrp) < 0)
6928 error("tcsetpgrp failed, errno=%d", errno);
6933 } else if (mode == FORK_BG) {
6936 if ((jp == NULL || jp->nprocs == 0) &&
6937 ! fd0_redirected_p ()) {
6939 if (open(devnull, O_RDONLY) != 0)
6940 error(nullerr, devnull);
6944 if (mode == FORK_BG) {
6947 if ((jp == NULL || jp->nprocs == 0) &&
6948 ! fd0_redirected_p ()) {
6950 if (open(devnull, O_RDONLY) != 0)
6951 error(nullerr, devnull);
6955 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6958 if (wasroot && iflag) {
6966 if (rootshell && mode != FORK_NOJOB && mflag) {
6967 if (jp == NULL || jp->nprocs == 0)
6970 pgrp = jp->ps[0].pid;
6974 if (mode == FORK_BG)
6975 backgndpid = pid; /* set $! */
6977 struct procstat *ps = &jp->ps[jp->nprocs++];
6981 if (iflag && rootshell && n)
6982 ps->cmd = commandtext(n);
6985 TRACE(("In parent shell: child = %d\n", pid));
6992 * Wait for job to finish.
6994 * Under job control we have the problem that while a child process is
6995 * running interrupts generated by the user are sent to the child but not
6996 * to the shell. This means that an infinite loop started by an inter-
6997 * active user may be hard to kill. With job control turned off, an
6998 * interactive user may place an interactive program inside a loop. If
6999 * the interactive program catches interrupts, the user doesn't want
7000 * these interrupts to also abort the loop. The approach we take here
7001 * is to have the shell ignore interrupt signals while waiting for a
7002 * forground process to terminate, and then send itself an interrupt
7003 * signal if the child process was terminated by an interrupt signal.
7004 * Unfortunately, some programs want to do a bit of cleanup and then
7005 * exit on interrupt; unless these processes terminate themselves by
7006 * sending a signal to themselves (instead of calling exit) they will
7007 * confuse this approach.
7011 waitforjob(struct job *jp)
7014 int mypgrp = getpgrp();
7018 struct sigaction act, oact;
7027 sigaction(SIGINT, 0, &act);
7028 act.sa_handler = waitonint;
7029 sigaction(SIGINT, &act, &oact);
7031 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
7032 while (jp->state == 0) {
7040 sigaction(SIGINT, &oact, 0);
7041 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
7045 #ifdef OLD_TTY_DRIVER
7046 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
7047 error("TIOCSPGRP failed, errno=%d\n", errno);
7049 if (tcsetpgrp(2, mypgrp) < 0)
7050 error("tcsetpgrp failed, errno=%d\n", errno);
7053 if (jp->state == JOBSTOPPED)
7054 curjob = jp - jobtab + 1;
7056 status = jp->ps[jp->nprocs - 1].status;
7057 /* convert to 8 bits */
7058 if (WIFEXITED(status))
7059 st = WEXITSTATUS(status);
7061 else if (WIFSTOPPED(status))
7062 st = WSTOPSIG(status) + 128;
7065 st = WTERMSIG(status) + 128;
7069 * This is truly gross.
7070 * If we're doing job control, then we did a TIOCSPGRP which
7071 * caused us (the shell) to no longer be in the controlling
7072 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
7073 * intuit from the subprocess exit status whether a SIGINT
7074 * occured, and if so interrupt ourselves. Yuck. - mycroft
7076 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
7079 if (jp->state == JOBDONE)
7090 * Wait for a process to terminate.
7094 * Do a wait system call. If job control is compiled in, we accept
7095 * stopped processes. If block is zero, we return a value of zero
7096 * rather than blocking.
7098 * System V doesn't have a non-blocking wait system call. It does
7099 * have a SIGCLD signal that is sent to a process when one of it's
7100 * children dies. The obvious way to use SIGCLD would be to install
7101 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
7102 * was received, and have waitproc bump another counter when it got
7103 * the status of a process. Waitproc would then know that a wait
7104 * system call would not block if the two counters were different.
7105 * This approach doesn't work because if a process has children that
7106 * have not been waited for, System V will send it a SIGCLD when it
7107 * installs a signal handler for SIGCLD. What this means is that when
7108 * a child exits, the shell will be sent SIGCLD signals continuously
7109 * until is runs out of stack space, unless it does a wait call before
7110 * restoring the signal handler. The code below takes advantage of
7111 * this (mis)feature by installing a signal handler for SIGCLD and
7112 * then checking to see whether it was called. If there are any
7113 * children to be waited for, it will be.
7118 waitproc(int block, int *status)
7129 return wait3(status, flags, (struct rusage *)NULL);
7133 dowait(int block, struct job *job)
7137 struct procstat *sp;
7139 struct job *thisjob;
7145 TRACE(("dowait(%d) called\n", block));
7147 pid = waitproc(block, &status);
7148 TRACE(("wait returns %d, status=%d\n", pid, status));
7149 } while (!(block & 2) && pid == -1 && errno == EINTR);
7154 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
7158 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
7161 if (sp->pid == pid) {
7162 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
7163 sp->status = status;
7166 if (sp->status == -1)
7168 else if (WIFSTOPPED(sp->status))
7171 if (stopped) { /* stopped or done */
7172 int state = done? JOBDONE : JOBSTOPPED;
7173 if (jp->state != state) {
7174 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
7177 if (done && curjob == jp - jobtab + 1)
7178 curjob = 0; /* no current job */
7185 if (! rootshell || ! iflag || (job && thisjob == job)) {
7186 core = WCOREDUMP(status);
7188 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
7191 if (WIFEXITED(status)) sig = 0;
7192 else sig = WTERMSIG(status);
7194 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
7196 out2fmt("%d: ", pid);
7198 if (sig == SIGTSTP && rootshell && iflag)
7200 (long)(job - jobtab + 1));
7202 if (sig < NSIG && sys_siglist[sig])
7203 out2str(sys_siglist[sig]);
7205 out2fmt("Signal %d", sig);
7207 out2str(" - core dumped");
7210 TRACE(("Not printing status: status=%d, sig=%d\n",
7214 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
7216 thisjob->changed = 1;
7225 * return 1 if there are stopped jobs, otherwise 0
7235 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7238 if (jp->state == JOBSTOPPED) {
7239 out2str("You have stopped jobs.\n");
7249 * Return a string identifying a command (to be printed by the
7253 static char *cmdnextc;
7254 static int cmdnleft;
7255 #define MAXCMDTEXT 200
7258 cmdputs(const char *s)
7269 while ((c = *p++) != '\0') {
7272 else if (c == CTLVAR) {
7277 } else if (c == '=' && subtype != 0) {
7278 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7280 } else if (c == CTLENDVAR) {
7282 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7283 cmdnleft++; /* ignore it */
7286 if (--cmdnleft <= 0) {
7296 //#define CMDTXT_TABLE
7299 * To collect a lot of redundant code in cmdtxt() case statements, we
7300 * implement a mini language here. Each type of node struct has an
7301 * associated instruction sequence that operates on its members via
7302 * their offsets. The instruction are pack in unsigned chars with
7303 * format IIDDDDDE where the bits are
7304 * I : part of the instruction opcode, which are
7305 * 00 : member is a pointer to another node -- process it recursively
7306 * 40 : member is a pointer to a char string -- output it
7307 * 80 : output the string whose index is stored in the data field
7308 * CC : flag signaling that this case needs external processing
7309 * D : data - either the (shifted) index of a fixed string to output or
7310 * the actual offset of the member to operate on in the struct
7311 * (since we assume bit 0 is set, the offset is not shifted)
7312 * E : flag signaling end of instruction sequence
7314 * WARNING: In order to handle larger offsets for 64bit archs, this code
7315 * assumes that no offset can be an odd number and stores the
7316 * end-of-instructions flag in bit 0.
7319 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7320 #define CMDTXT_CHARPTR 0x40
7321 #define CMDTXT_STRING 0x80
7322 #define CMDTXT_SPECIAL 0xC0
7323 #define CMDTXT_OFFSETMASK 0x3E
7325 static const char * const cmdtxt_strings[] = {
7326 /* 0 1 2 3 4 5 6 7 */
7327 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7328 /* 8 9 10 11 12 13 */
7329 "while ", "; do ", "; done", "until ", "for ", " in ...",
7331 "case ", "???", "() ...", "<<..."
7334 static const char * const redir_strings[] = {
7335 ">", "<", "<>", ">>", ">|", ">&", "<&"
7338 static const unsigned char cmdtxt_ops[] = {
7339 #define CMDTXT_NSEMI 0
7340 offsetof(union node, nbinary.ch1),
7342 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7343 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7344 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7345 #define CMDTXT_NCASE (CMDTXT_NCMD)
7346 #define CMDTXT_NTO (CMDTXT_NCMD)
7347 #define CMDTXT_NFROM (CMDTXT_NCMD)
7348 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7349 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7350 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7351 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7352 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7354 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7355 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7356 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7357 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7358 (1*2)|CMDTXT_STRING,
7359 offsetof(union node, nredir.n),
7360 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7361 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7362 offsetof(union node, nbinary.ch1),
7363 (3*2)|CMDTXT_STRING,
7364 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7365 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7366 offsetof(union node, nbinary.ch1),
7367 (4*2)|CMDTXT_STRING,
7368 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7369 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7370 (5*2)|CMDTXT_STRING,
7371 offsetof(union node, nif.test),
7372 (6*2)|CMDTXT_STRING,
7373 offsetof(union node, nif.ifpart),
7374 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7375 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7376 (8*2)|CMDTXT_STRING,
7377 offsetof(union node, nbinary.ch1),
7378 (9*2)|CMDTXT_STRING,
7379 offsetof(union node, nbinary.ch2),
7380 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7381 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7382 (11*2)|CMDTXT_STRING,
7383 offsetof(union node, nbinary.ch1),
7384 (9*2)|CMDTXT_STRING,
7385 offsetof(union node, nbinary.ch2),
7386 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7387 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7388 (12*2)|CMDTXT_STRING,
7389 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7390 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7391 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7392 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7393 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7394 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7395 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7396 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7397 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7398 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7399 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7400 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7401 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7404 #if CMDTXT_NXHERE != 36
7405 #error CMDTXT_NXHERE
7408 static const unsigned char cmdtxt_ops_index[26] = {
7438 cmdtxt(const union node *n)
7445 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7446 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7448 if (*p & CMDTXT_STRING) { /* output fixed string */
7449 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7451 const char *pf = ((const char *) n)
7452 + ((int)(*p & CMDTXT_OFFSETMASK));
7453 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7454 cmdputs(*((const char **) pf));
7455 } else { /* output field */
7456 cmdtxt(*((const union node **) pf));
7459 } while (!(*p++ & CMDTXT_NOMORE));
7460 } else if (n->type == NCMD) {
7462 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7467 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7471 } else if (n->type == NPIPE) {
7472 struct nodelist *lp;
7473 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7478 } else if (n->type == NCASE) {
7479 cmdputs(cmdtxt_strings[14]);
7480 cmdputs(n->ncase.expr->narg.text);
7481 cmdputs(cmdtxt_strings[13]);
7483 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7484 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7489 assert((n->type >= NTO) && (n->type <= NFROMFD));
7492 p = redir_strings[n->type - NTO];
7493 if (n->nfile.fd != ('>' == *p)) {
7494 s[0] = n->nfile.fd + '0';
7499 if (n->type >= NTOFD) {
7500 s[0] = n->ndup.dupfd + '0';
7504 cmdtxt(n->nfile.fname);
7508 #else /* CMDTXT_TABLE */
7510 cmdtxt(const union node *n)
7513 struct nodelist *lp;
7522 cmdtxt(n->nbinary.ch1);
7524 cmdtxt(n->nbinary.ch2);
7527 cmdtxt(n->nbinary.ch1);
7529 cmdtxt(n->nbinary.ch2);
7532 cmdtxt(n->nbinary.ch1);
7534 cmdtxt(n->nbinary.ch2);
7537 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7545 cmdtxt(n->nredir.n);
7550 cmdtxt(n->nredir.n);
7554 cmdtxt(n->nif.test);
7556 cmdtxt(n->nif.ifpart);
7565 cmdtxt(n->nbinary.ch1);
7567 cmdtxt(n->nbinary.ch2);
7572 cmdputs(n->nfor.var);
7577 cmdputs(n->ncase.expr->narg.text);
7581 cmdputs(n->narg.text);
7585 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7590 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7596 cmdputs(n->narg.text);
7599 p = ">"; i = 1; goto redir;
7601 p = ">>"; i = 1; goto redir;
7603 p = ">&"; i = 1; goto redir;
7605 p = ">|"; i = 1; goto redir;
7607 p = "<"; i = 0; goto redir;
7609 p = "<&"; i = 0; goto redir;
7611 p = "<>"; i = 0; goto redir;
7613 if (n->nfile.fd != i) {
7614 s[0] = n->nfile.fd + '0';
7619 if (n->type == NTOFD || n->type == NFROMFD) {
7620 s[0] = n->ndup.dupfd + '0';
7624 cmdtxt(n->nfile.fname);
7636 #endif /* CMDTXT_TABLE */
7639 commandtext(const union node *n)
7643 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7644 cmdnleft = MAXCMDTEXT - 4;
7651 static void waitonint(int sig) {
7656 * Routines to check for mail. (Perhaps make part of main.c?)
7660 #define MAXMBOXES 10
7663 static int nmboxes; /* number of mailboxes */
7664 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7669 * Print appropriate message(s) if mail has arrived. If the argument is
7670 * nozero, then the value of MAIL has changed, so we just update the
7681 struct stackmark smark;
7688 setstackmark(&smark);
7689 mpath = mpathset()? mpathval() : mailval();
7690 for (i = 0 ; i < nmboxes ; i++) {
7691 p = padvance(&mpath, nullstr);
7696 for (q = p ; *q ; q++);
7701 q[-1] = '\0'; /* delete trailing '/' */
7702 if (stat(p, &statb) < 0)
7704 if (statb.st_size > mailtime[i] && ! silent) {
7706 pathopt? pathopt : "you have mail");
7708 mailtime[i] = statb.st_size;
7711 popstackmark(&smark);
7717 static short profile_buf[16384];
7721 static void read_profile (const char *);
7722 static void cmdloop (int);
7723 static void options (int);
7724 static void setoption (int, int);
7725 static void procargs (int, char **);
7729 * Main routine. We initialize things, parse the arguments, execute
7730 * profiles if we're a login shell, and then call cmdloop to execute
7731 * commands. The setjmp call sets up the location to jump to when an
7732 * exception occurs. When an exception occurs the variable "state"
7733 * is used to figure out how far we had gotten.
7737 ash_main(argc, argv)
7741 struct jmploc jmploc;
7742 struct stackmark smark;
7746 BLTINCMD = find_builtin("builtin");
7747 EXECCMD = find_builtin("exec");
7748 EVALCMD = find_builtin("eval");
7750 #ifndef BB_FEATURE_SH_FANCY_PROMPT
7756 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7758 #if defined(linux) || defined(__GNU__)
7759 signal(SIGCHLD, SIG_DFL);
7762 if (setjmp(jmploc.loc)) {
7765 * When a shell procedure is executed, we raise the
7766 * exception EXSHELLPROC to clean up before executing
7767 * the shell procedure.
7769 if (exception == EXSHELLPROC) {
7775 if (exception == EXEXEC) {
7776 exitstatus = exerrno;
7777 } else if (exception == EXERROR) {
7780 if (state == 0 || iflag == 0 || ! rootshell)
7781 exitshell(exitstatus);
7784 if (exception == EXINT) {
7787 popstackmark(&smark);
7788 FORCEINTON; /* enable interrupts */
7791 else if (state == 2)
7793 else if (state == 3)
7801 trputs("Shell args: "); trargs(argv);
7806 setstackmark(&smark);
7807 procargs(argc, argv);
7808 if (argv[0] && argv[0][0] == '-') {
7810 read_profile("/etc/profile");
7813 read_profile(".profile");
7818 if (getuid() == geteuid() && getgid() == getegid()) {
7820 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7822 read_profile(shinit);
7829 if (sflag == 0 || minusc) {
7830 static const char sigs[] = {
7831 SIGINT, SIGQUIT, SIGHUP,
7837 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7840 for (i = 0; i < SIGSSIZE; i++)
7845 evalstring(minusc, 0);
7847 if (sflag || minusc == NULL) {
7848 state4: /* XXX ??? - why isn't this before the "if" statement */
7854 exitshell(exitstatus);
7860 * Read and execute commands. "Top" is nonzero for the top level command
7861 * loop; it turns on prompting if the shell is interactive.
7868 struct stackmark smark;
7872 TRACE(("cmdloop(%d) called\n", top));
7873 setstackmark(&smark);
7884 n = parsecmd(inter);
7885 /* showtree(n); DEBUG */
7887 if (!top || numeof >= 50)
7889 if (!stoppedjobs()) {
7892 out2str("\nUse \"exit\" to leave shell.\n");
7895 } else if (n != NULL && nflag == 0) {
7896 job_warning = (job_warning == 2) ? 1 : 0;
7900 popstackmark(&smark);
7901 setstackmark(&smark);
7902 if (evalskip == SKIPFILE) {
7907 popstackmark(&smark);
7913 * Read /etc/profile or .profile. Return on error.
7925 if ((fd = open(name, O_RDONLY)) >= 0)
7930 /* -q turns off -x and -v just when executing init files */
7931 /* Note: Might do a little redundant work, but reduces code size. */
7946 * Read a file containing shell functions.
7950 readcmdfile(const char *name)
7955 if ((fd = open(name, O_RDONLY)) >= 0)
7958 error("Can't open %s", name);
7967 * Take commands from a file. To be compatable we should do a path
7968 * search for the file, which is necessary to find sub-commands.
7972 static inline char *
7973 find_dot_file(mybasename)
7977 const char *path = pathval();
7980 /* don't try this for absolute or relative paths */
7981 if (strchr(mybasename, '/'))
7984 while ((fullname = padvance(&path, mybasename)) != NULL) {
7985 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7987 * Don't bother freeing here, since it will
7988 * be freed by the caller.
7992 stunalloc(fullname);
7995 /* not found in the PATH */
7996 error("%s: not found", mybasename);
8008 for (sp = cmdenviron; sp ; sp = sp->next)
8009 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
8011 if (argc >= 2) { /* That's what SVR2 does */
8013 struct stackmark smark;
8015 setstackmark(&smark);
8016 fullname = find_dot_file(argv[1]);
8017 setinputfile(fullname, 1);
8018 commandname = fullname;
8021 popstackmark(&smark);
8035 exitstatus = number(argv[1]);
8037 exitstatus = oexitstatus;
8038 exitshell(exitstatus);
8047 nbytes = ALIGN(nbytes);
8048 if (nbytes > stacknleft) {
8050 struct stack_block *sp;
8053 if (blocksize < MINSIZE)
8054 blocksize = MINSIZE;
8056 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
8058 stacknxt = sp->space;
8059 stacknleft = blocksize;
8065 stacknleft -= nbytes;
8071 stunalloc(pointer p)
8074 if (p == NULL) { /*DEBUG */
8075 write(2, "stunalloc\n", 10);
8079 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
8082 stacknleft += stacknxt - (char *)p;
8088 setstackmark(struct stackmark *mark)
8090 mark->stackp = stackp;
8091 mark->stacknxt = stacknxt;
8092 mark->stacknleft = stacknleft;
8093 mark->marknext = markp;
8099 popstackmark(struct stackmark *mark)
8101 struct stack_block *sp;
8104 markp = mark->marknext;
8105 while (stackp != mark->stackp) {
8110 stacknxt = mark->stacknxt;
8111 stacknleft = mark->stacknleft;
8117 * When the parser reads in a string, it wants to stick the string on the
8118 * stack and only adjust the stack pointer when it knows how big the
8119 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8120 * of space on top of the stack and stackblocklen returns the length of
8121 * this block. Growstackblock will grow this space by at least one byte,
8122 * possibly moving it (like realloc). Grabstackblock actually allocates the
8123 * part of the block that has been used.
8127 growstackblock(void) {
8129 int newlen = ALIGN(stacknleft * 2 + 100);
8130 char *oldspace = stacknxt;
8131 int oldlen = stacknleft;
8132 struct stack_block *sp;
8133 struct stack_block *oldstackp;
8135 if (stacknxt == stackp->space && stackp != &stackbase) {
8140 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8143 stacknxt = sp->space;
8144 stacknleft = newlen;
8146 /* Stack marks pointing to the start of the old block
8147 * must be relocated to point to the new block
8149 struct stackmark *xmark;
8151 while (xmark != NULL && xmark->stackp == oldstackp) {
8152 xmark->stackp = stackp;
8153 xmark->stacknxt = stacknxt;
8154 xmark->stacknleft = stacknleft;
8155 xmark = xmark->marknext;
8160 p = stalloc(newlen);
8161 memcpy(p, oldspace, oldlen);
8162 stacknxt = p; /* free the space */
8163 stacknleft += newlen; /* we just allocated */
8170 grabstackblock(int len)
8180 * The following routines are somewhat easier to use that the above.
8181 * The user declares a variable of type STACKSTR, which may be declared
8182 * to be a register. The macro STARTSTACKSTR initializes things. Then
8183 * the user uses the macro STPUTC to add characters to the string. In
8184 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8185 * grown as necessary. When the user is done, she can just leave the
8186 * string there and refer to it using stackblock(). Or she can allocate
8187 * the space for it using grabstackstr(). If it is necessary to allow
8188 * someone else to use the stack temporarily and then continue to grow
8189 * the string, the user should use grabstack to allocate the space, and
8190 * then call ungrabstr(p) to return to the previous mode of operation.
8192 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8193 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8194 * is space for at least one character.
8199 growstackstr(void) {
8200 int len = stackblocksize();
8201 if (herefd >= 0 && len >= 1024) {
8202 xwrite(herefd, stackblock(), len);
8203 sstrnleft = len - 1;
8204 return stackblock();
8207 sstrnleft = stackblocksize() - len - 1;
8208 return stackblock() + len;
8213 * Called from CHECKSTRSPACE.
8217 makestrspace(size_t newlen) {
8218 int len = stackblocksize() - sstrnleft;
8221 sstrnleft = stackblocksize() - len;
8222 } while (sstrnleft < newlen);
8223 return stackblock() + len;
8229 ungrabstackstr(char *s, char *p)
8231 stacknleft += stacknxt - s;
8233 sstrnleft = stacknleft - (p - s);
8236 * Miscelaneous builtins.
8242 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8243 typedef long rlim_t;
8249 * The read builtin. The -e option causes backslashes to escape the
8250 * following character.
8252 * This uses unbuffered input, which may be avoidable in some cases.
8256 readcmd(int argc, char **argv)
8271 while ((i = nextopt("p:r")) != '\0') {
8277 if (prompt && isatty(0)) {
8278 out2str(prompt); /* read without cmdedit */
8281 if (*(ap = argptr) == NULL)
8283 if ((ifs = bltinlookup("IFS")) == NULL)
8290 if (read(0, &c, 1) != 1) {
8302 if (!rflag && c == '\\') {
8308 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8312 if (backslash && c == '\\') {
8313 if (read(0, &c, 1) != 1) {
8318 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8320 setvar(*ap, stackblock(), 0);
8329 /* Remove trailing blanks */
8330 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8332 setvar(*ap, stackblock(), 0);
8333 while (*++ap != NULL)
8334 setvar(*ap, nullstr, 0);
8341 umaskcmd(argc, argv)
8345 static const char permuser[3] = "ugo";
8346 static const char permmode[3] = "rwx";
8347 static const short int permmask[] = {
8348 S_IRUSR, S_IWUSR, S_IXUSR,
8349 S_IRGRP, S_IWGRP, S_IXGRP,
8350 S_IROTH, S_IWOTH, S_IXOTH
8356 int symbolic_mode = 0;
8358 while (nextopt("S") != '\0') {
8367 if ((ap = *argptr) == NULL) {
8368 if (symbolic_mode) {
8371 for (i=0 ; i<3 ; i++) {
8375 for (j=0 ; j<3 ; j++) {
8376 if ((mask & permmask[3*i+j]) == 0) {
8385 printf("%.4o\n", mask);
8388 if (is_digit((unsigned char)*ap)) {
8391 if (*ap >= '8' || *ap < '0')
8392 error("Illegal number: %s", argv[1]);
8393 mask = (mask << 3) + (*ap - '0');
8394 } while (*++ap != '\0');
8397 mask = ~mask & 0777;
8398 if (parse_mode(ap, &mask) == FALSE) {
8399 error("Illegal mode: %s", ap);
8401 umask(~mask & 0777);
8410 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8411 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8412 * ash by J.T. Conklin.
8420 short factor; /* multiply by to get rlim_{cur,max} values */
8423 static const struct limits limits[] = {
8425 { "time(seconds)", RLIMIT_CPU, 1 },
8428 { "file(blocks)", RLIMIT_FSIZE, 512 },
8431 { "data(kbytes)", RLIMIT_DATA, 1024 },
8434 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8437 { "coredump(blocks)", RLIMIT_CORE, 512 },
8440 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8442 #ifdef RLIMIT_MEMLOCK
8443 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8446 { "process(processes)", RLIMIT_NPROC, 1 },
8448 #ifdef RLIMIT_NOFILE
8449 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8452 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8455 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8461 ulimitcmd(argc, argv)
8465 static const char unlimited_string[] = "unlimited";
8468 enum { SOFT = 0x1, HARD = 0x2 }
8470 const struct limits *l;
8473 struct rlimit limit;
8477 while ((optc = nextopt("HSa"
8496 #ifdef RLIMIT_MEMLOCK
8502 #ifdef RLIMIT_NOFILE
8514 } else if (optc == 'S') {
8516 } else if (optc == 'a') {
8523 for (l = limits; l->name; l++) {
8524 if(l->name[0] == what)
8526 if(l->name[1]=='w' && what=='w')
8530 set = *argptr ? 1 : 0;
8534 if (all || argptr[1])
8535 error("too many arguments");
8536 if (strcmp(p, unlimited_string) == 0)
8537 val = RLIM_INFINITY;
8541 while ((c = *p++) >= '0' && c <= '9')
8543 val = (val * 10) + (long)(c - '0');
8544 if (val < (rlim_t) 0)
8548 error("bad number");
8554 for (l = limits; l->name; l++) {
8555 printf("%-20s ", l->name);
8556 getrlimit(l->cmd, &limit);
8559 val = limit.rlim_cur;
8560 else if (how & HARD)
8561 val = limit.rlim_max;
8563 if (val == RLIM_INFINITY)
8564 puts(unlimited_string);
8568 printf("%lld\n", (long long) val);
8581 getrlimit(l->cmd, &limit);
8583 limit.rlim_max = val;
8585 limit.rlim_cur = val;
8586 if (setrlimit(l->cmd, &limit) < 0)
8587 error("error setting limit (%m)");
8591 * prefix -- see if pfx is a prefix of string.
8595 prefix(char const *pfx, char const *string)
8598 if (*pfx++ != *string++)
8605 * Return true if s is a string of digits, and save munber in intptr
8610 is_number(const char *p, int *intptr)
8618 ret += digit_val(*p);
8620 } while (*p != '\0');
8627 * Convert a string of digits to an integer, printing an error message on
8632 number(const char *s)
8635 if (! is_number(s, &i))
8636 error("Illegal number: %s", s);
8641 * Produce a possibly single quoted string suitable as input to the shell.
8642 * The return string is allocated on the stack.
8646 single_quote(const char *s) {
8653 size_t len1, len1p, len2, len2p;
8655 len1 = strcspn(s, "'");
8656 len2 = strspn(s + len1, "'");
8658 len1p = len1 ? len1 + 2 : len1;
8659 len2p = len2 + ((len2 < 2) ? len2 : 2);
8661 CHECKSTRSPACE(len1p + len2p + 1, p);
8666 memcpy(p + 1, s, len1);
8674 memcpy(q + 1, s, len2);
8677 } else if (len2 == 1) {
8683 STADJUST(len1p + len2p, p);
8688 return grabstackstr(p);
8692 * Like strdup but works with the ash stack.
8696 sstrdup(const char *p)
8698 size_t len = strlen(p) + 1;
8699 return memcpy(stalloc(len), p, len);
8704 * Routine for dealing with parsed shell commands.
8708 static void sizenodelist (const struct nodelist *);
8709 static struct nodelist *copynodelist (const struct nodelist *);
8710 static char *nodesavestr (const char *);
8712 //#define CALCSIZE_TABLE
8713 //#define COPYNODE_TABLE
8714 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8716 * To collect a lot of redundant code in case statements for copynode()
8717 * and calcsize(), we implement a mini language here. Each type of node
8718 * struct has an associated instruction sequence that operates on its
8719 * members via their offsets. The instruction are pack in unsigned chars
8720 * with format IIDDDDDE where the bits are
8721 * I : part of the instruction opcode, which are
8722 * 00 : member is a pointer to another node
8723 * 40 : member is an integer
8724 * 80 : member is a pointer to a nodelist
8725 * CC : member is a pointer to a char string
8726 * D : data - the actual offset of the member to operate on in the struct
8727 * (since we assume bit 0 is set, it is not shifted)
8728 * E : flag signaling end of instruction sequence
8730 * WARNING: In order to handle larger offsets for 64bit archs, this code
8731 * assumes that no offset can be an odd number and stores the
8732 * end-of-instructions flag in bit 0.
8735 #define NODE_INTEGER 0x40
8736 #define NODE_NODELIST 0x80
8737 #define NODE_CHARPTR 0xC0
8738 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8739 #define NODE_MBRMASK 0xC0
8740 #define NODE_OFFSETMASK 0x3E
8742 static const unsigned char copynode_ops[35] = {
8743 #define COPYNODE_OPS0 0
8744 offsetof(union node, nbinary.ch2),
8745 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8746 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8747 offsetof(union node, ncmd.redirect),
8748 offsetof(union node, ncmd.args),
8749 offsetof(union node, ncmd.assign),
8750 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8751 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8752 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8753 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8754 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8755 offsetof(union node, nredir.redirect),
8756 offsetof(union node, nredir.n)|NODE_NOMORE,
8757 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8758 offsetof(union node, nif.elsepart),
8759 offsetof(union node, nif.ifpart),
8760 offsetof(union node, nif.test)|NODE_NOMORE,
8761 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8762 offsetof(union node, nfor.var)|NODE_CHARPTR,
8763 offsetof(union node, nfor.body),
8764 offsetof(union node, nfor.args)|NODE_NOMORE,
8765 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8766 offsetof(union node, ncase.cases),
8767 offsetof(union node, ncase.expr)|NODE_NOMORE,
8768 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8769 offsetof(union node, nclist.body),
8770 offsetof(union node, nclist.pattern),
8771 offsetof(union node, nclist.next)|NODE_NOMORE,
8772 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8773 offsetof(union node, narg.backquote)|NODE_NODELIST,
8774 offsetof(union node, narg.text)|NODE_CHARPTR,
8775 offsetof(union node, narg.next)|NODE_NOMORE,
8776 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8777 offsetof(union node, nfile.fname),
8778 offsetof(union node, nfile.fd)|NODE_INTEGER,
8779 offsetof(union node, nfile.next)|NODE_NOMORE,
8780 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8781 offsetof(union node, ndup.vname),
8782 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8783 offsetof(union node, ndup.fd)|NODE_INTEGER,
8784 offsetof(union node, ndup.next)|NODE_NOMORE,
8785 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8786 offsetof(union node, nhere.doc),
8787 offsetof(union node, nhere.fd)|NODE_INTEGER,
8788 offsetof(union node, nhere.next)|NODE_NOMORE,
8789 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8790 offsetof(union node, nnot.com)|NODE_NOMORE,
8793 #if COPYNODE_OPS12 != 34
8794 #error COPYNODE_OPS12 is incorrect
8797 static const unsigned char copynode_ops_index[26] = {
8798 COPYNODE_OPS0, /* NSEMI */
8799 COPYNODE_OPS1, /* NCMD */
8800 COPYNODE_OPS2, /* NPIPE */
8801 COPYNODE_OPS3, /* NREDIR */
8802 COPYNODE_OPS3, /* NBACKGND */
8803 COPYNODE_OPS3, /* NSUBSHELL */
8804 COPYNODE_OPS0, /* NAND */
8805 COPYNODE_OPS0, /* NOR */
8806 COPYNODE_OPS4, /* NIF */
8807 COPYNODE_OPS0, /* NWHILE */
8808 COPYNODE_OPS0, /* NUNTIL */
8809 COPYNODE_OPS5, /* NFOR */
8810 COPYNODE_OPS6, /* NCASE */
8811 COPYNODE_OPS7, /* NCLIST */
8812 COPYNODE_OPS8, /* NDEFUN */
8813 COPYNODE_OPS8, /* NARG */
8814 COPYNODE_OPS9, /* NTO */
8815 COPYNODE_OPS9, /* NFROM */
8816 COPYNODE_OPS9, /* NFROMTO */
8817 COPYNODE_OPS9, /* NAPPEND */
8818 COPYNODE_OPS9, /* NTOOV */
8819 COPYNODE_OPS10, /* NTOFD */
8820 COPYNODE_OPS10, /* NFROMFD */
8821 COPYNODE_OPS11, /* NHERE */
8822 COPYNODE_OPS11, /* NXHERE */
8823 COPYNODE_OPS12, /* NNOT */
8826 #if NODE_CHARPTR != NODE_MBRMASK
8827 #error NODE_CHARPTR != NODE_MBRMASK!!!
8829 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8831 #ifdef COPYNODE_TABLE
8833 copynode(const union node *n)
8836 const unsigned char *p;
8842 new->type = n->type;
8843 funcblock = (char *) funcblock + (int) nodesize[n->type];
8844 p = copynode_ops + (int) copynode_ops_index[n->type];
8846 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8847 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8849 if (!(*p & NODE_MBRMASK)) { /* standard node */
8850 *((union node **)nn) = copynode(*((const union node **) no));
8851 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8852 *((const char **)nn) = nodesavestr(*((const char **)no));
8853 } else if (*p & NODE_NODELIST) { /* nodelist */
8854 *((struct nodelist **)nn)
8855 = copynodelist(*((const struct nodelist **) no));
8856 } else { /* integer */
8857 *((int *) nn) = *((int *) no);
8859 } while (!(*p++ & NODE_NOMORE));
8862 #else /* COPYNODE_TABLE */
8864 copynode(const union node *n)
8871 funcblock = (char *) funcblock + nodesize[n->type];
8878 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8879 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8882 new->ncmd.redirect = copynode(n->ncmd.redirect);
8883 new->ncmd.args = copynode(n->ncmd.args);
8884 new->ncmd.assign = copynode(n->ncmd.assign);
8885 new->ncmd.backgnd = n->ncmd.backgnd;
8888 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8889 new->npipe.backgnd = n->npipe.backgnd;
8894 new->nredir.redirect = copynode(n->nredir.redirect);
8895 new->nredir.n = copynode(n->nredir.n);
8898 new->nif.elsepart = copynode(n->nif.elsepart);
8899 new->nif.ifpart = copynode(n->nif.ifpart);
8900 new->nif.test = copynode(n->nif.test);
8903 new->nfor.var = nodesavestr(n->nfor.var);
8904 new->nfor.body = copynode(n->nfor.body);
8905 new->nfor.args = copynode(n->nfor.args);
8908 new->ncase.cases = copynode(n->ncase.cases);
8909 new->ncase.expr = copynode(n->ncase.expr);
8912 new->nclist.body = copynode(n->nclist.body);
8913 new->nclist.pattern = copynode(n->nclist.pattern);
8914 new->nclist.next = copynode(n->nclist.next);
8918 new->narg.backquote = copynodelist(n->narg.backquote);
8919 new->narg.text = nodesavestr(n->narg.text);
8920 new->narg.next = copynode(n->narg.next);
8927 new->nfile.fname = copynode(n->nfile.fname);
8928 new->nfile.fd = n->nfile.fd;
8929 new->nfile.next = copynode(n->nfile.next);
8933 new->ndup.vname = copynode(n->ndup.vname);
8934 new->ndup.dupfd = n->ndup.dupfd;
8935 new->ndup.fd = n->ndup.fd;
8936 new->ndup.next = copynode(n->ndup.next);
8940 new->nhere.doc = copynode(n->nhere.doc);
8941 new->nhere.fd = n->nhere.fd;
8942 new->nhere.next = copynode(n->nhere.next);
8945 new->nnot.com = copynode(n->nnot.com);
8948 new->type = n->type;
8951 #endif /* COPYNODE_TABLE */
8953 #ifdef CALCSIZE_TABLE
8955 calcsize(const union node *n)
8957 const unsigned char *p;
8961 funcblocksize += (int) nodesize[n->type];
8963 p = copynode_ops + (int) copynode_ops_index[n->type];
8965 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8967 if (!(*p & NODE_MBRMASK)) { /* standard node */
8968 calcsize(*((const union node **) no));
8969 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8970 funcstringsize += strlen(*((const char **)no)) + 1;
8971 } else if (*p & NODE_NODELIST) { /* nodelist */
8972 sizenodelist(*((const struct nodelist **) no));
8973 } /* else integer -- ignore */
8974 } while (!(*p++ & NODE_NOMORE));
8976 #else /* CALCSIZE_TABLE */
8978 calcsize(const union node *n)
8982 funcblocksize += nodesize[n->type];
8989 calcsize(n->nbinary.ch2);
8990 calcsize(n->nbinary.ch1);
8993 calcsize(n->ncmd.redirect);
8994 calcsize(n->ncmd.args);
8995 calcsize(n->ncmd.assign);
8998 sizenodelist(n->npipe.cmdlist);
9003 calcsize(n->nredir.redirect);
9004 calcsize(n->nredir.n);
9007 calcsize(n->nif.elsepart);
9008 calcsize(n->nif.ifpart);
9009 calcsize(n->nif.test);
9012 funcstringsize += strlen(n->nfor.var) + 1;
9013 calcsize(n->nfor.body);
9014 calcsize(n->nfor.args);
9017 calcsize(n->ncase.cases);
9018 calcsize(n->ncase.expr);
9021 calcsize(n->nclist.body);
9022 calcsize(n->nclist.pattern);
9023 calcsize(n->nclist.next);
9027 sizenodelist(n->narg.backquote);
9028 funcstringsize += strlen(n->narg.text) + 1;
9029 calcsize(n->narg.next);
9036 calcsize(n->nfile.fname);
9037 calcsize(n->nfile.next);
9041 calcsize(n->ndup.vname);
9042 calcsize(n->ndup.next);
9046 calcsize(n->nhere.doc);
9047 calcsize(n->nhere.next);
9050 calcsize(n->nnot.com);
9054 #endif /* CALCSIZE_TABLE */
9057 sizenodelist(const struct nodelist *lp)
9060 funcblocksize += ALIGN(sizeof(struct nodelist));
9067 static struct nodelist *
9068 copynodelist(const struct nodelist *lp)
9070 struct nodelist *start;
9071 struct nodelist **lpp;
9076 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
9077 (*lpp)->n = copynode(lp->n);
9079 lpp = &(*lpp)->next;
9087 nodesavestr(const char *s)
9090 char *q = funcstring;
9091 char *rtn = funcstring;
9093 while ((*q++ = *p++) != '\0')
9100 static int getopts (char *, char *, char **, int *, int *);
9105 * Process the shell command line arguments.
9109 procargs(argc, argv)
9118 for (i = 0; i < NOPTS; i++)
9121 if (*argptr == NULL && minusc == NULL)
9123 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
9127 for (i = 0; i < NOPTS; i++)
9128 if (optent_val(i) == 2)
9131 if (sflag == 0 && minusc == NULL) {
9132 commandname = argv[0];
9134 setinputfile(arg0, 0);
9137 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
9138 if (argptr && minusc && *argptr)
9141 shellparam.p = argptr;
9142 shellparam.optind = 1;
9143 shellparam.optoff = -1;
9144 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9146 shellparam.nparam++;
9155 * Process shell options. The global variable argptr contains a pointer
9156 * to the argument list; we advance it past the options.
9160 minus_o(const char *name, int val)
9165 out1str("Current option settings\n");
9166 for (i = 0; i < NOPTS; i++)
9167 printf("%-16s%s\n", optent_name(optlist[i]),
9168 optent_val(i) ? "on" : "off");
9170 for (i = 0; i < NOPTS; i++)
9171 if (equal(name, optent_name(optlist[i]))) {
9172 setoption(optent_letter(optlist[i]), val);
9175 error("Illegal option -o %s", name);
9181 options(int cmdline)
9189 while ((p = *argptr) != NULL) {
9191 if ((c = *p++) == '-') {
9193 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9195 /* "-" means turn off -x and -v */
9198 /* "--" means reset params */
9199 else if (*argptr == NULL)
9202 break; /* "-" or "--" terminates options */
9204 } else if (c == '+') {
9210 while ((c = *p++) != '\0') {
9211 if (c == 'c' && cmdline) {
9213 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9217 if (q == NULL || minusc != NULL)
9218 error("Bad -c option");
9223 } else if (c == 'o') {
9224 minus_o(*argptr, val);
9236 setoption(int flag, int val)
9240 for (i = 0; i < NOPTS; i++)
9241 if (optent_letter(optlist[i]) == flag) {
9242 optent_val(i) = val;
9244 /* #%$ hack for ksh semantics */
9247 else if (flag == 'E')
9252 error("Illegal option -%c", flag);
9259 * Set the shell parameters.
9263 setparam(char **argv)
9269 for (nparam = 0 ; argv[nparam] ; nparam++);
9270 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9272 *ap++ = savestr(*argv++);
9275 freeparam(&shellparam);
9276 shellparam.malloc = 1;
9277 shellparam.nparam = nparam;
9278 shellparam.p = newparam;
9279 shellparam.optind = 1;
9280 shellparam.optoff = -1;
9285 * Free the list of positional parameters.
9289 freeparam(volatile struct shparam *param)
9293 if (param->malloc) {
9294 for (ap = param->p ; *ap ; ap++)
9303 * The shift builtin command.
9307 shiftcmd(argc, argv)
9316 n = number(argv[1]);
9317 if (n > shellparam.nparam)
9318 error("can't shift that many");
9320 shellparam.nparam -= n;
9321 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9322 if (shellparam.malloc)
9326 while ((*ap2++ = *ap1++) != NULL);
9327 shellparam.optind = 1;
9328 shellparam.optoff = -1;
9336 * The set command builtin.
9345 return showvarscmd(argc, argv);
9349 if (*argptr != NULL) {
9358 getoptsreset(const char *value)
9360 shellparam.optind = number(value);
9361 shellparam.optoff = -1;
9364 #ifdef BB_LOCALE_SUPPORT
9365 static void change_lc_all(const char *value)
9367 if(value != 0 && *value != 0)
9368 setlocale(LC_ALL, value);
9371 static void change_lc_ctype(const char *value)
9373 if(value != 0 && *value != 0)
9374 setlocale(LC_CTYPE, value);
9381 * The getopts builtin. Shellparam.optnext points to the next argument
9382 * to be processed. Shellparam.optptr points to the next character to
9383 * be processed in the current argument. If shellparam.optnext is NULL,
9384 * then it's the first time getopts has been called.
9388 getoptscmd(argc, argv)
9395 error("Usage: getopts optstring var [arg]");
9396 else if (argc == 3) {
9397 optbase = shellparam.p;
9398 if (shellparam.optind > shellparam.nparam + 1) {
9399 shellparam.optind = 1;
9400 shellparam.optoff = -1;
9405 if (shellparam.optind > argc - 2) {
9406 shellparam.optind = 1;
9407 shellparam.optoff = -1;
9411 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9412 &shellparam.optoff);
9416 * Safe version of setvar, returns 1 on success 0 on failure.
9420 setvarsafe(name, val, flags)
9421 const char *name, *val;
9424 struct jmploc jmploc;
9425 struct jmploc *volatile savehandler = handler;
9431 if (setjmp(jmploc.loc))
9435 setvar(name, val, flags);
9437 handler = savehandler;
9442 getopts(optstr, optvar, optfirst, myoptind, optoff)
9454 char **optnext = optfirst + *myoptind - 1;
9456 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9457 strlen(*(optnext - 1)) < *optoff)
9460 p = *(optnext - 1) + *optoff;
9461 if (p == NULL || *p == '\0') {
9462 /* Current word is done, advance */
9463 if (optnext == NULL)
9466 if (p == NULL || *p != '-' || *++p == '\0') {
9468 *myoptind = optnext - optfirst + 1;
9474 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9479 for (q = optstr; *q != c; ) {
9481 if (optstr[0] == ':') {
9484 err |= setvarsafe("OPTARG", s, 0);
9487 out2fmt("Illegal option -%c\n", c);
9488 (void) unsetvar("OPTARG");
9498 if (*p == '\0' && (p = *optnext) == NULL) {
9499 if (optstr[0] == ':') {
9502 err |= setvarsafe("OPTARG", s, 0);
9506 out2fmt("No arg for -%c option\n", c);
9507 (void) unsetvar("OPTARG");
9515 setvarsafe("OPTARG", p, 0);
9519 setvarsafe("OPTARG", "", 0);
9520 *myoptind = optnext - optfirst + 1;
9527 *optoff = p ? p - *(optnext - 1) : -1;
9528 snprintf(s, sizeof(s), "%d", *myoptind);
9529 err |= setvarsafe("OPTIND", s, VNOFUNC);
9532 err |= setvarsafe(optvar, s, 0);
9543 * XXX - should get rid of. have all builtins use getopt(3). the
9544 * library getopt must have the BSD extension static variable "optreset"
9545 * otherwise it can't be used within the shell safely.
9547 * Standard option processing (a la getopt) for builtin routines. The
9548 * only argument that is passed to nextopt is the option string; the
9549 * other arguments are unnecessary. It return the character, or '\0' on
9554 nextopt(const char *optstring)
9560 if ((p = optptr) == NULL || *p == '\0') {
9562 if (p == NULL || *p != '-' || *++p == '\0')
9565 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9569 for (q = optstring ; *q != c ; ) {
9571 error("Illegal option -%c", c);
9576 if (*p == '\0' && (p = *argptr++) == NULL)
9577 error("No arg for -%c option", c);
9594 out2fmt(const char *fmt, ...)
9598 vfprintf(stderr, fmt, ap);
9603 * Version of write which resumes after a signal is caught.
9607 xwrite(int fd, const char *buf, int nbytes)
9616 i = write(fd, buf, n);
9622 } else if (i == 0) {
9625 } else if (errno != EINTR) {
9633 * Shell command parser.
9636 #define EOFMARKLEN 79
9641 struct heredoc *next; /* next here document in list */
9642 union node *here; /* redirection node */
9643 char *eofmark; /* string indicating end of input */
9644 int striptabs; /* if set, strip leading tabs */
9647 static struct heredoc *heredoclist; /* list of here documents to read */
9648 static int parsebackquote; /* nonzero if we are inside backquotes */
9649 static int doprompt; /* if set, prompt the user */
9650 static int needprompt; /* true if interactive and at start of line */
9651 static int lasttoken; /* last token read */
9653 static char *wordtext; /* text of last word returned by readtoken */
9655 static struct nodelist *backquotelist;
9656 static union node *redirnode;
9657 static struct heredoc *heredoc;
9658 static int quoteflag; /* set if (part of) last token was quoted */
9659 static int startlinno; /* line # where last token started */
9662 static union node *list (int);
9663 static union node *andor (void);
9664 static union node *pipeline (void);
9665 static union node *command (void);
9666 static union node *simplecmd (void);
9667 static void parsefname (void);
9668 static void parseheredoc (void);
9669 static char peektoken (void);
9670 static int readtoken (void);
9671 static int xxreadtoken (void);
9672 static int readtoken1 (int, int, const char *, int);
9673 static int noexpand (char *);
9674 static void synexpect (int) __attribute__((noreturn));
9675 static void synerror (const char *) __attribute__((noreturn));
9676 static void setprompt (int);
9680 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9681 * valid parse tree indicating a blank line.)
9685 parsecmd(int interact)
9690 doprompt = interact;
9710 union node *n1, *n2, *n3;
9714 if (nlflag == 0 && peektoken())
9720 if (tok == TBACKGND) {
9721 if (n2->type == NCMD || n2->type == NPIPE) {
9722 n2->ncmd.backgnd = 1;
9723 } else if (n2->type == NREDIR) {
9724 n2->type = NBACKGND;
9726 n3 = (union node *)stalloc(sizeof (struct nredir));
9727 n3->type = NBACKGND;
9729 n3->nredir.redirect = NULL;
9737 n3 = (union node *)stalloc(sizeof (struct nbinary));
9739 n3->nbinary.ch1 = n1;
9740 n3->nbinary.ch2 = n2;
9764 pungetc(); /* push back EOF on input */
9779 union node *n1, *n2, *n3;
9785 if ((t = readtoken()) == TAND) {
9787 } else if (t == TOR) {
9795 n3 = (union node *)stalloc(sizeof (struct nbinary));
9797 n3->nbinary.ch1 = n1;
9798 n3->nbinary.ch2 = n2;
9807 union node *n1, *n2, *pipenode;
9808 struct nodelist *lp, *prev;
9812 TRACE(("pipeline: entered\n"));
9813 if (readtoken() == TNOT) {
9819 if (readtoken() == TPIPE) {
9820 pipenode = (union node *)stalloc(sizeof (struct npipe));
9821 pipenode->type = NPIPE;
9822 pipenode->npipe.backgnd = 0;
9823 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9824 pipenode->npipe.cmdlist = lp;
9828 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9832 } while (readtoken() == TPIPE);
9838 n2 = (union node *)stalloc(sizeof (struct nnot));
9850 union node *n1, *n2;
9851 union node *ap, **app;
9852 union node *cp, **cpp;
9853 union node *redir, **rpp;
9860 /* Check for redirection which may precede command */
9861 while (readtoken() == TREDIR) {
9862 *rpp = n2 = redirnode;
9863 rpp = &n2->nfile.next;
9868 switch (readtoken()) {
9870 n1 = (union node *)stalloc(sizeof (struct nif));
9872 n1->nif.test = list(0);
9873 if (readtoken() != TTHEN)
9875 n1->nif.ifpart = list(0);
9877 while (readtoken() == TELIF) {
9878 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9879 n2 = n2->nif.elsepart;
9881 n2->nif.test = list(0);
9882 if (readtoken() != TTHEN)
9884 n2->nif.ifpart = list(0);
9886 if (lasttoken == TELSE)
9887 n2->nif.elsepart = list(0);
9889 n2->nif.elsepart = NULL;
9892 if (readtoken() != TFI)
9899 n1 = (union node *)stalloc(sizeof (struct nbinary));
9900 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9901 n1->nbinary.ch1 = list(0);
9902 if ((got=readtoken()) != TDO) {
9903 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9906 n1->nbinary.ch2 = list(0);
9907 if (readtoken() != TDONE)
9913 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9914 synerror("Bad for loop variable");
9915 n1 = (union node *)stalloc(sizeof (struct nfor));
9917 n1->nfor.var = wordtext;
9919 if (readtoken() == TIN) {
9921 while (readtoken() == TWORD) {
9922 n2 = (union node *)stalloc(sizeof (struct narg));
9924 n2->narg.text = wordtext;
9925 n2->narg.backquote = backquotelist;
9927 app = &n2->narg.next;
9931 if (lasttoken != TNL && lasttoken != TSEMI)
9934 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9936 n2 = (union node *)stalloc(sizeof (struct narg));
9938 n2->narg.text = argvars;
9939 n2->narg.backquote = NULL;
9940 n2->narg.next = NULL;
9943 * Newline or semicolon here is optional (but note
9944 * that the original Bourne shell only allowed NL).
9946 if (lasttoken != TNL && lasttoken != TSEMI)
9950 if (readtoken() != TDO)
9952 n1->nfor.body = list(0);
9953 if (readtoken() != TDONE)
9958 n1 = (union node *)stalloc(sizeof (struct ncase));
9960 if (readtoken() != TWORD)
9962 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9964 n2->narg.text = wordtext;
9965 n2->narg.backquote = backquotelist;
9966 n2->narg.next = NULL;
9969 } while (readtoken() == TNL);
9970 if (lasttoken != TIN)
9971 synerror("expecting \"in\"");
9972 cpp = &n1->ncase.cases;
9973 checkkwd = 2, readtoken();
9975 if (lasttoken == TLP)
9977 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9979 app = &cp->nclist.pattern;
9981 *app = ap = (union node *)stalloc(sizeof (struct narg));
9983 ap->narg.text = wordtext;
9984 ap->narg.backquote = backquotelist;
9985 if (checkkwd = 2, readtoken() != TPIPE)
9987 app = &ap->narg.next;
9990 ap->narg.next = NULL;
9991 if (lasttoken != TRP)
9993 cp->nclist.body = list(0);
9996 if ((t = readtoken()) != TESAC) {
9998 synexpect(TENDCASE);
10000 checkkwd = 2, readtoken();
10002 cpp = &cp->nclist.next;
10003 } while(lasttoken != TESAC);
10008 n1 = (union node *)stalloc(sizeof (struct nredir));
10009 n1->type = NSUBSHELL;
10010 n1->nredir.n = list(0);
10011 n1->nredir.redirect = NULL;
10012 if (readtoken() != TRP)
10018 if (readtoken() != TEND)
10022 /* Handle an empty command like other simple commands. */
10031 * An empty command before a ; doesn't make much sense, and
10032 * should certainly be disallowed in the case of `if ;'.
10045 /* Now check for redirection which may follow command */
10046 while (readtoken() == TREDIR) {
10047 *rpp = n2 = redirnode;
10048 rpp = &n2->nfile.next;
10054 if (n1->type != NSUBSHELL) {
10055 n2 = (union node *)stalloc(sizeof (struct nredir));
10060 n1->nredir.redirect = redir;
10067 static union node *
10069 union node *args, **app;
10070 union node *n = NULL;
10071 union node *vars, **vpp;
10072 union node **rpp, *redir;
10083 switch (readtoken()) {
10086 n = (union node *)stalloc(sizeof (struct narg));
10088 n->narg.text = wordtext;
10089 n->narg.backquote = backquotelist;
10090 if (lasttoken == TWORD) {
10092 app = &n->narg.next;
10095 vpp = &n->narg.next;
10099 *rpp = n = redirnode;
10100 rpp = &n->nfile.next;
10101 parsefname(); /* read name of redirection file */
10105 args && app == &args->narg.next &&
10108 /* We have a function */
10109 if (readtoken() != TRP)
10113 n->narg.next = command();
10126 n = (union node *)stalloc(sizeof (struct ncmd));
10128 n->ncmd.backgnd = 0;
10129 n->ncmd.args = args;
10130 n->ncmd.assign = vars;
10131 n->ncmd.redirect = redir;
10135 static union node *
10139 n = (union node *)stalloc(sizeof (struct narg));
10141 n->narg.next = NULL;
10142 n->narg.text = wordtext;
10143 n->narg.backquote = backquotelist;
10147 static void fixredir(union node *n, const char *text, int err)
10149 TRACE(("Fix redir %s %d\n", text, err));
10151 n->ndup.vname = NULL;
10153 if (is_digit(text[0]) && text[1] == '\0')
10154 n->ndup.dupfd = digit_val(text[0]);
10155 else if (text[0] == '-' && text[1] == '\0')
10156 n->ndup.dupfd = -1;
10160 synerror("Bad fd number");
10162 n->ndup.vname = makename();
10169 union node *n = redirnode;
10171 if (readtoken() != TWORD)
10173 if (n->type == NHERE) {
10174 struct heredoc *here = heredoc;
10178 if (quoteflag == 0)
10180 TRACE(("Here document %d\n", n->type));
10181 if (here->striptabs) {
10182 while (*wordtext == '\t')
10185 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10186 synerror("Illegal eof marker for << redirection");
10187 rmescapes(wordtext);
10188 here->eofmark = wordtext;
10190 if (heredoclist == NULL)
10191 heredoclist = here;
10193 for (p = heredoclist ; p->next ; p = p->next);
10196 } else if (n->type == NTOFD || n->type == NFROMFD) {
10197 fixredir(n, wordtext, 0);
10199 n->nfile.fname = makename();
10205 * Input any here documents.
10210 struct heredoc *here;
10213 while (heredoclist) {
10214 here = heredoclist;
10215 heredoclist = here->next;
10220 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10221 here->eofmark, here->striptabs);
10222 n = (union node *)stalloc(sizeof (struct narg));
10223 n->narg.type = NARG;
10224 n->narg.next = NULL;
10225 n->narg.text = wordtext;
10226 n->narg.backquote = backquotelist;
10227 here->here->nhere.doc = n;
10237 return tokname_array[t][0];
10245 int savecheckalias = checkalias;
10246 int savecheckkwd = checkkwd;
10251 int alreadyseen = tokpushback;
10261 checkalias = savecheckalias;
10268 if (checkkwd == 2) {
10277 * check for keywords
10279 if (t == TWORD && !quoteflag)
10281 const char *const *pp;
10283 if ((pp = findkwd(wordtext))) {
10284 lasttoken = t = pp - tokname_array;
10285 TRACE(("keyword %s recognized\n", tokname(t)));
10296 } else if (checkalias == 2 && isassignment(wordtext)) {
10297 lasttoken = t = TASSIGN;
10299 } else if (checkalias) {
10300 if (!quoteflag && (ap = lookupalias(wordtext, 1)) != NULL) {
10302 pushstring(ap->val, strlen(ap->val), ap);
10304 checkkwd = savecheckkwd;
10313 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10315 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10322 * Read the next input token.
10323 * If the token is a word, we set backquotelist to the list of cmds in
10324 * backquotes. We set quoteflag to true if any part of the word was
10326 * If the token is TREDIR, then we set redirnode to a structure containing
10328 * In all cases, the variable startlinno is set to the number of the line
10329 * on which the token starts.
10331 * [Change comment: here documents and internal procedures]
10332 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10333 * word parsing code into a separate routine. In this case, readtoken
10334 * doesn't need to have any internal procedures, but parseword does.
10335 * We could also make parseoperator in essence the main routine, and
10336 * have parseword (readtoken1?) handle both words and redirection.]
10339 #define RETURN(token) return lasttoken = token
10353 startlinno = plinno;
10354 for (;;) { /* until token or start of word found */
10357 case ' ': case '\t':
10363 while ((c = pgetc()) != '\n' && c != PEOF);
10367 if (pgetc() == '\n') {
10368 startlinno = ++plinno;
10379 needprompt = doprompt;
10384 if (pgetc() == '&')
10389 if (pgetc() == '|')
10394 if (pgetc() == ';')
10407 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10414 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10415 * is not NULL, read a here document. In the latter case, eofmark is the
10416 * word which marks the end of the document and striptabs is true if
10417 * leading tabs should be stripped from the document. The argument firstc
10418 * is the first character of the input token or document.
10420 * Because C does not have internal subroutines, I have simulated them
10421 * using goto's to implement the subroutine linkage. The following macros
10422 * will run code that appears at the end of readtoken1.
10425 #define CHECKEND() {goto checkend; checkend_return:;}
10426 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10427 #define PARSESUB() {goto parsesub; parsesub_return:;}
10428 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10429 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10430 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10433 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10438 char line[EOFMARKLEN + 1];
10439 struct nodelist *bqlist;
10442 int varnest; /* levels of variables expansion */
10443 int arinest; /* levels of arithmetic expansion */
10444 int parenlevel; /* levels of parens in arithmetic */
10445 int dqvarnest; /* levels of variables expansion within double quotes */
10447 int prevsyntax; /* syntax before arithmetic */
10449 /* Avoid longjmp clobbering */
10455 (void) &parenlevel;
10458 (void) &prevsyntax;
10462 startlinno = plinno;
10464 if (syntax == DQSYNTAX)
10473 STARTSTACKSTR(out);
10474 loop: { /* for each line, until end of word */
10475 CHECKEND(); /* set c to PEOF if at end of here document */
10476 for (;;) { /* until end of line or end of word */
10477 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10478 switch(SIT(c,syntax)) {
10479 case CNL: /* '\n' */
10480 if (syntax == BASESYNTAX)
10481 goto endword; /* exit outer loop */
10489 goto loop; /* continue outer loop */
10494 if ((eofmark == NULL || dblquote) &&
10496 USTPUTC(CTLESC, out);
10499 case CBACK: /* backslash */
10502 USTPUTC('\\', out);
10504 } else if (c == '\n') {
10510 if (dblquote && c != '\\' && c != '`' && c != '$'
10511 && (c != '"' || eofmark != NULL))
10512 USTPUTC('\\', out);
10513 if (SIT(c,SQSYNTAX) == CCTL)
10514 USTPUTC(CTLESC, out);
10515 else if (eofmark == NULL)
10516 USTPUTC(CTLQUOTEMARK, out);
10522 if (eofmark == NULL)
10523 USTPUTC(CTLQUOTEMARK, out);
10527 if (eofmark == NULL)
10528 USTPUTC(CTLQUOTEMARK, out);
10533 if (eofmark != NULL && arinest == 0 &&
10538 syntax = ARISYNTAX;
10540 } else if (eofmark == NULL &&
10542 syntax = BASESYNTAX;
10548 case CVAR: /* '$' */
10549 PARSESUB(); /* parse substitution */
10551 case CENDVAR: /* '}' */
10554 if (dqvarnest > 0) {
10557 USTPUTC(CTLENDVAR, out);
10562 #ifdef ASH_MATH_SUPPORT
10563 case CLP: /* '(' in arithmetic */
10567 case CRP: /* ')' in arithmetic */
10568 if (parenlevel > 0) {
10572 if (pgetc() == ')') {
10573 if (--arinest == 0) {
10574 USTPUTC(CTLENDARI, out);
10575 syntax = prevsyntax;
10576 if (syntax == DQSYNTAX)
10584 * unbalanced parens
10585 * (don't 2nd guess - no error)
10593 case CBQUOTE: /* '`' */
10597 goto endword; /* exit outer loop */
10602 goto endword; /* exit outer loop */
10613 if (syntax == ARISYNTAX)
10614 synerror("Missing '))'");
10615 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10616 synerror("Unterminated quoted string");
10617 if (varnest != 0) {
10618 startlinno = plinno;
10619 synerror("Missing '}'");
10621 USTPUTC('\0', out);
10622 len = out - stackblock();
10623 out = stackblock();
10624 if (eofmark == NULL) {
10625 if ((c == '>' || c == '<')
10628 && (*out == '\0' || is_digit(*out))) {
10630 return lasttoken = TREDIR;
10635 quoteflag = quotef;
10636 backquotelist = bqlist;
10637 grabstackblock(len);
10639 return lasttoken = TWORD;
10640 /* end of readtoken routine */
10645 * Check to see whether we are at the end of the here document. When this
10646 * is called, c is set to the first character of the next input line. If
10647 * we are at the end of the here document, this routine sets the c to PEOF.
10658 while (c == '\t') {
10662 if (c == *eofmark) {
10663 if (pfgets(line, sizeof line) != NULL) {
10667 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10668 if (*p == '\n' && *q == '\0') {
10671 needprompt = doprompt;
10673 pushstring(line, strlen(line), NULL);
10678 goto checkend_return;
10683 * Parse a redirection operator. The variable "out" points to a string
10684 * specifying the fd to be redirected. The variable "c" contains the
10685 * first character of the redirection operator.
10692 np = (union node *)stalloc(sizeof (struct nfile));
10697 np->type = NAPPEND;
10706 } else { /* c == '<' */
10708 switch (c = pgetc()) {
10710 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10711 np = (union node *)stalloc(sizeof (struct nhere));
10715 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10716 heredoc->here = np;
10717 if ((c = pgetc()) == '-') {
10718 heredoc->striptabs = 1;
10720 heredoc->striptabs = 0;
10726 np->type = NFROMFD;
10730 np->type = NFROMTO;
10740 np->nfile.fd = digit_val(fd);
10742 goto parseredir_return;
10747 * Parse a substitution. At this point, we have read the dollar sign
10748 * and nothing else.
10756 static const char types[] = "}-+?=";
10761 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10765 } else if (c == '(') { /* $(command) or $((arith)) */
10766 if (pgetc() == '(') {
10773 USTPUTC(CTLVAR, out);
10774 typeloc = out - stackblock();
10775 USTPUTC(VSNORMAL, out);
10776 subtype = VSNORMAL;
10780 if ((c = pgetc()) == '}')
10783 subtype = VSLENGTH;
10788 if (c > PEOA && is_name(c)) {
10792 } while (c > PEOA && is_in_name(c));
10793 } else if (is_digit(c)) {
10797 } while (is_digit(c));
10799 else if (is_special(c)) {
10804 badsub: synerror("Bad substitution");
10808 if (subtype == 0) {
10815 p = strchr(types, c);
10818 subtype = p - types + VSNORMAL;
10824 subtype = c == '#' ? VSTRIMLEFT :
10837 if (dblquote || arinest)
10839 *(stackblock() + typeloc) = subtype | flags;
10840 if (subtype != VSNORMAL) {
10847 goto parsesub_return;
10852 * Called to parse command substitutions. Newstyle is set if the command
10853 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10854 * list of commands (passed by reference), and savelen is the number of
10855 * characters on the top of the stack which must be preserved.
10859 struct nodelist **nlpp;
10862 char *volatile str;
10863 struct jmploc jmploc;
10864 struct jmploc *volatile savehandler;
10868 (void) &saveprompt;
10871 savepbq = parsebackquote;
10872 if (setjmp(jmploc.loc)) {
10875 parsebackquote = 0;
10876 handler = savehandler;
10877 longjmp(handler->loc, 1);
10881 savelen = out - stackblock();
10883 str = ckmalloc(savelen);
10884 memcpy(str, stackblock(), savelen);
10886 savehandler = handler;
10890 /* We must read until the closing backquote, giving special
10891 treatment to some slashes, and then push the string and
10892 reread it as input, interpreting it normally. */
10899 STARTSTACKSTR(pout);
10905 switch (pc = pgetc()) {
10910 if ((pc = pgetc()) == '\n') {
10917 * If eating a newline, avoid putting
10918 * the newline into the new character
10919 * stream (via the STPUTC after the
10924 if (pc != '\\' && pc != '`' && pc != '$'
10925 && (!dblquote || pc != '"'))
10926 STPUTC('\\', pout);
10936 startlinno = plinno;
10937 synerror("EOF in backquote substitution");
10941 needprompt = doprompt;
10950 STPUTC('\0', pout);
10951 psavelen = pout - stackblock();
10952 if (psavelen > 0) {
10953 pstr = grabstackstr(pout);
10954 setinputstring(pstr);
10959 nlpp = &(*nlpp)->next;
10960 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10961 (*nlpp)->next = NULL;
10962 parsebackquote = oldstyle;
10965 saveprompt = doprompt;
10972 doprompt = saveprompt;
10974 if (readtoken() != TRP)
10981 * Start reading from old file again, ignoring any pushed back
10982 * tokens left from the backquote parsing
10987 while (stackblocksize() <= savelen)
10989 STARTSTACKSTR(out);
10991 memcpy(out, str, savelen);
10992 STADJUST(savelen, out);
10998 parsebackquote = savepbq;
10999 handler = savehandler;
11000 if (arinest || dblquote)
11001 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11003 USTPUTC(CTLBACKQ, out);
11005 goto parsebackq_oldreturn;
11007 goto parsebackq_newreturn;
11011 * Parse an arithmetic expansion (indicate start of one and set state)
11015 if (++arinest == 1) {
11016 prevsyntax = syntax;
11017 syntax = ARISYNTAX;
11018 USTPUTC(CTLARI, out);
11025 * we collapse embedded arithmetic expansion to
11026 * parenthesis, which should be equivalent
11030 goto parsearith_return;
11033 } /* end of readtoken */
11037 * Returns true if the text contains nothing to expand (no dollar signs
11049 while ((c = *p++) != '\0') {
11050 if (c == CTLQUOTEMARK)
11054 else if (SIT(c,BASESYNTAX) == CCTL)
11062 * Return true if the argument is a legal variable name (a letter or
11063 * underscore followed by zero or more letters, underscores, and digits).
11067 goodname(const char *name)
11075 if (! is_in_name(*p))
11083 * Called when an unexpected token is read during the parse. The argument
11084 * is the token that is expected, or -1 if more than one type of token can
11085 * occur at this point.
11095 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11097 sprintf(msg+l, " (expecting %s)", tokname(token));
11104 synerror(const char *msg)
11107 out2fmt("%s: %d: ", commandname, startlinno);
11108 out2fmt("Syntax error: %s\n", msg);
11109 error((char *)NULL);
11115 * called by editline -- any expansions to the prompt
11116 * should be added here.
11119 setprompt(int whichprompt)
11122 switch (whichprompt) {
11137 * Code for dealing with input/output redirection.
11140 #define EMPTY -2 /* marks an unused slot in redirtab */
11142 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11144 # define PIPESIZE PIPE_BUF
11149 * Open a file in noclobber mode.
11150 * The code was copied from bash.
11153 noclobberopen(const char *fname)
11156 struct stat finfo, finfo2;
11159 * If the file exists and is a regular file, return an error
11162 r = stat(fname, &finfo);
11163 if (r == 0 && S_ISREG(finfo.st_mode)) {
11169 * If the file was not present (r != 0), make sure we open it
11170 * exclusively so that if it is created before we open it, our open
11171 * will fail. Make sure that we do not truncate an existing file.
11172 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11173 * file was not a regular file, we leave O_EXCL off.
11176 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11177 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11179 /* If the open failed, return the file descriptor right away. */
11184 * OK, the open succeeded, but the file may have been changed from a
11185 * non-regular file to a regular file between the stat and the open.
11186 * We are assuming that the O_EXCL open handles the case where FILENAME
11187 * did not exist and is symlinked to an existing file between the stat
11192 * If we can open it and fstat the file descriptor, and neither check
11193 * revealed that it was a regular file, and the file has not been
11194 * replaced, return the file descriptor.
11196 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11197 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11200 /* The file has been replaced. badness. */
11207 * Handle here documents. Normally we fork off a process to write the
11208 * data to a pipe. If the document is short, we can stuff the data in
11209 * the pipe without forking.
11213 openhere(const union node *redir)
11219 error("Pipe call failed");
11220 if (redir->type == NHERE) {
11221 len = strlen(redir->nhere.doc->narg.text);
11222 if (len <= PIPESIZE) {
11223 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11227 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11229 signal(SIGINT, SIG_IGN);
11230 signal(SIGQUIT, SIG_IGN);
11231 signal(SIGHUP, SIG_IGN);
11233 signal(SIGTSTP, SIG_IGN);
11235 signal(SIGPIPE, SIG_DFL);
11236 if (redir->type == NHERE)
11237 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11239 expandhere(redir->nhere.doc, pip[1]);
11249 openredirect(const union node *redir)
11254 switch (redir->nfile.type) {
11256 fname = redir->nfile.expfname;
11257 if ((f = open(fname, O_RDONLY)) < 0)
11261 fname = redir->nfile.expfname;
11262 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11266 /* Take care of noclobber mode. */
11268 fname = redir->nfile.expfname;
11269 if ((f = noclobberopen(fname)) < 0)
11274 fname = redir->nfile.expfname;
11276 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11279 if ((f = creat(fname, 0666)) < 0)
11284 fname = redir->nfile.expfname;
11286 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11289 if ((f = open(fname, O_WRONLY)) < 0
11290 && (f = creat(fname, 0666)) < 0)
11292 lseek(f, (off_t)0, 2);
11299 /* Fall through to eliminate warning. */
11306 f = openhere(redir);
11312 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11314 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11319 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11320 * old file descriptors are stashed away so that the redirection can be
11321 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11322 * standard output, and the standard error if it becomes a duplicate of
11327 redirect(union node *redir, int flags)
11330 struct redirtab *sv = NULL;
11335 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11337 if (flags & REDIR_PUSH) {
11338 sv = ckmalloc(sizeof (struct redirtab));
11339 for (i = 0 ; i < 10 ; i++)
11340 sv->renamed[i] = EMPTY;
11341 sv->next = redirlist;
11344 for (n = redir ; n ; n = n->nfile.next) {
11347 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11348 n->ndup.dupfd == fd)
11349 continue; /* redirect from/to same file descriptor */
11352 newfd = openredirect(n);
11353 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11356 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11360 dupredirect(n, newfd, fd1dup);
11370 error("%d: %m", fd);
11376 if (flags & REDIR_PUSH) {
11377 sv->renamed[fd] = i;
11380 } else if (fd != newfd) {
11386 dupredirect(n, newfd, fd1dup);
11393 dupredirect(const union node *redir, int f, int fd1dup)
11395 int fd = redir->nfile.fd;
11399 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11400 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11401 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11402 dup_as_newfd(redir->ndup.dupfd, fd);
11408 dup_as_newfd(f, fd);
11417 * Undo the effects of the last redirection.
11423 struct redirtab *rp = redirlist;
11427 for (i = 0 ; i < 10 ; i++) {
11428 if (rp->renamed[i] != EMPTY) {
11432 if (rp->renamed[i] >= 0) {
11433 dup_as_newfd(rp->renamed[i], i);
11434 close(rp->renamed[i]);
11438 redirlist = rp->next;
11444 * Discard all saved file descriptors.
11449 struct redirtab *rp;
11452 for (rp = redirlist ; rp ; rp = rp->next) {
11453 for (i = 0 ; i < 10 ; i++) {
11454 if (rp->renamed[i] >= 0) {
11455 close(rp->renamed[i]);
11457 rp->renamed[i] = EMPTY;
11464 * Copy a file descriptor to be >= to. Returns -1
11465 * if the source file descriptor is closed, EMPTY if there are no unused
11466 * file descriptors left.
11470 dup_as_newfd(from, to)
11476 newfd = fcntl(from, F_DUPFD, to);
11478 if (errno == EMFILE)
11481 error("%d: %m", from);
11487 static void shtree (union node *, int, char *, FILE*);
11488 static void shcmd (union node *, FILE *);
11489 static void sharg (union node *, FILE *);
11490 static void indent (int, char *, FILE *);
11491 static void trstring (char *);
11498 trputs("showtree called\n");
11499 shtree(n, 1, NULL, stdout);
11504 shtree(n, ind, pfx, fp)
11510 struct nodelist *lp;
11516 indent(ind, pfx, fp);
11527 shtree(n->nbinary.ch1, ind, NULL, fp);
11530 shtree(n->nbinary.ch2, ind, NULL, fp);
11538 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11543 if (n->npipe.backgnd)
11549 fprintf(fp, "<node type %d>", n->type);
11569 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11575 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11581 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11582 s = redir_strings[np->nfile.type - NTO];
11588 switch (np->nfile.type) {
11589 case NTO: s = ">"; dftfd = 1; break;
11590 case NAPPEND: s = ">>"; dftfd = 1; break;
11591 case NTOFD: s = ">&"; dftfd = 1; break;
11592 case NTOOV: s = ">|"; dftfd = 1; break;
11593 case NFROM: s = "<"; dftfd = 0; break;
11594 case NFROMFD: s = "<&"; dftfd = 0; break;
11595 case NFROMTO: s = "<>"; dftfd = 0; break;
11596 default: s = "*error*"; dftfd = 0; break;
11599 if (np->nfile.fd != dftfd)
11600 fprintf(fp, "%d", np->nfile.fd);
11602 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11603 fprintf(fp, "%d", np->ndup.dupfd);
11605 sharg(np->nfile.fname, fp);
11619 struct nodelist *bqlist;
11622 if (arg->type != NARG) {
11623 printf("<node type %d>\n", arg->type);
11627 bqlist = arg->narg.backquote;
11628 for (p = arg->narg.text ; *p ; p++) {
11637 if (subtype == VSLENGTH)
11643 if (subtype & VSNUL)
11646 switch (subtype & VSTYPE) {
11665 case VSTRIMLEFTMAX:
11672 case VSTRIMRIGHTMAX:
11679 printf("<subtype %d>", subtype);
11686 case CTLBACKQ|CTLQUOTE:
11689 shtree(bqlist->n, -1, NULL, fp);
11701 indent(amount, pfx, fp)
11708 for (i = 0 ; i < amount ; i++) {
11709 if (pfx && i == amount - 1)
11727 static int debug = 1;
11729 static int debug = 0;
11737 if (tracefile == NULL)
11739 putc(c, tracefile);
11745 trace(const char *fmt, ...)
11749 if (tracefile != NULL) {
11750 (void) vfprintf(tracefile, fmt, va);
11751 if (strchr(fmt, '\n'))
11752 (void) fflush(tracefile);
11762 if (tracefile == NULL)
11764 fputs(s, tracefile);
11765 if (strchr(s, '\n'))
11777 if (tracefile == NULL)
11779 putc('"', tracefile);
11780 for (p = s ; *p ; p++) {
11782 case '\n': c = 'n'; goto backslash;
11783 case '\t': c = 't'; goto backslash;
11784 case '\r': c = 'r'; goto backslash;
11785 case '"': c = '"'; goto backslash;
11786 case '\\': c = '\\'; goto backslash;
11787 case CTLESC: c = 'e'; goto backslash;
11788 case CTLVAR: c = 'v'; goto backslash;
11789 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11790 case CTLBACKQ: c = 'q'; goto backslash;
11791 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11792 backslash: putc('\\', tracefile);
11793 putc(c, tracefile);
11796 if (*p >= ' ' && *p <= '~')
11797 putc(*p, tracefile);
11799 putc('\\', tracefile);
11800 putc(*p >> 6 & 03, tracefile);
11801 putc(*p >> 3 & 07, tracefile);
11802 putc(*p & 07, tracefile);
11807 putc('"', tracefile);
11815 if (tracefile == NULL)
11820 putc(' ', tracefile);
11822 putc('\n', tracefile);
11837 #ifdef not_this_way
11840 if ((p = getenv("HOME")) == NULL) {
11841 if (geteuid() == 0)
11847 strcat(s, "/trace");
11850 strcpy(s, "./trace");
11851 #endif /* not_this_way */
11852 if ((tracefile = fopen(s, "a")) == NULL) {
11853 fprintf(stderr, "Can't open %s\n", s);
11857 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11858 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11860 fputs("\nTracing started.\n", tracefile);
11867 * The trap builtin.
11871 trapcmd(argc, argv)
11880 for (signo = 0 ; signo < NSIG ; signo++) {
11881 if (trap[signo] != NULL) {
11885 p = single_quote(trap[signo]);
11886 sn = sys_siglist[signo];
11888 sn = u_signal_names(0, &signo, 0);
11891 printf("trap -- %s %s\n", p, sn);
11903 if ((signo = decode_signal(*ap, 0)) < 0)
11904 error("%s: bad trap", *ap);
11907 if (action[0] == '-' && action[1] == '\0')
11910 action = savestr(action);
11913 ckfree(trap[signo]);
11914 trap[signo] = action;
11929 * Set the signal handler for the specified signal. The routine figures
11930 * out what it should be set to.
11934 setsignal(int signo)
11938 struct sigaction act;
11940 if ((t = trap[signo]) == NULL)
11942 else if (*t != '\0')
11946 if (rootshell && action == S_DFL) {
11949 if (iflag || minusc || sflag == 0)
11975 t = &sigmode[signo - 1];
11978 * current setting unknown
11980 if (sigaction(signo, 0, &act) == -1) {
11982 * Pretend it worked; maybe we should give a warning
11983 * here, but other shells don't. We don't alter
11984 * sigmode, so that we retry every time.
11988 if (act.sa_handler == SIG_IGN) {
11989 if (mflag && (signo == SIGTSTP ||
11990 signo == SIGTTIN || signo == SIGTTOU)) {
11991 *t = S_IGN; /* don't hard ignore these */
11995 *t = S_RESET; /* force to be set */
11998 if (*t == S_HARD_IGN || *t == action)
12000 act.sa_handler = ((action == S_CATCH) ? onsig
12001 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
12004 sigemptyset(&act.sa_mask);
12005 sigaction(signo, &act, 0);
12016 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
12017 signal(signo, SIG_IGN);
12019 sigmode[signo - 1] = S_HARD_IGN;
12030 if (signo == SIGINT && trap[SIGINT] == NULL) {
12034 gotsig[signo - 1] = 1;
12040 * Called to execute a trap. Perhaps we should avoid entering new trap
12041 * handlers while we are executing a trap handler.
12051 for (i = 1 ; ; i++) {
12058 savestatus=exitstatus;
12059 evalstring(trap[i], 0);
12060 exitstatus=savestatus;
12067 * Called to exit the shell.
12071 exitshell(int status)
12073 struct jmploc loc1, loc2;
12076 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12077 if (setjmp(loc1.loc)) {
12080 if (setjmp(loc2.loc)) {
12084 if ((p = trap[0]) != NULL && *p != '\0') {
12088 l1: handler = &loc2; /* probably unnecessary */
12097 static int decode_signal(const char *string, int minsig)
12100 const char *name = u_signal_names(string, &signo, minsig);
12102 return name ? signo : -1;
12105 static struct var **hashvar (const char *);
12106 static void showvars (const char *, int, int);
12107 static struct var **findvar (struct var **, const char *);
12110 * Initialize the varable symbol tables and import the environment
12114 * This routine initializes the builtin variables. It is called when the
12115 * shell is initialized and again when a shell procedure is spawned.
12120 const struct varinit *ip;
12124 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12125 if ((vp->flags & VEXPORT) == 0) {
12126 vpp = hashvar(ip->text);
12129 vp->text = strdup(ip->text);
12130 vp->flags = ip->flags;
12131 vp->func = ip->func;
12135 * PS1 depends on uid
12137 if ((vps1.flags & VEXPORT) == 0) {
12138 vpp = hashvar("PS1=");
12141 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12142 vps1.flags = VSTRFIXED|VTEXTFIXED;
12147 * Set the value of a variable. The flags argument is ored with the
12148 * flags of the variable. If val is NULL, the variable is unset.
12152 setvar(name, val, flags)
12153 const char *name, *val;
12169 if (! is_in_name(*p)) {
12170 if (*p == '\0' || *p == '=')
12176 namelen = p - name;
12178 error("%.*s: bad variable name", namelen, name);
12179 len = namelen + 2; /* 2 is space for '=' and '\0' */
12183 len += vallen = strlen(val);
12186 nameeq = ckmalloc(len);
12187 memcpy(nameeq, name, namelen);
12188 nameeq[namelen] = '=';
12190 memcpy(nameeq + namelen + 1, val, vallen + 1);
12192 nameeq[namelen + 1] = '\0';
12194 setvareq(nameeq, flags);
12201 * Same as setvar except that the variable and value are passed in
12202 * the first argument as name=value. Since the first argument will
12203 * be actually stored in the table, it should not be a string that
12212 struct var *vp, **vpp;
12215 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12216 if ((vp = *findvar(vpp, s))) {
12217 if (vp->flags & VREADONLY) {
12218 size_t len = strchr(s, '=') - s;
12219 error("%.*s: is read only", len, s);
12223 if (vp->func && (flags & VNOFUNC) == 0)
12224 (*vp->func)(strchr(s, '=') + 1);
12226 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12229 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12230 vp->flags |= flags;
12234 * We could roll this to a function, to handle it as
12235 * a regular variable function callback, but why bother?
12237 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12243 vp = ckmalloc(sizeof (*vp));
12254 * Process a linked list of variable assignments.
12259 struct strlist *mylist;
12261 struct strlist *lp;
12264 for (lp = mylist ; lp ; lp = lp->next) {
12265 setvareq(savestr(lp->text), 0);
12273 * Find the value of a variable. Returns NULL if not set.
12276 static const char *
12282 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12283 return strchr(v->text, '=') + 1;
12291 * Search the environment of a builtin command.
12294 static const char *
12295 bltinlookup(const char *name)
12297 const struct strlist *sp;
12299 for (sp = cmdenviron ; sp ; sp = sp->next) {
12300 if (varequal(sp->text, name))
12301 return strchr(sp->text, '=') + 1;
12303 return lookupvar(name);
12309 * Generate a list of exported variables. This routine is used to construct
12310 * the third argument to execve when executing a program.
12322 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12323 for (vp = *vpp ; vp ; vp = vp->next)
12324 if (vp->flags & VEXPORT)
12327 ep = env = stalloc((nenv + 1) * sizeof *env);
12328 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12329 for (vp = *vpp ; vp ; vp = vp->next)
12330 if (vp->flags & VEXPORT)
12339 * Called when a shell procedure is invoked to clear out nonexported
12340 * variables. It is also necessary to reallocate variables of with
12341 * VSTACK set since these are currently allocated on the stack.
12347 struct var *vp, **prev;
12349 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12350 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12351 if ((vp->flags & VEXPORT) == 0) {
12353 if ((vp->flags & VTEXTFIXED) == 0)
12355 if ((vp->flags & VSTRFIXED) == 0)
12358 if (vp->flags & VSTACK) {
12359 vp->text = savestr(vp->text);
12360 vp->flags &=~ VSTACK;
12372 * Command to list all variables which are set. Currently this command
12373 * is invoked from the set command when the set command is called without
12378 showvarscmd(argc, argv)
12382 showvars(nullstr, VUNSET, VUNSET);
12389 * The export and readonly commands.
12393 exportcmd(argc, argv)
12400 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12403 listsetvar(cmdenviron);
12404 pflag = (nextopt("p") == 'p');
12405 if (argc > 1 && !pflag) {
12406 while ((name = *argptr++) != NULL) {
12407 if ((p = strchr(name, '=')) != NULL) {
12410 if ((vp = *findvar(hashvar(name), name))) {
12415 setvar(name, p, flag);
12419 showvars(argv[0], flag, 0);
12426 * The "local" command.
12429 /* funcnest nonzero if we are currently evaluating a function */
12432 localcmd(argc, argv)
12439 error("Not in a function");
12440 while ((name = *argptr++) != NULL) {
12448 * Make a variable a local variable. When a variable is made local, it's
12449 * value and flags are saved in a localvar structure. The saved values
12450 * will be restored when the shell function returns. We handle the name
12451 * "-" as a special case.
12458 struct localvar *lvp;
12463 lvp = ckmalloc(sizeof (struct localvar));
12464 if (name[0] == '-' && name[1] == '\0') {
12466 p = ckmalloc(sizeof optet_vals);
12467 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12470 vpp = hashvar(name);
12471 vp = *findvar(vpp, name);
12473 if (strchr(name, '='))
12474 setvareq(savestr(name), VSTRFIXED);
12476 setvar(name, NULL, VSTRFIXED);
12477 vp = *vpp; /* the new variable */
12479 lvp->flags = VUNSET;
12481 lvp->text = vp->text;
12482 lvp->flags = vp->flags;
12483 vp->flags |= VSTRFIXED|VTEXTFIXED;
12484 if (strchr(name, '='))
12485 setvareq(savestr(name), 0);
12489 lvp->next = localvars;
12496 * Called after a function returns.
12501 struct localvar *lvp;
12504 while ((lvp = localvars) != NULL) {
12505 localvars = lvp->next;
12507 if (vp == NULL) { /* $- saved */
12508 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12510 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12511 (void)unsetvar(vp->text);
12513 if ((vp->flags & VTEXTFIXED) == 0)
12515 vp->flags = lvp->flags;
12516 vp->text = lvp->text;
12524 setvarcmd(argc, argv)
12529 return unsetcmd(argc, argv);
12530 else if (argc == 3)
12531 setvar(argv[1], argv[2], 0);
12533 error("List assignment not implemented");
12539 * The unset builtin command. We unset the function before we unset the
12540 * variable to allow a function to be unset when there is a readonly variable
12541 * with the same name.
12545 unsetcmd(argc, argv)
12555 while ((i = nextopt("vf")) != '\0') {
12561 if (flg_func == 0 && flg_var == 0)
12564 for (ap = argptr; *ap ; ap++) {
12568 ret |= unsetvar(*ap);
12575 * Unset the specified variable.
12579 unsetvar(const char *s)
12584 vpp = findvar(hashvar(s), s);
12587 if (vp->flags & VREADONLY)
12590 if (*(strchr(vp->text, '=') + 1) != '\0')
12591 setvar(s, nullstr, 0);
12592 vp->flags &= ~VEXPORT;
12593 vp->flags |= VUNSET;
12594 if ((vp->flags & VSTRFIXED) == 0) {
12595 if ((vp->flags & VTEXTFIXED) == 0)
12610 * Find the appropriate entry in the hash table from the name.
12613 static struct var **
12614 hashvar(const char *p)
12616 unsigned int hashval;
12618 hashval = ((unsigned char) *p) << 4;
12619 while (*p && *p != '=')
12620 hashval += (unsigned char) *p++;
12621 return &vartab[hashval % VTABSIZE];
12627 * Returns true if the two strings specify the same varable. The first
12628 * variable name is terminated by '='; the second may be terminated by
12629 * either '=' or '\0'.
12633 varequal(const char *p, const char *q)
12635 while (*p == *q++) {
12639 if (*p == '=' && *(q - 1) == '\0')
12645 showvars(const char *myprefix, int mask, int xor)
12649 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12651 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12652 for (vp = *vpp ; vp ; vp = vp->next) {
12653 if ((vp->flags & mask) ^ xor) {
12657 p = strchr(vp->text, '=') + 1;
12658 len = p - vp->text;
12659 p = single_quote(p);
12661 printf("%s%s%.*s%s\n", myprefix, sep, len,
12669 static struct var **
12670 findvar(struct var **vpp, const char *name)
12672 for (; *vpp; vpp = &(*vpp)->next) {
12673 if (varequal((*vpp)->text, name)) {
12681 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12682 * This file contains code for the times builtin.
12683 * $Id: ash.c,v 1.23 2001/09/06 17:35:20 andersen Exp $
12685 static int timescmd (int argc, char **argv)
12688 long int clk_tck = sysconf(_SC_CLK_TCK);
12691 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12692 (int) (buf.tms_utime / clk_tck / 60),
12693 ((double) buf.tms_utime) / clk_tck,
12694 (int) (buf.tms_stime / clk_tck / 60),
12695 ((double) buf.tms_stime) / clk_tck,
12696 (int) (buf.tms_cutime / clk_tck / 60),
12697 ((double) buf.tms_cutime) / clk_tck,
12698 (int) (buf.tms_cstime / clk_tck / 60),
12699 ((double) buf.tms_cstime) / clk_tck);
12703 #ifdef ASH_MATH_SUPPORT
12704 /* The let builtin. */
12705 int letcmd(int argc, char **argv)
12710 char *tmp, *expression, p[13];
12711 expression = strchr(argv[1], '=');
12713 /* Cannot use 'error()' here, or the return code
12714 * will be incorrect */
12715 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12718 *expression = '\0';
12719 tmp = ++expression;
12720 result = arith(tmp, &errcode);
12722 /* Cannot use 'error()' here, or the return code
12723 * will be incorrect */
12724 out2fmt("sh: let: ");
12726 out2fmt("divide by zero");
12728 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12731 snprintf(p, 12, "%ld", result);
12732 setvar(argv[1], savestr(p), 0);
12733 } else if (argc >= 3)
12734 synerror("invalid operand");
12742 * Copyright (c) 1989, 1991, 1993, 1994
12743 * The Regents of the University of California. All rights reserved.
12745 * This code is derived from software contributed to Berkeley by
12746 * Kenneth Almquist.
12748 * Redistribution and use in source and binary forms, with or without
12749 * modification, are permitted provided that the following conditions
12751 * 1. Redistributions of source code must retain the above copyright
12752 * notice, this list of conditions and the following disclaimer.
12753 * 2. Redistributions in binary form must reproduce the above copyright
12754 * notice, this list of conditions and the following disclaimer in the
12755 * documentation and/or other materials provided with the distribution.
12757 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12758 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12760 * 4. Neither the name of the University nor the names of its contributors
12761 * may be used to endorse or promote products derived from this software
12762 * without specific prior written permission.
12764 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12765 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12766 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12767 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12768 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12769 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12770 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12771 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12772 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12773 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF