1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * This version of ash is adapted from the source in Debian's ash 0.3.8-5
28 * Modified by Erik Andersen <andersee@debian.org> and
29 * Vladimir Oleynik <dzo@simtreas.ru> to be used in busybox
32 * Original copyright notice is retained at the end of this file.
36 /* These defines allow you to adjust the feature set to be compiled
37 * into the ash shell. As a rule, enabling these options will make
38 * ash get bigger... With all of these options off, ash adds about
39 * 60k to busybox on an x86 system.*/
42 /* Enable job control. This allows you to run jobs in the background,
43 * which is great when ash is being used as an interactive shell, but
44 * it completely useless for is all you are doing is running scripts.
45 * This adds about 2.5k on an x86 system. */
48 /* This enables alias support in ash. If you want to support things
49 * like "alias ls='ls -l'" with ash, enable this. This is only useful
50 * when ash is used as an intractive shell. This adds about 1.5k */
53 /* If you need ash to act as a full Posix shell, with full math
54 * support, enable this. This adds a bit over 2k an x86 system. */
55 //#undef ASH_MATH_SUPPORT
56 #define ASH_MATH_SUPPORT
58 /* Getopts is used by shell procedures to parse positional parameters.
59 * You probably want to leave this disabled, and use the busybox getopt
60 * applet if you want to do this sort of thing. There are some scripts
61 * out there that use it, so it you need it, enable. Most people will
62 * leave this disabled. This adds 1k on an x86 system. */
65 /* This allows you to override shell builtins and use whatever is on
66 * the filesystem. This is most useful when ash is acting as a
67 * standalone shell. Adds about 272 bytes. */
71 /* Optimize size vs speed as size */
72 #define ASH_OPTIMIZE_FOR_SIZE
74 /* Enable this to compile in extra debugging noise. When debugging is
75 * on, debugging info will be written to $HOME/trace and a quit signal
76 * will generate a core dump. */
79 /* These are here to work with glibc -- Don't change these... */
100 #include <sys/stat.h>
101 #include <sys/cdefs.h>
102 #include <sys/ioctl.h>
103 #include <sys/param.h>
104 #include <sys/resource.h>
105 #include <sys/time.h>
106 #include <sys/times.h>
107 #include <sys/types.h>
108 #include <sys/wait.h>
111 #if !defined(FNMATCH_BROKEN)
114 #if !defined(GLOB_BROKEN)
126 * This file was generated by the mksyntax program.
130 #define CWORD 0 /* character is nothing special */
131 #define CNL 1 /* newline character */
132 #define CBACK 2 /* a backslash character */
133 #define CSQUOTE 3 /* single quote */
134 #define CDQUOTE 4 /* double quote */
135 #define CENDQUOTE 5 /* a terminating quote */
136 #define CBQUOTE 6 /* backwards single quote */
137 #define CVAR 7 /* a dollar sign */
138 #define CENDVAR 8 /* a '}' character */
139 #define CLP 9 /* a left paren in arithmetic */
140 #define CRP 10 /* a right paren in arithmetic */
141 #define CENDFILE 11 /* end of file */
142 #define CCTL 12 /* like CWORD, except it must be escaped */
143 #define CSPCL 13 /* these terminate a word */
144 #define CIGN 14 /* character should be ignored */
164 #define TENDBQUOTE 13
184 /* control characters in argument strings */
185 #define CTLESC '\201'
186 #define CTLVAR '\202'
187 #define CTLENDVAR '\203'
188 #define CTLBACKQ '\204'
189 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
190 /* CTLBACKQ | CTLQUOTE == '\205' */
191 #define CTLARI '\206'
192 #define CTLENDARI '\207'
193 #define CTLQUOTEMARK '\210'
196 #define is_digit(c) ((c)>='0' && (c)<='9')
197 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
198 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
201 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
202 * (assuming ascii char codes, as the original implementation did)
204 #define is_special(c) \
205 ( (((unsigned int)c) - 33 < 32) \
206 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
208 #define digit_val(c) ((c) - '0')
211 #define _DIAGASSERT(x)
215 #define S_DFL 1 /* default signal handling (SIG_DFL) */
216 #define S_CATCH 2 /* signal is caught */
217 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
218 #define S_HARD_IGN 4 /* signal is ignored permenantly */
219 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
222 /* variable substitution byte (follows CTLVAR) */
223 #define VSTYPE 0x0f /* type of variable substitution */
224 #define VSNUL 0x10 /* colon--treat the empty string as unset */
225 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
227 /* values of VSTYPE field */
228 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
229 #define VSMINUS 0x2 /* ${var-text} */
230 #define VSPLUS 0x3 /* ${var+text} */
231 #define VSQUESTION 0x4 /* ${var?message} */
232 #define VSASSIGN 0x5 /* ${var=text} */
233 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
234 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
235 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
236 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
237 #define VSLENGTH 0xa /* ${#var} */
239 /* flags passed to redirect */
240 #define REDIR_PUSH 01 /* save previous values of file descriptors */
241 #define REDIR_BACKQ 02 /* save the command output to pipe */
244 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
245 * so we use _setjmp instead.
249 #define setjmp(jmploc) _setjmp(jmploc)
250 #define longjmp(jmploc, val) _longjmp(jmploc, val)
254 * Most machines require the value returned from malloc to be aligned
255 * in some way. The following macro will get this right on many machines.
264 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
267 #ifdef BB_LOCALE_SUPPORT
269 static void change_lc_all(const char *value);
270 static void change_lc_ctype(const char *value);
274 * These macros allow the user to suspend the handling of interrupt signals
275 * over a period of time. This is similar to SIGHOLD to or sigblock, but
276 * much more efficient and portable. (But hacking the kernel is so much
277 * more fun than worrying about efficiency and portability. :-))
280 static void onint (void);
281 static volatile int suppressint;
282 static volatile int intpending;
284 #define INTOFF suppressint++
285 #ifndef ASH_OPTIMIZE_FOR_SIZE
286 #define INTON { if (--suppressint == 0 && intpending) onint(); }
287 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
289 static void __inton (void);
290 static void forceinton (void);
291 #define INTON __inton()
292 #define FORCEINTON forceinton()
295 #define CLEAR_PENDING_INT intpending = 0
296 #define int_pending() intpending
299 typedef void *pointer;
301 #define NULL (void *)0
304 static inline pointer ckmalloc (int sz) { return xmalloc(sz); }
305 static inline pointer ckrealloc(void *p, int sz) { return xrealloc(p, sz); }
306 static inline char * savestr (const char *s) { return xstrdup(s); }
308 static pointer stalloc (int);
309 static void stunalloc (pointer);
310 static void ungrabstackstr (char *, char *);
311 static char * growstackstr(void);
312 static char * makestrspace(size_t newlen);
313 static char *sstrdup (const char *);
316 * Parse trees for commands are allocated in lifo order, so we use a stack
317 * to make this more efficient, and also to avoid all sorts of exception
318 * handling code to handle interrupts in the middle of a parse.
320 * The size 504 was chosen because the Ultrix malloc handles that size
324 #define MINSIZE 504 /* minimum size of a block */
328 struct stack_block *prev;
332 static struct stack_block stackbase;
333 static struct stack_block *stackp = &stackbase;
334 static struct stackmark *markp;
335 static char *stacknxt = stackbase.space;
336 static int stacknleft = MINSIZE;
339 #define equal(s1, s2) (strcmp(s1, s2) == 0)
341 #define stackblock() stacknxt
342 #define stackblocksize() stacknleft
343 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
345 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
346 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
347 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
350 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
351 #define STUNPUTC(p) (++sstrnleft, --p)
352 #define STTOPC(p) p[-1]
353 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
354 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
356 #define ckfree(p) free((pointer)(p))
360 #define TRACE(param) trace param
361 static void trace (const char *, ...);
362 static void trargs (char **);
363 static void showtree (union node *);
364 static void trputc (int);
365 static void trputs (const char *);
366 static void opentrace (void);
401 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
402 #define EXP_TILDE 0x2 /* do normal tilde expansion */
403 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
404 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
405 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
406 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
411 static char optet_vals[NOPTS];
413 static const char * const optlist[NOPTS] = {
432 #define optent_name(optent) (optent+1)
433 #define optent_letter(optent) optent[0]
434 #define optent_val(optent) optet_vals[optent]
436 #define eflag optent_val(0)
437 #define fflag optent_val(1)
438 #define Iflag optent_val(2)
439 #define iflag optent_val(3)
440 #define mflag optent_val(4)
441 #define nflag optent_val(5)
442 #define sflag optent_val(6)
443 #define xflag optent_val(7)
444 #define vflag optent_val(8)
445 #define Vflag optent_val(9)
446 #define Eflag optent_val(10)
447 #define Cflag optent_val(11)
448 #define aflag optent_val(12)
449 #define bflag optent_val(13)
450 #define uflag optent_val(14)
451 #define qflag optent_val(15)
454 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
472 union node *redirect;
479 struct nodelist *cmdlist;
486 union node *redirect;
494 union node *elsepart;
525 struct nodelist *backquote;
563 struct nbinary nbinary;
566 struct nredir nredir;
570 struct nclist nclist;
580 struct nodelist *next;
584 struct backcmd { /* result of evalbackcmd */
585 int fd; /* file descriptor to read from */
586 char *buf; /* buffer */
587 int nleft; /* number of chars in buffer */
588 struct job *jp; /* job structure for command */
596 const struct builtincmd *cmd;
601 struct strlist *next;
607 struct strlist *list;
608 struct strlist **lastp;
612 struct strpush *prev; /* preceding string on stack */
616 struct alias *ap; /* if push was associated with an alias */
618 char *string; /* remember the string since it may change */
622 struct parsefile *prev; /* preceding file on stack */
623 int linno; /* current line */
624 int fd; /* file descriptor (or -1 if string) */
625 int nleft; /* number of chars left in this line */
626 int lleft; /* number of chars left in this buffer */
627 char *nextc; /* next char in buffer */
628 char *buf; /* input buffer */
629 struct strpush *strpush; /* for pushing strings at this level */
630 struct strpush basestrpush; /* so pushing one is fast */
634 struct stack_block *stackp;
637 struct stackmark *marknext;
641 int nparam; /* # of positional parameters (without $0) */
642 unsigned char malloc; /* if parameter list dynamically allocated */
643 char **p; /* parameter list */
644 int optind; /* next parameter to be processed by getopts */
645 int optoff; /* used by getopts */
649 * When commands are first encountered, they are entered in a hash table.
650 * This ensures that a full path search will not have to be done for them
651 * on each invocation.
653 * We should investigate converting to a linear search, even though that
654 * would make the command name "hash" a misnomer.
656 #define CMDTABLESIZE 31 /* should be prime */
657 #define ARB 1 /* actual size determined at run time */
662 struct tblentry *next; /* next entry in hash chain */
663 union param param; /* definition of builtin function */
664 short cmdtype; /* index identifying command */
665 char rehash; /* if set, cd done since entry created */
666 char cmdname[ARB]; /* name of command */
670 static struct tblentry *cmdtable[CMDTABLESIZE];
671 static int builtinloc = -1; /* index in path of %builtin, or -1 */
672 static int exerrno = 0; /* Last exec error */
675 static void tryexec (char *, char **, char **);
676 static void printentry (struct tblentry *, int);
677 static void clearcmdentry (int);
678 static struct tblentry *cmdlookup (const char *, int);
679 static void delete_cmd_entry (void);
680 static int path_change (const char *, int *);
683 static void flushall (void);
684 static void out2fmt (const char *, ...)
685 __attribute__((__format__(__printf__,1,2)));
686 static int xwrite (int, const char *, int);
688 #define outstr(p,file) fputs(p, file)
689 static 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)]);
7451 } else if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7452 cmdputs(((const char *) n) + ((int)(*p & CMDTXT_OFFSETMASK)));
7453 } else { /* output field */
7454 cmdtxt((const union node *)
7455 (((const char *) n) + ((int)(*p & CMDTXT_OFFSETMASK))));
7457 } while (!(*p++ & CMDTXT_NOMORE));
7458 } else if (n->type == NCMD) {
7460 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7465 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7469 } else if (n->type == NPIPE) {
7470 struct nodelist *lp;
7471 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7476 } else if (n->type == NCASE) {
7477 cmdputs(cmdtxt_strings[14]);
7478 cmdputs(n->ncase.expr->narg.text);
7479 cmdputs(cmdtxt_strings[13]);
7481 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7482 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7487 assert((n->type >= NTO) && (n->type <= NFROMFD));
7490 p = redir_strings[n->type - NTO];
7491 if (n->nfile.fd != ('>' == *p)) {
7492 s[0] = n->nfile.fd + '0';
7497 if (n->type >= NTOFD) {
7498 s[0] = n->ndup.dupfd + '0';
7502 cmdtxt(n->nfile.fname);
7506 #else /* CMDTXT_TABLE */
7508 cmdtxt(const union node *n)
7511 struct nodelist *lp;
7520 cmdtxt(n->nbinary.ch1);
7522 cmdtxt(n->nbinary.ch2);
7525 cmdtxt(n->nbinary.ch1);
7527 cmdtxt(n->nbinary.ch2);
7530 cmdtxt(n->nbinary.ch1);
7532 cmdtxt(n->nbinary.ch2);
7535 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7543 cmdtxt(n->nredir.n);
7548 cmdtxt(n->nredir.n);
7552 cmdtxt(n->nif.test);
7554 cmdtxt(n->nif.ifpart);
7563 cmdtxt(n->nbinary.ch1);
7565 cmdtxt(n->nbinary.ch2);
7570 cmdputs(n->nfor.var);
7575 cmdputs(n->ncase.expr->narg.text);
7579 cmdputs(n->narg.text);
7583 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7588 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7594 cmdputs(n->narg.text);
7597 p = ">"; i = 1; goto redir;
7599 p = ">>"; i = 1; goto redir;
7601 p = ">&"; i = 1; goto redir;
7603 p = ">|"; i = 1; goto redir;
7605 p = "<"; i = 0; goto redir;
7607 p = "<&"; i = 0; goto redir;
7609 p = "<>"; i = 0; goto redir;
7611 if (n->nfile.fd != i) {
7612 s[0] = n->nfile.fd + '0';
7617 if (n->type == NTOFD || n->type == NFROMFD) {
7618 s[0] = n->ndup.dupfd + '0';
7622 cmdtxt(n->nfile.fname);
7637 commandtext(const union node *n)
7641 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7642 cmdnleft = MAXCMDTEXT - 4;
7649 static void waitonint(int sig) {
7654 * Routines to check for mail. (Perhaps make part of main.c?)
7658 #define MAXMBOXES 10
7661 static int nmboxes; /* number of mailboxes */
7662 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7667 * Print appropriate message(s) if mail has arrived. If the argument is
7668 * nozero, then the value of MAIL has changed, so we just update the
7679 struct stackmark smark;
7686 setstackmark(&smark);
7687 mpath = mpathset()? mpathval() : mailval();
7688 for (i = 0 ; i < nmboxes ; i++) {
7689 p = padvance(&mpath, nullstr);
7694 for (q = p ; *q ; q++);
7699 q[-1] = '\0'; /* delete trailing '/' */
7700 if (stat(p, &statb) < 0)
7702 if (statb.st_size > mailtime[i] && ! silent) {
7704 pathopt? pathopt : "you have mail");
7706 mailtime[i] = statb.st_size;
7709 popstackmark(&smark);
7715 static short profile_buf[16384];
7719 static void read_profile (const char *);
7720 static void cmdloop (int);
7721 static void options (int);
7722 static void setoption (int, int);
7723 static void procargs (int, char **);
7727 * Main routine. We initialize things, parse the arguments, execute
7728 * profiles if we're a login shell, and then call cmdloop to execute
7729 * commands. The setjmp call sets up the location to jump to when an
7730 * exception occurs. When an exception occurs the variable "state"
7731 * is used to figure out how far we had gotten.
7735 ash_main(argc, argv)
7739 struct jmploc jmploc;
7740 struct stackmark smark;
7744 BLTINCMD = find_builtin("builtin");
7745 EXECCMD = find_builtin("exec");
7746 EVALCMD = find_builtin("eval");
7748 #ifndef BB_FEATURE_SH_FANCY_PROMPT
7754 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7756 #if defined(linux) || defined(__GNU__)
7757 signal(SIGCHLD, SIG_DFL);
7760 if (setjmp(jmploc.loc)) {
7763 * When a shell procedure is executed, we raise the
7764 * exception EXSHELLPROC to clean up before executing
7765 * the shell procedure.
7767 if (exception == EXSHELLPROC) {
7773 if (exception == EXEXEC) {
7774 exitstatus = exerrno;
7775 } else if (exception == EXERROR) {
7778 if (state == 0 || iflag == 0 || ! rootshell)
7779 exitshell(exitstatus);
7782 if (exception == EXINT) {
7785 popstackmark(&smark);
7786 FORCEINTON; /* enable interrupts */
7789 else if (state == 2)
7791 else if (state == 3)
7799 trputs("Shell args: "); trargs(argv);
7804 setstackmark(&smark);
7805 procargs(argc, argv);
7806 if (argv[0] && argv[0][0] == '-') {
7808 read_profile("/etc/profile");
7811 read_profile(".profile");
7816 if (getuid() == geteuid() && getgid() == getegid()) {
7818 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7820 read_profile(shinit);
7827 if (sflag == 0 || minusc) {
7828 static const char sigs[] = {
7829 SIGINT, SIGQUIT, SIGHUP,
7835 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7838 for (i = 0; i < SIGSSIZE; i++)
7843 evalstring(minusc, 0);
7845 if (sflag || minusc == NULL) {
7846 state4: /* XXX ??? - why isn't this before the "if" statement */
7852 exitshell(exitstatus);
7858 * Read and execute commands. "Top" is nonzero for the top level command
7859 * loop; it turns on prompting if the shell is interactive.
7866 struct stackmark smark;
7870 TRACE(("cmdloop(%d) called\n", top));
7871 setstackmark(&smark);
7882 n = parsecmd(inter);
7883 /* showtree(n); DEBUG */
7885 if (!top || numeof >= 50)
7887 if (!stoppedjobs()) {
7890 out2str("\nUse \"exit\" to leave shell.\n");
7893 } else if (n != NULL && nflag == 0) {
7894 job_warning = (job_warning == 2) ? 1 : 0;
7898 popstackmark(&smark);
7899 setstackmark(&smark);
7900 if (evalskip == SKIPFILE) {
7905 popstackmark(&smark);
7911 * Read /etc/profile or .profile. Return on error.
7923 if ((fd = open(name, O_RDONLY)) >= 0)
7928 /* -q turns off -x and -v just when executing init files */
7929 /* Note: Might do a little redundant work, but reduces code size. */
7944 * Read a file containing shell functions.
7948 readcmdfile(const char *name)
7953 if ((fd = open(name, O_RDONLY)) >= 0)
7956 error("Can't open %s", name);
7965 * Take commands from a file. To be compatable we should do a path
7966 * search for the file, which is necessary to find sub-commands.
7970 static inline char *
7971 find_dot_file(mybasename)
7975 const char *path = pathval();
7978 /* don't try this for absolute or relative paths */
7979 if (strchr(mybasename, '/'))
7982 while ((fullname = padvance(&path, mybasename)) != NULL) {
7983 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7985 * Don't bother freeing here, since it will
7986 * be freed by the caller.
7990 stunalloc(fullname);
7993 /* not found in the PATH */
7994 error("%s: not found", mybasename);
8006 for (sp = cmdenviron; sp ; sp = sp->next)
8007 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
8009 if (argc >= 2) { /* That's what SVR2 does */
8011 struct stackmark smark;
8013 setstackmark(&smark);
8014 fullname = find_dot_file(argv[1]);
8015 setinputfile(fullname, 1);
8016 commandname = fullname;
8019 popstackmark(&smark);
8033 exitstatus = number(argv[1]);
8035 exitstatus = oexitstatus;
8036 exitshell(exitstatus);
8045 nbytes = ALIGN(nbytes);
8046 if (nbytes > stacknleft) {
8048 struct stack_block *sp;
8051 if (blocksize < MINSIZE)
8052 blocksize = MINSIZE;
8054 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
8056 stacknxt = sp->space;
8057 stacknleft = blocksize;
8063 stacknleft -= nbytes;
8069 stunalloc(pointer p)
8072 if (p == NULL) { /*DEBUG */
8073 write(2, "stunalloc\n", 10);
8077 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
8080 stacknleft += stacknxt - (char *)p;
8086 setstackmark(struct stackmark *mark)
8088 mark->stackp = stackp;
8089 mark->stacknxt = stacknxt;
8090 mark->stacknleft = stacknleft;
8091 mark->marknext = markp;
8097 popstackmark(struct stackmark *mark)
8099 struct stack_block *sp;
8102 markp = mark->marknext;
8103 while (stackp != mark->stackp) {
8108 stacknxt = mark->stacknxt;
8109 stacknleft = mark->stacknleft;
8115 * When the parser reads in a string, it wants to stick the string on the
8116 * stack and only adjust the stack pointer when it knows how big the
8117 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8118 * of space on top of the stack and stackblocklen returns the length of
8119 * this block. Growstackblock will grow this space by at least one byte,
8120 * possibly moving it (like realloc). Grabstackblock actually allocates the
8121 * part of the block that has been used.
8125 growstackblock(void) {
8127 int newlen = ALIGN(stacknleft * 2 + 100);
8128 char *oldspace = stacknxt;
8129 int oldlen = stacknleft;
8130 struct stack_block *sp;
8131 struct stack_block *oldstackp;
8133 if (stacknxt == stackp->space && stackp != &stackbase) {
8138 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8141 stacknxt = sp->space;
8142 stacknleft = newlen;
8144 /* Stack marks pointing to the start of the old block
8145 * must be relocated to point to the new block
8147 struct stackmark *xmark;
8149 while (xmark != NULL && xmark->stackp == oldstackp) {
8150 xmark->stackp = stackp;
8151 xmark->stacknxt = stacknxt;
8152 xmark->stacknleft = stacknleft;
8153 xmark = xmark->marknext;
8158 p = stalloc(newlen);
8159 memcpy(p, oldspace, oldlen);
8160 stacknxt = p; /* free the space */
8161 stacknleft += newlen; /* we just allocated */
8168 grabstackblock(int len)
8178 * The following routines are somewhat easier to use that the above.
8179 * The user declares a variable of type STACKSTR, which may be declared
8180 * to be a register. The macro STARTSTACKSTR initializes things. Then
8181 * the user uses the macro STPUTC to add characters to the string. In
8182 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8183 * grown as necessary. When the user is done, she can just leave the
8184 * string there and refer to it using stackblock(). Or she can allocate
8185 * the space for it using grabstackstr(). If it is necessary to allow
8186 * someone else to use the stack temporarily and then continue to grow
8187 * the string, the user should use grabstack to allocate the space, and
8188 * then call ungrabstr(p) to return to the previous mode of operation.
8190 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8191 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8192 * is space for at least one character.
8197 growstackstr(void) {
8198 int len = stackblocksize();
8199 if (herefd >= 0 && len >= 1024) {
8200 xwrite(herefd, stackblock(), len);
8201 sstrnleft = len - 1;
8202 return stackblock();
8205 sstrnleft = stackblocksize() - len - 1;
8206 return stackblock() + len;
8211 * Called from CHECKSTRSPACE.
8215 makestrspace(size_t newlen) {
8216 int len = stackblocksize() - sstrnleft;
8219 sstrnleft = stackblocksize() - len;
8220 } while (sstrnleft < newlen);
8221 return stackblock() + len;
8227 ungrabstackstr(char *s, char *p)
8229 stacknleft += stacknxt - s;
8231 sstrnleft = stacknleft - (p - s);
8234 * Miscelaneous builtins.
8240 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8241 typedef long rlim_t;
8247 * The read builtin. The -e option causes backslashes to escape the
8248 * following character.
8250 * This uses unbuffered input, which may be avoidable in some cases.
8254 readcmd(int argc, char **argv)
8269 while ((i = nextopt("p:r")) != '\0') {
8275 if (prompt && isatty(0)) {
8276 out2str(prompt); /* read without cmdedit */
8279 if (*(ap = argptr) == NULL)
8281 if ((ifs = bltinlookup("IFS")) == NULL)
8288 if (read(0, &c, 1) != 1) {
8300 if (!rflag && c == '\\') {
8306 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8310 if (backslash && c == '\\') {
8311 if (read(0, &c, 1) != 1) {
8316 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8318 setvar(*ap, stackblock(), 0);
8327 /* Remove trailing blanks */
8328 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8330 setvar(*ap, stackblock(), 0);
8331 while (*++ap != NULL)
8332 setvar(*ap, nullstr, 0);
8339 umaskcmd(argc, argv)
8343 static const char permuser[3] = "ugo";
8344 static const char permmode[3] = "rwx";
8345 static const short int permmask[] = {
8346 S_IRUSR, S_IWUSR, S_IXUSR,
8347 S_IRGRP, S_IWGRP, S_IXGRP,
8348 S_IROTH, S_IWOTH, S_IXOTH
8354 int symbolic_mode = 0;
8356 while (nextopt("S") != '\0') {
8365 if ((ap = *argptr) == NULL) {
8366 if (symbolic_mode) {
8369 for (i=0 ; i<3 ; i++) {
8373 for (j=0 ; j<3 ; j++) {
8374 if ((mask & permmask[3*i+j]) == 0) {
8383 printf("%.4o\n", mask);
8386 if (is_digit((unsigned char)*ap)) {
8389 if (*ap >= '8' || *ap < '0')
8390 error("Illegal number: %s", argv[1]);
8391 mask = (mask << 3) + (*ap - '0');
8392 } while (*++ap != '\0');
8395 mask = ~mask & 0777;
8396 if (parse_mode(ap, &mask) == FALSE) {
8397 error("Illegal mode: %s", ap);
8399 umask(~mask & 0777);
8408 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8409 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8410 * ash by J.T. Conklin.
8418 short factor; /* multiply by to get rlim_{cur,max} values */
8421 static const struct limits limits[] = {
8423 { "time(seconds)", RLIMIT_CPU, 1 },
8426 { "file(blocks)", RLIMIT_FSIZE, 512 },
8429 { "data(kbytes)", RLIMIT_DATA, 1024 },
8432 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8435 { "coredump(blocks)", RLIMIT_CORE, 512 },
8438 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8440 #ifdef RLIMIT_MEMLOCK
8441 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8444 { "process(processes)", RLIMIT_NPROC, 1 },
8446 #ifdef RLIMIT_NOFILE
8447 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8450 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8453 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8459 ulimitcmd(argc, argv)
8463 static const char unlimited_string[] = "unlimited";
8466 enum { SOFT = 0x1, HARD = 0x2 }
8468 const struct limits *l;
8471 struct rlimit limit;
8475 while ((optc = nextopt("HSa"
8494 #ifdef RLIMIT_MEMLOCK
8500 #ifdef RLIMIT_NOFILE
8512 } else if (optc == 'S') {
8514 } else if (optc == 'a') {
8521 for (l = limits; l->name; l++) {
8522 if(l->name[0] == what)
8524 if(l->name[1]=='w' && what=='w')
8528 set = *argptr ? 1 : 0;
8532 if (all || argptr[1])
8533 error("too many arguments");
8534 if (strcmp(p, unlimited_string) == 0)
8535 val = RLIM_INFINITY;
8539 while ((c = *p++) >= '0' && c <= '9')
8541 val = (val * 10) + (long)(c - '0');
8542 if (val < (rlim_t) 0)
8546 error("bad number");
8552 for (l = limits; l->name; l++) {
8553 printf("%-20s ", l->name);
8554 getrlimit(l->cmd, &limit);
8557 val = limit.rlim_cur;
8558 else if (how & HARD)
8559 val = limit.rlim_max;
8561 if (val == RLIM_INFINITY)
8562 puts(unlimited_string);
8566 printf("%lld\n", (long long) val);
8579 getrlimit(l->cmd, &limit);
8581 limit.rlim_max = val;
8583 limit.rlim_cur = val;
8584 if (setrlimit(l->cmd, &limit) < 0)
8585 error("error setting limit (%m)");
8589 * prefix -- see if pfx is a prefix of string.
8593 prefix(char const *pfx, char const *string)
8596 if (*pfx++ != *string++)
8603 * Return true if s is a string of digits, and save munber in intptr
8608 is_number(const char *p, int *intptr)
8616 ret += digit_val(*p);
8618 } while (*p != '\0');
8625 * Convert a string of digits to an integer, printing an error message on
8630 number(const char *s)
8633 if (! is_number(s, &i))
8634 error("Illegal number: %s", s);
8639 * Produce a possibly single quoted string suitable as input to the shell.
8640 * The return string is allocated on the stack.
8644 single_quote(const char *s) {
8651 size_t len1, len1p, len2, len2p;
8653 len1 = strcspn(s, "'");
8654 len2 = strspn(s + len1, "'");
8656 len1p = len1 ? len1 + 2 : len1;
8657 len2p = len2 + ((len2 < 2) ? len2 : 2);
8659 CHECKSTRSPACE(len1p + len2p + 1, p);
8664 memcpy(p + 1, s, len1);
8672 memcpy(q + 1, s, len2);
8675 } else if (len2 == 1) {
8681 STADJUST(len1p + len2p, p);
8686 return grabstackstr(p);
8690 * Like strdup but works with the ash stack.
8694 sstrdup(const char *p)
8696 size_t len = strlen(p) + 1;
8697 return memcpy(stalloc(len), p, len);
8702 * Routine for dealing with parsed shell commands.
8706 static void sizenodelist (const struct nodelist *);
8707 static struct nodelist *copynodelist (const struct nodelist *);
8708 static char *nodesavestr (const char *);
8710 //#define CALCSIZE_TABLE
8711 //#define COPYNODE_TABLE
8712 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8714 * To collect a lot of redundant code in case statements for copynode()
8715 * and calcsize(), we implement a mini language here. Each type of node
8716 * struct has an associated instruction sequence that operates on its
8717 * members via their offsets. The instruction are pack in unsigned chars
8718 * with format IIDDDDDE where the bits are
8719 * I : part of the instruction opcode, which are
8720 * 00 : member is a pointer to another node
8721 * 40 : member is an integer
8722 * 80 : member is a pointer to a nodelist
8723 * CC : member is a pointer to a char string
8724 * D : data - the actual offset of the member to operate on in the struct
8725 * (since we assume bit 0 is set, it is not shifted)
8726 * E : flag signaling end of instruction sequence
8728 * WARNING: In order to handle larger offsets for 64bit archs, this code
8729 * assumes that no offset can be an odd number and stores the
8730 * end-of-instructions flag in bit 0.
8733 #define NODE_INTEGER 0x40
8734 #define NODE_NODELIST 0x80
8735 #define NODE_CHARPTR 0xC0
8736 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8737 #define NODE_MBRMASK 0xC0
8738 #define NODE_OFFSETMASK 0x3E
8740 static const unsigned char copynode_ops[35] = {
8741 #define COPYNODE_OPS0 0
8742 offsetof(union node, nbinary.ch2),
8743 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8744 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8745 offsetof(union node, ncmd.redirect),
8746 offsetof(union node, ncmd.args),
8747 offsetof(union node, ncmd.assign),
8748 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8749 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8750 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8751 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8752 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8753 offsetof(union node, nredir.redirect),
8754 offsetof(union node, nredir.n)|NODE_NOMORE,
8755 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8756 offsetof(union node, nif.elsepart),
8757 offsetof(union node, nif.ifpart),
8758 offsetof(union node, nif.test)|NODE_NOMORE,
8759 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8760 offsetof(union node, nfor.var)|NODE_CHARPTR,
8761 offsetof(union node, nfor.body),
8762 offsetof(union node, nfor.args)|NODE_NOMORE,
8763 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8764 offsetof(union node, ncase.cases),
8765 offsetof(union node, ncase.expr)|NODE_NOMORE,
8766 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8767 offsetof(union node, nclist.body),
8768 offsetof(union node, nclist.pattern),
8769 offsetof(union node, nclist.next)|NODE_NOMORE,
8770 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8771 offsetof(union node, narg.backquote)|NODE_NODELIST,
8772 offsetof(union node, narg.text)|NODE_CHARPTR,
8773 offsetof(union node, narg.next)|NODE_NOMORE,
8774 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8775 offsetof(union node, nfile.fname),
8776 offsetof(union node, nfile.fd)|NODE_INTEGER,
8777 offsetof(union node, nfile.next)|NODE_NOMORE,
8778 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8779 offsetof(union node, ndup.vname),
8780 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8781 offsetof(union node, ndup.fd)|NODE_INTEGER,
8782 offsetof(union node, ndup.next)|NODE_NOMORE,
8783 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8784 offsetof(union node, nhere.doc),
8785 offsetof(union node, nhere.fd)|NODE_INTEGER,
8786 offsetof(union node, nhere.next)|NODE_NOMORE,
8787 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8788 offsetof(union node, nnot.com)|NODE_NOMORE,
8791 #if COPYNODE_OPS12 != 34
8792 #error COPYNODE_OPS12 is incorrect
8795 static const unsigned char copynode_ops_index[26] = {
8796 COPYNODE_OPS0, /* NSEMI */
8797 COPYNODE_OPS1, /* NCMD */
8798 COPYNODE_OPS2, /* NPIPE */
8799 COPYNODE_OPS3, /* NREDIR */
8800 COPYNODE_OPS3, /* NBACKGND */
8801 COPYNODE_OPS3, /* NSUBSHELL */
8802 COPYNODE_OPS0, /* NAND */
8803 COPYNODE_OPS0, /* NOR */
8804 COPYNODE_OPS4, /* NIF */
8805 COPYNODE_OPS0, /* NWHILE */
8806 COPYNODE_OPS0, /* NUNTIL */
8807 COPYNODE_OPS5, /* NFOR */
8808 COPYNODE_OPS6, /* NCASE */
8809 COPYNODE_OPS7, /* NCLIST */
8810 COPYNODE_OPS8, /* NDEFUN */
8811 COPYNODE_OPS8, /* NARG */
8812 COPYNODE_OPS9, /* NTO */
8813 COPYNODE_OPS9, /* NFROM */
8814 COPYNODE_OPS9, /* NFROMTO */
8815 COPYNODE_OPS9, /* NAPPEND */
8816 COPYNODE_OPS9, /* NTOOV */
8817 COPYNODE_OPS10, /* NTOFD */
8818 COPYNODE_OPS10, /* NFROMFD */
8819 COPYNODE_OPS11, /* NHERE */
8820 COPYNODE_OPS11, /* NXHERE */
8821 COPYNODE_OPS12, /* NNOT */
8824 #if NODE_CHARPTR != NODE_MBRMASK
8825 #error NODE_CHARPTR != NODE_MBRMASK!!!
8827 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8829 #ifdef COPYNODE_TABLE
8831 copynode(const union node *n)
8834 const unsigned char *p;
8839 new->type = n->type;
8840 funcblock = (char *) funcblock + (int) nodesize[n->type];
8841 p = copynode_ops + (int) copynode_ops_index[n->type];
8843 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8844 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8846 if (!(*p & NODE_MBRMASK)) { /* standard node */
8847 (union node *) nn = copynode((const union node *) no);
8848 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8849 nn = nodesavestr(no);
8850 } else if (*p & NODE_NODELIST) { /* nodelist */
8851 (struct nodelist *) nn
8852 = copynodelist((const struct nodelist *) no);
8853 } else { /* integer */
8854 *((int *) nn) = *((int *) no);
8856 } while (!(*p++ & NODE_NOMORE));
8859 #else /* COPYNODE_TABLE */
8861 copynode(const union node *n)
8868 funcblock = (char *) funcblock + nodesize[n->type];
8875 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8876 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8879 new->ncmd.redirect = copynode(n->ncmd.redirect);
8880 new->ncmd.args = copynode(n->ncmd.args);
8881 new->ncmd.assign = copynode(n->ncmd.assign);
8882 new->ncmd.backgnd = n->ncmd.backgnd;
8885 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8886 new->npipe.backgnd = n->npipe.backgnd;
8891 new->nredir.redirect = copynode(n->nredir.redirect);
8892 new->nredir.n = copynode(n->nredir.n);
8895 new->nif.elsepart = copynode(n->nif.elsepart);
8896 new->nif.ifpart = copynode(n->nif.ifpart);
8897 new->nif.test = copynode(n->nif.test);
8900 new->nfor.var = nodesavestr(n->nfor.var);
8901 new->nfor.body = copynode(n->nfor.body);
8902 new->nfor.args = copynode(n->nfor.args);
8905 new->ncase.cases = copynode(n->ncase.cases);
8906 new->ncase.expr = copynode(n->ncase.expr);
8909 new->nclist.body = copynode(n->nclist.body);
8910 new->nclist.pattern = copynode(n->nclist.pattern);
8911 new->nclist.next = copynode(n->nclist.next);
8915 new->narg.backquote = copynodelist(n->narg.backquote);
8916 new->narg.text = nodesavestr(n->narg.text);
8917 new->narg.next = copynode(n->narg.next);
8924 new->nfile.fname = copynode(n->nfile.fname);
8925 new->nfile.fd = n->nfile.fd;
8926 new->nfile.next = copynode(n->nfile.next);
8930 new->ndup.vname = copynode(n->ndup.vname);
8931 new->ndup.dupfd = n->ndup.dupfd;
8932 new->ndup.fd = n->ndup.fd;
8933 new->ndup.next = copynode(n->ndup.next);
8937 new->nhere.doc = copynode(n->nhere.doc);
8938 new->nhere.fd = n->nhere.fd;
8939 new->nhere.next = copynode(n->nhere.next);
8942 new->nnot.com = copynode(n->nnot.com);
8945 new->type = n->type;
8948 #endif /* COPYNODE_TABLE */
8950 #ifdef CALCSIZE_TABLE
8952 calcsize(const union node *n)
8954 const unsigned char *p;
8958 funcblocksize += (int) nodesize[n->type];
8960 p = copynode_ops + (int) copynode_ops_index[n->type];
8962 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8964 if (!(*p & NODE_MBRMASK)) { /* standard node */
8965 calcsize((const union node *) no);
8966 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8967 funcstringsize += strlen(no) + 1;
8968 } else if (*p & NODE_NODELIST) { /* nodelist */
8969 sizenodelist((const struct nodelist *) no);
8971 } while (!(*p++ & NODE_NOMORE));
8973 #else /* CALCSIZE_TABLE */
8975 calcsize(const union node *n)
8979 funcblocksize += nodesize[n->type];
8986 calcsize(n->nbinary.ch2);
8987 calcsize(n->nbinary.ch1);
8990 calcsize(n->ncmd.redirect);
8991 calcsize(n->ncmd.args);
8992 calcsize(n->ncmd.assign);
8995 sizenodelist(n->npipe.cmdlist);
9000 calcsize(n->nredir.redirect);
9001 calcsize(n->nredir.n);
9004 calcsize(n->nif.elsepart);
9005 calcsize(n->nif.ifpart);
9006 calcsize(n->nif.test);
9009 funcstringsize += strlen(n->nfor.var) + 1;
9010 calcsize(n->nfor.body);
9011 calcsize(n->nfor.args);
9014 calcsize(n->ncase.cases);
9015 calcsize(n->ncase.expr);
9018 calcsize(n->nclist.body);
9019 calcsize(n->nclist.pattern);
9020 calcsize(n->nclist.next);
9024 sizenodelist(n->narg.backquote);
9025 funcstringsize += strlen(n->narg.text) + 1;
9026 calcsize(n->narg.next);
9033 calcsize(n->nfile.fname);
9034 calcsize(n->nfile.next);
9038 calcsize(n->ndup.vname);
9039 calcsize(n->ndup.next);
9043 calcsize(n->nhere.doc);
9044 calcsize(n->nhere.next);
9047 calcsize(n->nnot.com);
9051 #endif /* CALCSIZE_TABLE */
9054 sizenodelist(const struct nodelist *lp)
9057 funcblocksize += ALIGN(sizeof(struct nodelist));
9064 static struct nodelist *
9065 copynodelist(const struct nodelist *lp)
9067 struct nodelist *start;
9068 struct nodelist **lpp;
9073 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
9074 (*lpp)->n = copynode(lp->n);
9076 lpp = &(*lpp)->next;
9084 nodesavestr(const char *s)
9087 char *q = funcstring;
9088 char *rtn = funcstring;
9090 while ((*q++ = *p++) != '\0')
9097 static int getopts (char *, char *, char **, int *, int *);
9102 * Process the shell command line arguments.
9106 procargs(argc, argv)
9115 for (i = 0; i < NOPTS; i++)
9118 if (*argptr == NULL && minusc == NULL)
9120 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
9124 for (i = 0; i < NOPTS; i++)
9125 if (optent_val(i) == 2)
9128 if (sflag == 0 && minusc == NULL) {
9129 commandname = argv[0];
9131 setinputfile(arg0, 0);
9134 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
9135 if (argptr && minusc && *argptr)
9138 shellparam.p = argptr;
9139 shellparam.optind = 1;
9140 shellparam.optoff = -1;
9141 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9143 shellparam.nparam++;
9152 * Process shell options. The global variable argptr contains a pointer
9153 * to the argument list; we advance it past the options.
9157 minus_o(const char *name, int val)
9162 out1str("Current option settings\n");
9163 for (i = 0; i < NOPTS; i++)
9164 printf("%-16s%s\n", optent_name(optlist[i]),
9165 optent_val(i) ? "on" : "off");
9167 for (i = 0; i < NOPTS; i++)
9168 if (equal(name, optent_name(optlist[i]))) {
9169 setoption(optent_letter(optlist[i]), val);
9172 error("Illegal option -o %s", name);
9178 options(int cmdline)
9186 while ((p = *argptr) != NULL) {
9188 if ((c = *p++) == '-') {
9190 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9192 /* "-" means turn off -x and -v */
9195 /* "--" means reset params */
9196 else if (*argptr == NULL)
9199 break; /* "-" or "--" terminates options */
9201 } else if (c == '+') {
9207 while ((c = *p++) != '\0') {
9208 if (c == 'c' && cmdline) {
9210 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9214 if (q == NULL || minusc != NULL)
9215 error("Bad -c option");
9220 } else if (c == 'o') {
9221 minus_o(*argptr, val);
9233 setoption(int flag, int val)
9237 for (i = 0; i < NOPTS; i++)
9238 if (optent_letter(optlist[i]) == flag) {
9239 optent_val(i) = val;
9241 /* #%$ hack for ksh semantics */
9244 else if (flag == 'E')
9249 error("Illegal option -%c", flag);
9256 * Set the shell parameters.
9260 setparam(char **argv)
9266 for (nparam = 0 ; argv[nparam] ; nparam++);
9267 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9269 *ap++ = savestr(*argv++);
9272 freeparam(&shellparam);
9273 shellparam.malloc = 1;
9274 shellparam.nparam = nparam;
9275 shellparam.p = newparam;
9276 shellparam.optind = 1;
9277 shellparam.optoff = -1;
9282 * Free the list of positional parameters.
9286 freeparam(volatile struct shparam *param)
9290 if (param->malloc) {
9291 for (ap = param->p ; *ap ; ap++)
9300 * The shift builtin command.
9304 shiftcmd(argc, argv)
9313 n = number(argv[1]);
9314 if (n > shellparam.nparam)
9315 error("can't shift that many");
9317 shellparam.nparam -= n;
9318 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9319 if (shellparam.malloc)
9323 while ((*ap2++ = *ap1++) != NULL);
9324 shellparam.optind = 1;
9325 shellparam.optoff = -1;
9333 * The set command builtin.
9342 return showvarscmd(argc, argv);
9346 if (*argptr != NULL) {
9355 getoptsreset(const char *value)
9357 shellparam.optind = number(value);
9358 shellparam.optoff = -1;
9361 #ifdef BB_LOCALE_SUPPORT
9362 static void change_lc_all(const char *value)
9364 if(value != 0 && *value != 0)
9365 setlocale(LC_ALL, value);
9368 static void change_lc_ctype(const char *value)
9370 if(value != 0 && *value != 0)
9371 setlocale(LC_CTYPE, value);
9378 * The getopts builtin. Shellparam.optnext points to the next argument
9379 * to be processed. Shellparam.optptr points to the next character to
9380 * be processed in the current argument. If shellparam.optnext is NULL,
9381 * then it's the first time getopts has been called.
9385 getoptscmd(argc, argv)
9392 error("Usage: getopts optstring var [arg]");
9393 else if (argc == 3) {
9394 optbase = shellparam.p;
9395 if (shellparam.optind > shellparam.nparam + 1) {
9396 shellparam.optind = 1;
9397 shellparam.optoff = -1;
9402 if (shellparam.optind > argc - 2) {
9403 shellparam.optind = 1;
9404 shellparam.optoff = -1;
9408 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9409 &shellparam.optoff);
9413 * Safe version of setvar, returns 1 on success 0 on failure.
9417 setvarsafe(name, val, flags)
9418 const char *name, *val;
9421 struct jmploc jmploc;
9422 struct jmploc *volatile savehandler = handler;
9428 if (setjmp(jmploc.loc))
9432 setvar(name, val, flags);
9434 handler = savehandler;
9439 getopts(optstr, optvar, optfirst, myoptind, optoff)
9451 char **optnext = optfirst + *myoptind - 1;
9453 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9454 strlen(*(optnext - 1)) < *optoff)
9457 p = *(optnext - 1) + *optoff;
9458 if (p == NULL || *p == '\0') {
9459 /* Current word is done, advance */
9460 if (optnext == NULL)
9463 if (p == NULL || *p != '-' || *++p == '\0') {
9465 *myoptind = optnext - optfirst + 1;
9471 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9476 for (q = optstr; *q != c; ) {
9478 if (optstr[0] == ':') {
9481 err |= setvarsafe("OPTARG", s, 0);
9484 out2fmt("Illegal option -%c\n", c);
9485 (void) unsetvar("OPTARG");
9495 if (*p == '\0' && (p = *optnext) == NULL) {
9496 if (optstr[0] == ':') {
9499 err |= setvarsafe("OPTARG", s, 0);
9503 out2fmt("No arg for -%c option\n", c);
9504 (void) unsetvar("OPTARG");
9512 setvarsafe("OPTARG", p, 0);
9516 setvarsafe("OPTARG", "", 0);
9517 *myoptind = optnext - optfirst + 1;
9524 *optoff = p ? p - *(optnext - 1) : -1;
9525 snprintf(s, sizeof(s), "%d", *myoptind);
9526 err |= setvarsafe("OPTIND", s, VNOFUNC);
9529 err |= setvarsafe(optvar, s, 0);
9540 * XXX - should get rid of. have all builtins use getopt(3). the
9541 * library getopt must have the BSD extension static variable "optreset"
9542 * otherwise it can't be used within the shell safely.
9544 * Standard option processing (a la getopt) for builtin routines. The
9545 * only argument that is passed to nextopt is the option string; the
9546 * other arguments are unnecessary. It return the character, or '\0' on
9551 nextopt(const char *optstring)
9557 if ((p = optptr) == NULL || *p == '\0') {
9559 if (p == NULL || *p != '-' || *++p == '\0')
9562 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9566 for (q = optstring ; *q != c ; ) {
9568 error("Illegal option -%c", c);
9573 if (*p == '\0' && (p = *argptr++) == NULL)
9574 error("No arg for -%c option", c);
9591 out2fmt(const char *fmt, ...)
9595 vfprintf(stderr, fmt, ap);
9600 * Version of write which resumes after a signal is caught.
9604 xwrite(int fd, const char *buf, int nbytes)
9613 i = write(fd, buf, n);
9619 } else if (i == 0) {
9622 } else if (errno != EINTR) {
9630 * Shell command parser.
9633 #define EOFMARKLEN 79
9638 struct heredoc *next; /* next here document in list */
9639 union node *here; /* redirection node */
9640 char *eofmark; /* string indicating end of input */
9641 int striptabs; /* if set, strip leading tabs */
9644 static struct heredoc *heredoclist; /* list of here documents to read */
9645 static int parsebackquote; /* nonzero if we are inside backquotes */
9646 static int doprompt; /* if set, prompt the user */
9647 static int needprompt; /* true if interactive and at start of line */
9648 static int lasttoken; /* last token read */
9650 static char *wordtext; /* text of last word returned by readtoken */
9652 static struct nodelist *backquotelist;
9653 static union node *redirnode;
9654 static struct heredoc *heredoc;
9655 static int quoteflag; /* set if (part of) last token was quoted */
9656 static int startlinno; /* line # where last token started */
9659 static union node *list (int);
9660 static union node *andor (void);
9661 static union node *pipeline (void);
9662 static union node *command (void);
9663 static union node *simplecmd (void);
9664 static void parsefname (void);
9665 static void parseheredoc (void);
9666 static char peektoken (void);
9667 static int readtoken (void);
9668 static int xxreadtoken (void);
9669 static int readtoken1 (int, int, const char *, int);
9670 static int noexpand (char *);
9671 static void synexpect (int) __attribute__((noreturn));
9672 static void synerror (const char *) __attribute__((noreturn));
9673 static void setprompt (int);
9677 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9678 * valid parse tree indicating a blank line.)
9682 parsecmd(int interact)
9687 doprompt = interact;
9707 union node *n1, *n2, *n3;
9711 if (nlflag == 0 && peektoken())
9717 if (tok == TBACKGND) {
9718 if (n2->type == NCMD || n2->type == NPIPE) {
9719 n2->ncmd.backgnd = 1;
9720 } else if (n2->type == NREDIR) {
9721 n2->type = NBACKGND;
9723 n3 = (union node *)stalloc(sizeof (struct nredir));
9724 n3->type = NBACKGND;
9726 n3->nredir.redirect = NULL;
9734 n3 = (union node *)stalloc(sizeof (struct nbinary));
9736 n3->nbinary.ch1 = n1;
9737 n3->nbinary.ch2 = n2;
9761 pungetc(); /* push back EOF on input */
9776 union node *n1, *n2, *n3;
9782 if ((t = readtoken()) == TAND) {
9784 } else if (t == TOR) {
9792 n3 = (union node *)stalloc(sizeof (struct nbinary));
9794 n3->nbinary.ch1 = n1;
9795 n3->nbinary.ch2 = n2;
9804 union node *n1, *n2, *pipenode;
9805 struct nodelist *lp, *prev;
9809 TRACE(("pipeline: entered\n"));
9810 if (readtoken() == TNOT) {
9816 if (readtoken() == TPIPE) {
9817 pipenode = (union node *)stalloc(sizeof (struct npipe));
9818 pipenode->type = NPIPE;
9819 pipenode->npipe.backgnd = 0;
9820 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9821 pipenode->npipe.cmdlist = lp;
9825 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9829 } while (readtoken() == TPIPE);
9835 n2 = (union node *)stalloc(sizeof (struct nnot));
9847 union node *n1, *n2;
9848 union node *ap, **app;
9849 union node *cp, **cpp;
9850 union node *redir, **rpp;
9857 switch (readtoken()) {
9859 n1 = (union node *)stalloc(sizeof (struct nif));
9861 n1->nif.test = list(0);
9862 if (readtoken() != TTHEN)
9864 n1->nif.ifpart = list(0);
9866 while (readtoken() == TELIF) {
9867 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9868 n2 = n2->nif.elsepart;
9870 n2->nif.test = list(0);
9871 if (readtoken() != TTHEN)
9873 n2->nif.ifpart = list(0);
9875 if (lasttoken == TELSE)
9876 n2->nif.elsepart = list(0);
9878 n2->nif.elsepart = NULL;
9881 if (readtoken() != TFI)
9888 n1 = (union node *)stalloc(sizeof (struct nbinary));
9889 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9890 n1->nbinary.ch1 = list(0);
9891 if ((got=readtoken()) != TDO) {
9892 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9895 n1->nbinary.ch2 = list(0);
9896 if (readtoken() != TDONE)
9902 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9903 synerror("Bad for loop variable");
9904 n1 = (union node *)stalloc(sizeof (struct nfor));
9906 n1->nfor.var = wordtext;
9908 if (readtoken() == TIN) {
9910 while (readtoken() == TWORD) {
9911 n2 = (union node *)stalloc(sizeof (struct narg));
9913 n2->narg.text = wordtext;
9914 n2->narg.backquote = backquotelist;
9916 app = &n2->narg.next;
9920 if (lasttoken != TNL && lasttoken != TSEMI)
9923 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9925 n2 = (union node *)stalloc(sizeof (struct narg));
9927 n2->narg.text = argvars;
9928 n2->narg.backquote = NULL;
9929 n2->narg.next = NULL;
9932 * Newline or semicolon here is optional (but note
9933 * that the original Bourne shell only allowed NL).
9935 if (lasttoken != TNL && lasttoken != TSEMI)
9939 if (readtoken() != TDO)
9941 n1->nfor.body = list(0);
9942 if (readtoken() != TDONE)
9947 n1 = (union node *)stalloc(sizeof (struct ncase));
9949 if (readtoken() != TWORD)
9951 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9953 n2->narg.text = wordtext;
9954 n2->narg.backquote = backquotelist;
9955 n2->narg.next = NULL;
9958 } while (readtoken() == TNL);
9959 if (lasttoken != TIN)
9960 synerror("expecting \"in\"");
9961 cpp = &n1->ncase.cases;
9962 checkkwd = 2, readtoken();
9964 if (lasttoken == TLP)
9966 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9968 app = &cp->nclist.pattern;
9970 *app = ap = (union node *)stalloc(sizeof (struct narg));
9972 ap->narg.text = wordtext;
9973 ap->narg.backquote = backquotelist;
9974 if (checkkwd = 2, readtoken() != TPIPE)
9976 app = &ap->narg.next;
9979 ap->narg.next = NULL;
9980 if (lasttoken != TRP)
9982 cp->nclist.body = list(0);
9985 if ((t = readtoken()) != TESAC) {
9987 synexpect(TENDCASE);
9989 checkkwd = 2, readtoken();
9991 cpp = &cp->nclist.next;
9992 } while(lasttoken != TESAC);
9997 n1 = (union node *)stalloc(sizeof (struct nredir));
9998 n1->type = NSUBSHELL;
9999 n1->nredir.n = list(0);
10000 n1->nredir.redirect = NULL;
10001 if (readtoken() != TRP)
10007 if (readtoken() != TEND)
10011 /* Handle an empty command like other simple commands. */
10020 * An empty command before a ; doesn't make much sense, and
10021 * should certainly be disallowed in the case of `if ;'.
10035 /* Now check for redirection which may follow command */
10036 while (readtoken() == TREDIR) {
10037 *rpp = n2 = redirnode;
10038 rpp = &n2->nfile.next;
10044 if (n1->type != NSUBSHELL) {
10045 n2 = (union node *)stalloc(sizeof (struct nredir));
10050 n1->nredir.redirect = redir;
10057 static union node *
10059 union node *args, **app;
10060 union node *n = NULL;
10061 union node *vars, **vpp;
10062 union node **rpp, *redir;
10073 switch (readtoken()) {
10076 n = (union node *)stalloc(sizeof (struct narg));
10078 n->narg.text = wordtext;
10079 n->narg.backquote = backquotelist;
10080 if (lasttoken == TWORD) {
10082 app = &n->narg.next;
10085 vpp = &n->narg.next;
10089 *rpp = n = redirnode;
10090 rpp = &n->nfile.next;
10091 parsefname(); /* read name of redirection file */
10095 args && app == &args->narg.next &&
10098 /* We have a function */
10099 if (readtoken() != TRP)
10103 n->narg.next = command();
10116 n = (union node *)stalloc(sizeof (struct ncmd));
10118 n->ncmd.backgnd = 0;
10119 n->ncmd.args = args;
10120 n->ncmd.assign = vars;
10121 n->ncmd.redirect = redir;
10125 static union node *
10129 n = (union node *)stalloc(sizeof (struct narg));
10131 n->narg.next = NULL;
10132 n->narg.text = wordtext;
10133 n->narg.backquote = backquotelist;
10137 static void fixredir(union node *n, const char *text, int err)
10139 TRACE(("Fix redir %s %d\n", text, err));
10141 n->ndup.vname = NULL;
10143 if (is_digit(text[0]) && text[1] == '\0')
10144 n->ndup.dupfd = digit_val(text[0]);
10145 else if (text[0] == '-' && text[1] == '\0')
10146 n->ndup.dupfd = -1;
10150 synerror("Bad fd number");
10152 n->ndup.vname = makename();
10159 union node *n = redirnode;
10161 if (readtoken() != TWORD)
10163 if (n->type == NHERE) {
10164 struct heredoc *here = heredoc;
10168 if (quoteflag == 0)
10170 TRACE(("Here document %d\n", n->type));
10171 if (here->striptabs) {
10172 while (*wordtext == '\t')
10175 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10176 synerror("Illegal eof marker for << redirection");
10177 rmescapes(wordtext);
10178 here->eofmark = wordtext;
10180 if (heredoclist == NULL)
10181 heredoclist = here;
10183 for (p = heredoclist ; p->next ; p = p->next);
10186 } else if (n->type == NTOFD || n->type == NFROMFD) {
10187 fixredir(n, wordtext, 0);
10189 n->nfile.fname = makename();
10195 * Input any here documents.
10200 struct heredoc *here;
10203 while (heredoclist) {
10204 here = heredoclist;
10205 heredoclist = here->next;
10210 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10211 here->eofmark, here->striptabs);
10212 n = (union node *)stalloc(sizeof (struct narg));
10213 n->narg.type = NARG;
10214 n->narg.next = NULL;
10215 n->narg.text = wordtext;
10216 n->narg.backquote = backquotelist;
10217 here->here->nhere.doc = n;
10227 return tokname_array[t][0];
10235 int savecheckalias = checkalias;
10236 int savecheckkwd = checkkwd;
10241 int alreadyseen = tokpushback;
10251 checkalias = savecheckalias;
10258 if (checkkwd == 2) {
10267 * check for keywords
10269 if (t == TWORD && !quoteflag)
10271 const char *const *pp;
10273 if ((pp = findkwd(wordtext))) {
10274 lasttoken = t = pp - tokname_array;
10275 TRACE(("keyword %s recognized\n", tokname(t)));
10286 } else if (checkalias == 2 && isassignment(wordtext)) {
10287 lasttoken = t = TASSIGN;
10289 } else if (checkalias) {
10290 if (!quoteflag && (ap = lookupalias(wordtext, 1)) != NULL) {
10292 pushstring(ap->val, strlen(ap->val), ap);
10294 checkkwd = savecheckkwd;
10303 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10305 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10312 * Read the next input token.
10313 * If the token is a word, we set backquotelist to the list of cmds in
10314 * backquotes. We set quoteflag to true if any part of the word was
10316 * If the token is TREDIR, then we set redirnode to a structure containing
10318 * In all cases, the variable startlinno is set to the number of the line
10319 * on which the token starts.
10321 * [Change comment: here documents and internal procedures]
10322 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10323 * word parsing code into a separate routine. In this case, readtoken
10324 * doesn't need to have any internal procedures, but parseword does.
10325 * We could also make parseoperator in essence the main routine, and
10326 * have parseword (readtoken1?) handle both words and redirection.]
10329 #define RETURN(token) return lasttoken = token
10343 startlinno = plinno;
10344 for (;;) { /* until token or start of word found */
10347 case ' ': case '\t':
10353 while ((c = pgetc()) != '\n' && c != PEOF);
10357 if (pgetc() == '\n') {
10358 startlinno = ++plinno;
10369 needprompt = doprompt;
10374 if (pgetc() == '&')
10379 if (pgetc() == '|')
10384 if (pgetc() == ';')
10397 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10404 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10405 * is not NULL, read a here document. In the latter case, eofmark is the
10406 * word which marks the end of the document and striptabs is true if
10407 * leading tabs should be stripped from the document. The argument firstc
10408 * is the first character of the input token or document.
10410 * Because C does not have internal subroutines, I have simulated them
10411 * using goto's to implement the subroutine linkage. The following macros
10412 * will run code that appears at the end of readtoken1.
10415 #define CHECKEND() {goto checkend; checkend_return:;}
10416 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10417 #define PARSESUB() {goto parsesub; parsesub_return:;}
10418 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10419 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10420 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10423 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10428 char line[EOFMARKLEN + 1];
10429 struct nodelist *bqlist;
10432 int varnest; /* levels of variables expansion */
10433 int arinest; /* levels of arithmetic expansion */
10434 int parenlevel; /* levels of parens in arithmetic */
10435 int dqvarnest; /* levels of variables expansion within double quotes */
10437 int prevsyntax; /* syntax before arithmetic */
10439 /* Avoid longjmp clobbering */
10445 (void) &parenlevel;
10448 (void) &prevsyntax;
10452 startlinno = plinno;
10454 if (syntax == DQSYNTAX)
10463 STARTSTACKSTR(out);
10464 loop: { /* for each line, until end of word */
10465 CHECKEND(); /* set c to PEOF if at end of here document */
10466 for (;;) { /* until end of line or end of word */
10467 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10468 switch(SIT(c,syntax)) {
10469 case CNL: /* '\n' */
10470 if (syntax == BASESYNTAX)
10471 goto endword; /* exit outer loop */
10479 goto loop; /* continue outer loop */
10484 if ((eofmark == NULL || dblquote) &&
10486 USTPUTC(CTLESC, out);
10489 case CBACK: /* backslash */
10492 USTPUTC('\\', out);
10494 } else if (c == '\n') {
10500 if (dblquote && c != '\\' && c != '`' && c != '$'
10501 && (c != '"' || eofmark != NULL))
10502 USTPUTC('\\', out);
10503 if (SIT(c,SQSYNTAX) == CCTL)
10504 USTPUTC(CTLESC, out);
10505 else if (eofmark == NULL)
10506 USTPUTC(CTLQUOTEMARK, out);
10512 if (eofmark == NULL)
10513 USTPUTC(CTLQUOTEMARK, out);
10517 if (eofmark == NULL)
10518 USTPUTC(CTLQUOTEMARK, out);
10523 if (eofmark != NULL && arinest == 0 &&
10528 syntax = ARISYNTAX;
10530 } else if (eofmark == NULL &&
10532 syntax = BASESYNTAX;
10538 case CVAR: /* '$' */
10539 PARSESUB(); /* parse substitution */
10541 case CENDVAR: /* '}' */
10544 if (dqvarnest > 0) {
10547 USTPUTC(CTLENDVAR, out);
10552 #ifdef ASH_MATH_SUPPORT
10553 case CLP: /* '(' in arithmetic */
10557 case CRP: /* ')' in arithmetic */
10558 if (parenlevel > 0) {
10562 if (pgetc() == ')') {
10563 if (--arinest == 0) {
10564 USTPUTC(CTLENDARI, out);
10565 syntax = prevsyntax;
10566 if (syntax == DQSYNTAX)
10574 * unbalanced parens
10575 * (don't 2nd guess - no error)
10583 case CBQUOTE: /* '`' */
10587 goto endword; /* exit outer loop */
10592 goto endword; /* exit outer loop */
10603 if (syntax == ARISYNTAX)
10604 synerror("Missing '))'");
10605 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10606 synerror("Unterminated quoted string");
10607 if (varnest != 0) {
10608 startlinno = plinno;
10609 synerror("Missing '}'");
10611 USTPUTC('\0', out);
10612 len = out - stackblock();
10613 out = stackblock();
10614 if (eofmark == NULL) {
10615 if ((c == '>' || c == '<')
10618 && (*out == '\0' || is_digit(*out))) {
10620 return lasttoken = TREDIR;
10625 quoteflag = quotef;
10626 backquotelist = bqlist;
10627 grabstackblock(len);
10629 return lasttoken = TWORD;
10630 /* end of readtoken routine */
10635 * Check to see whether we are at the end of the here document. When this
10636 * is called, c is set to the first character of the next input line. If
10637 * we are at the end of the here document, this routine sets the c to PEOF.
10648 while (c == '\t') {
10652 if (c == *eofmark) {
10653 if (pfgets(line, sizeof line) != NULL) {
10657 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10658 if (*p == '\n' && *q == '\0') {
10661 needprompt = doprompt;
10663 pushstring(line, strlen(line), NULL);
10668 goto checkend_return;
10673 * Parse a redirection operator. The variable "out" points to a string
10674 * specifying the fd to be redirected. The variable "c" contains the
10675 * first character of the redirection operator.
10682 np = (union node *)stalloc(sizeof (struct nfile));
10687 np->type = NAPPEND;
10696 } else { /* c == '<' */
10698 switch (c = pgetc()) {
10700 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10701 np = (union node *)stalloc(sizeof (struct nhere));
10705 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10706 heredoc->here = np;
10707 if ((c = pgetc()) == '-') {
10708 heredoc->striptabs = 1;
10710 heredoc->striptabs = 0;
10716 np->type = NFROMFD;
10720 np->type = NFROMTO;
10730 np->nfile.fd = digit_val(fd);
10732 goto parseredir_return;
10737 * Parse a substitution. At this point, we have read the dollar sign
10738 * and nothing else.
10746 static const char types[] = "}-+?=";
10751 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10755 } else if (c == '(') { /* $(command) or $((arith)) */
10756 if (pgetc() == '(') {
10763 USTPUTC(CTLVAR, out);
10764 typeloc = out - stackblock();
10765 USTPUTC(VSNORMAL, out);
10766 subtype = VSNORMAL;
10770 if ((c = pgetc()) == '}')
10773 subtype = VSLENGTH;
10778 if (c > PEOA && is_name(c)) {
10782 } while (c > PEOA && is_in_name(c));
10783 } else if (is_digit(c)) {
10787 } while (is_digit(c));
10789 else if (is_special(c)) {
10794 badsub: synerror("Bad substitution");
10798 if (subtype == 0) {
10805 p = strchr(types, c);
10808 subtype = p - types + VSNORMAL;
10814 subtype = c == '#' ? VSTRIMLEFT :
10827 if (dblquote || arinest)
10829 *(stackblock() + typeloc) = subtype | flags;
10830 if (subtype != VSNORMAL) {
10837 goto parsesub_return;
10842 * Called to parse command substitutions. Newstyle is set if the command
10843 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10844 * list of commands (passed by reference), and savelen is the number of
10845 * characters on the top of the stack which must be preserved.
10849 struct nodelist **nlpp;
10852 char *volatile str;
10853 struct jmploc jmploc;
10854 struct jmploc *volatile savehandler;
10858 (void) &saveprompt;
10861 savepbq = parsebackquote;
10862 if (setjmp(jmploc.loc)) {
10865 parsebackquote = 0;
10866 handler = savehandler;
10867 longjmp(handler->loc, 1);
10871 savelen = out - stackblock();
10873 str = ckmalloc(savelen);
10874 memcpy(str, stackblock(), savelen);
10876 savehandler = handler;
10880 /* We must read until the closing backquote, giving special
10881 treatment to some slashes, and then push the string and
10882 reread it as input, interpreting it normally. */
10889 STARTSTACKSTR(pout);
10895 switch (pc = pgetc()) {
10900 if ((pc = pgetc()) == '\n') {
10907 * If eating a newline, avoid putting
10908 * the newline into the new character
10909 * stream (via the STPUTC after the
10914 if (pc != '\\' && pc != '`' && pc != '$'
10915 && (!dblquote || pc != '"'))
10916 STPUTC('\\', pout);
10926 startlinno = plinno;
10927 synerror("EOF in backquote substitution");
10931 needprompt = doprompt;
10940 STPUTC('\0', pout);
10941 psavelen = pout - stackblock();
10942 if (psavelen > 0) {
10943 pstr = grabstackstr(pout);
10944 setinputstring(pstr);
10949 nlpp = &(*nlpp)->next;
10950 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10951 (*nlpp)->next = NULL;
10952 parsebackquote = oldstyle;
10955 saveprompt = doprompt;
10962 doprompt = saveprompt;
10964 if (readtoken() != TRP)
10971 * Start reading from old file again, ignoring any pushed back
10972 * tokens left from the backquote parsing
10977 while (stackblocksize() <= savelen)
10979 STARTSTACKSTR(out);
10981 memcpy(out, str, savelen);
10982 STADJUST(savelen, out);
10988 parsebackquote = savepbq;
10989 handler = savehandler;
10990 if (arinest || dblquote)
10991 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10993 USTPUTC(CTLBACKQ, out);
10995 goto parsebackq_oldreturn;
10997 goto parsebackq_newreturn;
11001 * Parse an arithmetic expansion (indicate start of one and set state)
11005 if (++arinest == 1) {
11006 prevsyntax = syntax;
11007 syntax = ARISYNTAX;
11008 USTPUTC(CTLARI, out);
11015 * we collapse embedded arithmetic expansion to
11016 * parenthesis, which should be equivalent
11020 goto parsearith_return;
11023 } /* end of readtoken */
11027 * Returns true if the text contains nothing to expand (no dollar signs
11039 while ((c = *p++) != '\0') {
11040 if (c == CTLQUOTEMARK)
11044 else if (SIT(c,BASESYNTAX) == CCTL)
11052 * Return true if the argument is a legal variable name (a letter or
11053 * underscore followed by zero or more letters, underscores, and digits).
11057 goodname(const char *name)
11065 if (! is_in_name(*p))
11073 * Called when an unexpected token is read during the parse. The argument
11074 * is the token that is expected, or -1 if more than one type of token can
11075 * occur at this point.
11085 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11087 sprintf(msg+l, " (expecting %s)", tokname(token));
11094 synerror(const char *msg)
11097 out2fmt("%s: %d: ", commandname, startlinno);
11098 out2fmt("Syntax error: %s\n", msg);
11099 error((char *)NULL);
11105 * called by editline -- any expansions to the prompt
11106 * should be added here.
11109 setprompt(int whichprompt)
11112 switch (whichprompt) {
11127 * Code for dealing with input/output redirection.
11130 #define EMPTY -2 /* marks an unused slot in redirtab */
11132 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11134 # define PIPESIZE PIPE_BUF
11139 * Open a file in noclobber mode.
11140 * The code was copied from bash.
11143 noclobberopen(const char *fname)
11146 struct stat finfo, finfo2;
11149 * If the file exists and is a regular file, return an error
11152 r = stat(fname, &finfo);
11153 if (r == 0 && S_ISREG(finfo.st_mode)) {
11159 * If the file was not present (r != 0), make sure we open it
11160 * exclusively so that if it is created before we open it, our open
11161 * will fail. Make sure that we do not truncate an existing file.
11162 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11163 * file was not a regular file, we leave O_EXCL off.
11166 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11167 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11169 /* If the open failed, return the file descriptor right away. */
11174 * OK, the open succeeded, but the file may have been changed from a
11175 * non-regular file to a regular file between the stat and the open.
11176 * We are assuming that the O_EXCL open handles the case where FILENAME
11177 * did not exist and is symlinked to an existing file between the stat
11182 * If we can open it and fstat the file descriptor, and neither check
11183 * revealed that it was a regular file, and the file has not been
11184 * replaced, return the file descriptor.
11186 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11187 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11190 /* The file has been replaced. badness. */
11197 * Handle here documents. Normally we fork off a process to write the
11198 * data to a pipe. If the document is short, we can stuff the data in
11199 * the pipe without forking.
11203 openhere(const union node *redir)
11209 error("Pipe call failed");
11210 if (redir->type == NHERE) {
11211 len = strlen(redir->nhere.doc->narg.text);
11212 if (len <= PIPESIZE) {
11213 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11217 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11219 signal(SIGINT, SIG_IGN);
11220 signal(SIGQUIT, SIG_IGN);
11221 signal(SIGHUP, SIG_IGN);
11223 signal(SIGTSTP, SIG_IGN);
11225 signal(SIGPIPE, SIG_DFL);
11226 if (redir->type == NHERE)
11227 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11229 expandhere(redir->nhere.doc, pip[1]);
11239 openredirect(const union node *redir)
11244 switch (redir->nfile.type) {
11246 fname = redir->nfile.expfname;
11247 if ((f = open(fname, O_RDONLY)) < 0)
11251 fname = redir->nfile.expfname;
11252 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11256 /* Take care of noclobber mode. */
11258 fname = redir->nfile.expfname;
11259 if ((f = noclobberopen(fname)) < 0)
11264 fname = redir->nfile.expfname;
11266 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11269 if ((f = creat(fname, 0666)) < 0)
11274 fname = redir->nfile.expfname;
11276 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11279 if ((f = open(fname, O_WRONLY)) < 0
11280 && (f = creat(fname, 0666)) < 0)
11282 lseek(f, (off_t)0, 2);
11289 /* Fall through to eliminate warning. */
11296 f = openhere(redir);
11302 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11304 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11309 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11310 * old file descriptors are stashed away so that the redirection can be
11311 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11312 * standard output, and the standard error if it becomes a duplicate of
11317 redirect(union node *redir, int flags)
11320 struct redirtab *sv = NULL;
11325 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11327 if (flags & REDIR_PUSH) {
11328 sv = ckmalloc(sizeof (struct redirtab));
11329 for (i = 0 ; i < 10 ; i++)
11330 sv->renamed[i] = EMPTY;
11331 sv->next = redirlist;
11334 for (n = redir ; n ; n = n->nfile.next) {
11337 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11338 n->ndup.dupfd == fd)
11339 continue; /* redirect from/to same file descriptor */
11342 newfd = openredirect(n);
11343 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11346 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11350 dupredirect(n, newfd, fd1dup);
11360 error("%d: %m", fd);
11366 if (flags & REDIR_PUSH) {
11367 sv->renamed[fd] = i;
11370 } else if (fd != newfd) {
11376 dupredirect(n, newfd, fd1dup);
11383 dupredirect(const union node *redir, int f, int fd1dup)
11385 int fd = redir->nfile.fd;
11389 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11390 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11391 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11392 dup_as_newfd(redir->ndup.dupfd, fd);
11398 dup_as_newfd(f, fd);
11407 * Undo the effects of the last redirection.
11413 struct redirtab *rp = redirlist;
11417 for (i = 0 ; i < 10 ; i++) {
11418 if (rp->renamed[i] != EMPTY) {
11422 if (rp->renamed[i] >= 0) {
11423 dup_as_newfd(rp->renamed[i], i);
11424 close(rp->renamed[i]);
11428 redirlist = rp->next;
11434 * Discard all saved file descriptors.
11439 struct redirtab *rp;
11442 for (rp = redirlist ; rp ; rp = rp->next) {
11443 for (i = 0 ; i < 10 ; i++) {
11444 if (rp->renamed[i] >= 0) {
11445 close(rp->renamed[i]);
11447 rp->renamed[i] = EMPTY;
11454 * Copy a file descriptor to be >= to. Returns -1
11455 * if the source file descriptor is closed, EMPTY if there are no unused
11456 * file descriptors left.
11460 dup_as_newfd(from, to)
11466 newfd = fcntl(from, F_DUPFD, to);
11468 if (errno == EMFILE)
11471 error("%d: %m", from);
11477 static void shtree (union node *, int, char *, FILE*);
11478 static void shcmd (union node *, FILE *);
11479 static void sharg (union node *, FILE *);
11480 static void indent (int, char *, FILE *);
11481 static void trstring (char *);
11488 trputs("showtree called\n");
11489 shtree(n, 1, NULL, stdout);
11494 shtree(n, ind, pfx, fp)
11500 struct nodelist *lp;
11506 indent(ind, pfx, fp);
11517 shtree(n->nbinary.ch1, ind, NULL, fp);
11520 shtree(n->nbinary.ch2, ind, NULL, fp);
11528 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11533 if (n->npipe.backgnd)
11539 fprintf(fp, "<node type %d>", n->type);
11559 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11565 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11571 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11572 s = redir_strings[np->nfile.type - NTO];
11578 switch (np->nfile.type) {
11579 case NTO: s = ">"; dftfd = 1; break;
11580 case NAPPEND: s = ">>"; dftfd = 1; break;
11581 case NTOFD: s = ">&"; dftfd = 1; break;
11582 case NTOOV: s = ">|"; dftfd = 1; break;
11583 case NFROM: s = "<"; dftfd = 0; break;
11584 case NFROMFD: s = "<&"; dftfd = 0; break;
11585 case NFROMTO: s = "<>"; dftfd = 0; break;
11586 default: s = "*error*"; dftfd = 0; break;
11589 if (np->nfile.fd != dftfd)
11590 fprintf(fp, "%d", np->nfile.fd);
11592 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11593 fprintf(fp, "%d", np->ndup.dupfd);
11595 sharg(np->nfile.fname, fp);
11609 struct nodelist *bqlist;
11612 if (arg->type != NARG) {
11613 printf("<node type %d>\n", arg->type);
11617 bqlist = arg->narg.backquote;
11618 for (p = arg->narg.text ; *p ; p++) {
11627 if (subtype == VSLENGTH)
11633 if (subtype & VSNUL)
11636 switch (subtype & VSTYPE) {
11655 case VSTRIMLEFTMAX:
11662 case VSTRIMRIGHTMAX:
11669 printf("<subtype %d>", subtype);
11676 case CTLBACKQ|CTLQUOTE:
11679 shtree(bqlist->n, -1, NULL, fp);
11691 indent(amount, pfx, fp)
11698 for (i = 0 ; i < amount ; i++) {
11699 if (pfx && i == amount - 1)
11717 static int debug = 1;
11719 static int debug = 0;
11727 if (tracefile == NULL)
11729 putc(c, tracefile);
11735 trace(const char *fmt, ...)
11739 if (tracefile != NULL) {
11740 (void) vfprintf(tracefile, fmt, va);
11741 if (strchr(fmt, '\n'))
11742 (void) fflush(tracefile);
11752 if (tracefile == NULL)
11754 fputs(s, tracefile);
11755 if (strchr(s, '\n'))
11767 if (tracefile == NULL)
11769 putc('"', tracefile);
11770 for (p = s ; *p ; p++) {
11772 case '\n': c = 'n'; goto backslash;
11773 case '\t': c = 't'; goto backslash;
11774 case '\r': c = 'r'; goto backslash;
11775 case '"': c = '"'; goto backslash;
11776 case '\\': c = '\\'; goto backslash;
11777 case CTLESC: c = 'e'; goto backslash;
11778 case CTLVAR: c = 'v'; goto backslash;
11779 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11780 case CTLBACKQ: c = 'q'; goto backslash;
11781 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11782 backslash: putc('\\', tracefile);
11783 putc(c, tracefile);
11786 if (*p >= ' ' && *p <= '~')
11787 putc(*p, tracefile);
11789 putc('\\', tracefile);
11790 putc(*p >> 6 & 03, tracefile);
11791 putc(*p >> 3 & 07, tracefile);
11792 putc(*p & 07, tracefile);
11797 putc('"', tracefile);
11805 if (tracefile == NULL)
11810 putc(' ', tracefile);
11812 putc('\n', tracefile);
11827 #ifdef not_this_way
11830 if ((p = getenv("HOME")) == NULL) {
11831 if (geteuid() == 0)
11837 strcat(s, "/trace");
11840 strcpy(s, "./trace");
11841 #endif /* not_this_way */
11842 if ((tracefile = fopen(s, "a")) == NULL) {
11843 fprintf(stderr, "Can't open %s\n", s);
11847 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11848 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11850 fputs("\nTracing started.\n", tracefile);
11857 * The trap builtin.
11861 trapcmd(argc, argv)
11870 for (signo = 0 ; signo < NSIG ; signo++) {
11871 if (trap[signo] != NULL) {
11875 p = single_quote(trap[signo]);
11876 sn = sys_siglist[signo];
11878 sn = u_signal_names(0, &signo, 0);
11881 printf("trap -- %s %s\n", p, sn);
11893 if ((signo = decode_signal(*ap, 0)) < 0)
11894 error("%s: bad trap", *ap);
11897 if (action[0] == '-' && action[1] == '\0')
11900 action = savestr(action);
11903 ckfree(trap[signo]);
11904 trap[signo] = action;
11919 * Set the signal handler for the specified signal. The routine figures
11920 * out what it should be set to.
11924 setsignal(int signo)
11928 struct sigaction act;
11930 if ((t = trap[signo]) == NULL)
11932 else if (*t != '\0')
11936 if (rootshell && action == S_DFL) {
11939 if (iflag || minusc || sflag == 0)
11965 t = &sigmode[signo - 1];
11968 * current setting unknown
11970 if (sigaction(signo, 0, &act) == -1) {
11972 * Pretend it worked; maybe we should give a warning
11973 * here, but other shells don't. We don't alter
11974 * sigmode, so that we retry every time.
11978 if (act.sa_handler == SIG_IGN) {
11979 if (mflag && (signo == SIGTSTP ||
11980 signo == SIGTTIN || signo == SIGTTOU)) {
11981 *t = S_IGN; /* don't hard ignore these */
11985 *t = S_RESET; /* force to be set */
11988 if (*t == S_HARD_IGN || *t == action)
11990 act.sa_handler = ((action == S_CATCH) ? onsig
11991 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11994 sigemptyset(&act.sa_mask);
11995 sigaction(signo, &act, 0);
12006 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
12007 signal(signo, SIG_IGN);
12009 sigmode[signo - 1] = S_HARD_IGN;
12020 if (signo == SIGINT && trap[SIGINT] == NULL) {
12024 gotsig[signo - 1] = 1;
12030 * Called to execute a trap. Perhaps we should avoid entering new trap
12031 * handlers while we are executing a trap handler.
12041 for (i = 1 ; ; i++) {
12048 savestatus=exitstatus;
12049 evalstring(trap[i], 0);
12050 exitstatus=savestatus;
12057 * Called to exit the shell.
12061 exitshell(int status)
12063 struct jmploc loc1, loc2;
12066 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12067 if (setjmp(loc1.loc)) {
12070 if (setjmp(loc2.loc)) {
12074 if ((p = trap[0]) != NULL && *p != '\0') {
12078 l1: handler = &loc2; /* probably unnecessary */
12087 static int decode_signal(const char *string, int minsig)
12090 const char *name = u_signal_names(string, &signo, minsig);
12092 return name ? signo : -1;
12095 static struct var **hashvar (const char *);
12096 static void showvars (const char *, int, int);
12097 static struct var **findvar (struct var **, const char *);
12100 * Initialize the varable symbol tables and import the environment
12104 * This routine initializes the builtin variables. It is called when the
12105 * shell is initialized and again when a shell procedure is spawned.
12110 const struct varinit *ip;
12114 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12115 if ((vp->flags & VEXPORT) == 0) {
12116 vpp = hashvar(ip->text);
12119 vp->text = strdup(ip->text);
12120 vp->flags = ip->flags;
12121 vp->func = ip->func;
12125 * PS1 depends on uid
12127 if ((vps1.flags & VEXPORT) == 0) {
12128 vpp = hashvar("PS1=");
12131 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12132 vps1.flags = VSTRFIXED|VTEXTFIXED;
12137 * Set the value of a variable. The flags argument is ored with the
12138 * flags of the variable. If val is NULL, the variable is unset.
12142 setvar(name, val, flags)
12143 const char *name, *val;
12159 if (! is_in_name(*p)) {
12160 if (*p == '\0' || *p == '=')
12166 namelen = p - name;
12168 error("%.*s: bad variable name", namelen, name);
12169 len = namelen + 2; /* 2 is space for '=' and '\0' */
12173 len += vallen = strlen(val);
12176 nameeq = ckmalloc(len);
12177 memcpy(nameeq, name, namelen);
12178 nameeq[namelen] = '=';
12180 memcpy(nameeq + namelen + 1, val, vallen + 1);
12182 nameeq[namelen + 1] = '\0';
12184 setvareq(nameeq, flags);
12191 * Same as setvar except that the variable and value are passed in
12192 * the first argument as name=value. Since the first argument will
12193 * be actually stored in the table, it should not be a string that
12202 struct var *vp, **vpp;
12205 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12206 if ((vp = *findvar(vpp, s))) {
12207 if (vp->flags & VREADONLY) {
12208 size_t len = strchr(s, '=') - s;
12209 error("%.*s: is read only", len, s);
12213 if (vp->func && (flags & VNOFUNC) == 0)
12214 (*vp->func)(strchr(s, '=') + 1);
12216 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12219 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12220 vp->flags |= flags;
12224 * We could roll this to a function, to handle it as
12225 * a regular variable function callback, but why bother?
12227 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12233 vp = ckmalloc(sizeof (*vp));
12244 * Process a linked list of variable assignments.
12249 struct strlist *mylist;
12251 struct strlist *lp;
12254 for (lp = mylist ; lp ; lp = lp->next) {
12255 setvareq(savestr(lp->text), 0);
12263 * Find the value of a variable. Returns NULL if not set.
12266 static const char *
12272 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12273 return strchr(v->text, '=') + 1;
12281 * Search the environment of a builtin command.
12284 static const char *
12285 bltinlookup(const char *name)
12287 const struct strlist *sp;
12289 for (sp = cmdenviron ; sp ; sp = sp->next) {
12290 if (varequal(sp->text, name))
12291 return strchr(sp->text, '=') + 1;
12293 return lookupvar(name);
12299 * Generate a list of exported variables. This routine is used to construct
12300 * the third argument to execve when executing a program.
12312 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12313 for (vp = *vpp ; vp ; vp = vp->next)
12314 if (vp->flags & VEXPORT)
12317 ep = env = stalloc((nenv + 1) * sizeof *env);
12318 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12319 for (vp = *vpp ; vp ; vp = vp->next)
12320 if (vp->flags & VEXPORT)
12329 * Called when a shell procedure is invoked to clear out nonexported
12330 * variables. It is also necessary to reallocate variables of with
12331 * VSTACK set since these are currently allocated on the stack.
12337 struct var *vp, **prev;
12339 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12340 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12341 if ((vp->flags & VEXPORT) == 0) {
12343 if ((vp->flags & VTEXTFIXED) == 0)
12345 if ((vp->flags & VSTRFIXED) == 0)
12348 if (vp->flags & VSTACK) {
12349 vp->text = savestr(vp->text);
12350 vp->flags &=~ VSTACK;
12362 * Command to list all variables which are set. Currently this command
12363 * is invoked from the set command when the set command is called without
12368 showvarscmd(argc, argv)
12372 showvars(nullstr, VUNSET, VUNSET);
12379 * The export and readonly commands.
12383 exportcmd(argc, argv)
12390 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12393 listsetvar(cmdenviron);
12394 pflag = (nextopt("p") == 'p');
12395 if (argc > 1 && !pflag) {
12396 while ((name = *argptr++) != NULL) {
12397 if ((p = strchr(name, '=')) != NULL) {
12400 if ((vp = *findvar(hashvar(name), name))) {
12405 setvar(name, p, flag);
12409 showvars(argv[0], flag, 0);
12416 * The "local" command.
12419 /* funcnest nonzero if we are currently evaluating a function */
12422 localcmd(argc, argv)
12429 error("Not in a function");
12430 while ((name = *argptr++) != NULL) {
12438 * Make a variable a local variable. When a variable is made local, it's
12439 * value and flags are saved in a localvar structure. The saved values
12440 * will be restored when the shell function returns. We handle the name
12441 * "-" as a special case.
12448 struct localvar *lvp;
12453 lvp = ckmalloc(sizeof (struct localvar));
12454 if (name[0] == '-' && name[1] == '\0') {
12456 p = ckmalloc(sizeof optet_vals);
12457 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12460 vpp = hashvar(name);
12461 vp = *findvar(vpp, name);
12463 if (strchr(name, '='))
12464 setvareq(savestr(name), VSTRFIXED);
12466 setvar(name, NULL, VSTRFIXED);
12467 vp = *vpp; /* the new variable */
12469 lvp->flags = VUNSET;
12471 lvp->text = vp->text;
12472 lvp->flags = vp->flags;
12473 vp->flags |= VSTRFIXED|VTEXTFIXED;
12474 if (strchr(name, '='))
12475 setvareq(savestr(name), 0);
12479 lvp->next = localvars;
12486 * Called after a function returns.
12491 struct localvar *lvp;
12494 while ((lvp = localvars) != NULL) {
12495 localvars = lvp->next;
12497 if (vp == NULL) { /* $- saved */
12498 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12500 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12501 (void)unsetvar(vp->text);
12503 if ((vp->flags & VTEXTFIXED) == 0)
12505 vp->flags = lvp->flags;
12506 vp->text = lvp->text;
12514 setvarcmd(argc, argv)
12519 return unsetcmd(argc, argv);
12520 else if (argc == 3)
12521 setvar(argv[1], argv[2], 0);
12523 error("List assignment not implemented");
12529 * The unset builtin command. We unset the function before we unset the
12530 * variable to allow a function to be unset when there is a readonly variable
12531 * with the same name.
12535 unsetcmd(argc, argv)
12545 while ((i = nextopt("vf")) != '\0') {
12551 if (flg_func == 0 && flg_var == 0)
12554 for (ap = argptr; *ap ; ap++) {
12558 ret |= unsetvar(*ap);
12565 * Unset the specified variable.
12569 unsetvar(const char *s)
12574 vpp = findvar(hashvar(s), s);
12577 if (vp->flags & VREADONLY)
12580 if (*(strchr(vp->text, '=') + 1) != '\0')
12581 setvar(s, nullstr, 0);
12582 vp->flags &= ~VEXPORT;
12583 vp->flags |= VUNSET;
12584 if ((vp->flags & VSTRFIXED) == 0) {
12585 if ((vp->flags & VTEXTFIXED) == 0)
12600 * Find the appropriate entry in the hash table from the name.
12603 static struct var **
12604 hashvar(const char *p)
12606 unsigned int hashval;
12608 hashval = ((unsigned char) *p) << 4;
12609 while (*p && *p != '=')
12610 hashval += (unsigned char) *p++;
12611 return &vartab[hashval % VTABSIZE];
12617 * Returns true if the two strings specify the same varable. The first
12618 * variable name is terminated by '='; the second may be terminated by
12619 * either '=' or '\0'.
12623 varequal(const char *p, const char *q)
12625 while (*p == *q++) {
12629 if (*p == '=' && *(q - 1) == '\0')
12635 showvars(const char *myprefix, int mask, int xor)
12639 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12641 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12642 for (vp = *vpp ; vp ; vp = vp->next) {
12643 if ((vp->flags & mask) ^ xor) {
12647 p = strchr(vp->text, '=') + 1;
12648 len = p - vp->text;
12649 p = single_quote(p);
12651 printf("%s%s%.*s%s\n", myprefix, sep, len,
12659 static struct var **
12660 findvar(struct var **vpp, const char *name)
12662 for (; *vpp; vpp = &(*vpp)->next) {
12663 if (varequal((*vpp)->text, name)) {
12671 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12672 * This file contains code for the times builtin.
12673 * $Id: ash.c,v 1.20 2001/08/10 19:36:07 mjn3 Exp $
12675 static int timescmd (int argc, char **argv)
12678 long int clk_tck = sysconf(_SC_CLK_TCK);
12681 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12682 (int) (buf.tms_utime / clk_tck / 60),
12683 ((double) buf.tms_utime) / clk_tck,
12684 (int) (buf.tms_stime / clk_tck / 60),
12685 ((double) buf.tms_stime) / clk_tck,
12686 (int) (buf.tms_cutime / clk_tck / 60),
12687 ((double) buf.tms_cutime) / clk_tck,
12688 (int) (buf.tms_cstime / clk_tck / 60),
12689 ((double) buf.tms_cstime) / clk_tck);
12693 #ifdef ASH_MATH_SUPPORT
12694 /* The let builtin. */
12695 int letcmd(int argc, char **argv)
12700 char *tmp, *expression, p[13];
12701 expression = strchr(argv[1], '=');
12703 /* Cannot use 'error()' here, or the return code
12704 * will be incorrect */
12705 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12708 *expression = '\0';
12709 tmp = ++expression;
12710 result = arith(tmp, &errcode);
12712 /* Cannot use 'error()' here, or the return code
12713 * will be incorrect */
12714 out2fmt("sh: let: ");
12716 out2fmt("divide by zero");
12718 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12721 snprintf(p, 12, "%ld", result);
12722 setvar(argv[1], savestr(p), 0);
12723 } else if (argc >= 3)
12724 synerror("invalid operand");
12732 * Copyright (c) 1989, 1991, 1993, 1994
12733 * The Regents of the University of California. All rights reserved.
12735 * This code is derived from software contributed to Berkeley by
12736 * Kenneth Almquist.
12738 * Redistribution and use in source and binary forms, with or without
12739 * modification, are permitted provided that the following conditions
12741 * 1. Redistributions of source code must retain the above copyright
12742 * notice, this list of conditions and the following disclaimer.
12743 * 2. Redistributions in binary form must reproduce the above copyright
12744 * notice, this list of conditions and the following disclaimer in the
12745 * documentation and/or other materials provided with the distribution.
12747 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12748 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12750 * 4. Neither the name of the University nor the names of its contributors
12751 * may be used to endorse or promote products derived from this software
12752 * without specific prior written permission.
12754 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12755 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12756 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12757 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12758 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12759 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12760 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12761 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12762 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12763 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF