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;
3002 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3010 * The return command.
3014 returncmd(int argc, char **argv)
3016 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3019 evalskip = SKIPFUNC;
3024 /* Do what ksh does; skip the rest of the file */
3025 evalskip = SKIPFILE;
3032 #ifndef CONFIG_FALSE
3034 false_main(int argc, char **argv)
3042 true_main(int argc, char **argv)
3049 * Controls whether the shell is interactive or not.
3052 static void setsignal(int signo);
3055 static void chkmail(int silent);
3059 setinteractive(int on)
3061 static int is_interactive;
3062 static int do_banner=0;
3064 if (on == is_interactive)
3072 is_interactive = on;
3073 if (do_banner==0 && is_interactive) {
3074 /* Looks like they want an interactive shell */
3075 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3076 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3077 printf( "Enter 'help' for a list of built-in commands.\n\n");
3086 setinteractive(iflag);
3092 execcmd(int argc, char **argv)
3097 iflag = 0; /* exit on error */
3100 for (sp = cmdenviron; sp ; sp = sp->next)
3101 setvareq(sp->text, VEXPORT|VSTACK);
3102 shellexec(argv + 1, environment(), pathval(), 0);
3108 eprintlist(struct strlist *sp)
3110 for (; sp; sp = sp->next) {
3111 out2fmt(" %s",sp->text);
3116 * Exec a program. Never returns. If you change this routine, you may
3117 * have to change the find_command routine as well.
3120 static const char *pathopt; /* set by padvance */
3123 shellexec(char **argv, char **envp, const char *path, int idx)
3128 if (strchr(argv[0], '/') != NULL) {
3129 tryexec(argv[0], argv, envp);
3133 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3134 if (--idx < 0 && pathopt == NULL) {
3135 tryexec(cmdname, argv, envp);
3136 if (errno != ENOENT && errno != ENOTDIR)
3143 /* Map to POSIX errors */
3155 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3160 * Clear traps on a fork.
3167 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3168 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3173 setsignal(tp - trap);
3208 /* from options.c: */
3212 for (i = 0; i < NOPTS; i++)
3228 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3240 static int preadbuffer(void);
3241 static void pushfile (void);
3244 * Read a character from the script, returning PEOF on end of file.
3245 * Nul characters in the input are silently discarded.
3248 #ifndef ASH_OPTIMIZE_FOR_SIZE
3249 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3253 return pgetc_macro();
3259 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3265 return pgetc_macro();
3271 * Undo the last call to pgetc. Only one character may be pushed back.
3272 * PEOF may be pushed back.
3275 static void pungetc(void)
3285 struct parsefile *pf = parsefile;
3294 parsefile = pf->prev;
3296 parsenleft = parsefile->nleft;
3297 parselleft = parsefile->lleft;
3298 parsenextc = parsefile->nextc;
3299 plinno = parsefile->linno;
3305 * Return to top level.
3311 while (parsefile != &basepf)
3316 * Close the file(s) that the shell is reading commands from. Called
3317 * after a fork is done.
3320 static void closescript(void)
3323 if (parsefile->fd > 0) {
3324 close(parsefile->fd);
3331 * Like setinputfile, but takes an open file descriptor. Call this with
3335 static void setinputfd(int fd, int push)
3337 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3343 while (parsefile->strpush)
3347 if (parsefile->buf == NULL)
3348 parsefile->buf = xmalloc(BUFSIZ);
3349 parselleft = parsenleft = 0;
3355 * Set the input to take input from a file. If push is set, push the
3356 * old input onto the stack first.
3360 setinputfile(const char *fname, int push)
3366 if ((fd = open(fname, O_RDONLY)) < 0)
3367 error("Can't open %s", fname);
3369 myfileno2 = dup_as_newfd(fd, 10);
3372 error("Out of file descriptors");
3375 setinputfd(fd, push);
3381 tryexec(char *cmd, char **argv, char **envp)
3385 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3389 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3390 name = get_last_path_component(name);
3393 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3396 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3398 run_applet_by_name(name, argc_l, argv);
3400 execve(cmd, argv, envp);
3405 setinputfile(cmd, 0);
3406 commandname = arg0 = xstrdup(argv[0]);
3408 exraise(EXSHELLPROC);
3413 static char *commandtext (const union node *);
3416 * Do a path search. The variable path (passed by reference) should be
3417 * set to the start of the path before the first call; padvance will update
3418 * this value as it proceeds. Successive calls to padvance will return
3419 * the possible path expansions in sequence. If an option (indicated by
3420 * a percent sign) appears in the path entry then the global variable
3421 * pathopt will be set to point to it; otherwise pathopt will be set to
3425 static const char *pathopt;
3427 static void growstackblock(void);
3431 padvance(const char **path, const char *name)
3441 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3442 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3443 while (stackblocksize() < len)
3447 memcpy(q, start, p - start);
3455 while (*p && *p != ':') p++;
3461 return stalloc(len);
3465 * Wrapper around strcmp for qsort/bsearch/...
3468 pstrcmp(const void *a, const void *b)
3470 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3474 * Find a keyword is in a sorted array.
3477 static const char *const *
3478 findkwd(const char *s)
3480 return bsearch(s, tokname_array + KWDOFFSET,
3481 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3482 sizeof(const char *), pstrcmp);
3486 /*** Command hashing code ***/
3490 hashcmd(int argc, char **argv)
3492 struct tblentry **pp;
3493 struct tblentry *cmdp;
3496 struct cmdentry entry;
3499 const struct alias *ap;
3503 while ((c = nextopt("rvV")) != '\0') {
3507 } else if (c == 'v' || c == 'V') {
3511 if (*argptr == NULL) {
3512 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3513 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3514 if (cmdp->cmdtype != CMDBUILTIN) {
3515 printentry(cmdp, verbose);
3522 while ((name = *argptr++) != NULL) {
3523 if ((cmdp = cmdlookup(name, 0)) != NULL
3524 && (cmdp->cmdtype == CMDNORMAL
3525 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3528 /* Then look at the aliases */
3529 if ((ap = *__lookupalias(name)) != NULL) {
3531 printf("%s is an alias for %s\n", name, ap->val);
3537 /* First look at the keywords */
3538 if (findkwd(name)!=0) {
3540 printf("%s is a shell keyword\n", name);
3546 find_command(name, &entry, DO_ERR, pathval());
3547 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3549 cmdp = cmdlookup(name, 0);
3550 if (cmdp) printentry(cmdp, verbose=='v');
3558 printentry(struct tblentry *cmdp, int verbose)
3564 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3565 if (cmdp->cmdtype == CMDNORMAL) {
3566 idx = cmdp->param.index;
3569 name = padvance(&path, cmdp->cmdname);
3571 } while (--idx >= 0);
3574 } else if (cmdp->cmdtype == CMDBUILTIN) {
3576 out1str("a shell builtin");
3577 } else if (cmdp->cmdtype == CMDFUNCTION) {
3580 out1str("a function\n");
3581 name = commandtext(cmdp->param.func);
3582 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3588 error("internal error: cmdtype %d", cmdp->cmdtype);
3591 puts(cmdp->rehash ? "*" : nullstr);
3596 /*** List the available builtins ***/
3599 static int helpcmd(int argc, char** argv)
3603 printf("\nBuilt-in commands:\n-------------------\n");
3604 for (col=0, i=0; i < NUMBUILTINS; i++) {
3605 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3606 builtincmds[i].name+1);
3612 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3614 extern const struct BB_applet applets[];
3615 extern const size_t NUM_APPLETS;
3617 for (i=0; i < NUM_APPLETS; i++) {
3619 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3629 return EXIT_SUCCESS;
3633 * Resolve a command name. If you change this routine, you may have to
3634 * change the shellexec routine as well.
3637 static int prefix (const char *, const char *);
3640 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3642 struct tblentry *cmdp;
3652 struct builtincmd *bcmd;
3654 /* If name contains a slash, don't use the hash table */
3655 if (strchr(name, '/') != NULL) {
3657 while (stat(name, &statb) < 0) {
3658 if (errno != ENOENT && errno != ENOTDIR)
3660 entry->cmdtype = CMDUNKNOWN;
3661 entry->u.index = -1;
3664 entry->cmdtype = CMDNORMAL;
3665 entry->u.index = -1;
3668 entry->cmdtype = CMDNORMAL;
3674 if (act & DO_BRUTE) {
3675 firstchange = path_change(path, &bltin);
3681 /* If name is in the table, and not invalidated by cd, we're done */
3682 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3683 if (cmdp->cmdtype == CMDFUNCTION) {
3684 if (act & DO_NOFUN) {
3689 } else if (act & DO_BRUTE) {
3690 if ((cmdp->cmdtype == CMDNORMAL &&
3691 cmdp->param.index >= firstchange) ||
3692 (cmdp->cmdtype == CMDBUILTIN &&
3693 ((builtinloc < 0 && bltin >= 0) ?
3694 bltin : builtinloc) >= firstchange)) {
3695 /* need to recompute the entry */
3704 bcmd = find_builtin(name);
3705 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3708 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3711 } else if (act & DO_BRUTE) {
3712 if (firstchange == 0) {
3717 /* If %builtin not in path, check for builtin next */
3718 if (regular || (bltin < 0 && bcmd)) {
3721 entry->cmdtype = CMDBUILTIN;
3722 entry->u.cmd = bcmd;
3726 cmdp = cmdlookup(name, 1);
3727 cmdp->cmdtype = CMDBUILTIN;
3728 cmdp->param.cmd = bcmd;
3733 /* We have to search path. */
3734 prev = -1; /* where to start */
3735 if (cmdp && cmdp->rehash) { /* doing a rehash */
3736 if (cmdp->cmdtype == CMDBUILTIN)
3739 prev = cmdp->param.index;
3745 while ((fullname = padvance(&path, name)) != NULL) {
3746 stunalloc(fullname);
3748 if (idx >= firstchange) {
3752 if (prefix("builtin", pathopt)) {
3753 if ((bcmd = find_builtin(name))) {
3757 } else if (!(act & DO_NOFUN) &&
3758 prefix("func", pathopt)) {
3761 continue; /* ignore unimplemented options */
3764 /* if rehash, don't redo absolute path names */
3765 if (fullname[0] == '/' && idx <= prev &&
3766 idx < firstchange) {
3769 TRACE(("searchexec \"%s\": no change\n", name));
3772 while (stat(fullname, &statb) < 0) {
3773 if (errno != ENOENT && errno != ENOTDIR)
3777 e = EACCES; /* if we fail, this will be the error */
3778 if (!S_ISREG(statb.st_mode))
3780 if (pathopt) { /* this is a %func directory */
3781 stalloc(strlen(fullname) + 1);
3782 readcmdfile(fullname);
3783 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3784 error("%s not defined in %s", name, fullname);
3785 stunalloc(fullname);
3788 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3789 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3790 be a function and we're being called with DO_NOFUN */
3792 entry->cmdtype = CMDNORMAL;
3793 entry->u.index = idx;
3797 cmdp = cmdlookup(name, 1);
3798 cmdp->cmdtype = CMDNORMAL;
3799 cmdp->param.index = idx;
3804 /* We failed. If there was an entry for this command, delete it */
3805 if (cmdp && updatetbl)
3808 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3809 entry->cmdtype = CMDUNKNOWN;
3814 entry->cmdtype = cmdp->cmdtype;
3815 entry->u = cmdp->param;
3821 * Search the table of builtin commands.
3825 bstrcmp(const void *name, const void *b)
3827 return strcmp((const char *)name, (*(const char *const *) b)+1);
3830 static struct builtincmd *
3831 find_builtin(const char *name)
3833 struct builtincmd *bp;
3835 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3843 * Called when a cd is done. Marks all commands so the next time they
3844 * are executed they will be rehashed.
3850 struct tblentry **pp;
3851 struct tblentry *cmdp;
3853 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3854 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3855 if (cmdp->cmdtype == CMDNORMAL
3856 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3865 * Called before PATH is changed. The argument is the new value of PATH;
3866 * pathval() still returns the old value at this point. Called with
3871 changepath(const char *newval)
3876 firstchange = path_change(newval, &bltin);
3877 if (builtinloc < 0 && bltin >= 0)
3878 builtinloc = bltin; /* zap builtins */
3879 clearcmdentry(firstchange);
3885 * Clear out command entries. The argument specifies the first entry in
3886 * PATH which has changed.
3890 clearcmdentry(int firstchange)
3892 struct tblentry **tblp;
3893 struct tblentry **pp;
3894 struct tblentry *cmdp;
3897 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3899 while ((cmdp = *pp) != NULL) {
3900 if ((cmdp->cmdtype == CMDNORMAL &&
3901 cmdp->param.index >= firstchange)
3902 || (cmdp->cmdtype == CMDBUILTIN &&
3903 builtinloc >= firstchange)) {
3916 * Delete all functions.
3922 struct tblentry **tblp;
3923 struct tblentry **pp;
3924 struct tblentry *cmdp;
3927 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3929 while ((cmdp = *pp) != NULL) {
3930 if (cmdp->cmdtype == CMDFUNCTION) {
3932 freefunc(cmdp->param.func);
3945 * Locate a command in the command hash table. If "add" is nonzero,
3946 * add the command to the table if it is not already present. The
3947 * variable "lastcmdentry" is set to point to the address of the link
3948 * pointing to the entry, so that delete_cmd_entry can delete the
3952 static struct tblentry **lastcmdentry;
3954 static struct tblentry *
3955 cmdlookup(const char *name, int add)
3959 struct tblentry *cmdp;
3960 struct tblentry **pp;
3967 pp = &cmdtable[hashval % CMDTABLESIZE];
3968 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3969 if (equal(cmdp->cmdname, name))
3973 if (add && cmdp == NULL) {
3975 cmdp = *pp = xmalloc(sizeof (struct tblentry) - ARB
3976 + strlen(name) + 1);
3978 cmdp->cmdtype = CMDUNKNOWN;
3980 strcpy(cmdp->cmdname, name);
3988 * Delete the command entry returned on the last lookup.
3994 struct tblentry *cmdp;
3997 cmdp = *lastcmdentry;
3998 *lastcmdentry = cmdp->next;
4007 static const unsigned char nodesize[26] = {
4008 ALIGN(sizeof (struct nbinary)),
4009 ALIGN(sizeof (struct ncmd)),
4010 ALIGN(sizeof (struct npipe)),
4011 ALIGN(sizeof (struct nredir)),
4012 ALIGN(sizeof (struct nredir)),
4013 ALIGN(sizeof (struct nredir)),
4014 ALIGN(sizeof (struct nbinary)),
4015 ALIGN(sizeof (struct nbinary)),
4016 ALIGN(sizeof (struct nif)),
4017 ALIGN(sizeof (struct nbinary)),
4018 ALIGN(sizeof (struct nbinary)),
4019 ALIGN(sizeof (struct nfor)),
4020 ALIGN(sizeof (struct ncase)),
4021 ALIGN(sizeof (struct nclist)),
4022 ALIGN(sizeof (struct narg)),
4023 ALIGN(sizeof (struct narg)),
4024 ALIGN(sizeof (struct nfile)),
4025 ALIGN(sizeof (struct nfile)),
4026 ALIGN(sizeof (struct nfile)),
4027 ALIGN(sizeof (struct nfile)),
4028 ALIGN(sizeof (struct nfile)),
4029 ALIGN(sizeof (struct ndup)),
4030 ALIGN(sizeof (struct ndup)),
4031 ALIGN(sizeof (struct nhere)),
4032 ALIGN(sizeof (struct nhere)),
4033 ALIGN(sizeof (struct nnot)),
4039 * Delete a function if it exists.
4043 unsetfunc(char *name)
4045 struct tblentry *cmdp;
4047 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4048 freefunc(cmdp->param.func);
4055 * Locate and print what a word is...
4059 typecmd(int argc, char **argv)
4067 for (i = 1; i < argc; i++) {
4068 argv_a[0] = argv[i];
4071 err |= hashcmd(argc, argv);
4078 commandcmd(int argc, char **argv)
4081 int default_path = 0;
4082 int verify_only = 0;
4083 int verbose_verify_only = 0;
4085 while ((c = nextopt("pvV")) != '\0')
4094 verbose_verify_only = 1;
4098 if (default_path + verify_only + verbose_verify_only > 1 ||
4101 "command [-p] command [arg ...]\n"
4102 "command {-v|-V} command\n");
4106 if (verify_only || verbose_verify_only) {
4110 argv_a[0] = *argptr;
4112 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4113 return hashcmd(argc, argv);
4121 path_change(const char *newval, int *bltin)
4123 const char *old, *new;
4129 firstchange = 9999; /* assume no change */
4135 if ((*old == '\0' && *new == ':')
4136 || (*old == ':' && *new == '\0'))
4138 old = new; /* ignore subsequent differences */
4142 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4149 if (builtinloc >= 0 && *bltin < 0)
4154 * Routines to expand arguments to commands. We have to deal with
4155 * backquotes, shell variables, and file metacharacters.
4160 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4161 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4164 * Structure specifying which parts of the string should be searched
4165 * for IFS characters.
4169 struct ifsregion *next; /* next region in list */
4170 int begoff; /* offset of start of region */
4171 int endoff; /* offset of end of region */
4172 int nulonly; /* search for nul bytes only */
4176 static char *expdest; /* output of current string */
4177 static struct nodelist *argbackq; /* list of back quote expressions */
4178 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4179 static struct ifsregion *ifslastp; /* last struct in list */
4180 static struct arglist exparg; /* holds expanded arg list */
4182 static void argstr (char *, int);
4183 static char *exptilde (char *, int);
4184 static void expbackq (union node *, int, int);
4185 static int subevalvar (char *, char *, int, int, int, int, int);
4186 static int varisset (char *, int);
4187 static void strtodest (const char *, int, int);
4188 static inline void varvalue (char *, int, int);
4189 static void recordregion (int, int, int);
4190 static void removerecordregions (int);
4191 static void ifsbreakup (char *, struct arglist *);
4192 static void ifsfree (void);
4193 static void expandmeta (struct strlist *, int);
4194 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4195 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4196 #if !defined(GLOB_BROKEN)
4197 static inline void addglob (const glob_t *);
4200 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4201 static void expmeta (char *, char *);
4203 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4204 static struct strlist *expsort (struct strlist *);
4205 static struct strlist *msort (struct strlist *, int);
4207 static int patmatch (char *, char *, int);
4208 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4209 static int patmatch2 (char *, char *, int);
4211 static int pmatch (char *, char *, int);
4212 #define patmatch2 patmatch
4214 static char *cvtnum (int, char *);
4217 * Expand shell variables and backquotes inside a here document.
4220 /* arg: the document, fd: where to write the expanded version */
4222 expandhere(union node *arg, int fd)
4225 expandarg(arg, (struct arglist *)NULL, 0);
4226 xwrite(fd, stackblock(), expdest - stackblock());
4231 * Perform variable substitution and command substitution on an argument,
4232 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4233 * perform splitting and file name expansion. When arglist is NULL, perform
4234 * here document expansion.
4238 expandarg(union node *arg, struct arglist *arglist, int flag)
4243 argbackq = arg->narg.backquote;
4244 STARTSTACKSTR(expdest);
4245 ifsfirst.next = NULL;
4247 argstr(arg->narg.text, flag);
4248 if (arglist == NULL) {
4249 return; /* here document expanded */
4251 STPUTC('\0', expdest);
4252 p = grabstackstr(expdest);
4253 exparg.lastp = &exparg.list;
4257 if (flag & EXP_FULL) {
4258 ifsbreakup(p, &exparg);
4259 *exparg.lastp = NULL;
4260 exparg.lastp = &exparg.list;
4261 expandmeta(exparg.list, flag);
4263 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4265 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4268 exparg.lastp = &sp->next;
4271 *exparg.lastp = NULL;
4273 *arglist->lastp = exparg.list;
4274 arglist->lastp = exparg.lastp;
4280 * Expand a variable, and return a pointer to the next character in the
4284 static inline char * evalvar(char *p, int flag)
4297 int quotes = flag & (EXP_FULL | EXP_CASE);
4300 subtype = varflags & VSTYPE;
4305 p = strchr(p, '=') + 1;
4306 again: /* jump here after setting a variable with ${var=text} */
4308 set = varisset(var, varflags & VSNUL);
4311 val = lookupvar(var);
4312 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4319 startloc = expdest - stackblock();
4320 if (set && subtype != VSPLUS) {
4321 /* insert the value of the variable */
4323 varvalue(var, varflags & VSQUOTE, flag);
4324 if (subtype == VSLENGTH) {
4325 varlen = expdest - stackblock() - startloc;
4326 STADJUST(-varlen, expdest);
4329 if (subtype == VSLENGTH) {
4330 varlen = strlen(val);
4334 varflags & VSQUOTE ?
4335 DQSYNTAX : BASESYNTAX,
4342 if (subtype == VSPLUS)
4345 easy = ((varflags & VSQUOTE) == 0 ||
4346 (*var == '@' && shellparam.nparam != 1));
4351 expdest = cvtnum(varlen, expdest);
4358 recordregion(startloc, expdest - stackblock(),
4359 varflags & VSQUOTE);
4375 case VSTRIMRIGHTMAX:
4379 * Terminate the string and start recording the pattern
4382 STPUTC('\0', expdest);
4383 patloc = expdest - stackblock();
4384 if (subevalvar(p, NULL, patloc, subtype,
4385 startloc, varflags, quotes) == 0) {
4386 int amount = (expdest - stackblock() - patloc) + 1;
4387 STADJUST(-amount, expdest);
4389 /* Remove any recorded regions beyond start of variable */
4390 removerecordregions(startloc);
4396 if (subevalvar(p, var, 0, subtype, startloc,
4397 varflags, quotes)) {
4400 * Remove any recorded regions beyond
4403 removerecordregions(startloc);
4418 if (subtype != VSNORMAL) { /* skip to end of alternative */
4421 if ((c = *p++) == CTLESC)
4423 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4425 argbackq = argbackq->next;
4426 } else if (c == CTLVAR) {
4427 if ((*p++ & VSTYPE) != VSNORMAL)
4429 } else if (c == CTLENDVAR) {
4440 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4441 * characters to allow for further processing. Otherwise treat
4442 * $@ like $* since no splitting will be performed.
4446 argstr(char *p, int flag)
4449 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4452 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4453 p = exptilde(p, flag);
4457 case CTLENDVAR: /* ??? */
4460 /* "$@" syntax adherence hack */
4461 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4463 if ((flag & EXP_FULL) != 0)
4473 p = evalvar(p, flag);
4476 case CTLBACKQ|CTLQUOTE:
4477 expbackq(argbackq->n, c & CTLQUOTE, flag);
4478 argbackq = argbackq->next;
4480 #ifdef ASH_MATH_SUPPORT
4488 * sort of a hack - expand tildes in variable
4489 * assignments (after the first '=' and after ':'s).
4492 if (flag & EXP_VARTILDE && *p == '~') {
4499 p = exptilde(p, flag);
4510 exptilde(char *p, int flag)
4512 char c, *startp = p;
4515 int quotes = flag & (EXP_FULL | EXP_CASE);
4517 while ((c = *p) != '\0') {
4524 if (flag & EXP_VARTILDE)
4534 if (*(startp+1) == '\0') {
4535 if ((home = lookupvar("HOME")) == NULL)
4538 if ((pw = getpwnam(startp+1)) == NULL)
4545 strtodest(home, SQSYNTAX, quotes);
4554 removerecordregions(int endoff)
4556 if (ifslastp == NULL)
4559 if (ifsfirst.endoff > endoff) {
4560 while (ifsfirst.next != NULL) {
4561 struct ifsregion *ifsp;
4563 ifsp = ifsfirst.next->next;
4564 ckfree(ifsfirst.next);
4565 ifsfirst.next = ifsp;
4568 if (ifsfirst.begoff > endoff)
4571 ifslastp = &ifsfirst;
4572 ifsfirst.endoff = endoff;
4577 ifslastp = &ifsfirst;
4578 while (ifslastp->next && ifslastp->next->begoff < endoff)
4579 ifslastp=ifslastp->next;
4580 while (ifslastp->next != NULL) {
4581 struct ifsregion *ifsp;
4583 ifsp = ifslastp->next->next;
4584 ckfree(ifslastp->next);
4585 ifslastp->next = ifsp;
4588 if (ifslastp->endoff > endoff)
4589 ifslastp->endoff = endoff;
4593 #ifdef ASH_MATH_SUPPORT
4595 * Expand arithmetic expression. Backup to start of expression,
4596 * evaluate, place result in (backed up) result, adjust string position.
4605 int quotes = flag & (EXP_FULL | EXP_CASE);
4611 * This routine is slightly over-complicated for
4612 * efficiency. First we make sure there is
4613 * enough space for the result, which may be bigger
4614 * than the expression if we add exponentation. Next we
4615 * scan backwards looking for the start of arithmetic. If the
4616 * next previous character is a CTLESC character, then we
4617 * have to rescan starting from the beginning since CTLESC
4618 * characters have to be processed left to right.
4620 CHECKSTRSPACE(10, expdest);
4621 USTPUTC('\0', expdest);
4622 start = stackblock();
4624 while (*p != CTLARI && p >= start)
4627 error("missing CTLARI (shouldn't happen)");
4628 if (p > start && *(p-1) == CTLESC)
4629 for (p = start; *p != CTLARI; p++)
4638 removerecordregions(begoff);
4641 result = arith(p+2, &errcode);
4644 error("divide by zero");
4646 error("syntax error: \"%s\"\n", p+2);
4648 snprintf(p, 12, "%d", result);
4654 recordregion(begoff, p - 1 - start, 0);
4655 result = expdest - p + 1;
4656 STADJUST(-result, expdest);
4661 * Expand stuff in backwards quotes.
4665 expbackq(union node *cmd, int quoted, int flag)
4667 volatile struct backcmd in;
4671 char *dest = expdest;
4672 volatile struct ifsregion saveifs;
4673 struct ifsregion *volatile savelastp;
4674 struct nodelist *volatile saveargbackq;
4676 int startloc = dest - stackblock();
4677 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4678 volatile int saveherefd;
4679 int quotes = flag & (EXP_FULL | EXP_CASE);
4680 struct jmploc jmploc;
4681 struct jmploc *volatile savehandler;
4685 /* Avoid longjmp clobbering */
4696 savelastp = ifslastp;
4697 saveargbackq = argbackq;
4698 saveherefd = herefd;
4700 if ((ex = setjmp(jmploc.loc))) {
4703 savehandler = handler;
4706 p = grabstackstr(dest);
4707 evalbackcmd(cmd, (struct backcmd *) &in);
4708 ungrabstackstr(p, dest);
4712 ifslastp = savelastp;
4713 argbackq = saveargbackq;
4714 herefd = saveherefd;
4722 if (--in.nleft < 0) {
4725 i = safe_read(in.fd, buf, sizeof buf);
4726 TRACE(("expbackq: read returns %d\n", i));
4733 if (lastc != '\0') {
4734 if (quotes && SIT(lastc, syntax) == CCTL)
4735 STPUTC(CTLESC, dest);
4736 STPUTC(lastc, dest);
4740 /* Eat all trailing newlines */
4741 for (; dest > stackblock() && dest[-1] == '\n';)
4750 exitstatus = waitforjob(in.jp);
4751 handler = savehandler;
4753 longjmp(handler->loc, 1);
4756 recordregion(startloc, dest - stackblock(), 0);
4757 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4758 (dest - stackblock()) - startloc,
4759 (dest - stackblock()) - startloc,
4760 stackblock() + startloc));
4766 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
4772 int saveherefd = herefd;
4773 struct nodelist *saveargbackq = argbackq;
4777 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4778 STACKSTRNUL(expdest);
4779 herefd = saveherefd;
4780 argbackq = saveargbackq;
4781 startp = stackblock() + startloc;
4783 str = stackblock() + strloc;
4787 setvar(str, startp, 0);
4788 amount = startp - expdest;
4789 STADJUST(amount, expdest);
4796 if (*p != CTLENDVAR) {
4797 out2fmt(snlfmt, startp);
4798 error((char *)NULL);
4800 error("%.*s: parameter %snot set", p - str - 1,
4801 str, (varflags & VSNUL) ? "null or "
4806 for (loc = startp; loc < str; loc++) {
4809 if (patmatch2(str, startp, quotes))
4812 if (quotes && *loc == CTLESC)
4818 for (loc = str - 1; loc >= startp;) {
4821 if (patmatch2(str, startp, quotes))
4825 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4826 for (q = startp; q < loc; q++)
4836 for (loc = str - 1; loc >= startp;) {
4837 if (patmatch2(str, loc, quotes))
4840 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4841 for (q = startp; q < loc; q++)
4850 case VSTRIMRIGHTMAX:
4851 for (loc = startp; loc < str - 1; loc++) {
4852 if (patmatch2(str, loc, quotes))
4854 if (quotes && *loc == CTLESC)
4867 amount = ((str - 1) - (loc - startp)) - expdest;
4868 STADJUST(amount, expdest);
4869 while (loc != str - 1)
4874 amount = loc - expdest;
4875 STADJUST(amount, expdest);
4876 STPUTC('\0', expdest);
4877 STADJUST(-1, expdest);
4883 * Test whether a specialized variable is set.
4887 varisset(char *name, int nulok)
4890 return backgndpid != -1;
4891 else if (*name == '@' || *name == '*') {
4892 if (*shellparam.p == NULL)
4898 for (av = shellparam.p; *av; av++)
4903 } else if (is_digit(*name)) {
4905 int num = atoi(name);
4907 if (num > shellparam.nparam)
4913 ap = shellparam.p[num - 1];
4915 if (nulok && (ap == NULL || *ap == '\0'))
4922 * Put a string on the stack.
4926 strtodest(const char *p, int syntax, int quotes)
4929 if (quotes && SIT(*p,syntax) == CCTL)
4930 STPUTC(CTLESC, expdest);
4931 STPUTC(*p++, expdest);
4936 * Add the value of a specialized variable to the stack string.
4940 varvalue(char *name, int quoted, int flags)
4949 int allow_split = flags & EXP_FULL;
4950 int quotes = flags & (EXP_FULL | EXP_CASE);
4952 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4961 num = shellparam.nparam;
4966 expdest = cvtnum(num, expdest);
4969 for (i = 0 ; i < NOPTS ; i++) {
4971 STPUTC(optent_letter(optlist[i]), expdest);
4975 if (allow_split && quoted) {
4976 sep = 1 << CHAR_BIT;
4981 sep = ifsset() ? ifsval()[0] : ' ';
4983 sepq = SIT(sep,syntax) == CCTL;
4986 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
4987 strtodest(p, syntax, quotes);
4990 STPUTC(CTLESC, expdest);
4991 STPUTC(sep, expdest);
4996 strtodest(arg0, syntax, quotes);
5000 if (num > 0 && num <= shellparam.nparam) {
5001 strtodest(shellparam.p[num - 1], syntax, quotes);
5009 * Record the fact that we have to scan this region of the
5010 * string for IFS characters.
5014 recordregion(int start, int end, int nulonly)
5016 struct ifsregion *ifsp;
5018 if (ifslastp == NULL) {
5022 ifsp = (struct ifsregion *)xmalloc(sizeof (struct ifsregion));
5024 ifslastp->next = ifsp;
5028 ifslastp->begoff = start;
5029 ifslastp->endoff = end;
5030 ifslastp->nulonly = nulonly;
5036 * Break the argument string into pieces based upon IFS and add the
5037 * strings to the argument list. The regions of the string to be
5038 * searched for IFS characters have been stored by recordregion.
5041 ifsbreakup(char *string, struct arglist *arglist)
5043 struct ifsregion *ifsp;
5048 const char *ifs, *realifs;
5056 realifs = ifsset() ? ifsval() : defifs;
5057 if (ifslastp != NULL) {
5060 p = string + ifsp->begoff;
5061 nulonly = ifsp->nulonly;
5062 ifs = nulonly ? nullstr : realifs;
5064 while (p < string + ifsp->endoff) {
5068 if (strchr(ifs, *p)) {
5070 ifsspc = (strchr(defifs, *p) != NULL);
5071 /* Ignore IFS whitespace at start */
5072 if (q == start && ifsspc) {
5078 sp = (struct strlist *)stalloc(sizeof *sp);
5080 *arglist->lastp = sp;
5081 arglist->lastp = &sp->next;
5085 if (p >= string + ifsp->endoff) {
5091 if (strchr(ifs, *p) == NULL ) {
5094 } else if (strchr(defifs, *p) == NULL) {
5110 } while ((ifsp = ifsp->next) != NULL);
5111 if (!(*start || (!ifsspc && start > string && nulonly))) {
5116 sp = (struct strlist *)stalloc(sizeof *sp);
5118 *arglist->lastp = sp;
5119 arglist->lastp = &sp->next;
5125 while (ifsfirst.next != NULL) {
5126 struct ifsregion *ifsp;
5128 ifsp = ifsfirst.next->next;
5129 ckfree(ifsfirst.next);
5130 ifsfirst.next = ifsp;
5134 ifsfirst.next = NULL;
5138 * Add a file name to the list.
5142 addfname(const char *name)
5148 sp = (struct strlist *)stalloc(sizeof *sp);
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);
6310 status = waitforjob(jp);
6317 bgcmd(int argc, char **argv)
6322 jp = getjob(*++argv);
6323 if (jp->jobctl == 0)
6324 error("job not created under job control");
6326 } while (--argc > 1);
6332 restartjob(struct job *jp)
6334 struct procstat *ps;
6337 if (jp->state == JOBDONE)
6340 killpg(jp->ps[0].pid, SIGCONT);
6341 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6342 if (WIFSTOPPED(ps->status)) {
6351 static void showjobs(int change);
6355 jobscmd(int argc, char **argv)
6363 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6364 * statuses have changed since the last call to showjobs.
6366 * If the shell is interrupted in the process of creating a job, the
6367 * result may be a job structure containing zero processes. Such structures
6368 * will be freed here.
6372 showjobs(int change)
6378 struct procstat *ps;
6382 TRACE(("showjobs(%d) called\n", change));
6383 while (dowait(0, (struct job *)NULL) > 0);
6384 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6387 if (jp->nprocs == 0) {
6391 if (change && ! jp->changed)
6393 procno = jp->nprocs;
6394 for (ps = jp->ps ; ; ps++) { /* for each process */
6396 snprintf(s, 64, "[%d] %ld ", jobno,
6399 snprintf(s, 64, " %ld ",
6404 if (ps->status == -1) {
6405 /* don't print anything */
6406 } else if (WIFEXITED(ps->status)) {
6407 snprintf(s, 64, "Exit %d",
6408 WEXITSTATUS(ps->status));
6411 if (WIFSTOPPED(ps->status))
6412 i = WSTOPSIG(ps->status);
6413 else /* WIFSIGNALED(ps->status) */
6415 i = WTERMSIG(ps->status);
6416 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6417 strcpy(s, sys_siglist[i & 0x7F]);
6419 snprintf(s, 64, "Signal %d", i & 0x7F);
6420 if (WCOREDUMP(ps->status))
6421 strcat(s, " (core dumped)");
6426 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6433 if (jp->state == JOBDONE) {
6441 * Mark a job structure as unused.
6445 freejob(struct job *jp)
6447 const struct procstat *ps;
6451 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6452 if (ps->cmd != nullstr)
6455 if (jp->ps != &jp->ps0)
6459 if (curjob == jp - jobtab + 1)
6468 waitcmd(int argc, char **argv)
6476 job = getjob(*++argv);
6480 for (;;) { /* loop until process terminated or stopped */
6483 status = job->ps[job->nprocs - 1].status;
6489 if (WIFEXITED(status))
6490 retval = WEXITSTATUS(status);
6492 else if (WIFSTOPPED(status))
6493 retval = WSTOPSIG(status) + 128;
6496 /* XXX: limits number of signals */
6497 retval = WTERMSIG(status) + 128;
6502 for (jp = jobtab ; ; jp++) {
6503 if (jp >= jobtab + njobs) { /* no running procs */
6506 if (jp->used && jp->state == 0)
6510 if (dowait(2, 0) < 0 && errno == EINTR) {
6519 * Convert a job name to a job structure.
6523 getjob(const char *name)
6533 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6534 error("No current job");
6535 return &jobtab[jobno - 1];
6537 error("No current job");
6539 } else if (name[0] == '%') {
6540 if (is_digit(name[1])) {
6541 jobno = number(name + 1);
6542 if (jobno > 0 && jobno <= njobs
6543 && jobtab[jobno - 1].used != 0)
6544 return &jobtab[jobno - 1];
6546 } else if (name[1] == '%' && name[2] == '\0') {
6550 struct job *found = NULL;
6551 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6552 if (jp->used && jp->nprocs > 0
6553 && prefix(name + 1, jp->ps[0].cmd)) {
6555 error("%s: ambiguous", name);
6562 } else if (is_number(name, &pid)) {
6563 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6564 if (jp->used && jp->nprocs > 0
6565 && jp->ps[jp->nprocs - 1].pid == pid)
6569 error("No such job: %s", name);
6576 * Return a new job structure,
6580 makejob(const union node *node, int nprocs)
6585 for (i = njobs, jp = jobtab ; ; jp++) {
6589 jobtab = xmalloc(4 * sizeof jobtab[0]);
6591 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6592 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6593 /* Relocate `ps' pointers */
6594 for (i = 0; i < njobs; i++)
6595 if (jp[i].ps == &jobtab[i].ps0)
6596 jp[i].ps = &jp[i].ps0;
6600 jp = jobtab + njobs;
6601 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6614 jp->jobctl = jobctl;
6617 jp->ps = xmalloc(nprocs * sizeof (struct procstat));
6622 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6629 * Fork of a subshell. If we are doing job control, give the subshell its
6630 * own process group. Jp is a job structure that the job is to be added to.
6631 * N is the command that will be evaluated by the child. Both jp and n may
6632 * be NULL. The mode parameter can be one of the following:
6633 * FORK_FG - Fork off a foreground process.
6634 * FORK_BG - Fork off a background process.
6635 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6636 * process group even if job control is on.
6638 * When job control is turned off, background processes have their standard
6639 * input redirected to /dev/null (except for the second and later processes
6646 forkshell(struct job *jp, const union node *n, int mode)
6652 const char *devnull = _PATH_DEVNULL;
6653 const char *nullerr = "Can't open %s";
6655 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6658 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6664 TRACE(("Fork failed, errno=%d\n", errno));
6666 error("Cannot fork");
6673 TRACE(("Child shell %d\n", getpid()));
6674 wasroot = rootshell;
6680 jobctl = 0; /* do job control only in root shell */
6681 if (wasroot && mode != FORK_NOJOB && mflag) {
6682 if (jp == NULL || jp->nprocs == 0)
6685 pgrp = jp->ps[0].pid;
6687 if (mode == FORK_FG) {
6688 /*** this causes superfluous TIOCSPGRPS ***/
6689 #ifdef OLD_TTY_DRIVER
6690 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6691 error("TIOCSPGRP failed, errno=%d", errno);
6693 if (tcsetpgrp(2, pgrp) < 0)
6694 error("tcsetpgrp failed, errno=%d", errno);
6699 } else if (mode == FORK_BG) {
6702 if ((jp == NULL || jp->nprocs == 0) &&
6703 ! fd0_redirected_p ()) {
6705 if (open(devnull, O_RDONLY) != 0)
6706 error(nullerr, devnull);
6710 if (mode == FORK_BG) {
6713 if ((jp == NULL || jp->nprocs == 0) &&
6714 ! fd0_redirected_p ()) {
6716 if (open(devnull, O_RDONLY) != 0)
6717 error(nullerr, devnull);
6721 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6724 if (wasroot && iflag) {
6732 if (rootshell && mode != FORK_NOJOB && mflag) {
6733 if (jp == NULL || jp->nprocs == 0)
6736 pgrp = jp->ps[0].pid;
6740 if (mode == FORK_BG)
6741 backgndpid = pid; /* set $! */
6743 struct procstat *ps = &jp->ps[jp->nprocs++];
6747 if (iflag && rootshell && n)
6748 ps->cmd = commandtext(n);
6751 TRACE(("In parent shell: child = %d\n", pid));
6758 * Wait for job to finish.
6760 * Under job control we have the problem that while a child process is
6761 * running interrupts generated by the user are sent to the child but not
6762 * to the shell. This means that an infinite loop started by an inter-
6763 * active user may be hard to kill. With job control turned off, an
6764 * interactive user may place an interactive program inside a loop. If
6765 * the interactive program catches interrupts, the user doesn't want
6766 * these interrupts to also abort the loop. The approach we take here
6767 * is to have the shell ignore interrupt signals while waiting for a
6768 * forground process to terminate, and then send itself an interrupt
6769 * signal if the child process was terminated by an interrupt signal.
6770 * Unfortunately, some programs want to do a bit of cleanup and then
6771 * exit on interrupt; unless these processes terminate themselves by
6772 * sending a signal to themselves (instead of calling exit) they will
6773 * confuse this approach.
6777 waitforjob(struct job *jp)
6780 int mypgrp = getpgrp();
6784 struct sigaction act, oact;
6793 sigaction(SIGINT, 0, &act);
6794 act.sa_handler = waitonint;
6795 sigaction(SIGINT, &act, &oact);
6797 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6798 while (jp->state == 0) {
6806 sigaction(SIGINT, &oact, 0);
6807 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6811 #ifdef OLD_TTY_DRIVER
6812 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6813 error("TIOCSPGRP failed, errno=%d\n", errno);
6815 if (tcsetpgrp(2, mypgrp) < 0)
6816 error("tcsetpgrp failed, errno=%d\n", errno);
6819 if (jp->state == JOBSTOPPED)
6820 curjob = jp - jobtab + 1;
6822 status = jp->ps[jp->nprocs - 1].status;
6823 /* convert to 8 bits */
6824 if (WIFEXITED(status))
6825 st = WEXITSTATUS(status);
6827 else if (WIFSTOPPED(status))
6828 st = WSTOPSIG(status) + 128;
6831 st = WTERMSIG(status) + 128;
6835 * This is truly gross.
6836 * If we're doing job control, then we did a TIOCSPGRP which
6837 * caused us (the shell) to no longer be in the controlling
6838 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6839 * intuit from the subprocess exit status whether a SIGINT
6840 * occured, and if so interrupt ourselves. Yuck. - mycroft
6842 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6845 if (jp->state == JOBDONE)
6856 * Wait for a process to terminate.
6860 * Do a wait system call. If job control is compiled in, we accept
6861 * stopped processes. If block is zero, we return a value of zero
6862 * rather than blocking.
6864 * System V doesn't have a non-blocking wait system call. It does
6865 * have a SIGCLD signal that is sent to a process when one of it's
6866 * children dies. The obvious way to use SIGCLD would be to install
6867 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6868 * was received, and have waitproc bump another counter when it got
6869 * the status of a process. Waitproc would then know that a wait
6870 * system call would not block if the two counters were different.
6871 * This approach doesn't work because if a process has children that
6872 * have not been waited for, System V will send it a SIGCLD when it
6873 * installs a signal handler for SIGCLD. What this means is that when
6874 * a child exits, the shell will be sent SIGCLD signals continuously
6875 * until is runs out of stack space, unless it does a wait call before
6876 * restoring the signal handler. The code below takes advantage of
6877 * this (mis)feature by installing a signal handler for SIGCLD and
6878 * then checking to see whether it was called. If there are any
6879 * children to be waited for, it will be.
6884 waitproc(int block, int *status)
6895 return wait3(status, flags, (struct rusage *)NULL);
6899 dowait(int block, struct job *job)
6903 struct procstat *sp;
6905 struct job *thisjob;
6911 TRACE(("dowait(%d) called\n", block));
6913 pid = waitproc(block, &status);
6914 TRACE(("wait returns %d, status=%d\n", pid, status));
6915 } while (!(block & 2) && pid == -1 && errno == EINTR);
6920 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
6924 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
6927 if (sp->pid == pid) {
6928 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
6929 sp->status = status;
6932 if (sp->status == -1)
6934 else if (WIFSTOPPED(sp->status))
6937 if (stopped) { /* stopped or done */
6938 int state = done? JOBDONE : JOBSTOPPED;
6939 if (jp->state != state) {
6940 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
6943 if (done && curjob == jp - jobtab + 1)
6944 curjob = 0; /* no current job */
6951 if (! rootshell || ! iflag || (job && thisjob == job)) {
6952 core = WCOREDUMP(status);
6954 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
6957 if (WIFEXITED(status)) sig = 0;
6958 else sig = WTERMSIG(status);
6960 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6962 out2fmt("%d: ", pid);
6964 if (sig == SIGTSTP && rootshell && iflag)
6966 (long)(job - jobtab + 1));
6968 if (sig < NSIG && sys_siglist[sig])
6969 out2str(sys_siglist[sig]);
6971 out2fmt("Signal %d", sig);
6973 out2str(" - core dumped");
6976 TRACE(("Not printing status: status=%d, sig=%d\n",
6980 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
6982 thisjob->changed = 1;
6991 * return 1 if there are stopped jobs, otherwise 0
7001 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
7004 if (jp->state == JOBSTOPPED) {
7005 out2str("You have stopped jobs.\n");
7015 * Return a string identifying a command (to be printed by the
7019 static char *cmdnextc;
7020 static int cmdnleft;
7021 #define MAXCMDTEXT 200
7024 cmdputs(const char *s)
7035 while ((c = *p++) != '\0') {
7038 else if (c == CTLVAR) {
7043 } else if (c == '=' && subtype != 0) {
7044 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7046 } else if (c == CTLENDVAR) {
7048 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7049 cmdnleft++; /* ignore it */
7052 if (--cmdnleft <= 0) {
7062 #define CMDTXT_TABLE
7065 * To collect a lot of redundant code in cmdtxt() case statements, we
7066 * implement a mini language here. Each type of node struct has an
7067 * associated instruction sequence that operates on its members via
7068 * their offsets. The instruction are pack in unsigned chars with
7069 * format IIDDDDDE where the bits are
7070 * I : part of the instruction opcode, which are
7071 * 00 : member is a pointer to another node -- process it recursively
7072 * 40 : member is a pointer to a char string -- output it
7073 * 80 : output the string whose index is stored in the data field
7074 * CC : flag signaling that this case needs external processing
7075 * D : data - either the (shifted) index of a fixed string to output or
7076 * the actual offset of the member to operate on in the struct
7077 * (since we assume bit 0 is set, the offset is not shifted)
7078 * E : flag signaling end of instruction sequence
7080 * WARNING: In order to handle larger offsets for 64bit archs, this code
7081 * assumes that no offset can be an odd number and stores the
7082 * end-of-instructions flag in bit 0.
7085 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7086 #define CMDTXT_CHARPTR 0x40
7087 #define CMDTXT_STRING 0x80
7088 #define CMDTXT_SPECIAL 0xC0
7089 #define CMDTXT_OFFSETMASK 0x3E
7091 static const char * const cmdtxt_strings[] = {
7092 /* 0 1 2 3 4 5 6 7 */
7093 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7094 /* 8 9 10 11 12 13 */
7095 "while ", "; do ", "; done", "until ", "for ", " in ...",
7097 "case ", "???", "() ...", "<<..."
7100 static const char * const redir_strings[] = {
7101 ">", "<", "<>", ">>", ">|", ">&", "<&"
7104 static const unsigned char cmdtxt_ops[] = {
7105 #define CMDTXT_NSEMI 0
7106 offsetof(union node, nbinary.ch1),
7108 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7109 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7110 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7111 #define CMDTXT_NCASE (CMDTXT_NCMD)
7112 #define CMDTXT_NTO (CMDTXT_NCMD)
7113 #define CMDTXT_NFROM (CMDTXT_NCMD)
7114 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7115 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7116 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7117 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7118 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7120 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7121 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7122 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7123 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7124 (1*2)|CMDTXT_STRING,
7125 offsetof(union node, nredir.n),
7126 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7127 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7128 offsetof(union node, nbinary.ch1),
7129 (3*2)|CMDTXT_STRING,
7130 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7131 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7132 offsetof(union node, nbinary.ch1),
7133 (4*2)|CMDTXT_STRING,
7134 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7135 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7136 (5*2)|CMDTXT_STRING,
7137 offsetof(union node, nif.test),
7138 (6*2)|CMDTXT_STRING,
7139 offsetof(union node, nif.ifpart),
7140 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7141 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7142 (8*2)|CMDTXT_STRING,
7143 offsetof(union node, nbinary.ch1),
7144 (9*2)|CMDTXT_STRING,
7145 offsetof(union node, nbinary.ch2),
7146 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7147 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7148 (11*2)|CMDTXT_STRING,
7149 offsetof(union node, nbinary.ch1),
7150 (9*2)|CMDTXT_STRING,
7151 offsetof(union node, nbinary.ch2),
7152 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7153 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7154 (12*2)|CMDTXT_STRING,
7155 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7156 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7157 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7158 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7159 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7160 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7161 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7162 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7163 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7164 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7165 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7166 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7167 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7170 #if CMDTXT_NXHERE != 36
7171 #error CMDTXT_NXHERE
7174 static const unsigned char cmdtxt_ops_index[26] = {
7204 cmdtxt(const union node *n)
7211 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7212 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7214 if (*p & CMDTXT_STRING) { /* output fixed string */
7215 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7217 const char *pf = ((const char *) n)
7218 + ((int)(*p & CMDTXT_OFFSETMASK));
7219 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7220 cmdputs(*((const char **) pf));
7221 } else { /* output field */
7222 cmdtxt(*((const union node **) pf));
7225 } while (!(*p++ & CMDTXT_NOMORE));
7226 } else if (n->type == NCMD) {
7228 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7233 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7237 } else if (n->type == NPIPE) {
7238 struct nodelist *lp;
7239 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7244 } else if (n->type == NCASE) {
7245 cmdputs(cmdtxt_strings[14]);
7246 cmdputs(n->ncase.expr->narg.text);
7247 cmdputs(cmdtxt_strings[13]);
7249 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7250 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7255 assert((n->type >= NTO) && (n->type <= NFROMFD));
7258 p = redir_strings[n->type - NTO];
7259 if (n->nfile.fd != ('>' == *p)) {
7260 s[0] = n->nfile.fd + '0';
7265 if (n->type >= NTOFD) {
7266 s[0] = n->ndup.dupfd + '0';
7270 cmdtxt(n->nfile.fname);
7274 #else /* CMDTXT_TABLE */
7276 cmdtxt(const union node *n)
7279 struct nodelist *lp;
7288 cmdtxt(n->nbinary.ch1);
7290 cmdtxt(n->nbinary.ch2);
7293 cmdtxt(n->nbinary.ch1);
7295 cmdtxt(n->nbinary.ch2);
7298 cmdtxt(n->nbinary.ch1);
7300 cmdtxt(n->nbinary.ch2);
7303 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7311 cmdtxt(n->nredir.n);
7316 cmdtxt(n->nredir.n);
7320 cmdtxt(n->nif.test);
7322 cmdtxt(n->nif.ifpart);
7331 cmdtxt(n->nbinary.ch1);
7333 cmdtxt(n->nbinary.ch2);
7338 cmdputs(n->nfor.var);
7343 cmdputs(n->ncase.expr->narg.text);
7347 cmdputs(n->narg.text);
7351 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7356 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7362 cmdputs(n->narg.text);
7365 p = ">"; i = 1; goto redir;
7367 p = ">>"; i = 1; goto redir;
7369 p = ">&"; i = 1; goto redir;
7371 p = ">|"; i = 1; goto redir;
7373 p = "<"; i = 0; goto redir;
7375 p = "<&"; i = 0; goto redir;
7377 p = "<>"; i = 0; goto redir;
7379 if (n->nfile.fd != i) {
7380 s[0] = n->nfile.fd + '0';
7385 if (n->type == NTOFD || n->type == NFROMFD) {
7386 s[0] = n->ndup.dupfd + '0';
7390 cmdtxt(n->nfile.fname);
7402 #endif /* CMDTXT_TABLE */
7405 commandtext(const union node *n)
7409 cmdnextc = name = xmalloc(MAXCMDTEXT);
7410 cmdnleft = MAXCMDTEXT - 4;
7417 static void waitonint(int sig) {
7425 * Routines to check for mail.
7429 #define MAXMBOXES 10
7432 static int nmboxes; /* number of mailboxes */
7433 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7438 * Print appropriate message(s) if mail has arrived. If the argument is
7439 * nozero, then the value of MAIL has changed, so we just update the
7450 struct stackmark smark;
7457 setstackmark(&smark);
7458 mpath = mpathset()? mpathval() : mailval();
7459 for (i = 0 ; i < nmboxes ; i++) {
7460 p = padvance(&mpath, nullstr);
7465 for (q = p ; *q ; q++);
7470 q[-1] = '\0'; /* delete trailing '/' */
7471 if (stat(p, &statb) < 0)
7473 if (statb.st_size > mailtime[i] && ! silent) {
7475 pathopt? pathopt : "you have mail");
7477 mailtime[i] = statb.st_size;
7480 popstackmark(&smark);
7483 #endif /* ASH_MAIL */
7488 static short profile_buf[16384];
7492 static void read_profile (const char *);
7493 static void cmdloop (int);
7494 static void options (int);
7495 static void setoption (int, int);
7496 static void procargs (int, char **);
7500 * Main routine. We initialize things, parse the arguments, execute
7501 * profiles if we're a login shell, and then call cmdloop to execute
7502 * commands. The setjmp call sets up the location to jump to when an
7503 * exception occurs. When an exception occurs the variable "state"
7504 * is used to figure out how far we had gotten.
7508 ash_main(int argc, char **argv)
7510 struct jmploc jmploc;
7511 struct stackmark smark;
7515 BLTINCMD = find_builtin("builtin");
7516 EXECCMD = find_builtin("exec");
7517 EVALCMD = find_builtin("eval");
7519 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7525 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7527 #if defined(linux) || defined(__GNU__)
7528 signal(SIGCHLD, SIG_DFL);
7531 if (setjmp(jmploc.loc)) {
7534 * When a shell procedure is executed, we raise the
7535 * exception EXSHELLPROC to clean up before executing
7536 * the shell procedure.
7538 if (exception == EXSHELLPROC) {
7544 if (exception == EXEXEC) {
7545 exitstatus = exerrno;
7546 } else if (exception == EXERROR) {
7549 if (state == 0 || iflag == 0 || ! rootshell)
7550 exitshell(exitstatus);
7553 if (exception == EXINT) {
7556 popstackmark(&smark);
7557 FORCEINTON; /* enable interrupts */
7560 else if (state == 2)
7562 else if (state == 3)
7570 trputs("Shell args: "); trargs(argv);
7575 setstackmark(&smark);
7576 procargs(argc, argv);
7577 if (argv[0] && argv[0][0] == '-') {
7579 read_profile("/etc/profile");
7582 read_profile(".profile");
7587 if (getuid() == geteuid() && getgid() == getegid()) {
7589 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7591 read_profile(shinit);
7598 if (sflag == 0 || minusc) {
7599 static const char sigs[] = {
7600 SIGINT, SIGQUIT, SIGHUP,
7606 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7609 for (i = 0; i < SIGSSIZE; i++)
7614 evalstring(minusc, 0);
7616 if (sflag || minusc == NULL) {
7617 state4: /* XXX ??? - why isn't this before the "if" statement */
7623 exitshell(exitstatus);
7629 * Read and execute commands. "Top" is nonzero for the top level command
7630 * loop; it turns on prompting if the shell is interactive.
7637 struct stackmark smark;
7641 TRACE(("cmdloop(%d) called\n", top));
7642 setstackmark(&smark);
7655 n = parsecmd(inter);
7656 /* showtree(n); DEBUG */
7658 if (!top || numeof >= 50)
7660 if (!stoppedjobs()) {
7663 out2str("\nUse \"exit\" to leave shell.\n");
7666 } else if (n != NULL && nflag == 0) {
7667 job_warning = (job_warning == 2) ? 1 : 0;
7671 popstackmark(&smark);
7672 setstackmark(&smark);
7673 if (evalskip == SKIPFILE) {
7678 popstackmark(&smark);
7684 * Read /etc/profile or .profile. Return on error.
7688 read_profile(const char *name)
7695 if ((fd = open(name, O_RDONLY)) >= 0)
7700 /* -q turns off -x and -v just when executing init files */
7701 /* Note: Might do a little redundant work, but reduces code size. */
7716 * Read a file containing shell functions.
7720 readcmdfile(const char *name)
7725 if ((fd = open(name, O_RDONLY)) >= 0)
7728 error("Can't open %s", name);
7737 * Take commands from a file. To be compatable we should do a path
7738 * search for the file, which is necessary to find sub-commands.
7741 static inline char *
7742 find_dot_file(char *mybasename)
7745 const char *path = pathval();
7748 /* don't try this for absolute or relative paths */
7749 if (strchr(mybasename, '/'))
7752 while ((fullname = padvance(&path, mybasename)) != NULL) {
7753 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7755 * Don't bother freeing here, since it will
7756 * be freed by the caller.
7760 stunalloc(fullname);
7763 /* not found in the PATH */
7764 error("%s: not found", mybasename);
7769 dotcmd(int argc, char **argv)
7772 volatile struct shparam saveparam;
7775 for (sp = cmdenviron; sp ; sp = sp->next)
7776 setvareq(xstrdup(sp->text), VSTRFIXED|VTEXTFIXED);
7778 if (argc >= 2) { /* That's what SVR2 does */
7780 struct stackmark smark;
7782 setstackmark(&smark);
7783 fullname = find_dot_file(argv[1]);
7786 saveparam = shellparam;
7787 shellparam.malloc = 0;
7788 shellparam.nparam = argc - 2;
7789 shellparam.p = argv + 2;
7792 setinputfile(fullname, 1);
7793 commandname = fullname;
7798 freeparam(&shellparam);
7799 shellparam = saveparam;
7802 popstackmark(&smark);
7809 exitcmd(int argc, char **argv)
7814 exitstatus = number(argv[1]);
7816 exitstatus = oexitstatus;
7817 exitshell(exitstatus);
7826 nbytes = ALIGN(nbytes);
7827 if (nbytes > stacknleft) {
7829 struct stack_block *sp;
7832 if (blocksize < MINSIZE)
7833 blocksize = MINSIZE;
7835 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7837 stacknxt = sp->space;
7838 stacknleft = blocksize;
7844 stacknleft -= nbytes;
7850 stunalloc(pointer p)
7853 if (p == NULL) { /*DEBUG */
7854 write(2, "stunalloc\n", 10);
7858 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7861 stacknleft += stacknxt - (char *)p;
7867 setstackmark(struct stackmark *mark)
7869 mark->stackp = stackp;
7870 mark->stacknxt = stacknxt;
7871 mark->stacknleft = stacknleft;
7872 mark->marknext = markp;
7878 popstackmark(struct stackmark *mark)
7880 struct stack_block *sp;
7883 markp = mark->marknext;
7884 while (stackp != mark->stackp) {
7889 stacknxt = mark->stacknxt;
7890 stacknleft = mark->stacknleft;
7896 * When the parser reads in a string, it wants to stick the string on the
7897 * stack and only adjust the stack pointer when it knows how big the
7898 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7899 * of space on top of the stack and stackblocklen returns the length of
7900 * this block. Growstackblock will grow this space by at least one byte,
7901 * possibly moving it (like realloc). Grabstackblock actually allocates the
7902 * part of the block that has been used.
7906 growstackblock(void) {
7908 int newlen = ALIGN(stacknleft * 2 + 100);
7909 char *oldspace = stacknxt;
7910 int oldlen = stacknleft;
7911 struct stack_block *sp;
7912 struct stack_block *oldstackp;
7914 if (stacknxt == stackp->space && stackp != &stackbase) {
7919 sp = xrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
7922 stacknxt = sp->space;
7923 stacknleft = newlen;
7925 /* Stack marks pointing to the start of the old block
7926 * must be relocated to point to the new block
7928 struct stackmark *xmark;
7930 while (xmark != NULL && xmark->stackp == oldstackp) {
7931 xmark->stackp = stackp;
7932 xmark->stacknxt = stacknxt;
7933 xmark->stacknleft = stacknleft;
7934 xmark = xmark->marknext;
7939 p = stalloc(newlen);
7940 memcpy(p, oldspace, oldlen);
7941 stacknxt = p; /* free the space */
7942 stacknleft += newlen; /* we just allocated */
7949 grabstackblock(int len)
7959 * The following routines are somewhat easier to use that the above.
7960 * The user declares a variable of type STACKSTR, which may be declared
7961 * to be a register. The macro STARTSTACKSTR initializes things. Then
7962 * the user uses the macro STPUTC to add characters to the string. In
7963 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7964 * grown as necessary. When the user is done, she can just leave the
7965 * string there and refer to it using stackblock(). Or she can allocate
7966 * the space for it using grabstackstr(). If it is necessary to allow
7967 * someone else to use the stack temporarily and then continue to grow
7968 * the string, the user should use grabstack to allocate the space, and
7969 * then call ungrabstr(p) to return to the previous mode of operation.
7971 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7972 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7973 * is space for at least one character.
7978 growstackstr(void) {
7979 int len = stackblocksize();
7980 if (herefd >= 0 && len >= 1024) {
7981 xwrite(herefd, stackblock(), len);
7982 sstrnleft = len - 1;
7983 return stackblock();
7986 sstrnleft = stackblocksize() - len - 1;
7987 return stackblock() + len;
7992 * Called from CHECKSTRSPACE.
7996 makestrspace(size_t newlen) {
7997 int len = stackblocksize() - sstrnleft;
8000 sstrnleft = stackblocksize() - len;
8001 } while (sstrnleft < newlen);
8002 return stackblock() + len;
8008 ungrabstackstr(char *s, char *p)
8010 stacknleft += stacknxt - s;
8012 sstrnleft = stacknleft - (p - s);
8015 * Miscelaneous builtins.
8021 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8022 typedef long rlim_t;
8028 * The read builtin. The -e option causes backslashes to escape the
8029 * following character.
8031 * This uses unbuffered input, which may be avoidable in some cases.
8035 readcmd(int argc, char **argv)
8050 while ((i = nextopt("p:r")) != '\0') {
8056 if (prompt && isatty(0)) {
8057 out2str(prompt); /* read without cmdedit */
8060 if (*(ap = argptr) == NULL)
8062 if ((ifs = bltinlookup("IFS")) == NULL)
8069 if (read(0, &c, 1) != 1) {
8081 if (!rflag && c == '\\') {
8087 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8091 if (backslash && c == '\\') {
8092 if (read(0, &c, 1) != 1) {
8097 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8099 setvar(*ap, stackblock(), 0);
8108 /* Remove trailing blanks */
8109 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8111 setvar(*ap, stackblock(), 0);
8112 while (*++ap != NULL)
8113 setvar(*ap, nullstr, 0);
8120 umaskcmd(int argc, char **argv)
8122 static const char permuser[3] = "ugo";
8123 static const char permmode[3] = "rwx";
8124 static const short int permmask[] = {
8125 S_IRUSR, S_IWUSR, S_IXUSR,
8126 S_IRGRP, S_IWGRP, S_IXGRP,
8127 S_IROTH, S_IWOTH, S_IXOTH
8133 int symbolic_mode = 0;
8135 while (nextopt("S") != '\0') {
8144 if ((ap = *argptr) == NULL) {
8145 if (symbolic_mode) {
8148 for (i=0 ; i<3 ; i++) {
8152 for (j=0 ; j<3 ; j++) {
8153 if ((mask & permmask[3*i+j]) == 0) {
8162 printf("%.4o\n", mask);
8165 if (is_digit((unsigned char)*ap)) {
8168 if (*ap >= '8' || *ap < '0')
8169 error("Illegal number: %s", argv[1]);
8170 mask = (mask << 3) + (*ap - '0');
8171 } while (*++ap != '\0');
8174 mask = ~mask & 0777;
8175 if (parse_mode(ap, &mask) == FALSE) {
8176 error("Illegal mode: %s", ap);
8178 umask(~mask & 0777);
8187 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8188 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8189 * ash by J.T. Conklin.
8197 short factor; /* multiply by to get rlim_{cur,max} values */
8200 static const struct limits limits[] = {
8202 { "time(seconds)", RLIMIT_CPU, 1 },
8205 { "file(blocks)", RLIMIT_FSIZE, 512 },
8208 { "data(kbytes)", RLIMIT_DATA, 1024 },
8211 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8214 { "coredump(blocks)", RLIMIT_CORE, 512 },
8217 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8219 #ifdef RLIMIT_MEMLOCK
8220 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8223 { "process(processes)", RLIMIT_NPROC, 1 },
8225 #ifdef RLIMIT_NOFILE
8226 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8229 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8232 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8238 ulimitcmd(int argc, char **argv)
8240 static const char unlimited_string[] = "unlimited";
8243 enum { SOFT = 0x1, HARD = 0x2 }
8245 const struct limits *l;
8248 struct rlimit limit;
8252 while ((optc = nextopt("HSa"
8271 #ifdef RLIMIT_MEMLOCK
8277 #ifdef RLIMIT_NOFILE
8289 } else if (optc == 'S') {
8291 } else if (optc == 'a') {
8298 for (l = limits; l->name; l++) {
8299 if(l->name[0] == what)
8301 if(l->name[1]=='w' && what=='w')
8305 set = *argptr ? 1 : 0;
8309 if (all || argptr[1])
8310 error("too many arguments");
8311 if (strcmp(p, unlimited_string) == 0)
8312 val = RLIM_INFINITY;
8316 while ((c = *p++) >= '0' && c <= '9')
8318 val = (val * 10) + (long)(c - '0');
8319 if (val < (rlim_t) 0)
8323 error("bad number");
8329 for (l = limits; l->name; l++) {
8330 printf("%-20s ", l->name);
8331 getrlimit(l->cmd, &limit);
8334 val = limit.rlim_cur;
8335 else if (how & HARD)
8336 val = limit.rlim_max;
8338 if (val == RLIM_INFINITY)
8339 puts(unlimited_string);
8343 printf("%lld\n", (long long) val);
8356 getrlimit(l->cmd, &limit);
8358 limit.rlim_max = val;
8360 limit.rlim_cur = val;
8361 if (setrlimit(l->cmd, &limit) < 0)
8362 error("error setting limit (%m)");
8366 * prefix -- see if pfx is a prefix of string.
8370 prefix(char const *pfx, char const *string)
8373 if (*pfx++ != *string++)
8380 * Return true if s is a string of digits, and save munber in intptr
8385 is_number(const char *p, int *intptr)
8393 ret += digit_val(*p);
8395 } while (*p != '\0');
8402 * Convert a string of digits to an integer, printing an error message on
8407 number(const char *s)
8410 if (! is_number(s, &i))
8411 error("Illegal number: %s", s);
8416 * Produce a possibly single quoted string suitable as input to the shell.
8417 * The return string is allocated on the stack.
8421 single_quote(const char *s)
8429 size_t len1, len1p, len2, len2p;
8431 len1 = strcspn(s, "'");
8432 len2 = strspn(s + len1, "'");
8434 len1p = len1 ? len1 + 2 : len1;
8435 len2p = len2 + ((len2 < 2) ? len2 : 2);
8437 CHECKSTRSPACE(len1p + len2p + 1, p);
8442 memcpy(p + 1, s, len1);
8450 memcpy(q + 1, s, len2);
8453 } else if (len2 == 1) {
8459 STADJUST(len1p + len2p, p);
8464 return grabstackstr(p);
8468 * Like strdup but works with the ash stack.
8472 sstrdup(const char *p)
8474 size_t len = strlen(p) + 1;
8475 return memcpy(stalloc(len), p, len);
8480 * Routine for dealing with parsed shell commands.
8484 static void sizenodelist (const struct nodelist *);
8485 static struct nodelist *copynodelist (const struct nodelist *);
8486 static char *nodexstrdup (const char *);
8488 #define CALCSIZE_TABLE
8489 #define COPYNODE_TABLE
8490 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8492 * To collect a lot of redundant code in case statements for copynode()
8493 * and calcsize(), we implement a mini language here. Each type of node
8494 * struct has an associated instruction sequence that operates on its
8495 * members via their offsets. The instruction are pack in unsigned chars
8496 * with format IIDDDDDE where the bits are
8497 * I : part of the instruction opcode, which are
8498 * 00 : member is a pointer to another node
8499 * 40 : member is an integer
8500 * 80 : member is a pointer to a nodelist
8501 * CC : member is a pointer to a char string
8502 * D : data - the actual offset of the member to operate on in the struct
8503 * (since we assume bit 0 is set, it is not shifted)
8504 * E : flag signaling end of instruction sequence
8506 * WARNING: In order to handle larger offsets for 64bit archs, this code
8507 * assumes that no offset can be an odd number and stores the
8508 * end-of-instructions flag in bit 0.
8511 #define NODE_INTEGER 0x40
8512 #define NODE_NODELIST 0x80
8513 #define NODE_CHARPTR 0xC0
8514 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8515 #define NODE_MBRMASK 0xC0
8516 #define NODE_OFFSETMASK 0x3E
8518 static const unsigned char copynode_ops[35] = {
8519 #define COPYNODE_OPS0 0
8520 offsetof(union node, nbinary.ch2),
8521 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8522 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8523 offsetof(union node, ncmd.redirect),
8524 offsetof(union node, ncmd.args),
8525 offsetof(union node, ncmd.assign),
8526 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8527 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8528 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8529 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8530 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8531 offsetof(union node, nredir.redirect),
8532 offsetof(union node, nredir.n)|NODE_NOMORE,
8533 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8534 offsetof(union node, nif.elsepart),
8535 offsetof(union node, nif.ifpart),
8536 offsetof(union node, nif.test)|NODE_NOMORE,
8537 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8538 offsetof(union node, nfor.var)|NODE_CHARPTR,
8539 offsetof(union node, nfor.body),
8540 offsetof(union node, nfor.args)|NODE_NOMORE,
8541 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8542 offsetof(union node, ncase.cases),
8543 offsetof(union node, ncase.expr)|NODE_NOMORE,
8544 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8545 offsetof(union node, nclist.body),
8546 offsetof(union node, nclist.pattern),
8547 offsetof(union node, nclist.next)|NODE_NOMORE,
8548 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8549 offsetof(union node, narg.backquote)|NODE_NODELIST,
8550 offsetof(union node, narg.text)|NODE_CHARPTR,
8551 offsetof(union node, narg.next)|NODE_NOMORE,
8552 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8553 offsetof(union node, nfile.fname),
8554 offsetof(union node, nfile.fd)|NODE_INTEGER,
8555 offsetof(union node, nfile.next)|NODE_NOMORE,
8556 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8557 offsetof(union node, ndup.vname),
8558 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8559 offsetof(union node, ndup.fd)|NODE_INTEGER,
8560 offsetof(union node, ndup.next)|NODE_NOMORE,
8561 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8562 offsetof(union node, nhere.doc),
8563 offsetof(union node, nhere.fd)|NODE_INTEGER,
8564 offsetof(union node, nhere.next)|NODE_NOMORE,
8565 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8566 offsetof(union node, nnot.com)|NODE_NOMORE,
8569 #if COPYNODE_OPS12 != 34
8570 #error COPYNODE_OPS12 is incorrect
8573 static const unsigned char copynode_ops_index[26] = {
8574 COPYNODE_OPS0, /* NSEMI */
8575 COPYNODE_OPS1, /* NCMD */
8576 COPYNODE_OPS2, /* NPIPE */
8577 COPYNODE_OPS3, /* NREDIR */
8578 COPYNODE_OPS3, /* NBACKGND */
8579 COPYNODE_OPS3, /* NSUBSHELL */
8580 COPYNODE_OPS0, /* NAND */
8581 COPYNODE_OPS0, /* NOR */
8582 COPYNODE_OPS4, /* NIF */
8583 COPYNODE_OPS0, /* NWHILE */
8584 COPYNODE_OPS0, /* NUNTIL */
8585 COPYNODE_OPS5, /* NFOR */
8586 COPYNODE_OPS6, /* NCASE */
8587 COPYNODE_OPS7, /* NCLIST */
8588 COPYNODE_OPS8, /* NDEFUN */
8589 COPYNODE_OPS8, /* NARG */
8590 COPYNODE_OPS9, /* NTO */
8591 COPYNODE_OPS9, /* NFROM */
8592 COPYNODE_OPS9, /* NFROMTO */
8593 COPYNODE_OPS9, /* NAPPEND */
8594 COPYNODE_OPS9, /* NTOOV */
8595 COPYNODE_OPS10, /* NTOFD */
8596 COPYNODE_OPS10, /* NFROMFD */
8597 COPYNODE_OPS11, /* NHERE */
8598 COPYNODE_OPS11, /* NXHERE */
8599 COPYNODE_OPS12, /* NNOT */
8602 #if NODE_CHARPTR != NODE_MBRMASK
8603 #error NODE_CHARPTR != NODE_MBRMASK!!!
8605 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8607 #ifdef COPYNODE_TABLE
8609 copynode(const union node *n)
8612 const unsigned char *p;
8618 new->type = n->type;
8619 funcblock = (char *) funcblock + (int) nodesize[n->type];
8620 p = copynode_ops + (int) copynode_ops_index[n->type];
8622 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8623 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8625 if (!(*p & NODE_MBRMASK)) { /* standard node */
8626 *((union node **)nn) = copynode(*((const union node **) no));
8627 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8628 *((const char **)nn) = nodexstrdup(*((const char **)no));
8629 } else if (*p & NODE_NODELIST) { /* nodelist */
8630 *((struct nodelist **)nn)
8631 = copynodelist(*((const struct nodelist **) no));
8632 } else { /* integer */
8633 *((int *) nn) = *((int *) no);
8635 } while (!(*p++ & NODE_NOMORE));
8638 #else /* COPYNODE_TABLE */
8640 copynode(const union node *n)
8647 funcblock = (char *) funcblock + nodesize[n->type];
8654 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8655 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8658 new->ncmd.redirect = copynode(n->ncmd.redirect);
8659 new->ncmd.args = copynode(n->ncmd.args);
8660 new->ncmd.assign = copynode(n->ncmd.assign);
8661 new->ncmd.backgnd = n->ncmd.backgnd;
8664 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8665 new->npipe.backgnd = n->npipe.backgnd;
8670 new->nredir.redirect = copynode(n->nredir.redirect);
8671 new->nredir.n = copynode(n->nredir.n);
8674 new->nif.elsepart = copynode(n->nif.elsepart);
8675 new->nif.ifpart = copynode(n->nif.ifpart);
8676 new->nif.test = copynode(n->nif.test);
8679 new->nfor.var = nodexstrdup(n->nfor.var);
8680 new->nfor.body = copynode(n->nfor.body);
8681 new->nfor.args = copynode(n->nfor.args);
8684 new->ncase.cases = copynode(n->ncase.cases);
8685 new->ncase.expr = copynode(n->ncase.expr);
8688 new->nclist.body = copynode(n->nclist.body);
8689 new->nclist.pattern = copynode(n->nclist.pattern);
8690 new->nclist.next = copynode(n->nclist.next);
8694 new->narg.backquote = copynodelist(n->narg.backquote);
8695 new->narg.text = nodexstrdup(n->narg.text);
8696 new->narg.next = copynode(n->narg.next);
8703 new->nfile.fname = copynode(n->nfile.fname);
8704 new->nfile.fd = n->nfile.fd;
8705 new->nfile.next = copynode(n->nfile.next);
8709 new->ndup.vname = copynode(n->ndup.vname);
8710 new->ndup.dupfd = n->ndup.dupfd;
8711 new->ndup.fd = n->ndup.fd;
8712 new->ndup.next = copynode(n->ndup.next);
8716 new->nhere.doc = copynode(n->nhere.doc);
8717 new->nhere.fd = n->nhere.fd;
8718 new->nhere.next = copynode(n->nhere.next);
8721 new->nnot.com = copynode(n->nnot.com);
8724 new->type = n->type;
8727 #endif /* COPYNODE_TABLE */
8729 #ifdef CALCSIZE_TABLE
8731 calcsize(const union node *n)
8733 const unsigned char *p;
8737 funcblocksize += (int) nodesize[n->type];
8739 p = copynode_ops + (int) copynode_ops_index[n->type];
8741 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8743 if (!(*p & NODE_MBRMASK)) { /* standard node */
8744 calcsize(*((const union node **) no));
8745 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8746 funcstringsize += strlen(*((const char **)no)) + 1;
8747 } else if (*p & NODE_NODELIST) { /* nodelist */
8748 sizenodelist(*((const struct nodelist **) no));
8749 } /* else integer -- ignore */
8750 } while (!(*p++ & NODE_NOMORE));
8752 #else /* CALCSIZE_TABLE */
8754 calcsize(const union node *n)
8758 funcblocksize += nodesize[n->type];
8765 calcsize(n->nbinary.ch2);
8766 calcsize(n->nbinary.ch1);
8769 calcsize(n->ncmd.redirect);
8770 calcsize(n->ncmd.args);
8771 calcsize(n->ncmd.assign);
8774 sizenodelist(n->npipe.cmdlist);
8779 calcsize(n->nredir.redirect);
8780 calcsize(n->nredir.n);
8783 calcsize(n->nif.elsepart);
8784 calcsize(n->nif.ifpart);
8785 calcsize(n->nif.test);
8788 funcstringsize += strlen(n->nfor.var) + 1;
8789 calcsize(n->nfor.body);
8790 calcsize(n->nfor.args);
8793 calcsize(n->ncase.cases);
8794 calcsize(n->ncase.expr);
8797 calcsize(n->nclist.body);
8798 calcsize(n->nclist.pattern);
8799 calcsize(n->nclist.next);
8803 sizenodelist(n->narg.backquote);
8804 funcstringsize += strlen(n->narg.text) + 1;
8805 calcsize(n->narg.next);
8812 calcsize(n->nfile.fname);
8813 calcsize(n->nfile.next);
8817 calcsize(n->ndup.vname);
8818 calcsize(n->ndup.next);
8822 calcsize(n->nhere.doc);
8823 calcsize(n->nhere.next);
8826 calcsize(n->nnot.com);
8830 #endif /* CALCSIZE_TABLE */
8833 sizenodelist(const struct nodelist *lp)
8836 funcblocksize += ALIGN(sizeof(struct nodelist));
8843 static struct nodelist *
8844 copynodelist(const struct nodelist *lp)
8846 struct nodelist *start;
8847 struct nodelist **lpp;
8852 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8853 (*lpp)->n = copynode(lp->n);
8855 lpp = &(*lpp)->next;
8863 nodexstrdup(const char *s)
8866 char *q = funcstring;
8867 char *rtn = funcstring;
8869 while ((*q++ = *p++) != '\0')
8876 static int getopts (char *, char *, char **, int *, int *);
8881 * Process the shell command line arguments.
8885 procargs(int argc, char **argv)
8892 for (i = 0; i < NOPTS; i++)
8895 if (*argptr == NULL && minusc == NULL)
8897 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8901 for (i = 0; i < NOPTS; i++)
8902 if (optent_val(i) == 2)
8905 if (sflag == 0 && minusc == NULL) {
8906 commandname = argv[0];
8908 setinputfile(arg0, 0);
8911 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8912 if (argptr && minusc && *argptr)
8915 shellparam.p = argptr;
8916 shellparam.optind = 1;
8917 shellparam.optoff = -1;
8918 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8920 shellparam.nparam++;
8929 * Process shell options. The global variable argptr contains a pointer
8930 * to the argument list; we advance it past the options.
8934 minus_o(const char *name, int val)
8939 out1str("Current option settings\n");
8940 for (i = 0; i < NOPTS; i++)
8941 printf("%-16s%s\n", optent_name(optlist[i]),
8942 optent_val(i) ? "on" : "off");
8944 for (i = 0; i < NOPTS; i++)
8945 if (equal(name, optent_name(optlist[i]))) {
8946 setoption(optent_letter(optlist[i]), val);
8949 error("Illegal option -o %s", name);
8955 options(int cmdline)
8963 while ((p = *argptr) != NULL) {
8965 if ((c = *p++) == '-') {
8967 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8969 /* "-" means turn off -x and -v */
8972 /* "--" means reset params */
8973 else if (*argptr == NULL)
8976 break; /* "-" or "--" terminates options */
8978 } else if (c == '+') {
8984 while ((c = *p++) != '\0') {
8985 if (c == 'c' && cmdline) {
8987 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8991 if (q == NULL || minusc != NULL)
8992 error("Bad -c option");
8997 } else if (c == 'o') {
8998 minus_o(*argptr, val);
9010 setoption(int flag, int val)
9014 for (i = 0; i < NOPTS; i++)
9015 if (optent_letter(optlist[i]) == flag) {
9016 optent_val(i) = val;
9018 /* #%$ hack for ksh semantics */
9021 else if (flag == 'E')
9026 error("Illegal option -%c", flag);
9033 * Set the shell parameters.
9037 setparam(char **argv)
9043 for (nparam = 0 ; argv[nparam] ; nparam++);
9044 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
9046 *ap++ = xstrdup(*argv++);
9049 freeparam(&shellparam);
9050 shellparam.malloc = 1;
9051 shellparam.nparam = nparam;
9052 shellparam.p = newparam;
9053 shellparam.optind = 1;
9054 shellparam.optoff = -1;
9059 * Free the list of positional parameters.
9063 freeparam(volatile struct shparam *param)
9067 if (param->malloc) {
9068 for (ap = param->p ; *ap ; ap++)
9077 * The shift builtin command.
9081 shiftcmd(int argc, char **argv)
9088 n = number(argv[1]);
9089 if (n > shellparam.nparam)
9090 error("can't shift that many");
9092 shellparam.nparam -= n;
9093 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9094 if (shellparam.malloc)
9098 while ((*ap2++ = *ap1++) != NULL);
9099 shellparam.optind = 1;
9100 shellparam.optoff = -1;
9108 * The set command builtin.
9112 setcmd(int argc, char **argv)
9115 return showvarscmd(argc, argv);
9119 if (*argptr != NULL) {
9128 getoptsreset(const char *value)
9130 shellparam.optind = number(value);
9131 shellparam.optoff = -1;
9134 #ifdef CONFIG_LOCALE_SUPPORT
9135 static void change_lc_all(const char *value)
9137 if(value != 0 && *value != 0)
9138 setlocale(LC_ALL, value);
9141 static void change_lc_ctype(const char *value)
9143 if(value != 0 && *value != 0)
9144 setlocale(LC_CTYPE, value);
9151 * The getopts builtin. Shellparam.optnext points to the next argument
9152 * to be processed. Shellparam.optptr points to the next character to
9153 * be processed in the current argument. If shellparam.optnext is NULL,
9154 * then it's the first time getopts has been called.
9158 getoptscmd(int argc, char **argv)
9163 error("Usage: getopts optstring var [arg]");
9164 else if (argc == 3) {
9165 optbase = shellparam.p;
9166 if (shellparam.optind > shellparam.nparam + 1) {
9167 shellparam.optind = 1;
9168 shellparam.optoff = -1;
9173 if (shellparam.optind > argc - 2) {
9174 shellparam.optind = 1;
9175 shellparam.optoff = -1;
9179 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9180 &shellparam.optoff);
9184 * Safe version of setvar, returns 1 on success 0 on failure.
9188 setvarsafe(const char *name, const char *val, int flags)
9190 struct jmploc jmploc;
9191 struct jmploc *volatile savehandler = handler;
9197 if (setjmp(jmploc.loc))
9201 setvar(name, val, flags);
9203 handler = savehandler;
9208 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind, int *optoff)
9215 char **optnext = optfirst + *myoptind - 1;
9217 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9218 strlen(*(optnext - 1)) < *optoff)
9221 p = *(optnext - 1) + *optoff;
9222 if (p == NULL || *p == '\0') {
9223 /* Current word is done, advance */
9224 if (optnext == NULL)
9227 if (p == NULL || *p != '-' || *++p == '\0') {
9229 *myoptind = optnext - optfirst + 1;
9235 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9240 for (q = optstr; *q != c; ) {
9242 if (optstr[0] == ':') {
9245 err |= setvarsafe("OPTARG", s, 0);
9248 out2fmt("Illegal option -%c\n", c);
9249 (void) unsetvar("OPTARG");
9259 if (*p == '\0' && (p = *optnext) == NULL) {
9260 if (optstr[0] == ':') {
9263 err |= setvarsafe("OPTARG", s, 0);
9267 out2fmt("No arg for -%c option\n", c);
9268 (void) unsetvar("OPTARG");
9276 setvarsafe("OPTARG", p, 0);
9280 setvarsafe("OPTARG", "", 0);
9281 *myoptind = optnext - optfirst + 1;
9288 *optoff = p ? p - *(optnext - 1) : -1;
9289 snprintf(s, sizeof(s), "%d", *myoptind);
9290 err |= setvarsafe("OPTIND", s, VNOFUNC);
9293 err |= setvarsafe(optvar, s, 0);
9304 * XXX - should get rid of. have all builtins use getopt(3). the
9305 * library getopt must have the BSD extension static variable "optreset"
9306 * otherwise it can't be used within the shell safely.
9308 * Standard option processing (a la getopt) for builtin routines. The
9309 * only argument that is passed to nextopt is the option string; the
9310 * other arguments are unnecessary. It return the character, or '\0' on
9315 nextopt(const char *optstring)
9321 if ((p = optptr) == NULL || *p == '\0') {
9323 if (p == NULL || *p != '-' || *++p == '\0')
9326 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9330 for (q = optstring ; *q != c ; ) {
9332 error("Illegal option -%c", c);
9337 if (*p == '\0' && (p = *argptr++) == NULL)
9338 error("No arg for -%c option", c);
9355 out2fmt(const char *fmt, ...)
9359 vfprintf(stderr, fmt, ap);
9364 * Version of write which resumes after a signal is caught.
9368 xwrite(int fd, const char *buf, int nbytes)
9377 i = write(fd, buf, n);
9383 } else if (i == 0) {
9386 } else if (errno != EINTR) {
9394 * Shell command parser.
9397 #define EOFMARKLEN 79
9402 struct heredoc *next; /* next here document in list */
9403 union node *here; /* redirection node */
9404 char *eofmark; /* string indicating end of input */
9405 int striptabs; /* if set, strip leading tabs */
9408 static struct heredoc *heredoclist; /* list of here documents to read */
9409 static int parsebackquote; /* nonzero if we are inside backquotes */
9410 static int doprompt; /* if set, prompt the user */
9411 static int needprompt; /* true if interactive and at start of line */
9412 static int lasttoken; /* last token read */
9414 static char *wordtext; /* text of last word returned by readtoken */
9416 static struct nodelist *backquotelist;
9417 static union node *redirnode;
9418 static struct heredoc *heredoc;
9419 static int quoteflag; /* set if (part of) last token was quoted */
9420 static int startlinno; /* line # where last token started */
9423 static union node *list (int);
9424 static union node *andor (void);
9425 static union node *pipeline (void);
9426 static union node *command (void);
9427 static union node *simplecmd(union node **rpp, union node *redir);
9428 static void parsefname (void);
9429 static void parseheredoc (void);
9430 static char peektoken (void);
9431 static int readtoken (void);
9432 static int xxreadtoken (void);
9433 static int readtoken1 (int, int, const char *, int);
9434 static int noexpand (char *);
9435 static void synexpect (int) __attribute__((noreturn));
9436 static void synerror (const char *) __attribute__((noreturn));
9437 static void setprompt (int);
9441 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9442 * valid parse tree indicating a blank line.)
9446 parsecmd(int interact)
9451 doprompt = interact;
9470 union node *n1, *n2, *n3;
9474 if (nlflag == 0 && peektoken())
9480 if (tok == TBACKGND) {
9481 if (n2->type == NCMD || n2->type == NPIPE) {
9482 n2->ncmd.backgnd = 1;
9483 } else if (n2->type == NREDIR) {
9484 n2->type = NBACKGND;
9486 n3 = (union node *)stalloc(sizeof (struct nredir));
9487 n3->type = NBACKGND;
9489 n3->nredir.redirect = NULL;
9497 n3 = (union node *)stalloc(sizeof (struct nbinary));
9499 n3->nbinary.ch1 = n1;
9500 n3->nbinary.ch2 = n2;
9524 pungetc(); /* push back EOF on input */
9539 union node *n1, *n2, *n3;
9545 if ((t = readtoken()) == TAND) {
9547 } else if (t == TOR) {
9555 n3 = (union node *)stalloc(sizeof (struct nbinary));
9557 n3->nbinary.ch1 = n1;
9558 n3->nbinary.ch2 = n2;
9567 union node *n1, *n2, *pipenode;
9568 struct nodelist *lp, *prev;
9572 TRACE(("pipeline: entered\n"));
9573 if (readtoken() == TNOT) {
9579 if (readtoken() == TPIPE) {
9580 pipenode = (union node *)stalloc(sizeof (struct npipe));
9581 pipenode->type = NPIPE;
9582 pipenode->npipe.backgnd = 0;
9583 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9584 pipenode->npipe.cmdlist = lp;
9588 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9592 } while (readtoken() == TPIPE);
9598 n2 = (union node *)stalloc(sizeof (struct nnot));
9610 union node *n1, *n2;
9611 union node *ap, **app;
9612 union node *cp, **cpp;
9613 union node *redir, **rpp;
9620 /* Check for redirection which may precede command */
9621 while (readtoken() == TREDIR) {
9622 *rpp = n2 = redirnode;
9623 rpp = &n2->nfile.next;
9628 switch (readtoken()) {
9630 n1 = (union node *)stalloc(sizeof (struct nif));
9632 n1->nif.test = list(0);
9633 if (readtoken() != TTHEN)
9635 n1->nif.ifpart = list(0);
9637 while (readtoken() == TELIF) {
9638 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9639 n2 = n2->nif.elsepart;
9641 n2->nif.test = list(0);
9642 if (readtoken() != TTHEN)
9644 n2->nif.ifpart = list(0);
9646 if (lasttoken == TELSE)
9647 n2->nif.elsepart = list(0);
9649 n2->nif.elsepart = NULL;
9652 if (readtoken() != TFI)
9659 n1 = (union node *)stalloc(sizeof (struct nbinary));
9660 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9661 n1->nbinary.ch1 = list(0);
9662 if ((got=readtoken()) != TDO) {
9663 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9666 n1->nbinary.ch2 = list(0);
9667 if (readtoken() != TDONE)
9673 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9674 synerror("Bad for loop variable");
9675 n1 = (union node *)stalloc(sizeof (struct nfor));
9677 n1->nfor.var = wordtext;
9679 if (readtoken() == TIN) {
9681 while (readtoken() == TWORD) {
9682 n2 = (union node *)stalloc(sizeof (struct narg));
9684 n2->narg.text = wordtext;
9685 n2->narg.backquote = backquotelist;
9687 app = &n2->narg.next;
9691 if (lasttoken != TNL && lasttoken != TSEMI)
9694 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9696 n2 = (union node *)stalloc(sizeof (struct narg));
9698 n2->narg.text = argvars;
9699 n2->narg.backquote = NULL;
9700 n2->narg.next = NULL;
9703 * Newline or semicolon here is optional (but note
9704 * that the original Bourne shell only allowed NL).
9706 if (lasttoken != TNL && lasttoken != TSEMI)
9710 if (readtoken() != TDO)
9712 n1->nfor.body = list(0);
9713 if (readtoken() != TDONE)
9718 n1 = (union node *)stalloc(sizeof (struct ncase));
9720 if (readtoken() != TWORD)
9722 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9724 n2->narg.text = wordtext;
9725 n2->narg.backquote = backquotelist;
9726 n2->narg.next = NULL;
9729 } while (readtoken() == TNL);
9730 if (lasttoken != TIN)
9731 synerror("expecting \"in\"");
9732 cpp = &n1->ncase.cases;
9733 checkkwd = 2, readtoken();
9735 if (lasttoken == TLP)
9737 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9739 app = &cp->nclist.pattern;
9741 *app = ap = (union node *)stalloc(sizeof (struct narg));
9743 ap->narg.text = wordtext;
9744 ap->narg.backquote = backquotelist;
9745 if (checkkwd = 2, readtoken() != TPIPE)
9747 app = &ap->narg.next;
9750 ap->narg.next = NULL;
9751 if (lasttoken != TRP)
9753 cp->nclist.body = list(0);
9756 if ((t = readtoken()) != TESAC) {
9758 synexpect(TENDCASE);
9760 checkkwd = 2, readtoken();
9762 cpp = &cp->nclist.next;
9763 } while(lasttoken != TESAC);
9768 n1 = (union node *)stalloc(sizeof (struct nredir));
9769 n1->type = NSUBSHELL;
9770 n1->nredir.n = list(0);
9771 n1->nredir.redirect = NULL;
9772 if (readtoken() != TRP)
9778 if (readtoken() != TEND)
9782 /* Handle an empty command like other simple commands. */
9791 * An empty command before a ; doesn't make much sense, and
9792 * should certainly be disallowed in the case of `if ;'.
9798 n1 = simplecmd(rpp, redir);
9805 /* Now check for redirection which may follow command */
9806 while (readtoken() == TREDIR) {
9807 *rpp = n2 = redirnode;
9808 rpp = &n2->nfile.next;
9814 if (n1->type != NSUBSHELL) {
9815 n2 = (union node *)stalloc(sizeof (struct nredir));
9820 n1->nredir.redirect = redir;
9828 simplecmd(union node **rpp, union node *redir) {
9829 union node *args, **app;
9830 union node *n = NULL;
9831 union node *vars, **vpp;
9832 union node **orig_rpp;
9839 /* If we don't have any redirections already, then we must reset
9840 rpp to be the address of the local redir variable. */
9843 /* We save the incoming value, because we need this for shell
9844 functions. There can not be a redirect or an argument between
9845 the function name and the open parenthesis. */
9850 switch (readtoken()) {
9853 n = (union node *)stalloc(sizeof (struct narg));
9855 n->narg.text = wordtext;
9856 n->narg.backquote = backquotelist;
9857 if (lasttoken == TWORD) {
9859 app = &n->narg.next;
9862 vpp = &n->narg.next;
9866 *rpp = n = redirnode;
9867 rpp = &n->nfile.next;
9868 parsefname(); /* read name of redirection file */
9872 args && app == &args->narg.next &&
9873 !vars && rpp == orig_rpp
9875 /* We have a function */
9876 if (readtoken() != TRP)
9880 n->narg.next = command();
9893 n = (union node *)stalloc(sizeof (struct ncmd));
9895 n->ncmd.backgnd = 0;
9896 n->ncmd.args = args;
9897 n->ncmd.assign = vars;
9898 n->ncmd.redirect = redir;
9906 n = (union node *)stalloc(sizeof (struct narg));
9908 n->narg.next = NULL;
9909 n->narg.text = wordtext;
9910 n->narg.backquote = backquotelist;
9914 static void fixredir(union node *n, const char *text, int err)
9916 TRACE(("Fix redir %s %d\n", text, err));
9918 n->ndup.vname = NULL;
9920 if (is_digit(text[0]) && text[1] == '\0')
9921 n->ndup.dupfd = digit_val(text[0]);
9922 else if (text[0] == '-' && text[1] == '\0')
9927 synerror("Bad fd number");
9929 n->ndup.vname = makename();
9936 union node *n = redirnode;
9938 if (readtoken() != TWORD)
9940 if (n->type == NHERE) {
9941 struct heredoc *here = heredoc;
9947 TRACE(("Here document %d\n", n->type));
9948 if (here->striptabs) {
9949 while (*wordtext == '\t')
9952 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9953 synerror("Illegal eof marker for << redirection");
9954 rmescapes(wordtext);
9955 here->eofmark = wordtext;
9957 if (heredoclist == NULL)
9960 for (p = heredoclist ; p->next ; p = p->next);
9963 } else if (n->type == NTOFD || n->type == NFROMFD) {
9964 fixredir(n, wordtext, 0);
9966 n->nfile.fname = makename();
9972 * Input any here documents.
9977 struct heredoc *here;
9980 while (heredoclist) {
9982 heredoclist = here->next;
9987 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9988 here->eofmark, here->striptabs);
9989 n = (union node *)stalloc(sizeof (struct narg));
9990 n->narg.type = NARG;
9991 n->narg.next = NULL;
9992 n->narg.text = wordtext;
9993 n->narg.backquote = backquotelist;
9994 here->here->nhere.doc = n;
10004 return tokname_array[t][0];
10012 int savecheckalias = checkalias;
10013 int savecheckkwd = checkkwd;
10018 int alreadyseen = tokpushback;
10028 checkalias = savecheckalias;
10035 if (checkkwd == 2) {
10044 * check for keywords
10046 if (t == TWORD && !quoteflag)
10048 const char *const *pp;
10050 if ((pp = findkwd(wordtext))) {
10051 lasttoken = t = pp - tokname_array;
10052 TRACE(("keyword %s recognized\n", tokname(t)));
10063 } else if (checkalias == 2 && isassignment(wordtext)) {
10064 lasttoken = t = TASSIGN;
10066 } else if (checkalias) {
10067 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10069 pushstring(ap->val, strlen(ap->val), ap);
10071 checkkwd = savecheckkwd;
10080 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10082 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10089 * Read the next input token.
10090 * If the token is a word, we set backquotelist to the list of cmds in
10091 * backquotes. We set quoteflag to true if any part of the word was
10093 * If the token is TREDIR, then we set redirnode to a structure containing
10095 * In all cases, the variable startlinno is set to the number of the line
10096 * on which the token starts.
10098 * [Change comment: here documents and internal procedures]
10099 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10100 * word parsing code into a separate routine. In this case, readtoken
10101 * doesn't need to have any internal procedures, but parseword does.
10102 * We could also make parseoperator in essence the main routine, and
10103 * have parseword (readtoken1?) handle both words and redirection.]
10106 #define NEW_xxreadtoken
10107 #ifdef NEW_xxreadtoken
10109 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10110 static const char xxreadtoken_tokens[] = {
10111 TNL, TLP, TRP, /* only single occurrence allowed */
10112 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10113 TEOF, /* corresponds to trailing nul */
10114 TAND, TOR, TENDCASE, /* if double occurrence */
10117 #define xxreadtoken_doubles \
10118 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10119 #define xxreadtoken_singles \
10120 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10134 startlinno = plinno;
10135 for (;;) { /* until token or start of word found */
10138 if ((c!=' ') && (c!='\t')
10144 while ((c = pgetc()) != '\n' && c != PEOF);
10146 } else if (c=='\\') {
10147 if (pgetc() != '\n') {
10151 startlinno = ++plinno;
10152 setprompt(doprompt ? 2 : 0);
10155 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10160 needprompt = doprompt;
10163 p = strchr(xxreadtoken_chars, c);
10166 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10169 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10170 if (pgetc() == *p) { /* double occurrence? */
10171 p += xxreadtoken_doubles + 1;
10178 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10186 #define RETURN(token) return lasttoken = token
10200 startlinno = plinno;
10201 for (;;) { /* until token or start of word found */
10204 case ' ': case '\t':
10210 while ((c = pgetc()) != '\n' && c != PEOF);
10214 if (pgetc() == '\n') {
10215 startlinno = ++plinno;
10226 needprompt = doprompt;
10231 if (pgetc() == '&')
10236 if (pgetc() == '|')
10241 if (pgetc() == ';')
10254 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10260 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10261 * is not NULL, read a here document. In the latter case, eofmark is the
10262 * word which marks the end of the document and striptabs is true if
10263 * leading tabs should be stripped from the document. The argument firstc
10264 * is the first character of the input token or document.
10266 * Because C does not have internal subroutines, I have simulated them
10267 * using goto's to implement the subroutine linkage. The following macros
10268 * will run code that appears at the end of readtoken1.
10271 #define CHECKEND() {goto checkend; checkend_return:;}
10272 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10273 #define PARSESUB() {goto parsesub; parsesub_return:;}
10274 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10275 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10276 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10279 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10284 char line[EOFMARKLEN + 1];
10285 struct nodelist *bqlist;
10288 int varnest; /* levels of variables expansion */
10289 int arinest; /* levels of arithmetic expansion */
10290 int parenlevel; /* levels of parens in arithmetic */
10291 int dqvarnest; /* levels of variables expansion within double quotes */
10293 int prevsyntax; /* syntax before arithmetic */
10295 /* Avoid longjmp clobbering */
10301 (void) &parenlevel;
10304 (void) &prevsyntax;
10308 startlinno = plinno;
10310 if (syntax == DQSYNTAX)
10319 STARTSTACKSTR(out);
10320 loop: { /* for each line, until end of word */
10321 CHECKEND(); /* set c to PEOF if at end of here document */
10322 for (;;) { /* until end of line or end of word */
10323 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10324 switch(SIT(c,syntax)) {
10325 case CNL: /* '\n' */
10326 if (syntax == BASESYNTAX)
10327 goto endword; /* exit outer loop */
10335 goto loop; /* continue outer loop */
10340 if ((eofmark == NULL || dblquote) &&
10342 USTPUTC(CTLESC, out);
10345 case CBACK: /* backslash */
10348 USTPUTC('\\', out);
10350 } else if (c == '\n') {
10356 if (dblquote && c != '\\' && c != '`' && c != '$'
10357 && (c != '"' || eofmark != NULL))
10358 USTPUTC('\\', out);
10359 if (SIT(c,SQSYNTAX) == CCTL)
10360 USTPUTC(CTLESC, out);
10361 else if (eofmark == NULL)
10362 USTPUTC(CTLQUOTEMARK, out);
10368 if (eofmark == NULL)
10369 USTPUTC(CTLQUOTEMARK, out);
10373 if (eofmark == NULL)
10374 USTPUTC(CTLQUOTEMARK, out);
10379 if (eofmark != NULL && arinest == 0 &&
10384 syntax = ARISYNTAX;
10386 } else if (eofmark == NULL &&
10388 syntax = BASESYNTAX;
10394 case CVAR: /* '$' */
10395 PARSESUB(); /* parse substitution */
10397 case CENDVAR: /* '}' */
10400 if (dqvarnest > 0) {
10403 USTPUTC(CTLENDVAR, out);
10408 #ifdef ASH_MATH_SUPPORT
10409 case CLP: /* '(' in arithmetic */
10413 case CRP: /* ')' in arithmetic */
10414 if (parenlevel > 0) {
10418 if (pgetc() == ')') {
10419 if (--arinest == 0) {
10420 USTPUTC(CTLENDARI, out);
10421 syntax = prevsyntax;
10422 if (syntax == DQSYNTAX)
10430 * unbalanced parens
10431 * (don't 2nd guess - no error)
10439 case CBQUOTE: /* '`' */
10443 goto endword; /* exit outer loop */
10448 goto endword; /* exit outer loop */
10459 if (syntax == ARISYNTAX)
10460 synerror("Missing '))'");
10461 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10462 synerror("Unterminated quoted string");
10463 if (varnest != 0) {
10464 startlinno = plinno;
10465 synerror("Missing '}'");
10467 USTPUTC('\0', out);
10468 len = out - stackblock();
10469 out = stackblock();
10470 if (eofmark == NULL) {
10471 if ((c == '>' || c == '<')
10474 && (*out == '\0' || is_digit(*out))) {
10476 return lasttoken = TREDIR;
10481 quoteflag = quotef;
10482 backquotelist = bqlist;
10483 grabstackblock(len);
10485 return lasttoken = TWORD;
10486 /* end of readtoken routine */
10491 * Check to see whether we are at the end of the here document. When this
10492 * is called, c is set to the first character of the next input line. If
10493 * we are at the end of the here document, this routine sets the c to PEOF.
10504 while (c == '\t') {
10508 if (c == *eofmark) {
10509 if (pfgets(line, sizeof line) != NULL) {
10513 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10514 if (*p == '\n' && *q == '\0') {
10517 needprompt = doprompt;
10519 pushstring(line, strlen(line), NULL);
10524 goto checkend_return;
10529 * Parse a redirection operator. The variable "out" points to a string
10530 * specifying the fd to be redirected. The variable "c" contains the
10531 * first character of the redirection operator.
10538 np = (union node *)stalloc(sizeof (struct nfile));
10543 np->type = NAPPEND;
10552 } else { /* c == '<' */
10554 switch (c = pgetc()) {
10556 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10557 np = (union node *)stalloc(sizeof (struct nhere));
10561 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10562 heredoc->here = np;
10563 if ((c = pgetc()) == '-') {
10564 heredoc->striptabs = 1;
10566 heredoc->striptabs = 0;
10572 np->type = NFROMFD;
10576 np->type = NFROMTO;
10586 np->nfile.fd = digit_val(fd);
10588 goto parseredir_return;
10593 * Parse a substitution. At this point, we have read the dollar sign
10594 * and nothing else.
10602 static const char types[] = "}-+?=";
10607 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10611 } else if (c == '(') { /* $(command) or $((arith)) */
10612 if (pgetc() == '(') {
10619 USTPUTC(CTLVAR, out);
10620 typeloc = out - stackblock();
10621 USTPUTC(VSNORMAL, out);
10622 subtype = VSNORMAL;
10626 if ((c = pgetc()) == '}')
10629 subtype = VSLENGTH;
10634 if (c > PEOA && is_name(c)) {
10638 } while (c > PEOA && is_in_name(c));
10639 } else if (is_digit(c)) {
10643 } while (is_digit(c));
10645 else if (is_special(c)) {
10650 badsub: synerror("Bad substitution");
10654 if (subtype == 0) {
10661 p = strchr(types, c);
10664 subtype = p - types + VSNORMAL;
10670 subtype = c == '#' ? VSTRIMLEFT :
10683 if (dblquote || arinest)
10685 *(stackblock() + typeloc) = subtype | flags;
10686 if (subtype != VSNORMAL) {
10693 goto parsesub_return;
10698 * Called to parse command substitutions. Newstyle is set if the command
10699 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10700 * list of commands (passed by reference), and savelen is the number of
10701 * characters on the top of the stack which must be preserved.
10705 struct nodelist **nlpp;
10708 char *volatile str;
10709 struct jmploc jmploc;
10710 struct jmploc *volatile savehandler;
10714 (void) &saveprompt;
10717 savepbq = parsebackquote;
10718 if (setjmp(jmploc.loc)) {
10721 parsebackquote = 0;
10722 handler = savehandler;
10723 longjmp(handler->loc, 1);
10727 savelen = out - stackblock();
10729 str = xmalloc(savelen);
10730 memcpy(str, stackblock(), savelen);
10732 savehandler = handler;
10736 /* We must read until the closing backquote, giving special
10737 treatment to some slashes, and then push the string and
10738 reread it as input, interpreting it normally. */
10745 STARTSTACKSTR(pout);
10751 switch (pc = pgetc()) {
10756 if ((pc = pgetc()) == '\n') {
10763 * If eating a newline, avoid putting
10764 * the newline into the new character
10765 * stream (via the STPUTC after the
10770 if (pc != '\\' && pc != '`' && pc != '$'
10771 && (!dblquote || pc != '"'))
10772 STPUTC('\\', pout);
10782 startlinno = plinno;
10783 synerror("EOF in backquote substitution");
10787 needprompt = doprompt;
10796 STPUTC('\0', pout);
10797 psavelen = pout - stackblock();
10798 if (psavelen > 0) {
10799 pstr = grabstackstr(pout);
10800 setinputstring(pstr);
10805 nlpp = &(*nlpp)->next;
10806 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10807 (*nlpp)->next = NULL;
10808 parsebackquote = oldstyle;
10811 saveprompt = doprompt;
10818 doprompt = saveprompt;
10820 if (readtoken() != TRP)
10827 * Start reading from old file again, ignoring any pushed back
10828 * tokens left from the backquote parsing
10833 while (stackblocksize() <= savelen)
10835 STARTSTACKSTR(out);
10837 memcpy(out, str, savelen);
10838 STADJUST(savelen, out);
10844 parsebackquote = savepbq;
10845 handler = savehandler;
10846 if (arinest || dblquote)
10847 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10849 USTPUTC(CTLBACKQ, out);
10851 goto parsebackq_oldreturn;
10853 goto parsebackq_newreturn;
10857 * Parse an arithmetic expansion (indicate start of one and set state)
10861 if (++arinest == 1) {
10862 prevsyntax = syntax;
10863 syntax = ARISYNTAX;
10864 USTPUTC(CTLARI, out);
10871 * we collapse embedded arithmetic expansion to
10872 * parenthesis, which should be equivalent
10876 goto parsearith_return;
10879 } /* end of readtoken */
10883 * Returns true if the text contains nothing to expand (no dollar signs
10888 noexpand(char *text)
10894 while ((c = *p++) != '\0') {
10895 if (c == CTLQUOTEMARK)
10899 else if (SIT(c,BASESYNTAX) == CCTL)
10907 * Return true if the argument is a legal variable name (a letter or
10908 * underscore followed by zero or more letters, underscores, and digits).
10912 goodname(const char *name)
10920 if (! is_in_name(*p))
10928 * Called when an unexpected token is read during the parse. The argument
10929 * is the token that is expected, or -1 if more than one type of token can
10930 * occur at this point.
10934 synexpect(int token)
10939 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10941 sprintf(msg+l, " (expecting %s)", tokname(token));
10948 synerror(const char *msg)
10951 out2fmt("%s: %d: ", commandname, startlinno);
10952 out2fmt("Syntax error: %s\n", msg);
10953 error((char *)NULL);
10959 * called by editline -- any expansions to the prompt
10960 * should be added here.
10963 setprompt(int whichprompt)
10966 switch (whichprompt) {
10981 * Code for dealing with input/output redirection.
10984 #define EMPTY -2 /* marks an unused slot in redirtab */
10986 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10988 # define PIPESIZE PIPE_BUF
10993 * Open a file in noclobber mode.
10994 * The code was copied from bash.
10997 noclobberopen(const char *fname)
11000 struct stat finfo, finfo2;
11003 * If the file exists and is a regular file, return an error
11006 r = stat(fname, &finfo);
11007 if (r == 0 && S_ISREG(finfo.st_mode)) {
11013 * If the file was not present (r != 0), make sure we open it
11014 * exclusively so that if it is created before we open it, our open
11015 * will fail. Make sure that we do not truncate an existing file.
11016 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11017 * file was not a regular file, we leave O_EXCL off.
11020 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11021 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11023 /* If the open failed, return the file descriptor right away. */
11028 * OK, the open succeeded, but the file may have been changed from a
11029 * non-regular file to a regular file between the stat and the open.
11030 * We are assuming that the O_EXCL open handles the case where FILENAME
11031 * did not exist and is symlinked to an existing file between the stat
11036 * If we can open it and fstat the file descriptor, and neither check
11037 * revealed that it was a regular file, and the file has not been
11038 * replaced, return the file descriptor.
11040 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11041 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11044 /* The file has been replaced. badness. */
11051 * Handle here documents. Normally we fork off a process to write the
11052 * data to a pipe. If the document is short, we can stuff the data in
11053 * the pipe without forking.
11057 openhere(const union node *redir)
11063 error("Pipe call failed");
11064 if (redir->type == NHERE) {
11065 len = strlen(redir->nhere.doc->narg.text);
11066 if (len <= PIPESIZE) {
11067 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11071 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11073 signal(SIGINT, SIG_IGN);
11074 signal(SIGQUIT, SIG_IGN);
11075 signal(SIGHUP, SIG_IGN);
11077 signal(SIGTSTP, SIG_IGN);
11079 signal(SIGPIPE, SIG_DFL);
11080 if (redir->type == NHERE)
11081 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11083 expandhere(redir->nhere.doc, pip[1]);
11093 openredirect(const union node *redir)
11098 switch (redir->nfile.type) {
11100 fname = redir->nfile.expfname;
11101 if ((f = open(fname, O_RDONLY)) < 0)
11105 fname = redir->nfile.expfname;
11106 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11110 /* Take care of noclobber mode. */
11112 fname = redir->nfile.expfname;
11113 if ((f = noclobberopen(fname)) < 0)
11118 fname = redir->nfile.expfname;
11120 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11123 if ((f = creat(fname, 0666)) < 0)
11128 fname = redir->nfile.expfname;
11130 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11133 if ((f = open(fname, O_WRONLY)) < 0
11134 && (f = creat(fname, 0666)) < 0)
11136 lseek(f, (off_t)0, 2);
11143 /* Fall through to eliminate warning. */
11150 f = openhere(redir);
11156 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11158 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11163 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11164 * old file descriptors are stashed away so that the redirection can be
11165 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11166 * standard output, and the standard error if it becomes a duplicate of
11171 redirect(union node *redir, int flags)
11174 struct redirtab *sv = NULL;
11179 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11181 if (flags & REDIR_PUSH) {
11182 sv = xmalloc(sizeof (struct redirtab));
11183 for (i = 0 ; i < 10 ; i++)
11184 sv->renamed[i] = EMPTY;
11185 sv->next = redirlist;
11188 for (n = redir ; n ; n = n->nfile.next) {
11191 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11192 n->ndup.dupfd == fd)
11193 continue; /* redirect from/to same file descriptor */
11196 newfd = openredirect(n);
11197 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11200 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11204 dupredirect(n, newfd, fd1dup);
11214 error("%d: %m", fd);
11220 if (flags & REDIR_PUSH) {
11221 sv->renamed[fd] = i;
11224 } else if (fd != newfd) {
11230 dupredirect(n, newfd, fd1dup);
11237 dupredirect(const union node *redir, int f, int fd1dup)
11239 int fd = redir->nfile.fd;
11243 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11244 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11245 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11246 dup_as_newfd(redir->ndup.dupfd, fd);
11252 dup_as_newfd(f, fd);
11261 * Undo the effects of the last redirection.
11267 struct redirtab *rp = redirlist;
11271 for (i = 0 ; i < 10 ; i++) {
11272 if (rp->renamed[i] != EMPTY) {
11276 if (rp->renamed[i] >= 0) {
11277 dup_as_newfd(rp->renamed[i], i);
11278 close(rp->renamed[i]);
11282 redirlist = rp->next;
11288 * Discard all saved file descriptors.
11293 struct redirtab *rp;
11296 for (rp = redirlist ; rp ; rp = rp->next) {
11297 for (i = 0 ; i < 10 ; i++) {
11298 if (rp->renamed[i] >= 0) {
11299 close(rp->renamed[i]);
11301 rp->renamed[i] = EMPTY;
11308 * Copy a file descriptor to be >= to. Returns -1
11309 * if the source file descriptor is closed, EMPTY if there are no unused
11310 * file descriptors left.
11314 dup_as_newfd(int from, int to)
11318 newfd = fcntl(from, F_DUPFD, to);
11320 if (errno == EMFILE)
11323 error("%d: %m", from);
11332 static void shtree (union node *, int, char *, FILE*);
11333 static void shcmd (union node *, FILE *);
11334 static void sharg (union node *, FILE *);
11335 static void indent (int, char *, FILE *);
11336 static void trstring (char *);
11343 trputs("showtree called\n");
11344 shtree(n, 1, NULL, stdout);
11349 shtree(union node *n, int ind, char *pfx, FILE *fp)
11351 struct nodelist *lp;
11357 indent(ind, pfx, fp);
11368 shtree(n->nbinary.ch1, ind, NULL, fp);
11371 shtree(n->nbinary.ch2, ind, NULL, fp);
11379 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11384 if (n->npipe.backgnd)
11390 fprintf(fp, "<node type %d>", n->type);
11400 shcmd(union node *cmd, FILE *fp)
11408 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11414 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11420 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11421 s = redir_strings[np->nfile.type - NTO];
11427 switch (np->nfile.type) {
11428 case NTO: s = ">"; dftfd = 1; break;
11429 case NAPPEND: s = ">>"; dftfd = 1; break;
11430 case NTOFD: s = ">&"; dftfd = 1; break;
11431 case NTOOV: s = ">|"; dftfd = 1; break;
11432 case NFROM: s = "<"; dftfd = 0; break;
11433 case NFROMFD: s = "<&"; dftfd = 0; break;
11434 case NFROMTO: s = "<>"; dftfd = 0; break;
11435 default: s = "*error*"; dftfd = 0; break;
11438 if (np->nfile.fd != dftfd)
11439 fprintf(fp, "%d", np->nfile.fd);
11441 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11442 fprintf(fp, "%d", np->ndup.dupfd);
11444 sharg(np->nfile.fname, fp);
11451 sharg(union node *arg, FILE *fp)
11454 struct nodelist *bqlist;
11457 if (arg->type != NARG) {
11458 printf("<node type %d>\n", arg->type);
11462 bqlist = arg->narg.backquote;
11463 for (p = arg->narg.text ; *p ; p++) {
11472 if (subtype == VSLENGTH)
11478 if (subtype & VSNUL)
11481 switch (subtype & VSTYPE) {
11500 case VSTRIMLEFTMAX:
11507 case VSTRIMRIGHTMAX:
11514 printf("<subtype %d>", subtype);
11521 case CTLBACKQ|CTLQUOTE:
11524 shtree(bqlist->n, -1, NULL, fp);
11536 indent(int amount, char *pfx, FILE *fp)
11540 for (i = 0 ; i < amount ; i++) {
11541 if (pfx && i == amount - 1)
11551 static int debug = 1;
11553 static int debug = 0;
11560 if (tracefile == NULL)
11562 putc(c, tracefile);
11568 trace(const char *fmt, ...)
11572 if (tracefile != NULL) {
11573 (void) vfprintf(tracefile, fmt, va);
11574 if (strchr(fmt, '\n'))
11575 (void) fflush(tracefile);
11582 trputs(const char *s)
11584 if (tracefile == NULL)
11586 fputs(s, tracefile);
11587 if (strchr(s, '\n'))
11598 if (tracefile == NULL)
11600 putc('"', tracefile);
11601 for (p = s ; *p ; p++) {
11603 case '\n': c = 'n'; goto backslash;
11604 case '\t': c = 't'; goto backslash;
11605 case '\r': c = 'r'; goto backslash;
11606 case '"': c = '"'; goto backslash;
11607 case '\\': c = '\\'; goto backslash;
11608 case CTLESC: c = 'e'; goto backslash;
11609 case CTLVAR: c = 'v'; goto backslash;
11610 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11611 case CTLBACKQ: c = 'q'; goto backslash;
11612 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11613 backslash: putc('\\', tracefile);
11614 putc(c, tracefile);
11617 if (*p >= ' ' && *p <= '~')
11618 putc(*p, tracefile);
11620 putc('\\', tracefile);
11621 putc(*p >> 6 & 03, tracefile);
11622 putc(*p >> 3 & 07, tracefile);
11623 putc(*p & 07, tracefile);
11628 putc('"', tracefile);
11635 if (tracefile == NULL)
11640 putc(' ', tracefile);
11642 putc('\n', tracefile);
11658 #ifdef not_this_way
11661 if ((p = getenv("HOME")) == NULL) {
11662 if (geteuid() == 0)
11668 strcat(s, "/trace");
11671 strcpy(s, "./trace");
11672 #endif /* not_this_way */
11673 if ((tracefile = wfopen(s, "a")) == NULL)
11676 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11677 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11679 fputs("\nTracing started.\n", tracefile);
11686 * The trap builtin.
11690 trapcmd(int argc, char **argv)
11697 for (signo = 0 ; signo < NSIG ; signo++) {
11698 if (trap[signo] != NULL) {
11702 p = single_quote(trap[signo]);
11703 sn = sys_siglist[signo];
11705 sn = u_signal_names(0, &signo, 0);
11708 printf("trap -- %s %s\n", p, sn);
11720 if ((signo = decode_signal(*ap, 0)) < 0)
11721 error("%s: bad trap", *ap);
11724 if (action[0] == '-' && action[1] == '\0')
11727 action = xstrdup(action);
11730 ckfree(trap[signo]);
11731 trap[signo] = action;
11746 * Set the signal handler for the specified signal. The routine figures
11747 * out what it should be set to.
11751 setsignal(int signo)
11755 struct sigaction act;
11757 if ((t = trap[signo]) == NULL)
11759 else if (*t != '\0')
11763 if (rootshell && action == S_DFL) {
11766 if (iflag || minusc || sflag == 0)
11792 t = &sigmode[signo - 1];
11795 * current setting unknown
11797 if (sigaction(signo, 0, &act) == -1) {
11799 * Pretend it worked; maybe we should give a warning
11800 * here, but other shells don't. We don't alter
11801 * sigmode, so that we retry every time.
11805 if (act.sa_handler == SIG_IGN) {
11806 if (mflag && (signo == SIGTSTP ||
11807 signo == SIGTTIN || signo == SIGTTOU)) {
11808 *t = S_IGN; /* don't hard ignore these */
11812 *t = S_RESET; /* force to be set */
11815 if (*t == S_HARD_IGN || *t == action)
11817 act.sa_handler = ((action == S_CATCH) ? onsig
11818 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11821 sigemptyset(&act.sa_mask);
11822 sigaction(signo, &act, 0);
11830 ignoresig(int signo)
11832 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11833 signal(signo, SIG_IGN);
11835 sigmode[signo - 1] = S_HARD_IGN;
11846 if (signo == SIGINT && trap[SIGINT] == NULL) {
11850 gotsig[signo - 1] = 1;
11856 * Called to execute a trap. Perhaps we should avoid entering new trap
11857 * handlers while we are executing a trap handler.
11867 for (i = 1 ; ; i++) {
11874 savestatus=exitstatus;
11875 evalstring(trap[i], 0);
11876 exitstatus=savestatus;
11883 * Called to exit the shell.
11887 exitshell(int status)
11889 struct jmploc loc1, loc2;
11892 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11893 if (setjmp(loc1.loc)) {
11896 if (setjmp(loc2.loc)) {
11900 if ((p = trap[0]) != NULL && *p != '\0') {
11904 l1: handler = &loc2; /* probably unnecessary */
11913 static int decode_signal(const char *string, int minsig)
11916 const char *name = u_signal_names(string, &signo, minsig);
11918 return name ? signo : -1;
11921 static struct var **hashvar (const char *);
11922 static void showvars (const char *, int, int);
11923 static struct var **findvar (struct var **, const char *);
11926 * Initialize the varable symbol tables and import the environment
11930 * This routine initializes the builtin variables. It is called when the
11931 * shell is initialized and again when a shell procedure is spawned.
11936 const struct varinit *ip;
11940 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
11941 if ((vp->flags & VEXPORT) == 0) {
11942 vpp = hashvar(ip->text);
11945 vp->text = xstrdup(ip->text);
11946 vp->flags = ip->flags;
11947 vp->func = ip->func;
11951 * PS1 depends on uid
11953 if ((vps1.flags & VEXPORT) == 0) {
11954 vpp = hashvar("PS1=");
11957 vps1.text = xstrdup(geteuid() ? "PS1=$ " : "PS1=# ");
11958 vps1.flags = VSTRFIXED|VTEXTFIXED;
11963 * Set the value of a variable. The flags argument is ored with the
11964 * flags of the variable. If val is NULL, the variable is unset.
11968 setvar(const char *name, const char *val, int flags)
11983 if (! is_in_name(*p)) {
11984 if (*p == '\0' || *p == '=')
11990 namelen = p - name;
11992 error("%.*s: bad variable name", namelen, name);
11993 len = namelen + 2; /* 2 is space for '=' and '\0' */
11997 len += vallen = strlen(val);
12000 nameeq = xmalloc(len);
12001 memcpy(nameeq, name, namelen);
12002 nameeq[namelen] = '=';
12004 memcpy(nameeq + namelen + 1, val, vallen + 1);
12006 nameeq[namelen + 1] = '\0';
12008 setvareq(nameeq, flags);
12015 * Same as setvar except that the variable and value are passed in
12016 * the first argument as name=value. Since the first argument will
12017 * be actually stored in the table, it should not be a string that
12022 setvareq(char *s, int flags)
12024 struct var *vp, **vpp;
12027 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12028 if ((vp = *findvar(vpp, s))) {
12029 if (vp->flags & VREADONLY) {
12030 size_t len = strchr(s, '=') - s;
12031 error("%.*s: is read only", len, s);
12035 if (vp->func && (flags & VNOFUNC) == 0)
12036 (*vp->func)(strchr(s, '=') + 1);
12038 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12041 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12042 vp->flags |= flags;
12047 * We could roll this to a function, to handle it as
12048 * a regular variable function callback, but why bother?
12050 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12057 vp = xmalloc(sizeof (*vp));
12068 * Process a linked list of variable assignments.
12072 listsetvar(struct strlist *mylist)
12074 struct strlist *lp;
12077 for (lp = mylist ; lp ; lp = lp->next) {
12078 setvareq(xstrdup(lp->text), 0);
12086 * Find the value of a variable. Returns NULL if not set.
12089 static const char *
12090 lookupvar(const char *name)
12094 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12095 return strchr(v->text, '=') + 1;
12103 * Search the environment of a builtin command.
12106 static const char *
12107 bltinlookup(const char *name)
12109 const struct strlist *sp;
12111 for (sp = cmdenviron ; sp ; sp = sp->next) {
12112 if (varequal(sp->text, name))
12113 return strchr(sp->text, '=') + 1;
12115 return lookupvar(name);
12121 * Generate a list of exported variables. This routine is used to construct
12122 * the third argument to execve when executing a program.
12134 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12135 for (vp = *vpp ; vp ; vp = vp->next)
12136 if (vp->flags & VEXPORT)
12139 ep = env = stalloc((nenv + 1) * sizeof *env);
12140 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12141 for (vp = *vpp ; vp ; vp = vp->next)
12142 if (vp->flags & VEXPORT)
12151 * Called when a shell procedure is invoked to clear out nonexported
12152 * variables. It is also necessary to reallocate variables of with
12153 * VSTACK set since these are currently allocated on the stack.
12159 struct var *vp, **prev;
12161 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12162 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12163 if ((vp->flags & VEXPORT) == 0) {
12165 if ((vp->flags & VTEXTFIXED) == 0)
12167 if ((vp->flags & VSTRFIXED) == 0)
12170 if (vp->flags & VSTACK) {
12171 vp->text = xstrdup(vp->text);
12172 vp->flags &=~ VSTACK;
12184 * Command to list all variables which are set. Currently this command
12185 * is invoked from the set command when the set command is called without
12190 showvarscmd(int argc, char **argv)
12192 showvars(nullstr, VUNSET, VUNSET);
12199 * The export and readonly commands.
12203 exportcmd(int argc, char **argv)
12208 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12211 listsetvar(cmdenviron);
12212 pflag = (nextopt("p") == 'p');
12213 if (argc > 1 && !pflag) {
12214 while ((name = *argptr++) != NULL) {
12215 if ((p = strchr(name, '=')) != NULL) {
12218 if ((vp = *findvar(hashvar(name), name))) {
12223 setvar(name, p, flag);
12227 showvars(argv[0], flag, 0);
12234 * The "local" command.
12237 /* funcnest nonzero if we are currently evaluating a function */
12240 localcmd(int argc, char **argv)
12245 error("Not in a function");
12246 while ((name = *argptr++) != NULL) {
12254 * Make a variable a local variable. When a variable is made local, it's
12255 * value and flags are saved in a localvar structure. The saved values
12256 * will be restored when the shell function returns. We handle the name
12257 * "-" as a special case.
12261 mklocal(char *name)
12263 struct localvar *lvp;
12268 lvp = xmalloc(sizeof (struct localvar));
12269 if (name[0] == '-' && name[1] == '\0') {
12271 p = xmalloc(sizeof optet_vals);
12272 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12275 vpp = hashvar(name);
12276 vp = *findvar(vpp, name);
12278 if (strchr(name, '='))
12279 setvareq(xstrdup(name), VSTRFIXED);
12281 setvar(name, NULL, VSTRFIXED);
12282 vp = *vpp; /* the new variable */
12284 lvp->flags = VUNSET;
12286 lvp->text = vp->text;
12287 lvp->flags = vp->flags;
12288 vp->flags |= VSTRFIXED|VTEXTFIXED;
12289 if (strchr(name, '='))
12290 setvareq(xstrdup(name), 0);
12294 lvp->next = localvars;
12301 * Called after a function returns.
12306 struct localvar *lvp;
12309 while ((lvp = localvars) != NULL) {
12310 localvars = lvp->next;
12312 if (vp == NULL) { /* $- saved */
12313 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12315 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12316 (void)unsetvar(vp->text);
12318 if ((vp->flags & VTEXTFIXED) == 0)
12320 vp->flags = lvp->flags;
12321 vp->text = lvp->text;
12329 setvarcmd(int argc, char **argv)
12332 return unsetcmd(argc, argv);
12333 else if (argc == 3)
12334 setvar(argv[1], argv[2], 0);
12336 error("List assignment not implemented");
12342 * The unset builtin command. We unset the function before we unset the
12343 * variable to allow a function to be unset when there is a readonly variable
12344 * with the same name.
12348 unsetcmd(int argc, char **argv)
12356 while ((i = nextopt("vf")) != '\0') {
12362 if (flg_func == 0 && flg_var == 0)
12365 for (ap = argptr; *ap ; ap++) {
12369 ret |= unsetvar(*ap);
12376 * Unset the specified variable.
12380 unsetvar(const char *s)
12385 vpp = findvar(hashvar(s), s);
12388 if (vp->flags & VREADONLY)
12391 if (*(strchr(vp->text, '=') + 1) != '\0')
12392 setvar(s, nullstr, 0);
12393 vp->flags &= ~VEXPORT;
12394 vp->flags |= VUNSET;
12395 if ((vp->flags & VSTRFIXED) == 0) {
12396 if ((vp->flags & VTEXTFIXED) == 0)
12411 * Find the appropriate entry in the hash table from the name.
12414 static struct var **
12415 hashvar(const char *p)
12417 unsigned int hashval;
12419 hashval = ((unsigned char) *p) << 4;
12420 while (*p && *p != '=')
12421 hashval += (unsigned char) *p++;
12422 return &vartab[hashval % VTABSIZE];
12428 * Returns true if the two strings specify the same varable. The first
12429 * variable name is terminated by '='; the second may be terminated by
12430 * either '=' or '\0'.
12434 varequal(const char *p, const char *q)
12436 while (*p == *q++) {
12440 if (*p == '=' && *(q - 1) == '\0')
12446 showvars(const char *myprefix, int mask, int xor)
12450 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12452 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12453 for (vp = *vpp ; vp ; vp = vp->next) {
12454 if ((vp->flags & mask) ^ xor) {
12458 p = strchr(vp->text, '=') + 1;
12459 len = p - vp->text;
12460 p = single_quote(p);
12462 printf("%s%s%.*s%s\n", myprefix, sep, len,
12470 static struct var **
12471 findvar(struct var **vpp, const char *name)
12473 for (; *vpp; vpp = &(*vpp)->next) {
12474 if (varequal((*vpp)->text, name)) {
12482 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12483 * This file contains code for the times builtin.
12484 * $Id: ash.c,v 1.37 2001/12/06 03:37:38 aaronl Exp $
12486 static int timescmd (int argc, char **argv)
12489 long int clk_tck = sysconf(_SC_CLK_TCK);
12492 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12493 (int) (buf.tms_utime / clk_tck / 60),
12494 ((double) buf.tms_utime) / clk_tck,
12495 (int) (buf.tms_stime / clk_tck / 60),
12496 ((double) buf.tms_stime) / clk_tck,
12497 (int) (buf.tms_cutime / clk_tck / 60),
12498 ((double) buf.tms_cutime) / clk_tck,
12499 (int) (buf.tms_cstime / clk_tck / 60),
12500 ((double) buf.tms_cstime) / clk_tck);
12504 #ifdef ASH_MATH_SUPPORT
12505 /* The let builtin. */
12506 int letcmd(int argc, char **argv)
12511 char *tmp, *expression, p[13];
12512 expression = strchr(argv[1], '=');
12514 /* Cannot use 'error()' here, or the return code
12515 * will be incorrect */
12516 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12519 *expression = '\0';
12520 tmp = ++expression;
12521 result = arith(tmp, &errcode);
12523 /* Cannot use 'error()' here, or the return code
12524 * will be incorrect */
12525 out2fmt("sh: let: ");
12527 out2fmt("divide by zero");
12529 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12532 snprintf(p, 12, "%ld", result);
12533 setvar(argv[1], xstrdup(p), 0);
12534 } else if (argc >= 3)
12535 synerror("invalid operand");
12543 * Copyright (c) 1989, 1991, 1993, 1994
12544 * The Regents of the University of California. All rights reserved.
12546 * This code is derived from software contributed to Berkeley by
12547 * Kenneth Almquist.
12549 * Redistribution and use in source and binary forms, with or without
12550 * modification, are permitted provided that the following conditions
12552 * 1. Redistributions of source code must retain the above copyright
12553 * notice, this list of conditions and the following disclaimer.
12554 * 2. Redistributions in binary form must reproduce the above copyright
12555 * notice, this list of conditions and the following disclaimer in the
12556 * documentation and/or other materials provided with the distribution.
12558 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12559 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12561 * 4. Neither the name of the University nor the names of its contributors
12562 * may be used to endorse or promote products derived from this software
12563 * without specific prior written permission.
12565 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12566 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12567 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12568 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12569 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12570 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12571 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12572 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12573 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12574 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF