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>
112 #if !defined(FNMATCH_BROKEN)
115 #if !defined(GLOB_BROKEN)
127 * This file was generated by the mksyntax program.
131 #define CWORD 0 /* character is nothing special */
132 #define CNL 1 /* newline character */
133 #define CBACK 2 /* a backslash character */
134 #define CSQUOTE 3 /* single quote */
135 #define CDQUOTE 4 /* double quote */
136 #define CENDQUOTE 5 /* a terminating quote */
137 #define CBQUOTE 6 /* backwards single quote */
138 #define CVAR 7 /* a dollar sign */
139 #define CENDVAR 8 /* a '}' character */
140 #define CLP 9 /* a left paren in arithmetic */
141 #define CRP 10 /* a right paren in arithmetic */
142 #define CENDFILE 11 /* end of file */
143 #define CCTL 12 /* like CWORD, except it must be escaped */
144 #define CSPCL 13 /* these terminate a word */
145 #define CIGN 14 /* character should be ignored */
165 #define TENDBQUOTE 13
185 /* control characters in argument strings */
186 #define CTLESC '\201'
187 #define CTLVAR '\202'
188 #define CTLENDVAR '\203'
189 #define CTLBACKQ '\204'
190 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
191 /* CTLBACKQ | CTLQUOTE == '\205' */
192 #define CTLARI '\206'
193 #define CTLENDARI '\207'
194 #define CTLQUOTEMARK '\210'
197 #define is_digit(c) ((c)>='0' && (c)<='9')
198 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
199 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
202 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
203 * (assuming ascii char codes, as the original implementation did)
205 #define is_special(c) \
206 ( (((unsigned int)c) - 33 < 32) \
207 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
209 #define digit_val(c) ((c) - '0')
212 #define _DIAGASSERT(x)
216 #define S_DFL 1 /* default signal handling (SIG_DFL) */
217 #define S_CATCH 2 /* signal is caught */
218 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
219 #define S_HARD_IGN 4 /* signal is ignored permenantly */
220 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
223 /* variable substitution byte (follows CTLVAR) */
224 #define VSTYPE 0x0f /* type of variable substitution */
225 #define VSNUL 0x10 /* colon--treat the empty string as unset */
226 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
228 /* values of VSTYPE field */
229 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
230 #define VSMINUS 0x2 /* ${var-text} */
231 #define VSPLUS 0x3 /* ${var+text} */
232 #define VSQUESTION 0x4 /* ${var?message} */
233 #define VSASSIGN 0x5 /* ${var=text} */
234 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
235 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
236 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
237 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
238 #define VSLENGTH 0xa /* ${#var} */
240 /* flags passed to redirect */
241 #define REDIR_PUSH 01 /* save previous values of file descriptors */
242 #define REDIR_BACKQ 02 /* save the command output to pipe */
245 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
246 * so we use _setjmp instead.
250 #define setjmp(jmploc) _setjmp(jmploc)
251 #define longjmp(jmploc, val) _longjmp(jmploc, val)
255 * Most machines require the value returned from malloc to be aligned
256 * in some way. The following macro will get this right on many machines.
265 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
268 #ifdef CONFIG_LOCALE_SUPPORT
270 static void change_lc_all(const char *value);
271 static void change_lc_ctype(const char *value);
275 * These macros allow the user to suspend the handling of interrupt signals
276 * over a period of time. This is similar to SIGHOLD to or sigblock, but
277 * much more efficient and portable. (But hacking the kernel is so much
278 * more fun than worrying about efficiency and portability. :-))
281 static void onint (void);
282 static volatile int suppressint;
283 static volatile int intpending;
285 #define INTOFF suppressint++
286 #ifndef ASH_OPTIMIZE_FOR_SIZE
287 #define INTON { if (--suppressint == 0 && intpending) onint(); }
288 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
290 static void __inton (void);
291 static void forceinton (void);
292 #define INTON __inton()
293 #define FORCEINTON forceinton()
296 #define CLEAR_PENDING_INT intpending = 0
297 #define int_pending() intpending
300 typedef void *pointer;
302 #define NULL (void *)0
305 static inline pointer ckmalloc (int sz) { return xmalloc(sz); }
306 static inline pointer ckrealloc(void *p, int sz) { return xrealloc(p, sz); }
307 static inline char * savestr (const char *s) { return xstrdup(s); }
309 static pointer stalloc (int);
310 static void stunalloc (pointer);
311 static void ungrabstackstr (char *, char *);
312 static char * growstackstr(void);
313 static char * makestrspace(size_t newlen);
314 static char *sstrdup (const char *);
317 * Parse trees for commands are allocated in lifo order, so we use a stack
318 * to make this more efficient, and also to avoid all sorts of exception
319 * handling code to handle interrupts in the middle of a parse.
321 * The size 504 was chosen because the Ultrix malloc handles that size
325 #define MINSIZE 504 /* minimum size of a block */
329 struct stack_block *prev;
333 static struct stack_block stackbase;
334 static struct stack_block *stackp = &stackbase;
335 static struct stackmark *markp;
336 static char *stacknxt = stackbase.space;
337 static int stacknleft = MINSIZE;
340 #define equal(s1, s2) (strcmp(s1, s2) == 0)
342 #define stackblock() stacknxt
343 #define stackblocksize() stacknleft
344 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
346 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
347 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
348 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
351 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
352 #define STUNPUTC(p) (++sstrnleft, --p)
353 #define STTOPC(p) p[-1]
354 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
355 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
357 #define ckfree(p) free((pointer)(p))
361 #define TRACE(param) trace param
362 typedef union node unode;
363 static void trace (const char *, ...);
364 static void trargs (char **);
365 static void showtree (unode *);
366 static void trputc (int);
367 static void trputs (const char *);
368 static void opentrace (void);
403 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
404 #define EXP_TILDE 0x2 /* do normal tilde expansion */
405 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
406 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
407 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
408 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
413 static char optet_vals[NOPTS];
415 static const char * const optlist[NOPTS] = {
434 #define optent_name(optent) (optent+1)
435 #define optent_letter(optent) optent[0]
436 #define optent_val(optent) optet_vals[optent]
438 #define eflag optent_val(0)
439 #define fflag optent_val(1)
440 #define Iflag optent_val(2)
441 #define iflag optent_val(3)
442 #define mflag optent_val(4)
443 #define nflag optent_val(5)
444 #define sflag optent_val(6)
445 #define xflag optent_val(7)
446 #define vflag optent_val(8)
447 #define Vflag optent_val(9)
448 #define Eflag optent_val(10)
449 #define Cflag optent_val(11)
450 #define aflag optent_val(12)
451 #define bflag optent_val(13)
452 #define uflag optent_val(14)
453 #define qflag optent_val(15)
456 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
474 union node *redirect;
481 struct nodelist *cmdlist;
488 union node *redirect;
496 union node *elsepart;
527 struct nodelist *backquote;
565 struct nbinary nbinary;
568 struct nredir nredir;
572 struct nclist nclist;
582 struct nodelist *next;
586 struct backcmd { /* result of evalbackcmd */
587 int fd; /* file descriptor to read from */
588 char *buf; /* buffer */
589 int nleft; /* number of chars in buffer */
590 struct job *jp; /* job structure for command */
598 const struct builtincmd *cmd;
603 struct strlist *next;
609 struct strlist *list;
610 struct strlist **lastp;
614 struct strpush *prev; /* preceding string on stack */
618 struct alias *ap; /* if push was associated with an alias */
620 char *string; /* remember the string since it may change */
624 struct parsefile *prev; /* preceding file on stack */
625 int linno; /* current line */
626 int fd; /* file descriptor (or -1 if string) */
627 int nleft; /* number of chars left in this line */
628 int lleft; /* number of chars left in this buffer */
629 char *nextc; /* next char in buffer */
630 char *buf; /* input buffer */
631 struct strpush *strpush; /* for pushing strings at this level */
632 struct strpush basestrpush; /* so pushing one is fast */
636 struct stack_block *stackp;
639 struct stackmark *marknext;
643 int nparam; /* # of positional parameters (without $0) */
644 unsigned char malloc; /* if parameter list dynamically allocated */
645 char **p; /* parameter list */
646 int optind; /* next parameter to be processed by getopts */
647 int optoff; /* used by getopts */
651 * When commands are first encountered, they are entered in a hash table.
652 * This ensures that a full path search will not have to be done for them
653 * on each invocation.
655 * We should investigate converting to a linear search, even though that
656 * would make the command name "hash" a misnomer.
658 #define CMDTABLESIZE 31 /* should be prime */
659 #define ARB 1 /* actual size determined at run time */
664 struct tblentry *next; /* next entry in hash chain */
665 union param param; /* definition of builtin function */
666 short cmdtype; /* index identifying command */
667 char rehash; /* if set, cd done since entry created */
668 char cmdname[ARB]; /* name of command */
672 static struct tblentry *cmdtable[CMDTABLESIZE];
673 static int builtinloc = -1; /* index in path of %builtin, or -1 */
674 static int exerrno = 0; /* Last exec error */
677 static void tryexec (char *, char **, char **);
678 static void printentry (struct tblentry *, int);
679 static void clearcmdentry (int);
680 static struct tblentry *cmdlookup (const char *, int);
681 static void delete_cmd_entry (void);
682 static int path_change (const char *, int *);
685 static void flushall (void);
686 static void out2fmt (const char *, ...)
687 __attribute__((__format__(__printf__,1,2)));
688 static int xwrite (int, const char *, int);
690 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
691 static void out1str(const char *p) { outstr(p, stdout); }
692 static void out2str(const char *p) { outstr(p, stderr); }
694 #ifndef ASH_OPTIMIZE_FOR_SIZE
695 #define out2c(c) putc((c), stderr)
697 static void out2c(int c) { putc(c, stderr); }
701 #ifdef ASH_OPTIMIZE_FOR_SIZE
702 #define USE_SIT_FUNCTION
705 /* number syntax index */
706 #define BASESYNTAX 0 /* not in quotes */
707 #define DQSYNTAX 1 /* in double quotes */
708 #define SQSYNTAX 2 /* in single quotes */
709 #define ARISYNTAX 3 /* in arithmetic */
711 static const char S_I_T[][4] = {
712 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
713 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
714 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
715 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
716 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
717 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
718 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
719 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
720 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
721 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
722 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
723 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
724 #ifndef USE_SIT_FUNCTION
725 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
726 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
727 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
731 #ifdef USE_SIT_FUNCTION
733 #define U_C(c) ((unsigned char)(c))
735 static int SIT(int c, int syntax)
737 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
738 static const char syntax_index_table [] = {
739 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
740 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
741 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
746 if(c==PEOF) /* 2^8+2 */
748 if(c==PEOA) /* 2^8+1 */
750 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
753 s = strchr(spec_symbls, c);
756 indx = syntax_index_table[(s-spec_symbls)];
758 return S_I_T[indx][syntax];
761 #else /* USE_SIT_FUNCTION */
763 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
765 #define CSPCL_CIGN_CIGN_CIGN 0
766 #define CSPCL_CWORD_CWORD_CWORD 1
767 #define CNL_CNL_CNL_CNL 2
768 #define CWORD_CCTL_CCTL_CWORD 3
769 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
770 #define CVAR_CVAR_CWORD_CVAR 5
771 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
772 #define CSPCL_CWORD_CWORD_CLP 7
773 #define CSPCL_CWORD_CWORD_CRP 8
774 #define CBACK_CBACK_CCTL_CBACK 9
775 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
776 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
777 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
778 #define CWORD_CWORD_CWORD_CWORD 13
779 #define CCTL_CCTL_CCTL_CCTL 14
781 static const char syntax_index_table[258] = {
782 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
783 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
784 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
785 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
786 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
787 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
788 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
789 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
790 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
791 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
792 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
793 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
794 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
795 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
796 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
797 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
798 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
799 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
800 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
801 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
802 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
803 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
804 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
805 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
806 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
807 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
808 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
809 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
810 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
811 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
812 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
813 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
814 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
815 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
816 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
817 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
818 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
819 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
820 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
821 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
822 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
823 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
824 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
825 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
826 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
827 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
828 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
829 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
830 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
831 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
832 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
833 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
834 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
835 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
836 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
837 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
838 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
839 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
840 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
841 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
842 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
843 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
844 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
845 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
846 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
847 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
848 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
849 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
850 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
851 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
852 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
853 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
854 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
855 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
856 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
857 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
858 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
859 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
860 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
861 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
862 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
863 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
864 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
865 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
866 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
867 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
868 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
869 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
870 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
871 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
872 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
873 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
874 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
875 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
876 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
877 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
878 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
879 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
880 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
881 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
882 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
883 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
884 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
885 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
886 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
887 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
888 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
889 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
890 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
891 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
892 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
893 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
894 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
895 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
896 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
897 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
898 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
899 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
900 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
901 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
902 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
903 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
904 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
905 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
906 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
907 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
908 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
909 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
910 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
911 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
912 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
913 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
914 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
915 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
916 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
917 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
918 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
919 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
920 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
921 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
922 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
923 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
924 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
925 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
926 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
927 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
928 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
929 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
930 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
931 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
932 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
933 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
934 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
935 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
936 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
937 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
938 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
939 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
940 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
941 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
942 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
943 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
944 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
945 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
946 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
947 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
948 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
949 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
950 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
951 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
952 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
953 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
954 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
955 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
956 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
957 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
958 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
959 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
960 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
961 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
962 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
963 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
964 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
965 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
966 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
967 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
968 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
969 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
970 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
971 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
972 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
973 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
974 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
975 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
976 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
977 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
978 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
979 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
980 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
981 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
982 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
983 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
984 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
985 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
986 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
987 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
988 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
989 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
990 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
991 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
992 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
993 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
994 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
995 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
996 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
997 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
998 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
999 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1004 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1005 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1006 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1007 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1010 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1032 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1033 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1034 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1035 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1036 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1037 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1038 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1039 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1040 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1043 #endif /* USE_SIT_FUNCTION */
1046 /* first char is indicating which tokens mark the end of a list */
1047 static const char *const tokname_array[] = {
1062 #define KWDOFFSET 14
1063 /* the following are keywords */
1082 static const char *tokname(int tok)
1084 static char buf[16];
1088 sprintf(buf+(tok>=TSEMI), "%s%c",
1089 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1093 static int plinno = 1; /* input line number */
1095 static int parselleft; /* copy of parsefile->lleft */
1097 static struct parsefile basepf; /* top level input file */
1098 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1099 static struct parsefile *parsefile = &basepf; /* current input file */
1102 * NEOF is returned by parsecmd when it encounters an end of file. It
1103 * must be distinct from NULL, so we use the address of a variable that
1104 * happens to be handy.
1107 static int tokpushback; /* last token pushed back */
1108 #define NEOF ((union node *)&tokpushback)
1109 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1112 static void error (const char *, ...) __attribute__((__noreturn__));
1113 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1114 static void shellexec (char **, char **, const char *, int)
1115 __attribute__((noreturn));
1116 static void exitshell (int) __attribute__((noreturn));
1118 static int goodname(const char *);
1119 static void ignoresig (int);
1120 static void onsig (int);
1121 static void dotrap (void);
1122 static int decode_signal (const char *, int);
1124 static void shprocvar(void);
1125 static void deletefuncs(void);
1126 static void setparam (char **);
1127 static void freeparam (volatile struct shparam *);
1129 /* reasons for skipping commands (see comment on breakcmd routine) */
1135 /* values of cmdtype */
1136 #define CMDUNKNOWN -1 /* no entry in table for command */
1137 #define CMDNORMAL 0 /* command is an executable program */
1138 #define CMDBUILTIN 1 /* command is a shell builtin */
1139 #define CMDFUNCTION 2 /* command is a shell function */
1141 #define DO_ERR 1 /* find_command prints errors */
1142 #define DO_ABS 2 /* find_command checks absolute paths */
1143 #define DO_NOFUN 4 /* find_command ignores functions */
1144 #define DO_BRUTE 8 /* find_command ignores hash table */
1151 #define VEXPORT 0x01 /* variable is exported */
1152 #define VREADONLY 0x02 /* variable cannot be modified */
1153 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1154 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1155 #define VSTACK 0x10 /* text is allocated on the stack */
1156 #define VUNSET 0x20 /* the variable is not set */
1157 #define VNOFUNC 0x40 /* don't call the callback function */
1161 struct var *next; /* next entry in hash list */
1162 int flags; /* flags are defined above */
1163 char *text; /* name=value */
1164 void (*func) (const char *);
1165 /* function to be called when */
1166 /* the variable gets set/unset */
1170 struct localvar *next; /* next local variable in list */
1171 struct var *vp; /* the variable that was made local */
1172 int flags; /* saved flags */
1173 char *text; /* saved text */
1177 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1178 #define rmescapes(p) _rmescapes((p), 0)
1179 static char *_rmescapes (char *, int);
1181 static void rmescapes (char *);
1184 static int casematch (union node *, const char *);
1185 static void clearredir(void);
1186 static void popstring(void);
1187 static void readcmdfile (const char *);
1189 static int number (const char *);
1190 static int is_number (const char *, int *num);
1191 static char *single_quote (const char *);
1192 static int nextopt (const char *);
1194 static void redirect (union node *, int);
1195 static void popredir (void);
1196 static int dup_as_newfd (int, int);
1198 static void changepath(const char *newval);
1199 static void getoptsreset(const char *value);
1202 static int parsenleft; /* copy of parsefile->nleft */
1203 static char *parsenextc; /* copy of parsefile->nextc */
1204 static int rootpid; /* pid of main shell */
1205 static int rootshell; /* true if we aren't a child of the main shell */
1207 static const char spcstr[] = " ";
1208 static const char snlfmt[] = "%s\n";
1210 static int sstrnleft;
1211 static int herefd = -1;
1213 static struct localvar *localvars;
1215 static struct var vifs;
1216 static struct var vmail;
1217 static struct var vmpath;
1218 static struct var vpath;
1219 static struct var vps1;
1220 static struct var vps2;
1221 static struct var voptind;
1222 #ifdef CONFIG_LOCALE_SUPPORT
1223 static struct var vlc_all;
1224 static struct var vlc_ctype;
1231 void (*func) (const char *);
1234 static const char defpathvar[] =
1235 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1236 #define defpath (defpathvar + 5)
1239 static const char defifsvar[] = "IFS= \t\n";
1240 #define defifs (defifsvar + 4)
1242 static const char defifs[] = " \t\n";
1245 static const struct varinit varinit[] = {
1247 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1249 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1252 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1254 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1256 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1259 * vps1 depends on uid
1261 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1263 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1265 #ifdef CONFIG_LOCALE_SUPPORT
1266 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1268 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1277 static struct var *vartab[VTABSIZE];
1280 * The following macros access the values of the above variables.
1281 * They have to skip over the name. They return the null string
1282 * for unset variables.
1285 #define ifsval() (vifs.text + 4)
1286 #define ifsset() ((vifs.flags & VUNSET) == 0)
1287 #define mailval() (vmail.text + 5)
1288 #define mpathval() (vmpath.text + 9)
1289 #define pathval() (vpath.text + 5)
1290 #define ps1val() (vps1.text + 4)
1291 #define ps2val() (vps2.text + 4)
1292 #define optindval() (voptind.text + 7)
1294 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1296 static void initvar (void);
1297 static void setvar (const char *, const char *, int);
1298 static void setvareq (char *, int);
1299 static void listsetvar (struct strlist *);
1300 static const char *lookupvar (const char *);
1301 static const char *bltinlookup (const char *);
1302 static char **environment (void);
1303 static int showvarscmd (int, char **);
1304 static void mklocal (char *);
1305 static void poplocalvars (void);
1306 static int unsetvar (const char *);
1307 static int varequal (const char *, const char *);
1310 static char *arg0; /* value of $0 */
1311 static struct shparam shellparam; /* current positional parameters */
1312 static char **argptr; /* argument list for builtin commands */
1313 static char *optionarg; /* set by nextopt (like getopt) */
1314 static char *optptr; /* used by nextopt */
1315 static char *minusc; /* argument to -c option */
1320 #define ALIASINUSE 1
1332 static struct alias *atab[ATABSIZE];
1334 static void setalias (char *, char *);
1335 static struct alias **hashalias (const char *);
1336 static struct alias *freealias (struct alias *);
1337 static struct alias **__lookupalias (const char *);
1343 struct alias *ap, **app;
1345 app = __lookupalias(name);
1349 if (!(ap->flag & ALIASINUSE)) {
1352 ap->val = savestr(val);
1353 ap->flag &= ~ALIASDEAD;
1356 ap = ckmalloc(sizeof (struct alias));
1357 ap->name = savestr(name);
1358 ap->val = savestr(val);
1371 app = __lookupalias(name);
1375 *app = freealias(*app);
1386 struct alias *ap, **app;
1390 for (i = 0; i < ATABSIZE; i++) {
1392 for (ap = *app; ap; ap = *app) {
1393 *app = freealias(*app);
1402 static struct alias *
1403 lookupalias(const char *name, int check)
1405 struct alias *ap = *__lookupalias(name);
1407 if (check && ap && (ap->flag & ALIASINUSE))
1413 printalias(const struct alias *ap) {
1416 p = single_quote(ap->val);
1417 printf("alias %s=%s\n", ap->name, p);
1423 * TODO - sort output
1426 aliascmd(int argc, char **argv)
1435 for (i = 0; i < ATABSIZE; i++)
1436 for (ap = atab[i]; ap; ap = ap->next) {
1441 while ((n = *++argv) != NULL) {
1442 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1443 if ((ap = *__lookupalias(n)) == NULL) {
1444 out2fmt("%s: %s not found\n", "alias", n);
1459 unaliascmd(int argc, char **argv)
1463 while ((i = nextopt("a")) != '\0') {
1469 for (i = 0; *argptr; argptr++) {
1470 if (unalias(*argptr)) {
1471 out2fmt("%s: %s not found\n", "unalias", *argptr);
1479 static struct alias **
1483 unsigned int hashval;
1488 return &atab[hashval % ATABSIZE];
1491 static struct alias *
1492 freealias(struct alias *ap) {
1495 if (ap->flag & ALIASINUSE) {
1496 ap->flag |= ALIASDEAD;
1508 static struct alias **
1509 __lookupalias(const char *name) {
1510 struct alias **app = hashalias(name);
1512 for (; *app; app = &(*app)->next) {
1513 if (equal(name, (*app)->name)) {
1522 #ifdef ASH_MATH_SUPPORT
1523 /* The generated file arith.c has been replaced with a custom hand
1524 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1525 * This is now part of libbb, so that it can be used by all the shells
1527 static void expari (int);
1530 static char *trap[NSIG]; /* trap handler commands */
1531 static char sigmode[NSIG - 1]; /* current value of signal */
1532 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1533 static int pendingsigs; /* indicates some signal received */
1536 * This file was generated by the mkbuiltins program.
1540 static int bgcmd (int, char **);
1541 static int fgcmd (int, char **);
1542 static int killcmd (int, char **);
1544 static int bltincmd (int, char **);
1545 static int cdcmd (int, char **);
1546 static int breakcmd (int, char **);
1548 static int commandcmd (int, char **);
1550 static int dotcmd (int, char **);
1551 static int evalcmd (int, char **);
1552 static int execcmd (int, char **);
1553 static int exitcmd (int, char **);
1554 static int exportcmd (int, char **);
1555 static int histcmd (int, char **);
1556 static int hashcmd (int, char **);
1557 static int helpcmd (int, char **);
1558 static int jobscmd (int, char **);
1559 static int localcmd (int, char **);
1560 static int pwdcmd (int, char **);
1561 static int readcmd (int, char **);
1562 static int returncmd (int, char **);
1563 static int setcmd (int, char **);
1564 static int setvarcmd (int, char **);
1565 static int shiftcmd (int, char **);
1566 static int trapcmd (int, char **);
1567 static int umaskcmd (int, char **);
1569 static int aliascmd (int, char **);
1570 static int unaliascmd (int, char **);
1572 static int unsetcmd (int, char **);
1573 static int waitcmd (int, char **);
1574 static int ulimitcmd (int, char **);
1575 static int timescmd (int, char **);
1576 #ifdef ASH_MATH_SUPPORT
1577 static int letcmd (int, char **);
1579 static int typecmd (int, char **);
1581 static int getoptscmd (int, char **);
1585 static int true_main (int, char **);
1587 #ifndef CONFIG_FALSE
1588 static int false_main (int, char **);
1591 static void setpwd (const char *, int);
1594 #define BUILTIN_NOSPEC "0"
1595 #define BUILTIN_SPECIAL "1"
1596 #define BUILTIN_REGULAR "2"
1597 #define BUILTIN_ASSIGN "4"
1598 #define BUILTIN_SPEC_ASSG "5"
1599 #define BUILTIN_REG_ASSG "6"
1601 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1602 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1603 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1607 int (*const builtinfunc) (int, char **);
1612 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1613 * the binary search in find_builtin() will stop working. If you value
1614 * your kneecaps, you'll be sure to *make sure* that any changes made
1615 * to this array result in the listing remaining in ascii order. You
1618 static const struct builtincmd builtincmds[] = {
1619 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1620 { BUILTIN_SPECIAL ":", true_main },
1622 { BUILTIN_REG_ASSG "alias", aliascmd },
1625 { BUILTIN_REGULAR "bg", bgcmd },
1627 { BUILTIN_SPECIAL "break", breakcmd },
1628 { BUILTIN_SPECIAL "builtin", bltincmd },
1629 { BUILTIN_REGULAR "cd", cdcmd },
1630 { BUILTIN_NOSPEC "chdir", cdcmd },
1632 { BUILTIN_REGULAR "command", commandcmd },
1634 { BUILTIN_SPECIAL "continue", breakcmd },
1635 { BUILTIN_SPECIAL "eval", evalcmd },
1636 { BUILTIN_SPECIAL "exec", execcmd },
1637 { BUILTIN_SPECIAL "exit", exitcmd },
1638 { BUILTIN_SPEC_ASSG "export", exportcmd },
1639 { BUILTIN_REGULAR "false", false_main },
1640 { BUILTIN_REGULAR "fc", histcmd },
1642 { BUILTIN_REGULAR "fg", fgcmd },
1645 { BUILTIN_REGULAR "getopts", getoptscmd },
1647 { BUILTIN_NOSPEC "hash", hashcmd },
1648 { BUILTIN_NOSPEC "help", helpcmd },
1649 { BUILTIN_REGULAR "jobs", jobscmd },
1651 { BUILTIN_REGULAR "kill", killcmd },
1653 #ifdef ASH_MATH_SUPPORT
1654 { BUILTIN_REGULAR "let", letcmd },
1656 { BUILTIN_ASSIGN "local", localcmd },
1657 { BUILTIN_NOSPEC "pwd", pwdcmd },
1658 { BUILTIN_REGULAR "read", readcmd },
1659 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1660 { BUILTIN_SPECIAL "return", returncmd },
1661 { BUILTIN_SPECIAL "set", setcmd },
1662 { BUILTIN_NOSPEC "setvar", setvarcmd },
1663 { BUILTIN_SPECIAL "shift", shiftcmd },
1664 { BUILTIN_SPECIAL "times", timescmd },
1665 { BUILTIN_SPECIAL "trap", trapcmd },
1666 { BUILTIN_REGULAR "true", true_main },
1667 { BUILTIN_NOSPEC "type", typecmd },
1668 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1669 { BUILTIN_REGULAR "umask", umaskcmd },
1671 { BUILTIN_REGULAR "unalias", unaliascmd },
1673 { BUILTIN_SPECIAL "unset", unsetcmd },
1674 { BUILTIN_REGULAR "wait", waitcmd },
1676 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1678 #define DOTCMD &builtincmds[0]
1679 static struct builtincmd *BLTINCMD;
1680 static struct builtincmd *EXECCMD;
1681 static struct builtincmd *EVALCMD;
1684 #define JOBSTOPPED 1 /* all procs are stopped */
1685 #define JOBDONE 2 /* all procs are completed */
1688 * A job structure contains information about a job. A job is either a
1689 * single process or a set of processes contained in a pipeline. In the
1690 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1695 pid_t pid; /* process id */
1696 int status; /* status flags (defined above) */
1697 char *cmd; /* text of command being run */
1701 static int job_warning; /* user was warned about stopped jobs */
1704 static void setjobctl(int enable);
1706 #define setjobctl(on) /* do nothing */
1711 struct procstat ps0; /* status of process */
1712 struct procstat *ps; /* status or processes when more than one */
1713 short nprocs; /* number of processes */
1714 short pgrp; /* process group of this job */
1715 char state; /* true if job is finished */
1716 char used; /* true if this entry is in used */
1717 char changed; /* true if status has changed */
1719 char jobctl; /* job running under job control */
1723 static struct job *jobtab; /* array of jobs */
1724 static int njobs; /* size of array */
1725 static int backgndpid = -1; /* pid of last background process */
1727 static int initialpgrp; /* pgrp of shell on invocation */
1728 static int curjob; /* current job */
1731 static int intreceived;
1733 static struct job *makejob (const union node *, int);
1734 static int forkshell (struct job *, const union node *, int);
1735 static int waitforjob (struct job *);
1737 static int docd (char *, int);
1738 static void updatepwd (const char *);
1739 static void getpwd (void);
1741 static char *padvance (const char **, const char *);
1743 static char nullstr[1]; /* zero length string */
1744 static char *curdir = nullstr; /* current working directory */
1758 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1759 error("HOME not set");
1762 if (dest[0] == '-' && dest[1] == '\0') {
1763 dest = bltinlookup("OLDPWD");
1764 if (!dest || !*dest) {
1773 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1775 while ((p = padvance(&path, dest)) != NULL) {
1776 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1781 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1783 print = strcmp(p, dest);
1785 if (docd(p, print) >= 0)
1790 error("can't cd to %s", dest);
1796 * Actually do the chdir. In an interactive shell, print the
1797 * directory name if "print" is nonzero.
1801 docd(char *dest, int print)
1803 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1805 if (chdir(dest) < 0) {
1812 printf(snlfmt, curdir);
1818 * Update curdir (the name of the current directory) in response to a
1819 * cd command. We also call hashcd to let the routines in exec.c know
1820 * that the current directory has changed.
1823 static void hashcd (void);
1826 updatepwd(const char *dir)
1828 hashcd(); /* update command hash table */
1830 /* If our argument is NULL, we don't know the current directory */
1831 if (dir == NULL || curdir == nullstr) {
1840 pwdcmd(int argc, char **argv)
1842 printf(snlfmt, curdir);
1846 /* Ask system the current directory */
1850 curdir = xgetcwd(0);
1856 setpwd(const char *val, int setold)
1861 setvar("OLDPWD", curdir, VEXPORT);
1864 if (curdir != nullstr) {
1865 if(val!=NULL && *val != '/')
1866 val = cated = concat_path_file(curdir, val);
1872 curdir = simplify_path(val);
1875 setvar("PWD", curdir, VEXPORT);
1879 * Errors and exceptions.
1883 * Code to handle exceptions in C.
1887 * We enclose jmp_buf in a structure so that we can declare pointers to
1888 * jump locations. The global variable handler contains the location to
1889 * jump to when an exception occurs, and the global variable exception
1890 * contains a code identifying the exeception. To implement nested
1891 * exception handlers, the user should save the value of handler on entry
1892 * to an inner scope, set handler to point to a jmploc structure for the
1893 * inner scope, and restore handler on exit from the scope.
1901 #define EXINT 0 /* SIGINT received */
1902 #define EXERROR 1 /* a generic error */
1903 #define EXSHELLPROC 2 /* execute a shell procedure */
1904 #define EXEXEC 3 /* command execution failed */
1906 static struct jmploc *handler;
1907 static int exception;
1909 static void exverror (int, const char *, va_list)
1910 __attribute__((__noreturn__));
1913 * Called to raise an exception. Since C doesn't include exceptions, we
1914 * just do a longjmp to the exception handler. The type of exception is
1915 * stored in the global variable "exception".
1918 static void exraise (int) __attribute__((__noreturn__));
1924 if (handler == NULL)
1929 longjmp(handler->loc, 1);
1934 * Called from trap.c when a SIGINT is received. (If the user specifies
1935 * that SIGINT is to be trapped or ignored using the trap builtin, then
1936 * this routine is not called.) Suppressint is nonzero when interrupts
1937 * are held using the INTOFF macro. The call to _exit is necessary because
1938 * there is a short period after a fork before the signal handlers are
1939 * set to the appropriate value for the child. (The test for iflag is
1940 * just defensive programming.)
1952 sigemptyset(&mysigset);
1953 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1954 if (rootshell && iflag)
1957 signal(SIGINT, SIG_DFL);
1964 static char *commandname; /* currently executing command */
1967 * Exverror is called to raise the error exception. If the first argument
1968 * is not NULL then error prints an error message using printf style
1969 * formatting. It then raises the error exception.
1972 exverror(int cond, const char *msg, va_list ap)
1979 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1981 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1985 out2fmt("%s: ", commandname);
1986 vfprintf(stderr, msg, ap);
1995 error(const char *msg, ...)
1999 exverror(EXERROR, msg, ap);
2006 exerror(int cond, const char *msg, ...)
2010 exverror(cond, msg, ap);
2018 * Table of error messages.
2022 short errcode; /* error number */
2023 char action; /* operation which encountered the error */
2027 * Types of operations (passed to the errmsg routine).
2030 #define E_OPEN 01 /* opening a file */
2031 #define E_CREAT 02 /* creating a file */
2032 #define E_EXEC 04 /* executing a program */
2034 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2036 static const struct errname errormsg[] = {
2041 { ENOENT, E_CREAT },
2043 { ENOTDIR, E_OPEN },
2044 { ENOTDIR, E_CREAT },
2045 { ENOTDIR, E_EXEC },
2047 { EEXIST, E_CREAT },
2086 { ELIBACC, E_EXEC },
2090 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2093 * Return a string describing an error. The returned string may be a
2094 * pointer to a static buffer that will be overwritten on the next call.
2095 * Action describes the operation that got the error.
2099 errmsg(int e, int action)
2101 struct errname const *ep;
2102 static char buf[12];
2104 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2105 if (ep->errcode == e && (ep->action & action) != 0)
2109 snprintf(buf, sizeof buf, "error %d", e);
2114 #ifdef ASH_OPTIMIZE_FOR_SIZE
2117 if (--suppressint == 0 && intpending) {
2121 static void forceinton (void) {
2128 /* flags in argument to evaltree */
2129 #define EV_EXIT 01 /* exit after evaluating tree */
2130 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2131 #define EV_BACKCMD 04 /* command executing within back quotes */
2133 static int evalskip; /* set if we are skipping commands */
2134 static int skipcount; /* number of levels to skip */
2135 static int loopnest; /* current loop nesting level */
2136 static int funcnest; /* depth of function calls */
2139 static struct strlist *cmdenviron; /* environment for builtin command */
2140 static int exitstatus; /* exit status of last command */
2141 static int oexitstatus; /* saved exit status */
2143 static void evalsubshell (const union node *, int);
2144 static void expredir (union node *);
2145 static void prehash (union node *);
2146 static void eprintlist (struct strlist *);
2148 static union node *parsecmd(int);
2150 * Called to reset things after an exception.
2154 * The eval commmand.
2156 static void evalstring (char *, int);
2170 STARTSTACKSTR(concat);
2174 STPUTC(*p++, concat);
2175 if ((p = *ap++) == NULL)
2177 STPUTC(' ', concat);
2179 STPUTC('\0', concat);
2180 p = grabstackstr(concat);
2182 evalstring(p, EV_TESTED);
2188 * Execute a command or commands contained in a string.
2191 static void evaltree (union node *, int);
2192 static void setinputstring (char *);
2193 static void popfile (void);
2194 static void setstackmark(struct stackmark *mark);
2195 static void popstackmark(struct stackmark *mark);
2199 evalstring(char *s, int flag)
2202 struct stackmark smark;
2204 setstackmark(&smark);
2206 while ((n = parsecmd(0)) != NEOF) {
2208 popstackmark(&smark);
2211 popstackmark(&smark);
2214 static struct builtincmd *find_builtin (const char *);
2215 static void expandarg (union node *, struct arglist *, int);
2216 static void calcsize (const union node *);
2217 static union node *copynode (const union node *);
2220 * Make a copy of a parse tree.
2223 static int funcblocksize; /* size of structures in function */
2224 static int funcstringsize; /* size of strings in node */
2225 static pointer funcblock; /* block to allocate function from */
2226 static char *funcstring; /* block to allocate strings from */
2229 static inline union node *
2230 copyfunc(union node *n)
2237 funcblock = ckmalloc(funcblocksize + funcstringsize);
2238 funcstring = (char *) funcblock + funcblocksize;
2243 * Free a parse tree.
2247 freefunc(union node *n)
2255 * Add a new command entry, replacing any existing command entry for
2260 addcmdentry(char *name, struct cmdentry *entry)
2262 struct tblentry *cmdp;
2265 cmdp = cmdlookup(name, 1);
2266 if (cmdp->cmdtype == CMDFUNCTION) {
2267 freefunc(cmdp->param.func);
2269 cmdp->cmdtype = entry->cmdtype;
2270 cmdp->param = entry->u;
2275 evalloop(const union node *n, int flags)
2282 evaltree(n->nbinary.ch1, EV_TESTED);
2284 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2288 if (evalskip == SKIPBREAK && --skipcount <= 0)
2292 if (n->type == NWHILE) {
2293 if (exitstatus != 0)
2296 if (exitstatus == 0)
2299 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2300 status = exitstatus;
2305 exitstatus = status;
2309 evalfor(const union node *n, int flags)
2311 struct arglist arglist;
2314 struct stackmark smark;
2316 setstackmark(&smark);
2317 arglist.lastp = &arglist.list;
2318 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2319 oexitstatus = exitstatus;
2320 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2324 *arglist.lastp = NULL;
2328 for (sp = arglist.list ; sp ; sp = sp->next) {
2329 setvar(n->nfor.var, sp->text, 0);
2330 evaltree(n->nfor.body, flags & EV_TESTED);
2332 if (evalskip == SKIPCONT && --skipcount <= 0) {
2336 if (evalskip == SKIPBREAK && --skipcount <= 0)
2343 popstackmark(&smark);
2347 evalcase(const union node *n, int flags)
2351 struct arglist arglist;
2352 struct stackmark smark;
2354 setstackmark(&smark);
2355 arglist.lastp = &arglist.list;
2356 oexitstatus = exitstatus;
2357 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2358 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2359 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2360 if (casematch(patp, arglist.list->text)) {
2361 if (evalskip == 0) {
2362 evaltree(cp->nclist.body, flags);
2369 popstackmark(&smark);
2373 * Evaluate a pipeline. All the processes in the pipeline are children
2374 * of the process creating the pipeline. (This differs from some versions
2375 * of the shell, which make the last process in a pipeline the parent
2379 static inline void evalpipe(union node *n)
2382 struct nodelist *lp;
2387 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2389 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2392 jp = makejob(n, pipelen);
2394 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2398 if (pipe(pip) < 0) {
2400 error("Pipe call failed");
2403 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2407 dup_as_newfd(prevfd, 0);
2419 dup_as_newfd(pip[1], 1);
2423 evaltree(lp->n, EV_EXIT);
2431 if (n->npipe.backgnd == 0) {
2433 exitstatus = waitforjob(jp);
2434 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2439 static void find_command (const char *, struct cmdentry *, int, const char *);
2442 isassignment(const char *word) {
2443 if (!is_name(*word)) {
2448 } while (is_in_name(*word));
2449 return *word == '=';
2454 evalcommand(union node *cmd, int flags)
2456 struct stackmark smark;
2458 struct arglist arglist;
2459 struct arglist varlist;
2465 struct cmdentry cmdentry;
2467 char *volatile savecmdname;
2468 volatile struct shparam saveparam;
2469 struct localvar *volatile savelocalvars;
2473 const struct builtincmd *firstbltin;
2474 struct jmploc *volatile savehandler;
2475 struct jmploc jmploc;
2477 /* Avoid longjmp clobbering */
2484 /* First expand the arguments. */
2485 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2486 setstackmark(&smark);
2487 arglist.lastp = &arglist.list;
2488 varlist.lastp = &varlist.list;
2490 oexitstatus = exitstatus;
2493 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2494 expandarg(argp, &varlist, EXP_VARTILDE);
2497 argp = cmd->ncmd.args; argp && !arglist.list;
2498 argp = argp->narg.next
2500 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2503 struct builtincmd *bcmd;
2505 bcmd = find_builtin(arglist.list->text);
2506 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2507 for (; argp; argp = argp->narg.next) {
2508 if (pseudovarflag && isassignment(argp->narg.text)) {
2509 expandarg(argp, &arglist, EXP_VARTILDE);
2512 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2515 *arglist.lastp = NULL;
2516 *varlist.lastp = NULL;
2517 expredir(cmd->ncmd.redirect);
2519 for (sp = arglist.list ; sp ; sp = sp->next)
2521 argv = stalloc(sizeof (char *) * (argc + 1));
2523 for (sp = arglist.list ; sp ; sp = sp->next) {
2524 TRACE(("evalcommand arg: %s\n", sp->text));
2529 if (iflag && funcnest == 0 && argc > 0)
2533 /* Print the command if xflag is set. */
2536 eprintlist(varlist.list);
2537 eprintlist(arglist.list);
2541 /* Now locate the command. */
2543 cmdentry.cmdtype = CMDBUILTIN;
2544 firstbltin = cmdentry.u.cmd = BLTINCMD;
2546 const char *oldpath;
2547 int findflag = DO_ERR;
2551 * Modify the command lookup path, if a PATH= assignment
2554 for (sp = varlist.list ; sp ; sp = sp->next)
2555 if (varequal(sp->text, defpathvar)) {
2556 path = sp->text + 5;
2557 findflag |= DO_BRUTE;
2560 oldfindflag = findflag;
2563 find_command(argv[0], &cmdentry, findflag, path);
2564 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2568 /* implement bltin and command here */
2569 if (cmdentry.cmdtype != CMDBUILTIN) {
2573 firstbltin = cmdentry.u.cmd;
2575 if (cmdentry.u.cmd == BLTINCMD) {
2577 struct builtincmd *bcmd;
2582 if (!(bcmd = find_builtin(*argv))) {
2583 out2fmt("%s: not found\n", *argv);
2587 cmdentry.u.cmd = bcmd;
2588 if (bcmd != BLTINCMD)
2592 if (cmdentry.u.cmd == find_builtin("command")) {
2597 if (*argv[0] == '-') {
2598 if (!equal(argv[0], "-p")) {
2608 findflag |= DO_BRUTE;
2611 findflag = oldfindflag;
2613 findflag |= DO_NOFUN;
2621 /* Fork off a child process if necessary. */
2622 if (cmd->ncmd.backgnd
2623 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2625 jp = makejob(cmd, 1);
2626 mode = cmd->ncmd.backgnd;
2627 if (forkshell(jp, cmd, mode) != 0)
2628 goto parent; /* at end of routine */
2632 /* This is the child process if a fork occurred. */
2633 /* Execute the command. */
2634 if (cmdentry.cmdtype == CMDFUNCTION) {
2636 trputs("Shell function: "); trargs(argv);
2638 exitstatus = oexitstatus;
2639 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2640 saveparam = shellparam;
2641 shellparam.malloc = 0;
2642 shellparam.nparam = argc - 1;
2643 shellparam.p = argv + 1;
2645 savelocalvars = localvars;
2648 if (setjmp(jmploc.loc)) {
2649 if (exception == EXSHELLPROC) {
2650 freeparam((volatile struct shparam *)
2653 saveparam.optind = shellparam.optind;
2654 saveparam.optoff = shellparam.optoff;
2655 freeparam(&shellparam);
2656 shellparam = saveparam;
2659 localvars = savelocalvars;
2660 handler = savehandler;
2661 longjmp(handler->loc, 1);
2663 savehandler = handler;
2665 for (sp = varlist.list ; sp ; sp = sp->next)
2668 evaltree(cmdentry.u.func, flags & EV_TESTED);
2672 localvars = savelocalvars;
2673 saveparam.optind = shellparam.optind;
2674 saveparam.optoff = shellparam.optoff;
2675 freeparam(&shellparam);
2676 shellparam = saveparam;
2677 handler = savehandler;
2680 if (evalskip == SKIPFUNC) {
2684 if (flags & EV_EXIT)
2685 exitshell(exitstatus);
2686 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2688 trputs("builtin command: "); trargs(argv);
2690 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2691 redirect(cmd->ncmd.redirect, mode);
2692 savecmdname = commandname;
2693 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2694 listsetvar(varlist.list);
2696 cmdenviron = varlist.list;
2699 if (setjmp(jmploc.loc)) {
2701 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2704 savehandler = handler;
2706 commandname = argv[0];
2708 optptr = NULL; /* initialize nextopt */
2709 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2713 if (e != EXSHELLPROC) {
2714 commandname = savecmdname;
2715 if (flags & EV_EXIT)
2716 exitshell(exitstatus);
2718 handler = savehandler;
2720 if ((e != EXERROR && e != EXEXEC)
2721 || cmdentry.u.cmd == BLTINCMD
2722 || cmdentry.u.cmd == DOTCMD
2723 || cmdentry.u.cmd == EVALCMD
2724 || cmdentry.u.cmd == EXECCMD)
2728 if (cmdentry.u.cmd != EXECCMD)
2732 trputs("normal command: "); trargs(argv);
2734 redirect(cmd->ncmd.redirect, 0);
2736 for (sp = varlist.list ; sp ; sp = sp->next)
2737 setvareq(sp->text, VEXPORT|VSTACK);
2738 envp = environment();
2739 shellexec(argv, envp, path, cmdentry.u.index);
2743 parent: /* parent process gets here (if we forked) */
2744 if (mode == 0) { /* argument to fork */
2746 exitstatus = waitforjob(jp);
2752 setvar("_", lastarg, 0);
2753 popstackmark(&smark);
2757 * Evaluate a parse tree. The value is left in the global variable
2767 TRACE(("evaltree(NULL) called\n"));
2770 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2773 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2776 evaltree(n->nbinary.ch2, flags);
2779 evaltree(n->nbinary.ch1, EV_TESTED);
2780 if (evalskip || exitstatus != 0)
2782 evaltree(n->nbinary.ch2, flags);
2785 evaltree(n->nbinary.ch1, EV_TESTED);
2786 if (evalskip || exitstatus == 0)
2788 evaltree(n->nbinary.ch2, flags);
2791 expredir(n->nredir.redirect);
2792 redirect(n->nredir.redirect, REDIR_PUSH);
2793 evaltree(n->nredir.n, flags);
2797 evalsubshell(n, flags);
2800 evalsubshell(n, flags);
2803 evaltree(n->nif.test, EV_TESTED);
2806 if (exitstatus == 0)
2807 evaltree(n->nif.ifpart, flags);
2808 else if (n->nif.elsepart)
2809 evaltree(n->nif.elsepart, flags);
2825 struct builtincmd *bcmd;
2826 struct cmdentry entry;
2828 (bcmd = find_builtin(n->narg.text)) &&
2829 IS_BUILTIN_SPECIAL(bcmd)
2831 out2fmt("%s is a special built-in\n", n->narg.text);
2835 entry.cmdtype = CMDFUNCTION;
2836 entry.u.func = copyfunc(n->narg.next);
2837 addcmdentry(n->narg.text, &entry);
2842 evaltree(n->nnot.com, EV_TESTED);
2843 exitstatus = !exitstatus;
2851 evalcommand(n, flags);
2856 printf("Node type = %d\n", n->type);
2865 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2867 exitshell(exitstatus);
2871 * Kick off a subshell to evaluate a tree.
2875 evalsubshell(const union node *n, int flags)
2878 int backgnd = (n->type == NBACKGND);
2880 expredir(n->nredir.redirect);
2882 if (forkshell(jp, n, backgnd) == 0) {
2884 flags &=~ EV_TESTED;
2885 redirect(n->nredir.redirect, 0);
2886 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2890 exitstatus = waitforjob(jp);
2896 * Compute the names of the files in a redirection list.
2899 static void fixredir(union node *n, const char *text, int err);
2902 expredir(union node *n)
2906 for (redir = n ; redir ; redir = redir->nfile.next) {
2908 fn.lastp = &fn.list;
2909 oexitstatus = exitstatus;
2910 switch (redir->type) {
2916 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2917 redir->nfile.expfname = fn.list->text;
2921 if (redir->ndup.vname) {
2922 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2923 fixredir(redir, fn.list->text, 1);
2932 * Execute a command inside back quotes. If it's a builtin command, we
2933 * want to save its output in a block obtained from malloc. Otherwise
2934 * we fork off a subprocess and get the output of the command via a pipe.
2935 * Should be called with interrupts off.
2939 evalbackcmd(union node *n, struct backcmd *result)
2943 struct stackmark smark; /* unnecessary */
2945 setstackmark(&smark);
2956 error("Pipe call failed");
2958 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2963 dup_as_newfd(pip[1], 1);
2967 evaltree(n, EV_EXIT);
2970 result->fd = pip[0];
2973 popstackmark(&smark);
2974 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2975 result->fd, result->buf, result->nleft, result->jp));
2980 * Execute a simple command.
2984 * Search for a command. This is called before we fork so that the
2985 * location of the command will be available in the parent as well as
2986 * the child. The check for "goodname" is an overly conservative
2987 * check that the name will not be subject to expansion.
2994 struct cmdentry entry;
2996 if (n->type == NCMD && n->ncmd.args)
2997 if (goodname(n->ncmd.args->narg.text))
2998 find_command(n->ncmd.args->narg.text, &entry, 0,
3004 * Builtin commands. Builtin commands whose functions are closely
3005 * tied to evaluation are implemented here.
3009 * No command given, or a bltin command with no arguments. Set the
3010 * specified variables.
3014 bltincmd(argc, argv)
3019 * Preserve exitstatus of a previous possible redirection
3027 * Handle break and continue commands. Break, continue, and return are
3028 * all handled by setting the evalskip flag. The evaluation routines
3029 * above all check this flag, and if it is set they start skipping
3030 * commands rather than executing them. The variable skipcount is
3031 * the number of loops to break/continue, or the number of function
3032 * levels to return. (The latter is always 1.) It should probably
3033 * be an error to break out of more loops than exist, but it isn't
3034 * in the standard shell so we don't make it one here.
3038 breakcmd(argc, argv)
3042 int n = argc > 1 ? number(argv[1]) : 1;
3047 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3055 * The return command.
3059 returncmd(argc, argv)
3063 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3066 evalskip = SKIPFUNC;
3071 /* Do what ksh does; skip the rest of the file */
3072 evalskip = SKIPFILE;
3079 #ifndef CONFIG_FALSE
3081 false_main(argc, argv)
3091 true_main(argc, argv)
3100 * Controls whether the shell is interactive or not.
3103 static void setsignal(int signo);
3104 static void chkmail(int silent);
3108 setinteractive(int on)
3110 static int is_interactive;
3111 static int do_banner=0;
3113 if (on == is_interactive)
3119 is_interactive = on;
3120 if (do_banner==0 && is_interactive) {
3121 /* Looks like they want an interactive shell */
3122 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3123 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3124 printf( "Enter 'help' for a list of built-in commands.\n\n");
3133 setinteractive(iflag);
3146 iflag = 0; /* exit on error */
3149 for (sp = cmdenviron; sp ; sp = sp->next)
3150 setvareq(sp->text, VEXPORT|VSTACK);
3151 shellexec(argv + 1, environment(), pathval(), 0);
3157 eprintlist(struct strlist *sp)
3159 for (; sp; sp = sp->next) {
3160 out2fmt(" %s",sp->text);
3165 * Exec a program. Never returns. If you change this routine, you may
3166 * have to change the find_command routine as well.
3169 static const char *pathopt; /* set by padvance */
3172 shellexec(argv, envp, path, idx)
3173 char **argv, **envp;
3180 if (strchr(argv[0], '/') != NULL) {
3181 tryexec(argv[0], argv, envp);
3185 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3186 if (--idx < 0 && pathopt == NULL) {
3187 tryexec(cmdname, argv, envp);
3188 if (errno != ENOENT && errno != ENOTDIR)
3195 /* Map to POSIX errors */
3207 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3212 * Clear traps on a fork.
3218 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3219 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3224 setsignal(tp - trap);
3232 initshellproc(void) {
3258 /* from options.c: */
3262 for (i = 0; i < NOPTS; i++)
3278 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3290 static int preadbuffer(void);
3291 static void pushfile (void);
3294 * Read a character from the script, returning PEOF on end of file.
3295 * Nul characters in the input are silently discarded.
3298 #ifndef ASH_OPTIMIZE_FOR_SIZE
3299 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3303 return pgetc_macro();
3309 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3315 return pgetc_macro();
3321 * Undo the last call to pgetc. Only one character may be pushed back.
3322 * PEOF may be pushed back.
3325 static void pungetc(void)
3334 struct parsefile *pf = parsefile;
3343 parsefile = pf->prev;
3345 parsenleft = parsefile->nleft;
3346 parselleft = parsefile->lleft;
3347 parsenextc = parsefile->nextc;
3348 plinno = parsefile->linno;
3354 * Return to top level.
3359 while (parsefile != &basepf)
3364 * Close the file(s) that the shell is reading commands from. Called
3365 * after a fork is done.
3368 static void closescript(void)
3371 if (parsefile->fd > 0) {
3372 close(parsefile->fd);
3379 * Like setinputfile, but takes an open file descriptor. Call this with
3383 static void setinputfd(int fd, int push)
3385 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3391 while (parsefile->strpush)
3395 if (parsefile->buf == NULL)
3396 parsefile->buf = ckmalloc(BUFSIZ);
3397 parselleft = parsenleft = 0;
3403 * Set the input to take input from a file. If push is set, push the
3404 * old input onto the stack first.
3408 setinputfile(const char *fname, int push)
3414 if ((fd = open(fname, O_RDONLY)) < 0)
3415 error("Can't open %s", fname);
3417 myfileno2 = dup_as_newfd(fd, 10);
3420 error("Out of file descriptors");
3423 setinputfd(fd, push);
3429 tryexec(char *cmd, char **argv, char **envp)
3433 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3437 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3438 name = get_last_path_component(name);
3441 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3444 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3446 run_applet_by_name(name, argc_l, argv);
3448 execve(cmd, argv, envp);
3453 setinputfile(cmd, 0);
3454 commandname = arg0 = savestr(argv[0]);
3456 exraise(EXSHELLPROC);
3461 static char *commandtext (const union node *);
3464 * Do a path search. The variable path (passed by reference) should be
3465 * set to the start of the path before the first call; padvance will update
3466 * this value as it proceeds. Successive calls to padvance will return
3467 * the possible path expansions in sequence. If an option (indicated by
3468 * a percent sign) appears in the path entry then the global variable
3469 * pathopt will be set to point to it; otherwise pathopt will be set to
3473 static const char *pathopt;
3475 static void growstackblock(void);
3479 padvance(const char **path, const char *name)
3489 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3490 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3491 while (stackblocksize() < len)
3495 memcpy(q, start, p - start);
3503 while (*p && *p != ':') p++;
3509 return stalloc(len);
3513 * Wrapper around strcmp for qsort/bsearch/...
3516 pstrcmp(const void *a, const void *b)
3518 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3522 * Find a keyword is in a sorted array.
3525 static const char *const *
3526 findkwd(const char *s)
3528 return bsearch(s, tokname_array + KWDOFFSET,
3529 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3530 sizeof(const char *), pstrcmp);
3534 /*** Command hashing code ***/
3542 struct tblentry **pp;
3543 struct tblentry *cmdp;
3546 struct cmdentry entry;
3549 const struct alias *ap;
3553 while ((c = nextopt("rvV")) != '\0') {
3557 } else if (c == 'v' || c == 'V') {
3561 if (*argptr == NULL) {
3562 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3563 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3564 if (cmdp->cmdtype != CMDBUILTIN) {
3565 printentry(cmdp, verbose);
3572 while ((name = *argptr++) != NULL) {
3573 if ((cmdp = cmdlookup(name, 0)) != NULL
3574 && (cmdp->cmdtype == CMDNORMAL
3575 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3578 /* Then look at the aliases */
3579 if ((ap = lookupalias(name, 0)) != NULL) {
3581 printf("%s is an alias for %s\n", name, ap->val);
3587 /* First look at the keywords */
3588 if (findkwd(name)!=0) {
3590 printf("%s is a shell keyword\n", name);
3592 printf(snlfmt, name);
3596 find_command(name, &entry, DO_ERR, pathval());
3597 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3599 cmdp = cmdlookup(name, 0);
3600 if (cmdp) printentry(cmdp, verbose=='v');
3608 printentry(cmdp, verbose)
3609 struct tblentry *cmdp;
3616 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3617 if (cmdp->cmdtype == CMDNORMAL) {
3618 idx = cmdp->param.index;
3621 name = padvance(&path, cmdp->cmdname);
3623 } while (--idx >= 0);
3626 } else if (cmdp->cmdtype == CMDBUILTIN) {
3628 out1str("a shell builtin");
3629 } else if (cmdp->cmdtype == CMDFUNCTION) {
3632 out1str("a function\n");
3633 name = commandtext(cmdp->param.func);
3634 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3640 error("internal error: cmdtype %d", cmdp->cmdtype);
3643 printf(snlfmt, cmdp->rehash ? "*" : nullstr);
3648 /*** List the available builtins ***/
3651 static int helpcmd(int argc, char** argv)
3655 printf("\nBuilt-in commands:\n-------------------\n");
3656 for (col=0, i=0; i < NUMBUILTINS; i++) {
3657 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3658 builtincmds[i].name+1);
3664 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3666 extern const struct BB_applet applets[];
3667 extern const size_t NUM_APPLETS;
3669 for (i=0; i < NUM_APPLETS; i++) {
3671 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3681 return EXIT_SUCCESS;
3685 * Resolve a command name. If you change this routine, you may have to
3686 * change the shellexec routine as well.
3689 static int prefix (const char *, const char *);
3692 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3694 struct tblentry *cmdp;
3704 struct builtincmd *bcmd;
3706 /* If name contains a slash, don't use the hash table */
3707 if (strchr(name, '/') != NULL) {
3709 while (stat(name, &statb) < 0) {
3710 if (errno != ENOENT && errno != ENOTDIR)
3712 entry->cmdtype = CMDUNKNOWN;
3713 entry->u.index = -1;
3716 entry->cmdtype = CMDNORMAL;
3717 entry->u.index = -1;
3720 entry->cmdtype = CMDNORMAL;
3726 if (act & DO_BRUTE) {
3727 firstchange = path_change(path, &bltin);
3733 /* If name is in the table, and not invalidated by cd, we're done */
3734 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3735 if (cmdp->cmdtype == CMDFUNCTION) {
3736 if (act & DO_NOFUN) {
3741 } else if (act & DO_BRUTE) {
3742 if ((cmdp->cmdtype == CMDNORMAL &&
3743 cmdp->param.index >= firstchange) ||
3744 (cmdp->cmdtype == CMDBUILTIN &&
3745 ((builtinloc < 0 && bltin >= 0) ?
3746 bltin : builtinloc) >= firstchange)) {
3747 /* need to recompute the entry */
3756 bcmd = find_builtin(name);
3757 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3760 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3763 } else if (act & DO_BRUTE) {
3764 if (firstchange == 0) {
3769 /* If %builtin not in path, check for builtin next */
3770 if (regular || (bltin < 0 && bcmd)) {
3773 entry->cmdtype = CMDBUILTIN;
3774 entry->u.cmd = bcmd;
3778 cmdp = cmdlookup(name, 1);
3779 cmdp->cmdtype = CMDBUILTIN;
3780 cmdp->param.cmd = bcmd;
3785 /* We have to search path. */
3786 prev = -1; /* where to start */
3787 if (cmdp && cmdp->rehash) { /* doing a rehash */
3788 if (cmdp->cmdtype == CMDBUILTIN)
3791 prev = cmdp->param.index;
3797 while ((fullname = padvance(&path, name)) != NULL) {
3798 stunalloc(fullname);
3800 if (idx >= firstchange) {
3804 if (prefix("builtin", pathopt)) {
3805 if ((bcmd = find_builtin(name))) {
3809 } else if (!(act & DO_NOFUN) &&
3810 prefix("func", pathopt)) {
3813 continue; /* ignore unimplemented options */
3816 /* if rehash, don't redo absolute path names */
3817 if (fullname[0] == '/' && idx <= prev &&
3818 idx < firstchange) {
3821 TRACE(("searchexec \"%s\": no change\n", name));
3824 while (stat(fullname, &statb) < 0) {
3825 if (errno != ENOENT && errno != ENOTDIR)
3829 e = EACCES; /* if we fail, this will be the error */
3830 if (!S_ISREG(statb.st_mode))
3832 if (pathopt) { /* this is a %func directory */
3833 stalloc(strlen(fullname) + 1);
3834 readcmdfile(fullname);
3835 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3836 error("%s not defined in %s", name, fullname);
3837 stunalloc(fullname);
3840 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3841 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3842 be a function and we're being called with DO_NOFUN */
3844 entry->cmdtype = CMDNORMAL;
3845 entry->u.index = idx;
3849 cmdp = cmdlookup(name, 1);
3850 cmdp->cmdtype = CMDNORMAL;
3851 cmdp->param.index = idx;
3856 /* We failed. If there was an entry for this command, delete it */
3857 if (cmdp && updatetbl)
3860 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3861 entry->cmdtype = CMDUNKNOWN;
3866 entry->cmdtype = cmdp->cmdtype;
3867 entry->u = cmdp->param;
3873 * Search the table of builtin commands.
3877 bstrcmp(const void *name, const void *b)
3879 return strcmp((const char *)name, (*(const char *const *) b)+1);
3882 static struct builtincmd *
3883 find_builtin(const char *name)
3885 struct builtincmd *bp;
3887 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3895 * Called when a cd is done. Marks all commands so the next time they
3896 * are executed they will be rehashed.
3901 struct tblentry **pp;
3902 struct tblentry *cmdp;
3904 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3905 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3906 if (cmdp->cmdtype == CMDNORMAL
3907 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3916 * Called before PATH is changed. The argument is the new value of PATH;
3917 * pathval() still returns the old value at this point. Called with
3922 changepath(const char *newval)
3927 firstchange = path_change(newval, &bltin);
3928 if (builtinloc < 0 && bltin >= 0)
3929 builtinloc = bltin; /* zap builtins */
3930 clearcmdentry(firstchange);
3936 * Clear out command entries. The argument specifies the first entry in
3937 * PATH which has changed.
3941 clearcmdentry(firstchange)
3944 struct tblentry **tblp;
3945 struct tblentry **pp;
3946 struct tblentry *cmdp;
3949 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3951 while ((cmdp = *pp) != NULL) {
3952 if ((cmdp->cmdtype == CMDNORMAL &&
3953 cmdp->param.index >= firstchange)
3954 || (cmdp->cmdtype == CMDBUILTIN &&
3955 builtinloc >= firstchange)) {
3968 * Delete all functions.
3973 struct tblentry **tblp;
3974 struct tblentry **pp;
3975 struct tblentry *cmdp;
3978 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3980 while ((cmdp = *pp) != NULL) {
3981 if (cmdp->cmdtype == CMDFUNCTION) {
3983 freefunc(cmdp->param.func);
3996 * Locate a command in the command hash table. If "add" is nonzero,
3997 * add the command to the table if it is not already present. The
3998 * variable "lastcmdentry" is set to point to the address of the link
3999 * pointing to the entry, so that delete_cmd_entry can delete the
4003 static struct tblentry **lastcmdentry;
4005 static struct tblentry *
4006 cmdlookup(const char *name, int add)
4010 struct tblentry *cmdp;
4011 struct tblentry **pp;
4018 pp = &cmdtable[hashval % CMDTABLESIZE];
4019 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4020 if (equal(cmdp->cmdname, name))
4024 if (add && cmdp == NULL) {
4026 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4027 + strlen(name) + 1);
4029 cmdp->cmdtype = CMDUNKNOWN;
4031 strcpy(cmdp->cmdname, name);
4039 * Delete the command entry returned on the last lookup.
4043 delete_cmd_entry() {
4044 struct tblentry *cmdp;
4047 cmdp = *lastcmdentry;
4048 *lastcmdentry = cmdp->next;
4057 static const unsigned char nodesize[26] = {
4058 ALIGN(sizeof (struct nbinary)),
4059 ALIGN(sizeof (struct ncmd)),
4060 ALIGN(sizeof (struct npipe)),
4061 ALIGN(sizeof (struct nredir)),
4062 ALIGN(sizeof (struct nredir)),
4063 ALIGN(sizeof (struct nredir)),
4064 ALIGN(sizeof (struct nbinary)),
4065 ALIGN(sizeof (struct nbinary)),
4066 ALIGN(sizeof (struct nif)),
4067 ALIGN(sizeof (struct nbinary)),
4068 ALIGN(sizeof (struct nbinary)),
4069 ALIGN(sizeof (struct nfor)),
4070 ALIGN(sizeof (struct ncase)),
4071 ALIGN(sizeof (struct nclist)),
4072 ALIGN(sizeof (struct narg)),
4073 ALIGN(sizeof (struct narg)),
4074 ALIGN(sizeof (struct nfile)),
4075 ALIGN(sizeof (struct nfile)),
4076 ALIGN(sizeof (struct nfile)),
4077 ALIGN(sizeof (struct nfile)),
4078 ALIGN(sizeof (struct nfile)),
4079 ALIGN(sizeof (struct ndup)),
4080 ALIGN(sizeof (struct ndup)),
4081 ALIGN(sizeof (struct nhere)),
4082 ALIGN(sizeof (struct nhere)),
4083 ALIGN(sizeof (struct nnot)),
4089 * Delete a function if it exists.
4093 unsetfunc(char *name)
4095 struct tblentry *cmdp;
4097 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4098 freefunc(cmdp->param.func);
4105 * Locate and print what a word is...
4109 typecmd(int argc, char **argv)
4117 for (i = 1; i < argc; i++) {
4118 argv_a[0] = argv[i];
4121 err |= hashcmd(argc, argv);
4128 commandcmd(argc, argv)
4133 int default_path = 0;
4134 int verify_only = 0;
4135 int verbose_verify_only = 0;
4137 while ((c = nextopt("pvV")) != '\0')
4146 verbose_verify_only = 1;
4150 if (default_path + verify_only + verbose_verify_only > 1 ||
4153 "command [-p] command [arg ...]\n"
4154 "command {-v|-V} command\n");
4158 if (verify_only || verbose_verify_only) {
4162 argv_a[0] = *argptr;
4164 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4165 return hashcmd(argc, argv);
4173 path_change(newval, bltin)
4177 const char *old, *new;
4183 firstchange = 9999; /* assume no change */
4189 if ((*old == '\0' && *new == ':')
4190 || (*old == ':' && *new == '\0'))
4192 old = new; /* ignore subsequent differences */
4196 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4203 if (builtinloc >= 0 && *bltin < 0)
4208 * Routines to expand arguments to commands. We have to deal with
4209 * backquotes, shell variables, and file metacharacters.
4214 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4215 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4218 * Structure specifying which parts of the string should be searched
4219 * for IFS characters.
4223 struct ifsregion *next; /* next region in list */
4224 int begoff; /* offset of start of region */
4225 int endoff; /* offset of end of region */
4226 int nulonly; /* search for nul bytes only */
4230 static char *expdest; /* output of current string */
4231 static struct nodelist *argbackq; /* list of back quote expressions */
4232 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4233 static struct ifsregion *ifslastp; /* last struct in list */
4234 static struct arglist exparg; /* holds expanded arg list */
4236 static void argstr (char *, int);
4237 static char *exptilde (char *, int);
4238 static void expbackq (union node *, int, int);
4239 static int subevalvar (char *, char *, int, int, int, int, int);
4240 static int varisset (char *, int);
4241 static void strtodest (const char *, int, int);
4242 static void varvalue (char *, int, int);
4243 static void recordregion (int, int, int);
4244 static void removerecordregions (int);
4245 static void ifsbreakup (char *, struct arglist *);
4246 static void ifsfree (void);
4247 static void expandmeta (struct strlist *, int);
4248 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4249 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4250 #if !defined(GLOB_BROKEN)
4251 static void addglob (const glob_t *);
4254 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4255 static void expmeta (char *, char *);
4257 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4258 static struct strlist *expsort (struct strlist *);
4259 static struct strlist *msort (struct strlist *, int);
4261 static int patmatch (char *, char *, int);
4262 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4263 static int patmatch2 (char *, char *, int);
4265 static int pmatch (char *, char *, int);
4266 #define patmatch2 patmatch
4268 static char *cvtnum (int, char *);
4271 * Expand shell variables and backquotes inside a here document.
4274 /* arg: the document, fd: where to write the expanded version */
4276 expandhere(union node *arg, int fd)
4279 expandarg(arg, (struct arglist *)NULL, 0);
4280 xwrite(fd, stackblock(), expdest - stackblock());
4285 * Perform variable substitution and command substitution on an argument,
4286 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4287 * perform splitting and file name expansion. When arglist is NULL, perform
4288 * here document expansion.
4292 expandarg(arg, arglist, flag)
4294 struct arglist *arglist;
4300 argbackq = arg->narg.backquote;
4301 STARTSTACKSTR(expdest);
4302 ifsfirst.next = NULL;
4304 argstr(arg->narg.text, flag);
4305 if (arglist == NULL) {
4306 return; /* here document expanded */
4308 STPUTC('\0', expdest);
4309 p = grabstackstr(expdest);
4310 exparg.lastp = &exparg.list;
4314 if (flag & EXP_FULL) {
4315 ifsbreakup(p, &exparg);
4316 *exparg.lastp = NULL;
4317 exparg.lastp = &exparg.list;
4318 expandmeta(exparg.list, flag);
4320 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4322 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4325 exparg.lastp = &sp->next;
4328 *exparg.lastp = NULL;
4330 *arglist->lastp = exparg.list;
4331 arglist->lastp = exparg.lastp;
4337 * Expand a variable, and return a pointer to the next character in the
4341 static inline char * evalvar(char *p, int flag)
4354 int quotes = flag & (EXP_FULL | EXP_CASE);
4357 subtype = varflags & VSTYPE;
4362 p = strchr(p, '=') + 1;
4363 again: /* jump here after setting a variable with ${var=text} */
4365 set = varisset(var, varflags & VSNUL);
4368 val = lookupvar(var);
4369 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4376 startloc = expdest - stackblock();
4377 if (set && subtype != VSPLUS) {
4378 /* insert the value of the variable */
4380 varvalue(var, varflags & VSQUOTE, flag);
4381 if (subtype == VSLENGTH) {
4382 varlen = expdest - stackblock() - startloc;
4383 STADJUST(-varlen, expdest);
4386 if (subtype == VSLENGTH) {
4387 varlen = strlen(val);
4391 varflags & VSQUOTE ?
4392 DQSYNTAX : BASESYNTAX,
4399 if (subtype == VSPLUS)
4402 easy = ((varflags & VSQUOTE) == 0 ||
4403 (*var == '@' && shellparam.nparam != 1));
4408 expdest = cvtnum(varlen, expdest);
4415 recordregion(startloc, expdest - stackblock(),
4416 varflags & VSQUOTE);
4432 case VSTRIMRIGHTMAX:
4436 * Terminate the string and start recording the pattern
4439 STPUTC('\0', expdest);
4440 patloc = expdest - stackblock();
4441 if (subevalvar(p, NULL, patloc, subtype,
4442 startloc, varflags, quotes) == 0) {
4443 int amount = (expdest - stackblock() - patloc) + 1;
4444 STADJUST(-amount, expdest);
4446 /* Remove any recorded regions beyond start of variable */
4447 removerecordregions(startloc);
4453 if (subevalvar(p, var, 0, subtype, startloc,
4454 varflags, quotes)) {
4457 * Remove any recorded regions beyond
4460 removerecordregions(startloc);
4475 if (subtype != VSNORMAL) { /* skip to end of alternative */
4478 if ((c = *p++) == CTLESC)
4480 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4482 argbackq = argbackq->next;
4483 } else if (c == CTLVAR) {
4484 if ((*p++ & VSTYPE) != VSNORMAL)
4486 } else if (c == CTLENDVAR) {
4497 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4498 * characters to allow for further processing. Otherwise treat
4499 * $@ like $* since no splitting will be performed.
4508 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4511 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4512 p = exptilde(p, flag);
4516 case CTLENDVAR: /* ??? */
4519 /* "$@" syntax adherence hack */
4520 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4522 if ((flag & EXP_FULL) != 0)
4532 p = evalvar(p, flag);
4535 case CTLBACKQ|CTLQUOTE:
4536 expbackq(argbackq->n, c & CTLQUOTE, flag);
4537 argbackq = argbackq->next;
4539 #ifdef ASH_MATH_SUPPORT
4547 * sort of a hack - expand tildes in variable
4548 * assignments (after the first '=' and after ':'s).
4551 if (flag & EXP_VARTILDE && *p == '~') {
4558 p = exptilde(p, flag);
4574 char c, *startp = p;
4577 int quotes = flag & (EXP_FULL | EXP_CASE);
4579 while ((c = *p) != '\0') {
4586 if (flag & EXP_VARTILDE)
4596 if (*(startp+1) == '\0') {
4597 if ((home = lookupvar("HOME")) == NULL)
4600 if ((pw = getpwnam(startp+1)) == NULL)
4607 strtodest(home, SQSYNTAX, quotes);
4616 removerecordregions(int endoff)
4618 if (ifslastp == NULL)
4621 if (ifsfirst.endoff > endoff) {
4622 while (ifsfirst.next != NULL) {
4623 struct ifsregion *ifsp;
4625 ifsp = ifsfirst.next->next;
4626 ckfree(ifsfirst.next);
4627 ifsfirst.next = ifsp;
4630 if (ifsfirst.begoff > endoff)
4633 ifslastp = &ifsfirst;
4634 ifsfirst.endoff = endoff;
4639 ifslastp = &ifsfirst;
4640 while (ifslastp->next && ifslastp->next->begoff < endoff)
4641 ifslastp=ifslastp->next;
4642 while (ifslastp->next != NULL) {
4643 struct ifsregion *ifsp;
4645 ifsp = ifslastp->next->next;
4646 ckfree(ifslastp->next);
4647 ifslastp->next = ifsp;
4650 if (ifslastp->endoff > endoff)
4651 ifslastp->endoff = endoff;
4655 #ifdef ASH_MATH_SUPPORT
4657 * Expand arithmetic expression. Backup to start of expression,
4658 * evaluate, place result in (backed up) result, adjust string position.
4667 int quotes = flag & (EXP_FULL | EXP_CASE);
4673 * This routine is slightly over-complicated for
4674 * efficiency. First we make sure there is
4675 * enough space for the result, which may be bigger
4676 * than the expression if we add exponentation. Next we
4677 * scan backwards looking for the start of arithmetic. If the
4678 * next previous character is a CTLESC character, then we
4679 * have to rescan starting from the beginning since CTLESC
4680 * characters have to be processed left to right.
4682 CHECKSTRSPACE(10, expdest);
4683 USTPUTC('\0', expdest);
4684 start = stackblock();
4686 while (*p != CTLARI && p >= start)
4689 error("missing CTLARI (shouldn't happen)");
4690 if (p > start && *(p-1) == CTLESC)
4691 for (p = start; *p != CTLARI; p++)
4700 removerecordregions(begoff);
4703 result = arith(p+2, &errcode);
4706 error("divide by zero");
4708 error("syntax error: \"%s\"\n", p+2);
4710 snprintf(p, 12, "%d", result);
4716 recordregion(begoff, p - 1 - start, 0);
4717 result = expdest - p + 1;
4718 STADJUST(-result, expdest);
4723 * Expand stuff in backwards quotes.
4727 expbackq(cmd, quoted, flag)
4732 volatile struct backcmd in;
4736 char *dest = expdest;
4737 volatile struct ifsregion saveifs;
4738 struct ifsregion *volatile savelastp;
4739 struct nodelist *volatile saveargbackq;
4741 int startloc = dest - stackblock();
4742 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4743 volatile int saveherefd;
4744 int quotes = flag & (EXP_FULL | EXP_CASE);
4745 struct jmploc jmploc;
4746 struct jmploc *volatile savehandler;
4750 /* Avoid longjmp clobbering */
4761 savelastp = ifslastp;
4762 saveargbackq = argbackq;
4763 saveherefd = herefd;
4765 if ((ex = setjmp(jmploc.loc))) {
4768 savehandler = handler;
4771 p = grabstackstr(dest);
4772 evalbackcmd(cmd, (struct backcmd *) &in);
4773 ungrabstackstr(p, dest);
4777 ifslastp = savelastp;
4778 argbackq = saveargbackq;
4779 herefd = saveherefd;
4787 if (--in.nleft < 0) {
4790 i = safe_read(in.fd, buf, sizeof buf);
4791 TRACE(("expbackq: read returns %d\n", i));
4798 if (lastc != '\0') {
4799 if (quotes && SIT(lastc, syntax) == CCTL)
4800 STPUTC(CTLESC, dest);
4801 STPUTC(lastc, dest);
4805 /* Eat all trailing newlines */
4806 for (; dest > stackblock() && dest[-1] == '\n';)
4815 exitstatus = waitforjob(in.jp);
4816 handler = savehandler;
4818 longjmp(handler->loc, 1);
4821 recordregion(startloc, dest - stackblock(), 0);
4822 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4823 (dest - stackblock()) - startloc,
4824 (dest - stackblock()) - startloc,
4825 stackblock() + startloc));
4831 subevalvar(p, str, strloc, subtype, startloc, varflags, quotes)
4844 int saveherefd = herefd;
4845 struct nodelist *saveargbackq = argbackq;
4849 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4850 STACKSTRNUL(expdest);
4851 herefd = saveherefd;
4852 argbackq = saveargbackq;
4853 startp = stackblock() + startloc;
4855 str = stackblock() + strloc;
4859 setvar(str, startp, 0);
4860 amount = startp - expdest;
4861 STADJUST(amount, expdest);
4868 if (*p != CTLENDVAR) {
4869 out2fmt(snlfmt, startp);
4870 error((char *)NULL);
4872 error("%.*s: parameter %snot set", p - str - 1,
4873 str, (varflags & VSNUL) ? "null or "
4878 for (loc = startp; loc < str; loc++) {
4881 if (patmatch2(str, startp, quotes))
4884 if (quotes && *loc == CTLESC)
4890 for (loc = str - 1; loc >= startp;) {
4893 if (patmatch2(str, startp, quotes))
4897 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4898 for (q = startp; q < loc; q++)
4908 for (loc = str - 1; loc >= startp;) {
4909 if (patmatch2(str, loc, quotes))
4912 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4913 for (q = startp; q < loc; q++)
4922 case VSTRIMRIGHTMAX:
4923 for (loc = startp; loc < str - 1; loc++) {
4924 if (patmatch2(str, loc, quotes))
4926 if (quotes && *loc == CTLESC)
4939 amount = ((str - 1) - (loc - startp)) - expdest;
4940 STADJUST(amount, expdest);
4941 while (loc != str - 1)
4946 amount = loc - expdest;
4947 STADJUST(amount, expdest);
4948 STPUTC('\0', expdest);
4949 STADJUST(-1, expdest);
4955 * Test whether a specialized variable is set.
4959 varisset(name, nulok)
4964 return backgndpid != -1;
4965 else if (*name == '@' || *name == '*') {
4966 if (*shellparam.p == NULL)
4972 for (av = shellparam.p; *av; av++)
4977 } else if (is_digit(*name)) {
4979 int num = atoi(name);
4981 if (num > shellparam.nparam)
4987 ap = shellparam.p[num - 1];
4989 if (nulok && (ap == NULL || *ap == '\0'))
4996 * Put a string on the stack.
5000 strtodest(const char *p, int syntax, int quotes)
5003 if (quotes && SIT(*p,syntax) == CCTL)
5004 STPUTC(CTLESC, expdest);
5005 STPUTC(*p++, expdest);
5010 * Add the value of a specialized variable to the stack string.
5014 varvalue(char *name, int quoted, int flags)
5023 int allow_split = flags & EXP_FULL;
5024 int quotes = flags & (EXP_FULL | EXP_CASE);
5026 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5035 num = shellparam.nparam;
5040 expdest = cvtnum(num, expdest);
5043 for (i = 0 ; i < NOPTS ; i++) {
5045 STPUTC(optent_letter(optlist[i]), expdest);
5049 if (allow_split && quoted) {
5050 sep = 1 << CHAR_BIT;
5055 sep = ifsset() ? ifsval()[0] : ' ';
5057 sepq = SIT(sep,syntax) == CCTL;
5060 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
5061 strtodest(p, syntax, quotes);
5064 STPUTC(CTLESC, expdest);
5065 STPUTC(sep, expdest);
5070 strtodest(arg0, syntax, quotes);
5074 if (num > 0 && num <= shellparam.nparam) {
5075 strtodest(shellparam.p[num - 1], syntax, quotes);
5083 * Record the fact that we have to scan this region of the
5084 * string for IFS characters.
5088 recordregion(start, end, nulonly)
5093 struct ifsregion *ifsp;
5095 if (ifslastp == NULL) {
5099 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5101 ifslastp->next = ifsp;
5105 ifslastp->begoff = start;
5106 ifslastp->endoff = end;
5107 ifslastp->nulonly = nulonly;
5113 * Break the argument string into pieces based upon IFS and add the
5114 * strings to the argument list. The regions of the string to be
5115 * searched for IFS characters have been stored by recordregion.
5118 ifsbreakup(string, arglist)
5120 struct arglist *arglist;
5122 struct ifsregion *ifsp;
5127 const char *ifs, *realifs;
5135 realifs = ifsset() ? ifsval() : defifs;
5136 if (ifslastp != NULL) {
5139 p = string + ifsp->begoff;
5140 nulonly = ifsp->nulonly;
5141 ifs = nulonly ? nullstr : realifs;
5143 while (p < string + ifsp->endoff) {
5147 if (strchr(ifs, *p)) {
5149 ifsspc = (strchr(defifs, *p) != NULL);
5150 /* Ignore IFS whitespace at start */
5151 if (q == start && ifsspc) {
5157 sp = (struct strlist *)stalloc(sizeof *sp);
5159 *arglist->lastp = sp;
5160 arglist->lastp = &sp->next;
5164 if (p >= string + ifsp->endoff) {
5170 if (strchr(ifs, *p) == NULL ) {
5173 } else if (strchr(defifs, *p) == NULL) {
5189 } while ((ifsp = ifsp->next) != NULL);
5190 if (!(*start || (!ifsspc && start > string && nulonly))) {
5195 sp = (struct strlist *)stalloc(sizeof *sp);
5197 *arglist->lastp = sp;
5198 arglist->lastp = &sp->next;
5204 while (ifsfirst.next != NULL) {
5205 struct ifsregion *ifsp;
5207 ifsp = ifsfirst.next->next;
5208 ckfree(ifsfirst.next);
5209 ifsfirst.next = ifsp;
5213 ifsfirst.next = NULL;
5217 * Add a file name to the list.
5221 addfname(const char *name)
5227 sp = (struct strlist *)stalloc(sizeof *sp);
5230 exparg.lastp = &sp->next;
5234 * Expand shell metacharacters. At this point, the only control characters
5235 * should be escapes. The results are stored in the list exparg.
5238 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5240 expandmeta(str, flag)
5241 struct strlist *str;
5246 /* TODO - EXP_REDIR */
5251 p = preglob(str->text);
5253 switch (glob(p, 0, 0, &pglob)) {
5255 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5266 *exparg.lastp = str;
5267 rmescapes(str->text);
5268 exparg.lastp = &str->next;
5270 default: /* GLOB_NOSPACE */
5271 error("Out of space");
5279 * Add the result of glob(3) to the list.
5284 const glob_t *pglob;
5286 char **p = pglob->gl_pathv;
5294 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5295 static char *expdir;
5299 expandmeta(str, flag)
5300 struct strlist *str;
5304 struct strlist **savelastp;
5307 /* TODO - EXP_REDIR */
5313 for (;;) { /* fast check for meta chars */
5314 if ((c = *p++) == '\0')
5316 if (c == '*' || c == '?' || c == '[' || c == '!')
5319 savelastp = exparg.lastp;
5321 if (expdir == NULL) {
5322 int i = strlen(str->text);
5323 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5326 expmeta(expdir, str->text);
5330 if (exparg.lastp == savelastp) {
5335 *exparg.lastp = str;
5336 rmescapes(str->text);
5337 exparg.lastp = &str->next;
5339 *exparg.lastp = NULL;
5340 *savelastp = sp = expsort(*savelastp);
5341 while (sp->next != NULL)
5343 exparg.lastp = &sp->next;
5351 * Do metacharacter (i.e. *, ?, [...]) expansion.
5355 expmeta(enddir, name)
5373 for (p = name ; ; p++) {
5374 if (*p == '*' || *p == '?')
5376 else if (*p == '[') {
5381 while (*q == CTLQUOTEMARK)
5385 if (*q == '/' || *q == '\0')
5392 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5394 } else if (*p == '\0')
5396 else if (*p == CTLQUOTEMARK)
5398 else if (*p == CTLESC)
5406 if (metaflag == 0) { /* we've reached the end of the file name */
5407 if (enddir != expdir)
5409 for (p = name ; ; p++) {
5410 if (*p == CTLQUOTEMARK)
5418 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5423 if (start != name) {
5426 while (*p == CTLQUOTEMARK)
5433 if (enddir == expdir) {
5435 } else if (enddir == expdir + 1 && *expdir == '/') {
5441 if ((dirp = opendir(cp)) == NULL)
5443 if (enddir != expdir)
5445 if (*endname == 0) {
5453 while (*p == CTLQUOTEMARK)
5459 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5460 if (dp->d_name[0] == '.' && ! matchdot)
5462 if (patmatch(start, dp->d_name, 0)) {
5464 strcpy(enddir, dp->d_name);
5467 for (p = enddir, cp = dp->d_name;
5468 (*p++ = *cp++) != '\0';)
5471 expmeta(p, endname);
5479 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5483 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5485 * Sort the results of file name expansion. It calculates the number of
5486 * strings to sort and then calls msort (short for merge sort) to do the
5490 static struct strlist *
5492 struct strlist *str;
5498 for (sp = str ; sp ; sp = sp->next)
5500 return msort(str, len);
5504 static struct strlist *
5506 struct strlist *list;
5509 struct strlist *p, *q = NULL;
5510 struct strlist **lpp;
5518 for (n = half ; --n >= 0 ; ) {
5522 q->next = NULL; /* terminate first half of list */
5523 q = msort(list, half); /* sort first half of list */
5524 p = msort(p, len - half); /* sort second half */
5527 if (strcmp(p->text, q->text) < 0) {
5530 if ((p = *lpp) == NULL) {
5537 if ((q = *lpp) == NULL) {
5550 * Returns true if the pattern matches the string.
5553 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5554 /* squoted: string might have quote chars */
5556 patmatch(char *pattern, char *string, int squoted)
5561 p = preglob(pattern);
5562 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5564 return !fnmatch(p, q, 0);
5569 patmatch2(char *pattern, char *string, int squoted)
5575 p = grabstackstr(expdest);
5576 res = patmatch(pattern, string, squoted);
5577 ungrabstackstr(p, expdest);
5582 patmatch(char *pattern, char *string, int squoted) {
5583 return pmatch(pattern, string, squoted);
5588 pmatch(char *pattern, char *string, int squoted)
5600 if (squoted && *q == CTLESC)
5608 if (squoted && *q == CTLESC)
5615 while (c == CTLQUOTEMARK || c == '*')
5617 if (c != CTLESC && c != CTLQUOTEMARK &&
5618 c != '?' && c != '*' && c != '[') {
5620 if (squoted && *q == CTLESC &&
5625 if (squoted && *q == CTLESC)
5631 if (pmatch(p, q, squoted))
5633 if (squoted && *q == CTLESC)
5635 } while (*q++ != '\0');
5646 while (*endp == CTLQUOTEMARK)
5649 goto dft; /* no matching ] */
5650 if (*endp == CTLESC)
5662 if (squoted && chr == CTLESC)
5668 if (c == CTLQUOTEMARK)
5672 if (*p == '-' && p[1] != ']') {
5674 while (*p == CTLQUOTEMARK)
5678 if (chr >= c && chr <= *p)
5685 } while ((c = *p++) != ']');
5686 if (found == invert)
5691 if (squoted && *q == CTLESC)
5708 * Remove any CTLESC characters from a string.
5711 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5713 _rmescapes(char *str, int flag)
5716 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5718 p = strpbrk(str, qchars);
5724 if (flag & RMESCAPE_ALLOC) {
5725 size_t len = p - str;
5726 q = r = stalloc(strlen(p) + len + 1);
5728 memcpy(q, str, len);
5733 if (*p == CTLQUOTEMARK) {
5739 if (flag & RMESCAPE_GLOB && *p != '/') {
5756 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5762 if (*p == CTLQUOTEMARK) {
5777 * See if a pattern matches in a case statement.
5781 casematch(union node *pattern, const char *val)
5783 struct stackmark smark;
5787 setstackmark(&smark);
5788 argbackq = pattern->narg.backquote;
5789 STARTSTACKSTR(expdest);
5791 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5792 STPUTC('\0', expdest);
5793 p = grabstackstr(expdest);
5794 result = patmatch(p, (char *)val, 0);
5795 popstackmark(&smark);
5810 CHECKSTRSPACE(32, buf);
5811 len = sprintf(buf, "%d", num);
5816 * Editline and history functions (and glue).
5818 static int histcmd(argc, argv)
5822 error("not compiled with history support");
5828 struct redirtab *next;
5829 short renamed[10]; /* Current ash support only 0-9 descriptors */
5830 /* char on arm (and others) can't be negative */
5833 static struct redirtab *redirlist;
5835 extern char **environ;
5840 * Initialization code.
5854 basepf.nextc = basepf.buf = basebuf;
5863 for (envp = environ ; *envp ; envp++) {
5864 if (strchr(*envp, '=')) {
5865 setvareq(*envp, VEXPORT|VTEXTFIXED);
5869 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5870 setvar("PPID", ppid, 0);
5877 * This routine is called when an error or an interrupt occurs in an
5878 * interactive shell and control is returned to the main command loop.
5881 /* 1 == check for aliases, 2 == also check for assignments */
5882 static int checkalias; /* also used in no alias mode for check assignments */
5896 if (exception != EXSHELLPROC)
5897 parselleft = parsenleft = 0; /* clear input buffer */
5901 /* from parser.c: */
5919 * This file implements the input routines used by the parser.
5922 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5923 static const char * cmdedit_prompt;
5924 static inline void putprompt(const char *s) {
5928 static inline void putprompt(const char *s) {
5933 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5938 * Same as pgetc(), but ignores PEOA.
5948 } while (c == PEOA);
5952 static inline int pgetc2() { return pgetc_macro(); }
5956 * Read a line from the script.
5959 static inline char *
5960 pfgets(char *line, int len)
5966 while (--nleft > 0) {
5985 char *buf = parsefile->buf;
5989 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5991 if (!iflag || parsefile->fd)
5992 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5994 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5998 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6002 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6003 int flags = fcntl(0, F_GETFL, 0);
6004 if (flags >= 0 && flags & O_NONBLOCK) {
6005 flags &=~ O_NONBLOCK;
6006 if (fcntl(0, F_SETFL, flags) >= 0) {
6007 out2str("sh: turning off NDELAY mode\n");
6019 struct strpush *sp = parsefile->strpush;
6024 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6029 if (sp->string != sp->ap->val) {
6033 sp->ap->flag &= ~ALIASINUSE;
6034 if (sp->ap->flag & ALIASDEAD) {
6035 unalias(sp->ap->name);
6039 parsenextc = sp->prevstring;
6040 parsenleft = sp->prevnleft;
6041 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6042 parsefile->strpush = sp->prev;
6043 if (sp != &(parsefile->basestrpush))
6050 * Refill the input buffer and return the next input character:
6052 * 1) If a string was pushed back on the input, pop it;
6053 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6054 * from a string so we can't refill the buffer, return EOF.
6055 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6056 * 4) Process input up to the next newline, deleting nul characters.
6066 while (parsefile->strpush) {
6068 if (parsenleft == -1 && parsefile->strpush->ap &&
6069 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6074 if (--parsenleft >= 0)
6075 return (*parsenextc++);
6077 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6082 if (parselleft <= 0) {
6083 if ((parselleft = preadfd()) <= 0) {
6084 parselleft = parsenleft = EOF_NLEFT;
6091 /* delete nul characters */
6092 for (more = 1; more;) {
6100 parsenleft = q - parsenextc;
6101 more = 0; /* Stop processing here */
6107 if (--parselleft <= 0 && more) {
6108 parsenleft = q - parsenextc - 1;
6119 out2str(parsenextc);
6124 return *parsenextc++;
6129 * Push a string back onto the input at this current parsefile level.
6130 * We handle aliases this way.
6133 pushstring(char *s, int len, void *ap)
6138 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6139 if (parsefile->strpush) {
6140 sp = ckmalloc(sizeof (struct strpush));
6141 sp->prev = parsefile->strpush;
6142 parsefile->strpush = sp;
6144 sp = parsefile->strpush = &(parsefile->basestrpush);
6145 sp->prevstring = parsenextc;
6146 sp->prevnleft = parsenleft;
6148 sp->ap = (struct alias *)ap;
6150 ((struct alias *)ap)->flag |= ALIASINUSE;
6161 * Like setinputfile, but takes input from a string.
6165 setinputstring(char *string)
6169 parsenextc = string;
6170 parsenleft = strlen(string);
6171 parsefile->buf = NULL;
6179 * To handle the "." command, a stack of input files is used. Pushfile
6180 * adds a new entry to the stack and popfile restores the previous level.
6185 struct parsefile *pf;
6187 parsefile->nleft = parsenleft;
6188 parsefile->lleft = parselleft;
6189 parsefile->nextc = parsenextc;
6190 parsefile->linno = plinno;
6191 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6192 pf->prev = parsefile;
6195 pf->basestrpush.prev = NULL;
6200 static void restartjob (struct job *);
6202 static void freejob (struct job *);
6203 static struct job *getjob (const char *);
6204 static int dowait (int, struct job *);
6205 static void waitonint(int);
6209 * We keep track of whether or not fd0 has been redirected. This is for
6210 * background commands, where we want to redirect fd0 to /dev/null only
6211 * if it hasn't already been redirected.
6213 static int fd0_redirected = 0;
6215 /* Return true if fd 0 has already been redirected at least once. */
6217 fd0_redirected_p (void)
6219 return fd0_redirected != 0;
6222 static void dupredirect (const union node *, int, int fd1dup);
6226 * Turn job control on and off.
6228 * Note: This code assumes that the third arg to ioctl is a character
6229 * pointer, which is true on Berkeley systems but not System V. Since
6230 * System V doesn't have job control yet, this isn't a problem now.
6235 static void setjobctl(int enable)
6237 #ifdef OLD_TTY_DRIVER
6241 if (enable == jobctl || rootshell == 0)
6244 do { /* while we are in the background */
6245 #ifdef OLD_TTY_DRIVER
6246 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6248 initialpgrp = tcgetpgrp(2);
6249 if (initialpgrp < 0) {
6251 out2str("sh: can't access tty; job control turned off\n");
6255 if (initialpgrp == -1)
6256 initialpgrp = getpgrp();
6257 else if (initialpgrp != getpgrp()) {
6258 killpg(initialpgrp, SIGTTIN);
6262 #ifdef OLD_TTY_DRIVER
6263 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6264 out2str("sh: need new tty driver to run job control; job control turned off\n");
6272 setpgid(0, rootpid);
6273 #ifdef OLD_TTY_DRIVER
6274 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6276 tcsetpgrp(2, rootpid);
6278 } else { /* turning job control off */
6279 setpgid(0, initialpgrp);
6280 #ifdef OLD_TTY_DRIVER
6281 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6283 tcsetpgrp(2, initialpgrp);
6309 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6310 "kill -l [exitstatus]"
6314 if (*argv[1] == '-') {
6315 signo = decode_signal(argv[1] + 1, 1);
6319 while ((c = nextopt("ls:")) != '\0')
6325 signo = decode_signal(optionarg, 1);
6328 "invalid signal number or name: %s",
6336 "nextopt returned character code 0%o", c);
6343 if (!list && signo < 0)
6346 if ((signo < 0 || !*argptr) ^ list) {
6355 for (i = 1; i < NSIG; i++) {
6356 name = u_signal_names(0, &i, 1);
6358 printf(snlfmt, name);
6362 name = u_signal_names(*argptr, &signo, -1);
6364 printf(snlfmt, name);
6366 error("invalid signal number or exit status: %s",
6372 if (**argptr == '%') {
6373 jp = getjob(*argptr);
6374 if (jp->jobctl == 0)
6375 error("job %s not created under job control",
6377 pid = -jp->ps[0].pid;
6379 pid = atoi(*argptr);
6380 if (kill(pid, signo) != 0)
6381 error("%s: %m", *argptr);
6382 } while (*++argptr);
6396 jp = getjob(argv[1]);
6397 if (jp->jobctl == 0)
6398 error("job not created under job control");
6399 pgrp = jp->ps[0].pid;
6400 #ifdef OLD_TTY_DRIVER
6401 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6407 status = waitforjob(jp);
6421 jp = getjob(*++argv);
6422 if (jp->jobctl == 0)
6423 error("job not created under job control");
6425 } while (--argc > 1);
6434 struct procstat *ps;
6437 if (jp->state == JOBDONE)
6440 killpg(jp->ps[0].pid, SIGCONT);
6441 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6442 if (WIFSTOPPED(ps->status)) {
6451 static void showjobs(int change);
6465 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6466 * statuses have changed since the last call to showjobs.
6468 * If the shell is interrupted in the process of creating a job, the
6469 * result may be a job structure containing zero processes. Such structures
6470 * will be freed here.
6481 struct procstat *ps;
6485 TRACE(("showjobs(%d) called\n", change));
6486 while (dowait(0, (struct job *)NULL) > 0);
6487 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6490 if (jp->nprocs == 0) {
6494 if (change && ! jp->changed)
6496 procno = jp->nprocs;
6497 for (ps = jp->ps ; ; ps++) { /* for each process */
6499 snprintf(s, 64, "[%d] %ld ", jobno,
6502 snprintf(s, 64, " %ld ",
6507 if (ps->status == -1) {
6508 /* don't print anything */
6509 } else if (WIFEXITED(ps->status)) {
6510 snprintf(s, 64, "Exit %d",
6511 WEXITSTATUS(ps->status));
6514 if (WIFSTOPPED(ps->status))
6515 i = WSTOPSIG(ps->status);
6516 else /* WIFSIGNALED(ps->status) */
6518 i = WTERMSIG(ps->status);
6519 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6520 strcpy(s, sys_siglist[i & 0x7F]);
6522 snprintf(s, 64, "Signal %d", i & 0x7F);
6523 if (WCOREDUMP(ps->status))
6524 strcat(s, " (core dumped)");
6529 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6536 if (jp->state == JOBDONE) {
6544 * Mark a job structure as unused.
6548 freejob(struct job *jp)
6550 const struct procstat *ps;
6554 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6555 if (ps->cmd != nullstr)
6558 if (jp->ps != &jp->ps0)
6562 if (curjob == jp - jobtab + 1)
6581 job = getjob(*++argv);
6585 for (;;) { /* loop until process terminated or stopped */
6588 status = job->ps[job->nprocs - 1].status;
6594 if (WIFEXITED(status))
6595 retval = WEXITSTATUS(status);
6597 else if (WIFSTOPPED(status))
6598 retval = WSTOPSIG(status) + 128;
6601 /* XXX: limits number of signals */
6602 retval = WTERMSIG(status) + 128;
6607 for (jp = jobtab ; ; jp++) {
6608 if (jp >= jobtab + njobs) { /* no running procs */
6611 if (jp->used && jp->state == 0)
6615 if (dowait(2, 0) < 0 && errno == EINTR) {
6624 * Convert a job name to a job structure.
6628 getjob(const char *name)
6638 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6639 error("No current job");
6640 return &jobtab[jobno - 1];
6642 error("No current job");
6644 } else if (name[0] == '%') {
6645 if (is_digit(name[1])) {
6646 jobno = number(name + 1);
6647 if (jobno > 0 && jobno <= njobs
6648 && jobtab[jobno - 1].used != 0)
6649 return &jobtab[jobno - 1];
6651 } else if (name[1] == '%' && name[2] == '\0') {
6655 struct job *found = NULL;
6656 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6657 if (jp->used && jp->nprocs > 0
6658 && prefix(name + 1, jp->ps[0].cmd)) {
6660 error("%s: ambiguous", name);
6667 } else if (is_number(name, &pid)) {
6668 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6669 if (jp->used && jp->nprocs > 0
6670 && jp->ps[jp->nprocs - 1].pid == pid)
6674 error("No such job: %s", name);
6681 * Return a new job structure,
6685 makejob(const union node *node, int nprocs)
6690 for (i = njobs, jp = jobtab ; ; jp++) {
6694 jobtab = ckmalloc(4 * sizeof jobtab[0]);
6696 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
6697 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6698 /* Relocate `ps' pointers */
6699 for (i = 0; i < njobs; i++)
6700 if (jp[i].ps == &jobtab[i].ps0)
6701 jp[i].ps = &jp[i].ps0;
6705 jp = jobtab + njobs;
6706 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6719 jp->jobctl = jobctl;
6722 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6727 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6734 * Fork of a subshell. If we are doing job control, give the subshell its
6735 * own process group. Jp is a job structure that the job is to be added to.
6736 * N is the command that will be evaluated by the child. Both jp and n may
6737 * be NULL. The mode parameter can be one of the following:
6738 * FORK_FG - Fork off a foreground process.
6739 * FORK_BG - Fork off a background process.
6740 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6741 * process group even if job control is on.
6743 * When job control is turned off, background processes have their standard
6744 * input redirected to /dev/null (except for the second and later processes
6751 forkshell(struct job *jp, const union node *n, int mode)
6757 const char *devnull = _PATH_DEVNULL;
6758 const char *nullerr = "Can't open %s";
6760 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6763 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6769 TRACE(("Fork failed, errno=%d\n", errno));
6771 error("Cannot fork");
6778 TRACE(("Child shell %d\n", getpid()));
6779 wasroot = rootshell;
6785 jobctl = 0; /* do job control only in root shell */
6786 if (wasroot && mode != FORK_NOJOB && mflag) {
6787 if (jp == NULL || jp->nprocs == 0)
6790 pgrp = jp->ps[0].pid;
6792 if (mode == FORK_FG) {
6793 /*** this causes superfluous TIOCSPGRPS ***/
6794 #ifdef OLD_TTY_DRIVER
6795 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6796 error("TIOCSPGRP failed, errno=%d", errno);
6798 if (tcsetpgrp(2, pgrp) < 0)
6799 error("tcsetpgrp failed, errno=%d", errno);
6804 } else if (mode == FORK_BG) {
6807 if ((jp == NULL || jp->nprocs == 0) &&
6808 ! fd0_redirected_p ()) {
6810 if (open(devnull, O_RDONLY) != 0)
6811 error(nullerr, devnull);
6815 if (mode == FORK_BG) {
6818 if ((jp == NULL || jp->nprocs == 0) &&
6819 ! fd0_redirected_p ()) {
6821 if (open(devnull, O_RDONLY) != 0)
6822 error(nullerr, devnull);
6826 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6829 if (wasroot && iflag) {
6837 if (rootshell && mode != FORK_NOJOB && mflag) {
6838 if (jp == NULL || jp->nprocs == 0)
6841 pgrp = jp->ps[0].pid;
6845 if (mode == FORK_BG)
6846 backgndpid = pid; /* set $! */
6848 struct procstat *ps = &jp->ps[jp->nprocs++];
6852 if (iflag && rootshell && n)
6853 ps->cmd = commandtext(n);
6856 TRACE(("In parent shell: child = %d\n", pid));
6863 * Wait for job to finish.
6865 * Under job control we have the problem that while a child process is
6866 * running interrupts generated by the user are sent to the child but not
6867 * to the shell. This means that an infinite loop started by an inter-
6868 * active user may be hard to kill. With job control turned off, an
6869 * interactive user may place an interactive program inside a loop. If
6870 * the interactive program catches interrupts, the user doesn't want
6871 * these interrupts to also abort the loop. The approach we take here
6872 * is to have the shell ignore interrupt signals while waiting for a
6873 * forground process to terminate, and then send itself an interrupt
6874 * signal if the child process was terminated by an interrupt signal.
6875 * Unfortunately, some programs want to do a bit of cleanup and then
6876 * exit on interrupt; unless these processes terminate themselves by
6877 * sending a signal to themselves (instead of calling exit) they will
6878 * confuse this approach.
6882 waitforjob(struct job *jp)
6885 int mypgrp = getpgrp();
6889 struct sigaction act, oact;
6898 sigaction(SIGINT, 0, &act);
6899 act.sa_handler = waitonint;
6900 sigaction(SIGINT, &act, &oact);
6902 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6903 while (jp->state == 0) {
6911 sigaction(SIGINT, &oact, 0);
6912 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6916 #ifdef OLD_TTY_DRIVER
6917 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6918 error("TIOCSPGRP failed, errno=%d\n", errno);
6920 if (tcsetpgrp(2, mypgrp) < 0)
6921 error("tcsetpgrp failed, errno=%d\n", errno);
6924 if (jp->state == JOBSTOPPED)
6925 curjob = jp - jobtab + 1;
6927 status = jp->ps[jp->nprocs - 1].status;
6928 /* convert to 8 bits */
6929 if (WIFEXITED(status))
6930 st = WEXITSTATUS(status);
6932 else if (WIFSTOPPED(status))
6933 st = WSTOPSIG(status) + 128;
6936 st = WTERMSIG(status) + 128;
6940 * This is truly gross.
6941 * If we're doing job control, then we did a TIOCSPGRP which
6942 * caused us (the shell) to no longer be in the controlling
6943 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6944 * intuit from the subprocess exit status whether a SIGINT
6945 * occured, and if so interrupt ourselves. Yuck. - mycroft
6947 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6950 if (jp->state == JOBDONE)
6961 * Wait for a process to terminate.
6965 * Do a wait system call. If job control is compiled in, we accept
6966 * stopped processes. If block is zero, we return a value of zero
6967 * rather than blocking.
6969 * System V doesn't have a non-blocking wait system call. It does
6970 * have a SIGCLD signal that is sent to a process when one of it's
6971 * children dies. The obvious way to use SIGCLD would be to install
6972 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6973 * was received, and have waitproc bump another counter when it got
6974 * the status of a process. Waitproc would then know that a wait
6975 * system call would not block if the two counters were different.
6976 * This approach doesn't work because if a process has children that
6977 * have not been waited for, System V will send it a SIGCLD when it
6978 * installs a signal handler for SIGCLD. What this means is that when
6979 * a child exits, the shell will be sent SIGCLD signals continuously
6980 * until is runs out of stack space, unless it does a wait call before
6981 * restoring the signal handler. The code below takes advantage of
6982 * this (mis)feature by installing a signal handler for SIGCLD and
6983 * then checking to see whether it was called. If there are any
6984 * children to be waited for, it will be.
6989 waitproc(int block, int *status)
7000 return wait3(status, flags, (struct rusage *)NULL);
7004 dowait(int block, struct job *job)
7008 struct procstat *sp;
7010 struct job *thisjob;
7016 TRACE(("dowait(%d) called\n", block));
7018 pid = waitproc(block, &status);
7019 TRACE(("wait returns %d, status=%d\n", pid, status));
7020 } while (!(block & 2) && pid == -1 && errno == EINTR);
7025 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
7029 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
7032 if (sp->pid == pid) {
7033 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
7034 sp->status = status;
7037 if (sp->status == -1)
7039 else if (WIFSTOPPED(sp->status))
7042 if (stopped) { /* stopped or done */
7043 int state = done? JOBDONE : JOBSTOPPED;
7044 if (jp->state != state) {
7045 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
7048 if (done && curjob == jp - jobtab + 1)
7049 curjob = 0; /* no current job */
7056 if (! rootshell || ! iflag || (job && thisjob == job)) {
7057 core = WCOREDUMP(status);
7059 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
7062 if (WIFEXITED(status)) sig = 0;
7063 else sig = WTERMSIG(status);
7065 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
7067 out2fmt("%d: ", pid);
7069 if (sig == SIGTSTP && rootshell && iflag)
7071 (long)(job - jobtab + 1));
7073 if (sig < NSIG && sys_siglist[sig])
7074 out2str(sys_siglist[sig]);
7076 out2fmt("Signal %d", sig);
7078 out2str(" - core dumped");
7081 TRACE(("Not printing status: status=%d, sig=%d\n",
7085 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
7087 thisjob->changed = 1;
7096 * return 1 if there are stopped jobs, otherwise 0
7106 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7109 if (jp->state == JOBSTOPPED) {
7110 out2str("You have stopped jobs.\n");
7120 * Return a string identifying a command (to be printed by the
7124 static char *cmdnextc;
7125 static int cmdnleft;
7126 #define MAXCMDTEXT 200
7129 cmdputs(const char *s)
7140 while ((c = *p++) != '\0') {
7143 else if (c == CTLVAR) {
7148 } else if (c == '=' && subtype != 0) {
7149 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7151 } else if (c == CTLENDVAR) {
7153 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7154 cmdnleft++; /* ignore it */
7157 if (--cmdnleft <= 0) {
7167 #define CMDTXT_TABLE
7170 * To collect a lot of redundant code in cmdtxt() case statements, we
7171 * implement a mini language here. Each type of node struct has an
7172 * associated instruction sequence that operates on its members via
7173 * their offsets. The instruction are pack in unsigned chars with
7174 * format IIDDDDDE where the bits are
7175 * I : part of the instruction opcode, which are
7176 * 00 : member is a pointer to another node -- process it recursively
7177 * 40 : member is a pointer to a char string -- output it
7178 * 80 : output the string whose index is stored in the data field
7179 * CC : flag signaling that this case needs external processing
7180 * D : data - either the (shifted) index of a fixed string to output or
7181 * the actual offset of the member to operate on in the struct
7182 * (since we assume bit 0 is set, the offset is not shifted)
7183 * E : flag signaling end of instruction sequence
7185 * WARNING: In order to handle larger offsets for 64bit archs, this code
7186 * assumes that no offset can be an odd number and stores the
7187 * end-of-instructions flag in bit 0.
7190 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7191 #define CMDTXT_CHARPTR 0x40
7192 #define CMDTXT_STRING 0x80
7193 #define CMDTXT_SPECIAL 0xC0
7194 #define CMDTXT_OFFSETMASK 0x3E
7196 static const char * const cmdtxt_strings[] = {
7197 /* 0 1 2 3 4 5 6 7 */
7198 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7199 /* 8 9 10 11 12 13 */
7200 "while ", "; do ", "; done", "until ", "for ", " in ...",
7202 "case ", "???", "() ...", "<<..."
7205 static const char * const redir_strings[] = {
7206 ">", "<", "<>", ">>", ">|", ">&", "<&"
7209 static const unsigned char cmdtxt_ops[] = {
7210 #define CMDTXT_NSEMI 0
7211 offsetof(union node, nbinary.ch1),
7213 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7214 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7215 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7216 #define CMDTXT_NCASE (CMDTXT_NCMD)
7217 #define CMDTXT_NTO (CMDTXT_NCMD)
7218 #define CMDTXT_NFROM (CMDTXT_NCMD)
7219 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7220 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7221 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7222 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7223 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7225 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7226 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7227 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7228 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7229 (1*2)|CMDTXT_STRING,
7230 offsetof(union node, nredir.n),
7231 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7232 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7233 offsetof(union node, nbinary.ch1),
7234 (3*2)|CMDTXT_STRING,
7235 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7236 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7237 offsetof(union node, nbinary.ch1),
7238 (4*2)|CMDTXT_STRING,
7239 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7240 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7241 (5*2)|CMDTXT_STRING,
7242 offsetof(union node, nif.test),
7243 (6*2)|CMDTXT_STRING,
7244 offsetof(union node, nif.ifpart),
7245 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7246 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7247 (8*2)|CMDTXT_STRING,
7248 offsetof(union node, nbinary.ch1),
7249 (9*2)|CMDTXT_STRING,
7250 offsetof(union node, nbinary.ch2),
7251 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7252 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7253 (11*2)|CMDTXT_STRING,
7254 offsetof(union node, nbinary.ch1),
7255 (9*2)|CMDTXT_STRING,
7256 offsetof(union node, nbinary.ch2),
7257 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7258 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7259 (12*2)|CMDTXT_STRING,
7260 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7261 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7262 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7263 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7264 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7265 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7266 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7267 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7268 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7269 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7270 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7271 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7272 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7275 #if CMDTXT_NXHERE != 36
7276 #error CMDTXT_NXHERE
7279 static const unsigned char cmdtxt_ops_index[26] = {
7309 cmdtxt(const union node *n)
7316 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7317 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7319 if (*p & CMDTXT_STRING) { /* output fixed string */
7320 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7322 const char *pf = ((const char *) n)
7323 + ((int)(*p & CMDTXT_OFFSETMASK));
7324 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7325 cmdputs(*((const char **) pf));
7326 } else { /* output field */
7327 cmdtxt(*((const union node **) pf));
7330 } while (!(*p++ & CMDTXT_NOMORE));
7331 } else if (n->type == NCMD) {
7333 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7338 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7342 } else if (n->type == NPIPE) {
7343 struct nodelist *lp;
7344 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7349 } else if (n->type == NCASE) {
7350 cmdputs(cmdtxt_strings[14]);
7351 cmdputs(n->ncase.expr->narg.text);
7352 cmdputs(cmdtxt_strings[13]);
7354 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7355 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7360 assert((n->type >= NTO) && (n->type <= NFROMFD));
7363 p = redir_strings[n->type - NTO];
7364 if (n->nfile.fd != ('>' == *p)) {
7365 s[0] = n->nfile.fd + '0';
7370 if (n->type >= NTOFD) {
7371 s[0] = n->ndup.dupfd + '0';
7375 cmdtxt(n->nfile.fname);
7379 #else /* CMDTXT_TABLE */
7381 cmdtxt(const union node *n)
7384 struct nodelist *lp;
7393 cmdtxt(n->nbinary.ch1);
7395 cmdtxt(n->nbinary.ch2);
7398 cmdtxt(n->nbinary.ch1);
7400 cmdtxt(n->nbinary.ch2);
7403 cmdtxt(n->nbinary.ch1);
7405 cmdtxt(n->nbinary.ch2);
7408 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7416 cmdtxt(n->nredir.n);
7421 cmdtxt(n->nredir.n);
7425 cmdtxt(n->nif.test);
7427 cmdtxt(n->nif.ifpart);
7436 cmdtxt(n->nbinary.ch1);
7438 cmdtxt(n->nbinary.ch2);
7443 cmdputs(n->nfor.var);
7448 cmdputs(n->ncase.expr->narg.text);
7452 cmdputs(n->narg.text);
7456 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7461 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7467 cmdputs(n->narg.text);
7470 p = ">"; i = 1; goto redir;
7472 p = ">>"; i = 1; goto redir;
7474 p = ">&"; i = 1; goto redir;
7476 p = ">|"; i = 1; goto redir;
7478 p = "<"; i = 0; goto redir;
7480 p = "<&"; i = 0; goto redir;
7482 p = "<>"; i = 0; goto redir;
7484 if (n->nfile.fd != i) {
7485 s[0] = n->nfile.fd + '0';
7490 if (n->type == NTOFD || n->type == NFROMFD) {
7491 s[0] = n->ndup.dupfd + '0';
7495 cmdtxt(n->nfile.fname);
7507 #endif /* CMDTXT_TABLE */
7510 commandtext(const union node *n)
7514 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7515 cmdnleft = MAXCMDTEXT - 4;
7522 static void waitonint(int sig) {
7527 * Routines to check for mail. (Perhaps make part of main.c?)
7531 #define MAXMBOXES 10
7534 static int nmboxes; /* number of mailboxes */
7535 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7540 * Print appropriate message(s) if mail has arrived. If the argument is
7541 * nozero, then the value of MAIL has changed, so we just update the
7552 struct stackmark smark;
7559 setstackmark(&smark);
7560 mpath = mpathset()? mpathval() : mailval();
7561 for (i = 0 ; i < nmboxes ; i++) {
7562 p = padvance(&mpath, nullstr);
7567 for (q = p ; *q ; q++);
7572 q[-1] = '\0'; /* delete trailing '/' */
7573 if (stat(p, &statb) < 0)
7575 if (statb.st_size > mailtime[i] && ! silent) {
7577 pathopt? pathopt : "you have mail");
7579 mailtime[i] = statb.st_size;
7582 popstackmark(&smark);
7588 static short profile_buf[16384];
7592 static void read_profile (const char *);
7593 static void cmdloop (int);
7594 static void options (int);
7595 static void setoption (int, int);
7596 static void procargs (int, char **);
7600 * Main routine. We initialize things, parse the arguments, execute
7601 * profiles if we're a login shell, and then call cmdloop to execute
7602 * commands. The setjmp call sets up the location to jump to when an
7603 * exception occurs. When an exception occurs the variable "state"
7604 * is used to figure out how far we had gotten.
7608 ash_main(argc, argv)
7612 struct jmploc jmploc;
7613 struct stackmark smark;
7617 BLTINCMD = find_builtin("builtin");
7618 EXECCMD = find_builtin("exec");
7619 EVALCMD = find_builtin("eval");
7621 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7627 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7629 #if defined(linux) || defined(__GNU__)
7630 signal(SIGCHLD, SIG_DFL);
7633 if (setjmp(jmploc.loc)) {
7636 * When a shell procedure is executed, we raise the
7637 * exception EXSHELLPROC to clean up before executing
7638 * the shell procedure.
7640 if (exception == EXSHELLPROC) {
7646 if (exception == EXEXEC) {
7647 exitstatus = exerrno;
7648 } else if (exception == EXERROR) {
7651 if (state == 0 || iflag == 0 || ! rootshell)
7652 exitshell(exitstatus);
7655 if (exception == EXINT) {
7658 popstackmark(&smark);
7659 FORCEINTON; /* enable interrupts */
7662 else if (state == 2)
7664 else if (state == 3)
7672 trputs("Shell args: "); trargs(argv);
7677 setstackmark(&smark);
7678 procargs(argc, argv);
7679 if (argv[0] && argv[0][0] == '-') {
7681 read_profile("/etc/profile");
7684 read_profile(".profile");
7689 if (getuid() == geteuid() && getgid() == getegid()) {
7691 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7693 read_profile(shinit);
7700 if (sflag == 0 || minusc) {
7701 static const char sigs[] = {
7702 SIGINT, SIGQUIT, SIGHUP,
7708 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7711 for (i = 0; i < SIGSSIZE; i++)
7716 evalstring(minusc, 0);
7718 if (sflag || minusc == NULL) {
7719 state4: /* XXX ??? - why isn't this before the "if" statement */
7725 exitshell(exitstatus);
7731 * Read and execute commands. "Top" is nonzero for the top level command
7732 * loop; it turns on prompting if the shell is interactive.
7739 struct stackmark smark;
7743 TRACE(("cmdloop(%d) called\n", top));
7744 setstackmark(&smark);
7755 n = parsecmd(inter);
7756 /* showtree(n); DEBUG */
7758 if (!top || numeof >= 50)
7760 if (!stoppedjobs()) {
7763 out2str("\nUse \"exit\" to leave shell.\n");
7766 } else if (n != NULL && nflag == 0) {
7767 job_warning = (job_warning == 2) ? 1 : 0;
7771 popstackmark(&smark);
7772 setstackmark(&smark);
7773 if (evalskip == SKIPFILE) {
7778 popstackmark(&smark);
7784 * Read /etc/profile or .profile. Return on error.
7796 if ((fd = open(name, O_RDONLY)) >= 0)
7801 /* -q turns off -x and -v just when executing init files */
7802 /* Note: Might do a little redundant work, but reduces code size. */
7817 * Read a file containing shell functions.
7821 readcmdfile(const char *name)
7826 if ((fd = open(name, O_RDONLY)) >= 0)
7829 error("Can't open %s", name);
7838 * Take commands from a file. To be compatable we should do a path
7839 * search for the file, which is necessary to find sub-commands.
7842 static inline char *
7843 find_dot_file(char *mybasename)
7846 const char *path = pathval();
7849 /* don't try this for absolute or relative paths */
7850 if (strchr(mybasename, '/'))
7853 while ((fullname = padvance(&path, mybasename)) != NULL) {
7854 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7856 * Don't bother freeing here, since it will
7857 * be freed by the caller.
7861 stunalloc(fullname);
7864 /* not found in the PATH */
7865 error("%s: not found", mybasename);
7875 volatile struct shparam saveparam;
7878 for (sp = cmdenviron; sp ; sp = sp->next)
7879 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
7881 if (argc >= 2) { /* That's what SVR2 does */
7883 struct stackmark smark;
7885 setstackmark(&smark);
7886 fullname = find_dot_file(argv[1]);
7889 saveparam = shellparam;
7890 shellparam.malloc = 0;
7891 shellparam.nparam = argc - 2;
7892 shellparam.p = argv + 2;
7895 setinputfile(fullname, 1);
7896 commandname = fullname;
7901 freeparam(&shellparam);
7902 shellparam = saveparam;
7905 popstackmark(&smark);
7919 exitstatus = number(argv[1]);
7921 exitstatus = oexitstatus;
7922 exitshell(exitstatus);
7931 nbytes = ALIGN(nbytes);
7932 if (nbytes > stacknleft) {
7934 struct stack_block *sp;
7937 if (blocksize < MINSIZE)
7938 blocksize = MINSIZE;
7940 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7942 stacknxt = sp->space;
7943 stacknleft = blocksize;
7949 stacknleft -= nbytes;
7955 stunalloc(pointer p)
7958 if (p == NULL) { /*DEBUG */
7959 write(2, "stunalloc\n", 10);
7963 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7966 stacknleft += stacknxt - (char *)p;
7972 setstackmark(struct stackmark *mark)
7974 mark->stackp = stackp;
7975 mark->stacknxt = stacknxt;
7976 mark->stacknleft = stacknleft;
7977 mark->marknext = markp;
7983 popstackmark(struct stackmark *mark)
7985 struct stack_block *sp;
7988 markp = mark->marknext;
7989 while (stackp != mark->stackp) {
7994 stacknxt = mark->stacknxt;
7995 stacknleft = mark->stacknleft;
8001 * When the parser reads in a string, it wants to stick the string on the
8002 * stack and only adjust the stack pointer when it knows how big the
8003 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8004 * of space on top of the stack and stackblocklen returns the length of
8005 * this block. Growstackblock will grow this space by at least one byte,
8006 * possibly moving it (like realloc). Grabstackblock actually allocates the
8007 * part of the block that has been used.
8011 growstackblock(void) {
8013 int newlen = ALIGN(stacknleft * 2 + 100);
8014 char *oldspace = stacknxt;
8015 int oldlen = stacknleft;
8016 struct stack_block *sp;
8017 struct stack_block *oldstackp;
8019 if (stacknxt == stackp->space && stackp != &stackbase) {
8024 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8027 stacknxt = sp->space;
8028 stacknleft = newlen;
8030 /* Stack marks pointing to the start of the old block
8031 * must be relocated to point to the new block
8033 struct stackmark *xmark;
8035 while (xmark != NULL && xmark->stackp == oldstackp) {
8036 xmark->stackp = stackp;
8037 xmark->stacknxt = stacknxt;
8038 xmark->stacknleft = stacknleft;
8039 xmark = xmark->marknext;
8044 p = stalloc(newlen);
8045 memcpy(p, oldspace, oldlen);
8046 stacknxt = p; /* free the space */
8047 stacknleft += newlen; /* we just allocated */
8054 grabstackblock(int len)
8064 * The following routines are somewhat easier to use that the above.
8065 * The user declares a variable of type STACKSTR, which may be declared
8066 * to be a register. The macro STARTSTACKSTR initializes things. Then
8067 * the user uses the macro STPUTC to add characters to the string. In
8068 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8069 * grown as necessary. When the user is done, she can just leave the
8070 * string there and refer to it using stackblock(). Or she can allocate
8071 * the space for it using grabstackstr(). If it is necessary to allow
8072 * someone else to use the stack temporarily and then continue to grow
8073 * the string, the user should use grabstack to allocate the space, and
8074 * then call ungrabstr(p) to return to the previous mode of operation.
8076 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8077 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8078 * is space for at least one character.
8083 growstackstr(void) {
8084 int len = stackblocksize();
8085 if (herefd >= 0 && len >= 1024) {
8086 xwrite(herefd, stackblock(), len);
8087 sstrnleft = len - 1;
8088 return stackblock();
8091 sstrnleft = stackblocksize() - len - 1;
8092 return stackblock() + len;
8097 * Called from CHECKSTRSPACE.
8101 makestrspace(size_t newlen) {
8102 int len = stackblocksize() - sstrnleft;
8105 sstrnleft = stackblocksize() - len;
8106 } while (sstrnleft < newlen);
8107 return stackblock() + len;
8113 ungrabstackstr(char *s, char *p)
8115 stacknleft += stacknxt - s;
8117 sstrnleft = stacknleft - (p - s);
8120 * Miscelaneous builtins.
8126 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8127 typedef long rlim_t;
8133 * The read builtin. The -e option causes backslashes to escape the
8134 * following character.
8136 * This uses unbuffered input, which may be avoidable in some cases.
8140 readcmd(int argc, char **argv)
8155 while ((i = nextopt("p:r")) != '\0') {
8161 if (prompt && isatty(0)) {
8162 out2str(prompt); /* read without cmdedit */
8165 if (*(ap = argptr) == NULL)
8167 if ((ifs = bltinlookup("IFS")) == NULL)
8174 if (read(0, &c, 1) != 1) {
8186 if (!rflag && c == '\\') {
8192 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8196 if (backslash && c == '\\') {
8197 if (read(0, &c, 1) != 1) {
8202 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8204 setvar(*ap, stackblock(), 0);
8213 /* Remove trailing blanks */
8214 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8216 setvar(*ap, stackblock(), 0);
8217 while (*++ap != NULL)
8218 setvar(*ap, nullstr, 0);
8225 umaskcmd(argc, argv)
8229 static const char permuser[3] = "ugo";
8230 static const char permmode[3] = "rwx";
8231 static const short int permmask[] = {
8232 S_IRUSR, S_IWUSR, S_IXUSR,
8233 S_IRGRP, S_IWGRP, S_IXGRP,
8234 S_IROTH, S_IWOTH, S_IXOTH
8240 int symbolic_mode = 0;
8242 while (nextopt("S") != '\0') {
8251 if ((ap = *argptr) == NULL) {
8252 if (symbolic_mode) {
8255 for (i=0 ; i<3 ; i++) {
8259 for (j=0 ; j<3 ; j++) {
8260 if ((mask & permmask[3*i+j]) == 0) {
8269 printf("%.4o\n", mask);
8272 if (is_digit((unsigned char)*ap)) {
8275 if (*ap >= '8' || *ap < '0')
8276 error("Illegal number: %s", argv[1]);
8277 mask = (mask << 3) + (*ap - '0');
8278 } while (*++ap != '\0');
8281 mask = ~mask & 0777;
8282 if (parse_mode(ap, &mask) == FALSE) {
8283 error("Illegal mode: %s", ap);
8285 umask(~mask & 0777);
8294 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8295 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8296 * ash by J.T. Conklin.
8304 short factor; /* multiply by to get rlim_{cur,max} values */
8307 static const struct limits limits[] = {
8309 { "time(seconds)", RLIMIT_CPU, 1 },
8312 { "file(blocks)", RLIMIT_FSIZE, 512 },
8315 { "data(kbytes)", RLIMIT_DATA, 1024 },
8318 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8321 { "coredump(blocks)", RLIMIT_CORE, 512 },
8324 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8326 #ifdef RLIMIT_MEMLOCK
8327 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8330 { "process(processes)", RLIMIT_NPROC, 1 },
8332 #ifdef RLIMIT_NOFILE
8333 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8336 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8339 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8345 ulimitcmd(argc, argv)
8349 static const char unlimited_string[] = "unlimited";
8352 enum { SOFT = 0x1, HARD = 0x2 }
8354 const struct limits *l;
8357 struct rlimit limit;
8361 while ((optc = nextopt("HSa"
8380 #ifdef RLIMIT_MEMLOCK
8386 #ifdef RLIMIT_NOFILE
8398 } else if (optc == 'S') {
8400 } else if (optc == 'a') {
8407 for (l = limits; l->name; l++) {
8408 if(l->name[0] == what)
8410 if(l->name[1]=='w' && what=='w')
8414 set = *argptr ? 1 : 0;
8418 if (all || argptr[1])
8419 error("too many arguments");
8420 if (strcmp(p, unlimited_string) == 0)
8421 val = RLIM_INFINITY;
8425 while ((c = *p++) >= '0' && c <= '9')
8427 val = (val * 10) + (long)(c - '0');
8428 if (val < (rlim_t) 0)
8432 error("bad number");
8438 for (l = limits; l->name; l++) {
8439 printf("%-20s ", l->name);
8440 getrlimit(l->cmd, &limit);
8443 val = limit.rlim_cur;
8444 else if (how & HARD)
8445 val = limit.rlim_max;
8447 if (val == RLIM_INFINITY)
8448 puts(unlimited_string);
8452 printf("%lld\n", (long long) val);
8465 getrlimit(l->cmd, &limit);
8467 limit.rlim_max = val;
8469 limit.rlim_cur = val;
8470 if (setrlimit(l->cmd, &limit) < 0)
8471 error("error setting limit (%m)");
8475 * prefix -- see if pfx is a prefix of string.
8479 prefix(char const *pfx, char const *string)
8482 if (*pfx++ != *string++)
8489 * Return true if s is a string of digits, and save munber in intptr
8494 is_number(const char *p, int *intptr)
8502 ret += digit_val(*p);
8504 } while (*p != '\0');
8511 * Convert a string of digits to an integer, printing an error message on
8516 number(const char *s)
8519 if (! is_number(s, &i))
8520 error("Illegal number: %s", s);
8525 * Produce a possibly single quoted string suitable as input to the shell.
8526 * The return string is allocated on the stack.
8530 single_quote(const char *s) {
8537 size_t len1, len1p, len2, len2p;
8539 len1 = strcspn(s, "'");
8540 len2 = strspn(s + len1, "'");
8542 len1p = len1 ? len1 + 2 : len1;
8543 len2p = len2 + ((len2 < 2) ? len2 : 2);
8545 CHECKSTRSPACE(len1p + len2p + 1, p);
8550 memcpy(p + 1, s, len1);
8558 memcpy(q + 1, s, len2);
8561 } else if (len2 == 1) {
8567 STADJUST(len1p + len2p, p);
8572 return grabstackstr(p);
8576 * Like strdup but works with the ash stack.
8580 sstrdup(const char *p)
8582 size_t len = strlen(p) + 1;
8583 return memcpy(stalloc(len), p, len);
8588 * Routine for dealing with parsed shell commands.
8592 static void sizenodelist (const struct nodelist *);
8593 static struct nodelist *copynodelist (const struct nodelist *);
8594 static char *nodesavestr (const char *);
8596 #define CALCSIZE_TABLE
8597 #define COPYNODE_TABLE
8598 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8600 * To collect a lot of redundant code in case statements for copynode()
8601 * and calcsize(), we implement a mini language here. Each type of node
8602 * struct has an associated instruction sequence that operates on its
8603 * members via their offsets. The instruction are pack in unsigned chars
8604 * with format IIDDDDDE where the bits are
8605 * I : part of the instruction opcode, which are
8606 * 00 : member is a pointer to another node
8607 * 40 : member is an integer
8608 * 80 : member is a pointer to a nodelist
8609 * CC : member is a pointer to a char string
8610 * D : data - the actual offset of the member to operate on in the struct
8611 * (since we assume bit 0 is set, it is not shifted)
8612 * E : flag signaling end of instruction sequence
8614 * WARNING: In order to handle larger offsets for 64bit archs, this code
8615 * assumes that no offset can be an odd number and stores the
8616 * end-of-instructions flag in bit 0.
8619 #define NODE_INTEGER 0x40
8620 #define NODE_NODELIST 0x80
8621 #define NODE_CHARPTR 0xC0
8622 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8623 #define NODE_MBRMASK 0xC0
8624 #define NODE_OFFSETMASK 0x3E
8626 static const unsigned char copynode_ops[35] = {
8627 #define COPYNODE_OPS0 0
8628 offsetof(union node, nbinary.ch2),
8629 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8630 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8631 offsetof(union node, ncmd.redirect),
8632 offsetof(union node, ncmd.args),
8633 offsetof(union node, ncmd.assign),
8634 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8635 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8636 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8637 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8638 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8639 offsetof(union node, nredir.redirect),
8640 offsetof(union node, nredir.n)|NODE_NOMORE,
8641 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8642 offsetof(union node, nif.elsepart),
8643 offsetof(union node, nif.ifpart),
8644 offsetof(union node, nif.test)|NODE_NOMORE,
8645 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8646 offsetof(union node, nfor.var)|NODE_CHARPTR,
8647 offsetof(union node, nfor.body),
8648 offsetof(union node, nfor.args)|NODE_NOMORE,
8649 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8650 offsetof(union node, ncase.cases),
8651 offsetof(union node, ncase.expr)|NODE_NOMORE,
8652 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8653 offsetof(union node, nclist.body),
8654 offsetof(union node, nclist.pattern),
8655 offsetof(union node, nclist.next)|NODE_NOMORE,
8656 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8657 offsetof(union node, narg.backquote)|NODE_NODELIST,
8658 offsetof(union node, narg.text)|NODE_CHARPTR,
8659 offsetof(union node, narg.next)|NODE_NOMORE,
8660 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8661 offsetof(union node, nfile.fname),
8662 offsetof(union node, nfile.fd)|NODE_INTEGER,
8663 offsetof(union node, nfile.next)|NODE_NOMORE,
8664 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8665 offsetof(union node, ndup.vname),
8666 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8667 offsetof(union node, ndup.fd)|NODE_INTEGER,
8668 offsetof(union node, ndup.next)|NODE_NOMORE,
8669 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8670 offsetof(union node, nhere.doc),
8671 offsetof(union node, nhere.fd)|NODE_INTEGER,
8672 offsetof(union node, nhere.next)|NODE_NOMORE,
8673 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8674 offsetof(union node, nnot.com)|NODE_NOMORE,
8677 #if COPYNODE_OPS12 != 34
8678 #error COPYNODE_OPS12 is incorrect
8681 static const unsigned char copynode_ops_index[26] = {
8682 COPYNODE_OPS0, /* NSEMI */
8683 COPYNODE_OPS1, /* NCMD */
8684 COPYNODE_OPS2, /* NPIPE */
8685 COPYNODE_OPS3, /* NREDIR */
8686 COPYNODE_OPS3, /* NBACKGND */
8687 COPYNODE_OPS3, /* NSUBSHELL */
8688 COPYNODE_OPS0, /* NAND */
8689 COPYNODE_OPS0, /* NOR */
8690 COPYNODE_OPS4, /* NIF */
8691 COPYNODE_OPS0, /* NWHILE */
8692 COPYNODE_OPS0, /* NUNTIL */
8693 COPYNODE_OPS5, /* NFOR */
8694 COPYNODE_OPS6, /* NCASE */
8695 COPYNODE_OPS7, /* NCLIST */
8696 COPYNODE_OPS8, /* NDEFUN */
8697 COPYNODE_OPS8, /* NARG */
8698 COPYNODE_OPS9, /* NTO */
8699 COPYNODE_OPS9, /* NFROM */
8700 COPYNODE_OPS9, /* NFROMTO */
8701 COPYNODE_OPS9, /* NAPPEND */
8702 COPYNODE_OPS9, /* NTOOV */
8703 COPYNODE_OPS10, /* NTOFD */
8704 COPYNODE_OPS10, /* NFROMFD */
8705 COPYNODE_OPS11, /* NHERE */
8706 COPYNODE_OPS11, /* NXHERE */
8707 COPYNODE_OPS12, /* NNOT */
8710 #if NODE_CHARPTR != NODE_MBRMASK
8711 #error NODE_CHARPTR != NODE_MBRMASK!!!
8713 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8715 #ifdef COPYNODE_TABLE
8717 copynode(const union node *n)
8720 const unsigned char *p;
8726 new->type = n->type;
8727 funcblock = (char *) funcblock + (int) nodesize[n->type];
8728 p = copynode_ops + (int) copynode_ops_index[n->type];
8730 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8731 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8733 if (!(*p & NODE_MBRMASK)) { /* standard node */
8734 *((union node **)nn) = copynode(*((const union node **) no));
8735 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8736 *((const char **)nn) = nodesavestr(*((const char **)no));
8737 } else if (*p & NODE_NODELIST) { /* nodelist */
8738 *((struct nodelist **)nn)
8739 = copynodelist(*((const struct nodelist **) no));
8740 } else { /* integer */
8741 *((int *) nn) = *((int *) no);
8743 } while (!(*p++ & NODE_NOMORE));
8746 #else /* COPYNODE_TABLE */
8748 copynode(const union node *n)
8755 funcblock = (char *) funcblock + nodesize[n->type];
8762 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8763 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8766 new->ncmd.redirect = copynode(n->ncmd.redirect);
8767 new->ncmd.args = copynode(n->ncmd.args);
8768 new->ncmd.assign = copynode(n->ncmd.assign);
8769 new->ncmd.backgnd = n->ncmd.backgnd;
8772 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8773 new->npipe.backgnd = n->npipe.backgnd;
8778 new->nredir.redirect = copynode(n->nredir.redirect);
8779 new->nredir.n = copynode(n->nredir.n);
8782 new->nif.elsepart = copynode(n->nif.elsepart);
8783 new->nif.ifpart = copynode(n->nif.ifpart);
8784 new->nif.test = copynode(n->nif.test);
8787 new->nfor.var = nodesavestr(n->nfor.var);
8788 new->nfor.body = copynode(n->nfor.body);
8789 new->nfor.args = copynode(n->nfor.args);
8792 new->ncase.cases = copynode(n->ncase.cases);
8793 new->ncase.expr = copynode(n->ncase.expr);
8796 new->nclist.body = copynode(n->nclist.body);
8797 new->nclist.pattern = copynode(n->nclist.pattern);
8798 new->nclist.next = copynode(n->nclist.next);
8802 new->narg.backquote = copynodelist(n->narg.backquote);
8803 new->narg.text = nodesavestr(n->narg.text);
8804 new->narg.next = copynode(n->narg.next);
8811 new->nfile.fname = copynode(n->nfile.fname);
8812 new->nfile.fd = n->nfile.fd;
8813 new->nfile.next = copynode(n->nfile.next);
8817 new->ndup.vname = copynode(n->ndup.vname);
8818 new->ndup.dupfd = n->ndup.dupfd;
8819 new->ndup.fd = n->ndup.fd;
8820 new->ndup.next = copynode(n->ndup.next);
8824 new->nhere.doc = copynode(n->nhere.doc);
8825 new->nhere.fd = n->nhere.fd;
8826 new->nhere.next = copynode(n->nhere.next);
8829 new->nnot.com = copynode(n->nnot.com);
8832 new->type = n->type;
8835 #endif /* COPYNODE_TABLE */
8837 #ifdef CALCSIZE_TABLE
8839 calcsize(const union node *n)
8841 const unsigned char *p;
8845 funcblocksize += (int) nodesize[n->type];
8847 p = copynode_ops + (int) copynode_ops_index[n->type];
8849 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8851 if (!(*p & NODE_MBRMASK)) { /* standard node */
8852 calcsize(*((const union node **) no));
8853 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8854 funcstringsize += strlen(*((const char **)no)) + 1;
8855 } else if (*p & NODE_NODELIST) { /* nodelist */
8856 sizenodelist(*((const struct nodelist **) no));
8857 } /* else integer -- ignore */
8858 } while (!(*p++ & NODE_NOMORE));
8860 #else /* CALCSIZE_TABLE */
8862 calcsize(const union node *n)
8866 funcblocksize += nodesize[n->type];
8873 calcsize(n->nbinary.ch2);
8874 calcsize(n->nbinary.ch1);
8877 calcsize(n->ncmd.redirect);
8878 calcsize(n->ncmd.args);
8879 calcsize(n->ncmd.assign);
8882 sizenodelist(n->npipe.cmdlist);
8887 calcsize(n->nredir.redirect);
8888 calcsize(n->nredir.n);
8891 calcsize(n->nif.elsepart);
8892 calcsize(n->nif.ifpart);
8893 calcsize(n->nif.test);
8896 funcstringsize += strlen(n->nfor.var) + 1;
8897 calcsize(n->nfor.body);
8898 calcsize(n->nfor.args);
8901 calcsize(n->ncase.cases);
8902 calcsize(n->ncase.expr);
8905 calcsize(n->nclist.body);
8906 calcsize(n->nclist.pattern);
8907 calcsize(n->nclist.next);
8911 sizenodelist(n->narg.backquote);
8912 funcstringsize += strlen(n->narg.text) + 1;
8913 calcsize(n->narg.next);
8920 calcsize(n->nfile.fname);
8921 calcsize(n->nfile.next);
8925 calcsize(n->ndup.vname);
8926 calcsize(n->ndup.next);
8930 calcsize(n->nhere.doc);
8931 calcsize(n->nhere.next);
8934 calcsize(n->nnot.com);
8938 #endif /* CALCSIZE_TABLE */
8941 sizenodelist(const struct nodelist *lp)
8944 funcblocksize += ALIGN(sizeof(struct nodelist));
8951 static struct nodelist *
8952 copynodelist(const struct nodelist *lp)
8954 struct nodelist *start;
8955 struct nodelist **lpp;
8960 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8961 (*lpp)->n = copynode(lp->n);
8963 lpp = &(*lpp)->next;
8971 nodesavestr(const char *s)
8974 char *q = funcstring;
8975 char *rtn = funcstring;
8977 while ((*q++ = *p++) != '\0')
8984 static int getopts (char *, char *, char **, int *, int *);
8989 * Process the shell command line arguments.
8993 procargs(argc, argv)
9002 for (i = 0; i < NOPTS; i++)
9005 if (*argptr == NULL && minusc == NULL)
9007 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
9011 for (i = 0; i < NOPTS; i++)
9012 if (optent_val(i) == 2)
9015 if (sflag == 0 && minusc == NULL) {
9016 commandname = argv[0];
9018 setinputfile(arg0, 0);
9021 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
9022 if (argptr && minusc && *argptr)
9025 shellparam.p = argptr;
9026 shellparam.optind = 1;
9027 shellparam.optoff = -1;
9028 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9030 shellparam.nparam++;
9039 * Process shell options. The global variable argptr contains a pointer
9040 * to the argument list; we advance it past the options.
9044 minus_o(const char *name, int val)
9049 out1str("Current option settings\n");
9050 for (i = 0; i < NOPTS; i++)
9051 printf("%-16s%s\n", optent_name(optlist[i]),
9052 optent_val(i) ? "on" : "off");
9054 for (i = 0; i < NOPTS; i++)
9055 if (equal(name, optent_name(optlist[i]))) {
9056 setoption(optent_letter(optlist[i]), val);
9059 error("Illegal option -o %s", name);
9065 options(int cmdline)
9073 while ((p = *argptr) != NULL) {
9075 if ((c = *p++) == '-') {
9077 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9079 /* "-" means turn off -x and -v */
9082 /* "--" means reset params */
9083 else if (*argptr == NULL)
9086 break; /* "-" or "--" terminates options */
9088 } else if (c == '+') {
9094 while ((c = *p++) != '\0') {
9095 if (c == 'c' && cmdline) {
9097 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9101 if (q == NULL || minusc != NULL)
9102 error("Bad -c option");
9107 } else if (c == 'o') {
9108 minus_o(*argptr, val);
9120 setoption(int flag, int val)
9124 for (i = 0; i < NOPTS; i++)
9125 if (optent_letter(optlist[i]) == flag) {
9126 optent_val(i) = val;
9128 /* #%$ hack for ksh semantics */
9131 else if (flag == 'E')
9136 error("Illegal option -%c", flag);
9143 * Set the shell parameters.
9147 setparam(char **argv)
9153 for (nparam = 0 ; argv[nparam] ; nparam++);
9154 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9156 *ap++ = savestr(*argv++);
9159 freeparam(&shellparam);
9160 shellparam.malloc = 1;
9161 shellparam.nparam = nparam;
9162 shellparam.p = newparam;
9163 shellparam.optind = 1;
9164 shellparam.optoff = -1;
9169 * Free the list of positional parameters.
9173 freeparam(volatile struct shparam *param)
9177 if (param->malloc) {
9178 for (ap = param->p ; *ap ; ap++)
9187 * The shift builtin command.
9191 shiftcmd(argc, argv)
9200 n = number(argv[1]);
9201 if (n > shellparam.nparam)
9202 error("can't shift that many");
9204 shellparam.nparam -= n;
9205 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9206 if (shellparam.malloc)
9210 while ((*ap2++ = *ap1++) != NULL);
9211 shellparam.optind = 1;
9212 shellparam.optoff = -1;
9220 * The set command builtin.
9229 return showvarscmd(argc, argv);
9233 if (*argptr != NULL) {
9242 getoptsreset(const char *value)
9244 shellparam.optind = number(value);
9245 shellparam.optoff = -1;
9248 #ifdef CONFIG_LOCALE_SUPPORT
9249 static void change_lc_all(const char *value)
9251 if(value != 0 && *value != 0)
9252 setlocale(LC_ALL, value);
9255 static void change_lc_ctype(const char *value)
9257 if(value != 0 && *value != 0)
9258 setlocale(LC_CTYPE, value);
9265 * The getopts builtin. Shellparam.optnext points to the next argument
9266 * to be processed. Shellparam.optptr points to the next character to
9267 * be processed in the current argument. If shellparam.optnext is NULL,
9268 * then it's the first time getopts has been called.
9272 getoptscmd(argc, argv)
9279 error("Usage: getopts optstring var [arg]");
9280 else if (argc == 3) {
9281 optbase = shellparam.p;
9282 if (shellparam.optind > shellparam.nparam + 1) {
9283 shellparam.optind = 1;
9284 shellparam.optoff = -1;
9289 if (shellparam.optind > argc - 2) {
9290 shellparam.optind = 1;
9291 shellparam.optoff = -1;
9295 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9296 &shellparam.optoff);
9300 * Safe version of setvar, returns 1 on success 0 on failure.
9304 setvarsafe(name, val, flags)
9305 const char *name, *val;
9308 struct jmploc jmploc;
9309 struct jmploc *volatile savehandler = handler;
9315 if (setjmp(jmploc.loc))
9319 setvar(name, val, flags);
9321 handler = savehandler;
9326 getopts(optstr, optvar, optfirst, myoptind, optoff)
9338 char **optnext = optfirst + *myoptind - 1;
9340 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9341 strlen(*(optnext - 1)) < *optoff)
9344 p = *(optnext - 1) + *optoff;
9345 if (p == NULL || *p == '\0') {
9346 /* Current word is done, advance */
9347 if (optnext == NULL)
9350 if (p == NULL || *p != '-' || *++p == '\0') {
9352 *myoptind = optnext - optfirst + 1;
9358 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9363 for (q = optstr; *q != c; ) {
9365 if (optstr[0] == ':') {
9368 err |= setvarsafe("OPTARG", s, 0);
9371 out2fmt("Illegal option -%c\n", c);
9372 (void) unsetvar("OPTARG");
9382 if (*p == '\0' && (p = *optnext) == NULL) {
9383 if (optstr[0] == ':') {
9386 err |= setvarsafe("OPTARG", s, 0);
9390 out2fmt("No arg for -%c option\n", c);
9391 (void) unsetvar("OPTARG");
9399 setvarsafe("OPTARG", p, 0);
9403 setvarsafe("OPTARG", "", 0);
9404 *myoptind = optnext - optfirst + 1;
9411 *optoff = p ? p - *(optnext - 1) : -1;
9412 snprintf(s, sizeof(s), "%d", *myoptind);
9413 err |= setvarsafe("OPTIND", s, VNOFUNC);
9416 err |= setvarsafe(optvar, s, 0);
9427 * XXX - should get rid of. have all builtins use getopt(3). the
9428 * library getopt must have the BSD extension static variable "optreset"
9429 * otherwise it can't be used within the shell safely.
9431 * Standard option processing (a la getopt) for builtin routines. The
9432 * only argument that is passed to nextopt is the option string; the
9433 * other arguments are unnecessary. It return the character, or '\0' on
9438 nextopt(const char *optstring)
9444 if ((p = optptr) == NULL || *p == '\0') {
9446 if (p == NULL || *p != '-' || *++p == '\0')
9449 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9453 for (q = optstring ; *q != c ; ) {
9455 error("Illegal option -%c", c);
9460 if (*p == '\0' && (p = *argptr++) == NULL)
9461 error("No arg for -%c option", c);
9478 out2fmt(const char *fmt, ...)
9482 vfprintf(stderr, fmt, ap);
9487 * Version of write which resumes after a signal is caught.
9491 xwrite(int fd, const char *buf, int nbytes)
9500 i = write(fd, buf, n);
9506 } else if (i == 0) {
9509 } else if (errno != EINTR) {
9517 * Shell command parser.
9520 #define EOFMARKLEN 79
9525 struct heredoc *next; /* next here document in list */
9526 union node *here; /* redirection node */
9527 char *eofmark; /* string indicating end of input */
9528 int striptabs; /* if set, strip leading tabs */
9531 static struct heredoc *heredoclist; /* list of here documents to read */
9532 static int parsebackquote; /* nonzero if we are inside backquotes */
9533 static int doprompt; /* if set, prompt the user */
9534 static int needprompt; /* true if interactive and at start of line */
9535 static int lasttoken; /* last token read */
9537 static char *wordtext; /* text of last word returned by readtoken */
9539 static struct nodelist *backquotelist;
9540 static union node *redirnode;
9541 static struct heredoc *heredoc;
9542 static int quoteflag; /* set if (part of) last token was quoted */
9543 static int startlinno; /* line # where last token started */
9546 static union node *list (int);
9547 static union node *andor (void);
9548 static union node *pipeline (void);
9549 static union node *command (void);
9550 static union node *simplecmd(union node **rpp, union node *redir);
9551 static void parsefname (void);
9552 static void parseheredoc (void);
9553 static char peektoken (void);
9554 static int readtoken (void);
9555 static int xxreadtoken (void);
9556 static int readtoken1 (int, int, const char *, int);
9557 static int noexpand (char *);
9558 static void synexpect (int) __attribute__((noreturn));
9559 static void synerror (const char *) __attribute__((noreturn));
9560 static void setprompt (int);
9564 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9565 * valid parse tree indicating a blank line.)
9569 parsecmd(int interact)
9574 doprompt = interact;
9594 union node *n1, *n2, *n3;
9598 if (nlflag == 0 && peektoken())
9604 if (tok == TBACKGND) {
9605 if (n2->type == NCMD || n2->type == NPIPE) {
9606 n2->ncmd.backgnd = 1;
9607 } else if (n2->type == NREDIR) {
9608 n2->type = NBACKGND;
9610 n3 = (union node *)stalloc(sizeof (struct nredir));
9611 n3->type = NBACKGND;
9613 n3->nredir.redirect = NULL;
9621 n3 = (union node *)stalloc(sizeof (struct nbinary));
9623 n3->nbinary.ch1 = n1;
9624 n3->nbinary.ch2 = n2;
9648 pungetc(); /* push back EOF on input */
9663 union node *n1, *n2, *n3;
9669 if ((t = readtoken()) == TAND) {
9671 } else if (t == TOR) {
9679 n3 = (union node *)stalloc(sizeof (struct nbinary));
9681 n3->nbinary.ch1 = n1;
9682 n3->nbinary.ch2 = n2;
9691 union node *n1, *n2, *pipenode;
9692 struct nodelist *lp, *prev;
9696 TRACE(("pipeline: entered\n"));
9697 if (readtoken() == TNOT) {
9703 if (readtoken() == TPIPE) {
9704 pipenode = (union node *)stalloc(sizeof (struct npipe));
9705 pipenode->type = NPIPE;
9706 pipenode->npipe.backgnd = 0;
9707 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9708 pipenode->npipe.cmdlist = lp;
9712 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9716 } while (readtoken() == TPIPE);
9722 n2 = (union node *)stalloc(sizeof (struct nnot));
9734 union node *n1, *n2;
9735 union node *ap, **app;
9736 union node *cp, **cpp;
9737 union node *redir, **rpp;
9744 /* Check for redirection which may precede command */
9745 while (readtoken() == TREDIR) {
9746 *rpp = n2 = redirnode;
9747 rpp = &n2->nfile.next;
9752 switch (readtoken()) {
9754 n1 = (union node *)stalloc(sizeof (struct nif));
9756 n1->nif.test = list(0);
9757 if (readtoken() != TTHEN)
9759 n1->nif.ifpart = list(0);
9761 while (readtoken() == TELIF) {
9762 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9763 n2 = n2->nif.elsepart;
9765 n2->nif.test = list(0);
9766 if (readtoken() != TTHEN)
9768 n2->nif.ifpart = list(0);
9770 if (lasttoken == TELSE)
9771 n2->nif.elsepart = list(0);
9773 n2->nif.elsepart = NULL;
9776 if (readtoken() != TFI)
9783 n1 = (union node *)stalloc(sizeof (struct nbinary));
9784 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9785 n1->nbinary.ch1 = list(0);
9786 if ((got=readtoken()) != TDO) {
9787 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9790 n1->nbinary.ch2 = list(0);
9791 if (readtoken() != TDONE)
9797 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9798 synerror("Bad for loop variable");
9799 n1 = (union node *)stalloc(sizeof (struct nfor));
9801 n1->nfor.var = wordtext;
9803 if (readtoken() == TIN) {
9805 while (readtoken() == TWORD) {
9806 n2 = (union node *)stalloc(sizeof (struct narg));
9808 n2->narg.text = wordtext;
9809 n2->narg.backquote = backquotelist;
9811 app = &n2->narg.next;
9815 if (lasttoken != TNL && lasttoken != TSEMI)
9818 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9820 n2 = (union node *)stalloc(sizeof (struct narg));
9822 n2->narg.text = argvars;
9823 n2->narg.backquote = NULL;
9824 n2->narg.next = NULL;
9827 * Newline or semicolon here is optional (but note
9828 * that the original Bourne shell only allowed NL).
9830 if (lasttoken != TNL && lasttoken != TSEMI)
9834 if (readtoken() != TDO)
9836 n1->nfor.body = list(0);
9837 if (readtoken() != TDONE)
9842 n1 = (union node *)stalloc(sizeof (struct ncase));
9844 if (readtoken() != TWORD)
9846 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9848 n2->narg.text = wordtext;
9849 n2->narg.backquote = backquotelist;
9850 n2->narg.next = NULL;
9853 } while (readtoken() == TNL);
9854 if (lasttoken != TIN)
9855 synerror("expecting \"in\"");
9856 cpp = &n1->ncase.cases;
9857 checkkwd = 2, readtoken();
9859 if (lasttoken == TLP)
9861 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9863 app = &cp->nclist.pattern;
9865 *app = ap = (union node *)stalloc(sizeof (struct narg));
9867 ap->narg.text = wordtext;
9868 ap->narg.backquote = backquotelist;
9869 if (checkkwd = 2, readtoken() != TPIPE)
9871 app = &ap->narg.next;
9874 ap->narg.next = NULL;
9875 if (lasttoken != TRP)
9877 cp->nclist.body = list(0);
9880 if ((t = readtoken()) != TESAC) {
9882 synexpect(TENDCASE);
9884 checkkwd = 2, readtoken();
9886 cpp = &cp->nclist.next;
9887 } while(lasttoken != TESAC);
9892 n1 = (union node *)stalloc(sizeof (struct nredir));
9893 n1->type = NSUBSHELL;
9894 n1->nredir.n = list(0);
9895 n1->nredir.redirect = NULL;
9896 if (readtoken() != TRP)
9902 if (readtoken() != TEND)
9906 /* Handle an empty command like other simple commands. */
9915 * An empty command before a ; doesn't make much sense, and
9916 * should certainly be disallowed in the case of `if ;'.
9922 n1 = simplecmd(rpp, redir);
9929 /* Now check for redirection which may follow command */
9930 while (readtoken() == TREDIR) {
9931 *rpp = n2 = redirnode;
9932 rpp = &n2->nfile.next;
9938 if (n1->type != NSUBSHELL) {
9939 n2 = (union node *)stalloc(sizeof (struct nredir));
9944 n1->nredir.redirect = redir;
9952 simplecmd(union node **rpp, union node *redir) {
9953 union node *args, **app;
9954 union node *n = NULL;
9955 union node *vars, **vpp;
9956 union node **orig_rpp;
9963 /* If we don't have any redirections already, then we must reset
9964 rpp to be the address of the local redir variable. */
9967 /* We save the incoming value, because we need this for shell
9968 functions. There can not be a redirect or an argument between
9969 the function name and the open parenthesis. */
9974 switch (readtoken()) {
9977 n = (union node *)stalloc(sizeof (struct narg));
9979 n->narg.text = wordtext;
9980 n->narg.backquote = backquotelist;
9981 if (lasttoken == TWORD) {
9983 app = &n->narg.next;
9986 vpp = &n->narg.next;
9990 *rpp = n = redirnode;
9991 rpp = &n->nfile.next;
9992 parsefname(); /* read name of redirection file */
9996 args && app == &args->narg.next &&
9997 !vars && rpp == orig_rpp
9999 /* We have a function */
10000 if (readtoken() != TRP)
10004 n->narg.next = command();
10017 n = (union node *)stalloc(sizeof (struct ncmd));
10019 n->ncmd.backgnd = 0;
10020 n->ncmd.args = args;
10021 n->ncmd.assign = vars;
10022 n->ncmd.redirect = redir;
10026 static union node *
10030 n = (union node *)stalloc(sizeof (struct narg));
10032 n->narg.next = NULL;
10033 n->narg.text = wordtext;
10034 n->narg.backquote = backquotelist;
10038 static void fixredir(union node *n, const char *text, int err)
10040 TRACE(("Fix redir %s %d\n", text, err));
10042 n->ndup.vname = NULL;
10044 if (is_digit(text[0]) && text[1] == '\0')
10045 n->ndup.dupfd = digit_val(text[0]);
10046 else if (text[0] == '-' && text[1] == '\0')
10047 n->ndup.dupfd = -1;
10051 synerror("Bad fd number");
10053 n->ndup.vname = makename();
10060 union node *n = redirnode;
10062 if (readtoken() != TWORD)
10064 if (n->type == NHERE) {
10065 struct heredoc *here = heredoc;
10069 if (quoteflag == 0)
10071 TRACE(("Here document %d\n", n->type));
10072 if (here->striptabs) {
10073 while (*wordtext == '\t')
10076 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10077 synerror("Illegal eof marker for << redirection");
10078 rmescapes(wordtext);
10079 here->eofmark = wordtext;
10081 if (heredoclist == NULL)
10082 heredoclist = here;
10084 for (p = heredoclist ; p->next ; p = p->next);
10087 } else if (n->type == NTOFD || n->type == NFROMFD) {
10088 fixredir(n, wordtext, 0);
10090 n->nfile.fname = makename();
10096 * Input any here documents.
10101 struct heredoc *here;
10104 while (heredoclist) {
10105 here = heredoclist;
10106 heredoclist = here->next;
10111 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10112 here->eofmark, here->striptabs);
10113 n = (union node *)stalloc(sizeof (struct narg));
10114 n->narg.type = NARG;
10115 n->narg.next = NULL;
10116 n->narg.text = wordtext;
10117 n->narg.backquote = backquotelist;
10118 here->here->nhere.doc = n;
10128 return tokname_array[t][0];
10136 int savecheckalias = checkalias;
10137 int savecheckkwd = checkkwd;
10142 int alreadyseen = tokpushback;
10152 checkalias = savecheckalias;
10159 if (checkkwd == 2) {
10168 * check for keywords
10170 if (t == TWORD && !quoteflag)
10172 const char *const *pp;
10174 if ((pp = findkwd(wordtext))) {
10175 lasttoken = t = pp - tokname_array;
10176 TRACE(("keyword %s recognized\n", tokname(t)));
10187 } else if (checkalias == 2 && isassignment(wordtext)) {
10188 lasttoken = t = TASSIGN;
10190 } else if (checkalias) {
10191 if (!quoteflag && (ap = lookupalias(wordtext, 1)) != NULL) {
10193 pushstring(ap->val, strlen(ap->val), ap);
10195 checkkwd = savecheckkwd;
10204 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10206 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10213 * Read the next input token.
10214 * If the token is a word, we set backquotelist to the list of cmds in
10215 * backquotes. We set quoteflag to true if any part of the word was
10217 * If the token is TREDIR, then we set redirnode to a structure containing
10219 * In all cases, the variable startlinno is set to the number of the line
10220 * on which the token starts.
10222 * [Change comment: here documents and internal procedures]
10223 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10224 * word parsing code into a separate routine. In this case, readtoken
10225 * doesn't need to have any internal procedures, but parseword does.
10226 * We could also make parseoperator in essence the main routine, and
10227 * have parseword (readtoken1?) handle both words and redirection.]
10230 #define NEW_xxreadtoken
10231 #ifdef NEW_xxreadtoken
10233 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10234 static const char xxreadtoken_tokens[] = {
10235 TNL, TLP, TRP, /* only single occurrence allowed */
10236 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10237 TEOF, /* corresponds to trailing nul */
10238 TAND, TOR, TENDCASE, /* if double occurrence */
10241 #define xxreadtoken_doubles \
10242 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10243 #define xxreadtoken_singles \
10244 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10258 startlinno = plinno;
10259 for (;;) { /* until token or start of word found */
10262 if ((c!=' ') && (c!='\t')
10268 while ((c = pgetc()) != '\n' && c != PEOF);
10270 } else if (c=='\\') {
10271 if (pgetc() != '\n') {
10275 startlinno = ++plinno;
10276 setprompt(doprompt ? 2 : 0);
10279 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10284 needprompt = doprompt;
10287 p = strchr(xxreadtoken_chars, c);
10290 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10293 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10294 if (pgetc() == *p) { /* double occurrence? */
10295 p += xxreadtoken_doubles + 1;
10302 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10310 #define RETURN(token) return lasttoken = token
10324 startlinno = plinno;
10325 for (;;) { /* until token or start of word found */
10328 case ' ': case '\t':
10334 while ((c = pgetc()) != '\n' && c != PEOF);
10338 if (pgetc() == '\n') {
10339 startlinno = ++plinno;
10350 needprompt = doprompt;
10355 if (pgetc() == '&')
10360 if (pgetc() == '|')
10365 if (pgetc() == ';')
10378 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10384 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10385 * is not NULL, read a here document. In the latter case, eofmark is the
10386 * word which marks the end of the document and striptabs is true if
10387 * leading tabs should be stripped from the document. The argument firstc
10388 * is the first character of the input token or document.
10390 * Because C does not have internal subroutines, I have simulated them
10391 * using goto's to implement the subroutine linkage. The following macros
10392 * will run code that appears at the end of readtoken1.
10395 #define CHECKEND() {goto checkend; checkend_return:;}
10396 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10397 #define PARSESUB() {goto parsesub; parsesub_return:;}
10398 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10399 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10400 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10403 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10408 char line[EOFMARKLEN + 1];
10409 struct nodelist *bqlist;
10412 int varnest; /* levels of variables expansion */
10413 int arinest; /* levels of arithmetic expansion */
10414 int parenlevel; /* levels of parens in arithmetic */
10415 int dqvarnest; /* levels of variables expansion within double quotes */
10417 int prevsyntax; /* syntax before arithmetic */
10419 /* Avoid longjmp clobbering */
10425 (void) &parenlevel;
10428 (void) &prevsyntax;
10432 startlinno = plinno;
10434 if (syntax == DQSYNTAX)
10443 STARTSTACKSTR(out);
10444 loop: { /* for each line, until end of word */
10445 CHECKEND(); /* set c to PEOF if at end of here document */
10446 for (;;) { /* until end of line or end of word */
10447 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10448 switch(SIT(c,syntax)) {
10449 case CNL: /* '\n' */
10450 if (syntax == BASESYNTAX)
10451 goto endword; /* exit outer loop */
10459 goto loop; /* continue outer loop */
10464 if ((eofmark == NULL || dblquote) &&
10466 USTPUTC(CTLESC, out);
10469 case CBACK: /* backslash */
10472 USTPUTC('\\', out);
10474 } else if (c == '\n') {
10480 if (dblquote && c != '\\' && c != '`' && c != '$'
10481 && (c != '"' || eofmark != NULL))
10482 USTPUTC('\\', out);
10483 if (SIT(c,SQSYNTAX) == CCTL)
10484 USTPUTC(CTLESC, out);
10485 else if (eofmark == NULL)
10486 USTPUTC(CTLQUOTEMARK, out);
10492 if (eofmark == NULL)
10493 USTPUTC(CTLQUOTEMARK, out);
10497 if (eofmark == NULL)
10498 USTPUTC(CTLQUOTEMARK, out);
10503 if (eofmark != NULL && arinest == 0 &&
10508 syntax = ARISYNTAX;
10510 } else if (eofmark == NULL &&
10512 syntax = BASESYNTAX;
10518 case CVAR: /* '$' */
10519 PARSESUB(); /* parse substitution */
10521 case CENDVAR: /* '}' */
10524 if (dqvarnest > 0) {
10527 USTPUTC(CTLENDVAR, out);
10532 #ifdef ASH_MATH_SUPPORT
10533 case CLP: /* '(' in arithmetic */
10537 case CRP: /* ')' in arithmetic */
10538 if (parenlevel > 0) {
10542 if (pgetc() == ')') {
10543 if (--arinest == 0) {
10544 USTPUTC(CTLENDARI, out);
10545 syntax = prevsyntax;
10546 if (syntax == DQSYNTAX)
10554 * unbalanced parens
10555 * (don't 2nd guess - no error)
10563 case CBQUOTE: /* '`' */
10567 goto endword; /* exit outer loop */
10572 goto endword; /* exit outer loop */
10583 if (syntax == ARISYNTAX)
10584 synerror("Missing '))'");
10585 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10586 synerror("Unterminated quoted string");
10587 if (varnest != 0) {
10588 startlinno = plinno;
10589 synerror("Missing '}'");
10591 USTPUTC('\0', out);
10592 len = out - stackblock();
10593 out = stackblock();
10594 if (eofmark == NULL) {
10595 if ((c == '>' || c == '<')
10598 && (*out == '\0' || is_digit(*out))) {
10600 return lasttoken = TREDIR;
10605 quoteflag = quotef;
10606 backquotelist = bqlist;
10607 grabstackblock(len);
10609 return lasttoken = TWORD;
10610 /* end of readtoken routine */
10615 * Check to see whether we are at the end of the here document. When this
10616 * is called, c is set to the first character of the next input line. If
10617 * we are at the end of the here document, this routine sets the c to PEOF.
10628 while (c == '\t') {
10632 if (c == *eofmark) {
10633 if (pfgets(line, sizeof line) != NULL) {
10637 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10638 if (*p == '\n' && *q == '\0') {
10641 needprompt = doprompt;
10643 pushstring(line, strlen(line), NULL);
10648 goto checkend_return;
10653 * Parse a redirection operator. The variable "out" points to a string
10654 * specifying the fd to be redirected. The variable "c" contains the
10655 * first character of the redirection operator.
10662 np = (union node *)stalloc(sizeof (struct nfile));
10667 np->type = NAPPEND;
10676 } else { /* c == '<' */
10678 switch (c = pgetc()) {
10680 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10681 np = (union node *)stalloc(sizeof (struct nhere));
10685 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10686 heredoc->here = np;
10687 if ((c = pgetc()) == '-') {
10688 heredoc->striptabs = 1;
10690 heredoc->striptabs = 0;
10696 np->type = NFROMFD;
10700 np->type = NFROMTO;
10710 np->nfile.fd = digit_val(fd);
10712 goto parseredir_return;
10717 * Parse a substitution. At this point, we have read the dollar sign
10718 * and nothing else.
10726 static const char types[] = "}-+?=";
10731 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10735 } else if (c == '(') { /* $(command) or $((arith)) */
10736 if (pgetc() == '(') {
10743 USTPUTC(CTLVAR, out);
10744 typeloc = out - stackblock();
10745 USTPUTC(VSNORMAL, out);
10746 subtype = VSNORMAL;
10750 if ((c = pgetc()) == '}')
10753 subtype = VSLENGTH;
10758 if (c > PEOA && is_name(c)) {
10762 } while (c > PEOA && is_in_name(c));
10763 } else if (is_digit(c)) {
10767 } while (is_digit(c));
10769 else if (is_special(c)) {
10774 badsub: synerror("Bad substitution");
10778 if (subtype == 0) {
10785 p = strchr(types, c);
10788 subtype = p - types + VSNORMAL;
10794 subtype = c == '#' ? VSTRIMLEFT :
10807 if (dblquote || arinest)
10809 *(stackblock() + typeloc) = subtype | flags;
10810 if (subtype != VSNORMAL) {
10817 goto parsesub_return;
10822 * Called to parse command substitutions. Newstyle is set if the command
10823 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10824 * list of commands (passed by reference), and savelen is the number of
10825 * characters on the top of the stack which must be preserved.
10829 struct nodelist **nlpp;
10832 char *volatile str;
10833 struct jmploc jmploc;
10834 struct jmploc *volatile savehandler;
10838 (void) &saveprompt;
10841 savepbq = parsebackquote;
10842 if (setjmp(jmploc.loc)) {
10845 parsebackquote = 0;
10846 handler = savehandler;
10847 longjmp(handler->loc, 1);
10851 savelen = out - stackblock();
10853 str = ckmalloc(savelen);
10854 memcpy(str, stackblock(), savelen);
10856 savehandler = handler;
10860 /* We must read until the closing backquote, giving special
10861 treatment to some slashes, and then push the string and
10862 reread it as input, interpreting it normally. */
10869 STARTSTACKSTR(pout);
10875 switch (pc = pgetc()) {
10880 if ((pc = pgetc()) == '\n') {
10887 * If eating a newline, avoid putting
10888 * the newline into the new character
10889 * stream (via the STPUTC after the
10894 if (pc != '\\' && pc != '`' && pc != '$'
10895 && (!dblquote || pc != '"'))
10896 STPUTC('\\', pout);
10906 startlinno = plinno;
10907 synerror("EOF in backquote substitution");
10911 needprompt = doprompt;
10920 STPUTC('\0', pout);
10921 psavelen = pout - stackblock();
10922 if (psavelen > 0) {
10923 pstr = grabstackstr(pout);
10924 setinputstring(pstr);
10929 nlpp = &(*nlpp)->next;
10930 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10931 (*nlpp)->next = NULL;
10932 parsebackquote = oldstyle;
10935 saveprompt = doprompt;
10942 doprompt = saveprompt;
10944 if (readtoken() != TRP)
10951 * Start reading from old file again, ignoring any pushed back
10952 * tokens left from the backquote parsing
10957 while (stackblocksize() <= savelen)
10959 STARTSTACKSTR(out);
10961 memcpy(out, str, savelen);
10962 STADJUST(savelen, out);
10968 parsebackquote = savepbq;
10969 handler = savehandler;
10970 if (arinest || dblquote)
10971 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10973 USTPUTC(CTLBACKQ, out);
10975 goto parsebackq_oldreturn;
10977 goto parsebackq_newreturn;
10981 * Parse an arithmetic expansion (indicate start of one and set state)
10985 if (++arinest == 1) {
10986 prevsyntax = syntax;
10987 syntax = ARISYNTAX;
10988 USTPUTC(CTLARI, out);
10995 * we collapse embedded arithmetic expansion to
10996 * parenthesis, which should be equivalent
11000 goto parsearith_return;
11003 } /* end of readtoken */
11007 * Returns true if the text contains nothing to expand (no dollar signs
11019 while ((c = *p++) != '\0') {
11020 if (c == CTLQUOTEMARK)
11024 else if (SIT(c,BASESYNTAX) == CCTL)
11032 * Return true if the argument is a legal variable name (a letter or
11033 * underscore followed by zero or more letters, underscores, and digits).
11037 goodname(const char *name)
11045 if (! is_in_name(*p))
11053 * Called when an unexpected token is read during the parse. The argument
11054 * is the token that is expected, or -1 if more than one type of token can
11055 * occur at this point.
11065 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11067 sprintf(msg+l, " (expecting %s)", tokname(token));
11074 synerror(const char *msg)
11077 out2fmt("%s: %d: ", commandname, startlinno);
11078 out2fmt("Syntax error: %s\n", msg);
11079 error((char *)NULL);
11085 * called by editline -- any expansions to the prompt
11086 * should be added here.
11089 setprompt(int whichprompt)
11092 switch (whichprompt) {
11107 * Code for dealing with input/output redirection.
11110 #define EMPTY -2 /* marks an unused slot in redirtab */
11112 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11114 # define PIPESIZE PIPE_BUF
11119 * Open a file in noclobber mode.
11120 * The code was copied from bash.
11123 noclobberopen(const char *fname)
11126 struct stat finfo, finfo2;
11129 * If the file exists and is a regular file, return an error
11132 r = stat(fname, &finfo);
11133 if (r == 0 && S_ISREG(finfo.st_mode)) {
11139 * If the file was not present (r != 0), make sure we open it
11140 * exclusively so that if it is created before we open it, our open
11141 * will fail. Make sure that we do not truncate an existing file.
11142 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11143 * file was not a regular file, we leave O_EXCL off.
11146 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11147 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11149 /* If the open failed, return the file descriptor right away. */
11154 * OK, the open succeeded, but the file may have been changed from a
11155 * non-regular file to a regular file between the stat and the open.
11156 * We are assuming that the O_EXCL open handles the case where FILENAME
11157 * did not exist and is symlinked to an existing file between the stat
11162 * If we can open it and fstat the file descriptor, and neither check
11163 * revealed that it was a regular file, and the file has not been
11164 * replaced, return the file descriptor.
11166 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11167 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11170 /* The file has been replaced. badness. */
11177 * Handle here documents. Normally we fork off a process to write the
11178 * data to a pipe. If the document is short, we can stuff the data in
11179 * the pipe without forking.
11183 openhere(const union node *redir)
11189 error("Pipe call failed");
11190 if (redir->type == NHERE) {
11191 len = strlen(redir->nhere.doc->narg.text);
11192 if (len <= PIPESIZE) {
11193 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11197 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11199 signal(SIGINT, SIG_IGN);
11200 signal(SIGQUIT, SIG_IGN);
11201 signal(SIGHUP, SIG_IGN);
11203 signal(SIGTSTP, SIG_IGN);
11205 signal(SIGPIPE, SIG_DFL);
11206 if (redir->type == NHERE)
11207 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11209 expandhere(redir->nhere.doc, pip[1]);
11219 openredirect(const union node *redir)
11224 switch (redir->nfile.type) {
11226 fname = redir->nfile.expfname;
11227 if ((f = open(fname, O_RDONLY)) < 0)
11231 fname = redir->nfile.expfname;
11232 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11236 /* Take care of noclobber mode. */
11238 fname = redir->nfile.expfname;
11239 if ((f = noclobberopen(fname)) < 0)
11244 fname = redir->nfile.expfname;
11246 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11249 if ((f = creat(fname, 0666)) < 0)
11254 fname = redir->nfile.expfname;
11256 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11259 if ((f = open(fname, O_WRONLY)) < 0
11260 && (f = creat(fname, 0666)) < 0)
11262 lseek(f, (off_t)0, 2);
11269 /* Fall through to eliminate warning. */
11276 f = openhere(redir);
11282 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11284 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11289 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11290 * old file descriptors are stashed away so that the redirection can be
11291 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11292 * standard output, and the standard error if it becomes a duplicate of
11297 redirect(union node *redir, int flags)
11300 struct redirtab *sv = NULL;
11305 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11307 if (flags & REDIR_PUSH) {
11308 sv = ckmalloc(sizeof (struct redirtab));
11309 for (i = 0 ; i < 10 ; i++)
11310 sv->renamed[i] = EMPTY;
11311 sv->next = redirlist;
11314 for (n = redir ; n ; n = n->nfile.next) {
11317 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11318 n->ndup.dupfd == fd)
11319 continue; /* redirect from/to same file descriptor */
11322 newfd = openredirect(n);
11323 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11326 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11330 dupredirect(n, newfd, fd1dup);
11340 error("%d: %m", fd);
11346 if (flags & REDIR_PUSH) {
11347 sv->renamed[fd] = i;
11350 } else if (fd != newfd) {
11356 dupredirect(n, newfd, fd1dup);
11363 dupredirect(const union node *redir, int f, int fd1dup)
11365 int fd = redir->nfile.fd;
11369 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11370 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11371 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11372 dup_as_newfd(redir->ndup.dupfd, fd);
11378 dup_as_newfd(f, fd);
11387 * Undo the effects of the last redirection.
11393 struct redirtab *rp = redirlist;
11397 for (i = 0 ; i < 10 ; i++) {
11398 if (rp->renamed[i] != EMPTY) {
11402 if (rp->renamed[i] >= 0) {
11403 dup_as_newfd(rp->renamed[i], i);
11404 close(rp->renamed[i]);
11408 redirlist = rp->next;
11414 * Discard all saved file descriptors.
11419 struct redirtab *rp;
11422 for (rp = redirlist ; rp ; rp = rp->next) {
11423 for (i = 0 ; i < 10 ; i++) {
11424 if (rp->renamed[i] >= 0) {
11425 close(rp->renamed[i]);
11427 rp->renamed[i] = EMPTY;
11434 * Copy a file descriptor to be >= to. Returns -1
11435 * if the source file descriptor is closed, EMPTY if there are no unused
11436 * file descriptors left.
11440 dup_as_newfd(from, to)
11446 newfd = fcntl(from, F_DUPFD, to);
11448 if (errno == EMFILE)
11451 error("%d: %m", from);
11457 static void shtree (union node *, int, char *, FILE*);
11458 static void shcmd (union node *, FILE *);
11459 static void sharg (union node *, FILE *);
11460 static void indent (int, char *, FILE *);
11461 static void trstring (char *);
11468 trputs("showtree called\n");
11469 shtree(n, 1, NULL, stdout);
11474 shtree(n, ind, pfx, fp)
11480 struct nodelist *lp;
11486 indent(ind, pfx, fp);
11497 shtree(n->nbinary.ch1, ind, NULL, fp);
11500 shtree(n->nbinary.ch2, ind, NULL, fp);
11508 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11513 if (n->npipe.backgnd)
11519 fprintf(fp, "<node type %d>", n->type);
11539 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11545 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11551 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11552 s = redir_strings[np->nfile.type - NTO];
11558 switch (np->nfile.type) {
11559 case NTO: s = ">"; dftfd = 1; break;
11560 case NAPPEND: s = ">>"; dftfd = 1; break;
11561 case NTOFD: s = ">&"; dftfd = 1; break;
11562 case NTOOV: s = ">|"; dftfd = 1; break;
11563 case NFROM: s = "<"; dftfd = 0; break;
11564 case NFROMFD: s = "<&"; dftfd = 0; break;
11565 case NFROMTO: s = "<>"; dftfd = 0; break;
11566 default: s = "*error*"; dftfd = 0; break;
11569 if (np->nfile.fd != dftfd)
11570 fprintf(fp, "%d", np->nfile.fd);
11572 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11573 fprintf(fp, "%d", np->ndup.dupfd);
11575 sharg(np->nfile.fname, fp);
11589 struct nodelist *bqlist;
11592 if (arg->type != NARG) {
11593 printf("<node type %d>\n", arg->type);
11597 bqlist = arg->narg.backquote;
11598 for (p = arg->narg.text ; *p ; p++) {
11607 if (subtype == VSLENGTH)
11613 if (subtype & VSNUL)
11616 switch (subtype & VSTYPE) {
11635 case VSTRIMLEFTMAX:
11642 case VSTRIMRIGHTMAX:
11649 printf("<subtype %d>", subtype);
11656 case CTLBACKQ|CTLQUOTE:
11659 shtree(bqlist->n, -1, NULL, fp);
11671 indent(amount, pfx, fp)
11678 for (i = 0 ; i < amount ; i++) {
11679 if (pfx && i == amount - 1)
11697 static int debug = 1;
11699 static int debug = 0;
11707 if (tracefile == NULL)
11709 putc(c, tracefile);
11715 trace(const char *fmt, ...)
11719 if (tracefile != NULL) {
11720 (void) vfprintf(tracefile, fmt, va);
11721 if (strchr(fmt, '\n'))
11722 (void) fflush(tracefile);
11732 if (tracefile == NULL)
11734 fputs(s, tracefile);
11735 if (strchr(s, '\n'))
11747 if (tracefile == NULL)
11749 putc('"', tracefile);
11750 for (p = s ; *p ; p++) {
11752 case '\n': c = 'n'; goto backslash;
11753 case '\t': c = 't'; goto backslash;
11754 case '\r': c = 'r'; goto backslash;
11755 case '"': c = '"'; goto backslash;
11756 case '\\': c = '\\'; goto backslash;
11757 case CTLESC: c = 'e'; goto backslash;
11758 case CTLVAR: c = 'v'; goto backslash;
11759 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11760 case CTLBACKQ: c = 'q'; goto backslash;
11761 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11762 backslash: putc('\\', tracefile);
11763 putc(c, tracefile);
11766 if (*p >= ' ' && *p <= '~')
11767 putc(*p, tracefile);
11769 putc('\\', tracefile);
11770 putc(*p >> 6 & 03, tracefile);
11771 putc(*p >> 3 & 07, tracefile);
11772 putc(*p & 07, tracefile);
11777 putc('"', tracefile);
11785 if (tracefile == NULL)
11790 putc(' ', tracefile);
11792 putc('\n', tracefile);
11807 #ifdef not_this_way
11810 if ((p = getenv("HOME")) == NULL) {
11811 if (geteuid() == 0)
11817 strcat(s, "/trace");
11820 strcpy(s, "./trace");
11821 #endif /* not_this_way */
11822 if ((tracefile = fopen(s, "a")) == NULL) {
11823 fprintf(stderr, "Can't open %s\n", s);
11827 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11828 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11830 fputs("\nTracing started.\n", tracefile);
11837 * The trap builtin.
11841 trapcmd(argc, argv)
11850 for (signo = 0 ; signo < NSIG ; signo++) {
11851 if (trap[signo] != NULL) {
11855 p = single_quote(trap[signo]);
11856 sn = sys_siglist[signo];
11858 sn = u_signal_names(0, &signo, 0);
11861 printf("trap -- %s %s\n", p, sn);
11873 if ((signo = decode_signal(*ap, 0)) < 0)
11874 error("%s: bad trap", *ap);
11877 if (action[0] == '-' && action[1] == '\0')
11880 action = savestr(action);
11883 ckfree(trap[signo]);
11884 trap[signo] = action;
11899 * Set the signal handler for the specified signal. The routine figures
11900 * out what it should be set to.
11904 setsignal(int signo)
11908 struct sigaction act;
11910 if ((t = trap[signo]) == NULL)
11912 else if (*t != '\0')
11916 if (rootshell && action == S_DFL) {
11919 if (iflag || minusc || sflag == 0)
11945 t = &sigmode[signo - 1];
11948 * current setting unknown
11950 if (sigaction(signo, 0, &act) == -1) {
11952 * Pretend it worked; maybe we should give a warning
11953 * here, but other shells don't. We don't alter
11954 * sigmode, so that we retry every time.
11958 if (act.sa_handler == SIG_IGN) {
11959 if (mflag && (signo == SIGTSTP ||
11960 signo == SIGTTIN || signo == SIGTTOU)) {
11961 *t = S_IGN; /* don't hard ignore these */
11965 *t = S_RESET; /* force to be set */
11968 if (*t == S_HARD_IGN || *t == action)
11970 act.sa_handler = ((action == S_CATCH) ? onsig
11971 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11974 sigemptyset(&act.sa_mask);
11975 sigaction(signo, &act, 0);
11986 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11987 signal(signo, SIG_IGN);
11989 sigmode[signo - 1] = S_HARD_IGN;
12000 if (signo == SIGINT && trap[SIGINT] == NULL) {
12004 gotsig[signo - 1] = 1;
12010 * Called to execute a trap. Perhaps we should avoid entering new trap
12011 * handlers while we are executing a trap handler.
12021 for (i = 1 ; ; i++) {
12028 savestatus=exitstatus;
12029 evalstring(trap[i], 0);
12030 exitstatus=savestatus;
12037 * Called to exit the shell.
12041 exitshell(int status)
12043 struct jmploc loc1, loc2;
12046 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12047 if (setjmp(loc1.loc)) {
12050 if (setjmp(loc2.loc)) {
12054 if ((p = trap[0]) != NULL && *p != '\0') {
12058 l1: handler = &loc2; /* probably unnecessary */
12067 static int decode_signal(const char *string, int minsig)
12070 const char *name = u_signal_names(string, &signo, minsig);
12072 return name ? signo : -1;
12075 static struct var **hashvar (const char *);
12076 static void showvars (const char *, int, int);
12077 static struct var **findvar (struct var **, const char *);
12080 * Initialize the varable symbol tables and import the environment
12084 * This routine initializes the builtin variables. It is called when the
12085 * shell is initialized and again when a shell procedure is spawned.
12090 const struct varinit *ip;
12094 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12095 if ((vp->flags & VEXPORT) == 0) {
12096 vpp = hashvar(ip->text);
12099 vp->text = strdup(ip->text);
12100 vp->flags = ip->flags;
12101 vp->func = ip->func;
12105 * PS1 depends on uid
12107 if ((vps1.flags & VEXPORT) == 0) {
12108 vpp = hashvar("PS1=");
12111 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12112 vps1.flags = VSTRFIXED|VTEXTFIXED;
12117 * Set the value of a variable. The flags argument is ored with the
12118 * flags of the variable. If val is NULL, the variable is unset.
12122 setvar(name, val, flags)
12123 const char *name, *val;
12139 if (! is_in_name(*p)) {
12140 if (*p == '\0' || *p == '=')
12146 namelen = p - name;
12148 error("%.*s: bad variable name", namelen, name);
12149 len = namelen + 2; /* 2 is space for '=' and '\0' */
12153 len += vallen = strlen(val);
12156 nameeq = ckmalloc(len);
12157 memcpy(nameeq, name, namelen);
12158 nameeq[namelen] = '=';
12160 memcpy(nameeq + namelen + 1, val, vallen + 1);
12162 nameeq[namelen + 1] = '\0';
12164 setvareq(nameeq, flags);
12171 * Same as setvar except that the variable and value are passed in
12172 * the first argument as name=value. Since the first argument will
12173 * be actually stored in the table, it should not be a string that
12182 struct var *vp, **vpp;
12185 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12186 if ((vp = *findvar(vpp, s))) {
12187 if (vp->flags & VREADONLY) {
12188 size_t len = strchr(s, '=') - s;
12189 error("%.*s: is read only", len, s);
12193 if (vp->func && (flags & VNOFUNC) == 0)
12194 (*vp->func)(strchr(s, '=') + 1);
12196 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12199 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12200 vp->flags |= flags;
12204 * We could roll this to a function, to handle it as
12205 * a regular variable function callback, but why bother?
12207 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12213 vp = ckmalloc(sizeof (*vp));
12224 * Process a linked list of variable assignments.
12229 struct strlist *mylist;
12231 struct strlist *lp;
12234 for (lp = mylist ; lp ; lp = lp->next) {
12235 setvareq(savestr(lp->text), 0);
12243 * Find the value of a variable. Returns NULL if not set.
12246 static const char *
12252 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12253 return strchr(v->text, '=') + 1;
12261 * Search the environment of a builtin command.
12264 static const char *
12265 bltinlookup(const char *name)
12267 const struct strlist *sp;
12269 for (sp = cmdenviron ; sp ; sp = sp->next) {
12270 if (varequal(sp->text, name))
12271 return strchr(sp->text, '=') + 1;
12273 return lookupvar(name);
12279 * Generate a list of exported variables. This routine is used to construct
12280 * the third argument to execve when executing a program.
12292 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12293 for (vp = *vpp ; vp ; vp = vp->next)
12294 if (vp->flags & VEXPORT)
12297 ep = env = stalloc((nenv + 1) * sizeof *env);
12298 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12299 for (vp = *vpp ; vp ; vp = vp->next)
12300 if (vp->flags & VEXPORT)
12309 * Called when a shell procedure is invoked to clear out nonexported
12310 * variables. It is also necessary to reallocate variables of with
12311 * VSTACK set since these are currently allocated on the stack.
12317 struct var *vp, **prev;
12319 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12320 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12321 if ((vp->flags & VEXPORT) == 0) {
12323 if ((vp->flags & VTEXTFIXED) == 0)
12325 if ((vp->flags & VSTRFIXED) == 0)
12328 if (vp->flags & VSTACK) {
12329 vp->text = savestr(vp->text);
12330 vp->flags &=~ VSTACK;
12342 * Command to list all variables which are set. Currently this command
12343 * is invoked from the set command when the set command is called without
12348 showvarscmd(argc, argv)
12352 showvars(nullstr, VUNSET, VUNSET);
12359 * The export and readonly commands.
12363 exportcmd(argc, argv)
12370 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12373 listsetvar(cmdenviron);
12374 pflag = (nextopt("p") == 'p');
12375 if (argc > 1 && !pflag) {
12376 while ((name = *argptr++) != NULL) {
12377 if ((p = strchr(name, '=')) != NULL) {
12380 if ((vp = *findvar(hashvar(name), name))) {
12385 setvar(name, p, flag);
12389 showvars(argv[0], flag, 0);
12396 * The "local" command.
12399 /* funcnest nonzero if we are currently evaluating a function */
12402 localcmd(argc, argv)
12409 error("Not in a function");
12410 while ((name = *argptr++) != NULL) {
12418 * Make a variable a local variable. When a variable is made local, it's
12419 * value and flags are saved in a localvar structure. The saved values
12420 * will be restored when the shell function returns. We handle the name
12421 * "-" as a special case.
12428 struct localvar *lvp;
12433 lvp = ckmalloc(sizeof (struct localvar));
12434 if (name[0] == '-' && name[1] == '\0') {
12436 p = ckmalloc(sizeof optet_vals);
12437 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12440 vpp = hashvar(name);
12441 vp = *findvar(vpp, name);
12443 if (strchr(name, '='))
12444 setvareq(savestr(name), VSTRFIXED);
12446 setvar(name, NULL, VSTRFIXED);
12447 vp = *vpp; /* the new variable */
12449 lvp->flags = VUNSET;
12451 lvp->text = vp->text;
12452 lvp->flags = vp->flags;
12453 vp->flags |= VSTRFIXED|VTEXTFIXED;
12454 if (strchr(name, '='))
12455 setvareq(savestr(name), 0);
12459 lvp->next = localvars;
12466 * Called after a function returns.
12471 struct localvar *lvp;
12474 while ((lvp = localvars) != NULL) {
12475 localvars = lvp->next;
12477 if (vp == NULL) { /* $- saved */
12478 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12480 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12481 (void)unsetvar(vp->text);
12483 if ((vp->flags & VTEXTFIXED) == 0)
12485 vp->flags = lvp->flags;
12486 vp->text = lvp->text;
12494 setvarcmd(argc, argv)
12499 return unsetcmd(argc, argv);
12500 else if (argc == 3)
12501 setvar(argv[1], argv[2], 0);
12503 error("List assignment not implemented");
12509 * The unset builtin command. We unset the function before we unset the
12510 * variable to allow a function to be unset when there is a readonly variable
12511 * with the same name.
12515 unsetcmd(argc, argv)
12525 while ((i = nextopt("vf")) != '\0') {
12531 if (flg_func == 0 && flg_var == 0)
12534 for (ap = argptr; *ap ; ap++) {
12538 ret |= unsetvar(*ap);
12545 * Unset the specified variable.
12549 unsetvar(const char *s)
12554 vpp = findvar(hashvar(s), s);
12557 if (vp->flags & VREADONLY)
12560 if (*(strchr(vp->text, '=') + 1) != '\0')
12561 setvar(s, nullstr, 0);
12562 vp->flags &= ~VEXPORT;
12563 vp->flags |= VUNSET;
12564 if ((vp->flags & VSTRFIXED) == 0) {
12565 if ((vp->flags & VTEXTFIXED) == 0)
12580 * Find the appropriate entry in the hash table from the name.
12583 static struct var **
12584 hashvar(const char *p)
12586 unsigned int hashval;
12588 hashval = ((unsigned char) *p) << 4;
12589 while (*p && *p != '=')
12590 hashval += (unsigned char) *p++;
12591 return &vartab[hashval % VTABSIZE];
12597 * Returns true if the two strings specify the same varable. The first
12598 * variable name is terminated by '='; the second may be terminated by
12599 * either '=' or '\0'.
12603 varequal(const char *p, const char *q)
12605 while (*p == *q++) {
12609 if (*p == '=' && *(q - 1) == '\0')
12615 showvars(const char *myprefix, int mask, int xor)
12619 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12621 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12622 for (vp = *vpp ; vp ; vp = vp->next) {
12623 if ((vp->flags & mask) ^ xor) {
12627 p = strchr(vp->text, '=') + 1;
12628 len = p - vp->text;
12629 p = single_quote(p);
12631 printf("%s%s%.*s%s\n", myprefix, sep, len,
12639 static struct var **
12640 findvar(struct var **vpp, const char *name)
12642 for (; *vpp; vpp = &(*vpp)->next) {
12643 if (varequal((*vpp)->text, name)) {
12651 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12652 * This file contains code for the times builtin.
12653 * $Id: ash.c,v 1.33 2001/10/31 10:40:37 andersen Exp $
12655 static int timescmd (int argc, char **argv)
12658 long int clk_tck = sysconf(_SC_CLK_TCK);
12661 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12662 (int) (buf.tms_utime / clk_tck / 60),
12663 ((double) buf.tms_utime) / clk_tck,
12664 (int) (buf.tms_stime / clk_tck / 60),
12665 ((double) buf.tms_stime) / clk_tck,
12666 (int) (buf.tms_cutime / clk_tck / 60),
12667 ((double) buf.tms_cutime) / clk_tck,
12668 (int) (buf.tms_cstime / clk_tck / 60),
12669 ((double) buf.tms_cstime) / clk_tck);
12673 #ifdef ASH_MATH_SUPPORT
12674 /* The let builtin. */
12675 int letcmd(int argc, char **argv)
12680 char *tmp, *expression, p[13];
12681 expression = strchr(argv[1], '=');
12683 /* Cannot use 'error()' here, or the return code
12684 * will be incorrect */
12685 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12688 *expression = '\0';
12689 tmp = ++expression;
12690 result = arith(tmp, &errcode);
12692 /* Cannot use 'error()' here, or the return code
12693 * will be incorrect */
12694 out2fmt("sh: let: ");
12696 out2fmt("divide by zero");
12698 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12701 snprintf(p, 12, "%ld", result);
12702 setvar(argv[1], savestr(p), 0);
12703 } else if (argc >= 3)
12704 synerror("invalid operand");
12712 * Copyright (c) 1989, 1991, 1993, 1994
12713 * The Regents of the University of California. All rights reserved.
12715 * This code is derived from software contributed to Berkeley by
12716 * Kenneth Almquist.
12718 * Redistribution and use in source and binary forms, with or without
12719 * modification, are permitted provided that the following conditions
12721 * 1. Redistributions of source code must retain the above copyright
12722 * notice, this list of conditions and the following disclaimer.
12723 * 2. Redistributions in binary form must reproduce the above copyright
12724 * notice, this list of conditions and the following disclaimer in the
12725 * documentation and/or other materials provided with the distribution.
12727 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12728 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12730 * 4. Neither the name of the University nor the names of its contributors
12731 * may be used to endorse or promote products derived from this software
12732 * without specific prior written permission.
12734 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12735 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12736 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12737 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12738 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12739 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12740 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12741 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12742 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12743 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF