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 static void trace (const char *, ...);
363 static void trargs (char **);
364 static void showtree (union node *);
365 static void trputc (int);
366 static void trputs (const char *);
367 static void opentrace (void);
402 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
403 #define EXP_TILDE 0x2 /* do normal tilde expansion */
404 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
405 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
406 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
407 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
412 static char optet_vals[NOPTS];
414 static const char * const optlist[NOPTS] = {
433 #define optent_name(optent) (optent+1)
434 #define optent_letter(optent) optent[0]
435 #define optent_val(optent) optet_vals[optent]
437 #define eflag optent_val(0)
438 #define fflag optent_val(1)
439 #define Iflag optent_val(2)
440 #define iflag optent_val(3)
441 #define mflag optent_val(4)
442 #define nflag optent_val(5)
443 #define sflag optent_val(6)
444 #define xflag optent_val(7)
445 #define vflag optent_val(8)
446 #define Vflag optent_val(9)
447 #define Eflag optent_val(10)
448 #define Cflag optent_val(11)
449 #define aflag optent_val(12)
450 #define bflag optent_val(13)
451 #define uflag optent_val(14)
452 #define qflag optent_val(15)
455 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
473 union node *redirect;
480 struct nodelist *cmdlist;
487 union node *redirect;
495 union node *elsepart;
526 struct nodelist *backquote;
564 struct nbinary nbinary;
567 struct nredir nredir;
571 struct nclist nclist;
581 struct nodelist *next;
585 struct backcmd { /* result of evalbackcmd */
586 int fd; /* file descriptor to read from */
587 char *buf; /* buffer */
588 int nleft; /* number of chars in buffer */
589 struct job *jp; /* job structure for command */
597 const struct builtincmd *cmd;
602 struct strlist *next;
608 struct strlist *list;
609 struct strlist **lastp;
613 struct strpush *prev; /* preceding string on stack */
617 struct alias *ap; /* if push was associated with an alias */
619 char *string; /* remember the string since it may change */
623 struct parsefile *prev; /* preceding file on stack */
624 int linno; /* current line */
625 int fd; /* file descriptor (or -1 if string) */
626 int nleft; /* number of chars left in this line */
627 int lleft; /* number of chars left in this buffer */
628 char *nextc; /* next char in buffer */
629 char *buf; /* input buffer */
630 struct strpush *strpush; /* for pushing strings at this level */
631 struct strpush basestrpush; /* so pushing one is fast */
635 struct stack_block *stackp;
638 struct stackmark *marknext;
642 int nparam; /* # of positional parameters (without $0) */
643 unsigned char malloc; /* if parameter list dynamically allocated */
644 char **p; /* parameter list */
645 int optind; /* next parameter to be processed by getopts */
646 int optoff; /* used by getopts */
650 * When commands are first encountered, they are entered in a hash table.
651 * This ensures that a full path search will not have to be done for them
652 * on each invocation.
654 * We should investigate converting to a linear search, even though that
655 * would make the command name "hash" a misnomer.
657 #define CMDTABLESIZE 31 /* should be prime */
658 #define ARB 1 /* actual size determined at run time */
663 struct tblentry *next; /* next entry in hash chain */
664 union param param; /* definition of builtin function */
665 short cmdtype; /* index identifying command */
666 char rehash; /* if set, cd done since entry created */
667 char cmdname[ARB]; /* name of command */
671 static struct tblentry *cmdtable[CMDTABLESIZE];
672 static int builtinloc = -1; /* index in path of %builtin, or -1 */
673 static int exerrno = 0; /* Last exec error */
676 static void tryexec (char *, char **, char **);
677 static void printentry (struct tblentry *, int);
678 static void clearcmdentry (int);
679 static struct tblentry *cmdlookup (const char *, int);
680 static void delete_cmd_entry (void);
681 static int path_change (const char *, int *);
684 static void flushall (void);
685 static void out2fmt (const char *, ...)
686 __attribute__((__format__(__printf__,1,2)));
687 static int xwrite (int, const char *, int);
689 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
690 static void out1str(const char *p) { outstr(p, stdout); }
691 static void out2str(const char *p) { outstr(p, stderr); }
693 #ifndef ASH_OPTIMIZE_FOR_SIZE
694 #define out2c(c) putc((c), stderr)
696 static void out2c(int c) { putc(c, stderr); }
700 #ifdef ASH_OPTIMIZE_FOR_SIZE
701 #define USE_SIT_FUNCTION
704 /* number syntax index */
705 #define BASESYNTAX 0 /* not in quotes */
706 #define DQSYNTAX 1 /* in double quotes */
707 #define SQSYNTAX 2 /* in single quotes */
708 #define ARISYNTAX 3 /* in arithmetic */
710 static const char S_I_T[][4] = {
711 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
712 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
713 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
714 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
715 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
716 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
717 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
718 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
719 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
720 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
721 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
722 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
723 #ifndef USE_SIT_FUNCTION
724 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
725 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
726 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
730 #ifdef USE_SIT_FUNCTION
732 #define U_C(c) ((unsigned char)(c))
734 static int SIT(int c, int syntax)
736 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
737 static const char syntax_index_table [] = {
738 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
739 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
740 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
745 if(c==PEOF) /* 2^8+2 */
747 if(c==PEOA) /* 2^8+1 */
749 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
752 s = strchr(spec_symbls, c);
755 indx = syntax_index_table[(s-spec_symbls)];
757 return S_I_T[indx][syntax];
760 #else /* USE_SIT_FUNCTION */
762 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
764 #define CSPCL_CIGN_CIGN_CIGN 0
765 #define CSPCL_CWORD_CWORD_CWORD 1
766 #define CNL_CNL_CNL_CNL 2
767 #define CWORD_CCTL_CCTL_CWORD 3
768 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
769 #define CVAR_CVAR_CWORD_CVAR 5
770 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
771 #define CSPCL_CWORD_CWORD_CLP 7
772 #define CSPCL_CWORD_CWORD_CRP 8
773 #define CBACK_CBACK_CCTL_CBACK 9
774 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
775 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
776 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
777 #define CWORD_CWORD_CWORD_CWORD 13
778 #define CCTL_CCTL_CCTL_CCTL 14
780 static const char syntax_index_table[258] = {
781 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
782 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
783 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
784 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
785 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
786 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
787 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
788 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
789 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
790 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
791 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
792 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
793 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
794 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
795 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
796 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
797 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
798 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
799 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
800 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
801 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
802 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
803 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
804 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
805 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
806 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
807 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
808 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
809 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
810 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
811 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
812 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
813 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
814 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
815 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
816 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
817 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
818 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
819 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
820 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
821 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
822 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
823 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
824 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
825 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
826 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
827 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
828 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
829 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
830 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
831 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
832 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
833 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
834 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
835 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
836 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
837 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
838 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
839 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
840 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
841 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
842 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
843 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
844 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
845 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
846 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
847 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
848 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
849 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
850 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
851 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
852 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
853 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
854 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
855 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
856 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
857 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
858 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
859 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
860 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
861 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
862 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
863 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
864 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
865 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
866 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
867 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
868 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
869 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
870 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
871 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
872 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
873 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
874 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
875 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
876 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
877 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
878 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
879 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
880 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
881 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
882 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
883 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
884 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
885 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
886 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
887 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
888 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
889 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
890 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
891 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
892 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
893 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
894 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
895 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
896 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
897 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
898 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
899 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
900 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
901 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
902 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
903 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
904 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
905 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
906 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
907 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
908 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
909 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
910 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
911 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
912 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
913 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
914 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
915 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
916 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
917 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
918 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
919 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
920 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
921 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
922 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
923 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
924 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
925 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
926 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
927 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
928 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
929 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
930 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
931 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
932 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
933 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
934 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
935 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
936 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
937 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
938 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
939 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
940 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
941 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
942 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
943 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
944 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
945 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
946 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
947 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
948 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
949 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
950 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
951 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
952 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
953 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
954 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
955 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
956 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
957 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
958 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
959 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
960 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
961 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
962 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
963 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
964 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
965 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
966 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
967 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
968 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
969 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
970 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
971 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
972 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
973 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
974 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
975 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
976 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
977 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
978 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
979 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
980 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
981 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
982 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
983 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
984 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
985 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
986 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
987 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
988 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
989 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
990 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
991 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
992 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
993 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
994 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
995 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
996 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
997 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
998 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
999 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1004 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1005 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1006 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1009 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1032 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1033 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1034 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1035 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1036 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1037 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1038 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1039 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1042 #endif /* USE_SIT_FUNCTION */
1045 /* first char is indicating which tokens mark the end of a list */
1046 static const char *const tokname_array[] = {
1061 #define KWDOFFSET 14
1062 /* the following are keywords */
1081 static const char *tokname(int tok)
1083 static char buf[16];
1087 sprintf(buf+(tok>=TSEMI), "%s%c",
1088 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1092 static int plinno = 1; /* input line number */
1094 static int parselleft; /* copy of parsefile->lleft */
1096 static struct parsefile basepf; /* top level input file */
1097 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1098 static struct parsefile *parsefile = &basepf; /* current input file */
1101 * NEOF is returned by parsecmd when it encounters an end of file. It
1102 * must be distinct from NULL, so we use the address of a variable that
1103 * happens to be handy.
1106 static int tokpushback; /* last token pushed back */
1107 #define NEOF ((union node *)&tokpushback)
1108 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1111 static void error (const char *, ...) __attribute__((__noreturn__));
1112 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1113 static void shellexec (char **, char **, const char *, int)
1114 __attribute__((noreturn));
1115 static void exitshell (int) __attribute__((noreturn));
1117 static int goodname(const char *);
1118 static void ignoresig (int);
1119 static void onsig (int);
1120 static void dotrap (void);
1121 static int decode_signal (const char *, int);
1123 static void shprocvar(void);
1124 static void deletefuncs(void);
1125 static void setparam (char **);
1126 static void freeparam (volatile struct shparam *);
1128 /* reasons for skipping commands (see comment on breakcmd routine) */
1134 /* values of cmdtype */
1135 #define CMDUNKNOWN -1 /* no entry in table for command */
1136 #define CMDNORMAL 0 /* command is an executable program */
1137 #define CMDBUILTIN 1 /* command is a shell builtin */
1138 #define CMDFUNCTION 2 /* command is a shell function */
1140 #define DO_ERR 1 /* find_command prints errors */
1141 #define DO_ABS 2 /* find_command checks absolute paths */
1142 #define DO_NOFUN 4 /* find_command ignores functions */
1143 #define DO_BRUTE 8 /* find_command ignores hash table */
1150 #define VEXPORT 0x01 /* variable is exported */
1151 #define VREADONLY 0x02 /* variable cannot be modified */
1152 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1153 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1154 #define VSTACK 0x10 /* text is allocated on the stack */
1155 #define VUNSET 0x20 /* the variable is not set */
1156 #define VNOFUNC 0x40 /* don't call the callback function */
1160 struct var *next; /* next entry in hash list */
1161 int flags; /* flags are defined above */
1162 char *text; /* name=value */
1163 void (*func) (const char *);
1164 /* function to be called when */
1165 /* the variable gets set/unset */
1169 struct localvar *next; /* next local variable in list */
1170 struct var *vp; /* the variable that was made local */
1171 int flags; /* saved flags */
1172 char *text; /* saved text */
1176 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1177 #define rmescapes(p) _rmescapes((p), 0)
1178 static char *_rmescapes (char *, int);
1180 static void rmescapes (char *);
1183 static int casematch (union node *, const char *);
1184 static void clearredir(void);
1185 static void popstring(void);
1186 static void readcmdfile (const char *);
1188 static int number (const char *);
1189 static int is_number (const char *, int *num);
1190 static char *single_quote (const char *);
1191 static int nextopt (const char *);
1193 static void redirect (union node *, int);
1194 static void popredir (void);
1195 static int dup_as_newfd (int, int);
1197 static void changepath(const char *newval);
1198 static void getoptsreset(const char *value);
1201 static int parsenleft; /* copy of parsefile->nleft */
1202 static char *parsenextc; /* copy of parsefile->nextc */
1203 static int rootpid; /* pid of main shell */
1204 static int rootshell; /* true if we aren't a child of the main shell */
1206 static const char spcstr[] = " ";
1207 static const char snlfmt[] = "%s\n";
1209 static int sstrnleft;
1210 static int herefd = -1;
1212 static struct localvar *localvars;
1214 static struct var vifs;
1215 static struct var vmail;
1216 static struct var vmpath;
1217 static struct var vpath;
1218 static struct var vps1;
1219 static struct var vps2;
1220 static struct var voptind;
1221 #ifdef CONFIG_LOCALE_SUPPORT
1222 static struct var vlc_all;
1223 static struct var vlc_ctype;
1230 void (*func) (const char *);
1233 static const char defpathvar[] =
1234 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1235 #define defpath (defpathvar + 5)
1238 static const char defifsvar[] = "IFS= \t\n";
1239 #define defifs (defifsvar + 4)
1241 static const char defifs[] = " \t\n";
1244 static const struct varinit varinit[] = {
1246 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1248 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1251 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1253 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1255 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1258 * vps1 depends on uid
1260 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1262 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1264 #ifdef CONFIG_LOCALE_SUPPORT
1265 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1267 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1276 static struct var *vartab[VTABSIZE];
1279 * The following macros access the values of the above variables.
1280 * They have to skip over the name. They return the null string
1281 * for unset variables.
1284 #define ifsval() (vifs.text + 4)
1285 #define ifsset() ((vifs.flags & VUNSET) == 0)
1286 #define mailval() (vmail.text + 5)
1287 #define mpathval() (vmpath.text + 9)
1288 #define pathval() (vpath.text + 5)
1289 #define ps1val() (vps1.text + 4)
1290 #define ps2val() (vps2.text + 4)
1291 #define optindval() (voptind.text + 7)
1293 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1295 static void initvar (void);
1296 static void setvar (const char *, const char *, int);
1297 static void setvareq (char *, int);
1298 static void listsetvar (struct strlist *);
1299 static const char *lookupvar (const char *);
1300 static const char *bltinlookup (const char *);
1301 static char **environment (void);
1302 static int showvarscmd (int, char **);
1303 static void mklocal (char *);
1304 static void poplocalvars (void);
1305 static int unsetvar (const char *);
1306 static int varequal (const char *, const char *);
1309 static char *arg0; /* value of $0 */
1310 static struct shparam shellparam; /* current positional parameters */
1311 static char **argptr; /* argument list for builtin commands */
1312 static char *optionarg; /* set by nextopt (like getopt) */
1313 static char *optptr; /* used by nextopt */
1314 static char *minusc; /* argument to -c option */
1319 #define ALIASINUSE 1
1331 static struct alias *atab[ATABSIZE];
1333 static void setalias (char *, char *);
1334 static struct alias **hashalias (const char *);
1335 static struct alias *freealias (struct alias *);
1336 static struct alias **__lookupalias (const char *);
1342 struct alias *ap, **app;
1344 app = __lookupalias(name);
1348 if (!(ap->flag & ALIASINUSE)) {
1351 ap->val = savestr(val);
1352 ap->flag &= ~ALIASDEAD;
1355 ap = ckmalloc(sizeof (struct alias));
1356 ap->name = savestr(name);
1357 ap->val = savestr(val);
1370 app = __lookupalias(name);
1374 *app = freealias(*app);
1385 struct alias *ap, **app;
1389 for (i = 0; i < ATABSIZE; i++) {
1391 for (ap = *app; ap; ap = *app) {
1392 *app = freealias(*app);
1401 static struct alias *
1402 lookupalias(const char *name, int check)
1404 struct alias *ap = *__lookupalias(name);
1406 if (check && ap && (ap->flag & ALIASINUSE))
1412 printalias(const struct alias *ap) {
1415 p = single_quote(ap->val);
1416 printf("alias %s=%s\n", ap->name, p);
1422 * TODO - sort output
1425 aliascmd(int argc, char **argv)
1434 for (i = 0; i < ATABSIZE; i++)
1435 for (ap = atab[i]; ap; ap = ap->next) {
1440 while ((n = *++argv) != NULL) {
1441 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1442 if ((ap = *__lookupalias(n)) == NULL) {
1443 out2fmt("%s: %s not found\n", "alias", n);
1458 unaliascmd(int argc, char **argv)
1462 while ((i = nextopt("a")) != '\0') {
1468 for (i = 0; *argptr; argptr++) {
1469 if (unalias(*argptr)) {
1470 out2fmt("%s: %s not found\n", "unalias", *argptr);
1478 static struct alias **
1482 unsigned int hashval;
1487 return &atab[hashval % ATABSIZE];
1490 static struct alias *
1491 freealias(struct alias *ap) {
1494 if (ap->flag & ALIASINUSE) {
1495 ap->flag |= ALIASDEAD;
1507 static struct alias **
1508 __lookupalias(const char *name) {
1509 struct alias **app = hashalias(name);
1511 for (; *app; app = &(*app)->next) {
1512 if (equal(name, (*app)->name)) {
1521 #ifdef ASH_MATH_SUPPORT
1522 /* The generated file arith.c has been replaced with a custom hand
1523 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1524 * This is now part of libbb, so that it can be used by all the shells
1526 static void expari (int);
1529 static char *trap[NSIG]; /* trap handler commands */
1530 static char sigmode[NSIG - 1]; /* current value of signal */
1531 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1532 static int pendingsigs; /* indicates some signal received */
1535 * This file was generated by the mkbuiltins program.
1539 static int bgcmd (int, char **);
1540 static int fgcmd (int, char **);
1541 static int killcmd (int, char **);
1543 static int bltincmd (int, char **);
1544 static int cdcmd (int, char **);
1545 static int breakcmd (int, char **);
1547 static int commandcmd (int, char **);
1549 static int dotcmd (int, char **);
1550 static int evalcmd (int, char **);
1551 static int execcmd (int, char **);
1552 static int exitcmd (int, char **);
1553 static int exportcmd (int, char **);
1554 static int histcmd (int, char **);
1555 static int hashcmd (int, char **);
1556 static int helpcmd (int, char **);
1557 static int jobscmd (int, char **);
1558 static int localcmd (int, char **);
1559 static int pwdcmd (int, char **);
1560 static int readcmd (int, char **);
1561 static int returncmd (int, char **);
1562 static int setcmd (int, char **);
1563 static int setvarcmd (int, char **);
1564 static int shiftcmd (int, char **);
1565 static int trapcmd (int, char **);
1566 static int umaskcmd (int, char **);
1568 static int aliascmd (int, char **);
1569 static int unaliascmd (int, char **);
1571 static int unsetcmd (int, char **);
1572 static int waitcmd (int, char **);
1573 static int ulimitcmd (int, char **);
1574 static int timescmd (int, char **);
1575 #ifdef ASH_MATH_SUPPORT
1576 static int letcmd (int, char **);
1578 static int typecmd (int, char **);
1580 static int getoptscmd (int, char **);
1583 #ifndef CONFIG_TRUE_FALSE
1584 static int true_main (int, char **);
1585 static int false_main (int, char **);
1588 static void setpwd (const char *, int);
1591 #define BUILTIN_NOSPEC "0"
1592 #define BUILTIN_SPECIAL "1"
1593 #define BUILTIN_REGULAR "2"
1594 #define BUILTIN_ASSIGN "4"
1595 #define BUILTIN_SPEC_ASSG "5"
1596 #define BUILTIN_REG_ASSG "6"
1598 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1599 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1600 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1604 int (*const builtinfunc) (int, char **);
1609 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1610 * the binary search in find_builtin() will stop working. If you value
1611 * your kneecaps, you'll be sure to *make sure* that any changes made
1612 * to this array result in the listing remaining in ascii order. You
1615 static const struct builtincmd builtincmds[] = {
1616 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1617 { BUILTIN_SPECIAL ":", true_main },
1619 { BUILTIN_REG_ASSG "alias", aliascmd },
1622 { BUILTIN_REGULAR "bg", bgcmd },
1624 { BUILTIN_SPECIAL "break", breakcmd },
1625 { BUILTIN_SPECIAL "builtin", bltincmd },
1626 { BUILTIN_REGULAR "cd", cdcmd },
1627 { BUILTIN_NOSPEC "chdir", cdcmd },
1629 { BUILTIN_REGULAR "command", commandcmd },
1631 { BUILTIN_SPECIAL "continue", breakcmd },
1632 { BUILTIN_SPECIAL "eval", evalcmd },
1633 { BUILTIN_SPECIAL "exec", execcmd },
1634 { BUILTIN_SPECIAL "exit", exitcmd },
1635 { BUILTIN_SPEC_ASSG "export", exportcmd },
1636 { BUILTIN_REGULAR "false", false_main },
1637 { BUILTIN_REGULAR "fc", histcmd },
1639 { BUILTIN_REGULAR "fg", fgcmd },
1642 { BUILTIN_REGULAR "getopts", getoptscmd },
1644 { BUILTIN_NOSPEC "hash", hashcmd },
1645 { BUILTIN_NOSPEC "help", helpcmd },
1646 { BUILTIN_REGULAR "jobs", jobscmd },
1648 { BUILTIN_REGULAR "kill", killcmd },
1650 #ifdef ASH_MATH_SUPPORT
1651 { BUILTIN_REGULAR "let", letcmd },
1653 { BUILTIN_ASSIGN "local", localcmd },
1654 { BUILTIN_NOSPEC "pwd", pwdcmd },
1655 { BUILTIN_REGULAR "read", readcmd },
1656 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1657 { BUILTIN_SPECIAL "return", returncmd },
1658 { BUILTIN_SPECIAL "set", setcmd },
1659 { BUILTIN_NOSPEC "setvar", setvarcmd },
1660 { BUILTIN_SPECIAL "shift", shiftcmd },
1661 { BUILTIN_SPECIAL "times", timescmd },
1662 { BUILTIN_SPECIAL "trap", trapcmd },
1663 { BUILTIN_REGULAR "true", true_main },
1664 { BUILTIN_NOSPEC "type", typecmd },
1665 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1666 { BUILTIN_REGULAR "umask", umaskcmd },
1668 { BUILTIN_REGULAR "unalias", unaliascmd },
1670 { BUILTIN_SPECIAL "unset", unsetcmd },
1671 { BUILTIN_REGULAR "wait", waitcmd },
1673 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1675 #define DOTCMD &builtincmds[0]
1676 static struct builtincmd *BLTINCMD;
1677 static struct builtincmd *EXECCMD;
1678 static struct builtincmd *EVALCMD;
1681 #define JOBSTOPPED 1 /* all procs are stopped */
1682 #define JOBDONE 2 /* all procs are completed */
1685 * A job structure contains information about a job. A job is either a
1686 * single process or a set of processes contained in a pipeline. In the
1687 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1692 pid_t pid; /* process id */
1693 int status; /* status flags (defined above) */
1694 char *cmd; /* text of command being run */
1698 static int job_warning; /* user was warned about stopped jobs */
1701 static void setjobctl(int enable);
1703 #define setjobctl(on) /* do nothing */
1708 struct procstat ps0; /* status of process */
1709 struct procstat *ps; /* status or processes when more than one */
1710 short nprocs; /* number of processes */
1711 short pgrp; /* process group of this job */
1712 char state; /* true if job is finished */
1713 char used; /* true if this entry is in used */
1714 char changed; /* true if status has changed */
1716 char jobctl; /* job running under job control */
1720 static struct job *jobtab; /* array of jobs */
1721 static int njobs; /* size of array */
1722 static int backgndpid = -1; /* pid of last background process */
1724 static int initialpgrp; /* pgrp of shell on invocation */
1725 static int curjob; /* current job */
1728 static int intreceived;
1730 static struct job *makejob (const union node *, int);
1731 static int forkshell (struct job *, const union node *, int);
1732 static int waitforjob (struct job *);
1734 static int docd (char *, int);
1735 static void updatepwd (const char *);
1736 static void getpwd (void);
1738 static char *padvance (const char **, const char *);
1740 static char nullstr[1]; /* zero length string */
1741 static char *curdir = nullstr; /* current working directory */
1755 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1756 error("HOME not set");
1759 if (dest[0] == '-' && dest[1] == '\0') {
1760 dest = bltinlookup("OLDPWD");
1761 if (!dest || !*dest) {
1770 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1772 while ((p = padvance(&path, dest)) != NULL) {
1773 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1778 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1780 print = strcmp(p, dest);
1782 if (docd(p, print) >= 0)
1787 error("can't cd to %s", dest);
1793 * Actually do the chdir. In an interactive shell, print the
1794 * directory name if "print" is nonzero.
1798 docd(char *dest, int print)
1800 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1802 if (chdir(dest) < 0) {
1809 printf(snlfmt, curdir);
1815 * Update curdir (the name of the current directory) in response to a
1816 * cd command. We also call hashcd to let the routines in exec.c know
1817 * that the current directory has changed.
1820 static void hashcd (void);
1823 updatepwd(const char *dir)
1825 hashcd(); /* update command hash table */
1827 /* If our argument is NULL, we don't know the current directory */
1828 if (dir == NULL || curdir == nullstr) {
1837 pwdcmd(int argc, char **argv)
1839 printf(snlfmt, curdir);
1843 /* Ask system the current directory */
1847 curdir = xgetcwd(0);
1853 setpwd(const char *val, int setold)
1858 setvar("OLDPWD", curdir, VEXPORT);
1861 if (curdir != nullstr) {
1862 if(val!=NULL && *val != '/')
1863 val = cated = concat_path_file(curdir, val);
1869 curdir = simplify_path(val);
1872 setvar("PWD", curdir, VEXPORT);
1876 * Errors and exceptions.
1880 * Code to handle exceptions in C.
1884 * We enclose jmp_buf in a structure so that we can declare pointers to
1885 * jump locations. The global variable handler contains the location to
1886 * jump to when an exception occurs, and the global variable exception
1887 * contains a code identifying the exeception. To implement nested
1888 * exception handlers, the user should save the value of handler on entry
1889 * to an inner scope, set handler to point to a jmploc structure for the
1890 * inner scope, and restore handler on exit from the scope.
1898 #define EXINT 0 /* SIGINT received */
1899 #define EXERROR 1 /* a generic error */
1900 #define EXSHELLPROC 2 /* execute a shell procedure */
1901 #define EXEXEC 3 /* command execution failed */
1903 static struct jmploc *handler;
1904 static int exception;
1906 static void exverror (int, const char *, va_list)
1907 __attribute__((__noreturn__));
1910 * Called to raise an exception. Since C doesn't include exceptions, we
1911 * just do a longjmp to the exception handler. The type of exception is
1912 * stored in the global variable "exception".
1915 static void exraise (int) __attribute__((__noreturn__));
1921 if (handler == NULL)
1926 longjmp(handler->loc, 1);
1931 * Called from trap.c when a SIGINT is received. (If the user specifies
1932 * that SIGINT is to be trapped or ignored using the trap builtin, then
1933 * this routine is not called.) Suppressint is nonzero when interrupts
1934 * are held using the INTOFF macro. The call to _exit is necessary because
1935 * there is a short period after a fork before the signal handlers are
1936 * set to the appropriate value for the child. (The test for iflag is
1937 * just defensive programming.)
1949 sigemptyset(&mysigset);
1950 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1951 if (rootshell && iflag)
1954 signal(SIGINT, SIG_DFL);
1961 static char *commandname; /* currently executing command */
1964 * Exverror is called to raise the error exception. If the first argument
1965 * is not NULL then error prints an error message using printf style
1966 * formatting. It then raises the error exception.
1969 exverror(int cond, const char *msg, va_list ap)
1976 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1978 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1982 out2fmt("%s: ", commandname);
1983 vfprintf(stderr, msg, ap);
1992 error(const char *msg, ...)
1996 exverror(EXERROR, msg, ap);
2003 exerror(int cond, const char *msg, ...)
2007 exverror(cond, msg, ap);
2015 * Table of error messages.
2019 short errcode; /* error number */
2020 char action; /* operation which encountered the error */
2024 * Types of operations (passed to the errmsg routine).
2027 #define E_OPEN 01 /* opening a file */
2028 #define E_CREAT 02 /* creating a file */
2029 #define E_EXEC 04 /* executing a program */
2031 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2033 static const struct errname errormsg[] = {
2038 { ENOENT, E_CREAT },
2040 { ENOTDIR, E_OPEN },
2041 { ENOTDIR, E_CREAT },
2042 { ENOTDIR, E_EXEC },
2044 { EEXIST, E_CREAT },
2083 { ELIBACC, E_EXEC },
2087 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2090 * Return a string describing an error. The returned string may be a
2091 * pointer to a static buffer that will be overwritten on the next call.
2092 * Action describes the operation that got the error.
2096 errmsg(int e, int action)
2098 struct errname const *ep;
2099 static char buf[12];
2101 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2102 if (ep->errcode == e && (ep->action & action) != 0)
2106 snprintf(buf, sizeof buf, "error %d", e);
2111 #ifdef ASH_OPTIMIZE_FOR_SIZE
2114 if (--suppressint == 0 && intpending) {
2118 static void forceinton (void) {
2125 /* flags in argument to evaltree */
2126 #define EV_EXIT 01 /* exit after evaluating tree */
2127 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2128 #define EV_BACKCMD 04 /* command executing within back quotes */
2130 static int evalskip; /* set if we are skipping commands */
2131 static int skipcount; /* number of levels to skip */
2132 static int loopnest; /* current loop nesting level */
2133 static int funcnest; /* depth of function calls */
2136 static struct strlist *cmdenviron; /* environment for builtin command */
2137 static int exitstatus; /* exit status of last command */
2138 static int oexitstatus; /* saved exit status */
2140 static void evalsubshell (const union node *, int);
2141 static void expredir (union node *);
2142 static void prehash (union node *);
2143 static void eprintlist (struct strlist *);
2145 static union node *parsecmd(int);
2147 * Called to reset things after an exception.
2151 * The eval commmand.
2153 static void evalstring (char *, int);
2167 STARTSTACKSTR(concat);
2171 STPUTC(*p++, concat);
2172 if ((p = *ap++) == NULL)
2174 STPUTC(' ', concat);
2176 STPUTC('\0', concat);
2177 p = grabstackstr(concat);
2179 evalstring(p, EV_TESTED);
2185 * Execute a command or commands contained in a string.
2188 static void evaltree (union node *, int);
2189 static void setinputstring (char *);
2190 static void popfile (void);
2191 static void setstackmark(struct stackmark *mark);
2192 static void popstackmark(struct stackmark *mark);
2196 evalstring(char *s, int flag)
2199 struct stackmark smark;
2201 setstackmark(&smark);
2203 while ((n = parsecmd(0)) != NEOF) {
2205 popstackmark(&smark);
2208 popstackmark(&smark);
2211 static struct builtincmd *find_builtin (const char *);
2212 static void expandarg (union node *, struct arglist *, int);
2213 static void calcsize (const union node *);
2214 static union node *copynode (const union node *);
2217 * Make a copy of a parse tree.
2220 static int funcblocksize; /* size of structures in function */
2221 static int funcstringsize; /* size of strings in node */
2222 static pointer funcblock; /* block to allocate function from */
2223 static char *funcstring; /* block to allocate strings from */
2226 static inline union node *
2227 copyfunc(union node *n)
2234 funcblock = ckmalloc(funcblocksize + funcstringsize);
2235 funcstring = (char *) funcblock + funcblocksize;
2240 * Free a parse tree.
2244 freefunc(union node *n)
2252 * Add a new command entry, replacing any existing command entry for
2257 addcmdentry(char *name, struct cmdentry *entry)
2259 struct tblentry *cmdp;
2262 cmdp = cmdlookup(name, 1);
2263 if (cmdp->cmdtype == CMDFUNCTION) {
2264 freefunc(cmdp->param.func);
2266 cmdp->cmdtype = entry->cmdtype;
2267 cmdp->param = entry->u;
2272 evalloop(const union node *n, int flags)
2279 evaltree(n->nbinary.ch1, EV_TESTED);
2281 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2285 if (evalskip == SKIPBREAK && --skipcount <= 0)
2289 if (n->type == NWHILE) {
2290 if (exitstatus != 0)
2293 if (exitstatus == 0)
2296 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2297 status = exitstatus;
2302 exitstatus = status;
2306 evalfor(const union node *n, int flags)
2308 struct arglist arglist;
2311 struct stackmark smark;
2313 setstackmark(&smark);
2314 arglist.lastp = &arglist.list;
2315 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2316 oexitstatus = exitstatus;
2317 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2321 *arglist.lastp = NULL;
2325 for (sp = arglist.list ; sp ; sp = sp->next) {
2326 setvar(n->nfor.var, sp->text, 0);
2327 evaltree(n->nfor.body, flags & EV_TESTED);
2329 if (evalskip == SKIPCONT && --skipcount <= 0) {
2333 if (evalskip == SKIPBREAK && --skipcount <= 0)
2340 popstackmark(&smark);
2344 evalcase(const union node *n, int flags)
2348 struct arglist arglist;
2349 struct stackmark smark;
2351 setstackmark(&smark);
2352 arglist.lastp = &arglist.list;
2353 oexitstatus = exitstatus;
2354 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2355 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2356 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2357 if (casematch(patp, arglist.list->text)) {
2358 if (evalskip == 0) {
2359 evaltree(cp->nclist.body, flags);
2366 popstackmark(&smark);
2370 * Evaluate a pipeline. All the processes in the pipeline are children
2371 * of the process creating the pipeline. (This differs from some versions
2372 * of the shell, which make the last process in a pipeline the parent
2376 static inline void evalpipe(union node *n)
2379 struct nodelist *lp;
2384 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2386 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2389 jp = makejob(n, pipelen);
2391 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2395 if (pipe(pip) < 0) {
2397 error("Pipe call failed");
2400 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2404 dup_as_newfd(prevfd, 0);
2416 dup_as_newfd(pip[1], 1);
2420 evaltree(lp->n, EV_EXIT);
2428 if (n->npipe.backgnd == 0) {
2430 exitstatus = waitforjob(jp);
2431 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2436 static void find_command (const char *, struct cmdentry *, int, const char *);
2439 isassignment(const char *word) {
2440 if (!is_name(*word)) {
2445 } while (is_in_name(*word));
2446 return *word == '=';
2451 evalcommand(union node *cmd, int flags)
2453 struct stackmark smark;
2455 struct arglist arglist;
2456 struct arglist varlist;
2462 struct cmdentry cmdentry;
2464 char *volatile savecmdname;
2465 volatile struct shparam saveparam;
2466 struct localvar *volatile savelocalvars;
2470 const struct builtincmd *firstbltin;
2471 struct jmploc *volatile savehandler;
2472 struct jmploc jmploc;
2474 /* Avoid longjmp clobbering */
2481 /* First expand the arguments. */
2482 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2483 setstackmark(&smark);
2484 arglist.lastp = &arglist.list;
2485 varlist.lastp = &varlist.list;
2487 oexitstatus = exitstatus;
2490 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2491 expandarg(argp, &varlist, EXP_VARTILDE);
2494 argp = cmd->ncmd.args; argp && !arglist.list;
2495 argp = argp->narg.next
2497 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2500 struct builtincmd *bcmd;
2502 bcmd = find_builtin(arglist.list->text);
2503 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2504 for (; argp; argp = argp->narg.next) {
2505 if (pseudovarflag && isassignment(argp->narg.text)) {
2506 expandarg(argp, &arglist, EXP_VARTILDE);
2509 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2512 *arglist.lastp = NULL;
2513 *varlist.lastp = NULL;
2514 expredir(cmd->ncmd.redirect);
2516 for (sp = arglist.list ; sp ; sp = sp->next)
2518 argv = stalloc(sizeof (char *) * (argc + 1));
2520 for (sp = arglist.list ; sp ; sp = sp->next) {
2521 TRACE(("evalcommand arg: %s\n", sp->text));
2526 if (iflag && funcnest == 0 && argc > 0)
2530 /* Print the command if xflag is set. */
2533 eprintlist(varlist.list);
2534 eprintlist(arglist.list);
2538 /* Now locate the command. */
2540 cmdentry.cmdtype = CMDBUILTIN;
2541 firstbltin = cmdentry.u.cmd = BLTINCMD;
2543 const char *oldpath;
2544 int findflag = DO_ERR;
2548 * Modify the command lookup path, if a PATH= assignment
2551 for (sp = varlist.list ; sp ; sp = sp->next)
2552 if (varequal(sp->text, defpathvar)) {
2553 path = sp->text + 5;
2554 findflag |= DO_BRUTE;
2557 oldfindflag = findflag;
2560 find_command(argv[0], &cmdentry, findflag, path);
2561 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2565 /* implement bltin and command here */
2566 if (cmdentry.cmdtype != CMDBUILTIN) {
2570 firstbltin = cmdentry.u.cmd;
2572 if (cmdentry.u.cmd == BLTINCMD) {
2574 struct builtincmd *bcmd;
2579 if (!(bcmd = find_builtin(*argv))) {
2580 out2fmt("%s: not found\n", *argv);
2584 cmdentry.u.cmd = bcmd;
2585 if (bcmd != BLTINCMD)
2589 if (cmdentry.u.cmd == find_builtin("command")) {
2594 if (*argv[0] == '-') {
2595 if (!equal(argv[0], "-p")) {
2605 findflag |= DO_BRUTE;
2608 findflag = oldfindflag;
2610 findflag |= DO_NOFUN;
2618 /* Fork off a child process if necessary. */
2619 if (cmd->ncmd.backgnd
2620 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2622 jp = makejob(cmd, 1);
2623 mode = cmd->ncmd.backgnd;
2624 if (forkshell(jp, cmd, mode) != 0)
2625 goto parent; /* at end of routine */
2629 /* This is the child process if a fork occurred. */
2630 /* Execute the command. */
2631 if (cmdentry.cmdtype == CMDFUNCTION) {
2633 trputs("Shell function: "); trargs(argv);
2635 exitstatus = oexitstatus;
2636 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2637 saveparam = shellparam;
2638 shellparam.malloc = 0;
2639 shellparam.nparam = argc - 1;
2640 shellparam.p = argv + 1;
2642 savelocalvars = localvars;
2645 if (setjmp(jmploc.loc)) {
2646 if (exception == EXSHELLPROC) {
2647 freeparam((volatile struct shparam *)
2650 saveparam.optind = shellparam.optind;
2651 saveparam.optoff = shellparam.optoff;
2652 freeparam(&shellparam);
2653 shellparam = saveparam;
2656 localvars = savelocalvars;
2657 handler = savehandler;
2658 longjmp(handler->loc, 1);
2660 savehandler = handler;
2662 for (sp = varlist.list ; sp ; sp = sp->next)
2665 evaltree(cmdentry.u.func, flags & EV_TESTED);
2669 localvars = savelocalvars;
2670 saveparam.optind = shellparam.optind;
2671 saveparam.optoff = shellparam.optoff;
2672 freeparam(&shellparam);
2673 shellparam = saveparam;
2674 handler = savehandler;
2677 if (evalskip == SKIPFUNC) {
2681 if (flags & EV_EXIT)
2682 exitshell(exitstatus);
2683 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2685 trputs("builtin command: "); trargs(argv);
2687 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2688 redirect(cmd->ncmd.redirect, mode);
2689 savecmdname = commandname;
2690 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2691 listsetvar(varlist.list);
2693 cmdenviron = varlist.list;
2696 if (setjmp(jmploc.loc)) {
2698 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2701 savehandler = handler;
2703 commandname = argv[0];
2705 optptr = NULL; /* initialize nextopt */
2706 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2710 if (e != EXSHELLPROC) {
2711 commandname = savecmdname;
2712 if (flags & EV_EXIT)
2713 exitshell(exitstatus);
2715 handler = savehandler;
2717 if ((e != EXERROR && e != EXEXEC)
2718 || cmdentry.u.cmd == BLTINCMD
2719 || cmdentry.u.cmd == DOTCMD
2720 || cmdentry.u.cmd == EVALCMD
2721 || cmdentry.u.cmd == EXECCMD)
2725 if (cmdentry.u.cmd != EXECCMD)
2729 trputs("normal command: "); trargs(argv);
2731 redirect(cmd->ncmd.redirect, 0);
2733 for (sp = varlist.list ; sp ; sp = sp->next)
2734 setvareq(sp->text, VEXPORT|VSTACK);
2735 envp = environment();
2736 shellexec(argv, envp, path, cmdentry.u.index);
2740 parent: /* parent process gets here (if we forked) */
2741 if (mode == 0) { /* argument to fork */
2743 exitstatus = waitforjob(jp);
2749 setvar("_", lastarg, 0);
2750 popstackmark(&smark);
2754 * Evaluate a parse tree. The value is left in the global variable
2764 TRACE(("evaltree(NULL) called\n"));
2767 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2770 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2773 evaltree(n->nbinary.ch2, flags);
2776 evaltree(n->nbinary.ch1, EV_TESTED);
2777 if (evalskip || exitstatus != 0)
2779 evaltree(n->nbinary.ch2, flags);
2782 evaltree(n->nbinary.ch1, EV_TESTED);
2783 if (evalskip || exitstatus == 0)
2785 evaltree(n->nbinary.ch2, flags);
2788 expredir(n->nredir.redirect);
2789 redirect(n->nredir.redirect, REDIR_PUSH);
2790 evaltree(n->nredir.n, flags);
2794 evalsubshell(n, flags);
2797 evalsubshell(n, flags);
2800 evaltree(n->nif.test, EV_TESTED);
2803 if (exitstatus == 0)
2804 evaltree(n->nif.ifpart, flags);
2805 else if (n->nif.elsepart)
2806 evaltree(n->nif.elsepart, flags);
2822 struct builtincmd *bcmd;
2823 struct cmdentry entry;
2825 (bcmd = find_builtin(n->narg.text)) &&
2826 IS_BUILTIN_SPECIAL(bcmd)
2828 out2fmt("%s is a special built-in\n", n->narg.text);
2832 entry.cmdtype = CMDFUNCTION;
2833 entry.u.func = copyfunc(n->narg.next);
2834 addcmdentry(n->narg.text, &entry);
2839 evaltree(n->nnot.com, EV_TESTED);
2840 exitstatus = !exitstatus;
2848 evalcommand(n, flags);
2853 printf("Node type = %d\n", n->type);
2862 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2864 exitshell(exitstatus);
2868 * Kick off a subshell to evaluate a tree.
2872 evalsubshell(const union node *n, int flags)
2875 int backgnd = (n->type == NBACKGND);
2877 expredir(n->nredir.redirect);
2879 if (forkshell(jp, n, backgnd) == 0) {
2881 flags &=~ EV_TESTED;
2882 redirect(n->nredir.redirect, 0);
2883 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2887 exitstatus = waitforjob(jp);
2893 * Compute the names of the files in a redirection list.
2896 static void fixredir(union node *n, const char *text, int err);
2899 expredir(union node *n)
2903 for (redir = n ; redir ; redir = redir->nfile.next) {
2905 fn.lastp = &fn.list;
2906 oexitstatus = exitstatus;
2907 switch (redir->type) {
2913 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2914 redir->nfile.expfname = fn.list->text;
2918 if (redir->ndup.vname) {
2919 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2920 fixredir(redir, fn.list->text, 1);
2929 * Execute a command inside back quotes. If it's a builtin command, we
2930 * want to save its output in a block obtained from malloc. Otherwise
2931 * we fork off a subprocess and get the output of the command via a pipe.
2932 * Should be called with interrupts off.
2936 evalbackcmd(union node *n, struct backcmd *result)
2940 struct stackmark smark; /* unnecessary */
2942 setstackmark(&smark);
2953 error("Pipe call failed");
2955 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2960 dup_as_newfd(pip[1], 1);
2964 evaltree(n, EV_EXIT);
2967 result->fd = pip[0];
2970 popstackmark(&smark);
2971 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2972 result->fd, result->buf, result->nleft, result->jp));
2977 * Execute a simple command.
2981 * Search for a command. This is called before we fork so that the
2982 * location of the command will be available in the parent as well as
2983 * the child. The check for "goodname" is an overly conservative
2984 * check that the name will not be subject to expansion.
2991 struct cmdentry entry;
2993 if (n->type == NCMD && n->ncmd.args)
2994 if (goodname(n->ncmd.args->narg.text))
2995 find_command(n->ncmd.args->narg.text, &entry, 0,
3001 * Builtin commands. Builtin commands whose functions are closely
3002 * tied to evaluation are implemented here.
3006 * No command given, or a bltin command with no arguments. Set the
3007 * specified variables.
3011 bltincmd(argc, argv)
3016 * Preserve exitstatus of a previous possible redirection
3024 * Handle break and continue commands. Break, continue, and return are
3025 * all handled by setting the evalskip flag. The evaluation routines
3026 * above all check this flag, and if it is set they start skipping
3027 * commands rather than executing them. The variable skipcount is
3028 * the number of loops to break/continue, or the number of function
3029 * levels to return. (The latter is always 1.) It should probably
3030 * be an error to break out of more loops than exist, but it isn't
3031 * in the standard shell so we don't make it one here.
3035 breakcmd(argc, argv)
3039 int n = argc > 1 ? number(argv[1]) : 1;
3044 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3052 * The return command.
3056 returncmd(argc, argv)
3060 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3063 evalskip = SKIPFUNC;
3068 /* Do what ksh does; skip the rest of the file */
3069 evalskip = SKIPFILE;
3076 #ifndef CONFIG_TRUE_FALSE
3078 false_main(argc, argv)
3087 true_main(argc, argv)
3096 * Controls whether the shell is interactive or not.
3099 static void setsignal(int signo);
3100 static void chkmail(int silent);
3104 setinteractive(int on)
3106 static int is_interactive;
3107 static int do_banner=0;
3109 if (on == is_interactive)
3115 is_interactive = on;
3116 if (do_banner==0 && is_interactive) {
3117 /* Looks like they want an interactive shell */
3118 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3119 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3120 printf( "Enter 'help' for a list of built-in commands.\n\n");
3129 setinteractive(iflag);
3142 iflag = 0; /* exit on error */
3145 for (sp = cmdenviron; sp ; sp = sp->next)
3146 setvareq(sp->text, VEXPORT|VSTACK);
3147 shellexec(argv + 1, environment(), pathval(), 0);
3153 eprintlist(struct strlist *sp)
3155 for (; sp; sp = sp->next) {
3156 out2fmt(" %s",sp->text);
3161 * Exec a program. Never returns. If you change this routine, you may
3162 * have to change the find_command routine as well.
3165 static const char *pathopt; /* set by padvance */
3168 shellexec(argv, envp, path, idx)
3169 char **argv, **envp;
3176 if (strchr(argv[0], '/') != NULL) {
3177 tryexec(argv[0], argv, envp);
3181 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3182 if (--idx < 0 && pathopt == NULL) {
3183 tryexec(cmdname, argv, envp);
3184 if (errno != ENOENT && errno != ENOTDIR)
3191 /* Map to POSIX errors */
3203 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3208 * Clear traps on a fork.
3214 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3215 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3220 setsignal(tp - trap);
3228 initshellproc(void) {
3254 /* from options.c: */
3258 for (i = 0; i < NOPTS; i++)
3274 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3286 static int preadbuffer(void);
3287 static void pushfile (void);
3290 * Read a character from the script, returning PEOF on end of file.
3291 * Nul characters in the input are silently discarded.
3294 #ifndef ASH_OPTIMIZE_FOR_SIZE
3295 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3299 return pgetc_macro();
3305 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3311 return pgetc_macro();
3317 * Undo the last call to pgetc. Only one character may be pushed back.
3318 * PEOF may be pushed back.
3321 static void pungetc(void)
3330 struct parsefile *pf = parsefile;
3339 parsefile = pf->prev;
3341 parsenleft = parsefile->nleft;
3342 parselleft = parsefile->lleft;
3343 parsenextc = parsefile->nextc;
3344 plinno = parsefile->linno;
3350 * Return to top level.
3355 while (parsefile != &basepf)
3360 * Close the file(s) that the shell is reading commands from. Called
3361 * after a fork is done.
3364 static void closescript(void)
3367 if (parsefile->fd > 0) {
3368 close(parsefile->fd);
3375 * Like setinputfile, but takes an open file descriptor. Call this with
3379 static void setinputfd(int fd, int push)
3381 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3387 while (parsefile->strpush)
3391 if (parsefile->buf == NULL)
3392 parsefile->buf = ckmalloc(BUFSIZ);
3393 parselleft = parsenleft = 0;
3399 * Set the input to take input from a file. If push is set, push the
3400 * old input onto the stack first.
3404 setinputfile(const char *fname, int push)
3410 if ((fd = open(fname, O_RDONLY)) < 0)
3411 error("Can't open %s", fname);
3413 myfileno2 = dup_as_newfd(fd, 10);
3416 error("Out of file descriptors");
3419 setinputfd(fd, push);
3425 tryexec(char *cmd, char **argv, char **envp)
3429 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3433 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3434 name = get_last_path_component(name);
3437 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3440 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3442 run_applet_by_name(name, argc_l, argv);
3444 execve(cmd, argv, envp);
3449 setinputfile(cmd, 0);
3450 commandname = arg0 = savestr(argv[0]);
3452 exraise(EXSHELLPROC);
3457 static char *commandtext (const union node *);
3460 * Do a path search. The variable path (passed by reference) should be
3461 * set to the start of the path before the first call; padvance will update
3462 * this value as it proceeds. Successive calls to padvance will return
3463 * the possible path expansions in sequence. If an option (indicated by
3464 * a percent sign) appears in the path entry then the global variable
3465 * pathopt will be set to point to it; otherwise pathopt will be set to
3469 static const char *pathopt;
3471 static void growstackblock(void);
3475 padvance(const char **path, const char *name)
3485 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3486 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3487 while (stackblocksize() < len)
3491 memcpy(q, start, p - start);
3499 while (*p && *p != ':') p++;
3505 return stalloc(len);
3509 * Wrapper around strcmp for qsort/bsearch/...
3512 pstrcmp(const void *a, const void *b)
3514 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3518 * Find a keyword is in a sorted array.
3521 static const char *const *
3522 findkwd(const char *s)
3524 return bsearch(s, tokname_array + KWDOFFSET,
3525 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3526 sizeof(const char *), pstrcmp);
3530 /*** Command hashing code ***/
3538 struct tblentry **pp;
3539 struct tblentry *cmdp;
3542 struct cmdentry entry;
3545 const struct alias *ap;
3549 while ((c = nextopt("rvV")) != '\0') {
3553 } else if (c == 'v' || c == 'V') {
3557 if (*argptr == NULL) {
3558 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3559 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3560 if (cmdp->cmdtype != CMDBUILTIN) {
3561 printentry(cmdp, verbose);
3568 while ((name = *argptr++) != NULL) {
3569 if ((cmdp = cmdlookup(name, 0)) != NULL
3570 && (cmdp->cmdtype == CMDNORMAL
3571 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3574 /* Then look at the aliases */
3575 if ((ap = lookupalias(name, 0)) != NULL) {
3577 printf("%s is an alias for %s\n", name, ap->val);
3583 /* First look at the keywords */
3584 if (findkwd(name)!=0) {
3586 printf("%s is a shell keyword\n", name);
3588 printf(snlfmt, name);
3592 find_command(name, &entry, DO_ERR, pathval());
3593 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3595 cmdp = cmdlookup(name, 0);
3596 if (cmdp) printentry(cmdp, verbose=='v');
3604 printentry(cmdp, verbose)
3605 struct tblentry *cmdp;
3612 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3613 if (cmdp->cmdtype == CMDNORMAL) {
3614 idx = cmdp->param.index;
3617 name = padvance(&path, cmdp->cmdname);
3619 } while (--idx >= 0);
3622 } else if (cmdp->cmdtype == CMDBUILTIN) {
3624 out1str("a shell builtin");
3625 } else if (cmdp->cmdtype == CMDFUNCTION) {
3628 out1str("a function\n");
3629 name = commandtext(cmdp->param.func);
3630 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3636 error("internal error: cmdtype %d", cmdp->cmdtype);
3639 printf(snlfmt, cmdp->rehash ? "*" : nullstr);
3644 /*** List the available builtins ***/
3647 static int helpcmd(int argc, char** argv)
3651 printf("\nBuilt-in commands:\n-------------------\n");
3652 for (col=0, i=0; i < NUMBUILTINS; i++) {
3653 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3654 builtincmds[i].name+1);
3660 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3662 extern const struct BB_applet applets[];
3663 extern const size_t NUM_APPLETS;
3665 for (i=0; i < NUM_APPLETS; i++) {
3667 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3677 return EXIT_SUCCESS;
3681 * Resolve a command name. If you change this routine, you may have to
3682 * change the shellexec routine as well.
3685 static int prefix (const char *, const char *);
3688 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3690 struct tblentry *cmdp;
3700 struct builtincmd *bcmd;
3702 /* If name contains a slash, don't use the hash table */
3703 if (strchr(name, '/') != NULL) {
3705 while (stat(name, &statb) < 0) {
3706 if (errno != ENOENT && errno != ENOTDIR)
3708 entry->cmdtype = CMDUNKNOWN;
3709 entry->u.index = -1;
3712 entry->cmdtype = CMDNORMAL;
3713 entry->u.index = -1;
3716 entry->cmdtype = CMDNORMAL;
3722 if (act & DO_BRUTE) {
3723 firstchange = path_change(path, &bltin);
3729 /* If name is in the table, and not invalidated by cd, we're done */
3730 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3731 if (cmdp->cmdtype == CMDFUNCTION) {
3732 if (act & DO_NOFUN) {
3737 } else if (act & DO_BRUTE) {
3738 if ((cmdp->cmdtype == CMDNORMAL &&
3739 cmdp->param.index >= firstchange) ||
3740 (cmdp->cmdtype == CMDBUILTIN &&
3741 ((builtinloc < 0 && bltin >= 0) ?
3742 bltin : builtinloc) >= firstchange)) {
3743 /* need to recompute the entry */
3752 bcmd = find_builtin(name);
3753 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3756 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3759 } else if (act & DO_BRUTE) {
3760 if (firstchange == 0) {
3765 /* If %builtin not in path, check for builtin next */
3766 if (regular || (bltin < 0 && bcmd)) {
3769 entry->cmdtype = CMDBUILTIN;
3770 entry->u.cmd = bcmd;
3774 cmdp = cmdlookup(name, 1);
3775 cmdp->cmdtype = CMDBUILTIN;
3776 cmdp->param.cmd = bcmd;
3781 /* We have to search path. */
3782 prev = -1; /* where to start */
3783 if (cmdp && cmdp->rehash) { /* doing a rehash */
3784 if (cmdp->cmdtype == CMDBUILTIN)
3787 prev = cmdp->param.index;
3793 while ((fullname = padvance(&path, name)) != NULL) {
3794 stunalloc(fullname);
3796 if (idx >= firstchange) {
3800 if (prefix("builtin", pathopt)) {
3801 if ((bcmd = find_builtin(name))) {
3805 } else if (!(act & DO_NOFUN) &&
3806 prefix("func", pathopt)) {
3809 continue; /* ignore unimplemented options */
3812 /* if rehash, don't redo absolute path names */
3813 if (fullname[0] == '/' && idx <= prev &&
3814 idx < firstchange) {
3817 TRACE(("searchexec \"%s\": no change\n", name));
3820 while (stat(fullname, &statb) < 0) {
3821 if (errno != ENOENT && errno != ENOTDIR)
3825 e = EACCES; /* if we fail, this will be the error */
3826 if (!S_ISREG(statb.st_mode))
3828 if (pathopt) { /* this is a %func directory */
3829 stalloc(strlen(fullname) + 1);
3830 readcmdfile(fullname);
3831 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3832 error("%s not defined in %s", name, fullname);
3833 stunalloc(fullname);
3836 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3837 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3838 be a function and we're being called with DO_NOFUN */
3840 entry->cmdtype = CMDNORMAL;
3841 entry->u.index = idx;
3845 cmdp = cmdlookup(name, 1);
3846 cmdp->cmdtype = CMDNORMAL;
3847 cmdp->param.index = idx;
3852 /* We failed. If there was an entry for this command, delete it */
3853 if (cmdp && updatetbl)
3856 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3857 entry->cmdtype = CMDUNKNOWN;
3862 entry->cmdtype = cmdp->cmdtype;
3863 entry->u = cmdp->param;
3869 * Search the table of builtin commands.
3873 bstrcmp(const void *name, const void *b)
3875 return strcmp((const char *)name, (*(const char *const *) b)+1);
3878 static struct builtincmd *
3879 find_builtin(const char *name)
3881 struct builtincmd *bp;
3883 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3891 * Called when a cd is done. Marks all commands so the next time they
3892 * are executed they will be rehashed.
3897 struct tblentry **pp;
3898 struct tblentry *cmdp;
3900 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3901 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3902 if (cmdp->cmdtype == CMDNORMAL
3903 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3912 * Called before PATH is changed. The argument is the new value of PATH;
3913 * pathval() still returns the old value at this point. Called with
3918 changepath(const char *newval)
3923 firstchange = path_change(newval, &bltin);
3924 if (builtinloc < 0 && bltin >= 0)
3925 builtinloc = bltin; /* zap builtins */
3926 clearcmdentry(firstchange);
3932 * Clear out command entries. The argument specifies the first entry in
3933 * PATH which has changed.
3937 clearcmdentry(firstchange)
3940 struct tblentry **tblp;
3941 struct tblentry **pp;
3942 struct tblentry *cmdp;
3945 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3947 while ((cmdp = *pp) != NULL) {
3948 if ((cmdp->cmdtype == CMDNORMAL &&
3949 cmdp->param.index >= firstchange)
3950 || (cmdp->cmdtype == CMDBUILTIN &&
3951 builtinloc >= firstchange)) {
3964 * Delete all functions.
3969 struct tblentry **tblp;
3970 struct tblentry **pp;
3971 struct tblentry *cmdp;
3974 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3976 while ((cmdp = *pp) != NULL) {
3977 if (cmdp->cmdtype == CMDFUNCTION) {
3979 freefunc(cmdp->param.func);
3992 * Locate a command in the command hash table. If "add" is nonzero,
3993 * add the command to the table if it is not already present. The
3994 * variable "lastcmdentry" is set to point to the address of the link
3995 * pointing to the entry, so that delete_cmd_entry can delete the
3999 static struct tblentry **lastcmdentry;
4001 static struct tblentry *
4002 cmdlookup(const char *name, int add)
4006 struct tblentry *cmdp;
4007 struct tblentry **pp;
4014 pp = &cmdtable[hashval % CMDTABLESIZE];
4015 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4016 if (equal(cmdp->cmdname, name))
4020 if (add && cmdp == NULL) {
4022 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4023 + strlen(name) + 1);
4025 cmdp->cmdtype = CMDUNKNOWN;
4027 strcpy(cmdp->cmdname, name);
4035 * Delete the command entry returned on the last lookup.
4039 delete_cmd_entry() {
4040 struct tblentry *cmdp;
4043 cmdp = *lastcmdentry;
4044 *lastcmdentry = cmdp->next;
4053 static const unsigned char nodesize[26] = {
4054 ALIGN(sizeof (struct nbinary)),
4055 ALIGN(sizeof (struct ncmd)),
4056 ALIGN(sizeof (struct npipe)),
4057 ALIGN(sizeof (struct nredir)),
4058 ALIGN(sizeof (struct nredir)),
4059 ALIGN(sizeof (struct nredir)),
4060 ALIGN(sizeof (struct nbinary)),
4061 ALIGN(sizeof (struct nbinary)),
4062 ALIGN(sizeof (struct nif)),
4063 ALIGN(sizeof (struct nbinary)),
4064 ALIGN(sizeof (struct nbinary)),
4065 ALIGN(sizeof (struct nfor)),
4066 ALIGN(sizeof (struct ncase)),
4067 ALIGN(sizeof (struct nclist)),
4068 ALIGN(sizeof (struct narg)),
4069 ALIGN(sizeof (struct narg)),
4070 ALIGN(sizeof (struct nfile)),
4071 ALIGN(sizeof (struct nfile)),
4072 ALIGN(sizeof (struct nfile)),
4073 ALIGN(sizeof (struct nfile)),
4074 ALIGN(sizeof (struct nfile)),
4075 ALIGN(sizeof (struct ndup)),
4076 ALIGN(sizeof (struct ndup)),
4077 ALIGN(sizeof (struct nhere)),
4078 ALIGN(sizeof (struct nhere)),
4079 ALIGN(sizeof (struct nnot)),
4085 * Delete a function if it exists.
4089 unsetfunc(char *name)
4091 struct tblentry *cmdp;
4093 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4094 freefunc(cmdp->param.func);
4101 * Locate and print what a word is...
4105 typecmd(int argc, char **argv)
4113 for (i = 1; i < argc; i++) {
4114 argv_a[0] = argv[i];
4117 err |= hashcmd(argc, argv);
4124 commandcmd(argc, argv)
4129 int default_path = 0;
4130 int verify_only = 0;
4131 int verbose_verify_only = 0;
4133 while ((c = nextopt("pvV")) != '\0')
4142 verbose_verify_only = 1;
4146 if (default_path + verify_only + verbose_verify_only > 1 ||
4149 "command [-p] command [arg ...]\n"
4150 "command {-v|-V} command\n");
4154 if (verify_only || verbose_verify_only) {
4158 argv_a[0] = *argptr;
4160 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4161 return hashcmd(argc, argv);
4169 path_change(newval, bltin)
4173 const char *old, *new;
4179 firstchange = 9999; /* assume no change */
4185 if ((*old == '\0' && *new == ':')
4186 || (*old == ':' && *new == '\0'))
4188 old = new; /* ignore subsequent differences */
4192 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4199 if (builtinloc >= 0 && *bltin < 0)
4204 * Routines to expand arguments to commands. We have to deal with
4205 * backquotes, shell variables, and file metacharacters.
4210 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4211 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4214 * Structure specifying which parts of the string should be searched
4215 * for IFS characters.
4219 struct ifsregion *next; /* next region in list */
4220 int begoff; /* offset of start of region */
4221 int endoff; /* offset of end of region */
4222 int nulonly; /* search for nul bytes only */
4226 static char *expdest; /* output of current string */
4227 static struct nodelist *argbackq; /* list of back quote expressions */
4228 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4229 static struct ifsregion *ifslastp; /* last struct in list */
4230 static struct arglist exparg; /* holds expanded arg list */
4232 static void argstr (char *, int);
4233 static char *exptilde (char *, int);
4234 static void expbackq (union node *, int, int);
4235 static int subevalvar (char *, char *, int, int, int, int, int);
4236 static int varisset (char *, int);
4237 static void strtodest (const char *, int, int);
4238 static void varvalue (char *, int, int);
4239 static void recordregion (int, int, int);
4240 static void removerecordregions (int);
4241 static void ifsbreakup (char *, struct arglist *);
4242 static void ifsfree (void);
4243 static void expandmeta (struct strlist *, int);
4244 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4245 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4246 #if !defined(GLOB_BROKEN)
4247 static void addglob (const glob_t *);
4250 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4251 static void expmeta (char *, char *);
4253 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4254 static struct strlist *expsort (struct strlist *);
4255 static struct strlist *msort (struct strlist *, int);
4257 static int patmatch (char *, char *, int);
4258 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4259 static int patmatch2 (char *, char *, int);
4261 static int pmatch (char *, char *, int);
4262 #define patmatch2 patmatch
4264 static char *cvtnum (int, char *);
4267 * Expand shell variables and backquotes inside a here document.
4270 /* arg: the document, fd: where to write the expanded version */
4272 expandhere(union node *arg, int fd)
4275 expandarg(arg, (struct arglist *)NULL, 0);
4276 xwrite(fd, stackblock(), expdest - stackblock());
4281 * Perform variable substitution and command substitution on an argument,
4282 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4283 * perform splitting and file name expansion. When arglist is NULL, perform
4284 * here document expansion.
4288 expandarg(arg, arglist, flag)
4290 struct arglist *arglist;
4296 argbackq = arg->narg.backquote;
4297 STARTSTACKSTR(expdest);
4298 ifsfirst.next = NULL;
4300 argstr(arg->narg.text, flag);
4301 if (arglist == NULL) {
4302 return; /* here document expanded */
4304 STPUTC('\0', expdest);
4305 p = grabstackstr(expdest);
4306 exparg.lastp = &exparg.list;
4310 if (flag & EXP_FULL) {
4311 ifsbreakup(p, &exparg);
4312 *exparg.lastp = NULL;
4313 exparg.lastp = &exparg.list;
4314 expandmeta(exparg.list, flag);
4316 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4318 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4321 exparg.lastp = &sp->next;
4324 *exparg.lastp = NULL;
4326 *arglist->lastp = exparg.list;
4327 arglist->lastp = exparg.lastp;
4333 * Expand a variable, and return a pointer to the next character in the
4337 static inline char * evalvar(char *p, int flag)
4350 int quotes = flag & (EXP_FULL | EXP_CASE);
4353 subtype = varflags & VSTYPE;
4358 p = strchr(p, '=') + 1;
4359 again: /* jump here after setting a variable with ${var=text} */
4361 set = varisset(var, varflags & VSNUL);
4364 val = lookupvar(var);
4365 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4372 startloc = expdest - stackblock();
4373 if (set && subtype != VSPLUS) {
4374 /* insert the value of the variable */
4376 varvalue(var, varflags & VSQUOTE, flag);
4377 if (subtype == VSLENGTH) {
4378 varlen = expdest - stackblock() - startloc;
4379 STADJUST(-varlen, expdest);
4382 if (subtype == VSLENGTH) {
4383 varlen = strlen(val);
4387 varflags & VSQUOTE ?
4388 DQSYNTAX : BASESYNTAX,
4395 if (subtype == VSPLUS)
4398 easy = ((varflags & VSQUOTE) == 0 ||
4399 (*var == '@' && shellparam.nparam != 1));
4404 expdest = cvtnum(varlen, expdest);
4411 recordregion(startloc, expdest - stackblock(),
4412 varflags & VSQUOTE);
4428 case VSTRIMRIGHTMAX:
4432 * Terminate the string and start recording the pattern
4435 STPUTC('\0', expdest);
4436 patloc = expdest - stackblock();
4437 if (subevalvar(p, NULL, patloc, subtype,
4438 startloc, varflags, quotes) == 0) {
4439 int amount = (expdest - stackblock() - patloc) + 1;
4440 STADJUST(-amount, expdest);
4442 /* Remove any recorded regions beyond start of variable */
4443 removerecordregions(startloc);
4449 if (subevalvar(p, var, 0, subtype, startloc,
4450 varflags, quotes)) {
4453 * Remove any recorded regions beyond
4456 removerecordregions(startloc);
4471 if (subtype != VSNORMAL) { /* skip to end of alternative */
4474 if ((c = *p++) == CTLESC)
4476 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4478 argbackq = argbackq->next;
4479 } else if (c == CTLVAR) {
4480 if ((*p++ & VSTYPE) != VSNORMAL)
4482 } else if (c == CTLENDVAR) {
4493 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4494 * characters to allow for further processing. Otherwise treat
4495 * $@ like $* since no splitting will be performed.
4504 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4507 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4508 p = exptilde(p, flag);
4512 case CTLENDVAR: /* ??? */
4515 /* "$@" syntax adherence hack */
4516 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4518 if ((flag & EXP_FULL) != 0)
4528 p = evalvar(p, flag);
4531 case CTLBACKQ|CTLQUOTE:
4532 expbackq(argbackq->n, c & CTLQUOTE, flag);
4533 argbackq = argbackq->next;
4535 #ifdef ASH_MATH_SUPPORT
4543 * sort of a hack - expand tildes in variable
4544 * assignments (after the first '=' and after ':'s).
4547 if (flag & EXP_VARTILDE && *p == '~') {
4554 p = exptilde(p, flag);
4570 char c, *startp = p;
4573 int quotes = flag & (EXP_FULL | EXP_CASE);
4575 while ((c = *p) != '\0') {
4582 if (flag & EXP_VARTILDE)
4592 if (*(startp+1) == '\0') {
4593 if ((home = lookupvar("HOME")) == NULL)
4596 if ((pw = getpwnam(startp+1)) == NULL)
4603 strtodest(home, SQSYNTAX, quotes);
4612 removerecordregions(int endoff)
4614 if (ifslastp == NULL)
4617 if (ifsfirst.endoff > endoff) {
4618 while (ifsfirst.next != NULL) {
4619 struct ifsregion *ifsp;
4621 ifsp = ifsfirst.next->next;
4622 ckfree(ifsfirst.next);
4623 ifsfirst.next = ifsp;
4626 if (ifsfirst.begoff > endoff)
4629 ifslastp = &ifsfirst;
4630 ifsfirst.endoff = endoff;
4635 ifslastp = &ifsfirst;
4636 while (ifslastp->next && ifslastp->next->begoff < endoff)
4637 ifslastp=ifslastp->next;
4638 while (ifslastp->next != NULL) {
4639 struct ifsregion *ifsp;
4641 ifsp = ifslastp->next->next;
4642 ckfree(ifslastp->next);
4643 ifslastp->next = ifsp;
4646 if (ifslastp->endoff > endoff)
4647 ifslastp->endoff = endoff;
4651 #ifdef ASH_MATH_SUPPORT
4653 * Expand arithmetic expression. Backup to start of expression,
4654 * evaluate, place result in (backed up) result, adjust string position.
4663 int quotes = flag & (EXP_FULL | EXP_CASE);
4669 * This routine is slightly over-complicated for
4670 * efficiency. First we make sure there is
4671 * enough space for the result, which may be bigger
4672 * than the expression if we add exponentation. Next we
4673 * scan backwards looking for the start of arithmetic. If the
4674 * next previous character is a CTLESC character, then we
4675 * have to rescan starting from the beginning since CTLESC
4676 * characters have to be processed left to right.
4678 CHECKSTRSPACE(10, expdest);
4679 USTPUTC('\0', expdest);
4680 start = stackblock();
4682 while (*p != CTLARI && p >= start)
4685 error("missing CTLARI (shouldn't happen)");
4686 if (p > start && *(p-1) == CTLESC)
4687 for (p = start; *p != CTLARI; p++)
4696 removerecordregions(begoff);
4699 result = arith(p+2, &errcode);
4702 error("divide by zero");
4704 error("syntax error: \"%s\"\n", p+2);
4706 snprintf(p, 12, "%d", result);
4712 recordregion(begoff, p - 1 - start, 0);
4713 result = expdest - p + 1;
4714 STADJUST(-result, expdest);
4719 * Expand stuff in backwards quotes.
4723 expbackq(cmd, quoted, flag)
4728 volatile struct backcmd in;
4732 char *dest = expdest;
4733 volatile struct ifsregion saveifs;
4734 struct ifsregion *volatile savelastp;
4735 struct nodelist *volatile saveargbackq;
4737 int startloc = dest - stackblock();
4738 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4739 volatile int saveherefd;
4740 int quotes = flag & (EXP_FULL | EXP_CASE);
4741 struct jmploc jmploc;
4742 struct jmploc *volatile savehandler;
4746 /* Avoid longjmp clobbering */
4757 savelastp = ifslastp;
4758 saveargbackq = argbackq;
4759 saveherefd = herefd;
4761 if ((ex = setjmp(jmploc.loc))) {
4764 savehandler = handler;
4767 p = grabstackstr(dest);
4768 evalbackcmd(cmd, (struct backcmd *) &in);
4769 ungrabstackstr(p, dest);
4773 ifslastp = savelastp;
4774 argbackq = saveargbackq;
4775 herefd = saveherefd;
4783 if (--in.nleft < 0) {
4786 i = safe_read(in.fd, buf, sizeof buf);
4787 TRACE(("expbackq: read returns %d\n", i));
4794 if (lastc != '\0') {
4795 if (quotes && SIT(lastc, syntax) == CCTL)
4796 STPUTC(CTLESC, dest);
4797 STPUTC(lastc, dest);
4801 /* Eat all trailing newlines */
4802 for (; dest > stackblock() && dest[-1] == '\n';)
4811 exitstatus = waitforjob(in.jp);
4812 handler = savehandler;
4814 longjmp(handler->loc, 1);
4817 recordregion(startloc, dest - stackblock(), 0);
4818 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4819 (dest - stackblock()) - startloc,
4820 (dest - stackblock()) - startloc,
4821 stackblock() + startloc));
4827 subevalvar(p, str, strloc, subtype, startloc, varflags, quotes)
4840 int saveherefd = herefd;
4841 struct nodelist *saveargbackq = argbackq;
4845 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4846 STACKSTRNUL(expdest);
4847 herefd = saveherefd;
4848 argbackq = saveargbackq;
4849 startp = stackblock() + startloc;
4851 str = stackblock() + strloc;
4855 setvar(str, startp, 0);
4856 amount = startp - expdest;
4857 STADJUST(amount, expdest);
4864 if (*p != CTLENDVAR) {
4865 out2fmt(snlfmt, startp);
4866 error((char *)NULL);
4868 error("%.*s: parameter %snot set", p - str - 1,
4869 str, (varflags & VSNUL) ? "null or "
4874 for (loc = startp; loc < str; loc++) {
4877 if (patmatch2(str, startp, quotes))
4880 if (quotes && *loc == CTLESC)
4886 for (loc = str - 1; loc >= startp;) {
4889 if (patmatch2(str, startp, quotes))
4893 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4894 for (q = startp; q < loc; q++)
4904 for (loc = str - 1; loc >= startp;) {
4905 if (patmatch2(str, loc, quotes))
4908 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4909 for (q = startp; q < loc; q++)
4918 case VSTRIMRIGHTMAX:
4919 for (loc = startp; loc < str - 1; loc++) {
4920 if (patmatch2(str, loc, quotes))
4922 if (quotes && *loc == CTLESC)
4935 amount = ((str - 1) - (loc - startp)) - expdest;
4936 STADJUST(amount, expdest);
4937 while (loc != str - 1)
4942 amount = loc - expdest;
4943 STADJUST(amount, expdest);
4944 STPUTC('\0', expdest);
4945 STADJUST(-1, expdest);
4951 * Test whether a specialized variable is set.
4955 varisset(name, nulok)
4960 return backgndpid != -1;
4961 else if (*name == '@' || *name == '*') {
4962 if (*shellparam.p == NULL)
4968 for (av = shellparam.p; *av; av++)
4973 } else if (is_digit(*name)) {
4975 int num = atoi(name);
4977 if (num > shellparam.nparam)
4983 ap = shellparam.p[num - 1];
4985 if (nulok && (ap == NULL || *ap == '\0'))
4992 * Put a string on the stack.
4996 strtodest(const char *p, int syntax, int quotes)
4999 if (quotes && SIT(*p,syntax) == CCTL)
5000 STPUTC(CTLESC, expdest);
5001 STPUTC(*p++, expdest);
5006 * Add the value of a specialized variable to the stack string.
5010 varvalue(char *name, int quoted, int flags)
5019 int allow_split = flags & EXP_FULL;
5020 int quotes = flags & (EXP_FULL | EXP_CASE);
5022 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5031 num = shellparam.nparam;
5036 expdest = cvtnum(num, expdest);
5039 for (i = 0 ; i < NOPTS ; i++) {
5041 STPUTC(optent_letter(optlist[i]), expdest);
5045 if (allow_split && quoted) {
5046 sep = 1 << CHAR_BIT;
5051 sep = ifsset() ? ifsval()[0] : ' ';
5053 sepq = SIT(sep,syntax) == CCTL;
5056 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
5057 strtodest(p, syntax, quotes);
5060 STPUTC(CTLESC, expdest);
5061 STPUTC(sep, expdest);
5066 strtodest(arg0, syntax, quotes);
5070 if (num > 0 && num <= shellparam.nparam) {
5071 strtodest(shellparam.p[num - 1], syntax, quotes);
5079 * Record the fact that we have to scan this region of the
5080 * string for IFS characters.
5084 recordregion(start, end, nulonly)
5089 struct ifsregion *ifsp;
5091 if (ifslastp == NULL) {
5095 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5097 ifslastp->next = ifsp;
5101 ifslastp->begoff = start;
5102 ifslastp->endoff = end;
5103 ifslastp->nulonly = nulonly;
5109 * Break the argument string into pieces based upon IFS and add the
5110 * strings to the argument list. The regions of the string to be
5111 * searched for IFS characters have been stored by recordregion.
5114 ifsbreakup(string, arglist)
5116 struct arglist *arglist;
5118 struct ifsregion *ifsp;
5123 const char *ifs, *realifs;
5131 realifs = ifsset() ? ifsval() : defifs;
5132 if (ifslastp != NULL) {
5135 p = string + ifsp->begoff;
5136 nulonly = ifsp->nulonly;
5137 ifs = nulonly ? nullstr : realifs;
5139 while (p < string + ifsp->endoff) {
5143 if (strchr(ifs, *p)) {
5145 ifsspc = (strchr(defifs, *p) != NULL);
5146 /* Ignore IFS whitespace at start */
5147 if (q == start && ifsspc) {
5153 sp = (struct strlist *)stalloc(sizeof *sp);
5155 *arglist->lastp = sp;
5156 arglist->lastp = &sp->next;
5160 if (p >= string + ifsp->endoff) {
5166 if (strchr(ifs, *p) == NULL ) {
5169 } else if (strchr(defifs, *p) == NULL) {
5185 } while ((ifsp = ifsp->next) != NULL);
5186 if (!(*start || (!ifsspc && start > string && nulonly))) {
5191 sp = (struct strlist *)stalloc(sizeof *sp);
5193 *arglist->lastp = sp;
5194 arglist->lastp = &sp->next;
5200 while (ifsfirst.next != NULL) {
5201 struct ifsregion *ifsp;
5203 ifsp = ifsfirst.next->next;
5204 ckfree(ifsfirst.next);
5205 ifsfirst.next = ifsp;
5209 ifsfirst.next = NULL;
5213 * Add a file name to the list.
5217 addfname(const char *name)
5223 sp = (struct strlist *)stalloc(sizeof *sp);
5226 exparg.lastp = &sp->next;
5230 * Expand shell metacharacters. At this point, the only control characters
5231 * should be escapes. The results are stored in the list exparg.
5234 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5236 expandmeta(str, flag)
5237 struct strlist *str;
5242 /* TODO - EXP_REDIR */
5247 p = preglob(str->text);
5249 switch (glob(p, 0, 0, &pglob)) {
5251 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5262 *exparg.lastp = str;
5263 rmescapes(str->text);
5264 exparg.lastp = &str->next;
5266 default: /* GLOB_NOSPACE */
5267 error("Out of space");
5275 * Add the result of glob(3) to the list.
5280 const glob_t *pglob;
5282 char **p = pglob->gl_pathv;
5290 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5291 static char *expdir;
5295 expandmeta(str, flag)
5296 struct strlist *str;
5300 struct strlist **savelastp;
5303 /* TODO - EXP_REDIR */
5309 for (;;) { /* fast check for meta chars */
5310 if ((c = *p++) == '\0')
5312 if (c == '*' || c == '?' || c == '[' || c == '!')
5315 savelastp = exparg.lastp;
5317 if (expdir == NULL) {
5318 int i = strlen(str->text);
5319 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5322 expmeta(expdir, str->text);
5326 if (exparg.lastp == savelastp) {
5331 *exparg.lastp = str;
5332 rmescapes(str->text);
5333 exparg.lastp = &str->next;
5335 *exparg.lastp = NULL;
5336 *savelastp = sp = expsort(*savelastp);
5337 while (sp->next != NULL)
5339 exparg.lastp = &sp->next;
5347 * Do metacharacter (i.e. *, ?, [...]) expansion.
5351 expmeta(enddir, name)
5369 for (p = name ; ; p++) {
5370 if (*p == '*' || *p == '?')
5372 else if (*p == '[') {
5377 while (*q == CTLQUOTEMARK)
5381 if (*q == '/' || *q == '\0')
5388 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5390 } else if (*p == '\0')
5392 else if (*p == CTLQUOTEMARK)
5394 else if (*p == CTLESC)
5402 if (metaflag == 0) { /* we've reached the end of the file name */
5403 if (enddir != expdir)
5405 for (p = name ; ; p++) {
5406 if (*p == CTLQUOTEMARK)
5414 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5419 if (start != name) {
5422 while (*p == CTLQUOTEMARK)
5429 if (enddir == expdir) {
5431 } else if (enddir == expdir + 1 && *expdir == '/') {
5437 if ((dirp = opendir(cp)) == NULL)
5439 if (enddir != expdir)
5441 if (*endname == 0) {
5449 while (*p == CTLQUOTEMARK)
5455 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5456 if (dp->d_name[0] == '.' && ! matchdot)
5458 if (patmatch(start, dp->d_name, 0)) {
5460 strcpy(enddir, dp->d_name);
5463 for (p = enddir, cp = dp->d_name;
5464 (*p++ = *cp++) != '\0';)
5467 expmeta(p, endname);
5475 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5479 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5481 * Sort the results of file name expansion. It calculates the number of
5482 * strings to sort and then calls msort (short for merge sort) to do the
5486 static struct strlist *
5488 struct strlist *str;
5494 for (sp = str ; sp ; sp = sp->next)
5496 return msort(str, len);
5500 static struct strlist *
5502 struct strlist *list;
5505 struct strlist *p, *q = NULL;
5506 struct strlist **lpp;
5514 for (n = half ; --n >= 0 ; ) {
5518 q->next = NULL; /* terminate first half of list */
5519 q = msort(list, half); /* sort first half of list */
5520 p = msort(p, len - half); /* sort second half */
5523 if (strcmp(p->text, q->text) < 0) {
5526 if ((p = *lpp) == NULL) {
5533 if ((q = *lpp) == NULL) {
5546 * Returns true if the pattern matches the string.
5549 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5550 /* squoted: string might have quote chars */
5552 patmatch(char *pattern, char *string, int squoted)
5557 p = preglob(pattern);
5558 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5560 return !fnmatch(p, q, 0);
5565 patmatch2(char *pattern, char *string, int squoted)
5571 p = grabstackstr(expdest);
5572 res = patmatch(pattern, string, squoted);
5573 ungrabstackstr(p, expdest);
5578 patmatch(char *pattern, char *string, int squoted) {
5579 return pmatch(pattern, string, squoted);
5584 pmatch(char *pattern, char *string, int squoted)
5596 if (squoted && *q == CTLESC)
5604 if (squoted && *q == CTLESC)
5611 while (c == CTLQUOTEMARK || c == '*')
5613 if (c != CTLESC && c != CTLQUOTEMARK &&
5614 c != '?' && c != '*' && c != '[') {
5616 if (squoted && *q == CTLESC &&
5621 if (squoted && *q == CTLESC)
5627 if (pmatch(p, q, squoted))
5629 if (squoted && *q == CTLESC)
5631 } while (*q++ != '\0');
5642 while (*endp == CTLQUOTEMARK)
5645 goto dft; /* no matching ] */
5646 if (*endp == CTLESC)
5658 if (squoted && chr == CTLESC)
5664 if (c == CTLQUOTEMARK)
5668 if (*p == '-' && p[1] != ']') {
5670 while (*p == CTLQUOTEMARK)
5674 if (chr >= c && chr <= *p)
5681 } while ((c = *p++) != ']');
5682 if (found == invert)
5687 if (squoted && *q == CTLESC)
5704 * Remove any CTLESC characters from a string.
5707 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5709 _rmescapes(char *str, int flag)
5712 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5714 p = strpbrk(str, qchars);
5720 if (flag & RMESCAPE_ALLOC) {
5721 size_t len = p - str;
5722 q = r = stalloc(strlen(p) + len + 1);
5724 memcpy(q, str, len);
5729 if (*p == CTLQUOTEMARK) {
5735 if (flag & RMESCAPE_GLOB && *p != '/') {
5752 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5758 if (*p == CTLQUOTEMARK) {
5773 * See if a pattern matches in a case statement.
5777 casematch(union node *pattern, const char *val)
5779 struct stackmark smark;
5783 setstackmark(&smark);
5784 argbackq = pattern->narg.backquote;
5785 STARTSTACKSTR(expdest);
5787 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5788 STPUTC('\0', expdest);
5789 p = grabstackstr(expdest);
5790 result = patmatch(p, (char *)val, 0);
5791 popstackmark(&smark);
5806 CHECKSTRSPACE(32, buf);
5807 len = sprintf(buf, "%d", num);
5812 * Editline and history functions (and glue).
5814 static int histcmd(argc, argv)
5818 error("not compiled with history support");
5824 struct redirtab *next;
5825 short renamed[10]; /* Current ash support only 0-9 descriptors */
5826 /* char on arm (and others) can't be negative */
5829 static struct redirtab *redirlist;
5831 extern char **environ;
5836 * Initialization code.
5850 basepf.nextc = basepf.buf = basebuf;
5859 for (envp = environ ; *envp ; envp++) {
5860 if (strchr(*envp, '=')) {
5861 setvareq(*envp, VEXPORT|VTEXTFIXED);
5865 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5866 setvar("PPID", ppid, 0);
5873 * This routine is called when an error or an interrupt occurs in an
5874 * interactive shell and control is returned to the main command loop.
5877 /* 1 == check for aliases, 2 == also check for assignments */
5878 static int checkalias; /* also used in no alias mode for check assignments */
5892 if (exception != EXSHELLPROC)
5893 parselleft = parsenleft = 0; /* clear input buffer */
5897 /* from parser.c: */
5915 * This file implements the input routines used by the parser.
5918 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5919 static const char * cmdedit_prompt;
5920 static inline void putprompt(const char *s) {
5924 static inline void putprompt(const char *s) {
5929 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5934 * Same as pgetc(), but ignores PEOA.
5944 } while (c == PEOA);
5948 static inline int pgetc2() { return pgetc_macro(); }
5952 * Read a line from the script.
5955 static inline char *
5956 pfgets(char *line, int len)
5962 while (--nleft > 0) {
5981 char *buf = parsefile->buf;
5985 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5987 if (!iflag || parsefile->fd)
5988 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5990 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5994 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5998 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5999 int flags = fcntl(0, F_GETFL, 0);
6000 if (flags >= 0 && flags & O_NONBLOCK) {
6001 flags &=~ O_NONBLOCK;
6002 if (fcntl(0, F_SETFL, flags) >= 0) {
6003 out2str("sh: turning off NDELAY mode\n");
6015 struct strpush *sp = parsefile->strpush;
6020 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6025 if (sp->string != sp->ap->val) {
6029 sp->ap->flag &= ~ALIASINUSE;
6030 if (sp->ap->flag & ALIASDEAD) {
6031 unalias(sp->ap->name);
6035 parsenextc = sp->prevstring;
6036 parsenleft = sp->prevnleft;
6037 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6038 parsefile->strpush = sp->prev;
6039 if (sp != &(parsefile->basestrpush))
6046 * Refill the input buffer and return the next input character:
6048 * 1) If a string was pushed back on the input, pop it;
6049 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6050 * from a string so we can't refill the buffer, return EOF.
6051 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6052 * 4) Process input up to the next newline, deleting nul characters.
6062 while (parsefile->strpush) {
6064 if (parsenleft == -1 && parsefile->strpush->ap &&
6065 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6070 if (--parsenleft >= 0)
6071 return (*parsenextc++);
6073 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6078 if (parselleft <= 0) {
6079 if ((parselleft = preadfd()) <= 0) {
6080 parselleft = parsenleft = EOF_NLEFT;
6087 /* delete nul characters */
6088 for (more = 1; more;) {
6096 parsenleft = q - parsenextc;
6097 more = 0; /* Stop processing here */
6103 if (--parselleft <= 0 && more) {
6104 parsenleft = q - parsenextc - 1;
6115 out2str(parsenextc);
6120 return *parsenextc++;
6125 * Push a string back onto the input at this current parsefile level.
6126 * We handle aliases this way.
6129 pushstring(char *s, int len, void *ap)
6134 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6135 if (parsefile->strpush) {
6136 sp = ckmalloc(sizeof (struct strpush));
6137 sp->prev = parsefile->strpush;
6138 parsefile->strpush = sp;
6140 sp = parsefile->strpush = &(parsefile->basestrpush);
6141 sp->prevstring = parsenextc;
6142 sp->prevnleft = parsenleft;
6144 sp->ap = (struct alias *)ap;
6146 ((struct alias *)ap)->flag |= ALIASINUSE;
6157 * Like setinputfile, but takes input from a string.
6161 setinputstring(char *string)
6165 parsenextc = string;
6166 parsenleft = strlen(string);
6167 parsefile->buf = NULL;
6175 * To handle the "." command, a stack of input files is used. Pushfile
6176 * adds a new entry to the stack and popfile restores the previous level.
6181 struct parsefile *pf;
6183 parsefile->nleft = parsenleft;
6184 parsefile->lleft = parselleft;
6185 parsefile->nextc = parsenextc;
6186 parsefile->linno = plinno;
6187 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6188 pf->prev = parsefile;
6191 pf->basestrpush.prev = NULL;
6196 static void restartjob (struct job *);
6198 static void freejob (struct job *);
6199 static struct job *getjob (const char *);
6200 static int dowait (int, struct job *);
6201 static void waitonint(int);
6205 * We keep track of whether or not fd0 has been redirected. This is for
6206 * background commands, where we want to redirect fd0 to /dev/null only
6207 * if it hasn't already been redirected.
6209 static int fd0_redirected = 0;
6211 /* Return true if fd 0 has already been redirected at least once. */
6213 fd0_redirected_p (void)
6215 return fd0_redirected != 0;
6218 static void dupredirect (const union node *, int, int fd1dup);
6222 * Turn job control on and off.
6224 * Note: This code assumes that the third arg to ioctl is a character
6225 * pointer, which is true on Berkeley systems but not System V. Since
6226 * System V doesn't have job control yet, this isn't a problem now.
6231 static void setjobctl(int enable)
6233 #ifdef OLD_TTY_DRIVER
6237 if (enable == jobctl || rootshell == 0)
6240 do { /* while we are in the background */
6241 #ifdef OLD_TTY_DRIVER
6242 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6244 initialpgrp = tcgetpgrp(2);
6245 if (initialpgrp < 0) {
6247 out2str("sh: can't access tty; job control turned off\n");
6251 if (initialpgrp == -1)
6252 initialpgrp = getpgrp();
6253 else if (initialpgrp != getpgrp()) {
6254 killpg(initialpgrp, SIGTTIN);
6258 #ifdef OLD_TTY_DRIVER
6259 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6260 out2str("sh: need new tty driver to run job control; job control turned off\n");
6268 setpgid(0, rootpid);
6269 #ifdef OLD_TTY_DRIVER
6270 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6272 tcsetpgrp(2, rootpid);
6274 } else { /* turning job control off */
6275 setpgid(0, initialpgrp);
6276 #ifdef OLD_TTY_DRIVER
6277 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6279 tcsetpgrp(2, initialpgrp);
6305 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6306 "kill -l [exitstatus]"
6310 if (*argv[1] == '-') {
6311 signo = decode_signal(argv[1] + 1, 1);
6315 while ((c = nextopt("ls:")) != '\0')
6321 signo = decode_signal(optionarg, 1);
6324 "invalid signal number or name: %s",
6332 "nextopt returned character code 0%o", c);
6339 if (!list && signo < 0)
6342 if ((signo < 0 || !*argptr) ^ list) {
6351 for (i = 1; i < NSIG; i++) {
6352 name = u_signal_names(0, &i, 1);
6354 printf(snlfmt, name);
6358 name = u_signal_names(*argptr, &signo, -1);
6360 printf(snlfmt, name);
6362 error("invalid signal number or exit status: %s",
6368 if (**argptr == '%') {
6369 jp = getjob(*argptr);
6370 if (jp->jobctl == 0)
6371 error("job %s not created under job control",
6373 pid = -jp->ps[0].pid;
6375 pid = atoi(*argptr);
6376 if (kill(pid, signo) != 0)
6377 error("%s: %m", *argptr);
6378 } while (*++argptr);
6392 jp = getjob(argv[1]);
6393 if (jp->jobctl == 0)
6394 error("job not created under job control");
6395 pgrp = jp->ps[0].pid;
6396 #ifdef OLD_TTY_DRIVER
6397 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6403 status = waitforjob(jp);
6417 jp = getjob(*++argv);
6418 if (jp->jobctl == 0)
6419 error("job not created under job control");
6421 } while (--argc > 1);
6430 struct procstat *ps;
6433 if (jp->state == JOBDONE)
6436 killpg(jp->ps[0].pid, SIGCONT);
6437 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6438 if (WIFSTOPPED(ps->status)) {
6447 static void showjobs(int change);
6461 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6462 * statuses have changed since the last call to showjobs.
6464 * If the shell is interrupted in the process of creating a job, the
6465 * result may be a job structure containing zero processes. Such structures
6466 * will be freed here.
6477 struct procstat *ps;
6481 TRACE(("showjobs(%d) called\n", change));
6482 while (dowait(0, (struct job *)NULL) > 0);
6483 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6486 if (jp->nprocs == 0) {
6490 if (change && ! jp->changed)
6492 procno = jp->nprocs;
6493 for (ps = jp->ps ; ; ps++) { /* for each process */
6495 snprintf(s, 64, "[%d] %ld ", jobno,
6498 snprintf(s, 64, " %ld ",
6503 if (ps->status == -1) {
6504 /* don't print anything */
6505 } else if (WIFEXITED(ps->status)) {
6506 snprintf(s, 64, "Exit %d",
6507 WEXITSTATUS(ps->status));
6510 if (WIFSTOPPED(ps->status))
6511 i = WSTOPSIG(ps->status);
6512 else /* WIFSIGNALED(ps->status) */
6514 i = WTERMSIG(ps->status);
6515 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6516 strcpy(s, sys_siglist[i & 0x7F]);
6518 snprintf(s, 64, "Signal %d", i & 0x7F);
6519 if (WCOREDUMP(ps->status))
6520 strcat(s, " (core dumped)");
6525 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6532 if (jp->state == JOBDONE) {
6540 * Mark a job structure as unused.
6544 freejob(struct job *jp)
6546 const struct procstat *ps;
6550 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6551 if (ps->cmd != nullstr)
6554 if (jp->ps != &jp->ps0)
6558 if (curjob == jp - jobtab + 1)
6577 job = getjob(*++argv);
6581 for (;;) { /* loop until process terminated or stopped */
6584 status = job->ps[job->nprocs - 1].status;
6590 if (WIFEXITED(status))
6591 retval = WEXITSTATUS(status);
6593 else if (WIFSTOPPED(status))
6594 retval = WSTOPSIG(status) + 128;
6597 /* XXX: limits number of signals */
6598 retval = WTERMSIG(status) + 128;
6603 for (jp = jobtab ; ; jp++) {
6604 if (jp >= jobtab + njobs) { /* no running procs */
6607 if (jp->used && jp->state == 0)
6611 if (dowait(2, 0) < 0 && errno == EINTR) {
6620 * Convert a job name to a job structure.
6624 getjob(const char *name)
6634 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6635 error("No current job");
6636 return &jobtab[jobno - 1];
6638 error("No current job");
6640 } else if (name[0] == '%') {
6641 if (is_digit(name[1])) {
6642 jobno = number(name + 1);
6643 if (jobno > 0 && jobno <= njobs
6644 && jobtab[jobno - 1].used != 0)
6645 return &jobtab[jobno - 1];
6647 } else if (name[1] == '%' && name[2] == '\0') {
6651 struct job *found = NULL;
6652 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6653 if (jp->used && jp->nprocs > 0
6654 && prefix(name + 1, jp->ps[0].cmd)) {
6656 error("%s: ambiguous", name);
6663 } else if (is_number(name, &pid)) {
6664 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6665 if (jp->used && jp->nprocs > 0
6666 && jp->ps[jp->nprocs - 1].pid == pid)
6670 error("No such job: %s", name);
6677 * Return a new job structure,
6681 makejob(const union node *node, int nprocs)
6686 for (i = njobs, jp = jobtab ; ; jp++) {
6690 jobtab = ckmalloc(4 * sizeof jobtab[0]);
6692 jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
6693 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6694 /* Relocate `ps' pointers */
6695 for (i = 0; i < njobs; i++)
6696 if (jp[i].ps == &jobtab[i].ps0)
6697 jp[i].ps = &jp[i].ps0;
6701 jp = jobtab + njobs;
6702 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6715 jp->jobctl = jobctl;
6718 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
6723 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6730 * Fork of a subshell. If we are doing job control, give the subshell its
6731 * own process group. Jp is a job structure that the job is to be added to.
6732 * N is the command that will be evaluated by the child. Both jp and n may
6733 * be NULL. The mode parameter can be one of the following:
6734 * FORK_FG - Fork off a foreground process.
6735 * FORK_BG - Fork off a background process.
6736 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6737 * process group even if job control is on.
6739 * When job control is turned off, background processes have their standard
6740 * input redirected to /dev/null (except for the second and later processes
6747 forkshell(struct job *jp, const union node *n, int mode)
6753 const char *devnull = _PATH_DEVNULL;
6754 const char *nullerr = "Can't open %s";
6756 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6761 TRACE(("Fork failed, errno=%d\n", errno));
6763 error("Cannot fork");
6770 TRACE(("Child shell %d\n", getpid()));
6771 wasroot = rootshell;
6777 jobctl = 0; /* do job control only in root shell */
6778 if (wasroot && mode != FORK_NOJOB && mflag) {
6779 if (jp == NULL || jp->nprocs == 0)
6782 pgrp = jp->ps[0].pid;
6784 if (mode == FORK_FG) {
6785 /*** this causes superfluous TIOCSPGRPS ***/
6786 #ifdef OLD_TTY_DRIVER
6787 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6788 error("TIOCSPGRP failed, errno=%d", errno);
6790 if (tcsetpgrp(2, pgrp) < 0)
6791 error("tcsetpgrp failed, errno=%d", errno);
6796 } else if (mode == FORK_BG) {
6799 if ((jp == NULL || jp->nprocs == 0) &&
6800 ! fd0_redirected_p ()) {
6802 if (open(devnull, O_RDONLY) != 0)
6803 error(nullerr, devnull);
6807 if (mode == FORK_BG) {
6810 if ((jp == NULL || jp->nprocs == 0) &&
6811 ! fd0_redirected_p ()) {
6813 if (open(devnull, O_RDONLY) != 0)
6814 error(nullerr, devnull);
6818 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6821 if (wasroot && iflag) {
6829 if (rootshell && mode != FORK_NOJOB && mflag) {
6830 if (jp == NULL || jp->nprocs == 0)
6833 pgrp = jp->ps[0].pid;
6837 if (mode == FORK_BG)
6838 backgndpid = pid; /* set $! */
6840 struct procstat *ps = &jp->ps[jp->nprocs++];
6844 if (iflag && rootshell && n)
6845 ps->cmd = commandtext(n);
6848 TRACE(("In parent shell: child = %d\n", pid));
6855 * Wait for job to finish.
6857 * Under job control we have the problem that while a child process is
6858 * running interrupts generated by the user are sent to the child but not
6859 * to the shell. This means that an infinite loop started by an inter-
6860 * active user may be hard to kill. With job control turned off, an
6861 * interactive user may place an interactive program inside a loop. If
6862 * the interactive program catches interrupts, the user doesn't want
6863 * these interrupts to also abort the loop. The approach we take here
6864 * is to have the shell ignore interrupt signals while waiting for a
6865 * forground process to terminate, and then send itself an interrupt
6866 * signal if the child process was terminated by an interrupt signal.
6867 * Unfortunately, some programs want to do a bit of cleanup and then
6868 * exit on interrupt; unless these processes terminate themselves by
6869 * sending a signal to themselves (instead of calling exit) they will
6870 * confuse this approach.
6874 waitforjob(struct job *jp)
6877 int mypgrp = getpgrp();
6881 struct sigaction act, oact;
6890 sigaction(SIGINT, 0, &act);
6891 act.sa_handler = waitonint;
6892 sigaction(SIGINT, &act, &oact);
6894 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6895 while (jp->state == 0) {
6903 sigaction(SIGINT, &oact, 0);
6904 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6908 #ifdef OLD_TTY_DRIVER
6909 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6910 error("TIOCSPGRP failed, errno=%d\n", errno);
6912 if (tcsetpgrp(2, mypgrp) < 0)
6913 error("tcsetpgrp failed, errno=%d\n", errno);
6916 if (jp->state == JOBSTOPPED)
6917 curjob = jp - jobtab + 1;
6919 status = jp->ps[jp->nprocs - 1].status;
6920 /* convert to 8 bits */
6921 if (WIFEXITED(status))
6922 st = WEXITSTATUS(status);
6924 else if (WIFSTOPPED(status))
6925 st = WSTOPSIG(status) + 128;
6928 st = WTERMSIG(status) + 128;
6932 * This is truly gross.
6933 * If we're doing job control, then we did a TIOCSPGRP which
6934 * caused us (the shell) to no longer be in the controlling
6935 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6936 * intuit from the subprocess exit status whether a SIGINT
6937 * occured, and if so interrupt ourselves. Yuck. - mycroft
6939 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6942 if (jp->state == JOBDONE)
6953 * Wait for a process to terminate.
6957 * Do a wait system call. If job control is compiled in, we accept
6958 * stopped processes. If block is zero, we return a value of zero
6959 * rather than blocking.
6961 * System V doesn't have a non-blocking wait system call. It does
6962 * have a SIGCLD signal that is sent to a process when one of it's
6963 * children dies. The obvious way to use SIGCLD would be to install
6964 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6965 * was received, and have waitproc bump another counter when it got
6966 * the status of a process. Waitproc would then know that a wait
6967 * system call would not block if the two counters were different.
6968 * This approach doesn't work because if a process has children that
6969 * have not been waited for, System V will send it a SIGCLD when it
6970 * installs a signal handler for SIGCLD. What this means is that when
6971 * a child exits, the shell will be sent SIGCLD signals continuously
6972 * until is runs out of stack space, unless it does a wait call before
6973 * restoring the signal handler. The code below takes advantage of
6974 * this (mis)feature by installing a signal handler for SIGCLD and
6975 * then checking to see whether it was called. If there are any
6976 * children to be waited for, it will be.
6981 waitproc(int block, int *status)
6992 return wait3(status, flags, (struct rusage *)NULL);
6996 dowait(int block, struct job *job)
7000 struct procstat *sp;
7002 struct job *thisjob;
7008 TRACE(("dowait(%d) called\n", block));
7010 pid = waitproc(block, &status);
7011 TRACE(("wait returns %d, status=%d\n", pid, status));
7012 } while (!(block & 2) && pid == -1 && errno == EINTR);
7017 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
7021 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
7024 if (sp->pid == pid) {
7025 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
7026 sp->status = status;
7029 if (sp->status == -1)
7031 else if (WIFSTOPPED(sp->status))
7034 if (stopped) { /* stopped or done */
7035 int state = done? JOBDONE : JOBSTOPPED;
7036 if (jp->state != state) {
7037 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
7040 if (done && curjob == jp - jobtab + 1)
7041 curjob = 0; /* no current job */
7048 if (! rootshell || ! iflag || (job && thisjob == job)) {
7049 core = WCOREDUMP(status);
7051 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
7054 if (WIFEXITED(status)) sig = 0;
7055 else sig = WTERMSIG(status);
7057 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
7059 out2fmt("%d: ", pid);
7061 if (sig == SIGTSTP && rootshell && iflag)
7063 (long)(job - jobtab + 1));
7065 if (sig < NSIG && sys_siglist[sig])
7066 out2str(sys_siglist[sig]);
7068 out2fmt("Signal %d", sig);
7070 out2str(" - core dumped");
7073 TRACE(("Not printing status: status=%d, sig=%d\n",
7077 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
7079 thisjob->changed = 1;
7088 * return 1 if there are stopped jobs, otherwise 0
7098 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7101 if (jp->state == JOBSTOPPED) {
7102 out2str("You have stopped jobs.\n");
7112 * Return a string identifying a command (to be printed by the
7116 static char *cmdnextc;
7117 static int cmdnleft;
7118 #define MAXCMDTEXT 200
7121 cmdputs(const char *s)
7132 while ((c = *p++) != '\0') {
7135 else if (c == CTLVAR) {
7140 } else if (c == '=' && subtype != 0) {
7141 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7143 } else if (c == CTLENDVAR) {
7145 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7146 cmdnleft++; /* ignore it */
7149 if (--cmdnleft <= 0) {
7159 #define CMDTXT_TABLE
7162 * To collect a lot of redundant code in cmdtxt() case statements, we
7163 * implement a mini language here. Each type of node struct has an
7164 * associated instruction sequence that operates on its members via
7165 * their offsets. The instruction are pack in unsigned chars with
7166 * format IIDDDDDE where the bits are
7167 * I : part of the instruction opcode, which are
7168 * 00 : member is a pointer to another node -- process it recursively
7169 * 40 : member is a pointer to a char string -- output it
7170 * 80 : output the string whose index is stored in the data field
7171 * CC : flag signaling that this case needs external processing
7172 * D : data - either the (shifted) index of a fixed string to output or
7173 * the actual offset of the member to operate on in the struct
7174 * (since we assume bit 0 is set, the offset is not shifted)
7175 * E : flag signaling end of instruction sequence
7177 * WARNING: In order to handle larger offsets for 64bit archs, this code
7178 * assumes that no offset can be an odd number and stores the
7179 * end-of-instructions flag in bit 0.
7182 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7183 #define CMDTXT_CHARPTR 0x40
7184 #define CMDTXT_STRING 0x80
7185 #define CMDTXT_SPECIAL 0xC0
7186 #define CMDTXT_OFFSETMASK 0x3E
7188 static const char * const cmdtxt_strings[] = {
7189 /* 0 1 2 3 4 5 6 7 */
7190 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7191 /* 8 9 10 11 12 13 */
7192 "while ", "; do ", "; done", "until ", "for ", " in ...",
7194 "case ", "???", "() ...", "<<..."
7197 static const char * const redir_strings[] = {
7198 ">", "<", "<>", ">>", ">|", ">&", "<&"
7201 static const unsigned char cmdtxt_ops[] = {
7202 #define CMDTXT_NSEMI 0
7203 offsetof(union node, nbinary.ch1),
7205 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7206 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7207 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7208 #define CMDTXT_NCASE (CMDTXT_NCMD)
7209 #define CMDTXT_NTO (CMDTXT_NCMD)
7210 #define CMDTXT_NFROM (CMDTXT_NCMD)
7211 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7212 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7213 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7214 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7215 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7217 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7218 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7219 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7220 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7221 (1*2)|CMDTXT_STRING,
7222 offsetof(union node, nredir.n),
7223 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7224 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7225 offsetof(union node, nbinary.ch1),
7226 (3*2)|CMDTXT_STRING,
7227 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7228 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7229 offsetof(union node, nbinary.ch1),
7230 (4*2)|CMDTXT_STRING,
7231 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7232 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7233 (5*2)|CMDTXT_STRING,
7234 offsetof(union node, nif.test),
7235 (6*2)|CMDTXT_STRING,
7236 offsetof(union node, nif.ifpart),
7237 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7238 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7239 (8*2)|CMDTXT_STRING,
7240 offsetof(union node, nbinary.ch1),
7241 (9*2)|CMDTXT_STRING,
7242 offsetof(union node, nbinary.ch2),
7243 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7244 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7245 (11*2)|CMDTXT_STRING,
7246 offsetof(union node, nbinary.ch1),
7247 (9*2)|CMDTXT_STRING,
7248 offsetof(union node, nbinary.ch2),
7249 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7250 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7251 (12*2)|CMDTXT_STRING,
7252 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7253 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7254 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7255 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7256 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7257 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7258 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7259 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7260 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7261 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7262 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7263 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7264 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7267 #if CMDTXT_NXHERE != 36
7268 #error CMDTXT_NXHERE
7271 static const unsigned char cmdtxt_ops_index[26] = {
7301 cmdtxt(const union node *n)
7308 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7309 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7311 if (*p & CMDTXT_STRING) { /* output fixed string */
7312 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7314 const char *pf = ((const char *) n)
7315 + ((int)(*p & CMDTXT_OFFSETMASK));
7316 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7317 cmdputs(*((const char **) pf));
7318 } else { /* output field */
7319 cmdtxt(*((const union node **) pf));
7322 } while (!(*p++ & CMDTXT_NOMORE));
7323 } else if (n->type == NCMD) {
7325 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7330 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7334 } else if (n->type == NPIPE) {
7335 struct nodelist *lp;
7336 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7341 } else if (n->type == NCASE) {
7342 cmdputs(cmdtxt_strings[14]);
7343 cmdputs(n->ncase.expr->narg.text);
7344 cmdputs(cmdtxt_strings[13]);
7346 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7347 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7352 assert((n->type >= NTO) && (n->type <= NFROMFD));
7355 p = redir_strings[n->type - NTO];
7356 if (n->nfile.fd != ('>' == *p)) {
7357 s[0] = n->nfile.fd + '0';
7362 if (n->type >= NTOFD) {
7363 s[0] = n->ndup.dupfd + '0';
7367 cmdtxt(n->nfile.fname);
7371 #else /* CMDTXT_TABLE */
7373 cmdtxt(const union node *n)
7376 struct nodelist *lp;
7385 cmdtxt(n->nbinary.ch1);
7387 cmdtxt(n->nbinary.ch2);
7390 cmdtxt(n->nbinary.ch1);
7392 cmdtxt(n->nbinary.ch2);
7395 cmdtxt(n->nbinary.ch1);
7397 cmdtxt(n->nbinary.ch2);
7400 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7408 cmdtxt(n->nredir.n);
7413 cmdtxt(n->nredir.n);
7417 cmdtxt(n->nif.test);
7419 cmdtxt(n->nif.ifpart);
7428 cmdtxt(n->nbinary.ch1);
7430 cmdtxt(n->nbinary.ch2);
7435 cmdputs(n->nfor.var);
7440 cmdputs(n->ncase.expr->narg.text);
7444 cmdputs(n->narg.text);
7448 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7453 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7459 cmdputs(n->narg.text);
7462 p = ">"; i = 1; goto redir;
7464 p = ">>"; i = 1; goto redir;
7466 p = ">&"; i = 1; goto redir;
7468 p = ">|"; i = 1; goto redir;
7470 p = "<"; i = 0; goto redir;
7472 p = "<&"; i = 0; goto redir;
7474 p = "<>"; i = 0; goto redir;
7476 if (n->nfile.fd != i) {
7477 s[0] = n->nfile.fd + '0';
7482 if (n->type == NTOFD || n->type == NFROMFD) {
7483 s[0] = n->ndup.dupfd + '0';
7487 cmdtxt(n->nfile.fname);
7499 #endif /* CMDTXT_TABLE */
7502 commandtext(const union node *n)
7506 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7507 cmdnleft = MAXCMDTEXT - 4;
7514 static void waitonint(int sig) {
7519 * Routines to check for mail. (Perhaps make part of main.c?)
7523 #define MAXMBOXES 10
7526 static int nmboxes; /* number of mailboxes */
7527 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7532 * Print appropriate message(s) if mail has arrived. If the argument is
7533 * nozero, then the value of MAIL has changed, so we just update the
7544 struct stackmark smark;
7551 setstackmark(&smark);
7552 mpath = mpathset()? mpathval() : mailval();
7553 for (i = 0 ; i < nmboxes ; i++) {
7554 p = padvance(&mpath, nullstr);
7559 for (q = p ; *q ; q++);
7564 q[-1] = '\0'; /* delete trailing '/' */
7565 if (stat(p, &statb) < 0)
7567 if (statb.st_size > mailtime[i] && ! silent) {
7569 pathopt? pathopt : "you have mail");
7571 mailtime[i] = statb.st_size;
7574 popstackmark(&smark);
7580 static short profile_buf[16384];
7584 static void read_profile (const char *);
7585 static void cmdloop (int);
7586 static void options (int);
7587 static void setoption (int, int);
7588 static void procargs (int, char **);
7592 * Main routine. We initialize things, parse the arguments, execute
7593 * profiles if we're a login shell, and then call cmdloop to execute
7594 * commands. The setjmp call sets up the location to jump to when an
7595 * exception occurs. When an exception occurs the variable "state"
7596 * is used to figure out how far we had gotten.
7600 ash_main(argc, argv)
7604 struct jmploc jmploc;
7605 struct stackmark smark;
7609 BLTINCMD = find_builtin("builtin");
7610 EXECCMD = find_builtin("exec");
7611 EVALCMD = find_builtin("eval");
7613 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7619 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7621 #if defined(linux) || defined(__GNU__)
7622 signal(SIGCHLD, SIG_DFL);
7625 if (setjmp(jmploc.loc)) {
7628 * When a shell procedure is executed, we raise the
7629 * exception EXSHELLPROC to clean up before executing
7630 * the shell procedure.
7632 if (exception == EXSHELLPROC) {
7638 if (exception == EXEXEC) {
7639 exitstatus = exerrno;
7640 } else if (exception == EXERROR) {
7643 if (state == 0 || iflag == 0 || ! rootshell)
7644 exitshell(exitstatus);
7647 if (exception == EXINT) {
7650 popstackmark(&smark);
7651 FORCEINTON; /* enable interrupts */
7654 else if (state == 2)
7656 else if (state == 3)
7664 trputs("Shell args: "); trargs(argv);
7669 setstackmark(&smark);
7670 procargs(argc, argv);
7671 if (argv[0] && argv[0][0] == '-') {
7673 read_profile("/etc/profile");
7676 read_profile(".profile");
7681 if (getuid() == geteuid() && getgid() == getegid()) {
7683 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7685 read_profile(shinit);
7692 if (sflag == 0 || minusc) {
7693 static const char sigs[] = {
7694 SIGINT, SIGQUIT, SIGHUP,
7700 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7703 for (i = 0; i < SIGSSIZE; i++)
7708 evalstring(minusc, 0);
7710 if (sflag || minusc == NULL) {
7711 state4: /* XXX ??? - why isn't this before the "if" statement */
7717 exitshell(exitstatus);
7723 * Read and execute commands. "Top" is nonzero for the top level command
7724 * loop; it turns on prompting if the shell is interactive.
7731 struct stackmark smark;
7735 TRACE(("cmdloop(%d) called\n", top));
7736 setstackmark(&smark);
7747 n = parsecmd(inter);
7748 /* showtree(n); DEBUG */
7750 if (!top || numeof >= 50)
7752 if (!stoppedjobs()) {
7755 out2str("\nUse \"exit\" to leave shell.\n");
7758 } else if (n != NULL && nflag == 0) {
7759 job_warning = (job_warning == 2) ? 1 : 0;
7763 popstackmark(&smark);
7764 setstackmark(&smark);
7765 if (evalskip == SKIPFILE) {
7770 popstackmark(&smark);
7776 * Read /etc/profile or .profile. Return on error.
7788 if ((fd = open(name, O_RDONLY)) >= 0)
7793 /* -q turns off -x and -v just when executing init files */
7794 /* Note: Might do a little redundant work, but reduces code size. */
7809 * Read a file containing shell functions.
7813 readcmdfile(const char *name)
7818 if ((fd = open(name, O_RDONLY)) >= 0)
7821 error("Can't open %s", name);
7830 * Take commands from a file. To be compatable we should do a path
7831 * search for the file, which is necessary to find sub-commands.
7834 static inline char *
7835 find_dot_file(char *mybasename)
7838 const char *path = pathval();
7841 /* don't try this for absolute or relative paths */
7842 if (strchr(mybasename, '/'))
7845 while ((fullname = padvance(&path, mybasename)) != NULL) {
7846 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7848 * Don't bother freeing here, since it will
7849 * be freed by the caller.
7853 stunalloc(fullname);
7856 /* not found in the PATH */
7857 error("%s: not found", mybasename);
7869 for (sp = cmdenviron; sp ; sp = sp->next)
7870 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
7872 if (argc >= 2) { /* That's what SVR2 does */
7874 struct stackmark smark;
7876 setstackmark(&smark);
7877 fullname = find_dot_file(argv[1]);
7878 setinputfile(fullname, 1);
7879 commandname = fullname;
7882 popstackmark(&smark);
7896 exitstatus = number(argv[1]);
7898 exitstatus = oexitstatus;
7899 exitshell(exitstatus);
7908 nbytes = ALIGN(nbytes);
7909 if (nbytes > stacknleft) {
7911 struct stack_block *sp;
7914 if (blocksize < MINSIZE)
7915 blocksize = MINSIZE;
7917 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7919 stacknxt = sp->space;
7920 stacknleft = blocksize;
7926 stacknleft -= nbytes;
7932 stunalloc(pointer p)
7935 if (p == NULL) { /*DEBUG */
7936 write(2, "stunalloc\n", 10);
7940 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7943 stacknleft += stacknxt - (char *)p;
7949 setstackmark(struct stackmark *mark)
7951 mark->stackp = stackp;
7952 mark->stacknxt = stacknxt;
7953 mark->stacknleft = stacknleft;
7954 mark->marknext = markp;
7960 popstackmark(struct stackmark *mark)
7962 struct stack_block *sp;
7965 markp = mark->marknext;
7966 while (stackp != mark->stackp) {
7971 stacknxt = mark->stacknxt;
7972 stacknleft = mark->stacknleft;
7978 * When the parser reads in a string, it wants to stick the string on the
7979 * stack and only adjust the stack pointer when it knows how big the
7980 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7981 * of space on top of the stack and stackblocklen returns the length of
7982 * this block. Growstackblock will grow this space by at least one byte,
7983 * possibly moving it (like realloc). Grabstackblock actually allocates the
7984 * part of the block that has been used.
7988 growstackblock(void) {
7990 int newlen = ALIGN(stacknleft * 2 + 100);
7991 char *oldspace = stacknxt;
7992 int oldlen = stacknleft;
7993 struct stack_block *sp;
7994 struct stack_block *oldstackp;
7996 if (stacknxt == stackp->space && stackp != &stackbase) {
8001 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8004 stacknxt = sp->space;
8005 stacknleft = newlen;
8007 /* Stack marks pointing to the start of the old block
8008 * must be relocated to point to the new block
8010 struct stackmark *xmark;
8012 while (xmark != NULL && xmark->stackp == oldstackp) {
8013 xmark->stackp = stackp;
8014 xmark->stacknxt = stacknxt;
8015 xmark->stacknleft = stacknleft;
8016 xmark = xmark->marknext;
8021 p = stalloc(newlen);
8022 memcpy(p, oldspace, oldlen);
8023 stacknxt = p; /* free the space */
8024 stacknleft += newlen; /* we just allocated */
8031 grabstackblock(int len)
8041 * The following routines are somewhat easier to use that the above.
8042 * The user declares a variable of type STACKSTR, which may be declared
8043 * to be a register. The macro STARTSTACKSTR initializes things. Then
8044 * the user uses the macro STPUTC to add characters to the string. In
8045 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8046 * grown as necessary. When the user is done, she can just leave the
8047 * string there and refer to it using stackblock(). Or she can allocate
8048 * the space for it using grabstackstr(). If it is necessary to allow
8049 * someone else to use the stack temporarily and then continue to grow
8050 * the string, the user should use grabstack to allocate the space, and
8051 * then call ungrabstr(p) to return to the previous mode of operation.
8053 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8054 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8055 * is space for at least one character.
8060 growstackstr(void) {
8061 int len = stackblocksize();
8062 if (herefd >= 0 && len >= 1024) {
8063 xwrite(herefd, stackblock(), len);
8064 sstrnleft = len - 1;
8065 return stackblock();
8068 sstrnleft = stackblocksize() - len - 1;
8069 return stackblock() + len;
8074 * Called from CHECKSTRSPACE.
8078 makestrspace(size_t newlen) {
8079 int len = stackblocksize() - sstrnleft;
8082 sstrnleft = stackblocksize() - len;
8083 } while (sstrnleft < newlen);
8084 return stackblock() + len;
8090 ungrabstackstr(char *s, char *p)
8092 stacknleft += stacknxt - s;
8094 sstrnleft = stacknleft - (p - s);
8097 * Miscelaneous builtins.
8103 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8104 typedef long rlim_t;
8110 * The read builtin. The -e option causes backslashes to escape the
8111 * following character.
8113 * This uses unbuffered input, which may be avoidable in some cases.
8117 readcmd(int argc, char **argv)
8132 while ((i = nextopt("p:r")) != '\0') {
8138 if (prompt && isatty(0)) {
8139 out2str(prompt); /* read without cmdedit */
8142 if (*(ap = argptr) == NULL)
8144 if ((ifs = bltinlookup("IFS")) == NULL)
8151 if (read(0, &c, 1) != 1) {
8163 if (!rflag && c == '\\') {
8169 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8173 if (backslash && c == '\\') {
8174 if (read(0, &c, 1) != 1) {
8179 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8181 setvar(*ap, stackblock(), 0);
8190 /* Remove trailing blanks */
8191 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8193 setvar(*ap, stackblock(), 0);
8194 while (*++ap != NULL)
8195 setvar(*ap, nullstr, 0);
8202 umaskcmd(argc, argv)
8206 static const char permuser[3] = "ugo";
8207 static const char permmode[3] = "rwx";
8208 static const short int permmask[] = {
8209 S_IRUSR, S_IWUSR, S_IXUSR,
8210 S_IRGRP, S_IWGRP, S_IXGRP,
8211 S_IROTH, S_IWOTH, S_IXOTH
8217 int symbolic_mode = 0;
8219 while (nextopt("S") != '\0') {
8228 if ((ap = *argptr) == NULL) {
8229 if (symbolic_mode) {
8232 for (i=0 ; i<3 ; i++) {
8236 for (j=0 ; j<3 ; j++) {
8237 if ((mask & permmask[3*i+j]) == 0) {
8246 printf("%.4o\n", mask);
8249 if (is_digit((unsigned char)*ap)) {
8252 if (*ap >= '8' || *ap < '0')
8253 error("Illegal number: %s", argv[1]);
8254 mask = (mask << 3) + (*ap - '0');
8255 } while (*++ap != '\0');
8258 mask = ~mask & 0777;
8259 if (parse_mode(ap, &mask) == FALSE) {
8260 error("Illegal mode: %s", ap);
8262 umask(~mask & 0777);
8271 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8272 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8273 * ash by J.T. Conklin.
8281 short factor; /* multiply by to get rlim_{cur,max} values */
8284 static const struct limits limits[] = {
8286 { "time(seconds)", RLIMIT_CPU, 1 },
8289 { "file(blocks)", RLIMIT_FSIZE, 512 },
8292 { "data(kbytes)", RLIMIT_DATA, 1024 },
8295 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8298 { "coredump(blocks)", RLIMIT_CORE, 512 },
8301 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8303 #ifdef RLIMIT_MEMLOCK
8304 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8307 { "process(processes)", RLIMIT_NPROC, 1 },
8309 #ifdef RLIMIT_NOFILE
8310 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8313 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8316 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8322 ulimitcmd(argc, argv)
8326 static const char unlimited_string[] = "unlimited";
8329 enum { SOFT = 0x1, HARD = 0x2 }
8331 const struct limits *l;
8334 struct rlimit limit;
8338 while ((optc = nextopt("HSa"
8357 #ifdef RLIMIT_MEMLOCK
8363 #ifdef RLIMIT_NOFILE
8375 } else if (optc == 'S') {
8377 } else if (optc == 'a') {
8384 for (l = limits; l->name; l++) {
8385 if(l->name[0] == what)
8387 if(l->name[1]=='w' && what=='w')
8391 set = *argptr ? 1 : 0;
8395 if (all || argptr[1])
8396 error("too many arguments");
8397 if (strcmp(p, unlimited_string) == 0)
8398 val = RLIM_INFINITY;
8402 while ((c = *p++) >= '0' && c <= '9')
8404 val = (val * 10) + (long)(c - '0');
8405 if (val < (rlim_t) 0)
8409 error("bad number");
8415 for (l = limits; l->name; l++) {
8416 printf("%-20s ", l->name);
8417 getrlimit(l->cmd, &limit);
8420 val = limit.rlim_cur;
8421 else if (how & HARD)
8422 val = limit.rlim_max;
8424 if (val == RLIM_INFINITY)
8425 puts(unlimited_string);
8429 printf("%lld\n", (long long) val);
8442 getrlimit(l->cmd, &limit);
8444 limit.rlim_max = val;
8446 limit.rlim_cur = val;
8447 if (setrlimit(l->cmd, &limit) < 0)
8448 error("error setting limit (%m)");
8452 * prefix -- see if pfx is a prefix of string.
8456 prefix(char const *pfx, char const *string)
8459 if (*pfx++ != *string++)
8466 * Return true if s is a string of digits, and save munber in intptr
8471 is_number(const char *p, int *intptr)
8479 ret += digit_val(*p);
8481 } while (*p != '\0');
8488 * Convert a string of digits to an integer, printing an error message on
8493 number(const char *s)
8496 if (! is_number(s, &i))
8497 error("Illegal number: %s", s);
8502 * Produce a possibly single quoted string suitable as input to the shell.
8503 * The return string is allocated on the stack.
8507 single_quote(const char *s) {
8514 size_t len1, len1p, len2, len2p;
8516 len1 = strcspn(s, "'");
8517 len2 = strspn(s + len1, "'");
8519 len1p = len1 ? len1 + 2 : len1;
8520 len2p = len2 + ((len2 < 2) ? len2 : 2);
8522 CHECKSTRSPACE(len1p + len2p + 1, p);
8527 memcpy(p + 1, s, len1);
8535 memcpy(q + 1, s, len2);
8538 } else if (len2 == 1) {
8544 STADJUST(len1p + len2p, p);
8549 return grabstackstr(p);
8553 * Like strdup but works with the ash stack.
8557 sstrdup(const char *p)
8559 size_t len = strlen(p) + 1;
8560 return memcpy(stalloc(len), p, len);
8565 * Routine for dealing with parsed shell commands.
8569 static void sizenodelist (const struct nodelist *);
8570 static struct nodelist *copynodelist (const struct nodelist *);
8571 static char *nodesavestr (const char *);
8573 #define CALCSIZE_TABLE
8574 #define COPYNODE_TABLE
8575 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8577 * To collect a lot of redundant code in case statements for copynode()
8578 * and calcsize(), we implement a mini language here. Each type of node
8579 * struct has an associated instruction sequence that operates on its
8580 * members via their offsets. The instruction are pack in unsigned chars
8581 * with format IIDDDDDE where the bits are
8582 * I : part of the instruction opcode, which are
8583 * 00 : member is a pointer to another node
8584 * 40 : member is an integer
8585 * 80 : member is a pointer to a nodelist
8586 * CC : member is a pointer to a char string
8587 * D : data - the actual offset of the member to operate on in the struct
8588 * (since we assume bit 0 is set, it is not shifted)
8589 * E : flag signaling end of instruction sequence
8591 * WARNING: In order to handle larger offsets for 64bit archs, this code
8592 * assumes that no offset can be an odd number and stores the
8593 * end-of-instructions flag in bit 0.
8596 #define NODE_INTEGER 0x40
8597 #define NODE_NODELIST 0x80
8598 #define NODE_CHARPTR 0xC0
8599 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8600 #define NODE_MBRMASK 0xC0
8601 #define NODE_OFFSETMASK 0x3E
8603 static const unsigned char copynode_ops[35] = {
8604 #define COPYNODE_OPS0 0
8605 offsetof(union node, nbinary.ch2),
8606 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8607 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8608 offsetof(union node, ncmd.redirect),
8609 offsetof(union node, ncmd.args),
8610 offsetof(union node, ncmd.assign),
8611 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8612 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8613 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8614 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8615 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8616 offsetof(union node, nredir.redirect),
8617 offsetof(union node, nredir.n)|NODE_NOMORE,
8618 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8619 offsetof(union node, nif.elsepart),
8620 offsetof(union node, nif.ifpart),
8621 offsetof(union node, nif.test)|NODE_NOMORE,
8622 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8623 offsetof(union node, nfor.var)|NODE_CHARPTR,
8624 offsetof(union node, nfor.body),
8625 offsetof(union node, nfor.args)|NODE_NOMORE,
8626 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8627 offsetof(union node, ncase.cases),
8628 offsetof(union node, ncase.expr)|NODE_NOMORE,
8629 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8630 offsetof(union node, nclist.body),
8631 offsetof(union node, nclist.pattern),
8632 offsetof(union node, nclist.next)|NODE_NOMORE,
8633 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8634 offsetof(union node, narg.backquote)|NODE_NODELIST,
8635 offsetof(union node, narg.text)|NODE_CHARPTR,
8636 offsetof(union node, narg.next)|NODE_NOMORE,
8637 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8638 offsetof(union node, nfile.fname),
8639 offsetof(union node, nfile.fd)|NODE_INTEGER,
8640 offsetof(union node, nfile.next)|NODE_NOMORE,
8641 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8642 offsetof(union node, ndup.vname),
8643 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8644 offsetof(union node, ndup.fd)|NODE_INTEGER,
8645 offsetof(union node, ndup.next)|NODE_NOMORE,
8646 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8647 offsetof(union node, nhere.doc),
8648 offsetof(union node, nhere.fd)|NODE_INTEGER,
8649 offsetof(union node, nhere.next)|NODE_NOMORE,
8650 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8651 offsetof(union node, nnot.com)|NODE_NOMORE,
8654 #if COPYNODE_OPS12 != 34
8655 #error COPYNODE_OPS12 is incorrect
8658 static const unsigned char copynode_ops_index[26] = {
8659 COPYNODE_OPS0, /* NSEMI */
8660 COPYNODE_OPS1, /* NCMD */
8661 COPYNODE_OPS2, /* NPIPE */
8662 COPYNODE_OPS3, /* NREDIR */
8663 COPYNODE_OPS3, /* NBACKGND */
8664 COPYNODE_OPS3, /* NSUBSHELL */
8665 COPYNODE_OPS0, /* NAND */
8666 COPYNODE_OPS0, /* NOR */
8667 COPYNODE_OPS4, /* NIF */
8668 COPYNODE_OPS0, /* NWHILE */
8669 COPYNODE_OPS0, /* NUNTIL */
8670 COPYNODE_OPS5, /* NFOR */
8671 COPYNODE_OPS6, /* NCASE */
8672 COPYNODE_OPS7, /* NCLIST */
8673 COPYNODE_OPS8, /* NDEFUN */
8674 COPYNODE_OPS8, /* NARG */
8675 COPYNODE_OPS9, /* NTO */
8676 COPYNODE_OPS9, /* NFROM */
8677 COPYNODE_OPS9, /* NFROMTO */
8678 COPYNODE_OPS9, /* NAPPEND */
8679 COPYNODE_OPS9, /* NTOOV */
8680 COPYNODE_OPS10, /* NTOFD */
8681 COPYNODE_OPS10, /* NFROMFD */
8682 COPYNODE_OPS11, /* NHERE */
8683 COPYNODE_OPS11, /* NXHERE */
8684 COPYNODE_OPS12, /* NNOT */
8687 #if NODE_CHARPTR != NODE_MBRMASK
8688 #error NODE_CHARPTR != NODE_MBRMASK!!!
8690 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8692 #ifdef COPYNODE_TABLE
8694 copynode(const union node *n)
8697 const unsigned char *p;
8703 new->type = n->type;
8704 funcblock = (char *) funcblock + (int) nodesize[n->type];
8705 p = copynode_ops + (int) copynode_ops_index[n->type];
8707 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8708 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8710 if (!(*p & NODE_MBRMASK)) { /* standard node */
8711 *((union node **)nn) = copynode(*((const union node **) no));
8712 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8713 *((const char **)nn) = nodesavestr(*((const char **)no));
8714 } else if (*p & NODE_NODELIST) { /* nodelist */
8715 *((struct nodelist **)nn)
8716 = copynodelist(*((const struct nodelist **) no));
8717 } else { /* integer */
8718 *((int *) nn) = *((int *) no);
8720 } while (!(*p++ & NODE_NOMORE));
8723 #else /* COPYNODE_TABLE */
8725 copynode(const union node *n)
8732 funcblock = (char *) funcblock + nodesize[n->type];
8739 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8740 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8743 new->ncmd.redirect = copynode(n->ncmd.redirect);
8744 new->ncmd.args = copynode(n->ncmd.args);
8745 new->ncmd.assign = copynode(n->ncmd.assign);
8746 new->ncmd.backgnd = n->ncmd.backgnd;
8749 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8750 new->npipe.backgnd = n->npipe.backgnd;
8755 new->nredir.redirect = copynode(n->nredir.redirect);
8756 new->nredir.n = copynode(n->nredir.n);
8759 new->nif.elsepart = copynode(n->nif.elsepart);
8760 new->nif.ifpart = copynode(n->nif.ifpart);
8761 new->nif.test = copynode(n->nif.test);
8764 new->nfor.var = nodesavestr(n->nfor.var);
8765 new->nfor.body = copynode(n->nfor.body);
8766 new->nfor.args = copynode(n->nfor.args);
8769 new->ncase.cases = copynode(n->ncase.cases);
8770 new->ncase.expr = copynode(n->ncase.expr);
8773 new->nclist.body = copynode(n->nclist.body);
8774 new->nclist.pattern = copynode(n->nclist.pattern);
8775 new->nclist.next = copynode(n->nclist.next);
8779 new->narg.backquote = copynodelist(n->narg.backquote);
8780 new->narg.text = nodesavestr(n->narg.text);
8781 new->narg.next = copynode(n->narg.next);
8788 new->nfile.fname = copynode(n->nfile.fname);
8789 new->nfile.fd = n->nfile.fd;
8790 new->nfile.next = copynode(n->nfile.next);
8794 new->ndup.vname = copynode(n->ndup.vname);
8795 new->ndup.dupfd = n->ndup.dupfd;
8796 new->ndup.fd = n->ndup.fd;
8797 new->ndup.next = copynode(n->ndup.next);
8801 new->nhere.doc = copynode(n->nhere.doc);
8802 new->nhere.fd = n->nhere.fd;
8803 new->nhere.next = copynode(n->nhere.next);
8806 new->nnot.com = copynode(n->nnot.com);
8809 new->type = n->type;
8812 #endif /* COPYNODE_TABLE */
8814 #ifdef CALCSIZE_TABLE
8816 calcsize(const union node *n)
8818 const unsigned char *p;
8822 funcblocksize += (int) nodesize[n->type];
8824 p = copynode_ops + (int) copynode_ops_index[n->type];
8826 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8828 if (!(*p & NODE_MBRMASK)) { /* standard node */
8829 calcsize(*((const union node **) no));
8830 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8831 funcstringsize += strlen(*((const char **)no)) + 1;
8832 } else if (*p & NODE_NODELIST) { /* nodelist */
8833 sizenodelist(*((const struct nodelist **) no));
8834 } /* else integer -- ignore */
8835 } while (!(*p++ & NODE_NOMORE));
8837 #else /* CALCSIZE_TABLE */
8839 calcsize(const union node *n)
8843 funcblocksize += nodesize[n->type];
8850 calcsize(n->nbinary.ch2);
8851 calcsize(n->nbinary.ch1);
8854 calcsize(n->ncmd.redirect);
8855 calcsize(n->ncmd.args);
8856 calcsize(n->ncmd.assign);
8859 sizenodelist(n->npipe.cmdlist);
8864 calcsize(n->nredir.redirect);
8865 calcsize(n->nredir.n);
8868 calcsize(n->nif.elsepart);
8869 calcsize(n->nif.ifpart);
8870 calcsize(n->nif.test);
8873 funcstringsize += strlen(n->nfor.var) + 1;
8874 calcsize(n->nfor.body);
8875 calcsize(n->nfor.args);
8878 calcsize(n->ncase.cases);
8879 calcsize(n->ncase.expr);
8882 calcsize(n->nclist.body);
8883 calcsize(n->nclist.pattern);
8884 calcsize(n->nclist.next);
8888 sizenodelist(n->narg.backquote);
8889 funcstringsize += strlen(n->narg.text) + 1;
8890 calcsize(n->narg.next);
8897 calcsize(n->nfile.fname);
8898 calcsize(n->nfile.next);
8902 calcsize(n->ndup.vname);
8903 calcsize(n->ndup.next);
8907 calcsize(n->nhere.doc);
8908 calcsize(n->nhere.next);
8911 calcsize(n->nnot.com);
8915 #endif /* CALCSIZE_TABLE */
8918 sizenodelist(const struct nodelist *lp)
8921 funcblocksize += ALIGN(sizeof(struct nodelist));
8928 static struct nodelist *
8929 copynodelist(const struct nodelist *lp)
8931 struct nodelist *start;
8932 struct nodelist **lpp;
8937 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8938 (*lpp)->n = copynode(lp->n);
8940 lpp = &(*lpp)->next;
8948 nodesavestr(const char *s)
8951 char *q = funcstring;
8952 char *rtn = funcstring;
8954 while ((*q++ = *p++) != '\0')
8961 static int getopts (char *, char *, char **, int *, int *);
8966 * Process the shell command line arguments.
8970 procargs(argc, argv)
8979 for (i = 0; i < NOPTS; i++)
8982 if (*argptr == NULL && minusc == NULL)
8984 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8988 for (i = 0; i < NOPTS; i++)
8989 if (optent_val(i) == 2)
8992 if (sflag == 0 && minusc == NULL) {
8993 commandname = argv[0];
8995 setinputfile(arg0, 0);
8998 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8999 if (argptr && minusc && *argptr)
9002 shellparam.p = argptr;
9003 shellparam.optind = 1;
9004 shellparam.optoff = -1;
9005 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9007 shellparam.nparam++;
9016 * Process shell options. The global variable argptr contains a pointer
9017 * to the argument list; we advance it past the options.
9021 minus_o(const char *name, int val)
9026 out1str("Current option settings\n");
9027 for (i = 0; i < NOPTS; i++)
9028 printf("%-16s%s\n", optent_name(optlist[i]),
9029 optent_val(i) ? "on" : "off");
9031 for (i = 0; i < NOPTS; i++)
9032 if (equal(name, optent_name(optlist[i]))) {
9033 setoption(optent_letter(optlist[i]), val);
9036 error("Illegal option -o %s", name);
9042 options(int cmdline)
9050 while ((p = *argptr) != NULL) {
9052 if ((c = *p++) == '-') {
9054 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9056 /* "-" means turn off -x and -v */
9059 /* "--" means reset params */
9060 else if (*argptr == NULL)
9063 break; /* "-" or "--" terminates options */
9065 } else if (c == '+') {
9071 while ((c = *p++) != '\0') {
9072 if (c == 'c' && cmdline) {
9074 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9078 if (q == NULL || minusc != NULL)
9079 error("Bad -c option");
9084 } else if (c == 'o') {
9085 minus_o(*argptr, val);
9097 setoption(int flag, int val)
9101 for (i = 0; i < NOPTS; i++)
9102 if (optent_letter(optlist[i]) == flag) {
9103 optent_val(i) = val;
9105 /* #%$ hack for ksh semantics */
9108 else if (flag == 'E')
9113 error("Illegal option -%c", flag);
9120 * Set the shell parameters.
9124 setparam(char **argv)
9130 for (nparam = 0 ; argv[nparam] ; nparam++);
9131 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9133 *ap++ = savestr(*argv++);
9136 freeparam(&shellparam);
9137 shellparam.malloc = 1;
9138 shellparam.nparam = nparam;
9139 shellparam.p = newparam;
9140 shellparam.optind = 1;
9141 shellparam.optoff = -1;
9146 * Free the list of positional parameters.
9150 freeparam(volatile struct shparam *param)
9154 if (param->malloc) {
9155 for (ap = param->p ; *ap ; ap++)
9164 * The shift builtin command.
9168 shiftcmd(argc, argv)
9177 n = number(argv[1]);
9178 if (n > shellparam.nparam)
9179 error("can't shift that many");
9181 shellparam.nparam -= n;
9182 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9183 if (shellparam.malloc)
9187 while ((*ap2++ = *ap1++) != NULL);
9188 shellparam.optind = 1;
9189 shellparam.optoff = -1;
9197 * The set command builtin.
9206 return showvarscmd(argc, argv);
9210 if (*argptr != NULL) {
9219 getoptsreset(const char *value)
9221 shellparam.optind = number(value);
9222 shellparam.optoff = -1;
9225 #ifdef CONFIG_LOCALE_SUPPORT
9226 static void change_lc_all(const char *value)
9228 if(value != 0 && *value != 0)
9229 setlocale(LC_ALL, value);
9232 static void change_lc_ctype(const char *value)
9234 if(value != 0 && *value != 0)
9235 setlocale(LC_CTYPE, value);
9242 * The getopts builtin. Shellparam.optnext points to the next argument
9243 * to be processed. Shellparam.optptr points to the next character to
9244 * be processed in the current argument. If shellparam.optnext is NULL,
9245 * then it's the first time getopts has been called.
9249 getoptscmd(argc, argv)
9256 error("Usage: getopts optstring var [arg]");
9257 else if (argc == 3) {
9258 optbase = shellparam.p;
9259 if (shellparam.optind > shellparam.nparam + 1) {
9260 shellparam.optind = 1;
9261 shellparam.optoff = -1;
9266 if (shellparam.optind > argc - 2) {
9267 shellparam.optind = 1;
9268 shellparam.optoff = -1;
9272 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9273 &shellparam.optoff);
9277 * Safe version of setvar, returns 1 on success 0 on failure.
9281 setvarsafe(name, val, flags)
9282 const char *name, *val;
9285 struct jmploc jmploc;
9286 struct jmploc *volatile savehandler = handler;
9292 if (setjmp(jmploc.loc))
9296 setvar(name, val, flags);
9298 handler = savehandler;
9303 getopts(optstr, optvar, optfirst, myoptind, optoff)
9315 char **optnext = optfirst + *myoptind - 1;
9317 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9318 strlen(*(optnext - 1)) < *optoff)
9321 p = *(optnext - 1) + *optoff;
9322 if (p == NULL || *p == '\0') {
9323 /* Current word is done, advance */
9324 if (optnext == NULL)
9327 if (p == NULL || *p != '-' || *++p == '\0') {
9329 *myoptind = optnext - optfirst + 1;
9335 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9340 for (q = optstr; *q != c; ) {
9342 if (optstr[0] == ':') {
9345 err |= setvarsafe("OPTARG", s, 0);
9348 out2fmt("Illegal option -%c\n", c);
9349 (void) unsetvar("OPTARG");
9359 if (*p == '\0' && (p = *optnext) == NULL) {
9360 if (optstr[0] == ':') {
9363 err |= setvarsafe("OPTARG", s, 0);
9367 out2fmt("No arg for -%c option\n", c);
9368 (void) unsetvar("OPTARG");
9376 setvarsafe("OPTARG", p, 0);
9380 setvarsafe("OPTARG", "", 0);
9381 *myoptind = optnext - optfirst + 1;
9388 *optoff = p ? p - *(optnext - 1) : -1;
9389 snprintf(s, sizeof(s), "%d", *myoptind);
9390 err |= setvarsafe("OPTIND", s, VNOFUNC);
9393 err |= setvarsafe(optvar, s, 0);
9404 * XXX - should get rid of. have all builtins use getopt(3). the
9405 * library getopt must have the BSD extension static variable "optreset"
9406 * otherwise it can't be used within the shell safely.
9408 * Standard option processing (a la getopt) for builtin routines. The
9409 * only argument that is passed to nextopt is the option string; the
9410 * other arguments are unnecessary. It return the character, or '\0' on
9415 nextopt(const char *optstring)
9421 if ((p = optptr) == NULL || *p == '\0') {
9423 if (p == NULL || *p != '-' || *++p == '\0')
9426 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9430 for (q = optstring ; *q != c ; ) {
9432 error("Illegal option -%c", c);
9437 if (*p == '\0' && (p = *argptr++) == NULL)
9438 error("No arg for -%c option", c);
9455 out2fmt(const char *fmt, ...)
9459 vfprintf(stderr, fmt, ap);
9464 * Version of write which resumes after a signal is caught.
9468 xwrite(int fd, const char *buf, int nbytes)
9477 i = write(fd, buf, n);
9483 } else if (i == 0) {
9486 } else if (errno != EINTR) {
9494 * Shell command parser.
9497 #define EOFMARKLEN 79
9502 struct heredoc *next; /* next here document in list */
9503 union node *here; /* redirection node */
9504 char *eofmark; /* string indicating end of input */
9505 int striptabs; /* if set, strip leading tabs */
9508 static struct heredoc *heredoclist; /* list of here documents to read */
9509 static int parsebackquote; /* nonzero if we are inside backquotes */
9510 static int doprompt; /* if set, prompt the user */
9511 static int needprompt; /* true if interactive and at start of line */
9512 static int lasttoken; /* last token read */
9514 static char *wordtext; /* text of last word returned by readtoken */
9516 static struct nodelist *backquotelist;
9517 static union node *redirnode;
9518 static struct heredoc *heredoc;
9519 static int quoteflag; /* set if (part of) last token was quoted */
9520 static int startlinno; /* line # where last token started */
9523 static union node *list (int);
9524 static union node *andor (void);
9525 static union node *pipeline (void);
9526 static union node *command (void);
9527 static union node *simplecmd(union node **rpp, union node *redir);
9528 static void parsefname (void);
9529 static void parseheredoc (void);
9530 static char peektoken (void);
9531 static int readtoken (void);
9532 static int xxreadtoken (void);
9533 static int readtoken1 (int, int, const char *, int);
9534 static int noexpand (char *);
9535 static void synexpect (int) __attribute__((noreturn));
9536 static void synerror (const char *) __attribute__((noreturn));
9537 static void setprompt (int);
9541 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9542 * valid parse tree indicating a blank line.)
9546 parsecmd(int interact)
9551 doprompt = interact;
9571 union node *n1, *n2, *n3;
9575 if (nlflag == 0 && peektoken())
9581 if (tok == TBACKGND) {
9582 if (n2->type == NCMD || n2->type == NPIPE) {
9583 n2->ncmd.backgnd = 1;
9584 } else if (n2->type == NREDIR) {
9585 n2->type = NBACKGND;
9587 n3 = (union node *)stalloc(sizeof (struct nredir));
9588 n3->type = NBACKGND;
9590 n3->nredir.redirect = NULL;
9598 n3 = (union node *)stalloc(sizeof (struct nbinary));
9600 n3->nbinary.ch1 = n1;
9601 n3->nbinary.ch2 = n2;
9625 pungetc(); /* push back EOF on input */
9640 union node *n1, *n2, *n3;
9646 if ((t = readtoken()) == TAND) {
9648 } else if (t == TOR) {
9656 n3 = (union node *)stalloc(sizeof (struct nbinary));
9658 n3->nbinary.ch1 = n1;
9659 n3->nbinary.ch2 = n2;
9668 union node *n1, *n2, *pipenode;
9669 struct nodelist *lp, *prev;
9673 TRACE(("pipeline: entered\n"));
9674 if (readtoken() == TNOT) {
9680 if (readtoken() == TPIPE) {
9681 pipenode = (union node *)stalloc(sizeof (struct npipe));
9682 pipenode->type = NPIPE;
9683 pipenode->npipe.backgnd = 0;
9684 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9685 pipenode->npipe.cmdlist = lp;
9689 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9693 } while (readtoken() == TPIPE);
9699 n2 = (union node *)stalloc(sizeof (struct nnot));
9711 union node *n1, *n2;
9712 union node *ap, **app;
9713 union node *cp, **cpp;
9714 union node *redir, **rpp;
9721 /* Check for redirection which may precede command */
9722 while (readtoken() == TREDIR) {
9723 *rpp = n2 = redirnode;
9724 rpp = &n2->nfile.next;
9729 switch (readtoken()) {
9731 n1 = (union node *)stalloc(sizeof (struct nif));
9733 n1->nif.test = list(0);
9734 if (readtoken() != TTHEN)
9736 n1->nif.ifpart = list(0);
9738 while (readtoken() == TELIF) {
9739 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9740 n2 = n2->nif.elsepart;
9742 n2->nif.test = list(0);
9743 if (readtoken() != TTHEN)
9745 n2->nif.ifpart = list(0);
9747 if (lasttoken == TELSE)
9748 n2->nif.elsepart = list(0);
9750 n2->nif.elsepart = NULL;
9753 if (readtoken() != TFI)
9760 n1 = (union node *)stalloc(sizeof (struct nbinary));
9761 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9762 n1->nbinary.ch1 = list(0);
9763 if ((got=readtoken()) != TDO) {
9764 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9767 n1->nbinary.ch2 = list(0);
9768 if (readtoken() != TDONE)
9774 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9775 synerror("Bad for loop variable");
9776 n1 = (union node *)stalloc(sizeof (struct nfor));
9778 n1->nfor.var = wordtext;
9780 if (readtoken() == TIN) {
9782 while (readtoken() == TWORD) {
9783 n2 = (union node *)stalloc(sizeof (struct narg));
9785 n2->narg.text = wordtext;
9786 n2->narg.backquote = backquotelist;
9788 app = &n2->narg.next;
9792 if (lasttoken != TNL && lasttoken != TSEMI)
9795 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9797 n2 = (union node *)stalloc(sizeof (struct narg));
9799 n2->narg.text = argvars;
9800 n2->narg.backquote = NULL;
9801 n2->narg.next = NULL;
9804 * Newline or semicolon here is optional (but note
9805 * that the original Bourne shell only allowed NL).
9807 if (lasttoken != TNL && lasttoken != TSEMI)
9811 if (readtoken() != TDO)
9813 n1->nfor.body = list(0);
9814 if (readtoken() != TDONE)
9819 n1 = (union node *)stalloc(sizeof (struct ncase));
9821 if (readtoken() != TWORD)
9823 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9825 n2->narg.text = wordtext;
9826 n2->narg.backquote = backquotelist;
9827 n2->narg.next = NULL;
9830 } while (readtoken() == TNL);
9831 if (lasttoken != TIN)
9832 synerror("expecting \"in\"");
9833 cpp = &n1->ncase.cases;
9834 checkkwd = 2, readtoken();
9836 if (lasttoken == TLP)
9838 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9840 app = &cp->nclist.pattern;
9842 *app = ap = (union node *)stalloc(sizeof (struct narg));
9844 ap->narg.text = wordtext;
9845 ap->narg.backquote = backquotelist;
9846 if (checkkwd = 2, readtoken() != TPIPE)
9848 app = &ap->narg.next;
9851 ap->narg.next = NULL;
9852 if (lasttoken != TRP)
9854 cp->nclist.body = list(0);
9857 if ((t = readtoken()) != TESAC) {
9859 synexpect(TENDCASE);
9861 checkkwd = 2, readtoken();
9863 cpp = &cp->nclist.next;
9864 } while(lasttoken != TESAC);
9869 n1 = (union node *)stalloc(sizeof (struct nredir));
9870 n1->type = NSUBSHELL;
9871 n1->nredir.n = list(0);
9872 n1->nredir.redirect = NULL;
9873 if (readtoken() != TRP)
9879 if (readtoken() != TEND)
9883 /* Handle an empty command like other simple commands. */
9892 * An empty command before a ; doesn't make much sense, and
9893 * should certainly be disallowed in the case of `if ;'.
9899 n1 = simplecmd(rpp, redir);
9906 /* Now check for redirection which may follow command */
9907 while (readtoken() == TREDIR) {
9908 *rpp = n2 = redirnode;
9909 rpp = &n2->nfile.next;
9915 if (n1->type != NSUBSHELL) {
9916 n2 = (union node *)stalloc(sizeof (struct nredir));
9921 n1->nredir.redirect = redir;
9929 simplecmd(union node **rpp, union node *redir) {
9930 union node *args, **app;
9931 union node *n = NULL;
9932 union node *vars, **vpp;
9933 union node **orig_rpp;
9940 /* If we don't have any redirections already, then we must reset
9941 rpp to be the address of the local redir variable. */
9944 /* We save the incoming value, because we need this for shell
9945 functions. There can not be a redirect or an argument between
9946 the function name and the open parenthesis. */
9951 switch (readtoken()) {
9954 n = (union node *)stalloc(sizeof (struct narg));
9956 n->narg.text = wordtext;
9957 n->narg.backquote = backquotelist;
9958 if (lasttoken == TWORD) {
9960 app = &n->narg.next;
9963 vpp = &n->narg.next;
9967 *rpp = n = redirnode;
9968 rpp = &n->nfile.next;
9969 parsefname(); /* read name of redirection file */
9973 args && app == &args->narg.next &&
9974 !vars && rpp == orig_rpp
9976 /* We have a function */
9977 if (readtoken() != TRP)
9981 n->narg.next = command();
9994 n = (union node *)stalloc(sizeof (struct ncmd));
9996 n->ncmd.backgnd = 0;
9997 n->ncmd.args = args;
9998 n->ncmd.assign = vars;
9999 n->ncmd.redirect = redir;
10003 static union node *
10007 n = (union node *)stalloc(sizeof (struct narg));
10009 n->narg.next = NULL;
10010 n->narg.text = wordtext;
10011 n->narg.backquote = backquotelist;
10015 static void fixredir(union node *n, const char *text, int err)
10017 TRACE(("Fix redir %s %d\n", text, err));
10019 n->ndup.vname = NULL;
10021 if (is_digit(text[0]) && text[1] == '\0')
10022 n->ndup.dupfd = digit_val(text[0]);
10023 else if (text[0] == '-' && text[1] == '\0')
10024 n->ndup.dupfd = -1;
10028 synerror("Bad fd number");
10030 n->ndup.vname = makename();
10037 union node *n = redirnode;
10039 if (readtoken() != TWORD)
10041 if (n->type == NHERE) {
10042 struct heredoc *here = heredoc;
10046 if (quoteflag == 0)
10048 TRACE(("Here document %d\n", n->type));
10049 if (here->striptabs) {
10050 while (*wordtext == '\t')
10053 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10054 synerror("Illegal eof marker for << redirection");
10055 rmescapes(wordtext);
10056 here->eofmark = wordtext;
10058 if (heredoclist == NULL)
10059 heredoclist = here;
10061 for (p = heredoclist ; p->next ; p = p->next);
10064 } else if (n->type == NTOFD || n->type == NFROMFD) {
10065 fixredir(n, wordtext, 0);
10067 n->nfile.fname = makename();
10073 * Input any here documents.
10078 struct heredoc *here;
10081 while (heredoclist) {
10082 here = heredoclist;
10083 heredoclist = here->next;
10088 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10089 here->eofmark, here->striptabs);
10090 n = (union node *)stalloc(sizeof (struct narg));
10091 n->narg.type = NARG;
10092 n->narg.next = NULL;
10093 n->narg.text = wordtext;
10094 n->narg.backquote = backquotelist;
10095 here->here->nhere.doc = n;
10105 return tokname_array[t][0];
10113 int savecheckalias = checkalias;
10114 int savecheckkwd = checkkwd;
10119 int alreadyseen = tokpushback;
10129 checkalias = savecheckalias;
10136 if (checkkwd == 2) {
10145 * check for keywords
10147 if (t == TWORD && !quoteflag)
10149 const char *const *pp;
10151 if ((pp = findkwd(wordtext))) {
10152 lasttoken = t = pp - tokname_array;
10153 TRACE(("keyword %s recognized\n", tokname(t)));
10164 } else if (checkalias == 2 && isassignment(wordtext)) {
10165 lasttoken = t = TASSIGN;
10167 } else if (checkalias) {
10168 if (!quoteflag && (ap = lookupalias(wordtext, 1)) != NULL) {
10170 pushstring(ap->val, strlen(ap->val), ap);
10172 checkkwd = savecheckkwd;
10181 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10183 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10190 * Read the next input token.
10191 * If the token is a word, we set backquotelist to the list of cmds in
10192 * backquotes. We set quoteflag to true if any part of the word was
10194 * If the token is TREDIR, then we set redirnode to a structure containing
10196 * In all cases, the variable startlinno is set to the number of the line
10197 * on which the token starts.
10199 * [Change comment: here documents and internal procedures]
10200 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10201 * word parsing code into a separate routine. In this case, readtoken
10202 * doesn't need to have any internal procedures, but parseword does.
10203 * We could also make parseoperator in essence the main routine, and
10204 * have parseword (readtoken1?) handle both words and redirection.]
10207 #define NEW_xxreadtoken
10208 #ifdef NEW_xxreadtoken
10210 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10211 static const char xxreadtoken_tokens[] = {
10212 TNL, TLP, TRP, /* only single occurrence allowed */
10213 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10214 TEOF, /* corresponds to trailing nul */
10215 TAND, TOR, TENDCASE, /* if double occurrence */
10218 #define xxreadtoken_doubles \
10219 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10220 #define xxreadtoken_singles \
10221 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10235 startlinno = plinno;
10236 for (;;) { /* until token or start of word found */
10239 if ((c!=' ') && (c!='\t')
10245 while ((c = pgetc()) != '\n' && c != PEOF);
10247 } else if (c=='\\') {
10248 if (pgetc() != '\n') {
10252 startlinno = ++plinno;
10253 setprompt(doprompt ? 2 : 0);
10256 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10261 needprompt = doprompt;
10264 p = strchr(xxreadtoken_chars, c);
10267 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10270 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10271 if (pgetc() == *p) { /* double occurrence? */
10272 p += xxreadtoken_doubles + 1;
10279 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10287 #define RETURN(token) return lasttoken = token
10301 startlinno = plinno;
10302 for (;;) { /* until token or start of word found */
10305 case ' ': case '\t':
10311 while ((c = pgetc()) != '\n' && c != PEOF);
10315 if (pgetc() == '\n') {
10316 startlinno = ++plinno;
10327 needprompt = doprompt;
10332 if (pgetc() == '&')
10337 if (pgetc() == '|')
10342 if (pgetc() == ';')
10355 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10361 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10362 * is not NULL, read a here document. In the latter case, eofmark is the
10363 * word which marks the end of the document and striptabs is true if
10364 * leading tabs should be stripped from the document. The argument firstc
10365 * is the first character of the input token or document.
10367 * Because C does not have internal subroutines, I have simulated them
10368 * using goto's to implement the subroutine linkage. The following macros
10369 * will run code that appears at the end of readtoken1.
10372 #define CHECKEND() {goto checkend; checkend_return:;}
10373 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10374 #define PARSESUB() {goto parsesub; parsesub_return:;}
10375 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10376 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10377 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10380 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10385 char line[EOFMARKLEN + 1];
10386 struct nodelist *bqlist;
10389 int varnest; /* levels of variables expansion */
10390 int arinest; /* levels of arithmetic expansion */
10391 int parenlevel; /* levels of parens in arithmetic */
10392 int dqvarnest; /* levels of variables expansion within double quotes */
10394 int prevsyntax; /* syntax before arithmetic */
10396 /* Avoid longjmp clobbering */
10402 (void) &parenlevel;
10405 (void) &prevsyntax;
10409 startlinno = plinno;
10411 if (syntax == DQSYNTAX)
10420 STARTSTACKSTR(out);
10421 loop: { /* for each line, until end of word */
10422 CHECKEND(); /* set c to PEOF if at end of here document */
10423 for (;;) { /* until end of line or end of word */
10424 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10425 switch(SIT(c,syntax)) {
10426 case CNL: /* '\n' */
10427 if (syntax == BASESYNTAX)
10428 goto endword; /* exit outer loop */
10436 goto loop; /* continue outer loop */
10441 if ((eofmark == NULL || dblquote) &&
10443 USTPUTC(CTLESC, out);
10446 case CBACK: /* backslash */
10449 USTPUTC('\\', out);
10451 } else if (c == '\n') {
10457 if (dblquote && c != '\\' && c != '`' && c != '$'
10458 && (c != '"' || eofmark != NULL))
10459 USTPUTC('\\', out);
10460 if (SIT(c,SQSYNTAX) == CCTL)
10461 USTPUTC(CTLESC, out);
10462 else if (eofmark == NULL)
10463 USTPUTC(CTLQUOTEMARK, out);
10469 if (eofmark == NULL)
10470 USTPUTC(CTLQUOTEMARK, out);
10474 if (eofmark == NULL)
10475 USTPUTC(CTLQUOTEMARK, out);
10480 if (eofmark != NULL && arinest == 0 &&
10485 syntax = ARISYNTAX;
10487 } else if (eofmark == NULL &&
10489 syntax = BASESYNTAX;
10495 case CVAR: /* '$' */
10496 PARSESUB(); /* parse substitution */
10498 case CENDVAR: /* '}' */
10501 if (dqvarnest > 0) {
10504 USTPUTC(CTLENDVAR, out);
10509 #ifdef ASH_MATH_SUPPORT
10510 case CLP: /* '(' in arithmetic */
10514 case CRP: /* ')' in arithmetic */
10515 if (parenlevel > 0) {
10519 if (pgetc() == ')') {
10520 if (--arinest == 0) {
10521 USTPUTC(CTLENDARI, out);
10522 syntax = prevsyntax;
10523 if (syntax == DQSYNTAX)
10531 * unbalanced parens
10532 * (don't 2nd guess - no error)
10540 case CBQUOTE: /* '`' */
10544 goto endword; /* exit outer loop */
10549 goto endword; /* exit outer loop */
10560 if (syntax == ARISYNTAX)
10561 synerror("Missing '))'");
10562 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10563 synerror("Unterminated quoted string");
10564 if (varnest != 0) {
10565 startlinno = plinno;
10566 synerror("Missing '}'");
10568 USTPUTC('\0', out);
10569 len = out - stackblock();
10570 out = stackblock();
10571 if (eofmark == NULL) {
10572 if ((c == '>' || c == '<')
10575 && (*out == '\0' || is_digit(*out))) {
10577 return lasttoken = TREDIR;
10582 quoteflag = quotef;
10583 backquotelist = bqlist;
10584 grabstackblock(len);
10586 return lasttoken = TWORD;
10587 /* end of readtoken routine */
10592 * Check to see whether we are at the end of the here document. When this
10593 * is called, c is set to the first character of the next input line. If
10594 * we are at the end of the here document, this routine sets the c to PEOF.
10605 while (c == '\t') {
10609 if (c == *eofmark) {
10610 if (pfgets(line, sizeof line) != NULL) {
10614 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10615 if (*p == '\n' && *q == '\0') {
10618 needprompt = doprompt;
10620 pushstring(line, strlen(line), NULL);
10625 goto checkend_return;
10630 * Parse a redirection operator. The variable "out" points to a string
10631 * specifying the fd to be redirected. The variable "c" contains the
10632 * first character of the redirection operator.
10639 np = (union node *)stalloc(sizeof (struct nfile));
10644 np->type = NAPPEND;
10653 } else { /* c == '<' */
10655 switch (c = pgetc()) {
10657 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10658 np = (union node *)stalloc(sizeof (struct nhere));
10662 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10663 heredoc->here = np;
10664 if ((c = pgetc()) == '-') {
10665 heredoc->striptabs = 1;
10667 heredoc->striptabs = 0;
10673 np->type = NFROMFD;
10677 np->type = NFROMTO;
10687 np->nfile.fd = digit_val(fd);
10689 goto parseredir_return;
10694 * Parse a substitution. At this point, we have read the dollar sign
10695 * and nothing else.
10703 static const char types[] = "}-+?=";
10708 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10712 } else if (c == '(') { /* $(command) or $((arith)) */
10713 if (pgetc() == '(') {
10720 USTPUTC(CTLVAR, out);
10721 typeloc = out - stackblock();
10722 USTPUTC(VSNORMAL, out);
10723 subtype = VSNORMAL;
10727 if ((c = pgetc()) == '}')
10730 subtype = VSLENGTH;
10735 if (c > PEOA && is_name(c)) {
10739 } while (c > PEOA && is_in_name(c));
10740 } else if (is_digit(c)) {
10744 } while (is_digit(c));
10746 else if (is_special(c)) {
10751 badsub: synerror("Bad substitution");
10755 if (subtype == 0) {
10762 p = strchr(types, c);
10765 subtype = p - types + VSNORMAL;
10771 subtype = c == '#' ? VSTRIMLEFT :
10784 if (dblquote || arinest)
10786 *(stackblock() + typeloc) = subtype | flags;
10787 if (subtype != VSNORMAL) {
10794 goto parsesub_return;
10799 * Called to parse command substitutions. Newstyle is set if the command
10800 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10801 * list of commands (passed by reference), and savelen is the number of
10802 * characters on the top of the stack which must be preserved.
10806 struct nodelist **nlpp;
10809 char *volatile str;
10810 struct jmploc jmploc;
10811 struct jmploc *volatile savehandler;
10815 (void) &saveprompt;
10818 savepbq = parsebackquote;
10819 if (setjmp(jmploc.loc)) {
10822 parsebackquote = 0;
10823 handler = savehandler;
10824 longjmp(handler->loc, 1);
10828 savelen = out - stackblock();
10830 str = ckmalloc(savelen);
10831 memcpy(str, stackblock(), savelen);
10833 savehandler = handler;
10837 /* We must read until the closing backquote, giving special
10838 treatment to some slashes, and then push the string and
10839 reread it as input, interpreting it normally. */
10846 STARTSTACKSTR(pout);
10852 switch (pc = pgetc()) {
10857 if ((pc = pgetc()) == '\n') {
10864 * If eating a newline, avoid putting
10865 * the newline into the new character
10866 * stream (via the STPUTC after the
10871 if (pc != '\\' && pc != '`' && pc != '$'
10872 && (!dblquote || pc != '"'))
10873 STPUTC('\\', pout);
10883 startlinno = plinno;
10884 synerror("EOF in backquote substitution");
10888 needprompt = doprompt;
10897 STPUTC('\0', pout);
10898 psavelen = pout - stackblock();
10899 if (psavelen > 0) {
10900 pstr = grabstackstr(pout);
10901 setinputstring(pstr);
10906 nlpp = &(*nlpp)->next;
10907 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10908 (*nlpp)->next = NULL;
10909 parsebackquote = oldstyle;
10912 saveprompt = doprompt;
10919 doprompt = saveprompt;
10921 if (readtoken() != TRP)
10928 * Start reading from old file again, ignoring any pushed back
10929 * tokens left from the backquote parsing
10934 while (stackblocksize() <= savelen)
10936 STARTSTACKSTR(out);
10938 memcpy(out, str, savelen);
10939 STADJUST(savelen, out);
10945 parsebackquote = savepbq;
10946 handler = savehandler;
10947 if (arinest || dblquote)
10948 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10950 USTPUTC(CTLBACKQ, out);
10952 goto parsebackq_oldreturn;
10954 goto parsebackq_newreturn;
10958 * Parse an arithmetic expansion (indicate start of one and set state)
10962 if (++arinest == 1) {
10963 prevsyntax = syntax;
10964 syntax = ARISYNTAX;
10965 USTPUTC(CTLARI, out);
10972 * we collapse embedded arithmetic expansion to
10973 * parenthesis, which should be equivalent
10977 goto parsearith_return;
10980 } /* end of readtoken */
10984 * Returns true if the text contains nothing to expand (no dollar signs
10996 while ((c = *p++) != '\0') {
10997 if (c == CTLQUOTEMARK)
11001 else if (SIT(c,BASESYNTAX) == CCTL)
11009 * Return true if the argument is a legal variable name (a letter or
11010 * underscore followed by zero or more letters, underscores, and digits).
11014 goodname(const char *name)
11022 if (! is_in_name(*p))
11030 * Called when an unexpected token is read during the parse. The argument
11031 * is the token that is expected, or -1 if more than one type of token can
11032 * occur at this point.
11042 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11044 sprintf(msg+l, " (expecting %s)", tokname(token));
11051 synerror(const char *msg)
11054 out2fmt("%s: %d: ", commandname, startlinno);
11055 out2fmt("Syntax error: %s\n", msg);
11056 error((char *)NULL);
11062 * called by editline -- any expansions to the prompt
11063 * should be added here.
11066 setprompt(int whichprompt)
11069 switch (whichprompt) {
11084 * Code for dealing with input/output redirection.
11087 #define EMPTY -2 /* marks an unused slot in redirtab */
11089 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11091 # define PIPESIZE PIPE_BUF
11096 * Open a file in noclobber mode.
11097 * The code was copied from bash.
11100 noclobberopen(const char *fname)
11103 struct stat finfo, finfo2;
11106 * If the file exists and is a regular file, return an error
11109 r = stat(fname, &finfo);
11110 if (r == 0 && S_ISREG(finfo.st_mode)) {
11116 * If the file was not present (r != 0), make sure we open it
11117 * exclusively so that if it is created before we open it, our open
11118 * will fail. Make sure that we do not truncate an existing file.
11119 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11120 * file was not a regular file, we leave O_EXCL off.
11123 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11124 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11126 /* If the open failed, return the file descriptor right away. */
11131 * OK, the open succeeded, but the file may have been changed from a
11132 * non-regular file to a regular file between the stat and the open.
11133 * We are assuming that the O_EXCL open handles the case where FILENAME
11134 * did not exist and is symlinked to an existing file between the stat
11139 * If we can open it and fstat the file descriptor, and neither check
11140 * revealed that it was a regular file, and the file has not been
11141 * replaced, return the file descriptor.
11143 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11144 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11147 /* The file has been replaced. badness. */
11154 * Handle here documents. Normally we fork off a process to write the
11155 * data to a pipe. If the document is short, we can stuff the data in
11156 * the pipe without forking.
11160 openhere(const union node *redir)
11166 error("Pipe call failed");
11167 if (redir->type == NHERE) {
11168 len = strlen(redir->nhere.doc->narg.text);
11169 if (len <= PIPESIZE) {
11170 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11174 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11176 signal(SIGINT, SIG_IGN);
11177 signal(SIGQUIT, SIG_IGN);
11178 signal(SIGHUP, SIG_IGN);
11180 signal(SIGTSTP, SIG_IGN);
11182 signal(SIGPIPE, SIG_DFL);
11183 if (redir->type == NHERE)
11184 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11186 expandhere(redir->nhere.doc, pip[1]);
11196 openredirect(const union node *redir)
11201 switch (redir->nfile.type) {
11203 fname = redir->nfile.expfname;
11204 if ((f = open(fname, O_RDONLY)) < 0)
11208 fname = redir->nfile.expfname;
11209 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11213 /* Take care of noclobber mode. */
11215 fname = redir->nfile.expfname;
11216 if ((f = noclobberopen(fname)) < 0)
11221 fname = redir->nfile.expfname;
11223 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11226 if ((f = creat(fname, 0666)) < 0)
11231 fname = redir->nfile.expfname;
11233 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11236 if ((f = open(fname, O_WRONLY)) < 0
11237 && (f = creat(fname, 0666)) < 0)
11239 lseek(f, (off_t)0, 2);
11246 /* Fall through to eliminate warning. */
11253 f = openhere(redir);
11259 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11261 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11266 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11267 * old file descriptors are stashed away so that the redirection can be
11268 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11269 * standard output, and the standard error if it becomes a duplicate of
11274 redirect(union node *redir, int flags)
11277 struct redirtab *sv = NULL;
11282 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11284 if (flags & REDIR_PUSH) {
11285 sv = ckmalloc(sizeof (struct redirtab));
11286 for (i = 0 ; i < 10 ; i++)
11287 sv->renamed[i] = EMPTY;
11288 sv->next = redirlist;
11291 for (n = redir ; n ; n = n->nfile.next) {
11294 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11295 n->ndup.dupfd == fd)
11296 continue; /* redirect from/to same file descriptor */
11299 newfd = openredirect(n);
11300 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11303 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11307 dupredirect(n, newfd, fd1dup);
11317 error("%d: %m", fd);
11323 if (flags & REDIR_PUSH) {
11324 sv->renamed[fd] = i;
11327 } else if (fd != newfd) {
11333 dupredirect(n, newfd, fd1dup);
11340 dupredirect(const union node *redir, int f, int fd1dup)
11342 int fd = redir->nfile.fd;
11346 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11347 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11348 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11349 dup_as_newfd(redir->ndup.dupfd, fd);
11355 dup_as_newfd(f, fd);
11364 * Undo the effects of the last redirection.
11370 struct redirtab *rp = redirlist;
11374 for (i = 0 ; i < 10 ; i++) {
11375 if (rp->renamed[i] != EMPTY) {
11379 if (rp->renamed[i] >= 0) {
11380 dup_as_newfd(rp->renamed[i], i);
11381 close(rp->renamed[i]);
11385 redirlist = rp->next;
11391 * Discard all saved file descriptors.
11396 struct redirtab *rp;
11399 for (rp = redirlist ; rp ; rp = rp->next) {
11400 for (i = 0 ; i < 10 ; i++) {
11401 if (rp->renamed[i] >= 0) {
11402 close(rp->renamed[i]);
11404 rp->renamed[i] = EMPTY;
11411 * Copy a file descriptor to be >= to. Returns -1
11412 * if the source file descriptor is closed, EMPTY if there are no unused
11413 * file descriptors left.
11417 dup_as_newfd(from, to)
11423 newfd = fcntl(from, F_DUPFD, to);
11425 if (errno == EMFILE)
11428 error("%d: %m", from);
11434 static void shtree (union node *, int, char *, FILE*);
11435 static void shcmd (union node *, FILE *);
11436 static void sharg (union node *, FILE *);
11437 static void indent (int, char *, FILE *);
11438 static void trstring (char *);
11445 trputs("showtree called\n");
11446 shtree(n, 1, NULL, stdout);
11451 shtree(n, ind, pfx, fp)
11457 struct nodelist *lp;
11463 indent(ind, pfx, fp);
11474 shtree(n->nbinary.ch1, ind, NULL, fp);
11477 shtree(n->nbinary.ch2, ind, NULL, fp);
11485 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11490 if (n->npipe.backgnd)
11496 fprintf(fp, "<node type %d>", n->type);
11516 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11522 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11528 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11529 s = redir_strings[np->nfile.type - NTO];
11535 switch (np->nfile.type) {
11536 case NTO: s = ">"; dftfd = 1; break;
11537 case NAPPEND: s = ">>"; dftfd = 1; break;
11538 case NTOFD: s = ">&"; dftfd = 1; break;
11539 case NTOOV: s = ">|"; dftfd = 1; break;
11540 case NFROM: s = "<"; dftfd = 0; break;
11541 case NFROMFD: s = "<&"; dftfd = 0; break;
11542 case NFROMTO: s = "<>"; dftfd = 0; break;
11543 default: s = "*error*"; dftfd = 0; break;
11546 if (np->nfile.fd != dftfd)
11547 fprintf(fp, "%d", np->nfile.fd);
11549 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11550 fprintf(fp, "%d", np->ndup.dupfd);
11552 sharg(np->nfile.fname, fp);
11566 struct nodelist *bqlist;
11569 if (arg->type != NARG) {
11570 printf("<node type %d>\n", arg->type);
11574 bqlist = arg->narg.backquote;
11575 for (p = arg->narg.text ; *p ; p++) {
11584 if (subtype == VSLENGTH)
11590 if (subtype & VSNUL)
11593 switch (subtype & VSTYPE) {
11612 case VSTRIMLEFTMAX:
11619 case VSTRIMRIGHTMAX:
11626 printf("<subtype %d>", subtype);
11633 case CTLBACKQ|CTLQUOTE:
11636 shtree(bqlist->n, -1, NULL, fp);
11648 indent(amount, pfx, fp)
11655 for (i = 0 ; i < amount ; i++) {
11656 if (pfx && i == amount - 1)
11674 static int debug = 1;
11676 static int debug = 0;
11684 if (tracefile == NULL)
11686 putc(c, tracefile);
11692 trace(const char *fmt, ...)
11696 if (tracefile != NULL) {
11697 (void) vfprintf(tracefile, fmt, va);
11698 if (strchr(fmt, '\n'))
11699 (void) fflush(tracefile);
11709 if (tracefile == NULL)
11711 fputs(s, tracefile);
11712 if (strchr(s, '\n'))
11724 if (tracefile == NULL)
11726 putc('"', tracefile);
11727 for (p = s ; *p ; p++) {
11729 case '\n': c = 'n'; goto backslash;
11730 case '\t': c = 't'; goto backslash;
11731 case '\r': c = 'r'; goto backslash;
11732 case '"': c = '"'; goto backslash;
11733 case '\\': c = '\\'; goto backslash;
11734 case CTLESC: c = 'e'; goto backslash;
11735 case CTLVAR: c = 'v'; goto backslash;
11736 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11737 case CTLBACKQ: c = 'q'; goto backslash;
11738 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11739 backslash: putc('\\', tracefile);
11740 putc(c, tracefile);
11743 if (*p >= ' ' && *p <= '~')
11744 putc(*p, tracefile);
11746 putc('\\', tracefile);
11747 putc(*p >> 6 & 03, tracefile);
11748 putc(*p >> 3 & 07, tracefile);
11749 putc(*p & 07, tracefile);
11754 putc('"', tracefile);
11762 if (tracefile == NULL)
11767 putc(' ', tracefile);
11769 putc('\n', tracefile);
11784 #ifdef not_this_way
11787 if ((p = getenv("HOME")) == NULL) {
11788 if (geteuid() == 0)
11794 strcat(s, "/trace");
11797 strcpy(s, "./trace");
11798 #endif /* not_this_way */
11799 if ((tracefile = fopen(s, "a")) == NULL) {
11800 fprintf(stderr, "Can't open %s\n", s);
11804 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11805 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11807 fputs("\nTracing started.\n", tracefile);
11814 * The trap builtin.
11818 trapcmd(argc, argv)
11827 for (signo = 0 ; signo < NSIG ; signo++) {
11828 if (trap[signo] != NULL) {
11832 p = single_quote(trap[signo]);
11833 sn = sys_siglist[signo];
11835 sn = u_signal_names(0, &signo, 0);
11838 printf("trap -- %s %s\n", p, sn);
11850 if ((signo = decode_signal(*ap, 0)) < 0)
11851 error("%s: bad trap", *ap);
11854 if (action[0] == '-' && action[1] == '\0')
11857 action = savestr(action);
11860 ckfree(trap[signo]);
11861 trap[signo] = action;
11876 * Set the signal handler for the specified signal. The routine figures
11877 * out what it should be set to.
11881 setsignal(int signo)
11885 struct sigaction act;
11887 if ((t = trap[signo]) == NULL)
11889 else if (*t != '\0')
11893 if (rootshell && action == S_DFL) {
11896 if (iflag || minusc || sflag == 0)
11922 t = &sigmode[signo - 1];
11925 * current setting unknown
11927 if (sigaction(signo, 0, &act) == -1) {
11929 * Pretend it worked; maybe we should give a warning
11930 * here, but other shells don't. We don't alter
11931 * sigmode, so that we retry every time.
11935 if (act.sa_handler == SIG_IGN) {
11936 if (mflag && (signo == SIGTSTP ||
11937 signo == SIGTTIN || signo == SIGTTOU)) {
11938 *t = S_IGN; /* don't hard ignore these */
11942 *t = S_RESET; /* force to be set */
11945 if (*t == S_HARD_IGN || *t == action)
11947 act.sa_handler = ((action == S_CATCH) ? onsig
11948 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11951 sigemptyset(&act.sa_mask);
11952 sigaction(signo, &act, 0);
11963 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11964 signal(signo, SIG_IGN);
11966 sigmode[signo - 1] = S_HARD_IGN;
11977 if (signo == SIGINT && trap[SIGINT] == NULL) {
11981 gotsig[signo - 1] = 1;
11987 * Called to execute a trap. Perhaps we should avoid entering new trap
11988 * handlers while we are executing a trap handler.
11998 for (i = 1 ; ; i++) {
12005 savestatus=exitstatus;
12006 evalstring(trap[i], 0);
12007 exitstatus=savestatus;
12014 * Called to exit the shell.
12018 exitshell(int status)
12020 struct jmploc loc1, loc2;
12023 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12024 if (setjmp(loc1.loc)) {
12027 if (setjmp(loc2.loc)) {
12031 if ((p = trap[0]) != NULL && *p != '\0') {
12035 l1: handler = &loc2; /* probably unnecessary */
12044 static int decode_signal(const char *string, int minsig)
12047 const char *name = u_signal_names(string, &signo, minsig);
12049 return name ? signo : -1;
12052 static struct var **hashvar (const char *);
12053 static void showvars (const char *, int, int);
12054 static struct var **findvar (struct var **, const char *);
12057 * Initialize the varable symbol tables and import the environment
12061 * This routine initializes the builtin variables. It is called when the
12062 * shell is initialized and again when a shell procedure is spawned.
12067 const struct varinit *ip;
12071 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12072 if ((vp->flags & VEXPORT) == 0) {
12073 vpp = hashvar(ip->text);
12076 vp->text = strdup(ip->text);
12077 vp->flags = ip->flags;
12078 vp->func = ip->func;
12082 * PS1 depends on uid
12084 if ((vps1.flags & VEXPORT) == 0) {
12085 vpp = hashvar("PS1=");
12088 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12089 vps1.flags = VSTRFIXED|VTEXTFIXED;
12094 * Set the value of a variable. The flags argument is ored with the
12095 * flags of the variable. If val is NULL, the variable is unset.
12099 setvar(name, val, flags)
12100 const char *name, *val;
12116 if (! is_in_name(*p)) {
12117 if (*p == '\0' || *p == '=')
12123 namelen = p - name;
12125 error("%.*s: bad variable name", namelen, name);
12126 len = namelen + 2; /* 2 is space for '=' and '\0' */
12130 len += vallen = strlen(val);
12133 nameeq = ckmalloc(len);
12134 memcpy(nameeq, name, namelen);
12135 nameeq[namelen] = '=';
12137 memcpy(nameeq + namelen + 1, val, vallen + 1);
12139 nameeq[namelen + 1] = '\0';
12141 setvareq(nameeq, flags);
12148 * Same as setvar except that the variable and value are passed in
12149 * the first argument as name=value. Since the first argument will
12150 * be actually stored in the table, it should not be a string that
12159 struct var *vp, **vpp;
12162 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12163 if ((vp = *findvar(vpp, s))) {
12164 if (vp->flags & VREADONLY) {
12165 size_t len = strchr(s, '=') - s;
12166 error("%.*s: is read only", len, s);
12170 if (vp->func && (flags & VNOFUNC) == 0)
12171 (*vp->func)(strchr(s, '=') + 1);
12173 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12176 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12177 vp->flags |= flags;
12181 * We could roll this to a function, to handle it as
12182 * a regular variable function callback, but why bother?
12184 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12190 vp = ckmalloc(sizeof (*vp));
12201 * Process a linked list of variable assignments.
12206 struct strlist *mylist;
12208 struct strlist *lp;
12211 for (lp = mylist ; lp ; lp = lp->next) {
12212 setvareq(savestr(lp->text), 0);
12220 * Find the value of a variable. Returns NULL if not set.
12223 static const char *
12229 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12230 return strchr(v->text, '=') + 1;
12238 * Search the environment of a builtin command.
12241 static const char *
12242 bltinlookup(const char *name)
12244 const struct strlist *sp;
12246 for (sp = cmdenviron ; sp ; sp = sp->next) {
12247 if (varequal(sp->text, name))
12248 return strchr(sp->text, '=') + 1;
12250 return lookupvar(name);
12256 * Generate a list of exported variables. This routine is used to construct
12257 * the third argument to execve when executing a program.
12269 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12270 for (vp = *vpp ; vp ; vp = vp->next)
12271 if (vp->flags & VEXPORT)
12274 ep = env = stalloc((nenv + 1) * sizeof *env);
12275 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12276 for (vp = *vpp ; vp ; vp = vp->next)
12277 if (vp->flags & VEXPORT)
12286 * Called when a shell procedure is invoked to clear out nonexported
12287 * variables. It is also necessary to reallocate variables of with
12288 * VSTACK set since these are currently allocated on the stack.
12294 struct var *vp, **prev;
12296 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12297 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12298 if ((vp->flags & VEXPORT) == 0) {
12300 if ((vp->flags & VTEXTFIXED) == 0)
12302 if ((vp->flags & VSTRFIXED) == 0)
12305 if (vp->flags & VSTACK) {
12306 vp->text = savestr(vp->text);
12307 vp->flags &=~ VSTACK;
12319 * Command to list all variables which are set. Currently this command
12320 * is invoked from the set command when the set command is called without
12325 showvarscmd(argc, argv)
12329 showvars(nullstr, VUNSET, VUNSET);
12336 * The export and readonly commands.
12340 exportcmd(argc, argv)
12347 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12350 listsetvar(cmdenviron);
12351 pflag = (nextopt("p") == 'p');
12352 if (argc > 1 && !pflag) {
12353 while ((name = *argptr++) != NULL) {
12354 if ((p = strchr(name, '=')) != NULL) {
12357 if ((vp = *findvar(hashvar(name), name))) {
12362 setvar(name, p, flag);
12366 showvars(argv[0], flag, 0);
12373 * The "local" command.
12376 /* funcnest nonzero if we are currently evaluating a function */
12379 localcmd(argc, argv)
12386 error("Not in a function");
12387 while ((name = *argptr++) != NULL) {
12395 * Make a variable a local variable. When a variable is made local, it's
12396 * value and flags are saved in a localvar structure. The saved values
12397 * will be restored when the shell function returns. We handle the name
12398 * "-" as a special case.
12405 struct localvar *lvp;
12410 lvp = ckmalloc(sizeof (struct localvar));
12411 if (name[0] == '-' && name[1] == '\0') {
12413 p = ckmalloc(sizeof optet_vals);
12414 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12417 vpp = hashvar(name);
12418 vp = *findvar(vpp, name);
12420 if (strchr(name, '='))
12421 setvareq(savestr(name), VSTRFIXED);
12423 setvar(name, NULL, VSTRFIXED);
12424 vp = *vpp; /* the new variable */
12426 lvp->flags = VUNSET;
12428 lvp->text = vp->text;
12429 lvp->flags = vp->flags;
12430 vp->flags |= VSTRFIXED|VTEXTFIXED;
12431 if (strchr(name, '='))
12432 setvareq(savestr(name), 0);
12436 lvp->next = localvars;
12443 * Called after a function returns.
12448 struct localvar *lvp;
12451 while ((lvp = localvars) != NULL) {
12452 localvars = lvp->next;
12454 if (vp == NULL) { /* $- saved */
12455 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12457 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12458 (void)unsetvar(vp->text);
12460 if ((vp->flags & VTEXTFIXED) == 0)
12462 vp->flags = lvp->flags;
12463 vp->text = lvp->text;
12471 setvarcmd(argc, argv)
12476 return unsetcmd(argc, argv);
12477 else if (argc == 3)
12478 setvar(argv[1], argv[2], 0);
12480 error("List assignment not implemented");
12486 * The unset builtin command. We unset the function before we unset the
12487 * variable to allow a function to be unset when there is a readonly variable
12488 * with the same name.
12492 unsetcmd(argc, argv)
12502 while ((i = nextopt("vf")) != '\0') {
12508 if (flg_func == 0 && flg_var == 0)
12511 for (ap = argptr; *ap ; ap++) {
12515 ret |= unsetvar(*ap);
12522 * Unset the specified variable.
12526 unsetvar(const char *s)
12531 vpp = findvar(hashvar(s), s);
12534 if (vp->flags & VREADONLY)
12537 if (*(strchr(vp->text, '=') + 1) != '\0')
12538 setvar(s, nullstr, 0);
12539 vp->flags &= ~VEXPORT;
12540 vp->flags |= VUNSET;
12541 if ((vp->flags & VSTRFIXED) == 0) {
12542 if ((vp->flags & VTEXTFIXED) == 0)
12557 * Find the appropriate entry in the hash table from the name.
12560 static struct var **
12561 hashvar(const char *p)
12563 unsigned int hashval;
12565 hashval = ((unsigned char) *p) << 4;
12566 while (*p && *p != '=')
12567 hashval += (unsigned char) *p++;
12568 return &vartab[hashval % VTABSIZE];
12574 * Returns true if the two strings specify the same varable. The first
12575 * variable name is terminated by '='; the second may be terminated by
12576 * either '=' or '\0'.
12580 varequal(const char *p, const char *q)
12582 while (*p == *q++) {
12586 if (*p == '=' && *(q - 1) == '\0')
12592 showvars(const char *myprefix, int mask, int xor)
12596 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12598 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12599 for (vp = *vpp ; vp ; vp = vp->next) {
12600 if ((vp->flags & mask) ^ xor) {
12604 p = strchr(vp->text, '=') + 1;
12605 len = p - vp->text;
12606 p = single_quote(p);
12608 printf("%s%s%.*s%s\n", myprefix, sep, len,
12616 static struct var **
12617 findvar(struct var **vpp, const char *name)
12619 for (; *vpp; vpp = &(*vpp)->next) {
12620 if (varequal((*vpp)->text, name)) {
12628 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12629 * This file contains code for the times builtin.
12630 * $Id: ash.c,v 1.31 2001/10/24 17:19:35 andersen Exp $
12632 static int timescmd (int argc, char **argv)
12635 long int clk_tck = sysconf(_SC_CLK_TCK);
12638 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12639 (int) (buf.tms_utime / clk_tck / 60),
12640 ((double) buf.tms_utime) / clk_tck,
12641 (int) (buf.tms_stime / clk_tck / 60),
12642 ((double) buf.tms_stime) / clk_tck,
12643 (int) (buf.tms_cutime / clk_tck / 60),
12644 ((double) buf.tms_cutime) / clk_tck,
12645 (int) (buf.tms_cstime / clk_tck / 60),
12646 ((double) buf.tms_cstime) / clk_tck);
12650 #ifdef ASH_MATH_SUPPORT
12651 /* The let builtin. */
12652 int letcmd(int argc, char **argv)
12657 char *tmp, *expression, p[13];
12658 expression = strchr(argv[1], '=');
12660 /* Cannot use 'error()' here, or the return code
12661 * will be incorrect */
12662 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12665 *expression = '\0';
12666 tmp = ++expression;
12667 result = arith(tmp, &errcode);
12669 /* Cannot use 'error()' here, or the return code
12670 * will be incorrect */
12671 out2fmt("sh: let: ");
12673 out2fmt("divide by zero");
12675 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12678 snprintf(p, 12, "%ld", result);
12679 setvar(argv[1], savestr(p), 0);
12680 } else if (argc >= 3)
12681 synerror("invalid operand");
12689 * Copyright (c) 1989, 1991, 1993, 1994
12690 * The Regents of the University of California. All rights reserved.
12692 * This code is derived from software contributed to Berkeley by
12693 * Kenneth Almquist.
12695 * Redistribution and use in source and binary forms, with or without
12696 * modification, are permitted provided that the following conditions
12698 * 1. Redistributions of source code must retain the above copyright
12699 * notice, this list of conditions and the following disclaimer.
12700 * 2. Redistributions in binary form must reproduce the above copyright
12701 * notice, this list of conditions and the following disclaimer in the
12702 * documentation and/or other materials provided with the distribution.
12704 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12705 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12707 * 4. Neither the name of the University nor the names of its contributors
12708 * may be used to endorse or promote products derived from this software
12709 * without specific prior written permission.
12711 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12712 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12713 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12714 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12715 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12716 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12717 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12718 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12719 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12720 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF