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. */
70 /* Check for new mail on interactive shells? */
73 /* Optimize size vs speed as size */
74 #define ASH_OPTIMIZE_FOR_SIZE
76 /* Enable this to compile in extra debugging noise. When debugging is
77 * on, debugging info will be written to $HOME/trace and a quit signal
78 * will generate a core dump. */
81 /* These are here to work with glibc -- Don't change these... */
100 #include <sysexits.h>
102 #include <sys/stat.h>
103 #include <sys/cdefs.h>
104 #include <sys/ioctl.h>
105 #include <sys/param.h>
106 #include <sys/resource.h>
107 #include <sys/time.h>
108 #include <sys/times.h>
109 #include <sys/types.h>
110 #include <sys/wait.h>
114 #if !defined(FNMATCH_BROKEN)
117 #if !defined(GLOB_BROKEN)
129 * This file was generated by the mksyntax program.
133 #define CWORD 0 /* character is nothing special */
134 #define CNL 1 /* newline character */
135 #define CBACK 2 /* a backslash character */
136 #define CSQUOTE 3 /* single quote */
137 #define CDQUOTE 4 /* double quote */
138 #define CENDQUOTE 5 /* a terminating quote */
139 #define CBQUOTE 6 /* backwards single quote */
140 #define CVAR 7 /* a dollar sign */
141 #define CENDVAR 8 /* a '}' character */
142 #define CLP 9 /* a left paren in arithmetic */
143 #define CRP 10 /* a right paren in arithmetic */
144 #define CENDFILE 11 /* end of file */
145 #define CCTL 12 /* like CWORD, except it must be escaped */
146 #define CSPCL 13 /* these terminate a word */
147 #define CIGN 14 /* character should be ignored */
167 #define TENDBQUOTE 13
187 /* control characters in argument strings */
188 #define CTLESC '\201'
189 #define CTLVAR '\202'
190 #define CTLENDVAR '\203'
191 #define CTLBACKQ '\204'
192 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
193 /* CTLBACKQ | CTLQUOTE == '\205' */
194 #define CTLARI '\206'
195 #define CTLENDARI '\207'
196 #define CTLQUOTEMARK '\210'
199 #define is_digit(c) ((c)>='0' && (c)<='9')
200 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
201 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
204 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
205 * (assuming ascii char codes, as the original implementation did)
207 #define is_special(c) \
208 ( (((unsigned int)c) - 33 < 32) \
209 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
211 #define digit_val(c) ((c) - '0')
214 #define _DIAGASSERT(x)
218 #define S_DFL 1 /* default signal handling (SIG_DFL) */
219 #define S_CATCH 2 /* signal is caught */
220 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
221 #define S_HARD_IGN 4 /* signal is ignored permenantly */
222 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
225 /* variable substitution byte (follows CTLVAR) */
226 #define VSTYPE 0x0f /* type of variable substitution */
227 #define VSNUL 0x10 /* colon--treat the empty string as unset */
228 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
230 /* values of VSTYPE field */
231 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
232 #define VSMINUS 0x2 /* ${var-text} */
233 #define VSPLUS 0x3 /* ${var+text} */
234 #define VSQUESTION 0x4 /* ${var?message} */
235 #define VSASSIGN 0x5 /* ${var=text} */
236 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
237 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
238 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
239 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
240 #define VSLENGTH 0xa /* ${#var} */
242 /* flags passed to redirect */
243 #define REDIR_PUSH 01 /* save previous values of file descriptors */
244 #define REDIR_BACKQ 02 /* save the command output to pipe */
247 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
248 * so we use _setjmp instead.
252 #define setjmp(jmploc) _setjmp(jmploc)
253 #define longjmp(jmploc, val) _longjmp(jmploc, val)
257 * Most machines require the value returned from malloc to be aligned
258 * in some way. The following macro will get this right on many machines.
267 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
270 #ifdef CONFIG_LOCALE_SUPPORT
272 static void change_lc_all(const char *value);
273 static void change_lc_ctype(const char *value);
277 * These macros allow the user to suspend the handling of interrupt signals
278 * over a period of time. This is similar to SIGHOLD to or sigblock, but
279 * much more efficient and portable. (But hacking the kernel is so much
280 * more fun than worrying about efficiency and portability. :-))
283 static void onint (void);
284 static volatile int suppressint;
285 static volatile int intpending;
287 #define INTOFF suppressint++
288 #ifndef ASH_OPTIMIZE_FOR_SIZE
289 #define INTON { if (--suppressint == 0 && intpending) onint(); }
290 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
292 static void __inton (void);
293 static void forceinton (void);
294 #define INTON __inton()
295 #define FORCEINTON forceinton()
298 #define CLEAR_PENDING_INT intpending = 0
299 #define int_pending() intpending
302 typedef void *pointer;
304 #define NULL (void *)0
307 static inline pointer ckmalloc (int sz) { return xmalloc(sz); }
308 static inline pointer ckrealloc(void *p, int sz) { return xrealloc(p, sz); }
309 static inline char * savestr (const char *s) { return xstrdup(s); }
311 static pointer stalloc (int);
312 static void stunalloc (pointer);
313 static void ungrabstackstr (char *, char *);
314 static char * growstackstr(void);
315 static char * makestrspace(size_t newlen);
316 static char *sstrdup (const char *);
319 * Parse trees for commands are allocated in lifo order, so we use a stack
320 * to make this more efficient, and also to avoid all sorts of exception
321 * handling code to handle interrupts in the middle of a parse.
323 * The size 504 was chosen because the Ultrix malloc handles that size
327 #define MINSIZE 504 /* minimum size of a block */
331 struct stack_block *prev;
335 static struct stack_block stackbase;
336 static struct stack_block *stackp = &stackbase;
337 static struct stackmark *markp;
338 static char *stacknxt = stackbase.space;
339 static int stacknleft = MINSIZE;
342 #define equal(s1, s2) (strcmp(s1, s2) == 0)
344 #define stackblock() stacknxt
345 #define stackblocksize() stacknleft
346 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
348 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
349 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
350 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
353 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
354 #define STUNPUTC(p) (++sstrnleft, --p)
355 #define STTOPC(p) p[-1]
356 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
357 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
359 #define ckfree(p) free((pointer)(p))
363 #define TRACE(param) trace param
364 typedef union node unode;
365 static void trace (const char *, ...);
366 static void trargs (char **);
367 static void showtree (unode *);
368 static void trputc (int);
369 static void trputs (const char *);
370 static void opentrace (void);
405 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
406 #define EXP_TILDE 0x2 /* do normal tilde expansion */
407 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
408 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
409 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
410 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
415 static char optet_vals[NOPTS];
417 static const char * const optlist[NOPTS] = {
436 #define optent_name(optent) (optent+1)
437 #define optent_letter(optent) optent[0]
438 #define optent_val(optent) optet_vals[optent]
440 #define eflag optent_val(0)
441 #define fflag optent_val(1)
442 #define Iflag optent_val(2)
443 #define iflag optent_val(3)
444 #define mflag optent_val(4)
445 #define nflag optent_val(5)
446 #define sflag optent_val(6)
447 #define xflag optent_val(7)
448 #define vflag optent_val(8)
449 #define Vflag optent_val(9)
450 #define Eflag optent_val(10)
451 #define Cflag optent_val(11)
452 #define aflag optent_val(12)
453 #define bflag optent_val(13)
454 #define uflag optent_val(14)
455 #define qflag optent_val(15)
458 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
476 union node *redirect;
483 struct nodelist *cmdlist;
490 union node *redirect;
498 union node *elsepart;
529 struct nodelist *backquote;
567 struct nbinary nbinary;
570 struct nredir nredir;
574 struct nclist nclist;
584 struct nodelist *next;
588 struct backcmd { /* result of evalbackcmd */
589 int fd; /* file descriptor to read from */
590 char *buf; /* buffer */
591 int nleft; /* number of chars in buffer */
592 struct job *jp; /* job structure for command */
600 const struct builtincmd *cmd;
605 struct strlist *next;
611 struct strlist *list;
612 struct strlist **lastp;
616 struct strpush *prev; /* preceding string on stack */
620 struct alias *ap; /* if push was associated with an alias */
622 char *string; /* remember the string since it may change */
626 struct parsefile *prev; /* preceding file on stack */
627 int linno; /* current line */
628 int fd; /* file descriptor (or -1 if string) */
629 int nleft; /* number of chars left in this line */
630 int lleft; /* number of chars left in this buffer */
631 char *nextc; /* next char in buffer */
632 char *buf; /* input buffer */
633 struct strpush *strpush; /* for pushing strings at this level */
634 struct strpush basestrpush; /* so pushing one is fast */
638 struct stack_block *stackp;
641 struct stackmark *marknext;
645 int nparam; /* # of positional parameters (without $0) */
646 unsigned char malloc; /* if parameter list dynamically allocated */
647 char **p; /* parameter list */
648 int optind; /* next parameter to be processed by getopts */
649 int optoff; /* used by getopts */
653 * When commands are first encountered, they are entered in a hash table.
654 * This ensures that a full path search will not have to be done for them
655 * on each invocation.
657 * We should investigate converting to a linear search, even though that
658 * would make the command name "hash" a misnomer.
660 #define CMDTABLESIZE 31 /* should be prime */
661 #define ARB 1 /* actual size determined at run time */
666 struct tblentry *next; /* next entry in hash chain */
667 union param param; /* definition of builtin function */
668 short cmdtype; /* index identifying command */
669 char rehash; /* if set, cd done since entry created */
670 char cmdname[ARB]; /* name of command */
674 static struct tblentry *cmdtable[CMDTABLESIZE];
675 static int builtinloc = -1; /* index in path of %builtin, or -1 */
676 static int exerrno = 0; /* Last exec error */
679 static void tryexec (char *, char **, char **);
680 static void printentry (struct tblentry *, int);
681 static void clearcmdentry (int);
682 static struct tblentry *cmdlookup (const char *, int);
683 static void delete_cmd_entry (void);
684 static int path_change (const char *, int *);
687 static void flushall (void);
688 static void out2fmt (const char *, ...)
689 __attribute__((__format__(__printf__,1,2)));
690 static int xwrite (int, const char *, int);
692 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
693 static void out1str(const char *p) { outstr(p, stdout); }
694 static void out2str(const char *p) { outstr(p, stderr); }
696 #ifndef ASH_OPTIMIZE_FOR_SIZE
697 #define out2c(c) putc((c), stderr)
699 static void out2c(int c) { putc(c, stderr); }
703 #ifdef ASH_OPTIMIZE_FOR_SIZE
704 #define USE_SIT_FUNCTION
707 /* number syntax index */
708 #define BASESYNTAX 0 /* not in quotes */
709 #define DQSYNTAX 1 /* in double quotes */
710 #define SQSYNTAX 2 /* in single quotes */
711 #define ARISYNTAX 3 /* in arithmetic */
713 static const char S_I_T[][4] = {
714 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
715 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
716 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
717 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
718 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
719 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
720 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
721 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
722 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
723 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
724 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
725 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
726 #ifndef USE_SIT_FUNCTION
727 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
728 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
729 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
733 #ifdef USE_SIT_FUNCTION
735 #define U_C(c) ((unsigned char)(c))
737 static int SIT(int c, int syntax)
739 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
740 static const char syntax_index_table [] = {
741 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
742 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
743 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
748 if(c==PEOF) /* 2^8+2 */
750 if(c==PEOA) /* 2^8+1 */
752 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
755 s = strchr(spec_symbls, c);
758 indx = syntax_index_table[(s-spec_symbls)];
760 return S_I_T[indx][syntax];
763 #else /* USE_SIT_FUNCTION */
765 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
767 #define CSPCL_CIGN_CIGN_CIGN 0
768 #define CSPCL_CWORD_CWORD_CWORD 1
769 #define CNL_CNL_CNL_CNL 2
770 #define CWORD_CCTL_CCTL_CWORD 3
771 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
772 #define CVAR_CVAR_CWORD_CVAR 5
773 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
774 #define CSPCL_CWORD_CWORD_CLP 7
775 #define CSPCL_CWORD_CWORD_CRP 8
776 #define CBACK_CBACK_CCTL_CBACK 9
777 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
778 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
779 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
780 #define CWORD_CWORD_CWORD_CWORD 13
781 #define CCTL_CCTL_CCTL_CCTL 14
783 static const char syntax_index_table[258] = {
784 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
785 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
786 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
787 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
788 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
789 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
790 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
791 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
792 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
793 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
794 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
795 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
796 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
797 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
798 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
799 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
800 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
801 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
802 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
803 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
804 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
805 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
806 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
807 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
808 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
809 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
810 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
811 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
812 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
813 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
814 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
815 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
816 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
817 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
818 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
819 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
820 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
821 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
822 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
823 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
824 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
825 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
826 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
827 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
828 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
829 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
830 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
831 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
832 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
833 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
834 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
835 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
836 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
837 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
838 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
839 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
840 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
841 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
842 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
843 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
844 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
845 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
846 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
847 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
848 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
849 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
850 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
851 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
852 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
853 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
854 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
855 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
856 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
857 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
858 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
859 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
860 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
861 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
862 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
863 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
864 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
865 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
866 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
867 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
868 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
869 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
870 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
871 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
872 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
873 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
874 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
875 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
876 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
877 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
878 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
879 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
880 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
881 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
882 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
883 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
884 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
885 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
886 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
887 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
888 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
889 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
890 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
891 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
892 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
893 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
894 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
895 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
896 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
897 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
898 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
899 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
900 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
901 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
902 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
903 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
904 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
905 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
906 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
907 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
908 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
909 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
910 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
911 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
912 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
913 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
914 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
915 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
916 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
917 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
918 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
919 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
920 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
921 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
922 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
923 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
924 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
925 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
926 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
927 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
928 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
929 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
930 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
931 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
932 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
933 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
934 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
935 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
936 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
937 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
938 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
939 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
940 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
941 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
942 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
943 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
944 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
945 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
946 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
947 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
948 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
949 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
950 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
951 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
952 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
953 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
954 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
955 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
956 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
957 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
958 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
959 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
960 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
961 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
962 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
963 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
964 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
965 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
966 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
967 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
968 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
969 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
970 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
971 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
972 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
973 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
974 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
975 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
976 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
977 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
978 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
979 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
980 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
981 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
982 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
983 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
984 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
985 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
986 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
987 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
988 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
989 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
990 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
991 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
992 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
993 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
994 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
995 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
996 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
997 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
998 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
999 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
1000 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
1001 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1004 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1005 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1007 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1008 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1009 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1012 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1032 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1033 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1034 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1035 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1036 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1037 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1038 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1039 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1040 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1041 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1042 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1045 #endif /* USE_SIT_FUNCTION */
1048 /* first char is indicating which tokens mark the end of a list */
1049 static const char *const tokname_array[] = {
1064 #define KWDOFFSET 14
1065 /* the following are keywords */
1084 static const char *tokname(int tok)
1086 static char buf[16];
1090 sprintf(buf+(tok>=TSEMI), "%s%c",
1091 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1095 static int plinno = 1; /* input line number */
1097 static int parselleft; /* copy of parsefile->lleft */
1099 static struct parsefile basepf; /* top level input file */
1100 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1101 static struct parsefile *parsefile = &basepf; /* current input file */
1104 * NEOF is returned by parsecmd when it encounters an end of file. It
1105 * must be distinct from NULL, so we use the address of a variable that
1106 * happens to be handy.
1109 static int tokpushback; /* last token pushed back */
1110 #define NEOF ((union node *)&tokpushback)
1111 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1114 static void error (const char *, ...) __attribute__((__noreturn__));
1115 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1116 static void shellexec (char **, char **, const char *, int)
1117 __attribute__((noreturn));
1118 static void exitshell (int) __attribute__((noreturn));
1120 static int goodname(const char *);
1121 static void ignoresig (int);
1122 static void onsig (int);
1123 static void dotrap (void);
1124 static int decode_signal (const char *, int);
1126 static void shprocvar(void);
1127 static void deletefuncs(void);
1128 static void setparam (char **);
1129 static void freeparam (volatile struct shparam *);
1131 /* reasons for skipping commands (see comment on breakcmd routine) */
1137 /* values of cmdtype */
1138 #define CMDUNKNOWN -1 /* no entry in table for command */
1139 #define CMDNORMAL 0 /* command is an executable program */
1140 #define CMDBUILTIN 1 /* command is a shell builtin */
1141 #define CMDFUNCTION 2 /* command is a shell function */
1143 #define DO_ERR 1 /* find_command prints errors */
1144 #define DO_ABS 2 /* find_command checks absolute paths */
1145 #define DO_NOFUN 4 /* find_command ignores functions */
1146 #define DO_BRUTE 8 /* find_command ignores hash table */
1153 #define VEXPORT 0x01 /* variable is exported */
1154 #define VREADONLY 0x02 /* variable cannot be modified */
1155 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1156 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1157 #define VSTACK 0x10 /* text is allocated on the stack */
1158 #define VUNSET 0x20 /* the variable is not set */
1159 #define VNOFUNC 0x40 /* don't call the callback function */
1163 struct var *next; /* next entry in hash list */
1164 int flags; /* flags are defined above */
1165 char *text; /* name=value */
1166 void (*func) (const char *);
1167 /* function to be called when */
1168 /* the variable gets set/unset */
1172 struct localvar *next; /* next local variable in list */
1173 struct var *vp; /* the variable that was made local */
1174 int flags; /* saved flags */
1175 char *text; /* saved text */
1179 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1180 #define rmescapes(p) _rmescapes((p), 0)
1181 static char *_rmescapes (char *, int);
1183 static void rmescapes (char *);
1186 static int casematch (union node *, const char *);
1187 static void clearredir(void);
1188 static void popstring(void);
1189 static void readcmdfile (const char *);
1191 static int number (const char *);
1192 static int is_number (const char *, int *num);
1193 static char *single_quote (const char *);
1194 static int nextopt (const char *);
1196 static void redirect (union node *, int);
1197 static void popredir (void);
1198 static int dup_as_newfd (int, int);
1200 static void changepath(const char *newval);
1201 static void getoptsreset(const char *value);
1204 static int parsenleft; /* copy of parsefile->nleft */
1205 static char *parsenextc; /* copy of parsefile->nextc */
1206 static int rootpid; /* pid of main shell */
1207 static int rootshell; /* true if we aren't a child of the main shell */
1209 static const char spcstr[] = " ";
1210 static const char snlfmt[] = "%s\n";
1212 static int sstrnleft;
1213 static int herefd = -1;
1215 static struct localvar *localvars;
1217 static struct var vifs;
1218 static struct var vmail;
1219 static struct var vmpath;
1220 static struct var vpath;
1221 static struct var vps1;
1222 static struct var vps2;
1223 static struct var voptind;
1224 #ifdef CONFIG_LOCALE_SUPPORT
1225 static struct var vlc_all;
1226 static struct var vlc_ctype;
1233 void (*func) (const char *);
1236 static const char defpathvar[] =
1237 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1238 #define defpath (defpathvar + 5)
1241 static const char defifsvar[] = "IFS= \t\n";
1242 #define defifs (defifsvar + 4)
1244 static const char defifs[] = " \t\n";
1247 static const struct varinit varinit[] = {
1249 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1251 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1254 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1256 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1258 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1261 * vps1 depends on uid
1263 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1265 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1267 #ifdef CONFIG_LOCALE_SUPPORT
1268 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1270 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1279 static struct var *vartab[VTABSIZE];
1282 * The following macros access the values of the above variables.
1283 * They have to skip over the name. They return the null string
1284 * for unset variables.
1287 #define ifsval() (vifs.text + 4)
1288 #define ifsset() ((vifs.flags & VUNSET) == 0)
1289 #define mailval() (vmail.text + 5)
1290 #define mpathval() (vmpath.text + 9)
1291 #define pathval() (vpath.text + 5)
1292 #define ps1val() (vps1.text + 4)
1293 #define ps2val() (vps2.text + 4)
1294 #define optindval() (voptind.text + 7)
1296 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1298 static void initvar (void);
1299 static void setvar (const char *, const char *, int);
1300 static void setvareq (char *, int);
1301 static void listsetvar (struct strlist *);
1302 static const char *lookupvar (const char *);
1303 static const char *bltinlookup (const char *);
1304 static char **environment (void);
1305 static int showvarscmd (int, char **);
1306 static void mklocal (char *);
1307 static void poplocalvars (void);
1308 static int unsetvar (const char *);
1309 static int varequal (const char *, const char *);
1312 static char *arg0; /* value of $0 */
1313 static struct shparam shellparam; /* current positional parameters */
1314 static char **argptr; /* argument list for builtin commands */
1315 static char *optionarg; /* set by nextopt (like getopt) */
1316 static char *optptr; /* used by nextopt */
1317 static char *minusc; /* argument to -c option */
1322 #define ALIASINUSE 1
1334 static struct alias *atab[ATABSIZE];
1336 static void setalias (char *, char *);
1337 static struct alias **hashalias (const char *);
1338 static struct alias *freealias (struct alias *);
1339 static struct alias **__lookupalias (const char *);
1345 struct alias *ap, **app;
1347 app = __lookupalias(name);
1351 if (!(ap->flag & ALIASINUSE)) {
1354 ap->val = savestr(val);
1355 ap->flag &= ~ALIASDEAD;
1358 ap = ckmalloc(sizeof (struct alias));
1359 ap->name = savestr(name);
1360 ap->val = savestr(val);
1373 app = __lookupalias(name);
1377 *app = freealias(*app);
1388 struct alias *ap, **app;
1392 for (i = 0; i < ATABSIZE; i++) {
1394 for (ap = *app; ap; ap = *app) {
1395 *app = freealias(*app);
1405 printalias(const struct alias *ap) {
1408 p = single_quote(ap->val);
1409 printf("alias %s=%s\n", ap->name, p);
1415 * TODO - sort output
1418 aliascmd(int argc, char **argv)
1427 for (i = 0; i < ATABSIZE; i++)
1428 for (ap = atab[i]; ap; ap = ap->next) {
1433 while ((n = *++argv) != NULL) {
1434 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1435 if ((ap = *__lookupalias(n)) == NULL) {
1436 out2fmt("%s: %s not found\n", "alias", n);
1451 unaliascmd(int argc, char **argv)
1455 while ((i = nextopt("a")) != '\0') {
1461 for (i = 0; *argptr; argptr++) {
1462 if (unalias(*argptr)) {
1463 out2fmt("%s: %s not found\n", "unalias", *argptr);
1471 static struct alias **
1475 unsigned int hashval;
1480 return &atab[hashval % ATABSIZE];
1483 static struct alias *
1484 freealias(struct alias *ap) {
1487 if (ap->flag & ALIASINUSE) {
1488 ap->flag |= ALIASDEAD;
1500 static struct alias **
1501 __lookupalias(const char *name) {
1502 struct alias **app = hashalias(name);
1504 for (; *app; app = &(*app)->next) {
1505 if (equal(name, (*app)->name)) {
1514 #ifdef ASH_MATH_SUPPORT
1515 /* The generated file arith.c has been replaced with a custom hand
1516 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1517 * This is now part of libbb, so that it can be used by all the shells
1519 static void expari (int);
1522 static char *trap[NSIG]; /* trap handler commands */
1523 static char sigmode[NSIG - 1]; /* current value of signal */
1524 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1525 static int pendingsigs; /* indicates some signal received */
1528 * This file was generated by the mkbuiltins program.
1532 static int bgcmd (int, char **);
1533 static int fgcmd (int, char **);
1534 static int killcmd (int, char **);
1536 static int bltincmd (int, char **);
1537 static int cdcmd (int, char **);
1538 static int breakcmd (int, char **);
1540 static int commandcmd (int, char **);
1542 static int dotcmd (int, char **);
1543 static int evalcmd (int, char **);
1544 static int execcmd (int, char **);
1545 static int exitcmd (int, char **);
1546 static int exportcmd (int, char **);
1547 static int histcmd (int, char **);
1548 static int hashcmd (int, char **);
1549 static int helpcmd (int, char **);
1550 static int jobscmd (int, char **);
1551 static int localcmd (int, char **);
1552 static int pwdcmd (int, char **);
1553 static int readcmd (int, char **);
1554 static int returncmd (int, char **);
1555 static int setcmd (int, char **);
1556 static int setvarcmd (int, char **);
1557 static int shiftcmd (int, char **);
1558 static int trapcmd (int, char **);
1559 static int umaskcmd (int, char **);
1561 static int aliascmd (int, char **);
1562 static int unaliascmd (int, char **);
1564 static int unsetcmd (int, char **);
1565 static int waitcmd (int, char **);
1566 static int ulimitcmd (int, char **);
1567 static int timescmd (int, char **);
1568 #ifdef ASH_MATH_SUPPORT
1569 static int letcmd (int, char **);
1571 static int typecmd (int, char **);
1573 static int getoptscmd (int, char **);
1577 static int true_main (int, char **);
1579 #ifndef CONFIG_FALSE
1580 static int false_main (int, char **);
1583 static void setpwd (const char *, int);
1586 #define BUILTIN_NOSPEC "0"
1587 #define BUILTIN_SPECIAL "1"
1588 #define BUILTIN_REGULAR "2"
1589 #define BUILTIN_ASSIGN "4"
1590 #define BUILTIN_SPEC_ASSG "5"
1591 #define BUILTIN_REG_ASSG "6"
1593 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1594 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1595 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1599 int (*const builtinfunc) (int, char **);
1604 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1605 * the binary search in find_builtin() will stop working. If you value
1606 * your kneecaps, you'll be sure to *make sure* that any changes made
1607 * to this array result in the listing remaining in ascii order. You
1610 static const struct builtincmd builtincmds[] = {
1611 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1612 { BUILTIN_SPECIAL ":", true_main },
1614 { BUILTIN_REG_ASSG "alias", aliascmd },
1617 { BUILTIN_REGULAR "bg", bgcmd },
1619 { BUILTIN_SPECIAL "break", breakcmd },
1620 { BUILTIN_SPECIAL "builtin", bltincmd },
1621 { BUILTIN_REGULAR "cd", cdcmd },
1622 { BUILTIN_NOSPEC "chdir", cdcmd },
1624 { BUILTIN_REGULAR "command", commandcmd },
1626 { BUILTIN_SPECIAL "continue", breakcmd },
1627 { BUILTIN_SPECIAL "eval", evalcmd },
1628 { BUILTIN_SPECIAL "exec", execcmd },
1629 { BUILTIN_SPECIAL "exit", exitcmd },
1630 { BUILTIN_SPEC_ASSG "export", exportcmd },
1631 { BUILTIN_REGULAR "false", false_main },
1632 { BUILTIN_REGULAR "fc", histcmd },
1634 { BUILTIN_REGULAR "fg", fgcmd },
1637 { BUILTIN_REGULAR "getopts", getoptscmd },
1639 { BUILTIN_NOSPEC "hash", hashcmd },
1640 { BUILTIN_NOSPEC "help", helpcmd },
1641 { BUILTIN_REGULAR "jobs", jobscmd },
1643 { BUILTIN_REGULAR "kill", killcmd },
1645 #ifdef ASH_MATH_SUPPORT
1646 { BUILTIN_REGULAR "let", letcmd },
1648 { BUILTIN_ASSIGN "local", localcmd },
1649 { BUILTIN_NOSPEC "pwd", pwdcmd },
1650 { BUILTIN_REGULAR "read", readcmd },
1651 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1652 { BUILTIN_SPECIAL "return", returncmd },
1653 { BUILTIN_SPECIAL "set", setcmd },
1654 { BUILTIN_NOSPEC "setvar", setvarcmd },
1655 { BUILTIN_SPECIAL "shift", shiftcmd },
1656 { BUILTIN_SPECIAL "times", timescmd },
1657 { BUILTIN_SPECIAL "trap", trapcmd },
1658 { BUILTIN_REGULAR "true", true_main },
1659 { BUILTIN_NOSPEC "type", typecmd },
1660 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1661 { BUILTIN_REGULAR "umask", umaskcmd },
1663 { BUILTIN_REGULAR "unalias", unaliascmd },
1665 { BUILTIN_SPECIAL "unset", unsetcmd },
1666 { BUILTIN_REGULAR "wait", waitcmd },
1668 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1670 #define DOTCMD &builtincmds[0]
1671 static struct builtincmd *BLTINCMD;
1672 static struct builtincmd *EXECCMD;
1673 static struct builtincmd *EVALCMD;
1676 #define JOBSTOPPED 1 /* all procs are stopped */
1677 #define JOBDONE 2 /* all procs are completed */
1680 * A job structure contains information about a job. A job is either a
1681 * single process or a set of processes contained in a pipeline. In the
1682 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1687 pid_t pid; /* process id */
1688 int status; /* status flags (defined above) */
1689 char *cmd; /* text of command being run */
1693 static int job_warning; /* user was warned about stopped jobs */
1696 static void setjobctl(int enable);
1698 #define setjobctl(on) /* do nothing */
1703 struct procstat ps0; /* status of process */
1704 struct procstat *ps; /* status or processes when more than one */
1705 short nprocs; /* number of processes */
1706 short pgrp; /* process group of this job */
1707 char state; /* true if job is finished */
1708 char used; /* true if this entry is in used */
1709 char changed; /* true if status has changed */
1711 char jobctl; /* job running under job control */
1715 static struct job *jobtab; /* array of jobs */
1716 static int njobs; /* size of array */
1717 static int backgndpid = -1; /* pid of last background process */
1719 static int initialpgrp; /* pgrp of shell on invocation */
1720 static int curjob; /* current job */
1723 static int intreceived;
1725 static struct job *makejob (const union node *, int);
1726 static int forkshell (struct job *, const union node *, int);
1727 static int waitforjob (struct job *);
1729 static int docd (char *, int);
1730 static void updatepwd (const char *);
1731 static void getpwd (void);
1733 static char *padvance (const char **, const char *);
1735 static char nullstr[1]; /* zero length string */
1736 static char *curdir = nullstr; /* current working directory */
1750 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1751 error("HOME not set");
1754 if (dest[0] == '-' && dest[1] == '\0') {
1755 dest = bltinlookup("OLDPWD");
1756 if (!dest || !*dest) {
1765 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1767 while ((p = padvance(&path, dest)) != NULL) {
1768 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1773 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1775 print = strcmp(p, dest);
1777 if (docd(p, print) >= 0)
1782 error("can't cd to %s", dest);
1788 * Actually do the chdir. In an interactive shell, print the
1789 * directory name if "print" is nonzero.
1793 docd(char *dest, int print)
1795 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1797 if (chdir(dest) < 0) {
1804 printf(snlfmt, curdir);
1810 * Update curdir (the name of the current directory) in response to a
1811 * cd command. We also call hashcd to let the routines in exec.c know
1812 * that the current directory has changed.
1815 static void hashcd (void);
1818 updatepwd(const char *dir)
1820 hashcd(); /* update command hash table */
1822 /* If our argument is NULL, we don't know the current directory */
1823 if (dir == NULL || curdir == nullstr) {
1832 pwdcmd(int argc, char **argv)
1834 printf(snlfmt, curdir);
1838 /* Ask system the current directory */
1842 curdir = xgetcwd(0);
1848 setpwd(const char *val, int setold)
1853 setvar("OLDPWD", curdir, VEXPORT);
1856 if (curdir != nullstr) {
1857 if(val!=NULL && *val != '/')
1858 val = cated = concat_path_file(curdir, val);
1864 curdir = simplify_path(val);
1867 setvar("PWD", curdir, VEXPORT);
1871 * Errors and exceptions.
1875 * Code to handle exceptions in C.
1879 * We enclose jmp_buf in a structure so that we can declare pointers to
1880 * jump locations. The global variable handler contains the location to
1881 * jump to when an exception occurs, and the global variable exception
1882 * contains a code identifying the exeception. To implement nested
1883 * exception handlers, the user should save the value of handler on entry
1884 * to an inner scope, set handler to point to a jmploc structure for the
1885 * inner scope, and restore handler on exit from the scope.
1893 #define EXINT 0 /* SIGINT received */
1894 #define EXERROR 1 /* a generic error */
1895 #define EXSHELLPROC 2 /* execute a shell procedure */
1896 #define EXEXEC 3 /* command execution failed */
1898 static struct jmploc *handler;
1899 static int exception;
1901 static void exverror (int, const char *, va_list)
1902 __attribute__((__noreturn__));
1905 * Called to raise an exception. Since C doesn't include exceptions, we
1906 * just do a longjmp to the exception handler. The type of exception is
1907 * stored in the global variable "exception".
1910 static void exraise (int) __attribute__((__noreturn__));
1916 if (handler == NULL)
1921 longjmp(handler->loc, 1);
1926 * Called from trap.c when a SIGINT is received. (If the user specifies
1927 * that SIGINT is to be trapped or ignored using the trap builtin, then
1928 * this routine is not called.) Suppressint is nonzero when interrupts
1929 * are held using the INTOFF macro. The call to _exit is necessary because
1930 * there is a short period after a fork before the signal handlers are
1931 * set to the appropriate value for the child. (The test for iflag is
1932 * just defensive programming.)
1944 sigemptyset(&mysigset);
1945 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1946 if (rootshell && iflag)
1949 signal(SIGINT, SIG_DFL);
1956 static char *commandname; /* currently executing command */
1959 * Exverror is called to raise the error exception. If the first argument
1960 * is not NULL then error prints an error message using printf style
1961 * formatting. It then raises the error exception.
1964 exverror(int cond, const char *msg, va_list ap)
1971 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1973 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1977 out2fmt("%s: ", commandname);
1978 vfprintf(stderr, msg, ap);
1987 error(const char *msg, ...)
1991 exverror(EXERROR, msg, ap);
1998 exerror(int cond, const char *msg, ...)
2002 exverror(cond, msg, ap);
2010 * Table of error messages.
2014 short errcode; /* error number */
2015 char action; /* operation which encountered the error */
2019 * Types of operations (passed to the errmsg routine).
2022 #define E_OPEN 01 /* opening a file */
2023 #define E_CREAT 02 /* creating a file */
2024 #define E_EXEC 04 /* executing a program */
2026 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2028 static const struct errname errormsg[] = {
2033 { ENOENT, E_CREAT },
2035 { ENOTDIR, E_OPEN },
2036 { ENOTDIR, E_CREAT },
2037 { ENOTDIR, E_EXEC },
2039 { EEXIST, E_CREAT },
2078 { ELIBACC, E_EXEC },
2082 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2085 * Return a string describing an error. The returned string may be a
2086 * pointer to a static buffer that will be overwritten on the next call.
2087 * Action describes the operation that got the error.
2091 errmsg(int e, int action)
2093 struct errname const *ep;
2094 static char buf[12];
2096 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2097 if (ep->errcode == e && (ep->action & action) != 0)
2101 snprintf(buf, sizeof buf, "error %d", e);
2106 #ifdef ASH_OPTIMIZE_FOR_SIZE
2109 if (--suppressint == 0 && intpending) {
2113 static void forceinton (void) {
2120 /* flags in argument to evaltree */
2121 #define EV_EXIT 01 /* exit after evaluating tree */
2122 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2123 #define EV_BACKCMD 04 /* command executing within back quotes */
2125 static int evalskip; /* set if we are skipping commands */
2126 static int skipcount; /* number of levels to skip */
2127 static int loopnest; /* current loop nesting level */
2128 static int funcnest; /* depth of function calls */
2131 static struct strlist *cmdenviron; /* environment for builtin command */
2132 static int exitstatus; /* exit status of last command */
2133 static int oexitstatus; /* saved exit status */
2135 static void evalsubshell (const union node *, int);
2136 static void expredir (union node *);
2137 static void prehash (union node *);
2138 static void eprintlist (struct strlist *);
2140 static union node *parsecmd(int);
2142 * Called to reset things after an exception.
2146 * The eval commmand.
2148 static void evalstring (char *, int);
2162 STARTSTACKSTR(concat);
2166 STPUTC(*p++, concat);
2167 if ((p = *ap++) == NULL)
2169 STPUTC(' ', concat);
2171 STPUTC('\0', concat);
2172 p = grabstackstr(concat);
2174 evalstring(p, EV_TESTED);
2180 * Execute a command or commands contained in a string.
2183 static void evaltree (union node *, int);
2184 static void setinputstring (char *);
2185 static void popfile (void);
2186 static void setstackmark(struct stackmark *mark);
2187 static void popstackmark(struct stackmark *mark);
2191 evalstring(char *s, int flag)
2194 struct stackmark smark;
2196 setstackmark(&smark);
2198 while ((n = parsecmd(0)) != NEOF) {
2200 popstackmark(&smark);
2203 popstackmark(&smark);
2206 static struct builtincmd *find_builtin (const char *);
2207 static void expandarg (union node *, struct arglist *, int);
2208 static void calcsize (const union node *);
2209 static union node *copynode (const union node *);
2212 * Make a copy of a parse tree.
2215 static int funcblocksize; /* size of structures in function */
2216 static int funcstringsize; /* size of strings in node */
2217 static pointer funcblock; /* block to allocate function from */
2218 static char *funcstring; /* block to allocate strings from */
2221 static inline union node *
2222 copyfunc(union node *n)
2229 funcblock = ckmalloc(funcblocksize + funcstringsize);
2230 funcstring = (char *) funcblock + funcblocksize;
2235 * Free a parse tree.
2239 freefunc(union node *n)
2247 * Add a new command entry, replacing any existing command entry for
2252 addcmdentry(char *name, struct cmdentry *entry)
2254 struct tblentry *cmdp;
2257 cmdp = cmdlookup(name, 1);
2258 if (cmdp->cmdtype == CMDFUNCTION) {
2259 freefunc(cmdp->param.func);
2261 cmdp->cmdtype = entry->cmdtype;
2262 cmdp->param = entry->u;
2267 evalloop(const union node *n, int flags)
2274 evaltree(n->nbinary.ch1, EV_TESTED);
2276 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2280 if (evalskip == SKIPBREAK && --skipcount <= 0)
2284 if (n->type == NWHILE) {
2285 if (exitstatus != 0)
2288 if (exitstatus == 0)
2291 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2292 status = exitstatus;
2297 exitstatus = status;
2301 evalfor(const union node *n, int flags)
2303 struct arglist arglist;
2306 struct stackmark smark;
2308 setstackmark(&smark);
2309 arglist.lastp = &arglist.list;
2310 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2311 oexitstatus = exitstatus;
2312 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2316 *arglist.lastp = NULL;
2320 for (sp = arglist.list ; sp ; sp = sp->next) {
2321 setvar(n->nfor.var, sp->text, 0);
2322 evaltree(n->nfor.body, flags & EV_TESTED);
2324 if (evalskip == SKIPCONT && --skipcount <= 0) {
2328 if (evalskip == SKIPBREAK && --skipcount <= 0)
2335 popstackmark(&smark);
2339 evalcase(const union node *n, int flags)
2343 struct arglist arglist;
2344 struct stackmark smark;
2346 setstackmark(&smark);
2347 arglist.lastp = &arglist.list;
2348 oexitstatus = exitstatus;
2349 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2350 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2351 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2352 if (casematch(patp, arglist.list->text)) {
2353 if (evalskip == 0) {
2354 evaltree(cp->nclist.body, flags);
2361 popstackmark(&smark);
2365 * Evaluate a pipeline. All the processes in the pipeline are children
2366 * of the process creating the pipeline. (This differs from some versions
2367 * of the shell, which make the last process in a pipeline the parent
2371 static inline void evalpipe(union node *n)
2374 struct nodelist *lp;
2379 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2381 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2384 jp = makejob(n, pipelen);
2386 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2390 if (pipe(pip) < 0) {
2392 error("Pipe call failed");
2395 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2399 dup_as_newfd(prevfd, 0);
2411 dup_as_newfd(pip[1], 1);
2415 evaltree(lp->n, EV_EXIT);
2423 if (n->npipe.backgnd == 0) {
2425 exitstatus = waitforjob(jp);
2426 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2431 static void find_command (const char *, struct cmdentry *, int, const char *);
2434 isassignment(const char *word) {
2435 if (!is_name(*word)) {
2440 } while (is_in_name(*word));
2441 return *word == '=';
2446 evalcommand(union node *cmd, int flags)
2448 struct stackmark smark;
2450 struct arglist arglist;
2451 struct arglist varlist;
2457 struct cmdentry cmdentry;
2459 char *volatile savecmdname;
2460 volatile struct shparam saveparam;
2461 struct localvar *volatile savelocalvars;
2465 const struct builtincmd *firstbltin;
2466 struct jmploc *volatile savehandler;
2467 struct jmploc jmploc;
2469 /* Avoid longjmp clobbering */
2476 /* First expand the arguments. */
2477 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2478 setstackmark(&smark);
2479 arglist.lastp = &arglist.list;
2480 varlist.lastp = &varlist.list;
2482 oexitstatus = exitstatus;
2485 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2486 expandarg(argp, &varlist, EXP_VARTILDE);
2489 argp = cmd->ncmd.args; argp && !arglist.list;
2490 argp = argp->narg.next
2492 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2495 struct builtincmd *bcmd;
2497 bcmd = find_builtin(arglist.list->text);
2498 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2499 for (; argp; argp = argp->narg.next) {
2500 if (pseudovarflag && isassignment(argp->narg.text)) {
2501 expandarg(argp, &arglist, EXP_VARTILDE);
2504 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2507 *arglist.lastp = NULL;
2508 *varlist.lastp = NULL;
2509 expredir(cmd->ncmd.redirect);
2511 for (sp = arglist.list ; sp ; sp = sp->next)
2513 argv = stalloc(sizeof (char *) * (argc + 1));
2515 for (sp = arglist.list ; sp ; sp = sp->next) {
2516 TRACE(("evalcommand arg: %s\n", sp->text));
2521 if (iflag && funcnest == 0 && argc > 0)
2525 /* Print the command if xflag is set. */
2528 eprintlist(varlist.list);
2529 eprintlist(arglist.list);
2533 /* Now locate the command. */
2535 cmdentry.cmdtype = CMDBUILTIN;
2536 firstbltin = cmdentry.u.cmd = BLTINCMD;
2538 const char *oldpath;
2539 int findflag = DO_ERR;
2543 * Modify the command lookup path, if a PATH= assignment
2546 for (sp = varlist.list ; sp ; sp = sp->next)
2547 if (varequal(sp->text, defpathvar)) {
2548 path = sp->text + 5;
2549 findflag |= DO_BRUTE;
2552 oldfindflag = findflag;
2555 find_command(argv[0], &cmdentry, findflag, path);
2556 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2560 /* implement bltin and command here */
2561 if (cmdentry.cmdtype != CMDBUILTIN) {
2565 firstbltin = cmdentry.u.cmd;
2567 if (cmdentry.u.cmd == BLTINCMD) {
2569 struct builtincmd *bcmd;
2574 if (!(bcmd = find_builtin(*argv))) {
2575 out2fmt("%s: not found\n", *argv);
2579 cmdentry.u.cmd = bcmd;
2580 if (bcmd != BLTINCMD)
2584 if (cmdentry.u.cmd == find_builtin("command")) {
2589 if (*argv[0] == '-') {
2590 if (!equal(argv[0], "-p")) {
2600 findflag |= DO_BRUTE;
2603 findflag = oldfindflag;
2605 findflag |= DO_NOFUN;
2613 /* Fork off a child process if necessary. */
2614 if (cmd->ncmd.backgnd
2615 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2617 jp = makejob(cmd, 1);
2618 mode = cmd->ncmd.backgnd;
2619 if (forkshell(jp, cmd, mode) != 0)
2620 goto parent; /* at end of routine */
2624 /* This is the child process if a fork occurred. */
2625 /* Execute the command. */
2626 if (cmdentry.cmdtype == CMDFUNCTION) {
2628 trputs("Shell function: "); trargs(argv);
2630 exitstatus = oexitstatus;
2631 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2632 saveparam = shellparam;
2633 shellparam.malloc = 0;
2634 shellparam.nparam = argc - 1;
2635 shellparam.p = argv + 1;
2637 savelocalvars = localvars;
2640 if (setjmp(jmploc.loc)) {
2641 if (exception == EXSHELLPROC) {
2642 freeparam((volatile struct shparam *)
2645 saveparam.optind = shellparam.optind;
2646 saveparam.optoff = shellparam.optoff;
2647 freeparam(&shellparam);
2648 shellparam = saveparam;
2651 localvars = savelocalvars;
2652 handler = savehandler;
2653 longjmp(handler->loc, 1);
2655 savehandler = handler;
2657 for (sp = varlist.list ; sp ; sp = sp->next)
2660 evaltree(cmdentry.u.func, flags & EV_TESTED);
2664 localvars = savelocalvars;
2665 saveparam.optind = shellparam.optind;
2666 saveparam.optoff = shellparam.optoff;
2667 freeparam(&shellparam);
2668 shellparam = saveparam;
2669 handler = savehandler;
2672 if (evalskip == SKIPFUNC) {
2676 if (flags & EV_EXIT)
2677 exitshell(exitstatus);
2678 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2680 trputs("builtin command: "); trargs(argv);
2682 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2683 redirect(cmd->ncmd.redirect, mode);
2684 savecmdname = commandname;
2685 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2686 listsetvar(varlist.list);
2688 cmdenviron = varlist.list;
2691 if (setjmp(jmploc.loc)) {
2693 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2696 savehandler = handler;
2698 commandname = argv[0];
2700 optptr = NULL; /* initialize nextopt */
2701 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2705 if (e != EXSHELLPROC) {
2706 commandname = savecmdname;
2707 if (flags & EV_EXIT)
2708 exitshell(exitstatus);
2710 handler = savehandler;
2712 if ((e != EXERROR && e != EXEXEC)
2713 || cmdentry.u.cmd == BLTINCMD
2714 || cmdentry.u.cmd == DOTCMD
2715 || cmdentry.u.cmd == EVALCMD
2716 || cmdentry.u.cmd == EXECCMD)
2720 if (cmdentry.u.cmd != EXECCMD)
2724 trputs("normal command: "); trargs(argv);
2726 redirect(cmd->ncmd.redirect, 0);
2728 for (sp = varlist.list ; sp ; sp = sp->next)
2729 setvareq(sp->text, VEXPORT|VSTACK);
2730 envp = environment();
2731 shellexec(argv, envp, path, cmdentry.u.index);
2735 parent: /* parent process gets here (if we forked) */
2736 if (mode == 0) { /* argument to fork */
2738 exitstatus = waitforjob(jp);
2744 setvar("_", lastarg, 0);
2745 popstackmark(&smark);
2749 * Evaluate a parse tree. The value is left in the global variable
2759 TRACE(("evaltree(NULL) called\n"));
2762 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2765 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2768 evaltree(n->nbinary.ch2, flags);
2771 evaltree(n->nbinary.ch1, EV_TESTED);
2772 if (evalskip || exitstatus != 0)
2774 evaltree(n->nbinary.ch2, flags);
2777 evaltree(n->nbinary.ch1, EV_TESTED);
2778 if (evalskip || exitstatus == 0)
2780 evaltree(n->nbinary.ch2, flags);
2783 expredir(n->nredir.redirect);
2784 redirect(n->nredir.redirect, REDIR_PUSH);
2785 evaltree(n->nredir.n, flags);
2789 evalsubshell(n, flags);
2792 evalsubshell(n, flags);
2795 evaltree(n->nif.test, EV_TESTED);
2798 if (exitstatus == 0)
2799 evaltree(n->nif.ifpart, flags);
2800 else if (n->nif.elsepart)
2801 evaltree(n->nif.elsepart, flags);
2817 struct builtincmd *bcmd;
2818 struct cmdentry entry;
2820 (bcmd = find_builtin(n->narg.text)) &&
2821 IS_BUILTIN_SPECIAL(bcmd)
2823 out2fmt("%s is a special built-in\n", n->narg.text);
2827 entry.cmdtype = CMDFUNCTION;
2828 entry.u.func = copyfunc(n->narg.next);
2829 addcmdentry(n->narg.text, &entry);
2834 evaltree(n->nnot.com, EV_TESTED);
2835 exitstatus = !exitstatus;
2843 evalcommand(n, flags);
2848 printf("Node type = %d\n", n->type);
2857 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2859 exitshell(exitstatus);
2863 * Kick off a subshell to evaluate a tree.
2867 evalsubshell(const union node *n, int flags)
2870 int backgnd = (n->type == NBACKGND);
2872 expredir(n->nredir.redirect);
2874 if (forkshell(jp, n, backgnd) == 0) {
2876 flags &=~ EV_TESTED;
2877 redirect(n->nredir.redirect, 0);
2878 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2882 exitstatus = waitforjob(jp);
2888 * Compute the names of the files in a redirection list.
2891 static void fixredir(union node *n, const char *text, int err);
2894 expredir(union node *n)
2898 for (redir = n ; redir ; redir = redir->nfile.next) {
2900 fn.lastp = &fn.list;
2901 oexitstatus = exitstatus;
2902 switch (redir->type) {
2908 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2909 redir->nfile.expfname = fn.list->text;
2913 if (redir->ndup.vname) {
2914 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2915 fixredir(redir, fn.list->text, 1);
2924 * Execute a command inside back quotes. If it's a builtin command, we
2925 * want to save its output in a block obtained from malloc. Otherwise
2926 * we fork off a subprocess and get the output of the command via a pipe.
2927 * Should be called with interrupts off.
2931 evalbackcmd(union node *n, struct backcmd *result)
2935 struct stackmark smark; /* unnecessary */
2937 setstackmark(&smark);
2948 error("Pipe call failed");
2950 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2955 dup_as_newfd(pip[1], 1);
2959 evaltree(n, EV_EXIT);
2962 result->fd = pip[0];
2965 popstackmark(&smark);
2966 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2967 result->fd, result->buf, result->nleft, result->jp));
2972 * Execute a simple command.
2976 * Search for a command. This is called before we fork so that the
2977 * location of the command will be available in the parent as well as
2978 * the child. The check for "goodname" is an overly conservative
2979 * check that the name will not be subject to expansion.
2986 struct cmdentry entry;
2988 if (n->type == NCMD && n->ncmd.args)
2989 if (goodname(n->ncmd.args->narg.text))
2990 find_command(n->ncmd.args->narg.text, &entry, 0,
2996 * Builtin commands. Builtin commands whose functions are closely
2997 * tied to evaluation are implemented here.
3001 * No command given, or a bltin command with no arguments. Set the
3002 * specified variables.
3006 bltincmd(argc, argv)
3011 * Preserve exitstatus of a previous possible redirection
3019 * Handle break and continue commands. Break, continue, and return are
3020 * all handled by setting the evalskip flag. The evaluation routines
3021 * above all check this flag, and if it is set they start skipping
3022 * commands rather than executing them. The variable skipcount is
3023 * the number of loops to break/continue, or the number of function
3024 * levels to return. (The latter is always 1.) It should probably
3025 * be an error to break out of more loops than exist, but it isn't
3026 * in the standard shell so we don't make it one here.
3030 breakcmd(argc, argv)
3034 int n = argc > 1 ? number(argv[1]) : 1;
3039 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3047 * The return command.
3051 returncmd(argc, argv)
3055 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3058 evalskip = SKIPFUNC;
3063 /* Do what ksh does; skip the rest of the file */
3064 evalskip = SKIPFILE;
3071 #ifndef CONFIG_FALSE
3073 false_main(argc, argv)
3083 true_main(argc, argv)
3092 * Controls whether the shell is interactive or not.
3095 static void setsignal(int signo);
3098 static void chkmail(int silent);
3102 setinteractive(int on)
3104 static int is_interactive;
3105 static int do_banner=0;
3107 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)) != 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,
6759 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6765 TRACE(("Fork failed, errno=%d\n", errno));
6767 error("Cannot fork");
6774 TRACE(("Child shell %d\n", getpid()));
6775 wasroot = rootshell;
6781 jobctl = 0; /* do job control only in root shell */
6782 if (wasroot && mode != FORK_NOJOB && mflag) {
6783 if (jp == NULL || jp->nprocs == 0)
6786 pgrp = jp->ps[0].pid;
6788 if (mode == FORK_FG) {
6789 /*** this causes superfluous TIOCSPGRPS ***/
6790 #ifdef OLD_TTY_DRIVER
6791 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6792 error("TIOCSPGRP failed, errno=%d", errno);
6794 if (tcsetpgrp(2, pgrp) < 0)
6795 error("tcsetpgrp failed, errno=%d", errno);
6800 } else if (mode == FORK_BG) {
6803 if ((jp == NULL || jp->nprocs == 0) &&
6804 ! fd0_redirected_p ()) {
6806 if (open(devnull, O_RDONLY) != 0)
6807 error(nullerr, devnull);
6811 if (mode == FORK_BG) {
6814 if ((jp == NULL || jp->nprocs == 0) &&
6815 ! fd0_redirected_p ()) {
6817 if (open(devnull, O_RDONLY) != 0)
6818 error(nullerr, devnull);
6822 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6825 if (wasroot && iflag) {
6833 if (rootshell && mode != FORK_NOJOB && mflag) {
6834 if (jp == NULL || jp->nprocs == 0)
6837 pgrp = jp->ps[0].pid;
6841 if (mode == FORK_BG)
6842 backgndpid = pid; /* set $! */
6844 struct procstat *ps = &jp->ps[jp->nprocs++];
6848 if (iflag && rootshell && n)
6849 ps->cmd = commandtext(n);
6852 TRACE(("In parent shell: child = %d\n", pid));
6859 * Wait for job to finish.
6861 * Under job control we have the problem that while a child process is
6862 * running interrupts generated by the user are sent to the child but not
6863 * to the shell. This means that an infinite loop started by an inter-
6864 * active user may be hard to kill. With job control turned off, an
6865 * interactive user may place an interactive program inside a loop. If
6866 * the interactive program catches interrupts, the user doesn't want
6867 * these interrupts to also abort the loop. The approach we take here
6868 * is to have the shell ignore interrupt signals while waiting for a
6869 * forground process to terminate, and then send itself an interrupt
6870 * signal if the child process was terminated by an interrupt signal.
6871 * Unfortunately, some programs want to do a bit of cleanup and then
6872 * exit on interrupt; unless these processes terminate themselves by
6873 * sending a signal to themselves (instead of calling exit) they will
6874 * confuse this approach.
6878 waitforjob(struct job *jp)
6881 int mypgrp = getpgrp();
6885 struct sigaction act, oact;
6894 sigaction(SIGINT, 0, &act);
6895 act.sa_handler = waitonint;
6896 sigaction(SIGINT, &act, &oact);
6898 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6899 while (jp->state == 0) {
6907 sigaction(SIGINT, &oact, 0);
6908 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6912 #ifdef OLD_TTY_DRIVER
6913 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6914 error("TIOCSPGRP failed, errno=%d\n", errno);
6916 if (tcsetpgrp(2, mypgrp) < 0)
6917 error("tcsetpgrp failed, errno=%d\n", errno);
6920 if (jp->state == JOBSTOPPED)
6921 curjob = jp - jobtab + 1;
6923 status = jp->ps[jp->nprocs - 1].status;
6924 /* convert to 8 bits */
6925 if (WIFEXITED(status))
6926 st = WEXITSTATUS(status);
6928 else if (WIFSTOPPED(status))
6929 st = WSTOPSIG(status) + 128;
6932 st = WTERMSIG(status) + 128;
6936 * This is truly gross.
6937 * If we're doing job control, then we did a TIOCSPGRP which
6938 * caused us (the shell) to no longer be in the controlling
6939 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6940 * intuit from the subprocess exit status whether a SIGINT
6941 * occured, and if so interrupt ourselves. Yuck. - mycroft
6943 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6946 if (jp->state == JOBDONE)
6957 * Wait for a process to terminate.
6961 * Do a wait system call. If job control is compiled in, we accept
6962 * stopped processes. If block is zero, we return a value of zero
6963 * rather than blocking.
6965 * System V doesn't have a non-blocking wait system call. It does
6966 * have a SIGCLD signal that is sent to a process when one of it's
6967 * children dies. The obvious way to use SIGCLD would be to install
6968 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6969 * was received, and have waitproc bump another counter when it got
6970 * the status of a process. Waitproc would then know that a wait
6971 * system call would not block if the two counters were different.
6972 * This approach doesn't work because if a process has children that
6973 * have not been waited for, System V will send it a SIGCLD when it
6974 * installs a signal handler for SIGCLD. What this means is that when
6975 * a child exits, the shell will be sent SIGCLD signals continuously
6976 * until is runs out of stack space, unless it does a wait call before
6977 * restoring the signal handler. The code below takes advantage of
6978 * this (mis)feature by installing a signal handler for SIGCLD and
6979 * then checking to see whether it was called. If there are any
6980 * children to be waited for, it will be.
6985 waitproc(int block, int *status)
6996 return wait3(status, flags, (struct rusage *)NULL);
7000 dowait(int block, struct job *job)
7004 struct procstat *sp;
7006 struct job *thisjob;
7012 TRACE(("dowait(%d) called\n", block));
7014 pid = waitproc(block, &status);
7015 TRACE(("wait returns %d, status=%d\n", pid, status));
7016 } while (!(block & 2) && pid == -1 && errno == EINTR);
7021 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
7025 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
7028 if (sp->pid == pid) {
7029 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
7030 sp->status = status;
7033 if (sp->status == -1)
7035 else if (WIFSTOPPED(sp->status))
7038 if (stopped) { /* stopped or done */
7039 int state = done? JOBDONE : JOBSTOPPED;
7040 if (jp->state != state) {
7041 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
7044 if (done && curjob == jp - jobtab + 1)
7045 curjob = 0; /* no current job */
7052 if (! rootshell || ! iflag || (job && thisjob == job)) {
7053 core = WCOREDUMP(status);
7055 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
7058 if (WIFEXITED(status)) sig = 0;
7059 else sig = WTERMSIG(status);
7061 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
7063 out2fmt("%d: ", pid);
7065 if (sig == SIGTSTP && rootshell && iflag)
7067 (long)(job - jobtab + 1));
7069 if (sig < NSIG && sys_siglist[sig])
7070 out2str(sys_siglist[sig]);
7072 out2fmt("Signal %d", sig);
7074 out2str(" - core dumped");
7077 TRACE(("Not printing status: status=%d, sig=%d\n",
7081 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
7083 thisjob->changed = 1;
7092 * return 1 if there are stopped jobs, otherwise 0
7102 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7105 if (jp->state == JOBSTOPPED) {
7106 out2str("You have stopped jobs.\n");
7116 * Return a string identifying a command (to be printed by the
7120 static char *cmdnextc;
7121 static int cmdnleft;
7122 #define MAXCMDTEXT 200
7125 cmdputs(const char *s)
7136 while ((c = *p++) != '\0') {
7139 else if (c == CTLVAR) {
7144 } else if (c == '=' && subtype != 0) {
7145 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7147 } else if (c == CTLENDVAR) {
7149 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7150 cmdnleft++; /* ignore it */
7153 if (--cmdnleft <= 0) {
7163 #define CMDTXT_TABLE
7166 * To collect a lot of redundant code in cmdtxt() case statements, we
7167 * implement a mini language here. Each type of node struct has an
7168 * associated instruction sequence that operates on its members via
7169 * their offsets. The instruction are pack in unsigned chars with
7170 * format IIDDDDDE where the bits are
7171 * I : part of the instruction opcode, which are
7172 * 00 : member is a pointer to another node -- process it recursively
7173 * 40 : member is a pointer to a char string -- output it
7174 * 80 : output the string whose index is stored in the data field
7175 * CC : flag signaling that this case needs external processing
7176 * D : data - either the (shifted) index of a fixed string to output or
7177 * the actual offset of the member to operate on in the struct
7178 * (since we assume bit 0 is set, the offset is not shifted)
7179 * E : flag signaling end of instruction sequence
7181 * WARNING: In order to handle larger offsets for 64bit archs, this code
7182 * assumes that no offset can be an odd number and stores the
7183 * end-of-instructions flag in bit 0.
7186 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7187 #define CMDTXT_CHARPTR 0x40
7188 #define CMDTXT_STRING 0x80
7189 #define CMDTXT_SPECIAL 0xC0
7190 #define CMDTXT_OFFSETMASK 0x3E
7192 static const char * const cmdtxt_strings[] = {
7193 /* 0 1 2 3 4 5 6 7 */
7194 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7195 /* 8 9 10 11 12 13 */
7196 "while ", "; do ", "; done", "until ", "for ", " in ...",
7198 "case ", "???", "() ...", "<<..."
7201 static const char * const redir_strings[] = {
7202 ">", "<", "<>", ">>", ">|", ">&", "<&"
7205 static const unsigned char cmdtxt_ops[] = {
7206 #define CMDTXT_NSEMI 0
7207 offsetof(union node, nbinary.ch1),
7209 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7210 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7211 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7212 #define CMDTXT_NCASE (CMDTXT_NCMD)
7213 #define CMDTXT_NTO (CMDTXT_NCMD)
7214 #define CMDTXT_NFROM (CMDTXT_NCMD)
7215 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7216 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7217 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7218 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7219 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7221 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7222 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7223 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7224 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7225 (1*2)|CMDTXT_STRING,
7226 offsetof(union node, nredir.n),
7227 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7228 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7229 offsetof(union node, nbinary.ch1),
7230 (3*2)|CMDTXT_STRING,
7231 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7232 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7233 offsetof(union node, nbinary.ch1),
7234 (4*2)|CMDTXT_STRING,
7235 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7236 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7237 (5*2)|CMDTXT_STRING,
7238 offsetof(union node, nif.test),
7239 (6*2)|CMDTXT_STRING,
7240 offsetof(union node, nif.ifpart),
7241 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7242 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7243 (8*2)|CMDTXT_STRING,
7244 offsetof(union node, nbinary.ch1),
7245 (9*2)|CMDTXT_STRING,
7246 offsetof(union node, nbinary.ch2),
7247 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7248 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7249 (11*2)|CMDTXT_STRING,
7250 offsetof(union node, nbinary.ch1),
7251 (9*2)|CMDTXT_STRING,
7252 offsetof(union node, nbinary.ch2),
7253 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7254 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7255 (12*2)|CMDTXT_STRING,
7256 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7257 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7258 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7259 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7260 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7261 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7262 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7263 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7264 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7265 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7266 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7267 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7268 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7271 #if CMDTXT_NXHERE != 36
7272 #error CMDTXT_NXHERE
7275 static const unsigned char cmdtxt_ops_index[26] = {
7305 cmdtxt(const union node *n)
7312 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7313 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7315 if (*p & CMDTXT_STRING) { /* output fixed string */
7316 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7318 const char *pf = ((const char *) n)
7319 + ((int)(*p & CMDTXT_OFFSETMASK));
7320 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7321 cmdputs(*((const char **) pf));
7322 } else { /* output field */
7323 cmdtxt(*((const union node **) pf));
7326 } while (!(*p++ & CMDTXT_NOMORE));
7327 } else if (n->type == NCMD) {
7329 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7334 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7338 } else if (n->type == NPIPE) {
7339 struct nodelist *lp;
7340 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7345 } else if (n->type == NCASE) {
7346 cmdputs(cmdtxt_strings[14]);
7347 cmdputs(n->ncase.expr->narg.text);
7348 cmdputs(cmdtxt_strings[13]);
7350 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7351 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7356 assert((n->type >= NTO) && (n->type <= NFROMFD));
7359 p = redir_strings[n->type - NTO];
7360 if (n->nfile.fd != ('>' == *p)) {
7361 s[0] = n->nfile.fd + '0';
7366 if (n->type >= NTOFD) {
7367 s[0] = n->ndup.dupfd + '0';
7371 cmdtxt(n->nfile.fname);
7375 #else /* CMDTXT_TABLE */
7377 cmdtxt(const union node *n)
7380 struct nodelist *lp;
7389 cmdtxt(n->nbinary.ch1);
7391 cmdtxt(n->nbinary.ch2);
7394 cmdtxt(n->nbinary.ch1);
7396 cmdtxt(n->nbinary.ch2);
7399 cmdtxt(n->nbinary.ch1);
7401 cmdtxt(n->nbinary.ch2);
7404 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7412 cmdtxt(n->nredir.n);
7417 cmdtxt(n->nredir.n);
7421 cmdtxt(n->nif.test);
7423 cmdtxt(n->nif.ifpart);
7432 cmdtxt(n->nbinary.ch1);
7434 cmdtxt(n->nbinary.ch2);
7439 cmdputs(n->nfor.var);
7444 cmdputs(n->ncase.expr->narg.text);
7448 cmdputs(n->narg.text);
7452 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7457 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7463 cmdputs(n->narg.text);
7466 p = ">"; i = 1; goto redir;
7468 p = ">>"; i = 1; goto redir;
7470 p = ">&"; i = 1; goto redir;
7472 p = ">|"; i = 1; goto redir;
7474 p = "<"; i = 0; goto redir;
7476 p = "<&"; i = 0; goto redir;
7478 p = "<>"; i = 0; goto redir;
7480 if (n->nfile.fd != i) {
7481 s[0] = n->nfile.fd + '0';
7486 if (n->type == NTOFD || n->type == NFROMFD) {
7487 s[0] = n->ndup.dupfd + '0';
7491 cmdtxt(n->nfile.fname);
7503 #endif /* CMDTXT_TABLE */
7506 commandtext(const union node *n)
7510 cmdnextc = name = ckmalloc(MAXCMDTEXT);
7511 cmdnleft = MAXCMDTEXT - 4;
7518 static void waitonint(int sig) {
7526 * Routines to check for mail.
7530 #define MAXMBOXES 10
7533 static int nmboxes; /* number of mailboxes */
7534 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7539 * Print appropriate message(s) if mail has arrived. If the argument is
7540 * nozero, then the value of MAIL has changed, so we just update the
7551 struct stackmark smark;
7558 setstackmark(&smark);
7559 mpath = mpathset()? mpathval() : mailval();
7560 for (i = 0 ; i < nmboxes ; i++) {
7561 p = padvance(&mpath, nullstr);
7566 for (q = p ; *q ; q++);
7571 q[-1] = '\0'; /* delete trailing '/' */
7572 if (stat(p, &statb) < 0)
7574 if (statb.st_size > mailtime[i] && ! silent) {
7576 pathopt? pathopt : "you have mail");
7578 mailtime[i] = statb.st_size;
7581 popstackmark(&smark);
7584 #endif /* ASH_MAIL */
7589 static short profile_buf[16384];
7593 static void read_profile (const char *);
7594 static void cmdloop (int);
7595 static void options (int);
7596 static void setoption (int, int);
7597 static void procargs (int, char **);
7601 * Main routine. We initialize things, parse the arguments, execute
7602 * profiles if we're a login shell, and then call cmdloop to execute
7603 * commands. The setjmp call sets up the location to jump to when an
7604 * exception occurs. When an exception occurs the variable "state"
7605 * is used to figure out how far we had gotten.
7609 ash_main(argc, argv)
7613 struct jmploc jmploc;
7614 struct stackmark smark;
7618 BLTINCMD = find_builtin("builtin");
7619 EXECCMD = find_builtin("exec");
7620 EVALCMD = find_builtin("eval");
7622 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7628 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7630 #if defined(linux) || defined(__GNU__)
7631 signal(SIGCHLD, SIG_DFL);
7634 if (setjmp(jmploc.loc)) {
7637 * When a shell procedure is executed, we raise the
7638 * exception EXSHELLPROC to clean up before executing
7639 * the shell procedure.
7641 if (exception == EXSHELLPROC) {
7647 if (exception == EXEXEC) {
7648 exitstatus = exerrno;
7649 } else if (exception == EXERROR) {
7652 if (state == 0 || iflag == 0 || ! rootshell)
7653 exitshell(exitstatus);
7656 if (exception == EXINT) {
7659 popstackmark(&smark);
7660 FORCEINTON; /* enable interrupts */
7663 else if (state == 2)
7665 else if (state == 3)
7673 trputs("Shell args: "); trargs(argv);
7678 setstackmark(&smark);
7679 procargs(argc, argv);
7680 if (argv[0] && argv[0][0] == '-') {
7682 read_profile("/etc/profile");
7685 read_profile(".profile");
7690 if (getuid() == geteuid() && getgid() == getegid()) {
7692 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7694 read_profile(shinit);
7701 if (sflag == 0 || minusc) {
7702 static const char sigs[] = {
7703 SIGINT, SIGQUIT, SIGHUP,
7709 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7712 for (i = 0; i < SIGSSIZE; i++)
7717 evalstring(minusc, 0);
7719 if (sflag || minusc == NULL) {
7720 state4: /* XXX ??? - why isn't this before the "if" statement */
7726 exitshell(exitstatus);
7732 * Read and execute commands. "Top" is nonzero for the top level command
7733 * loop; it turns on prompting if the shell is interactive.
7740 struct stackmark smark;
7744 TRACE(("cmdloop(%d) called\n", top));
7745 setstackmark(&smark);
7758 n = parsecmd(inter);
7759 /* showtree(n); DEBUG */
7761 if (!top || numeof >= 50)
7763 if (!stoppedjobs()) {
7766 out2str("\nUse \"exit\" to leave shell.\n");
7769 } else if (n != NULL && nflag == 0) {
7770 job_warning = (job_warning == 2) ? 1 : 0;
7774 popstackmark(&smark);
7775 setstackmark(&smark);
7776 if (evalskip == SKIPFILE) {
7781 popstackmark(&smark);
7787 * Read /etc/profile or .profile. Return on error.
7799 if ((fd = open(name, O_RDONLY)) >= 0)
7804 /* -q turns off -x and -v just when executing init files */
7805 /* Note: Might do a little redundant work, but reduces code size. */
7820 * Read a file containing shell functions.
7824 readcmdfile(const char *name)
7829 if ((fd = open(name, O_RDONLY)) >= 0)
7832 error("Can't open %s", name);
7841 * Take commands from a file. To be compatable we should do a path
7842 * search for the file, which is necessary to find sub-commands.
7845 static inline char *
7846 find_dot_file(char *mybasename)
7849 const char *path = pathval();
7852 /* don't try this for absolute or relative paths */
7853 if (strchr(mybasename, '/'))
7856 while ((fullname = padvance(&path, mybasename)) != NULL) {
7857 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7859 * Don't bother freeing here, since it will
7860 * be freed by the caller.
7864 stunalloc(fullname);
7867 /* not found in the PATH */
7868 error("%s: not found", mybasename);
7878 volatile struct shparam saveparam;
7881 for (sp = cmdenviron; sp ; sp = sp->next)
7882 setvareq(savestr(sp->text), VSTRFIXED|VTEXTFIXED);
7884 if (argc >= 2) { /* That's what SVR2 does */
7886 struct stackmark smark;
7888 setstackmark(&smark);
7889 fullname = find_dot_file(argv[1]);
7892 saveparam = shellparam;
7893 shellparam.malloc = 0;
7894 shellparam.nparam = argc - 2;
7895 shellparam.p = argv + 2;
7898 setinputfile(fullname, 1);
7899 commandname = fullname;
7904 freeparam(&shellparam);
7905 shellparam = saveparam;
7908 popstackmark(&smark);
7922 exitstatus = number(argv[1]);
7924 exitstatus = oexitstatus;
7925 exitshell(exitstatus);
7934 nbytes = ALIGN(nbytes);
7935 if (nbytes > stacknleft) {
7937 struct stack_block *sp;
7940 if (blocksize < MINSIZE)
7941 blocksize = MINSIZE;
7943 sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7945 stacknxt = sp->space;
7946 stacknleft = blocksize;
7952 stacknleft -= nbytes;
7958 stunalloc(pointer p)
7961 if (p == NULL) { /*DEBUG */
7962 write(2, "stunalloc\n", 10);
7966 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7969 stacknleft += stacknxt - (char *)p;
7975 setstackmark(struct stackmark *mark)
7977 mark->stackp = stackp;
7978 mark->stacknxt = stacknxt;
7979 mark->stacknleft = stacknleft;
7980 mark->marknext = markp;
7986 popstackmark(struct stackmark *mark)
7988 struct stack_block *sp;
7991 markp = mark->marknext;
7992 while (stackp != mark->stackp) {
7997 stacknxt = mark->stacknxt;
7998 stacknleft = mark->stacknleft;
8004 * When the parser reads in a string, it wants to stick the string on the
8005 * stack and only adjust the stack pointer when it knows how big the
8006 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8007 * of space on top of the stack and stackblocklen returns the length of
8008 * this block. Growstackblock will grow this space by at least one byte,
8009 * possibly moving it (like realloc). Grabstackblock actually allocates the
8010 * part of the block that has been used.
8014 growstackblock(void) {
8016 int newlen = ALIGN(stacknleft * 2 + 100);
8017 char *oldspace = stacknxt;
8018 int oldlen = stacknleft;
8019 struct stack_block *sp;
8020 struct stack_block *oldstackp;
8022 if (stacknxt == stackp->space && stackp != &stackbase) {
8027 sp = ckrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
8030 stacknxt = sp->space;
8031 stacknleft = newlen;
8033 /* Stack marks pointing to the start of the old block
8034 * must be relocated to point to the new block
8036 struct stackmark *xmark;
8038 while (xmark != NULL && xmark->stackp == oldstackp) {
8039 xmark->stackp = stackp;
8040 xmark->stacknxt = stacknxt;
8041 xmark->stacknleft = stacknleft;
8042 xmark = xmark->marknext;
8047 p = stalloc(newlen);
8048 memcpy(p, oldspace, oldlen);
8049 stacknxt = p; /* free the space */
8050 stacknleft += newlen; /* we just allocated */
8057 grabstackblock(int len)
8067 * The following routines are somewhat easier to use that the above.
8068 * The user declares a variable of type STACKSTR, which may be declared
8069 * to be a register. The macro STARTSTACKSTR initializes things. Then
8070 * the user uses the macro STPUTC to add characters to the string. In
8071 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8072 * grown as necessary. When the user is done, she can just leave the
8073 * string there and refer to it using stackblock(). Or she can allocate
8074 * the space for it using grabstackstr(). If it is necessary to allow
8075 * someone else to use the stack temporarily and then continue to grow
8076 * the string, the user should use grabstack to allocate the space, and
8077 * then call ungrabstr(p) to return to the previous mode of operation.
8079 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8080 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8081 * is space for at least one character.
8086 growstackstr(void) {
8087 int len = stackblocksize();
8088 if (herefd >= 0 && len >= 1024) {
8089 xwrite(herefd, stackblock(), len);
8090 sstrnleft = len - 1;
8091 return stackblock();
8094 sstrnleft = stackblocksize() - len - 1;
8095 return stackblock() + len;
8100 * Called from CHECKSTRSPACE.
8104 makestrspace(size_t newlen) {
8105 int len = stackblocksize() - sstrnleft;
8108 sstrnleft = stackblocksize() - len;
8109 } while (sstrnleft < newlen);
8110 return stackblock() + len;
8116 ungrabstackstr(char *s, char *p)
8118 stacknleft += stacknxt - s;
8120 sstrnleft = stacknleft - (p - s);
8123 * Miscelaneous builtins.
8129 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8130 typedef long rlim_t;
8136 * The read builtin. The -e option causes backslashes to escape the
8137 * following character.
8139 * This uses unbuffered input, which may be avoidable in some cases.
8143 readcmd(int argc, char **argv)
8158 while ((i = nextopt("p:r")) != '\0') {
8164 if (prompt && isatty(0)) {
8165 out2str(prompt); /* read without cmdedit */
8168 if (*(ap = argptr) == NULL)
8170 if ((ifs = bltinlookup("IFS")) == NULL)
8177 if (read(0, &c, 1) != 1) {
8189 if (!rflag && c == '\\') {
8195 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8199 if (backslash && c == '\\') {
8200 if (read(0, &c, 1) != 1) {
8205 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8207 setvar(*ap, stackblock(), 0);
8216 /* Remove trailing blanks */
8217 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8219 setvar(*ap, stackblock(), 0);
8220 while (*++ap != NULL)
8221 setvar(*ap, nullstr, 0);
8228 umaskcmd(argc, argv)
8232 static const char permuser[3] = "ugo";
8233 static const char permmode[3] = "rwx";
8234 static const short int permmask[] = {
8235 S_IRUSR, S_IWUSR, S_IXUSR,
8236 S_IRGRP, S_IWGRP, S_IXGRP,
8237 S_IROTH, S_IWOTH, S_IXOTH
8243 int symbolic_mode = 0;
8245 while (nextopt("S") != '\0') {
8254 if ((ap = *argptr) == NULL) {
8255 if (symbolic_mode) {
8258 for (i=0 ; i<3 ; i++) {
8262 for (j=0 ; j<3 ; j++) {
8263 if ((mask & permmask[3*i+j]) == 0) {
8272 printf("%.4o\n", mask);
8275 if (is_digit((unsigned char)*ap)) {
8278 if (*ap >= '8' || *ap < '0')
8279 error("Illegal number: %s", argv[1]);
8280 mask = (mask << 3) + (*ap - '0');
8281 } while (*++ap != '\0');
8284 mask = ~mask & 0777;
8285 if (parse_mode(ap, &mask) == FALSE) {
8286 error("Illegal mode: %s", ap);
8288 umask(~mask & 0777);
8297 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8298 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8299 * ash by J.T. Conklin.
8307 short factor; /* multiply by to get rlim_{cur,max} values */
8310 static const struct limits limits[] = {
8312 { "time(seconds)", RLIMIT_CPU, 1 },
8315 { "file(blocks)", RLIMIT_FSIZE, 512 },
8318 { "data(kbytes)", RLIMIT_DATA, 1024 },
8321 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8324 { "coredump(blocks)", RLIMIT_CORE, 512 },
8327 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8329 #ifdef RLIMIT_MEMLOCK
8330 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8333 { "process(processes)", RLIMIT_NPROC, 1 },
8335 #ifdef RLIMIT_NOFILE
8336 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8339 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8342 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8348 ulimitcmd(argc, argv)
8352 static const char unlimited_string[] = "unlimited";
8355 enum { SOFT = 0x1, HARD = 0x2 }
8357 const struct limits *l;
8360 struct rlimit limit;
8364 while ((optc = nextopt("HSa"
8383 #ifdef RLIMIT_MEMLOCK
8389 #ifdef RLIMIT_NOFILE
8401 } else if (optc == 'S') {
8403 } else if (optc == 'a') {
8410 for (l = limits; l->name; l++) {
8411 if(l->name[0] == what)
8413 if(l->name[1]=='w' && what=='w')
8417 set = *argptr ? 1 : 0;
8421 if (all || argptr[1])
8422 error("too many arguments");
8423 if (strcmp(p, unlimited_string) == 0)
8424 val = RLIM_INFINITY;
8428 while ((c = *p++) >= '0' && c <= '9')
8430 val = (val * 10) + (long)(c - '0');
8431 if (val < (rlim_t) 0)
8435 error("bad number");
8441 for (l = limits; l->name; l++) {
8442 printf("%-20s ", l->name);
8443 getrlimit(l->cmd, &limit);
8446 val = limit.rlim_cur;
8447 else if (how & HARD)
8448 val = limit.rlim_max;
8450 if (val == RLIM_INFINITY)
8451 puts(unlimited_string);
8455 printf("%lld\n", (long long) val);
8468 getrlimit(l->cmd, &limit);
8470 limit.rlim_max = val;
8472 limit.rlim_cur = val;
8473 if (setrlimit(l->cmd, &limit) < 0)
8474 error("error setting limit (%m)");
8478 * prefix -- see if pfx is a prefix of string.
8482 prefix(char const *pfx, char const *string)
8485 if (*pfx++ != *string++)
8492 * Return true if s is a string of digits, and save munber in intptr
8497 is_number(const char *p, int *intptr)
8505 ret += digit_val(*p);
8507 } while (*p != '\0');
8514 * Convert a string of digits to an integer, printing an error message on
8519 number(const char *s)
8522 if (! is_number(s, &i))
8523 error("Illegal number: %s", s);
8528 * Produce a possibly single quoted string suitable as input to the shell.
8529 * The return string is allocated on the stack.
8533 single_quote(const char *s) {
8540 size_t len1, len1p, len2, len2p;
8542 len1 = strcspn(s, "'");
8543 len2 = strspn(s + len1, "'");
8545 len1p = len1 ? len1 + 2 : len1;
8546 len2p = len2 + ((len2 < 2) ? len2 : 2);
8548 CHECKSTRSPACE(len1p + len2p + 1, p);
8553 memcpy(p + 1, s, len1);
8561 memcpy(q + 1, s, len2);
8564 } else if (len2 == 1) {
8570 STADJUST(len1p + len2p, p);
8575 return grabstackstr(p);
8579 * Like strdup but works with the ash stack.
8583 sstrdup(const char *p)
8585 size_t len = strlen(p) + 1;
8586 return memcpy(stalloc(len), p, len);
8591 * Routine for dealing with parsed shell commands.
8595 static void sizenodelist (const struct nodelist *);
8596 static struct nodelist *copynodelist (const struct nodelist *);
8597 static char *nodesavestr (const char *);
8599 #define CALCSIZE_TABLE
8600 #define COPYNODE_TABLE
8601 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8603 * To collect a lot of redundant code in case statements for copynode()
8604 * and calcsize(), we implement a mini language here. Each type of node
8605 * struct has an associated instruction sequence that operates on its
8606 * members via their offsets. The instruction are pack in unsigned chars
8607 * with format IIDDDDDE where the bits are
8608 * I : part of the instruction opcode, which are
8609 * 00 : member is a pointer to another node
8610 * 40 : member is an integer
8611 * 80 : member is a pointer to a nodelist
8612 * CC : member is a pointer to a char string
8613 * D : data - the actual offset of the member to operate on in the struct
8614 * (since we assume bit 0 is set, it is not shifted)
8615 * E : flag signaling end of instruction sequence
8617 * WARNING: In order to handle larger offsets for 64bit archs, this code
8618 * assumes that no offset can be an odd number and stores the
8619 * end-of-instructions flag in bit 0.
8622 #define NODE_INTEGER 0x40
8623 #define NODE_NODELIST 0x80
8624 #define NODE_CHARPTR 0xC0
8625 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8626 #define NODE_MBRMASK 0xC0
8627 #define NODE_OFFSETMASK 0x3E
8629 static const unsigned char copynode_ops[35] = {
8630 #define COPYNODE_OPS0 0
8631 offsetof(union node, nbinary.ch2),
8632 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8633 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8634 offsetof(union node, ncmd.redirect),
8635 offsetof(union node, ncmd.args),
8636 offsetof(union node, ncmd.assign),
8637 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8638 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8639 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8640 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8641 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8642 offsetof(union node, nredir.redirect),
8643 offsetof(union node, nredir.n)|NODE_NOMORE,
8644 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8645 offsetof(union node, nif.elsepart),
8646 offsetof(union node, nif.ifpart),
8647 offsetof(union node, nif.test)|NODE_NOMORE,
8648 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8649 offsetof(union node, nfor.var)|NODE_CHARPTR,
8650 offsetof(union node, nfor.body),
8651 offsetof(union node, nfor.args)|NODE_NOMORE,
8652 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8653 offsetof(union node, ncase.cases),
8654 offsetof(union node, ncase.expr)|NODE_NOMORE,
8655 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8656 offsetof(union node, nclist.body),
8657 offsetof(union node, nclist.pattern),
8658 offsetof(union node, nclist.next)|NODE_NOMORE,
8659 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8660 offsetof(union node, narg.backquote)|NODE_NODELIST,
8661 offsetof(union node, narg.text)|NODE_CHARPTR,
8662 offsetof(union node, narg.next)|NODE_NOMORE,
8663 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8664 offsetof(union node, nfile.fname),
8665 offsetof(union node, nfile.fd)|NODE_INTEGER,
8666 offsetof(union node, nfile.next)|NODE_NOMORE,
8667 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8668 offsetof(union node, ndup.vname),
8669 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8670 offsetof(union node, ndup.fd)|NODE_INTEGER,
8671 offsetof(union node, ndup.next)|NODE_NOMORE,
8672 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8673 offsetof(union node, nhere.doc),
8674 offsetof(union node, nhere.fd)|NODE_INTEGER,
8675 offsetof(union node, nhere.next)|NODE_NOMORE,
8676 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8677 offsetof(union node, nnot.com)|NODE_NOMORE,
8680 #if COPYNODE_OPS12 != 34
8681 #error COPYNODE_OPS12 is incorrect
8684 static const unsigned char copynode_ops_index[26] = {
8685 COPYNODE_OPS0, /* NSEMI */
8686 COPYNODE_OPS1, /* NCMD */
8687 COPYNODE_OPS2, /* NPIPE */
8688 COPYNODE_OPS3, /* NREDIR */
8689 COPYNODE_OPS3, /* NBACKGND */
8690 COPYNODE_OPS3, /* NSUBSHELL */
8691 COPYNODE_OPS0, /* NAND */
8692 COPYNODE_OPS0, /* NOR */
8693 COPYNODE_OPS4, /* NIF */
8694 COPYNODE_OPS0, /* NWHILE */
8695 COPYNODE_OPS0, /* NUNTIL */
8696 COPYNODE_OPS5, /* NFOR */
8697 COPYNODE_OPS6, /* NCASE */
8698 COPYNODE_OPS7, /* NCLIST */
8699 COPYNODE_OPS8, /* NDEFUN */
8700 COPYNODE_OPS8, /* NARG */
8701 COPYNODE_OPS9, /* NTO */
8702 COPYNODE_OPS9, /* NFROM */
8703 COPYNODE_OPS9, /* NFROMTO */
8704 COPYNODE_OPS9, /* NAPPEND */
8705 COPYNODE_OPS9, /* NTOOV */
8706 COPYNODE_OPS10, /* NTOFD */
8707 COPYNODE_OPS10, /* NFROMFD */
8708 COPYNODE_OPS11, /* NHERE */
8709 COPYNODE_OPS11, /* NXHERE */
8710 COPYNODE_OPS12, /* NNOT */
8713 #if NODE_CHARPTR != NODE_MBRMASK
8714 #error NODE_CHARPTR != NODE_MBRMASK!!!
8716 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8718 #ifdef COPYNODE_TABLE
8720 copynode(const union node *n)
8723 const unsigned char *p;
8729 new->type = n->type;
8730 funcblock = (char *) funcblock + (int) nodesize[n->type];
8731 p = copynode_ops + (int) copynode_ops_index[n->type];
8733 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8734 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8736 if (!(*p & NODE_MBRMASK)) { /* standard node */
8737 *((union node **)nn) = copynode(*((const union node **) no));
8738 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8739 *((const char **)nn) = nodesavestr(*((const char **)no));
8740 } else if (*p & NODE_NODELIST) { /* nodelist */
8741 *((struct nodelist **)nn)
8742 = copynodelist(*((const struct nodelist **) no));
8743 } else { /* integer */
8744 *((int *) nn) = *((int *) no);
8746 } while (!(*p++ & NODE_NOMORE));
8749 #else /* COPYNODE_TABLE */
8751 copynode(const union node *n)
8758 funcblock = (char *) funcblock + nodesize[n->type];
8765 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8766 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8769 new->ncmd.redirect = copynode(n->ncmd.redirect);
8770 new->ncmd.args = copynode(n->ncmd.args);
8771 new->ncmd.assign = copynode(n->ncmd.assign);
8772 new->ncmd.backgnd = n->ncmd.backgnd;
8775 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8776 new->npipe.backgnd = n->npipe.backgnd;
8781 new->nredir.redirect = copynode(n->nredir.redirect);
8782 new->nredir.n = copynode(n->nredir.n);
8785 new->nif.elsepart = copynode(n->nif.elsepart);
8786 new->nif.ifpart = copynode(n->nif.ifpart);
8787 new->nif.test = copynode(n->nif.test);
8790 new->nfor.var = nodesavestr(n->nfor.var);
8791 new->nfor.body = copynode(n->nfor.body);
8792 new->nfor.args = copynode(n->nfor.args);
8795 new->ncase.cases = copynode(n->ncase.cases);
8796 new->ncase.expr = copynode(n->ncase.expr);
8799 new->nclist.body = copynode(n->nclist.body);
8800 new->nclist.pattern = copynode(n->nclist.pattern);
8801 new->nclist.next = copynode(n->nclist.next);
8805 new->narg.backquote = copynodelist(n->narg.backquote);
8806 new->narg.text = nodesavestr(n->narg.text);
8807 new->narg.next = copynode(n->narg.next);
8814 new->nfile.fname = copynode(n->nfile.fname);
8815 new->nfile.fd = n->nfile.fd;
8816 new->nfile.next = copynode(n->nfile.next);
8820 new->ndup.vname = copynode(n->ndup.vname);
8821 new->ndup.dupfd = n->ndup.dupfd;
8822 new->ndup.fd = n->ndup.fd;
8823 new->ndup.next = copynode(n->ndup.next);
8827 new->nhere.doc = copynode(n->nhere.doc);
8828 new->nhere.fd = n->nhere.fd;
8829 new->nhere.next = copynode(n->nhere.next);
8832 new->nnot.com = copynode(n->nnot.com);
8835 new->type = n->type;
8838 #endif /* COPYNODE_TABLE */
8840 #ifdef CALCSIZE_TABLE
8842 calcsize(const union node *n)
8844 const unsigned char *p;
8848 funcblocksize += (int) nodesize[n->type];
8850 p = copynode_ops + (int) copynode_ops_index[n->type];
8852 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8854 if (!(*p & NODE_MBRMASK)) { /* standard node */
8855 calcsize(*((const union node **) no));
8856 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8857 funcstringsize += strlen(*((const char **)no)) + 1;
8858 } else if (*p & NODE_NODELIST) { /* nodelist */
8859 sizenodelist(*((const struct nodelist **) no));
8860 } /* else integer -- ignore */
8861 } while (!(*p++ & NODE_NOMORE));
8863 #else /* CALCSIZE_TABLE */
8865 calcsize(const union node *n)
8869 funcblocksize += nodesize[n->type];
8876 calcsize(n->nbinary.ch2);
8877 calcsize(n->nbinary.ch1);
8880 calcsize(n->ncmd.redirect);
8881 calcsize(n->ncmd.args);
8882 calcsize(n->ncmd.assign);
8885 sizenodelist(n->npipe.cmdlist);
8890 calcsize(n->nredir.redirect);
8891 calcsize(n->nredir.n);
8894 calcsize(n->nif.elsepart);
8895 calcsize(n->nif.ifpart);
8896 calcsize(n->nif.test);
8899 funcstringsize += strlen(n->nfor.var) + 1;
8900 calcsize(n->nfor.body);
8901 calcsize(n->nfor.args);
8904 calcsize(n->ncase.cases);
8905 calcsize(n->ncase.expr);
8908 calcsize(n->nclist.body);
8909 calcsize(n->nclist.pattern);
8910 calcsize(n->nclist.next);
8914 sizenodelist(n->narg.backquote);
8915 funcstringsize += strlen(n->narg.text) + 1;
8916 calcsize(n->narg.next);
8923 calcsize(n->nfile.fname);
8924 calcsize(n->nfile.next);
8928 calcsize(n->ndup.vname);
8929 calcsize(n->ndup.next);
8933 calcsize(n->nhere.doc);
8934 calcsize(n->nhere.next);
8937 calcsize(n->nnot.com);
8941 #endif /* CALCSIZE_TABLE */
8944 sizenodelist(const struct nodelist *lp)
8947 funcblocksize += ALIGN(sizeof(struct nodelist));
8954 static struct nodelist *
8955 copynodelist(const struct nodelist *lp)
8957 struct nodelist *start;
8958 struct nodelist **lpp;
8963 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8964 (*lpp)->n = copynode(lp->n);
8966 lpp = &(*lpp)->next;
8974 nodesavestr(const char *s)
8977 char *q = funcstring;
8978 char *rtn = funcstring;
8980 while ((*q++ = *p++) != '\0')
8987 static int getopts (char *, char *, char **, int *, int *);
8992 * Process the shell command line arguments.
8996 procargs(argc, argv)
9005 for (i = 0; i < NOPTS; i++)
9008 if (*argptr == NULL && minusc == NULL)
9010 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
9014 for (i = 0; i < NOPTS; i++)
9015 if (optent_val(i) == 2)
9018 if (sflag == 0 && minusc == NULL) {
9019 commandname = argv[0];
9021 setinputfile(arg0, 0);
9024 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
9025 if (argptr && minusc && *argptr)
9028 shellparam.p = argptr;
9029 shellparam.optind = 1;
9030 shellparam.optoff = -1;
9031 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
9033 shellparam.nparam++;
9042 * Process shell options. The global variable argptr contains a pointer
9043 * to the argument list; we advance it past the options.
9047 minus_o(const char *name, int val)
9052 out1str("Current option settings\n");
9053 for (i = 0; i < NOPTS; i++)
9054 printf("%-16s%s\n", optent_name(optlist[i]),
9055 optent_val(i) ? "on" : "off");
9057 for (i = 0; i < NOPTS; i++)
9058 if (equal(name, optent_name(optlist[i]))) {
9059 setoption(optent_letter(optlist[i]), val);
9062 error("Illegal option -o %s", name);
9068 options(int cmdline)
9076 while ((p = *argptr) != NULL) {
9078 if ((c = *p++) == '-') {
9080 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
9082 /* "-" means turn off -x and -v */
9085 /* "--" means reset params */
9086 else if (*argptr == NULL)
9089 break; /* "-" or "--" terminates options */
9091 } else if (c == '+') {
9097 while ((c = *p++) != '\0') {
9098 if (c == 'c' && cmdline) {
9100 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
9104 if (q == NULL || minusc != NULL)
9105 error("Bad -c option");
9110 } else if (c == 'o') {
9111 minus_o(*argptr, val);
9123 setoption(int flag, int val)
9127 for (i = 0; i < NOPTS; i++)
9128 if (optent_letter(optlist[i]) == flag) {
9129 optent_val(i) = val;
9131 /* #%$ hack for ksh semantics */
9134 else if (flag == 'E')
9139 error("Illegal option -%c", flag);
9146 * Set the shell parameters.
9150 setparam(char **argv)
9156 for (nparam = 0 ; argv[nparam] ; nparam++);
9157 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
9159 *ap++ = savestr(*argv++);
9162 freeparam(&shellparam);
9163 shellparam.malloc = 1;
9164 shellparam.nparam = nparam;
9165 shellparam.p = newparam;
9166 shellparam.optind = 1;
9167 shellparam.optoff = -1;
9172 * Free the list of positional parameters.
9176 freeparam(volatile struct shparam *param)
9180 if (param->malloc) {
9181 for (ap = param->p ; *ap ; ap++)
9190 * The shift builtin command.
9194 shiftcmd(argc, argv)
9203 n = number(argv[1]);
9204 if (n > shellparam.nparam)
9205 error("can't shift that many");
9207 shellparam.nparam -= n;
9208 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9209 if (shellparam.malloc)
9213 while ((*ap2++ = *ap1++) != NULL);
9214 shellparam.optind = 1;
9215 shellparam.optoff = -1;
9223 * The set command builtin.
9232 return showvarscmd(argc, argv);
9236 if (*argptr != NULL) {
9245 getoptsreset(const char *value)
9247 shellparam.optind = number(value);
9248 shellparam.optoff = -1;
9251 #ifdef CONFIG_LOCALE_SUPPORT
9252 static void change_lc_all(const char *value)
9254 if(value != 0 && *value != 0)
9255 setlocale(LC_ALL, value);
9258 static void change_lc_ctype(const char *value)
9260 if(value != 0 && *value != 0)
9261 setlocale(LC_CTYPE, value);
9268 * The getopts builtin. Shellparam.optnext points to the next argument
9269 * to be processed. Shellparam.optptr points to the next character to
9270 * be processed in the current argument. If shellparam.optnext is NULL,
9271 * then it's the first time getopts has been called.
9275 getoptscmd(argc, argv)
9282 error("Usage: getopts optstring var [arg]");
9283 else if (argc == 3) {
9284 optbase = shellparam.p;
9285 if (shellparam.optind > shellparam.nparam + 1) {
9286 shellparam.optind = 1;
9287 shellparam.optoff = -1;
9292 if (shellparam.optind > argc - 2) {
9293 shellparam.optind = 1;
9294 shellparam.optoff = -1;
9298 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9299 &shellparam.optoff);
9303 * Safe version of setvar, returns 1 on success 0 on failure.
9307 setvarsafe(name, val, flags)
9308 const char *name, *val;
9311 struct jmploc jmploc;
9312 struct jmploc *volatile savehandler = handler;
9318 if (setjmp(jmploc.loc))
9322 setvar(name, val, flags);
9324 handler = savehandler;
9329 getopts(optstr, optvar, optfirst, myoptind, optoff)
9341 char **optnext = optfirst + *myoptind - 1;
9343 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9344 strlen(*(optnext - 1)) < *optoff)
9347 p = *(optnext - 1) + *optoff;
9348 if (p == NULL || *p == '\0') {
9349 /* Current word is done, advance */
9350 if (optnext == NULL)
9353 if (p == NULL || *p != '-' || *++p == '\0') {
9355 *myoptind = optnext - optfirst + 1;
9361 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9366 for (q = optstr; *q != c; ) {
9368 if (optstr[0] == ':') {
9371 err |= setvarsafe("OPTARG", s, 0);
9374 out2fmt("Illegal option -%c\n", c);
9375 (void) unsetvar("OPTARG");
9385 if (*p == '\0' && (p = *optnext) == NULL) {
9386 if (optstr[0] == ':') {
9389 err |= setvarsafe("OPTARG", s, 0);
9393 out2fmt("No arg for -%c option\n", c);
9394 (void) unsetvar("OPTARG");
9402 setvarsafe("OPTARG", p, 0);
9406 setvarsafe("OPTARG", "", 0);
9407 *myoptind = optnext - optfirst + 1;
9414 *optoff = p ? p - *(optnext - 1) : -1;
9415 snprintf(s, sizeof(s), "%d", *myoptind);
9416 err |= setvarsafe("OPTIND", s, VNOFUNC);
9419 err |= setvarsafe(optvar, s, 0);
9430 * XXX - should get rid of. have all builtins use getopt(3). the
9431 * library getopt must have the BSD extension static variable "optreset"
9432 * otherwise it can't be used within the shell safely.
9434 * Standard option processing (a la getopt) for builtin routines. The
9435 * only argument that is passed to nextopt is the option string; the
9436 * other arguments are unnecessary. It return the character, or '\0' on
9441 nextopt(const char *optstring)
9447 if ((p = optptr) == NULL || *p == '\0') {
9449 if (p == NULL || *p != '-' || *++p == '\0')
9452 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9456 for (q = optstring ; *q != c ; ) {
9458 error("Illegal option -%c", c);
9463 if (*p == '\0' && (p = *argptr++) == NULL)
9464 error("No arg for -%c option", c);
9481 out2fmt(const char *fmt, ...)
9485 vfprintf(stderr, fmt, ap);
9490 * Version of write which resumes after a signal is caught.
9494 xwrite(int fd, const char *buf, int nbytes)
9503 i = write(fd, buf, n);
9509 } else if (i == 0) {
9512 } else if (errno != EINTR) {
9520 * Shell command parser.
9523 #define EOFMARKLEN 79
9528 struct heredoc *next; /* next here document in list */
9529 union node *here; /* redirection node */
9530 char *eofmark; /* string indicating end of input */
9531 int striptabs; /* if set, strip leading tabs */
9534 static struct heredoc *heredoclist; /* list of here documents to read */
9535 static int parsebackquote; /* nonzero if we are inside backquotes */
9536 static int doprompt; /* if set, prompt the user */
9537 static int needprompt; /* true if interactive and at start of line */
9538 static int lasttoken; /* last token read */
9540 static char *wordtext; /* text of last word returned by readtoken */
9542 static struct nodelist *backquotelist;
9543 static union node *redirnode;
9544 static struct heredoc *heredoc;
9545 static int quoteflag; /* set if (part of) last token was quoted */
9546 static int startlinno; /* line # where last token started */
9549 static union node *list (int);
9550 static union node *andor (void);
9551 static union node *pipeline (void);
9552 static union node *command (void);
9553 static union node *simplecmd(union node **rpp, union node *redir);
9554 static void parsefname (void);
9555 static void parseheredoc (void);
9556 static char peektoken (void);
9557 static int readtoken (void);
9558 static int xxreadtoken (void);
9559 static int readtoken1 (int, int, const char *, int);
9560 static int noexpand (char *);
9561 static void synexpect (int) __attribute__((noreturn));
9562 static void synerror (const char *) __attribute__((noreturn));
9563 static void setprompt (int);
9567 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9568 * valid parse tree indicating a blank line.)
9572 parsecmd(int interact)
9577 doprompt = interact;
9597 union node *n1, *n2, *n3;
9601 if (nlflag == 0 && peektoken())
9607 if (tok == TBACKGND) {
9608 if (n2->type == NCMD || n2->type == NPIPE) {
9609 n2->ncmd.backgnd = 1;
9610 } else if (n2->type == NREDIR) {
9611 n2->type = NBACKGND;
9613 n3 = (union node *)stalloc(sizeof (struct nredir));
9614 n3->type = NBACKGND;
9616 n3->nredir.redirect = NULL;
9624 n3 = (union node *)stalloc(sizeof (struct nbinary));
9626 n3->nbinary.ch1 = n1;
9627 n3->nbinary.ch2 = n2;
9651 pungetc(); /* push back EOF on input */
9666 union node *n1, *n2, *n3;
9672 if ((t = readtoken()) == TAND) {
9674 } else if (t == TOR) {
9682 n3 = (union node *)stalloc(sizeof (struct nbinary));
9684 n3->nbinary.ch1 = n1;
9685 n3->nbinary.ch2 = n2;
9694 union node *n1, *n2, *pipenode;
9695 struct nodelist *lp, *prev;
9699 TRACE(("pipeline: entered\n"));
9700 if (readtoken() == TNOT) {
9706 if (readtoken() == TPIPE) {
9707 pipenode = (union node *)stalloc(sizeof (struct npipe));
9708 pipenode->type = NPIPE;
9709 pipenode->npipe.backgnd = 0;
9710 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9711 pipenode->npipe.cmdlist = lp;
9715 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9719 } while (readtoken() == TPIPE);
9725 n2 = (union node *)stalloc(sizeof (struct nnot));
9737 union node *n1, *n2;
9738 union node *ap, **app;
9739 union node *cp, **cpp;
9740 union node *redir, **rpp;
9747 /* Check for redirection which may precede command */
9748 while (readtoken() == TREDIR) {
9749 *rpp = n2 = redirnode;
9750 rpp = &n2->nfile.next;
9755 switch (readtoken()) {
9757 n1 = (union node *)stalloc(sizeof (struct nif));
9759 n1->nif.test = list(0);
9760 if (readtoken() != TTHEN)
9762 n1->nif.ifpart = list(0);
9764 while (readtoken() == TELIF) {
9765 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9766 n2 = n2->nif.elsepart;
9768 n2->nif.test = list(0);
9769 if (readtoken() != TTHEN)
9771 n2->nif.ifpart = list(0);
9773 if (lasttoken == TELSE)
9774 n2->nif.elsepart = list(0);
9776 n2->nif.elsepart = NULL;
9779 if (readtoken() != TFI)
9786 n1 = (union node *)stalloc(sizeof (struct nbinary));
9787 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9788 n1->nbinary.ch1 = list(0);
9789 if ((got=readtoken()) != TDO) {
9790 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9793 n1->nbinary.ch2 = list(0);
9794 if (readtoken() != TDONE)
9800 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9801 synerror("Bad for loop variable");
9802 n1 = (union node *)stalloc(sizeof (struct nfor));
9804 n1->nfor.var = wordtext;
9806 if (readtoken() == TIN) {
9808 while (readtoken() == TWORD) {
9809 n2 = (union node *)stalloc(sizeof (struct narg));
9811 n2->narg.text = wordtext;
9812 n2->narg.backquote = backquotelist;
9814 app = &n2->narg.next;
9818 if (lasttoken != TNL && lasttoken != TSEMI)
9821 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9823 n2 = (union node *)stalloc(sizeof (struct narg));
9825 n2->narg.text = argvars;
9826 n2->narg.backquote = NULL;
9827 n2->narg.next = NULL;
9830 * Newline or semicolon here is optional (but note
9831 * that the original Bourne shell only allowed NL).
9833 if (lasttoken != TNL && lasttoken != TSEMI)
9837 if (readtoken() != TDO)
9839 n1->nfor.body = list(0);
9840 if (readtoken() != TDONE)
9845 n1 = (union node *)stalloc(sizeof (struct ncase));
9847 if (readtoken() != TWORD)
9849 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9851 n2->narg.text = wordtext;
9852 n2->narg.backquote = backquotelist;
9853 n2->narg.next = NULL;
9856 } while (readtoken() == TNL);
9857 if (lasttoken != TIN)
9858 synerror("expecting \"in\"");
9859 cpp = &n1->ncase.cases;
9860 checkkwd = 2, readtoken();
9862 if (lasttoken == TLP)
9864 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9866 app = &cp->nclist.pattern;
9868 *app = ap = (union node *)stalloc(sizeof (struct narg));
9870 ap->narg.text = wordtext;
9871 ap->narg.backquote = backquotelist;
9872 if (checkkwd = 2, readtoken() != TPIPE)
9874 app = &ap->narg.next;
9877 ap->narg.next = NULL;
9878 if (lasttoken != TRP)
9880 cp->nclist.body = list(0);
9883 if ((t = readtoken()) != TESAC) {
9885 synexpect(TENDCASE);
9887 checkkwd = 2, readtoken();
9889 cpp = &cp->nclist.next;
9890 } while(lasttoken != TESAC);
9895 n1 = (union node *)stalloc(sizeof (struct nredir));
9896 n1->type = NSUBSHELL;
9897 n1->nredir.n = list(0);
9898 n1->nredir.redirect = NULL;
9899 if (readtoken() != TRP)
9905 if (readtoken() != TEND)
9909 /* Handle an empty command like other simple commands. */
9918 * An empty command before a ; doesn't make much sense, and
9919 * should certainly be disallowed in the case of `if ;'.
9925 n1 = simplecmd(rpp, redir);
9932 /* Now check for redirection which may follow command */
9933 while (readtoken() == TREDIR) {
9934 *rpp = n2 = redirnode;
9935 rpp = &n2->nfile.next;
9941 if (n1->type != NSUBSHELL) {
9942 n2 = (union node *)stalloc(sizeof (struct nredir));
9947 n1->nredir.redirect = redir;
9955 simplecmd(union node **rpp, union node *redir) {
9956 union node *args, **app;
9957 union node *n = NULL;
9958 union node *vars, **vpp;
9959 union node **orig_rpp;
9966 /* If we don't have any redirections already, then we must reset
9967 rpp to be the address of the local redir variable. */
9970 /* We save the incoming value, because we need this for shell
9971 functions. There can not be a redirect or an argument between
9972 the function name and the open parenthesis. */
9977 switch (readtoken()) {
9980 n = (union node *)stalloc(sizeof (struct narg));
9982 n->narg.text = wordtext;
9983 n->narg.backquote = backquotelist;
9984 if (lasttoken == TWORD) {
9986 app = &n->narg.next;
9989 vpp = &n->narg.next;
9993 *rpp = n = redirnode;
9994 rpp = &n->nfile.next;
9995 parsefname(); /* read name of redirection file */
9999 args && app == &args->narg.next &&
10000 !vars && rpp == orig_rpp
10002 /* We have a function */
10003 if (readtoken() != TRP)
10007 n->narg.next = command();
10020 n = (union node *)stalloc(sizeof (struct ncmd));
10022 n->ncmd.backgnd = 0;
10023 n->ncmd.args = args;
10024 n->ncmd.assign = vars;
10025 n->ncmd.redirect = redir;
10029 static union node *
10033 n = (union node *)stalloc(sizeof (struct narg));
10035 n->narg.next = NULL;
10036 n->narg.text = wordtext;
10037 n->narg.backquote = backquotelist;
10041 static void fixredir(union node *n, const char *text, int err)
10043 TRACE(("Fix redir %s %d\n", text, err));
10045 n->ndup.vname = NULL;
10047 if (is_digit(text[0]) && text[1] == '\0')
10048 n->ndup.dupfd = digit_val(text[0]);
10049 else if (text[0] == '-' && text[1] == '\0')
10050 n->ndup.dupfd = -1;
10054 synerror("Bad fd number");
10056 n->ndup.vname = makename();
10063 union node *n = redirnode;
10065 if (readtoken() != TWORD)
10067 if (n->type == NHERE) {
10068 struct heredoc *here = heredoc;
10072 if (quoteflag == 0)
10074 TRACE(("Here document %d\n", n->type));
10075 if (here->striptabs) {
10076 while (*wordtext == '\t')
10079 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
10080 synerror("Illegal eof marker for << redirection");
10081 rmescapes(wordtext);
10082 here->eofmark = wordtext;
10084 if (heredoclist == NULL)
10085 heredoclist = here;
10087 for (p = heredoclist ; p->next ; p = p->next);
10090 } else if (n->type == NTOFD || n->type == NFROMFD) {
10091 fixredir(n, wordtext, 0);
10093 n->nfile.fname = makename();
10099 * Input any here documents.
10104 struct heredoc *here;
10107 while (heredoclist) {
10108 here = heredoclist;
10109 heredoclist = here->next;
10114 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
10115 here->eofmark, here->striptabs);
10116 n = (union node *)stalloc(sizeof (struct narg));
10117 n->narg.type = NARG;
10118 n->narg.next = NULL;
10119 n->narg.text = wordtext;
10120 n->narg.backquote = backquotelist;
10121 here->here->nhere.doc = n;
10131 return tokname_array[t][0];
10139 int savecheckalias = checkalias;
10140 int savecheckkwd = checkkwd;
10145 int alreadyseen = tokpushback;
10155 checkalias = savecheckalias;
10162 if (checkkwd == 2) {
10171 * check for keywords
10173 if (t == TWORD && !quoteflag)
10175 const char *const *pp;
10177 if ((pp = findkwd(wordtext))) {
10178 lasttoken = t = pp - tokname_array;
10179 TRACE(("keyword %s recognized\n", tokname(t)));
10190 } else if (checkalias == 2 && isassignment(wordtext)) {
10191 lasttoken = t = TASSIGN;
10193 } else if (checkalias) {
10194 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10196 pushstring(ap->val, strlen(ap->val), ap);
10198 checkkwd = savecheckkwd;
10207 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10209 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10216 * Read the next input token.
10217 * If the token is a word, we set backquotelist to the list of cmds in
10218 * backquotes. We set quoteflag to true if any part of the word was
10220 * If the token is TREDIR, then we set redirnode to a structure containing
10222 * In all cases, the variable startlinno is set to the number of the line
10223 * on which the token starts.
10225 * [Change comment: here documents and internal procedures]
10226 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10227 * word parsing code into a separate routine. In this case, readtoken
10228 * doesn't need to have any internal procedures, but parseword does.
10229 * We could also make parseoperator in essence the main routine, and
10230 * have parseword (readtoken1?) handle both words and redirection.]
10233 #define NEW_xxreadtoken
10234 #ifdef NEW_xxreadtoken
10236 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10237 static const char xxreadtoken_tokens[] = {
10238 TNL, TLP, TRP, /* only single occurrence allowed */
10239 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10240 TEOF, /* corresponds to trailing nul */
10241 TAND, TOR, TENDCASE, /* if double occurrence */
10244 #define xxreadtoken_doubles \
10245 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10246 #define xxreadtoken_singles \
10247 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10261 startlinno = plinno;
10262 for (;;) { /* until token or start of word found */
10265 if ((c!=' ') && (c!='\t')
10271 while ((c = pgetc()) != '\n' && c != PEOF);
10273 } else if (c=='\\') {
10274 if (pgetc() != '\n') {
10278 startlinno = ++plinno;
10279 setprompt(doprompt ? 2 : 0);
10282 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10287 needprompt = doprompt;
10290 p = strchr(xxreadtoken_chars, c);
10293 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10296 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10297 if (pgetc() == *p) { /* double occurrence? */
10298 p += xxreadtoken_doubles + 1;
10305 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10313 #define RETURN(token) return lasttoken = token
10327 startlinno = plinno;
10328 for (;;) { /* until token or start of word found */
10331 case ' ': case '\t':
10337 while ((c = pgetc()) != '\n' && c != PEOF);
10341 if (pgetc() == '\n') {
10342 startlinno = ++plinno;
10353 needprompt = doprompt;
10358 if (pgetc() == '&')
10363 if (pgetc() == '|')
10368 if (pgetc() == ';')
10381 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10387 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10388 * is not NULL, read a here document. In the latter case, eofmark is the
10389 * word which marks the end of the document and striptabs is true if
10390 * leading tabs should be stripped from the document. The argument firstc
10391 * is the first character of the input token or document.
10393 * Because C does not have internal subroutines, I have simulated them
10394 * using goto's to implement the subroutine linkage. The following macros
10395 * will run code that appears at the end of readtoken1.
10398 #define CHECKEND() {goto checkend; checkend_return:;}
10399 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10400 #define PARSESUB() {goto parsesub; parsesub_return:;}
10401 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10402 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10403 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10406 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10411 char line[EOFMARKLEN + 1];
10412 struct nodelist *bqlist;
10415 int varnest; /* levels of variables expansion */
10416 int arinest; /* levels of arithmetic expansion */
10417 int parenlevel; /* levels of parens in arithmetic */
10418 int dqvarnest; /* levels of variables expansion within double quotes */
10420 int prevsyntax; /* syntax before arithmetic */
10422 /* Avoid longjmp clobbering */
10428 (void) &parenlevel;
10431 (void) &prevsyntax;
10435 startlinno = plinno;
10437 if (syntax == DQSYNTAX)
10446 STARTSTACKSTR(out);
10447 loop: { /* for each line, until end of word */
10448 CHECKEND(); /* set c to PEOF if at end of here document */
10449 for (;;) { /* until end of line or end of word */
10450 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10451 switch(SIT(c,syntax)) {
10452 case CNL: /* '\n' */
10453 if (syntax == BASESYNTAX)
10454 goto endword; /* exit outer loop */
10462 goto loop; /* continue outer loop */
10467 if ((eofmark == NULL || dblquote) &&
10469 USTPUTC(CTLESC, out);
10472 case CBACK: /* backslash */
10475 USTPUTC('\\', out);
10477 } else if (c == '\n') {
10483 if (dblquote && c != '\\' && c != '`' && c != '$'
10484 && (c != '"' || eofmark != NULL))
10485 USTPUTC('\\', out);
10486 if (SIT(c,SQSYNTAX) == CCTL)
10487 USTPUTC(CTLESC, out);
10488 else if (eofmark == NULL)
10489 USTPUTC(CTLQUOTEMARK, out);
10495 if (eofmark == NULL)
10496 USTPUTC(CTLQUOTEMARK, out);
10500 if (eofmark == NULL)
10501 USTPUTC(CTLQUOTEMARK, out);
10506 if (eofmark != NULL && arinest == 0 &&
10511 syntax = ARISYNTAX;
10513 } else if (eofmark == NULL &&
10515 syntax = BASESYNTAX;
10521 case CVAR: /* '$' */
10522 PARSESUB(); /* parse substitution */
10524 case CENDVAR: /* '}' */
10527 if (dqvarnest > 0) {
10530 USTPUTC(CTLENDVAR, out);
10535 #ifdef ASH_MATH_SUPPORT
10536 case CLP: /* '(' in arithmetic */
10540 case CRP: /* ')' in arithmetic */
10541 if (parenlevel > 0) {
10545 if (pgetc() == ')') {
10546 if (--arinest == 0) {
10547 USTPUTC(CTLENDARI, out);
10548 syntax = prevsyntax;
10549 if (syntax == DQSYNTAX)
10557 * unbalanced parens
10558 * (don't 2nd guess - no error)
10566 case CBQUOTE: /* '`' */
10570 goto endword; /* exit outer loop */
10575 goto endword; /* exit outer loop */
10586 if (syntax == ARISYNTAX)
10587 synerror("Missing '))'");
10588 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10589 synerror("Unterminated quoted string");
10590 if (varnest != 0) {
10591 startlinno = plinno;
10592 synerror("Missing '}'");
10594 USTPUTC('\0', out);
10595 len = out - stackblock();
10596 out = stackblock();
10597 if (eofmark == NULL) {
10598 if ((c == '>' || c == '<')
10601 && (*out == '\0' || is_digit(*out))) {
10603 return lasttoken = TREDIR;
10608 quoteflag = quotef;
10609 backquotelist = bqlist;
10610 grabstackblock(len);
10612 return lasttoken = TWORD;
10613 /* end of readtoken routine */
10618 * Check to see whether we are at the end of the here document. When this
10619 * is called, c is set to the first character of the next input line. If
10620 * we are at the end of the here document, this routine sets the c to PEOF.
10631 while (c == '\t') {
10635 if (c == *eofmark) {
10636 if (pfgets(line, sizeof line) != NULL) {
10640 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10641 if (*p == '\n' && *q == '\0') {
10644 needprompt = doprompt;
10646 pushstring(line, strlen(line), NULL);
10651 goto checkend_return;
10656 * Parse a redirection operator. The variable "out" points to a string
10657 * specifying the fd to be redirected. The variable "c" contains the
10658 * first character of the redirection operator.
10665 np = (union node *)stalloc(sizeof (struct nfile));
10670 np->type = NAPPEND;
10679 } else { /* c == '<' */
10681 switch (c = pgetc()) {
10683 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10684 np = (union node *)stalloc(sizeof (struct nhere));
10688 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10689 heredoc->here = np;
10690 if ((c = pgetc()) == '-') {
10691 heredoc->striptabs = 1;
10693 heredoc->striptabs = 0;
10699 np->type = NFROMFD;
10703 np->type = NFROMTO;
10713 np->nfile.fd = digit_val(fd);
10715 goto parseredir_return;
10720 * Parse a substitution. At this point, we have read the dollar sign
10721 * and nothing else.
10729 static const char types[] = "}-+?=";
10734 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10738 } else if (c == '(') { /* $(command) or $((arith)) */
10739 if (pgetc() == '(') {
10746 USTPUTC(CTLVAR, out);
10747 typeloc = out - stackblock();
10748 USTPUTC(VSNORMAL, out);
10749 subtype = VSNORMAL;
10753 if ((c = pgetc()) == '}')
10756 subtype = VSLENGTH;
10761 if (c > PEOA && is_name(c)) {
10765 } while (c > PEOA && is_in_name(c));
10766 } else if (is_digit(c)) {
10770 } while (is_digit(c));
10772 else if (is_special(c)) {
10777 badsub: synerror("Bad substitution");
10781 if (subtype == 0) {
10788 p = strchr(types, c);
10791 subtype = p - types + VSNORMAL;
10797 subtype = c == '#' ? VSTRIMLEFT :
10810 if (dblquote || arinest)
10812 *(stackblock() + typeloc) = subtype | flags;
10813 if (subtype != VSNORMAL) {
10820 goto parsesub_return;
10825 * Called to parse command substitutions. Newstyle is set if the command
10826 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10827 * list of commands (passed by reference), and savelen is the number of
10828 * characters on the top of the stack which must be preserved.
10832 struct nodelist **nlpp;
10835 char *volatile str;
10836 struct jmploc jmploc;
10837 struct jmploc *volatile savehandler;
10841 (void) &saveprompt;
10844 savepbq = parsebackquote;
10845 if (setjmp(jmploc.loc)) {
10848 parsebackquote = 0;
10849 handler = savehandler;
10850 longjmp(handler->loc, 1);
10854 savelen = out - stackblock();
10856 str = ckmalloc(savelen);
10857 memcpy(str, stackblock(), savelen);
10859 savehandler = handler;
10863 /* We must read until the closing backquote, giving special
10864 treatment to some slashes, and then push the string and
10865 reread it as input, interpreting it normally. */
10872 STARTSTACKSTR(pout);
10878 switch (pc = pgetc()) {
10883 if ((pc = pgetc()) == '\n') {
10890 * If eating a newline, avoid putting
10891 * the newline into the new character
10892 * stream (via the STPUTC after the
10897 if (pc != '\\' && pc != '`' && pc != '$'
10898 && (!dblquote || pc != '"'))
10899 STPUTC('\\', pout);
10909 startlinno = plinno;
10910 synerror("EOF in backquote substitution");
10914 needprompt = doprompt;
10923 STPUTC('\0', pout);
10924 psavelen = pout - stackblock();
10925 if (psavelen > 0) {
10926 pstr = grabstackstr(pout);
10927 setinputstring(pstr);
10932 nlpp = &(*nlpp)->next;
10933 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10934 (*nlpp)->next = NULL;
10935 parsebackquote = oldstyle;
10938 saveprompt = doprompt;
10945 doprompt = saveprompt;
10947 if (readtoken() != TRP)
10954 * Start reading from old file again, ignoring any pushed back
10955 * tokens left from the backquote parsing
10960 while (stackblocksize() <= savelen)
10962 STARTSTACKSTR(out);
10964 memcpy(out, str, savelen);
10965 STADJUST(savelen, out);
10971 parsebackquote = savepbq;
10972 handler = savehandler;
10973 if (arinest || dblquote)
10974 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10976 USTPUTC(CTLBACKQ, out);
10978 goto parsebackq_oldreturn;
10980 goto parsebackq_newreturn;
10984 * Parse an arithmetic expansion (indicate start of one and set state)
10988 if (++arinest == 1) {
10989 prevsyntax = syntax;
10990 syntax = ARISYNTAX;
10991 USTPUTC(CTLARI, out);
10998 * we collapse embedded arithmetic expansion to
10999 * parenthesis, which should be equivalent
11003 goto parsearith_return;
11006 } /* end of readtoken */
11010 * Returns true if the text contains nothing to expand (no dollar signs
11022 while ((c = *p++) != '\0') {
11023 if (c == CTLQUOTEMARK)
11027 else if (SIT(c,BASESYNTAX) == CCTL)
11035 * Return true if the argument is a legal variable name (a letter or
11036 * underscore followed by zero or more letters, underscores, and digits).
11040 goodname(const char *name)
11048 if (! is_in_name(*p))
11056 * Called when an unexpected token is read during the parse. The argument
11057 * is the token that is expected, or -1 if more than one type of token can
11058 * occur at this point.
11068 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
11070 sprintf(msg+l, " (expecting %s)", tokname(token));
11077 synerror(const char *msg)
11080 out2fmt("%s: %d: ", commandname, startlinno);
11081 out2fmt("Syntax error: %s\n", msg);
11082 error((char *)NULL);
11088 * called by editline -- any expansions to the prompt
11089 * should be added here.
11092 setprompt(int whichprompt)
11095 switch (whichprompt) {
11110 * Code for dealing with input/output redirection.
11113 #define EMPTY -2 /* marks an unused slot in redirtab */
11115 # define PIPESIZE 4096 /* amount of buffering in a pipe */
11117 # define PIPESIZE PIPE_BUF
11122 * Open a file in noclobber mode.
11123 * The code was copied from bash.
11126 noclobberopen(const char *fname)
11129 struct stat finfo, finfo2;
11132 * If the file exists and is a regular file, return an error
11135 r = stat(fname, &finfo);
11136 if (r == 0 && S_ISREG(finfo.st_mode)) {
11142 * If the file was not present (r != 0), make sure we open it
11143 * exclusively so that if it is created before we open it, our open
11144 * will fail. Make sure that we do not truncate an existing file.
11145 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11146 * file was not a regular file, we leave O_EXCL off.
11149 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11150 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11152 /* If the open failed, return the file descriptor right away. */
11157 * OK, the open succeeded, but the file may have been changed from a
11158 * non-regular file to a regular file between the stat and the open.
11159 * We are assuming that the O_EXCL open handles the case where FILENAME
11160 * did not exist and is symlinked to an existing file between the stat
11165 * If we can open it and fstat the file descriptor, and neither check
11166 * revealed that it was a regular file, and the file has not been
11167 * replaced, return the file descriptor.
11169 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11170 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11173 /* The file has been replaced. badness. */
11180 * Handle here documents. Normally we fork off a process to write the
11181 * data to a pipe. If the document is short, we can stuff the data in
11182 * the pipe without forking.
11186 openhere(const union node *redir)
11192 error("Pipe call failed");
11193 if (redir->type == NHERE) {
11194 len = strlen(redir->nhere.doc->narg.text);
11195 if (len <= PIPESIZE) {
11196 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11200 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11202 signal(SIGINT, SIG_IGN);
11203 signal(SIGQUIT, SIG_IGN);
11204 signal(SIGHUP, SIG_IGN);
11206 signal(SIGTSTP, SIG_IGN);
11208 signal(SIGPIPE, SIG_DFL);
11209 if (redir->type == NHERE)
11210 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11212 expandhere(redir->nhere.doc, pip[1]);
11222 openredirect(const union node *redir)
11227 switch (redir->nfile.type) {
11229 fname = redir->nfile.expfname;
11230 if ((f = open(fname, O_RDONLY)) < 0)
11234 fname = redir->nfile.expfname;
11235 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11239 /* Take care of noclobber mode. */
11241 fname = redir->nfile.expfname;
11242 if ((f = noclobberopen(fname)) < 0)
11247 fname = redir->nfile.expfname;
11249 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11252 if ((f = creat(fname, 0666)) < 0)
11257 fname = redir->nfile.expfname;
11259 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11262 if ((f = open(fname, O_WRONLY)) < 0
11263 && (f = creat(fname, 0666)) < 0)
11265 lseek(f, (off_t)0, 2);
11272 /* Fall through to eliminate warning. */
11279 f = openhere(redir);
11285 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11287 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11292 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11293 * old file descriptors are stashed away so that the redirection can be
11294 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11295 * standard output, and the standard error if it becomes a duplicate of
11300 redirect(union node *redir, int flags)
11303 struct redirtab *sv = NULL;
11308 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11310 if (flags & REDIR_PUSH) {
11311 sv = ckmalloc(sizeof (struct redirtab));
11312 for (i = 0 ; i < 10 ; i++)
11313 sv->renamed[i] = EMPTY;
11314 sv->next = redirlist;
11317 for (n = redir ; n ; n = n->nfile.next) {
11320 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11321 n->ndup.dupfd == fd)
11322 continue; /* redirect from/to same file descriptor */
11325 newfd = openredirect(n);
11326 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11329 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11333 dupredirect(n, newfd, fd1dup);
11343 error("%d: %m", fd);
11349 if (flags & REDIR_PUSH) {
11350 sv->renamed[fd] = i;
11353 } else if (fd != newfd) {
11359 dupredirect(n, newfd, fd1dup);
11366 dupredirect(const union node *redir, int f, int fd1dup)
11368 int fd = redir->nfile.fd;
11372 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11373 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11374 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11375 dup_as_newfd(redir->ndup.dupfd, fd);
11381 dup_as_newfd(f, fd);
11390 * Undo the effects of the last redirection.
11396 struct redirtab *rp = redirlist;
11400 for (i = 0 ; i < 10 ; i++) {
11401 if (rp->renamed[i] != EMPTY) {
11405 if (rp->renamed[i] >= 0) {
11406 dup_as_newfd(rp->renamed[i], i);
11407 close(rp->renamed[i]);
11411 redirlist = rp->next;
11417 * Discard all saved file descriptors.
11422 struct redirtab *rp;
11425 for (rp = redirlist ; rp ; rp = rp->next) {
11426 for (i = 0 ; i < 10 ; i++) {
11427 if (rp->renamed[i] >= 0) {
11428 close(rp->renamed[i]);
11430 rp->renamed[i] = EMPTY;
11437 * Copy a file descriptor to be >= to. Returns -1
11438 * if the source file descriptor is closed, EMPTY if there are no unused
11439 * file descriptors left.
11443 dup_as_newfd(from, to)
11449 newfd = fcntl(from, F_DUPFD, to);
11451 if (errno == EMFILE)
11454 error("%d: %m", from);
11463 static void shtree (union node *, int, char *, FILE*);
11464 static void shcmd (union node *, FILE *);
11465 static void sharg (union node *, FILE *);
11466 static void indent (int, char *, FILE *);
11467 static void trstring (char *);
11474 trputs("showtree called\n");
11475 shtree(n, 1, NULL, stdout);
11480 shtree(n, ind, pfx, fp)
11486 struct nodelist *lp;
11492 indent(ind, pfx, fp);
11503 shtree(n->nbinary.ch1, ind, NULL, fp);
11506 shtree(n->nbinary.ch2, ind, NULL, fp);
11514 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11519 if (n->npipe.backgnd)
11525 fprintf(fp, "<node type %d>", n->type);
11545 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11551 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11557 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11558 s = redir_strings[np->nfile.type - NTO];
11564 switch (np->nfile.type) {
11565 case NTO: s = ">"; dftfd = 1; break;
11566 case NAPPEND: s = ">>"; dftfd = 1; break;
11567 case NTOFD: s = ">&"; dftfd = 1; break;
11568 case NTOOV: s = ">|"; dftfd = 1; break;
11569 case NFROM: s = "<"; dftfd = 0; break;
11570 case NFROMFD: s = "<&"; dftfd = 0; break;
11571 case NFROMTO: s = "<>"; dftfd = 0; break;
11572 default: s = "*error*"; dftfd = 0; break;
11575 if (np->nfile.fd != dftfd)
11576 fprintf(fp, "%d", np->nfile.fd);
11578 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11579 fprintf(fp, "%d", np->ndup.dupfd);
11581 sharg(np->nfile.fname, fp);
11593 struct nodelist *bqlist;
11596 if (arg->type != NARG) {
11597 printf("<node type %d>\n", arg->type);
11601 bqlist = arg->narg.backquote;
11602 for (p = arg->narg.text ; *p ; p++) {
11611 if (subtype == VSLENGTH)
11617 if (subtype & VSNUL)
11620 switch (subtype & VSTYPE) {
11639 case VSTRIMLEFTMAX:
11646 case VSTRIMRIGHTMAX:
11653 printf("<subtype %d>", subtype);
11660 case CTLBACKQ|CTLQUOTE:
11663 shtree(bqlist->n, -1, NULL, fp);
11675 indent(amount, pfx, fp)
11682 for (i = 0 ; i < amount ; i++) {
11683 if (pfx && i == amount - 1)
11693 static int debug = 1;
11695 static int debug = 0;
11703 if (tracefile == NULL)
11705 putc(c, tracefile);
11711 trace(const char *fmt, ...)
11715 if (tracefile != NULL) {
11716 (void) vfprintf(tracefile, fmt, va);
11717 if (strchr(fmt, '\n'))
11718 (void) fflush(tracefile);
11728 if (tracefile == NULL)
11730 fputs(s, tracefile);
11731 if (strchr(s, '\n'))
11743 if (tracefile == NULL)
11745 putc('"', tracefile);
11746 for (p = s ; *p ; p++) {
11748 case '\n': c = 'n'; goto backslash;
11749 case '\t': c = 't'; goto backslash;
11750 case '\r': c = 'r'; goto backslash;
11751 case '"': c = '"'; goto backslash;
11752 case '\\': c = '\\'; goto backslash;
11753 case CTLESC: c = 'e'; goto backslash;
11754 case CTLVAR: c = 'v'; goto backslash;
11755 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11756 case CTLBACKQ: c = 'q'; goto backslash;
11757 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11758 backslash: putc('\\', tracefile);
11759 putc(c, tracefile);
11762 if (*p >= ' ' && *p <= '~')
11763 putc(*p, tracefile);
11765 putc('\\', tracefile);
11766 putc(*p >> 6 & 03, tracefile);
11767 putc(*p >> 3 & 07, tracefile);
11768 putc(*p & 07, tracefile);
11773 putc('"', tracefile);
11781 if (tracefile == NULL)
11786 putc(' ', tracefile);
11788 putc('\n', tracefile);
11803 #ifdef not_this_way
11806 if ((p = getenv("HOME")) == NULL) {
11807 if (geteuid() == 0)
11813 strcat(s, "/trace");
11816 strcpy(s, "./trace");
11817 #endif /* not_this_way */
11818 if ((tracefile = fopen(s, "a")) == NULL) {
11819 fprintf(stderr, "Can't open %s\n", s);
11823 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11824 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11826 fputs("\nTracing started.\n", tracefile);
11833 * The trap builtin.
11837 trapcmd(argc, argv)
11846 for (signo = 0 ; signo < NSIG ; signo++) {
11847 if (trap[signo] != NULL) {
11851 p = single_quote(trap[signo]);
11852 sn = sys_siglist[signo];
11854 sn = u_signal_names(0, &signo, 0);
11857 printf("trap -- %s %s\n", p, sn);
11869 if ((signo = decode_signal(*ap, 0)) < 0)
11870 error("%s: bad trap", *ap);
11873 if (action[0] == '-' && action[1] == '\0')
11876 action = savestr(action);
11879 ckfree(trap[signo]);
11880 trap[signo] = action;
11895 * Set the signal handler for the specified signal. The routine figures
11896 * out what it should be set to.
11900 setsignal(int signo)
11904 struct sigaction act;
11906 if ((t = trap[signo]) == NULL)
11908 else if (*t != '\0')
11912 if (rootshell && action == S_DFL) {
11915 if (iflag || minusc || sflag == 0)
11941 t = &sigmode[signo - 1];
11944 * current setting unknown
11946 if (sigaction(signo, 0, &act) == -1) {
11948 * Pretend it worked; maybe we should give a warning
11949 * here, but other shells don't. We don't alter
11950 * sigmode, so that we retry every time.
11954 if (act.sa_handler == SIG_IGN) {
11955 if (mflag && (signo == SIGTSTP ||
11956 signo == SIGTTIN || signo == SIGTTOU)) {
11957 *t = S_IGN; /* don't hard ignore these */
11961 *t = S_RESET; /* force to be set */
11964 if (*t == S_HARD_IGN || *t == action)
11966 act.sa_handler = ((action == S_CATCH) ? onsig
11967 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11970 sigemptyset(&act.sa_mask);
11971 sigaction(signo, &act, 0);
11982 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11983 signal(signo, SIG_IGN);
11985 sigmode[signo - 1] = S_HARD_IGN;
11996 if (signo == SIGINT && trap[SIGINT] == NULL) {
12000 gotsig[signo - 1] = 1;
12006 * Called to execute a trap. Perhaps we should avoid entering new trap
12007 * handlers while we are executing a trap handler.
12017 for (i = 1 ; ; i++) {
12024 savestatus=exitstatus;
12025 evalstring(trap[i], 0);
12026 exitstatus=savestatus;
12033 * Called to exit the shell.
12037 exitshell(int status)
12039 struct jmploc loc1, loc2;
12042 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
12043 if (setjmp(loc1.loc)) {
12046 if (setjmp(loc2.loc)) {
12050 if ((p = trap[0]) != NULL && *p != '\0') {
12054 l1: handler = &loc2; /* probably unnecessary */
12063 static int decode_signal(const char *string, int minsig)
12066 const char *name = u_signal_names(string, &signo, minsig);
12068 return name ? signo : -1;
12071 static struct var **hashvar (const char *);
12072 static void showvars (const char *, int, int);
12073 static struct var **findvar (struct var **, const char *);
12076 * Initialize the varable symbol tables and import the environment
12080 * This routine initializes the builtin variables. It is called when the
12081 * shell is initialized and again when a shell procedure is spawned.
12086 const struct varinit *ip;
12090 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
12091 if ((vp->flags & VEXPORT) == 0) {
12092 vpp = hashvar(ip->text);
12095 vp->text = strdup(ip->text);
12096 vp->flags = ip->flags;
12097 vp->func = ip->func;
12101 * PS1 depends on uid
12103 if ((vps1.flags & VEXPORT) == 0) {
12104 vpp = hashvar("PS1=");
12107 vps1.text = strdup(geteuid() ? "PS1=$ " : "PS1=# ");
12108 vps1.flags = VSTRFIXED|VTEXTFIXED;
12113 * Set the value of a variable. The flags argument is ored with the
12114 * flags of the variable. If val is NULL, the variable is unset.
12118 setvar(name, val, flags)
12119 const char *name, *val;
12135 if (! is_in_name(*p)) {
12136 if (*p == '\0' || *p == '=')
12142 namelen = p - name;
12144 error("%.*s: bad variable name", namelen, name);
12145 len = namelen + 2; /* 2 is space for '=' and '\0' */
12149 len += vallen = strlen(val);
12152 nameeq = ckmalloc(len);
12153 memcpy(nameeq, name, namelen);
12154 nameeq[namelen] = '=';
12156 memcpy(nameeq + namelen + 1, val, vallen + 1);
12158 nameeq[namelen + 1] = '\0';
12160 setvareq(nameeq, flags);
12167 * Same as setvar except that the variable and value are passed in
12168 * the first argument as name=value. Since the first argument will
12169 * be actually stored in the table, it should not be a string that
12178 struct var *vp, **vpp;
12181 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12182 if ((vp = *findvar(vpp, s))) {
12183 if (vp->flags & VREADONLY) {
12184 size_t len = strchr(s, '=') - s;
12185 error("%.*s: is read only", len, s);
12189 if (vp->func && (flags & VNOFUNC) == 0)
12190 (*vp->func)(strchr(s, '=') + 1);
12192 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12195 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12196 vp->flags |= flags;
12201 * We could roll this to a function, to handle it as
12202 * a regular variable function callback, but why bother?
12204 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12211 vp = ckmalloc(sizeof (*vp));
12222 * Process a linked list of variable assignments.
12227 struct strlist *mylist;
12229 struct strlist *lp;
12232 for (lp = mylist ; lp ; lp = lp->next) {
12233 setvareq(savestr(lp->text), 0);
12241 * Find the value of a variable. Returns NULL if not set.
12244 static const char *
12250 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12251 return strchr(v->text, '=') + 1;
12259 * Search the environment of a builtin command.
12262 static const char *
12263 bltinlookup(const char *name)
12265 const struct strlist *sp;
12267 for (sp = cmdenviron ; sp ; sp = sp->next) {
12268 if (varequal(sp->text, name))
12269 return strchr(sp->text, '=') + 1;
12271 return lookupvar(name);
12277 * Generate a list of exported variables. This routine is used to construct
12278 * the third argument to execve when executing a program.
12290 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12291 for (vp = *vpp ; vp ; vp = vp->next)
12292 if (vp->flags & VEXPORT)
12295 ep = env = stalloc((nenv + 1) * sizeof *env);
12296 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12297 for (vp = *vpp ; vp ; vp = vp->next)
12298 if (vp->flags & VEXPORT)
12307 * Called when a shell procedure is invoked to clear out nonexported
12308 * variables. It is also necessary to reallocate variables of with
12309 * VSTACK set since these are currently allocated on the stack.
12315 struct var *vp, **prev;
12317 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12318 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12319 if ((vp->flags & VEXPORT) == 0) {
12321 if ((vp->flags & VTEXTFIXED) == 0)
12323 if ((vp->flags & VSTRFIXED) == 0)
12326 if (vp->flags & VSTACK) {
12327 vp->text = savestr(vp->text);
12328 vp->flags &=~ VSTACK;
12340 * Command to list all variables which are set. Currently this command
12341 * is invoked from the set command when the set command is called without
12346 showvarscmd(argc, argv)
12350 showvars(nullstr, VUNSET, VUNSET);
12357 * The export and readonly commands.
12361 exportcmd(argc, argv)
12368 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12371 listsetvar(cmdenviron);
12372 pflag = (nextopt("p") == 'p');
12373 if (argc > 1 && !pflag) {
12374 while ((name = *argptr++) != NULL) {
12375 if ((p = strchr(name, '=')) != NULL) {
12378 if ((vp = *findvar(hashvar(name), name))) {
12383 setvar(name, p, flag);
12387 showvars(argv[0], flag, 0);
12394 * The "local" command.
12397 /* funcnest nonzero if we are currently evaluating a function */
12400 localcmd(argc, argv)
12407 error("Not in a function");
12408 while ((name = *argptr++) != NULL) {
12416 * Make a variable a local variable. When a variable is made local, it's
12417 * value and flags are saved in a localvar structure. The saved values
12418 * will be restored when the shell function returns. We handle the name
12419 * "-" as a special case.
12426 struct localvar *lvp;
12431 lvp = ckmalloc(sizeof (struct localvar));
12432 if (name[0] == '-' && name[1] == '\0') {
12434 p = ckmalloc(sizeof optet_vals);
12435 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12438 vpp = hashvar(name);
12439 vp = *findvar(vpp, name);
12441 if (strchr(name, '='))
12442 setvareq(savestr(name), VSTRFIXED);
12444 setvar(name, NULL, VSTRFIXED);
12445 vp = *vpp; /* the new variable */
12447 lvp->flags = VUNSET;
12449 lvp->text = vp->text;
12450 lvp->flags = vp->flags;
12451 vp->flags |= VSTRFIXED|VTEXTFIXED;
12452 if (strchr(name, '='))
12453 setvareq(savestr(name), 0);
12457 lvp->next = localvars;
12464 * Called after a function returns.
12469 struct localvar *lvp;
12472 while ((lvp = localvars) != NULL) {
12473 localvars = lvp->next;
12475 if (vp == NULL) { /* $- saved */
12476 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12478 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12479 (void)unsetvar(vp->text);
12481 if ((vp->flags & VTEXTFIXED) == 0)
12483 vp->flags = lvp->flags;
12484 vp->text = lvp->text;
12492 setvarcmd(argc, argv)
12497 return unsetcmd(argc, argv);
12498 else if (argc == 3)
12499 setvar(argv[1], argv[2], 0);
12501 error("List assignment not implemented");
12507 * The unset builtin command. We unset the function before we unset the
12508 * variable to allow a function to be unset when there is a readonly variable
12509 * with the same name.
12513 unsetcmd(argc, argv)
12523 while ((i = nextopt("vf")) != '\0') {
12529 if (flg_func == 0 && flg_var == 0)
12532 for (ap = argptr; *ap ; ap++) {
12536 ret |= unsetvar(*ap);
12543 * Unset the specified variable.
12547 unsetvar(const char *s)
12552 vpp = findvar(hashvar(s), s);
12555 if (vp->flags & VREADONLY)
12558 if (*(strchr(vp->text, '=') + 1) != '\0')
12559 setvar(s, nullstr, 0);
12560 vp->flags &= ~VEXPORT;
12561 vp->flags |= VUNSET;
12562 if ((vp->flags & VSTRFIXED) == 0) {
12563 if ((vp->flags & VTEXTFIXED) == 0)
12578 * Find the appropriate entry in the hash table from the name.
12581 static struct var **
12582 hashvar(const char *p)
12584 unsigned int hashval;
12586 hashval = ((unsigned char) *p) << 4;
12587 while (*p && *p != '=')
12588 hashval += (unsigned char) *p++;
12589 return &vartab[hashval % VTABSIZE];
12595 * Returns true if the two strings specify the same varable. The first
12596 * variable name is terminated by '='; the second may be terminated by
12597 * either '=' or '\0'.
12601 varequal(const char *p, const char *q)
12603 while (*p == *q++) {
12607 if (*p == '=' && *(q - 1) == '\0')
12613 showvars(const char *myprefix, int mask, int xor)
12617 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12619 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12620 for (vp = *vpp ; vp ; vp = vp->next) {
12621 if ((vp->flags & mask) ^ xor) {
12625 p = strchr(vp->text, '=') + 1;
12626 len = p - vp->text;
12627 p = single_quote(p);
12629 printf("%s%s%.*s%s\n", myprefix, sep, len,
12637 static struct var **
12638 findvar(struct var **vpp, const char *name)
12640 for (; *vpp; vpp = &(*vpp)->next) {
12641 if (varequal((*vpp)->text, name)) {
12649 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12650 * This file contains code for the times builtin.
12651 * $Id: ash.c,v 1.34 2001/10/31 11:05:49 andersen Exp $
12653 static int timescmd (int argc, char **argv)
12656 long int clk_tck = sysconf(_SC_CLK_TCK);
12659 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12660 (int) (buf.tms_utime / clk_tck / 60),
12661 ((double) buf.tms_utime) / clk_tck,
12662 (int) (buf.tms_stime / clk_tck / 60),
12663 ((double) buf.tms_stime) / clk_tck,
12664 (int) (buf.tms_cutime / clk_tck / 60),
12665 ((double) buf.tms_cutime) / clk_tck,
12666 (int) (buf.tms_cstime / clk_tck / 60),
12667 ((double) buf.tms_cstime) / clk_tck);
12671 #ifdef ASH_MATH_SUPPORT
12672 /* The let builtin. */
12673 int letcmd(int argc, char **argv)
12678 char *tmp, *expression, p[13];
12679 expression = strchr(argv[1], '=');
12681 /* Cannot use 'error()' here, or the return code
12682 * will be incorrect */
12683 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12686 *expression = '\0';
12687 tmp = ++expression;
12688 result = arith(tmp, &errcode);
12690 /* Cannot use 'error()' here, or the return code
12691 * will be incorrect */
12692 out2fmt("sh: let: ");
12694 out2fmt("divide by zero");
12696 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12699 snprintf(p, 12, "%ld", result);
12700 setvar(argv[1], savestr(p), 0);
12701 } else if (argc >= 3)
12702 synerror("invalid operand");
12710 * Copyright (c) 1989, 1991, 1993, 1994
12711 * The Regents of the University of California. All rights reserved.
12713 * This code is derived from software contributed to Berkeley by
12714 * Kenneth Almquist.
12716 * Redistribution and use in source and binary forms, with or without
12717 * modification, are permitted provided that the following conditions
12719 * 1. Redistributions of source code must retain the above copyright
12720 * notice, this list of conditions and the following disclaimer.
12721 * 2. Redistributions in binary form must reproduce the above copyright
12722 * notice, this list of conditions and the following disclaimer in the
12723 * documentation and/or other materials provided with the distribution.
12725 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12726 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12728 * 4. Neither the name of the University nor the names of its contributors
12729 * may be used to endorse or promote products derived from this software
12730 * without specific prior written permission.
12732 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12733 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12734 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12735 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12736 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12737 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12738 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12739 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12740 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12741 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF