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... */
101 #include <sys/stat.h>
102 #include <sys/cdefs.h>
103 #include <sys/ioctl.h>
104 #include <sys/param.h>
105 #include <sys/resource.h>
106 #include <sys/time.h>
107 #include <sys/times.h>
108 #include <sys/types.h>
109 #include <sys/wait.h>
112 #if !defined(FNMATCH_BROKEN)
115 #if !defined(GLOB_BROKEN)
127 * This file was generated by the mksyntax program.
131 #define CWORD 0 /* character is nothing special */
132 #define CNL 1 /* newline character */
133 #define CBACK 2 /* a backslash character */
134 #define CSQUOTE 3 /* single quote */
135 #define CDQUOTE 4 /* double quote */
136 #define CENDQUOTE 5 /* a terminating quote */
137 #define CBQUOTE 6 /* backwards single quote */
138 #define CVAR 7 /* a dollar sign */
139 #define CENDVAR 8 /* a '}' character */
140 #define CLP 9 /* a left paren in arithmetic */
141 #define CRP 10 /* a right paren in arithmetic */
142 #define CENDFILE 11 /* end of file */
143 #define CCTL 12 /* like CWORD, except it must be escaped */
144 #define CSPCL 13 /* these terminate a word */
145 #define CIGN 14 /* character should be ignored */
165 #define TENDBQUOTE 13
185 /* control characters in argument strings */
186 #define CTLESC '\201'
187 #define CTLVAR '\202'
188 #define CTLENDVAR '\203'
189 #define CTLBACKQ '\204'
190 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
191 /* CTLBACKQ | CTLQUOTE == '\205' */
192 #define CTLARI '\206'
193 #define CTLENDARI '\207'
194 #define CTLQUOTEMARK '\210'
197 #define is_digit(c) ((c)>='0' && (c)<='9')
198 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
199 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
202 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
203 * (assuming ascii char codes, as the original implementation did)
205 #define is_special(c) \
206 ( (((unsigned int)c) - 33 < 32) \
207 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
209 #define digit_val(c) ((c) - '0')
212 #define _DIAGASSERT(x)
216 #define S_DFL 1 /* default signal handling (SIG_DFL) */
217 #define S_CATCH 2 /* signal is caught */
218 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
219 #define S_HARD_IGN 4 /* signal is ignored permenantly */
220 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
223 /* variable substitution byte (follows CTLVAR) */
224 #define VSTYPE 0x0f /* type of variable substitution */
225 #define VSNUL 0x10 /* colon--treat the empty string as unset */
226 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
228 /* values of VSTYPE field */
229 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
230 #define VSMINUS 0x2 /* ${var-text} */
231 #define VSPLUS 0x3 /* ${var+text} */
232 #define VSQUESTION 0x4 /* ${var?message} */
233 #define VSASSIGN 0x5 /* ${var=text} */
234 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
235 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
236 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
237 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
238 #define VSLENGTH 0xa /* ${#var} */
240 /* flags passed to redirect */
241 #define REDIR_PUSH 01 /* save previous values of file descriptors */
242 #define REDIR_BACKQ 02 /* save the command output to pipe */
245 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
246 * so we use _setjmp instead.
250 #define setjmp(jmploc) _setjmp(jmploc)
251 #define longjmp(jmploc, val) _longjmp(jmploc, val)
255 * Most machines require the value returned from malloc to be aligned
256 * in some way. The following macro will get this right on many machines.
265 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
268 #ifdef BB_LOCALE_SUPPORT
270 static void change_lc_all(const char *value);
271 static void change_lc_ctype(const char *value);
275 * These macros allow the user to suspend the handling of interrupt signals
276 * over a period of time. This is similar to SIGHOLD to or sigblock, but
277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
281 static void onint (void);
282 static volatile int suppressint;
283 static volatile int intpending;
285 #define INTOFF suppressint++
286 #ifndef ASH_OPTIMIZE_FOR_SIZE
287 #define INTON { if (--suppressint == 0 && intpending) onint(); }
288 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
290 static void __inton (void);
291 static void forceinton (void);
292 #define INTON __inton()
293 #define FORCEINTON forceinton()
296 #define CLEAR_PENDING_INT intpending = 0
297 #define int_pending() intpending
300 typedef void *pointer;
302 #define NULL (void *)0
305 static inline pointer ckmalloc (int sz) { return xmalloc(sz); }
306 static inline pointer ckrealloc(void *p, int sz) { return xrealloc(p, sz); }
307 static inline char * savestr (const char *s) { return xstrdup(s); }
309 static pointer stalloc (int);
310 static void stunalloc (pointer);
311 static void ungrabstackstr (char *, char *);
312 static char * growstackstr(void);
313 static char * makestrspace(size_t newlen);
314 static char *sstrdup (const char *);
317 * Parse trees for commands are allocated in lifo order, so we use a stack
318 * to make this more efficient, and also to avoid all sorts of exception
319 * handling code to handle interrupts in the middle of a parse.
321 * The size 504 was chosen because the Ultrix malloc handles that size
325 #define MINSIZE 504 /* minimum size of a block */
329 struct stack_block *prev;
333 static struct stack_block stackbase;
334 static struct stack_block *stackp = &stackbase;
335 static struct stackmark *markp;
336 static char *stacknxt = stackbase.space;
337 static int stacknleft = MINSIZE;
340 #define equal(s1, s2) (strcmp(s1, s2) == 0)
342 #define stackblock() stacknxt
343 #define stackblocksize() stacknleft
344 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
346 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
347 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
348 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
351 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
352 #define STUNPUTC(p) (++sstrnleft, --p)
353 #define STTOPC(p) p[-1]
354 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
355 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
357 #define ckfree(p) free((pointer)(p))
361 #define TRACE(param) trace param
362 static void trace (const char *, ...);
363 static void trargs (char **);
364 static void showtree (union node *);
365 static void trputc (int);
366 static void trputs (const char *);
367 static void opentrace (void);
402 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
403 #define EXP_TILDE 0x2 /* do normal tilde expansion */
404 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
405 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
406 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
407 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
412 static char optet_vals[NOPTS];
414 static const char * const optlist[NOPTS] = {
433 #define optent_name(optent) (optent+1)
434 #define optent_letter(optent) optent[0]
435 #define optent_val(optent) optet_vals[optent]
437 #define eflag optent_val(0)
438 #define fflag optent_val(1)
439 #define Iflag optent_val(2)
440 #define iflag optent_val(3)
441 #define mflag optent_val(4)
442 #define nflag optent_val(5)
443 #define sflag optent_val(6)
444 #define xflag optent_val(7)
445 #define vflag optent_val(8)
446 #define Vflag optent_val(9)
447 #define Eflag optent_val(10)
448 #define Cflag optent_val(11)
449 #define aflag optent_val(12)
450 #define bflag optent_val(13)
451 #define uflag optent_val(14)
452 #define qflag optent_val(15)
455 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
473 union node *redirect;
480 struct nodelist *cmdlist;
487 union node *redirect;
495 union node *elsepart;
526 struct nodelist *backquote;
564 struct nbinary nbinary;
567 struct nredir nredir;
571 struct nclist nclist;
581 struct nodelist *next;
585 struct backcmd { /* result of evalbackcmd */
586 int fd; /* file descriptor to read from */
587 char *buf; /* buffer */
588 int nleft; /* number of chars in buffer */
589 struct job *jp; /* job structure for command */
597 const struct builtincmd *cmd;
602 struct strlist *next;
608 struct strlist *list;
609 struct strlist **lastp;
613 struct strpush *prev; /* preceding string on stack */
617 struct alias *ap; /* if push was associated with an alias */
619 char *string; /* remember the string since it may change */
623 struct parsefile *prev; /* preceding file on stack */
624 int linno; /* current line */
625 int fd; /* file descriptor (or -1 if string) */
626 int nleft; /* number of chars left in this line */
627 int lleft; /* number of chars left in this buffer */
628 char *nextc; /* next char in buffer */
629 char *buf; /* input buffer */
630 struct strpush *strpush; /* for pushing strings at this level */
631 struct strpush basestrpush; /* so pushing one is fast */
635 struct stack_block *stackp;
638 struct stackmark *marknext;
642 int nparam; /* # of positional parameters (without $0) */
643 unsigned char malloc; /* if parameter list dynamically allocated */
644 char **p; /* parameter list */
645 int optind; /* next parameter to be processed by getopts */
646 int optoff; /* used by getopts */
650 * When commands are first encountered, they are entered in a hash table.
651 * This ensures that a full path search will not have to be done for them
652 * on each invocation.
654 * We should investigate converting to a linear search, even though that
655 * would make the command name "hash" a misnomer.
657 #define CMDTABLESIZE 31 /* should be prime */
658 #define ARB 1 /* actual size determined at run time */
663 struct tblentry *next; /* next entry in hash chain */
664 union param param; /* definition of builtin function */
665 short cmdtype; /* index identifying command */
666 char rehash; /* if set, cd done since entry created */
667 char cmdname[ARB]; /* name of command */
671 static struct tblentry *cmdtable[CMDTABLESIZE];
672 static int builtinloc = -1; /* index in path of %builtin, or -1 */
673 static int exerrno = 0; /* Last exec error */
676 static void tryexec (char *, char **, char **);
677 static void printentry (struct tblentry *, int);
678 static void clearcmdentry (int);
679 static struct tblentry *cmdlookup (const char *, int);
680 static void delete_cmd_entry (void);
681 static int path_change (const char *, int *);
684 static void flushall (void);
685 static void out2fmt (const char *, ...)
686 __attribute__((__format__(__printf__,1,2)));
687 static int xwrite (int, const char *, int);
689 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
690 static void out1str(const char *p) { outstr(p, stdout); }
691 static void out2str(const char *p) { outstr(p, stderr); }
693 #ifndef ASH_OPTIMIZE_FOR_SIZE
694 #define out2c(c) putc((c), stderr)
696 static void out2c(int c) { putc(c, stderr); }
700 #ifdef ASH_OPTIMIZE_FOR_SIZE
701 #define USE_SIT_FUNCTION
704 /* number syntax index */
705 #define BASESYNTAX 0 /* not in quotes */
706 #define DQSYNTAX 1 /* in double quotes */
707 #define SQSYNTAX 2 /* in single quotes */
708 #define ARISYNTAX 3 /* in arithmetic */
710 static const char S_I_T[][4] = {
711 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
712 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
713 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
714 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
715 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
716 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
717 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
718 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
719 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
720 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
721 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
722 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
723 #ifndef USE_SIT_FUNCTION
724 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
725 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
726 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
730 #ifdef USE_SIT_FUNCTION
732 #define U_C(c) ((unsigned char)(c))
734 static int SIT(int c, int syntax)
736 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
737 static const char syntax_index_table [] = {
738 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
739 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
740 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
745 if(c==PEOF) /* 2^8+2 */
747 if(c==PEOA) /* 2^8+1 */
749 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
752 s = strchr(spec_symbls, c);
755 indx = syntax_index_table[(s-spec_symbls)];
757 return S_I_T[indx][syntax];
760 #else /* USE_SIT_FUNCTION */
762 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
764 #define CSPCL_CIGN_CIGN_CIGN 0
765 #define CSPCL_CWORD_CWORD_CWORD 1
766 #define CNL_CNL_CNL_CNL 2
767 #define CWORD_CCTL_CCTL_CWORD 3
768 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
769 #define CVAR_CVAR_CWORD_CVAR 5
770 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
771 #define CSPCL_CWORD_CWORD_CLP 7
772 #define CSPCL_CWORD_CWORD_CRP 8
773 #define CBACK_CBACK_CCTL_CBACK 9
774 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
775 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
776 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
777 #define CWORD_CWORD_CWORD_CWORD 13
778 #define CCTL_CCTL_CCTL_CCTL 14
780 static const char syntax_index_table[258] = {
781 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
782 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
783 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
784 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
785 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
786 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
787 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
788 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
789 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
790 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
791 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
792 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
793 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
794 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
795 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
796 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
797 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
798 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
799 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
800 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
801 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
802 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
803 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
804 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
805 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
806 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
807 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
808 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
809 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
810 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
811 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
812 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
813 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
814 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
815 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
816 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
817 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
818 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
819 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
820 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
821 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
822 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
823 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
824 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
825 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
826 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
827 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
828 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
829 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
830 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
831 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
832 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
833 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
834 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
835 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
836 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
837 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
838 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
839 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
840 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
841 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
842 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
843 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
844 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
845 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
846 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
847 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
848 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
849 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
850 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
851 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
852 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
853 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
854 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
855 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
856 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
857 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
858 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
859 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
860 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
861 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
862 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
863 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
864 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
865 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
866 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
867 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
868 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
869 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
870 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
871 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
872 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
873 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
874 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
875 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
876 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
877 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
878 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
879 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
880 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
881 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
882 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
883 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
884 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
885 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
886 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
887 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
888 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
889 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
890 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
891 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
892 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
893 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
894 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
895 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
896 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
897 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
898 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
899 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
900 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
901 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
902 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
903 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
904 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
905 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
906 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
907 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
908 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
909 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
910 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
911 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
912 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
913 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
914 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
915 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
916 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
917 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
918 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
919 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
920 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
921 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
922 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
923 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
924 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
925 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
926 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
927 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
928 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
929 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
930 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
931 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
932 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
933 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
934 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
935 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
936 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
937 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
938 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
939 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
940 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
941 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
942 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
943 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
944 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
945 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
946 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
947 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
948 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
949 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
950 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
951 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
952 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
953 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
954 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
955 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
956 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
957 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
958 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
959 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
960 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
961 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
962 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
963 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
964 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
965 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
966 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
967 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
968 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
969 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
970 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
971 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
972 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
973 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
974 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
975 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
976 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
977 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
978 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
979 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
980 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
981 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
982 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
983 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
984 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
985 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
986 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
987 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
988 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
989 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
990 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
991 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
992 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
993 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
994 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
995 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
996 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
997 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
998 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
999 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1004 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1005 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1006 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1009 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1032 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1033 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1034 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1035 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1036 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1037 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1038 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1039 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1042 #endif /* USE_SIT_FUNCTION */
1045 /* first char is indicating which tokens mark the end of a list */
1046 static const char *const tokname_array[] = {
1061 #define KWDOFFSET 14
1062 /* the following are keywords */
1081 static const char *tokname(int tok)
1083 static char buf[16];
1087 sprintf(buf+(tok>=TSEMI), "%s%c",
1088 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1092 static int plinno = 1; /* input line number */
1094 static int parselleft; /* copy of parsefile->lleft */
1096 static struct parsefile basepf; /* top level input file */
1097 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1098 static struct parsefile *parsefile = &basepf; /* current input file */
1101 * NEOF is returned by parsecmd when it encounters an end of file. It
1102 * must be distinct from NULL, so we use the address of a variable that
1103 * happens to be handy.
1106 static int tokpushback; /* last token pushed back */
1107 #define NEOF ((union node *)&tokpushback)
1108 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1111 static void error (const char *, ...) __attribute__((__noreturn__));
1112 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1113 static void shellexec (char **, char **, const char *, int)
1114 __attribute__((noreturn));
1115 static void exitshell (int) __attribute__((noreturn));
1117 static int goodname(const char *);
1118 static void ignoresig (int);
1119 static void onsig (int);
1120 static void dotrap (void);
1121 static int decode_signal (const char *, int);
1123 static void shprocvar(void);
1124 static void deletefuncs(void);
1125 static void setparam (char **);
1126 static void freeparam (volatile struct shparam *);
1128 /* reasons for skipping commands (see comment on breakcmd routine) */
1134 /* values of cmdtype */
1135 #define CMDUNKNOWN -1 /* no entry in table for command */
1136 #define CMDNORMAL 0 /* command is an executable program */
1137 #define CMDBUILTIN 1 /* command is a shell builtin */
1138 #define CMDFUNCTION 2 /* command is a shell function */
1140 #define DO_ERR 1 /* find_command prints errors */
1141 #define DO_ABS 2 /* find_command checks absolute paths */
1142 #define DO_NOFUN 4 /* find_command ignores functions */
1143 #define DO_BRUTE 8 /* find_command ignores hash table */
1150 #define VEXPORT 0x01 /* variable is exported */
1151 #define VREADONLY 0x02 /* variable cannot be modified */
1152 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1153 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1154 #define VSTACK 0x10 /* text is allocated on the stack */
1155 #define VUNSET 0x20 /* the variable is not set */
1156 #define VNOFUNC 0x40 /* don't call the callback function */
1160 struct var *next; /* next entry in hash list */
1161 int flags; /* flags are defined above */
1162 char *text; /* name=value */
1163 void (*func) (const char *);
1164 /* function to be called when */
1165 /* the variable gets set/unset */
1169 struct localvar *next; /* next local variable in list */
1170 struct var *vp; /* the variable that was made local */
1171 int flags; /* saved flags */
1172 char *text; /* saved text */
1176 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1177 #define rmescapes(p) _rmescapes((p), 0)
1178 static char *_rmescapes (char *, int);
1180 static void rmescapes (char *);
1183 static int casematch (union node *, const char *);
1184 static void clearredir(void);
1185 static void popstring(void);
1186 static void readcmdfile (const char *);
1188 static int number (const char *);
1189 static int is_number (const char *, int *num);
1190 static char *single_quote (const char *);
1191 static int nextopt (const char *);
1193 static void redirect (union node *, int);
1194 static void popredir (void);
1195 static int dup_as_newfd (int, int);
1197 static void changepath(const char *newval);
1198 static void getoptsreset(const char *value);
1201 static int parsenleft; /* copy of parsefile->nleft */
1202 static char *parsenextc; /* copy of parsefile->nextc */
1203 static int rootpid; /* pid of main shell */
1204 static int rootshell; /* true if we aren't a child of the main shell */
1206 static const char spcstr[] = " ";
1207 static const char snlfmt[] = "%s\n";
1209 static int sstrnleft;
1210 static int herefd = -1;
1212 static struct localvar *localvars;
1214 static struct var vifs;
1215 static struct var vmail;
1216 static struct var vmpath;
1217 static struct var vpath;
1218 static struct var vps1;
1219 static struct var vps2;
1220 static struct var voptind;
1221 #ifdef BB_LOCALE_SUPPORT
1222 static struct var vlc_all;
1223 static struct var vlc_ctype;
1230 void (*func) (const char *);
1233 static const char defpathvar[] =
1234 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1235 #define defpath (defpathvar + 5)
1238 static const char defifsvar[] = "IFS= \t\n";
1239 #define defifs (defifsvar + 4)
1241 static const char defifs[] = " \t\n";
1244 static const struct varinit varinit[] = {
1246 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1248 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1251 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1253 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1255 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1258 * vps1 depends on uid
1260 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1262 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1264 #ifdef BB_LOCALE_SUPPORT
1265 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1267 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1276 static struct var *vartab[VTABSIZE];
1279 * The following macros access the values of the above variables.
1280 * They have to skip over the name. They return the null string
1281 * for unset variables.
1284 #define ifsval() (vifs.text + 4)
1285 #define ifsset() ((vifs.flags & VUNSET) == 0)
1286 #define mailval() (vmail.text + 5)
1287 #define mpathval() (vmpath.text + 9)
1288 #define pathval() (vpath.text + 5)
1289 #define ps1val() (vps1.text + 4)
1290 #define ps2val() (vps2.text + 4)
1291 #define optindval() (voptind.text + 7)
1293 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1295 static void initvar (void);
1296 static void setvar (const char *, const char *, int);
1297 static void setvareq (char *, int);
1298 static void listsetvar (struct strlist *);
1299 static const char *lookupvar (const char *);
1300 static const char *bltinlookup (const char *);
1301 static char **environment (void);
1302 static int showvarscmd (int, char **);
1303 static void mklocal (char *);
1304 static void poplocalvars (void);
1305 static int unsetvar (const char *);
1306 static int varequal (const char *, const char *);
1309 static char *arg0; /* value of $0 */
1310 static struct shparam shellparam; /* current positional parameters */
1311 static char **argptr; /* argument list for builtin commands */
1312 static char *optionarg; /* set by nextopt (like getopt) */
1313 static char *optptr; /* used by nextopt */
1314 static char *minusc; /* argument to -c option */
1319 #define ALIASINUSE 1
1331 static struct alias *atab[ATABSIZE];
1333 static void setalias (char *, char *);
1334 static struct alias **hashalias (const char *);
1335 static struct alias *freealias (struct alias *);
1336 static struct alias **__lookupalias (const char *);
1342 struct alias *ap, **app;
1344 app = __lookupalias(name);
1348 if (!(ap->flag & ALIASINUSE)) {
1351 ap->val = savestr(val);
1352 ap->flag &= ~ALIASDEAD;
1355 ap = ckmalloc(sizeof (struct alias));
1356 ap->name = savestr(name);
1357 ap->val = savestr(val);
1370 app = __lookupalias(name);
1374 *app = freealias(*app);
1385 struct alias *ap, **app;
1389 for (i = 0; i < ATABSIZE; i++) {
1391 for (ap = *app; ap; ap = *app) {
1392 *app = freealias(*app);
1401 static struct alias *
1402 lookupalias(const char *name, int check)
1404 struct alias *ap = *__lookupalias(name);
1406 if (check && ap && (ap->flag & ALIASINUSE))
1412 printalias(const struct alias *ap) {
1415 p = single_quote(ap->val);
1416 printf("alias %s=%s\n", ap->name, p);
1422 * TODO - sort output
1425 aliascmd(int argc, char **argv)
1434 for (i = 0; i < ATABSIZE; i++)
1435 for (ap = atab[i]; ap; ap = ap->next) {
1440 while ((n = *++argv) != NULL) {
1441 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1442 if ((ap = *__lookupalias(n)) == NULL) {
1443 out2fmt("%s: %s not found\n", "alias", n);
1458 unaliascmd(int argc, char **argv)
1462 while ((i = nextopt("a")) != '\0') {
1468 for (i = 0; *argptr; argptr++) {
1469 if (unalias(*argptr)) {
1470 out2fmt("%s: %s not found\n", "unalias", *argptr);
1478 static struct alias **
1482 unsigned int hashval;
1487 return &atab[hashval % ATABSIZE];
1490 static struct alias *
1491 freealias(struct alias *ap) {
1494 if (ap->flag & ALIASINUSE) {
1495 ap->flag |= ALIASDEAD;
1507 static struct alias **
1508 __lookupalias(const char *name) {
1509 struct alias **app = hashalias(name);
1511 for (; *app; app = &(*app)->next) {
1512 if (equal(name, (*app)->name)) {
1521 #ifdef ASH_MATH_SUPPORT
1522 /* The generated file arith.c has been replaced with a custom hand
1523 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1524 * This is now part of libbb, so that it can be used by all the shells
1526 #define ARITH_NUM 257
1527 #define ARITH_LPAREN 258
1528 #define ARITH_RPAREN 259
1529 #define ARITH_OR 260
1530 #define ARITH_AND 261
1531 #define ARITH_BOR 262
1532 #define ARITH_BXOR 263
1533 #define ARITH_BAND 264
1534 #define ARITH_EQ 265
1535 #define ARITH_NE 266
1536 #define ARITH_LT 267
1537 #define ARITH_GT 268
1538 #define ARITH_GE 269
1539 #define ARITH_LE 270
1540 #define ARITH_LSHIFT 271
1541 #define ARITH_RSHIFT 272
1542 #define ARITH_ADD 273
1543 #define ARITH_SUB 274
1544 #define ARITH_MUL 275
1545 #define ARITH_DIV 276
1546 #define ARITH_REM 277
1547 #define ARITH_UNARYMINUS 278
1548 #define ARITH_UNARYPLUS 279
1549 #define ARITH_NOT 280
1550 #define ARITH_BNOT 281
1552 static void expari (int);
1555 static char *trap[NSIG]; /* trap handler commands */
1556 static char sigmode[NSIG - 1]; /* current value of signal */
1557 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1558 static int pendingsigs; /* indicates some signal received */
1561 * This file was generated by the mkbuiltins program.
1565 static int bgcmd (int, char **);
1566 static int fgcmd (int, char **);
1567 static int killcmd (int, char **);
1569 static int bltincmd (int, char **);
1570 static int cdcmd (int, char **);
1571 static int breakcmd (int, char **);
1573 static int commandcmd (int, char **);
1575 static int dotcmd (int, char **);
1576 static int evalcmd (int, char **);
1577 static int execcmd (int, char **);
1578 static int exitcmd (int, char **);
1579 static int exportcmd (int, char **);
1580 static int histcmd (int, char **);
1581 static int hashcmd (int, char **);
1582 static int helpcmd (int, char **);
1583 static int jobscmd (int, char **);
1584 static int localcmd (int, char **);
1586 static int pwdcmd (int, char **);
1588 static int readcmd (int, char **);
1589 static int returncmd (int, char **);
1590 static int setcmd (int, char **);
1591 static int setvarcmd (int, char **);
1592 static int shiftcmd (int, char **);
1593 static int trapcmd (int, char **);
1594 static int umaskcmd (int, char **);
1596 static int aliascmd (int, char **);
1597 static int unaliascmd (int, char **);
1599 static int unsetcmd (int, char **);
1600 static int waitcmd (int, char **);
1601 static int ulimitcmd (int, char **);
1602 static int timescmd (int, char **);
1603 #ifdef ASH_MATH_SUPPORT
1604 static int letcmd (int, char **);
1606 static int typecmd (int, char **);
1608 static int getoptscmd (int, char **);
1611 #ifndef BB_TRUE_FALSE
1612 static int true_main (int, char **);
1613 static int false_main (int, char **);
1616 static void setpwd (const char *, int);
1619 #define BUILTIN_NOSPEC "0"
1620 #define BUILTIN_SPECIAL "1"
1621 #define BUILTIN_REGULAR "2"
1622 #define BUILTIN_ASSIGN "4"
1623 #define BUILTIN_SPEC_ASSG "5"
1624 #define BUILTIN_REG_ASSG "6"
1626 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1627 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1628 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1632 int (*const builtinfunc) (int, char **);
1637 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1638 * the binary search in find_builtin() will stop working. If you value
1639 * your kneecaps, you'll be sure to *make sure* that any changes made
1640 * to this array result in the listing remaining in ascii order. You
1643 static const struct builtincmd builtincmds[] = {
1644 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1645 { BUILTIN_SPECIAL ":", true_main },
1647 { BUILTIN_REG_ASSG "alias", aliascmd },
1650 { BUILTIN_REGULAR "bg", bgcmd },
1652 { BUILTIN_SPECIAL "break", breakcmd },
1653 { BUILTIN_SPECIAL "builtin", bltincmd },
1654 { BUILTIN_REGULAR "cd", cdcmd },
1655 { BUILTIN_NOSPEC "chdir", cdcmd },
1657 { BUILTIN_REGULAR "command", commandcmd },
1659 { BUILTIN_SPECIAL "continue", breakcmd },
1660 { BUILTIN_SPECIAL "eval", evalcmd },
1661 { BUILTIN_SPECIAL "exec", execcmd },
1662 { BUILTIN_SPECIAL "exit", exitcmd },
1663 { BUILTIN_SPEC_ASSG "export", exportcmd },
1664 { BUILTIN_REGULAR "false", false_main },
1665 { BUILTIN_REGULAR "fc", histcmd },
1667 { BUILTIN_REGULAR "fg", fgcmd },
1670 { BUILTIN_REGULAR "getopts", getoptscmd },
1672 { BUILTIN_NOSPEC "hash", hashcmd },
1673 { BUILTIN_NOSPEC "help", helpcmd },
1674 { BUILTIN_REGULAR "jobs", jobscmd },
1676 { BUILTIN_REGULAR "kill", killcmd },
1678 #ifdef ASH_MATH_SUPPORT
1679 { BUILTIN_REGULAR "let", letcmd },
1681 { BUILTIN_ASSIGN "local", localcmd },
1683 { BUILTIN_NOSPEC "pwd", pwdcmd },
1685 { BUILTIN_REGULAR "read", readcmd },
1686 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1687 { BUILTIN_SPECIAL "return", returncmd },
1688 { BUILTIN_SPECIAL "set", setcmd },
1689 { BUILTIN_NOSPEC "setvar", setvarcmd },
1690 { BUILTIN_SPECIAL "shift", shiftcmd },
1691 { BUILTIN_SPECIAL "times", timescmd },
1692 { BUILTIN_SPECIAL "trap", trapcmd },
1693 { BUILTIN_REGULAR "true", true_main },
1694 { BUILTIN_NOSPEC "type", typecmd },
1695 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1696 { BUILTIN_REGULAR "umask", umaskcmd },
1698 { BUILTIN_REGULAR "unalias", unaliascmd },
1700 { BUILTIN_SPECIAL "unset", unsetcmd },
1701 { BUILTIN_REGULAR "wait", waitcmd },
1703 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1705 #define DOTCMD &builtincmds[0]
1706 static struct builtincmd *BLTINCMD;
1707 static struct builtincmd *EXECCMD;
1708 static struct builtincmd *EVALCMD;
1711 #define JOBSTOPPED 1 /* all procs are stopped */
1712 #define JOBDONE 2 /* all procs are completed */
1715 * A job structure contains information about a job. A job is either a
1716 * single process or a set of processes contained in a pipeline. In the
1717 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1722 pid_t pid; /* process id */
1723 int status; /* status flags (defined above) */
1724 char *cmd; /* text of command being run */
1728 static int job_warning; /* user was warned about stopped jobs */
1731 static void setjobctl(int enable);
1733 #define setjobctl(on) /* do nothing */
1738 struct procstat ps0; /* status of process */
1739 struct procstat *ps; /* status or processes when more than one */
1740 short nprocs; /* number of processes */
1741 short pgrp; /* process group of this job */
1742 char state; /* true if job is finished */
1743 char used; /* true if this entry is in used */
1744 char changed; /* true if status has changed */
1746 char jobctl; /* job running under job control */
1750 static struct job *jobtab; /* array of jobs */
1751 static int njobs; /* size of array */
1752 static int backgndpid = -1; /* pid of last background process */
1754 static int initialpgrp; /* pgrp of shell on invocation */
1755 static int curjob; /* current job */
1758 static int intreceived;
1760 static struct job *makejob (const union node *, int);
1761 static int forkshell (struct job *, const union node *, int);
1762 static int waitforjob (struct job *);
1764 static int docd (char *, int);
1765 static char *getcomponent (void);
1766 static void updatepwd (const char *);
1767 static void getpwd (void);
1769 static char *padvance (const char **, const char *);
1771 static char nullstr[1]; /* zero length string */
1772 static char *curdir = nullstr; /* current working directory */
1773 static char *cdcomppath;
1787 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1788 error("HOME not set");
1791 if (dest[0] == '-' && dest[1] == '\0') {
1792 dest = bltinlookup("OLDPWD");
1793 if (!dest || !*dest) {
1802 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1804 while ((p = padvance(&path, dest)) != NULL) {
1805 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1810 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1812 print = strcmp(p, dest);
1814 if (docd(p, print) >= 0)
1819 error("can't cd to %s", dest);
1825 * Actually do the chdir. In an interactive shell, print the
1826 * directory name if "print" is nonzero.
1841 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1844 * Check each component of the path. If we find a symlink or
1845 * something we can't stat, clear curdir to force a getcwd()
1846 * next time we get the value of the current directory.
1849 cdcomppath = sstrdup(dest);
1856 while ((q = getcomponent()) != NULL) {
1857 if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
1865 if (equal(component, ".."))
1868 if ((lstat(stackblock(), &statb) < 0)
1869 || (S_ISLNK(statb.st_mode))) {
1877 if (chdir(dest) < 0) {
1881 updatepwd(badstat ? NULL : dest);
1884 printf(snlfmt, curdir);
1890 * Get the next component of the path name pointed to by cdcomppath.
1891 * This routine overwrites the string pointed to by cdcomppath.
1899 if ((p = cdcomppath) == NULL)
1902 while (*p != '/' && *p != '\0')
1916 * Update curdir (the name of the current directory) in response to a
1917 * cd command. We also call hashcd to let the routines in exec.c know
1918 * that the current directory has changed.
1921 static void hashcd (void);
1924 updatepwd(const char *dir)
1930 hashcd(); /* update command hash table */
1933 * If our argument is NULL, we don't know the current directory
1934 * any more because we traversed a symbolic link or something
1935 * we couldn't stat().
1937 if (dir == NULL || curdir == nullstr) {
1942 cdcomppath = sstrdup(dir);
1951 while ((p = getcomponent()) != NULL) {
1952 if (equal(p, "..")) {
1953 while (new > stackblock() && (STUNPUTC(new), *new) != '/');
1954 } else if (*p != '\0' && ! equal(p, ".")) {
1960 if (new == stackblock())
1963 setpwd(stackblock(), 1);
1973 printf(snlfmt, curdir);
1979 * Find out what the current directory is. If we already know the current
1980 * directory, this routine returns immediately.
1985 curdir = xgetcwd(0);
1991 setpwd(const char *val, int setold)
1994 setvar("OLDPWD", curdir, VEXPORT);
1997 if (curdir != nullstr) {
2004 curdir = savestr(val);
2007 setvar("PWD", curdir, VEXPORT);
2011 * Errors and exceptions.
2015 * Code to handle exceptions in C.
2019 * We enclose jmp_buf in a structure so that we can declare pointers to
2020 * jump locations. The global variable handler contains the location to
2021 * jump to when an exception occurs, and the global variable exception
2022 * contains a code identifying the exeception. To implement nested
2023 * exception handlers, the user should save the value of handler on entry
2024 * to an inner scope, set handler to point to a jmploc structure for the
2025 * inner scope, and restore handler on exit from the scope.
2033 #define EXINT 0 /* SIGINT received */
2034 #define EXERROR 1 /* a generic error */
2035 #define EXSHELLPROC 2 /* execute a shell procedure */
2036 #define EXEXEC 3 /* command execution failed */
2038 static struct jmploc *handler;
2039 static int exception;
2041 static void exverror (int, const char *, va_list)
2042 __attribute__((__noreturn__));
2045 * Called to raise an exception. Since C doesn't include exceptions, we
2046 * just do a longjmp to the exception handler. The type of exception is
2047 * stored in the global variable "exception".
2050 static void exraise (int) __attribute__((__noreturn__));
2056 if (handler == NULL)
2061 longjmp(handler->loc, 1);
2066 * Called from trap.c when a SIGINT is received. (If the user specifies
2067 * that SIGINT is to be trapped or ignored using the trap builtin, then
2068 * this routine is not called.) Suppressint is nonzero when interrupts
2069 * are held using the INTOFF macro. The call to _exit is necessary because
2070 * there is a short period after a fork before the signal handlers are
2071 * set to the appropriate value for the child. (The test for iflag is
2072 * just defensive programming.)
2084 sigemptyset(&mysigset);
2085 sigprocmask(SIG_SETMASK, &mysigset, NULL);
2086 if (rootshell && iflag)
2089 signal(SIGINT, SIG_DFL);
2096 static char *commandname; /* currently executing command */
2099 * Exverror is called to raise the error exception. If the first argument
2100 * is not NULL then error prints an error message using printf style
2101 * formatting. It then raises the error exception.
2104 exverror(int cond, const char *msg, va_list ap)
2111 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
2113 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
2117 out2fmt("%s: ", commandname);
2118 vfprintf(stderr, msg, ap);
2127 error(const char *msg, ...)
2131 exverror(EXERROR, msg, ap);
2138 exerror(int cond, const char *msg, ...)
2142 exverror(cond, msg, ap);
2150 * Table of error messages.
2154 short errcode; /* error number */
2155 char action; /* operation which encountered the error */
2159 * Types of operations (passed to the errmsg routine).
2162 #define E_OPEN 01 /* opening a file */
2163 #define E_CREAT 02 /* creating a file */
2164 #define E_EXEC 04 /* executing a program */
2166 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2168 static const struct errname errormsg[] = {
2173 { ENOENT, E_CREAT },
2175 { ENOTDIR, E_OPEN },
2176 { ENOTDIR, E_CREAT },
2177 { ENOTDIR, E_EXEC },
2179 { EEXIST, E_CREAT },
2218 { ELIBACC, E_EXEC },
2222 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2225 * Return a string describing an error. The returned string may be a
2226 * pointer to a static buffer that will be overwritten on the next call.
2227 * Action describes the operation that got the error.
2231 errmsg(int e, int action)
2233 struct errname const *ep;
2234 static char buf[12];
2236 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2237 if (ep->errcode == e && (ep->action & action) != 0)
2241 snprintf(buf, sizeof buf, "error %d", e);
2246 #ifdef ASH_OPTIMIZE_FOR_SIZE
2249 if (--suppressint == 0 && intpending) {
2253 static void forceinton (void) {
2260 /* flags in argument to evaltree */
2261 #define EV_EXIT 01 /* exit after evaluating tree */
2262 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2263 #define EV_BACKCMD 04 /* command executing within back quotes */
2265 static int evalskip; /* set if we are skipping commands */
2266 static int skipcount; /* number of levels to skip */
2267 static int loopnest; /* current loop nesting level */
2268 static int funcnest; /* depth of function calls */
2271 static struct strlist *cmdenviron; /* environment for builtin command */
2272 static int exitstatus; /* exit status of last command */
2273 static int oexitstatus; /* saved exit status */
2275 static void evalsubshell (const union node *, int);
2276 static void expredir (union node *);
2277 static void prehash (union node *);
2278 static void eprintlist (struct strlist *);
2280 static union node *parsecmd(int);
2282 * Called to reset things after an exception.
2286 * The eval commmand.
2288 static void evalstring (char *, int);
2302 STARTSTACKSTR(concat);
2306 STPUTC(*p++, concat);
2307 if ((p = *ap++) == NULL)
2309 STPUTC(' ', concat);
2311 STPUTC('\0', concat);
2312 p = grabstackstr(concat);
2314 evalstring(p, EV_TESTED);
2320 * Execute a command or commands contained in a string.
2323 static void evaltree (union node *, int);
2324 static void setinputstring (char *);
2325 static void popfile (void);
2326 static void setstackmark(struct stackmark *mark);
2327 static void popstackmark(struct stackmark *mark);
2331 evalstring(char *s, int flag)
2334 struct stackmark smark;
2336 setstackmark(&smark);
2338 while ((n = parsecmd(0)) != NEOF) {
2340 popstackmark(&smark);
2343 popstackmark(&smark);
2346 static struct builtincmd *find_builtin (const char *);
2347 static void expandarg (union node *, struct arglist *, int);
2348 static void calcsize (const union node *);
2349 static union node *copynode (const union node *);
2352 * Make a copy of a parse tree.
2355 static int funcblocksize; /* size of structures in function */
2356 static int funcstringsize; /* size of strings in node */
2357 static pointer funcblock; /* block to allocate function from */
2358 static char *funcstring; /* block to allocate strings from */
2361 static inline union node *
2362 copyfunc(union node *n)
2369 funcblock = ckmalloc(funcblocksize + funcstringsize);
2370 funcstring = (char *) funcblock + funcblocksize;
2375 * Free a parse tree.
2379 freefunc(union node *n)
2387 * Add a new command entry, replacing any existing command entry for
2392 addcmdentry(char *name, struct cmdentry *entry)
2394 struct tblentry *cmdp;
2397 cmdp = cmdlookup(name, 1);
2398 if (cmdp->cmdtype == CMDFUNCTION) {
2399 freefunc(cmdp->param.func);
2401 cmdp->cmdtype = entry->cmdtype;
2402 cmdp->param = entry->u;
2407 evalloop(const union node *n, int flags)
2414 evaltree(n->nbinary.ch1, EV_TESTED);
2416 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2420 if (evalskip == SKIPBREAK && --skipcount <= 0)
2424 if (n->type == NWHILE) {
2425 if (exitstatus != 0)
2428 if (exitstatus == 0)
2431 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2432 status = exitstatus;
2437 exitstatus = status;
2441 evalfor(const union node *n, int flags)
2443 struct arglist arglist;
2446 struct stackmark smark;
2448 setstackmark(&smark);
2449 arglist.lastp = &arglist.list;
2450 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2451 oexitstatus = exitstatus;
2452 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2456 *arglist.lastp = NULL;
2460 for (sp = arglist.list ; sp ; sp = sp->next) {
2461 setvar(n->nfor.var, sp->text, 0);
2462 evaltree(n->nfor.body, flags & EV_TESTED);
2464 if (evalskip == SKIPCONT && --skipcount <= 0) {
2468 if (evalskip == SKIPBREAK && --skipcount <= 0)
2475 popstackmark(&smark);
2479 evalcase(const union node *n, int flags)
2483 struct arglist arglist;
2484 struct stackmark smark;
2486 setstackmark(&smark);
2487 arglist.lastp = &arglist.list;
2488 oexitstatus = exitstatus;
2489 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2490 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2491 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2492 if (casematch(patp, arglist.list->text)) {
2493 if (evalskip == 0) {
2494 evaltree(cp->nclist.body, flags);
2501 popstackmark(&smark);
2505 * Evaluate a pipeline. All the processes in the pipeline are children
2506 * of the process creating the pipeline. (This differs from some versions
2507 * of the shell, which make the last process in a pipeline the parent
2516 struct nodelist *lp;
2521 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2523 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2526 jp = makejob(n, pipelen);
2528 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2532 if (pipe(pip) < 0) {
2534 error("Pipe call failed");
2537 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2541 dup_as_newfd(prevfd, 0);
2553 dup_as_newfd(pip[1], 1);
2557 evaltree(lp->n, EV_EXIT);
2565 if (n->npipe.backgnd == 0) {
2567 exitstatus = waitforjob(jp);
2568 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2573 static void find_command (const char *, struct cmdentry *, int, const char *);
2576 isassignment(const char *word) {
2577 if (!is_name(*word)) {
2582 } while (is_in_name(*word));
2583 return *word == '=';
2588 evalcommand(union node *cmd, int flags)
2590 struct stackmark smark;
2592 struct arglist arglist;
2593 struct arglist varlist;
2599 struct cmdentry cmdentry;
2601 char *volatile savecmdname;
2602 volatile struct shparam saveparam;
2603 struct localvar *volatile savelocalvars;
2607 const struct builtincmd *firstbltin;
2608 struct jmploc *volatile savehandler;
2609 struct jmploc jmploc;
2611 /* Avoid longjmp clobbering */
2618 /* First expand the arguments. */
2619 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2620 setstackmark(&smark);
2621 arglist.lastp = &arglist.list;
2622 varlist.lastp = &varlist.list;
2624 oexitstatus = exitstatus;
2627 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2628 expandarg(argp, &varlist, EXP_VARTILDE);
2631 argp = cmd->ncmd.args; argp && !arglist.list;
2632 argp = argp->narg.next
2634 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2637 struct builtincmd *bcmd;
2639 bcmd = find_builtin(arglist.list->text);
2640 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2641 for (; argp; argp = argp->narg.next) {
2642 if (pseudovarflag && isassignment(argp->narg.text)) {
2643 expandarg(argp, &arglist, EXP_VARTILDE);
2646 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2649 *arglist.lastp = NULL;
2650 *varlist.lastp = NULL;
2651 expredir(cmd->ncmd.redirect);
2653 for (sp = arglist.list ; sp ; sp = sp->next)
2655 argv = stalloc(sizeof (char *) * (argc + 1));
2657 for (sp = arglist.list ; sp ; sp = sp->next) {
2658 TRACE(("evalcommand arg: %s\n", sp->text));
2663 if (iflag && funcnest == 0 && argc > 0)
2667 /* Print the command if xflag is set. */
2670 eprintlist(varlist.list);
2671 eprintlist(arglist.list);
2675 /* Now locate the command. */
2677 cmdentry.cmdtype = CMDBUILTIN;
2678 firstbltin = cmdentry.u.cmd = BLTINCMD;
2680 const char *oldpath;
2681 int findflag = DO_ERR;
2685 * Modify the command lookup path, if a PATH= assignment
2688 for (sp = varlist.list ; sp ; sp = sp->next)
2689 if (varequal(sp->text, defpathvar)) {
2690 path = sp->text + 5;
2691 findflag |= DO_BRUTE;
2694 oldfindflag = findflag;
2697 find_command(argv[0], &cmdentry, findflag, path);
2698 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2702 /* implement bltin and command here */
2703 if (cmdentry.cmdtype != CMDBUILTIN) {
2707 firstbltin = cmdentry.u.cmd;
2709 if (cmdentry.u.cmd == BLTINCMD) {
2711 struct builtincmd *bcmd;
2716 if (!(bcmd = find_builtin(*argv))) {
2717 out2fmt("%s: not found\n", *argv);
2721 cmdentry.u.cmd = bcmd;
2722 if (bcmd != BLTINCMD)
2726 if (cmdentry.u.cmd == find_builtin("command")) {
2731 if (*argv[0] == '-') {
2732 if (!equal(argv[0], "-p")) {
2742 findflag |= DO_BRUTE;
2745 findflag = oldfindflag;
2747 findflag |= DO_NOFUN;
2755 /* Fork off a child process if necessary. */
2756 if (cmd->ncmd.backgnd
2757 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2759 jp = makejob(cmd, 1);
2760 mode = cmd->ncmd.backgnd;
2761 if (forkshell(jp, cmd, mode) != 0)
2762 goto parent; /* at end of routine */
2766 /* This is the child process if a fork occurred. */
2767 /* Execute the command. */
2768 if (cmdentry.cmdtype == CMDFUNCTION) {
2770 trputs("Shell function: "); trargs(argv);
2772 exitstatus = oexitstatus;
2773 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2774 saveparam = shellparam;
2775 shellparam.malloc = 0;
2776 shellparam.nparam = argc - 1;
2777 shellparam.p = argv + 1;
2779 savelocalvars = localvars;
2782 if (setjmp(jmploc.loc)) {
2783 if (exception == EXSHELLPROC) {
2784 freeparam((volatile struct shparam *)
2787 saveparam.optind = shellparam.optind;
2788 saveparam.optoff = shellparam.optoff;
2789 freeparam(&shellparam);
2790 shellparam = saveparam;
2793 localvars = savelocalvars;
2794 handler = savehandler;
2795 longjmp(handler->loc, 1);
2797 savehandler = handler;
2799 for (sp = varlist.list ; sp ; sp = sp->next)
2802 evaltree(cmdentry.u.func, flags & EV_TESTED);
2806 localvars = savelocalvars;
2807 saveparam.optind = shellparam.optind;
2808 saveparam.optoff = shellparam.optoff;
2809 freeparam(&shellparam);
2810 shellparam = saveparam;
2811 handler = savehandler;
2814 if (evalskip == SKIPFUNC) {
2818 if (flags & EV_EXIT)
2819 exitshell(exitstatus);
2820 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2822 trputs("builtin command: "); trargs(argv);
2824 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2825 redirect(cmd->ncmd.redirect, mode);
2826 savecmdname = commandname;
2827 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2828 listsetvar(varlist.list);
2830 cmdenviron = varlist.list;
2833 if (setjmp(jmploc.loc)) {
2835 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2838 savehandler = handler;
2840 commandname = argv[0];
2842 optptr = NULL; /* initialize nextopt */
2843 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2847 if (e != EXSHELLPROC) {
2848 commandname = savecmdname;
2849 if (flags & EV_EXIT)
2850 exitshell(exitstatus);
2852 handler = savehandler;
2854 if ((e != EXERROR && e != EXEXEC)
2855 || cmdentry.u.cmd == BLTINCMD
2856 || cmdentry.u.cmd == DOTCMD
2857 || cmdentry.u.cmd == EVALCMD
2858 || cmdentry.u.cmd == EXECCMD)
2862 if (cmdentry.u.cmd != EXECCMD)
2866 trputs("normal command: "); trargs(argv);
2868 redirect(cmd->ncmd.redirect, 0);
2870 for (sp = varlist.list ; sp ; sp = sp->next)
2871 setvareq(sp->text, VEXPORT|VSTACK);
2872 envp = environment();
2873 shellexec(argv, envp, path, cmdentry.u.index);
2877 parent: /* parent process gets here (if we forked) */
2878 if (mode == 0) { /* argument to fork */
2880 exitstatus = waitforjob(jp);
2886 setvar("_", lastarg, 0);
2887 popstackmark(&smark);
2891 * Evaluate a parse tree. The value is left in the global variable
2901 TRACE(("evaltree(NULL) called\n"));
2904 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2907 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2910 evaltree(n->nbinary.ch2, flags);
2913 evaltree(n->nbinary.ch1, EV_TESTED);
2914 if (evalskip || exitstatus != 0)
2916 evaltree(n->nbinary.ch2, flags);
2919 evaltree(n->nbinary.ch1, EV_TESTED);
2920 if (evalskip || exitstatus == 0)
2922 evaltree(n->nbinary.ch2, flags);
2925 expredir(n->nredir.redirect);
2926 redirect(n->nredir.redirect, REDIR_PUSH);
2927 evaltree(n->nredir.n, flags);
2931 evalsubshell(n, flags);
2934 evalsubshell(n, flags);
2937 evaltree(n->nif.test, EV_TESTED);
2940 if (exitstatus == 0)
2941 evaltree(n->nif.ifpart, flags);
2942 else if (n->nif.elsepart)
2943 evaltree(n->nif.elsepart, flags);
2959 struct builtincmd *bcmd;
2960 struct cmdentry entry;
2962 (bcmd = find_builtin(n->narg.text)) &&
2963 IS_BUILTIN_SPECIAL(bcmd)
2965 out2fmt("%s is a special built-in\n", n->narg.text);
2969 entry.cmdtype = CMDFUNCTION;
2970 entry.u.func = copyfunc(n->narg.next);
2971 addcmdentry(n->narg.text, &entry);
2976 evaltree(n->nnot.com, EV_TESTED);
2977 exitstatus = !exitstatus;
2985 evalcommand(n, flags);
2990 printf("Node type = %d\n", n->type);
2999 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
3001 exitshell(exitstatus);
3005 * Kick off a subshell to evaluate a tree.
3009 evalsubshell(const union node *n, int flags)
3012 int backgnd = (n->type == NBACKGND);
3014 expredir(n->nredir.redirect);
3016 if (forkshell(jp, n, backgnd) == 0) {
3018 flags &=~ EV_TESTED;
3019 redirect(n->nredir.redirect, 0);
3020 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
3024 exitstatus = waitforjob(jp);
3030 * Compute the names of the files in a redirection list.
3033 static void fixredir(union node *n, const char *text, int err);
3036 expredir(union node *n)
3040 for (redir = n ; redir ; redir = redir->nfile.next) {
3042 fn.lastp = &fn.list;
3043 oexitstatus = exitstatus;
3044 switch (redir->type) {
3050 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
3051 redir->nfile.expfname = fn.list->text;
3055 if (redir->ndup.vname) {
3056 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
3057 fixredir(redir, fn.list->text, 1);
3066 * Execute a command inside back quotes. If it's a builtin command, we
3067 * want to save its output in a block obtained from malloc. Otherwise
3068 * we fork off a subprocess and get the output of the command via a pipe.
3069 * Should be called with interrupts off.
3073 evalbackcmd(union node *n, struct backcmd *result)
3077 struct stackmark smark; /* unnecessary */
3079 setstackmark(&smark);
3090 error("Pipe call failed");
3092 if (forkshell(jp, n, FORK_NOJOB) == 0) {
3097 dup_as_newfd(pip[1], 1);
3101 evaltree(n, EV_EXIT);
3104 result->fd = pip[0];
3107 popstackmark(&smark);
3108 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
3109 result->fd, result->buf, result->nleft, result->jp));
3114 * Execute a simple command.
3118 * Search for a command. This is called before we fork so that the
3119 * location of the command will be available in the parent as well as
3120 * the child. The check for "goodname" is an overly conservative
3121 * check that the name will not be subject to expansion.
3128 struct cmdentry entry;
3130 if (n->type == NCMD && n->ncmd.args)
3131 if (goodname(n->ncmd.args->narg.text))
3132 find_command(n->ncmd.args->narg.text, &entry, 0,
3138 * Builtin commands. Builtin commands whose functions are closely
3139 * tied to evaluation are implemented here.
3143 * No command given, or a bltin command with no arguments. Set the
3144 * specified variables.
3148 bltincmd(argc, argv)
3153 * Preserve exitstatus of a previous possible redirection
3161 * Handle break and continue commands. Break, continue, and return are
3162 * all handled by setting the evalskip flag. The evaluation routines
3163 * above all check this flag, and if it is set they start skipping
3164 * commands rather than executing them. The variable skipcount is
3165 * the number of loops to break/continue, or the number of function
3166 * levels to return. (The latter is always 1.) It should probably
3167 * be an error to break out of more loops than exist, but it isn't
3168 * in the standard shell so we don't make it one here.
3172 breakcmd(argc, argv)
3176 int n = argc > 1 ? number(argv[1]) : 1;
3181 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3189 * The return command.
3193 returncmd(argc, argv)
3197 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3200 evalskip = SKIPFUNC;
3205 /* Do what ksh does; skip the rest of the file */
3206 evalskip = SKIPFILE;
3213 #ifndef BB_TRUE_FALSE
3215 false_main(argc, argv)
3224 true_main(argc, argv)
3233 * Controls whether the shell is interactive or not.
3236 static void setsignal(int signo);
3237 static void chkmail(int silent);
3241 setinteractive(int on)
3243 static int is_interactive;
3244 static int do_banner=0;
3246 if (on == is_interactive)
3252 is_interactive = on;
3253 if (do_banner==0 && is_interactive) {
3254 /* Looks like they want an interactive shell */
3255 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3256 printf( "Enter 'help' for a list of built-in commands.\n\n");
3264 setinteractive(iflag);
3277 iflag = 0; /* exit on error */
3280 for (sp = cmdenviron; sp ; sp = sp->next)
3281 setvareq(sp->text, VEXPORT|VSTACK);
3282 shellexec(argv + 1, environment(), pathval(), 0);
3288 eprintlist(struct strlist *sp)
3290 for (; sp; sp = sp->next) {
3291 out2fmt(" %s",sp->text);
3296 * Exec a program. Never returns. If you change this routine, you may
3297 * have to change the find_command routine as well.
3300 static const char *pathopt; /* set by padvance */
3303 shellexec(argv, envp, path, idx)
3304 char **argv, **envp;
3311 if (strchr(argv[0], '/') != NULL) {
3312 tryexec(argv[0], argv, envp);
3316 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3317 if (--idx < 0 && pathopt == NULL) {
3318 tryexec(cmdname, argv, envp);
3319 if (errno != ENOENT && errno != ENOTDIR)
3326 /* Map to POSIX errors */
3338 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3343 * Clear traps on a fork.
3349 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3350 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3355 setsignal(tp - trap);
3363 initshellproc(void) {
3389 /* from options.c: */
3393 for (i = 0; i < NOPTS; i++)
3409 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3421 static int preadbuffer(void);
3422 static void pushfile (void);
3425 * Read a character from the script, returning PEOF on end of file.
3426 * Nul characters in the input are silently discarded.
3429 #ifndef ASH_OPTIMIZE_FOR_SIZE
3430 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3434 return pgetc_macro();
3440 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3446 return pgetc_macro();
3452 * Undo the last call to pgetc. Only one character may be pushed back.
3453 * PEOF may be pushed back.
3465 struct parsefile *pf = parsefile;
3474 parsefile = pf->prev;
3476 parsenleft = parsefile->nleft;
3477 parselleft = parsefile->lleft;
3478 parsenextc = parsefile->nextc;
3479 plinno = parsefile->linno;
3485 * Return to top level.
3490 while (parsefile != &basepf)
3495 * Close the file(s) that the shell is reading commands from. Called
3496 * after a fork is done.
3502 if (parsefile->fd > 0) {
3503 close(parsefile->fd);
3510 * Like setinputfile, but takes an open file descriptor. Call this with
3515 setinputfd(fd, push)
3518 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3524 while (parsefile->strpush)
3528 if (parsefile->buf == NULL)
3529 parsefile->buf = ckmalloc(BUFSIZ);
3530 parselleft = parsenleft = 0;
3536 * Set the input to take input from a file. If push is set, push the
3537 * old input onto the stack first.
3541 setinputfile(const char *fname, int push)
3547 if ((fd = open(fname, O_RDONLY)) < 0)
3548 error("Can't open %s", fname);
3550 myfileno2 = dup_as_newfd(fd, 10);
3553 error("Out of file descriptors");
3556 setinputfd(fd, push);
3562 tryexec(char *cmd, char **argv, char **envp)
3566 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
3570 #ifdef BB_FEATURE_SH_APPLETS_ALWAYS_WIN
3571 name = get_last_path_component(name);
3574 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3577 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3579 run_applet_by_name(name, argc_l, argv);
3581 execve(cmd, argv, envp);
3586 setinputfile(cmd, 0);
3587 commandname = arg0 = savestr(argv[0]);
3589 exraise(EXSHELLPROC);
3594 static char *commandtext (const union node *);
3597 * Do a path search. The variable path (passed by reference) should be
3598 * set to the start of the path before the first call; padvance will update
3599 * this value as it proceeds. Successive calls to padvance will return
3600 * the possible path expansions in sequence. If an option (indicated by
3601 * a percent sign) appears in the path entry then the global variable
3602 * pathopt will be set to point to it; otherwise pathopt will be set to
3606 static const char *pathopt;
3608 static void growstackblock(void);
3612 padvance(const char **path, const char *name)
3622 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3623 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3624 while (stackblocksize() < len)
3628 memcpy(q, start, p - start);
3636 while (*p && *p != ':') p++;
3642 return stalloc(len);
3646 * Wrapper around strcmp for qsort/bsearch/...
3649 pstrcmp(const void *a, const void *b)
3651 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3655 * Find a keyword is in a sorted array.
3658 static const char *const *
3659 findkwd(const char *s)
3661 return bsearch(s, tokname_array + KWDOFFSET,
3662 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3663 sizeof(const char *), pstrcmp);
3667 /*** Command hashing code ***/
3675 struct tblentry **pp;
3676 struct tblentry *cmdp;
3679 struct cmdentry entry;
3682 const struct alias *ap;
3686 while ((c = nextopt("rvV")) != '\0') {
3690 } else if (c == 'v' || c == 'V') {
3694 if (*argptr == NULL) {
3695 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3696 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3697 if (cmdp->cmdtype != CMDBUILTIN) {
3698 printentry(cmdp, verbose);
3705 while ((name = *argptr++) != NULL) {
3706 if ((cmdp = cmdlookup(name, 0)) != NULL
3707 && (cmdp->cmdtype == CMDNORMAL
3708 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3711 /* Then look at the aliases */
3712 if ((ap = lookupalias(name, 0)) != NULL) {
3714 printf("%s is an alias for %s\n", name, ap->val);
3720 /* First look at the keywords */
3721 if (findkwd(name)!=0) {
3723 printf("%s is a shell keyword\n", name);
3725 printf(snlfmt, name);
3729 find_command(name, &entry, DO_ERR, pathval());
3730 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3732 cmdp = cmdlookup(name, 0);
3733 if (cmdp) printentry(cmdp, verbose=='v');
3741 printentry(cmdp, verbose)
3742 struct tblentry *cmdp;
3749 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3750 if (cmdp->cmdtype == CMDNORMAL) {
3751 idx = cmdp->param.index;
3754 name = padvance(&path, cmdp->cmdname);
3756 } while (--idx >= 0);
3759 } else if (cmdp->cmdtype == CMDBUILTIN) {
3761 out1str("a shell builtin");
3762 } else if (cmdp->cmdtype == CMDFUNCTION) {
3765 out1str("a function\n");
3766 name = commandtext(cmdp->param.func);
3767 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3773 error("internal error: cmdtype %d", cmdp->cmdtype);
3776 printf(snlfmt, cmdp->rehash ? "*" : nullstr);
3781 /*** List the available builtins ***/
3784 static int helpcmd(int argc, char** argv)
3788 printf("\nBuilt-in commands:\n-------------------\n");
3789 for (col=0, i=0; i < NUMBUILTINS; i++) {
3790 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3791 builtincmds[i].name+1);
3797 #ifdef BB_FEATURE_SH_STANDALONE_SHELL
3799 extern const struct BB_applet applets[];
3800 extern const size_t NUM_APPLETS;
3802 for (i=0; i < NUM_APPLETS; i++) {
3804 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3814 return EXIT_SUCCESS;
3818 * Resolve a command name. If you change this routine, you may have to
3819 * change the shellexec routine as well.
3822 static int prefix (const char *, const char *);
3825 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3827 struct tblentry *cmdp;
3837 struct builtincmd *bcmd;
3839 /* If name contains a slash, don't use the hash table */
3840 if (strchr(name, '/') != NULL) {
3842 while (stat(name, &statb) < 0) {
3843 if (errno != ENOENT && errno != ENOTDIR)
3845 entry->cmdtype = CMDUNKNOWN;
3846 entry->u.index = -1;
3849 entry->cmdtype = CMDNORMAL;
3850 entry->u.index = -1;
3853 entry->cmdtype = CMDNORMAL;
3859 if (act & DO_BRUTE) {
3860 firstchange = path_change(path, &bltin);
3866 /* If name is in the table, and not invalidated by cd, we're done */
3867 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3868 if (cmdp->cmdtype == CMDFUNCTION) {
3869 if (act & DO_NOFUN) {
3874 } else if (act & DO_BRUTE) {
3875 if ((cmdp->cmdtype == CMDNORMAL &&
3876 cmdp->param.index >= firstchange) ||
3877 (cmdp->cmdtype == CMDBUILTIN &&
3878 ((builtinloc < 0 && bltin >= 0) ?
3879 bltin : builtinloc) >= firstchange)) {
3880 /* need to recompute the entry */
3889 bcmd = find_builtin(name);
3890 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3893 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3896 } else if (act & DO_BRUTE) {
3897 if (firstchange == 0) {
3902 /* If %builtin not in path, check for builtin next */
3903 if (regular || (bltin < 0 && bcmd)) {
3906 entry->cmdtype = CMDBUILTIN;
3907 entry->u.cmd = bcmd;
3911 cmdp = cmdlookup(name, 1);
3912 cmdp->cmdtype = CMDBUILTIN;
3913 cmdp->param.cmd = bcmd;
3918 /* We have to search path. */
3919 prev = -1; /* where to start */
3920 if (cmdp && cmdp->rehash) { /* doing a rehash */
3921 if (cmdp->cmdtype == CMDBUILTIN)
3924 prev = cmdp->param.index;
3930 while ((fullname = padvance(&path, name)) != NULL) {
3931 stunalloc(fullname);
3933 if (idx >= firstchange) {
3937 if (prefix("builtin", pathopt)) {
3938 if ((bcmd = find_builtin(name))) {
3942 } else if (!(act & DO_NOFUN) &&
3943 prefix("func", pathopt)) {
3946 continue; /* ignore unimplemented options */
3949 /* if rehash, don't redo absolute path names */
3950 if (fullname[0] == '/' && idx <= prev &&
3951 idx < firstchange) {
3954 TRACE(("searchexec \"%s\": no change\n", name));
3957 while (stat(fullname, &statb) < 0) {
3958 if (errno != ENOENT && errno != ENOTDIR)
3962 e = EACCES; /* if we fail, this will be the error */
3963 if (!S_ISREG(statb.st_mode))
3965 if (pathopt) { /* this is a %func directory */
3966 stalloc(strlen(fullname) + 1);
3967 readcmdfile(fullname);
3968 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3969 error("%s not defined in %s", name, fullname);
3970 stunalloc(fullname);
3973 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3974 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3975 be a function and we're being called with DO_NOFUN */
3977 entry->cmdtype = CMDNORMAL;
3978 entry->u.index = idx;
3982 cmdp = cmdlookup(name, 1);
3983 cmdp->cmdtype = CMDNORMAL;
3984 cmdp->param.index = idx;
3989 /* We failed. If there was an entry for this command, delete it */
3990 if (cmdp && updatetbl)
3993 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3994 entry->cmdtype = CMDUNKNOWN;
3999 entry->cmdtype = cmdp->cmdtype;
4000 entry->u = cmdp->param;
4006 * Search the table of builtin commands.
4010 bstrcmp(const void *name, const void *b)
4012 return strcmp((const char *)name, (*(const char *const *) b)+1);
4015 static struct builtincmd *
4016 find_builtin(const char *name)
4018 struct builtincmd *bp;
4020 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
4028 * Called when a cd is done. Marks all commands so the next time they
4029 * are executed they will be rehashed.
4034 struct tblentry **pp;
4035 struct tblentry *cmdp;
4037 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
4038 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4039 if (cmdp->cmdtype == CMDNORMAL
4040 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
4049 * Called before PATH is changed. The argument is the new value of PATH;
4050 * pathval() still returns the old value at this point. Called with
4055 changepath(const char *newval)
4060 firstchange = path_change(newval, &bltin);
4061 if (builtinloc < 0 && bltin >= 0)
4062 builtinloc = bltin; /* zap builtins */
4063 clearcmdentry(firstchange);
4069 * Clear out command entries. The argument specifies the first entry in
4070 * PATH which has changed.
4074 clearcmdentry(firstchange)
4077 struct tblentry **tblp;
4078 struct tblentry **pp;
4079 struct tblentry *cmdp;
4082 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4084 while ((cmdp = *pp) != NULL) {
4085 if ((cmdp->cmdtype == CMDNORMAL &&
4086 cmdp->param.index >= firstchange)
4087 || (cmdp->cmdtype == CMDBUILTIN &&
4088 builtinloc >= firstchange)) {
4101 * Delete all functions.
4106 struct tblentry **tblp;
4107 struct tblentry **pp;
4108 struct tblentry *cmdp;
4111 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4113 while ((cmdp = *pp) != NULL) {
4114 if (cmdp->cmdtype == CMDFUNCTION) {
4116 freefunc(cmdp->param.func);
4129 * Locate a command in the command hash table. If "add" is nonzero,
4130 * add the command to the table if it is not already present. The
4131 * variable "lastcmdentry" is set to point to the address of the link
4132 * pointing to the entry, so that delete_cmd_entry can delete the
4136 static struct tblentry **lastcmdentry;
4138 static struct tblentry *
4139 cmdlookup(const char *name, int add)
4143 struct tblentry *cmdp;
4144 struct tblentry **pp;
4151 pp = &cmdtable[hashval % CMDTABLESIZE];
4152 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4153 if (equal(cmdp->cmdname, name))
4157 if (add && cmdp == NULL) {
4159 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4160 + strlen(name) + 1);
4162 cmdp->cmdtype = CMDUNKNOWN;
4164 strcpy(cmdp->cmdname, name);
4172 * Delete the command entry returned on the last lookup.
4176 delete_cmd_entry() {
4177 struct tblentry *cmdp;
4180 cmdp = *lastcmdentry;
4181 *lastcmdentry = cmdp->next;
4190 static const unsigned char nodesize[26] = {
4191 ALIGN(sizeof (struct nbinary)),
4192 ALIGN(sizeof (struct ncmd)),
4193 ALIGN(sizeof (struct npipe)),
4194 ALIGN(sizeof (struct nredir)),
4195 ALIGN(sizeof (struct nredir)),
4196 ALIGN(sizeof (struct nredir)),
4197 ALIGN(sizeof (struct nbinary)),
4198 ALIGN(sizeof (struct nbinary)),
4199 ALIGN(sizeof (struct nif)),
4200 ALIGN(sizeof (struct nbinary)),
4201 ALIGN(sizeof (struct nbinary)),
4202 ALIGN(sizeof (struct nfor)),
4203 ALIGN(sizeof (struct ncase)),
4204 ALIGN(sizeof (struct nclist)),
4205 ALIGN(sizeof (struct narg)),
4206 ALIGN(sizeof (struct narg)),
4207 ALIGN(sizeof (struct nfile)),
4208 ALIGN(sizeof (struct nfile)),
4209 ALIGN(sizeof (struct nfile)),
4210 ALIGN(sizeof (struct nfile)),
4211 ALIGN(sizeof (struct nfile)),
4212 ALIGN(sizeof (struct ndup)),
4213 ALIGN(sizeof (struct ndup)),
4214 ALIGN(sizeof (struct nhere)),
4215 ALIGN(sizeof (struct nhere)),
4216 ALIGN(sizeof (struct nnot)),
4222 * Delete a function if it exists.
4226 unsetfunc(char *name)
4228 struct tblentry *cmdp;
4230 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4231 freefunc(cmdp->param.func);
4238 * Locate and print what a word is...
4242 typecmd(int argc, char **argv)
4250 for (i = 1; i < argc; i++) {
4251 argv_a[0] = argv[i];
4254 err |= hashcmd(argc, argv);
4261 commandcmd(argc, argv)
4266 int default_path = 0;
4267 int verify_only = 0;
4268 int verbose_verify_only = 0;
4270 while ((c = nextopt("pvV")) != '\0')
4279 verbose_verify_only = 1;
4283 if (default_path + verify_only + verbose_verify_only > 1 ||
4286 "command [-p] command [arg ...]\n"
4287 "command {-v|-V} command\n");
4291 if (verify_only || verbose_verify_only) {
4295 argv_a[0] = *argptr;
4297 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4298 return hashcmd(argc, argv);
4306 path_change(newval, bltin)
4310 const char *old, *new;
4316 firstchange = 9999; /* assume no change */
4322 if ((*old == '\0' && *new == ':')
4323 || (*old == ':' && *new == '\0'))
4325 old = new; /* ignore subsequent differences */
4329 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4336 if (builtinloc >= 0 && *bltin < 0)
4341 * Routines to expand arguments to commands. We have to deal with
4342 * backquotes, shell variables, and file metacharacters.
4347 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4348 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4351 * Structure specifying which parts of the string should be searched
4352 * for IFS characters.
4356 struct ifsregion *next; /* next region in list */
4357 int begoff; /* offset of start of region */
4358 int endoff; /* offset of end of region */
4359 int nulonly; /* search for nul bytes only */
4363 static char *expdest; /* output of current string */
4364 static struct nodelist *argbackq; /* list of back quote expressions */
4365 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4366 static struct ifsregion *ifslastp; /* last struct in list */
4367 static struct arglist exparg; /* holds expanded arg list */
4369 static void argstr (char *, int);
4370 static char *exptilde (char *, int);
4371 static void expbackq (union node *, int, int);
4372 static int subevalvar (char *, char *, int, int, int, int, int);
4373 static int varisset (char *, int);
4374 static void strtodest (const char *, int, int);
4375 static void varvalue (char *, int, int);
4376 static void recordregion (int, int, int);
4377 static void removerecordregions (int);
4378 static void ifsbreakup (char *, struct arglist *);
4379 static void ifsfree (void);
4380 static void expandmeta (struct strlist *, int);
4381 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4382 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4383 #if !defined(GLOB_BROKEN)
4384 static void addglob (const glob_t *);
4387 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4388 static void expmeta (char *, char *);
4390 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4391 static struct strlist *expsort (struct strlist *);
4392 static struct strlist *msort (struct strlist *, int);
4394 static int patmatch (char *, char *, int);
4395 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4396 static int patmatch2 (char *, char *, int);
4398 static int pmatch (char *, char *, int);
4399 #define patmatch2 patmatch
4401 static char *cvtnum (int, char *);
4404 * Expand shell variables and backquotes inside a here document.
4407 /* arg: the document, fd: where to write the expanded version */
4409 expandhere(union node *arg, int fd)
4412 expandarg(arg, (struct arglist *)NULL, 0);
4413 xwrite(fd, stackblock(), expdest - stackblock());
4418 * Perform variable substitution and command substitution on an argument,
4419 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4420 * perform splitting and file name expansion. When arglist is NULL, perform
4421 * here document expansion.
4425 expandarg(arg, arglist, flag)
4427 struct arglist *arglist;
4433 argbackq = arg->narg.backquote;
4434 STARTSTACKSTR(expdest);
4435 ifsfirst.next = NULL;
4437 argstr(arg->narg.text, flag);
4438 if (arglist == NULL) {
4439 return; /* here document expanded */
4441 STPUTC('\0', expdest);
4442 p = grabstackstr(expdest);
4443 exparg.lastp = &exparg.list;
4447 if (flag & EXP_FULL) {
4448 ifsbreakup(p, &exparg);
4449 *exparg.lastp = NULL;
4450 exparg.lastp = &exparg.list;
4451 expandmeta(exparg.list, flag);
4453 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4455 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4458 exparg.lastp = &sp->next;
4461 *exparg.lastp = NULL;
4463 *arglist->lastp = exparg.list;
4464 arglist->lastp = exparg.lastp;
4470 * Expand a variable, and return a pointer to the next character in the
4474 static inline char *
4490 int quotes = flag & (EXP_FULL | EXP_CASE);
4493 subtype = varflags & VSTYPE;
4498 p = strchr(p, '=') + 1;
4499 again: /* jump here after setting a variable with ${var=text} */
4501 set = varisset(var, varflags & VSNUL);
4504 val = lookupvar(var);
4505 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4512 startloc = expdest - stackblock();
4513 if (set && subtype != VSPLUS) {
4514 /* insert the value of the variable */
4516 varvalue(var, varflags & VSQUOTE, flag);
4517 if (subtype == VSLENGTH) {
4518 varlen = expdest - stackblock() - startloc;
4519 STADJUST(-varlen, expdest);
4522 if (subtype == VSLENGTH) {
4523 varlen = strlen(val);
4527 varflags & VSQUOTE ?
4528 DQSYNTAX : BASESYNTAX,
4535 if (subtype == VSPLUS)
4538 easy = ((varflags & VSQUOTE) == 0 ||
4539 (*var == '@' && shellparam.nparam != 1));
4544 expdest = cvtnum(varlen, expdest);
4551 recordregion(startloc, expdest - stackblock(),
4552 varflags & VSQUOTE);
4568 case VSTRIMRIGHTMAX:
4572 * Terminate the string and start recording the pattern
4575 STPUTC('\0', expdest);
4576 patloc = expdest - stackblock();
4577 if (subevalvar(p, NULL, patloc, subtype,
4578 startloc, varflags, quotes) == 0) {
4579 int amount = (expdest - stackblock() - patloc) + 1;
4580 STADJUST(-amount, expdest);
4582 /* Remove any recorded regions beyond start of variable */
4583 removerecordregions(startloc);
4589 if (subevalvar(p, var, 0, subtype, startloc,
4590 varflags, quotes)) {
4593 * Remove any recorded regions beyond
4596 removerecordregions(startloc);
4611 if (subtype != VSNORMAL) { /* skip to end of alternative */
4614 if ((c = *p++) == CTLESC)
4616 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4618 argbackq = argbackq->next;
4619 } else if (c == CTLVAR) {
4620 if ((*p++ & VSTYPE) != VSNORMAL)
4622 } else if (c == CTLENDVAR) {
4633 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4634 * characters to allow for further processing. Otherwise treat
4635 * $@ like $* since no splitting will be performed.
4644 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4647 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4648 p = exptilde(p, flag);
4652 case CTLENDVAR: /* ??? */
4655 /* "$@" syntax adherence hack */
4656 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4658 if ((flag & EXP_FULL) != 0)
4668 p = evalvar(p, flag);
4671 case CTLBACKQ|CTLQUOTE:
4672 expbackq(argbackq->n, c & CTLQUOTE, flag);
4673 argbackq = argbackq->next;
4675 #ifdef ASH_MATH_SUPPORT
4683 * sort of a hack - expand tildes in variable
4684 * assignments (after the first '=' and after ':'s).
4687 if (flag & EXP_VARTILDE && *p == '~') {
4694 p = exptilde(p, flag);
4710 char c, *startp = p;
4713 int quotes = flag & (EXP_FULL | EXP_CASE);
4715 while ((c = *p) != '\0') {
4722 if (flag & EXP_VARTILDE)
4732 if (*(startp+1) == '\0') {
4733 if ((home = lookupvar("HOME")) == NULL)
4736 if ((pw = getpwnam(startp+1)) == NULL)
4743 strtodest(home, SQSYNTAX, quotes);
4752 removerecordregions(int endoff)
4754 if (ifslastp == NULL)
4757 if (ifsfirst.endoff > endoff) {
4758 while (ifsfirst.next != NULL) {
4759 struct ifsregion *ifsp;
4761 ifsp = ifsfirst.next->next;
4762 ckfree(ifsfirst.next);
4763 ifsfirst.next = ifsp;
4766 if (ifsfirst.begoff > endoff)
4769 ifslastp = &ifsfirst;
4770 ifsfirst.endoff = endoff;
4775 ifslastp = &ifsfirst;
4776 while (ifslastp->next && ifslastp->next->begoff < endoff)
4777 ifslastp=ifslastp->next;
4778 while (ifslastp->next != NULL) {
4779 struct ifsregion *ifsp;
4781 ifsp = ifslastp->next->next;
4782 ckfree(ifslastp->next);
4783 ifslastp->next = ifsp;
4786 if (ifslastp->endoff > endoff)
4787 ifslastp->endoff = endoff;
4791 #ifdef ASH_MATH_SUPPORT
4793 * Expand arithmetic expression. Backup to start of expression,
4794 * evaluate, place result in (backed up) result, adjust string position.
4803 int quotes = flag & (EXP_FULL | EXP_CASE);
4809 * This routine is slightly over-complicated for
4810 * efficiency. First we make sure there is
4811 * enough space for the result, which may be bigger
4812 * than the expression if we add exponentation. Next we
4813 * scan backwards looking for the start of arithmetic. If the
4814 * next previous character is a CTLESC character, then we
4815 * have to rescan starting from the beginning since CTLESC
4816 * characters have to be processed left to right.
4818 CHECKSTRSPACE(10, expdest);
4819 USTPUTC('\0', expdest);
4820 start = stackblock();
4822 while (*p != CTLARI && p >= start)
4825 error("missing CTLARI (shouldn't happen)");
4826 if (p > start && *(p-1) == CTLESC)
4827 for (p = start; *p != CTLARI; p++)
4836 removerecordregions(begoff);
4839 result = arith(p+2, &errcode);
4842 error("divide by zero");
4844 error("syntax error: \"%s\"\n", p+2);
4846 snprintf(p, 12, "%d", result);
4852 recordregion(begoff, p - 1 - start, 0);
4853 result = expdest - p + 1;
4854 STADJUST(-result, expdest);
4859 * Expand stuff in backwards quotes.
4863 expbackq(cmd, quoted, flag)
4868 volatile struct backcmd in;
4872 char *dest = expdest;
4873 volatile struct ifsregion saveifs;
4874 struct ifsregion *volatile savelastp;
4875 struct nodelist *volatile saveargbackq;
4877 int startloc = dest - stackblock();
4878 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4879 volatile int saveherefd;
4880 int quotes = flag & (EXP_FULL | EXP_CASE);
4881 struct jmploc jmploc;
4882 struct jmploc *volatile savehandler;
4886 /* Avoid longjmp clobbering */
4897 savelastp = ifslastp;
4898 saveargbackq = argbackq;
4899 saveherefd = herefd;
4901 if ((ex = setjmp(jmploc.loc))) {
4904 savehandler = handler;
4907 p = grabstackstr(dest);
4908 evalbackcmd(cmd, (struct backcmd *) &in);
4909 ungrabstackstr(p, dest);
4913 ifslastp = savelastp;
4914 argbackq = saveargbackq;
4915 herefd = saveherefd;
4923 if (--in.nleft < 0) {
4926 i = safe_read(in.fd, buf, sizeof buf);
4927 TRACE(("expbackq: read returns %d\n", i));
4934 if (lastc != '\0') {
4935 if (quotes && SIT(lastc, syntax) == CCTL)
4936 STPUTC(CTLESC, dest);
4937 STPUTC(lastc, dest);
4941 /* Eat all trailing newlines */
4942 for (; dest > stackblock() && dest[-1] == '\n';)
4951 exitstatus = waitforjob(in.jp);
4952 handler = savehandler;
4954 longjmp(handler->loc, 1);
4957 recordregion(startloc, dest - stackblock(), 0);
4958 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4959 (dest - stackblock()) - startloc,
4960 (dest - stackblock()) - startloc,
4961 stackblock() + startloc));
4967 subevalvar(p, str, strloc, subtype, startloc, varflags, quotes)
4980 int saveherefd = herefd;
4981 struct nodelist *saveargbackq = argbackq;
4985 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4986 STACKSTRNUL(expdest);
4987 herefd = saveherefd;
4988 argbackq = saveargbackq;
4989 startp = stackblock() + startloc;
4991 str = stackblock() + strloc;
4995 setvar(str, startp, 0);
4996 amount = startp - expdest;
4997 STADJUST(amount, expdest);
5004 if (*p != CTLENDVAR) {
5005 out2fmt(snlfmt, startp);
5006 error((char *)NULL);
5008 error("%.*s: parameter %snot set", p - str - 1,
5009 str, (varflags & VSNUL) ? "null or "
5014 for (loc = startp; loc < str; loc++) {
5017 if (patmatch2(str, startp, quotes))
5020 if (quotes && *loc == CTLESC)
5026 for (loc = str - 1; loc >= startp;) {
5029 if (patmatch2(str, startp, quotes))
5033 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
5034 for (q = startp; q < loc; q++)
5044 for (loc = str - 1; loc >= startp;) {
5045 if (patmatch2(str, loc, quotes))
5048 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
5049 for (q = startp; q < loc; q++)
5058 case VSTRIMRIGHTMAX:
5059 for (loc = startp; loc < str - 1; loc++) {
5060 if (patmatch2(str, loc, quotes))
5062 if (quotes && *loc == CTLESC)
5075 amount = ((str - 1) - (loc - startp)) - expdest;
5076 STADJUST(amount, expdest);
5077 while (loc != str - 1)
5082 amount = loc - expdest;
5083 STADJUST(amount, expdest);
5084 STPUTC('\0', expdest);
5085 STADJUST(-1, expdest);
5091 * Test whether a specialized variable is set.
5095 varisset(name, nulok)
5100 return backgndpid != -1;
5101 else if (*name == '@' || *name == '*') {
5102 if (*shellparam.p == NULL)
5108 for (av = shellparam.p; *av; av++)
5113 } else if (is_digit(*name)) {
5115 int num = atoi(name);
5117 if (num > shellparam.nparam)
5123 ap = shellparam.p[num - 1];
5125 if (nulok && (ap == NULL || *ap == '\0'))
5132 * Put a string on the stack.
5136 strtodest(const char *p, int syntax, int quotes)
5139 if (quotes && SIT(*p,syntax) == CCTL)
5140 STPUTC(CTLESC, expdest);
5141 STPUTC(*p++, expdest);
5146 * Add the value of a specialized variable to the stack string.
5150 varvalue(char *name, int quoted, int flags)
5159 int allow_split = flags & EXP_FULL;
5160 int quotes = flags & (EXP_FULL | EXP_CASE);
5162 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5171 num = shellparam.nparam;
5176 expdest = cvtnum(num, expdest);
5179 for (i = 0 ; i < NOPTS ; i++) {
5181 STPUTC(optent_letter(optlist[i]), expdest);
5185 if (allow_split && quoted) {
5186 sep = 1 << CHAR_BIT;
5191 sep = ifsset() ? ifsval()[0] : ' ';
5193 sepq = SIT(sep,syntax) == CCTL;
5196 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
5197 strtodest(p, syntax, quotes);
5200 STPUTC(CTLESC, expdest);
5201 STPUTC(sep, expdest);
5206 strtodest(arg0, syntax, quotes);
5210 if (num > 0 && num <= shellparam.nparam) {
5211 strtodest(shellparam.p[num - 1], syntax, quotes);
5219 * Record the fact that we have to scan this region of the
5220 * string for IFS characters.
5224 recordregion(start, end, nulonly)
5229 struct ifsregion *ifsp;
5231 if (ifslastp == NULL) {
5235 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5237 ifslastp->next = ifsp;
5241 ifslastp->begoff = start;
5242 ifslastp->endoff = end;
5243 ifslastp->nulonly = nulonly;
5249 * Break the argument string into pieces based upon IFS and add the
5250 * strings to the argument list. The regions of the string to be
5251 * searched for IFS characters have been stored by recordregion.
5254 ifsbreakup(string, arglist)
5256 struct arglist *arglist;
5258 struct ifsregion *ifsp;
5263 const char *ifs, *realifs;
5271 realifs = ifsset() ? ifsval() : defifs;
5272 if (ifslastp != NULL) {
5275 p = string + ifsp->begoff;
5276 nulonly = ifsp->nulonly;
5277 ifs = nulonly ? nullstr : realifs;
5279 while (p < string + ifsp->endoff) {
5283 if (strchr(ifs, *p)) {
5285 ifsspc = (strchr(defifs, *p) != NULL);
5286 /* Ignore IFS whitespace at start */
5287 if (q == start && ifsspc) {
5293 sp = (struct strlist *)stalloc(sizeof *sp);
5295 *arglist->lastp = sp;
5296 arglist->lastp = &sp->next;
5300 if (p >= string + ifsp->endoff) {
5306 if (strchr(ifs, *p) == NULL ) {
5309 } else if (strchr(defifs, *p) == NULL) {
5325 } while ((ifsp = ifsp->next) != NULL);
5326 if (!(*start || (!ifsspc && start > string && nulonly))) {
5331 sp = (struct strlist *)stalloc(sizeof *sp);
5333 *arglist->lastp = sp;
5334 arglist->lastp = &sp->next;
5340 while (ifsfirst.next != NULL) {
5341 struct ifsregion *ifsp;
5343 ifsp = ifsfirst.next->next;
5344 ckfree(ifsfirst.next);
5345 ifsfirst.next = ifsp;
5349 ifsfirst.next = NULL;
5353 * Add a file name to the list.
5357 addfname(const char *name)
5363 sp = (struct strlist *)stalloc(sizeof *sp);
5366 exparg.lastp = &sp->next;
5370 * Expand shell metacharacters. At this point, the only control characters
5371 * should be escapes. The results are stored in the list exparg.
5374 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5376 expandmeta(str, flag)
5377 struct strlist *str;
5382 /* TODO - EXP_REDIR */
5387 p = preglob(str->text);
5389 switch (glob(p, 0, 0, &pglob)) {
5391 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5402 *exparg.lastp = str;
5403 rmescapes(str->text);
5404 exparg.lastp = &str->next;
5406 default: /* GLOB_NOSPACE */
5407 error("Out of space");
5415 * Add the result of glob(3) to the list.
5420 const glob_t *pglob;
5422 char **p = pglob->gl_pathv;
5430 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5431 static char *expdir;
5435 expandmeta(str, flag)
5436 struct strlist *str;
5440 struct strlist **savelastp;
5443 /* TODO - EXP_REDIR */
5449 for (;;) { /* fast check for meta chars */
5450 if ((c = *p++) == '\0')
5452 if (c == '*' || c == '?' || c == '[' || c == '!')
5455 savelastp = exparg.lastp;
5457 if (expdir == NULL) {
5458 int i = strlen(str->text);
5459 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5462 expmeta(expdir, str->text);
5466 if (exparg.lastp == savelastp) {
5471 *exparg.lastp = str;
5472 rmescapes(str->text);
5473 exparg.lastp = &str->next;
5475 *exparg.lastp = NULL;
5476 *savelastp = sp = expsort(*savelastp);
5477 while (sp->next != NULL)
5479 exparg.lastp = &sp->next;
5487 * Do metacharacter (i.e. *, ?, [...]) expansion.
5491 expmeta(enddir, name)
5509 for (p = name ; ; p++) {
5510 if (*p == '*' || *p == '?')
5512 else if (*p == '[') {
5517 while (*q == CTLQUOTEMARK)
5521 if (*q == '/' || *q == '\0')
5528 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5530 } else if (*p == '\0')
5532 else if (*p == CTLQUOTEMARK)
5534 else if (*p == CTLESC)
5542 if (metaflag == 0) { /* we've reached the end of the file name */
5543 if (enddir != expdir)
5545 for (p = name ; ; p++) {
5546 if (*p == CTLQUOTEMARK)
5554 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5559 if (start != name) {
5562 while (*p == CTLQUOTEMARK)
5569 if (enddir == expdir) {
5571 } else if (enddir == expdir + 1 && *expdir == '/') {
5577 if ((dirp = opendir(cp)) == NULL)
5579 if (enddir != expdir)
5581 if (*endname == 0) {
5589 while (*p == CTLQUOTEMARK)
5595 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5596 if (dp->d_name[0] == '.' && ! matchdot)
5598 if (patmatch(start, dp->d_name, 0)) {
5600 strcpy(enddir, dp->d_name);
5603 for (p = enddir, cp = dp->d_name;
5604 (*p++ = *cp++) != '\0';)
5607 expmeta(p, endname);
5615 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5619 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5621 * Sort the results of file name expansion. It calculates the number of
5622 * strings to sort and then calls msort (short for merge sort) to do the
5626 static struct strlist *
5628 struct strlist *str;
5634 for (sp = str ; sp ; sp = sp->next)
5636 return msort(str, len);
5640 static struct strlist *
5642 struct strlist *list;
5645 struct strlist *p, *q = NULL;
5646 struct strlist **lpp;
5654 for (n = half ; --n >= 0 ; ) {
5658 q->next = NULL; /* terminate first half of list */
5659 q = msort(list, half); /* sort first half of list */
5660 p = msort(p, len - half); /* sort second half */
5663 if (strcmp(p->text, q->text) < 0) {
5666 if ((p = *lpp) == NULL) {
5673 if ((q = *lpp) == NULL) {
5686 * Returns true if the pattern matches the string.
5689 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5690 /* squoted: string might have quote chars */
5692 patmatch(char *pattern, char *string, int squoted)
5697 p = preglob(pattern);
5698 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5700 return !fnmatch(p, q, 0);
5705 patmatch2(char *pattern, char *string, int squoted)
5711 p = grabstackstr(expdest);
5712 res = patmatch(pattern, string, squoted);
5713 ungrabstackstr(p, expdest);
5718 patmatch(char *pattern, char *string, int squoted) {
5719 return pmatch(pattern, string, squoted);
5724 pmatch(char *pattern, char *string, int squoted)
5736 if (squoted && *q == CTLESC)
5744 if (squoted && *q == CTLESC)
5751 while (c == CTLQUOTEMARK || c == '*')
5753 if (c != CTLESC && c != CTLQUOTEMARK &&
5754 c != '?' && c != '*' && c != '[') {
5756 if (squoted && *q == CTLESC &&
5761 if (squoted && *q == CTLESC)
5767 if (pmatch(p, q, squoted))
5769 if (squoted && *q == CTLESC)
5771 } while (*q++ != '\0');
5782 while (*endp == CTLQUOTEMARK)
5785 goto dft; /* no matching ] */
5786 if (*endp == CTLESC)
5798 if (squoted && chr == CTLESC)
5804 if (c == CTLQUOTEMARK)
5808 if (*p == '-' && p[1] != ']') {
5810 while (*p == CTLQUOTEMARK)
5814 if (chr >= c && chr <= *p)
5821 } while ((c = *p++) != ']');
5822 if (found == invert)
5827 if (squoted && *q == CTLESC)
5844 * Remove any CTLESC characters from a string.
5847 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5849 _rmescapes(char *str, int flag)
5852 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5854 p = strpbrk(str, qchars);
5860 if (flag & RMESCAPE_ALLOC) {
5861 size_t len = p - str;
5862 q = r = stalloc(strlen(p) + len + 1);
5864 memcpy(q, str, len);
5869 if (*p == CTLQUOTEMARK) {
5875 if (flag & RMESCAPE_GLOB && *p != '/') {
5892 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5898 if (*p == CTLQUOTEMARK) {
5913 * See if a pattern matches in a case statement.
5917 casematch(union node *pattern, const char *val)
5919 struct stackmark smark;
5923 setstackmark(&smark);
5924 argbackq = pattern->narg.backquote;
5925 STARTSTACKSTR(expdest);
5927 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5928 STPUTC('\0', expdest);
5929 p = grabstackstr(expdest);
5930 result = patmatch(p, (char *)val, 0);
5931 popstackmark(&smark);
5946 CHECKSTRSPACE(32, buf);
5947 len = sprintf(buf, "%d", num);
5952 * Editline and history functions (and glue).
5954 static int histcmd(argc, argv)
5958 error("not compiled with history support");
5964 struct redirtab *next;
5965 short renamed[10]; /* Current ash support only 0-9 descriptors */
5966 /* char on arm (and others) can't be negative */
5969 static struct redirtab *redirlist;
5971 extern char **environ;
5976 * Initialization code.
5989 basepf.nextc = basepf.buf = basebuf;
5998 for (envp = environ ; *envp ; envp++) {
5999 if (strchr(*envp, '=')) {
6000 setvareq(*envp, VEXPORT|VTEXTFIXED);
6004 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
6005 setvar("PPID", ppid, 0);
6012 * This routine is called when an error or an interrupt occurs in an
6013 * interactive shell and control is returned to the main command loop.
6016 /* 1 == check for aliases, 2 == also check for assignments */
6017 static int checkalias; /* also used in no alias mode for check assignments */
6031 if (exception != EXSHELLPROC)
6032 parselleft = parsenleft = 0; /* clear input buffer */
6036 /* from parser.c: */
6054 * This file implements the input routines used by the parser.
6057 #ifdef BB_FEATURE_COMMAND_EDITING
6058 static const char * cmdedit_prompt;
6059 static inline void putprompt(const char *s) {
6063 static inline void putprompt(const char *s) {
6068 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
6073 * Same as pgetc(), but ignores PEOA.
6083 } while (c == PEOA);
6087 static inline int pgetc2() { return pgetc_macro(); }
6091 * Read a line from the script.
6094 static inline char *
6095 pfgets(char *line, int len)
6101 while (--nleft > 0) {
6120 char *buf = parsefile->buf;
6124 #ifdef BB_FEATURE_COMMAND_EDITING
6126 if (!iflag || parsefile->fd)
6127 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6129 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
6133 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6137 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6138 int flags = fcntl(0, F_GETFL, 0);
6139 if (flags >= 0 && flags & O_NONBLOCK) {
6140 flags &=~ O_NONBLOCK;
6141 if (fcntl(0, F_SETFL, flags) >= 0) {
6142 out2str("sh: turning off NDELAY mode\n");
6154 struct strpush *sp = parsefile->strpush;
6159 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6164 if (sp->string != sp->ap->val) {
6168 sp->ap->flag &= ~ALIASINUSE;
6169 if (sp->ap->flag & ALIASDEAD) {
6170 unalias(sp->ap->name);
6174 parsenextc = sp->prevstring;
6175 parsenleft = sp->prevnleft;
6176 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6177 parsefile->strpush = sp->prev;
6178 if (sp != &(parsefile->basestrpush))
6185 * Refill the input buffer and return the next input character:
6187 * 1) If a string was pushed back on the input, pop it;
6188 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6189 * from a string so we can't refill the buffer, return EOF.
6190 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6191 * 4) Process input up to the next newline, deleting nul characters.
6201 while (parsefile->strpush) {
6203 if (parsenleft == -1 && parsefile->strpush->ap &&
6204 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6209 if (--parsenleft >= 0)
6210 return (*parsenextc++);
6212 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6217 if (parselleft <= 0) {
6218 if ((parselleft = preadfd()) <= 0) {
6219 parselleft = parsenleft = EOF_NLEFT;
6226 /* delete nul characters */
6227 for (more = 1; more;) {
6235 parsenleft = q - parsenextc;
6236 more = 0; /* Stop processing here */
6242 if (--parselleft <= 0 && more) {
6243 parsenleft = q - parsenextc - 1;
6254 out2str(parsenextc);
6259 return *parsenextc++;
6264 * Push a string back onto the input at this current parsefile level.
6265 * We handle aliases this way.
6268 pushstring(char *s, int len, void *ap)
6273 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6274 if (parsefile->strpush) {
6275 sp = ckmalloc(sizeof (struct strpush));
6276 sp->prev = parsefile->strpush;
6277 parsefile->strpush = sp;
6279 sp = parsefile->strpush = &(parsefile->basestrpush);
6280 sp->prevstring = parsenextc;
6281 sp->prevnleft = parsenleft;
6283 sp->ap = (struct alias *)ap;
6285 ((struct alias *)ap)->flag |= ALIASINUSE;
6296 * Like setinputfile, but takes input from a string.
6300 setinputstring(char *string)
6304 parsenextc = string;
6305 parsenleft = strlen(string);
6306 parsefile->buf = NULL;
6314 * To handle the "." command, a stack of input files is used. Pushfile
6315 * adds a new entry to the stack and popfile restores the previous level.
6320 struct parsefile *pf;
6322 parsefile->nleft = parsenleft;
6323 parsefile->lleft = parselleft;
6324 parsefile->nextc = parsenextc;
6325 parsefile->linno = plinno;
6326 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6327 pf->prev = parsefile;
6330 pf->basestrpush.prev = NULL;
6335 static void restartjob (struct job *);
6337 static void freejob (struct job *);
6338 static struct job *getjob (const char *);
6339 static int dowait (int, struct job *);
6340 static void waitonint(int);
6344 * We keep track of whether or not fd0 has been redirected. This is for
6345 * background commands, where we want to redirect fd0 to /dev/null only
6346 * if it hasn't already been redirected.
6348 static int fd0_redirected = 0;
6350 /* Return true if fd 0 has already been redirected at least once. */
6352 fd0_redirected_p () {
6353 return fd0_redirected != 0;
6356 static void dupredirect (const union node *, int, int fd1dup);
6360 * Turn job control on and off.
6362 * Note: This code assumes that the third arg to ioctl is a character
6363 * pointer, which is true on Berkeley systems but not System V. Since
6364 * System V doesn't have job control yet, this isn't a problem now.
6369 static void setjobctl(int enable)
6371 #ifdef OLD_TTY_DRIVER
6375 if (enable == jobctl || rootshell == 0)
6378 do { /* while we are in the background */
6379 #ifdef OLD_TTY_DRIVER
6380 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6382 initialpgrp = tcgetpgrp(2);
6383 if (initialpgrp < 0) {
6385 out2str("sh: can't access tty; job control turned off\n");
6389 if (initialpgrp == -1)
6390 initialpgrp = getpgrp();
6391 else if (initialpgrp != getpgrp()) {
6392 killpg(initialpgrp, SIGTTIN);
6396 #ifdef OLD_TTY_DRIVER
6397 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6398 out2str("sh: need new tty driver to run job control; job control turned off\n");
6406 setpgid(0, rootpid);
6407 #ifdef OLD_TTY_DRIVER
6408 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6410 tcsetpgrp(2, rootpid);
6412 } else { /* turning job control off */
6413 setpgid(0, initialpgrp);
6414 #ifdef OLD_TTY_DRIVER
6415 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6417 tcsetpgrp(2, initialpgrp);
6443 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6444 "kill -l [exitstatus]"
6448 if (*argv[1] == '-') {
6449 signo = decode_signal(argv[1] + 1, 1);
6453 while ((c = nextopt("ls:")) != '\0')
6459 signo = decode_signal(optionarg, 1);
6462 "invalid signal number or name: %s",
6470 "nextopt returned character code 0%o", c);
6477 if (!list && signo < 0)
6480 if ((signo < 0 || !*argptr) ^ list) {
6489 for (i = 1; i < NSIG; i++) {
6490 name = u_signal_names(0, &i, 1);
6492 printf(snlfmt, name);
6496 name = u_signal_names(*argptr, &signo, -1);
6498 printf(snlfmt, name);
6500 error("invalid signal number or exit status: %s",
6506 if (**argptr == '%') {
6507 jp = getjob(*argptr);
6508 if (jp->jobctl == 0)
6509 error("job %s not created under job control",
6511 pid = -jp->ps[0].pid;
6513 pid = atoi(*argptr);
6514 if (kill(pid, signo) != 0)
6515 error("%s: %m", *argptr);
6516 } while (*++argptr);
6530 jp = getjob(argv[1]);
6531 if (jp->jobctl == 0)
6532 error("job not created under job control");
6533 pgrp = jp->ps[0].pid;
6534 #ifdef OLD_TTY_DRIVER
6535 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6541 status = waitforjob(jp);
6555 jp = getjob(*++argv);
6556 if (jp->jobctl == 0)
6557 error("job not created under job control");
6559 } while (--argc > 1);
6568 struct procstat *ps;
6571 if (jp->state == JOBDONE)
6574 killpg(jp->ps[0].pid, SIGCONT);
6575 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6576 if (WIFSTOPPED(ps->status)) {
6585 static void showjobs(int change);
6599 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6600 * statuses have changed since the last call to showjobs.
6602 * If the shell is interrupted in the process of creating a job, the
6603 * result may be a job structure containing zero processes. Such structures
6604 * will be freed here.
6615 struct procstat *ps;
6619 TRACE(("showjobs(%d) called\n", change));
6620 while (dowait(0, (struct job *)NULL) > 0);
6621 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6624 if (jp->nprocs == 0) {
6628 if (change && ! jp->changed)
6630 procno = jp->nprocs;
6631 for (ps = jp->ps ; ; ps++) { /* for each process */
6633 snprintf(s, 64, "[%d] %ld ", jobno,
6636 snprintf(s, 64, " %ld ",
6641 if (ps->status == -1) {
6642 /* don't print anything */
6643 } else if (WIFEXITED(ps->status)) {
6644 snprintf(s, 64, "Exit %d",
6645 WEXITSTATUS(ps->status));
6648 if (WIFSTOPPED(ps->status))
6649 i = WSTOPSIG(ps->status);
6650 else /* WIFSIGNALED(ps->status) */
6652 i = WTERMSIG(ps->status);
6653 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6654 strcpy(s, sys_siglist[i & 0x7F]);
6656 snprintf(s, 64, "Signal %d", i & 0x7F);
6657 if (WCOREDUMP(ps->status))
6658 strcat(s, " (core dumped)");
6663 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6670 if (jp->state == JOBDONE) {
6678 * Mark a job structure as unused.
6682 freejob(struct job *jp)
6684 const struct procstat *ps;
6688 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6689 if (ps->cmd != nullstr)
6692 if (jp->ps != &jp->ps0)
6696 if (curjob == jp - jobtab + 1)
6715 job = getjob(*++argv);
6719 for (;;) { /* loop until process terminated or stopped */
6722 status = job->ps[job->nprocs - 1].status;
6728 if (WIFEXITED(status))
6729 retval = WEXITSTATUS(status);
6731 else if (WIFSTOPPED(status))
6732 retval = WSTOPSIG(status) + 128;
6735 /* XXX: limits number of signals */
6736 retval = WTERMSIG(status) + 128;
6741 for (jp = jobtab ; ; jp++) {
6742 if (jp >= jobtab + njobs) { /* no running procs */
6745 if (jp->used && jp->state == 0)
6749 if (dowait(2, 0) < 0 && errno == EINTR) {
6758 * Convert a job name to a job structure.
6762 getjob(const char *name)
6772 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6773 error("No current job");
6774 return &jobtab[jobno - 1];
6776 error("No current job");
6778 } else if (name[0] == '%') {
6779 if (is_digit(name[1])) {
6780 jobno = number(name + 1);
6781 if (jobno > 0 && jobno <= njobs
6782 && jobtab[jobno - 1].used != 0)
6783 return &jobtab[jobno - 1];
6785 } else if (name[1] == '%' && name[2] == '\0') {
6789 struct job *found = NULL;
6790 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6791 if (jp->used && jp->nprocs > 0
6792 && prefix(name + 1, jp->ps[0].cmd)) {
6794 error("%s: ambiguous", name);
6801 } else if (is_number(name, &pid)) {
6802 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6803 if (jp->used && jp->nprocs > 0
6804 && jp->ps[jp->nprocs - 1].pid == pid)
6808 error("No such job: %s", name);
6815 * Return a new job structure,
6819 makejob(const union node *node, int nprocs)
6824 for (i = njobs, jp = jobtab ; ; jp++) {
6828 jobtab = ckmalloc(4 * sizeof jobtab[0]);
6830 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
6831 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6832 /* Relocate `ps' pointers */
6833 for (i = 0; i < njobs; i++)
6834 if (jp[i].ps == &jobtab[i].ps0)
6835 jp[i].ps = &jp[i].ps0;
6839 jp = jobtab + njobs;
6840 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6853 jp->jobctl = jobctl;
6856 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6861 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6868 * Fork of a subshell. If we are doing job control, give the subshell its
6869 * own process group. Jp is a job structure that the job is to be added to.
6870 * N is the command that will be evaluated by the child. Both jp and n may
6871 * be NULL. The mode parameter can be one of the following:
6872 * FORK_FG - Fork off a foreground process.
6873 * FORK_BG - Fork off a background process.
6874 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6875 * process group even if job control is on.
6877 * When job control is turned off, background processes have their standard
6878 * input redirected to /dev/null (except for the second and later processes
6885 forkshell(struct job *jp, const union node *n, int mode)
6891 const char *devnull = _PATH_DEVNULL;
6892 const char *nullerr = "Can't open %s";
6894 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6899 TRACE(("Fork failed, errno=%d\n", errno));
6901 error("Cannot fork");
6908 TRACE(("Child shell %d\n", getpid()));
6909 wasroot = rootshell;
6915 jobctl = 0; /* do job control only in root shell */
6916 if (wasroot && mode != FORK_NOJOB && mflag) {
6917 if (jp == NULL || jp->nprocs == 0)
6920 pgrp = jp->ps[0].pid;
6922 if (mode == FORK_FG) {
6923 /*** this causes superfluous TIOCSPGRPS ***/
6924 #ifdef OLD_TTY_DRIVER
6925 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6926 error("TIOCSPGRP failed, errno=%d", errno);
6928 if (tcsetpgrp(2, pgrp) < 0)
6929 error("tcsetpgrp failed, errno=%d", errno);
6934 } else if (mode == FORK_BG) {
6937 if ((jp == NULL || jp->nprocs == 0) &&
6938 ! fd0_redirected_p ()) {
6940 if (open(devnull, O_RDONLY) != 0)
6941 error(nullerr, devnull);
6945 if (mode == FORK_BG) {
6948 if ((jp == NULL || jp->nprocs == 0) &&
6949 ! fd0_redirected_p ()) {
6951 if (open(devnull, O_RDONLY) != 0)
6952 error(nullerr, devnull);
6956 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6959 if (wasroot && iflag) {
6967 if (rootshell && mode != FORK_NOJOB && mflag) {
6968 if (jp == NULL || jp->nprocs == 0)
6971 pgrp = jp->ps[0].pid;
6975 if (mode == FORK_BG)
6976 backgndpid = pid; /* set $! */
6978 struct procstat *ps = &jp->ps[jp->nprocs++];
6982 if (iflag && rootshell && n)
6983 ps->cmd = commandtext(n);
6986 TRACE(("In parent shell: child = %d\n", pid));
6993 * Wait for job to finish.
6995 * Under job control we have the problem that while a child process is
6996 * running interrupts generated by the user are sent to the child but not
6997 * to the shell. This means that an infinite loop started by an inter-
6998 * active user may be hard to kill. With job control turned off, an
6999 * interactive user may place an interactive program inside a loop. If
7000 * the interactive program catches interrupts, the user doesn't want
7001 * these interrupts to also abort the loop. The approach we take here
7002 * is to have the shell ignore interrupt signals while waiting for a
7003 * forground process to terminate, and then send itself an interrupt
7004 * signal if the child process was terminated by an interrupt signal.
7005 * Unfortunately, some programs want to do a bit of cleanup and then
7006 * exit on interrupt; unless these processes terminate themselves by
7007 * sending a signal to themselves (instead of calling exit) they will
7008 * confuse this approach.
7012 waitforjob(struct job *jp)
7015 int mypgrp = getpgrp();
7019 struct sigaction act, oact;
7028 sigaction(SIGINT, 0, &act);
7029 act.sa_handler = waitonint;
7030 sigaction(SIGINT, &act, &oact);
7032 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
7033 while (jp->state == 0) {
7041 sigaction(SIGINT, &oact, 0);
7042 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
7046 #ifdef OLD_TTY_DRIVER
7047 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
7048 error("TIOCSPGRP failed, errno=%d\n", errno);
7050 if (tcsetpgrp(2, mypgrp) < 0)
7051 error("tcsetpgrp failed, errno=%d\n", errno);
7054 if (jp->state == JOBSTOPPED)
7055 curjob = jp - jobtab + 1;
7057 status = jp->ps[jp->nprocs - 1].status;
7058 /* convert to 8 bits */
7059 if (WIFEXITED(status))
7060 st = WEXITSTATUS(status);
7062 else if (WIFSTOPPED(status))
7063 st = WSTOPSIG(status) + 128;
7066 st = WTERMSIG(status) + 128;
7070 * This is truly gross.
7071 * If we're doing job control, then we did a TIOCSPGRP which
7072 * caused us (the shell) to no longer be in the controlling
7073 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
7074 * intuit from the subprocess exit status whether a SIGINT
7075 * occured, and if so interrupt ourselves. Yuck. - mycroft
7077 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
7080 if (jp->state == JOBDONE)
7091 * Wait for a process to terminate.
7095 * Do a wait system call. If job control is compiled in, we accept
7096 * stopped processes. If block is zero, we return a value of zero
7097 * rather than blocking.
7099 * System V doesn't have a non-blocking wait system call. It does
7100 * have a SIGCLD signal that is sent to a process when one of it's
7101 * children dies. The obvious way to use SIGCLD would be to install
7102 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
7103 * was received, and have waitproc bump another counter when it got
7104 * the status of a process. Waitproc would then know that a wait
7105 * system call would not block if the two counters were different.
7106 * This approach doesn't work because if a process has children that
7107 * have not been waited for, System V will send it a SIGCLD when it
7108 * installs a signal handler for SIGCLD. What this means is that when
7109 * a child exits, the shell will be sent SIGCLD signals continuously
7110 * until is runs out of stack space, unless it does a wait call before
7111 * restoring the signal handler. The code below takes advantage of
7112 * this (mis)feature by installing a signal handler for SIGCLD and
7113 * then checking to see whether it was called. If there are any
7114 * children to be waited for, it will be.
7119 waitproc(int block, int *status)
7130 return wait3(status, flags, (struct rusage *)NULL);
7134 dowait(int block, struct job *job)
7138 struct procstat *sp;
7140 struct job *thisjob;
7146 TRACE(("dowait(%d) called\n", block));
7148 pid = waitproc(block, &status);
7149 TRACE(("wait returns %d, status=%d\n", pid, status));
7150 } while (!(block & 2) && pid == -1 && errno == EINTR);
7155 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
7159 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
7162 if (sp->pid == pid) {
7163 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
7164 sp->status = status;
7167 if (sp->status == -1)
7169 else if (WIFSTOPPED(sp->status))
7172 if (stopped) { /* stopped or done */
7173 int state = done? JOBDONE : JOBSTOPPED;
7174 if (jp->state != state) {
7175 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
7178 if (done && curjob == jp - jobtab + 1)
7179 curjob = 0; /* no current job */
7186 if (! rootshell || ! iflag || (job && thisjob == job)) {
7187 core = WCOREDUMP(status);
7189 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
7192 if (WIFEXITED(status)) sig = 0;
7193 else sig = WTERMSIG(status);
7195 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
7197 out2fmt("%d: ", pid);
7199 if (sig == SIGTSTP && rootshell && iflag)
7201 (long)(job - jobtab + 1));
7203 if (sig < NSIG && sys_siglist[sig])
7204 out2str(sys_siglist[sig]);
7206 out2fmt("Signal %d", sig);
7208 out2str(" - core dumped");
7211 TRACE(("Not printing status: status=%d, sig=%d\n",
7215 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
7217 thisjob->changed = 1;
7226 * return 1 if there are stopped jobs, otherwise 0
7236 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7239 if (jp->state == JOBSTOPPED) {
7240 out2str("You have stopped jobs.\n");
7250 * Return a string identifying a command (to be printed by the
7254 static char *cmdnextc;
7255 static int cmdnleft;
7256 #define MAXCMDTEXT 200
7259 cmdputs(const char *s)
7270 while ((c = *p++) != '\0') {
7273 else if (c == CTLVAR) {
7278 } else if (c == '=' && subtype != 0) {
7279 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7281 } else if (c == CTLENDVAR) {
7283 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7284 cmdnleft++; /* ignore it */
7287 if (--cmdnleft <= 0) {
7297 //#define CMDTXT_TABLE
7300 * To collect a lot of redundant code in cmdtxt() case statements, we
7301 * implement a mini language here. Each type of node struct has an
7302 * associated instruction sequence that operates on its members via
7303 * their offsets. The instruction are pack in unsigned chars with
7304 * format IIDDDDDE where the bits are
7305 * I : part of the instruction opcode, which are
7306 * 00 : member is a pointer to another node -- process it recursively
7307 * 40 : member is a pointer to a char string -- output it
7308 * 80 : output the string whose index is stored in the data field
7309 * CC : flag signaling that this case needs external processing
7310 * D : data - either the (shifted) index of a fixed string to output or
7311 * the actual offset of the member to operate on in the struct
7312 * (since we assume bit 0 is set, the offset is not shifted)
7313 * E : flag signaling end of instruction sequence
7315 * WARNING: In order to handle larger offsets for 64bit archs, this code
7316 * assumes that no offset can be an odd number and stores the
7317 * end-of-instructions flag in bit 0.
7320 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7321 #define CMDTXT_CHARPTR 0x40
7322 #define CMDTXT_STRING 0x80
7323 #define CMDTXT_SPECIAL 0xC0
7324 #define CMDTXT_OFFSETMASK 0x3E
7326 static const char * const cmdtxt_strings[] = {
7327 /* 0 1 2 3 4 5 6 7 */
7328 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7329 /* 8 9 10 11 12 13 */
7330 "while ", "; do ", "; done", "until ", "for ", " in ...",
7332 "case ", "???", "() ...", "<<..."
7335 static const char * const redir_strings[] = {
7336 ">", "<", "<>", ">>", ">|", ">&", "<&"
7339 static const unsigned char cmdtxt_ops[] = {
7340 #define CMDTXT_NSEMI 0
7341 offsetof(union node, nbinary.ch1),
7343 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7344 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7345 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7346 #define CMDTXT_NCASE (CMDTXT_NCMD)
7347 #define CMDTXT_NTO (CMDTXT_NCMD)
7348 #define CMDTXT_NFROM (CMDTXT_NCMD)
7349 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7350 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7351 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7352 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7353 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7355 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7356 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7357 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7358 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7359 (1*2)|CMDTXT_STRING,
7360 offsetof(union node, nredir.n),
7361 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7362 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7363 offsetof(union node, nbinary.ch1),
7364 (3*2)|CMDTXT_STRING,
7365 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7366 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7367 offsetof(union node, nbinary.ch1),
7368 (4*2)|CMDTXT_STRING,
7369 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7370 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7371 (5*2)|CMDTXT_STRING,
7372 offsetof(union node, nif.test),
7373 (6*2)|CMDTXT_STRING,
7374 offsetof(union node, nif.ifpart),
7375 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7376 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7377 (8*2)|CMDTXT_STRING,
7378 offsetof(union node, nbinary.ch1),
7379 (9*2)|CMDTXT_STRING,
7380 offsetof(union node, nbinary.ch2),
7381 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7382 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7383 (11*2)|CMDTXT_STRING,
7384 offsetof(union node, nbinary.ch1),
7385 (9*2)|CMDTXT_STRING,
7386 offsetof(union node, nbinary.ch2),
7387 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7388 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7389 (12*2)|CMDTXT_STRING,
7390 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7391 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7392 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7393 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7394 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7395 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7396 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7397 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7398 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7399 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7400 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7401 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7402 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7405 #if CMDTXT_NXHERE != 36
7406 #error CMDTXT_NXHERE
7409 static const unsigned char cmdtxt_ops_index[26] = {
7439 cmdtxt(const union node *n)
7446 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7447 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7449 if (*p & CMDTXT_STRING) { /* output fixed string */
7450 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7452 const char *pf = ((const char *) n)
7453 + ((int)(*p & CMDTXT_OFFSETMASK));
7454 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7455 cmdputs(*((const char **) pf));
7456 } else { /* output field */
7457 cmdtxt(*((const union node **) pf));
7460 } while (!(*p++ & CMDTXT_NOMORE));
7461 } else if (n->type == NCMD) {
7463 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7468 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7472 } else if (n->type == NPIPE) {
7473 struct nodelist *lp;
7474 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7479 } else if (n->type == NCASE) {
7480 cmdputs(cmdtxt_strings[14]);
7481 cmdputs(n->ncase.expr->narg.text);
7482 cmdputs(cmdtxt_strings[13]);
7484 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7485 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7490 assert((n->type >= NTO) && (n->type <= NFROMFD));
7493 p = redir_strings[n->type - NTO];
7494 if (n->nfile.fd != ('>' == *p)) {
7495 s[0] = n->nfile.fd + '0';
7500 if (n->type >= NTOFD) {
7501 s[0] = n->ndup.dupfd + '0';
7505 cmdtxt(n->nfile.fname);
7509 #else /* CMDTXT_TABLE */
7511 cmdtxt(const union node *n)
7514 struct nodelist *lp;
7523 cmdtxt(n->nbinary.ch1);
7525 cmdtxt(n->nbinary.ch2);
7528 cmdtxt(n->nbinary.ch1);
7530 cmdtxt(n->nbinary.ch2);
7533 cmdtxt(n->nbinary.ch1);
7535 cmdtxt(n->nbinary.ch2);
7538 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7546 cmdtxt(n->nredir.n);
7551 cmdtxt(n->nredir.n);
7555 cmdtxt(n->nif.test);
7557 cmdtxt(n->nif.ifpart);
7566 cmdtxt(n->nbinary.ch1);
7568 cmdtxt(n->nbinary.ch2);
7573 cmdputs(n->nfor.var);
7578 cmdputs(n->ncase.expr->narg.text);
7582 cmdputs(n->narg.text);
7586 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7591 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7597 cmdputs(n->narg.text);
7600 p = ">"; i = 1; goto redir;
7602 p = ">>"; i = 1; goto redir;
7604 p = ">&"; i = 1; goto redir;
7606 p = ">|"; i = 1; goto redir;
7608 p = "<"; i = 0; goto redir;
7610 p = "<&"; i = 0; goto redir;
7612 p = "<>"; i = 0; goto redir;
7614 if (n->nfile.fd != i) {
7615 s[0] = n->nfile.fd + '0';
7620 if (n->type == NTOFD || n->type == NFROMFD) {
7621 s[0] = n->ndup.dupfd + '0';
7625 cmdtxt(n->nfile.fname);
7637 #endif /* CMDTXT_TABLE */
7640 commandtext(const union node *n)
7644 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7645 cmdnleft = MAXCMDTEXT - 4;
7652 static void waitonint(int sig) {
7657 * Routines to check for mail. (Perhaps make part of main.c?)
7661 #define MAXMBOXES 10
7664 static int nmboxes; /* number of mailboxes */
7665 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7670 * Print appropriate message(s) if mail has arrived. If the argument is
7671 * nozero, then the value of MAIL has changed, so we just update the
7682 struct stackmark smark;
7689 setstackmark(&smark);
7690 mpath = mpathset()? mpathval() : mailval();
7691 for (i = 0 ; i < nmboxes ; i++) {
7692 p = padvance(&mpath, nullstr);
7697 for (q = p ; *q ; q++);
7702 q[-1] = '\0'; /* delete trailing '/' */
7703 if (stat(p, &statb) < 0)
7705 if (statb.st_size > mailtime[i] && ! silent) {
7707 pathopt? pathopt : "you have mail");
7709 mailtime[i] = statb.st_size;
7712 popstackmark(&smark);
7718 static short profile_buf[16384];
7722 static void read_profile (const char *);
7723 static void cmdloop (int);
7724 static void options (int);
7725 static void setoption (int, int);
7726 static void procargs (int, char **);
7730 * Main routine. We initialize things, parse the arguments, execute
7731 * profiles if we're a login shell, and then call cmdloop to execute
7732 * commands. The setjmp call sets up the location to jump to when an
7733 * exception occurs. When an exception occurs the variable "state"
7734 * is used to figure out how far we had gotten.
7738 ash_main(argc, argv)
7742 struct jmploc jmploc;
7743 struct stackmark smark;
7747 BLTINCMD = find_builtin("builtin");
7748 EXECCMD = find_builtin("exec");
7749 EVALCMD = find_builtin("eval");
7751 #ifndef BB_FEATURE_SH_FANCY_PROMPT
7757 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7759 #if defined(linux) || defined(__GNU__)
7760 signal(SIGCHLD, SIG_DFL);
7763 if (setjmp(jmploc.loc)) {
7766 * When a shell procedure is executed, we raise the
7767 * exception EXSHELLPROC to clean up before executing
7768 * the shell procedure.
7770 if (exception == EXSHELLPROC) {
7776 if (exception == EXEXEC) {
7777 exitstatus = exerrno;
7778 } else if (exception == EXERROR) {
7781 if (state == 0 || iflag == 0 || ! rootshell)
7782 exitshell(exitstatus);
7785 if (exception == EXINT) {
7788 popstackmark(&smark);
7789 FORCEINTON; /* enable interrupts */
7792 else if (state == 2)
7794 else if (state == 3)
7802 trputs("Shell args: "); trargs(argv);
7807 setstackmark(&smark);
7808 procargs(argc, argv);
7809 if (argv[0] && argv[0][0] == '-') {
7811 read_profile("/etc/profile");
7814 read_profile(".profile");
7819 if (getuid() == geteuid() && getgid() == getegid()) {
7821 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7823 read_profile(shinit);
7830 if (sflag == 0 || minusc) {
7831 static const char sigs[] = {
7832 SIGINT, SIGQUIT, SIGHUP,
7838 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7841 for (i = 0; i < SIGSSIZE; i++)
7846 evalstring(minusc, 0);
7848 if (sflag || minusc == NULL) {
7849 state4: /* XXX ??? - why isn't this before the "if" statement */
7855 exitshell(exitstatus);
7861 * Read and execute commands. "Top" is nonzero for the top level command
7862 * loop; it turns on prompting if the shell is interactive.
7869 struct stackmark smark;
7873 TRACE(("cmdloop(%d) called\n", top));
7874 setstackmark(&smark);
7885 n = parsecmd(inter);
7886 /* showtree(n); DEBUG */
7888 if (!top || numeof >= 50)
7890 if (!stoppedjobs()) {
7893 out2str("\nUse \"exit\" to leave shell.\n");
7896 } else if (n != NULL && nflag == 0) {
7897 job_warning = (job_warning == 2) ? 1 : 0;
7901 popstackmark(&smark);
7902 setstackmark(&smark);
7903 if (evalskip == SKIPFILE) {
7908 popstackmark(&smark);
7914 * Read /etc/profile or .profile. Return on error.
7926 if ((fd = open(name, O_RDONLY)) >= 0)
7931 /* -q turns off -x and -v just when executing init files */
7932 /* Note: Might do a little redundant work, but reduces code size. */
7947 * Read a file containing shell functions.
7951 readcmdfile(const char *name)
7956 if ((fd = open(name, O_RDONLY)) >= 0)
7959 error("Can't open %s", name);
7968 * Take commands from a file. To be compatable we should do a path
7969 * search for the file, which is necessary to find sub-commands.
7973 static inline char *
7974 find_dot_file(mybasename)
7978 const char *path = pathval();
7981 /* don't try this for absolute or relative paths */
7982 if (strchr(mybasename, '/'))
7985 while ((fullname = padvance(&path, mybasename)) != NULL) {
7986 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7988 * Don't bother freeing here, since it will
7989 * be freed by the caller.
7993 stunalloc(fullname);
7996 /* not found in the PATH */
7997 error("%s: not found", mybasename);
8009 for (sp = cmdenviron; sp ; sp = sp->next)
8010 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
8012 if (argc >= 2) { /* That's what SVR2 does */
8014 struct stackmark smark;
8016 setstackmark(&smark);
8017 fullname = find_dot_file(argv[1]);
8018 setinputfile(fullname, 1);
8019 commandname = fullname;
8022 popstackmark(&smark);
8036 exitstatus = number(argv[1]);
8038 exitstatus = oexitstatus;
8039 exitshell(exitstatus);
8048 nbytes = ALIGN(nbytes);
8049 if (nbytes > stacknleft) {
8051 struct stack_block *sp;
8054 if (blocksize < MINSIZE)
8055 blocksize = MINSIZE;
8057 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
8059 stacknxt = sp->space;
8060 stacknleft = blocksize;
8066 stacknleft -= nbytes;
8072 stunalloc(pointer p)
8075 if (p == NULL) { /*DEBUG */
8076 write(2, "stunalloc\n", 10);
8080 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
8083 stacknleft += stacknxt - (char *)p;
8089 setstackmark(struct stackmark *mark)
8091 mark->stackp = stackp;
8092 mark->stacknxt = stacknxt;
8093 mark->stacknleft = stacknleft;
8094 mark->marknext = markp;
8100 popstackmark(struct stackmark *mark)
8102 struct stack_block *sp;
8105 markp = mark->marknext;
8106 while (stackp != mark->stackp) {
8111 stacknxt = mark->stacknxt;
8112 stacknleft = mark->stacknleft;
8118 * When the parser reads in a string, it wants to stick the string on the
8119 * stack and only adjust the stack pointer when it knows how big the
8120 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8121 * of space on top of the stack and stackblocklen returns the length of
8122 * this block. Growstackblock will grow this space by at least one byte,
8123 * possibly moving it (like realloc). Grabstackblock actually allocates the
8124 * part of the block that has been used.
8128 growstackblock(void) {
8130 int newlen = ALIGN(stacknleft * 2 + 100);
8131 char *oldspace = stacknxt;
8132 int oldlen = stacknleft;
8133 struct stack_block *sp;
8134 struct stack_block *oldstackp;
8136 if (stacknxt == stackp->space && stackp != &stackbase) {
8141 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8144 stacknxt = sp->space;
8145 stacknleft = newlen;
8147 /* Stack marks pointing to the start of the old block
8148 * must be relocated to point to the new block
8150 struct stackmark *xmark;
8152 while (xmark != NULL && xmark->stackp == oldstackp) {
8153 xmark->stackp = stackp;
8154 xmark->stacknxt = stacknxt;
8155 xmark->stacknleft = stacknleft;
8156 xmark = xmark->marknext;
8161 p = stalloc(newlen);
8162 memcpy(p, oldspace, oldlen);
8163 stacknxt = p; /* free the space */
8164 stacknleft += newlen; /* we just allocated */
8171 grabstackblock(int len)
8181 * The following routines are somewhat easier to use that the above.
8182 * The user declares a variable of type STACKSTR, which may be declared
8183 * to be a register. The macro STARTSTACKSTR initializes things. Then
8184 * the user uses the macro STPUTC to add characters to the string. In
8185 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8186 * grown as necessary. When the user is done, she can just leave the
8187 * string there and refer to it using stackblock(). Or she can allocate
8188 * the space for it using grabstackstr(). If it is necessary to allow
8189 * someone else to use the stack temporarily and then continue to grow
8190 * the string, the user should use grabstack to allocate the space, and
8191 * then call ungrabstr(p) to return to the previous mode of operation.
8193 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8194 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8195 * is space for at least one character.
8200 growstackstr(void) {
8201 int len = stackblocksize();
8202 if (herefd >= 0 && len >= 1024) {
8203 xwrite(herefd, stackblock(), len);
8204 sstrnleft = len - 1;
8205 return stackblock();
8208 sstrnleft = stackblocksize() - len - 1;
8209 return stackblock() + len;
8214 * Called from CHECKSTRSPACE.
8218 makestrspace(size_t newlen) {
8219 int len = stackblocksize() - sstrnleft;
8222 sstrnleft = stackblocksize() - len;
8223 } while (sstrnleft < newlen);
8224 return stackblock() + len;
8230 ungrabstackstr(char *s, char *p)
8232 stacknleft += stacknxt - s;
8234 sstrnleft = stacknleft - (p - s);
8237 * Miscelaneous builtins.
8243 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8244 typedef long rlim_t;
8250 * The read builtin. The -e option causes backslashes to escape the
8251 * following character.
8253 * This uses unbuffered input, which may be avoidable in some cases.
8257 readcmd(int argc, char **argv)
8272 while ((i = nextopt("p:r")) != '\0') {
8278 if (prompt && isatty(0)) {
8279 out2str(prompt); /* read without cmdedit */
8282 if (*(ap = argptr) == NULL)
8284 if ((ifs = bltinlookup("IFS")) == NULL)
8291 if (read(0, &c, 1) != 1) {
8303 if (!rflag && c == '\\') {
8309 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8313 if (backslash && c == '\\') {
8314 if (read(0, &c, 1) != 1) {
8319 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8321 setvar(*ap, stackblock(), 0);
8330 /* Remove trailing blanks */
8331 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8333 setvar(*ap, stackblock(), 0);
8334 while (*++ap != NULL)
8335 setvar(*ap, nullstr, 0);
8342 umaskcmd(argc, argv)
8346 static const char permuser[3] = "ugo";
8347 static const char permmode[3] = "rwx";
8348 static const short int permmask[] = {
8349 S_IRUSR, S_IWUSR, S_IXUSR,
8350 S_IRGRP, S_IWGRP, S_IXGRP,
8351 S_IROTH, S_IWOTH, S_IXOTH
8357 int symbolic_mode = 0;
8359 while (nextopt("S") != '\0') {
8368 if ((ap = *argptr) == NULL) {
8369 if (symbolic_mode) {
8372 for (i=0 ; i<3 ; i++) {
8376 for (j=0 ; j<3 ; j++) {
8377 if ((mask & permmask[3*i+j]) == 0) {
8386 printf("%.4o\n", mask);
8389 if (is_digit((unsigned char)*ap)) {
8392 if (*ap >= '8' || *ap < '0')
8393 error("Illegal number: %s", argv[1]);
8394 mask = (mask << 3) + (*ap - '0');
8395 } while (*++ap != '\0');
8398 mask = ~mask & 0777;
8399 if (parse_mode(ap, &mask) == FALSE) {
8400 error("Illegal mode: %s", ap);
8402 umask(~mask & 0777);
8411 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8412 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8413 * ash by J.T. Conklin.
8421 short factor; /* multiply by to get rlim_{cur,max} values */
8424 static const struct limits limits[] = {
8426 { "time(seconds)", RLIMIT_CPU, 1 },
8429 { "file(blocks)", RLIMIT_FSIZE, 512 },
8432 { "data(kbytes)", RLIMIT_DATA, 1024 },
8435 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8438 { "coredump(blocks)", RLIMIT_CORE, 512 },
8441 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8443 #ifdef RLIMIT_MEMLOCK
8444 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8447 { "process(processes)", RLIMIT_NPROC, 1 },
8449 #ifdef RLIMIT_NOFILE
8450 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8453 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8456 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8462 ulimitcmd(argc, argv)
8466 static const char unlimited_string[] = "unlimited";
8469 enum { SOFT = 0x1, HARD = 0x2 }
8471 const struct limits *l;
8474 struct rlimit limit;
8478 while ((optc = nextopt("HSa"
8497 #ifdef RLIMIT_MEMLOCK
8503 #ifdef RLIMIT_NOFILE
8515 } else if (optc == 'S') {
8517 } else if (optc == 'a') {
8524 for (l = limits; l->name; l++) {
8525 if(l->name[0] == what)
8527 if(l->name[1]=='w' && what=='w')
8531 set = *argptr ? 1 : 0;
8535 if (all || argptr[1])
8536 error("too many arguments");
8537 if (strcmp(p, unlimited_string) == 0)
8538 val = RLIM_INFINITY;
8542 while ((c = *p++) >= '0' && c <= '9')
8544 val = (val * 10) + (long)(c - '0');
8545 if (val < (rlim_t) 0)
8549 error("bad number");
8555 for (l = limits; l->name; l++) {
8556 printf("%-20s ", l->name);
8557 getrlimit(l->cmd, &limit);
8560 val = limit.rlim_cur;
8561 else if (how & HARD)
8562 val = limit.rlim_max;
8564 if (val == RLIM_INFINITY)
8565 puts(unlimited_string);
8569 printf("%lld\n", (long long) val);
8582 getrlimit(l->cmd, &limit);
8584 limit.rlim_max = val;
8586 limit.rlim_cur = val;
8587 if (setrlimit(l->cmd, &limit) < 0)
8588 error("error setting limit (%m)");
8592 * prefix -- see if pfx is a prefix of string.
8596 prefix(char const *pfx, char const *string)
8599 if (*pfx++ != *string++)
8606 * Return true if s is a string of digits, and save munber in intptr
8611 is_number(const char *p, int *intptr)
8619 ret += digit_val(*p);
8621 } while (*p != '\0');
8628 * Convert a string of digits to an integer, printing an error message on
8633 number(const char *s)
8636 if (! is_number(s, &i))
8637 error("Illegal number: %s", s);
8642 * Produce a possibly single quoted string suitable as input to the shell.
8643 * The return string is allocated on the stack.
8647 single_quote(const char *s) {
8654 size_t len1, len1p, len2, len2p;
8656 len1 = strcspn(s, "'");
8657 len2 = strspn(s + len1, "'");
8659 len1p = len1 ? len1 + 2 : len1;
8660 len2p = len2 + ((len2 < 2) ? len2 : 2);
8662 CHECKSTRSPACE(len1p + len2p + 1, p);
8667 memcpy(p + 1, s, len1);
8675 memcpy(q + 1, s, len2);
8678 } else if (len2 == 1) {
8684 STADJUST(len1p + len2p, p);
8689 return grabstackstr(p);
8693 * Like strdup but works with the ash stack.
8697 sstrdup(const char *p)
8699 size_t len = strlen(p) + 1;
8700 return memcpy(stalloc(len), p, len);
8705 * Routine for dealing with parsed shell commands.
8709 static void sizenodelist (const struct nodelist *);
8710 static struct nodelist *copynodelist (const struct nodelist *);
8711 static char *nodesavestr (const char *);
8713 //#define CALCSIZE_TABLE
8714 //#define COPYNODE_TABLE
8715 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8717 * To collect a lot of redundant code in case statements for copynode()
8718 * and calcsize(), we implement a mini language here. Each type of node
8719 * struct has an associated instruction sequence that operates on its
8720 * members via their offsets. The instruction are pack in unsigned chars
8721 * with format IIDDDDDE where the bits are
8722 * I : part of the instruction opcode, which are
8723 * 00 : member is a pointer to another node
8724 * 40 : member is an integer
8725 * 80 : member is a pointer to a nodelist
8726 * CC : member is a pointer to a char string
8727 * D : data - the actual offset of the member to operate on in the struct
8728 * (since we assume bit 0 is set, it is not shifted)
8729 * E : flag signaling end of instruction sequence
8731 * WARNING: In order to handle larger offsets for 64bit archs, this code
8732 * assumes that no offset can be an odd number and stores the
8733 * end-of-instructions flag in bit 0.
8736 #define NODE_INTEGER 0x40
8737 #define NODE_NODELIST 0x80
8738 #define NODE_CHARPTR 0xC0
8739 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8740 #define NODE_MBRMASK 0xC0
8741 #define NODE_OFFSETMASK 0x3E
8743 static const unsigned char copynode_ops[35] = {
8744 #define COPYNODE_OPS0 0
8745 offsetof(union node, nbinary.ch2),
8746 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8747 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8748 offsetof(union node, ncmd.redirect),
8749 offsetof(union node, ncmd.args),
8750 offsetof(union node, ncmd.assign),
8751 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8752 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8753 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8754 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8755 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8756 offsetof(union node, nredir.redirect),
8757 offsetof(union node, nredir.n)|NODE_NOMORE,
8758 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8759 offsetof(union node, nif.elsepart),
8760 offsetof(union node, nif.ifpart),
8761 offsetof(union node, nif.test)|NODE_NOMORE,
8762 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8763 offsetof(union node, nfor.var)|NODE_CHARPTR,
8764 offsetof(union node, nfor.body),
8765 offsetof(union node, nfor.args)|NODE_NOMORE,
8766 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8767 offsetof(union node, ncase.cases),
8768 offsetof(union node, ncase.expr)|NODE_NOMORE,
8769 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8770 offsetof(union node, nclist.body),
8771 offsetof(union node, nclist.pattern),
8772 offsetof(union node, nclist.next)|NODE_NOMORE,
8773 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8774 offsetof(union node, narg.backquote)|NODE_NODELIST,
8775 offsetof(union node, narg.text)|NODE_CHARPTR,
8776 offsetof(union node, narg.next)|NODE_NOMORE,
8777 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8778 offsetof(union node, nfile.fname),
8779 offsetof(union node, nfile.fd)|NODE_INTEGER,
8780 offsetof(union node, nfile.next)|NODE_NOMORE,
8781 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8782 offsetof(union node, ndup.vname),
8783 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8784 offsetof(union node, ndup.fd)|NODE_INTEGER,
8785 offsetof(union node, ndup.next)|NODE_NOMORE,
8786 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8787 offsetof(union node, nhere.doc),
8788 offsetof(union node, nhere.fd)|NODE_INTEGER,
8789 offsetof(union node, nhere.next)|NODE_NOMORE,
8790 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8791 offsetof(union node, nnot.com)|NODE_NOMORE,
8794 #if COPYNODE_OPS12 != 34
8795 #error COPYNODE_OPS12 is incorrect
8798 static const unsigned char copynode_ops_index[26] = {
8799 COPYNODE_OPS0, /* NSEMI */
8800 COPYNODE_OPS1, /* NCMD */
8801 COPYNODE_OPS2, /* NPIPE */
8802 COPYNODE_OPS3, /* NREDIR */
8803 COPYNODE_OPS3, /* NBACKGND */
8804 COPYNODE_OPS3, /* NSUBSHELL */
8805 COPYNODE_OPS0, /* NAND */
8806 COPYNODE_OPS0, /* NOR */
8807 COPYNODE_OPS4, /* NIF */
8808 COPYNODE_OPS0, /* NWHILE */
8809 COPYNODE_OPS0, /* NUNTIL */
8810 COPYNODE_OPS5, /* NFOR */
8811 COPYNODE_OPS6, /* NCASE */
8812 COPYNODE_OPS7, /* NCLIST */
8813 COPYNODE_OPS8, /* NDEFUN */
8814 COPYNODE_OPS8, /* NARG */
8815 COPYNODE_OPS9, /* NTO */
8816 COPYNODE_OPS9, /* NFROM */
8817 COPYNODE_OPS9, /* NFROMTO */
8818 COPYNODE_OPS9, /* NAPPEND */
8819 COPYNODE_OPS9, /* NTOOV */
8820 COPYNODE_OPS10, /* NTOFD */
8821 COPYNODE_OPS10, /* NFROMFD */
8822 COPYNODE_OPS11, /* NHERE */
8823 COPYNODE_OPS11, /* NXHERE */
8824 COPYNODE_OPS12, /* NNOT */
8827 #if NODE_CHARPTR != NODE_MBRMASK
8828 #error NODE_CHARPTR != NODE_MBRMASK!!!
8830 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8832 #ifdef COPYNODE_TABLE
8834 copynode(const union node *n)
8837 const unsigned char *p;
8843 new->type = n->type;
8844 funcblock = (char *) funcblock + (int) nodesize[n->type];
8845 p = copynode_ops + (int) copynode_ops_index[n->type];
8847 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8848 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8850 if (!(*p & NODE_MBRMASK)) { /* standard node */
8851 *((union node **)nn) = copynode(*((const union node **) no));
8852 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8853 *((const char **)nn) = nodesavestr(*((const char **)no));
8854 } else if (*p & NODE_NODELIST) { /* nodelist */
8855 *((struct nodelist **)nn)
8856 = copynodelist(*((const struct nodelist **) no));
8857 } else { /* integer */
8858 *((int *) nn) = *((int *) no);
8860 } while (!(*p++ & NODE_NOMORE));
8863 #else /* COPYNODE_TABLE */
8865 copynode(const union node *n)
8872 funcblock = (char *) funcblock + nodesize[n->type];
8879 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8880 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8883 new->ncmd.redirect = copynode(n->ncmd.redirect);
8884 new->ncmd.args = copynode(n->ncmd.args);
8885 new->ncmd.assign = copynode(n->ncmd.assign);
8886 new->ncmd.backgnd = n->ncmd.backgnd;
8889 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8890 new->npipe.backgnd = n->npipe.backgnd;
8895 new->nredir.redirect = copynode(n->nredir.redirect);
8896 new->nredir.n = copynode(n->nredir.n);
8899 new->nif.elsepart = copynode(n->nif.elsepart);
8900 new->nif.ifpart = copynode(n->nif.ifpart);
8901 new->nif.test = copynode(n->nif.test);
8904 new->nfor.var = nodesavestr(n->nfor.var);
8905 new->nfor.body = copynode(n->nfor.body);
8906 new->nfor.args = copynode(n->nfor.args);
8909 new->ncase.cases = copynode(n->ncase.cases);
8910 new->ncase.expr = copynode(n->ncase.expr);
8913 new->nclist.body = copynode(n->nclist.body);
8914 new->nclist.pattern = copynode(n->nclist.pattern);
8915 new->nclist.next = copynode(n->nclist.next);
8919 new->narg.backquote = copynodelist(n->narg.backquote);
8920 new->narg.text = nodesavestr(n->narg.text);
8921 new->narg.next = copynode(n->narg.next);
8928 new->nfile.fname = copynode(n->nfile.fname);
8929 new->nfile.fd = n->nfile.fd;
8930 new->nfile.next = copynode(n->nfile.next);
8934 new->ndup.vname = copynode(n->ndup.vname);
8935 new->ndup.dupfd = n->ndup.dupfd;
8936 new->ndup.fd = n->ndup.fd;
8937 new->ndup.next = copynode(n->ndup.next);
8941 new->nhere.doc = copynode(n->nhere.doc);
8942 new->nhere.fd = n->nhere.fd;
8943 new->nhere.next = copynode(n->nhere.next);
8946 new->nnot.com = copynode(n->nnot.com);
8949 new->type = n->type;
8952 #endif /* COPYNODE_TABLE */
8954 #ifdef CALCSIZE_TABLE
8956 calcsize(const union node *n)
8958 const unsigned char *p;
8962 funcblocksize += (int) nodesize[n->type];
8964 p = copynode_ops + (int) copynode_ops_index[n->type];
8966 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8968 if (!(*p & NODE_MBRMASK)) { /* standard node */
8969 calcsize(*((const union node **) no));
8970 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8971 funcstringsize += strlen(*((const char **)no)) + 1;
8972 } else if (*p & NODE_NODELIST) { /* nodelist */
8973 sizenodelist(*((const struct nodelist **) no));
8974 } /* else integer -- ignore */
8975 } while (!(*p++ & NODE_NOMORE));
8977 #else /* CALCSIZE_TABLE */
8979 calcsize(const union node *n)
8983 funcblocksize += nodesize[n->type];
8990 calcsize(n->nbinary.ch2);
8991 calcsize(n->nbinary.ch1);
8994 calcsize(n->ncmd.redirect);
8995 calcsize(n->ncmd.args);
8996 calcsize(n->ncmd.assign);
8999 sizenodelist(n->npipe.cmdlist);
9004 calcsize(n->nredir.redirect);
9005 calcsize(n->nredir.n);
9008 calcsize(n->nif.elsepart);
9009 calcsize(n->nif.ifpart);
9010 calcsize(n->nif.test);
9013 funcstringsize += strlen(n->nfor.var) + 1;
9014 calcsize(n->nfor.body);
9015 calcsize(n->nfor.args);
9018 calcsize(n->ncase.cases);
9019 calcsize(n->ncase.expr);
9022 calcsize(n->nclist.body);
9023 calcsize(n->nclist.pattern);
9024 calcsize(n->nclist.next);
9028 sizenodelist(n->narg.backquote);
9029 funcstringsize += strlen(n->narg.text) + 1;
9030 calcsize(n->narg.next);
9037 calcsize(n->nfile.fname);
9038 calcsize(n->nfile.next);
9042 calcsize(n->ndup.vname);
9043 calcsize(n->ndup.next);
9047 calcsize(n->nhere.doc);
9048 calcsize(n->nhere.next);
9051 calcsize(n->nnot.com);
9055 #endif /* CALCSIZE_TABLE */
9058 sizenodelist(const struct nodelist *lp)
9061 funcblocksize += ALIGN(sizeof(struct nodelist));
9068 static struct nodelist *
9069 copynodelist(const struct nodelist *lp)
9071 struct nodelist *start;
9072 struct nodelist **lpp;
9077 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
9078 (*lpp)->n = copynode(lp->n);
9080 lpp = &(*lpp)->next;
9088 nodesavestr(const char *s)
9091 char *q = funcstring;
9092 char *rtn = funcstring;
9094 while ((*q++ = *p++) != '\0')
9101 static int getopts (char *, char *, char **, int *, int *);
9106 * Process the shell command line arguments.
9110 procargs(argc, argv)
9119 for (i = 0; i < NOPTS; i++)
9122 if (*argptr == NULL && minusc == NULL)
9124 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
9128 for (i = 0; i < NOPTS; i++)
9129 if (optent_val(i) == 2)
9132 if (sflag == 0 && minusc == NULL) {
9133 commandname = argv[0];
9135 setinputfile(arg0, 0);
9138 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
9139 if (argptr && minusc && *argptr)
9142 shellparam.p = argptr;
9143 shellparam.optind = 1;
9144 shellparam.optoff = -1;
9145 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9147 shellparam.nparam++;
9156 * Process shell options. The global variable argptr contains a pointer
9157 * to the argument list; we advance it past the options.
9161 minus_o(const char *name, int val)
9166 out1str("Current option settings\n");
9167 for (i = 0; i < NOPTS; i++)
9168 printf("%-16s%s\n", optent_name(optlist[i]),
9169 optent_val(i) ? "on" : "off");
9171 for (i = 0; i < NOPTS; i++)
9172 if (equal(name, optent_name(optlist[i]))) {
9173 setoption(optent_letter(optlist[i]), val);
9176 error("Illegal option -o %s", name);
9182 options(int cmdline)
9190 while ((p = *argptr) != NULL) {
9192 if ((c = *p++) == '-') {
9194 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9196 /* "-" means turn off -x and -v */
9199 /* "--" means reset params */
9200 else if (*argptr == NULL)
9203 break; /* "-" or "--" terminates options */
9205 } else if (c == '+') {
9211 while ((c = *p++) != '\0') {
9212 if (c == 'c' && cmdline) {
9214 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9218 if (q == NULL || minusc != NULL)
9219 error("Bad -c option");
9224 } else if (c == 'o') {
9225 minus_o(*argptr, val);
9237 setoption(int flag, int val)
9241 for (i = 0; i < NOPTS; i++)
9242 if (optent_letter(optlist[i]) == flag) {
9243 optent_val(i) = val;
9245 /* #%$ hack for ksh semantics */
9248 else if (flag == 'E')
9253 error("Illegal option -%c", flag);
9260 * Set the shell parameters.
9264 setparam(char **argv)
9270 for (nparam = 0 ; argv[nparam] ; nparam++);
9271 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9273 *ap++ = savestr(*argv++);
9276 freeparam(&shellparam);
9277 shellparam.malloc = 1;
9278 shellparam.nparam = nparam;
9279 shellparam.p = newparam;
9280 shellparam.optind = 1;
9281 shellparam.optoff = -1;
9286 * Free the list of positional parameters.
9290 freeparam(volatile struct shparam *param)
9294 if (param->malloc) {
9295 for (ap = param->p ; *ap ; ap++)
9304 * The shift builtin command.
9308 shiftcmd(argc, argv)
9317 n = number(argv[1]);
9318 if (n > shellparam.nparam)
9319 error("can't shift that many");
9321 shellparam.nparam -= n;
9322 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9323 if (shellparam.malloc)
9327 while ((*ap2++ = *ap1++) != NULL);
9328 shellparam.optind = 1;
9329 shellparam.optoff = -1;
9337 * The set command builtin.
9346 return showvarscmd(argc, argv);
9350 if (*argptr != NULL) {
9359 getoptsreset(const char *value)
9361 shellparam.optind = number(value);
9362 shellparam.optoff = -1;
9365 #ifdef BB_LOCALE_SUPPORT
9366 static void change_lc_all(const char *value)
9368 if(value != 0 && *value != 0)
9369 setlocale(LC_ALL, value);
9372 static void change_lc_ctype(const char *value)
9374 if(value != 0 && *value != 0)
9375 setlocale(LC_CTYPE, value);
9382 * The getopts builtin. Shellparam.optnext points to the next argument
9383 * to be processed. Shellparam.optptr points to the next character to
9384 * be processed in the current argument. If shellparam.optnext is NULL,
9385 * then it's the first time getopts has been called.
9389 getoptscmd(argc, argv)
9396 error("Usage: getopts optstring var [arg]");
9397 else if (argc == 3) {
9398 optbase = shellparam.p;
9399 if (shellparam.optind > shellparam.nparam + 1) {
9400 shellparam.optind = 1;
9401 shellparam.optoff = -1;
9406 if (shellparam.optind > argc - 2) {
9407 shellparam.optind = 1;
9408 shellparam.optoff = -1;
9412 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9413 &shellparam.optoff);
9417 * Safe version of setvar, returns 1 on success 0 on failure.
9421 setvarsafe(name, val, flags)
9422 const char *name, *val;
9425 struct jmploc jmploc;
9426 struct jmploc *volatile savehandler = handler;
9432 if (setjmp(jmploc.loc))
9436 setvar(name, val, flags);
9438 handler = savehandler;
9443 getopts(optstr, optvar, optfirst, myoptind, optoff)
9455 char **optnext = optfirst + *myoptind - 1;
9457 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9458 strlen(*(optnext - 1)) < *optoff)
9461 p = *(optnext - 1) + *optoff;
9462 if (p == NULL || *p == '\0') {
9463 /* Current word is done, advance */
9464 if (optnext == NULL)
9467 if (p == NULL || *p != '-' || *++p == '\0') {
9469 *myoptind = optnext - optfirst + 1;
9475 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9480 for (q = optstr; *q != c; ) {
9482 if (optstr[0] == ':') {
9485 err |= setvarsafe("OPTARG", s, 0);
9488 out2fmt("Illegal option -%c\n", c);
9489 (void) unsetvar("OPTARG");
9499 if (*p == '\0' && (p = *optnext) == NULL) {
9500 if (optstr[0] == ':') {
9503 err |= setvarsafe("OPTARG", s, 0);
9507 out2fmt("No arg for -%c option\n", c);
9508 (void) unsetvar("OPTARG");
9516 setvarsafe("OPTARG", p, 0);
9520 setvarsafe("OPTARG", "", 0);
9521 *myoptind = optnext - optfirst + 1;
9528 *optoff = p ? p - *(optnext - 1) : -1;
9529 snprintf(s, sizeof(s), "%d", *myoptind);
9530 err |= setvarsafe("OPTIND", s, VNOFUNC);
9533 err |= setvarsafe(optvar, s, 0);
9544 * XXX - should get rid of. have all builtins use getopt(3). the
9545 * library getopt must have the BSD extension static variable "optreset"
9546 * otherwise it can't be used within the shell safely.
9548 * Standard option processing (a la getopt) for builtin routines. The
9549 * only argument that is passed to nextopt is the option string; the
9550 * other arguments are unnecessary. It return the character, or '\0' on
9555 nextopt(const char *optstring)
9561 if ((p = optptr) == NULL || *p == '\0') {
9563 if (p == NULL || *p != '-' || *++p == '\0')
9566 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9570 for (q = optstring ; *q != c ; ) {
9572 error("Illegal option -%c", c);
9577 if (*p == '\0' && (p = *argptr++) == NULL)
9578 error("No arg for -%c option", c);
9595 out2fmt(const char *fmt, ...)
9599 vfprintf(stderr, fmt, ap);
9604 * Version of write which resumes after a signal is caught.
9608 xwrite(int fd, const char *buf, int nbytes)
9617 i = write(fd, buf, n);
9623 } else if (i == 0) {
9626 } else if (errno != EINTR) {
9634 * Shell command parser.
9637 #define EOFMARKLEN 79
9642 struct heredoc *next; /* next here document in list */
9643 union node *here; /* redirection node */
9644 char *eofmark; /* string indicating end of input */
9645 int striptabs; /* if set, strip leading tabs */
9648 static struct heredoc *heredoclist; /* list of here documents to read */
9649 static int parsebackquote; /* nonzero if we are inside backquotes */
9650 static int doprompt; /* if set, prompt the user */
9651 static int needprompt; /* true if interactive and at start of line */
9652 static int lasttoken; /* last token read */
9654 static char *wordtext; /* text of last word returned by readtoken */
9656 static struct nodelist *backquotelist;
9657 static union node *redirnode;
9658 static struct heredoc *heredoc;
9659 static int quoteflag; /* set if (part of) last token was quoted */
9660 static int startlinno; /* line # where last token started */
9663 static union node *list (int);
9664 static union node *andor (void);
9665 static union node *pipeline (void);
9666 static union node *command (void);
9667 static union node *simplecmd (void);
9668 static void parsefname (void);
9669 static void parseheredoc (void);
9670 static char peektoken (void);
9671 static int readtoken (void);
9672 static int xxreadtoken (void);
9673 static int readtoken1 (int, int, const char *, int);
9674 static int noexpand (char *);
9675 static void synexpect (int) __attribute__((noreturn));
9676 static void synerror (const char *) __attribute__((noreturn));
9677 static void setprompt (int);
9681 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9682 * valid parse tree indicating a blank line.)
9686 parsecmd(int interact)
9691 doprompt = interact;
9711 union node *n1, *n2, *n3;
9715 if (nlflag == 0 && peektoken())
9721 if (tok == TBACKGND) {
9722 if (n2->type == NCMD || n2->type == NPIPE) {
9723 n2->ncmd.backgnd = 1;
9724 } else if (n2->type == NREDIR) {
9725 n2->type = NBACKGND;
9727 n3 = (union node *)stalloc(sizeof (struct nredir));
9728 n3->type = NBACKGND;
9730 n3->nredir.redirect = NULL;
9738 n3 = (union node *)stalloc(sizeof (struct nbinary));
9740 n3->nbinary.ch1 = n1;
9741 n3->nbinary.ch2 = n2;
9765 pungetc(); /* push back EOF on input */
9780 union node *n1, *n2, *n3;
9786 if ((t = readtoken()) == TAND) {
9788 } else if (t == TOR) {
9796 n3 = (union node *)stalloc(sizeof (struct nbinary));
9798 n3->nbinary.ch1 = n1;
9799 n3->nbinary.ch2 = n2;
9808 union node *n1, *n2, *pipenode;
9809 struct nodelist *lp, *prev;
9813 TRACE(("pipeline: entered\n"));
9814 if (readtoken() == TNOT) {
9820 if (readtoken() == TPIPE) {
9821 pipenode = (union node *)stalloc(sizeof (struct npipe));
9822 pipenode->type = NPIPE;
9823 pipenode->npipe.backgnd = 0;
9824 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9825 pipenode->npipe.cmdlist = lp;
9829 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9833 } while (readtoken() == TPIPE);
9839 n2 = (union node *)stalloc(sizeof (struct nnot));
9851 union node *n1, *n2;
9852 union node *ap, **app;
9853 union node *cp, **cpp;
9854 union node *redir, **rpp;
9861 /* Check for redirection which may precede command */
9862 while (readtoken() == TREDIR) {
9863 *rpp = n2 = redirnode;
9864 rpp = &n2->nfile.next;
9869 switch (readtoken()) {
9871 n1 = (union node *)stalloc(sizeof (struct nif));
9873 n1->nif.test = list(0);
9874 if (readtoken() != TTHEN)
9876 n1->nif.ifpart = list(0);
9878 while (readtoken() == TELIF) {
9879 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9880 n2 = n2->nif.elsepart;
9882 n2->nif.test = list(0);
9883 if (readtoken() != TTHEN)
9885 n2->nif.ifpart = list(0);
9887 if (lasttoken == TELSE)
9888 n2->nif.elsepart = list(0);
9890 n2->nif.elsepart = NULL;
9893 if (readtoken() != TFI)
9900 n1 = (union node *)stalloc(sizeof (struct nbinary));
9901 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9902 n1->nbinary.ch1 = list(0);
9903 if ((got=readtoken()) != TDO) {
9904 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9907 n1->nbinary.ch2 = list(0);
9908 if (readtoken() != TDONE)
9914 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9915 synerror("Bad for loop variable");
9916 n1 = (union node *)stalloc(sizeof (struct nfor));
9918 n1->nfor.var = wordtext;
9920 if (readtoken() == TIN) {
9922 while (readtoken() == TWORD) {
9923 n2 = (union node *)stalloc(sizeof (struct narg));
9925 n2->narg.text = wordtext;
9926 n2->narg.backquote = backquotelist;
9928 app = &n2->narg.next;
9932 if (lasttoken != TNL && lasttoken != TSEMI)
9935 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9937 n2 = (union node *)stalloc(sizeof (struct narg));
9939 n2->narg.text = argvars;
9940 n2->narg.backquote = NULL;
9941 n2->narg.next = NULL;
9944 * Newline or semicolon here is optional (but note
9945 * that the original Bourne shell only allowed NL).
9947 if (lasttoken != TNL && lasttoken != TSEMI)
9951 if (readtoken() != TDO)
9953 n1->nfor.body = list(0);
9954 if (readtoken() != TDONE)
9959 n1 = (union node *)stalloc(sizeof (struct ncase));
9961 if (readtoken() != TWORD)
9963 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9965 n2->narg.text = wordtext;
9966 n2->narg.backquote = backquotelist;
9967 n2->narg.next = NULL;
9970 } while (readtoken() == TNL);
9971 if (lasttoken != TIN)
9972 synerror("expecting \"in\"");
9973 cpp = &n1->ncase.cases;
9974 checkkwd = 2, readtoken();
9976 if (lasttoken == TLP)
9978 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9980 app = &cp->nclist.pattern;
9982 *app = ap = (union node *)stalloc(sizeof (struct narg));
9984 ap->narg.text = wordtext;
9985 ap->narg.backquote = backquotelist;
9986 if (checkkwd = 2, readtoken() != TPIPE)
9988 app = &ap->narg.next;
9991 ap->narg.next = NULL;
9992 if (lasttoken != TRP)
9994 cp->nclist.body = list(0);
9997 if ((t = readtoken()) != TESAC) {
9999 synexpect(TENDCASE);
10001 checkkwd = 2, readtoken();
10003 cpp = &cp->nclist.next;
10004 } while(lasttoken != TESAC);
10009 n1 = (union node *)stalloc(sizeof (struct nredir));
10010 n1->type = NSUBSHELL;
10011 n1->nredir.n = list(0);
10012 n1->nredir.redirect = NULL;
10013 if (readtoken() != TRP)
10019 if (readtoken() != TEND)
10023 /* Handle an empty command like other simple commands. */
10032 * An empty command before a ; doesn't make much sense, and
10033 * should certainly be disallowed in the case of `if ;'.
10046 /* Now check for redirection which may follow command */
10047 while (readtoken() == TREDIR) {
10048 *rpp = n2 = redirnode;
10049 rpp = &n2->nfile.next;
10055 if (n1->type != NSUBSHELL) {
10056 n2 = (union node *)stalloc(sizeof (struct nredir));
10061 n1->nredir.redirect = redir;
10068 static union node *
10070 union node *args, **app;
10071 union node *n = NULL;
10072 union node *vars, **vpp;
10073 union node **rpp, *redir;
10084 switch (readtoken()) {
10087 n = (union node *)stalloc(sizeof (struct narg));
10089 n->narg.text = wordtext;
10090 n->narg.backquote = backquotelist;
10091 if (lasttoken == TWORD) {
10093 app = &n->narg.next;
10096 vpp = &n->narg.next;
10100 *rpp = n = redirnode;
10101 rpp = &n->nfile.next;
10102 parsefname(); /* read name of redirection file */
10106 args && app == &args->narg.next &&
10109 /* We have a function */
10110 if (readtoken() != TRP)
10114 n->narg.next = command();
10127 n = (union node *)stalloc(sizeof (struct ncmd));
10129 n->ncmd.backgnd = 0;
10130 n->ncmd.args = args;
10131 n->ncmd.assign = vars;
10132 n->ncmd.redirect = redir;
10136 static union node *
10140 n = (union node *)stalloc(sizeof (struct narg));
10142 n->narg.next = NULL;
10143 n->narg.text = wordtext;
10144 n->narg.backquote = backquotelist;
10148 static void fixredir(union node *n, const char *text, int err)
10150 TRACE(("Fix redir %s %d\n", text, err));
10152 n->ndup.vname = NULL;
10154 if (is_digit(text[0]) && text[1] == '\0')
10155 n->ndup.dupfd = digit_val(text[0]);
10156 else if (text[0] == '-' && text[1] == '\0')
10157 n->ndup.dupfd = -1;
10161 synerror("Bad fd number");
10163 n->ndup.vname = makename();
10170 union node *n = redirnode;
10172 if (readtoken() != TWORD)
10174 if (n->type == NHERE) {
10175 struct heredoc *here = heredoc;
10179 if (quoteflag == 0)
10181 TRACE(("Here document %d\n", n->type));
10182 if (here->striptabs) {
10183 while (*wordtext == '\t')
10186 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10187 synerror("Illegal eof marker for << redirection");
10188 rmescapes(wordtext);
10189 here->eofmark = wordtext;
10191 if (heredoclist == NULL)
10192 heredoclist = here;
10194 for (p = heredoclist ; p->next ; p = p->next);
10197 } else if (n->type == NTOFD || n->type == NFROMFD) {
10198 fixredir(n, wordtext, 0);
10200 n->nfile.fname = makename();
10206 * Input any here documents.
10211 struct heredoc *here;
10214 while (heredoclist) {
10215 here = heredoclist;
10216 heredoclist = here->next;
10221 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10222 here->eofmark, here->striptabs);
10223 n = (union node *)stalloc(sizeof (struct narg));
10224 n->narg.type = NARG;
10225 n->narg.next = NULL;
10226 n->narg.text = wordtext;
10227 n->narg.backquote = backquotelist;
10228 here->here->nhere.doc = n;
10238 return tokname_array[t][0];
10246 int savecheckalias = checkalias;
10247 int savecheckkwd = checkkwd;
10252 int alreadyseen = tokpushback;
10262 checkalias = savecheckalias;
10269 if (checkkwd == 2) {
10278 * check for keywords
10280 if (t == TWORD && !quoteflag)
10282 const char *const *pp;
10284 if ((pp = findkwd(wordtext))) {
10285 lasttoken = t = pp - tokname_array;
10286 TRACE(("keyword %s recognized\n", tokname(t)));
10297 } else if (checkalias == 2 && isassignment(wordtext)) {
10298 lasttoken = t = TASSIGN;
10300 } else if (checkalias) {
10301 if (!quoteflag && (ap = lookupalias(wordtext, 1)) != NULL) {
10303 pushstring(ap->val, strlen(ap->val), ap);
10305 checkkwd = savecheckkwd;
10314 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10316 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10323 * Read the next input token.
10324 * If the token is a word, we set backquotelist to the list of cmds in
10325 * backquotes. We set quoteflag to true if any part of the word was
10327 * If the token is TREDIR, then we set redirnode to a structure containing
10329 * In all cases, the variable startlinno is set to the number of the line
10330 * on which the token starts.
10332 * [Change comment: here documents and internal procedures]
10333 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10334 * word parsing code into a separate routine. In this case, readtoken
10335 * doesn't need to have any internal procedures, but parseword does.
10336 * We could also make parseoperator in essence the main routine, and
10337 * have parseword (readtoken1?) handle both words and redirection.]
10340 #define RETURN(token) return lasttoken = token
10354 startlinno = plinno;
10355 for (;;) { /* until token or start of word found */
10358 case ' ': case '\t':
10364 while ((c = pgetc()) != '\n' && c != PEOF);
10368 if (pgetc() == '\n') {
10369 startlinno = ++plinno;
10380 needprompt = doprompt;
10385 if (pgetc() == '&')
10390 if (pgetc() == '|')
10395 if (pgetc() == ';')
10408 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10415 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10416 * is not NULL, read a here document. In the latter case, eofmark is the
10417 * word which marks the end of the document and striptabs is true if
10418 * leading tabs should be stripped from the document. The argument firstc
10419 * is the first character of the input token or document.
10421 * Because C does not have internal subroutines, I have simulated them
10422 * using goto's to implement the subroutine linkage. The following macros
10423 * will run code that appears at the end of readtoken1.
10426 #define CHECKEND() {goto checkend; checkend_return:;}
10427 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10428 #define PARSESUB() {goto parsesub; parsesub_return:;}
10429 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10430 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10431 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10434 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10439 char line[EOFMARKLEN + 1];
10440 struct nodelist *bqlist;
10443 int varnest; /* levels of variables expansion */
10444 int arinest; /* levels of arithmetic expansion */
10445 int parenlevel; /* levels of parens in arithmetic */
10446 int dqvarnest; /* levels of variables expansion within double quotes */
10448 int prevsyntax; /* syntax before arithmetic */
10450 /* Avoid longjmp clobbering */
10456 (void) &parenlevel;
10459 (void) &prevsyntax;
10463 startlinno = plinno;
10465 if (syntax == DQSYNTAX)
10474 STARTSTACKSTR(out);
10475 loop: { /* for each line, until end of word */
10476 CHECKEND(); /* set c to PEOF if at end of here document */
10477 for (;;) { /* until end of line or end of word */
10478 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10479 switch(SIT(c,syntax)) {
10480 case CNL: /* '\n' */
10481 if (syntax == BASESYNTAX)
10482 goto endword; /* exit outer loop */
10490 goto loop; /* continue outer loop */
10495 if ((eofmark == NULL || dblquote) &&
10497 USTPUTC(CTLESC, out);
10500 case CBACK: /* backslash */
10503 USTPUTC('\\', out);
10505 } else if (c == '\n') {
10511 if (dblquote && c != '\\' && c != '`' && c != '$'
10512 && (c != '"' || eofmark != NULL))
10513 USTPUTC('\\', out);
10514 if (SIT(c,SQSYNTAX) == CCTL)
10515 USTPUTC(CTLESC, out);
10516 else if (eofmark == NULL)
10517 USTPUTC(CTLQUOTEMARK, out);
10523 if (eofmark == NULL)
10524 USTPUTC(CTLQUOTEMARK, out);
10528 if (eofmark == NULL)
10529 USTPUTC(CTLQUOTEMARK, out);
10534 if (eofmark != NULL && arinest == 0 &&
10539 syntax = ARISYNTAX;
10541 } else if (eofmark == NULL &&
10543 syntax = BASESYNTAX;
10549 case CVAR: /* '$' */
10550 PARSESUB(); /* parse substitution */
10552 case CENDVAR: /* '}' */
10555 if (dqvarnest > 0) {
10558 USTPUTC(CTLENDVAR, out);
10563 #ifdef ASH_MATH_SUPPORT
10564 case CLP: /* '(' in arithmetic */
10568 case CRP: /* ')' in arithmetic */
10569 if (parenlevel > 0) {
10573 if (pgetc() == ')') {
10574 if (--arinest == 0) {
10575 USTPUTC(CTLENDARI, out);
10576 syntax = prevsyntax;
10577 if (syntax == DQSYNTAX)
10585 * unbalanced parens
10586 * (don't 2nd guess - no error)
10594 case CBQUOTE: /* '`' */
10598 goto endword; /* exit outer loop */
10603 goto endword; /* exit outer loop */
10614 if (syntax == ARISYNTAX)
10615 synerror("Missing '))'");
10616 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10617 synerror("Unterminated quoted string");
10618 if (varnest != 0) {
10619 startlinno = plinno;
10620 synerror("Missing '}'");
10622 USTPUTC('\0', out);
10623 len = out - stackblock();
10624 out = stackblock();
10625 if (eofmark == NULL) {
10626 if ((c == '>' || c == '<')
10629 && (*out == '\0' || is_digit(*out))) {
10631 return lasttoken = TREDIR;
10636 quoteflag = quotef;
10637 backquotelist = bqlist;
10638 grabstackblock(len);
10640 return lasttoken = TWORD;
10641 /* end of readtoken routine */
10646 * Check to see whether we are at the end of the here document. When this
10647 * is called, c is set to the first character of the next input line. If
10648 * we are at the end of the here document, this routine sets the c to PEOF.
10659 while (c == '\t') {
10663 if (c == *eofmark) {
10664 if (pfgets(line, sizeof line) != NULL) {
10668 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10669 if (*p == '\n' && *q == '\0') {
10672 needprompt = doprompt;
10674 pushstring(line, strlen(line), NULL);
10679 goto checkend_return;
10684 * Parse a redirection operator. The variable "out" points to a string
10685 * specifying the fd to be redirected. The variable "c" contains the
10686 * first character of the redirection operator.
10693 np = (union node *)stalloc(sizeof (struct nfile));
10698 np->type = NAPPEND;
10707 } else { /* c == '<' */
10709 switch (c = pgetc()) {
10711 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10712 np = (union node *)stalloc(sizeof (struct nhere));
10716 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10717 heredoc->here = np;
10718 if ((c = pgetc()) == '-') {
10719 heredoc->striptabs = 1;
10721 heredoc->striptabs = 0;
10727 np->type = NFROMFD;
10731 np->type = NFROMTO;
10741 np->nfile.fd = digit_val(fd);
10743 goto parseredir_return;
10748 * Parse a substitution. At this point, we have read the dollar sign
10749 * and nothing else.
10757 static const char types[] = "}-+?=";
10762 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10766 } else if (c == '(') { /* $(command) or $((arith)) */
10767 if (pgetc() == '(') {
10774 USTPUTC(CTLVAR, out);
10775 typeloc = out - stackblock();
10776 USTPUTC(VSNORMAL, out);
10777 subtype = VSNORMAL;
10781 if ((c = pgetc()) == '}')
10784 subtype = VSLENGTH;
10789 if (c > PEOA && is_name(c)) {
10793 } while (c > PEOA && is_in_name(c));
10794 } else if (is_digit(c)) {
10798 } while (is_digit(c));
10800 else if (is_special(c)) {
10805 badsub: synerror("Bad substitution");
10809 if (subtype == 0) {
10816 p = strchr(types, c);
10819 subtype = p - types + VSNORMAL;
10825 subtype = c == '#' ? VSTRIMLEFT :
10838 if (dblquote || arinest)
10840 *(stackblock() + typeloc) = subtype | flags;
10841 if (subtype != VSNORMAL) {
10848 goto parsesub_return;
10853 * Called to parse command substitutions. Newstyle is set if the command
10854 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10855 * list of commands (passed by reference), and savelen is the number of
10856 * characters on the top of the stack which must be preserved.
10860 struct nodelist **nlpp;
10863 char *volatile str;
10864 struct jmploc jmploc;
10865 struct jmploc *volatile savehandler;
10869 (void) &saveprompt;
10872 savepbq = parsebackquote;
10873 if (setjmp(jmploc.loc)) {
10876 parsebackquote = 0;
10877 handler = savehandler;
10878 longjmp(handler->loc, 1);
10882 savelen = out - stackblock();
10884 str = ckmalloc(savelen);
10885 memcpy(str, stackblock(), savelen);
10887 savehandler = handler;
10891 /* We must read until the closing backquote, giving special
10892 treatment to some slashes, and then push the string and
10893 reread it as input, interpreting it normally. */
10900 STARTSTACKSTR(pout);
10906 switch (pc = pgetc()) {
10911 if ((pc = pgetc()) == '\n') {
10918 * If eating a newline, avoid putting
10919 * the newline into the new character
10920 * stream (via the STPUTC after the
10925 if (pc != '\\' && pc != '`' && pc != '$'
10926 && (!dblquote || pc != '"'))
10927 STPUTC('\\', pout);
10937 startlinno = plinno;
10938 synerror("EOF in backquote substitution");
10942 needprompt = doprompt;
10951 STPUTC('\0', pout);
10952 psavelen = pout - stackblock();
10953 if (psavelen > 0) {
10954 pstr = grabstackstr(pout);
10955 setinputstring(pstr);
10960 nlpp = &(*nlpp)->next;
10961 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10962 (*nlpp)->next = NULL;
10963 parsebackquote = oldstyle;
10966 saveprompt = doprompt;
10973 doprompt = saveprompt;
10975 if (readtoken() != TRP)
10982 * Start reading from old file again, ignoring any pushed back
10983 * tokens left from the backquote parsing
10988 while (stackblocksize() <= savelen)
10990 STARTSTACKSTR(out);
10992 memcpy(out, str, savelen);
10993 STADJUST(savelen, out);
10999 parsebackquote = savepbq;
11000 handler = savehandler;
11001 if (arinest || dblquote)
11002 USTPUTC(CTLBACKQ | CTLQUOTE, out);
11004 USTPUTC(CTLBACKQ, out);
11006 goto parsebackq_oldreturn;
11008 goto parsebackq_newreturn;
11012 * Parse an arithmetic expansion (indicate start of one and set state)
11016 if (++arinest == 1) {
11017 prevsyntax = syntax;
11018 syntax = ARISYNTAX;
11019 USTPUTC(CTLARI, out);
11026 * we collapse embedded arithmetic expansion to
11027 * parenthesis, which should be equivalent
11031 goto parsearith_return;
11034 } /* end of readtoken */
11038 * Returns true if the text contains nothing to expand (no dollar signs
11050 while ((c = *p++) != '\0') {
11051 if (c == CTLQUOTEMARK)
11055 else if (SIT(c,BASESYNTAX) == CCTL)
11063 * Return true if the argument is a legal variable name (a letter or
11064 * underscore followed by zero or more letters, underscores, and digits).
11068 goodname(const char *name)
11076 if (! is_in_name(*p))
11084 * Called when an unexpected token is read during the parse. The argument
11085 * is the token that is expected, or -1 if more than one type of token can
11086 * occur at this point.
11096 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11098 sprintf(msg+l, " (expecting %s)", tokname(token));
11105 synerror(const char *msg)
11108 out2fmt("%s: %d: ", commandname, startlinno);
11109 out2fmt("Syntax error: %s\n", msg);
11110 error((char *)NULL);
11116 * called by editline -- any expansions to the prompt
11117 * should be added here.
11120 setprompt(int whichprompt)
11123 switch (whichprompt) {
11138 * Code for dealing with input/output redirection.
11141 #define EMPTY -2 /* marks an unused slot in redirtab */
11143 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11145 # define PIPESIZE PIPE_BUF
11150 * Open a file in noclobber mode.
11151 * The code was copied from bash.
11154 noclobberopen(const char *fname)
11157 struct stat finfo, finfo2;
11160 * If the file exists and is a regular file, return an error
11163 r = stat(fname, &finfo);
11164 if (r == 0 && S_ISREG(finfo.st_mode)) {
11170 * If the file was not present (r != 0), make sure we open it
11171 * exclusively so that if it is created before we open it, our open
11172 * will fail. Make sure that we do not truncate an existing file.
11173 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11174 * file was not a regular file, we leave O_EXCL off.
11177 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11178 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11180 /* If the open failed, return the file descriptor right away. */
11185 * OK, the open succeeded, but the file may have been changed from a
11186 * non-regular file to a regular file between the stat and the open.
11187 * We are assuming that the O_EXCL open handles the case where FILENAME
11188 * did not exist and is symlinked to an existing file between the stat
11193 * If we can open it and fstat the file descriptor, and neither check
11194 * revealed that it was a regular file, and the file has not been
11195 * replaced, return the file descriptor.
11197 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11198 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11201 /* The file has been replaced. badness. */
11208 * Handle here documents. Normally we fork off a process to write the
11209 * data to a pipe. If the document is short, we can stuff the data in
11210 * the pipe without forking.
11214 openhere(const union node *redir)
11220 error("Pipe call failed");
11221 if (redir->type == NHERE) {
11222 len = strlen(redir->nhere.doc->narg.text);
11223 if (len <= PIPESIZE) {
11224 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11228 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11230 signal(SIGINT, SIG_IGN);
11231 signal(SIGQUIT, SIG_IGN);
11232 signal(SIGHUP, SIG_IGN);
11234 signal(SIGTSTP, SIG_IGN);
11236 signal(SIGPIPE, SIG_DFL);
11237 if (redir->type == NHERE)
11238 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11240 expandhere(redir->nhere.doc, pip[1]);
11250 openredirect(const union node *redir)
11255 switch (redir->nfile.type) {
11257 fname = redir->nfile.expfname;
11258 if ((f = open(fname, O_RDONLY)) < 0)
11262 fname = redir->nfile.expfname;
11263 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11267 /* Take care of noclobber mode. */
11269 fname = redir->nfile.expfname;
11270 if ((f = noclobberopen(fname)) < 0)
11275 fname = redir->nfile.expfname;
11277 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11280 if ((f = creat(fname, 0666)) < 0)
11285 fname = redir->nfile.expfname;
11287 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11290 if ((f = open(fname, O_WRONLY)) < 0
11291 && (f = creat(fname, 0666)) < 0)
11293 lseek(f, (off_t)0, 2);
11300 /* Fall through to eliminate warning. */
11307 f = openhere(redir);
11313 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11315 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11320 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11321 * old file descriptors are stashed away so that the redirection can be
11322 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11323 * standard output, and the standard error if it becomes a duplicate of
11328 redirect(union node *redir, int flags)
11331 struct redirtab *sv = NULL;
11336 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11338 if (flags & REDIR_PUSH) {
11339 sv = ckmalloc(sizeof (struct redirtab));
11340 for (i = 0 ; i < 10 ; i++)
11341 sv->renamed[i] = EMPTY;
11342 sv->next = redirlist;
11345 for (n = redir ; n ; n = n->nfile.next) {
11348 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11349 n->ndup.dupfd == fd)
11350 continue; /* redirect from/to same file descriptor */
11353 newfd = openredirect(n);
11354 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11357 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11361 dupredirect(n, newfd, fd1dup);
11371 error("%d: %m", fd);
11377 if (flags & REDIR_PUSH) {
11378 sv->renamed[fd] = i;
11381 } else if (fd != newfd) {
11387 dupredirect(n, newfd, fd1dup);
11394 dupredirect(const union node *redir, int f, int fd1dup)
11396 int fd = redir->nfile.fd;
11400 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11401 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11402 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11403 dup_as_newfd(redir->ndup.dupfd, fd);
11409 dup_as_newfd(f, fd);
11418 * Undo the effects of the last redirection.
11424 struct redirtab *rp = redirlist;
11428 for (i = 0 ; i < 10 ; i++) {
11429 if (rp->renamed[i] != EMPTY) {
11433 if (rp->renamed[i] >= 0) {
11434 dup_as_newfd(rp->renamed[i], i);
11435 close(rp->renamed[i]);
11439 redirlist = rp->next;
11445 * Discard all saved file descriptors.
11450 struct redirtab *rp;
11453 for (rp = redirlist ; rp ; rp = rp->next) {
11454 for (i = 0 ; i < 10 ; i++) {
11455 if (rp->renamed[i] >= 0) {
11456 close(rp->renamed[i]);
11458 rp->renamed[i] = EMPTY;
11465 * Copy a file descriptor to be >= to. Returns -1
11466 * if the source file descriptor is closed, EMPTY if there are no unused
11467 * file descriptors left.
11471 dup_as_newfd(from, to)
11477 newfd = fcntl(from, F_DUPFD, to);
11479 if (errno == EMFILE)
11482 error("%d: %m", from);
11488 static void shtree (union node *, int, char *, FILE*);
11489 static void shcmd (union node *, FILE *);
11490 static void sharg (union node *, FILE *);
11491 static void indent (int, char *, FILE *);
11492 static void trstring (char *);
11499 trputs("showtree called\n");
11500 shtree(n, 1, NULL, stdout);
11505 shtree(n, ind, pfx, fp)
11511 struct nodelist *lp;
11517 indent(ind, pfx, fp);
11528 shtree(n->nbinary.ch1, ind, NULL, fp);
11531 shtree(n->nbinary.ch2, ind, NULL, fp);
11539 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11544 if (n->npipe.backgnd)
11550 fprintf(fp, "<node type %d>", n->type);
11570 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11576 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11582 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11583 s = redir_strings[np->nfile.type - NTO];
11589 switch (np->nfile.type) {
11590 case NTO: s = ">"; dftfd = 1; break;
11591 case NAPPEND: s = ">>"; dftfd = 1; break;
11592 case NTOFD: s = ">&"; dftfd = 1; break;
11593 case NTOOV: s = ">|"; dftfd = 1; break;
11594 case NFROM: s = "<"; dftfd = 0; break;
11595 case NFROMFD: s = "<&"; dftfd = 0; break;
11596 case NFROMTO: s = "<>"; dftfd = 0; break;
11597 default: s = "*error*"; dftfd = 0; break;
11600 if (np->nfile.fd != dftfd)
11601 fprintf(fp, "%d", np->nfile.fd);
11603 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11604 fprintf(fp, "%d", np->ndup.dupfd);
11606 sharg(np->nfile.fname, fp);
11620 struct nodelist *bqlist;
11623 if (arg->type != NARG) {
11624 printf("<node type %d>\n", arg->type);
11628 bqlist = arg->narg.backquote;
11629 for (p = arg->narg.text ; *p ; p++) {
11638 if (subtype == VSLENGTH)
11644 if (subtype & VSNUL)
11647 switch (subtype & VSTYPE) {
11666 case VSTRIMLEFTMAX:
11673 case VSTRIMRIGHTMAX:
11680 printf("<subtype %d>", subtype);
11687 case CTLBACKQ|CTLQUOTE:
11690 shtree(bqlist->n, -1, NULL, fp);
11702 indent(amount, pfx, fp)
11709 for (i = 0 ; i < amount ; i++) {
11710 if (pfx && i == amount - 1)
11728 static int debug = 1;
11730 static int debug = 0;
11738 if (tracefile == NULL)
11740 putc(c, tracefile);
11746 trace(const char *fmt, ...)
11750 if (tracefile != NULL) {
11751 (void) vfprintf(tracefile, fmt, va);
11752 if (strchr(fmt, '\n'))
11753 (void) fflush(tracefile);
11763 if (tracefile == NULL)
11765 fputs(s, tracefile);
11766 if (strchr(s, '\n'))
11778 if (tracefile == NULL)
11780 putc('"', tracefile);
11781 for (p = s ; *p ; p++) {
11783 case '\n': c = 'n'; goto backslash;
11784 case '\t': c = 't'; goto backslash;
11785 case '\r': c = 'r'; goto backslash;
11786 case '"': c = '"'; goto backslash;
11787 case '\\': c = '\\'; goto backslash;
11788 case CTLESC: c = 'e'; goto backslash;
11789 case CTLVAR: c = 'v'; goto backslash;
11790 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11791 case CTLBACKQ: c = 'q'; goto backslash;
11792 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11793 backslash: putc('\\', tracefile);
11794 putc(c, tracefile);
11797 if (*p >= ' ' && *p <= '~')
11798 putc(*p, tracefile);
11800 putc('\\', tracefile);
11801 putc(*p >> 6 & 03, tracefile);
11802 putc(*p >> 3 & 07, tracefile);
11803 putc(*p & 07, tracefile);
11808 putc('"', tracefile);
11816 if (tracefile == NULL)
11821 putc(' ', tracefile);
11823 putc('\n', tracefile);
11838 #ifdef not_this_way
11841 if ((p = getenv("HOME")) == NULL) {
11842 if (geteuid() == 0)
11848 strcat(s, "/trace");
11851 strcpy(s, "./trace");
11852 #endif /* not_this_way */
11853 if ((tracefile = fopen(s, "a")) == NULL) {
11854 fprintf(stderr, "Can't open %s\n", s);
11858 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11859 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11861 fputs("\nTracing started.\n", tracefile);
11868 * The trap builtin.
11872 trapcmd(argc, argv)
11881 for (signo = 0 ; signo < NSIG ; signo++) {
11882 if (trap[signo] != NULL) {
11886 p = single_quote(trap[signo]);
11887 sn = sys_siglist[signo];
11889 sn = u_signal_names(0, &signo, 0);
11892 printf("trap -- %s %s\n", p, sn);
11904 if ((signo = decode_signal(*ap, 0)) < 0)
11905 error("%s: bad trap", *ap);
11908 if (action[0] == '-' && action[1] == '\0')
11911 action = savestr(action);
11914 ckfree(trap[signo]);
11915 trap[signo] = action;
11930 * Set the signal handler for the specified signal. The routine figures
11931 * out what it should be set to.
11935 setsignal(int signo)
11939 struct sigaction act;
11941 if ((t = trap[signo]) == NULL)
11943 else if (*t != '\0')
11947 if (rootshell && action == S_DFL) {
11950 if (iflag || minusc || sflag == 0)
11976 t = &sigmode[signo - 1];
11979 * current setting unknown
11981 if (sigaction(signo, 0, &act) == -1) {
11983 * Pretend it worked; maybe we should give a warning
11984 * here, but other shells don't. We don't alter
11985 * sigmode, so that we retry every time.
11989 if (act.sa_handler == SIG_IGN) {
11990 if (mflag && (signo == SIGTSTP ||
11991 signo == SIGTTIN || signo == SIGTTOU)) {
11992 *t = S_IGN; /* don't hard ignore these */
11996 *t = S_RESET; /* force to be set */
11999 if (*t == S_HARD_IGN || *t == action)
12001 act.sa_handler = ((action == S_CATCH) ? onsig
12002 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
12005 sigemptyset(&act.sa_mask);
12006 sigaction(signo, &act, 0);
12017 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
12018 signal(signo, SIG_IGN);
12020 sigmode[signo - 1] = S_HARD_IGN;
12031 if (signo == SIGINT && trap[SIGINT] == NULL) {
12035 gotsig[signo - 1] = 1;
12041 * Called to execute a trap. Perhaps we should avoid entering new trap
12042 * handlers while we are executing a trap handler.
12052 for (i = 1 ; ; i++) {
12059 savestatus=exitstatus;
12060 evalstring(trap[i], 0);
12061 exitstatus=savestatus;
12068 * Called to exit the shell.
12072 exitshell(int status)
12074 struct jmploc loc1, loc2;
12077 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12078 if (setjmp(loc1.loc)) {
12081 if (setjmp(loc2.loc)) {
12085 if ((p = trap[0]) != NULL && *p != '\0') {
12089 l1: handler = &loc2; /* probably unnecessary */
12098 static int decode_signal(const char *string, int minsig)
12101 const char *name = u_signal_names(string, &signo, minsig);
12103 return name ? signo : -1;
12106 static struct var **hashvar (const char *);
12107 static void showvars (const char *, int, int);
12108 static struct var **findvar (struct var **, const char *);
12111 * Initialize the varable symbol tables and import the environment
12115 * This routine initializes the builtin variables. It is called when the
12116 * shell is initialized and again when a shell procedure is spawned.
12121 const struct varinit *ip;
12125 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12126 if ((vp->flags & VEXPORT) == 0) {
12127 vpp = hashvar(ip->text);
12130 vp->text = strdup(ip->text);
12131 vp->flags = ip->flags;
12132 vp->func = ip->func;
12136 * PS1 depends on uid
12138 if ((vps1.flags & VEXPORT) == 0) {
12139 vpp = hashvar("PS1=");
12142 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12143 vps1.flags = VSTRFIXED|VTEXTFIXED;
12148 * Set the value of a variable. The flags argument is ored with the
12149 * flags of the variable. If val is NULL, the variable is unset.
12153 setvar(name, val, flags)
12154 const char *name, *val;
12170 if (! is_in_name(*p)) {
12171 if (*p == '\0' || *p == '=')
12177 namelen = p - name;
12179 error("%.*s: bad variable name", namelen, name);
12180 len = namelen + 2; /* 2 is space for '=' and '\0' */
12184 len += vallen = strlen(val);
12187 nameeq = ckmalloc(len);
12188 memcpy(nameeq, name, namelen);
12189 nameeq[namelen] = '=';
12191 memcpy(nameeq + namelen + 1, val, vallen + 1);
12193 nameeq[namelen + 1] = '\0';
12195 setvareq(nameeq, flags);
12202 * Same as setvar except that the variable and value are passed in
12203 * the first argument as name=value. Since the first argument will
12204 * be actually stored in the table, it should not be a string that
12213 struct var *vp, **vpp;
12216 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12217 if ((vp = *findvar(vpp, s))) {
12218 if (vp->flags & VREADONLY) {
12219 size_t len = strchr(s, '=') - s;
12220 error("%.*s: is read only", len, s);
12224 if (vp->func && (flags & VNOFUNC) == 0)
12225 (*vp->func)(strchr(s, '=') + 1);
12227 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12230 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12231 vp->flags |= flags;
12235 * We could roll this to a function, to handle it as
12236 * a regular variable function callback, but why bother?
12238 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12244 vp = ckmalloc(sizeof (*vp));
12255 * Process a linked list of variable assignments.
12260 struct strlist *mylist;
12262 struct strlist *lp;
12265 for (lp = mylist ; lp ; lp = lp->next) {
12266 setvareq(savestr(lp->text), 0);
12274 * Find the value of a variable. Returns NULL if not set.
12277 static const char *
12283 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12284 return strchr(v->text, '=') + 1;
12292 * Search the environment of a builtin command.
12295 static const char *
12296 bltinlookup(const char *name)
12298 const struct strlist *sp;
12300 for (sp = cmdenviron ; sp ; sp = sp->next) {
12301 if (varequal(sp->text, name))
12302 return strchr(sp->text, '=') + 1;
12304 return lookupvar(name);
12310 * Generate a list of exported variables. This routine is used to construct
12311 * the third argument to execve when executing a program.
12323 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12324 for (vp = *vpp ; vp ; vp = vp->next)
12325 if (vp->flags & VEXPORT)
12328 ep = env = stalloc((nenv + 1) * sizeof *env);
12329 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12330 for (vp = *vpp ; vp ; vp = vp->next)
12331 if (vp->flags & VEXPORT)
12340 * Called when a shell procedure is invoked to clear out nonexported
12341 * variables. It is also necessary to reallocate variables of with
12342 * VSTACK set since these are currently allocated on the stack.
12348 struct var *vp, **prev;
12350 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12351 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12352 if ((vp->flags & VEXPORT) == 0) {
12354 if ((vp->flags & VTEXTFIXED) == 0)
12356 if ((vp->flags & VSTRFIXED) == 0)
12359 if (vp->flags & VSTACK) {
12360 vp->text = savestr(vp->text);
12361 vp->flags &=~ VSTACK;
12373 * Command to list all variables which are set. Currently this command
12374 * is invoked from the set command when the set command is called without
12379 showvarscmd(argc, argv)
12383 showvars(nullstr, VUNSET, VUNSET);
12390 * The export and readonly commands.
12394 exportcmd(argc, argv)
12401 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12404 listsetvar(cmdenviron);
12405 pflag = (nextopt("p") == 'p');
12406 if (argc > 1 && !pflag) {
12407 while ((name = *argptr++) != NULL) {
12408 if ((p = strchr(name, '=')) != NULL) {
12411 if ((vp = *findvar(hashvar(name), name))) {
12416 setvar(name, p, flag);
12420 showvars(argv[0], flag, 0);
12427 * The "local" command.
12430 /* funcnest nonzero if we are currently evaluating a function */
12433 localcmd(argc, argv)
12440 error("Not in a function");
12441 while ((name = *argptr++) != NULL) {
12449 * Make a variable a local variable. When a variable is made local, it's
12450 * value and flags are saved in a localvar structure. The saved values
12451 * will be restored when the shell function returns. We handle the name
12452 * "-" as a special case.
12459 struct localvar *lvp;
12464 lvp = ckmalloc(sizeof (struct localvar));
12465 if (name[0] == '-' && name[1] == '\0') {
12467 p = ckmalloc(sizeof optet_vals);
12468 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12471 vpp = hashvar(name);
12472 vp = *findvar(vpp, name);
12474 if (strchr(name, '='))
12475 setvareq(savestr(name), VSTRFIXED);
12477 setvar(name, NULL, VSTRFIXED);
12478 vp = *vpp; /* the new variable */
12480 lvp->flags = VUNSET;
12482 lvp->text = vp->text;
12483 lvp->flags = vp->flags;
12484 vp->flags |= VSTRFIXED|VTEXTFIXED;
12485 if (strchr(name, '='))
12486 setvareq(savestr(name), 0);
12490 lvp->next = localvars;
12497 * Called after a function returns.
12502 struct localvar *lvp;
12505 while ((lvp = localvars) != NULL) {
12506 localvars = lvp->next;
12508 if (vp == NULL) { /* $- saved */
12509 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12511 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12512 (void)unsetvar(vp->text);
12514 if ((vp->flags & VTEXTFIXED) == 0)
12516 vp->flags = lvp->flags;
12517 vp->text = lvp->text;
12525 setvarcmd(argc, argv)
12530 return unsetcmd(argc, argv);
12531 else if (argc == 3)
12532 setvar(argv[1], argv[2], 0);
12534 error("List assignment not implemented");
12540 * The unset builtin command. We unset the function before we unset the
12541 * variable to allow a function to be unset when there is a readonly variable
12542 * with the same name.
12546 unsetcmd(argc, argv)
12556 while ((i = nextopt("vf")) != '\0') {
12562 if (flg_func == 0 && flg_var == 0)
12565 for (ap = argptr; *ap ; ap++) {
12569 ret |= unsetvar(*ap);
12576 * Unset the specified variable.
12580 unsetvar(const char *s)
12585 vpp = findvar(hashvar(s), s);
12588 if (vp->flags & VREADONLY)
12591 if (*(strchr(vp->text, '=') + 1) != '\0')
12592 setvar(s, nullstr, 0);
12593 vp->flags &= ~VEXPORT;
12594 vp->flags |= VUNSET;
12595 if ((vp->flags & VSTRFIXED) == 0) {
12596 if ((vp->flags & VTEXTFIXED) == 0)
12611 * Find the appropriate entry in the hash table from the name.
12614 static struct var **
12615 hashvar(const char *p)
12617 unsigned int hashval;
12619 hashval = ((unsigned char) *p) << 4;
12620 while (*p && *p != '=')
12621 hashval += (unsigned char) *p++;
12622 return &vartab[hashval % VTABSIZE];
12628 * Returns true if the two strings specify the same varable. The first
12629 * variable name is terminated by '='; the second may be terminated by
12630 * either '=' or '\0'.
12634 varequal(const char *p, const char *q)
12636 while (*p == *q++) {
12640 if (*p == '=' && *(q - 1) == '\0')
12646 showvars(const char *myprefix, int mask, int xor)
12650 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12652 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12653 for (vp = *vpp ; vp ; vp = vp->next) {
12654 if ((vp->flags & mask) ^ xor) {
12658 p = strchr(vp->text, '=') + 1;
12659 len = p - vp->text;
12660 p = single_quote(p);
12662 printf("%s%s%.*s%s\n", myprefix, sep, len,
12670 static struct var **
12671 findvar(struct var **vpp, const char *name)
12673 for (; *vpp; vpp = &(*vpp)->next) {
12674 if (varequal((*vpp)->text, name)) {
12682 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12683 * This file contains code for the times builtin.
12684 * $Id: ash.c,v 1.24 2001/09/06 18:00:41 andersen Exp $
12686 static int timescmd (int argc, char **argv)
12689 long int clk_tck = sysconf(_SC_CLK_TCK);
12692 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12693 (int) (buf.tms_utime / clk_tck / 60),
12694 ((double) buf.tms_utime) / clk_tck,
12695 (int) (buf.tms_stime / clk_tck / 60),
12696 ((double) buf.tms_stime) / clk_tck,
12697 (int) (buf.tms_cutime / clk_tck / 60),
12698 ((double) buf.tms_cutime) / clk_tck,
12699 (int) (buf.tms_cstime / clk_tck / 60),
12700 ((double) buf.tms_cstime) / clk_tck);
12704 #ifdef ASH_MATH_SUPPORT
12705 /* The let builtin. */
12706 int letcmd(int argc, char **argv)
12711 char *tmp, *expression, p[13];
12712 expression = strchr(argv[1], '=');
12714 /* Cannot use 'error()' here, or the return code
12715 * will be incorrect */
12716 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12719 *expression = '\0';
12720 tmp = ++expression;
12721 result = arith(tmp, &errcode);
12723 /* Cannot use 'error()' here, or the return code
12724 * will be incorrect */
12725 out2fmt("sh: let: ");
12727 out2fmt("divide by zero");
12729 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12732 snprintf(p, 12, "%ld", result);
12733 setvar(argv[1], savestr(p), 0);
12734 } else if (argc >= 3)
12735 synerror("invalid operand");
12743 * Copyright (c) 1989, 1991, 1993, 1994
12744 * The Regents of the University of California. All rights reserved.
12746 * This code is derived from software contributed to Berkeley by
12747 * Kenneth Almquist.
12749 * Redistribution and use in source and binary forms, with or without
12750 * modification, are permitted provided that the following conditions
12752 * 1. Redistributions of source code must retain the above copyright
12753 * notice, this list of conditions and the following disclaimer.
12754 * 2. Redistributions in binary form must reproduce the above copyright
12755 * notice, this list of conditions and the following disclaimer in the
12756 * documentation and/or other materials provided with the distribution.
12758 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12759 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12761 * 4. Neither the name of the University nor the names of its contributors
12762 * may be used to endorse or promote products derived from this software
12763 * without specific prior written permission.
12765 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12766 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12767 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12768 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12769 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12770 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12771 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12772 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12773 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12774 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF