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 S_DFL 1 /* default signal handling (SIG_DFL) */
215 #define S_CATCH 2 /* signal is caught */
216 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
217 #define S_HARD_IGN 4 /* signal is ignored permenantly */
218 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
221 /* variable substitution byte (follows CTLVAR) */
222 #define VSTYPE 0x0f /* type of variable substitution */
223 #define VSNUL 0x10 /* colon--treat the empty string as unset */
224 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
226 /* values of VSTYPE field */
227 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
228 #define VSMINUS 0x2 /* ${var-text} */
229 #define VSPLUS 0x3 /* ${var+text} */
230 #define VSQUESTION 0x4 /* ${var?message} */
231 #define VSASSIGN 0x5 /* ${var=text} */
232 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
233 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
234 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
235 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
236 #define VSLENGTH 0xa /* ${#var} */
238 /* flags passed to redirect */
239 #define REDIR_PUSH 01 /* save previous values of file descriptors */
240 #define REDIR_BACKQ 02 /* save the command output to pipe */
243 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
244 * so we use _setjmp instead.
248 #define setjmp(jmploc) _setjmp(jmploc)
249 #define longjmp(jmploc, val) _longjmp(jmploc, val)
253 * Most machines require the value returned from malloc to be aligned
254 * in some way. The following macro will get this right on many machines.
263 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
266 #ifdef CONFIG_LOCALE_SUPPORT
268 static void change_lc_all(const char *value);
269 static void change_lc_ctype(const char *value);
273 * These macros allow the user to suspend the handling of interrupt signals
274 * over a period of time. This is similar to SIGHOLD to or sigblock, but
275 * much more efficient and portable. (But hacking the kernel is so much
276 * more fun than worrying about efficiency and portability. :-))
279 static void onint (void);
280 static volatile int suppressint;
281 static volatile int intpending;
283 #define INTOFF suppressint++
284 #ifndef ASH_OPTIMIZE_FOR_SIZE
285 #define INTON { if (--suppressint == 0 && intpending) onint(); }
286 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
288 static void __inton (void);
289 static void forceinton (void);
290 #define INTON __inton()
291 #define FORCEINTON forceinton()
294 #define CLEAR_PENDING_INT intpending = 0
295 #define int_pending() intpending
298 typedef void *pointer;
300 #define NULL (void *)0
303 static pointer stalloc (int);
304 static void stunalloc (pointer);
305 static void ungrabstackstr (char *, char *);
306 static char * growstackstr(void);
307 static char * makestrspace(size_t newlen);
308 static char *sstrdup (const char *);
311 * Parse trees for commands are allocated in lifo order, so we use a stack
312 * to make this more efficient, and also to avoid all sorts of exception
313 * handling code to handle interrupts in the middle of a parse.
315 * The size 504 was chosen because the Ultrix malloc handles that size
319 #define MINSIZE 504 /* minimum size of a block */
323 struct stack_block *prev;
327 static struct stack_block stackbase;
328 static struct stack_block *stackp = &stackbase;
329 static struct stackmark *markp;
330 static char *stacknxt = stackbase.space;
331 static int stacknleft = MINSIZE;
334 #define equal(s1, s2) (strcmp(s1, s2) == 0)
336 #define stackblock() stacknxt
337 #define stackblocksize() stacknleft
338 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
340 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
341 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
342 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
345 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
346 #define STUNPUTC(p) (++sstrnleft, --p)
347 #define STTOPC(p) p[-1]
348 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
349 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
351 #define ckfree(p) free((pointer)(p))
355 #define TRACE(param) trace param
356 typedef union node unode;
357 static void trace (const char *, ...);
358 static void trargs (char **);
359 static void showtree (unode *);
360 static void trputc (int);
361 static void trputs (const char *);
362 static void opentrace (void);
397 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
398 #define EXP_TILDE 0x2 /* do normal tilde expansion */
399 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
400 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
401 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
402 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
407 static char optet_vals[NOPTS];
409 static const char * const optlist[NOPTS] = {
428 #define optent_name(optent) (optent+1)
429 #define optent_letter(optent) optent[0]
430 #define optent_val(optent) optet_vals[optent]
432 #define eflag optent_val(0)
433 #define fflag optent_val(1)
434 #define Iflag optent_val(2)
435 #define iflag optent_val(3)
436 #define mflag optent_val(4)
437 #define nflag optent_val(5)
438 #define sflag optent_val(6)
439 #define xflag optent_val(7)
440 #define vflag optent_val(8)
441 #define Vflag optent_val(9)
442 #define Eflag optent_val(10)
443 #define Cflag optent_val(11)
444 #define aflag optent_val(12)
445 #define bflag optent_val(13)
446 #define uflag optent_val(14)
447 #define qflag optent_val(15)
450 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
468 union node *redirect;
475 struct nodelist *cmdlist;
482 union node *redirect;
490 union node *elsepart;
521 struct nodelist *backquote;
559 struct nbinary nbinary;
562 struct nredir nredir;
566 struct nclist nclist;
576 struct nodelist *next;
580 struct backcmd { /* result of evalbackcmd */
581 int fd; /* file descriptor to read from */
582 char *buf; /* buffer */
583 int nleft; /* number of chars in buffer */
584 struct job *jp; /* job structure for command */
592 const struct builtincmd *cmd;
597 struct strlist *next;
603 struct strlist *list;
604 struct strlist **lastp;
608 struct strpush *prev; /* preceding string on stack */
612 struct alias *ap; /* if push was associated with an alias */
614 char *string; /* remember the string since it may change */
618 struct parsefile *prev; /* preceding file on stack */
619 int linno; /* current line */
620 int fd; /* file descriptor (or -1 if string) */
621 int nleft; /* number of chars left in this line */
622 int lleft; /* number of chars left in this buffer */
623 char *nextc; /* next char in buffer */
624 char *buf; /* input buffer */
625 struct strpush *strpush; /* for pushing strings at this level */
626 struct strpush basestrpush; /* so pushing one is fast */
630 struct stack_block *stackp;
633 struct stackmark *marknext;
637 int nparam; /* # of positional parameters (without $0) */
638 unsigned char malloc; /* if parameter list dynamically allocated */
639 char **p; /* parameter list */
640 int optind; /* next parameter to be processed by getopts */
641 int optoff; /* used by getopts */
645 * When commands are first encountered, they are entered in a hash table.
646 * This ensures that a full path search will not have to be done for them
647 * on each invocation.
649 * We should investigate converting to a linear search, even though that
650 * would make the command name "hash" a misnomer.
652 #define CMDTABLESIZE 31 /* should be prime */
653 #define ARB 1 /* actual size determined at run time */
658 struct tblentry *next; /* next entry in hash chain */
659 union param param; /* definition of builtin function */
660 short cmdtype; /* index identifying command */
661 char rehash; /* if set, cd done since entry created */
662 char cmdname[ARB]; /* name of command */
666 static struct tblentry *cmdtable[CMDTABLESIZE];
667 static int builtinloc = -1; /* index in path of %builtin, or -1 */
668 static int exerrno = 0; /* Last exec error */
671 static void tryexec (char *, char **, char **);
672 static void printentry (struct tblentry *, int);
673 static void clearcmdentry (int);
674 static struct tblentry *cmdlookup (const char *, int);
675 static void delete_cmd_entry (void);
676 static int path_change (const char *, int *);
679 static void flushall (void);
680 static void out2fmt (const char *, ...)
681 __attribute__((__format__(__printf__,1,2)));
682 static int xwrite (int, const char *, int);
684 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
685 static void out1str(const char *p) { outstr(p, stdout); }
686 static void out2str(const char *p) { outstr(p, stderr); }
688 #ifndef ASH_OPTIMIZE_FOR_SIZE
689 #define out2c(c) putc((c), stderr)
691 static void out2c(int c) { putc(c, stderr); }
695 #ifdef ASH_OPTIMIZE_FOR_SIZE
696 #define USE_SIT_FUNCTION
699 /* number syntax index */
700 #define BASESYNTAX 0 /* not in quotes */
701 #define DQSYNTAX 1 /* in double quotes */
702 #define SQSYNTAX 2 /* in single quotes */
703 #define ARISYNTAX 3 /* in arithmetic */
705 static const char S_I_T[][4] = {
706 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
707 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
708 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
709 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
710 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
711 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
712 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
713 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
714 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
715 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
716 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
717 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
718 #ifndef USE_SIT_FUNCTION
719 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
720 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
721 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
725 #ifdef USE_SIT_FUNCTION
727 #define U_C(c) ((unsigned char)(c))
729 static int SIT(int c, int syntax)
731 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
732 static const char syntax_index_table [] = {
733 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
734 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
735 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
740 if(c==PEOF) /* 2^8+2 */
742 if(c==PEOA) /* 2^8+1 */
744 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
747 s = strchr(spec_symbls, c);
750 indx = syntax_index_table[(s-spec_symbls)];
752 return S_I_T[indx][syntax];
755 #else /* USE_SIT_FUNCTION */
757 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
759 #define CSPCL_CIGN_CIGN_CIGN 0
760 #define CSPCL_CWORD_CWORD_CWORD 1
761 #define CNL_CNL_CNL_CNL 2
762 #define CWORD_CCTL_CCTL_CWORD 3
763 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
764 #define CVAR_CVAR_CWORD_CVAR 5
765 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
766 #define CSPCL_CWORD_CWORD_CLP 7
767 #define CSPCL_CWORD_CWORD_CRP 8
768 #define CBACK_CBACK_CCTL_CBACK 9
769 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
770 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
771 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
772 #define CWORD_CWORD_CWORD_CWORD 13
773 #define CCTL_CCTL_CCTL_CCTL 14
775 static const char syntax_index_table[258] = {
776 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
777 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
778 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
779 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
780 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
781 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
782 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
783 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
784 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
785 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
786 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
787 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
788 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
789 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
790 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
791 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
792 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
793 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
794 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
795 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
796 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
797 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
798 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
799 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
800 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
801 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
802 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
803 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
804 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
805 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
806 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
807 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
808 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
809 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
810 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
811 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
812 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
813 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
814 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
815 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
816 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
817 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
818 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
819 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
820 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
821 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
822 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
823 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
824 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
825 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
826 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
827 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
828 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
829 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
830 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
831 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
832 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
833 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
834 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
835 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
836 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
837 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
838 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
839 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
840 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
841 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
842 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
843 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
844 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
845 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
846 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
847 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
848 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
849 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
850 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
851 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
852 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
853 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
854 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
855 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
856 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
857 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
858 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
859 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
860 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
861 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
862 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
863 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
864 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
865 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
866 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
867 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
868 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
869 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
870 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
871 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
872 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
873 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
874 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
875 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
876 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
877 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
878 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
879 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
880 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
881 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
882 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
883 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
884 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
885 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
886 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
887 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
888 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
889 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
890 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
891 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
892 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
893 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
894 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
895 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
896 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
897 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
898 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
899 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
900 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
901 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
902 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
903 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
904 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
905 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
906 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
907 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
908 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
909 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
910 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
911 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
912 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
913 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
914 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
915 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
916 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
917 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
918 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
919 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
920 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
921 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
922 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
923 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
924 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
925 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
926 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
927 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
928 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
929 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
930 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
931 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
932 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
933 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
934 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
935 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
936 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
937 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
938 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
939 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
940 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
941 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
942 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
943 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
944 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
945 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
946 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
947 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
948 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
949 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
950 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
951 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
952 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
953 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
954 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
955 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
956 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
957 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
958 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
959 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
960 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
961 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
962 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
963 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
964 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
965 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
966 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
967 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
968 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
969 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
970 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
971 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
972 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
973 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
974 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
975 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
976 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
977 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
978 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
979 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
980 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
981 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
982 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
983 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
984 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
985 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
986 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
987 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
988 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
989 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
990 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
991 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
992 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
993 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
994 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
995 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
996 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
997 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
998 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
999 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1000 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1001 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1004 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1005 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1032 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1033 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1034 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1037 #endif /* USE_SIT_FUNCTION */
1040 /* first char is indicating which tokens mark the end of a list */
1041 static const char *const tokname_array[] = {
1056 #define KWDOFFSET 14
1057 /* the following are keywords */
1076 static const char *tokname(int tok)
1078 static char buf[16];
1082 sprintf(buf+(tok>=TSEMI), "%s%c",
1083 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1087 static int plinno = 1; /* input line number */
1089 static int parselleft; /* copy of parsefile->lleft */
1091 static struct parsefile basepf; /* top level input file */
1092 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1093 static struct parsefile *parsefile = &basepf; /* current input file */
1096 * NEOF is returned by parsecmd when it encounters an end of file. It
1097 * must be distinct from NULL, so we use the address of a variable that
1098 * happens to be handy.
1101 static int tokpushback; /* last token pushed back */
1102 #define NEOF ((union node *)&tokpushback)
1103 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1106 static void error (const char *, ...) __attribute__((__noreturn__));
1107 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1108 static void shellexec (char **, char **, const char *, int)
1109 __attribute__((noreturn));
1110 static void exitshell (int) __attribute__((noreturn));
1112 static int goodname(const char *);
1113 static void ignoresig (int);
1114 static void onsig (int);
1115 static void dotrap (void);
1116 static int decode_signal (const char *, int);
1118 static void shprocvar(void);
1119 static void deletefuncs(void);
1120 static void setparam (char **);
1121 static void freeparam (volatile struct shparam *);
1123 static void find_command (const char *, struct cmdentry *, int, const char *);
1125 static inline void hashcd (void);
1127 /* reasons for skipping commands (see comment on breakcmd routine) */
1133 /* values of cmdtype */
1134 #define CMDUNKNOWN -1 /* no entry in table for command */
1135 #define CMDNORMAL 0 /* command is an executable program */
1136 #define CMDBUILTIN 1 /* command is a shell builtin */
1137 #define CMDFUNCTION 2 /* command is a shell function */
1139 #define DO_ERR 1 /* find_command prints errors */
1140 #define DO_ABS 2 /* find_command checks absolute paths */
1141 #define DO_NOFUN 4 /* find_command ignores functions */
1142 #define DO_BRUTE 8 /* find_command ignores hash table */
1149 #define VEXPORT 0x01 /* variable is exported */
1150 #define VREADONLY 0x02 /* variable cannot be modified */
1151 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1152 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1153 #define VSTACK 0x10 /* text is allocated on the stack */
1154 #define VUNSET 0x20 /* the variable is not set */
1155 #define VNOFUNC 0x40 /* don't call the callback function */
1159 struct var *next; /* next entry in hash list */
1160 int flags; /* flags are defined above */
1161 char *text; /* name=value */
1162 void (*func) (const char *);
1163 /* function to be called when */
1164 /* the variable gets set/unset */
1168 struct localvar *next; /* next local variable in list */
1169 struct var *vp; /* the variable that was made local */
1170 int flags; /* saved flags */
1171 char *text; /* saved text */
1175 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1176 #define rmescapes(p) _rmescapes((p), 0)
1177 static char *_rmescapes (char *, int);
1179 static void rmescapes (char *);
1182 static int casematch (union node *, const char *);
1183 static void clearredir(void);
1184 static void popstring(void);
1185 static void readcmdfile (const char *);
1187 static int number (const char *);
1188 static int is_number (const char *, int *num);
1189 static char *single_quote (const char *);
1190 static int nextopt (const char *);
1192 static void redirect (union node *, int);
1193 static void popredir (void);
1194 static int dup_as_newfd (int, int);
1196 static void changepath(const char *newval);
1197 static void getoptsreset(const char *value);
1200 static int parsenleft; /* copy of parsefile->nleft */
1201 static char *parsenextc; /* copy of parsefile->nextc */
1202 static int rootpid; /* pid of main shell */
1203 static int rootshell; /* true if we aren't a child of the main shell */
1205 static const char spcstr[] = " ";
1206 static const char snlfmt[] = "%s\n";
1208 static int sstrnleft;
1209 static int herefd = -1;
1211 static struct localvar *localvars;
1213 static struct var vifs;
1214 static struct var vmail;
1215 static struct var vmpath;
1216 static struct var vpath;
1217 static struct var vps1;
1218 static struct var vps2;
1219 static struct var voptind;
1220 #ifdef CONFIG_LOCALE_SUPPORT
1221 static struct var vlc_all;
1222 static struct var vlc_ctype;
1229 void (*func) (const char *);
1232 static const char defpathvar[] =
1233 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1234 #define defpath (defpathvar + 5)
1237 static const char defifsvar[] = "IFS= \t\n";
1238 #define defifs (defifsvar + 4)
1240 static const char defifs[] = " \t\n";
1243 static const struct varinit varinit[] = {
1245 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1247 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1250 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1252 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1254 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1257 * vps1 depends on uid
1259 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1261 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1263 #ifdef CONFIG_LOCALE_SUPPORT
1264 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1266 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1275 static struct var *vartab[VTABSIZE];
1278 * The following macros access the values of the above variables.
1279 * They have to skip over the name. They return the null string
1280 * for unset variables.
1283 #define ifsval() (vifs.text + 4)
1284 #define ifsset() ((vifs.flags & VUNSET) == 0)
1285 #define mailval() (vmail.text + 5)
1286 #define mpathval() (vmpath.text + 9)
1287 #define pathval() (vpath.text + 5)
1288 #define ps1val() (vps1.text + 4)
1289 #define ps2val() (vps2.text + 4)
1290 #define optindval() (voptind.text + 7)
1292 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1294 static void initvar (void);
1295 static void setvar (const char *, const char *, int);
1296 static void setvareq (char *, int);
1297 static void listsetvar (struct strlist *);
1298 static const char *lookupvar (const char *);
1299 static const char *bltinlookup (const char *);
1300 static char **environment (void);
1301 static int showvarscmd (int, char **);
1302 static void mklocal (char *);
1303 static void poplocalvars (void);
1304 static int unsetvar (const char *);
1305 static int varequal (const char *, const char *);
1308 static char *arg0; /* value of $0 */
1309 static struct shparam shellparam; /* current positional parameters */
1310 static char **argptr; /* argument list for builtin commands */
1311 static char *optionarg; /* set by nextopt (like getopt) */
1312 static char *optptr; /* used by nextopt */
1313 static char *minusc; /* argument to -c option */
1318 #define ALIASINUSE 1
1330 static struct alias *atab[ATABSIZE];
1332 static void setalias (char *, char *);
1333 static struct alias **hashalias (const char *);
1334 static struct alias *freealias (struct alias *);
1335 static struct alias **__lookupalias (const char *);
1338 setalias(char *name, char *val)
1340 struct alias *ap, **app;
1342 app = __lookupalias(name);
1346 if (!(ap->flag & ALIASINUSE)) {
1349 ap->val = xstrdup(val);
1350 ap->flag &= ~ALIASDEAD;
1353 ap = xmalloc(sizeof (struct alias));
1354 ap->name = xstrdup(name);
1355 ap->val = xstrdup(val);
1368 app = __lookupalias(name);
1372 *app = freealias(*app);
1383 struct alias *ap, **app;
1387 for (i = 0; i < ATABSIZE; i++) {
1389 for (ap = *app; ap; ap = *app) {
1390 *app = freealias(*app);
1400 printalias(const struct alias *ap) {
1403 p = single_quote(ap->val);
1404 printf("alias %s=%s\n", ap->name, p);
1410 * TODO - sort output
1413 aliascmd(int argc, char **argv)
1422 for (i = 0; i < ATABSIZE; i++)
1423 for (ap = atab[i]; ap; ap = ap->next) {
1428 while ((n = *++argv) != NULL) {
1429 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1430 if ((ap = *__lookupalias(n)) == NULL) {
1431 out2fmt("%s: %s not found\n", "alias", n);
1446 unaliascmd(int argc, char **argv)
1450 while ((i = nextopt("a")) != '\0') {
1456 for (i = 0; *argptr; argptr++) {
1457 if (unalias(*argptr)) {
1458 out2fmt("%s: %s not found\n", "unalias", *argptr);
1466 static struct alias **
1467 hashalias(const char *p)
1469 unsigned int hashval;
1474 return &atab[hashval % ATABSIZE];
1477 static struct alias *
1478 freealias(struct alias *ap)
1482 if (ap->flag & ALIASINUSE) {
1483 ap->flag |= ALIASDEAD;
1495 static struct alias **
1496 __lookupalias(const char *name)
1498 struct alias **app = hashalias(name);
1500 for (; *app; app = &(*app)->next) {
1501 if (equal(name, (*app)->name)) {
1510 #ifdef ASH_MATH_SUPPORT
1511 /* The generated file arith.c has been replaced with a custom hand
1512 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1513 * This is now part of libbb, so that it can be used by all the shells
1515 static void expari (int);
1518 static char *trap[NSIG]; /* trap handler commands */
1519 static char sigmode[NSIG - 1]; /* current value of signal */
1520 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1521 static int pendingsigs; /* indicates some signal received */
1524 * This file was generated by the mkbuiltins program.
1528 static int bgcmd (int, char **);
1529 static int fgcmd (int, char **);
1530 static int killcmd (int, char **);
1532 static int bltincmd (int, char **);
1533 static int cdcmd (int, char **);
1534 static int breakcmd (int, char **);
1536 static int commandcmd (int, char **);
1538 static int dotcmd (int, char **);
1539 static int evalcmd (int, char **);
1540 static int execcmd (int, char **);
1541 static int exitcmd (int, char **);
1542 static int exportcmd (int, char **);
1543 static int histcmd (int, char **);
1544 static int hashcmd (int, char **);
1545 static int helpcmd (int, char **);
1546 static int jobscmd (int, char **);
1547 static int localcmd (int, char **);
1548 static int pwdcmd (int, char **);
1549 static int readcmd (int, char **);
1550 static int returncmd (int, char **);
1551 static int setcmd (int, char **);
1552 static int setvarcmd (int, char **);
1553 static int shiftcmd (int, char **);
1554 static int trapcmd (int, char **);
1555 static int umaskcmd (int, char **);
1557 static int aliascmd (int, char **);
1558 static int unaliascmd (int, char **);
1560 static int unsetcmd (int, char **);
1561 static int waitcmd (int, char **);
1562 static int ulimitcmd (int, char **);
1563 static int timescmd (int, char **);
1564 #ifdef ASH_MATH_SUPPORT
1565 static int letcmd (int, char **);
1567 static int typecmd (int, char **);
1569 static int getoptscmd (int, char **);
1573 static int true_main (int, char **);
1575 #ifndef CONFIG_FALSE
1576 static int false_main (int, char **);
1579 static void setpwd (const char *, int);
1582 #define BUILTIN_NOSPEC "0"
1583 #define BUILTIN_SPECIAL "1"
1584 #define BUILTIN_REGULAR "2"
1585 #define BUILTIN_ASSIGN "4"
1586 #define BUILTIN_SPEC_ASSG "5"
1587 #define BUILTIN_REG_ASSG "6"
1589 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1590 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1591 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1595 int (*const builtinfunc) (int, char **);
1600 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1601 * the binary search in find_builtin() will stop working. If you value
1602 * your kneecaps, you'll be sure to *make sure* that any changes made
1603 * to this array result in the listing remaining in ascii order. You
1606 static const struct builtincmd builtincmds[] = {
1607 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1608 { BUILTIN_SPECIAL ":", true_main },
1610 { BUILTIN_REG_ASSG "alias", aliascmd },
1613 { BUILTIN_REGULAR "bg", bgcmd },
1615 { BUILTIN_SPECIAL "break", breakcmd },
1616 { BUILTIN_SPECIAL "builtin", bltincmd },
1617 { BUILTIN_REGULAR "cd", cdcmd },
1618 { BUILTIN_NOSPEC "chdir", cdcmd },
1620 { BUILTIN_REGULAR "command", commandcmd },
1622 { BUILTIN_SPECIAL "continue", breakcmd },
1623 { BUILTIN_SPECIAL "eval", evalcmd },
1624 { BUILTIN_SPECIAL "exec", execcmd },
1625 { BUILTIN_SPECIAL "exit", exitcmd },
1626 { BUILTIN_SPEC_ASSG "export", exportcmd },
1627 { BUILTIN_REGULAR "false", false_main },
1628 { BUILTIN_REGULAR "fc", histcmd },
1630 { BUILTIN_REGULAR "fg", fgcmd },
1633 { BUILTIN_REGULAR "getopts", getoptscmd },
1635 { BUILTIN_NOSPEC "hash", hashcmd },
1636 { BUILTIN_NOSPEC "help", helpcmd },
1637 { BUILTIN_REGULAR "jobs", jobscmd },
1639 { BUILTIN_REGULAR "kill", killcmd },
1641 #ifdef ASH_MATH_SUPPORT
1642 { BUILTIN_REGULAR "let", letcmd },
1644 { BUILTIN_ASSIGN "local", localcmd },
1645 { BUILTIN_NOSPEC "pwd", pwdcmd },
1646 { BUILTIN_REGULAR "read", readcmd },
1647 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1648 { BUILTIN_SPECIAL "return", returncmd },
1649 { BUILTIN_SPECIAL "set", setcmd },
1650 { BUILTIN_NOSPEC "setvar", setvarcmd },
1651 { BUILTIN_SPECIAL "shift", shiftcmd },
1652 { BUILTIN_SPECIAL "times", timescmd },
1653 { BUILTIN_SPECIAL "trap", trapcmd },
1654 { BUILTIN_REGULAR "true", true_main },
1655 { BUILTIN_NOSPEC "type", typecmd },
1656 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1657 { BUILTIN_REGULAR "umask", umaskcmd },
1659 { BUILTIN_REGULAR "unalias", unaliascmd },
1661 { BUILTIN_SPECIAL "unset", unsetcmd },
1662 { BUILTIN_REGULAR "wait", waitcmd },
1664 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1666 #define DOTCMD &builtincmds[0]
1667 static struct builtincmd *BLTINCMD;
1668 static struct builtincmd *EXECCMD;
1669 static struct builtincmd *EVALCMD;
1672 #define JOBSTOPPED 1 /* all procs are stopped */
1673 #define JOBDONE 2 /* all procs are completed */
1676 * A job structure contains information about a job. A job is either a
1677 * single process or a set of processes contained in a pipeline. In the
1678 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1683 pid_t pid; /* process id */
1684 int status; /* status flags (defined above) */
1685 char *cmd; /* text of command being run */
1689 static int job_warning; /* user was warned about stopped jobs */
1692 static void setjobctl(int enable);
1694 #define setjobctl(on) /* do nothing */
1699 struct procstat ps0; /* status of process */
1700 struct procstat *ps; /* status or processes when more than one */
1701 short nprocs; /* number of processes */
1702 short pgrp; /* process group of this job */
1703 char state; /* true if job is finished */
1704 char used; /* true if this entry is in used */
1705 char changed; /* true if status has changed */
1707 char jobctl; /* job running under job control */
1711 static struct job *jobtab; /* array of jobs */
1712 static int njobs; /* size of array */
1713 static int backgndpid = -1; /* pid of last background process */
1715 static int initialpgrp; /* pgrp of shell on invocation */
1716 static int curjob; /* current job */
1719 static int intreceived;
1721 static struct job *makejob (const union node *, int);
1722 static int forkshell (struct job *, const union node *, int);
1723 static int waitforjob (struct job *);
1725 static int docd (char *, int);
1726 static void getpwd (void);
1728 static char *padvance (const char **, const char *);
1730 static char nullstr[1]; /* zero length string */
1731 static char *curdir = nullstr; /* current working directory */
1734 cdcmd(int argc, char **argv)
1743 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1744 error("HOME not set");
1747 if (dest[0] == '-' && dest[1] == '\0') {
1748 dest = bltinlookup("OLDPWD");
1749 if (!dest || !*dest) {
1758 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1760 while ((p = padvance(&path, dest)) != NULL) {
1761 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1766 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1768 print = strcmp(p, dest);
1770 if (docd(p, print) >= 0)
1775 error("can't cd to %s", dest);
1781 * Actually do the chdir. In an interactive shell, print the
1782 * directory name if "print" is nonzero.
1786 docd(char *dest, int print)
1788 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1790 if (chdir(dest) < 0) {
1796 * Update curdir (the name of the current directory) in response to a
1797 * cd command. We also call hashcd to let the routines in exec.c know
1798 * that the current directory has changed.
1800 /* If dest is NULL, we don't know the current directory */
1801 if (dest == NULL || curdir == nullstr)
1814 pwdcmd(int argc, char **argv)
1820 /* Ask system the current directory */
1824 curdir = xgetcwd(0);
1830 setpwd(const char *val, int setold)
1835 setvar("OLDPWD", curdir, VEXPORT);
1838 if (curdir != nullstr) {
1839 if(val!=NULL && *val != '/')
1840 val = cated = concat_path_file(curdir, val);
1846 curdir = simplify_path(val);
1849 setvar("PWD", curdir, VEXPORT);
1853 * Errors and exceptions.
1857 * Code to handle exceptions in C.
1861 * We enclose jmp_buf in a structure so that we can declare pointers to
1862 * jump locations. The global variable handler contains the location to
1863 * jump to when an exception occurs, and the global variable exception
1864 * contains a code identifying the exeception. To implement nested
1865 * exception handlers, the user should save the value of handler on entry
1866 * to an inner scope, set handler to point to a jmploc structure for the
1867 * inner scope, and restore handler on exit from the scope.
1875 #define EXINT 0 /* SIGINT received */
1876 #define EXERROR 1 /* a generic error */
1877 #define EXSHELLPROC 2 /* execute a shell procedure */
1878 #define EXEXEC 3 /* command execution failed */
1880 static struct jmploc *handler;
1881 static int exception;
1883 static void exverror (int, const char *, va_list)
1884 __attribute__((__noreturn__));
1887 * Called to raise an exception. Since C doesn't include exceptions, we
1888 * just do a longjmp to the exception handler. The type of exception is
1889 * stored in the global variable "exception".
1892 static void exraise (int) __attribute__((__noreturn__));
1898 if (handler == NULL)
1903 longjmp(handler->loc, 1);
1908 * Called from trap.c when a SIGINT is received. (If the user specifies
1909 * that SIGINT is to be trapped or ignored using the trap builtin, then
1910 * this routine is not called.) Suppressint is nonzero when interrupts
1911 * are held using the INTOFF macro. The call to _exit is necessary because
1912 * there is a short period after a fork before the signal handlers are
1913 * set to the appropriate value for the child. (The test for iflag is
1914 * just defensive programming.)
1926 sigemptyset(&mysigset);
1927 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1928 if (rootshell && iflag)
1931 signal(SIGINT, SIG_DFL);
1938 static char *commandname; /* currently executing command */
1941 * Exverror is called to raise the error exception. If the first argument
1942 * is not NULL then error prints an error message using printf style
1943 * formatting. It then raises the error exception.
1946 exverror(int cond, const char *msg, va_list ap)
1953 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1955 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1959 out2fmt("%s: ", commandname);
1960 vfprintf(stderr, msg, ap);
1969 error(const char *msg, ...)
1973 exverror(EXERROR, msg, ap);
1980 exerror(int cond, const char *msg, ...)
1984 exverror(cond, msg, ap);
1992 * Table of error messages.
1996 short errcode; /* error number */
1997 char action; /* operation which encountered the error */
2001 * Types of operations (passed to the errmsg routine).
2004 #define E_OPEN 01 /* opening a file */
2005 #define E_CREAT 02 /* creating a file */
2006 #define E_EXEC 04 /* executing a program */
2008 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2010 static const struct errname errormsg[] = {
2015 { ENOENT, E_CREAT },
2017 { ENOTDIR, E_OPEN },
2018 { ENOTDIR, E_CREAT },
2019 { ENOTDIR, E_EXEC },
2021 { EEXIST, E_CREAT },
2060 { ELIBACC, E_EXEC },
2064 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2067 * Return a string describing an error. The returned string may be a
2068 * pointer to a static buffer that will be overwritten on the next call.
2069 * Action describes the operation that got the error.
2073 errmsg(int e, int action)
2075 struct errname const *ep;
2076 static char buf[12];
2078 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2079 if (ep->errcode == e && (ep->action & action) != 0)
2083 snprintf(buf, sizeof buf, "error %d", e);
2088 #ifdef ASH_OPTIMIZE_FOR_SIZE
2091 if (--suppressint == 0 && intpending) {
2095 static void forceinton (void) {
2102 /* flags in argument to evaltree */
2103 #define EV_EXIT 01 /* exit after evaluating tree */
2104 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2105 #define EV_BACKCMD 04 /* command executing within back quotes */
2107 static int evalskip; /* set if we are skipping commands */
2108 static int skipcount; /* number of levels to skip */
2109 static int loopnest; /* current loop nesting level */
2110 static int funcnest; /* depth of function calls */
2113 static struct strlist *cmdenviron; /* environment for builtin command */
2114 static int exitstatus; /* exit status of last command */
2115 static int oexitstatus; /* saved exit status */
2117 static void evalsubshell (const union node *, int);
2118 static void expredir (union node *);
2119 static void eprintlist (struct strlist *);
2121 static union node *parsecmd(int);
2123 * Called to reset things after an exception.
2127 * The eval commmand.
2129 static void evalstring (char *, int);
2132 evalcmd(int argc, char **argv)
2141 STARTSTACKSTR(concat);
2145 STPUTC(*p++, concat);
2146 if ((p = *ap++) == NULL)
2148 STPUTC(' ', concat);
2150 STPUTC('\0', concat);
2151 p = grabstackstr(concat);
2153 evalstring(p, EV_TESTED);
2159 * Execute a command or commands contained in a string.
2162 static void evaltree (union node *, int);
2163 static void setinputstring (char *);
2164 static void popfile (void);
2165 static void setstackmark(struct stackmark *mark);
2166 static void popstackmark(struct stackmark *mark);
2170 evalstring(char *s, int flag)
2173 struct stackmark smark;
2175 setstackmark(&smark);
2177 while ((n = parsecmd(0)) != NEOF) {
2179 popstackmark(&smark);
2182 popstackmark(&smark);
2185 static struct builtincmd *find_builtin (const char *);
2186 static void expandarg (union node *, struct arglist *, int);
2187 static void calcsize (const union node *);
2188 static union node *copynode (const union node *);
2191 * Make a copy of a parse tree.
2194 static int funcblocksize; /* size of structures in function */
2195 static int funcstringsize; /* size of strings in node */
2196 static pointer funcblock; /* block to allocate function from */
2197 static char *funcstring; /* block to allocate strings from */
2200 static inline union node *
2201 copyfunc(union node *n)
2208 funcblock = xmalloc(funcblocksize + funcstringsize);
2209 funcstring = (char *) funcblock + funcblocksize;
2214 * Free a parse tree.
2218 freefunc(union node *n)
2226 * Add a new command entry, replacing any existing command entry for
2231 addcmdentry(char *name, struct cmdentry *entry)
2233 struct tblentry *cmdp;
2236 cmdp = cmdlookup(name, 1);
2237 if (cmdp->cmdtype == CMDFUNCTION) {
2238 freefunc(cmdp->param.func);
2240 cmdp->cmdtype = entry->cmdtype;
2241 cmdp->param = entry->u;
2246 evalloop(const union node *n, int flags)
2253 evaltree(n->nbinary.ch1, EV_TESTED);
2255 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2259 if (evalskip == SKIPBREAK && --skipcount <= 0)
2263 if (n->type == NWHILE) {
2264 if (exitstatus != 0)
2267 if (exitstatus == 0)
2270 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2271 status = exitstatus;
2276 exitstatus = status;
2280 evalfor(const union node *n, int flags)
2282 struct arglist arglist;
2285 struct stackmark smark;
2287 setstackmark(&smark);
2288 arglist.lastp = &arglist.list;
2289 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2290 oexitstatus = exitstatus;
2291 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2295 *arglist.lastp = NULL;
2299 for (sp = arglist.list ; sp ; sp = sp->next) {
2300 setvar(n->nfor.var, sp->text, 0);
2301 evaltree(n->nfor.body, flags & EV_TESTED);
2303 if (evalskip == SKIPCONT && --skipcount <= 0) {
2307 if (evalskip == SKIPBREAK && --skipcount <= 0)
2314 popstackmark(&smark);
2318 evalcase(const union node *n, int flags)
2322 struct arglist arglist;
2323 struct stackmark smark;
2325 setstackmark(&smark);
2326 arglist.lastp = &arglist.list;
2327 oexitstatus = exitstatus;
2328 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2329 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2330 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2331 if (casematch(patp, arglist.list->text)) {
2332 if (evalskip == 0) {
2333 evaltree(cp->nclist.body, flags);
2340 popstackmark(&smark);
2344 * Evaluate a pipeline. All the processes in the pipeline are children
2345 * of the process creating the pipeline. (This differs from some versions
2346 * of the shell, which make the last process in a pipeline the parent
2350 static inline void evalpipe(union node *n)
2353 struct nodelist *lp;
2358 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2360 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2363 jp = makejob(n, pipelen);
2365 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2367 * Search for a command. This is called before we fork so that the
2368 * location of the command will be available in the parent as well as
2369 * the child. The check for "goodname" is an overly conservative
2370 * check that the name will not be subject to expansion.
2373 struct cmdentry entry;
2374 union node *lpn = lp->n;
2375 if (lpn->type == NCMD && lpn->ncmd.args && goodname(lpn->ncmd.args->narg.text))
2376 find_command(lpn->ncmd.args->narg.text, &entry, 0, pathval());
2380 if (pipe(pip) < 0) {
2382 error("Pipe call failed");
2385 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2389 dup_as_newfd(prevfd, 0);
2401 dup_as_newfd(pip[1], 1);
2405 evaltree(lp->n, EV_EXIT);
2413 if (n->npipe.backgnd == 0) {
2415 exitstatus = waitforjob(jp);
2416 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2422 isassignment(const char *word) {
2423 if (!is_name(*word)) {
2428 } while (is_in_name(*word));
2429 return *word == '=';
2434 evalcommand(union node *cmd, int flags)
2436 struct stackmark smark;
2438 struct arglist arglist;
2439 struct arglist varlist;
2445 struct cmdentry cmdentry;
2447 char *volatile savecmdname;
2448 volatile struct shparam saveparam;
2449 struct localvar *volatile savelocalvars;
2453 const struct builtincmd *firstbltin;
2454 struct jmploc *volatile savehandler;
2455 struct jmploc jmploc;
2457 /* Avoid longjmp clobbering */
2464 /* First expand the arguments. */
2465 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2466 setstackmark(&smark);
2467 arglist.lastp = &arglist.list;
2468 varlist.lastp = &varlist.list;
2470 oexitstatus = exitstatus;
2473 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2474 expandarg(argp, &varlist, EXP_VARTILDE);
2477 argp = cmd->ncmd.args; argp && !arglist.list;
2478 argp = argp->narg.next
2480 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2483 struct builtincmd *bcmd;
2485 bcmd = find_builtin(arglist.list->text);
2486 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2487 for (; argp; argp = argp->narg.next) {
2488 if (pseudovarflag && isassignment(argp->narg.text)) {
2489 expandarg(argp, &arglist, EXP_VARTILDE);
2492 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2495 *arglist.lastp = NULL;
2496 *varlist.lastp = NULL;
2497 expredir(cmd->ncmd.redirect);
2499 for (sp = arglist.list ; sp ; sp = sp->next)
2501 argv = stalloc(sizeof (char *) * (argc + 1));
2503 for (sp = arglist.list ; sp ; sp = sp->next) {
2504 TRACE(("evalcommand arg: %s\n", sp->text));
2509 if (iflag && funcnest == 0 && argc > 0)
2513 /* Print the command if xflag is set. */
2516 eprintlist(varlist.list);
2517 eprintlist(arglist.list);
2521 /* Now locate the command. */
2523 cmdentry.cmdtype = CMDBUILTIN;
2524 firstbltin = cmdentry.u.cmd = BLTINCMD;
2526 const char *oldpath;
2527 int findflag = DO_ERR;
2531 * Modify the command lookup path, if a PATH= assignment
2534 for (sp = varlist.list ; sp ; sp = sp->next)
2535 if (varequal(sp->text, defpathvar)) {
2536 path = sp->text + 5;
2537 findflag |= DO_BRUTE;
2540 oldfindflag = findflag;
2543 find_command(argv[0], &cmdentry, findflag, path);
2544 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2548 /* implement bltin and command here */
2549 if (cmdentry.cmdtype != CMDBUILTIN) {
2553 firstbltin = cmdentry.u.cmd;
2555 if (cmdentry.u.cmd == BLTINCMD) {
2557 struct builtincmd *bcmd;
2562 if (!(bcmd = find_builtin(*argv))) {
2563 out2fmt("%s: not found\n", *argv);
2567 cmdentry.u.cmd = bcmd;
2568 if (bcmd != BLTINCMD)
2572 if (cmdentry.u.cmd == find_builtin("command")) {
2577 if (*argv[0] == '-') {
2578 if (!equal(argv[0], "-p")) {
2588 findflag |= DO_BRUTE;
2591 findflag = oldfindflag;
2593 findflag |= DO_NOFUN;
2601 /* Fork off a child process if necessary. */
2602 if (cmd->ncmd.backgnd
2603 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2605 jp = makejob(cmd, 1);
2606 mode = cmd->ncmd.backgnd;
2607 if (forkshell(jp, cmd, mode) != 0)
2608 goto parent; /* at end of routine */
2612 /* This is the child process if a fork occurred. */
2613 /* Execute the command. */
2614 if (cmdentry.cmdtype == CMDFUNCTION) {
2616 trputs("Shell function: "); trargs(argv);
2618 exitstatus = oexitstatus;
2619 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2620 saveparam = shellparam;
2621 shellparam.malloc = 0;
2622 shellparam.nparam = argc - 1;
2623 shellparam.p = argv + 1;
2625 savelocalvars = localvars;
2628 if (setjmp(jmploc.loc)) {
2629 if (exception == EXSHELLPROC) {
2630 freeparam((volatile struct shparam *)
2633 saveparam.optind = shellparam.optind;
2634 saveparam.optoff = shellparam.optoff;
2635 freeparam(&shellparam);
2636 shellparam = saveparam;
2639 localvars = savelocalvars;
2640 handler = savehandler;
2641 longjmp(handler->loc, 1);
2643 savehandler = handler;
2645 for (sp = varlist.list ; sp ; sp = sp->next)
2648 evaltree(cmdentry.u.func, flags & EV_TESTED);
2652 localvars = savelocalvars;
2653 saveparam.optind = shellparam.optind;
2654 saveparam.optoff = shellparam.optoff;
2655 freeparam(&shellparam);
2656 shellparam = saveparam;
2657 handler = savehandler;
2660 if (evalskip == SKIPFUNC) {
2664 if (flags & EV_EXIT)
2665 exitshell(exitstatus);
2666 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2668 trputs("builtin command: "); trargs(argv);
2670 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2671 redirect(cmd->ncmd.redirect, mode);
2672 savecmdname = commandname;
2673 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2674 listsetvar(varlist.list);
2676 cmdenviron = varlist.list;
2679 if (setjmp(jmploc.loc)) {
2681 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2684 savehandler = handler;
2686 commandname = argv[0];
2688 optptr = NULL; /* initialize nextopt */
2689 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2693 if (e != EXSHELLPROC) {
2694 commandname = savecmdname;
2695 if (flags & EV_EXIT)
2696 exitshell(exitstatus);
2698 handler = savehandler;
2700 if ((e != EXERROR && e != EXEXEC)
2701 || cmdentry.u.cmd == BLTINCMD
2702 || cmdentry.u.cmd == DOTCMD
2703 || cmdentry.u.cmd == EVALCMD
2704 || cmdentry.u.cmd == EXECCMD)
2708 if (cmdentry.u.cmd != EXECCMD)
2712 trputs("normal command: "); trargs(argv);
2714 redirect(cmd->ncmd.redirect, 0);
2716 for (sp = varlist.list ; sp ; sp = sp->next)
2717 setvareq(sp->text, VEXPORT|VSTACK);
2718 envp = environment();
2719 shellexec(argv, envp, path, cmdentry.u.index);
2723 parent: /* parent process gets here (if we forked) */
2724 if (mode == 0) { /* argument to fork */
2726 exitstatus = waitforjob(jp);
2732 setvar("_", lastarg, 0);
2733 popstackmark(&smark);
2737 * Evaluate a parse tree. The value is left in the global variable
2741 evaltree(union node *n, int flags)
2745 TRACE(("evaltree(NULL) called\n"));
2748 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2751 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2754 evaltree(n->nbinary.ch2, flags);
2757 evaltree(n->nbinary.ch1, EV_TESTED);
2758 if (evalskip || exitstatus != 0)
2760 evaltree(n->nbinary.ch2, flags);
2763 evaltree(n->nbinary.ch1, EV_TESTED);
2764 if (evalskip || exitstatus == 0)
2766 evaltree(n->nbinary.ch2, flags);
2769 expredir(n->nredir.redirect);
2770 redirect(n->nredir.redirect, REDIR_PUSH);
2771 evaltree(n->nredir.n, flags);
2775 evalsubshell(n, flags);
2778 evalsubshell(n, flags);
2781 evaltree(n->nif.test, EV_TESTED);
2784 if (exitstatus == 0)
2785 evaltree(n->nif.ifpart, flags);
2786 else if (n->nif.elsepart)
2787 evaltree(n->nif.elsepart, flags);
2803 struct builtincmd *bcmd;
2804 struct cmdentry entry;
2806 (bcmd = find_builtin(n->narg.text)) &&
2807 IS_BUILTIN_SPECIAL(bcmd)
2809 out2fmt("%s is a special built-in\n", n->narg.text);
2813 entry.cmdtype = CMDFUNCTION;
2814 entry.u.func = copyfunc(n->narg.next);
2815 addcmdentry(n->narg.text, &entry);
2820 evaltree(n->nnot.com, EV_TESTED);
2821 exitstatus = !exitstatus;
2829 evalcommand(n, flags);
2834 printf("Node type = %d\n", n->type);
2843 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2845 exitshell(exitstatus);
2849 * Kick off a subshell to evaluate a tree.
2853 evalsubshell(const union node *n, int flags)
2856 int backgnd = (n->type == NBACKGND);
2858 expredir(n->nredir.redirect);
2860 if (forkshell(jp, n, backgnd) == 0) {
2862 flags &=~ EV_TESTED;
2863 redirect(n->nredir.redirect, 0);
2864 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2868 exitstatus = waitforjob(jp);
2874 * Compute the names of the files in a redirection list.
2877 static void fixredir(union node *n, const char *text, int err);
2880 expredir(union node *n)
2884 for (redir = n ; redir ; redir = redir->nfile.next) {
2886 fn.lastp = &fn.list;
2887 oexitstatus = exitstatus;
2888 switch (redir->type) {
2894 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2895 redir->nfile.expfname = fn.list->text;
2899 if (redir->ndup.vname) {
2900 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2901 fixredir(redir, fn.list->text, 1);
2910 * Execute a command inside back quotes. If it's a builtin command, we
2911 * want to save its output in a block obtained from malloc. Otherwise
2912 * we fork off a subprocess and get the output of the command via a pipe.
2913 * Should be called with interrupts off.
2917 evalbackcmd(union node *n, struct backcmd *result)
2921 struct stackmark smark; /* unnecessary */
2923 setstackmark(&smark);
2934 error("Pipe call failed");
2936 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2941 dup_as_newfd(pip[1], 1);
2945 evaltree(n, EV_EXIT);
2948 result->fd = pip[0];
2951 popstackmark(&smark);
2952 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2953 result->fd, result->buf, result->nleft, result->jp));
2958 * Execute a simple command.
2963 * Builtin commands. Builtin commands whose functions are closely
2964 * tied to evaluation are implemented here.
2968 * No command given, or a bltin command with no arguments. Set the
2969 * specified variables.
2973 bltincmd(int argc, char **argv)
2976 * Preserve exitstatus of a previous possible redirection
2984 * Handle break and continue commands. Break, continue, and return are
2985 * all handled by setting the evalskip flag. The evaluation routines
2986 * above all check this flag, and if it is set they start skipping
2987 * commands rather than executing them. The variable skipcount is
2988 * the number of loops to break/continue, or the number of function
2989 * levels to return. (The latter is always 1.) It should probably
2990 * be an error to break out of more loops than exist, but it isn't
2991 * in the standard shell so we don't make it one here.
2995 breakcmd(int argc, char **argv)
2997 int n = argc > 1 ? number(argv[1]) : 1;
3000 error("Illegal number: %s", argv[1]);
3004 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3012 * The return command.
3016 returncmd(int argc, char **argv)
3018 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3021 evalskip = SKIPFUNC;
3026 /* Do what ksh does; skip the rest of the file */
3027 evalskip = SKIPFILE;
3034 #ifndef CONFIG_FALSE
3036 false_main(int argc, char **argv)
3044 true_main(int argc, char **argv)
3051 * Controls whether the shell is interactive or not.
3054 static void setsignal(int signo);
3057 static void chkmail(int silent);
3061 setinteractive(int on)
3063 static int is_interactive;
3064 static int do_banner=0;
3066 if (on == is_interactive)
3074 is_interactive = on;
3075 if (do_banner==0 && is_interactive) {
3076 /* Looks like they want an interactive shell */
3077 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3078 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3079 printf( "Enter 'help' for a list of built-in commands.\n\n");
3088 setinteractive(iflag);
3094 execcmd(int argc, char **argv)
3099 iflag = 0; /* exit on error */
3102 for (sp = cmdenviron; sp ; sp = sp->next)
3103 setvareq(sp->text, VEXPORT|VSTACK);
3104 shellexec(argv + 1, environment(), pathval(), 0);
3110 eprintlist(struct strlist *sp)
3112 for (; sp; sp = sp->next) {
3113 out2fmt(" %s",sp->text);
3118 * Exec a program. Never returns. If you change this routine, you may
3119 * have to change the find_command routine as well.
3122 static const char *pathopt; /* set by padvance */
3125 shellexec(char **argv, char **envp, const char *path, int idx)
3130 if (strchr(argv[0], '/') != NULL) {
3131 tryexec(argv[0], argv, envp);
3135 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3136 if (--idx < 0 && pathopt == NULL) {
3137 tryexec(cmdname, argv, envp);
3138 if (errno != ENOENT && errno != ENOTDIR)
3145 /* Map to POSIX errors */
3157 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3162 * Clear traps on a fork.
3169 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3170 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3175 setsignal(tp - trap);
3210 /* from options.c: */
3214 for (i = 0; i < NOPTS; i++)
3230 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3242 static int preadbuffer(void);
3243 static void pushfile (void);
3246 * Read a character from the script, returning PEOF on end of file.
3247 * Nul characters in the input are silently discarded.
3250 #ifndef ASH_OPTIMIZE_FOR_SIZE
3251 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3255 return pgetc_macro();
3261 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3267 return pgetc_macro();
3273 * Undo the last call to pgetc. Only one character may be pushed back.
3274 * PEOF may be pushed back.
3277 static void pungetc(void)
3287 struct parsefile *pf = parsefile;
3296 parsefile = pf->prev;
3298 parsenleft = parsefile->nleft;
3299 parselleft = parsefile->lleft;
3300 parsenextc = parsefile->nextc;
3301 plinno = parsefile->linno;
3307 * Return to top level.
3313 while (parsefile != &basepf)
3318 * Close the file(s) that the shell is reading commands from. Called
3319 * after a fork is done.
3322 static void closescript(void)
3325 if (parsefile->fd > 0) {
3326 close(parsefile->fd);
3333 * Like setinputfile, but takes an open file descriptor. Call this with
3337 static void setinputfd(int fd, int push)
3339 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3345 while (parsefile->strpush)
3349 if (parsefile->buf == NULL)
3350 parsefile->buf = xmalloc(BUFSIZ);
3351 parselleft = parsenleft = 0;
3357 * Set the input to take input from a file. If push is set, push the
3358 * old input onto the stack first.
3362 setinputfile(const char *fname, int push)
3368 if ((fd = open(fname, O_RDONLY)) < 0)
3369 error("Can't open %s", fname);
3371 myfileno2 = dup_as_newfd(fd, 10);
3374 error("Out of file descriptors");
3377 setinputfd(fd, push);
3383 tryexec(char *cmd, char **argv, char **envp)
3387 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3391 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3392 name = get_last_path_component(name);
3395 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3398 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3400 run_applet_by_name(name, argc_l, argv);
3402 execve(cmd, argv, envp);
3407 setinputfile(cmd, 0);
3408 commandname = arg0 = xstrdup(argv[0]);
3410 exraise(EXSHELLPROC);
3415 static char *commandtext (const union node *);
3418 * Do a path search. The variable path (passed by reference) should be
3419 * set to the start of the path before the first call; padvance will update
3420 * this value as it proceeds. Successive calls to padvance will return
3421 * the possible path expansions in sequence. If an option (indicated by
3422 * a percent sign) appears in the path entry then the global variable
3423 * pathopt will be set to point to it; otherwise pathopt will be set to
3427 static const char *pathopt;
3429 static void growstackblock(void);
3433 padvance(const char **path, const char *name)
3443 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3444 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3445 while (stackblocksize() < len)
3449 memcpy(q, start, p - start);
3457 while (*p && *p != ':') p++;
3463 return stalloc(len);
3467 * Wrapper around strcmp for qsort/bsearch/...
3470 pstrcmp(const void *a, const void *b)
3472 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3476 * Find a keyword is in a sorted array.
3479 static const char *const *
3480 findkwd(const char *s)
3482 return bsearch(s, tokname_array + KWDOFFSET,
3483 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3484 sizeof(const char *), pstrcmp);
3488 /*** Command hashing code ***/
3492 hashcmd(int argc, char **argv)
3494 struct tblentry **pp;
3495 struct tblentry *cmdp;
3498 struct cmdentry entry;
3501 const struct alias *ap;
3505 while ((c = nextopt("rvV")) != '\0') {
3509 } else if (c == 'v' || c == 'V') {
3513 if (*argptr == NULL) {
3514 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3515 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3516 if (cmdp->cmdtype != CMDBUILTIN) {
3517 printentry(cmdp, verbose);
3524 while ((name = *argptr++) != NULL) {
3525 if ((cmdp = cmdlookup(name, 0)) != NULL
3526 && (cmdp->cmdtype == CMDNORMAL
3527 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3530 /* Then look at the aliases */
3531 if ((ap = *__lookupalias(name)) != NULL) {
3533 printf("%s is an alias for %s\n", name, ap->val);
3539 /* First look at the keywords */
3540 if (findkwd(name)!=0) {
3542 printf("%s is a shell keyword\n", name);
3548 find_command(name, &entry, DO_ERR, pathval());
3549 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3551 cmdp = cmdlookup(name, 0);
3552 if (cmdp) printentry(cmdp, verbose=='v');
3560 printentry(struct tblentry *cmdp, int verbose)
3566 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3567 if (cmdp->cmdtype == CMDNORMAL) {
3568 idx = cmdp->param.index;
3571 name = padvance(&path, cmdp->cmdname);
3573 } while (--idx >= 0);
3576 } else if (cmdp->cmdtype == CMDBUILTIN) {
3578 out1str("a shell builtin");
3579 } else if (cmdp->cmdtype == CMDFUNCTION) {
3582 out1str("a function\n");
3583 name = commandtext(cmdp->param.func);
3584 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3590 error("internal error: cmdtype %d", cmdp->cmdtype);
3593 puts(cmdp->rehash ? "*" : nullstr);
3598 /*** List the available builtins ***/
3601 static int helpcmd(int argc, char** argv)
3605 printf("\nBuilt-in commands:\n-------------------\n");
3606 for (col=0, i=0; i < NUMBUILTINS; i++) {
3607 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3608 builtincmds[i].name+1);
3614 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3616 extern const struct BB_applet applets[];
3617 extern const size_t NUM_APPLETS;
3619 for (i=0; i < NUM_APPLETS; i++) {
3621 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3631 return EXIT_SUCCESS;
3635 * Resolve a command name. If you change this routine, you may have to
3636 * change the shellexec routine as well.
3639 static int prefix (const char *, const char *);
3642 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3644 struct tblentry *cmdp;
3654 struct builtincmd *bcmd;
3656 /* If name contains a slash, don't use the hash table */
3657 if (strchr(name, '/') != NULL) {
3659 while (stat(name, &statb) < 0) {
3660 if (errno != ENOENT && errno != ENOTDIR)
3662 entry->cmdtype = CMDUNKNOWN;
3663 entry->u.index = -1;
3666 entry->cmdtype = CMDNORMAL;
3667 entry->u.index = -1;
3670 entry->cmdtype = CMDNORMAL;
3676 if (act & DO_BRUTE) {
3677 firstchange = path_change(path, &bltin);
3683 /* If name is in the table, and not invalidated by cd, we're done */
3684 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3685 if (cmdp->cmdtype == CMDFUNCTION) {
3686 if (act & DO_NOFUN) {
3691 } else if (act & DO_BRUTE) {
3692 if ((cmdp->cmdtype == CMDNORMAL &&
3693 cmdp->param.index >= firstchange) ||
3694 (cmdp->cmdtype == CMDBUILTIN &&
3695 ((builtinloc < 0 && bltin >= 0) ?
3696 bltin : builtinloc) >= firstchange)) {
3697 /* need to recompute the entry */
3706 bcmd = find_builtin(name);
3707 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3710 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3713 } else if (act & DO_BRUTE) {
3714 if (firstchange == 0) {
3719 /* If %builtin not in path, check for builtin next */
3720 if (regular || (bltin < 0 && bcmd)) {
3723 entry->cmdtype = CMDBUILTIN;
3724 entry->u.cmd = bcmd;
3728 cmdp = cmdlookup(name, 1);
3729 cmdp->cmdtype = CMDBUILTIN;
3730 cmdp->param.cmd = bcmd;
3735 /* We have to search path. */
3736 prev = -1; /* where to start */
3737 if (cmdp && cmdp->rehash) { /* doing a rehash */
3738 if (cmdp->cmdtype == CMDBUILTIN)
3741 prev = cmdp->param.index;
3747 while ((fullname = padvance(&path, name)) != NULL) {
3748 stunalloc(fullname);
3750 if (idx >= firstchange) {
3754 if (prefix("builtin", pathopt)) {
3755 if ((bcmd = find_builtin(name))) {
3759 } else if (!(act & DO_NOFUN) &&
3760 prefix("func", pathopt)) {
3763 continue; /* ignore unimplemented options */
3766 /* if rehash, don't redo absolute path names */
3767 if (fullname[0] == '/' && idx <= prev &&
3768 idx < firstchange) {
3771 TRACE(("searchexec \"%s\": no change\n", name));
3774 while (stat(fullname, &statb) < 0) {
3775 if (errno != ENOENT && errno != ENOTDIR)
3779 e = EACCES; /* if we fail, this will be the error */
3780 if (!S_ISREG(statb.st_mode))
3782 if (pathopt) { /* this is a %func directory */
3783 stalloc(strlen(fullname) + 1);
3784 readcmdfile(fullname);
3785 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3786 error("%s not defined in %s", name, fullname);
3787 stunalloc(fullname);
3790 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3791 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3792 be a function and we're being called with DO_NOFUN */
3794 entry->cmdtype = CMDNORMAL;
3795 entry->u.index = idx;
3799 cmdp = cmdlookup(name, 1);
3800 cmdp->cmdtype = CMDNORMAL;
3801 cmdp->param.index = idx;
3806 /* We failed. If there was an entry for this command, delete it */
3807 if (cmdp && updatetbl)
3810 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3811 entry->cmdtype = CMDUNKNOWN;
3816 entry->cmdtype = cmdp->cmdtype;
3817 entry->u = cmdp->param;
3823 * Search the table of builtin commands.
3827 bstrcmp(const void *name, const void *b)
3829 return strcmp((const char *)name, (*(const char *const *) b)+1);
3832 static struct builtincmd *
3833 find_builtin(const char *name)
3835 struct builtincmd *bp;
3837 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3845 * Called when a cd is done. Marks all commands so the next time they
3846 * are executed they will be rehashed.
3852 struct tblentry **pp;
3853 struct tblentry *cmdp;
3855 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3856 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3857 if (cmdp->cmdtype == CMDNORMAL
3858 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3867 * Called before PATH is changed. The argument is the new value of PATH;
3868 * pathval() still returns the old value at this point. Called with
3873 changepath(const char *newval)
3878 firstchange = path_change(newval, &bltin);
3879 if (builtinloc < 0 && bltin >= 0)
3880 builtinloc = bltin; /* zap builtins */
3881 clearcmdentry(firstchange);
3887 * Clear out command entries. The argument specifies the first entry in
3888 * PATH which has changed.
3892 clearcmdentry(int firstchange)
3894 struct tblentry **tblp;
3895 struct tblentry **pp;
3896 struct tblentry *cmdp;
3899 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3901 while ((cmdp = *pp) != NULL) {
3902 if ((cmdp->cmdtype == CMDNORMAL &&
3903 cmdp->param.index >= firstchange)
3904 || (cmdp->cmdtype == CMDBUILTIN &&
3905 builtinloc >= firstchange)) {
3918 * Delete all functions.
3924 struct tblentry **tblp;
3925 struct tblentry **pp;
3926 struct tblentry *cmdp;
3929 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3931 while ((cmdp = *pp) != NULL) {
3932 if (cmdp->cmdtype == CMDFUNCTION) {
3934 freefunc(cmdp->param.func);
3947 * Locate a command in the command hash table. If "add" is nonzero,
3948 * add the command to the table if it is not already present. The
3949 * variable "lastcmdentry" is set to point to the address of the link
3950 * pointing to the entry, so that delete_cmd_entry can delete the
3954 static struct tblentry **lastcmdentry;
3956 static struct tblentry *
3957 cmdlookup(const char *name, int add)
3961 struct tblentry *cmdp;
3962 struct tblentry **pp;
3969 pp = &cmdtable[hashval % CMDTABLESIZE];
3970 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3971 if (equal(cmdp->cmdname, name))
3975 if (add && cmdp == NULL) {
3977 cmdp = *pp = xmalloc(sizeof (struct tblentry) - ARB
3978 + strlen(name) + 1);
3980 cmdp->cmdtype = CMDUNKNOWN;
3982 strcpy(cmdp->cmdname, name);
3990 * Delete the command entry returned on the last lookup.
3996 struct tblentry *cmdp;
3999 cmdp = *lastcmdentry;
4000 *lastcmdentry = cmdp->next;
4009 static const unsigned char nodesize[26] = {
4010 ALIGN(sizeof (struct nbinary)),
4011 ALIGN(sizeof (struct ncmd)),
4012 ALIGN(sizeof (struct npipe)),
4013 ALIGN(sizeof (struct nredir)),
4014 ALIGN(sizeof (struct nredir)),
4015 ALIGN(sizeof (struct nredir)),
4016 ALIGN(sizeof (struct nbinary)),
4017 ALIGN(sizeof (struct nbinary)),
4018 ALIGN(sizeof (struct nif)),
4019 ALIGN(sizeof (struct nbinary)),
4020 ALIGN(sizeof (struct nbinary)),
4021 ALIGN(sizeof (struct nfor)),
4022 ALIGN(sizeof (struct ncase)),
4023 ALIGN(sizeof (struct nclist)),
4024 ALIGN(sizeof (struct narg)),
4025 ALIGN(sizeof (struct narg)),
4026 ALIGN(sizeof (struct nfile)),
4027 ALIGN(sizeof (struct nfile)),
4028 ALIGN(sizeof (struct nfile)),
4029 ALIGN(sizeof (struct nfile)),
4030 ALIGN(sizeof (struct nfile)),
4031 ALIGN(sizeof (struct ndup)),
4032 ALIGN(sizeof (struct ndup)),
4033 ALIGN(sizeof (struct nhere)),
4034 ALIGN(sizeof (struct nhere)),
4035 ALIGN(sizeof (struct nnot)),
4041 * Delete a function if it exists.
4045 unsetfunc(char *name)
4047 struct tblentry *cmdp;
4049 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4050 freefunc(cmdp->param.func);
4057 * Locate and print what a word is...
4061 typecmd(int argc, char **argv)
4069 for (i = 1; i < argc; i++) {
4070 argv_a[0] = argv[i];
4073 err |= hashcmd(argc, argv);
4080 commandcmd(int argc, char **argv)
4083 int default_path = 0;
4084 int verify_only = 0;
4085 int verbose_verify_only = 0;
4087 while ((c = nextopt("pvV")) != '\0')
4096 verbose_verify_only = 1;
4100 if (default_path + verify_only + verbose_verify_only > 1 ||
4103 "command [-p] command [arg ...]\n"
4104 "command {-v|-V} command\n");
4108 if (verify_only || verbose_verify_only) {
4112 argv_a[0] = *argptr;
4114 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4115 return hashcmd(argc, argv);
4123 path_change(const char *newval, int *bltin)
4125 const char *old, *new;
4131 firstchange = 9999; /* assume no change */
4137 if ((*old == '\0' && *new == ':')
4138 || (*old == ':' && *new == '\0'))
4140 old = new; /* ignore subsequent differences */
4144 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4151 if (builtinloc >= 0 && *bltin < 0)
4156 * Routines to expand arguments to commands. We have to deal with
4157 * backquotes, shell variables, and file metacharacters.
4162 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4163 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4166 * Structure specifying which parts of the string should be searched
4167 * for IFS characters.
4171 struct ifsregion *next; /* next region in list */
4172 int begoff; /* offset of start of region */
4173 int endoff; /* offset of end of region */
4174 int nulonly; /* search for nul bytes only */
4178 static char *expdest; /* output of current string */
4179 static struct nodelist *argbackq; /* list of back quote expressions */
4180 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4181 static struct ifsregion *ifslastp; /* last struct in list */
4182 static struct arglist exparg; /* holds expanded arg list */
4184 static void argstr (char *, int);
4185 static char *exptilde (char *, int);
4186 static void expbackq (union node *, int, int);
4187 static int subevalvar (char *, char *, int, int, int, int, int);
4188 static int varisset (char *, int);
4189 static void strtodest (const char *, int, int);
4190 static inline void varvalue (char *, int, int);
4191 static void recordregion (int, int, int);
4192 static void removerecordregions (int);
4193 static void ifsbreakup (char *, struct arglist *);
4194 static void ifsfree (void);
4195 static void expandmeta (struct strlist *, int);
4196 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4197 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4198 #if !defined(GLOB_BROKEN)
4199 static inline void addglob (const glob_t *);
4202 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4203 static void expmeta (char *, char *);
4205 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4206 static struct strlist *expsort (struct strlist *);
4207 static struct strlist *msort (struct strlist *, int);
4209 static int patmatch (char *, char *, int);
4210 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4211 static int patmatch2 (char *, char *, int);
4213 static int pmatch (char *, char *, int);
4214 #define patmatch2 patmatch
4216 static char *cvtnum (int, char *);
4219 * Expand shell variables and backquotes inside a here document.
4222 /* arg: the document, fd: where to write the expanded version */
4224 expandhere(union node *arg, int fd)
4227 expandarg(arg, (struct arglist *)NULL, 0);
4228 xwrite(fd, stackblock(), expdest - stackblock());
4233 * Perform variable substitution and command substitution on an argument,
4234 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4235 * perform splitting and file name expansion. When arglist is NULL, perform
4236 * here document expansion.
4240 expandarg(union node *arg, struct arglist *arglist, int flag)
4245 argbackq = arg->narg.backquote;
4246 STARTSTACKSTR(expdest);
4247 ifsfirst.next = NULL;
4249 argstr(arg->narg.text, flag);
4250 if (arglist == NULL) {
4251 return; /* here document expanded */
4253 STPUTC('\0', expdest);
4254 p = grabstackstr(expdest);
4255 exparg.lastp = &exparg.list;
4259 if (flag & EXP_FULL) {
4260 ifsbreakup(p, &exparg);
4261 *exparg.lastp = NULL;
4262 exparg.lastp = &exparg.list;
4263 expandmeta(exparg.list, flag);
4265 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4267 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4270 exparg.lastp = &sp->next;
4273 *exparg.lastp = NULL;
4275 *arglist->lastp = exparg.list;
4276 arglist->lastp = exparg.lastp;
4282 * Expand a variable, and return a pointer to the next character in the
4286 static inline char * evalvar(char *p, int flag)
4299 int quotes = flag & (EXP_FULL | EXP_CASE);
4302 subtype = varflags & VSTYPE;
4307 p = strchr(p, '=') + 1;
4308 again: /* jump here after setting a variable with ${var=text} */
4310 set = varisset(var, varflags & VSNUL);
4313 val = lookupvar(var);
4314 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4321 startloc = expdest - stackblock();
4322 if (set && subtype != VSPLUS) {
4323 /* insert the value of the variable */
4325 varvalue(var, varflags & VSQUOTE, flag);
4326 if (subtype == VSLENGTH) {
4327 varlen = expdest - stackblock() - startloc;
4328 STADJUST(-varlen, expdest);
4331 if (subtype == VSLENGTH) {
4332 varlen = strlen(val);
4336 varflags & VSQUOTE ?
4337 DQSYNTAX : BASESYNTAX,
4344 if (subtype == VSPLUS)
4347 easy = ((varflags & VSQUOTE) == 0 ||
4348 (*var == '@' && shellparam.nparam != 1));
4353 expdest = cvtnum(varlen, expdest);
4360 recordregion(startloc, expdest - stackblock(),
4361 varflags & VSQUOTE);
4377 case VSTRIMRIGHTMAX:
4381 * Terminate the string and start recording the pattern
4384 STPUTC('\0', expdest);
4385 patloc = expdest - stackblock();
4386 if (subevalvar(p, NULL, patloc, subtype,
4387 startloc, varflags, quotes) == 0) {
4388 int amount = (expdest - stackblock() - patloc) + 1;
4389 STADJUST(-amount, expdest);
4391 /* Remove any recorded regions beyond start of variable */
4392 removerecordregions(startloc);
4398 if (subevalvar(p, var, 0, subtype, startloc,
4399 varflags, quotes)) {
4402 * Remove any recorded regions beyond
4405 removerecordregions(startloc);
4420 if (subtype != VSNORMAL) { /* skip to end of alternative */
4423 if ((c = *p++) == CTLESC)
4425 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4427 argbackq = argbackq->next;
4428 } else if (c == CTLVAR) {
4429 if ((*p++ & VSTYPE) != VSNORMAL)
4431 } else if (c == CTLENDVAR) {
4442 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4443 * characters to allow for further processing. Otherwise treat
4444 * $@ like $* since no splitting will be performed.
4448 argstr(char *p, int flag)
4451 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4454 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4455 p = exptilde(p, flag);
4459 case CTLENDVAR: /* ??? */
4462 /* "$@" syntax adherence hack */
4463 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4465 if ((flag & EXP_FULL) != 0)
4475 p = evalvar(p, flag);
4478 case CTLBACKQ|CTLQUOTE:
4479 expbackq(argbackq->n, c & CTLQUOTE, flag);
4480 argbackq = argbackq->next;
4482 #ifdef ASH_MATH_SUPPORT
4490 * sort of a hack - expand tildes in variable
4491 * assignments (after the first '=' and after ':'s).
4494 if (flag & EXP_VARTILDE && *p == '~') {
4501 p = exptilde(p, flag);
4512 exptilde(char *p, int flag)
4514 char c, *startp = p;
4517 int quotes = flag & (EXP_FULL | EXP_CASE);
4519 while ((c = *p) != '\0') {
4526 if (flag & EXP_VARTILDE)
4536 if (*(startp+1) == '\0') {
4537 if ((home = lookupvar("HOME")) == NULL)
4540 if ((pw = getpwnam(startp+1)) == NULL)
4547 strtodest(home, SQSYNTAX, quotes);
4556 removerecordregions(int endoff)
4558 if (ifslastp == NULL)
4561 if (ifsfirst.endoff > endoff) {
4562 while (ifsfirst.next != NULL) {
4563 struct ifsregion *ifsp;
4565 ifsp = ifsfirst.next->next;
4566 ckfree(ifsfirst.next);
4567 ifsfirst.next = ifsp;
4570 if (ifsfirst.begoff > endoff)
4573 ifslastp = &ifsfirst;
4574 ifsfirst.endoff = endoff;
4579 ifslastp = &ifsfirst;
4580 while (ifslastp->next && ifslastp->next->begoff < endoff)
4581 ifslastp=ifslastp->next;
4582 while (ifslastp->next != NULL) {
4583 struct ifsregion *ifsp;
4585 ifsp = ifslastp->next->next;
4586 ckfree(ifslastp->next);
4587 ifslastp->next = ifsp;
4590 if (ifslastp->endoff > endoff)
4591 ifslastp->endoff = endoff;
4595 #ifdef ASH_MATH_SUPPORT
4597 * Expand arithmetic expression. Backup to start of expression,
4598 * evaluate, place result in (backed up) result, adjust string position.
4607 int quotes = flag & (EXP_FULL | EXP_CASE);
4613 * This routine is slightly over-complicated for
4614 * efficiency. First we make sure there is
4615 * enough space for the result, which may be bigger
4616 * than the expression if we add exponentation. Next we
4617 * scan backwards looking for the start of arithmetic. If the
4618 * next previous character is a CTLESC character, then we
4619 * have to rescan starting from the beginning since CTLESC
4620 * characters have to be processed left to right.
4622 CHECKSTRSPACE(10, expdest);
4623 USTPUTC('\0', expdest);
4624 start = stackblock();
4626 while (*p != CTLARI && p >= start)
4629 error("missing CTLARI (shouldn't happen)");
4630 if (p > start && *(p-1) == CTLESC)
4631 for (p = start; *p != CTLARI; p++)
4640 removerecordregions(begoff);
4643 result = arith(p+2, &errcode);
4646 error("divide by zero");
4648 error("syntax error: \"%s\"\n", p+2);
4650 snprintf(p, 12, "%d", result);
4656 recordregion(begoff, p - 1 - start, 0);
4657 result = expdest - p + 1;
4658 STADJUST(-result, expdest);
4663 * Expand stuff in backwards quotes.
4667 expbackq(union node *cmd, int quoted, int flag)
4669 volatile struct backcmd in;
4673 char *dest = expdest;
4674 volatile struct ifsregion saveifs;
4675 struct ifsregion *volatile savelastp;
4676 struct nodelist *volatile saveargbackq;
4678 int startloc = dest - stackblock();
4679 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4680 volatile int saveherefd;
4681 int quotes = flag & (EXP_FULL | EXP_CASE);
4682 struct jmploc jmploc;
4683 struct jmploc *volatile savehandler;
4687 /* Avoid longjmp clobbering */
4698 savelastp = ifslastp;
4699 saveargbackq = argbackq;
4700 saveherefd = herefd;
4702 if ((ex = setjmp(jmploc.loc))) {
4705 savehandler = handler;
4708 p = grabstackstr(dest);
4709 evalbackcmd(cmd, (struct backcmd *) &in);
4710 ungrabstackstr(p, dest);
4714 ifslastp = savelastp;
4715 argbackq = saveargbackq;
4716 herefd = saveherefd;
4724 if (--in.nleft < 0) {
4727 i = safe_read(in.fd, buf, sizeof buf);
4728 TRACE(("expbackq: read returns %d\n", i));
4735 if (lastc != '\0') {
4736 if (quotes && SIT(lastc, syntax) == CCTL)
4737 STPUTC(CTLESC, dest);
4738 STPUTC(lastc, dest);
4742 /* Eat all trailing newlines */
4743 for (; dest > stackblock() && dest[-1] == '\n';)
4752 exitstatus = waitforjob(in.jp);
4753 handler = savehandler;
4755 longjmp(handler->loc, 1);
4758 recordregion(startloc, dest - stackblock(), 0);
4759 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4760 (dest - stackblock()) - startloc,
4761 (dest - stackblock()) - startloc,
4762 stackblock() + startloc));
4768 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
4774 int saveherefd = herefd;
4775 struct nodelist *saveargbackq = argbackq;
4779 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4780 STACKSTRNUL(expdest);
4781 herefd = saveherefd;
4782 argbackq = saveargbackq;
4783 startp = stackblock() + startloc;
4785 str = stackblock() + strloc;
4789 setvar(str, startp, 0);
4790 amount = startp - expdest;
4791 STADJUST(amount, expdest);
4798 if (*p != CTLENDVAR) {
4799 out2fmt(snlfmt, startp);
4800 error((char *)NULL);
4802 error("%.*s: parameter %snot set", p - str - 1,
4803 str, (varflags & VSNUL) ? "null or "
4808 for (loc = startp; loc < str; loc++) {
4811 if (patmatch2(str, startp, quotes))
4814 if (quotes && *loc == CTLESC)
4820 for (loc = str - 1; loc >= startp;) {
4823 if (patmatch2(str, startp, quotes))
4827 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4828 for (q = startp; q < loc; q++)
4838 for (loc = str - 1; loc >= startp;) {
4839 if (patmatch2(str, loc, quotes))
4842 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4843 for (q = startp; q < loc; q++)
4852 case VSTRIMRIGHTMAX:
4853 for (loc = startp; loc < str - 1; loc++) {
4854 if (patmatch2(str, loc, quotes))
4856 if (quotes && *loc == CTLESC)
4869 amount = ((str - 1) - (loc - startp)) - expdest;
4870 STADJUST(amount, expdest);
4871 while (loc != str - 1)
4876 amount = loc - expdest;
4877 STADJUST(amount, expdest);
4878 STPUTC('\0', expdest);
4879 STADJUST(-1, expdest);
4885 * Test whether a specialized variable is set.
4889 varisset(char *name, int nulok)
4892 return backgndpid != -1;
4893 else if (*name == '@' || *name == '*') {
4894 if (*shellparam.p == NULL)
4900 for (av = shellparam.p; *av; av++)
4905 } else if (is_digit(*name)) {
4907 int num = atoi(name);
4909 if (num > shellparam.nparam)
4915 ap = shellparam.p[num - 1];
4917 if (nulok && (ap == NULL || *ap == '\0'))
4924 * Put a string on the stack.
4928 strtodest(const char *p, int syntax, int quotes)
4931 if (quotes && SIT(*p,syntax) == CCTL)
4932 STPUTC(CTLESC, expdest);
4933 STPUTC(*p++, expdest);
4938 * Add the value of a specialized variable to the stack string.
4942 varvalue(char *name, int quoted, int flags)
4951 int allow_split = flags & EXP_FULL;
4952 int quotes = flags & (EXP_FULL | EXP_CASE);
4954 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4963 num = shellparam.nparam;
4968 expdest = cvtnum(num, expdest);
4971 for (i = 0 ; i < NOPTS ; i++) {
4973 STPUTC(optent_letter(optlist[i]), expdest);
4977 if (allow_split && quoted) {
4978 sep = 1 << CHAR_BIT;
4983 sep = ifsset() ? ifsval()[0] : ' ';
4985 sepq = SIT(sep,syntax) == CCTL;
4988 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
4989 strtodest(p, syntax, quotes);
4992 STPUTC(CTLESC, expdest);
4993 STPUTC(sep, expdest);
4998 strtodest(arg0, syntax, quotes);
5002 if (num > 0 && num <= shellparam.nparam) {
5003 strtodest(shellparam.p[num - 1], syntax, quotes);
5011 * Record the fact that we have to scan this region of the
5012 * string for IFS characters.
5016 recordregion(int start, int end, int nulonly)
5018 struct ifsregion *ifsp;
5020 if (ifslastp == NULL) {
5024 ifsp = (struct ifsregion *)xmalloc(sizeof (struct ifsregion));
5026 ifslastp->next = ifsp;
5030 ifslastp->begoff = start;
5031 ifslastp->endoff = end;
5032 ifslastp->nulonly = nulonly;
5038 * Break the argument string into pieces based upon IFS and add the
5039 * strings to the argument list. The regions of the string to be
5040 * searched for IFS characters have been stored by recordregion.
5043 ifsbreakup(char *string, struct arglist *arglist)
5045 struct ifsregion *ifsp;
5050 const char *ifs, *realifs;
5058 realifs = ifsset() ? ifsval() : defifs;
5059 if (ifslastp != NULL) {
5062 p = string + ifsp->begoff;
5063 nulonly = ifsp->nulonly;
5064 ifs = nulonly ? nullstr : realifs;
5066 while (p < string + ifsp->endoff) {
5070 if (strchr(ifs, *p)) {
5072 ifsspc = (strchr(defifs, *p) != NULL);
5073 /* Ignore IFS whitespace at start */
5074 if (q == start && ifsspc) {
5080 sp = (struct strlist *)stalloc(sizeof *sp);
5082 *arglist->lastp = sp;
5083 arglist->lastp = &sp->next;
5087 if (p >= string + ifsp->endoff) {
5093 if (strchr(ifs, *p) == NULL ) {
5096 } else if (strchr(defifs, *p) == NULL) {
5112 } while ((ifsp = ifsp->next) != NULL);
5113 if (!(*start || (!ifsspc && start > string && nulonly))) {
5118 sp = (struct strlist *)stalloc(sizeof *sp);
5120 *arglist->lastp = sp;
5121 arglist->lastp = &sp->next;
5127 while (ifsfirst.next != NULL) {
5128 struct ifsregion *ifsp;
5130 ifsp = ifsfirst.next->next;
5131 ckfree(ifsfirst.next);
5132 ifsfirst.next = ifsp;
5136 ifsfirst.next = NULL;
5140 * Add a file name to the list.
5144 addfname(const char *name)
5148 sp = (struct strlist *)stalloc(sizeof *sp);
5149 sp->text = sstrdup(name);
5151 exparg.lastp = &sp->next;
5155 * Expand shell metacharacters. At this point, the only control characters
5156 * should be escapes. The results are stored in the list exparg.
5159 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5161 expandmeta(struct strlist *str, int flag)
5165 /* TODO - EXP_REDIR */
5170 p = preglob(str->text);
5172 switch (glob(p, 0, 0, &pglob)) {
5174 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5185 *exparg.lastp = str;
5186 rmescapes(str->text);
5187 exparg.lastp = &str->next;
5189 default: /* GLOB_NOSPACE */
5190 error("Out of space");
5198 * Add the result of glob(3) to the list.
5202 addglob(const glob_t *pglob)
5204 char **p = pglob->gl_pathv;
5212 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5213 static char *expdir;
5217 expandmeta(struct strlist *str, int flag)
5220 struct strlist **savelastp;
5223 /* TODO - EXP_REDIR */
5229 for (;;) { /* fast check for meta chars */
5230 if ((c = *p++) == '\0')
5232 if (c == '*' || c == '?' || c == '[' || c == '!')
5235 savelastp = exparg.lastp;
5237 if (expdir == NULL) {
5238 int i = strlen(str->text);
5239 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5242 expmeta(expdir, str->text);
5246 if (exparg.lastp == savelastp) {
5251 *exparg.lastp = str;
5252 rmescapes(str->text);
5253 exparg.lastp = &str->next;
5255 *exparg.lastp = NULL;
5256 *savelastp = sp = expsort(*savelastp);
5257 while (sp->next != NULL)
5259 exparg.lastp = &sp->next;
5267 * Do metacharacter (i.e. *, ?, [...]) expansion.
5271 expmeta(char *enddir, char *name)
5287 for (p = name ; ; p++) {
5288 if (*p == '*' || *p == '?')
5290 else if (*p == '[') {
5295 while (*q == CTLQUOTEMARK)
5299 if (*q == '/' || *q == '\0')
5306 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5308 } else if (*p == '\0')
5310 else if (*p == CTLQUOTEMARK)
5312 else if (*p == CTLESC)
5320 if (metaflag == 0) { /* we've reached the end of the file name */
5321 if (enddir != expdir)
5323 for (p = name ; ; p++) {
5324 if (*p == CTLQUOTEMARK)
5332 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5337 if (start != name) {
5340 while (*p == CTLQUOTEMARK)
5347 if (enddir == expdir) {
5349 } else if (enddir == expdir + 1 && *expdir == '/') {
5355 if ((dirp = opendir(cp)) == NULL)
5357 if (enddir != expdir)
5359 if (*endname == 0) {
5367 while (*p == CTLQUOTEMARK)
5373 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5374 if (dp->d_name[0] == '.' && ! matchdot)
5376 if (patmatch(start, dp->d_name, 0)) {
5378 strcpy(enddir, dp->d_name);
5381 for (p = enddir, cp = dp->d_name;
5382 (*p++ = *cp++) != '\0';)
5385 expmeta(p, endname);
5393 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5397 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5399 * Sort the results of file name expansion. It calculates the number of
5400 * strings to sort and then calls msort (short for merge sort) to do the
5404 static struct strlist *
5405 expsort(struct strlist *str)
5411 for (sp = str ; sp ; sp = sp->next)
5413 return msort(str, len);
5417 static struct strlist *
5418 msort(struct strlist *list, int len)
5420 struct strlist *p, *q = NULL;
5421 struct strlist **lpp;
5429 for (n = half ; --n >= 0 ; ) {
5433 q->next = NULL; /* terminate first half of list */
5434 q = msort(list, half); /* sort first half of list */
5435 p = msort(p, len - half); /* sort second half */
5438 if (strcmp(p->text, q->text) < 0) {
5441 if ((p = *lpp) == NULL) {
5448 if ((q = *lpp) == NULL) {
5461 * Returns true if the pattern matches the string.
5464 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5465 /* squoted: string might have quote chars */
5467 patmatch(char *pattern, char *string, int squoted)
5472 p = preglob(pattern);
5473 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5475 return !fnmatch(p, q, 0);
5480 patmatch2(char *pattern, char *string, int squoted)
5486 p = grabstackstr(expdest);
5487 res = patmatch(pattern, string, squoted);
5488 ungrabstackstr(p, expdest);
5493 patmatch(char *pattern, char *string, int squoted) {
5494 return pmatch(pattern, string, squoted);
5499 pmatch(char *pattern, char *string, int squoted)
5511 if (squoted && *q == CTLESC)
5519 if (squoted && *q == CTLESC)
5526 while (c == CTLQUOTEMARK || c == '*')
5528 if (c != CTLESC && c != CTLQUOTEMARK &&
5529 c != '?' && c != '*' && c != '[') {
5531 if (squoted && *q == CTLESC &&
5536 if (squoted && *q == CTLESC)
5542 if (pmatch(p, q, squoted))
5544 if (squoted && *q == CTLESC)
5546 } while (*q++ != '\0');
5557 while (*endp == CTLQUOTEMARK)
5560 goto dft; /* no matching ] */
5561 if (*endp == CTLESC)
5573 if (squoted && chr == CTLESC)
5579 if (c == CTLQUOTEMARK)
5583 if (*p == '-' && p[1] != ']') {
5585 while (*p == CTLQUOTEMARK)
5589 if (chr >= c && chr <= *p)
5596 } while ((c = *p++) != ']');
5597 if (found == invert)
5602 if (squoted && *q == CTLESC)
5619 * Remove any CTLESC characters from a string.
5622 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5624 _rmescapes(char *str, int flag)
5627 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5629 p = strpbrk(str, qchars);
5635 if (flag & RMESCAPE_ALLOC) {
5636 size_t len = p - str;
5637 q = r = stalloc(strlen(p) + len + 1);
5639 memcpy(q, str, len);
5644 if (*p == CTLQUOTEMARK) {
5650 if (flag & RMESCAPE_GLOB && *p != '/') {
5661 rmescapes(char *str)
5666 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5672 if (*p == CTLQUOTEMARK) {
5687 * See if a pattern matches in a case statement.
5691 casematch(union node *pattern, const char *val)
5693 struct stackmark smark;
5697 setstackmark(&smark);
5698 argbackq = pattern->narg.backquote;
5699 STARTSTACKSTR(expdest);
5701 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5702 STPUTC('\0', expdest);
5703 p = grabstackstr(expdest);
5704 result = patmatch(p, (char *)val, 0);
5705 popstackmark(&smark);
5714 cvtnum(int num, char *buf)
5718 CHECKSTRSPACE(32, buf);
5719 len = sprintf(buf, "%d", num);
5724 * Editline and history functions (and glue).
5726 static int histcmd(int argc, char **argv)
5728 error("not compiled with history support");
5734 struct redirtab *next;
5735 short renamed[10]; /* Current ash support only 0-9 descriptors */
5736 /* char on arm (and others) can't be negative */
5739 static struct redirtab *redirlist;
5741 extern char **environ;
5746 * Initialization code.
5760 basepf.nextc = basepf.buf = basebuf;
5769 for (envp = environ ; *envp ; envp++) {
5770 if (strchr(*envp, '=')) {
5771 setvareq(*envp, VEXPORT|VTEXTFIXED);
5775 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5776 setvar("PPID", ppid, 0);
5783 * This routine is called when an error or an interrupt occurs in an
5784 * interactive shell and control is returned to the main command loop.
5787 /* 1 == check for aliases, 2 == also check for assignments */
5788 static int checkalias; /* also used in no alias mode for check assignments */
5802 if (exception != EXSHELLPROC)
5803 parselleft = parsenleft = 0; /* clear input buffer */
5807 /* from parser.c: */
5825 * This file implements the input routines used by the parser.
5828 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5829 static const char * cmdedit_prompt;
5830 static inline void putprompt(const char *s) {
5834 static inline void putprompt(const char *s) {
5839 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5844 * Same as pgetc(), but ignores PEOA.
5854 } while (c == PEOA);
5858 static inline int pgetc2() { return pgetc_macro(); }
5862 * Read a line from the script.
5865 static inline char *
5866 pfgets(char *line, int len)
5872 while (--nleft > 0) {
5891 char *buf = parsefile->buf;
5895 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5897 if (!iflag || parsefile->fd)
5898 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5900 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5904 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5908 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5909 int flags = fcntl(0, F_GETFL, 0);
5910 if (flags >= 0 && flags & O_NONBLOCK) {
5911 flags &=~ O_NONBLOCK;
5912 if (fcntl(0, F_SETFL, flags) >= 0) {
5913 out2str("sh: turning off NDELAY mode\n");
5925 struct strpush *sp = parsefile->strpush;
5930 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5935 if (sp->string != sp->ap->val) {
5939 sp->ap->flag &= ~ALIASINUSE;
5940 if (sp->ap->flag & ALIASDEAD) {
5941 unalias(sp->ap->name);
5945 parsenextc = sp->prevstring;
5946 parsenleft = sp->prevnleft;
5947 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5948 parsefile->strpush = sp->prev;
5949 if (sp != &(parsefile->basestrpush))
5956 * Refill the input buffer and return the next input character:
5958 * 1) If a string was pushed back on the input, pop it;
5959 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5960 * from a string so we can't refill the buffer, return EOF.
5961 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5962 * 4) Process input up to the next newline, deleting nul characters.
5972 while (parsefile->strpush) {
5974 if (parsenleft == -1 && parsefile->strpush->ap &&
5975 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5980 if (--parsenleft >= 0)
5981 return (*parsenextc++);
5983 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5988 if (parselleft <= 0) {
5989 if ((parselleft = preadfd()) <= 0) {
5990 parselleft = parsenleft = EOF_NLEFT;
5997 /* delete nul characters */
5998 for (more = 1; more;) {
6006 parsenleft = q - parsenextc;
6007 more = 0; /* Stop processing here */
6013 if (--parselleft <= 0 && more) {
6014 parsenleft = q - parsenextc - 1;
6025 out2str(parsenextc);
6030 return *parsenextc++;
6035 * Push a string back onto the input at this current parsefile level.
6036 * We handle aliases this way.
6039 pushstring(char *s, int len, void *ap)
6044 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6045 if (parsefile->strpush) {
6046 sp = xmalloc(sizeof (struct strpush));
6047 sp->prev = parsefile->strpush;
6048 parsefile->strpush = sp;
6050 sp = parsefile->strpush = &(parsefile->basestrpush);
6051 sp->prevstring = parsenextc;
6052 sp->prevnleft = parsenleft;
6054 sp->ap = (struct alias *)ap;
6056 ((struct alias *)ap)->flag |= ALIASINUSE;
6067 * Like setinputfile, but takes input from a string.
6071 setinputstring(char *string)
6075 parsenextc = string;
6076 parsenleft = strlen(string);
6077 parsefile->buf = NULL;
6085 * To handle the "." command, a stack of input files is used. Pushfile
6086 * adds a new entry to the stack and popfile restores the previous level.
6092 struct parsefile *pf;
6094 parsefile->nleft = parsenleft;
6095 parsefile->lleft = parselleft;
6096 parsefile->nextc = parsenextc;
6097 parsefile->linno = plinno;
6098 pf = (struct parsefile *)xmalloc(sizeof (struct parsefile));
6099 pf->prev = parsefile;
6102 pf->basestrpush.prev = NULL;
6107 static void restartjob (struct job *);
6109 static void freejob (struct job *);
6110 static struct job *getjob (const char *);
6111 static int dowait (int, struct job *);
6112 static void waitonint(int);
6116 * We keep track of whether or not fd0 has been redirected. This is for
6117 * background commands, where we want to redirect fd0 to /dev/null only
6118 * if it hasn't already been redirected.
6120 static int fd0_redirected = 0;
6122 /* Return true if fd 0 has already been redirected at least once. */
6124 fd0_redirected_p (void)
6126 return fd0_redirected != 0;
6129 static void dupredirect (const union node *, int, int fd1dup);
6133 * Turn job control on and off.
6135 * Note: This code assumes that the third arg to ioctl is a character
6136 * pointer, which is true on Berkeley systems but not System V. Since
6137 * System V doesn't have job control yet, this isn't a problem now.
6142 static void setjobctl(int enable)
6144 #ifdef OLD_TTY_DRIVER
6148 if (enable == jobctl || rootshell == 0)
6151 do { /* while we are in the background */
6152 #ifdef OLD_TTY_DRIVER
6153 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6155 initialpgrp = tcgetpgrp(2);
6156 if (initialpgrp < 0) {
6158 out2str("sh: can't access tty; job control turned off\n");
6162 if (initialpgrp == -1)
6163 initialpgrp = getpgrp();
6164 else if (initialpgrp != getpgrp()) {
6165 killpg(initialpgrp, SIGTTIN);
6169 #ifdef OLD_TTY_DRIVER
6170 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6171 out2str("sh: need new tty driver to run job control; job control turned off\n");
6179 setpgid(0, rootpid);
6180 #ifdef OLD_TTY_DRIVER
6181 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6183 tcsetpgrp(2, rootpid);
6185 } else { /* turning job control off */
6186 setpgid(0, initialpgrp);
6187 #ifdef OLD_TTY_DRIVER
6188 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6190 tcsetpgrp(2, initialpgrp);
6203 killcmd(int argc, char **argv)
6214 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6215 "kill -l [exitstatus]"
6219 if (*argv[1] == '-') {
6220 signo = decode_signal(argv[1] + 1, 1);
6224 while ((c = nextopt("ls:")) != '\0')
6230 signo = decode_signal(optionarg, 1);
6233 "invalid signal number or name: %s",
6241 "nextopt returned character code 0%o", c);
6248 if (!list && signo < 0)
6251 if ((signo < 0 || !*argptr) ^ list) {
6260 for (i = 1; i < NSIG; i++) {
6261 name = u_signal_names(0, &i, 1);
6267 name = u_signal_names(*argptr, &signo, -1);
6271 error("invalid signal number or exit status: %s",
6277 if (**argptr == '%') {
6278 jp = getjob(*argptr);
6279 if (jp->jobctl == 0)
6280 error("job %s not created under job control",
6282 pid = -jp->ps[0].pid;
6284 pid = atoi(*argptr);
6285 if (kill(pid, signo) != 0)
6286 error("%s: %m", *argptr);
6287 } while (*++argptr);
6293 fgcmd(int argc, char **argv)
6299 jp = getjob(argv[1]);
6300 if (jp->jobctl == 0)
6301 error("job not created under job control");
6302 pgrp = jp->ps[0].pid;
6303 #ifdef OLD_TTY_DRIVER
6304 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6309 status = waitforjob(jp);
6315 bgcmd(int argc, char **argv)
6320 jp = getjob(*++argv);
6321 if (jp->jobctl == 0)
6322 error("job not created under job control");
6324 } while (--argc > 1);
6330 restartjob(struct job *jp)
6332 struct procstat *ps;
6335 if (jp->state == JOBDONE)
6338 killpg(jp->ps[0].pid, SIGCONT);
6339 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6340 if (WIFSTOPPED(ps->status)) {
6349 static void showjobs(int change);
6353 jobscmd(int argc, char **argv)
6361 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6362 * statuses have changed since the last call to showjobs.
6364 * If the shell is interrupted in the process of creating a job, the
6365 * result may be a job structure containing zero processes. Such structures
6366 * will be freed here.
6370 showjobs(int change)
6376 struct procstat *ps;
6380 TRACE(("showjobs(%d) called\n", change));
6381 while (dowait(0, (struct job *)NULL) > 0);
6382 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6385 if (jp->nprocs == 0) {
6389 if (change && ! jp->changed)
6391 procno = jp->nprocs;
6392 for (ps = jp->ps ; ; ps++) { /* for each process */
6394 snprintf(s, 64, "[%d] %ld ", jobno,
6397 snprintf(s, 64, " %ld ",
6402 if (ps->status == -1) {
6403 /* don't print anything */
6404 } else if (WIFEXITED(ps->status)) {
6405 snprintf(s, 64, "Exit %d",
6406 WEXITSTATUS(ps->status));
6409 if (WIFSTOPPED(ps->status))
6410 i = WSTOPSIG(ps->status);
6411 else /* WIFSIGNALED(ps->status) */
6413 i = WTERMSIG(ps->status);
6414 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6415 strcpy(s, sys_siglist[i & 0x7F]);
6417 snprintf(s, 64, "Signal %d", i & 0x7F);
6418 if (WCOREDUMP(ps->status))
6419 strcat(s, " (core dumped)");
6424 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6431 if (jp->state == JOBDONE) {
6439 * Mark a job structure as unused.
6443 freejob(struct job *jp)
6445 const struct procstat *ps;
6449 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6450 if (ps->cmd != nullstr)
6453 if (jp->ps != &jp->ps0)
6457 if (curjob == jp - jobtab + 1)
6466 waitcmd(int argc, char **argv)
6474 job = getjob(*++argv);
6478 for (;;) { /* loop until process terminated or stopped */
6481 status = job->ps[job->nprocs - 1].status;
6487 if (WIFEXITED(status))
6488 retval = WEXITSTATUS(status);
6490 else if (WIFSTOPPED(status))
6491 retval = WSTOPSIG(status) + 128;
6494 /* XXX: limits number of signals */
6495 retval = WTERMSIG(status) + 128;
6500 for (jp = jobtab ; ; jp++) {
6501 if (jp >= jobtab + njobs) { /* no running procs */
6504 if (jp->used && jp->state == 0)
6508 if (dowait(2, 0) < 0 && errno == EINTR) {
6517 * Convert a job name to a job structure.
6521 getjob(const char *name)
6531 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6532 error("No current job");
6533 return &jobtab[jobno - 1];
6535 error("No current job");
6537 } else if (name[0] == '%') {
6538 if (is_digit(name[1])) {
6539 jobno = number(name + 1);
6540 if (jobno > 0 && jobno <= njobs
6541 && jobtab[jobno - 1].used != 0)
6542 return &jobtab[jobno - 1];
6544 } else if (name[1] == '%' && name[2] == '\0') {
6548 struct job *found = NULL;
6549 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6550 if (jp->used && jp->nprocs > 0
6551 && prefix(name + 1, jp->ps[0].cmd)) {
6553 error("%s: ambiguous", name);
6560 } else if (is_number(name, &pid)) {
6561 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6562 if (jp->used && jp->nprocs > 0
6563 && jp->ps[jp->nprocs - 1].pid == pid)
6567 error("No such job: %s", name);
6574 * Return a new job structure,
6578 makejob(const union node *node, int nprocs)
6583 for (i = njobs, jp = jobtab ; ; jp++) {
6587 jobtab = xmalloc(4 * sizeof jobtab[0]);
6589 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6590 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6591 /* Relocate `ps' pointers */
6592 for (i = 0; i < njobs; i++)
6593 if (jp[i].ps == &jobtab[i].ps0)
6594 jp[i].ps = &jp[i].ps0;
6598 jp = jobtab + njobs;
6599 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6612 jp->jobctl = jobctl;
6615 jp->ps = xmalloc(nprocs * sizeof (struct procstat));
6620 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6627 * Fork of a subshell. If we are doing job control, give the subshell its
6628 * own process group. Jp is a job structure that the job is to be added to.
6629 * N is the command that will be evaluated by the child. Both jp and n may
6630 * be NULL. The mode parameter can be one of the following:
6631 * FORK_FG - Fork off a foreground process.
6632 * FORK_BG - Fork off a background process.
6633 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6634 * process group even if job control is on.
6636 * When job control is turned off, background processes have their standard
6637 * input redirected to /dev/null (except for the second and later processes
6644 forkshell(struct job *jp, const union node *n, int mode)
6650 const char *devnull = _PATH_DEVNULL;
6651 const char *nullerr = "Can't open %s";
6653 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6656 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6662 TRACE(("Fork failed, errno=%d\n", errno));
6664 error("Cannot fork");
6671 TRACE(("Child shell %d\n", getpid()));
6672 wasroot = rootshell;
6678 jobctl = 0; /* do job control only in root shell */
6679 if (wasroot && mode != FORK_NOJOB && mflag) {
6680 if (jp == NULL || jp->nprocs == 0)
6683 pgrp = jp->ps[0].pid;
6685 if (mode == FORK_FG) {
6686 /*** this causes superfluous TIOCSPGRPS ***/
6687 #ifdef OLD_TTY_DRIVER
6688 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6689 error("TIOCSPGRP failed, errno=%d", errno);
6691 if (tcsetpgrp(2, pgrp) < 0)
6692 error("tcsetpgrp failed, errno=%d", errno);
6697 } else if (mode == FORK_BG) {
6700 if ((jp == NULL || jp->nprocs == 0) &&
6701 ! fd0_redirected_p ()) {
6703 if (open(devnull, O_RDONLY) != 0)
6704 error(nullerr, devnull);
6708 if (mode == FORK_BG) {
6711 if ((jp == NULL || jp->nprocs == 0) &&
6712 ! fd0_redirected_p ()) {
6714 if (open(devnull, O_RDONLY) != 0)
6715 error(nullerr, devnull);
6719 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6722 if (wasroot && iflag) {
6730 if (rootshell && mode != FORK_NOJOB && mflag) {
6731 if (jp == NULL || jp->nprocs == 0)
6734 pgrp = jp->ps[0].pid;
6738 if (mode == FORK_BG)
6739 backgndpid = pid; /* set $! */
6741 struct procstat *ps = &jp->ps[jp->nprocs++];
6745 if (iflag && rootshell && n)
6746 ps->cmd = commandtext(n);
6749 TRACE(("In parent shell: child = %d\n", pid));
6756 * Wait for job to finish.
6758 * Under job control we have the problem that while a child process is
6759 * running interrupts generated by the user are sent to the child but not
6760 * to the shell. This means that an infinite loop started by an inter-
6761 * active user may be hard to kill. With job control turned off, an
6762 * interactive user may place an interactive program inside a loop. If
6763 * the interactive program catches interrupts, the user doesn't want
6764 * these interrupts to also abort the loop. The approach we take here
6765 * is to have the shell ignore interrupt signals while waiting for a
6766 * forground process to terminate, and then send itself an interrupt
6767 * signal if the child process was terminated by an interrupt signal.
6768 * Unfortunately, some programs want to do a bit of cleanup and then
6769 * exit on interrupt; unless these processes terminate themselves by
6770 * sending a signal to themselves (instead of calling exit) they will
6771 * confuse this approach.
6775 waitforjob(struct job *jp)
6778 int mypgrp = getpgrp();
6782 struct sigaction act, oact;
6791 sigaction(SIGINT, 0, &act);
6792 act.sa_handler = waitonint;
6793 sigaction(SIGINT, &act, &oact);
6795 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6796 while (jp->state == 0) {
6804 sigaction(SIGINT, &oact, 0);
6805 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6809 #ifdef OLD_TTY_DRIVER
6810 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6811 error("TIOCSPGRP failed, errno=%d\n", errno);
6813 if (tcsetpgrp(2, mypgrp) < 0)
6814 error("tcsetpgrp failed, errno=%d\n", errno);
6817 if (jp->state == JOBSTOPPED)
6818 curjob = jp - jobtab + 1;
6820 status = jp->ps[jp->nprocs - 1].status;
6821 /* convert to 8 bits */
6822 if (WIFEXITED(status))
6823 st = WEXITSTATUS(status);
6825 else if (WIFSTOPPED(status))
6826 st = WSTOPSIG(status) + 128;
6829 st = WTERMSIG(status) + 128;
6833 * This is truly gross.
6834 * If we're doing job control, then we did a TIOCSPGRP which
6835 * caused us (the shell) to no longer be in the controlling
6836 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6837 * intuit from the subprocess exit status whether a SIGINT
6838 * occured, and if so interrupt ourselves. Yuck. - mycroft
6840 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6843 if (jp->state == JOBDONE)
6854 * Wait for a process to terminate.
6858 * Do a wait system call. If job control is compiled in, we accept
6859 * stopped processes. If block is zero, we return a value of zero
6860 * rather than blocking.
6862 * System V doesn't have a non-blocking wait system call. It does
6863 * have a SIGCLD signal that is sent to a process when one of it's
6864 * children dies. The obvious way to use SIGCLD would be to install
6865 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6866 * was received, and have waitproc bump another counter when it got
6867 * the status of a process. Waitproc would then know that a wait
6868 * system call would not block if the two counters were different.
6869 * This approach doesn't work because if a process has children that
6870 * have not been waited for, System V will send it a SIGCLD when it
6871 * installs a signal handler for SIGCLD. What this means is that when
6872 * a child exits, the shell will be sent SIGCLD signals continuously
6873 * until is runs out of stack space, unless it does a wait call before
6874 * restoring the signal handler. The code below takes advantage of
6875 * this (mis)feature by installing a signal handler for SIGCLD and
6876 * then checking to see whether it was called. If there are any
6877 * children to be waited for, it will be.
6882 waitproc(int block, int *status)
6893 return wait3(status, flags, (struct rusage *)NULL);
6897 dowait(int block, struct job *job)
6901 struct procstat *sp;
6903 struct job *thisjob;
6909 TRACE(("dowait(%d) called\n", block));
6911 pid = waitproc(block, &status);
6912 TRACE(("wait returns %d, status=%d\n", pid, status));
6913 } while (!(block & 2) && pid == -1 && errno == EINTR);
6918 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
6922 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
6925 if (sp->pid == pid) {
6926 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
6927 sp->status = status;
6930 if (sp->status == -1)
6932 else if (WIFSTOPPED(sp->status))
6935 if (stopped) { /* stopped or done */
6936 int state = done? JOBDONE : JOBSTOPPED;
6937 if (jp->state != state) {
6938 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
6941 if (done && curjob == jp - jobtab + 1)
6942 curjob = 0; /* no current job */
6949 if (! rootshell || ! iflag || (job && thisjob == job)) {
6950 core = WCOREDUMP(status);
6952 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
6955 if (WIFEXITED(status)) sig = 0;
6956 else sig = WTERMSIG(status);
6958 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6960 out2fmt("%d: ", pid);
6962 if (sig == SIGTSTP && rootshell && iflag)
6964 (long)(job - jobtab + 1));
6966 if (sig < NSIG && sys_siglist[sig])
6967 out2str(sys_siglist[sig]);
6969 out2fmt("Signal %d", sig);
6971 out2str(" - core dumped");
6974 TRACE(("Not printing status: status=%d, sig=%d\n",
6978 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
6980 thisjob->changed = 1;
6989 * return 1 if there are stopped jobs, otherwise 0
6999 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7002 if (jp->state == JOBSTOPPED) {
7003 out2str("You have stopped jobs.\n");
7013 * Return a string identifying a command (to be printed by the
7017 static char *cmdnextc;
7018 static int cmdnleft;
7019 #define MAXCMDTEXT 200
7022 cmdputs(const char *s)
7033 while ((c = *p++) != '\0') {
7036 else if (c == CTLVAR) {
7041 } else if (c == '=' && subtype != 0) {
7042 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7044 } else if (c == CTLENDVAR) {
7046 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7047 cmdnleft++; /* ignore it */
7050 if (--cmdnleft <= 0) {
7060 #define CMDTXT_TABLE
7063 * To collect a lot of redundant code in cmdtxt() case statements, we
7064 * implement a mini language here. Each type of node struct has an
7065 * associated instruction sequence that operates on its members via
7066 * their offsets. The instruction are pack in unsigned chars with
7067 * format IIDDDDDE where the bits are
7068 * I : part of the instruction opcode, which are
7069 * 00 : member is a pointer to another node -- process it recursively
7070 * 40 : member is a pointer to a char string -- output it
7071 * 80 : output the string whose index is stored in the data field
7072 * CC : flag signaling that this case needs external processing
7073 * D : data - either the (shifted) index of a fixed string to output or
7074 * the actual offset of the member to operate on in the struct
7075 * (since we assume bit 0 is set, the offset is not shifted)
7076 * E : flag signaling end of instruction sequence
7078 * WARNING: In order to handle larger offsets for 64bit archs, this code
7079 * assumes that no offset can be an odd number and stores the
7080 * end-of-instructions flag in bit 0.
7083 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7084 #define CMDTXT_CHARPTR 0x40
7085 #define CMDTXT_STRING 0x80
7086 #define CMDTXT_SPECIAL 0xC0
7087 #define CMDTXT_OFFSETMASK 0x3E
7089 static const char * const cmdtxt_strings[] = {
7090 /* 0 1 2 3 4 5 6 7 */
7091 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7092 /* 8 9 10 11 12 13 */
7093 "while ", "; do ", "; done", "until ", "for ", " in ...",
7095 "case ", "???", "() ...", "<<..."
7098 static const char * const redir_strings[] = {
7099 ">", "<", "<>", ">>", ">|", ">&", "<&"
7102 static const unsigned char cmdtxt_ops[] = {
7103 #define CMDTXT_NSEMI 0
7104 offsetof(union node, nbinary.ch1),
7106 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7107 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7108 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7109 #define CMDTXT_NCASE (CMDTXT_NCMD)
7110 #define CMDTXT_NTO (CMDTXT_NCMD)
7111 #define CMDTXT_NFROM (CMDTXT_NCMD)
7112 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7113 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7114 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7115 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7116 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7118 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7119 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7120 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7121 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7122 (1*2)|CMDTXT_STRING,
7123 offsetof(union node, nredir.n),
7124 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7125 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7126 offsetof(union node, nbinary.ch1),
7127 (3*2)|CMDTXT_STRING,
7128 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7129 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7130 offsetof(union node, nbinary.ch1),
7131 (4*2)|CMDTXT_STRING,
7132 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7133 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7134 (5*2)|CMDTXT_STRING,
7135 offsetof(union node, nif.test),
7136 (6*2)|CMDTXT_STRING,
7137 offsetof(union node, nif.ifpart),
7138 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7139 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7140 (8*2)|CMDTXT_STRING,
7141 offsetof(union node, nbinary.ch1),
7142 (9*2)|CMDTXT_STRING,
7143 offsetof(union node, nbinary.ch2),
7144 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7145 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7146 (11*2)|CMDTXT_STRING,
7147 offsetof(union node, nbinary.ch1),
7148 (9*2)|CMDTXT_STRING,
7149 offsetof(union node, nbinary.ch2),
7150 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7151 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7152 (12*2)|CMDTXT_STRING,
7153 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7154 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7155 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7156 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7157 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7158 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7159 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7160 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7161 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7162 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7163 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7164 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7165 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7168 #if CMDTXT_NXHERE != 36
7169 #error CMDTXT_NXHERE
7172 static const unsigned char cmdtxt_ops_index[26] = {
7202 cmdtxt(const union node *n)
7209 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7210 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7212 if (*p & CMDTXT_STRING) { /* output fixed string */
7213 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7215 const char *pf = ((const char *) n)
7216 + ((int)(*p & CMDTXT_OFFSETMASK));
7217 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7218 cmdputs(*((const char **) pf));
7219 } else { /* output field */
7220 cmdtxt(*((const union node **) pf));
7223 } while (!(*p++ & CMDTXT_NOMORE));
7224 } else if (n->type == NCMD) {
7226 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7231 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7235 } else if (n->type == NPIPE) {
7236 struct nodelist *lp;
7237 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7242 } else if (n->type == NCASE) {
7243 cmdputs(cmdtxt_strings[14]);
7244 cmdputs(n->ncase.expr->narg.text);
7245 cmdputs(cmdtxt_strings[13]);
7247 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7248 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7253 assert((n->type >= NTO) && (n->type <= NFROMFD));
7256 p = redir_strings[n->type - NTO];
7257 if (n->nfile.fd != ('>' == *p)) {
7258 s[0] = n->nfile.fd + '0';
7263 if (n->type >= NTOFD) {
7264 s[0] = n->ndup.dupfd + '0';
7268 cmdtxt(n->nfile.fname);
7272 #else /* CMDTXT_TABLE */
7274 cmdtxt(const union node *n)
7277 struct nodelist *lp;
7286 cmdtxt(n->nbinary.ch1);
7288 cmdtxt(n->nbinary.ch2);
7291 cmdtxt(n->nbinary.ch1);
7293 cmdtxt(n->nbinary.ch2);
7296 cmdtxt(n->nbinary.ch1);
7298 cmdtxt(n->nbinary.ch2);
7301 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7309 cmdtxt(n->nredir.n);
7314 cmdtxt(n->nredir.n);
7318 cmdtxt(n->nif.test);
7320 cmdtxt(n->nif.ifpart);
7329 cmdtxt(n->nbinary.ch1);
7331 cmdtxt(n->nbinary.ch2);
7336 cmdputs(n->nfor.var);
7341 cmdputs(n->ncase.expr->narg.text);
7345 cmdputs(n->narg.text);
7349 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7354 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7360 cmdputs(n->narg.text);
7363 p = ">"; i = 1; goto redir;
7365 p = ">>"; i = 1; goto redir;
7367 p = ">&"; i = 1; goto redir;
7369 p = ">|"; i = 1; goto redir;
7371 p = "<"; i = 0; goto redir;
7373 p = "<&"; i = 0; goto redir;
7375 p = "<>"; i = 0; goto redir;
7377 if (n->nfile.fd != i) {
7378 s[0] = n->nfile.fd + '0';
7383 if (n->type == NTOFD || n->type == NFROMFD) {
7384 s[0] = n->ndup.dupfd + '0';
7388 cmdtxt(n->nfile.fname);
7400 #endif /* CMDTXT_TABLE */
7403 commandtext(const union node *n)
7407 cmdnextc = name = xmalloc(MAXCMDTEXT);
7408 cmdnleft = MAXCMDTEXT - 4;
7415 static void waitonint(int sig) {
7423 * Routines to check for mail.
7427 #define MAXMBOXES 10
7430 static int nmboxes; /* number of mailboxes */
7431 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7436 * Print appropriate message(s) if mail has arrived. If the argument is
7437 * nozero, then the value of MAIL has changed, so we just update the
7448 struct stackmark smark;
7455 setstackmark(&smark);
7456 mpath = mpathset()? mpathval() : mailval();
7457 for (i = 0 ; i < nmboxes ; i++) {
7458 p = padvance(&mpath, nullstr);
7463 for (q = p ; *q ; q++);
7468 q[-1] = '\0'; /* delete trailing '/' */
7469 if (stat(p, &statb) < 0)
7471 if (statb.st_size > mailtime[i] && ! silent) {
7473 pathopt? pathopt : "you have mail");
7475 mailtime[i] = statb.st_size;
7478 popstackmark(&smark);
7481 #endif /* ASH_MAIL */
7486 static short profile_buf[16384];
7490 static void read_profile (const char *);
7491 static void cmdloop (int);
7492 static void options (int);
7493 static void setoption (int, int);
7494 static void procargs (int, char **);
7498 * Main routine. We initialize things, parse the arguments, execute
7499 * profiles if we're a login shell, and then call cmdloop to execute
7500 * commands. The setjmp call sets up the location to jump to when an
7501 * exception occurs. When an exception occurs the variable "state"
7502 * is used to figure out how far we had gotten.
7506 ash_main(int argc, char **argv)
7508 struct jmploc jmploc;
7509 struct stackmark smark;
7513 BLTINCMD = find_builtin("builtin");
7514 EXECCMD = find_builtin("exec");
7515 EVALCMD = find_builtin("eval");
7517 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7523 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7525 #if defined(linux) || defined(__GNU__)
7526 signal(SIGCHLD, SIG_DFL);
7529 if (setjmp(jmploc.loc)) {
7532 * When a shell procedure is executed, we raise the
7533 * exception EXSHELLPROC to clean up before executing
7534 * the shell procedure.
7536 if (exception == EXSHELLPROC) {
7542 if (exception == EXEXEC) {
7543 exitstatus = exerrno;
7544 } else if (exception == EXERROR) {
7547 if (state == 0 || iflag == 0 || ! rootshell)
7548 exitshell(exitstatus);
7551 if (exception == EXINT) {
7554 popstackmark(&smark);
7555 FORCEINTON; /* enable interrupts */
7558 else if (state == 2)
7560 else if (state == 3)
7568 trputs("Shell args: "); trargs(argv);
7573 setstackmark(&smark);
7574 procargs(argc, argv);
7575 if (argv[0] && argv[0][0] == '-') {
7577 read_profile("/etc/profile");
7580 read_profile(".profile");
7585 if (getuid() == geteuid() && getgid() == getegid()) {
7587 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7589 read_profile(shinit);
7596 if (sflag == 0 || minusc) {
7597 static const char sigs[] = {
7598 SIGINT, SIGQUIT, SIGHUP,
7604 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7607 for (i = 0; i < SIGSSIZE; i++)
7612 evalstring(minusc, 0);
7614 if (sflag || minusc == NULL) {
7615 state4: /* XXX ??? - why isn't this before the "if" statement */
7621 exitshell(exitstatus);
7627 * Read and execute commands. "Top" is nonzero for the top level command
7628 * loop; it turns on prompting if the shell is interactive.
7635 struct stackmark smark;
7639 TRACE(("cmdloop(%d) called\n", top));
7640 setstackmark(&smark);
7653 n = parsecmd(inter);
7654 /* showtree(n); DEBUG */
7656 if (!top || numeof >= 50)
7658 if (!stoppedjobs()) {
7661 out2str("\nUse \"exit\" to leave shell.\n");
7664 } else if (n != NULL && nflag == 0) {
7665 job_warning = (job_warning == 2) ? 1 : 0;
7669 popstackmark(&smark);
7670 setstackmark(&smark);
7671 if (evalskip == SKIPFILE) {
7676 popstackmark(&smark);
7682 * Read /etc/profile or .profile. Return on error.
7686 read_profile(const char *name)
7693 if ((fd = open(name, O_RDONLY)) >= 0)
7698 /* -q turns off -x and -v just when executing init files */
7699 /* Note: Might do a little redundant work, but reduces code size. */
7714 * Read a file containing shell functions.
7718 readcmdfile(const char *name)
7723 if ((fd = open(name, O_RDONLY)) >= 0)
7726 error("Can't open %s", name);
7735 * Take commands from a file. To be compatable we should do a path
7736 * search for the file, which is necessary to find sub-commands.
7739 static inline char *
7740 find_dot_file(char *mybasename)
7743 const char *path = pathval();
7746 /* don't try this for absolute or relative paths */
7747 if (strchr(mybasename, '/'))
7750 while ((fullname = padvance(&path, mybasename)) != NULL) {
7751 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7753 * Don't bother freeing here, since it will
7754 * be freed by the caller.
7758 stunalloc(fullname);
7761 /* not found in the PATH */
7762 error("%s: not found", mybasename);
7767 dotcmd(int argc, char **argv)
7770 volatile struct shparam saveparam;
7773 for (sp = cmdenviron; sp ; sp = sp->next)
7774 setvareq(xstrdup(sp->text), VSTRFIXED|VTEXTFIXED);
7776 if (argc >= 2) { /* That's what SVR2 does */
7778 struct stackmark smark;
7780 setstackmark(&smark);
7781 fullname = find_dot_file(argv[1]);
7784 saveparam = shellparam;
7785 shellparam.malloc = 0;
7786 shellparam.nparam = argc - 2;
7787 shellparam.p = argv + 2;
7790 setinputfile(fullname, 1);
7791 commandname = fullname;
7796 freeparam(&shellparam);
7797 shellparam = saveparam;
7800 popstackmark(&smark);
7807 exitcmd(int argc, char **argv)
7812 exitstatus = number(argv[1]);
7814 exitstatus = oexitstatus;
7815 exitshell(exitstatus);
7824 nbytes = ALIGN(nbytes);
7825 if (nbytes > stacknleft) {
7827 struct stack_block *sp;
7830 if (blocksize < MINSIZE)
7831 blocksize = MINSIZE;
7833 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7835 stacknxt = sp->space;
7836 stacknleft = blocksize;
7842 stacknleft -= nbytes;
7848 stunalloc(pointer p)
7851 if (p == NULL) { /*DEBUG */
7852 write(2, "stunalloc\n", 10);
7856 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7859 stacknleft += stacknxt - (char *)p;
7865 setstackmark(struct stackmark *mark)
7867 mark->stackp = stackp;
7868 mark->stacknxt = stacknxt;
7869 mark->stacknleft = stacknleft;
7870 mark->marknext = markp;
7876 popstackmark(struct stackmark *mark)
7878 struct stack_block *sp;
7881 markp = mark->marknext;
7882 while (stackp != mark->stackp) {
7887 stacknxt = mark->stacknxt;
7888 stacknleft = mark->stacknleft;
7894 * When the parser reads in a string, it wants to stick the string on the
7895 * stack and only adjust the stack pointer when it knows how big the
7896 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7897 * of space on top of the stack and stackblocklen returns the length of
7898 * this block. Growstackblock will grow this space by at least one byte,
7899 * possibly moving it (like realloc). Grabstackblock actually allocates the
7900 * part of the block that has been used.
7904 growstackblock(void) {
7906 int newlen = ALIGN(stacknleft * 2 + 100);
7907 char *oldspace = stacknxt;
7908 int oldlen = stacknleft;
7909 struct stack_block *sp;
7910 struct stack_block *oldstackp;
7912 if (stacknxt == stackp->space && stackp != &stackbase) {
7917 sp = xrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
7920 stacknxt = sp->space;
7921 stacknleft = newlen;
7923 /* Stack marks pointing to the start of the old block
7924 * must be relocated to point to the new block
7926 struct stackmark *xmark;
7928 while (xmark != NULL && xmark->stackp == oldstackp) {
7929 xmark->stackp = stackp;
7930 xmark->stacknxt = stacknxt;
7931 xmark->stacknleft = stacknleft;
7932 xmark = xmark->marknext;
7937 p = stalloc(newlen);
7938 memcpy(p, oldspace, oldlen);
7939 stacknxt = p; /* free the space */
7940 stacknleft += newlen; /* we just allocated */
7947 grabstackblock(int len)
7957 * The following routines are somewhat easier to use that the above.
7958 * The user declares a variable of type STACKSTR, which may be declared
7959 * to be a register. The macro STARTSTACKSTR initializes things. Then
7960 * the user uses the macro STPUTC to add characters to the string. In
7961 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7962 * grown as necessary. When the user is done, she can just leave the
7963 * string there and refer to it using stackblock(). Or she can allocate
7964 * the space for it using grabstackstr(). If it is necessary to allow
7965 * someone else to use the stack temporarily and then continue to grow
7966 * the string, the user should use grabstack to allocate the space, and
7967 * then call ungrabstr(p) to return to the previous mode of operation.
7969 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7970 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7971 * is space for at least one character.
7976 growstackstr(void) {
7977 int len = stackblocksize();
7978 if (herefd >= 0 && len >= 1024) {
7979 xwrite(herefd, stackblock(), len);
7980 sstrnleft = len - 1;
7981 return stackblock();
7984 sstrnleft = stackblocksize() - len - 1;
7985 return stackblock() + len;
7990 * Called from CHECKSTRSPACE.
7994 makestrspace(size_t newlen) {
7995 int len = stackblocksize() - sstrnleft;
7998 sstrnleft = stackblocksize() - len;
7999 } while (sstrnleft < newlen);
8000 return stackblock() + len;
8006 ungrabstackstr(char *s, char *p)
8008 stacknleft += stacknxt - s;
8010 sstrnleft = stacknleft - (p - s);
8013 * Miscelaneous builtins.
8019 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8020 typedef long rlim_t;
8026 * The read builtin. The -e option causes backslashes to escape the
8027 * following character.
8029 * This uses unbuffered input, which may be avoidable in some cases.
8033 readcmd(int argc, char **argv)
8048 while ((i = nextopt("p:r")) != '\0') {
8054 if (prompt && isatty(0)) {
8055 out2str(prompt); /* read without cmdedit */
8058 if (*(ap = argptr) == NULL)
8060 if ((ifs = bltinlookup("IFS")) == NULL)
8067 if (read(0, &c, 1) != 1) {
8079 if (!rflag && c == '\\') {
8085 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8089 if (backslash && c == '\\') {
8090 if (read(0, &c, 1) != 1) {
8095 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8097 setvar(*ap, stackblock(), 0);
8106 /* Remove trailing blanks */
8107 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8109 setvar(*ap, stackblock(), 0);
8110 while (*++ap != NULL)
8111 setvar(*ap, nullstr, 0);
8118 umaskcmd(int argc, char **argv)
8120 static const char permuser[3] = "ugo";
8121 static const char permmode[3] = "rwx";
8122 static const short int permmask[] = {
8123 S_IRUSR, S_IWUSR, S_IXUSR,
8124 S_IRGRP, S_IWGRP, S_IXGRP,
8125 S_IROTH, S_IWOTH, S_IXOTH
8131 int symbolic_mode = 0;
8133 while (nextopt("S") != '\0') {
8142 if ((ap = *argptr) == NULL) {
8143 if (symbolic_mode) {
8146 for (i=0 ; i<3 ; i++) {
8150 for (j=0 ; j<3 ; j++) {
8151 if ((mask & permmask[3*i+j]) == 0) {
8160 printf("%.4o\n", mask);
8163 if (is_digit((unsigned char)*ap)) {
8166 if (*ap >= '8' || *ap < '0')
8167 error("Illegal number: %s", argv[1]);
8168 mask = (mask << 3) + (*ap - '0');
8169 } while (*++ap != '\0');
8172 mask = ~mask & 0777;
8173 if (! parse_mode(ap, &mask)) {
8174 error("Illegal mode: %s", ap);
8176 umask(~mask & 0777);
8185 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8186 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8187 * ash by J.T. Conklin.
8195 short factor; /* multiply by to get rlim_{cur,max} values */
8198 static const struct limits limits[] = {
8200 { "time(seconds)", RLIMIT_CPU, 1 },
8203 { "file(blocks)", RLIMIT_FSIZE, 512 },
8206 { "data(kbytes)", RLIMIT_DATA, 1024 },
8209 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8212 { "coredump(blocks)", RLIMIT_CORE, 512 },
8215 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8217 #ifdef RLIMIT_MEMLOCK
8218 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8221 { "process(processes)", RLIMIT_NPROC, 1 },
8223 #ifdef RLIMIT_NOFILE
8224 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8227 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8230 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8236 ulimitcmd(int argc, char **argv)
8238 static const char unlimited_string[] = "unlimited";
8241 enum { SOFT = 0x1, HARD = 0x2 }
8243 const struct limits *l;
8246 struct rlimit limit;
8250 while ((optc = nextopt("HSa"
8269 #ifdef RLIMIT_MEMLOCK
8275 #ifdef RLIMIT_NOFILE
8287 } else if (optc == 'S') {
8289 } else if (optc == 'a') {
8296 for (l = limits; l->name; l++) {
8297 if(l->name[0] == what)
8299 if(l->name[1]=='w' && what=='w')
8303 set = *argptr ? 1 : 0;
8307 if (all || argptr[1])
8308 error("too many arguments");
8309 if (strcmp(p, unlimited_string) == 0)
8310 val = RLIM_INFINITY;
8314 while ((c = *p++) >= '0' && c <= '9')
8316 val = (val * 10) + (long)(c - '0');
8317 if (val < (rlim_t) 0)
8321 error("bad number");
8327 for (l = limits; l->name; l++) {
8328 printf("%-20s ", l->name);
8329 getrlimit(l->cmd, &limit);
8332 val = limit.rlim_cur;
8333 else if (how & HARD)
8334 val = limit.rlim_max;
8336 if (val == RLIM_INFINITY)
8337 puts(unlimited_string);
8341 printf("%lld\n", (long long) val);
8354 getrlimit(l->cmd, &limit);
8356 limit.rlim_max = val;
8358 limit.rlim_cur = val;
8359 if (setrlimit(l->cmd, &limit) < 0)
8360 error("error setting limit (%m)");
8364 * prefix -- see if pfx is a prefix of string.
8368 prefix(char const *pfx, char const *string)
8371 if (*pfx++ != *string++)
8378 * Return true if s is a string of digits, and save munber in intptr
8383 is_number(const char *p, int *intptr)
8391 ret += digit_val(*p);
8393 } while (*p != '\0');
8400 * Convert a string of digits to an integer, printing an error message on
8405 number(const char *s)
8408 if (! is_number(s, &i))
8409 error("Illegal number: %s", s);
8414 * Produce a possibly single quoted string suitable as input to the shell.
8415 * The return string is allocated on the stack.
8419 single_quote(const char *s)
8427 size_t len1, len1p, len2, len2p;
8429 len1 = strcspn(s, "'");
8430 len2 = strspn(s + len1, "'");
8432 len1p = len1 ? len1 + 2 : len1;
8433 len2p = len2 + ((len2 < 2) ? len2 : 2);
8435 CHECKSTRSPACE(len1p + len2p + 1, p);
8440 memcpy(p + 1, s, len1);
8448 memcpy(q + 1, s, len2);
8451 } else if (len2 == 1) {
8457 STADJUST(len1p + len2p, p);
8462 return grabstackstr(p);
8466 * Like strdup but works with the ash stack.
8470 sstrdup(const char *p)
8472 size_t len = strlen(p) + 1;
8473 return memcpy(stalloc(len), p, len);
8478 * Routine for dealing with parsed shell commands.
8482 static void sizenodelist (const struct nodelist *);
8483 static struct nodelist *copynodelist (const struct nodelist *);
8484 static char *nodexstrdup (const char *);
8486 #define CALCSIZE_TABLE
8487 #define COPYNODE_TABLE
8488 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8490 * To collect a lot of redundant code in case statements for copynode()
8491 * and calcsize(), we implement a mini language here. Each type of node
8492 * struct has an associated instruction sequence that operates on its
8493 * members via their offsets. The instruction are pack in unsigned chars
8494 * with format IIDDDDDE where the bits are
8495 * I : part of the instruction opcode, which are
8496 * 00 : member is a pointer to another node
8497 * 40 : member is an integer
8498 * 80 : member is a pointer to a nodelist
8499 * CC : member is a pointer to a char string
8500 * D : data - the actual offset of the member to operate on in the struct
8501 * (since we assume bit 0 is set, it is not shifted)
8502 * E : flag signaling end of instruction sequence
8504 * WARNING: In order to handle larger offsets for 64bit archs, this code
8505 * assumes that no offset can be an odd number and stores the
8506 * end-of-instructions flag in bit 0.
8509 #define NODE_INTEGER 0x40
8510 #define NODE_NODELIST 0x80
8511 #define NODE_CHARPTR 0xC0
8512 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8513 #define NODE_MBRMASK 0xC0
8514 #define NODE_OFFSETMASK 0x3E
8516 static const unsigned char copynode_ops[35] = {
8517 #define COPYNODE_OPS0 0
8518 offsetof(union node, nbinary.ch2),
8519 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8520 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8521 offsetof(union node, ncmd.redirect),
8522 offsetof(union node, ncmd.args),
8523 offsetof(union node, ncmd.assign),
8524 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8525 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8526 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8527 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8528 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8529 offsetof(union node, nredir.redirect),
8530 offsetof(union node, nredir.n)|NODE_NOMORE,
8531 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8532 offsetof(union node, nif.elsepart),
8533 offsetof(union node, nif.ifpart),
8534 offsetof(union node, nif.test)|NODE_NOMORE,
8535 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8536 offsetof(union node, nfor.var)|NODE_CHARPTR,
8537 offsetof(union node, nfor.body),
8538 offsetof(union node, nfor.args)|NODE_NOMORE,
8539 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8540 offsetof(union node, ncase.cases),
8541 offsetof(union node, ncase.expr)|NODE_NOMORE,
8542 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8543 offsetof(union node, nclist.body),
8544 offsetof(union node, nclist.pattern),
8545 offsetof(union node, nclist.next)|NODE_NOMORE,
8546 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8547 offsetof(union node, narg.backquote)|NODE_NODELIST,
8548 offsetof(union node, narg.text)|NODE_CHARPTR,
8549 offsetof(union node, narg.next)|NODE_NOMORE,
8550 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8551 offsetof(union node, nfile.fname),
8552 offsetof(union node, nfile.fd)|NODE_INTEGER,
8553 offsetof(union node, nfile.next)|NODE_NOMORE,
8554 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8555 offsetof(union node, ndup.vname),
8556 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8557 offsetof(union node, ndup.fd)|NODE_INTEGER,
8558 offsetof(union node, ndup.next)|NODE_NOMORE,
8559 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8560 offsetof(union node, nhere.doc),
8561 offsetof(union node, nhere.fd)|NODE_INTEGER,
8562 offsetof(union node, nhere.next)|NODE_NOMORE,
8563 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8564 offsetof(union node, nnot.com)|NODE_NOMORE,
8567 #if COPYNODE_OPS12 != 34
8568 #error COPYNODE_OPS12 is incorrect
8571 static const unsigned char copynode_ops_index[26] = {
8572 COPYNODE_OPS0, /* NSEMI */
8573 COPYNODE_OPS1, /* NCMD */
8574 COPYNODE_OPS2, /* NPIPE */
8575 COPYNODE_OPS3, /* NREDIR */
8576 COPYNODE_OPS3, /* NBACKGND */
8577 COPYNODE_OPS3, /* NSUBSHELL */
8578 COPYNODE_OPS0, /* NAND */
8579 COPYNODE_OPS0, /* NOR */
8580 COPYNODE_OPS4, /* NIF */
8581 COPYNODE_OPS0, /* NWHILE */
8582 COPYNODE_OPS0, /* NUNTIL */
8583 COPYNODE_OPS5, /* NFOR */
8584 COPYNODE_OPS6, /* NCASE */
8585 COPYNODE_OPS7, /* NCLIST */
8586 COPYNODE_OPS8, /* NDEFUN */
8587 COPYNODE_OPS8, /* NARG */
8588 COPYNODE_OPS9, /* NTO */
8589 COPYNODE_OPS9, /* NFROM */
8590 COPYNODE_OPS9, /* NFROMTO */
8591 COPYNODE_OPS9, /* NAPPEND */
8592 COPYNODE_OPS9, /* NTOOV */
8593 COPYNODE_OPS10, /* NTOFD */
8594 COPYNODE_OPS10, /* NFROMFD */
8595 COPYNODE_OPS11, /* NHERE */
8596 COPYNODE_OPS11, /* NXHERE */
8597 COPYNODE_OPS12, /* NNOT */
8600 #if NODE_CHARPTR != NODE_MBRMASK
8601 #error NODE_CHARPTR != NODE_MBRMASK!!!
8603 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8605 #ifdef COPYNODE_TABLE
8607 copynode(const union node *n)
8610 const unsigned char *p;
8616 new->type = n->type;
8617 funcblock = (char *) funcblock + (int) nodesize[n->type];
8618 p = copynode_ops + (int) copynode_ops_index[n->type];
8620 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8621 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8623 if (!(*p & NODE_MBRMASK)) { /* standard node */
8624 *((union node **)nn) = copynode(*((const union node **) no));
8625 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8626 *((const char **)nn) = nodexstrdup(*((const char **)no));
8627 } else if (*p & NODE_NODELIST) { /* nodelist */
8628 *((struct nodelist **)nn)
8629 = copynodelist(*((const struct nodelist **) no));
8630 } else { /* integer */
8631 *((int *) nn) = *((int *) no);
8633 } while (!(*p++ & NODE_NOMORE));
8636 #else /* COPYNODE_TABLE */
8638 copynode(const union node *n)
8645 funcblock = (char *) funcblock + nodesize[n->type];
8652 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8653 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8656 new->ncmd.redirect = copynode(n->ncmd.redirect);
8657 new->ncmd.args = copynode(n->ncmd.args);
8658 new->ncmd.assign = copynode(n->ncmd.assign);
8659 new->ncmd.backgnd = n->ncmd.backgnd;
8662 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8663 new->npipe.backgnd = n->npipe.backgnd;
8668 new->nredir.redirect = copynode(n->nredir.redirect);
8669 new->nredir.n = copynode(n->nredir.n);
8672 new->nif.elsepart = copynode(n->nif.elsepart);
8673 new->nif.ifpart = copynode(n->nif.ifpart);
8674 new->nif.test = copynode(n->nif.test);
8677 new->nfor.var = nodexstrdup(n->nfor.var);
8678 new->nfor.body = copynode(n->nfor.body);
8679 new->nfor.args = copynode(n->nfor.args);
8682 new->ncase.cases = copynode(n->ncase.cases);
8683 new->ncase.expr = copynode(n->ncase.expr);
8686 new->nclist.body = copynode(n->nclist.body);
8687 new->nclist.pattern = copynode(n->nclist.pattern);
8688 new->nclist.next = copynode(n->nclist.next);
8692 new->narg.backquote = copynodelist(n->narg.backquote);
8693 new->narg.text = nodexstrdup(n->narg.text);
8694 new->narg.next = copynode(n->narg.next);
8701 new->nfile.fname = copynode(n->nfile.fname);
8702 new->nfile.fd = n->nfile.fd;
8703 new->nfile.next = copynode(n->nfile.next);
8707 new->ndup.vname = copynode(n->ndup.vname);
8708 new->ndup.dupfd = n->ndup.dupfd;
8709 new->ndup.fd = n->ndup.fd;
8710 new->ndup.next = copynode(n->ndup.next);
8714 new->nhere.doc = copynode(n->nhere.doc);
8715 new->nhere.fd = n->nhere.fd;
8716 new->nhere.next = copynode(n->nhere.next);
8719 new->nnot.com = copynode(n->nnot.com);
8722 new->type = n->type;
8725 #endif /* COPYNODE_TABLE */
8727 #ifdef CALCSIZE_TABLE
8729 calcsize(const union node *n)
8731 const unsigned char *p;
8735 funcblocksize += (int) nodesize[n->type];
8737 p = copynode_ops + (int) copynode_ops_index[n->type];
8739 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8741 if (!(*p & NODE_MBRMASK)) { /* standard node */
8742 calcsize(*((const union node **) no));
8743 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8744 funcstringsize += strlen(*((const char **)no)) + 1;
8745 } else if (*p & NODE_NODELIST) { /* nodelist */
8746 sizenodelist(*((const struct nodelist **) no));
8747 } /* else integer -- ignore */
8748 } while (!(*p++ & NODE_NOMORE));
8750 #else /* CALCSIZE_TABLE */
8752 calcsize(const union node *n)
8756 funcblocksize += nodesize[n->type];
8763 calcsize(n->nbinary.ch2);
8764 calcsize(n->nbinary.ch1);
8767 calcsize(n->ncmd.redirect);
8768 calcsize(n->ncmd.args);
8769 calcsize(n->ncmd.assign);
8772 sizenodelist(n->npipe.cmdlist);
8777 calcsize(n->nredir.redirect);
8778 calcsize(n->nredir.n);
8781 calcsize(n->nif.elsepart);
8782 calcsize(n->nif.ifpart);
8783 calcsize(n->nif.test);
8786 funcstringsize += strlen(n->nfor.var) + 1;
8787 calcsize(n->nfor.body);
8788 calcsize(n->nfor.args);
8791 calcsize(n->ncase.cases);
8792 calcsize(n->ncase.expr);
8795 calcsize(n->nclist.body);
8796 calcsize(n->nclist.pattern);
8797 calcsize(n->nclist.next);
8801 sizenodelist(n->narg.backquote);
8802 funcstringsize += strlen(n->narg.text) + 1;
8803 calcsize(n->narg.next);
8810 calcsize(n->nfile.fname);
8811 calcsize(n->nfile.next);
8815 calcsize(n->ndup.vname);
8816 calcsize(n->ndup.next);
8820 calcsize(n->nhere.doc);
8821 calcsize(n->nhere.next);
8824 calcsize(n->nnot.com);
8828 #endif /* CALCSIZE_TABLE */
8831 sizenodelist(const struct nodelist *lp)
8834 funcblocksize += ALIGN(sizeof(struct nodelist));
8841 static struct nodelist *
8842 copynodelist(const struct nodelist *lp)
8844 struct nodelist *start;
8845 struct nodelist **lpp;
8850 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8851 (*lpp)->n = copynode(lp->n);
8853 lpp = &(*lpp)->next;
8861 nodexstrdup(const char *s)
8864 char *q = funcstring;
8865 char *rtn = funcstring;
8867 while ((*q++ = *p++) != '\0')
8874 static int getopts (char *, char *, char **, int *, int *);
8879 * Process the shell command line arguments.
8883 procargs(int argc, char **argv)
8890 for (i = 0; i < NOPTS; i++)
8893 if (*argptr == NULL && minusc == NULL)
8895 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8899 for (i = 0; i < NOPTS; i++)
8900 if (optent_val(i) == 2)
8903 if (sflag == 0 && minusc == NULL) {
8904 commandname = argv[0];
8906 setinputfile(arg0, 0);
8909 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8910 if (argptr && minusc && *argptr)
8913 shellparam.p = argptr;
8914 shellparam.optind = 1;
8915 shellparam.optoff = -1;
8916 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8918 shellparam.nparam++;
8927 * Process shell options. The global variable argptr contains a pointer
8928 * to the argument list; we advance it past the options.
8932 minus_o(const char *name, int val)
8937 out1str("Current option settings\n");
8938 for (i = 0; i < NOPTS; i++)
8939 printf("%-16s%s\n", optent_name(optlist[i]),
8940 optent_val(i) ? "on" : "off");
8942 for (i = 0; i < NOPTS; i++)
8943 if (equal(name, optent_name(optlist[i]))) {
8944 setoption(optent_letter(optlist[i]), val);
8947 error("Illegal option -o %s", name);
8953 options(int cmdline)
8961 while ((p = *argptr) != NULL) {
8963 if ((c = *p++) == '-') {
8965 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8967 /* "-" means turn off -x and -v */
8970 /* "--" means reset params */
8971 else if (*argptr == NULL)
8974 break; /* "-" or "--" terminates options */
8976 } else if (c == '+') {
8982 while ((c = *p++) != '\0') {
8983 if (c == 'c' && cmdline) {
8985 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8989 if (q == NULL || minusc != NULL)
8990 error("Bad -c option");
8995 } else if (c == 'o') {
8996 minus_o(*argptr, val);
9008 setoption(int flag, int val)
9012 for (i = 0; i < NOPTS; i++)
9013 if (optent_letter(optlist[i]) == flag) {
9014 optent_val(i) = val;
9016 /* #%$ hack for ksh semantics */
9019 else if (flag == 'E')
9024 error("Illegal option -%c", flag);
9031 * Set the shell parameters.
9035 setparam(char **argv)
9041 for (nparam = 0 ; argv[nparam] ; nparam++);
9042 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
9044 *ap++ = xstrdup(*argv++);
9047 freeparam(&shellparam);
9048 shellparam.malloc = 1;
9049 shellparam.nparam = nparam;
9050 shellparam.p = newparam;
9051 shellparam.optind = 1;
9052 shellparam.optoff = -1;
9057 * Free the list of positional parameters.
9061 freeparam(volatile struct shparam *param)
9065 if (param->malloc) {
9066 for (ap = param->p ; *ap ; ap++)
9075 * The shift builtin command.
9079 shiftcmd(int argc, char **argv)
9086 n = number(argv[1]);
9087 if (n > shellparam.nparam)
9088 error("can't shift that many");
9090 shellparam.nparam -= n;
9091 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9092 if (shellparam.malloc)
9096 while ((*ap2++ = *ap1++) != NULL);
9097 shellparam.optind = 1;
9098 shellparam.optoff = -1;
9106 * The set command builtin.
9110 setcmd(int argc, char **argv)
9113 return showvarscmd(argc, argv);
9117 if (*argptr != NULL) {
9126 getoptsreset(const char *value)
9128 shellparam.optind = number(value);
9129 shellparam.optoff = -1;
9132 #ifdef CONFIG_LOCALE_SUPPORT
9133 static void change_lc_all(const char *value)
9135 if(value != 0 && *value != 0)
9136 setlocale(LC_ALL, value);
9139 static void change_lc_ctype(const char *value)
9141 if(value != 0 && *value != 0)
9142 setlocale(LC_CTYPE, value);
9149 * The getopts builtin. Shellparam.optnext points to the next argument
9150 * to be processed. Shellparam.optptr points to the next character to
9151 * be processed in the current argument. If shellparam.optnext is NULL,
9152 * then it's the first time getopts has been called.
9156 getoptscmd(int argc, char **argv)
9161 error("Usage: getopts optstring var [arg]");
9162 else if (argc == 3) {
9163 optbase = shellparam.p;
9164 if (shellparam.optind > shellparam.nparam + 1) {
9165 shellparam.optind = 1;
9166 shellparam.optoff = -1;
9171 if (shellparam.optind > argc - 2) {
9172 shellparam.optind = 1;
9173 shellparam.optoff = -1;
9177 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9178 &shellparam.optoff);
9182 * Safe version of setvar, returns 1 on success 0 on failure.
9186 setvarsafe(const char *name, const char *val, int flags)
9188 struct jmploc jmploc;
9189 struct jmploc *volatile savehandler = handler;
9195 if (setjmp(jmploc.loc))
9199 setvar(name, val, flags);
9201 handler = savehandler;
9206 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind, int *optoff)
9213 char **optnext = optfirst + *myoptind - 1;
9215 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9216 strlen(*(optnext - 1)) < *optoff)
9219 p = *(optnext - 1) + *optoff;
9220 if (p == NULL || *p == '\0') {
9221 /* Current word is done, advance */
9222 if (optnext == NULL)
9225 if (p == NULL || *p != '-' || *++p == '\0') {
9227 *myoptind = optnext - optfirst + 1;
9233 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9238 for (q = optstr; *q != c; ) {
9240 if (optstr[0] == ':') {
9243 err |= setvarsafe("OPTARG", s, 0);
9246 out2fmt("Illegal option -%c\n", c);
9247 (void) unsetvar("OPTARG");
9257 if (*p == '\0' && (p = *optnext) == NULL) {
9258 if (optstr[0] == ':') {
9261 err |= setvarsafe("OPTARG", s, 0);
9265 out2fmt("No arg for -%c option\n", c);
9266 (void) unsetvar("OPTARG");
9274 setvarsafe("OPTARG", p, 0);
9278 setvarsafe("OPTARG", "", 0);
9279 *myoptind = optnext - optfirst + 1;
9286 *optoff = p ? p - *(optnext - 1) : -1;
9287 snprintf(s, sizeof(s), "%d", *myoptind);
9288 err |= setvarsafe("OPTIND", s, VNOFUNC);
9291 err |= setvarsafe(optvar, s, 0);
9302 * XXX - should get rid of. have all builtins use getopt(3). the
9303 * library getopt must have the BSD extension static variable "optreset"
9304 * otherwise it can't be used within the shell safely.
9306 * Standard option processing (a la getopt) for builtin routines. The
9307 * only argument that is passed to nextopt is the option string; the
9308 * other arguments are unnecessary. It return the character, or '\0' on
9313 nextopt(const char *optstring)
9319 if ((p = optptr) == NULL || *p == '\0') {
9321 if (p == NULL || *p != '-' || *++p == '\0')
9324 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9328 for (q = optstring ; *q != c ; ) {
9330 error("Illegal option -%c", c);
9335 if (*p == '\0' && (p = *argptr++) == NULL)
9336 error("No arg for -%c option", c);
9353 out2fmt(const char *fmt, ...)
9357 vfprintf(stderr, fmt, ap);
9362 * Version of write which resumes after a signal is caught.
9366 xwrite(int fd, const char *buf, int nbytes)
9375 i = write(fd, buf, n);
9381 } else if (i == 0) {
9384 } else if (errno != EINTR) {
9392 * Shell command parser.
9395 #define EOFMARKLEN 79
9400 struct heredoc *next; /* next here document in list */
9401 union node *here; /* redirection node */
9402 char *eofmark; /* string indicating end of input */
9403 int striptabs; /* if set, strip leading tabs */
9406 static struct heredoc *heredoclist; /* list of here documents to read */
9407 static int parsebackquote; /* nonzero if we are inside backquotes */
9408 static int doprompt; /* if set, prompt the user */
9409 static int needprompt; /* true if interactive and at start of line */
9410 static int lasttoken; /* last token read */
9412 static char *wordtext; /* text of last word returned by readtoken */
9414 static struct nodelist *backquotelist;
9415 static union node *redirnode;
9416 static struct heredoc *heredoc;
9417 static int quoteflag; /* set if (part of) last token was quoted */
9418 static int startlinno; /* line # where last token started */
9421 static union node *list (int);
9422 static union node *andor (void);
9423 static union node *pipeline (void);
9424 static union node *command (void);
9425 static union node *simplecmd(union node **rpp, union node *redir);
9426 static void parsefname (void);
9427 static void parseheredoc (void);
9428 static char peektoken (void);
9429 static int readtoken (void);
9430 static int xxreadtoken (void);
9431 static int readtoken1 (int, int, const char *, int);
9432 static int noexpand (char *);
9433 static void synexpect (int) __attribute__((noreturn));
9434 static void synerror (const char *) __attribute__((noreturn));
9435 static void setprompt (int);
9439 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9440 * valid parse tree indicating a blank line.)
9444 parsecmd(int interact)
9449 doprompt = interact;
9468 union node *n1, *n2, *n3;
9472 if (nlflag == 0 && peektoken())
9478 if (tok == TBACKGND) {
9479 if (n2->type == NCMD || n2->type == NPIPE) {
9480 n2->ncmd.backgnd = 1;
9481 } else if (n2->type == NREDIR) {
9482 n2->type = NBACKGND;
9484 n3 = (union node *)stalloc(sizeof (struct nredir));
9485 n3->type = NBACKGND;
9487 n3->nredir.redirect = NULL;
9495 n3 = (union node *)stalloc(sizeof (struct nbinary));
9497 n3->nbinary.ch1 = n1;
9498 n3->nbinary.ch2 = n2;
9522 pungetc(); /* push back EOF on input */
9537 union node *n1, *n2, *n3;
9543 if ((t = readtoken()) == TAND) {
9545 } else if (t == TOR) {
9553 n3 = (union node *)stalloc(sizeof (struct nbinary));
9555 n3->nbinary.ch1 = n1;
9556 n3->nbinary.ch2 = n2;
9565 union node *n1, *n2, *pipenode;
9566 struct nodelist *lp, *prev;
9570 TRACE(("pipeline: entered\n"));
9571 if (readtoken() == TNOT) {
9577 if (readtoken() == TPIPE) {
9578 pipenode = (union node *)stalloc(sizeof (struct npipe));
9579 pipenode->type = NPIPE;
9580 pipenode->npipe.backgnd = 0;
9581 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9582 pipenode->npipe.cmdlist = lp;
9586 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9590 } while (readtoken() == TPIPE);
9596 n2 = (union node *)stalloc(sizeof (struct nnot));
9608 union node *n1, *n2;
9609 union node *ap, **app;
9610 union node *cp, **cpp;
9611 union node *redir, **rpp;
9618 /* Check for redirection which may precede command */
9619 while (readtoken() == TREDIR) {
9620 *rpp = n2 = redirnode;
9621 rpp = &n2->nfile.next;
9626 switch (readtoken()) {
9628 n1 = (union node *)stalloc(sizeof (struct nif));
9630 n1->nif.test = list(0);
9631 if (readtoken() != TTHEN)
9633 n1->nif.ifpart = list(0);
9635 while (readtoken() == TELIF) {
9636 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9637 n2 = n2->nif.elsepart;
9639 n2->nif.test = list(0);
9640 if (readtoken() != TTHEN)
9642 n2->nif.ifpart = list(0);
9644 if (lasttoken == TELSE)
9645 n2->nif.elsepart = list(0);
9647 n2->nif.elsepart = NULL;
9650 if (readtoken() != TFI)
9657 n1 = (union node *)stalloc(sizeof (struct nbinary));
9658 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9659 n1->nbinary.ch1 = list(0);
9660 if ((got=readtoken()) != TDO) {
9661 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9664 n1->nbinary.ch2 = list(0);
9665 if (readtoken() != TDONE)
9671 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9672 synerror("Bad for loop variable");
9673 n1 = (union node *)stalloc(sizeof (struct nfor));
9675 n1->nfor.var = wordtext;
9677 if (readtoken() == TIN) {
9679 while (readtoken() == TWORD) {
9680 n2 = (union node *)stalloc(sizeof (struct narg));
9682 n2->narg.text = wordtext;
9683 n2->narg.backquote = backquotelist;
9685 app = &n2->narg.next;
9689 if (lasttoken != TNL && lasttoken != TSEMI)
9692 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9694 n2 = (union node *)stalloc(sizeof (struct narg));
9696 n2->narg.text = argvars;
9697 n2->narg.backquote = NULL;
9698 n2->narg.next = NULL;
9701 * Newline or semicolon here is optional (but note
9702 * that the original Bourne shell only allowed NL).
9704 if (lasttoken != TNL && lasttoken != TSEMI)
9708 if (readtoken() != TDO)
9710 n1->nfor.body = list(0);
9711 if (readtoken() != TDONE)
9716 n1 = (union node *)stalloc(sizeof (struct ncase));
9718 if (readtoken() != TWORD)
9720 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9722 n2->narg.text = wordtext;
9723 n2->narg.backquote = backquotelist;
9724 n2->narg.next = NULL;
9727 } while (readtoken() == TNL);
9728 if (lasttoken != TIN)
9729 synerror("expecting \"in\"");
9730 cpp = &n1->ncase.cases;
9731 checkkwd = 2, readtoken();
9733 if (lasttoken == TLP)
9735 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9737 app = &cp->nclist.pattern;
9739 *app = ap = (union node *)stalloc(sizeof (struct narg));
9741 ap->narg.text = wordtext;
9742 ap->narg.backquote = backquotelist;
9743 if (checkkwd = 2, readtoken() != TPIPE)
9745 app = &ap->narg.next;
9748 ap->narg.next = NULL;
9749 if (lasttoken != TRP)
9751 cp->nclist.body = list(0);
9754 if ((t = readtoken()) != TESAC) {
9756 synexpect(TENDCASE);
9758 checkkwd = 2, readtoken();
9760 cpp = &cp->nclist.next;
9761 } while(lasttoken != TESAC);
9766 n1 = (union node *)stalloc(sizeof (struct nredir));
9767 n1->type = NSUBSHELL;
9768 n1->nredir.n = list(0);
9769 n1->nredir.redirect = NULL;
9770 if (readtoken() != TRP)
9776 if (readtoken() != TEND)
9780 /* Handle an empty command like other simple commands. */
9789 * An empty command before a ; doesn't make much sense, and
9790 * should certainly be disallowed in the case of `if ;'.
9796 n1 = simplecmd(rpp, redir);
9803 /* Now check for redirection which may follow command */
9804 while (readtoken() == TREDIR) {
9805 *rpp = n2 = redirnode;
9806 rpp = &n2->nfile.next;
9812 if (n1->type != NSUBSHELL) {
9813 n2 = (union node *)stalloc(sizeof (struct nredir));
9818 n1->nredir.redirect = redir;
9826 simplecmd(union node **rpp, union node *redir) {
9827 union node *args, **app;
9828 union node *n = NULL;
9829 union node *vars, **vpp;
9830 union node **orig_rpp;
9837 /* If we don't have any redirections already, then we must reset
9838 rpp to be the address of the local redir variable. */
9841 /* We save the incoming value, because we need this for shell
9842 functions. There can not be a redirect or an argument between
9843 the function name and the open parenthesis. */
9848 switch (readtoken()) {
9851 n = (union node *)stalloc(sizeof (struct narg));
9853 n->narg.text = wordtext;
9854 n->narg.backquote = backquotelist;
9855 if (lasttoken == TWORD) {
9857 app = &n->narg.next;
9860 vpp = &n->narg.next;
9864 *rpp = n = redirnode;
9865 rpp = &n->nfile.next;
9866 parsefname(); /* read name of redirection file */
9870 args && app == &args->narg.next &&
9871 !vars && rpp == orig_rpp
9873 /* We have a function */
9874 if (readtoken() != TRP)
9878 n->narg.next = command();
9891 n = (union node *)stalloc(sizeof (struct ncmd));
9893 n->ncmd.backgnd = 0;
9894 n->ncmd.args = args;
9895 n->ncmd.assign = vars;
9896 n->ncmd.redirect = redir;
9904 n = (union node *)stalloc(sizeof (struct narg));
9906 n->narg.next = NULL;
9907 n->narg.text = wordtext;
9908 n->narg.backquote = backquotelist;
9912 static void fixredir(union node *n, const char *text, int err)
9914 TRACE(("Fix redir %s %d\n", text, err));
9916 n->ndup.vname = NULL;
9918 if (is_digit(text[0]) && text[1] == '\0')
9919 n->ndup.dupfd = digit_val(text[0]);
9920 else if (text[0] == '-' && text[1] == '\0')
9925 synerror("Bad fd number");
9927 n->ndup.vname = makename();
9934 union node *n = redirnode;
9936 if (readtoken() != TWORD)
9938 if (n->type == NHERE) {
9939 struct heredoc *here = heredoc;
9945 TRACE(("Here document %d\n", n->type));
9946 if (here->striptabs) {
9947 while (*wordtext == '\t')
9950 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9951 synerror("Illegal eof marker for << redirection");
9952 rmescapes(wordtext);
9953 here->eofmark = wordtext;
9955 if (heredoclist == NULL)
9958 for (p = heredoclist ; p->next ; p = p->next);
9961 } else if (n->type == NTOFD || n->type == NFROMFD) {
9962 fixredir(n, wordtext, 0);
9964 n->nfile.fname = makename();
9970 * Input any here documents.
9975 struct heredoc *here;
9978 while (heredoclist) {
9980 heredoclist = here->next;
9985 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9986 here->eofmark, here->striptabs);
9987 n = (union node *)stalloc(sizeof (struct narg));
9988 n->narg.type = NARG;
9989 n->narg.next = NULL;
9990 n->narg.text = wordtext;
9991 n->narg.backquote = backquotelist;
9992 here->here->nhere.doc = n;
10002 return tokname_array[t][0];
10010 int savecheckalias = checkalias;
10011 int savecheckkwd = checkkwd;
10016 int alreadyseen = tokpushback;
10026 checkalias = savecheckalias;
10033 if (checkkwd == 2) {
10042 * check for keywords
10044 if (t == TWORD && !quoteflag)
10046 const char *const *pp;
10048 if ((pp = findkwd(wordtext))) {
10049 lasttoken = t = pp - tokname_array;
10050 TRACE(("keyword %s recognized\n", tokname(t)));
10061 } else if (checkalias == 2 && isassignment(wordtext)) {
10062 lasttoken = t = TASSIGN;
10064 } else if (checkalias) {
10065 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10067 pushstring(ap->val, strlen(ap->val), ap);
10069 checkkwd = savecheckkwd;
10078 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10080 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10087 * Read the next input token.
10088 * If the token is a word, we set backquotelist to the list of cmds in
10089 * backquotes. We set quoteflag to true if any part of the word was
10091 * If the token is TREDIR, then we set redirnode to a structure containing
10093 * In all cases, the variable startlinno is set to the number of the line
10094 * on which the token starts.
10096 * [Change comment: here documents and internal procedures]
10097 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10098 * word parsing code into a separate routine. In this case, readtoken
10099 * doesn't need to have any internal procedures, but parseword does.
10100 * We could also make parseoperator in essence the main routine, and
10101 * have parseword (readtoken1?) handle both words and redirection.]
10104 #define NEW_xxreadtoken
10105 #ifdef NEW_xxreadtoken
10107 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10108 static const char xxreadtoken_tokens[] = {
10109 TNL, TLP, TRP, /* only single occurrence allowed */
10110 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10111 TEOF, /* corresponds to trailing nul */
10112 TAND, TOR, TENDCASE, /* if double occurrence */
10115 #define xxreadtoken_doubles \
10116 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10117 #define xxreadtoken_singles \
10118 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10132 startlinno = plinno;
10133 for (;;) { /* until token or start of word found */
10136 if ((c!=' ') && (c!='\t')
10142 while ((c = pgetc()) != '\n' && c != PEOF);
10144 } else if (c=='\\') {
10145 if (pgetc() != '\n') {
10149 startlinno = ++plinno;
10150 setprompt(doprompt ? 2 : 0);
10153 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10158 needprompt = doprompt;
10161 p = strchr(xxreadtoken_chars, c);
10164 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10167 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10168 if (pgetc() == *p) { /* double occurrence? */
10169 p += xxreadtoken_doubles + 1;
10176 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10184 #define RETURN(token) return lasttoken = token
10198 startlinno = plinno;
10199 for (;;) { /* until token or start of word found */
10202 case ' ': case '\t':
10208 while ((c = pgetc()) != '\n' && c != PEOF);
10212 if (pgetc() == '\n') {
10213 startlinno = ++plinno;
10224 needprompt = doprompt;
10229 if (pgetc() == '&')
10234 if (pgetc() == '|')
10239 if (pgetc() == ';')
10252 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10258 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10259 * is not NULL, read a here document. In the latter case, eofmark is the
10260 * word which marks the end of the document and striptabs is true if
10261 * leading tabs should be stripped from the document. The argument firstc
10262 * is the first character of the input token or document.
10264 * Because C does not have internal subroutines, I have simulated them
10265 * using goto's to implement the subroutine linkage. The following macros
10266 * will run code that appears at the end of readtoken1.
10269 #define CHECKEND() {goto checkend; checkend_return:;}
10270 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10271 #define PARSESUB() {goto parsesub; parsesub_return:;}
10272 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10273 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10274 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10277 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10282 char line[EOFMARKLEN + 1];
10283 struct nodelist *bqlist;
10286 int varnest; /* levels of variables expansion */
10287 int arinest; /* levels of arithmetic expansion */
10288 int parenlevel; /* levels of parens in arithmetic */
10289 int dqvarnest; /* levels of variables expansion within double quotes */
10291 int prevsyntax; /* syntax before arithmetic */
10293 /* Avoid longjmp clobbering */
10299 (void) &parenlevel;
10302 (void) &prevsyntax;
10306 startlinno = plinno;
10308 if (syntax == DQSYNTAX)
10317 STARTSTACKSTR(out);
10318 loop: { /* for each line, until end of word */
10319 CHECKEND(); /* set c to PEOF if at end of here document */
10320 for (;;) { /* until end of line or end of word */
10321 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10322 switch(SIT(c,syntax)) {
10323 case CNL: /* '\n' */
10324 if (syntax == BASESYNTAX)
10325 goto endword; /* exit outer loop */
10333 goto loop; /* continue outer loop */
10338 if ((eofmark == NULL || dblquote) &&
10340 USTPUTC(CTLESC, out);
10343 case CBACK: /* backslash */
10346 USTPUTC('\\', out);
10348 } else if (c == '\n') {
10354 if (dblquote && c != '\\' && c != '`' && c != '$'
10355 && (c != '"' || eofmark != NULL))
10356 USTPUTC('\\', out);
10357 if (SIT(c,SQSYNTAX) == CCTL)
10358 USTPUTC(CTLESC, out);
10359 else if (eofmark == NULL)
10360 USTPUTC(CTLQUOTEMARK, out);
10366 if (eofmark == NULL)
10367 USTPUTC(CTLQUOTEMARK, out);
10371 if (eofmark == NULL)
10372 USTPUTC(CTLQUOTEMARK, out);
10377 if (eofmark != NULL && arinest == 0 &&
10382 syntax = ARISYNTAX;
10384 } else if (eofmark == NULL &&
10386 syntax = BASESYNTAX;
10392 case CVAR: /* '$' */
10393 PARSESUB(); /* parse substitution */
10395 case CENDVAR: /* '}' */
10398 if (dqvarnest > 0) {
10401 USTPUTC(CTLENDVAR, out);
10406 #ifdef ASH_MATH_SUPPORT
10407 case CLP: /* '(' in arithmetic */
10411 case CRP: /* ')' in arithmetic */
10412 if (parenlevel > 0) {
10416 if (pgetc() == ')') {
10417 if (--arinest == 0) {
10418 USTPUTC(CTLENDARI, out);
10419 syntax = prevsyntax;
10420 if (syntax == DQSYNTAX)
10428 * unbalanced parens
10429 * (don't 2nd guess - no error)
10437 case CBQUOTE: /* '`' */
10441 goto endword; /* exit outer loop */
10446 goto endword; /* exit outer loop */
10457 if (syntax == ARISYNTAX)
10458 synerror("Missing '))'");
10459 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10460 synerror("Unterminated quoted string");
10461 if (varnest != 0) {
10462 startlinno = plinno;
10463 synerror("Missing '}'");
10465 USTPUTC('\0', out);
10466 len = out - stackblock();
10467 out = stackblock();
10468 if (eofmark == NULL) {
10469 if ((c == '>' || c == '<')
10472 && (*out == '\0' || is_digit(*out))) {
10474 return lasttoken = TREDIR;
10479 quoteflag = quotef;
10480 backquotelist = bqlist;
10481 grabstackblock(len);
10483 return lasttoken = TWORD;
10484 /* end of readtoken routine */
10489 * Check to see whether we are at the end of the here document. When this
10490 * is called, c is set to the first character of the next input line. If
10491 * we are at the end of the here document, this routine sets the c to PEOF.
10502 while (c == '\t') {
10506 if (c == *eofmark) {
10507 if (pfgets(line, sizeof line) != NULL) {
10511 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10512 if (*p == '\n' && *q == '\0') {
10515 needprompt = doprompt;
10517 pushstring(line, strlen(line), NULL);
10522 goto checkend_return;
10527 * Parse a redirection operator. The variable "out" points to a string
10528 * specifying the fd to be redirected. The variable "c" contains the
10529 * first character of the redirection operator.
10536 np = (union node *)stalloc(sizeof (struct nfile));
10541 np->type = NAPPEND;
10550 } else { /* c == '<' */
10552 switch (c = pgetc()) {
10554 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10555 np = (union node *)stalloc(sizeof (struct nhere));
10559 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10560 heredoc->here = np;
10561 if ((c = pgetc()) == '-') {
10562 heredoc->striptabs = 1;
10564 heredoc->striptabs = 0;
10570 np->type = NFROMFD;
10574 np->type = NFROMTO;
10584 np->nfile.fd = digit_val(fd);
10586 goto parseredir_return;
10591 * Parse a substitution. At this point, we have read the dollar sign
10592 * and nothing else.
10600 static const char types[] = "}-+?=";
10605 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10609 } else if (c == '(') { /* $(command) or $((arith)) */
10610 if (pgetc() == '(') {
10617 USTPUTC(CTLVAR, out);
10618 typeloc = out - stackblock();
10619 USTPUTC(VSNORMAL, out);
10620 subtype = VSNORMAL;
10624 if ((c = pgetc()) == '}')
10627 subtype = VSLENGTH;
10632 if (c > PEOA && is_name(c)) {
10636 } while (c > PEOA && is_in_name(c));
10637 } else if (is_digit(c)) {
10641 } while (is_digit(c));
10643 else if (is_special(c)) {
10648 badsub: synerror("Bad substitution");
10652 if (subtype == 0) {
10659 p = strchr(types, c);
10662 subtype = p - types + VSNORMAL;
10668 subtype = c == '#' ? VSTRIMLEFT :
10681 if (dblquote || arinest)
10683 *(stackblock() + typeloc) = subtype | flags;
10684 if (subtype != VSNORMAL) {
10691 goto parsesub_return;
10696 * Called to parse command substitutions. Newstyle is set if the command
10697 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10698 * list of commands (passed by reference), and savelen is the number of
10699 * characters on the top of the stack which must be preserved.
10703 struct nodelist **nlpp;
10706 char *volatile str;
10707 struct jmploc jmploc;
10708 struct jmploc *volatile savehandler;
10712 (void) &saveprompt;
10715 savepbq = parsebackquote;
10716 if (setjmp(jmploc.loc)) {
10719 parsebackquote = 0;
10720 handler = savehandler;
10721 longjmp(handler->loc, 1);
10725 savelen = out - stackblock();
10727 str = xmalloc(savelen);
10728 memcpy(str, stackblock(), savelen);
10730 savehandler = handler;
10734 /* We must read until the closing backquote, giving special
10735 treatment to some slashes, and then push the string and
10736 reread it as input, interpreting it normally. */
10743 STARTSTACKSTR(pout);
10749 switch (pc = pgetc()) {
10754 if ((pc = pgetc()) == '\n') {
10761 * If eating a newline, avoid putting
10762 * the newline into the new character
10763 * stream (via the STPUTC after the
10768 if (pc != '\\' && pc != '`' && pc != '$'
10769 && (!dblquote || pc != '"'))
10770 STPUTC('\\', pout);
10780 startlinno = plinno;
10781 synerror("EOF in backquote substitution");
10785 needprompt = doprompt;
10794 STPUTC('\0', pout);
10795 psavelen = pout - stackblock();
10796 if (psavelen > 0) {
10797 pstr = grabstackstr(pout);
10798 setinputstring(pstr);
10803 nlpp = &(*nlpp)->next;
10804 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10805 (*nlpp)->next = NULL;
10806 parsebackquote = oldstyle;
10809 saveprompt = doprompt;
10816 doprompt = saveprompt;
10818 if (readtoken() != TRP)
10825 * Start reading from old file again, ignoring any pushed back
10826 * tokens left from the backquote parsing
10831 while (stackblocksize() <= savelen)
10833 STARTSTACKSTR(out);
10835 memcpy(out, str, savelen);
10836 STADJUST(savelen, out);
10842 parsebackquote = savepbq;
10843 handler = savehandler;
10844 if (arinest || dblquote)
10845 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10847 USTPUTC(CTLBACKQ, out);
10849 goto parsebackq_oldreturn;
10851 goto parsebackq_newreturn;
10855 * Parse an arithmetic expansion (indicate start of one and set state)
10859 if (++arinest == 1) {
10860 prevsyntax = syntax;
10861 syntax = ARISYNTAX;
10862 USTPUTC(CTLARI, out);
10869 * we collapse embedded arithmetic expansion to
10870 * parenthesis, which should be equivalent
10874 goto parsearith_return;
10877 } /* end of readtoken */
10881 * Returns true if the text contains nothing to expand (no dollar signs
10886 noexpand(char *text)
10892 while ((c = *p++) != '\0') {
10893 if (c == CTLQUOTEMARK)
10897 else if (SIT(c,BASESYNTAX) == CCTL)
10905 * Return true if the argument is a legal variable name (a letter or
10906 * underscore followed by zero or more letters, underscores, and digits).
10910 goodname(const char *name)
10918 if (! is_in_name(*p))
10926 * Called when an unexpected token is read during the parse. The argument
10927 * is the token that is expected, or -1 if more than one type of token can
10928 * occur at this point.
10932 synexpect(int token)
10937 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10939 sprintf(msg+l, " (expecting %s)", tokname(token));
10946 synerror(const char *msg)
10949 out2fmt("%s: %d: ", commandname, startlinno);
10950 out2fmt("Syntax error: %s\n", msg);
10951 error((char *)NULL);
10957 * called by editline -- any expansions to the prompt
10958 * should be added here.
10961 setprompt(int whichprompt)
10964 switch (whichprompt) {
10979 * Code for dealing with input/output redirection.
10982 #define EMPTY -2 /* marks an unused slot in redirtab */
10984 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10986 # define PIPESIZE PIPE_BUF
10991 * Open a file in noclobber mode.
10992 * The code was copied from bash.
10995 noclobberopen(const char *fname)
10998 struct stat finfo, finfo2;
11001 * If the file exists and is a regular file, return an error
11004 r = stat(fname, &finfo);
11005 if (r == 0 && S_ISREG(finfo.st_mode)) {
11011 * If the file was not present (r != 0), make sure we open it
11012 * exclusively so that if it is created before we open it, our open
11013 * will fail. Make sure that we do not truncate an existing file.
11014 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11015 * file was not a regular file, we leave O_EXCL off.
11018 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11019 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11021 /* If the open failed, return the file descriptor right away. */
11026 * OK, the open succeeded, but the file may have been changed from a
11027 * non-regular file to a regular file between the stat and the open.
11028 * We are assuming that the O_EXCL open handles the case where FILENAME
11029 * did not exist and is symlinked to an existing file between the stat
11034 * If we can open it and fstat the file descriptor, and neither check
11035 * revealed that it was a regular file, and the file has not been
11036 * replaced, return the file descriptor.
11038 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11039 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11042 /* The file has been replaced. badness. */
11049 * Handle here documents. Normally we fork off a process to write the
11050 * data to a pipe. If the document is short, we can stuff the data in
11051 * the pipe without forking.
11055 openhere(const union node *redir)
11061 error("Pipe call failed");
11062 if (redir->type == NHERE) {
11063 len = strlen(redir->nhere.doc->narg.text);
11064 if (len <= PIPESIZE) {
11065 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11069 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11071 signal(SIGINT, SIG_IGN);
11072 signal(SIGQUIT, SIG_IGN);
11073 signal(SIGHUP, SIG_IGN);
11075 signal(SIGTSTP, SIG_IGN);
11077 signal(SIGPIPE, SIG_DFL);
11078 if (redir->type == NHERE)
11079 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11081 expandhere(redir->nhere.doc, pip[1]);
11091 openredirect(const union node *redir)
11096 switch (redir->nfile.type) {
11098 fname = redir->nfile.expfname;
11099 if ((f = open(fname, O_RDONLY)) < 0)
11103 fname = redir->nfile.expfname;
11104 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11108 /* Take care of noclobber mode. */
11110 fname = redir->nfile.expfname;
11111 if ((f = noclobberopen(fname)) < 0)
11116 fname = redir->nfile.expfname;
11118 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11121 if ((f = creat(fname, 0666)) < 0)
11126 fname = redir->nfile.expfname;
11128 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11131 if ((f = open(fname, O_WRONLY)) < 0
11132 && (f = creat(fname, 0666)) < 0)
11134 lseek(f, (off_t)0, 2);
11141 /* Fall through to eliminate warning. */
11148 f = openhere(redir);
11154 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11156 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11161 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11162 * old file descriptors are stashed away so that the redirection can be
11163 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11164 * standard output, and the standard error if it becomes a duplicate of
11169 redirect(union node *redir, int flags)
11172 struct redirtab *sv = NULL;
11177 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11179 if (flags & REDIR_PUSH) {
11180 sv = xmalloc(sizeof (struct redirtab));
11181 for (i = 0 ; i < 10 ; i++)
11182 sv->renamed[i] = EMPTY;
11183 sv->next = redirlist;
11186 for (n = redir ; n ; n = n->nfile.next) {
11189 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11190 n->ndup.dupfd == fd)
11191 continue; /* redirect from/to same file descriptor */
11194 newfd = openredirect(n);
11195 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11198 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11202 dupredirect(n, newfd, fd1dup);
11212 error("%d: %m", fd);
11218 if (flags & REDIR_PUSH) {
11219 sv->renamed[fd] = i;
11222 } else if (fd != newfd) {
11228 dupredirect(n, newfd, fd1dup);
11235 dupredirect(const union node *redir, int f, int fd1dup)
11237 int fd = redir->nfile.fd;
11241 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11242 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11243 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11244 dup_as_newfd(redir->ndup.dupfd, fd);
11250 dup_as_newfd(f, fd);
11259 * Undo the effects of the last redirection.
11265 struct redirtab *rp = redirlist;
11269 for (i = 0 ; i < 10 ; i++) {
11270 if (rp->renamed[i] != EMPTY) {
11274 if (rp->renamed[i] >= 0) {
11275 dup_as_newfd(rp->renamed[i], i);
11276 close(rp->renamed[i]);
11280 redirlist = rp->next;
11286 * Discard all saved file descriptors.
11291 struct redirtab *rp;
11294 for (rp = redirlist ; rp ; rp = rp->next) {
11295 for (i = 0 ; i < 10 ; i++) {
11296 if (rp->renamed[i] >= 0) {
11297 close(rp->renamed[i]);
11299 rp->renamed[i] = EMPTY;
11306 * Copy a file descriptor to be >= to. Returns -1
11307 * if the source file descriptor is closed, EMPTY if there are no unused
11308 * file descriptors left.
11312 dup_as_newfd(int from, int to)
11316 newfd = fcntl(from, F_DUPFD, to);
11318 if (errno == EMFILE)
11321 error("%d: %m", from);
11330 static void shtree (union node *, int, char *, FILE*);
11331 static void shcmd (union node *, FILE *);
11332 static void sharg (union node *, FILE *);
11333 static void indent (int, char *, FILE *);
11334 static void trstring (char *);
11341 trputs("showtree called\n");
11342 shtree(n, 1, NULL, stdout);
11347 shtree(union node *n, int ind, char *pfx, FILE *fp)
11349 struct nodelist *lp;
11355 indent(ind, pfx, fp);
11366 shtree(n->nbinary.ch1, ind, NULL, fp);
11369 shtree(n->nbinary.ch2, ind, NULL, fp);
11377 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11382 if (n->npipe.backgnd)
11388 fprintf(fp, "<node type %d>", n->type);
11398 shcmd(union node *cmd, FILE *fp)
11406 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11412 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11418 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11419 s = redir_strings[np->nfile.type - NTO];
11425 switch (np->nfile.type) {
11426 case NTO: s = ">"; dftfd = 1; break;
11427 case NAPPEND: s = ">>"; dftfd = 1; break;
11428 case NTOFD: s = ">&"; dftfd = 1; break;
11429 case NTOOV: s = ">|"; dftfd = 1; break;
11430 case NFROM: s = "<"; dftfd = 0; break;
11431 case NFROMFD: s = "<&"; dftfd = 0; break;
11432 case NFROMTO: s = "<>"; dftfd = 0; break;
11433 default: s = "*error*"; dftfd = 0; break;
11436 if (np->nfile.fd != dftfd)
11437 fprintf(fp, "%d", np->nfile.fd);
11439 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11440 fprintf(fp, "%d", np->ndup.dupfd);
11442 sharg(np->nfile.fname, fp);
11449 sharg(union node *arg, FILE *fp)
11452 struct nodelist *bqlist;
11455 if (arg->type != NARG) {
11456 printf("<node type %d>\n", arg->type);
11460 bqlist = arg->narg.backquote;
11461 for (p = arg->narg.text ; *p ; p++) {
11470 if (subtype == VSLENGTH)
11476 if (subtype & VSNUL)
11479 switch (subtype & VSTYPE) {
11498 case VSTRIMLEFTMAX:
11505 case VSTRIMRIGHTMAX:
11512 printf("<subtype %d>", subtype);
11519 case CTLBACKQ|CTLQUOTE:
11522 shtree(bqlist->n, -1, NULL, fp);
11534 indent(int amount, char *pfx, FILE *fp)
11538 for (i = 0 ; i < amount ; i++) {
11539 if (pfx && i == amount - 1)
11549 static int debug = 1;
11551 static int debug = 0;
11558 if (tracefile == NULL)
11560 putc(c, tracefile);
11566 trace(const char *fmt, ...)
11570 if (tracefile != NULL) {
11571 (void) vfprintf(tracefile, fmt, va);
11572 if (strchr(fmt, '\n'))
11573 (void) fflush(tracefile);
11580 trputs(const char *s)
11582 if (tracefile == NULL)
11584 fputs(s, tracefile);
11585 if (strchr(s, '\n'))
11596 if (tracefile == NULL)
11598 putc('"', tracefile);
11599 for (p = s ; *p ; p++) {
11601 case '\n': c = 'n'; goto backslash;
11602 case '\t': c = 't'; goto backslash;
11603 case '\r': c = 'r'; goto backslash;
11604 case '"': c = '"'; goto backslash;
11605 case '\\': c = '\\'; goto backslash;
11606 case CTLESC: c = 'e'; goto backslash;
11607 case CTLVAR: c = 'v'; goto backslash;
11608 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11609 case CTLBACKQ: c = 'q'; goto backslash;
11610 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11611 backslash: putc('\\', tracefile);
11612 putc(c, tracefile);
11615 if (*p >= ' ' && *p <= '~')
11616 putc(*p, tracefile);
11618 putc('\\', tracefile);
11619 putc(*p >> 6 & 03, tracefile);
11620 putc(*p >> 3 & 07, tracefile);
11621 putc(*p & 07, tracefile);
11626 putc('"', tracefile);
11633 if (tracefile == NULL)
11638 putc(' ', tracefile);
11640 putc('\n', tracefile);
11656 #ifdef not_this_way
11659 if ((p = getenv("HOME")) == NULL) {
11660 if (geteuid() == 0)
11666 strcat(s, "/trace");
11669 strcpy(s, "./trace");
11670 #endif /* not_this_way */
11671 if ((tracefile = wfopen(s, "a")) == NULL)
11674 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11675 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11677 fputs("\nTracing started.\n", tracefile);
11684 * The trap builtin.
11688 trapcmd(int argc, char **argv)
11695 for (signo = 0 ; signo < NSIG ; signo++) {
11696 if (trap[signo] != NULL) {
11700 p = single_quote(trap[signo]);
11701 sn = sys_siglist[signo];
11703 sn = u_signal_names(0, &signo, 0);
11706 printf("trap -- %s %s\n", p, sn);
11718 if ((signo = decode_signal(*ap, 0)) < 0)
11719 error("%s: bad trap", *ap);
11722 if (action[0] == '-' && action[1] == '\0')
11725 action = xstrdup(action);
11728 ckfree(trap[signo]);
11729 trap[signo] = action;
11744 * Set the signal handler for the specified signal. The routine figures
11745 * out what it should be set to.
11749 setsignal(int signo)
11753 struct sigaction act;
11755 if ((t = trap[signo]) == NULL)
11757 else if (*t != '\0')
11761 if (rootshell && action == S_DFL) {
11764 if (iflag || minusc || sflag == 0)
11790 t = &sigmode[signo - 1];
11793 * current setting unknown
11795 if (sigaction(signo, 0, &act) == -1) {
11797 * Pretend it worked; maybe we should give a warning
11798 * here, but other shells don't. We don't alter
11799 * sigmode, so that we retry every time.
11803 if (act.sa_handler == SIG_IGN) {
11804 if (mflag && (signo == SIGTSTP ||
11805 signo == SIGTTIN || signo == SIGTTOU)) {
11806 *t = S_IGN; /* don't hard ignore these */
11810 *t = S_RESET; /* force to be set */
11813 if (*t == S_HARD_IGN || *t == action)
11815 act.sa_handler = ((action == S_CATCH) ? onsig
11816 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11819 sigemptyset(&act.sa_mask);
11820 sigaction(signo, &act, 0);
11828 ignoresig(int signo)
11830 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11831 signal(signo, SIG_IGN);
11833 sigmode[signo - 1] = S_HARD_IGN;
11844 if (signo == SIGINT && trap[SIGINT] == NULL) {
11848 gotsig[signo - 1] = 1;
11854 * Called to execute a trap. Perhaps we should avoid entering new trap
11855 * handlers while we are executing a trap handler.
11865 for (i = 1 ; ; i++) {
11872 savestatus=exitstatus;
11873 evalstring(trap[i], 0);
11874 exitstatus=savestatus;
11881 * Called to exit the shell.
11885 exitshell(int status)
11887 struct jmploc loc1, loc2;
11890 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11891 if (setjmp(loc1.loc)) {
11894 if (setjmp(loc2.loc)) {
11898 if ((p = trap[0]) != NULL && *p != '\0') {
11902 l1: handler = &loc2; /* probably unnecessary */
11911 static int decode_signal(const char *string, int minsig)
11914 const char *name = u_signal_names(string, &signo, minsig);
11916 return name ? signo : -1;
11919 static struct var **hashvar (const char *);
11920 static void showvars (const char *, int, int);
11921 static struct var **findvar (struct var **, const char *);
11924 * Initialize the varable symbol tables and import the environment
11928 * This routine initializes the builtin variables. It is called when the
11929 * shell is initialized and again when a shell procedure is spawned.
11934 const struct varinit *ip;
11938 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
11939 if ((vp->flags & VEXPORT) == 0) {
11940 vpp = hashvar(ip->text);
11943 vp->text = xstrdup(ip->text);
11944 vp->flags = ip->flags;
11945 vp->func = ip->func;
11949 * PS1 depends on uid
11951 if ((vps1.flags & VEXPORT) == 0) {
11952 vpp = hashvar("PS1=");
11955 vps1.text = xstrdup(geteuid() ? "PS1=$ " : "PS1=# ");
11956 vps1.flags = VSTRFIXED|VTEXTFIXED;
11961 * Set the value of a variable. The flags argument is ored with the
11962 * flags of the variable. If val is NULL, the variable is unset.
11966 setvar(const char *name, const char *val, int flags)
11981 if (! is_in_name(*p)) {
11982 if (*p == '\0' || *p == '=')
11988 namelen = p - name;
11990 error("%.*s: bad variable name", namelen, name);
11991 len = namelen + 2; /* 2 is space for '=' and '\0' */
11995 len += vallen = strlen(val);
11998 nameeq = xmalloc(len);
11999 memcpy(nameeq, name, namelen);
12000 nameeq[namelen] = '=';
12002 memcpy(nameeq + namelen + 1, val, vallen + 1);
12004 nameeq[namelen + 1] = '\0';
12006 setvareq(nameeq, flags);
12013 * Same as setvar except that the variable and value are passed in
12014 * the first argument as name=value. Since the first argument will
12015 * be actually stored in the table, it should not be a string that
12020 setvareq(char *s, int flags)
12022 struct var *vp, **vpp;
12025 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12026 if ((vp = *findvar(vpp, s))) {
12027 if (vp->flags & VREADONLY) {
12028 size_t len = strchr(s, '=') - s;
12029 error("%.*s: is read only", len, s);
12033 if (vp->func && (flags & VNOFUNC) == 0)
12034 (*vp->func)(strchr(s, '=') + 1);
12036 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12039 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12040 vp->flags |= flags;
12045 * We could roll this to a function, to handle it as
12046 * a regular variable function callback, but why bother?
12048 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12055 vp = xmalloc(sizeof (*vp));
12066 * Process a linked list of variable assignments.
12070 listsetvar(struct strlist *mylist)
12072 struct strlist *lp;
12075 for (lp = mylist ; lp ; lp = lp->next) {
12076 setvareq(xstrdup(lp->text), 0);
12084 * Find the value of a variable. Returns NULL if not set.
12087 static const char *
12088 lookupvar(const char *name)
12092 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12093 return strchr(v->text, '=') + 1;
12101 * Search the environment of a builtin command.
12104 static const char *
12105 bltinlookup(const char *name)
12107 const struct strlist *sp;
12109 for (sp = cmdenviron ; sp ; sp = sp->next) {
12110 if (varequal(sp->text, name))
12111 return strchr(sp->text, '=') + 1;
12113 return lookupvar(name);
12119 * Generate a list of exported variables. This routine is used to construct
12120 * the third argument to execve when executing a program.
12132 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12133 for (vp = *vpp ; vp ; vp = vp->next)
12134 if (vp->flags & VEXPORT)
12137 ep = env = stalloc((nenv + 1) * sizeof *env);
12138 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12139 for (vp = *vpp ; vp ; vp = vp->next)
12140 if (vp->flags & VEXPORT)
12149 * Called when a shell procedure is invoked to clear out nonexported
12150 * variables. It is also necessary to reallocate variables of with
12151 * VSTACK set since these are currently allocated on the stack.
12157 struct var *vp, **prev;
12159 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12160 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12161 if ((vp->flags & VEXPORT) == 0) {
12163 if ((vp->flags & VTEXTFIXED) == 0)
12165 if ((vp->flags & VSTRFIXED) == 0)
12168 if (vp->flags & VSTACK) {
12169 vp->text = xstrdup(vp->text);
12170 vp->flags &=~ VSTACK;
12182 * Command to list all variables which are set. Currently this command
12183 * is invoked from the set command when the set command is called without
12188 showvarscmd(int argc, char **argv)
12190 showvars(nullstr, VUNSET, VUNSET);
12197 * The export and readonly commands.
12201 exportcmd(int argc, char **argv)
12206 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12209 listsetvar(cmdenviron);
12210 pflag = (nextopt("p") == 'p');
12211 if (argc > 1 && !pflag) {
12212 while ((name = *argptr++) != NULL) {
12213 if ((p = strchr(name, '=')) != NULL) {
12216 if ((vp = *findvar(hashvar(name), name))) {
12221 setvar(name, p, flag);
12225 showvars(argv[0], flag, 0);
12232 * The "local" command.
12235 /* funcnest nonzero if we are currently evaluating a function */
12238 localcmd(int argc, char **argv)
12243 error("Not in a function");
12244 while ((name = *argptr++) != NULL) {
12252 * Make a variable a local variable. When a variable is made local, it's
12253 * value and flags are saved in a localvar structure. The saved values
12254 * will be restored when the shell function returns. We handle the name
12255 * "-" as a special case.
12259 mklocal(char *name)
12261 struct localvar *lvp;
12266 lvp = xmalloc(sizeof (struct localvar));
12267 if (name[0] == '-' && name[1] == '\0') {
12269 p = xmalloc(sizeof optet_vals);
12270 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12273 vpp = hashvar(name);
12274 vp = *findvar(vpp, name);
12276 if (strchr(name, '='))
12277 setvareq(xstrdup(name), VSTRFIXED);
12279 setvar(name, NULL, VSTRFIXED);
12280 vp = *vpp; /* the new variable */
12282 lvp->flags = VUNSET;
12284 lvp->text = vp->text;
12285 lvp->flags = vp->flags;
12286 vp->flags |= VSTRFIXED|VTEXTFIXED;
12287 if (strchr(name, '='))
12288 setvareq(xstrdup(name), 0);
12292 lvp->next = localvars;
12299 * Called after a function returns.
12304 struct localvar *lvp;
12307 while ((lvp = localvars) != NULL) {
12308 localvars = lvp->next;
12310 if (vp == NULL) { /* $- saved */
12311 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12313 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12314 (void)unsetvar(vp->text);
12316 if ((vp->flags & VTEXTFIXED) == 0)
12318 vp->flags = lvp->flags;
12319 vp->text = lvp->text;
12327 setvarcmd(int argc, char **argv)
12330 return unsetcmd(argc, argv);
12331 else if (argc == 3)
12332 setvar(argv[1], argv[2], 0);
12334 error("List assignment not implemented");
12340 * The unset builtin command. We unset the function before we unset the
12341 * variable to allow a function to be unset when there is a readonly variable
12342 * with the same name.
12346 unsetcmd(int argc, char **argv)
12354 while ((i = nextopt("vf")) != '\0') {
12360 if (flg_func == 0 && flg_var == 0)
12363 for (ap = argptr; *ap ; ap++) {
12367 ret |= unsetvar(*ap);
12374 * Unset the specified variable.
12378 unsetvar(const char *s)
12383 vpp = findvar(hashvar(s), s);
12386 if (vp->flags & VREADONLY)
12389 if (*(strchr(vp->text, '=') + 1) != '\0')
12390 setvar(s, nullstr, 0);
12391 vp->flags &= ~VEXPORT;
12392 vp->flags |= VUNSET;
12393 if ((vp->flags & VSTRFIXED) == 0) {
12394 if ((vp->flags & VTEXTFIXED) == 0)
12409 * Find the appropriate entry in the hash table from the name.
12412 static struct var **
12413 hashvar(const char *p)
12415 unsigned int hashval;
12417 hashval = ((unsigned char) *p) << 4;
12418 while (*p && *p != '=')
12419 hashval += (unsigned char) *p++;
12420 return &vartab[hashval % VTABSIZE];
12426 * Returns true if the two strings specify the same varable. The first
12427 * variable name is terminated by '='; the second may be terminated by
12428 * either '=' or '\0'.
12432 varequal(const char *p, const char *q)
12434 while (*p == *q++) {
12438 if (*p == '=' && *(q - 1) == '\0')
12444 showvars(const char *myprefix, int mask, int xor)
12448 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12450 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12451 for (vp = *vpp ; vp ; vp = vp->next) {
12452 if ((vp->flags & mask) ^ xor) {
12456 p = strchr(vp->text, '=') + 1;
12457 len = p - vp->text;
12458 p = single_quote(p);
12460 printf("%s%s%.*s%s\n", myprefix, sep, len,
12468 static struct var **
12469 findvar(struct var **vpp, const char *name)
12471 for (; *vpp; vpp = &(*vpp)->next) {
12472 if (varequal((*vpp)->text, name)) {
12480 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12481 * This file contains code for the times builtin.
12482 * $Id: ash.c,v 1.42 2001/12/31 06:07:57 aaronl Exp $
12484 static int timescmd (int argc, char **argv)
12487 long int clk_tck = sysconf(_SC_CLK_TCK);
12490 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12491 (int) (buf.tms_utime / clk_tck / 60),
12492 ((double) buf.tms_utime) / clk_tck,
12493 (int) (buf.tms_stime / clk_tck / 60),
12494 ((double) buf.tms_stime) / clk_tck,
12495 (int) (buf.tms_cutime / clk_tck / 60),
12496 ((double) buf.tms_cutime) / clk_tck,
12497 (int) (buf.tms_cstime / clk_tck / 60),
12498 ((double) buf.tms_cstime) / clk_tck);
12502 #ifdef ASH_MATH_SUPPORT
12503 /* The let builtin. */
12504 int letcmd(int argc, char **argv)
12509 char *tmp, *expression, p[13];
12510 expression = strchr(argv[1], '=');
12512 /* Cannot use 'error()' here, or the return code
12513 * will be incorrect */
12514 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12517 *expression = '\0';
12518 tmp = ++expression;
12519 result = arith(tmp, &errcode);
12521 /* Cannot use 'error()' here, or the return code
12522 * will be incorrect */
12523 out2fmt("sh: let: ");
12525 out2fmt("divide by zero");
12527 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12530 snprintf(p, 12, "%ld", result);
12531 setvar(argv[1], xstrdup(p), 0);
12532 } else if (argc >= 3)
12533 synerror("invalid operand");
12541 * Copyright (c) 1989, 1991, 1993, 1994
12542 * The Regents of the University of California. All rights reserved.
12544 * This code is derived from software contributed to Berkeley by
12545 * Kenneth Almquist.
12547 * Redistribution and use in source and binary forms, with or without
12548 * modification, are permitted provided that the following conditions
12550 * 1. Redistributions of source code must retain the above copyright
12551 * notice, this list of conditions and the following disclaimer.
12552 * 2. Redistributions in binary form must reproduce the above copyright
12553 * notice, this list of conditions and the following disclaimer in the
12554 * documentation and/or other materials provided with the distribution.
12556 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12557 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12559 * 4. Neither the name of the University nor the names of its contributors
12560 * may be used to endorse or promote products derived from this software
12561 * without specific prior written permission.
12563 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12564 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12565 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12566 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12567 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12568 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12569 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12570 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12571 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12572 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF