1 /* vi: set sw=4 ts=4: */
3 * ash shell port for busybox
5 * Copyright (c) 1989, 1991, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 * This version of ash is adapted from the source in Debian's ash 0.3.8-5
28 * Modified by Erik Andersen <andersee@debian.org> and
29 * Vladimir Oleynik <dzo@simtreas.ru> to be used in busybox
32 * Original copyright notice is retained at the end of this file.
36 /* These defines allow you to adjust the feature set to be compiled
37 * into the ash shell. As a rule, enabling these options will make
38 * ash get bigger... With all of these options off, ash adds about
39 * 60k to busybox on an x86 system.*/
42 /* Enable job control. This allows you to run jobs in the background,
43 * which is great when ash is being used as an interactive shell, but
44 * it completely useless for is all you are doing is running scripts.
45 * This adds about 2.5k on an x86 system. */
48 /* This enables alias support in ash. If you want to support things
49 * like "alias ls='ls -l'" with ash, enable this. This is only useful
50 * when ash is used as an intractive shell. This adds about 1.5k */
53 /* If you need ash to act as a full Posix shell, with full math
54 * support, enable this. This adds a bit over 2k an x86 system. */
55 //#undef ASH_MATH_SUPPORT
56 #define ASH_MATH_SUPPORT
58 /* Getopts is used by shell procedures to parse positional parameters.
59 * You probably want to leave this disabled, and use the busybox getopt
60 * applet if you want to do this sort of thing. There are some scripts
61 * out there that use it, so it you need it, enable. Most people will
62 * leave this disabled. This adds 1k on an x86 system. */
65 /* This allows you to override shell builtins and use whatever is on
66 * the filesystem. This is most useful when ash is acting as a
67 * standalone shell. Adds about 272 bytes. */
70 /* Check for new mail on interactive shells? */
73 /* Optimize size vs speed as size */
74 #define ASH_OPTIMIZE_FOR_SIZE
76 /* Enable this to compile in extra debugging noise. When debugging is
77 * on, debugging info will be written to $HOME/trace and a quit signal
78 * will generate a core dump. */
81 /* These are here to work with glibc -- Don't change these... */
100 #include <sysexits.h>
102 #include <sys/stat.h>
103 #include <sys/cdefs.h>
104 #include <sys/ioctl.h>
105 #include <sys/param.h>
106 #include <sys/resource.h>
107 #include <sys/time.h>
108 #include <sys/times.h>
109 #include <sys/types.h>
110 #include <sys/wait.h>
114 #if !defined(FNMATCH_BROKEN)
117 #if !defined(GLOB_BROKEN)
129 * This file was generated by the mksyntax program.
133 #define CWORD 0 /* character is nothing special */
134 #define CNL 1 /* newline character */
135 #define CBACK 2 /* a backslash character */
136 #define CSQUOTE 3 /* single quote */
137 #define CDQUOTE 4 /* double quote */
138 #define CENDQUOTE 5 /* a terminating quote */
139 #define CBQUOTE 6 /* backwards single quote */
140 #define CVAR 7 /* a dollar sign */
141 #define CENDVAR 8 /* a '}' character */
142 #define CLP 9 /* a left paren in arithmetic */
143 #define CRP 10 /* a right paren in arithmetic */
144 #define CENDFILE 11 /* end of file */
145 #define CCTL 12 /* like CWORD, except it must be escaped */
146 #define CSPCL 13 /* these terminate a word */
147 #define CIGN 14 /* character should be ignored */
167 #define TENDBQUOTE 13
187 /* control characters in argument strings */
188 #define CTLESC '\201'
189 #define CTLVAR '\202'
190 #define CTLENDVAR '\203'
191 #define CTLBACKQ '\204'
192 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
193 /* CTLBACKQ | CTLQUOTE == '\205' */
194 #define CTLARI '\206'
195 #define CTLENDARI '\207'
196 #define CTLQUOTEMARK '\210'
199 #define is_digit(c) ((c)>='0' && (c)<='9')
200 #define is_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalpha((unsigned char) (c))))
201 #define is_in_name(c) (((c) < CTLESC || (c) > CTLENDARI) && ((c) == '_' || isalnum((unsigned char) (c))))
204 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
205 * (assuming ascii char codes, as the original implementation did)
207 #define is_special(c) \
208 ( (((unsigned int)c) - 33 < 32) \
209 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
211 #define digit_val(c) ((c) - '0')
214 #define S_DFL 1 /* default signal handling (SIG_DFL) */
215 #define S_CATCH 2 /* signal is caught */
216 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
217 #define S_HARD_IGN 4 /* signal is ignored permenantly */
218 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
221 /* variable substitution byte (follows CTLVAR) */
222 #define VSTYPE 0x0f /* type of variable substitution */
223 #define VSNUL 0x10 /* colon--treat the empty string as unset */
224 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
226 /* values of VSTYPE field */
227 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
228 #define VSMINUS 0x2 /* ${var-text} */
229 #define VSPLUS 0x3 /* ${var+text} */
230 #define VSQUESTION 0x4 /* ${var?message} */
231 #define VSASSIGN 0x5 /* ${var=text} */
232 #define VSTRIMLEFT 0x6 /* ${var#pattern} */
233 #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
234 #define VSTRIMRIGHT 0x8 /* ${var%pattern} */
235 #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
236 #define VSLENGTH 0xa /* ${#var} */
238 /* flags passed to redirect */
239 #define REDIR_PUSH 01 /* save previous values of file descriptors */
240 #define REDIR_BACKQ 02 /* save the command output to pipe */
243 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
244 * so we use _setjmp instead.
248 #define setjmp(jmploc) _setjmp(jmploc)
249 #define longjmp(jmploc, val) _longjmp(jmploc, val)
253 * Most machines require the value returned from malloc to be aligned
254 * in some way. The following macro will get this right on many machines.
263 #define ALIGN(nbytes) (((nbytes) + sizeof(union align) - 1) & ~(sizeof(union align) - 1))
266 #ifdef CONFIG_LOCALE_SUPPORT
268 static void change_lc_all(const char *value);
269 static void change_lc_ctype(const char *value);
273 * These macros allow the user to suspend the handling of interrupt signals
274 * over a period of time. This is similar to SIGHOLD to or sigblock, but
275 * much more efficient and portable. (But hacking the kernel is so much
276 * more fun than worrying about efficiency and portability. :-))
279 static void onint (void);
280 static volatile int suppressint;
281 static volatile int intpending;
283 #define INTOFF suppressint++
284 #ifndef ASH_OPTIMIZE_FOR_SIZE
285 #define INTON { if (--suppressint == 0 && intpending) onint(); }
286 #define FORCEINTON {suppressint = 0; if (intpending) onint();}
288 static void __inton (void);
289 static void forceinton (void);
290 #define INTON __inton()
291 #define FORCEINTON forceinton()
294 #define CLEAR_PENDING_INT intpending = 0
295 #define int_pending() intpending
298 typedef void *pointer;
300 #define NULL (void *)0
303 static pointer stalloc (int);
304 static void stunalloc (pointer);
305 static void ungrabstackstr (char *, char *);
306 static char * growstackstr(void);
307 static char * makestrspace(size_t newlen);
308 static char *sstrdup (const char *);
311 * Parse trees for commands are allocated in lifo order, so we use a stack
312 * to make this more efficient, and also to avoid all sorts of exception
313 * handling code to handle interrupts in the middle of a parse.
315 * The size 504 was chosen because the Ultrix malloc handles that size
319 #define MINSIZE 504 /* minimum size of a block */
323 struct stack_block *prev;
327 static struct stack_block stackbase;
328 static struct stack_block *stackp = &stackbase;
329 static struct stackmark *markp;
330 static char *stacknxt = stackbase.space;
331 static int stacknleft = MINSIZE;
334 #define equal(s1, s2) (strcmp(s1, s2) == 0)
336 #define stackblock() stacknxt
337 #define stackblocksize() stacknleft
338 #define STARTSTACKSTR(p) p = stackblock(), sstrnleft = stackblocksize()
340 #define STPUTC(c, p) (--sstrnleft >= 0? (*p++ = (c)) : (p = growstackstr(), *p++ = (c)))
341 #define CHECKSTRSPACE(n, p) { if (sstrnleft < n) p = makestrspace(n); }
342 #define STACKSTRNUL(p) (sstrnleft == 0? (p = growstackstr(), *p = '\0') : (*p = '\0'))
345 #define USTPUTC(c, p) (--sstrnleft, *p++ = (c))
346 #define STUNPUTC(p) (++sstrnleft, --p)
347 #define STTOPC(p) p[-1]
348 #define STADJUST(amount, p) (p += (amount), sstrnleft -= (amount))
349 #define grabstackstr(p) stalloc(stackblocksize() - sstrnleft)
351 #define ckfree(p) free((pointer)(p))
355 #define TRACE(param) trace param
356 typedef union node unode;
357 static void trace (const char *, ...);
358 static void trargs (char **);
359 static void showtree (unode *);
360 static void trputc (int);
361 static void trputs (const char *);
362 static void opentrace (void);
397 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
398 #define EXP_TILDE 0x2 /* do normal tilde expansion */
399 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
400 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
401 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
402 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
407 static char optet_vals[NOPTS];
409 static const char * const optlist[NOPTS] = {
428 #define optent_name(optent) (optent+1)
429 #define optent_letter(optent) optent[0]
430 #define optent_val(optent) optet_vals[optent]
432 #define eflag optent_val(0)
433 #define fflag optent_val(1)
434 #define Iflag optent_val(2)
435 #define iflag optent_val(3)
436 #define mflag optent_val(4)
437 #define nflag optent_val(5)
438 #define sflag optent_val(6)
439 #define xflag optent_val(7)
440 #define vflag optent_val(8)
441 #define Vflag optent_val(9)
442 #define Eflag optent_val(10)
443 #define Cflag optent_val(11)
444 #define aflag optent_val(12)
445 #define bflag optent_val(13)
446 #define uflag optent_val(14)
447 #define qflag optent_val(15)
450 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
468 union node *redirect;
475 struct nodelist *cmdlist;
482 union node *redirect;
490 union node *elsepart;
521 struct nodelist *backquote;
559 struct nbinary nbinary;
562 struct nredir nredir;
566 struct nclist nclist;
576 struct nodelist *next;
580 struct backcmd { /* result of evalbackcmd */
581 int fd; /* file descriptor to read from */
582 char *buf; /* buffer */
583 int nleft; /* number of chars in buffer */
584 struct job *jp; /* job structure for command */
592 const struct builtincmd *cmd;
597 struct strlist *next;
603 struct strlist *list;
604 struct strlist **lastp;
608 struct strpush *prev; /* preceding string on stack */
612 struct alias *ap; /* if push was associated with an alias */
614 char *string; /* remember the string since it may change */
618 struct parsefile *prev; /* preceding file on stack */
619 int linno; /* current line */
620 int fd; /* file descriptor (or -1 if string) */
621 int nleft; /* number of chars left in this line */
622 int lleft; /* number of chars left in this buffer */
623 char *nextc; /* next char in buffer */
624 char *buf; /* input buffer */
625 struct strpush *strpush; /* for pushing strings at this level */
626 struct strpush basestrpush; /* so pushing one is fast */
630 struct stack_block *stackp;
633 struct stackmark *marknext;
637 int nparam; /* # of positional parameters (without $0) */
638 unsigned char malloc; /* if parameter list dynamically allocated */
639 char **p; /* parameter list */
640 int optind; /* next parameter to be processed by getopts */
641 int optoff; /* used by getopts */
645 * When commands are first encountered, they are entered in a hash table.
646 * This ensures that a full path search will not have to be done for them
647 * on each invocation.
649 * We should investigate converting to a linear search, even though that
650 * would make the command name "hash" a misnomer.
652 #define CMDTABLESIZE 31 /* should be prime */
653 #define ARB 1 /* actual size determined at run time */
658 struct tblentry *next; /* next entry in hash chain */
659 union param param; /* definition of builtin function */
660 short cmdtype; /* index identifying command */
661 char rehash; /* if set, cd done since entry created */
662 char cmdname[ARB]; /* name of command */
666 static struct tblentry *cmdtable[CMDTABLESIZE];
667 static int builtinloc = -1; /* index in path of %builtin, or -1 */
668 static int exerrno = 0; /* Last exec error */
671 static void tryexec (char *, char **, char **);
672 static void printentry (struct tblentry *, int);
673 static void clearcmdentry (int);
674 static struct tblentry *cmdlookup (const char *, int);
675 static void delete_cmd_entry (void);
676 static int path_change (const char *, int *);
679 static void flushall (void);
680 static void out2fmt (const char *, ...)
681 __attribute__((__format__(__printf__,1,2)));
682 static int xwrite (int, const char *, int);
684 static inline void outstr (const char *p, FILE *file) { fputs(p, file); }
685 static void out1str(const char *p) { outstr(p, stdout); }
686 static void out2str(const char *p) { outstr(p, stderr); }
688 #ifndef ASH_OPTIMIZE_FOR_SIZE
689 #define out2c(c) putc((c), stderr)
691 static void out2c(int c) { putc(c, stderr); }
695 #ifdef ASH_OPTIMIZE_FOR_SIZE
696 #define USE_SIT_FUNCTION
699 /* number syntax index */
700 #define BASESYNTAX 0 /* not in quotes */
701 #define DQSYNTAX 1 /* in double quotes */
702 #define SQSYNTAX 2 /* in single quotes */
703 #define ARISYNTAX 3 /* in arithmetic */
705 static const char S_I_T[][4] = {
706 /* 0 */ { CSPCL, CIGN, CIGN, CIGN }, /* PEOA */
707 /* 1 */ { CSPCL, CWORD, CWORD, CWORD }, /* ' ' */
708 /* 2 */ { CNL, CNL, CNL, CNL }, /* \n */
709 /* 3 */ { CWORD, CCTL, CCTL, CWORD }, /* !*-/:=?[]~ */
710 /* 4 */ { CDQUOTE, CENDQUOTE, CWORD, CDQUOTE }, /* '"' */
711 /* 5 */ { CVAR, CVAR, CWORD, CVAR }, /* $ */
712 /* 6 */ { CSQUOTE, CWORD, CENDQUOTE, CSQUOTE }, /* "'" */
713 /* 7 */ { CSPCL, CWORD, CWORD, CLP }, /* ( */
714 /* 8 */ { CSPCL, CWORD, CWORD, CRP }, /* ) */
715 /* 9 */ { CBACK, CBACK, CCTL, CBACK }, /* \ */
716 /* 10 */ { CBQUOTE, CBQUOTE, CWORD, CBQUOTE }, /* ` */
717 /* 11 */ { CENDVAR, CENDVAR, CWORD, CENDVAR }, /* } */
718 #ifndef USE_SIT_FUNCTION
719 /* 12 */ { CENDFILE, CENDFILE, CENDFILE, CENDFILE }, /* PEOF */
720 /* 13 */ { CWORD, CWORD, CWORD, CWORD }, /* 0-9A-Za-z */
721 /* 14 */ { CCTL, CCTL, CCTL, CCTL } /* CTLESC ... */
725 #ifdef USE_SIT_FUNCTION
727 #define U_C(c) ((unsigned char)(c))
729 static int SIT(int c, int syntax)
731 static const char spec_symbls[]="\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
732 static const char syntax_index_table [] = {
733 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
734 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
735 3, 1, 3, 3, 9, 3,10, 1, /* "=>?[\\]`|" */
740 if(c==PEOF) /* 2^8+2 */
742 if(c==PEOA) /* 2^8+1 */
744 else if(U_C(c)>=U_C(CTLESC) && U_C(c)<=U_C(CTLQUOTEMARK))
747 s = strchr(spec_symbls, c);
750 indx = syntax_index_table[(s-spec_symbls)];
752 return S_I_T[indx][syntax];
755 #else /* USE_SIT_FUNCTION */
757 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
759 #define CSPCL_CIGN_CIGN_CIGN 0
760 #define CSPCL_CWORD_CWORD_CWORD 1
761 #define CNL_CNL_CNL_CNL 2
762 #define CWORD_CCTL_CCTL_CWORD 3
763 #define CDQUOTE_CENDQUOTE_CWORD_CDQUOTE 4
764 #define CVAR_CVAR_CWORD_CVAR 5
765 #define CSQUOTE_CWORD_CENDQUOTE_CSQUOTE 6
766 #define CSPCL_CWORD_CWORD_CLP 7
767 #define CSPCL_CWORD_CWORD_CRP 8
768 #define CBACK_CBACK_CCTL_CBACK 9
769 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
770 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
771 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
772 #define CWORD_CWORD_CWORD_CWORD 13
773 #define CCTL_CCTL_CCTL_CCTL 14
775 static const char syntax_index_table[258] = {
776 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
777 /* 0 -130 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
778 /* 1 -129 PEOA */ CSPCL_CIGN_CIGN_CIGN,
779 /* 2 -128 0xff */ CWORD_CWORD_CWORD_CWORD,
780 /* 3 -127 */ CCTL_CCTL_CCTL_CCTL, /* CTLQUOTEMARK */
781 /* 4 -126 */ CCTL_CCTL_CCTL_CCTL,
782 /* 5 -125 */ CCTL_CCTL_CCTL_CCTL,
783 /* 6 -124 */ CCTL_CCTL_CCTL_CCTL,
784 /* 7 -123 */ CCTL_CCTL_CCTL_CCTL,
785 /* 8 -122 */ CCTL_CCTL_CCTL_CCTL,
786 /* 9 -121 */ CCTL_CCTL_CCTL_CCTL,
787 /* 10 -120 */ CCTL_CCTL_CCTL_CCTL, /* CTLESC */
788 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
789 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
790 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
791 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
792 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
793 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
794 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
795 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
796 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
797 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
798 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
799 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
800 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
801 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
802 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
803 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
804 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
805 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
806 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
807 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
808 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
809 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
810 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
811 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
812 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
813 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
814 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
815 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
816 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
817 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
818 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
819 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
820 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
821 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
822 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
823 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
824 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
825 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
826 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
827 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
828 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
829 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
830 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
831 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
832 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
833 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
834 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
835 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
836 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
837 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
838 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
839 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
840 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
841 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
842 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
843 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
844 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
845 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
846 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
847 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
848 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
849 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
850 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
851 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
852 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
853 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
854 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
855 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
856 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
857 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
858 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
859 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
860 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
861 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
862 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
863 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
864 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
865 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
866 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
867 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
868 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
869 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
870 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
871 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
872 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
873 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
874 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
875 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
876 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
877 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
878 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
879 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
880 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
881 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
882 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
883 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
884 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
885 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
886 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
887 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
888 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
889 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
890 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
891 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
892 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
893 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
894 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
895 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
896 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
897 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
898 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
899 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
900 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
901 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
902 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
903 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
904 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
905 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
906 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
907 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
908 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
909 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
910 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
911 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
912 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
913 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
914 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
915 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
916 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
917 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
918 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
919 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
920 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
921 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
922 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
923 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
924 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
925 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
926 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
927 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
928 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
929 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
930 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
931 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
932 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
933 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
934 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
935 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
936 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
937 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
938 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
939 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
940 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
941 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CDQUOTE,
942 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
943 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
944 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
945 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
946 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CSQUOTE,
947 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
948 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
949 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
950 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
951 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
952 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
953 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
954 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
955 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
956 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
957 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
958 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
959 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
960 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
961 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
962 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
963 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
964 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
965 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
966 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
967 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
968 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
969 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
970 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
971 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
972 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
973 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
974 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
975 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
976 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
977 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
978 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
979 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
980 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
981 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
982 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
983 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
984 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
985 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
986 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
987 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
988 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
989 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
990 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
991 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
992 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
993 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
994 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
995 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
996 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
997 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
998 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
999 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1000 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1001 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1002 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1003 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1004 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1005 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1006 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1007 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1008 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1009 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1010 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1011 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1012 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1013 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1014 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1015 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1016 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1017 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1018 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1019 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1020 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1021 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1022 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1023 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1024 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1025 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1026 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1027 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1028 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1029 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1030 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1031 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1032 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1033 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1034 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1037 #endif /* USE_SIT_FUNCTION */
1040 /* first char is indicating which tokens mark the end of a list */
1041 static const char *const tokname_array[] = {
1056 #define KWDOFFSET 14
1057 /* the following are keywords */
1076 static const char *tokname(int tok)
1078 static char buf[16];
1082 sprintf(buf+(tok>=TSEMI), "%s%c",
1083 tokname_array[tok]+1, (tok>=TSEMI ? '"' : 0));
1087 static int plinno = 1; /* input line number */
1089 static int parselleft; /* copy of parsefile->lleft */
1091 static struct parsefile basepf; /* top level input file */
1092 static char basebuf[BUFSIZ]; /* buffer for top level input file */
1093 static struct parsefile *parsefile = &basepf; /* current input file */
1096 * NEOF is returned by parsecmd when it encounters an end of file. It
1097 * must be distinct from NULL, so we use the address of a variable that
1098 * happens to be handy.
1101 static int tokpushback; /* last token pushed back */
1102 #define NEOF ((union node *)&tokpushback)
1103 static int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */
1106 static void error (const char *, ...) __attribute__((__noreturn__));
1107 static void exerror (int, const char *, ...) __attribute__((__noreturn__));
1108 static void shellexec (char **, char **, const char *, int)
1109 __attribute__((noreturn));
1110 static void exitshell (int) __attribute__((noreturn));
1112 static int goodname(const char *);
1113 static void ignoresig (int);
1114 static void onsig (int);
1115 static void dotrap (void);
1116 static int decode_signal (const char *, int);
1118 static void shprocvar(void);
1119 static void deletefuncs(void);
1120 static void setparam (char **);
1121 static void freeparam (volatile struct shparam *);
1123 static void find_command (const char *, struct cmdentry *, int, const char *);
1125 static inline void hashcd (void);
1127 /* reasons for skipping commands (see comment on breakcmd routine) */
1133 /* values of cmdtype */
1134 #define CMDUNKNOWN -1 /* no entry in table for command */
1135 #define CMDNORMAL 0 /* command is an executable program */
1136 #define CMDBUILTIN 1 /* command is a shell builtin */
1137 #define CMDFUNCTION 2 /* command is a shell function */
1139 #define DO_ERR 1 /* find_command prints errors */
1140 #define DO_ABS 2 /* find_command checks absolute paths */
1141 #define DO_NOFUN 4 /* find_command ignores functions */
1142 #define DO_BRUTE 8 /* find_command ignores hash table */
1149 #define VEXPORT 0x01 /* variable is exported */
1150 #define VREADONLY 0x02 /* variable cannot be modified */
1151 #define VSTRFIXED 0x04 /* variable struct is staticly allocated */
1152 #define VTEXTFIXED 0x08 /* text is staticly allocated */
1153 #define VSTACK 0x10 /* text is allocated on the stack */
1154 #define VUNSET 0x20 /* the variable is not set */
1155 #define VNOFUNC 0x40 /* don't call the callback function */
1159 struct var *next; /* next entry in hash list */
1160 int flags; /* flags are defined above */
1161 char *text; /* name=value */
1162 void (*func) (const char *);
1163 /* function to be called when */
1164 /* the variable gets set/unset */
1168 struct localvar *next; /* next local variable in list */
1169 struct var *vp; /* the variable that was made local */
1170 int flags; /* saved flags */
1171 char *text; /* saved text */
1175 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
1176 #define rmescapes(p) _rmescapes((p), 0)
1177 static char *_rmescapes (char *, int);
1179 static void rmescapes (char *);
1182 static int casematch (union node *, const char *);
1183 static void clearredir(void);
1184 static void popstring(void);
1185 static void readcmdfile (const char *);
1187 static int number (const char *);
1188 static int is_number (const char *, int *num);
1189 static char *single_quote (const char *);
1190 static int nextopt (const char *);
1192 static void redirect (union node *, int);
1193 static void popredir (void);
1194 static int dup_as_newfd (int, int);
1196 static void changepath(const char *newval);
1197 static void getoptsreset(const char *value);
1200 static int parsenleft; /* copy of parsefile->nleft */
1201 static char *parsenextc; /* copy of parsefile->nextc */
1202 static int rootpid; /* pid of main shell */
1203 static int rootshell; /* true if we aren't a child of the main shell */
1205 static const char spcstr[] = " ";
1206 static const char snlfmt[] = "%s\n";
1208 static int sstrnleft;
1209 static int herefd = -1;
1211 static struct localvar *localvars;
1213 static struct var vifs;
1214 static struct var vmail;
1215 static struct var vmpath;
1216 static struct var vpath;
1217 static struct var vps1;
1218 static struct var vps2;
1219 static struct var voptind;
1220 #ifdef CONFIG_LOCALE_SUPPORT
1221 static struct var vlc_all;
1222 static struct var vlc_ctype;
1229 void (*func) (const char *);
1232 static const char defpathvar[] =
1233 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
1234 #define defpath (defpathvar + 5)
1237 static const char defifsvar[] = "IFS= \t\n";
1238 #define defifs (defifsvar + 4)
1240 static const char defifs[] = " \t\n";
1243 static const struct varinit varinit[] = {
1245 { &vifs, VSTRFIXED|VTEXTFIXED, defifsvar,
1247 { &vifs, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS=",
1250 { &vmail, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL=",
1252 { &vmpath, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH=",
1254 { &vpath, VSTRFIXED|VTEXTFIXED, defpathvar,
1257 * vps1 depends on uid
1259 { &vps2, VSTRFIXED|VTEXTFIXED, "PS2=> ",
1261 { &voptind, VSTRFIXED|VTEXTFIXED, "OPTIND=1",
1263 #ifdef CONFIG_LOCALE_SUPPORT
1264 { &vlc_all, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_ALL=",
1266 { &vlc_ctype, VSTRFIXED|VTEXTFIXED|VUNSET, "LC_CTYPE=",
1275 static struct var *vartab[VTABSIZE];
1278 * The following macros access the values of the above variables.
1279 * They have to skip over the name. They return the null string
1280 * for unset variables.
1283 #define ifsval() (vifs.text + 4)
1284 #define ifsset() ((vifs.flags & VUNSET) == 0)
1285 #define mailval() (vmail.text + 5)
1286 #define mpathval() (vmpath.text + 9)
1287 #define pathval() (vpath.text + 5)
1288 #define ps1val() (vps1.text + 4)
1289 #define ps2val() (vps2.text + 4)
1290 #define optindval() (voptind.text + 7)
1292 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1294 static void initvar (void);
1295 static void setvar (const char *, const char *, int);
1296 static void setvareq (char *, int);
1297 static void listsetvar (struct strlist *);
1298 static const char *lookupvar (const char *);
1299 static const char *bltinlookup (const char *);
1300 static char **environment (void);
1301 static int showvarscmd (int, char **);
1302 static void mklocal (char *);
1303 static void poplocalvars (void);
1304 static int unsetvar (const char *);
1305 static int varequal (const char *, const char *);
1308 static char *arg0; /* value of $0 */
1309 static struct shparam shellparam; /* current positional parameters */
1310 static char **argptr; /* argument list for builtin commands */
1311 static char *optionarg; /* set by nextopt (like getopt) */
1312 static char *optptr; /* used by nextopt */
1313 static char *minusc; /* argument to -c option */
1318 #define ALIASINUSE 1
1330 static struct alias *atab[ATABSIZE];
1332 static void setalias (char *, char *);
1333 static struct alias **hashalias (const char *);
1334 static struct alias *freealias (struct alias *);
1335 static struct alias **__lookupalias (const char *);
1338 setalias(char *name, char *val)
1340 struct alias *ap, **app;
1342 app = __lookupalias(name);
1346 if (!(ap->flag & ALIASINUSE)) {
1349 ap->val = xstrdup(val);
1350 ap->flag &= ~ALIASDEAD;
1353 ap = xmalloc(sizeof (struct alias));
1354 ap->name = xstrdup(name);
1355 ap->val = xstrdup(val);
1368 app = __lookupalias(name);
1372 *app = freealias(*app);
1383 struct alias *ap, **app;
1387 for (i = 0; i < ATABSIZE; i++) {
1389 for (ap = *app; ap; ap = *app) {
1390 *app = freealias(*app);
1400 printalias(const struct alias *ap) {
1403 p = single_quote(ap->val);
1404 printf("alias %s=%s\n", ap->name, p);
1410 * TODO - sort output
1413 aliascmd(int argc, char **argv)
1422 for (i = 0; i < ATABSIZE; i++)
1423 for (ap = atab[i]; ap; ap = ap->next) {
1428 while ((n = *++argv) != NULL) {
1429 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
1430 if ((ap = *__lookupalias(n)) == NULL) {
1431 out2fmt("%s: %s not found\n", "alias", n);
1446 unaliascmd(int argc, char **argv)
1450 while ((i = nextopt("a")) != '\0') {
1456 for (i = 0; *argptr; argptr++) {
1457 if (unalias(*argptr)) {
1458 out2fmt("%s: %s not found\n", "unalias", *argptr);
1466 static struct alias **
1467 hashalias(const char *p)
1469 unsigned int hashval;
1474 return &atab[hashval % ATABSIZE];
1477 static struct alias *
1478 freealias(struct alias *ap)
1482 if (ap->flag & ALIASINUSE) {
1483 ap->flag |= ALIASDEAD;
1495 static struct alias **
1496 __lookupalias(const char *name)
1498 struct alias **app = hashalias(name);
1500 for (; *app; app = &(*app)->next) {
1501 if (equal(name, (*app)->name)) {
1510 #ifdef ASH_MATH_SUPPORT
1511 /* The generated file arith.c has been replaced with a custom hand
1512 * written implementation written by Aaron Lehmann <aaronl@vitelus.com>.
1513 * This is now part of libbb, so that it can be used by all the shells
1515 static void expari (int);
1518 static char *trap[NSIG]; /* trap handler commands */
1519 static char sigmode[NSIG - 1]; /* current value of signal */
1520 static char gotsig[NSIG - 1]; /* indicates specified signal received */
1521 static int pendingsigs; /* indicates some signal received */
1524 * This file was generated by the mkbuiltins program.
1528 static int bgcmd (int, char **);
1529 static int fgcmd (int, char **);
1530 static int killcmd (int, char **);
1532 static int bltincmd (int, char **);
1533 static int cdcmd (int, char **);
1534 static int breakcmd (int, char **);
1536 static int commandcmd (int, char **);
1538 static int dotcmd (int, char **);
1539 static int evalcmd (int, char **);
1540 static int execcmd (int, char **);
1541 static int exitcmd (int, char **);
1542 static int exportcmd (int, char **);
1543 static int histcmd (int, char **);
1544 static int hashcmd (int, char **);
1545 static int helpcmd (int, char **);
1546 static int jobscmd (int, char **);
1547 static int localcmd (int, char **);
1548 static int pwdcmd (int, char **);
1549 static int readcmd (int, char **);
1550 static int returncmd (int, char **);
1551 static int setcmd (int, char **);
1552 static int setvarcmd (int, char **);
1553 static int shiftcmd (int, char **);
1554 static int trapcmd (int, char **);
1555 static int umaskcmd (int, char **);
1557 static int aliascmd (int, char **);
1558 static int unaliascmd (int, char **);
1560 static int unsetcmd (int, char **);
1561 static int waitcmd (int, char **);
1562 static int ulimitcmd (int, char **);
1563 static int timescmd (int, char **);
1564 #ifdef ASH_MATH_SUPPORT
1565 static int letcmd (int, char **);
1567 static int typecmd (int, char **);
1569 static int getoptscmd (int, char **);
1573 static int true_main (int, char **);
1575 #ifndef CONFIG_FALSE
1576 static int false_main (int, char **);
1579 static void setpwd (const char *, int);
1582 #define BUILTIN_NOSPEC "0"
1583 #define BUILTIN_SPECIAL "1"
1584 #define BUILTIN_REGULAR "2"
1585 #define BUILTIN_ASSIGN "4"
1586 #define BUILTIN_SPEC_ASSG "5"
1587 #define BUILTIN_REG_ASSG "6"
1589 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1590 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1591 #define IS_BUILTIN_ASSIGN(builtincmd) ((builtincmd)->name[0] & 4)
1595 int (*const builtinfunc) (int, char **);
1600 /* It is CRUCIAL that this listing be kept in ascii order, otherwise
1601 * the binary search in find_builtin() will stop working. If you value
1602 * your kneecaps, you'll be sure to *make sure* that any changes made
1603 * to this array result in the listing remaining in ascii order. You
1606 static const struct builtincmd builtincmds[] = {
1607 { BUILTIN_SPECIAL ".", dotcmd }, /* first, see declare DOTCMD */
1608 { BUILTIN_SPECIAL ":", true_main },
1610 { BUILTIN_REG_ASSG "alias", aliascmd },
1613 { BUILTIN_REGULAR "bg", bgcmd },
1615 { BUILTIN_SPECIAL "break", breakcmd },
1616 { BUILTIN_SPECIAL "builtin", bltincmd },
1617 { BUILTIN_REGULAR "cd", cdcmd },
1618 { BUILTIN_NOSPEC "chdir", cdcmd },
1620 { BUILTIN_REGULAR "command", commandcmd },
1622 { BUILTIN_SPECIAL "continue", breakcmd },
1623 { BUILTIN_SPECIAL "eval", evalcmd },
1624 { BUILTIN_SPECIAL "exec", execcmd },
1625 { BUILTIN_SPECIAL "exit", exitcmd },
1626 { BUILTIN_SPEC_ASSG "export", exportcmd },
1627 { BUILTIN_REGULAR "false", false_main },
1628 { BUILTIN_REGULAR "fc", histcmd },
1630 { BUILTIN_REGULAR "fg", fgcmd },
1633 { BUILTIN_REGULAR "getopts", getoptscmd },
1635 { BUILTIN_NOSPEC "hash", hashcmd },
1636 { BUILTIN_NOSPEC "help", helpcmd },
1637 { BUILTIN_REGULAR "jobs", jobscmd },
1639 { BUILTIN_REGULAR "kill", killcmd },
1641 #ifdef ASH_MATH_SUPPORT
1642 { BUILTIN_REGULAR "let", letcmd },
1644 { BUILTIN_ASSIGN "local", localcmd },
1645 { BUILTIN_NOSPEC "pwd", pwdcmd },
1646 { BUILTIN_REGULAR "read", readcmd },
1647 { BUILTIN_SPEC_ASSG "readonly", exportcmd },
1648 { BUILTIN_SPECIAL "return", returncmd },
1649 { BUILTIN_SPECIAL "set", setcmd },
1650 { BUILTIN_NOSPEC "setvar", setvarcmd },
1651 { BUILTIN_SPECIAL "shift", shiftcmd },
1652 { BUILTIN_SPECIAL "times", timescmd },
1653 { BUILTIN_SPECIAL "trap", trapcmd },
1654 { BUILTIN_REGULAR "true", true_main },
1655 { BUILTIN_NOSPEC "type", typecmd },
1656 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1657 { BUILTIN_REGULAR "umask", umaskcmd },
1659 { BUILTIN_REGULAR "unalias", unaliascmd },
1661 { BUILTIN_SPECIAL "unset", unsetcmd },
1662 { BUILTIN_REGULAR "wait", waitcmd },
1664 #define NUMBUILTINS (sizeof (builtincmds) / sizeof (struct builtincmd) )
1666 #define DOTCMD &builtincmds[0]
1667 static struct builtincmd *BLTINCMD;
1668 static struct builtincmd *EXECCMD;
1669 static struct builtincmd *EVALCMD;
1672 #define JOBSTOPPED 1 /* all procs are stopped */
1673 #define JOBDONE 2 /* all procs are completed */
1676 * A job structure contains information about a job. A job is either a
1677 * single process or a set of processes contained in a pipeline. In the
1678 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1683 pid_t pid; /* process id */
1684 int status; /* status flags (defined above) */
1685 char *cmd; /* text of command being run */
1689 static int job_warning; /* user was warned about stopped jobs */
1692 static void setjobctl(int enable);
1694 #define setjobctl(on) /* do nothing */
1699 struct procstat ps0; /* status of process */
1700 struct procstat *ps; /* status or processes when more than one */
1701 short nprocs; /* number of processes */
1702 short pgrp; /* process group of this job */
1703 char state; /* true if job is finished */
1704 char used; /* true if this entry is in used */
1705 char changed; /* true if status has changed */
1707 char jobctl; /* job running under job control */
1711 static struct job *jobtab; /* array of jobs */
1712 static int njobs; /* size of array */
1713 static int backgndpid = -1; /* pid of last background process */
1715 static int initialpgrp; /* pgrp of shell on invocation */
1716 static int curjob; /* current job */
1719 static int intreceived;
1721 static struct job *makejob (const union node *, int);
1722 static int forkshell (struct job *, const union node *, int);
1723 static int waitforjob (struct job *);
1725 static int docd (char *, int);
1726 static void getpwd (void);
1728 static char *padvance (const char **, const char *);
1730 static char nullstr[1]; /* zero length string */
1731 static char *curdir = nullstr; /* current working directory */
1734 cdcmd(int argc, char **argv)
1743 if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME")) == NULL)
1744 error("HOME not set");
1747 if (dest[0] == '-' && dest[1] == '\0') {
1748 dest = bltinlookup("OLDPWD");
1749 if (!dest || !*dest) {
1758 if (*dest == '/' || (path = bltinlookup("CDPATH")) == NULL)
1760 while ((p = padvance(&path, dest)) != NULL) {
1761 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
1766 if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
1768 print = strcmp(p, dest);
1770 if (docd(p, print) >= 0)
1775 error("can't cd to %s", dest);
1781 * Actually do the chdir. In an interactive shell, print the
1782 * directory name if "print" is nonzero.
1786 docd(char *dest, int print)
1788 TRACE(("docd(\"%s\", %d) called\n", dest, print));
1790 if (chdir(dest) < 0) {
1796 * Update curdir (the name of the current directory) in response to a
1797 * cd command. We also call hashcd to let the routines in exec.c know
1798 * that the current directory has changed.
1800 /* If dest is NULL, we don't know the current directory */
1801 if (dest == NULL || curdir == nullstr)
1814 pwdcmd(int argc, char **argv)
1820 /* Ask system the current directory */
1824 curdir = xgetcwd(0);
1830 setpwd(const char *val, int setold)
1835 setvar("OLDPWD", curdir, VEXPORT);
1838 if (curdir != nullstr) {
1839 if(val!=NULL && *val != '/')
1840 val = cated = concat_path_file(curdir, val);
1846 curdir = simplify_path(val);
1849 setvar("PWD", curdir, VEXPORT);
1853 * Errors and exceptions.
1857 * Code to handle exceptions in C.
1861 * We enclose jmp_buf in a structure so that we can declare pointers to
1862 * jump locations. The global variable handler contains the location to
1863 * jump to when an exception occurs, and the global variable exception
1864 * contains a code identifying the exeception. To implement nested
1865 * exception handlers, the user should save the value of handler on entry
1866 * to an inner scope, set handler to point to a jmploc structure for the
1867 * inner scope, and restore handler on exit from the scope.
1875 #define EXINT 0 /* SIGINT received */
1876 #define EXERROR 1 /* a generic error */
1877 #define EXSHELLPROC 2 /* execute a shell procedure */
1878 #define EXEXEC 3 /* command execution failed */
1880 static struct jmploc *handler;
1881 static int exception;
1883 static void exverror (int, const char *, va_list)
1884 __attribute__((__noreturn__));
1887 * Called to raise an exception. Since C doesn't include exceptions, we
1888 * just do a longjmp to the exception handler. The type of exception is
1889 * stored in the global variable "exception".
1892 static void exraise (int) __attribute__((__noreturn__));
1898 if (handler == NULL)
1903 longjmp(handler->loc, 1);
1908 * Called from trap.c when a SIGINT is received. (If the user specifies
1909 * that SIGINT is to be trapped or ignored using the trap builtin, then
1910 * this routine is not called.) Suppressint is nonzero when interrupts
1911 * are held using the INTOFF macro. The call to _exit is necessary because
1912 * there is a short period after a fork before the signal handlers are
1913 * set to the appropriate value for the child. (The test for iflag is
1914 * just defensive programming.)
1926 sigemptyset(&mysigset);
1927 sigprocmask(SIG_SETMASK, &mysigset, NULL);
1928 if (rootshell && iflag)
1931 signal(SIGINT, SIG_DFL);
1938 static char *commandname; /* currently executing command */
1941 * Exverror is called to raise the error exception. If the first argument
1942 * is not NULL then error prints an error message using printf style
1943 * formatting. It then raises the error exception.
1946 exverror(int cond, const char *msg, va_list ap)
1953 TRACE(("exverror(%d, \"%s\") pid=%d\n", cond, msg, getpid()));
1955 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
1959 out2fmt("%s: ", commandname);
1960 vfprintf(stderr, msg, ap);
1969 error(const char *msg, ...)
1973 exverror(EXERROR, msg, ap);
1980 exerror(int cond, const char *msg, ...)
1984 exverror(cond, msg, ap);
1992 * Table of error messages.
1996 short errcode; /* error number */
1997 char action; /* operation which encountered the error */
2001 * Types of operations (passed to the errmsg routine).
2004 #define E_OPEN 01 /* opening a file */
2005 #define E_CREAT 02 /* creating a file */
2006 #define E_EXEC 04 /* executing a program */
2008 #define ALL (E_OPEN|E_CREAT|E_EXEC)
2010 static const struct errname errormsg[] = {
2015 { ENOENT, E_CREAT },
2017 { ENOTDIR, E_OPEN },
2018 { ENOTDIR, E_CREAT },
2019 { ENOTDIR, E_EXEC },
2021 { EEXIST, E_CREAT },
2060 { ELIBACC, E_EXEC },
2064 #define ERRNAME_SIZE (sizeof(errormsg)/sizeof(struct errname))
2067 * Return a string describing an error. The returned string may be a
2068 * pointer to a static buffer that will be overwritten on the next call.
2069 * Action describes the operation that got the error.
2073 errmsg(int e, int action)
2075 struct errname const *ep;
2076 static char buf[12];
2078 for (ep = errormsg ; ep < errormsg+ERRNAME_SIZE; ep++) {
2079 if (ep->errcode == e && (ep->action & action) != 0)
2083 snprintf(buf, sizeof buf, "error %d", e);
2088 #ifdef ASH_OPTIMIZE_FOR_SIZE
2091 if (--suppressint == 0 && intpending) {
2095 static void forceinton (void) {
2102 /* flags in argument to evaltree */
2103 #define EV_EXIT 01 /* exit after evaluating tree */
2104 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2105 #define EV_BACKCMD 04 /* command executing within back quotes */
2107 static int evalskip; /* set if we are skipping commands */
2108 static int skipcount; /* number of levels to skip */
2109 static int loopnest; /* current loop nesting level */
2110 static int funcnest; /* depth of function calls */
2113 static struct strlist *cmdenviron; /* environment for builtin command */
2114 static int exitstatus; /* exit status of last command */
2115 static int oexitstatus; /* saved exit status */
2117 static void evalsubshell (const union node *, int);
2118 static void expredir (union node *);
2119 static void eprintlist (struct strlist *);
2121 static union node *parsecmd(int);
2123 * Called to reset things after an exception.
2127 * The eval commmand.
2129 static void evalstring (char *, int);
2132 evalcmd(int argc, char **argv)
2141 STARTSTACKSTR(concat);
2145 STPUTC(*p++, concat);
2146 if ((p = *ap++) == NULL)
2148 STPUTC(' ', concat);
2150 STPUTC('\0', concat);
2151 p = grabstackstr(concat);
2153 evalstring(p, EV_TESTED);
2159 * Execute a command or commands contained in a string.
2162 static void evaltree (union node *, int);
2163 static void setinputstring (char *);
2164 static void popfile (void);
2165 static void setstackmark(struct stackmark *mark);
2166 static void popstackmark(struct stackmark *mark);
2170 evalstring(char *s, int flag)
2173 struct stackmark smark;
2175 setstackmark(&smark);
2177 while ((n = parsecmd(0)) != NEOF) {
2179 popstackmark(&smark);
2182 popstackmark(&smark);
2185 static struct builtincmd *find_builtin (const char *);
2186 static void expandarg (union node *, struct arglist *, int);
2187 static void calcsize (const union node *);
2188 static union node *copynode (const union node *);
2191 * Make a copy of a parse tree.
2194 static int funcblocksize; /* size of structures in function */
2195 static int funcstringsize; /* size of strings in node */
2196 static pointer funcblock; /* block to allocate function from */
2197 static char *funcstring; /* block to allocate strings from */
2200 static inline union node *
2201 copyfunc(union node *n)
2208 funcblock = xmalloc(funcblocksize + funcstringsize);
2209 funcstring = (char *) funcblock + funcblocksize;
2214 * Free a parse tree.
2218 freefunc(union node *n)
2226 * Add a new command entry, replacing any existing command entry for
2231 addcmdentry(char *name, struct cmdentry *entry)
2233 struct tblentry *cmdp;
2236 cmdp = cmdlookup(name, 1);
2237 if (cmdp->cmdtype == CMDFUNCTION) {
2238 freefunc(cmdp->param.func);
2240 cmdp->cmdtype = entry->cmdtype;
2241 cmdp->param = entry->u;
2246 evalloop(const union node *n, int flags)
2253 evaltree(n->nbinary.ch1, EV_TESTED);
2255 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2259 if (evalskip == SKIPBREAK && --skipcount <= 0)
2263 if (n->type == NWHILE) {
2264 if (exitstatus != 0)
2267 if (exitstatus == 0)
2270 evaltree(n->nbinary.ch2, flags & EV_TESTED);
2271 status = exitstatus;
2276 exitstatus = status;
2280 evalfor(const union node *n, int flags)
2282 struct arglist arglist;
2285 struct stackmark smark;
2287 setstackmark(&smark);
2288 arglist.lastp = &arglist.list;
2289 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2290 oexitstatus = exitstatus;
2291 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2295 *arglist.lastp = NULL;
2299 for (sp = arglist.list ; sp ; sp = sp->next) {
2300 setvar(n->nfor.var, sp->text, 0);
2301 evaltree(n->nfor.body, flags & EV_TESTED);
2303 if (evalskip == SKIPCONT && --skipcount <= 0) {
2307 if (evalskip == SKIPBREAK && --skipcount <= 0)
2314 popstackmark(&smark);
2318 evalcase(const union node *n, int flags)
2322 struct arglist arglist;
2323 struct stackmark smark;
2325 setstackmark(&smark);
2326 arglist.lastp = &arglist.list;
2327 oexitstatus = exitstatus;
2328 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2329 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2330 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2331 if (casematch(patp, arglist.list->text)) {
2332 if (evalskip == 0) {
2333 evaltree(cp->nclist.body, flags);
2340 popstackmark(&smark);
2344 * Evaluate a pipeline. All the processes in the pipeline are children
2345 * of the process creating the pipeline. (This differs from some versions
2346 * of the shell, which make the last process in a pipeline the parent
2350 static inline void evalpipe(union node *n)
2353 struct nodelist *lp;
2358 TRACE(("evalpipe(0x%lx) called\n", (long)n));
2360 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
2363 jp = makejob(n, pipelen);
2365 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
2367 * Search for a command. This is called before we fork so that the
2368 * location of the command will be available in the parent as well as
2369 * the child. The check for "goodname" is an overly conservative
2370 * check that the name will not be subject to expansion.
2373 struct cmdentry entry;
2374 union node *lpn = lp->n;
2375 if (lpn->type == NCMD && lpn->ncmd.args && goodname(lpn->ncmd.args->narg.text))
2376 find_command(lpn->ncmd.args->narg.text, &entry, 0, pathval());
2380 if (pipe(pip) < 0) {
2382 error("Pipe call failed");
2385 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
2389 dup_as_newfd(prevfd, 0);
2401 dup_as_newfd(pip[1], 1);
2405 evaltree(lp->n, EV_EXIT);
2413 if (n->npipe.backgnd == 0) {
2415 exitstatus = waitforjob(jp);
2416 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
2422 isassignment(const char *word) {
2423 if (!is_name(*word)) {
2428 } while (is_in_name(*word));
2429 return *word == '=';
2434 evalcommand(union node *cmd, int flags)
2436 struct stackmark smark;
2438 struct arglist arglist;
2439 struct arglist varlist;
2445 struct cmdentry cmdentry;
2447 char *volatile savecmdname;
2448 volatile struct shparam saveparam;
2449 struct localvar *volatile savelocalvars;
2453 const struct builtincmd *firstbltin;
2454 struct jmploc *volatile savehandler;
2455 struct jmploc jmploc;
2457 /* Avoid longjmp clobbering */
2464 /* First expand the arguments. */
2465 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
2466 setstackmark(&smark);
2467 arglist.lastp = &arglist.list;
2468 varlist.lastp = &varlist.list;
2470 oexitstatus = exitstatus;
2473 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
2474 expandarg(argp, &varlist, EXP_VARTILDE);
2477 argp = cmd->ncmd.args; argp && !arglist.list;
2478 argp = argp->narg.next
2480 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2483 struct builtincmd *bcmd;
2485 bcmd = find_builtin(arglist.list->text);
2486 pseudovarflag = bcmd && IS_BUILTIN_ASSIGN(bcmd);
2487 for (; argp; argp = argp->narg.next) {
2488 if (pseudovarflag && isassignment(argp->narg.text)) {
2489 expandarg(argp, &arglist, EXP_VARTILDE);
2492 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
2495 *arglist.lastp = NULL;
2496 *varlist.lastp = NULL;
2497 expredir(cmd->ncmd.redirect);
2499 for (sp = arglist.list ; sp ; sp = sp->next)
2501 argv = stalloc(sizeof (char *) * (argc + 1));
2503 for (sp = arglist.list ; sp ; sp = sp->next) {
2504 TRACE(("evalcommand arg: %s\n", sp->text));
2509 if (iflag && funcnest == 0 && argc > 0)
2513 /* Print the command if xflag is set. */
2516 eprintlist(varlist.list);
2517 eprintlist(arglist.list);
2521 /* Now locate the command. */
2523 cmdentry.cmdtype = CMDBUILTIN;
2524 firstbltin = cmdentry.u.cmd = BLTINCMD;
2526 const char *oldpath;
2527 int findflag = DO_ERR;
2531 * Modify the command lookup path, if a PATH= assignment
2534 for (sp = varlist.list ; sp ; sp = sp->next)
2535 if (varequal(sp->text, defpathvar)) {
2536 path = sp->text + 5;
2537 findflag |= DO_BRUTE;
2540 oldfindflag = findflag;
2543 find_command(argv[0], &cmdentry, findflag, path);
2544 if (cmdentry.cmdtype == CMDUNKNOWN) { /* command not found */
2548 /* implement bltin and command here */
2549 if (cmdentry.cmdtype != CMDBUILTIN) {
2553 firstbltin = cmdentry.u.cmd;
2555 if (cmdentry.u.cmd == BLTINCMD) {
2557 struct builtincmd *bcmd;
2562 if (!(bcmd = find_builtin(*argv))) {
2563 out2fmt("%s: not found\n", *argv);
2567 cmdentry.u.cmd = bcmd;
2568 if (bcmd != BLTINCMD)
2572 if (cmdentry.u.cmd == find_builtin("command")) {
2577 if (*argv[0] == '-') {
2578 if (!equal(argv[0], "-p")) {
2588 findflag |= DO_BRUTE;
2591 findflag = oldfindflag;
2593 findflag |= DO_NOFUN;
2601 /* Fork off a child process if necessary. */
2602 if (cmd->ncmd.backgnd
2603 || (cmdentry.cmdtype == CMDNORMAL && (flags & EV_EXIT) == 0)
2605 jp = makejob(cmd, 1);
2606 mode = cmd->ncmd.backgnd;
2607 if (forkshell(jp, cmd, mode) != 0)
2608 goto parent; /* at end of routine */
2612 /* This is the child process if a fork occurred. */
2613 /* Execute the command. */
2614 if (cmdentry.cmdtype == CMDFUNCTION) {
2616 trputs("Shell function: "); trargs(argv);
2618 exitstatus = oexitstatus;
2619 redirect(cmd->ncmd.redirect, REDIR_PUSH);
2620 saveparam = shellparam;
2621 shellparam.malloc = 0;
2622 shellparam.nparam = argc - 1;
2623 shellparam.p = argv + 1;
2625 savelocalvars = localvars;
2628 if (setjmp(jmploc.loc)) {
2629 if (exception == EXSHELLPROC) {
2630 freeparam((volatile struct shparam *)
2633 saveparam.optind = shellparam.optind;
2634 saveparam.optoff = shellparam.optoff;
2635 freeparam(&shellparam);
2636 shellparam = saveparam;
2639 localvars = savelocalvars;
2640 handler = savehandler;
2641 longjmp(handler->loc, 1);
2643 savehandler = handler;
2645 for (sp = varlist.list ; sp ; sp = sp->next)
2648 evaltree(cmdentry.u.func, flags & EV_TESTED);
2652 localvars = savelocalvars;
2653 saveparam.optind = shellparam.optind;
2654 saveparam.optoff = shellparam.optoff;
2655 freeparam(&shellparam);
2656 shellparam = saveparam;
2657 handler = savehandler;
2660 if (evalskip == SKIPFUNC) {
2664 if (flags & EV_EXIT)
2665 exitshell(exitstatus);
2666 } else if (cmdentry.cmdtype == CMDBUILTIN) {
2668 trputs("builtin command: "); trargs(argv);
2670 mode = (cmdentry.u.cmd == EXECCMD)? 0 : REDIR_PUSH;
2671 redirect(cmd->ncmd.redirect, mode);
2672 savecmdname = commandname;
2673 if (IS_BUILTIN_SPECIAL(firstbltin)) {
2674 listsetvar(varlist.list);
2676 cmdenviron = varlist.list;
2679 if (setjmp(jmploc.loc)) {
2681 exitstatus = (e == EXINT)? SIGINT+128 : 2;
2684 savehandler = handler;
2686 commandname = argv[0];
2688 optptr = NULL; /* initialize nextopt */
2689 exitstatus = (*cmdentry.u.cmd->builtinfunc)(argc, argv);
2693 if (e != EXSHELLPROC) {
2694 commandname = savecmdname;
2695 if (flags & EV_EXIT)
2696 exitshell(exitstatus);
2698 handler = savehandler;
2700 if ((e != EXERROR && e != EXEXEC)
2701 || cmdentry.u.cmd == BLTINCMD
2702 || cmdentry.u.cmd == DOTCMD
2703 || cmdentry.u.cmd == EVALCMD
2704 || cmdentry.u.cmd == EXECCMD)
2708 if (cmdentry.u.cmd != EXECCMD)
2712 trputs("normal command: "); trargs(argv);
2714 redirect(cmd->ncmd.redirect, 0);
2716 for (sp = varlist.list ; sp ; sp = sp->next)
2717 setvareq(sp->text, VEXPORT|VSTACK);
2718 envp = environment();
2719 shellexec(argv, envp, path, cmdentry.u.index);
2723 parent: /* parent process gets here (if we forked) */
2724 if (mode == 0) { /* argument to fork */
2726 exitstatus = waitforjob(jp);
2732 setvar("_", lastarg, 0);
2733 popstackmark(&smark);
2737 * Evaluate a parse tree. The value is left in the global variable
2741 evaltree(union node *n, int flags)
2745 TRACE(("evaltree(NULL) called\n"));
2748 TRACE(("evaltree(0x%lx: %d) called\n", (long)n, n->type));
2751 evaltree(n->nbinary.ch1, flags & EV_TESTED);
2754 evaltree(n->nbinary.ch2, flags);
2757 evaltree(n->nbinary.ch1, EV_TESTED);
2758 if (evalskip || exitstatus != 0)
2760 evaltree(n->nbinary.ch2, flags);
2763 evaltree(n->nbinary.ch1, EV_TESTED);
2764 if (evalskip || exitstatus == 0)
2766 evaltree(n->nbinary.ch2, flags);
2769 expredir(n->nredir.redirect);
2770 redirect(n->nredir.redirect, REDIR_PUSH);
2771 evaltree(n->nredir.n, flags);
2775 evalsubshell(n, flags);
2778 evalsubshell(n, flags);
2781 evaltree(n->nif.test, EV_TESTED);
2784 if (exitstatus == 0)
2785 evaltree(n->nif.ifpart, flags);
2786 else if (n->nif.elsepart)
2787 evaltree(n->nif.elsepart, flags);
2803 struct builtincmd *bcmd;
2804 struct cmdentry entry;
2806 (bcmd = find_builtin(n->narg.text)) &&
2807 IS_BUILTIN_SPECIAL(bcmd)
2809 out2fmt("%s is a special built-in\n", n->narg.text);
2813 entry.cmdtype = CMDFUNCTION;
2814 entry.u.func = copyfunc(n->narg.next);
2815 addcmdentry(n->narg.text, &entry);
2820 evaltree(n->nnot.com, EV_TESTED);
2821 exitstatus = !exitstatus;
2829 evalcommand(n, flags);
2834 printf("Node type = %d\n", n->type);
2843 (checkexit && eflag && exitstatus && !(flags & EV_TESTED))
2845 exitshell(exitstatus);
2849 * Kick off a subshell to evaluate a tree.
2853 evalsubshell(const union node *n, int flags)
2856 int backgnd = (n->type == NBACKGND);
2858 expredir(n->nredir.redirect);
2860 if (forkshell(jp, n, backgnd) == 0) {
2862 flags &=~ EV_TESTED;
2863 redirect(n->nredir.redirect, 0);
2864 evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
2868 exitstatus = waitforjob(jp);
2874 * Compute the names of the files in a redirection list.
2877 static void fixredir(union node *n, const char *text, int err);
2880 expredir(union node *n)
2884 for (redir = n ; redir ; redir = redir->nfile.next) {
2886 fn.lastp = &fn.list;
2887 oexitstatus = exitstatus;
2888 switch (redir->type) {
2894 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
2895 redir->nfile.expfname = fn.list->text;
2899 if (redir->ndup.vname) {
2900 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
2901 fixredir(redir, fn.list->text, 1);
2910 * Execute a command inside back quotes. If it's a builtin command, we
2911 * want to save its output in a block obtained from malloc. Otherwise
2912 * we fork off a subprocess and get the output of the command via a pipe.
2913 * Should be called with interrupts off.
2917 evalbackcmd(union node *n, struct backcmd *result)
2921 struct stackmark smark; /* unnecessary */
2923 setstackmark(&smark);
2934 error("Pipe call failed");
2936 if (forkshell(jp, n, FORK_NOJOB) == 0) {
2941 dup_as_newfd(pip[1], 1);
2945 evaltree(n, EV_EXIT);
2948 result->fd = pip[0];
2951 popstackmark(&smark);
2952 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
2953 result->fd, result->buf, result->nleft, result->jp));
2958 * Execute a simple command.
2963 * Builtin commands. Builtin commands whose functions are closely
2964 * tied to evaluation are implemented here.
2968 * No command given, or a bltin command with no arguments. Set the
2969 * specified variables.
2973 bltincmd(int argc, char **argv)
2976 * Preserve exitstatus of a previous possible redirection
2984 * Handle break and continue commands. Break, continue, and return are
2985 * all handled by setting the evalskip flag. The evaluation routines
2986 * above all check this flag, and if it is set they start skipping
2987 * commands rather than executing them. The variable skipcount is
2988 * the number of loops to break/continue, or the number of function
2989 * levels to return. (The latter is always 1.) It should probably
2990 * be an error to break out of more loops than exist, but it isn't
2991 * in the standard shell so we don't make it one here.
2995 breakcmd(int argc, char **argv)
2997 int n = argc > 1 ? number(argv[1]) : 1;
3000 error("Illegal number: %s", argv[1]);
3004 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3012 * The return command.
3016 returncmd(int argc, char **argv)
3018 int ret = argc > 1 ? number(argv[1]) : oexitstatus;
3021 evalskip = SKIPFUNC;
3026 /* Do what ksh does; skip the rest of the file */
3027 evalskip = SKIPFILE;
3034 #ifndef CONFIG_FALSE
3036 false_main(int argc, char **argv)
3044 true_main(int argc, char **argv)
3051 * Controls whether the shell is interactive or not.
3054 static void setsignal(int signo);
3057 static void chkmail(int silent);
3061 setinteractive(int on)
3063 static int is_interactive;
3064 static int do_banner=0;
3066 if (on == is_interactive)
3074 is_interactive = on;
3075 if (do_banner==0 && is_interactive) {
3076 /* Looks like they want an interactive shell */
3077 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
3078 printf( "\n\n" BB_BANNER " Built-in shell (ash)\n");
3079 printf( "Enter 'help' for a list of built-in commands.\n\n");
3088 setinteractive(iflag);
3094 execcmd(int argc, char **argv)
3099 iflag = 0; /* exit on error */
3102 for (sp = cmdenviron; sp ; sp = sp->next)
3103 setvareq(sp->text, VEXPORT|VSTACK);
3104 shellexec(argv + 1, environment(), pathval(), 0);
3110 eprintlist(struct strlist *sp)
3112 for (; sp; sp = sp->next) {
3113 out2fmt(" %s",sp->text);
3118 * Exec a program. Never returns. If you change this routine, you may
3119 * have to change the find_command routine as well.
3122 static const char *pathopt; /* set by padvance */
3125 shellexec(char **argv, char **envp, const char *path, int idx)
3130 if (strchr(argv[0], '/') != NULL) {
3131 tryexec(argv[0], argv, envp);
3135 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3136 if (--idx < 0 && pathopt == NULL) {
3137 tryexec(cmdname, argv, envp);
3138 if (errno != ENOENT && errno != ENOTDIR)
3145 /* Map to POSIX errors */
3157 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3162 * Clear traps on a fork.
3169 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
3170 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
3175 setsignal(tp - trap);
3210 /* from options.c: */
3214 for (i = 0; i < NOPTS; i++)
3230 for (sm = sigmode ; sm < sigmode + NSIG - 1; sm++) {
3242 static int preadbuffer(void);
3243 static void pushfile (void);
3246 * Read a character from the script, returning PEOF on end of file.
3247 * Nul characters in the input are silently discarded.
3250 #ifndef ASH_OPTIMIZE_FOR_SIZE
3251 #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
3255 return pgetc_macro();
3261 return --parsenleft >= 0? *parsenextc++ : preadbuffer();
3267 return pgetc_macro();
3273 * Undo the last call to pgetc. Only one character may be pushed back.
3274 * PEOF may be pushed back.
3277 static void pungetc(void)
3287 struct parsefile *pf = parsefile;
3296 parsefile = pf->prev;
3298 parsenleft = parsefile->nleft;
3299 parselleft = parsefile->lleft;
3300 parsenextc = parsefile->nextc;
3301 plinno = parsefile->linno;
3307 * Return to top level.
3313 while (parsefile != &basepf)
3318 * Close the file(s) that the shell is reading commands from. Called
3319 * after a fork is done.
3322 static void closescript(void)
3325 if (parsefile->fd > 0) {
3326 close(parsefile->fd);
3333 * Like setinputfile, but takes an open file descriptor. Call this with
3337 static void setinputfd(int fd, int push)
3339 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
3345 while (parsefile->strpush)
3349 if (parsefile->buf == NULL)
3350 parsefile->buf = xmalloc(BUFSIZ);
3351 parselleft = parsenleft = 0;
3357 * Set the input to take input from a file. If push is set, push the
3358 * old input onto the stack first.
3362 setinputfile(const char *fname, int push)
3368 if ((fd = open(fname, O_RDONLY)) < 0)
3369 error("Can't open %s", fname);
3371 myfileno2 = dup_as_newfd(fd, 10);
3374 error("Out of file descriptors");
3377 setinputfd(fd, push);
3383 tryexec(char *cmd, char **argv, char **envp)
3387 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3391 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3392 name = get_last_path_component(name);
3395 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3398 for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++)
3400 run_applet_by_name(name, argc_l, argv);
3402 execve(cmd, argv, envp);
3407 setinputfile(cmd, 0);
3408 commandname = arg0 = xstrdup(argv[0]);
3410 exraise(EXSHELLPROC);
3415 static char *commandtext (const union node *);
3418 * Do a path search. The variable path (passed by reference) should be
3419 * set to the start of the path before the first call; padvance will update
3420 * this value as it proceeds. Successive calls to padvance will return
3421 * the possible path expansions in sequence. If an option (indicated by
3422 * a percent sign) appears in the path entry then the global variable
3423 * pathopt will be set to point to it; otherwise pathopt will be set to
3427 static const char *pathopt;
3429 static void growstackblock(void);
3433 padvance(const char **path, const char *name)
3443 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3444 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3445 while (stackblocksize() < len)
3449 memcpy(q, start, p - start);
3457 while (*p && *p != ':') p++;
3463 return stalloc(len);
3467 * Wrapper around strcmp for qsort/bsearch/...
3470 pstrcmp(const void *a, const void *b)
3472 return strcmp((const char *) a, (*(const char *const *) b) + 1);
3476 * Find a keyword is in a sorted array.
3479 static const char *const *
3480 findkwd(const char *s)
3482 return bsearch(s, tokname_array + KWDOFFSET,
3483 (sizeof(tokname_array)/sizeof(const char *)) - KWDOFFSET,
3484 sizeof(const char *), pstrcmp);
3488 /*** Command hashing code ***/
3492 hashcmd(int argc, char **argv)
3494 struct tblentry **pp;
3495 struct tblentry *cmdp;
3498 struct cmdentry entry;
3501 const struct alias *ap;
3505 while ((c = nextopt("rvV")) != '\0') {
3509 } else if (c == 'v' || c == 'V') {
3513 if (*argptr == NULL) {
3514 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3515 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3516 if (cmdp->cmdtype != CMDBUILTIN) {
3517 printentry(cmdp, verbose);
3524 while ((name = *argptr++) != NULL) {
3525 if ((cmdp = cmdlookup(name, 0)) != NULL
3526 && (cmdp->cmdtype == CMDNORMAL
3527 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3530 /* Then look at the aliases */
3531 if ((ap = *__lookupalias(name)) != NULL) {
3533 printf("%s is an alias for %s\n", name, ap->val);
3539 /* First look at the keywords */
3540 if (findkwd(name)!=0) {
3542 printf("%s is a shell keyword\n", name);
3548 find_command(name, &entry, DO_ERR, pathval());
3549 if (entry.cmdtype == CMDUNKNOWN) c = 1;
3551 cmdp = cmdlookup(name, 0);
3552 if (cmdp) printentry(cmdp, verbose=='v');
3560 printentry(struct tblentry *cmdp, int verbose)
3566 printf("%s%s", cmdp->cmdname, (verbose ? " is " : ""));
3567 if (cmdp->cmdtype == CMDNORMAL) {
3568 idx = cmdp->param.index;
3571 name = padvance(&path, cmdp->cmdname);
3573 } while (--idx >= 0);
3576 } else if (cmdp->cmdtype == CMDBUILTIN) {
3578 out1str("a shell builtin");
3579 } else if (cmdp->cmdtype == CMDFUNCTION) {
3582 out1str("a function\n");
3583 name = commandtext(cmdp->param.func);
3584 printf("%s() {\n %s\n}", cmdp->cmdname, name);
3590 error("internal error: cmdtype %d", cmdp->cmdtype);
3593 puts(cmdp->rehash ? "*" : nullstr);
3598 /*** List the available builtins ***/
3601 static int helpcmd(int argc, char** argv)
3605 printf("\nBuilt-in commands:\n-------------------\n");
3606 for (col=0, i=0; i < NUMBUILTINS; i++) {
3607 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3608 builtincmds[i].name+1);
3614 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3616 extern const struct BB_applet applets[];
3617 extern const size_t NUM_APPLETS;
3619 for (i=0; i < NUM_APPLETS; i++) {
3621 col += printf("%c%s", ((col == 0) ? '\t' : ' '),
3631 return EXIT_SUCCESS;
3635 * Resolve a command name. If you change this routine, you may have to
3636 * change the shellexec routine as well.
3639 static int prefix (const char *, const char *);
3642 find_command(const char *name, struct cmdentry *entry, int act, const char *path)
3644 struct tblentry *cmdp;
3654 struct builtincmd *bcmd;
3656 /* If name contains a slash, don't use the hash table */
3657 if (strchr(name, '/') != NULL) {
3659 while (stat(name, &statb) < 0) {
3660 if (errno != ENOENT && errno != ENOTDIR)
3662 entry->cmdtype = CMDUNKNOWN;
3663 entry->u.index = -1;
3666 entry->cmdtype = CMDNORMAL;
3667 entry->u.index = -1;
3670 entry->cmdtype = CMDNORMAL;
3676 if (act & DO_BRUTE) {
3677 firstchange = path_change(path, &bltin);
3683 /* If name is in the table, and not invalidated by cd, we're done */
3684 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->rehash == 0) {
3685 if (cmdp->cmdtype == CMDFUNCTION) {
3686 if (act & DO_NOFUN) {
3691 } else if (act & DO_BRUTE) {
3692 if ((cmdp->cmdtype == CMDNORMAL &&
3693 cmdp->param.index >= firstchange) ||
3694 (cmdp->cmdtype == CMDBUILTIN &&
3695 ((builtinloc < 0 && bltin >= 0) ?
3696 bltin : builtinloc) >= firstchange)) {
3697 /* need to recompute the entry */
3706 bcmd = find_builtin(name);
3707 regular = bcmd && IS_BUILTIN_REGULAR(bcmd);
3710 if (cmdp && (cmdp->cmdtype == CMDBUILTIN)) {
3713 } else if (act & DO_BRUTE) {
3714 if (firstchange == 0) {
3719 /* If %builtin not in path, check for builtin next */
3720 if (regular || (bltin < 0 && bcmd)) {
3723 entry->cmdtype = CMDBUILTIN;
3724 entry->u.cmd = bcmd;
3728 cmdp = cmdlookup(name, 1);
3729 cmdp->cmdtype = CMDBUILTIN;
3730 cmdp->param.cmd = bcmd;
3735 /* We have to search path. */
3736 prev = -1; /* where to start */
3737 if (cmdp && cmdp->rehash) { /* doing a rehash */
3738 if (cmdp->cmdtype == CMDBUILTIN)
3741 prev = cmdp->param.index;
3747 while ((fullname = padvance(&path, name)) != NULL) {
3748 stunalloc(fullname);
3750 if (idx >= firstchange) {
3754 if (prefix("builtin", pathopt)) {
3755 if ((bcmd = find_builtin(name))) {
3759 } else if (!(act & DO_NOFUN) &&
3760 prefix("func", pathopt)) {
3763 continue; /* ignore unimplemented options */
3766 /* if rehash, don't redo absolute path names */
3767 if (fullname[0] == '/' && idx <= prev &&
3768 idx < firstchange) {
3771 TRACE(("searchexec \"%s\": no change\n", name));
3774 while (stat(fullname, &statb) < 0) {
3775 if (errno != ENOENT && errno != ENOTDIR)
3779 e = EACCES; /* if we fail, this will be the error */
3780 if (!S_ISREG(statb.st_mode))
3782 if (pathopt) { /* this is a %func directory */
3783 stalloc(strlen(fullname) + 1);
3784 readcmdfile(fullname);
3785 if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
3786 error("%s not defined in %s", name, fullname);
3787 stunalloc(fullname);
3790 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3791 /* If we aren't called with DO_BRUTE and cmdp is set, it must
3792 be a function and we're being called with DO_NOFUN */
3794 entry->cmdtype = CMDNORMAL;
3795 entry->u.index = idx;
3799 cmdp = cmdlookup(name, 1);
3800 cmdp->cmdtype = CMDNORMAL;
3801 cmdp->param.index = idx;
3806 /* We failed. If there was an entry for this command, delete it */
3807 if (cmdp && updatetbl)
3810 out2fmt("%s: %s\n", name, errmsg(e, E_EXEC));
3811 entry->cmdtype = CMDUNKNOWN;
3816 entry->cmdtype = cmdp->cmdtype;
3817 entry->u = cmdp->param;
3823 * Search the table of builtin commands.
3827 bstrcmp(const void *name, const void *b)
3829 return strcmp((const char *)name, (*(const char *const *) b)+1);
3832 static struct builtincmd *
3833 find_builtin(const char *name)
3835 struct builtincmd *bp;
3837 bp = bsearch(name, builtincmds, NUMBUILTINS, sizeof(struct builtincmd),
3845 * Called when a cd is done. Marks all commands so the next time they
3846 * are executed they will be rehashed.
3852 struct tblentry **pp;
3853 struct tblentry *cmdp;
3855 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3856 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3857 if (cmdp->cmdtype == CMDNORMAL
3858 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0))
3867 * Called before PATH is changed. The argument is the new value of PATH;
3868 * pathval() still returns the old value at this point. Called with
3873 changepath(const char *newval)
3878 firstchange = path_change(newval, &bltin);
3879 if (builtinloc < 0 && bltin >= 0)
3880 builtinloc = bltin; /* zap builtins */
3881 clearcmdentry(firstchange);
3887 * Clear out command entries. The argument specifies the first entry in
3888 * PATH which has changed.
3892 clearcmdentry(int firstchange)
3894 struct tblentry **tblp;
3895 struct tblentry **pp;
3896 struct tblentry *cmdp;
3899 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3901 while ((cmdp = *pp) != NULL) {
3902 if ((cmdp->cmdtype == CMDNORMAL &&
3903 cmdp->param.index >= firstchange)
3904 || (cmdp->cmdtype == CMDBUILTIN &&
3905 builtinloc >= firstchange)) {
3918 * Delete all functions.
3924 struct tblentry **tblp;
3925 struct tblentry **pp;
3926 struct tblentry *cmdp;
3929 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
3931 while ((cmdp = *pp) != NULL) {
3932 if (cmdp->cmdtype == CMDFUNCTION) {
3934 freefunc(cmdp->param.func);
3947 * Locate a command in the command hash table. If "add" is nonzero,
3948 * add the command to the table if it is not already present. The
3949 * variable "lastcmdentry" is set to point to the address of the link
3950 * pointing to the entry, so that delete_cmd_entry can delete the
3954 static struct tblentry **lastcmdentry;
3956 static struct tblentry *
3957 cmdlookup(const char *name, int add)
3961 struct tblentry *cmdp;
3962 struct tblentry **pp;
3969 pp = &cmdtable[hashval % CMDTABLESIZE];
3970 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3971 if (equal(cmdp->cmdname, name))
3975 if (add && cmdp == NULL) {
3977 cmdp = *pp = xmalloc(sizeof (struct tblentry) - ARB
3978 + strlen(name) + 1);
3980 cmdp->cmdtype = CMDUNKNOWN;
3982 strcpy(cmdp->cmdname, name);
3990 * Delete the command entry returned on the last lookup.
3996 struct tblentry *cmdp;
3999 cmdp = *lastcmdentry;
4000 *lastcmdentry = cmdp->next;
4009 static const unsigned char nodesize[26] = {
4010 ALIGN(sizeof (struct nbinary)),
4011 ALIGN(sizeof (struct ncmd)),
4012 ALIGN(sizeof (struct npipe)),
4013 ALIGN(sizeof (struct nredir)),
4014 ALIGN(sizeof (struct nredir)),
4015 ALIGN(sizeof (struct nredir)),
4016 ALIGN(sizeof (struct nbinary)),
4017 ALIGN(sizeof (struct nbinary)),
4018 ALIGN(sizeof (struct nif)),
4019 ALIGN(sizeof (struct nbinary)),
4020 ALIGN(sizeof (struct nbinary)),
4021 ALIGN(sizeof (struct nfor)),
4022 ALIGN(sizeof (struct ncase)),
4023 ALIGN(sizeof (struct nclist)),
4024 ALIGN(sizeof (struct narg)),
4025 ALIGN(sizeof (struct narg)),
4026 ALIGN(sizeof (struct nfile)),
4027 ALIGN(sizeof (struct nfile)),
4028 ALIGN(sizeof (struct nfile)),
4029 ALIGN(sizeof (struct nfile)),
4030 ALIGN(sizeof (struct nfile)),
4031 ALIGN(sizeof (struct ndup)),
4032 ALIGN(sizeof (struct ndup)),
4033 ALIGN(sizeof (struct nhere)),
4034 ALIGN(sizeof (struct nhere)),
4035 ALIGN(sizeof (struct nnot)),
4041 * Delete a function if it exists.
4045 unsetfunc(char *name)
4047 struct tblentry *cmdp;
4049 if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
4050 freefunc(cmdp->param.func);
4057 * Locate and print what a word is...
4061 typecmd(int argc, char **argv)
4069 for (i = 1; i < argc; i++) {
4070 argv_a[0] = argv[i];
4073 err |= hashcmd(argc, argv);
4080 commandcmd(int argc, char **argv)
4083 int default_path = 0;
4084 int verify_only = 0;
4085 int verbose_verify_only = 0;
4087 while ((c = nextopt("pvV")) != '\0')
4096 verbose_verify_only = 1;
4100 if (default_path + verify_only + verbose_verify_only > 1 ||
4103 "command [-p] command [arg ...]\n"
4104 "command {-v|-V} command\n");
4108 if (verify_only || verbose_verify_only) {
4112 argv_a[0] = *argptr;
4114 optptr = verbose_verify_only ? "v" : "V"; /* reverse special */
4115 return hashcmd(argc, argv);
4123 path_change(const char *newval, int *bltin)
4125 const char *old, *new;
4131 firstchange = 9999; /* assume no change */
4137 if ((*old == '\0' && *new == ':')
4138 || (*old == ':' && *new == '\0'))
4140 old = new; /* ignore subsequent differences */
4144 if (*new == '%' && *bltin < 0 && prefix("builtin", new + 1))
4151 if (builtinloc >= 0 && *bltin < 0)
4156 * Routines to expand arguments to commands. We have to deal with
4157 * backquotes, shell variables, and file metacharacters.
4162 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4163 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4166 * Structure specifying which parts of the string should be searched
4167 * for IFS characters.
4171 struct ifsregion *next; /* next region in list */
4172 int begoff; /* offset of start of region */
4173 int endoff; /* offset of end of region */
4174 int nulonly; /* search for nul bytes only */
4178 static char *expdest; /* output of current string */
4179 static struct nodelist *argbackq; /* list of back quote expressions */
4180 static struct ifsregion ifsfirst; /* first struct in list of ifs regions */
4181 static struct ifsregion *ifslastp; /* last struct in list */
4182 static struct arglist exparg; /* holds expanded arg list */
4184 static void argstr (char *, int);
4185 static char *exptilde (char *, int);
4186 static void expbackq (union node *, int, int);
4187 static int subevalvar (char *, char *, int, int, int, int, int);
4188 static int varisset (char *, int);
4189 static void strtodest (const char *, int, int);
4190 static inline void varvalue (char *, int, int);
4191 static void recordregion (int, int, int);
4192 static void removerecordregions (int);
4193 static void ifsbreakup (char *, struct arglist *);
4194 static void ifsfree (void);
4195 static void expandmeta (struct strlist *, int);
4196 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4197 #define preglob(p) _rmescapes((p), RMESCAPE_ALLOC | RMESCAPE_GLOB)
4198 #if !defined(GLOB_BROKEN)
4199 static inline void addglob (const glob_t *);
4202 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4203 static void expmeta (char *, char *);
4205 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
4206 static struct strlist *expsort (struct strlist *);
4207 static struct strlist *msort (struct strlist *, int);
4209 static int patmatch (char *, char *, int);
4210 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
4211 static int patmatch2 (char *, char *, int);
4213 static int pmatch (char *, char *, int);
4214 #define patmatch2 patmatch
4216 static char *cvtnum (int, char *);
4219 * Expand shell variables and backquotes inside a here document.
4222 /* arg: the document, fd: where to write the expanded version */
4224 expandhere(union node *arg, int fd)
4227 expandarg(arg, (struct arglist *)NULL, 0);
4228 xwrite(fd, stackblock(), expdest - stackblock());
4233 * Perform variable substitution and command substitution on an argument,
4234 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4235 * perform splitting and file name expansion. When arglist is NULL, perform
4236 * here document expansion.
4240 expandarg(union node *arg, struct arglist *arglist, int flag)
4245 argbackq = arg->narg.backquote;
4246 STARTSTACKSTR(expdest);
4247 ifsfirst.next = NULL;
4249 argstr(arg->narg.text, flag);
4250 if (arglist == NULL) {
4251 return; /* here document expanded */
4253 STPUTC('\0', expdest);
4254 p = grabstackstr(expdest);
4255 exparg.lastp = &exparg.list;
4259 if (flag & EXP_FULL) {
4260 ifsbreakup(p, &exparg);
4261 *exparg.lastp = NULL;
4262 exparg.lastp = &exparg.list;
4263 expandmeta(exparg.list, flag);
4265 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4267 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4270 exparg.lastp = &sp->next;
4273 *exparg.lastp = NULL;
4275 *arglist->lastp = exparg.list;
4276 arglist->lastp = exparg.lastp;
4282 * Expand a variable, and return a pointer to the next character in the
4286 static inline char * evalvar(char *p, int flag)
4299 int quotes = flag & (EXP_FULL | EXP_CASE);
4302 subtype = varflags & VSTYPE;
4307 p = strchr(p, '=') + 1;
4308 again: /* jump here after setting a variable with ${var=text} */
4310 set = varisset(var, varflags & VSNUL);
4313 val = lookupvar(var);
4314 if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
4321 startloc = expdest - stackblock();
4322 if (set && subtype != VSPLUS) {
4323 /* insert the value of the variable */
4325 varvalue(var, varflags & VSQUOTE, flag);
4326 if (subtype == VSLENGTH) {
4327 varlen = expdest - stackblock() - startloc;
4328 STADJUST(-varlen, expdest);
4331 if (subtype == VSLENGTH) {
4332 varlen = strlen(val);
4336 varflags & VSQUOTE ?
4337 DQSYNTAX : BASESYNTAX,
4344 if (subtype == VSPLUS)
4347 easy = ((varflags & VSQUOTE) == 0 ||
4348 (*var == '@' && shellparam.nparam != 1));
4353 expdest = cvtnum(varlen, expdest);
4360 recordregion(startloc, expdest - stackblock(),
4361 varflags & VSQUOTE);
4377 case VSTRIMRIGHTMAX:
4381 * Terminate the string and start recording the pattern
4384 STPUTC('\0', expdest);
4385 patloc = expdest - stackblock();
4386 if (subevalvar(p, NULL, patloc, subtype,
4387 startloc, varflags, quotes) == 0) {
4388 int amount = (expdest - stackblock() - patloc) + 1;
4389 STADJUST(-amount, expdest);
4391 /* Remove any recorded regions beyond start of variable */
4392 removerecordregions(startloc);
4398 if (subevalvar(p, var, 0, subtype, startloc,
4399 varflags, quotes)) {
4402 * Remove any recorded regions beyond
4405 removerecordregions(startloc);
4420 if (subtype != VSNORMAL) { /* skip to end of alternative */
4423 if ((c = *p++) == CTLESC)
4425 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
4427 argbackq = argbackq->next;
4428 } else if (c == CTLVAR) {
4429 if ((*p++ & VSTYPE) != VSNORMAL)
4431 } else if (c == CTLENDVAR) {
4442 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4443 * characters to allow for further processing. Otherwise treat
4444 * $@ like $* since no splitting will be performed.
4448 argstr(char *p, int flag)
4451 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4454 if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
4455 p = exptilde(p, flag);
4459 case CTLENDVAR: /* ??? */
4462 /* "$@" syntax adherence hack */
4463 if (p[0] == CTLVAR && p[2] == '@' && p[3] == '=')
4465 if ((flag & EXP_FULL) != 0)
4475 p = evalvar(p, flag);
4478 case CTLBACKQ|CTLQUOTE:
4479 expbackq(argbackq->n, c & CTLQUOTE, flag);
4480 argbackq = argbackq->next;
4482 #ifdef ASH_MATH_SUPPORT
4490 * sort of a hack - expand tildes in variable
4491 * assignments (after the first '=' and after ':'s).
4494 if (flag & EXP_VARTILDE && *p == '~') {
4501 p = exptilde(p, flag);
4512 exptilde(char *p, int flag)
4514 char c, *startp = p;
4517 int quotes = flag & (EXP_FULL | EXP_CASE);
4519 while ((c = *p) != '\0') {
4526 if (flag & EXP_VARTILDE)
4536 if (*(startp+1) == '\0') {
4537 if ((home = lookupvar("HOME")) == NULL)
4540 if ((pw = getpwnam(startp+1)) == NULL)
4547 strtodest(home, SQSYNTAX, quotes);
4556 removerecordregions(int endoff)
4558 if (ifslastp == NULL)
4561 if (ifsfirst.endoff > endoff) {
4562 while (ifsfirst.next != NULL) {
4563 struct ifsregion *ifsp;
4565 ifsp = ifsfirst.next->next;
4566 ckfree(ifsfirst.next);
4567 ifsfirst.next = ifsp;
4570 if (ifsfirst.begoff > endoff)
4573 ifslastp = &ifsfirst;
4574 ifsfirst.endoff = endoff;
4579 ifslastp = &ifsfirst;
4580 while (ifslastp->next && ifslastp->next->begoff < endoff)
4581 ifslastp=ifslastp->next;
4582 while (ifslastp->next != NULL) {
4583 struct ifsregion *ifsp;
4585 ifsp = ifslastp->next->next;
4586 ckfree(ifslastp->next);
4587 ifslastp->next = ifsp;
4590 if (ifslastp->endoff > endoff)
4591 ifslastp->endoff = endoff;
4595 #ifdef ASH_MATH_SUPPORT
4597 * Expand arithmetic expression. Backup to start of expression,
4598 * evaluate, place result in (backed up) result, adjust string position.
4607 int quotes = flag & (EXP_FULL | EXP_CASE);
4613 * This routine is slightly over-complicated for
4614 * efficiency. First we make sure there is
4615 * enough space for the result, which may be bigger
4616 * than the expression if we add exponentation. Next we
4617 * scan backwards looking for the start of arithmetic. If the
4618 * next previous character is a CTLESC character, then we
4619 * have to rescan starting from the beginning since CTLESC
4620 * characters have to be processed left to right.
4622 CHECKSTRSPACE(10, expdest);
4623 USTPUTC('\0', expdest);
4624 start = stackblock();
4626 while (*p != CTLARI && p >= start)
4629 error("missing CTLARI (shouldn't happen)");
4630 if (p > start && *(p-1) == CTLESC)
4631 for (p = start; *p != CTLARI; p++)
4640 removerecordregions(begoff);
4643 result = arith(p+2, &errcode);
4646 error("divide by zero");
4648 error("syntax error: \"%s\"\n", p+2);
4650 snprintf(p, 12, "%d", result);
4656 recordregion(begoff, p - 1 - start, 0);
4657 result = expdest - p + 1;
4658 STADJUST(-result, expdest);
4663 * Expand stuff in backwards quotes.
4667 expbackq(union node *cmd, int quoted, int flag)
4669 volatile struct backcmd in;
4673 char *dest = expdest;
4674 volatile struct ifsregion saveifs;
4675 struct ifsregion *volatile savelastp;
4676 struct nodelist *volatile saveargbackq;
4678 int startloc = dest - stackblock();
4679 int syntax = quoted ? DQSYNTAX : BASESYNTAX;
4680 volatile int saveherefd;
4681 int quotes = flag & (EXP_FULL | EXP_CASE);
4682 struct jmploc jmploc;
4683 struct jmploc *volatile savehandler;
4687 /* Avoid longjmp clobbering */
4698 savelastp = ifslastp;
4699 saveargbackq = argbackq;
4700 saveherefd = herefd;
4702 if ((ex = setjmp(jmploc.loc))) {
4705 savehandler = handler;
4708 p = grabstackstr(dest);
4709 evalbackcmd(cmd, (struct backcmd *) &in);
4710 ungrabstackstr(p, dest);
4714 ifslastp = savelastp;
4715 argbackq = saveargbackq;
4716 herefd = saveherefd;
4724 if (--in.nleft < 0) {
4727 i = safe_read(in.fd, buf, sizeof buf);
4728 TRACE(("expbackq: read returns %d\n", i));
4735 if (lastc != '\0') {
4736 if (quotes && SIT(lastc, syntax) == CCTL)
4737 STPUTC(CTLESC, dest);
4738 STPUTC(lastc, dest);
4742 /* Eat all trailing newlines */
4743 for (; dest > stackblock() && dest[-1] == '\n';)
4752 exitstatus = waitforjob(in.jp);
4753 handler = savehandler;
4755 longjmp(handler->loc, 1);
4758 recordregion(startloc, dest - stackblock(), 0);
4759 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4760 (dest - stackblock()) - startloc,
4761 (dest - stackblock()) - startloc,
4762 stackblock() + startloc));
4768 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
4774 int saveherefd = herefd;
4775 struct nodelist *saveargbackq = argbackq;
4779 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
4780 STACKSTRNUL(expdest);
4781 herefd = saveherefd;
4782 argbackq = saveargbackq;
4783 startp = stackblock() + startloc;
4785 str = stackblock() + strloc;
4789 setvar(str, startp, 0);
4790 amount = startp - expdest;
4791 STADJUST(amount, expdest);
4798 if (*p != CTLENDVAR) {
4799 out2fmt(snlfmt, startp);
4800 error((char *)NULL);
4802 error("%.*s: parameter %snot set", p - str - 1,
4803 str, (varflags & VSNUL) ? "null or "
4808 for (loc = startp; loc < str; loc++) {
4811 if (patmatch2(str, startp, quotes))
4814 if (quotes && *loc == CTLESC)
4820 for (loc = str - 1; loc >= startp;) {
4823 if (patmatch2(str, startp, quotes))
4827 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4828 for (q = startp; q < loc; q++)
4838 for (loc = str - 1; loc >= startp;) {
4839 if (patmatch2(str, loc, quotes))
4842 if (quotes && loc > startp && *(loc - 1) == CTLESC) {
4843 for (q = startp; q < loc; q++)
4852 case VSTRIMRIGHTMAX:
4853 for (loc = startp; loc < str - 1; loc++) {
4854 if (patmatch2(str, loc, quotes))
4856 if (quotes && *loc == CTLESC)
4869 amount = ((str - 1) - (loc - startp)) - expdest;
4870 STADJUST(amount, expdest);
4871 while (loc != str - 1)
4876 amount = loc - expdest;
4877 STADJUST(amount, expdest);
4878 STPUTC('\0', expdest);
4879 STADJUST(-1, expdest);
4885 * Test whether a specialized variable is set.
4889 varisset(char *name, int nulok)
4892 return backgndpid != -1;
4893 else if (*name == '@' || *name == '*') {
4894 if (*shellparam.p == NULL)
4900 for (av = shellparam.p; *av; av++)
4905 } else if (is_digit(*name)) {
4907 int num = atoi(name);
4909 if (num > shellparam.nparam)
4915 ap = shellparam.p[num - 1];
4917 if (nulok && (ap == NULL || *ap == '\0'))
4924 * Put a string on the stack.
4928 strtodest(const char *p, int syntax, int quotes)
4931 if (quotes && SIT(*p,syntax) == CCTL)
4932 STPUTC(CTLESC, expdest);
4933 STPUTC(*p++, expdest);
4938 * Add the value of a specialized variable to the stack string.
4942 varvalue(char *name, int quoted, int flags)
4951 int allow_split = flags & EXP_FULL;
4952 int quotes = flags & (EXP_FULL | EXP_CASE);
4954 syntax = quoted ? DQSYNTAX : BASESYNTAX;
4963 num = shellparam.nparam;
4968 expdest = cvtnum(num, expdest);
4971 for (i = 0 ; i < NOPTS ; i++) {
4973 STPUTC(optent_letter(optlist[i]), expdest);
4977 if (allow_split && quoted) {
4978 sep = 1 << CHAR_BIT;
4983 sep = ifsset() ? ifsval()[0] : ' ';
4985 sepq = SIT(sep,syntax) == CCTL;
4988 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
4989 strtodest(p, syntax, quotes);
4992 STPUTC(CTLESC, expdest);
4993 STPUTC(sep, expdest);
4998 strtodest(arg0, syntax, quotes);
5002 if (num > 0 && num <= shellparam.nparam) {
5003 strtodest(shellparam.p[num - 1], syntax, quotes);
5011 * Record the fact that we have to scan this region of the
5012 * string for IFS characters.
5016 recordregion(int start, int end, int nulonly)
5018 struct ifsregion *ifsp;
5020 if (ifslastp == NULL) {
5024 ifsp = (struct ifsregion *)xmalloc(sizeof (struct ifsregion));
5026 ifslastp->next = ifsp;
5030 ifslastp->begoff = start;
5031 ifslastp->endoff = end;
5032 ifslastp->nulonly = nulonly;
5038 * Break the argument string into pieces based upon IFS and add the
5039 * strings to the argument list. The regions of the string to be
5040 * searched for IFS characters have been stored by recordregion.
5043 ifsbreakup(char *string, struct arglist *arglist)
5045 struct ifsregion *ifsp;
5050 const char *ifs, *realifs;
5058 realifs = ifsset() ? ifsval() : defifs;
5059 if (ifslastp != NULL) {
5062 p = string + ifsp->begoff;
5063 nulonly = ifsp->nulonly;
5064 ifs = nulonly ? nullstr : realifs;
5066 while (p < string + ifsp->endoff) {
5070 if (strchr(ifs, *p)) {
5072 ifsspc = (strchr(defifs, *p) != NULL);
5073 /* Ignore IFS whitespace at start */
5074 if (q == start && ifsspc) {
5080 sp = (struct strlist *)stalloc(sizeof *sp);
5082 *arglist->lastp = sp;
5083 arglist->lastp = &sp->next;
5087 if (p >= string + ifsp->endoff) {
5093 if (strchr(ifs, *p) == NULL ) {
5096 } else if (strchr(defifs, *p) == NULL) {
5112 } while ((ifsp = ifsp->next) != NULL);
5113 if (!(*start || (!ifsspc && start > string && nulonly))) {
5118 sp = (struct strlist *)stalloc(sizeof *sp);
5120 *arglist->lastp = sp;
5121 arglist->lastp = &sp->next;
5127 while (ifsfirst.next != NULL) {
5128 struct ifsregion *ifsp;
5130 ifsp = ifsfirst.next->next;
5131 ckfree(ifsfirst.next);
5132 ifsfirst.next = ifsp;
5136 ifsfirst.next = NULL;
5140 * Add a file name to the list.
5144 addfname(const char *name)
5148 sp = (struct strlist *)stalloc(sizeof *sp);
5149 sp->text = sstrdup(name);
5151 exparg.lastp = &sp->next;
5155 * Expand shell metacharacters. At this point, the only control characters
5156 * should be escapes. The results are stored in the list exparg.
5159 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN)
5161 expandmeta(struct strlist *str, int flag)
5165 /* TODO - EXP_REDIR */
5170 p = preglob(str->text);
5172 switch (glob(p, 0, 0, &pglob)) {
5174 if(pglob.gl_pathv[1]==0 && !strcmp(p, pglob.gl_pathv[0]))
5185 *exparg.lastp = str;
5186 rmescapes(str->text);
5187 exparg.lastp = &str->next;
5189 default: /* GLOB_NOSPACE */
5190 error("Out of space");
5198 * Add the result of glob(3) to the list.
5202 addglob(const glob_t *pglob)
5204 char **p = pglob->gl_pathv;
5212 #else /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5213 static char *expdir;
5217 expandmeta(struct strlist *str, int flag)
5220 struct strlist **savelastp;
5223 /* TODO - EXP_REDIR */
5229 for (;;) { /* fast check for meta chars */
5230 if ((c = *p++) == '\0')
5232 if (c == '*' || c == '?' || c == '[' || c == '!')
5235 savelastp = exparg.lastp;
5237 if (expdir == NULL) {
5238 int i = strlen(str->text);
5239 expdir = xmalloc(i < 2048 ? 2048 : i); /* XXX */
5242 expmeta(expdir, str->text);
5246 if (exparg.lastp == savelastp) {
5251 *exparg.lastp = str;
5252 rmescapes(str->text);
5253 exparg.lastp = &str->next;
5255 *exparg.lastp = NULL;
5256 *savelastp = sp = expsort(*savelastp);
5257 while (sp->next != NULL)
5259 exparg.lastp = &sp->next;
5267 * Do metacharacter (i.e. *, ?, [...]) expansion.
5271 expmeta(char *enddir, char *name)
5287 for (p = name ; ; p++) {
5288 if (*p == '*' || *p == '?')
5290 else if (*p == '[') {
5295 while (*q == CTLQUOTEMARK)
5299 if (*q == '/' || *q == '\0')
5306 } else if (*p == '!' && p[1] == '!' && (p == name || p[-1] == '/')) {
5308 } else if (*p == '\0')
5310 else if (*p == CTLQUOTEMARK)
5312 else if (*p == CTLESC)
5320 if (metaflag == 0) { /* we've reached the end of the file name */
5321 if (enddir != expdir)
5323 for (p = name ; ; p++) {
5324 if (*p == CTLQUOTEMARK)
5332 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5337 if (start != name) {
5340 while (*p == CTLQUOTEMARK)
5347 if (enddir == expdir) {
5349 } else if (enddir == expdir + 1 && *expdir == '/') {
5355 if ((dirp = opendir(cp)) == NULL)
5357 if (enddir != expdir)
5359 if (*endname == 0) {
5367 while (*p == CTLQUOTEMARK)
5373 while (! int_pending() && (dp = readdir(dirp)) != NULL) {
5374 if (dp->d_name[0] == '.' && ! matchdot)
5376 if (patmatch(start, dp->d_name, 0)) {
5378 strcpy(enddir, dp->d_name);
5381 for (p = enddir, cp = dp->d_name;
5382 (*p++ = *cp++) != '\0';)
5385 expmeta(p, endname);
5393 #endif /* defined(__GLIBC__) && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN) */
5397 #if !(defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN) && !defined(GLOB_BROKEN))
5399 * Sort the results of file name expansion. It calculates the number of
5400 * strings to sort and then calls msort (short for merge sort) to do the
5404 static struct strlist *
5405 expsort(struct strlist *str)
5411 for (sp = str ; sp ; sp = sp->next)
5413 return msort(str, len);
5417 static struct strlist *
5418 msort(struct strlist *list, int len)
5420 struct strlist *p, *q = NULL;
5421 struct strlist **lpp;
5429 for (n = half ; --n >= 0 ; ) {
5433 q->next = NULL; /* terminate first half of list */
5434 q = msort(list, half); /* sort first half of list */
5435 p = msort(p, len - half); /* sort second half */
5438 if (strcmp(p->text, q->text) < 0) {
5441 if ((p = *lpp) == NULL) {
5448 if ((q = *lpp) == NULL) {
5461 * Returns true if the pattern matches the string.
5464 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5465 /* squoted: string might have quote chars */
5467 patmatch(char *pattern, char *string, int squoted)
5472 p = preglob(pattern);
5473 q = squoted ? _rmescapes(string, RMESCAPE_ALLOC) : string;
5475 return !fnmatch(p, q, 0);
5480 patmatch2(char *pattern, char *string, int squoted)
5486 p = grabstackstr(expdest);
5487 res = patmatch(pattern, string, squoted);
5488 ungrabstackstr(p, expdest);
5493 patmatch(char *pattern, char *string, int squoted) {
5494 return pmatch(pattern, string, squoted);
5499 pmatch(char *pattern, char *string, int squoted)
5511 if (squoted && *q == CTLESC)
5519 if (squoted && *q == CTLESC)
5526 while (c == CTLQUOTEMARK || c == '*')
5528 if (c != CTLESC && c != CTLQUOTEMARK &&
5529 c != '?' && c != '*' && c != '[') {
5531 if (squoted && *q == CTLESC &&
5536 if (squoted && *q == CTLESC)
5542 if (pmatch(p, q, squoted))
5544 if (squoted && *q == CTLESC)
5546 } while (*q++ != '\0');
5557 while (*endp == CTLQUOTEMARK)
5560 goto dft; /* no matching ] */
5561 if (*endp == CTLESC)
5573 if (squoted && chr == CTLESC)
5579 if (c == CTLQUOTEMARK)
5583 if (*p == '-' && p[1] != ']') {
5585 while (*p == CTLQUOTEMARK)
5589 if (chr >= c && chr <= *p)
5596 } while ((c = *p++) != ']');
5597 if (found == invert)
5602 if (squoted && *q == CTLESC)
5619 * Remove any CTLESC characters from a string.
5622 #if defined(__GLIBC__) && __GLIBC__ >= 2 && !defined(FNMATCH_BROKEN)
5624 _rmescapes(char *str, int flag)
5627 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5629 p = strpbrk(str, qchars);
5635 if (flag & RMESCAPE_ALLOC) {
5636 size_t len = p - str;
5637 q = r = stalloc(strlen(p) + len + 1);
5639 memcpy(q, str, len);
5644 if (*p == CTLQUOTEMARK) {
5650 if (flag & RMESCAPE_GLOB && *p != '/') {
5661 rmescapes(char *str)
5666 while (*p != CTLESC && *p != CTLQUOTEMARK) {
5672 if (*p == CTLQUOTEMARK) {
5687 * See if a pattern matches in a case statement.
5691 casematch(union node *pattern, const char *val)
5693 struct stackmark smark;
5697 setstackmark(&smark);
5698 argbackq = pattern->narg.backquote;
5699 STARTSTACKSTR(expdest);
5701 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5702 STPUTC('\0', expdest);
5703 p = grabstackstr(expdest);
5704 result = patmatch(p, (char *)val, 0);
5705 popstackmark(&smark);
5714 cvtnum(int num, char *buf)
5718 CHECKSTRSPACE(32, buf);
5719 len = sprintf(buf, "%d", num);
5724 * Editline and history functions (and glue).
5726 static int histcmd(int argc, char **argv)
5728 error("not compiled with history support");
5734 struct redirtab *next;
5735 short renamed[10]; /* Current ash support only 0-9 descriptors */
5736 /* char on arm (and others) can't be negative */
5739 static struct redirtab *redirlist;
5741 extern char **environ;
5746 * Initialization code.
5760 basepf.nextc = basepf.buf = basebuf;
5769 for (envp = environ ; *envp ; envp++) {
5770 if (strchr(*envp, '=')) {
5771 setvareq(*envp, VEXPORT|VTEXTFIXED);
5775 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
5776 setvar("PPID", ppid, 0);
5783 * This routine is called when an error or an interrupt occurs in an
5784 * interactive shell and control is returned to the main command loop.
5787 /* 1 == check for aliases, 2 == also check for assignments */
5788 static int checkalias; /* also used in no alias mode for check assignments */
5802 if (exception != EXSHELLPROC)
5803 parselleft = parsenleft = 0; /* clear input buffer */
5807 /* from parser.c: */
5825 * This file implements the input routines used by the parser.
5828 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5829 static const char * cmdedit_prompt;
5830 static inline void putprompt(const char *s) {
5834 static inline void putprompt(const char *s) {
5839 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5844 * Same as pgetc(), but ignores PEOA.
5854 } while (c == PEOA);
5858 static inline int pgetc2() { return pgetc_macro(); }
5862 * Read a line from the script.
5865 static inline char *
5866 pfgets(char *line, int len)
5872 while (--nleft > 0) {
5891 char *buf = parsefile->buf;
5895 #ifdef CONFIG_FEATURE_COMMAND_EDITING
5897 if (!iflag || parsefile->fd)
5898 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5900 nr = cmdedit_read_input((char*)cmdedit_prompt, buf);
5904 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
5908 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
5909 int flags = fcntl(0, F_GETFL, 0);
5910 if (flags >= 0 && flags & O_NONBLOCK) {
5911 flags &=~ O_NONBLOCK;
5912 if (fcntl(0, F_SETFL, flags) >= 0) {
5913 out2str("sh: turning off NDELAY mode\n");
5925 struct strpush *sp = parsefile->strpush;
5930 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
5935 if (sp->string != sp->ap->val) {
5939 sp->ap->flag &= ~ALIASINUSE;
5940 if (sp->ap->flag & ALIASDEAD) {
5941 unalias(sp->ap->name);
5945 parsenextc = sp->prevstring;
5946 parsenleft = sp->prevnleft;
5947 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
5948 parsefile->strpush = sp->prev;
5949 if (sp != &(parsefile->basestrpush))
5956 * Refill the input buffer and return the next input character:
5958 * 1) If a string was pushed back on the input, pop it;
5959 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
5960 * from a string so we can't refill the buffer, return EOF.
5961 * 3) If the is more stuff in this buffer, use it else call read to fill it.
5962 * 4) Process input up to the next newline, deleting nul characters.
5972 while (parsefile->strpush) {
5974 if (parsenleft == -1 && parsefile->strpush->ap &&
5975 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
5980 if (--parsenleft >= 0)
5981 return (*parsenextc++);
5983 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
5988 if (parselleft <= 0) {
5989 if ((parselleft = preadfd()) <= 0) {
5990 parselleft = parsenleft = EOF_NLEFT;
5997 /* delete nul characters */
5998 for (more = 1; more;) {
6006 parsenleft = q - parsenextc;
6007 more = 0; /* Stop processing here */
6013 if (--parselleft <= 0 && more) {
6014 parsenleft = q - parsenextc - 1;
6025 out2str(parsenextc);
6030 return *parsenextc++;
6035 * Push a string back onto the input at this current parsefile level.
6036 * We handle aliases this way.
6039 pushstring(char *s, int len, void *ap)
6044 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6045 if (parsefile->strpush) {
6046 sp = xmalloc(sizeof (struct strpush));
6047 sp->prev = parsefile->strpush;
6048 parsefile->strpush = sp;
6050 sp = parsefile->strpush = &(parsefile->basestrpush);
6051 sp->prevstring = parsenextc;
6052 sp->prevnleft = parsenleft;
6054 sp->ap = (struct alias *)ap;
6056 ((struct alias *)ap)->flag |= ALIASINUSE;
6067 * Like setinputfile, but takes input from a string.
6071 setinputstring(char *string)
6075 parsenextc = string;
6076 parsenleft = strlen(string);
6077 parsefile->buf = NULL;
6085 * To handle the "." command, a stack of input files is used. Pushfile
6086 * adds a new entry to the stack and popfile restores the previous level.
6092 struct parsefile *pf;
6094 parsefile->nleft = parsenleft;
6095 parsefile->lleft = parselleft;
6096 parsefile->nextc = parsenextc;
6097 parsefile->linno = plinno;
6098 pf = (struct parsefile *)xmalloc(sizeof (struct parsefile));
6099 pf->prev = parsefile;
6102 pf->basestrpush.prev = NULL;
6107 static void restartjob (struct job *);
6109 static void freejob (struct job *);
6110 static struct job *getjob (const char *);
6111 static int dowait (int, struct job *);
6112 static void waitonint(int);
6116 * We keep track of whether or not fd0 has been redirected. This is for
6117 * background commands, where we want to redirect fd0 to /dev/null only
6118 * if it hasn't already been redirected.
6120 static int fd0_redirected = 0;
6122 /* Return true if fd 0 has already been redirected at least once. */
6124 fd0_redirected_p (void)
6126 return fd0_redirected != 0;
6129 static void dupredirect (const union node *, int, int fd1dup);
6133 * Turn job control on and off.
6135 * Note: This code assumes that the third arg to ioctl is a character
6136 * pointer, which is true on Berkeley systems but not System V. Since
6137 * System V doesn't have job control yet, this isn't a problem now.
6142 static void setjobctl(int enable)
6144 #ifdef OLD_TTY_DRIVER
6148 if (enable == jobctl || rootshell == 0)
6151 do { /* while we are in the background */
6152 #ifdef OLD_TTY_DRIVER
6153 if (ioctl(2, TIOCGPGRP, (char *)&initialpgrp) < 0) {
6155 initialpgrp = tcgetpgrp(2);
6156 if (initialpgrp < 0) {
6158 out2str("sh: can't access tty; job control turned off\n");
6162 if (initialpgrp == -1)
6163 initialpgrp = getpgrp();
6164 else if (initialpgrp != getpgrp()) {
6165 killpg(initialpgrp, SIGTTIN);
6169 #ifdef OLD_TTY_DRIVER
6170 if (ioctl(2, TIOCGETD, (char *)&ldisc) < 0 || ldisc != NTTYDISC) {
6171 out2str("sh: need new tty driver to run job control; job control turned off\n");
6179 setpgid(0, rootpid);
6180 #ifdef OLD_TTY_DRIVER
6181 ioctl(2, TIOCSPGRP, (char *)&rootpid);
6183 tcsetpgrp(2, rootpid);
6185 } else { /* turning job control off */
6186 setpgid(0, initialpgrp);
6187 #ifdef OLD_TTY_DRIVER
6188 ioctl(2, TIOCSPGRP, (char *)&initialpgrp);
6190 tcsetpgrp(2, initialpgrp);
6203 killcmd(int argc, char **argv)
6214 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6215 "kill -l [exitstatus]"
6219 if (*argv[1] == '-') {
6220 signo = decode_signal(argv[1] + 1, 1);
6224 while ((c = nextopt("ls:")) != '\0')
6230 signo = decode_signal(optionarg, 1);
6233 "invalid signal number or name: %s",
6241 "nextopt returned character code 0%o", c);
6248 if (!list && signo < 0)
6251 if ((signo < 0 || !*argptr) ^ list) {
6260 for (i = 1; i < NSIG; i++) {
6261 name = u_signal_names(0, &i, 1);
6267 name = u_signal_names(*argptr, &signo, -1);
6271 error("invalid signal number or exit status: %s",
6277 if (**argptr == '%') {
6278 jp = getjob(*argptr);
6279 if (jp->jobctl == 0)
6280 error("job %s not created under job control",
6282 pid = -jp->ps[0].pid;
6284 pid = atoi(*argptr);
6285 if (kill(pid, signo) != 0)
6286 error("%s: %m", *argptr);
6287 } while (*++argptr);
6293 fgcmd(int argc, char **argv)
6299 jp = getjob(argv[1]);
6300 if (jp->jobctl == 0)
6301 error("job not created under job control");
6302 pgrp = jp->ps[0].pid;
6303 #ifdef OLD_TTY_DRIVER
6304 ioctl(2, TIOCSPGRP, (char *)&pgrp);
6309 status = waitforjob(jp);
6315 bgcmd(int argc, char **argv)
6320 jp = getjob(*++argv);
6321 if (jp->jobctl == 0)
6322 error("job not created under job control");
6324 } while (--argc > 1);
6330 restartjob(struct job *jp)
6332 struct procstat *ps;
6335 if (jp->state == JOBDONE)
6338 killpg(jp->ps[0].pid, SIGCONT);
6339 for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
6340 if (WIFSTOPPED(ps->status)) {
6349 static void showjobs(int change);
6353 jobscmd(int argc, char **argv)
6361 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6362 * statuses have changed since the last call to showjobs.
6364 * If the shell is interrupted in the process of creating a job, the
6365 * result may be a job structure containing zero processes. Such structures
6366 * will be freed here.
6370 showjobs(int change)
6376 struct procstat *ps;
6380 TRACE(("showjobs(%d) called\n", change));
6381 while (dowait(0, (struct job *)NULL) > 0);
6382 for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
6385 if (jp->nprocs == 0) {
6389 if (change && ! jp->changed)
6391 procno = jp->nprocs;
6392 for (ps = jp->ps ; ; ps++) { /* for each process */
6394 snprintf(s, 64, "[%d] %ld ", jobno,
6397 snprintf(s, 64, " %ld ",
6402 if (ps->status == -1) {
6403 /* don't print anything */
6404 } else if (WIFEXITED(ps->status)) {
6405 snprintf(s, 64, "Exit %d",
6406 WEXITSTATUS(ps->status));
6409 if (WIFSTOPPED(ps->status))
6410 i = WSTOPSIG(ps->status);
6411 else /* WIFSIGNALED(ps->status) */
6413 i = WTERMSIG(ps->status);
6414 if ((i & 0x7F) < NSIG && sys_siglist[i & 0x7F])
6415 strcpy(s, sys_siglist[i & 0x7F]);
6417 snprintf(s, 64, "Signal %d", i & 0x7F);
6418 if (WCOREDUMP(ps->status))
6419 strcat(s, " (core dumped)");
6424 "%*c%s\n", 30 - col >= 0 ? 30 - col : 0, ' ',
6431 if (jp->state == JOBDONE) {
6439 * Mark a job structure as unused.
6443 freejob(struct job *jp)
6445 const struct procstat *ps;
6449 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6450 if (ps->cmd != nullstr)
6453 if (jp->ps != &jp->ps0)
6457 if (curjob == jp - jobtab + 1)
6466 waitcmd(int argc, char **argv)
6474 job = getjob(*++argv);
6478 for (;;) { /* loop until process terminated or stopped */
6481 status = job->ps[job->nprocs - 1].status;
6487 if (WIFEXITED(status))
6488 retval = WEXITSTATUS(status);
6490 else if (WIFSTOPPED(status))
6491 retval = WSTOPSIG(status) + 128;
6494 /* XXX: limits number of signals */
6495 retval = WTERMSIG(status) + 128;
6500 for (jp = jobtab ; ; jp++) {
6501 if (jp >= jobtab + njobs) { /* no running procs */
6504 if (jp->used && jp->state == 0)
6508 if (dowait(2, 0) < 0 && errno == EINTR) {
6517 * Convert a job name to a job structure.
6521 getjob(const char *name)
6531 if ((jobno = curjob) == 0 || jobtab[jobno - 1].used == 0)
6532 error("No current job");
6533 return &jobtab[jobno - 1];
6535 error("No current job");
6537 } else if (name[0] == '%') {
6538 if (is_digit(name[1])) {
6539 jobno = number(name + 1);
6540 if (jobno > 0 && jobno <= njobs
6541 && jobtab[jobno - 1].used != 0)
6542 return &jobtab[jobno - 1];
6544 } else if (name[1] == '%' && name[2] == '\0') {
6548 struct job *found = NULL;
6549 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6550 if (jp->used && jp->nprocs > 0
6551 && prefix(name + 1, jp->ps[0].cmd)) {
6553 error("%s: ambiguous", name);
6560 } else if (is_number(name, &pid)) {
6561 for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
6562 if (jp->used && jp->nprocs > 0
6563 && jp->ps[jp->nprocs - 1].pid == pid)
6567 error("No such job: %s", name);
6574 * Return a new job structure,
6578 makejob(const union node *node, int nprocs)
6583 for (i = njobs, jp = jobtab ; ; jp++) {
6587 jobtab = xmalloc(4 * sizeof jobtab[0]);
6589 jp = xmalloc((njobs + 4) * sizeof jobtab[0]);
6590 memcpy(jp, jobtab, njobs * sizeof jp[0]);
6591 /* Relocate `ps' pointers */
6592 for (i = 0; i < njobs; i++)
6593 if (jp[i].ps == &jobtab[i].ps0)
6594 jp[i].ps = &jp[i].ps0;
6598 jp = jobtab + njobs;
6599 for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0);
6612 jp->jobctl = jobctl;
6615 jp->ps = xmalloc(nprocs * sizeof (struct procstat));
6620 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
6627 * Fork of a subshell. If we are doing job control, give the subshell its
6628 * own process group. Jp is a job structure that the job is to be added to.
6629 * N is the command that will be evaluated by the child. Both jp and n may
6630 * be NULL. The mode parameter can be one of the following:
6631 * FORK_FG - Fork off a foreground process.
6632 * FORK_BG - Fork off a background process.
6633 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
6634 * process group even if job control is on.
6636 * When job control is turned off, background processes have their standard
6637 * input redirected to /dev/null (except for the second and later processes
6644 forkshell(struct job *jp, const union node *n, int mode)
6650 const char *devnull = _PATH_DEVNULL;
6651 const char *nullerr = "Can't open %s";
6653 TRACE(("forkshell(%%%d, 0x%lx, %d) called\n", jp - jobtab, (long)n,
6656 #if !defined(__UCLIBC__) || defined(__UCLIBC_HAS_MMU__)
6662 TRACE(("Fork failed, errno=%d\n", errno));
6664 error("Cannot fork");
6671 TRACE(("Child shell %d\n", getpid()));
6672 wasroot = rootshell;
6678 jobctl = 0; /* do job control only in root shell */
6679 if (wasroot && mode != FORK_NOJOB && mflag) {
6680 if (jp == NULL || jp->nprocs == 0)
6683 pgrp = jp->ps[0].pid;
6685 if (mode == FORK_FG) {
6686 /*** this causes superfluous TIOCSPGRPS ***/
6687 #ifdef OLD_TTY_DRIVER
6688 if (ioctl(2, TIOCSPGRP, (char *)&pgrp) < 0)
6689 error("TIOCSPGRP failed, errno=%d", errno);
6691 if (tcsetpgrp(2, pgrp) < 0)
6692 error("tcsetpgrp failed, errno=%d", errno);
6697 } else if (mode == FORK_BG) {
6699 if (mode == FORK_BG) {
6703 if ((jp == NULL || jp->nprocs == 0) &&
6704 ! fd0_redirected_p ()) {
6706 if (open(devnull, O_RDONLY) != 0)
6707 error(nullerr, devnull);
6710 for (i = njobs, p = jobtab ; --i >= 0 ; p++)
6713 if (wasroot && iflag) {
6721 if (rootshell && mode != FORK_NOJOB && mflag) {
6722 if (jp == NULL || jp->nprocs == 0)
6725 pgrp = jp->ps[0].pid;
6729 if (mode == FORK_BG)
6730 backgndpid = pid; /* set $! */
6732 struct procstat *ps = &jp->ps[jp->nprocs++];
6736 if (iflag && rootshell && n)
6737 ps->cmd = commandtext(n);
6740 TRACE(("In parent shell: child = %d\n", pid));
6747 * Wait for job to finish.
6749 * Under job control we have the problem that while a child process is
6750 * running interrupts generated by the user are sent to the child but not
6751 * to the shell. This means that an infinite loop started by an inter-
6752 * active user may be hard to kill. With job control turned off, an
6753 * interactive user may place an interactive program inside a loop. If
6754 * the interactive program catches interrupts, the user doesn't want
6755 * these interrupts to also abort the loop. The approach we take here
6756 * is to have the shell ignore interrupt signals while waiting for a
6757 * forground process to terminate, and then send itself an interrupt
6758 * signal if the child process was terminated by an interrupt signal.
6759 * Unfortunately, some programs want to do a bit of cleanup and then
6760 * exit on interrupt; unless these processes terminate themselves by
6761 * sending a signal to themselves (instead of calling exit) they will
6762 * confuse this approach.
6766 waitforjob(struct job *jp)
6769 int mypgrp = getpgrp();
6773 struct sigaction act, oact;
6782 sigaction(SIGINT, 0, &act);
6783 act.sa_handler = waitonint;
6784 sigaction(SIGINT, &act, &oact);
6786 TRACE(("waitforjob(%%%d) called\n", jp - jobtab + 1));
6787 while (jp->state == 0) {
6795 sigaction(SIGINT, &oact, 0);
6796 if (intreceived && trap[SIGINT]) kill(getpid(), SIGINT);
6800 #ifdef OLD_TTY_DRIVER
6801 if (ioctl(2, TIOCSPGRP, (char *)&mypgrp) < 0)
6802 error("TIOCSPGRP failed, errno=%d\n", errno);
6804 if (tcsetpgrp(2, mypgrp) < 0)
6805 error("tcsetpgrp failed, errno=%d\n", errno);
6808 if (jp->state == JOBSTOPPED)
6809 curjob = jp - jobtab + 1;
6811 status = jp->ps[jp->nprocs - 1].status;
6812 /* convert to 8 bits */
6813 if (WIFEXITED(status))
6814 st = WEXITSTATUS(status);
6816 else if (WIFSTOPPED(status))
6817 st = WSTOPSIG(status) + 128;
6820 st = WTERMSIG(status) + 128;
6824 * This is truly gross.
6825 * If we're doing job control, then we did a TIOCSPGRP which
6826 * caused us (the shell) to no longer be in the controlling
6827 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
6828 * intuit from the subprocess exit status whether a SIGINT
6829 * occured, and if so interrupt ourselves. Yuck. - mycroft
6831 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
6834 if (jp->state == JOBDONE)
6845 * Wait for a process to terminate.
6849 * Do a wait system call. If job control is compiled in, we accept
6850 * stopped processes. If block is zero, we return a value of zero
6851 * rather than blocking.
6853 * System V doesn't have a non-blocking wait system call. It does
6854 * have a SIGCLD signal that is sent to a process when one of it's
6855 * children dies. The obvious way to use SIGCLD would be to install
6856 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
6857 * was received, and have waitproc bump another counter when it got
6858 * the status of a process. Waitproc would then know that a wait
6859 * system call would not block if the two counters were different.
6860 * This approach doesn't work because if a process has children that
6861 * have not been waited for, System V will send it a SIGCLD when it
6862 * installs a signal handler for SIGCLD. What this means is that when
6863 * a child exits, the shell will be sent SIGCLD signals continuously
6864 * until is runs out of stack space, unless it does a wait call before
6865 * restoring the signal handler. The code below takes advantage of
6866 * this (mis)feature by installing a signal handler for SIGCLD and
6867 * then checking to see whether it was called. If there are any
6868 * children to be waited for, it will be.
6873 waitproc(int block, int *status)
6884 return wait3(status, flags, (struct rusage *)NULL);
6888 dowait(int block, struct job *job)
6892 struct procstat *sp;
6894 struct job *thisjob;
6900 TRACE(("dowait(%d) called\n", block));
6902 pid = waitproc(block, &status);
6903 TRACE(("wait returns %d, status=%d\n", pid, status));
6904 } while (!(block & 2) && pid == -1 && errno == EINTR);
6909 for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
6913 for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
6916 if (sp->pid == pid) {
6917 TRACE(("Changing status of proc %d from 0x%x to 0x%x\n", pid, sp->status, status));
6918 sp->status = status;
6921 if (sp->status == -1)
6923 else if (WIFSTOPPED(sp->status))
6926 if (stopped) { /* stopped or done */
6927 int state = done? JOBDONE : JOBSTOPPED;
6928 if (jp->state != state) {
6929 TRACE(("Job %d: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
6932 if (done && curjob == jp - jobtab + 1)
6933 curjob = 0; /* no current job */
6940 if (! rootshell || ! iflag || (job && thisjob == job)) {
6941 core = WCOREDUMP(status);
6943 if (WIFSTOPPED(status)) sig = WSTOPSIG(status);
6946 if (WIFEXITED(status)) sig = 0;
6947 else sig = WTERMSIG(status);
6949 if (sig != 0 && sig != SIGINT && sig != SIGPIPE) {
6951 out2fmt("%d: ", pid);
6953 if (sig == SIGTSTP && rootshell && iflag)
6955 (long)(job - jobtab + 1));
6957 if (sig < NSIG && sys_siglist[sig])
6958 out2str(sys_siglist[sig]);
6960 out2fmt("Signal %d", sig);
6962 out2str(" - core dumped");
6965 TRACE(("Not printing status: status=%d, sig=%d\n",
6969 TRACE(("Not printing status, rootshell=%d, job=0x%x\n", rootshell, job));
6971 thisjob->changed = 1;
6980 * return 1 if there are stopped jobs, otherwise 0
6990 for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
6993 if (jp->state == JOBSTOPPED) {
6994 out2str("You have stopped jobs.\n");
7004 * Return a string identifying a command (to be printed by the
7008 static char *cmdnextc;
7009 static int cmdnleft;
7010 #define MAXCMDTEXT 200
7013 cmdputs(const char *s)
7024 while ((c = *p++) != '\0') {
7027 else if (c == CTLVAR) {
7032 } else if (c == '=' && subtype != 0) {
7033 *q++ = "}-+?="[(subtype & VSTYPE) - VSNORMAL];
7035 } else if (c == CTLENDVAR) {
7037 } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE)
7038 cmdnleft++; /* ignore it */
7041 if (--cmdnleft <= 0) {
7051 #define CMDTXT_TABLE
7054 * To collect a lot of redundant code in cmdtxt() case statements, we
7055 * implement a mini language here. Each type of node struct has an
7056 * associated instruction sequence that operates on its members via
7057 * their offsets. The instruction are pack in unsigned chars with
7058 * format IIDDDDDE where the bits are
7059 * I : part of the instruction opcode, which are
7060 * 00 : member is a pointer to another node -- process it recursively
7061 * 40 : member is a pointer to a char string -- output it
7062 * 80 : output the string whose index is stored in the data field
7063 * CC : flag signaling that this case needs external processing
7064 * D : data - either the (shifted) index of a fixed string to output or
7065 * the actual offset of the member to operate on in the struct
7066 * (since we assume bit 0 is set, the offset is not shifted)
7067 * E : flag signaling end of instruction sequence
7069 * WARNING: In order to handle larger offsets for 64bit archs, this code
7070 * assumes that no offset can be an odd number and stores the
7071 * end-of-instructions flag in bit 0.
7074 #define CMDTXT_NOMORE 0x01 /* NOTE: no offset should be odd */
7075 #define CMDTXT_CHARPTR 0x40
7076 #define CMDTXT_STRING 0x80
7077 #define CMDTXT_SPECIAL 0xC0
7078 #define CMDTXT_OFFSETMASK 0x3E
7080 static const char * const cmdtxt_strings[] = {
7081 /* 0 1 2 3 4 5 6 7 */
7082 "; ", "(", ")", " && ", " || ", "if ", "; then ", "...",
7083 /* 8 9 10 11 12 13 */
7084 "while ", "; do ", "; done", "until ", "for ", " in ...",
7086 "case ", "???", "() ...", "<<..."
7089 static const char * const redir_strings[] = {
7090 ">", "<", "<>", ">>", ">|", ">&", "<&"
7093 static const unsigned char cmdtxt_ops[] = {
7094 #define CMDTXT_NSEMI 0
7095 offsetof(union node, nbinary.ch1),
7097 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7098 #define CMDTXT_NCMD (CMDTXT_NSEMI + 3)
7099 #define CMDTXT_NPIPE (CMDTXT_NCMD)
7100 #define CMDTXT_NCASE (CMDTXT_NCMD)
7101 #define CMDTXT_NTO (CMDTXT_NCMD)
7102 #define CMDTXT_NFROM (CMDTXT_NCMD)
7103 #define CMDTXT_NFROMTO (CMDTXT_NCMD)
7104 #define CMDTXT_NAPPEND (CMDTXT_NCMD)
7105 #define CMDTXT_NTOOV (CMDTXT_NCMD)
7106 #define CMDTXT_NTOFD (CMDTXT_NCMD)
7107 #define CMDTXT_NFROMFD (CMDTXT_NCMD)
7109 #define CMDTXT_NREDIR (CMDTXT_NPIPE + 1)
7110 #define CMDTXT_NBACKGND (CMDTXT_NREDIR)
7111 offsetof(union node, nredir.n)|CMDTXT_NOMORE,
7112 #define CMDTXT_NSUBSHELL (CMDTXT_NBACKGND + 1)
7113 (1*2)|CMDTXT_STRING,
7114 offsetof(union node, nredir.n),
7115 (2*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7116 #define CMDTXT_NAND (CMDTXT_NSUBSHELL + 3)
7117 offsetof(union node, nbinary.ch1),
7118 (3*2)|CMDTXT_STRING,
7119 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7120 #define CMDTXT_NOR (CMDTXT_NAND + 3)
7121 offsetof(union node, nbinary.ch1),
7122 (4*2)|CMDTXT_STRING,
7123 offsetof(union node, nbinary.ch2)|CMDTXT_NOMORE,
7124 #define CMDTXT_NIF (CMDTXT_NOR + 3)
7125 (5*2)|CMDTXT_STRING,
7126 offsetof(union node, nif.test),
7127 (6*2)|CMDTXT_STRING,
7128 offsetof(union node, nif.ifpart),
7129 (7*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7130 #define CMDTXT_NWHILE (CMDTXT_NIF + 5)
7131 (8*2)|CMDTXT_STRING,
7132 offsetof(union node, nbinary.ch1),
7133 (9*2)|CMDTXT_STRING,
7134 offsetof(union node, nbinary.ch2),
7135 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7136 #define CMDTXT_NUNTIL (CMDTXT_NWHILE + 5)
7137 (11*2)|CMDTXT_STRING,
7138 offsetof(union node, nbinary.ch1),
7139 (9*2)|CMDTXT_STRING,
7140 offsetof(union node, nbinary.ch2),
7141 (10*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7142 #define CMDTXT_NFOR (CMDTXT_NUNTIL + 5)
7143 (12*2)|CMDTXT_STRING,
7144 offsetof(union node, nfor.var)|CMDTXT_CHARPTR,
7145 (13*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7146 #define CMDTXT_NCLIST (CMDTXT_NFOR + 3) /* TODO: IS THIS CORRECT??? */
7147 #define CMDTXT_NNOT (CMDTXT_NCLIST) /* TODO: IS THIS CORRECT??? */
7148 (15*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7149 #define CMDTXT_NDEFUN (CMDTXT_NCLIST + 1)
7150 offsetof(union node, narg.text)|CMDTXT_CHARPTR,
7151 (16*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7152 #define CMDTXT_NARG (CMDTXT_NDEFUN + 2)
7153 offsetof(union node, narg.text)|CMDTXT_CHARPTR|CMDTXT_NOMORE,
7154 #define CMDTXT_NHERE (CMDTXT_NARG + 1)
7155 #define CMDTXT_NXHERE (CMDTXT_NHERE)
7156 (17*2)|CMDTXT_STRING|CMDTXT_NOMORE,
7159 #if CMDTXT_NXHERE != 36
7160 #error CMDTXT_NXHERE
7163 static const unsigned char cmdtxt_ops_index[26] = {
7193 cmdtxt(const union node *n)
7200 p = cmdtxt_ops + (int) cmdtxt_ops_index[n->type];
7201 if ((*p & CMDTXT_SPECIAL) != CMDTXT_SPECIAL) { /* normal case */
7203 if (*p & CMDTXT_STRING) { /* output fixed string */
7204 cmdputs(cmdtxt_strings[((int)(*p & CMDTXT_OFFSETMASK) >> 1)]);
7206 const char *pf = ((const char *) n)
7207 + ((int)(*p & CMDTXT_OFFSETMASK));
7208 if (*p & CMDTXT_CHARPTR) { /* output dynamic string */
7209 cmdputs(*((const char **) pf));
7210 } else { /* output field */
7211 cmdtxt(*((const union node **) pf));
7214 } while (!(*p++ & CMDTXT_NOMORE));
7215 } else if (n->type == NCMD) {
7217 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7222 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7226 } else if (n->type == NPIPE) {
7227 struct nodelist *lp;
7228 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7233 } else if (n->type == NCASE) {
7234 cmdputs(cmdtxt_strings[14]);
7235 cmdputs(n->ncase.expr->narg.text);
7236 cmdputs(cmdtxt_strings[13]);
7238 #if (NTO != 16) || (NFROM != 17) || (NFROMTO != 18) || (NAPPEND != 19) || (NTOOV != 20) || (NTOFD != 21) || (NFROMFD != 22)
7239 #error Assumption violated regarding range and ordering of NTO ... NFROMFD!
7244 assert((n->type >= NTO) && (n->type <= NFROMFD));
7247 p = redir_strings[n->type - NTO];
7248 if (n->nfile.fd != ('>' == *p)) {
7249 s[0] = n->nfile.fd + '0';
7254 if (n->type >= NTOFD) {
7255 s[0] = n->ndup.dupfd + '0';
7259 cmdtxt(n->nfile.fname);
7263 #else /* CMDTXT_TABLE */
7265 cmdtxt(const union node *n)
7268 struct nodelist *lp;
7277 cmdtxt(n->nbinary.ch1);
7279 cmdtxt(n->nbinary.ch2);
7282 cmdtxt(n->nbinary.ch1);
7284 cmdtxt(n->nbinary.ch2);
7287 cmdtxt(n->nbinary.ch1);
7289 cmdtxt(n->nbinary.ch2);
7292 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
7300 cmdtxt(n->nredir.n);
7305 cmdtxt(n->nredir.n);
7309 cmdtxt(n->nif.test);
7311 cmdtxt(n->nif.ifpart);
7320 cmdtxt(n->nbinary.ch1);
7322 cmdtxt(n->nbinary.ch2);
7327 cmdputs(n->nfor.var);
7332 cmdputs(n->ncase.expr->narg.text);
7336 cmdputs(n->narg.text);
7340 for (np = n->ncmd.args ; np ; np = np->narg.next) {
7345 for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
7351 cmdputs(n->narg.text);
7354 p = ">"; i = 1; goto redir;
7356 p = ">>"; i = 1; goto redir;
7358 p = ">&"; i = 1; goto redir;
7360 p = ">|"; i = 1; goto redir;
7362 p = "<"; i = 0; goto redir;
7364 p = "<&"; i = 0; goto redir;
7366 p = "<>"; i = 0; goto redir;
7368 if (n->nfile.fd != i) {
7369 s[0] = n->nfile.fd + '0';
7374 if (n->type == NTOFD || n->type == NFROMFD) {
7375 s[0] = n->ndup.dupfd + '0';
7379 cmdtxt(n->nfile.fname);
7391 #endif /* CMDTXT_TABLE */
7394 commandtext(const union node *n)
7398 cmdnextc = name = xmalloc(MAXCMDTEXT);
7399 cmdnleft = MAXCMDTEXT - 4;
7406 static void waitonint(int sig) {
7414 * Routines to check for mail.
7418 #define MAXMBOXES 10
7421 static int nmboxes; /* number of mailboxes */
7422 static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
7427 * Print appropriate message(s) if mail has arrived. If the argument is
7428 * nozero, then the value of MAIL has changed, so we just update the
7439 struct stackmark smark;
7446 setstackmark(&smark);
7447 mpath = mpathset()? mpathval() : mailval();
7448 for (i = 0 ; i < nmboxes ; i++) {
7449 p = padvance(&mpath, nullstr);
7454 for (q = p ; *q ; q++);
7459 q[-1] = '\0'; /* delete trailing '/' */
7460 if (stat(p, &statb) < 0)
7462 if (statb.st_size > mailtime[i] && ! silent) {
7464 pathopt? pathopt : "you have mail");
7466 mailtime[i] = statb.st_size;
7469 popstackmark(&smark);
7472 #endif /* ASH_MAIL */
7477 static short profile_buf[16384];
7481 static void read_profile (const char *);
7482 static void cmdloop (int);
7483 static void options (int);
7484 static void setoption (int, int);
7485 static void procargs (int, char **);
7489 * Main routine. We initialize things, parse the arguments, execute
7490 * profiles if we're a login shell, and then call cmdloop to execute
7491 * commands. The setjmp call sets up the location to jump to when an
7492 * exception occurs. When an exception occurs the variable "state"
7493 * is used to figure out how far we had gotten.
7497 ash_main(int argc, char **argv)
7499 struct jmploc jmploc;
7500 struct stackmark smark;
7504 BLTINCMD = find_builtin("builtin");
7505 EXECCMD = find_builtin("exec");
7506 EVALCMD = find_builtin("eval");
7508 #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
7514 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7516 #if defined(linux) || defined(__GNU__)
7517 signal(SIGCHLD, SIG_DFL);
7520 if (setjmp(jmploc.loc)) {
7523 * When a shell procedure is executed, we raise the
7524 * exception EXSHELLPROC to clean up before executing
7525 * the shell procedure.
7527 if (exception == EXSHELLPROC) {
7533 if (exception == EXEXEC) {
7534 exitstatus = exerrno;
7535 } else if (exception == EXERROR) {
7538 if (state == 0 || iflag == 0 || ! rootshell)
7539 exitshell(exitstatus);
7542 if (exception == EXINT) {
7545 popstackmark(&smark);
7546 FORCEINTON; /* enable interrupts */
7549 else if (state == 2)
7551 else if (state == 3)
7559 trputs("Shell args: "); trargs(argv);
7564 setstackmark(&smark);
7565 procargs(argc, argv);
7566 if (argv[0] && argv[0][0] == '-') {
7568 read_profile("/etc/profile");
7571 read_profile(".profile");
7576 if (getuid() == geteuid() && getgid() == getegid()) {
7578 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7580 read_profile(shinit);
7587 if (sflag == 0 || minusc) {
7588 static const char sigs[] = {
7589 SIGINT, SIGQUIT, SIGHUP,
7595 #define SIGSSIZE ((sizeof(sigs)/sizeof(sigs[0])) - 1) /* trailing nul */
7598 for (i = 0; i < SIGSSIZE; i++)
7603 evalstring(minusc, 0);
7605 if (sflag || minusc == NULL) {
7606 state4: /* XXX ??? - why isn't this before the "if" statement */
7612 exitshell(exitstatus);
7618 * Read and execute commands. "Top" is nonzero for the top level command
7619 * loop; it turns on prompting if the shell is interactive.
7626 struct stackmark smark;
7630 TRACE(("cmdloop(%d) called\n", top));
7631 setstackmark(&smark);
7644 n = parsecmd(inter);
7645 /* showtree(n); DEBUG */
7647 if (!top || numeof >= 50)
7649 if (!stoppedjobs()) {
7652 out2str("\nUse \"exit\" to leave shell.\n");
7655 } else if (n != NULL && nflag == 0) {
7656 job_warning = (job_warning == 2) ? 1 : 0;
7660 popstackmark(&smark);
7661 setstackmark(&smark);
7662 if (evalskip == SKIPFILE) {
7667 popstackmark(&smark);
7673 * Read /etc/profile or .profile. Return on error.
7677 read_profile(const char *name)
7684 if ((fd = open(name, O_RDONLY)) >= 0)
7689 /* -q turns off -x and -v just when executing init files */
7690 /* Note: Might do a little redundant work, but reduces code size. */
7705 * Read a file containing shell functions.
7709 readcmdfile(const char *name)
7714 if ((fd = open(name, O_RDONLY)) >= 0)
7717 error("Can't open %s", name);
7726 * Take commands from a file. To be compatable we should do a path
7727 * search for the file, which is necessary to find sub-commands.
7730 static inline char *
7731 find_dot_file(char *mybasename)
7734 const char *path = pathval();
7737 /* don't try this for absolute or relative paths */
7738 if (strchr(mybasename, '/'))
7741 while ((fullname = padvance(&path, mybasename)) != NULL) {
7742 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
7744 * Don't bother freeing here, since it will
7745 * be freed by the caller.
7749 stunalloc(fullname);
7752 /* not found in the PATH */
7753 error("%s: not found", mybasename);
7758 dotcmd(int argc, char **argv)
7761 volatile struct shparam saveparam;
7764 for (sp = cmdenviron; sp ; sp = sp->next)
7765 setvareq(xstrdup(sp->text), VSTRFIXED|VTEXTFIXED);
7767 if (argc >= 2) { /* That's what SVR2 does */
7769 struct stackmark smark;
7771 setstackmark(&smark);
7772 fullname = find_dot_file(argv[1]);
7775 saveparam = shellparam;
7776 shellparam.malloc = 0;
7777 shellparam.nparam = argc - 2;
7778 shellparam.p = argv + 2;
7781 setinputfile(fullname, 1);
7782 commandname = fullname;
7787 freeparam(&shellparam);
7788 shellparam = saveparam;
7791 popstackmark(&smark);
7798 exitcmd(int argc, char **argv)
7803 exitstatus = number(argv[1]);
7805 exitstatus = oexitstatus;
7806 exitshell(exitstatus);
7815 nbytes = ALIGN(nbytes);
7816 if (nbytes > stacknleft) {
7818 struct stack_block *sp;
7821 if (blocksize < MINSIZE)
7822 blocksize = MINSIZE;
7824 sp = xmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
7826 stacknxt = sp->space;
7827 stacknleft = blocksize;
7833 stacknleft -= nbytes;
7839 stunalloc(pointer p)
7842 if (p == NULL) { /*DEBUG */
7843 write(2, "stunalloc\n", 10);
7847 if (!(stacknxt >= (char *)p && (char *)p >= stackp->space)) {
7850 stacknleft += stacknxt - (char *)p;
7856 setstackmark(struct stackmark *mark)
7858 mark->stackp = stackp;
7859 mark->stacknxt = stacknxt;
7860 mark->stacknleft = stacknleft;
7861 mark->marknext = markp;
7867 popstackmark(struct stackmark *mark)
7869 struct stack_block *sp;
7872 markp = mark->marknext;
7873 while (stackp != mark->stackp) {
7878 stacknxt = mark->stacknxt;
7879 stacknleft = mark->stacknleft;
7885 * When the parser reads in a string, it wants to stick the string on the
7886 * stack and only adjust the stack pointer when it knows how big the
7887 * string is. Stackblock (defined in stack.h) returns a pointer to a block
7888 * of space on top of the stack and stackblocklen returns the length of
7889 * this block. Growstackblock will grow this space by at least one byte,
7890 * possibly moving it (like realloc). Grabstackblock actually allocates the
7891 * part of the block that has been used.
7895 growstackblock(void) {
7897 int newlen = ALIGN(stacknleft * 2 + 100);
7898 char *oldspace = stacknxt;
7899 int oldlen = stacknleft;
7900 struct stack_block *sp;
7901 struct stack_block *oldstackp;
7903 if (stacknxt == stackp->space && stackp != &stackbase) {
7908 sp = xrealloc((pointer)sp, sizeof(struct stack_block) - MINSIZE + newlen);
7911 stacknxt = sp->space;
7912 stacknleft = newlen;
7914 /* Stack marks pointing to the start of the old block
7915 * must be relocated to point to the new block
7917 struct stackmark *xmark;
7919 while (xmark != NULL && xmark->stackp == oldstackp) {
7920 xmark->stackp = stackp;
7921 xmark->stacknxt = stacknxt;
7922 xmark->stacknleft = stacknleft;
7923 xmark = xmark->marknext;
7928 p = stalloc(newlen);
7929 memcpy(p, oldspace, oldlen);
7930 stacknxt = p; /* free the space */
7931 stacknleft += newlen; /* we just allocated */
7938 grabstackblock(int len)
7948 * The following routines are somewhat easier to use that the above.
7949 * The user declares a variable of type STACKSTR, which may be declared
7950 * to be a register. The macro STARTSTACKSTR initializes things. Then
7951 * the user uses the macro STPUTC to add characters to the string. In
7952 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
7953 * grown as necessary. When the user is done, she can just leave the
7954 * string there and refer to it using stackblock(). Or she can allocate
7955 * the space for it using grabstackstr(). If it is necessary to allow
7956 * someone else to use the stack temporarily and then continue to grow
7957 * the string, the user should use grabstack to allocate the space, and
7958 * then call ungrabstr(p) to return to the previous mode of operation.
7960 * USTPUTC is like STPUTC except that it doesn't check for overflow.
7961 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
7962 * is space for at least one character.
7967 growstackstr(void) {
7968 int len = stackblocksize();
7969 if (herefd >= 0 && len >= 1024) {
7970 xwrite(herefd, stackblock(), len);
7971 sstrnleft = len - 1;
7972 return stackblock();
7975 sstrnleft = stackblocksize() - len - 1;
7976 return stackblock() + len;
7981 * Called from CHECKSTRSPACE.
7985 makestrspace(size_t newlen) {
7986 int len = stackblocksize() - sstrnleft;
7989 sstrnleft = stackblocksize() - len;
7990 } while (sstrnleft < newlen);
7991 return stackblock() + len;
7997 ungrabstackstr(char *s, char *p)
7999 stacknleft += stacknxt - s;
8001 sstrnleft = stacknleft - (p - s);
8004 * Miscelaneous builtins.
8010 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
8011 typedef long rlim_t;
8017 * The read builtin. The -e option causes backslashes to escape the
8018 * following character.
8020 * This uses unbuffered input, which may be avoidable in some cases.
8024 readcmd(int argc, char **argv)
8039 while ((i = nextopt("p:r")) != '\0') {
8045 if (prompt && isatty(0)) {
8046 out2str(prompt); /* read without cmdedit */
8049 if (*(ap = argptr) == NULL)
8051 if ((ifs = bltinlookup("IFS")) == NULL)
8058 if (read(0, &c, 1) != 1) {
8070 if (!rflag && c == '\\') {
8076 if (startword && *ifs == ' ' && strchr(ifs, c)) {
8080 if (backslash && c == '\\') {
8081 if (read(0, &c, 1) != 1) {
8086 } else if (ap[1] != NULL && strchr(ifs, c) != NULL) {
8088 setvar(*ap, stackblock(), 0);
8097 /* Remove trailing blanks */
8098 while (stackblock() <= --p && strchr(ifs, *p) != NULL)
8100 setvar(*ap, stackblock(), 0);
8101 while (*++ap != NULL)
8102 setvar(*ap, nullstr, 0);
8109 umaskcmd(int argc, char **argv)
8111 static const char permuser[3] = "ugo";
8112 static const char permmode[3] = "rwx";
8113 static const short int permmask[] = {
8114 S_IRUSR, S_IWUSR, S_IXUSR,
8115 S_IRGRP, S_IWGRP, S_IXGRP,
8116 S_IROTH, S_IWOTH, S_IXOTH
8122 int symbolic_mode = 0;
8124 while (nextopt("S") != '\0') {
8133 if ((ap = *argptr) == NULL) {
8134 if (symbolic_mode) {
8137 for (i=0 ; i<3 ; i++) {
8141 for (j=0 ; j<3 ; j++) {
8142 if ((mask & permmask[3*i+j]) == 0) {
8151 printf("%.4o\n", mask);
8154 if (is_digit((unsigned char)*ap)) {
8157 if (*ap >= '8' || *ap < '0')
8158 error("Illegal number: %s", argv[1]);
8159 mask = (mask << 3) + (*ap - '0');
8160 } while (*++ap != '\0');
8163 mask = ~mask & 0777;
8164 if (! parse_mode(ap, &mask)) {
8165 error("Illegal mode: %s", ap);
8167 umask(~mask & 0777);
8176 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
8177 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
8178 * ash by J.T. Conklin.
8186 short factor; /* multiply by to get rlim_{cur,max} values */
8189 static const struct limits limits[] = {
8191 { "time(seconds)", RLIMIT_CPU, 1 },
8194 { "file(blocks)", RLIMIT_FSIZE, 512 },
8197 { "data(kbytes)", RLIMIT_DATA, 1024 },
8200 { "stack(kbytes)", RLIMIT_STACK, 1024 },
8203 { "coredump(blocks)", RLIMIT_CORE, 512 },
8206 { "memory(kbytes)", RLIMIT_RSS, 1024 },
8208 #ifdef RLIMIT_MEMLOCK
8209 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024 },
8212 { "process(processes)", RLIMIT_NPROC, 1 },
8214 #ifdef RLIMIT_NOFILE
8215 { "nofiles(descriptors)", RLIMIT_NOFILE, 1 },
8218 { "vmemory(kbytes)", RLIMIT_VMEM, 1024 },
8221 { "swap(kbytes)", RLIMIT_SWAP, 1024 },
8227 ulimitcmd(int argc, char **argv)
8229 static const char unlimited_string[] = "unlimited";
8232 enum { SOFT = 0x1, HARD = 0x2 }
8234 const struct limits *l;
8237 struct rlimit limit;
8241 while ((optc = nextopt("HSa"
8260 #ifdef RLIMIT_MEMLOCK
8266 #ifdef RLIMIT_NOFILE
8278 } else if (optc == 'S') {
8280 } else if (optc == 'a') {
8287 for (l = limits; l->name; l++) {
8288 if(l->name[0] == what)
8290 if(l->name[1]=='w' && what=='w')
8294 set = *argptr ? 1 : 0;
8298 if (all || argptr[1])
8299 error("too many arguments");
8300 if (strcmp(p, unlimited_string) == 0)
8301 val = RLIM_INFINITY;
8305 while ((c = *p++) >= '0' && c <= '9')
8307 val = (val * 10) + (long)(c - '0');
8308 if (val < (rlim_t) 0)
8312 error("bad number");
8318 for (l = limits; l->name; l++) {
8319 printf("%-20s ", l->name);
8320 getrlimit(l->cmd, &limit);
8323 val = limit.rlim_cur;
8324 else if (how & HARD)
8325 val = limit.rlim_max;
8327 if (val == RLIM_INFINITY)
8328 puts(unlimited_string);
8332 printf("%lld\n", (long long) val);
8345 getrlimit(l->cmd, &limit);
8347 limit.rlim_max = val;
8349 limit.rlim_cur = val;
8350 if (setrlimit(l->cmd, &limit) < 0)
8351 error("error setting limit (%m)");
8355 * prefix -- see if pfx is a prefix of string.
8359 prefix(char const *pfx, char const *string)
8362 if (*pfx++ != *string++)
8369 * Return true if s is a string of digits, and save munber in intptr
8374 is_number(const char *p, int *intptr)
8382 ret += digit_val(*p);
8384 } while (*p != '\0');
8391 * Convert a string of digits to an integer, printing an error message on
8396 number(const char *s)
8399 if (! is_number(s, &i))
8400 error("Illegal number: %s", s);
8405 * Produce a possibly single quoted string suitable as input to the shell.
8406 * The return string is allocated on the stack.
8410 single_quote(const char *s)
8418 size_t len1, len1p, len2, len2p;
8420 len1 = strcspn(s, "'");
8421 len2 = strspn(s + len1, "'");
8423 len1p = len1 ? len1 + 2 : len1;
8424 len2p = len2 + ((len2 < 2) ? len2 : 2);
8426 CHECKSTRSPACE(len1p + len2p + 1, p);
8431 memcpy(p + 1, s, len1);
8439 memcpy(q + 1, s, len2);
8442 } else if (len2 == 1) {
8448 STADJUST(len1p + len2p, p);
8453 return grabstackstr(p);
8457 * Like strdup but works with the ash stack.
8461 sstrdup(const char *p)
8463 size_t len = strlen(p) + 1;
8464 return memcpy(stalloc(len), p, len);
8469 * Routine for dealing with parsed shell commands.
8473 static void sizenodelist (const struct nodelist *);
8474 static struct nodelist *copynodelist (const struct nodelist *);
8475 static char *nodexstrdup (const char *);
8477 #define CALCSIZE_TABLE
8478 #define COPYNODE_TABLE
8479 #if defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE)
8481 * To collect a lot of redundant code in case statements for copynode()
8482 * and calcsize(), we implement a mini language here. Each type of node
8483 * struct has an associated instruction sequence that operates on its
8484 * members via their offsets. The instruction are pack in unsigned chars
8485 * with format IIDDDDDE where the bits are
8486 * I : part of the instruction opcode, which are
8487 * 00 : member is a pointer to another node
8488 * 40 : member is an integer
8489 * 80 : member is a pointer to a nodelist
8490 * CC : member is a pointer to a char string
8491 * D : data - the actual offset of the member to operate on in the struct
8492 * (since we assume bit 0 is set, it is not shifted)
8493 * E : flag signaling end of instruction sequence
8495 * WARNING: In order to handle larger offsets for 64bit archs, this code
8496 * assumes that no offset can be an odd number and stores the
8497 * end-of-instructions flag in bit 0.
8500 #define NODE_INTEGER 0x40
8501 #define NODE_NODELIST 0x80
8502 #define NODE_CHARPTR 0xC0
8503 #define NODE_NOMORE 0x01 /* Note: no offset should be odd (aligned)*/
8504 #define NODE_MBRMASK 0xC0
8505 #define NODE_OFFSETMASK 0x3E
8507 static const unsigned char copynode_ops[35] = {
8508 #define COPYNODE_OPS0 0
8509 offsetof(union node, nbinary.ch2),
8510 offsetof(union node, nbinary.ch1)|NODE_NOMORE,
8511 #define COPYNODE_OPS1 (COPYNODE_OPS0 + 2)
8512 offsetof(union node, ncmd.redirect),
8513 offsetof(union node, ncmd.args),
8514 offsetof(union node, ncmd.assign),
8515 offsetof(union node, ncmd.backgnd)|NODE_INTEGER|NODE_NOMORE,
8516 #define COPYNODE_OPS2 (COPYNODE_OPS1 + 4)
8517 offsetof(union node, npipe.cmdlist)|NODE_NODELIST,
8518 offsetof(union node, npipe.backgnd)|NODE_INTEGER|NODE_NOMORE,
8519 #define COPYNODE_OPS3 (COPYNODE_OPS2 + 2)
8520 offsetof(union node, nredir.redirect),
8521 offsetof(union node, nredir.n)|NODE_NOMORE,
8522 #define COPYNODE_OPS4 (COPYNODE_OPS3 + 2)
8523 offsetof(union node, nif.elsepart),
8524 offsetof(union node, nif.ifpart),
8525 offsetof(union node, nif.test)|NODE_NOMORE,
8526 #define COPYNODE_OPS5 (COPYNODE_OPS4 + 3)
8527 offsetof(union node, nfor.var)|NODE_CHARPTR,
8528 offsetof(union node, nfor.body),
8529 offsetof(union node, nfor.args)|NODE_NOMORE,
8530 #define COPYNODE_OPS6 (COPYNODE_OPS5 + 3)
8531 offsetof(union node, ncase.cases),
8532 offsetof(union node, ncase.expr)|NODE_NOMORE,
8533 #define COPYNODE_OPS7 (COPYNODE_OPS6 + 2)
8534 offsetof(union node, nclist.body),
8535 offsetof(union node, nclist.pattern),
8536 offsetof(union node, nclist.next)|NODE_NOMORE,
8537 #define COPYNODE_OPS8 (COPYNODE_OPS7 + 3)
8538 offsetof(union node, narg.backquote)|NODE_NODELIST,
8539 offsetof(union node, narg.text)|NODE_CHARPTR,
8540 offsetof(union node, narg.next)|NODE_NOMORE,
8541 #define COPYNODE_OPS9 (COPYNODE_OPS8 + 3)
8542 offsetof(union node, nfile.fname),
8543 offsetof(union node, nfile.fd)|NODE_INTEGER,
8544 offsetof(union node, nfile.next)|NODE_NOMORE,
8545 #define COPYNODE_OPS10 (COPYNODE_OPS9 + 3)
8546 offsetof(union node, ndup.vname),
8547 offsetof(union node, ndup.dupfd)|NODE_INTEGER,
8548 offsetof(union node, ndup.fd)|NODE_INTEGER,
8549 offsetof(union node, ndup.next)|NODE_NOMORE,
8550 #define COPYNODE_OPS11 (COPYNODE_OPS10 + 4)
8551 offsetof(union node, nhere.doc),
8552 offsetof(union node, nhere.fd)|NODE_INTEGER,
8553 offsetof(union node, nhere.next)|NODE_NOMORE,
8554 #define COPYNODE_OPS12 (COPYNODE_OPS11 + 3)
8555 offsetof(union node, nnot.com)|NODE_NOMORE,
8558 #if COPYNODE_OPS12 != 34
8559 #error COPYNODE_OPS12 is incorrect
8562 static const unsigned char copynode_ops_index[26] = {
8563 COPYNODE_OPS0, /* NSEMI */
8564 COPYNODE_OPS1, /* NCMD */
8565 COPYNODE_OPS2, /* NPIPE */
8566 COPYNODE_OPS3, /* NREDIR */
8567 COPYNODE_OPS3, /* NBACKGND */
8568 COPYNODE_OPS3, /* NSUBSHELL */
8569 COPYNODE_OPS0, /* NAND */
8570 COPYNODE_OPS0, /* NOR */
8571 COPYNODE_OPS4, /* NIF */
8572 COPYNODE_OPS0, /* NWHILE */
8573 COPYNODE_OPS0, /* NUNTIL */
8574 COPYNODE_OPS5, /* NFOR */
8575 COPYNODE_OPS6, /* NCASE */
8576 COPYNODE_OPS7, /* NCLIST */
8577 COPYNODE_OPS8, /* NDEFUN */
8578 COPYNODE_OPS8, /* NARG */
8579 COPYNODE_OPS9, /* NTO */
8580 COPYNODE_OPS9, /* NFROM */
8581 COPYNODE_OPS9, /* NFROMTO */
8582 COPYNODE_OPS9, /* NAPPEND */
8583 COPYNODE_OPS9, /* NTOOV */
8584 COPYNODE_OPS10, /* NTOFD */
8585 COPYNODE_OPS10, /* NFROMFD */
8586 COPYNODE_OPS11, /* NHERE */
8587 COPYNODE_OPS11, /* NXHERE */
8588 COPYNODE_OPS12, /* NNOT */
8591 #if NODE_CHARPTR != NODE_MBRMASK
8592 #error NODE_CHARPTR != NODE_MBRMASK!!!
8594 #endif /* defined(CALCSIZE_TABLE) || defined(COPYNODE_TABLE) */
8596 #ifdef COPYNODE_TABLE
8598 copynode(const union node *n)
8601 const unsigned char *p;
8607 new->type = n->type;
8608 funcblock = (char *) funcblock + (int) nodesize[n->type];
8609 p = copynode_ops + (int) copynode_ops_index[n->type];
8611 char *nn = ((char *) new) + ((int)(*p & NODE_OFFSETMASK));
8612 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8614 if (!(*p & NODE_MBRMASK)) { /* standard node */
8615 *((union node **)nn) = copynode(*((const union node **) no));
8616 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8617 *((const char **)nn) = nodexstrdup(*((const char **)no));
8618 } else if (*p & NODE_NODELIST) { /* nodelist */
8619 *((struct nodelist **)nn)
8620 = copynodelist(*((const struct nodelist **) no));
8621 } else { /* integer */
8622 *((int *) nn) = *((int *) no);
8624 } while (!(*p++ & NODE_NOMORE));
8627 #else /* COPYNODE_TABLE */
8629 copynode(const union node *n)
8636 funcblock = (char *) funcblock + nodesize[n->type];
8643 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8644 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8647 new->ncmd.redirect = copynode(n->ncmd.redirect);
8648 new->ncmd.args = copynode(n->ncmd.args);
8649 new->ncmd.assign = copynode(n->ncmd.assign);
8650 new->ncmd.backgnd = n->ncmd.backgnd;
8653 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8654 new->npipe.backgnd = n->npipe.backgnd;
8659 new->nredir.redirect = copynode(n->nredir.redirect);
8660 new->nredir.n = copynode(n->nredir.n);
8663 new->nif.elsepart = copynode(n->nif.elsepart);
8664 new->nif.ifpart = copynode(n->nif.ifpart);
8665 new->nif.test = copynode(n->nif.test);
8668 new->nfor.var = nodexstrdup(n->nfor.var);
8669 new->nfor.body = copynode(n->nfor.body);
8670 new->nfor.args = copynode(n->nfor.args);
8673 new->ncase.cases = copynode(n->ncase.cases);
8674 new->ncase.expr = copynode(n->ncase.expr);
8677 new->nclist.body = copynode(n->nclist.body);
8678 new->nclist.pattern = copynode(n->nclist.pattern);
8679 new->nclist.next = copynode(n->nclist.next);
8683 new->narg.backquote = copynodelist(n->narg.backquote);
8684 new->narg.text = nodexstrdup(n->narg.text);
8685 new->narg.next = copynode(n->narg.next);
8692 new->nfile.fname = copynode(n->nfile.fname);
8693 new->nfile.fd = n->nfile.fd;
8694 new->nfile.next = copynode(n->nfile.next);
8698 new->ndup.vname = copynode(n->ndup.vname);
8699 new->ndup.dupfd = n->ndup.dupfd;
8700 new->ndup.fd = n->ndup.fd;
8701 new->ndup.next = copynode(n->ndup.next);
8705 new->nhere.doc = copynode(n->nhere.doc);
8706 new->nhere.fd = n->nhere.fd;
8707 new->nhere.next = copynode(n->nhere.next);
8710 new->nnot.com = copynode(n->nnot.com);
8713 new->type = n->type;
8716 #endif /* COPYNODE_TABLE */
8718 #ifdef CALCSIZE_TABLE
8720 calcsize(const union node *n)
8722 const unsigned char *p;
8726 funcblocksize += (int) nodesize[n->type];
8728 p = copynode_ops + (int) copynode_ops_index[n->type];
8730 const char *no = ((const char *) n) + ((int)(*p & NODE_OFFSETMASK));
8732 if (!(*p & NODE_MBRMASK)) { /* standard node */
8733 calcsize(*((const union node **) no));
8734 } else if ((*p & NODE_MBRMASK) == NODE_CHARPTR) { /* string */
8735 funcstringsize += strlen(*((const char **)no)) + 1;
8736 } else if (*p & NODE_NODELIST) { /* nodelist */
8737 sizenodelist(*((const struct nodelist **) no));
8738 } /* else integer -- ignore */
8739 } while (!(*p++ & NODE_NOMORE));
8741 #else /* CALCSIZE_TABLE */
8743 calcsize(const union node *n)
8747 funcblocksize += nodesize[n->type];
8754 calcsize(n->nbinary.ch2);
8755 calcsize(n->nbinary.ch1);
8758 calcsize(n->ncmd.redirect);
8759 calcsize(n->ncmd.args);
8760 calcsize(n->ncmd.assign);
8763 sizenodelist(n->npipe.cmdlist);
8768 calcsize(n->nredir.redirect);
8769 calcsize(n->nredir.n);
8772 calcsize(n->nif.elsepart);
8773 calcsize(n->nif.ifpart);
8774 calcsize(n->nif.test);
8777 funcstringsize += strlen(n->nfor.var) + 1;
8778 calcsize(n->nfor.body);
8779 calcsize(n->nfor.args);
8782 calcsize(n->ncase.cases);
8783 calcsize(n->ncase.expr);
8786 calcsize(n->nclist.body);
8787 calcsize(n->nclist.pattern);
8788 calcsize(n->nclist.next);
8792 sizenodelist(n->narg.backquote);
8793 funcstringsize += strlen(n->narg.text) + 1;
8794 calcsize(n->narg.next);
8801 calcsize(n->nfile.fname);
8802 calcsize(n->nfile.next);
8806 calcsize(n->ndup.vname);
8807 calcsize(n->ndup.next);
8811 calcsize(n->nhere.doc);
8812 calcsize(n->nhere.next);
8815 calcsize(n->nnot.com);
8819 #endif /* CALCSIZE_TABLE */
8822 sizenodelist(const struct nodelist *lp)
8825 funcblocksize += ALIGN(sizeof(struct nodelist));
8832 static struct nodelist *
8833 copynodelist(const struct nodelist *lp)
8835 struct nodelist *start;
8836 struct nodelist **lpp;
8841 funcblock = (char *) funcblock + ALIGN(sizeof(struct nodelist));
8842 (*lpp)->n = copynode(lp->n);
8844 lpp = &(*lpp)->next;
8852 nodexstrdup(const char *s)
8855 char *q = funcstring;
8856 char *rtn = funcstring;
8858 while ((*q++ = *p++) != '\0')
8865 static int getopts (char *, char *, char **, int *, int *);
8870 * Process the shell command line arguments.
8874 procargs(int argc, char **argv)
8881 for (i = 0; i < NOPTS; i++)
8884 if (*argptr == NULL && minusc == NULL)
8886 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8890 for (i = 0; i < NOPTS; i++)
8891 if (optent_val(i) == 2)
8894 if (sflag == 0 && minusc == NULL) {
8895 commandname = argv[0];
8897 setinputfile(arg0, 0);
8900 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8901 if (argptr && minusc && *argptr)
8904 shellparam.p = argptr;
8905 shellparam.optind = 1;
8906 shellparam.optoff = -1;
8907 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8909 shellparam.nparam++;
8918 * Process shell options. The global variable argptr contains a pointer
8919 * to the argument list; we advance it past the options.
8923 minus_o(const char *name, int val)
8928 out1str("Current option settings\n");
8929 for (i = 0; i < NOPTS; i++)
8930 printf("%-16s%s\n", optent_name(optlist[i]),
8931 optent_val(i) ? "on" : "off");
8933 for (i = 0; i < NOPTS; i++)
8934 if (equal(name, optent_name(optlist[i]))) {
8935 setoption(optent_letter(optlist[i]), val);
8938 error("Illegal option -o %s", name);
8944 options(int cmdline)
8952 while ((p = *argptr) != NULL) {
8954 if ((c = *p++) == '-') {
8956 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8958 /* "-" means turn off -x and -v */
8961 /* "--" means reset params */
8962 else if (*argptr == NULL)
8965 break; /* "-" or "--" terminates options */
8967 } else if (c == '+') {
8973 while ((c = *p++) != '\0') {
8974 if (c == 'c' && cmdline) {
8976 #ifdef NOHACK /* removing this code allows sh -ce 'foo' for compat */
8980 if (q == NULL || minusc != NULL)
8981 error("Bad -c option");
8986 } else if (c == 'o') {
8987 minus_o(*argptr, val);
8999 setoption(int flag, int val)
9003 for (i = 0; i < NOPTS; i++)
9004 if (optent_letter(optlist[i]) == flag) {
9005 optent_val(i) = val;
9007 /* #%$ hack for ksh semantics */
9010 else if (flag == 'E')
9015 error("Illegal option -%c", flag);
9022 * Set the shell parameters.
9026 setparam(char **argv)
9032 for (nparam = 0 ; argv[nparam] ; nparam++);
9033 ap = newparam = xmalloc((nparam + 1) * sizeof *ap);
9035 *ap++ = xstrdup(*argv++);
9038 freeparam(&shellparam);
9039 shellparam.malloc = 1;
9040 shellparam.nparam = nparam;
9041 shellparam.p = newparam;
9042 shellparam.optind = 1;
9043 shellparam.optoff = -1;
9048 * Free the list of positional parameters.
9052 freeparam(volatile struct shparam *param)
9056 if (param->malloc) {
9057 for (ap = param->p ; *ap ; ap++)
9066 * The shift builtin command.
9070 shiftcmd(int argc, char **argv)
9077 n = number(argv[1]);
9078 if (n > shellparam.nparam)
9079 error("can't shift that many");
9081 shellparam.nparam -= n;
9082 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
9083 if (shellparam.malloc)
9087 while ((*ap2++ = *ap1++) != NULL);
9088 shellparam.optind = 1;
9089 shellparam.optoff = -1;
9097 * The set command builtin.
9101 setcmd(int argc, char **argv)
9104 return showvarscmd(argc, argv);
9108 if (*argptr != NULL) {
9117 getoptsreset(const char *value)
9119 shellparam.optind = number(value);
9120 shellparam.optoff = -1;
9123 #ifdef CONFIG_LOCALE_SUPPORT
9124 static void change_lc_all(const char *value)
9126 if(value != 0 && *value != 0)
9127 setlocale(LC_ALL, value);
9130 static void change_lc_ctype(const char *value)
9132 if(value != 0 && *value != 0)
9133 setlocale(LC_CTYPE, value);
9140 * The getopts builtin. Shellparam.optnext points to the next argument
9141 * to be processed. Shellparam.optptr points to the next character to
9142 * be processed in the current argument. If shellparam.optnext is NULL,
9143 * then it's the first time getopts has been called.
9147 getoptscmd(int argc, char **argv)
9152 error("Usage: getopts optstring var [arg]");
9153 else if (argc == 3) {
9154 optbase = shellparam.p;
9155 if (shellparam.optind > shellparam.nparam + 1) {
9156 shellparam.optind = 1;
9157 shellparam.optoff = -1;
9162 if (shellparam.optind > argc - 2) {
9163 shellparam.optind = 1;
9164 shellparam.optoff = -1;
9168 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9169 &shellparam.optoff);
9173 * Safe version of setvar, returns 1 on success 0 on failure.
9177 setvarsafe(const char *name, const char *val, int flags)
9179 struct jmploc jmploc;
9180 struct jmploc *volatile savehandler = handler;
9186 if (setjmp(jmploc.loc))
9190 setvar(name, val, flags);
9192 handler = savehandler;
9197 getopts(char *optstr, char *optvar, char **optfirst, int *myoptind, int *optoff)
9204 char **optnext = optfirst + *myoptind - 1;
9206 if (*myoptind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9207 strlen(*(optnext - 1)) < *optoff)
9210 p = *(optnext - 1) + *optoff;
9211 if (p == NULL || *p == '\0') {
9212 /* Current word is done, advance */
9213 if (optnext == NULL)
9216 if (p == NULL || *p != '-' || *++p == '\0') {
9218 *myoptind = optnext - optfirst + 1;
9224 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9229 for (q = optstr; *q != c; ) {
9231 if (optstr[0] == ':') {
9234 err |= setvarsafe("OPTARG", s, 0);
9237 out2fmt("Illegal option -%c\n", c);
9238 (void) unsetvar("OPTARG");
9248 if (*p == '\0' && (p = *optnext) == NULL) {
9249 if (optstr[0] == ':') {
9252 err |= setvarsafe("OPTARG", s, 0);
9256 out2fmt("No arg for -%c option\n", c);
9257 (void) unsetvar("OPTARG");
9265 setvarsafe("OPTARG", p, 0);
9269 setvarsafe("OPTARG", "", 0);
9270 *myoptind = optnext - optfirst + 1;
9277 *optoff = p ? p - *(optnext - 1) : -1;
9278 snprintf(s, sizeof(s), "%d", *myoptind);
9279 err |= setvarsafe("OPTIND", s, VNOFUNC);
9282 err |= setvarsafe(optvar, s, 0);
9293 * XXX - should get rid of. have all builtins use getopt(3). the
9294 * library getopt must have the BSD extension static variable "optreset"
9295 * otherwise it can't be used within the shell safely.
9297 * Standard option processing (a la getopt) for builtin routines. The
9298 * only argument that is passed to nextopt is the option string; the
9299 * other arguments are unnecessary. It return the character, or '\0' on
9304 nextopt(const char *optstring)
9310 if ((p = optptr) == NULL || *p == '\0') {
9312 if (p == NULL || *p != '-' || *++p == '\0')
9315 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9319 for (q = optstring ; *q != c ; ) {
9321 error("Illegal option -%c", c);
9326 if (*p == '\0' && (p = *argptr++) == NULL)
9327 error("No arg for -%c option", c);
9344 out2fmt(const char *fmt, ...)
9348 vfprintf(stderr, fmt, ap);
9353 * Version of write which resumes after a signal is caught.
9357 xwrite(int fd, const char *buf, int nbytes)
9366 i = write(fd, buf, n);
9372 } else if (i == 0) {
9375 } else if (errno != EINTR) {
9383 * Shell command parser.
9386 #define EOFMARKLEN 79
9391 struct heredoc *next; /* next here document in list */
9392 union node *here; /* redirection node */
9393 char *eofmark; /* string indicating end of input */
9394 int striptabs; /* if set, strip leading tabs */
9397 static struct heredoc *heredoclist; /* list of here documents to read */
9398 static int parsebackquote; /* nonzero if we are inside backquotes */
9399 static int doprompt; /* if set, prompt the user */
9400 static int needprompt; /* true if interactive and at start of line */
9401 static int lasttoken; /* last token read */
9403 static char *wordtext; /* text of last word returned by readtoken */
9405 static struct nodelist *backquotelist;
9406 static union node *redirnode;
9407 static struct heredoc *heredoc;
9408 static int quoteflag; /* set if (part of) last token was quoted */
9409 static int startlinno; /* line # where last token started */
9412 static union node *list (int);
9413 static union node *andor (void);
9414 static union node *pipeline (void);
9415 static union node *command (void);
9416 static union node *simplecmd(union node **rpp, union node *redir);
9417 static void parsefname (void);
9418 static void parseheredoc (void);
9419 static char peektoken (void);
9420 static int readtoken (void);
9421 static int xxreadtoken (void);
9422 static int readtoken1 (int, int, const char *, int);
9423 static int noexpand (char *);
9424 static void synexpect (int) __attribute__((noreturn));
9425 static void synerror (const char *) __attribute__((noreturn));
9426 static void setprompt (int);
9430 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9431 * valid parse tree indicating a blank line.)
9435 parsecmd(int interact)
9440 doprompt = interact;
9459 union node *n1, *n2, *n3;
9463 if (nlflag == 0 && peektoken())
9469 if (tok == TBACKGND) {
9470 if (n2->type == NCMD || n2->type == NPIPE) {
9471 n2->ncmd.backgnd = 1;
9472 } else if (n2->type == NREDIR) {
9473 n2->type = NBACKGND;
9475 n3 = (union node *)stalloc(sizeof (struct nredir));
9476 n3->type = NBACKGND;
9478 n3->nredir.redirect = NULL;
9486 n3 = (union node *)stalloc(sizeof (struct nbinary));
9488 n3->nbinary.ch1 = n1;
9489 n3->nbinary.ch2 = n2;
9513 pungetc(); /* push back EOF on input */
9528 union node *n1, *n2, *n3;
9534 if ((t = readtoken()) == TAND) {
9536 } else if (t == TOR) {
9544 n3 = (union node *)stalloc(sizeof (struct nbinary));
9546 n3->nbinary.ch1 = n1;
9547 n3->nbinary.ch2 = n2;
9556 union node *n1, *n2, *pipenode;
9557 struct nodelist *lp, *prev;
9561 TRACE(("pipeline: entered\n"));
9562 if (readtoken() == TNOT) {
9568 if (readtoken() == TPIPE) {
9569 pipenode = (union node *)stalloc(sizeof (struct npipe));
9570 pipenode->type = NPIPE;
9571 pipenode->npipe.backgnd = 0;
9572 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9573 pipenode->npipe.cmdlist = lp;
9577 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9581 } while (readtoken() == TPIPE);
9587 n2 = (union node *)stalloc(sizeof (struct nnot));
9599 union node *n1, *n2;
9600 union node *ap, **app;
9601 union node *cp, **cpp;
9602 union node *redir, **rpp;
9609 /* Check for redirection which may precede command */
9610 while (readtoken() == TREDIR) {
9611 *rpp = n2 = redirnode;
9612 rpp = &n2->nfile.next;
9617 switch (readtoken()) {
9619 n1 = (union node *)stalloc(sizeof (struct nif));
9621 n1->nif.test = list(0);
9622 if (readtoken() != TTHEN)
9624 n1->nif.ifpart = list(0);
9626 while (readtoken() == TELIF) {
9627 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9628 n2 = n2->nif.elsepart;
9630 n2->nif.test = list(0);
9631 if (readtoken() != TTHEN)
9633 n2->nif.ifpart = list(0);
9635 if (lasttoken == TELSE)
9636 n2->nif.elsepart = list(0);
9638 n2->nif.elsepart = NULL;
9641 if (readtoken() != TFI)
9648 n1 = (union node *)stalloc(sizeof (struct nbinary));
9649 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9650 n1->nbinary.ch1 = list(0);
9651 if ((got=readtoken()) != TDO) {
9652 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9655 n1->nbinary.ch2 = list(0);
9656 if (readtoken() != TDONE)
9662 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9663 synerror("Bad for loop variable");
9664 n1 = (union node *)stalloc(sizeof (struct nfor));
9666 n1->nfor.var = wordtext;
9668 if (readtoken() == TIN) {
9670 while (readtoken() == TWORD) {
9671 n2 = (union node *)stalloc(sizeof (struct narg));
9673 n2->narg.text = wordtext;
9674 n2->narg.backquote = backquotelist;
9676 app = &n2->narg.next;
9680 if (lasttoken != TNL && lasttoken != TSEMI)
9683 static char argvars[5] = {CTLVAR, VSNORMAL|VSQUOTE,
9685 n2 = (union node *)stalloc(sizeof (struct narg));
9687 n2->narg.text = argvars;
9688 n2->narg.backquote = NULL;
9689 n2->narg.next = NULL;
9692 * Newline or semicolon here is optional (but note
9693 * that the original Bourne shell only allowed NL).
9695 if (lasttoken != TNL && lasttoken != TSEMI)
9699 if (readtoken() != TDO)
9701 n1->nfor.body = list(0);
9702 if (readtoken() != TDONE)
9707 n1 = (union node *)stalloc(sizeof (struct ncase));
9709 if (readtoken() != TWORD)
9711 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9713 n2->narg.text = wordtext;
9714 n2->narg.backquote = backquotelist;
9715 n2->narg.next = NULL;
9718 } while (readtoken() == TNL);
9719 if (lasttoken != TIN)
9720 synerror("expecting \"in\"");
9721 cpp = &n1->ncase.cases;
9722 checkkwd = 2, readtoken();
9724 if (lasttoken == TLP)
9726 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9728 app = &cp->nclist.pattern;
9730 *app = ap = (union node *)stalloc(sizeof (struct narg));
9732 ap->narg.text = wordtext;
9733 ap->narg.backquote = backquotelist;
9734 if (checkkwd = 2, readtoken() != TPIPE)
9736 app = &ap->narg.next;
9739 ap->narg.next = NULL;
9740 if (lasttoken != TRP)
9742 cp->nclist.body = list(0);
9745 if ((t = readtoken()) != TESAC) {
9747 synexpect(TENDCASE);
9749 checkkwd = 2, readtoken();
9751 cpp = &cp->nclist.next;
9752 } while(lasttoken != TESAC);
9757 n1 = (union node *)stalloc(sizeof (struct nredir));
9758 n1->type = NSUBSHELL;
9759 n1->nredir.n = list(0);
9760 n1->nredir.redirect = NULL;
9761 if (readtoken() != TRP)
9767 if (readtoken() != TEND)
9771 /* Handle an empty command like other simple commands. */
9780 * An empty command before a ; doesn't make much sense, and
9781 * should certainly be disallowed in the case of `if ;'.
9787 n1 = simplecmd(rpp, redir);
9794 /* Now check for redirection which may follow command */
9795 while (readtoken() == TREDIR) {
9796 *rpp = n2 = redirnode;
9797 rpp = &n2->nfile.next;
9803 if (n1->type != NSUBSHELL) {
9804 n2 = (union node *)stalloc(sizeof (struct nredir));
9809 n1->nredir.redirect = redir;
9817 simplecmd(union node **rpp, union node *redir) {
9818 union node *args, **app;
9819 union node *n = NULL;
9820 union node *vars, **vpp;
9821 union node **orig_rpp;
9828 /* If we don't have any redirections already, then we must reset
9829 rpp to be the address of the local redir variable. */
9832 /* We save the incoming value, because we need this for shell
9833 functions. There can not be a redirect or an argument between
9834 the function name and the open parenthesis. */
9839 switch (readtoken()) {
9842 n = (union node *)stalloc(sizeof (struct narg));
9844 n->narg.text = wordtext;
9845 n->narg.backquote = backquotelist;
9846 if (lasttoken == TWORD) {
9848 app = &n->narg.next;
9851 vpp = &n->narg.next;
9855 *rpp = n = redirnode;
9856 rpp = &n->nfile.next;
9857 parsefname(); /* read name of redirection file */
9861 args && app == &args->narg.next &&
9862 !vars && rpp == orig_rpp
9864 /* We have a function */
9865 if (readtoken() != TRP)
9869 n->narg.next = command();
9882 n = (union node *)stalloc(sizeof (struct ncmd));
9884 n->ncmd.backgnd = 0;
9885 n->ncmd.args = args;
9886 n->ncmd.assign = vars;
9887 n->ncmd.redirect = redir;
9895 n = (union node *)stalloc(sizeof (struct narg));
9897 n->narg.next = NULL;
9898 n->narg.text = wordtext;
9899 n->narg.backquote = backquotelist;
9903 static void fixredir(union node *n, const char *text, int err)
9905 TRACE(("Fix redir %s %d\n", text, err));
9907 n->ndup.vname = NULL;
9909 if (is_digit(text[0]) && text[1] == '\0')
9910 n->ndup.dupfd = digit_val(text[0]);
9911 else if (text[0] == '-' && text[1] == '\0')
9916 synerror("Bad fd number");
9918 n->ndup.vname = makename();
9925 union node *n = redirnode;
9927 if (readtoken() != TWORD)
9929 if (n->type == NHERE) {
9930 struct heredoc *here = heredoc;
9936 TRACE(("Here document %d\n", n->type));
9937 if (here->striptabs) {
9938 while (*wordtext == '\t')
9941 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9942 synerror("Illegal eof marker for << redirection");
9943 rmescapes(wordtext);
9944 here->eofmark = wordtext;
9946 if (heredoclist == NULL)
9949 for (p = heredoclist ; p->next ; p = p->next);
9952 } else if (n->type == NTOFD || n->type == NFROMFD) {
9953 fixredir(n, wordtext, 0);
9955 n->nfile.fname = makename();
9961 * Input any here documents.
9966 struct heredoc *here;
9969 while (heredoclist) {
9971 heredoclist = here->next;
9976 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9977 here->eofmark, here->striptabs);
9978 n = (union node *)stalloc(sizeof (struct narg));
9979 n->narg.type = NARG;
9980 n->narg.next = NULL;
9981 n->narg.text = wordtext;
9982 n->narg.backquote = backquotelist;
9983 here->here->nhere.doc = n;
9993 return tokname_array[t][0];
10001 int savecheckalias = checkalias;
10002 int savecheckkwd = checkkwd;
10007 int alreadyseen = tokpushback;
10017 checkalias = savecheckalias;
10024 if (checkkwd == 2) {
10033 * check for keywords
10035 if (t == TWORD && !quoteflag)
10037 const char *const *pp;
10039 if ((pp = findkwd(wordtext))) {
10040 lasttoken = t = pp - tokname_array;
10041 TRACE(("keyword %s recognized\n", tokname(t)));
10052 } else if (checkalias == 2 && isassignment(wordtext)) {
10053 lasttoken = t = TASSIGN;
10055 } else if (checkalias) {
10056 if (!quoteflag && (ap = *__lookupalias(wordtext)) != NULL && !(ap->flag & ALIASINUSE)) {
10058 pushstring(ap->val, strlen(ap->val), ap);
10060 checkkwd = savecheckkwd;
10069 TRACE(("token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10071 TRACE(("reread token %s %s\n", tokname(t), t == TWORD || t == TASSIGN ? wordtext : ""));
10078 * Read the next input token.
10079 * If the token is a word, we set backquotelist to the list of cmds in
10080 * backquotes. We set quoteflag to true if any part of the word was
10082 * If the token is TREDIR, then we set redirnode to a structure containing
10084 * In all cases, the variable startlinno is set to the number of the line
10085 * on which the token starts.
10087 * [Change comment: here documents and internal procedures]
10088 * [Readtoken shouldn't have any arguments. Perhaps we should make the
10089 * word parsing code into a separate routine. In this case, readtoken
10090 * doesn't need to have any internal procedures, but parseword does.
10091 * We could also make parseoperator in essence the main routine, and
10092 * have parseword (readtoken1?) handle both words and redirection.]
10095 #define NEW_xxreadtoken
10096 #ifdef NEW_xxreadtoken
10098 static const char xxreadtoken_chars[] = "\n()&|;"; /* singles must be first! */
10099 static const char xxreadtoken_tokens[] = {
10100 TNL, TLP, TRP, /* only single occurrence allowed */
10101 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
10102 TEOF, /* corresponds to trailing nul */
10103 TAND, TOR, TENDCASE, /* if double occurrence */
10106 #define xxreadtoken_doubles \
10107 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
10108 #define xxreadtoken_singles \
10109 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
10123 startlinno = plinno;
10124 for (;;) { /* until token or start of word found */
10127 if ((c!=' ') && (c!='\t')
10133 while ((c = pgetc()) != '\n' && c != PEOF);
10135 } else if (c=='\\') {
10136 if (pgetc() != '\n') {
10140 startlinno = ++plinno;
10141 setprompt(doprompt ? 2 : 0);
10144 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10149 needprompt = doprompt;
10152 p = strchr(xxreadtoken_chars, c);
10155 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10158 if (p-xxreadtoken_chars >= xxreadtoken_singles) {
10159 if (pgetc() == *p) { /* double occurrence? */
10160 p += xxreadtoken_doubles + 1;
10167 return lasttoken = xxreadtoken_tokens[p-xxreadtoken_chars];
10175 #define RETURN(token) return lasttoken = token
10189 startlinno = plinno;
10190 for (;;) { /* until token or start of word found */
10193 case ' ': case '\t':
10199 while ((c = pgetc()) != '\n' && c != PEOF);
10203 if (pgetc() == '\n') {
10204 startlinno = ++plinno;
10215 needprompt = doprompt;
10220 if (pgetc() == '&')
10225 if (pgetc() == '|')
10230 if (pgetc() == ';')
10243 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10249 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10250 * is not NULL, read a here document. In the latter case, eofmark is the
10251 * word which marks the end of the document and striptabs is true if
10252 * leading tabs should be stripped from the document. The argument firstc
10253 * is the first character of the input token or document.
10255 * Because C does not have internal subroutines, I have simulated them
10256 * using goto's to implement the subroutine linkage. The following macros
10257 * will run code that appears at the end of readtoken1.
10260 #define CHECKEND() {goto checkend; checkend_return:;}
10261 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10262 #define PARSESUB() {goto parsesub; parsesub_return:;}
10263 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10264 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10265 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10268 readtoken1(int firstc, int syntax, const char *eofmark, int striptabs)
10273 char line[EOFMARKLEN + 1];
10274 struct nodelist *bqlist;
10277 int varnest; /* levels of variables expansion */
10278 int arinest; /* levels of arithmetic expansion */
10279 int parenlevel; /* levels of parens in arithmetic */
10280 int dqvarnest; /* levels of variables expansion within double quotes */
10282 int prevsyntax; /* syntax before arithmetic */
10284 /* Avoid longjmp clobbering */
10290 (void) &parenlevel;
10293 (void) &prevsyntax;
10297 startlinno = plinno;
10299 if (syntax == DQSYNTAX)
10308 STARTSTACKSTR(out);
10309 loop: { /* for each line, until end of word */
10310 CHECKEND(); /* set c to PEOF if at end of here document */
10311 for (;;) { /* until end of line or end of word */
10312 CHECKSTRSPACE(3, out); /* permit 3 calls to USTPUTC */
10313 switch(SIT(c,syntax)) {
10314 case CNL: /* '\n' */
10315 if (syntax == BASESYNTAX)
10316 goto endword; /* exit outer loop */
10324 goto loop; /* continue outer loop */
10329 if ((eofmark == NULL || dblquote) &&
10331 USTPUTC(CTLESC, out);
10334 case CBACK: /* backslash */
10337 USTPUTC('\\', out);
10339 } else if (c == '\n') {
10345 if (dblquote && c != '\\' && c != '`' && c != '$'
10346 && (c != '"' || eofmark != NULL))
10347 USTPUTC('\\', out);
10348 if (SIT(c,SQSYNTAX) == CCTL)
10349 USTPUTC(CTLESC, out);
10350 else if (eofmark == NULL)
10351 USTPUTC(CTLQUOTEMARK, out);
10357 if (eofmark == NULL)
10358 USTPUTC(CTLQUOTEMARK, out);
10362 if (eofmark == NULL)
10363 USTPUTC(CTLQUOTEMARK, out);
10368 if (eofmark != NULL && arinest == 0 &&
10373 syntax = ARISYNTAX;
10375 } else if (eofmark == NULL &&
10377 syntax = BASESYNTAX;
10383 case CVAR: /* '$' */
10384 PARSESUB(); /* parse substitution */
10386 case CENDVAR: /* '}' */
10389 if (dqvarnest > 0) {
10392 USTPUTC(CTLENDVAR, out);
10397 #ifdef ASH_MATH_SUPPORT
10398 case CLP: /* '(' in arithmetic */
10402 case CRP: /* ')' in arithmetic */
10403 if (parenlevel > 0) {
10407 if (pgetc() == ')') {
10408 if (--arinest == 0) {
10409 USTPUTC(CTLENDARI, out);
10410 syntax = prevsyntax;
10411 if (syntax == DQSYNTAX)
10419 * unbalanced parens
10420 * (don't 2nd guess - no error)
10428 case CBQUOTE: /* '`' */
10432 goto endword; /* exit outer loop */
10437 goto endword; /* exit outer loop */
10448 if (syntax == ARISYNTAX)
10449 synerror("Missing '))'");
10450 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10451 synerror("Unterminated quoted string");
10452 if (varnest != 0) {
10453 startlinno = plinno;
10454 synerror("Missing '}'");
10456 USTPUTC('\0', out);
10457 len = out - stackblock();
10458 out = stackblock();
10459 if (eofmark == NULL) {
10460 if ((c == '>' || c == '<')
10463 && (*out == '\0' || is_digit(*out))) {
10465 return lasttoken = TREDIR;
10470 quoteflag = quotef;
10471 backquotelist = bqlist;
10472 grabstackblock(len);
10474 return lasttoken = TWORD;
10475 /* end of readtoken routine */
10480 * Check to see whether we are at the end of the here document. When this
10481 * is called, c is set to the first character of the next input line. If
10482 * we are at the end of the here document, this routine sets the c to PEOF.
10493 while (c == '\t') {
10497 if (c == *eofmark) {
10498 if (pfgets(line, sizeof line) != NULL) {
10502 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10503 if (*p == '\n' && *q == '\0') {
10506 needprompt = doprompt;
10508 pushstring(line, strlen(line), NULL);
10513 goto checkend_return;
10518 * Parse a redirection operator. The variable "out" points to a string
10519 * specifying the fd to be redirected. The variable "c" contains the
10520 * first character of the redirection operator.
10527 np = (union node *)stalloc(sizeof (struct nfile));
10532 np->type = NAPPEND;
10541 } else { /* c == '<' */
10543 switch (c = pgetc()) {
10545 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10546 np = (union node *)stalloc(sizeof (struct nhere));
10550 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10551 heredoc->here = np;
10552 if ((c = pgetc()) == '-') {
10553 heredoc->striptabs = 1;
10555 heredoc->striptabs = 0;
10561 np->type = NFROMFD;
10565 np->type = NFROMTO;
10575 np->nfile.fd = digit_val(fd);
10577 goto parseredir_return;
10582 * Parse a substitution. At this point, we have read the dollar sign
10583 * and nothing else.
10591 static const char types[] = "}-+?=";
10596 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10600 } else if (c == '(') { /* $(command) or $((arith)) */
10601 if (pgetc() == '(') {
10608 USTPUTC(CTLVAR, out);
10609 typeloc = out - stackblock();
10610 USTPUTC(VSNORMAL, out);
10611 subtype = VSNORMAL;
10615 if ((c = pgetc()) == '}')
10618 subtype = VSLENGTH;
10623 if (c > PEOA && is_name(c)) {
10627 } while (c > PEOA && is_in_name(c));
10628 } else if (is_digit(c)) {
10632 } while (is_digit(c));
10634 else if (is_special(c)) {
10639 badsub: synerror("Bad substitution");
10643 if (subtype == 0) {
10650 p = strchr(types, c);
10653 subtype = p - types + VSNORMAL;
10659 subtype = c == '#' ? VSTRIMLEFT :
10672 if (dblquote || arinest)
10674 *(stackblock() + typeloc) = subtype | flags;
10675 if (subtype != VSNORMAL) {
10682 goto parsesub_return;
10687 * Called to parse command substitutions. Newstyle is set if the command
10688 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10689 * list of commands (passed by reference), and savelen is the number of
10690 * characters on the top of the stack which must be preserved.
10694 struct nodelist **nlpp;
10697 char *volatile str;
10698 struct jmploc jmploc;
10699 struct jmploc *volatile savehandler;
10703 (void) &saveprompt;
10706 savepbq = parsebackquote;
10707 if (setjmp(jmploc.loc)) {
10710 parsebackquote = 0;
10711 handler = savehandler;
10712 longjmp(handler->loc, 1);
10716 savelen = out - stackblock();
10718 str = xmalloc(savelen);
10719 memcpy(str, stackblock(), savelen);
10721 savehandler = handler;
10725 /* We must read until the closing backquote, giving special
10726 treatment to some slashes, and then push the string and
10727 reread it as input, interpreting it normally. */
10734 STARTSTACKSTR(pout);
10740 switch (pc = pgetc()) {
10745 if ((pc = pgetc()) == '\n') {
10752 * If eating a newline, avoid putting
10753 * the newline into the new character
10754 * stream (via the STPUTC after the
10759 if (pc != '\\' && pc != '`' && pc != '$'
10760 && (!dblquote || pc != '"'))
10761 STPUTC('\\', pout);
10771 startlinno = plinno;
10772 synerror("EOF in backquote substitution");
10776 needprompt = doprompt;
10785 STPUTC('\0', pout);
10786 psavelen = pout - stackblock();
10787 if (psavelen > 0) {
10788 pstr = grabstackstr(pout);
10789 setinputstring(pstr);
10794 nlpp = &(*nlpp)->next;
10795 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10796 (*nlpp)->next = NULL;
10797 parsebackquote = oldstyle;
10800 saveprompt = doprompt;
10807 doprompt = saveprompt;
10809 if (readtoken() != TRP)
10816 * Start reading from old file again, ignoring any pushed back
10817 * tokens left from the backquote parsing
10822 while (stackblocksize() <= savelen)
10824 STARTSTACKSTR(out);
10826 memcpy(out, str, savelen);
10827 STADJUST(savelen, out);
10833 parsebackquote = savepbq;
10834 handler = savehandler;
10835 if (arinest || dblquote)
10836 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10838 USTPUTC(CTLBACKQ, out);
10840 goto parsebackq_oldreturn;
10842 goto parsebackq_newreturn;
10846 * Parse an arithmetic expansion (indicate start of one and set state)
10850 if (++arinest == 1) {
10851 prevsyntax = syntax;
10852 syntax = ARISYNTAX;
10853 USTPUTC(CTLARI, out);
10860 * we collapse embedded arithmetic expansion to
10861 * parenthesis, which should be equivalent
10865 goto parsearith_return;
10868 } /* end of readtoken */
10872 * Returns true if the text contains nothing to expand (no dollar signs
10877 noexpand(char *text)
10883 while ((c = *p++) != '\0') {
10884 if (c == CTLQUOTEMARK)
10888 else if (SIT(c,BASESYNTAX) == CCTL)
10896 * Return true if the argument is a legal variable name (a letter or
10897 * underscore followed by zero or more letters, underscores, and digits).
10901 goodname(const char *name)
10909 if (! is_in_name(*p))
10917 * Called when an unexpected token is read during the parse. The argument
10918 * is the token that is expected, or -1 if more than one type of token can
10919 * occur at this point.
10923 synexpect(int token)
10928 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10930 sprintf(msg+l, " (expecting %s)", tokname(token));
10937 synerror(const char *msg)
10940 out2fmt("%s: %d: ", commandname, startlinno);
10941 out2fmt("Syntax error: %s\n", msg);
10942 error((char *)NULL);
10948 * called by editline -- any expansions to the prompt
10949 * should be added here.
10952 setprompt(int whichprompt)
10955 switch (whichprompt) {
10970 * Code for dealing with input/output redirection.
10973 #define EMPTY -2 /* marks an unused slot in redirtab */
10975 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10977 # define PIPESIZE PIPE_BUF
10982 * Open a file in noclobber mode.
10983 * The code was copied from bash.
10986 noclobberopen(const char *fname)
10989 struct stat finfo, finfo2;
10992 * If the file exists and is a regular file, return an error
10995 r = stat(fname, &finfo);
10996 if (r == 0 && S_ISREG(finfo.st_mode)) {
11002 * If the file was not present (r != 0), make sure we open it
11003 * exclusively so that if it is created before we open it, our open
11004 * will fail. Make sure that we do not truncate an existing file.
11005 * Note that we don't turn on O_EXCL unless the stat failed -- if the
11006 * file was not a regular file, we leave O_EXCL off.
11009 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
11010 fd = open(fname, O_WRONLY|O_CREAT, 0666);
11012 /* If the open failed, return the file descriptor right away. */
11017 * OK, the open succeeded, but the file may have been changed from a
11018 * non-regular file to a regular file between the stat and the open.
11019 * We are assuming that the O_EXCL open handles the case where FILENAME
11020 * did not exist and is symlinked to an existing file between the stat
11025 * If we can open it and fstat the file descriptor, and neither check
11026 * revealed that it was a regular file, and the file has not been
11027 * replaced, return the file descriptor.
11029 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
11030 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
11033 /* The file has been replaced. badness. */
11040 * Handle here documents. Normally we fork off a process to write the
11041 * data to a pipe. If the document is short, we can stuff the data in
11042 * the pipe without forking.
11046 openhere(const union node *redir)
11052 error("Pipe call failed");
11053 if (redir->type == NHERE) {
11054 len = strlen(redir->nhere.doc->narg.text);
11055 if (len <= PIPESIZE) {
11056 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11060 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
11062 signal(SIGINT, SIG_IGN);
11063 signal(SIGQUIT, SIG_IGN);
11064 signal(SIGHUP, SIG_IGN);
11066 signal(SIGTSTP, SIG_IGN);
11068 signal(SIGPIPE, SIG_DFL);
11069 if (redir->type == NHERE)
11070 xwrite(pip[1], redir->nhere.doc->narg.text, len);
11072 expandhere(redir->nhere.doc, pip[1]);
11082 openredirect(const union node *redir)
11087 switch (redir->nfile.type) {
11089 fname = redir->nfile.expfname;
11090 if ((f = open(fname, O_RDONLY)) < 0)
11094 fname = redir->nfile.expfname;
11095 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
11099 /* Take care of noclobber mode. */
11101 fname = redir->nfile.expfname;
11102 if ((f = noclobberopen(fname)) < 0)
11107 fname = redir->nfile.expfname;
11109 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
11112 if ((f = creat(fname, 0666)) < 0)
11117 fname = redir->nfile.expfname;
11119 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11122 if ((f = open(fname, O_WRONLY)) < 0
11123 && (f = creat(fname, 0666)) < 0)
11125 lseek(f, (off_t)0, 2);
11132 /* Fall through to eliminate warning. */
11139 f = openhere(redir);
11145 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11147 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11152 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11153 * old file descriptors are stashed away so that the redirection can be
11154 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11155 * standard output, and the standard error if it becomes a duplicate of
11160 redirect(union node *redir, int flags)
11163 struct redirtab *sv = NULL;
11168 int fd1dup = flags & REDIR_BACKQ;; /* stdout `cmd` redir to pipe */
11170 if (flags & REDIR_PUSH) {
11171 sv = xmalloc(sizeof (struct redirtab));
11172 for (i = 0 ; i < 10 ; i++)
11173 sv->renamed[i] = EMPTY;
11174 sv->next = redirlist;
11177 for (n = redir ; n ; n = n->nfile.next) {
11180 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11181 n->ndup.dupfd == fd)
11182 continue; /* redirect from/to same file descriptor */
11185 newfd = openredirect(n);
11186 if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
11189 } else if ((i = fcntl(fd, F_DUPFD, 10)) == -1) {
11193 dupredirect(n, newfd, fd1dup);
11203 error("%d: %m", fd);
11209 if (flags & REDIR_PUSH) {
11210 sv->renamed[fd] = i;
11213 } else if (fd != newfd) {
11219 dupredirect(n, newfd, fd1dup);
11226 dupredirect(const union node *redir, int f, int fd1dup)
11228 int fd = redir->nfile.fd;
11232 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11233 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11234 if (redir->ndup.dupfd!=1 || fd1dup!=1)
11235 dup_as_newfd(redir->ndup.dupfd, fd);
11241 dup_as_newfd(f, fd);
11250 * Undo the effects of the last redirection.
11256 struct redirtab *rp = redirlist;
11260 for (i = 0 ; i < 10 ; i++) {
11261 if (rp->renamed[i] != EMPTY) {
11265 if (rp->renamed[i] >= 0) {
11266 dup_as_newfd(rp->renamed[i], i);
11267 close(rp->renamed[i]);
11271 redirlist = rp->next;
11277 * Discard all saved file descriptors.
11282 struct redirtab *rp;
11285 for (rp = redirlist ; rp ; rp = rp->next) {
11286 for (i = 0 ; i < 10 ; i++) {
11287 if (rp->renamed[i] >= 0) {
11288 close(rp->renamed[i]);
11290 rp->renamed[i] = EMPTY;
11297 * Copy a file descriptor to be >= to. Returns -1
11298 * if the source file descriptor is closed, EMPTY if there are no unused
11299 * file descriptors left.
11303 dup_as_newfd(int from, int to)
11307 newfd = fcntl(from, F_DUPFD, to);
11309 if (errno == EMFILE)
11312 error("%d: %m", from);
11321 static void shtree (union node *, int, char *, FILE*);
11322 static void shcmd (union node *, FILE *);
11323 static void sharg (union node *, FILE *);
11324 static void indent (int, char *, FILE *);
11325 static void trstring (char *);
11332 trputs("showtree called\n");
11333 shtree(n, 1, NULL, stdout);
11338 shtree(union node *n, int ind, char *pfx, FILE *fp)
11340 struct nodelist *lp;
11346 indent(ind, pfx, fp);
11357 shtree(n->nbinary.ch1, ind, NULL, fp);
11360 shtree(n->nbinary.ch2, ind, NULL, fp);
11368 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11373 if (n->npipe.backgnd)
11379 fprintf(fp, "<node type %d>", n->type);
11389 shcmd(union node *cmd, FILE *fp)
11397 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11403 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11409 if ((np->nfile.type <= NFROMFD) && (np->nfile.type >= NTO)) {
11410 s = redir_strings[np->nfile.type - NTO];
11416 switch (np->nfile.type) {
11417 case NTO: s = ">"; dftfd = 1; break;
11418 case NAPPEND: s = ">>"; dftfd = 1; break;
11419 case NTOFD: s = ">&"; dftfd = 1; break;
11420 case NTOOV: s = ">|"; dftfd = 1; break;
11421 case NFROM: s = "<"; dftfd = 0; break;
11422 case NFROMFD: s = "<&"; dftfd = 0; break;
11423 case NFROMTO: s = "<>"; dftfd = 0; break;
11424 default: s = "*error*"; dftfd = 0; break;
11427 if (np->nfile.fd != dftfd)
11428 fprintf(fp, "%d", np->nfile.fd);
11430 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11431 fprintf(fp, "%d", np->ndup.dupfd);
11433 sharg(np->nfile.fname, fp);
11440 sharg(union node *arg, FILE *fp)
11443 struct nodelist *bqlist;
11446 if (arg->type != NARG) {
11447 printf("<node type %d>\n", arg->type);
11451 bqlist = arg->narg.backquote;
11452 for (p = arg->narg.text ; *p ; p++) {
11461 if (subtype == VSLENGTH)
11467 if (subtype & VSNUL)
11470 switch (subtype & VSTYPE) {
11489 case VSTRIMLEFTMAX:
11496 case VSTRIMRIGHTMAX:
11503 printf("<subtype %d>", subtype);
11510 case CTLBACKQ|CTLQUOTE:
11513 shtree(bqlist->n, -1, NULL, fp);
11525 indent(int amount, char *pfx, FILE *fp)
11529 for (i = 0 ; i < amount ; i++) {
11530 if (pfx && i == amount - 1)
11540 static int debug = 1;
11542 static int debug = 0;
11549 if (tracefile == NULL)
11551 putc(c, tracefile);
11557 trace(const char *fmt, ...)
11561 if (tracefile != NULL) {
11562 (void) vfprintf(tracefile, fmt, va);
11563 if (strchr(fmt, '\n'))
11564 (void) fflush(tracefile);
11571 trputs(const char *s)
11573 if (tracefile == NULL)
11575 fputs(s, tracefile);
11576 if (strchr(s, '\n'))
11587 if (tracefile == NULL)
11589 putc('"', tracefile);
11590 for (p = s ; *p ; p++) {
11592 case '\n': c = 'n'; goto backslash;
11593 case '\t': c = 't'; goto backslash;
11594 case '\r': c = 'r'; goto backslash;
11595 case '"': c = '"'; goto backslash;
11596 case '\\': c = '\\'; goto backslash;
11597 case CTLESC: c = 'e'; goto backslash;
11598 case CTLVAR: c = 'v'; goto backslash;
11599 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11600 case CTLBACKQ: c = 'q'; goto backslash;
11601 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11602 backslash: putc('\\', tracefile);
11603 putc(c, tracefile);
11606 if (*p >= ' ' && *p <= '~')
11607 putc(*p, tracefile);
11609 putc('\\', tracefile);
11610 putc(*p >> 6 & 03, tracefile);
11611 putc(*p >> 3 & 07, tracefile);
11612 putc(*p & 07, tracefile);
11617 putc('"', tracefile);
11624 if (tracefile == NULL)
11629 putc(' ', tracefile);
11631 putc('\n', tracefile);
11647 #ifdef not_this_way
11650 if ((p = getenv("HOME")) == NULL) {
11651 if (geteuid() == 0)
11657 strcat(s, "/trace");
11660 strcpy(s, "./trace");
11661 #endif /* not_this_way */
11662 if ((tracefile = wfopen(s, "a")) == NULL)
11665 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11666 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11668 fputs("\nTracing started.\n", tracefile);
11675 * The trap builtin.
11679 trapcmd(int argc, char **argv)
11686 for (signo = 0 ; signo < NSIG ; signo++) {
11687 if (trap[signo] != NULL) {
11691 p = single_quote(trap[signo]);
11692 sn = sys_siglist[signo];
11694 sn = u_signal_names(0, &signo, 0);
11697 printf("trap -- %s %s\n", p, sn);
11709 if ((signo = decode_signal(*ap, 0)) < 0)
11710 error("%s: bad trap", *ap);
11713 if (action[0] == '-' && action[1] == '\0')
11716 action = xstrdup(action);
11719 ckfree(trap[signo]);
11720 trap[signo] = action;
11735 * Set the signal handler for the specified signal. The routine figures
11736 * out what it should be set to.
11740 setsignal(int signo)
11744 struct sigaction act;
11746 if ((t = trap[signo]) == NULL)
11748 else if (*t != '\0')
11752 if (rootshell && action == S_DFL) {
11755 if (iflag || minusc || sflag == 0)
11781 t = &sigmode[signo - 1];
11784 * current setting unknown
11786 if (sigaction(signo, 0, &act) == -1) {
11788 * Pretend it worked; maybe we should give a warning
11789 * here, but other shells don't. We don't alter
11790 * sigmode, so that we retry every time.
11794 if (act.sa_handler == SIG_IGN) {
11795 if (mflag && (signo == SIGTSTP ||
11796 signo == SIGTTIN || signo == SIGTTOU)) {
11797 *t = S_IGN; /* don't hard ignore these */
11801 *t = S_RESET; /* force to be set */
11804 if (*t == S_HARD_IGN || *t == action)
11806 act.sa_handler = ((action == S_CATCH) ? onsig
11807 : ((action == S_IGN) ? SIG_IGN : SIG_DFL));
11810 sigemptyset(&act.sa_mask);
11811 sigaction(signo, &act, 0);
11819 ignoresig(int signo)
11821 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11822 signal(signo, SIG_IGN);
11824 sigmode[signo - 1] = S_HARD_IGN;
11835 if (signo == SIGINT && trap[SIGINT] == NULL) {
11839 gotsig[signo - 1] = 1;
11845 * Called to execute a trap. Perhaps we should avoid entering new trap
11846 * handlers while we are executing a trap handler.
11856 for (i = 1 ; ; i++) {
11863 savestatus=exitstatus;
11864 evalstring(trap[i], 0);
11865 exitstatus=savestatus;
11872 * Called to exit the shell.
11876 exitshell(int status)
11878 struct jmploc loc1, loc2;
11881 TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
11882 if (setjmp(loc1.loc)) {
11885 if (setjmp(loc2.loc)) {
11889 if ((p = trap[0]) != NULL && *p != '\0') {
11893 l1: handler = &loc2; /* probably unnecessary */
11902 static int decode_signal(const char *string, int minsig)
11905 const char *name = u_signal_names(string, &signo, minsig);
11907 return name ? signo : -1;
11910 static struct var **hashvar (const char *);
11911 static void showvars (const char *, int, int);
11912 static struct var **findvar (struct var **, const char *);
11915 * Initialize the varable symbol tables and import the environment
11919 * This routine initializes the builtin variables. It is called when the
11920 * shell is initialized and again when a shell procedure is spawned.
11925 const struct varinit *ip;
11929 for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
11930 if ((vp->flags & VEXPORT) == 0) {
11931 vpp = hashvar(ip->text);
11934 vp->text = xstrdup(ip->text);
11935 vp->flags = ip->flags;
11936 vp->func = ip->func;
11940 * PS1 depends on uid
11942 if ((vps1.flags & VEXPORT) == 0) {
11943 vpp = hashvar("PS1=");
11946 vps1.text = xstrdup(geteuid() ? "PS1=$ " : "PS1=# ");
11947 vps1.flags = VSTRFIXED|VTEXTFIXED;
11952 * Set the value of a variable. The flags argument is ored with the
11953 * flags of the variable. If val is NULL, the variable is unset.
11957 setvar(const char *name, const char *val, int flags)
11972 if (! is_in_name(*p)) {
11973 if (*p == '\0' || *p == '=')
11979 namelen = p - name;
11981 error("%.*s: bad variable name", namelen, name);
11982 len = namelen + 2; /* 2 is space for '=' and '\0' */
11986 len += vallen = strlen(val);
11989 nameeq = xmalloc(len);
11990 memcpy(nameeq, name, namelen);
11991 nameeq[namelen] = '=';
11993 memcpy(nameeq + namelen + 1, val, vallen + 1);
11995 nameeq[namelen + 1] = '\0';
11997 setvareq(nameeq, flags);
12004 * Same as setvar except that the variable and value are passed in
12005 * the first argument as name=value. Since the first argument will
12006 * be actually stored in the table, it should not be a string that
12011 setvareq(char *s, int flags)
12013 struct var *vp, **vpp;
12016 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
12017 if ((vp = *findvar(vpp, s))) {
12018 if (vp->flags & VREADONLY) {
12019 size_t len = strchr(s, '=') - s;
12020 error("%.*s: is read only", len, s);
12024 if (vp->func && (flags & VNOFUNC) == 0)
12025 (*vp->func)(strchr(s, '=') + 1);
12027 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12030 vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
12031 vp->flags |= flags;
12036 * We could roll this to a function, to handle it as
12037 * a regular variable function callback, but why bother?
12039 if (iflag && (vp == &vmpath || (vp == &vmail && !mpathset())))
12046 vp = xmalloc(sizeof (*vp));
12057 * Process a linked list of variable assignments.
12061 listsetvar(struct strlist *mylist)
12063 struct strlist *lp;
12066 for (lp = mylist ; lp ; lp = lp->next) {
12067 setvareq(xstrdup(lp->text), 0);
12075 * Find the value of a variable. Returns NULL if not set.
12078 static const char *
12079 lookupvar(const char *name)
12083 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12084 return strchr(v->text, '=') + 1;
12092 * Search the environment of a builtin command.
12095 static const char *
12096 bltinlookup(const char *name)
12098 const struct strlist *sp;
12100 for (sp = cmdenviron ; sp ; sp = sp->next) {
12101 if (varequal(sp->text, name))
12102 return strchr(sp->text, '=') + 1;
12104 return lookupvar(name);
12110 * Generate a list of exported variables. This routine is used to construct
12111 * the third argument to execve when executing a program.
12123 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12124 for (vp = *vpp ; vp ; vp = vp->next)
12125 if (vp->flags & VEXPORT)
12128 ep = env = stalloc((nenv + 1) * sizeof *env);
12129 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12130 for (vp = *vpp ; vp ; vp = vp->next)
12131 if (vp->flags & VEXPORT)
12140 * Called when a shell procedure is invoked to clear out nonexported
12141 * variables. It is also necessary to reallocate variables of with
12142 * VSTACK set since these are currently allocated on the stack.
12148 struct var *vp, **prev;
12150 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12151 for (prev = vpp ; (vp = *prev) != NULL ; ) {
12152 if ((vp->flags & VEXPORT) == 0) {
12154 if ((vp->flags & VTEXTFIXED) == 0)
12156 if ((vp->flags & VSTRFIXED) == 0)
12159 if (vp->flags & VSTACK) {
12160 vp->text = xstrdup(vp->text);
12161 vp->flags &=~ VSTACK;
12173 * Command to list all variables which are set. Currently this command
12174 * is invoked from the set command when the set command is called without
12179 showvarscmd(int argc, char **argv)
12181 showvars(nullstr, VUNSET, VUNSET);
12188 * The export and readonly commands.
12192 exportcmd(int argc, char **argv)
12197 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12200 listsetvar(cmdenviron);
12201 pflag = (nextopt("p") == 'p');
12202 if (argc > 1 && !pflag) {
12203 while ((name = *argptr++) != NULL) {
12204 if ((p = strchr(name, '=')) != NULL) {
12207 if ((vp = *findvar(hashvar(name), name))) {
12212 setvar(name, p, flag);
12216 showvars(argv[0], flag, 0);
12223 * The "local" command.
12226 /* funcnest nonzero if we are currently evaluating a function */
12229 localcmd(int argc, char **argv)
12234 error("Not in a function");
12235 while ((name = *argptr++) != NULL) {
12243 * Make a variable a local variable. When a variable is made local, it's
12244 * value and flags are saved in a localvar structure. The saved values
12245 * will be restored when the shell function returns. We handle the name
12246 * "-" as a special case.
12250 mklocal(char *name)
12252 struct localvar *lvp;
12257 lvp = xmalloc(sizeof (struct localvar));
12258 if (name[0] == '-' && name[1] == '\0') {
12260 p = xmalloc(sizeof optet_vals);
12261 lvp->text = memcpy(p, optet_vals, sizeof optet_vals);
12264 vpp = hashvar(name);
12265 vp = *findvar(vpp, name);
12267 if (strchr(name, '='))
12268 setvareq(xstrdup(name), VSTRFIXED);
12270 setvar(name, NULL, VSTRFIXED);
12271 vp = *vpp; /* the new variable */
12273 lvp->flags = VUNSET;
12275 lvp->text = vp->text;
12276 lvp->flags = vp->flags;
12277 vp->flags |= VSTRFIXED|VTEXTFIXED;
12278 if (strchr(name, '='))
12279 setvareq(xstrdup(name), 0);
12283 lvp->next = localvars;
12290 * Called after a function returns.
12295 struct localvar *lvp;
12298 while ((lvp = localvars) != NULL) {
12299 localvars = lvp->next;
12301 if (vp == NULL) { /* $- saved */
12302 memcpy(optet_vals, lvp->text, sizeof optet_vals);
12304 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12305 (void)unsetvar(vp->text);
12307 if ((vp->flags & VTEXTFIXED) == 0)
12309 vp->flags = lvp->flags;
12310 vp->text = lvp->text;
12318 setvarcmd(int argc, char **argv)
12321 return unsetcmd(argc, argv);
12322 else if (argc == 3)
12323 setvar(argv[1], argv[2], 0);
12325 error("List assignment not implemented");
12331 * The unset builtin command. We unset the function before we unset the
12332 * variable to allow a function to be unset when there is a readonly variable
12333 * with the same name.
12337 unsetcmd(int argc, char **argv)
12345 while ((i = nextopt("vf")) != '\0') {
12351 if (flg_func == 0 && flg_var == 0)
12354 for (ap = argptr; *ap ; ap++) {
12358 ret |= unsetvar(*ap);
12365 * Unset the specified variable.
12369 unsetvar(const char *s)
12374 vpp = findvar(hashvar(s), s);
12377 if (vp->flags & VREADONLY)
12380 if (*(strchr(vp->text, '=') + 1) != '\0')
12381 setvar(s, nullstr, 0);
12382 vp->flags &= ~VEXPORT;
12383 vp->flags |= VUNSET;
12384 if ((vp->flags & VSTRFIXED) == 0) {
12385 if ((vp->flags & VTEXTFIXED) == 0)
12400 * Find the appropriate entry in the hash table from the name.
12403 static struct var **
12404 hashvar(const char *p)
12406 unsigned int hashval;
12408 hashval = ((unsigned char) *p) << 4;
12409 while (*p && *p != '=')
12410 hashval += (unsigned char) *p++;
12411 return &vartab[hashval % VTABSIZE];
12417 * Returns true if the two strings specify the same varable. The first
12418 * variable name is terminated by '='; the second may be terminated by
12419 * either '=' or '\0'.
12423 varequal(const char *p, const char *q)
12425 while (*p == *q++) {
12429 if (*p == '=' && *(q - 1) == '\0')
12435 showvars(const char *myprefix, int mask, int xor)
12439 const char *sep = myprefix == nullstr ? myprefix : spcstr;
12441 for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
12442 for (vp = *vpp ; vp ; vp = vp->next) {
12443 if ((vp->flags & mask) ^ xor) {
12447 p = strchr(vp->text, '=') + 1;
12448 len = p - vp->text;
12449 p = single_quote(p);
12451 printf("%s%s%.*s%s\n", myprefix, sep, len,
12459 static struct var **
12460 findvar(struct var **vpp, const char *name)
12462 for (; *vpp; vpp = &(*vpp)->next) {
12463 if (varequal((*vpp)->text, name)) {
12471 * Copyright (c) 1999 Herbert Xu <herbert@debian.org>
12472 * This file contains code for the times builtin.
12473 * $Id: ash.c,v 1.43 2001/12/31 06:12:48 aaronl Exp $
12475 static int timescmd (int argc, char **argv)
12478 long int clk_tck = sysconf(_SC_CLK_TCK);
12481 printf("%dm%fs %dm%fs\n%dm%fs %dm%fs\n",
12482 (int) (buf.tms_utime / clk_tck / 60),
12483 ((double) buf.tms_utime) / clk_tck,
12484 (int) (buf.tms_stime / clk_tck / 60),
12485 ((double) buf.tms_stime) / clk_tck,
12486 (int) (buf.tms_cutime / clk_tck / 60),
12487 ((double) buf.tms_cutime) / clk_tck,
12488 (int) (buf.tms_cstime / clk_tck / 60),
12489 ((double) buf.tms_cstime) / clk_tck);
12493 #ifdef ASH_MATH_SUPPORT
12494 /* The let builtin. */
12495 int letcmd(int argc, char **argv)
12500 char *tmp, *expression, p[13];
12501 expression = strchr(argv[1], '=');
12503 /* Cannot use 'error()' here, or the return code
12504 * will be incorrect */
12505 out2fmt("sh: let: syntax error: \"%s\"\n", argv[1]);
12508 *expression = '\0';
12509 tmp = ++expression;
12510 result = arith(tmp, &errcode);
12512 /* Cannot use 'error()' here, or the return code
12513 * will be incorrect */
12514 out2fmt("sh: let: ");
12516 out2fmt("divide by zero");
12518 out2fmt("syntax error: \"%s=%s\"\n", argv[1], expression);
12521 snprintf(p, 12, "%ld", result);
12522 setvar(argv[1], xstrdup(p), 0);
12523 } else if (argc >= 3)
12524 synerror("invalid operand");
12532 * Copyright (c) 1989, 1991, 1993, 1994
12533 * The Regents of the University of California. All rights reserved.
12535 * This code is derived from software contributed to Berkeley by
12536 * Kenneth Almquist.
12538 * Redistribution and use in source and binary forms, with or without
12539 * modification, are permitted provided that the following conditions
12541 * 1. Redistributions of source code must retain the above copyright
12542 * notice, this list of conditions and the following disclaimer.
12543 * 2. Redistributions in binary form must reproduce the above copyright
12544 * notice, this list of conditions and the following disclaimer in the
12545 * documentation and/or other materials provided with the distribution.
12547 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
12548 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
12550 * 4. Neither the name of the University nor the names of its contributors
12551 * may be used to endorse or promote products derived from this software
12552 * without specific prior written permission.
12554 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
12555 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
12556 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
12557 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
12558 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
12559 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
12560 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
12561 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
12562 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
12563 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF