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 * Copyright (c) 1997-2003 Herbert Xu <herbert@debian.org>
9 * was re-ported from NetBSD and debianized.
12 * This code is derived from software contributed to Berkeley by
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 * General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program; if not, write to the Free Software
27 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 * Original BSD copyright notice is retained at the end of this file.
33 * rewrite arith.y to micro stack based cryptic algorithm by
34 * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
36 * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2003 to be
37 * used in busybox and size optimizations,
38 * support locale, rewrited arith (see notes to this)
44 * The follow should be set to reflect the type of system you have:
45 * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
46 * define SYSV if you are running under System V.
47 * define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
48 * define DEBUG=2 to compile in and turn on debugging.
50 * When debugging is on, debugging info will be written to ./trace and
51 * a quit signal will generate a core dump.
64 #include <sys/types.h>
65 #include <sys/cdefs.h>
66 #include <sys/ioctl.h>
67 #include <sys/param.h>
68 #include <sys/resource.h>
98 #ifdef CONFIG_ASH_JOB_CONTROL
112 static int *dash_errno;
114 #define errno (*dash_errno)
117 #if defined(__uClinux__)
118 #error "Do not even bother, ash will not run on uClinux"
122 #define _DIAGASSERT(assert_expr) assert(assert_expr)
124 #define _DIAGASSERT(assert_expr)
128 #ifdef CONFIG_ASH_ALIAS
129 /* $NetBSD: alias.h,v 1.5 2002/11/24 22:35:38 christos Exp $ */
141 static struct alias *lookupalias(const char *, int);
142 static int aliascmd(int, char **);
143 static int unaliascmd(int, char **);
144 static void rmaliases(void);
145 static int unalias(const char *);
146 static void printalias(const struct alias *);
149 /* $NetBSD: cd.h,v 1.3 2002/11/24 22:35:39 christos Exp $ */
152 static void setpwd(const char *, int);
154 /* $NetBSD: error.h,v 1.15 2002/11/24 22:35:39 christos Exp $ */
158 * Types of operations (passed to the errmsg routine).
162 static const char not_found_msg[] = "%s: not found";
165 #define E_OPEN "No such file" /* opening a file */
166 #define E_CREAT "Directory nonexistent" /* creating a file */
167 #define E_EXEC not_found_msg+4 /* executing a program */
170 * We enclose jmp_buf in a structure so that we can declare pointers to
171 * jump locations. The global variable handler contains the location to
172 * jump to when an exception occurs, and the global variable exception
173 * contains a code identifying the exeception. To implement nested
174 * exception handlers, the user should save the value of handler on entry
175 * to an inner scope, set handler to point to a jmploc structure for the
176 * inner scope, and restore handler on exit from the scope.
183 static struct jmploc *handler;
184 static int exception;
185 static volatile int suppressint;
186 static volatile sig_atomic_t intpending;
188 static int exerrno; /* Last exec error, error for EXEXEC */
191 #define EXINT 0 /* SIGINT received */
192 #define EXERROR 1 /* a generic error */
193 #define EXSHELLPROC 2 /* execute a shell procedure */
194 #define EXEXEC 3 /* command execution failed */
195 #define EXEXIT 4 /* exit the shell */
196 #define EXSIG 5 /* trapped signal in wait(1) */
199 /* do we generate EXSIG events */
201 /* last pending signal */
202 static volatile sig_atomic_t pendingsigs;
205 * These macros allow the user to suspend the handling of interrupt signals
206 * over a period of time. This is similar to SIGHOLD to or sigblock, but
207 * much more efficient and portable. (But hacking the kernel is so much
208 * more fun than worrying about efficiency and portability. :-))
211 #define barrier() ({ __asm__ __volatile__ ("": : :"memory"); })
218 #define SAVEINT(v) ((v) = suppressint)
219 #define RESTOREINT(v) \
222 if ((suppressint = (v)) == 0 && intpending) onint(); \
233 /* EXSIG is turned off by evalbltin(). */
236 static void exraise(int) __attribute__((__noreturn__));
237 static void onint(void) __attribute__((__noreturn__));
239 static void error(const char *, ...) __attribute__((__noreturn__));
240 static void exerror(int, const char *, ...) __attribute__((__noreturn__));
242 static void sh_warnx(const char *, ...);
244 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
247 if (--suppressint == 0 && intpending) {
251 #define INTON inton()
252 static void forceinton(void)
258 #define FORCEINTON forceinton()
263 if (--suppressint == 0 && intpending) onint(); \
270 if (intpending) onint(); \
273 #endif /* CONFIG_ASH_OPTIMIZE_FOR_SIZE */
276 * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
277 * so we use _setjmp instead.
280 #if defined(BSD) && !defined(__SVR4) && !defined(__GLIBC__)
281 #define setjmp(jmploc) _setjmp(jmploc)
282 #define longjmp(jmploc, val) _longjmp(jmploc, val)
285 /* $NetBSD: expand.h,v 1.13 2002/11/24 22:35:40 christos Exp $ */
288 struct strlist *next;
294 struct strlist *list;
295 struct strlist **lastp;
301 #define EXP_FULL 0x1 /* perform word splitting & file globbing */
302 #define EXP_TILDE 0x2 /* do normal tilde expansion */
303 #define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
304 #define EXP_REDIR 0x8 /* file glob for a redirection (1 match only) */
305 #define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
306 #define EXP_RECORD 0x20 /* need to record arguments for ifs breakup */
307 #define EXP_VARTILDE2 0x40 /* expand tildes after colons only */
308 #define EXP_WORD 0x80 /* expand word in parameter expansion */
309 #define EXP_QWORD 0x100 /* expand word in quoted parameter expansion */
313 static void expandarg(union node *, struct arglist *, int);
314 #define rmescapes(p) _rmescapes((p), 0)
315 static char *_rmescapes(char *, int);
316 static int casematch(union node *, char *);
318 #ifdef CONFIG_ASH_MATH_SUPPORT
319 static void expari(int);
322 /* $NetBSD: eval.h,v 1.13 2002/11/24 22:35:39 christos Exp $ */
324 static char *commandname; /* currently executing command */
325 static struct strlist *cmdenviron; /* environment for builtin command */
326 static int exitstatus; /* exit status of last command */
327 static int back_exitstatus; /* exit status of backquoted command */
330 struct backcmd { /* result of evalbackcmd */
331 int fd; /* file descriptor to read from */
332 char *buf; /* buffer */
333 int nleft; /* number of chars in buffer */
334 struct job *jp; /* job structure for command */
338 * This file was generated by the mknodes program.
374 union node *redirect;
381 struct nodelist *cmdlist;
388 union node *redirect;
403 union node *elsepart;
434 struct nodelist *backquote;
474 struct nredir nredir;
475 struct nbinary nbinary;
479 struct nclist nclist;
489 struct nodelist *next;
500 static void freefunc(struct funcnode *);
501 /* $NetBSD: parser.h,v 1.15 2002/11/24 22:35:42 christos Exp $ */
503 /* control characters in argument strings */
504 #define CTL_FIRST '\201' /* first 'special' character */
505 #define CTLESC '\201' /* escape next character */
506 #define CTLVAR '\202' /* variable defn */
507 #define CTLENDVAR '\203'
508 #define CTLBACKQ '\204'
509 #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
510 /* CTLBACKQ | CTLQUOTE == '\205' */
511 #define CTLARI '\206' /* arithmetic expression */
512 #define CTLENDARI '\207'
513 #define CTLQUOTEMARK '\210'
514 #define CTL_LAST '\210' /* last 'special' character */
516 /* variable substitution byte (follows CTLVAR) */
517 #define VSTYPE 0x0f /* type of variable substitution */
518 #define VSNUL 0x10 /* colon--treat the empty string as unset */
519 #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
521 /* values of VSTYPE field */
522 #define VSNORMAL 0x1 /* normal variable: $var or ${var} */
523 #define VSMINUS 0x2 /* ${var-text} */
524 #define VSPLUS 0x3 /* ${var+text} */
525 #define VSQUESTION 0x4 /* ${var?message} */
526 #define VSASSIGN 0x5 /* ${var=text} */
527 #define VSTRIMRIGHT 0x6 /* ${var%pattern} */
528 #define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
529 #define VSTRIMLEFT 0x8 /* ${var#pattern} */
530 #define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
531 #define VSLENGTH 0xa /* ${#var} */
533 /* values of checkkwd variable */
538 #define IBUFSIZ (BUFSIZ + 1)
541 * NEOF is returned by parsecmd when it encounters an end of file. It
542 * must be distinct from NULL, so we use the address of a variable that
543 * happens to be handy.
545 static int plinno = 1; /* input line number */
547 /* number of characters left in input buffer */
548 static int parsenleft; /* copy of parsefile->nleft */
549 static int parselleft; /* copy of parsefile->lleft */
551 /* next character in input buffer */
552 static char *parsenextc; /* copy of parsefile->nextc */
553 static struct parsefile basepf; /* top level input file */
554 static char basebuf[IBUFSIZ]; /* buffer for top level input file */
555 static struct parsefile *parsefile = &basepf; /* current input file */
558 static int tokpushback; /* last token pushed back */
559 #define NEOF ((union node *)&tokpushback)
560 static int parsebackquote; /* nonzero if we are inside backquotes */
561 static int doprompt; /* if set, prompt the user */
562 static int needprompt; /* true if interactive and at start of line */
563 static int lasttoken; /* last token read */
564 static char *wordtext; /* text of last word returned by readtoken */
566 static struct nodelist *backquotelist;
567 static union node *redirnode;
568 static struct heredoc *heredoc;
569 static int quoteflag; /* set if (part of) last token was quoted */
570 static int startlinno; /* line # where last token started */
572 static union node *parsecmd(int);
573 static void fixredir(union node *, const char *, int);
574 static const char *const *findkwd(const char *);
575 static char *endofname(const char *);
577 /* $NetBSD: shell.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
579 typedef void *pointer;
581 static char nullstr[1]; /* zero length string */
582 static const char spcstr[] = " ";
583 static const char snlfmt[] = "%s\n";
584 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
585 static const char illnum[] = "Illegal number: %s";
586 static const char homestr[] = "HOME";
589 #define TRACE(param) trace param
590 #define TRACEV(param) tracev param
593 #define TRACEV(param)
596 #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
597 #define __builtin_expect(x, expected_value) (x)
600 #define likely(x) __builtin_expect((x),1)
615 #define TENDBQUOTE 12
633 /* first char is indicating which tokens mark the end of a list */
634 static const char *const tokname_array[] = {
649 /* the following are keywords */
668 static const char *tokname(int tok)
674 sprintf(buf + (tok >= TSEMI), "%s%c",
675 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
679 /* $NetBSD: machdep.h,v 1.10 2002/10/07 14:26:08 christos Exp $ */
682 * Most machines require the value returned from malloc to be aligned
683 * in some way. The following macro will get this right on many machines.
686 #define SHELL_SIZE (sizeof(union {int i; char *cp; double d; }) - 1)
688 * It appears that grabstackstr() will barf with such alignments
689 * because stalloc() will return a string allocated in a new stackblock.
691 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
694 * This file was generated by the mksyntax program.
699 #define CWORD 0 /* character is nothing special */
700 #define CNL 1 /* newline character */
701 #define CBACK 2 /* a backslash character */
702 #define CSQUOTE 3 /* single quote */
703 #define CDQUOTE 4 /* double quote */
704 #define CENDQUOTE 5 /* a terminating quote */
705 #define CBQUOTE 6 /* backwards single quote */
706 #define CVAR 7 /* a dollar sign */
707 #define CENDVAR 8 /* a '}' character */
708 #define CLP 9 /* a left paren in arithmetic */
709 #define CRP 10 /* a right paren in arithmetic */
710 #define CENDFILE 11 /* end of file */
711 #define CCTL 12 /* like CWORD, except it must be escaped */
712 #define CSPCL 13 /* these terminate a word */
713 #define CIGN 14 /* character should be ignored */
715 #ifdef CONFIG_ASH_ALIAS
719 #define PEOA_OR_PEOF PEOA
723 #define PEOA_OR_PEOF PEOF
726 #define is_digit(c) ((unsigned)((c) - '0') <= 9)
727 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
728 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
731 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
732 * (assuming ascii char codes, as the original implementation did)
734 #define is_special(c) \
735 ( (((unsigned int)c) - 33 < 32) \
736 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
738 #define digit_val(c) ((c) - '0')
741 * This file was generated by the mksyntax program.
744 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
745 #define USE_SIT_FUNCTION
748 /* number syntax index */
749 #define BASESYNTAX 0 /* not in quotes */
750 #define DQSYNTAX 1 /* in double quotes */
751 #define SQSYNTAX 2 /* in single quotes */
752 #define ARISYNTAX 3 /* in arithmetic */
754 #ifdef CONFIG_ASH_MATH_SUPPORT
755 static const char S_I_T[][4] = {
756 #ifdef CONFIG_ASH_ALIAS
757 {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
759 {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
760 {CNL, CNL, CNL, CNL}, /* 2, \n */
761 {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
762 {CDQUOTE, CENDQUOTE, CWORD, CWORD}, /* 4, '"' */
763 {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
764 {CSQUOTE, CWORD, CENDQUOTE, CWORD}, /* 6, "'" */
765 {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
766 {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
767 {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
768 {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
769 {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
770 #ifndef USE_SIT_FUNCTION
771 {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
772 {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
773 {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
777 static const char S_I_T[][3] = {
778 #ifdef CONFIG_ASH_ALIAS
779 {CSPCL, CIGN, CIGN}, /* 0, PEOA */
781 {CSPCL, CWORD, CWORD}, /* 1, ' ' */
782 {CNL, CNL, CNL}, /* 2, \n */
783 {CWORD, CCTL, CCTL}, /* 3, !*-/:=?[]~ */
784 {CDQUOTE, CENDQUOTE, CWORD}, /* 4, '"' */
785 {CVAR, CVAR, CWORD}, /* 5, $ */
786 {CSQUOTE, CWORD, CENDQUOTE}, /* 6, "'" */
787 {CSPCL, CWORD, CWORD}, /* 7, ( */
788 {CSPCL, CWORD, CWORD}, /* 8, ) */
789 {CBACK, CBACK, CCTL}, /* 9, \ */
790 {CBQUOTE, CBQUOTE, CWORD}, /* 10, ` */
791 {CENDVAR, CENDVAR, CWORD}, /* 11, } */
792 #ifndef USE_SIT_FUNCTION
793 {CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
794 {CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
795 {CCTL, CCTL, CCTL} /* 14, CTLESC ... */
798 #endif /* CONFIG_ASH_MATH_SUPPORT */
800 #ifdef USE_SIT_FUNCTION
802 #define U_C(c) ((unsigned char)(c))
804 static int SIT(int c, int syntax)
806 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
807 #ifdef CONFIG_ASH_ALIAS
808 static const char syntax_index_table[] = {
809 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
810 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
811 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
815 static const char syntax_index_table[] = {
816 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
817 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
818 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
825 if (c == PEOF) /* 2^8+2 */
827 #ifdef CONFIG_ASH_ALIAS
828 if (c == PEOA) /* 2^8+1 */
832 if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
835 s = strchr(spec_symbls, c);
836 if (s == 0 || *s == 0)
838 indx = syntax_index_table[(s - spec_symbls)];
840 return S_I_T[indx][syntax];
843 #else /* USE_SIT_FUNCTION */
845 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
847 #ifdef CONFIG_ASH_ALIAS
848 #define CSPCL_CIGN_CIGN_CIGN 0
849 #define CSPCL_CWORD_CWORD_CWORD 1
850 #define CNL_CNL_CNL_CNL 2
851 #define CWORD_CCTL_CCTL_CWORD 3
852 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
853 #define CVAR_CVAR_CWORD_CVAR 5
854 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
855 #define CSPCL_CWORD_CWORD_CLP 7
856 #define CSPCL_CWORD_CWORD_CRP 8
857 #define CBACK_CBACK_CCTL_CBACK 9
858 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
859 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
860 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
861 #define CWORD_CWORD_CWORD_CWORD 13
862 #define CCTL_CCTL_CCTL_CCTL 14
864 #define CSPCL_CWORD_CWORD_CWORD 0
865 #define CNL_CNL_CNL_CNL 1
866 #define CWORD_CCTL_CCTL_CWORD 2
867 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
868 #define CVAR_CVAR_CWORD_CVAR 4
869 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
870 #define CSPCL_CWORD_CWORD_CLP 6
871 #define CSPCL_CWORD_CWORD_CRP 7
872 #define CBACK_CBACK_CCTL_CBACK 8
873 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
874 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
875 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
876 #define CWORD_CWORD_CWORD_CWORD 12
877 #define CCTL_CCTL_CCTL_CCTL 13
880 static const char syntax_index_table[258] = {
881 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
882 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
883 #ifdef CONFIG_ASH_ALIAS
884 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
886 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
887 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
888 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
889 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
890 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
891 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
892 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
893 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
894 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
895 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
896 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
897 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
898 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
899 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
900 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
901 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
902 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
903 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
904 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
905 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
906 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
907 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
908 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
909 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
910 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
911 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
912 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
913 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
914 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
915 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
916 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
917 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
918 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
919 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
920 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
921 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
922 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
923 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
924 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
925 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
926 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
927 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
928 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
929 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
930 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
931 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
932 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
933 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
934 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
935 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
936 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
937 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
938 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
939 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
940 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
941 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
942 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
943 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
944 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
945 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
946 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
947 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
948 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
949 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
950 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
951 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
952 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
953 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
954 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
955 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
956 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
957 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
958 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
959 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
960 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
961 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
962 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
963 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
964 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
965 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
966 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
967 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
968 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
969 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
970 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
971 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
972 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
973 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
974 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
975 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
976 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
977 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
978 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
979 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
980 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
981 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
982 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
983 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
984 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
985 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
986 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
987 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
988 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
989 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
990 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
991 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
992 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
993 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
994 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
995 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
996 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
997 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
998 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
999 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
1000 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
1001 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
1002 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
1003 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
1004 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
1005 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
1006 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
1007 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
1008 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
1009 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
1010 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
1011 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
1012 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
1013 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
1014 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
1015 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
1016 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
1017 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
1018 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
1019 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
1020 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
1021 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
1022 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
1023 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
1024 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
1025 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
1026 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
1027 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
1028 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
1029 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
1030 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
1031 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
1032 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
1033 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
1034 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
1035 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
1036 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
1037 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
1038 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
1039 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
1040 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
1041 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
1042 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
1043 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
1044 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
1045 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
1046 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
1047 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
1048 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
1049 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
1050 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
1051 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
1052 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
1053 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
1054 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
1055 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
1056 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
1057 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
1058 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
1059 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
1060 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
1061 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
1062 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
1063 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
1064 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
1065 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
1066 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
1067 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
1068 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
1069 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
1070 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
1071 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
1072 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
1073 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
1074 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
1075 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
1076 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
1077 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
1078 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
1079 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
1080 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
1081 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
1082 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
1083 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
1084 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
1085 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
1086 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
1087 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
1088 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
1089 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
1090 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
1091 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
1092 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
1093 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
1094 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
1095 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
1096 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
1097 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
1098 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
1099 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
1100 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
1101 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1102 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1103 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1104 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1105 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1106 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1107 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1108 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1109 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1110 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1111 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1112 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1113 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1114 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1115 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1116 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1117 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1118 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1119 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1120 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1121 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1122 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1123 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1124 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1125 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1126 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1127 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1128 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1129 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1130 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1131 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1132 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1133 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1134 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1135 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1136 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1137 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1138 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1139 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1140 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1141 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1144 #endif /* USE_SIT_FUNCTION */
1146 /* $NetBSD: alias.c,v 1.11 2002/11/24 22:35:38 christos Exp $ */
1151 static int funcblocksize; /* size of structures in function */
1152 static int funcstringsize; /* size of strings in node */
1153 static pointer funcblock; /* block to allocate function from */
1154 static char *funcstring; /* block to allocate strings from */
1156 static const short nodesize[26] = {
1157 SHELL_ALIGN(sizeof (struct ncmd)),
1158 SHELL_ALIGN(sizeof (struct npipe)),
1159 SHELL_ALIGN(sizeof (struct nredir)),
1160 SHELL_ALIGN(sizeof (struct nredir)),
1161 SHELL_ALIGN(sizeof (struct nredir)),
1162 SHELL_ALIGN(sizeof (struct nbinary)),
1163 SHELL_ALIGN(sizeof (struct nbinary)),
1164 SHELL_ALIGN(sizeof (struct nbinary)),
1165 SHELL_ALIGN(sizeof (struct nif)),
1166 SHELL_ALIGN(sizeof (struct nbinary)),
1167 SHELL_ALIGN(sizeof (struct nbinary)),
1168 SHELL_ALIGN(sizeof (struct nfor)),
1169 SHELL_ALIGN(sizeof (struct ncase)),
1170 SHELL_ALIGN(sizeof (struct nclist)),
1171 SHELL_ALIGN(sizeof (struct narg)),
1172 SHELL_ALIGN(sizeof (struct narg)),
1173 SHELL_ALIGN(sizeof (struct nfile)),
1174 SHELL_ALIGN(sizeof (struct nfile)),
1175 SHELL_ALIGN(sizeof (struct nfile)),
1176 SHELL_ALIGN(sizeof (struct nfile)),
1177 SHELL_ALIGN(sizeof (struct nfile)),
1178 SHELL_ALIGN(sizeof (struct ndup)),
1179 SHELL_ALIGN(sizeof (struct ndup)),
1180 SHELL_ALIGN(sizeof (struct nhere)),
1181 SHELL_ALIGN(sizeof (struct nhere)),
1182 SHELL_ALIGN(sizeof (struct nnot)),
1186 static void calcsize(union node *);
1187 static void sizenodelist(struct nodelist *);
1188 static union node *copynode(union node *);
1189 static struct nodelist *copynodelist(struct nodelist *);
1190 static char *nodesavestr(char *);
1194 static void evalstring(char *, int);
1195 union node; /* BLETCH for ansi C */
1196 static void evaltree(union node *, int);
1197 static void evalbackcmd(union node *, struct backcmd *);
1199 /* in_function returns nonzero if we are currently evaluating a function */
1200 #define in_function() funcnest
1201 static int evalskip; /* set if we are skipping commands */
1202 static int skipcount; /* number of levels to skip */
1203 static int funcnest; /* depth of function calls */
1205 /* reasons for skipping commands (see comment on breakcmd routine) */
1212 * This file was generated by the mkbuiltins program.
1216 static int bgcmd(int, char **);
1218 static int breakcmd(int, char **);
1219 static int cdcmd(int, char **);
1220 #ifdef CONFIG_ASH_CMDCMD
1221 static int commandcmd(int, char **);
1223 static int dotcmd(int, char **);
1224 static int evalcmd(int, char **);
1225 static int execcmd(int, char **);
1226 static int exitcmd(int, char **);
1227 static int exportcmd(int, char **);
1228 static int falsecmd(int, char **);
1230 static int fgcmd(int, char **);
1232 #ifdef CONFIG_ASH_GETOPTS
1233 static int getoptscmd(int, char **);
1235 static int hashcmd(int, char **);
1236 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
1237 static int helpcmd(int argc, char **argv);
1240 static int jobscmd(int, char **);
1242 #ifdef CONFIG_ASH_MATH_SUPPORT
1243 static int letcmd(int, char **);
1245 static int localcmd(int, char **);
1246 static int pwdcmd(int, char **);
1247 static int readcmd(int, char **);
1248 static int returncmd(int, char **);
1249 static int setcmd(int, char **);
1250 static int shiftcmd(int, char **);
1251 static int timescmd(int, char **);
1252 static int trapcmd(int, char **);
1253 static int truecmd(int, char **);
1254 static int typecmd(int, char **);
1255 static int umaskcmd(int, char **);
1256 static int unsetcmd(int, char **);
1257 static int waitcmd(int, char **);
1258 static int ulimitcmd(int, char **);
1260 static int killcmd(int, char **);
1263 /* $NetBSD: mail.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
1265 #ifdef CONFIG_ASH_MAIL
1266 static void chkmail(void);
1267 static void changemail(const char *);
1270 /* $NetBSD: exec.h,v 1.20 2003/01/22 20:36:04 dsl Exp $ */
1272 /* values of cmdtype */
1273 #define CMDUNKNOWN -1 /* no entry in table for command */
1274 #define CMDNORMAL 0 /* command is an executable program */
1275 #define CMDFUNCTION 1 /* command is a shell function */
1276 #define CMDBUILTIN 2 /* command is a shell builtin */
1280 int (*builtin)(int, char **);
1281 /* unsigned flags; */
1284 #ifdef CONFIG_ASH_CMDCMD
1286 # ifdef CONFIG_ASH_ALIAS
1287 # define COMMANDCMD (builtincmd + 7)
1288 # define EXECCMD (builtincmd + 10)
1290 # define COMMANDCMD (builtincmd + 6)
1291 # define EXECCMD (builtincmd + 9)
1294 # ifdef CONFIG_ASH_ALIAS
1295 # define COMMANDCMD (builtincmd + 6)
1296 # define EXECCMD (builtincmd + 9)
1298 # define COMMANDCMD (builtincmd + 5)
1299 # define EXECCMD (builtincmd + 8)
1302 #else /* ! CONFIG_ASH_CMDCMD */
1304 # ifdef CONFIG_ASH_ALIAS
1305 # define EXECCMD (builtincmd + 9)
1307 # define EXECCMD (builtincmd + 8)
1310 # ifdef CONFIG_ASH_ALIAS
1311 # define EXECCMD (builtincmd + 8)
1313 # define EXECCMD (builtincmd + 7)
1316 #endif /* CONFIG_ASH_CMDCMD */
1318 #define BUILTIN_NOSPEC "0"
1319 #define BUILTIN_SPECIAL "1"
1320 #define BUILTIN_REGULAR "2"
1321 #define BUILTIN_SPEC_REG "3"
1322 #define BUILTIN_ASSIGN "4"
1323 #define BUILTIN_SPEC_ASSG "5"
1324 #define BUILTIN_REG_ASSG "6"
1325 #define BUILTIN_SPEC_REG_ASSG "7"
1327 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1328 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1330 static const struct builtincmd builtincmd[] = {
1331 { BUILTIN_SPEC_REG ".", dotcmd },
1332 { BUILTIN_SPEC_REG ":", truecmd },
1333 #ifdef CONFIG_ASH_ALIAS
1334 { BUILTIN_REG_ASSG "alias", aliascmd },
1337 { BUILTIN_REGULAR "bg", bgcmd },
1339 { BUILTIN_SPEC_REG "break", breakcmd },
1340 { BUILTIN_REGULAR "cd", cdcmd },
1341 { BUILTIN_NOSPEC "chdir", cdcmd },
1342 #ifdef CONFIG_ASH_CMDCMD
1343 { BUILTIN_REGULAR "command", commandcmd },
1345 { BUILTIN_SPEC_REG "continue", breakcmd },
1346 { BUILTIN_SPEC_REG "eval", evalcmd },
1347 { BUILTIN_SPEC_REG "exec", execcmd },
1348 { BUILTIN_SPEC_REG "exit", exitcmd },
1349 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
1350 { BUILTIN_REGULAR "false", falsecmd },
1352 { BUILTIN_REGULAR "fg", fgcmd },
1354 #ifdef CONFIG_ASH_GETOPTS
1355 { BUILTIN_REGULAR "getopts", getoptscmd },
1357 { BUILTIN_NOSPEC "hash", hashcmd },
1358 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
1359 { BUILTIN_NOSPEC "help", helpcmd },
1362 { BUILTIN_REGULAR "jobs", jobscmd },
1363 { BUILTIN_REGULAR "kill", killcmd },
1365 #ifdef CONFIG_ASH_MATH_SUPPORT
1366 { BUILTIN_NOSPEC "let", letcmd },
1368 { BUILTIN_ASSIGN "local", localcmd },
1369 { BUILTIN_NOSPEC "pwd", pwdcmd },
1370 { BUILTIN_REGULAR "read", readcmd },
1371 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
1372 { BUILTIN_SPEC_REG "return", returncmd },
1373 { BUILTIN_SPEC_REG "set", setcmd },
1374 { BUILTIN_SPEC_REG "shift", shiftcmd },
1375 { BUILTIN_SPEC_REG "times", timescmd },
1376 { BUILTIN_SPEC_REG "trap", trapcmd },
1377 { BUILTIN_REGULAR "true", truecmd },
1378 { BUILTIN_NOSPEC "type", typecmd },
1379 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1380 { BUILTIN_REGULAR "umask", umaskcmd },
1381 #ifdef CONFIG_ASH_ALIAS
1382 { BUILTIN_REGULAR "unalias", unaliascmd },
1384 { BUILTIN_SPEC_REG "unset", unsetcmd },
1385 { BUILTIN_REGULAR "wait", waitcmd },
1388 #define NUMBUILTINS (sizeof (builtincmd) / sizeof (struct builtincmd) )
1396 const struct builtincmd *cmd;
1397 struct funcnode *func;
1402 /* action to find_command() */
1403 #define DO_ERR 0x01 /* prints errors */
1404 #define DO_ABS 0x02 /* checks absolute paths */
1405 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
1406 #define DO_ALTPATH 0x08 /* using alternate path */
1407 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
1409 static const char *pathopt; /* set by padvance */
1411 static void shellexec(char **, const char *, int)
1412 __attribute__((__noreturn__));
1413 static char *padvance(const char **, const char *);
1414 static void find_command(char *, struct cmdentry *, int, const char *);
1415 static struct builtincmd *find_builtin(const char *);
1416 static void hashcd(void);
1417 static void changepath(const char *);
1418 static void defun(char *, union node *);
1419 static void unsetfunc(const char *);
1421 #ifdef CONFIG_ASH_MATH_SUPPORT
1422 static int dash_arith(const char *);
1425 /* $NetBSD: init.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
1427 static void reset(void);
1429 /* $NetBSD: var.h,v 1.21 2003/01/22 20:36:04 dsl Exp $ */
1436 #define VEXPORT 0x01 /* variable is exported */
1437 #define VREADONLY 0x02 /* variable cannot be modified */
1438 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1439 #define VTEXTFIXED 0x08 /* text is statically allocated */
1440 #define VSTACK 0x10 /* text is allocated on the stack */
1441 #define VUNSET 0x20 /* the variable is not set */
1442 #define VNOFUNC 0x40 /* don't call the callback function */
1443 #define VNOSET 0x80 /* do not set variable - just readonly test */
1444 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1448 struct var *next; /* next entry in hash list */
1449 int flags; /* flags are defined above */
1450 const char *text; /* name=value */
1451 void (*func)(const char *);
1452 /* function to be called when */
1453 /* the variable gets set/unset */
1457 struct localvar *next; /* next local variable in list */
1458 struct var *vp; /* the variable that was made local */
1459 int flags; /* saved flags */
1460 const char *text; /* saved text */
1464 static struct localvar *localvars;
1470 #ifdef CONFIG_ASH_GETOPTS
1471 static void getoptsreset(const char *);
1474 #ifdef CONFIG_LOCALE_SUPPORT
1476 static void change_lc_all(const char *value);
1477 static void change_lc_ctype(const char *value);
1482 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
1484 static const char defifsvar[] = "IFS= \t\n";
1485 #define defifs (defifsvar + 4)
1487 static const char defifs[] = " \t\n";
1491 static struct var varinit[] = {
1493 { 0, VSTRFIXED|VTEXTFIXED, defifsvar, 0 },
1495 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", 0 },
1498 #ifdef CONFIG_ASH_MAIL
1499 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1500 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1503 { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
1504 { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
1505 { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
1506 { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
1507 #ifdef CONFIG_ASH_GETOPTS
1508 { 0, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1510 #ifdef CONFIG_LOCALE_SUPPORT
1511 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=", change_lc_all},
1512 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=", change_lc_ctype},
1514 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1515 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE=", NULL},
1519 #define vifs varinit[0]
1520 #ifdef CONFIG_ASH_MAIL
1521 #define vmail (&vifs)[1]
1522 #define vmpath (&vmail)[1]
1526 #define vpath (&vmpath)[1]
1527 #define vps1 (&vpath)[1]
1528 #define vps2 (&vps1)[1]
1529 #define vps4 (&vps2)[1]
1530 #define voptind (&vps4)[1]
1532 #define defpath (defpathvar + 5)
1535 * The following macros access the values of the above variables.
1536 * They have to skip over the name. They return the null string
1537 * for unset variables.
1540 #define ifsval() (vifs.text + 4)
1541 #define ifsset() ((vifs.flags & VUNSET) == 0)
1542 #define mailval() (vmail.text + 5)
1543 #define mpathval() (vmpath.text + 9)
1544 #define pathval() (vpath.text + 5)
1545 #define ps1val() (vps1.text + 4)
1546 #define ps2val() (vps2.text + 4)
1547 #define ps4val() (vps4.text + 4)
1548 #define optindval() (voptind.text + 7)
1550 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1552 static void setvar(const char *, const char *, int);
1553 static void setvareq(char *, int);
1554 static void listsetvar(struct strlist *, int);
1555 static char *lookupvar(const char *);
1556 static char *bltinlookup(const char *);
1557 static char **listvars(int, int, char ***);
1558 #define environment() listvars(VEXPORT, VUNSET, 0)
1559 static int showvars(const char *, int, int);
1560 static void poplocalvars(void);
1561 static int unsetvar(const char *);
1562 #ifdef CONFIG_ASH_GETOPTS
1563 static int setvarsafe(const char *, const char *, int);
1565 static int varcmp(const char *, const char *);
1566 static struct var **hashvar(const char *);
1569 static inline int varequal(const char *a, const char *b) {
1570 return !varcmp(a, b);
1574 static int loopnest; /* current loop nesting level */
1577 struct strpush *prev; /* preceding string on stack */
1580 #ifdef CONFIG_ASH_ALIAS
1581 struct alias *ap; /* if push was associated with an alias */
1583 char *string; /* remember the string since it may change */
1587 struct parsefile *prev; /* preceding file on stack */
1588 int linno; /* current line */
1589 int fd; /* file descriptor (or -1 if string) */
1590 int nleft; /* number of chars left in this line */
1591 int lleft; /* number of chars left in this buffer */
1592 char *nextc; /* next char in buffer */
1593 char *buf; /* input buffer */
1594 struct strpush *strpush; /* for pushing strings at this level */
1595 struct strpush basestrpush; /* so pushing one is fast */
1599 * The parsefile structure pointed to by the global variable parsefile
1600 * contains information about the current file being read.
1605 struct redirtab *next;
1610 static struct redirtab *redirlist;
1611 static int nullredirs;
1613 extern char **environ;
1615 /* $NetBSD: output.h,v 1.16 2002/11/24 22:35:42 christos Exp $ */
1618 static void outstr(const char *, FILE *);
1619 static void outcslow(int, FILE *);
1620 static void flushall(void);
1621 static void flushout(FILE *);
1622 static int out1fmt(const char *, ...)
1623 __attribute__((__format__(__printf__,1,2)));
1624 static int fmtstr(char *, size_t, const char *, ...)
1625 __attribute__((__format__(__printf__,3,4)));
1626 static void xwrite(int, const void *, size_t);
1628 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1631 static void out1str(const char *p)
1636 static void out2str(const char *p)
1643 * Initialization code.
1647 * This routine initializes the builtin variables.
1658 * PS1 depends on uid
1660 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1661 vps1.text = "PS1=\\w \\$ ";
1664 vps1.text = "PS1=# ";
1667 end = vp + sizeof(varinit) / sizeof(varinit[0]);
1669 vpp = hashvar(vp->text);
1672 } while (++vp < end);
1681 basepf.nextc = basepf.buf = basebuf;
1686 signal(SIGCHLD, SIG_DFL);
1695 for (envp = environ ; *envp ; envp++) {
1696 if (strchr(*envp, '=')) {
1697 setvareq(*envp, VEXPORT|VTEXTFIXED);
1701 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
1702 setvar("PPID", ppid, 0);
1707 /* PEOF (the end of file marker) */
1710 * The input line number. Input.c just defines this variable, and saves
1711 * and restores it when files are pushed and popped. The user of this
1712 * package must set its value.
1715 static int pgetc(void);
1716 static int pgetc2(void);
1717 static int preadbuffer(void);
1718 static void pungetc(void);
1719 static void pushstring(char *, void *);
1720 static void popstring(void);
1721 static void setinputfile(const char *, int);
1722 static void setinputfd(int, int);
1723 static void setinputstring(char *);
1724 static void popfile(void);
1725 static void popallfiles(void);
1726 static void closescript(void);
1729 /* $NetBSD: jobs.h,v 1.17 2003/01/22 20:36:04 dsl Exp $ */
1732 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
1735 #define FORK_NOJOB 2
1737 /* mode flags for showjob(s) */
1738 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
1739 #define SHOW_PID 0x04 /* include process pid */
1740 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
1744 * A job structure contains information about a job. A job is either a
1745 * single process or a set of processes contained in a pipeline. In the
1746 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1751 pid_t pid; /* process id */
1752 int status; /* last process status from wait() */
1753 char *cmd; /* text of command being run */
1757 struct procstat ps0; /* status of process */
1758 struct procstat *ps; /* status or processes when more than one */
1760 int stopstatus; /* status of a stopped job */
1763 nprocs: 16, /* number of processes */
1765 #define JOBRUNNING 0 /* at least one proc running */
1766 #define JOBSTOPPED 1 /* all procs are stopped */
1767 #define JOBDONE 2 /* all procs are completed */
1769 sigint: 1, /* job was killed by SIGINT */
1770 jobctl: 1, /* job running under job control */
1772 waited: 1, /* true if this entry has been waited for */
1773 used: 1, /* true if this entry is in used */
1774 changed: 1; /* true if status has changed */
1775 struct job *prev_job; /* previous job */
1778 static pid_t backgndpid; /* pid of last background process */
1779 static int job_warning; /* user was warned about stopped jobs */
1781 static int jobctl; /* true if doing job control */
1784 static struct job *makejob(union node *, int);
1785 static int forkshell(struct job *, union node *, int);
1786 static int waitforjob(struct job *);
1787 static int stoppedjobs(void);
1790 #define setjobctl(on) /* do nothing */
1792 static void setjobctl(int);
1793 static void showjobs(FILE *, int);
1796 /* $NetBSD: main.h,v 1.9 2002/11/24 22:35:41 christos Exp $ */
1799 /* pid of main shell */
1801 /* true if we aren't a child of the main shell */
1802 static int rootshell;
1804 static void readcmdfile(char *);
1805 static void cmdloop(int);
1807 /* $NetBSD: memalloc.h,v 1.13 2003/01/22 20:36:04 dsl Exp $ */
1811 struct stack_block *stackp;
1814 struct stackmark *marknext;
1817 /* minimum size of a block */
1818 #define MINSIZE SHELL_ALIGN(504)
1820 struct stack_block {
1821 struct stack_block *prev;
1822 char space[MINSIZE];
1825 static struct stack_block stackbase;
1826 static struct stack_block *stackp = &stackbase;
1827 static struct stackmark *markp;
1828 static char *stacknxt = stackbase.space;
1829 static size_t stacknleft = MINSIZE;
1830 static char *sstrend = stackbase.space + MINSIZE;
1831 static int herefd = -1;
1834 static pointer ckmalloc(size_t);
1835 static pointer ckrealloc(pointer, size_t);
1836 static char *savestr(const char *);
1837 static pointer stalloc(size_t);
1838 static void stunalloc(pointer);
1839 static void setstackmark(struct stackmark *);
1840 static void popstackmark(struct stackmark *);
1841 static void growstackblock(void);
1842 static void *growstackstr(void);
1843 static char *makestrspace(size_t, char *);
1844 static char *stnputs(const char *, size_t, char *);
1845 static char *stputs(const char *, char *);
1848 static inline char *_STPUTC(char c, char *p) {
1855 #define stackblock() ((void *)stacknxt)
1856 #define stackblocksize() stacknleft
1857 #define STARTSTACKSTR(p) ((p) = stackblock())
1858 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1859 #define CHECKSTRSPACE(n, p) \
1863 size_t m = sstrend - q; \
1865 (p) = makestrspace(l, q); \
1868 #define USTPUTC(c, p) (*p++ = (c))
1869 #define STACKSTRNUL(p) ((p) == sstrend? (p = growstackstr(), *p = '\0') : (*p = '\0'))
1870 #define STUNPUTC(p) (--p)
1871 #define STTOPC(p) p[-1]
1872 #define STADJUST(amount, p) (p += (amount))
1874 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1875 #define ungrabstackstr(s, p) stunalloc((s))
1876 #define stackstrend() ((void *)sstrend)
1878 #define ckfree(p) free((pointer)(p))
1880 /* $NetBSD: mystring.h,v 1.10 2002/11/24 22:35:42 christos Exp $ */
1883 #define DOLATSTRLEN 4
1885 static char *prefix(const char *, const char *);
1886 static int number(const char *);
1887 static int is_number(const char *);
1888 static char *single_quote(const char *);
1889 static char *sstrdup(const char *);
1891 #define equal(s1, s2) (strcmp(s1, s2) == 0)
1892 #define scopy(s1, s2) ((void)strcpy(s2, s1))
1894 /* $NetBSD: options.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
1897 int nparam; /* # of positional parameters (without $0) */
1898 unsigned char malloc; /* if parameter list dynamically allocated */
1899 char **p; /* parameter list */
1900 #ifdef CONFIG_ASH_GETOPTS
1901 int optind; /* next parameter to be processed by getopts */
1902 int optoff; /* used by getopts */
1907 #define eflag optlist[0]
1908 #define fflag optlist[1]
1909 #define Iflag optlist[2]
1910 #define iflag optlist[3]
1911 #define mflag optlist[4]
1912 #define nflag optlist[5]
1913 #define sflag optlist[6]
1914 #define xflag optlist[7]
1915 #define vflag optlist[8]
1916 #define Cflag optlist[9]
1917 #define aflag optlist[10]
1918 #define bflag optlist[11]
1919 #define uflag optlist[12]
1920 #define qflag optlist[13]
1923 #define nolog optlist[14]
1924 #define debug optlist[15]
1930 /* $NetBSD: options.c,v 1.33 2003/01/22 20:36:04 dsl Exp $ */
1933 static const char *const optletters_optnames[NOPTS] = {
1954 #define optletters(n) optletters_optnames[(n)][0]
1955 #define optnames(n) (&optletters_optnames[(n)][1])
1958 static char optlist[NOPTS];
1961 static char *arg0; /* value of $0 */
1962 static struct shparam shellparam; /* $@ current positional parameters */
1963 static char **argptr; /* argument list for builtin commands */
1964 static char *optionarg; /* set by nextopt (like getopt) */
1965 static char *optptr; /* used by nextopt */
1967 static char *minusc; /* argument to -c option */
1970 static void procargs(int, char **);
1971 static void optschanged(void);
1972 static void setparam(char **);
1973 static void freeparam(volatile struct shparam *);
1974 static int shiftcmd(int, char **);
1975 static int setcmd(int, char **);
1976 static int nextopt(const char *);
1978 /* $NetBSD: redir.h,v 1.14 2002/11/24 22:35:43 christos Exp $ */
1980 /* flags passed to redirect */
1981 #define REDIR_PUSH 01 /* save previous values of file descriptors */
1982 #define REDIR_SAVEFD2 03 /* set preverrout */
1985 static void redirect(union node *, int);
1986 static void popredir(int);
1987 static void clearredir(int);
1988 static int copyfd(int, int);
1989 static int redirectsafe(union node *, int);
1991 /* $NetBSD: show.h,v 1.6 2003/01/22 20:36:04 dsl Exp $ */
1995 static void showtree(union node *);
1996 static void trace(const char *, ...);
1997 static void tracev(const char *, va_list);
1998 static void trargs(char **);
1999 static void trputc(int);
2000 static void trputs(const char *);
2001 static void opentrace(void);
2004 /* $NetBSD: trap.h,v 1.16 2002/11/24 22:35:43 christos Exp $ */
2007 /* trap handler commands */
2008 static char *trap[NSIG];
2009 /* current value of signal */
2010 static char sigmode[NSIG - 1];
2011 /* indicates specified signal received */
2012 static char gotsig[NSIG - 1];
2014 static void clear_traps(void);
2015 static void setsignal(int);
2016 static void ignoresig(int);
2017 static void onsig(int);
2018 static void dotrap(void);
2019 static void setinteractive(int);
2020 static void exitshell(void) __attribute__((__noreturn__));
2021 static int decode_signal(const char *, int);
2024 * This routine is called when an error or an interrupt occurs in an
2025 * interactive shell and control is returned to the main command loop.
2040 parselleft = parsenleft = 0; /* clear input buffer */
2044 /* from parser.c: */
2057 #ifdef CONFIG_ASH_ALIAS
2058 static struct alias *atab[ATABSIZE];
2060 static void setalias(const char *, const char *);
2061 static struct alias *freealias(struct alias *);
2062 static struct alias **__lookupalias(const char *);
2065 setalias(const char *name, const char *val)
2067 struct alias *ap, **app;
2069 app = __lookupalias(name);
2073 if (!(ap->flag & ALIASINUSE)) {
2076 ap->val = savestr(val);
2077 ap->flag &= ~ALIASDEAD;
2080 ap = ckmalloc(sizeof (struct alias));
2081 ap->name = savestr(name);
2082 ap->val = savestr(val);
2091 unalias(const char *name)
2095 app = __lookupalias(name);
2099 *app = freealias(*app);
2110 struct alias *ap, **app;
2114 for (i = 0; i < ATABSIZE; i++) {
2116 for (ap = *app; ap; ap = *app) {
2117 *app = freealias(*app);
2126 static struct alias *
2127 lookupalias(const char *name, int check)
2129 struct alias *ap = *__lookupalias(name);
2131 if (check && ap && (ap->flag & ALIASINUSE))
2137 * TODO - sort output
2140 aliascmd(int argc, char **argv)
2149 for (i = 0; i < ATABSIZE; i++)
2150 for (ap = atab[i]; ap; ap = ap->next) {
2155 while ((n = *++argv) != NULL) {
2156 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
2157 if ((ap = *__lookupalias(n)) == NULL) {
2158 fprintf(stderr, "%s: %s not found\n", "alias", n);
2172 unaliascmd(int argc, char **argv)
2176 while ((i = nextopt("a")) != '\0') {
2182 for (i = 0; *argptr; argptr++) {
2183 if (unalias(*argptr)) {
2184 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
2192 static struct alias *
2193 freealias(struct alias *ap) {
2196 if (ap->flag & ALIASINUSE) {
2197 ap->flag |= ALIASDEAD;
2209 printalias(const struct alias *ap) {
2210 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
2213 static struct alias **
2214 __lookupalias(const char *name) {
2215 unsigned int hashval;
2222 ch = (unsigned char)*p;
2226 ch = (unsigned char)*++p;
2228 app = &atab[hashval % ATABSIZE];
2230 for (; *app; app = &(*app)->next) {
2231 if (equal(name, (*app)->name)) {
2238 #endif /* CONFIG_ASH_ALIAS */
2241 /* $NetBSD: cd.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
2244 * The cd and pwd commands.
2247 #define CD_PHYSICAL 1
2250 static int docd(const char *, int);
2251 static int cdopt(void);
2253 static char *curdir = nullstr; /* current working directory */
2254 static char *physdir = nullstr; /* physical working directory */
2263 while ((i = nextopt("LP"))) {
2265 flags ^= CD_PHYSICAL;
2274 cdcmd(int argc, char **argv)
2286 dest = bltinlookup(homestr);
2287 else if (dest[0] == '-' && dest[1] == '\0') {
2288 dest = bltinlookup("OLDPWD");
2311 if (!(path = bltinlookup("CDPATH"))) {
2319 p = padvance(&path, dest);
2320 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2324 if (!docd(p, flags))
2329 error("can't cd to %s", dest);
2332 if (flags & CD_PRINT)
2333 out1fmt(snlfmt, curdir);
2339 * Update curdir (the name of the current directory) in response to a
2343 static inline const char *
2344 updatepwd(const char *dir)
2351 cdcomppath = sstrdup(dir);
2354 if (curdir == nullstr)
2356 new = stputs(curdir, new);
2358 new = makestrspace(strlen(dir) + 2, new);
2359 lim = stackblock() + 1;
2363 if (new > lim && *lim == '/')
2368 if (dir[1] == '/' && dir[2] != '/') {
2374 p = strtok(cdcomppath, "/");
2378 if (p[1] == '.' && p[2] == '\0') {
2385 } else if (p[1] == '\0')
2389 new = stputs(p, new);
2397 return stackblock();
2401 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2402 * know that the current directory has changed.
2406 docd(const char *dest, int flags)
2408 const char *dir = 0;
2411 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2414 if (!(flags & CD_PHYSICAL)) {
2415 dir = updatepwd(dest);
2430 * Find out what the current directory is. If we already know the current
2431 * directory, this routine returns immediately.
2433 static inline char *
2436 char *dir = getcwd(0, 0);
2437 return dir ? dir : nullstr;
2441 pwdcmd(int argc, char **argv)
2444 const char *dir = curdir;
2448 if (physdir == nullstr)
2452 out1fmt(snlfmt, dir);
2457 setpwd(const char *val, int setold)
2461 oldcur = dir = curdir;
2464 setvar("OLDPWD", oldcur, VEXPORT);
2467 if (physdir != nullstr) {
2468 if (physdir != oldcur)
2472 if (oldcur == val || !val) {
2479 if (oldcur != dir && oldcur != nullstr) {
2484 setvar("PWD", dir, VEXPORT);
2487 /* $NetBSD: error.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
2490 * Errors and exceptions.
2494 * Code to handle exceptions in C.
2499 static void exverror(int, const char *, va_list)
2500 __attribute__((__noreturn__));
2503 * Called to raise an exception. Since C doesn't include exceptions, we
2504 * just do a longjmp to the exception handler. The type of exception is
2505 * stored in the global variable "exception".
2512 if (handler == NULL)
2518 longjmp(handler->loc, 1);
2523 * Called from trap.c when a SIGINT is received. (If the user specifies
2524 * that SIGINT is to be trapped or ignored using the trap builtin, then
2525 * this routine is not called.) Suppressint is nonzero when interrupts
2526 * are held using the INTOFF macro. (The test for iflag is just
2527 * defensive programming.)
2537 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
2538 if (!(rootshell && iflag)) {
2539 signal(SIGINT, SIG_DFL);
2549 exvwarning(const char *msg, va_list ap)
2562 fprintf(errs, fmt, name, startlinno);
2563 vfprintf(errs, msg, ap);
2564 outcslow('\n', errs);
2568 * Exverror is called to raise the error exception. If the second argument
2569 * is not NULL then error prints an error message using printf style
2570 * formatting. It then raises the error exception.
2573 exverror(int cond, const char *msg, va_list ap)
2577 TRACE(("exverror(%d, \"", cond));
2579 TRACE(("\") pid=%d\n", getpid()));
2581 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
2584 exvwarning(msg, ap);
2593 error(const char *msg, ...)
2598 exverror(EXERROR, msg, ap);
2605 exerror(int cond, const char *msg, ...)
2610 exverror(cond, msg, ap);
2616 * error/warning routines for external builtins
2620 sh_warnx(const char *fmt, ...)
2625 exvwarning(fmt, ap);
2631 * Return a string describing an error. The returned string may be a
2632 * pointer to a static buffer that will be overwritten on the next call.
2633 * Action describes the operation that got the error.
2637 errmsg(int e, const char *em)
2639 if(e == ENOENT || e == ENOTDIR) {
2647 /* $NetBSD: eval.c,v 1.71 2003/01/23 03:33:16 rafal Exp $ */
2650 * Evaluate a command.
2653 /* flags in argument to evaltree */
2654 #define EV_EXIT 01 /* exit after evaluating tree */
2655 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2656 #define EV_BACKCMD 04 /* command executing within back quotes */
2659 static void evalloop(union node *, int);
2660 static void evalfor(union node *, int);
2661 static void evalcase(union node *, int);
2662 static void evalsubshell(union node *, int);
2663 static void expredir(union node *);
2664 static void evalpipe(union node *, int);
2665 static void evalcommand(union node *, int);
2666 static int evalbltin(const struct builtincmd *, int, char **);
2667 static int evalfun(struct funcnode *, int, char **, int);
2668 static void prehash(union node *);
2669 static int bltincmd(int, char **);
2672 static const struct builtincmd bltin = {
2678 * Called to reset things after an exception.
2682 * The eval commmand.
2686 evalcmd(int argc, char **argv)
2695 STARTSTACKSTR(concat);
2698 concat = stputs(p, concat);
2699 if ((p = *ap++) == NULL)
2701 STPUTC(' ', concat);
2703 STPUTC('\0', concat);
2704 p = grabstackstr(concat);
2706 evalstring(p, EV_TESTED);
2713 * Execute a command or commands contained in a string.
2717 evalstring(char *s, int flag)
2720 struct stackmark smark;
2722 setstackmark(&smark);
2725 while ((n = parsecmd(0)) != NEOF) {
2727 popstackmark(&smark);
2732 popstackmark(&smark);
2738 * Evaluate a parse tree. The value is left in the global variable
2743 evaltree(union node *n, int flags)
2746 void (*evalfn)(union node *, int);
2750 TRACE(("evaltree(NULL) called\n"));
2753 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
2754 getpid(), n, n->type, flags));
2758 out1fmt("Node type = %d\n", n->type);
2763 evaltree(n->nnot.com, EV_TESTED);
2764 status = !exitstatus;
2767 expredir(n->nredir.redirect);
2768 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
2770 evaltree(n->nredir.n, flags & EV_TESTED);
2771 status = exitstatus;
2776 evalfn = evalcommand;
2778 if (eflag && !(flags & EV_TESTED))
2790 evalfn = evalsubshell;
2802 #error NAND + 1 != NOR
2804 #if NOR + 1 != NSEMI
2805 #error NOR + 1 != NSEMI
2807 isor = n->type - NAND;
2810 (flags | ((isor >> 1) - 1)) & EV_TESTED
2812 if (!exitstatus == isor)
2824 evaltree(n->nif.test, EV_TESTED);
2827 if (exitstatus == 0) {
2830 } else if (n->nif.elsepart) {
2831 n = n->nif.elsepart;
2836 defun(n->narg.text, n->narg.next);
2840 exitstatus = status;
2846 if (flags & EV_EXIT || checkexit & exitstatus)
2851 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
2854 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
2858 evalloop(union node *n, int flags)
2868 evaltree(n->nbinary.ch1, EV_TESTED);
2870 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2874 if (evalskip == SKIPBREAK && --skipcount <= 0)
2879 if (n->type != NWHILE)
2883 evaltree(n->nbinary.ch2, flags);
2884 status = exitstatus;
2889 exitstatus = status;
2895 evalfor(union node *n, int flags)
2897 struct arglist arglist;
2900 struct stackmark smark;
2902 setstackmark(&smark);
2903 arglist.lastp = &arglist.list;
2904 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2905 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2910 *arglist.lastp = NULL;
2915 for (sp = arglist.list ; sp ; sp = sp->next) {
2916 setvar(n->nfor.var, sp->text, 0);
2917 evaltree(n->nfor.body, flags);
2919 if (evalskip == SKIPCONT && --skipcount <= 0) {
2923 if (evalskip == SKIPBREAK && --skipcount <= 0)
2930 popstackmark(&smark);
2936 evalcase(union node *n, int flags)
2940 struct arglist arglist;
2941 struct stackmark smark;
2943 setstackmark(&smark);
2944 arglist.lastp = &arglist.list;
2945 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2947 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2948 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2949 if (casematch(patp, arglist.list->text)) {
2950 if (evalskip == 0) {
2951 evaltree(cp->nclist.body, flags);
2958 popstackmark(&smark);
2964 * Kick off a subshell to evaluate a tree.
2968 evalsubshell(union node *n, int flags)
2971 int backgnd = (n->type == NBACKGND);
2974 expredir(n->nredir.redirect);
2975 if (!backgnd && flags & EV_EXIT && !trap[0])
2979 if (forkshell(jp, n, backgnd) == 0) {
2983 flags &=~ EV_TESTED;
2985 redirect(n->nredir.redirect, 0);
2986 evaltreenr(n->nredir.n, flags);
2991 status = waitforjob(jp);
2992 exitstatus = status;
2999 * Compute the names of the files in a redirection list.
3003 expredir(union node *n)
3007 for (redir = n ; redir ; redir = redir->nfile.next) {
3009 fn.lastp = &fn.list;
3010 switch (redir->type) {
3016 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
3017 redir->nfile.expfname = fn.list->text;
3021 if (redir->ndup.vname) {
3022 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
3023 fixredir(redir, fn.list->text, 1);
3033 * Evaluate a pipeline. All the processes in the pipeline are children
3034 * of the process creating the pipeline. (This differs from some versions
3035 * of the shell, which make the last process in a pipeline the parent
3040 evalpipe(union node *n, int flags)
3043 struct nodelist *lp;
3048 TRACE(("evalpipe(0x%lx) called\n", (long)n));
3050 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
3054 jp = makejob(n, pipelen);
3056 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
3060 if (pipe(pip) < 0) {
3062 error("Pipe call failed");
3065 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
3078 evaltreenr(lp->n, flags);
3086 if (n->npipe.backgnd == 0) {
3087 exitstatus = waitforjob(jp);
3088 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
3096 * Execute a command inside back quotes. If it's a builtin command, we
3097 * want to save its output in a block obtained from malloc. Otherwise
3098 * we fork off a subprocess and get the output of the command via a pipe.
3099 * Should be called with interrupts off.
3103 evalbackcmd(union node *n, struct backcmd *result)
3115 saveherefd = herefd;
3123 error("Pipe call failed");
3125 if (forkshell(jp, n, FORK_NOJOB) == 0) {
3134 evaltreenr(n, EV_EXIT);
3138 result->fd = pip[0];
3141 herefd = saveherefd;
3143 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
3144 result->fd, result->buf, result->nleft, result->jp));
3147 #ifdef CONFIG_ASH_CMDCMD
3148 static inline char **
3149 parse_command_args(char **argv, const char **path)
3161 if (c == '-' && !*cp) {
3171 /* run 'typecmd' for other options */
3174 } while ((c = *cp++));
3183 * Execute a simple command.
3187 evalcommand(union node *cmd, int flags)
3189 struct stackmark smark;
3191 struct arglist arglist;
3192 struct arglist varlist;
3195 const struct strlist *sp;
3196 struct cmdentry cmdentry;
3205 /* First expand the arguments. */
3206 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
3207 setstackmark(&smark);
3208 back_exitstatus = 0;
3210 cmdentry.cmdtype = CMDBUILTIN;
3211 cmdentry.u.cmd = &bltin;
3212 varlist.lastp = &varlist.list;
3213 *varlist.lastp = NULL;
3214 arglist.lastp = &arglist.list;
3215 *arglist.lastp = NULL;
3218 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
3219 struct strlist **spp;
3221 spp = arglist.lastp;
3222 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3223 for (sp = *spp; sp; sp = sp->next)
3227 argv = nargv = stalloc(sizeof (char *) * (argc + 1));
3228 for (sp = arglist.list ; sp ; sp = sp->next) {
3229 TRACE(("evalcommand arg: %s\n", sp->text));
3230 *nargv++ = sp->text;
3235 if (iflag && funcnest == 0 && argc > 0)
3236 lastarg = nargv[-1];
3239 expredir(cmd->ncmd.redirect);
3240 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
3243 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
3244 struct strlist **spp;
3247 spp = varlist.lastp;
3248 expandarg(argp, &varlist, EXP_VARTILDE);
3251 * Modify the command lookup path, if a PATH= assignment
3255 if (varequal(p, path))
3259 /* Print the command if xflag is set. */
3262 const char *p = " %s";
3265 dprintf(preverrout_fd, p, ps4val());
3268 for(n = 0; n < 2; n++) {
3270 dprintf(preverrout_fd, p, sp->text);
3278 xwrite(preverrout_fd, "\n", 1);
3284 /* Now locate the command. */
3286 const char *oldpath;
3287 int cmd_flag = DO_ERR;
3292 find_command(argv[0], &cmdentry, cmd_flag, path);
3293 if (cmdentry.cmdtype == CMDUNKNOWN) {
3299 /* implement bltin and command here */
3300 if (cmdentry.cmdtype != CMDBUILTIN)
3303 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
3304 if (cmdentry.u.cmd == EXECCMD)
3306 #ifdef CONFIG_ASH_CMDCMD
3307 if (cmdentry.u.cmd == COMMANDCMD) {
3310 nargv = parse_command_args(argv, &path);
3313 argc -= nargv - argv;
3315 cmd_flag |= DO_NOFUNC;
3323 /* We have a redirection error. */
3327 exitstatus = status;
3331 /* Execute the command. */
3332 switch (cmdentry.cmdtype) {
3334 /* Fork off a child process if necessary. */
3335 if (!(flags & EV_EXIT) || trap[0]) {
3337 jp = makejob(cmd, 1);
3338 if (forkshell(jp, cmd, FORK_FG) != 0) {
3339 exitstatus = waitforjob(jp);
3345 listsetvar(varlist.list, VEXPORT|VSTACK);
3346 shellexec(argv, path, cmdentry.u.index);
3350 cmdenviron = varlist.list;
3352 struct strlist *list = cmdenviron;
3354 if (spclbltin > 0 || argc == 0) {
3356 if (cmd_is_exec && argc > 1)
3359 listsetvar(list, i);
3361 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
3376 exit_status = j + 128;
3377 exitstatus = exit_status;
3379 if (i == EXINT || spclbltin > 0) {
3381 longjmp(handler->loc, 1);
3388 listsetvar(varlist.list, 0);
3389 if (evalfun(cmdentry.u.func, argc, argv, flags))
3395 popredir(cmd_is_exec);
3397 /* dsl: I think this is intended to be used to support
3398 * '_' in 'vi' command mode during line editing...
3399 * However I implemented that within libedit itself.
3401 setvar("_", lastarg, 0);
3402 popstackmark(&smark);
3406 evalbltin(const struct builtincmd *cmd, int argc, char **argv) {
3407 char *volatile savecmdname;
3408 struct jmploc *volatile savehandler;
3409 struct jmploc jmploc;
3412 savecmdname = commandname;
3413 if ((i = setjmp(jmploc.loc)))
3415 savehandler = handler;
3417 commandname = argv[0];
3419 optptr = NULL; /* initialize nextopt */
3420 exitstatus = (*cmd->builtin)(argc, argv);
3423 exitstatus |= ferror(stdout);
3424 commandname = savecmdname;
3426 handler = savehandler;
3432 evalfun(struct funcnode *func, int argc, char **argv, int flags)
3434 volatile struct shparam saveparam;
3435 struct localvar *volatile savelocalvars;
3436 struct jmploc *volatile savehandler;
3437 struct jmploc jmploc;
3440 saveparam = shellparam;
3441 savelocalvars = localvars;
3442 if ((e = setjmp(jmploc.loc))) {
3446 savehandler = handler;
3449 shellparam.malloc = 0;
3452 shellparam.nparam = argc - 1;
3453 shellparam.p = argv + 1;
3454 #ifdef CONFIG_ASH_GETOPTS
3455 shellparam.optind = 1;
3456 shellparam.optoff = -1;
3459 evaltree(&func->n, flags & EV_TESTED);
3465 localvars = savelocalvars;
3466 freeparam(&shellparam);
3467 shellparam = saveparam;
3468 handler = savehandler;
3470 if (evalskip == SKIPFUNC) {
3479 * Search for a command. This is called before we fork so that the
3480 * location of the command will be available in the parent as well as
3485 prehash(union node *n)
3487 struct cmdentry entry;
3489 if (n->type == NCMD && n->ncmd.args)
3490 find_command(n->ncmd.args->narg.text, &entry, 0, pathval());
3496 * Builtin commands. Builtin commands whose functions are closely
3497 * tied to evaluation are implemented here.
3505 bltincmd(int argc, char **argv)
3508 * Preserve exitstatus of a previous possible redirection
3511 return back_exitstatus;
3516 * Handle break and continue commands. Break, continue, and return are
3517 * all handled by setting the evalskip flag. The evaluation routines
3518 * above all check this flag, and if it is set they start skipping
3519 * commands rather than executing them. The variable skipcount is
3520 * the number of loops to break/continue, or the number of function
3521 * levels to return. (The latter is always 1.) It should probably
3522 * be an error to break out of more loops than exist, but it isn't
3523 * in the standard shell so we don't make it one here.
3527 breakcmd(int argc, char **argv)
3529 int n = argc > 1 ? number(argv[1]) : 1;
3532 error(illnum, argv[1]);
3536 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3544 * The return command.
3548 returncmd(int argc, char **argv)
3550 int ret = argc > 1 ? number(argv[1]) : exitstatus;
3553 evalskip = SKIPFUNC;
3558 /* Do what ksh does; skip the rest of the file */
3559 evalskip = SKIPFILE;
3567 falsecmd(int argc, char **argv)
3574 truecmd(int argc, char **argv)
3581 execcmd(int argc, char **argv)
3584 iflag = 0; /* exit on error */
3587 shellexec(argv + 1, pathval(), 0);
3593 /* $NetBSD: exec.c,v 1.35 2003/01/22 20:36:04 dsl Exp $ */
3596 * When commands are first encountered, they are entered in a hash table.
3597 * This ensures that a full path search will not have to be done for them
3598 * on each invocation.
3600 * We should investigate converting to a linear search, even though that
3601 * would make the command name "hash" a misnomer.
3604 #define CMDTABLESIZE 31 /* should be prime */
3605 #define ARB 1 /* actual size determined at run time */
3610 struct tblentry *next; /* next entry in hash chain */
3611 union param param; /* definition of builtin function */
3612 short cmdtype; /* index identifying command */
3613 char rehash; /* if set, cd done since entry created */
3614 char cmdname[ARB]; /* name of command */
3618 static struct tblentry *cmdtable[CMDTABLESIZE];
3619 static int builtinloc = -1; /* index in path of %builtin, or -1 */
3622 static void tryexec(char *, char **, char **);
3623 static void clearcmdentry(int);
3624 static struct tblentry *cmdlookup(const char *, int);
3625 static void delete_cmd_entry(void);
3629 * Exec a program. Never returns. If you change this routine, you may
3630 * have to change the find_command routine as well.
3634 shellexec(char **argv, const char *path, int idx)
3641 envp = environment();
3642 if (strchr(argv[0], '/') != NULL
3643 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3644 || find_applet_by_name(argv[0])
3647 tryexec(argv[0], argv, envp);
3651 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3652 if (--idx < 0 && pathopt == NULL) {
3653 tryexec(cmdname, argv, envp);
3654 if (errno != ENOENT && errno != ENOTDIR)
3661 /* Map to POSIX errors */
3673 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
3674 argv[0], e, suppressint ));
3675 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3681 tryexec(char *cmd, char **argv, char **envp)
3684 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3688 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3689 name = bb_get_last_path_component(name);
3690 if(find_applet_by_name(name) != NULL)
3693 if(strchr(name, '/') == NULL && find_applet_by_name(name) != NULL) {
3702 if(strcmp(name, "busybox")) {
3703 for (ap = argv; *ap; ap++);
3704 ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
3705 *ap++ = cmd = "/bin/busybox";
3706 while ((*ap++ = *argv++));
3710 cmd = "/bin/busybox";
3718 execve(cmd, argv, envp);
3719 } while (errno == EINTR);
3721 execve(cmd, argv, envp);
3725 } else if (errno == ENOEXEC) {
3729 for (ap = argv; *ap; ap++)
3731 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
3733 *ap = cmd = (char *)DEFAULT_SHELL;
3736 while ((*ap++ = *argv++))
3746 * Do a path search. The variable path (passed by reference) should be
3747 * set to the start of the path before the first call; padvance will update
3748 * this value as it proceeds. Successive calls to padvance will return
3749 * the possible path expansions in sequence. If an option (indicated by
3750 * a percent sign) appears in the path entry then the global variable
3751 * pathopt will be set to point to it; otherwise pathopt will be set to
3756 padvance(const char **path, const char *name)
3766 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3767 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3768 while (stackblocksize() < len)
3772 memcpy(q, start, p - start);
3780 while (*p && *p != ':') p++;
3786 return stalloc(len);
3790 /*** Command hashing code ***/
3793 printentry(struct tblentry *cmdp)
3799 idx = cmdp->param.index;
3802 name = padvance(&path, cmdp->cmdname);
3804 } while (--idx >= 0);
3805 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
3810 hashcmd(int argc, char **argv)
3812 struct tblentry **pp;
3813 struct tblentry *cmdp;
3815 struct cmdentry entry;
3818 while ((c = nextopt("r")) != '\0') {
3822 if (*argptr == NULL) {
3823 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3824 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3825 if (cmdp->cmdtype == CMDNORMAL)
3832 while ((name = *argptr) != NULL) {
3833 if ((cmdp = cmdlookup(name, 0)) != NULL
3834 && (cmdp->cmdtype == CMDNORMAL
3835 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3837 find_command(name, &entry, DO_ERR, pathval());
3838 if (entry.cmdtype == CMDUNKNOWN)
3847 * Resolve a command name. If you change this routine, you may have to
3848 * change the shellexec routine as well.
3852 find_command(char *name, struct cmdentry *entry, int act, const char *path)
3854 struct tblentry *cmdp;
3861 struct builtincmd *bcmd;
3863 /* If name contains a slash, don't use PATH or hash table */
3864 if (strchr(name, '/') != NULL) {
3865 entry->u.index = -1;
3867 while (stat(name, &statb) < 0) {
3872 entry->cmdtype = CMDUNKNOWN;
3876 entry->cmdtype = CMDNORMAL;
3880 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3881 if (find_applet_by_name(name)) {
3882 entry->cmdtype = CMDNORMAL;
3883 entry->u.index = -1;
3888 updatetbl = (path == pathval());
3891 if (strstr(path, "%builtin") != NULL)
3895 /* If name is in the table, check answer will be ok */
3896 if ((cmdp = cmdlookup(name, 0)) != NULL) {
3899 switch (cmdp->cmdtype) {
3917 } else if (cmdp->rehash == 0)
3918 /* if not invalidated by cd, we're done */
3922 /* If %builtin not in path, check for builtin next */
3923 bcmd = find_builtin(name);
3924 if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
3925 act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
3927 goto builtin_success;
3929 /* We have to search path. */
3930 prev = -1; /* where to start */
3931 if (cmdp && cmdp->rehash) { /* doing a rehash */
3932 if (cmdp->cmdtype == CMDBUILTIN)
3935 prev = cmdp->param.index;
3941 while ((fullname = padvance(&path, name)) != NULL) {
3942 stunalloc(fullname);
3945 if (prefix(pathopt, "builtin")) {
3947 goto builtin_success;
3949 } else if (!(act & DO_NOFUNC) &&
3950 prefix(pathopt, "func")) {
3953 /* ignore unimplemented options */
3957 /* if rehash, don't redo absolute path names */
3958 if (fullname[0] == '/' && idx <= prev) {
3961 TRACE(("searchexec \"%s\": no change\n", name));
3964 while (stat(fullname, &statb) < 0) {
3969 if (errno != ENOENT && errno != ENOTDIR)
3973 e = EACCES; /* if we fail, this will be the error */
3974 if (!S_ISREG(statb.st_mode))
3976 if (pathopt) { /* this is a %func directory */
3977 stalloc(strlen(fullname) + 1);
3978 readcmdfile(fullname);
3979 if ((cmdp = cmdlookup(name, 0)) == NULL ||
3980 cmdp->cmdtype != CMDFUNCTION)
3981 error("%s not defined in %s", name, fullname);
3982 stunalloc(fullname);
3985 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3987 entry->cmdtype = CMDNORMAL;
3988 entry->u.index = idx;
3992 cmdp = cmdlookup(name, 1);
3993 cmdp->cmdtype = CMDNORMAL;
3994 cmdp->param.index = idx;
3999 /* We failed. If there was an entry for this command, delete it */
4000 if (cmdp && updatetbl)
4003 sh_warnx("%s: %s", name, errmsg(e, E_EXEC));
4004 entry->cmdtype = CMDUNKNOWN;
4009 entry->cmdtype = CMDBUILTIN;
4010 entry->u.cmd = bcmd;
4014 cmdp = cmdlookup(name, 1);
4015 cmdp->cmdtype = CMDBUILTIN;
4016 cmdp->param.cmd = bcmd;
4020 entry->cmdtype = cmdp->cmdtype;
4021 entry->u = cmdp->param;
4026 * Wrapper around strcmp for qsort/bsearch/...
4028 static int pstrcmp(const void *a, const void *b)
4030 return strcmp((const char *) a, (*(const char *const *) b) + 1);
4034 * Search the table of builtin commands.
4037 static struct builtincmd *
4038 find_builtin(const char *name)
4040 struct builtincmd *bp;
4043 name, builtincmd, NUMBUILTINS, sizeof(struct builtincmd),
4052 * Called when a cd is done. Marks all commands so the next time they
4053 * are executed they will be rehashed.
4059 struct tblentry **pp;
4060 struct tblentry *cmdp;
4062 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
4063 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4064 if (cmdp->cmdtype == CMDNORMAL || (
4065 cmdp->cmdtype == CMDBUILTIN &&
4066 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
4077 * Fix command hash table when PATH changed.
4078 * Called before PATH is changed. The argument is the new value of PATH;
4079 * pathval() still returns the old value at this point.
4080 * Called with interrupts off.
4084 changepath(const char *newval)
4086 const char *old, *new;
4093 firstchange = 9999; /* assume no change */
4099 if ((*old == '\0' && *new == ':')
4100 || (*old == ':' && *new == '\0'))
4102 old = new; /* ignore subsequent differences */
4106 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
4113 if (builtinloc < 0 && idx_bltin >= 0)
4114 builtinloc = idx_bltin; /* zap builtins */
4115 if (builtinloc >= 0 && idx_bltin < 0)
4117 clearcmdentry(firstchange);
4118 builtinloc = idx_bltin;
4123 * Clear out command entries. The argument specifies the first entry in
4124 * PATH which has changed.
4128 clearcmdentry(int firstchange)
4130 struct tblentry **tblp;
4131 struct tblentry **pp;
4132 struct tblentry *cmdp;
4135 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4137 while ((cmdp = *pp) != NULL) {
4138 if ((cmdp->cmdtype == CMDNORMAL &&
4139 cmdp->param.index >= firstchange)
4140 || (cmdp->cmdtype == CMDBUILTIN &&
4141 builtinloc >= firstchange)) {
4155 * Locate a command in the command hash table. If "add" is nonzero,
4156 * add the command to the table if it is not already present. The
4157 * variable "lastcmdentry" is set to point to the address of the link
4158 * pointing to the entry, so that delete_cmd_entry can delete the
4161 * Interrupts must be off if called with add != 0.
4164 static struct tblentry **lastcmdentry;
4167 static struct tblentry *
4168 cmdlookup(const char *name, int add)
4170 unsigned int hashval;
4172 struct tblentry *cmdp;
4173 struct tblentry **pp;
4176 hashval = (unsigned char)*p << 4;
4178 hashval += (unsigned char)*p++;
4180 pp = &cmdtable[hashval % CMDTABLESIZE];
4181 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4182 if (equal(cmdp->cmdname, name))
4186 if (add && cmdp == NULL) {
4187 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4188 + strlen(name) + 1);
4190 cmdp->cmdtype = CMDUNKNOWN;
4191 strcpy(cmdp->cmdname, name);
4198 * Delete the command entry returned on the last lookup.
4202 delete_cmd_entry(void)
4204 struct tblentry *cmdp;
4207 cmdp = *lastcmdentry;
4208 *lastcmdentry = cmdp->next;
4209 if (cmdp->cmdtype == CMDFUNCTION)
4210 freefunc(cmdp->param.func);
4217 * Add a new command entry, replacing any existing command entry for
4218 * the same name - except special builtins.
4222 addcmdentry(char *name, struct cmdentry *entry)
4224 struct tblentry *cmdp;
4226 cmdp = cmdlookup(name, 1);
4227 if (cmdp->cmdtype == CMDFUNCTION) {
4228 freefunc(cmdp->param.func);
4230 cmdp->cmdtype = entry->cmdtype;
4231 cmdp->param = entry->u;
4236 * Make a copy of a parse tree.
4239 static inline struct funcnode *
4240 copyfunc(union node *n)
4245 funcblocksize = offsetof(struct funcnode, n);
4248 blocksize = funcblocksize;
4249 f = ckmalloc(blocksize + funcstringsize);
4250 funcblock = (char *) f + offsetof(struct funcnode, n);
4251 funcstring = (char *) f + blocksize;
4258 * Define a shell function.
4262 defun(char *name, union node *func)
4264 struct cmdentry entry;
4267 entry.cmdtype = CMDFUNCTION;
4268 entry.u.func = copyfunc(func);
4269 addcmdentry(name, &entry);
4275 * Delete a function if it exists.
4279 unsetfunc(const char *name)
4281 struct tblentry *cmdp;
4283 if ((cmdp = cmdlookup(name, 0)) != NULL &&
4284 cmdp->cmdtype == CMDFUNCTION)
4289 * Locate and print what a word is...
4293 #ifdef CONFIG_ASH_CMDCMD
4295 describe_command(char *command, int describe_command_verbose)
4297 #define describe_command_verbose 1
4299 describe_command(char *command)
4302 struct cmdentry entry;
4303 struct tblentry *cmdp;
4304 #ifdef CONFIG_ASH_ALIAS
4305 const struct alias *ap;
4307 const char *path = pathval();
4309 if (describe_command_verbose) {
4313 /* First look at the keywords */
4314 if (findkwd(command)) {
4315 out1str(describe_command_verbose ? " is a shell keyword" : command);
4319 #ifdef CONFIG_ASH_ALIAS
4320 /* Then look at the aliases */
4321 if ((ap = lookupalias(command, 0)) != NULL) {
4322 if (describe_command_verbose) {
4323 out1fmt(" is an alias for %s", ap->val);
4332 /* Then check if it is a tracked alias */
4333 if ((cmdp = cmdlookup(command, 0)) != NULL) {
4334 entry.cmdtype = cmdp->cmdtype;
4335 entry.u = cmdp->param;
4337 /* Finally use brute force */
4338 find_command(command, &entry, DO_ABS, path);
4341 switch (entry.cmdtype) {
4343 int j = entry.u.index;
4349 p = padvance(&path, command);
4353 if (describe_command_verbose) {
4355 (cmdp ? " a tracked alias for" : nullstr), p
4364 if (describe_command_verbose) {
4365 out1str(" is a shell function");
4372 if (describe_command_verbose) {
4373 out1fmt(" is a %sshell builtin",
4374 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
4375 "special " : nullstr
4383 if (describe_command_verbose) {
4384 out1str(": not found\n");
4390 outstr("\n", stdout);
4395 typecmd(int argc, char **argv)
4400 for (i = 1; i < argc; i++) {
4401 #ifdef CONFIG_ASH_CMDCMD
4402 err |= describe_command(argv[i], 1);
4404 err |= describe_command(argv[i]);
4410 #ifdef CONFIG_ASH_CMDCMD
4412 commandcmd(int argc, char **argv)
4415 int default_path = 0;
4416 int verify_only = 0;
4417 int verbose_verify_only = 0;
4419 while ((c = nextopt("pvV")) != '\0')
4424 "command: nextopt returned character code 0%o\n", c);
4434 verbose_verify_only = 1;
4438 if (default_path + verify_only + verbose_verify_only > 1 ||
4441 "command [-p] command [arg ...]\n"
4442 "command {-v|-V} command\n");
4446 if (verify_only || verbose_verify_only) {
4447 return describe_command(*argptr, verbose_verify_only);
4454 /* $NetBSD: expand.c,v 1.56 2002/11/24 22:35:39 christos Exp $ */
4457 * Routines to expand arguments to commands. We have to deal with
4458 * backquotes, shell variables, and file metacharacters.
4464 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4465 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4466 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4467 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4468 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4471 * Structure specifying which parts of the string should be searched
4472 * for IFS characters.
4476 struct ifsregion *next; /* next region in list */
4477 int begoff; /* offset of start of region */
4478 int endoff; /* offset of end of region */
4479 int nulonly; /* search for nul bytes only */
4482 /* output of current string */
4483 static char *expdest;
4484 /* list of back quote expressions */
4485 static struct nodelist *argbackq;
4486 /* first struct in list of ifs regions */
4487 static struct ifsregion ifsfirst;
4488 /* last struct in list */
4489 static struct ifsregion *ifslastp;
4490 /* holds expanded arg list */
4491 static struct arglist exparg;
4493 static void argstr(char *, int);
4494 static char *exptilde(char *, char *, int);
4495 static void expbackq(union node *, int, int);
4496 static const char *subevalvar(char *, char *, int, int, int, int, int);
4497 static char *evalvar(char *, int);
4498 static int varisset(char *, int);
4499 static void strtodest(const char *, int, int);
4500 static void memtodest(const char *p, size_t len, int syntax, int quotes);
4501 static void varvalue(char *, int, int);
4502 static void recordregion(int, int, int);
4503 static void removerecordregions(int);
4504 static void ifsbreakup(char *, struct arglist *);
4505 static void ifsfree(void);
4506 static void expandmeta(struct strlist *, int);
4507 static int patmatch(char *, const char *);
4509 static int cvtnum(long);
4510 static size_t esclen(const char *, const char *);
4511 static char *scanleft(char *, char *, char *, char *, int, int);
4512 static char *scanright(char *, char *, char *, char *, int, int);
4513 static void varunset(const char *, const char *, const char *, int)
4514 __attribute__((__noreturn__));
4517 #define pmatch(a, b) !fnmatch((a), (b), 0)
4519 * Prepare a pattern for a expmeta (internal glob(3)) call.
4521 * Returns an stalloced string.
4524 static inline char *
4525 preglob(const char *pattern, int quoted, int flag) {
4526 flag |= RMESCAPE_GLOB;
4528 flag |= RMESCAPE_QUOTED;
4530 return _rmescapes((char *)pattern, flag);
4535 esclen(const char *start, const char *p) {
4538 while (p > start && *--p == CTLESC) {
4546 * Expand shell variables and backquotes inside a here document.
4550 expandhere(union node *arg, int fd)
4553 expandarg(arg, (struct arglist *)NULL, 0);
4554 xwrite(fd, stackblock(), expdest - (char *)stackblock());
4559 * Perform variable substitution and command substitution on an argument,
4560 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4561 * perform splitting and file name expansion. When arglist is NULL, perform
4562 * here document expansion.
4566 expandarg(union node *arg, struct arglist *arglist, int flag)
4571 argbackq = arg->narg.backquote;
4572 STARTSTACKSTR(expdest);
4573 ifsfirst.next = NULL;
4575 argstr(arg->narg.text, flag);
4576 if (arglist == NULL) {
4577 return; /* here document expanded */
4579 STPUTC('\0', expdest);
4580 p = grabstackstr(expdest);
4581 exparg.lastp = &exparg.list;
4585 if (flag & EXP_FULL) {
4586 ifsbreakup(p, &exparg);
4587 *exparg.lastp = NULL;
4588 exparg.lastp = &exparg.list;
4589 expandmeta(exparg.list, flag);
4591 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4593 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4596 exparg.lastp = &sp->next;
4600 *exparg.lastp = NULL;
4602 *arglist->lastp = exparg.list;
4603 arglist->lastp = exparg.lastp;
4609 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4610 * characters to allow for further processing. Otherwise treat
4611 * $@ like $* since no splitting will be performed.
4615 argstr(char *p, int flag)
4617 static const char spclchars[] = {
4625 CTLBACKQ | CTLQUOTE,
4626 #ifdef CONFIG_ASH_MATH_SUPPORT
4631 const char *reject = spclchars;
4633 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4634 int breakall = flag & EXP_WORD;
4639 if (!(flag & EXP_VARTILDE)) {
4641 } else if (flag & EXP_VARTILDE2) {
4646 if (flag & EXP_TILDE) {
4652 if (*q == CTLESC && (flag & EXP_QWORD))
4655 p = exptilde(p, q, flag);
4658 startloc = expdest - (char *)stackblock();
4660 length += strcspn(p + length, reject);
4662 if (c && (!(c & 0x80)
4663 #ifdef CONFIG_ASH_MATH_SUPPORT
4667 /* c == '=' || c == ':' || c == CTLENDARI */
4672 expdest = stnputs(p, length, expdest);
4673 newloc = expdest - (char *)stackblock();
4674 if (breakall && !inquotes && newloc > startloc) {
4675 recordregion(startloc, newloc, 0);
4686 if (flag & EXP_VARTILDE2) {
4690 flag |= EXP_VARTILDE2;
4695 * sort of a hack - expand tildes in variable
4696 * assignments (after the first '=' and after ':'s).
4705 case CTLENDVAR: /* ??? */
4708 /* "$@" syntax adherence hack */
4711 !memcmp(p, dolatstr, DOLATSTRLEN) &&
4712 (p[4] == CTLQUOTEMARK || (
4713 p[4] == CTLENDVAR &&
4714 p[5] == CTLQUOTEMARK
4717 p = evalvar(p + 1, flag) + 1;
4720 inquotes = !inquotes;
4733 p = evalvar(p, flag);
4737 case CTLBACKQ|CTLQUOTE:
4738 expbackq(argbackq->n, c, quotes);
4739 argbackq = argbackq->next;
4741 #ifdef CONFIG_ASH_MATH_SUPPORT
4754 exptilde(char *startp, char *p, int flag)
4760 int quotes = flag & (EXP_FULL | EXP_CASE);
4765 while ((c = *++p) != '\0') {
4772 if (flag & EXP_VARTILDE)
4782 if (*name == '\0') {
4783 if ((home = lookupvar(homestr)) == NULL)
4786 if ((pw = getpwnam(name)) == NULL)
4793 startloc = expdest - (char *)stackblock();
4794 strtodest(home, SQSYNTAX, quotes);
4795 recordregion(startloc, expdest - (char *)stackblock(), 0);
4804 removerecordregions(int endoff)
4806 if (ifslastp == NULL)
4809 if (ifsfirst.endoff > endoff) {
4810 while (ifsfirst.next != NULL) {
4811 struct ifsregion *ifsp;
4813 ifsp = ifsfirst.next->next;
4814 ckfree(ifsfirst.next);
4815 ifsfirst.next = ifsp;
4818 if (ifsfirst.begoff > endoff)
4821 ifslastp = &ifsfirst;
4822 ifsfirst.endoff = endoff;
4827 ifslastp = &ifsfirst;
4828 while (ifslastp->next && ifslastp->next->begoff < endoff)
4829 ifslastp=ifslastp->next;
4830 while (ifslastp->next != NULL) {
4831 struct ifsregion *ifsp;
4833 ifsp = ifslastp->next->next;
4834 ckfree(ifslastp->next);
4835 ifslastp->next = ifsp;
4838 if (ifslastp->endoff > endoff)
4839 ifslastp->endoff = endoff;
4843 #ifdef CONFIG_ASH_MATH_SUPPORT
4845 * Expand arithmetic expression. Backup to start of expression,
4846 * evaluate, place result in (backed up) result, adjust string position.
4859 * This routine is slightly over-complicated for
4860 * efficiency. Next we scan backwards looking for the
4861 * start of arithmetic.
4863 start = stackblock();
4870 while (*p != CTLARI) {
4874 error("missing CTLARI (shouldn't happen)");
4879 esc = esclen(start, p);
4889 removerecordregions(begoff);
4898 len = cvtnum(dash_arith(p + 2));
4901 recordregion(begoff, begoff + len, 0);
4906 * Expand stuff in backwards quotes.
4910 expbackq(union node *cmd, int quoted, int quotes)
4918 int syntax = quoted? DQSYNTAX : BASESYNTAX;
4919 struct stackmark smark;
4922 setstackmark(&smark);
4924 startloc = dest - (char *)stackblock();
4926 evalbackcmd(cmd, (struct backcmd *) &in);
4927 popstackmark(&smark);
4934 memtodest(p, i, syntax, quotes);
4938 i = safe_read(in.fd, buf, sizeof buf);
4939 TRACE(("expbackq: read returns %d\n", i));
4949 back_exitstatus = waitforjob(in.jp);
4953 /* Eat all trailing newlines */
4955 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
4960 recordregion(startloc, dest - (char *)stackblock(), 0);
4961 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4962 (dest - (char *)stackblock()) - startloc,
4963 (dest - (char *)stackblock()) - startloc,
4964 stackblock() + startloc));
4969 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
4980 const char *s = loc2;
4986 match = pmatch(str, s);
4990 if (quotes && *loc == CTLESC)
5000 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5007 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5010 const char *s = loc2;
5015 match = pmatch(str, s);
5022 esc = esclen(startp, loc);
5034 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5038 int saveherefd = herefd;
5039 struct nodelist *saveargbackq = argbackq;
5041 char *rmesc, *rmescend;
5043 char *(*scan)(char *, char *, char *, char *, int , int);
5046 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5047 STPUTC('\0', expdest);
5048 herefd = saveherefd;
5049 argbackq = saveargbackq;
5050 startp = stackblock() + startloc;
5054 setvar(str, startp, 0);
5055 amount = startp - expdest;
5056 STADJUST(amount, expdest);
5060 varunset(p, str, startp, varflags);
5064 subtype -= VSTRIMRIGHT;
5066 if (subtype < 0 || subtype > 3)
5071 rmescend = stackblock() + strloc;
5073 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5074 if (rmesc != startp) {
5076 startp = stackblock() + startloc;
5080 str = stackblock() + strloc;
5081 preglob(str, varflags & VSQUOTE, 0);
5083 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5084 zero = subtype >> 1;
5085 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5086 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5088 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5091 memmove(startp, loc, str - loc);
5092 loc = startp + (str - loc) - 1;
5095 amount = loc - expdest;
5096 STADJUST(amount, expdest);
5103 * Expand a variable, and return a pointer to the next character in the
5107 evalvar(char *p, int flag)
5121 quotes = flag & (EXP_FULL | EXP_CASE);
5123 subtype = varflags & VSTYPE;
5124 quoted = varflags & VSQUOTE;
5126 easy = (!quoted || (*var == '@' && shellparam.nparam));
5128 startloc = expdest - (char *)stackblock();
5129 p = strchr(p, '=') + 1;
5131 if (!is_name(*var)) {
5132 set = varisset(var, varflags & VSNUL);
5134 if (subtype == VSPLUS)
5137 varvalue(var, quoted, flag);
5138 if (subtype == VSLENGTH) {
5140 expdest - (char *)stackblock() -
5142 STADJUST(-varlen, expdest);
5149 /* jump here after setting a variable with ${var=text} */
5150 val = lookupvar(var);
5151 set = !val || ((varflags & VSNUL) && !*val);
5152 if (subtype == VSPLUS)
5155 varlen = strlen(val);
5156 if (subtype == VSLENGTH)
5159 val, varlen, quoted ? DQSYNTAX : BASESYNTAX,
5166 if (subtype == VSMINUS) {
5170 p, flag | EXP_TILDE |
5171 (quoted ? EXP_QWORD : EXP_WORD)
5180 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5182 if (subevalvar(p, var, 0, subtype, startloc,
5186 * Remove any recorded regions beyond
5189 removerecordregions(startloc);
5200 varunset(p, var, 0, 0);
5202 if (subtype == VSLENGTH) {
5208 if (subtype == VSNORMAL) {
5212 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5221 case VSTRIMRIGHTMAX:
5230 * Terminate the string and start recording the pattern
5233 STPUTC('\0', expdest);
5234 patloc = expdest - (char *)stackblock();
5235 if (subevalvar(p, NULL, patloc, subtype,
5236 startloc, varflags, quotes) == 0) {
5237 int amount = expdest - (
5238 (char *)stackblock() + patloc - 1
5240 STADJUST(-amount, expdest);
5242 /* Remove any recorded regions beyond start of variable */
5243 removerecordregions(startloc);
5248 if (subtype != VSNORMAL) { /* skip to end of alternative */
5251 if ((c = *p++) == CTLESC)
5253 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5255 argbackq = argbackq->next;
5256 } else if (c == CTLVAR) {
5257 if ((*p++ & VSTYPE) != VSNORMAL)
5259 } else if (c == CTLENDVAR) {
5271 * Test whether a specialized variable is set.
5275 varisset(char *name, int nulok)
5278 return backgndpid != 0;
5279 else if (*name == '@' || *name == '*') {
5280 if (*shellparam.p == NULL)
5286 for (av = shellparam.p; *av; av++)
5291 } else if (is_digit(*name)) {
5293 int num = atoi(name);
5295 if (num > shellparam.nparam)
5301 ap = shellparam.p[num - 1];
5303 if (nulok && (ap == NULL || *ap == '\0'))
5311 * Put a string on the stack.
5315 memtodest(const char *p, size_t len, int syntax, int quotes) {
5318 q = makestrspace(len * 2, q);
5324 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5334 strtodest(const char *p, int syntax, int quotes)
5336 memtodest(p, strlen(p), syntax, quotes);
5341 * Add the value of a specialized variable to the stack string.
5345 varvalue(char *name, int quoted, int flags)
5354 int allow_split = flags & EXP_FULL;
5355 int quotes = flags & (EXP_FULL | EXP_CASE);
5357 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5366 num = shellparam.nparam;
5374 for (i = 0 ; i < NOPTS ; i++) {
5376 STPUTC(optletters(i), expdest);
5380 if (allow_split && quoted) {
5381 sep = 1 << CHAR_BIT;
5386 sep = ifsset() ? ifsval()[0] : ' ';
5388 sepq = (SIT(sep, syntax) == CCTL) || (SIT(sep, syntax) == CBACK);
5391 for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
5392 strtodest(p, syntax, quotes);
5403 strtodest(arg0, syntax, quotes);
5407 if (num > 0 && num <= shellparam.nparam) {
5408 strtodest(shellparam.p[num - 1], syntax, quotes);
5416 * Record the fact that we have to scan this region of the
5417 * string for IFS characters.
5421 recordregion(int start, int end, int nulonly)
5423 struct ifsregion *ifsp;
5425 if (ifslastp == NULL) {
5429 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5431 ifslastp->next = ifsp;
5435 ifslastp->begoff = start;
5436 ifslastp->endoff = end;
5437 ifslastp->nulonly = nulonly;
5442 * Break the argument string into pieces based upon IFS and add the
5443 * strings to the argument list. The regions of the string to be
5444 * searched for IFS characters have been stored by recordregion.
5447 ifsbreakup(char *string, struct arglist *arglist)
5449 struct ifsregion *ifsp;
5454 const char *ifs, *realifs;
5460 if (ifslastp != NULL) {
5463 realifs = ifsset() ? ifsval() : defifs;
5466 p = string + ifsp->begoff;
5467 nulonly = ifsp->nulonly;
5468 ifs = nulonly ? nullstr : realifs;
5470 while (p < string + ifsp->endoff) {
5474 if (strchr(ifs, *p)) {
5476 ifsspc = (strchr(defifs, *p) != NULL);
5477 /* Ignore IFS whitespace at start */
5478 if (q == start && ifsspc) {
5484 sp = (struct strlist *)stalloc(sizeof *sp);
5486 *arglist->lastp = sp;
5487 arglist->lastp = &sp->next;
5491 if (p >= string + ifsp->endoff) {
5497 if (strchr(ifs, *p) == NULL ) {
5500 } else if (strchr(defifs, *p) == NULL) {
5516 } while ((ifsp = ifsp->next) != NULL);
5525 sp = (struct strlist *)stalloc(sizeof *sp);
5527 *arglist->lastp = sp;
5528 arglist->lastp = &sp->next;
5534 struct ifsregion *p;
5539 struct ifsregion *ifsp;
5545 ifsfirst.next = NULL;
5549 static void expmeta(char *, char *);
5550 static struct strlist *expsort(struct strlist *);
5551 static struct strlist *msort(struct strlist *, int);
5553 static char *expdir;
5557 expandmeta(struct strlist *str, int flag)
5559 static const char metachars[] = {
5562 /* TODO - EXP_REDIR */
5565 struct strlist **savelastp;
5571 if (!strpbrk(str->text, metachars))
5573 savelastp = exparg.lastp;
5576 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
5578 int i = strlen(str->text);
5579 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5587 if (exparg.lastp == savelastp) {
5592 *exparg.lastp = str;
5593 rmescapes(str->text);
5594 exparg.lastp = &str->next;
5596 *exparg.lastp = NULL;
5597 *savelastp = sp = expsort(*savelastp);
5598 while (sp->next != NULL)
5600 exparg.lastp = &sp->next;
5607 * Add a file name to the list.
5611 addfname(const char *name)
5615 sp = (struct strlist *)stalloc(sizeof *sp);
5616 sp->text = sstrdup(name);
5618 exparg.lastp = &sp->next;
5623 * Do metacharacter (i.e. *, ?, [...]) expansion.
5627 expmeta(char *enddir, char *name)
5642 for (p = name; *p; p++) {
5643 if (*p == '*' || *p == '?')
5645 else if (*p == '[') {
5652 if (*q == '/' || *q == '\0')
5659 } else if (*p == '\\')
5661 else if (*p == '/') {
5668 if (metaflag == 0) { /* we've reached the end of the file name */
5669 if (enddir != expdir)
5677 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5688 } while (p < start);
5690 if (enddir == expdir) {
5692 } else if (enddir == expdir + 1 && *expdir == '/') {
5698 if ((dirp = opendir(cp)) == NULL)
5700 if (enddir != expdir)
5702 if (*endname == 0) {
5714 while (! intpending && (dp = readdir(dirp)) != NULL) {
5715 if (dp->d_name[0] == '.' && ! matchdot)
5717 if (pmatch(start, dp->d_name)) {
5719 scopy(dp->d_name, enddir);
5722 for (p = enddir, cp = dp->d_name;
5723 (*p++ = *cp++) != '\0';)
5726 expmeta(p, endname);
5736 * Sort the results of file name expansion. It calculates the number of
5737 * strings to sort and then calls msort (short for merge sort) to do the
5741 static struct strlist *
5742 expsort(struct strlist *str)
5748 for (sp = str ; sp ; sp = sp->next)
5750 return msort(str, len);
5754 static struct strlist *
5755 msort(struct strlist *list, int len)
5757 struct strlist *p, *q = NULL;
5758 struct strlist **lpp;
5766 for (n = half ; --n >= 0 ; ) {
5770 q->next = NULL; /* terminate first half of list */
5771 q = msort(list, half); /* sort first half of list */
5772 p = msort(p, len - half); /* sort second half */
5775 #ifdef CONFIG_LOCALE_SUPPORT
5776 if (strcoll(p->text, q->text) < 0)
5778 if (strcmp(p->text, q->text) < 0)
5783 if ((p = *lpp) == NULL) {
5790 if ((q = *lpp) == NULL) {
5801 * Returns true if the pattern matches the string.
5805 patmatch(char *pattern, const char *string)
5807 return pmatch(preglob(pattern, 0, 0), string);
5812 * Remove any CTLESC characters from a string.
5816 _rmescapes(char *str, int flag)
5819 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5824 p = strpbrk(str, qchars);
5830 if (flag & RMESCAPE_ALLOC) {
5831 size_t len = p - str;
5832 size_t fulllen = len + strlen(p) + 1;
5834 if (flag & RMESCAPE_GROW) {
5835 r = makestrspace(fulllen, expdest);
5836 } else if (flag & RMESCAPE_HEAP) {
5837 r = ckmalloc(fulllen);
5839 r = stalloc(fulllen);
5843 q = mempcpy(q, str, len);
5846 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5847 globbing = flag & RMESCAPE_GLOB;
5848 notescaped = globbing;
5850 if (*p == CTLQUOTEMARK) {
5851 inquotes = ~inquotes;
5853 notescaped = globbing;
5857 /* naked back slash */
5863 if (notescaped && inquotes && *p != '/') {
5867 notescaped = globbing;
5872 if (flag & RMESCAPE_GROW) {
5874 STADJUST(q - r + 1, expdest);
5881 * See if a pattern matches in a case statement.
5885 casematch(union node *pattern, char *val)
5887 struct stackmark smark;
5890 setstackmark(&smark);
5891 argbackq = pattern->narg.backquote;
5892 STARTSTACKSTR(expdest);
5894 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5895 STACKSTRNUL(expdest);
5896 result = patmatch(stackblock(), val);
5897 popstackmark(&smark);
5910 expdest = makestrspace(32, expdest);
5911 len = fmtstr(expdest, 32, "%ld", num);
5912 STADJUST(len, expdest);
5917 varunset(const char *end, const char *var, const char *umsg, int varflags)
5923 msg = "parameter not set";
5925 if (*end == CTLENDVAR) {
5926 if (varflags & VSNUL)
5931 error("%.*s: %s%s", end - var - 1, var, msg, tail);
5935 /* $NetBSD: input.c,v 1.37 2002/11/24 22:35:40 christos Exp $ */
5938 * This implements the input routines used by the parser.
5941 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5942 #define IBUFSIZ (BUFSIZ + 1)
5944 static void pushfile(void);
5947 * Read a line from the script.
5950 static inline char *
5951 pfgets(char *line, int len)
5957 while (--nleft > 0) {
5974 * Read a character from the script, returning PEOF on end of file.
5975 * Nul characters in the input are silently discarded.
5978 #define pgetc_as_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
5980 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
5981 #define pgetc_macro() pgetc()
5985 return pgetc_as_macro();
5988 #define pgetc_macro() pgetc_as_macro()
5992 return pgetc_macro();
5998 * Same as pgetc(), but ignores PEOA.
6000 #ifdef CONFIG_ASH_ALIAS
6001 static int pgetc2(void)
6007 } while (c == PEOA);
6011 static inline int pgetc2(void)
6013 return pgetc_macro();
6018 #ifdef CONFIG_FEATURE_COMMAND_EDITING
6019 static const char *cmdedit_prompt;
6020 static inline void putprompt(const char *s)
6025 static inline void putprompt(const char *s)
6035 char *buf = parsefile->buf;
6039 #ifdef CONFIG_FEATURE_COMMAND_EDITING
6040 if (!iflag || parsefile->fd)
6041 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6043 nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
6045 /* Ctrl+C presend */
6050 /* Ctrl+D presend */
6055 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6059 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6060 int flags = fcntl(0, F_GETFL, 0);
6061 if (flags >= 0 && flags & O_NONBLOCK) {
6062 flags &=~ O_NONBLOCK;
6063 if (fcntl(0, F_SETFL, flags) >= 0) {
6064 out2str("sh: turning off NDELAY mode\n");
6074 * Refill the input buffer and return the next input character:
6076 * 1) If a string was pushed back on the input, pop it;
6077 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6078 * from a string so we can't refill the buffer, return EOF.
6079 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6080 * 4) Process input up to the next newline, deleting nul characters.
6090 while (parsefile->strpush) {
6091 #ifdef CONFIG_ASH_ALIAS
6092 if (parsenleft == -1 && parsefile->strpush->ap &&
6093 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6098 if (--parsenleft >= 0)
6099 return (*parsenextc++);
6101 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6106 if (parselleft <= 0) {
6107 if ((parselleft = preadfd()) <= 0) {
6108 parselleft = parsenleft = EOF_NLEFT;
6115 /* delete nul characters */
6116 for (more = 1; more;) {
6123 parsenleft = q - parsenextc;
6124 more = 0; /* Stop processing here */
6131 if (--parselleft <= 0 && more) {
6132 parsenleft = q - parsenextc - 1;
6143 out2str(parsenextc);
6148 return *parsenextc++;
6152 * Undo the last call to pgetc. Only one character may be pushed back.
6153 * PEOF may be pushed back.
6164 * Push a string back onto the input at this current parsefile level.
6165 * We handle aliases this way.
6168 pushstring(char *s, void *ap)
6175 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6176 if (parsefile->strpush) {
6177 sp = ckmalloc(sizeof (struct strpush));
6178 sp->prev = parsefile->strpush;
6179 parsefile->strpush = sp;
6181 sp = parsefile->strpush = &(parsefile->basestrpush);
6182 sp->prevstring = parsenextc;
6183 sp->prevnleft = parsenleft;
6184 #ifdef CONFIG_ASH_ALIAS
6185 sp->ap = (struct alias *)ap;
6187 ((struct alias *)ap)->flag |= ALIASINUSE;
6199 struct strpush *sp = parsefile->strpush;
6202 #ifdef CONFIG_ASH_ALIAS
6204 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6205 checkkwd |= CHKALIAS;
6207 if (sp->string != sp->ap->val) {
6210 sp->ap->flag &= ~ALIASINUSE;
6211 if (sp->ap->flag & ALIASDEAD) {
6212 unalias(sp->ap->name);
6216 parsenextc = sp->prevstring;
6217 parsenleft = sp->prevnleft;
6218 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6219 parsefile->strpush = sp->prev;
6220 if (sp != &(parsefile->basestrpush))
6226 * Set the input to take input from a file. If push is set, push the
6227 * old input onto the stack first.
6231 setinputfile(const char *fname, int push)
6237 if ((fd = open(fname, O_RDONLY)) < 0)
6238 error("Can't open %s", fname);
6240 fd2 = copyfd(fd, 10);
6243 error("Out of file descriptors");
6246 setinputfd(fd, push);
6252 * Like setinputfile, but takes an open file descriptor. Call this with
6257 setinputfd(int fd, int push)
6259 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
6265 if (parsefile->buf == NULL)
6266 parsefile->buf = ckmalloc(IBUFSIZ);
6267 parselleft = parsenleft = 0;
6273 * Like setinputfile, but takes input from a string.
6277 setinputstring(char *string)
6281 parsenextc = string;
6282 parsenleft = strlen(string);
6283 parsefile->buf = NULL;
6290 * To handle the "." command, a stack of input files is used. Pushfile
6291 * adds a new entry to the stack and popfile restores the previous level.
6297 struct parsefile *pf;
6299 parsefile->nleft = parsenleft;
6300 parsefile->lleft = parselleft;
6301 parsefile->nextc = parsenextc;
6302 parsefile->linno = plinno;
6303 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6304 pf->prev = parsefile;
6307 pf->basestrpush.prev = NULL;
6315 struct parsefile *pf = parsefile;
6324 parsefile = pf->prev;
6326 parsenleft = parsefile->nleft;
6327 parselleft = parsefile->lleft;
6328 parsenextc = parsefile->nextc;
6329 plinno = parsefile->linno;
6335 * Return to top level.
6341 while (parsefile != &basepf)
6347 * Close the file(s) that the shell is reading commands from. Called
6348 * after a fork is done.
6355 if (parsefile->fd > 0) {
6356 close(parsefile->fd);
6361 /* $NetBSD: jobs.c,v 1.56 2002/11/25 12:13:03 agc Exp $ */
6363 /* mode flags for set_curjob */
6364 #define CUR_DELETE 2
6365 #define CUR_RUNNING 1
6366 #define CUR_STOPPED 0
6368 /* mode flags for dowait */
6369 #define DOWAIT_NORMAL 0
6370 #define DOWAIT_BLOCK 1
6373 static struct job *jobtab;
6375 static unsigned njobs;
6377 /* pgrp of shell on invocation */
6378 static int initialpgrp;
6379 static int ttyfd = -1;
6382 static struct job *curjob;
6383 /* number of presumed living untracked jobs */
6386 static void set_curjob(struct job *, unsigned);
6388 static int restartjob(struct job *, int);
6389 static void xtcsetpgrp(int, pid_t);
6390 static char *commandtext(union node *);
6391 static void cmdlist(union node *, int);
6392 static void cmdtxt(union node *);
6393 static void cmdputs(const char *);
6394 static void showpipe(struct job *, FILE *);
6396 static int sprint_status(char *, int, int);
6397 static void freejob(struct job *);
6398 static struct job *getjob(const char *, int);
6399 static struct job *growjobtab(void);
6400 static void forkchild(struct job *, union node *, int);
6401 static void forkparent(struct job *, union node *, int, pid_t);
6402 static int dowait(int, struct job *);
6403 static int getstatus(struct job *);
6406 set_curjob(struct job *jp, unsigned mode)
6409 struct job **jpp, **curp;
6411 /* first remove from list */
6412 jpp = curp = &curjob;
6417 jpp = &jp1->prev_job;
6419 *jpp = jp1->prev_job;
6421 /* Then re-insert in correct position */
6429 /* job being deleted */
6432 /* newly created job or backgrounded job,
6433 put after all stopped jobs. */
6437 if (!jp1 || jp1->state != JOBSTOPPED)
6440 jpp = &jp1->prev_job;
6446 /* newly stopped job - becomes curjob */
6447 jp->prev_job = *jpp;
6455 * Turn job control on and off.
6457 * Note: This code assumes that the third arg to ioctl is a character
6458 * pointer, which is true on Berkeley systems but not System V. Since
6459 * System V doesn't have job control yet, this isn't a problem now.
6461 * Called with interrupts off.
6470 if (on == jobctl || rootshell == 0)
6474 ofd = fd = open(_PATH_TTY, O_RDWR);
6477 while (!isatty(fd) && --fd >= 0)
6480 fd = fcntl(fd, F_DUPFD, 10);
6484 fcntl(fd, F_SETFD, FD_CLOEXEC);
6485 do { /* while we are in the background */
6486 if ((pgrp = tcgetpgrp(fd)) < 0) {
6488 sh_warnx("can't access tty; job control turned off");
6492 if (pgrp == getpgrp())
6503 xtcsetpgrp(fd, pgrp);
6505 /* turning job control off */
6508 xtcsetpgrp(fd, pgrp);
6522 killcmd(int argc, char **argv)
6533 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6534 "kill -l [exitstatus]"
6538 if (**++argv == '-') {
6539 signo = decode_signal(*argv + 1, 1);
6543 while ((c = nextopt("ls:")) != '\0')
6553 signo = decode_signal(optionarg, 1);
6556 "invalid signal number or name: %s",
6567 if (!list && signo < 0)
6570 if ((signo < 0 || !*argv) ^ list) {
6578 for (i = 1; i < NSIG; i++) {
6579 name = u_signal_names(0, &i, 1);
6581 out1fmt(snlfmt, name);
6585 name = u_signal_names(*argptr, &signo, -1);
6587 out1fmt(snlfmt, name);
6589 error("invalid signal number or exit status: %s", *argptr);
6595 if (**argv == '%') {
6596 jp = getjob(*argv, 0);
6597 pid = -jp->ps[0].pid;
6599 pid = number(*argv);
6600 if (kill(pid, signo) != 0) {
6610 #if defined(JOBS) || defined(DEBUG)
6612 jobno(const struct job *jp)
6614 return jp - jobtab + 1;
6620 fgcmd(int argc, char **argv)
6627 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
6632 jp = getjob(*argv, 1);
6633 if (mode == FORK_BG) {
6634 set_curjob(jp, CUR_RUNNING);
6635 fprintf(out, "[%d] ", jobno(jp));
6637 outstr(jp->ps->cmd, out);
6639 retval = restartjob(jp, mode);
6640 } while (*argv && *++argv);
6644 static int bgcmd(int, char **) __attribute__((__alias__("fgcmd")));
6648 restartjob(struct job *jp, int mode)
6650 struct procstat *ps;
6656 if (jp->state == JOBDONE)
6658 jp->state = JOBRUNNING;
6660 if (mode == FORK_FG)
6661 xtcsetpgrp(ttyfd, pgid);
6662 killpg(pgid, SIGCONT);
6666 if (WIFSTOPPED(ps->status)) {
6669 } while (ps++, --i);
6671 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
6678 sprint_status(char *s, int status, int sigonly)
6684 st = WEXITSTATUS(status);
6685 if (!WIFEXITED(status)) {
6686 st = WTERMSIG(status);
6688 if (WIFSTOPPED(status))
6689 st = WSTOPSIG(status);
6692 if (st == SIGINT || st == SIGPIPE)
6694 if (WIFSTOPPED(status))
6698 col = fmtstr(s, 32, u_signal_names(NULL, &st, 0));
6699 if (WCOREDUMP(status)) {
6700 col += fmtstr(s + col, 16, " (core dumped)");
6702 } else if (!sigonly) {
6704 col = fmtstr(s, 16, "Done(%d)", st);
6706 col = fmtstr(s, 16, "Done");
6715 showjob(FILE *out, struct job *jp, int mode)
6717 struct procstat *ps;
6718 struct procstat *psend;
6725 if (mode & SHOW_PGID) {
6726 /* just output process (group) id of pipeline */
6727 fprintf(out, "%d\n", ps->pid);
6731 col = fmtstr(s, 16, "[%d] ", jobno(jp));
6736 else if (curjob && jp == curjob->prev_job)
6739 if (mode & SHOW_PID)
6740 col += fmtstr(s + col, 16, "%d ", ps->pid);
6742 psend = ps + jp->nprocs;
6744 if (jp->state == JOBRUNNING) {
6745 scopy("Running", s + col);
6746 col += strlen("Running");
6748 int status = psend[-1].status;
6750 if (jp->state == JOBSTOPPED)
6751 status = jp->stopstatus;
6753 col += sprint_status(s + col, status, 0);
6759 /* for each process */
6760 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
6763 fprintf(out, "%s%*c%s",
6764 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
6766 if (!(mode & SHOW_PID)) {
6770 if (++ps == psend) {
6771 outcslow('\n', out);
6778 if (jp->state == JOBDONE) {
6779 TRACE(("showjob: freeing job %d\n", jobno(jp)));
6786 jobscmd(int argc, char **argv)
6792 while ((m = nextopt("lp")))
6802 showjob(out, getjob(*argv,0), mode);
6805 showjobs(out, mode);
6812 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6813 * statuses have changed since the last call to showjobs.
6817 showjobs(FILE *out, int mode)
6821 TRACE(("showjobs(%x) called\n", mode));
6823 /* If not even one one job changed, there is nothing to do */
6824 while (dowait(DOWAIT_NORMAL, NULL) > 0)
6827 for (jp = curjob; jp; jp = jp->prev_job) {
6828 if (!(mode & SHOW_CHANGED) || jp->changed)
6829 showjob(out, jp, mode);
6835 * Mark a job structure as unused.
6839 freejob(struct job *jp)
6841 struct procstat *ps;
6845 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6846 if (ps->cmd != nullstr)
6849 if (jp->ps != &jp->ps0)
6852 set_curjob(jp, CUR_DELETE);
6858 waitcmd(int argc, char **argv)
6871 /* wait for all jobs */
6876 /* no running procs */
6879 if (jp->state == JOBRUNNING)
6884 dowait(DOWAIT_BLOCK, 0);
6890 if (**argv != '%') {
6891 pid_t pid = number(*argv);
6895 if (job->ps[job->nprocs - 1].pid == pid)
6897 job = job->prev_job;
6903 job = getjob(*argv, 0);
6904 /* loop until process terminated or stopped */
6905 while (job->state == JOBRUNNING)
6906 dowait(DOWAIT_BLOCK, 0);
6908 retval = getstatus(job);
6919 * Convert a job name to a job structure.
6923 getjob(const char *name, int getctl)
6927 const char *err_msg = "No such job: %s";
6931 char *(*match)(const char *, const char *);
6946 if (c == '+' || c == '%') {
6948 err_msg = "No current job";
6950 } else if (c == '-') {
6953 err_msg = "No previous job";
6964 jp = jobtab + num - 1;
6981 if (match(jp->ps[0].cmd, p)) {
6985 err_msg = "%s: ambiguous";
6992 err_msg = "job %s not created under job control";
6993 if (getctl && jp->jobctl == 0)
6998 error(err_msg, name);
7003 * Return a new job structure.
7004 * Called with interrupts off.
7008 makejob(union node *node, int nprocs)
7013 for (i = njobs, jp = jobtab ; ; jp++) {
7020 if (jp->state != JOBDONE || !jp->waited)
7029 memset(jp, 0, sizeof(*jp));
7034 jp->prev_job = curjob;
7039 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
7041 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
7051 struct job *jp, *jq;
7053 len = njobs * sizeof(*jp);
7055 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
7057 offset = (char *)jp - (char *)jq;
7059 /* Relocate pointers */
7062 jq = (struct job *)((char *)jq + l);
7066 #define joff(p) ((struct job *)((char *)(p) + l))
7067 #define jmove(p) (p) = (void *)((char *)(p) + offset)
7068 if (likely(joff(jp)->ps == &jq->ps0))
7069 jmove(joff(jp)->ps);
7070 if (joff(jp)->prev_job)
7071 jmove(joff(jp)->prev_job);
7081 jp = (struct job *)((char *)jp + len);
7085 } while (--jq >= jp);
7091 * Fork off a subshell. If we are doing job control, give the subshell its
7092 * own process group. Jp is a job structure that the job is to be added to.
7093 * N is the command that will be evaluated by the child. Both jp and n may
7094 * be NULL. The mode parameter can be one of the following:
7095 * FORK_FG - Fork off a foreground process.
7096 * FORK_BG - Fork off a background process.
7097 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
7098 * process group even if job control is on.
7100 * When job control is turned off, background processes have their standard
7101 * input redirected to /dev/null (except for the second and later processes
7104 * Called with interrupts off.
7108 forkchild(struct job *jp, union node *n, int mode)
7112 TRACE(("Child shell %d\n", getpid()));
7113 wasroot = rootshell;
7119 /* do job control only in root shell */
7121 if (mode != FORK_NOJOB && jp->jobctl && wasroot) {
7124 if (jp->nprocs == 0)
7127 pgrp = jp->ps[0].pid;
7128 /* This can fail because we are doing it in the parent also */
7129 (void)setpgid(0, pgrp);
7130 if (mode == FORK_FG)
7131 xtcsetpgrp(ttyfd, pgrp);
7136 if (mode == FORK_BG) {
7139 if (jp->nprocs == 0) {
7141 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
7142 error("Can't open %s", _PATH_DEVNULL);
7145 if (wasroot && iflag) {
7150 for (jp = curjob; jp; jp = jp->prev_job)
7156 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
7158 TRACE(("In parent shell: child = %d\n", pid));
7160 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
7165 if (mode != FORK_NOJOB && jp->jobctl) {
7168 if (jp->nprocs == 0)
7171 pgrp = jp->ps[0].pid;
7172 /* This can fail because we are doing it in the child also */
7173 (void)setpgid(pid, pgrp);
7176 if (mode == FORK_BG) {
7177 backgndpid = pid; /* set $! */
7178 set_curjob(jp, CUR_RUNNING);
7181 struct procstat *ps = &jp->ps[jp->nprocs++];
7187 ps->cmd = commandtext(n);
7193 forkshell(struct job *jp, union node *n, int mode)
7197 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
7200 TRACE(("Fork failed, errno=%d", errno));
7203 error("Cannot fork");
7206 forkchild(jp, n, mode);
7208 forkparent(jp, n, mode, pid);
7213 * Wait for job to finish.
7215 * Under job control we have the problem that while a child process is
7216 * running interrupts generated by the user are sent to the child but not
7217 * to the shell. This means that an infinite loop started by an inter-
7218 * active user may be hard to kill. With job control turned off, an
7219 * interactive user may place an interactive program inside a loop. If
7220 * the interactive program catches interrupts, the user doesn't want
7221 * these interrupts to also abort the loop. The approach we take here
7222 * is to have the shell ignore interrupt signals while waiting for a
7223 * forground process to terminate, and then send itself an interrupt
7224 * signal if the child process was terminated by an interrupt signal.
7225 * Unfortunately, some programs want to do a bit of cleanup and then
7226 * exit on interrupt; unless these processes terminate themselves by
7227 * sending a signal to themselves (instead of calling exit) they will
7228 * confuse this approach.
7230 * Called with interrupts off.
7234 waitforjob(struct job *jp)
7238 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
7239 while (jp->state == JOBRUNNING) {
7240 dowait(DOWAIT_BLOCK, jp);
7245 xtcsetpgrp(ttyfd, rootpid);
7247 * This is truly gross.
7248 * If we're doing job control, then we did a TIOCSPGRP which
7249 * caused us (the shell) to no longer be in the controlling
7250 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
7251 * intuit from the subprocess exit status whether a SIGINT
7252 * occurred, and if so interrupt ourselves. Yuck. - mycroft
7257 if (jp->state == JOBDONE)
7265 * Do a wait system call. If job control is compiled in, we accept
7266 * stopped processes. If block is zero, we return a value of zero
7267 * rather than blocking.
7269 * System V doesn't have a non-blocking wait system call. It does
7270 * have a SIGCLD signal that is sent to a process when one of it's
7271 * children dies. The obvious way to use SIGCLD would be to install
7272 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
7273 * was received, and have waitproc bump another counter when it got
7274 * the status of a process. Waitproc would then know that a wait
7275 * system call would not block if the two counters were different.
7276 * This approach doesn't work because if a process has children that
7277 * have not been waited for, System V will send it a SIGCLD when it
7278 * installs a signal handler for SIGCLD. What this means is that when
7279 * a child exits, the shell will be sent SIGCLD signals continuously
7280 * until is runs out of stack space, unless it does a wait call before
7281 * restoring the signal handler. The code below takes advantage of
7282 * this (mis)feature by installing a signal handler for SIGCLD and
7283 * then checking to see whether it was called. If there are any
7284 * children to be waited for, it will be.
7286 * If neither SYSV nor BSD is defined, we don't implement nonblocking
7287 * waits at all. In this case, the user will not be informed when
7288 * a background process until the next time she runs a real program
7289 * (as opposed to running a builtin command or just typing return),
7290 * and the jobs command may give out of date information.
7294 waitproc(int block, int *status)
7304 return wait3(status, flags, (struct rusage *)NULL);
7308 * Wait for a process to terminate.
7312 dowait(int block, struct job *job)
7317 struct job *thisjob;
7320 TRACE(("dowait(%d) called\n", block));
7321 pid = waitproc(block, &status);
7322 TRACE(("wait returns pid %d, status=%d\n", pid, status));
7327 for (jp = curjob; jp; jp = jp->prev_job) {
7328 struct procstat *sp;
7329 struct procstat *spend;
7330 if (jp->state == JOBDONE)
7333 spend = jp->ps + jp->nprocs;
7336 if (sp->pid == pid) {
7337 TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status));
7338 sp->status = status;
7341 if (sp->status == -1)
7344 if (state == JOBRUNNING)
7346 if (WIFSTOPPED(sp->status)) {
7347 jp->stopstatus = sp->status;
7351 } while (++sp < spend);
7356 if (!WIFSTOPPED(status))
7363 if (state != JOBRUNNING) {
7364 thisjob->changed = 1;
7366 if (thisjob->state != state) {
7367 TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state));
7368 thisjob->state = state;
7370 if (state == JOBSTOPPED) {
7371 set_curjob(thisjob, CUR_STOPPED);
7380 if (thisjob && thisjob == job) {
7384 len = sprint_status(s, status, 1);
7396 * return 1 if there are stopped jobs, otherwise 0
7409 if (jp && jp->state == JOBSTOPPED) {
7410 out2str("You have stopped jobs.\n");
7420 * Return a string identifying a command (to be printed by the
7425 static char *cmdnextc;
7428 commandtext(union node *n)
7432 STARTSTACKSTR(cmdnextc);
7434 name = stackblock();
7435 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
7436 name, cmdnextc, cmdnextc));
7437 return savestr(name);
7441 cmdtxt(union node *n)
7444 struct nodelist *lp;
7454 lp = n->npipe.cmdlist;
7472 cmdtxt(n->nbinary.ch1);
7488 cmdtxt(n->nif.test);
7491 if (n->nif.elsepart) {
7494 n = n->nif.elsepart;
7510 cmdtxt(n->nbinary.ch1);
7520 cmdputs(n->nfor.var);
7522 cmdlist(n->nfor.args, 1);
7527 cmdputs(n->narg.text);
7531 cmdlist(n->ncmd.args, 1);
7532 cmdlist(n->ncmd.redirect, 0);
7545 cmdputs(n->ncase.expr->narg.text);
7547 for (np = n->ncase.cases; np; np = np->nclist.next) {
7548 cmdtxt(np->nclist.pattern);
7550 cmdtxt(np->nclist.body);
7576 s[0] = n->nfile.fd + '0';
7580 if (n->type == NTOFD || n->type == NFROMFD) {
7581 s[0] = n->ndup.dupfd + '0';
7592 cmdlist(union node *np, int sep)
7594 for (; np; np = np->narg.next) {
7598 if (sep && np->narg.next)
7604 cmdputs(const char *s)
7606 const char *p, *str;
7607 char c, cc[2] = " ";
7611 static const char *const vstype[16] = {
7612 nullstr, "}", "-", "+", "?", "=",
7613 "#", "##", "%", "%%"
7616 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
7618 while ((c = *p++) != 0) {
7626 if ((subtype & VSTYPE) == VSLENGTH)
7630 if (!(subtype & VSQUOTE) != !(quoted & 1)) {
7648 case CTLBACKQ+CTLQUOTE:
7651 #ifdef CONFIG_ASH_MATH_SUPPORT
7666 str = vstype[subtype & VSTYPE];
7667 if (subtype & VSNUL)
7678 /* These can only happen inside quotes */
7690 while ((c = *str++)) {
7695 USTPUTC('"', nextc);
7703 showpipe(struct job *jp, FILE *out)
7705 struct procstat *sp;
7706 struct procstat *spend;
7708 spend = jp->ps + jp->nprocs;
7709 for (sp = jp->ps + 1; sp < spend; sp++)
7710 fprintf(out, " | %s", sp->cmd);
7711 outcslow('\n', out);
7716 xtcsetpgrp(int fd, pid_t pgrp)
7718 if (tcsetpgrp(fd, pgrp))
7719 error("Cannot set tty process group (%m)");
7724 getstatus(struct job *job) {
7728 status = job->ps[job->nprocs - 1].status;
7729 retval = WEXITSTATUS(status);
7730 if (!WIFEXITED(status)) {
7732 retval = WSTOPSIG(status);
7733 if (!WIFSTOPPED(status))
7736 /* XXX: limits number of signals */
7737 retval = WTERMSIG(status);
7739 if (retval == SIGINT)
7745 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
7746 jobno(job), job->nprocs, status, retval));
7750 #ifdef CONFIG_ASH_MAIL
7751 /* $NetBSD: mail.c,v 1.15 2002/11/24 22:35:40 christos Exp $ */
7754 * Routines to check for mail. (Perhaps make part of main.c?)
7757 #define MAXMBOXES 10
7759 /* times of mailboxes */
7760 static time_t mailtime[MAXMBOXES];
7761 /* Set if MAIL or MAILPATH is changed. */
7762 static int mail_var_path_changed;
7767 * Print appropriate message(s) if mail has arrived.
7768 * If mail_var_path_changed is set,
7769 * then the value of MAIL has mail_var_path_changed,
7770 * so we just update the values.
7780 struct stackmark smark;
7783 setstackmark(&smark);
7784 mpath = mpathset() ? mpathval() : mailval();
7785 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
7786 p = padvance(&mpath, nullstr);
7791 for (q = p ; *q ; q++);
7796 q[-1] = '\0'; /* delete trailing '/' */
7797 if (stat(p, &statb) < 0) {
7801 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
7804 pathopt ? pathopt : "you have mail"
7807 *mtp = statb.st_mtime;
7809 mail_var_path_changed = 0;
7810 popstackmark(&smark);
7815 changemail(const char *val)
7817 mail_var_path_changed++;
7820 #endif /* CONFIG_ASH_MAIL */
7822 /* $NetBSD: main.c,v 1.46 2002/12/11 19:12:18 christos Exp $ */
7826 static short profile_buf[16384];
7830 static int isloginsh;
7832 static void read_profile(const char *);
7835 * Main routine. We initialize things, parse the arguments, execute
7836 * profiles if we're a login shell, and then call cmdloop to execute
7837 * commands. The setjmp call sets up the location to jump to when an
7838 * exception occurs. When an exception occurs the variable "state"
7839 * is used to figure out how far we had gotten.
7843 ash_main(int argc, char **argv)
7847 struct jmploc jmploc;
7848 struct stackmark smark;
7851 dash_errno = __errno_location();
7855 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7858 if (setjmp(jmploc.loc)) {
7865 switch (exception) {
7875 status = exitstatus;
7878 exitstatus = status;
7880 if (e == EXEXIT || state == 0 || iflag == 0 || ! rootshell)
7884 outcslow('\n', stderr);
7886 popstackmark(&smark);
7887 FORCEINTON; /* enable interrupts */
7890 else if (state == 2)
7892 else if (state == 3)
7900 trputs("Shell args: "); trargs(argv);
7905 setstackmark(&smark);
7906 procargs(argc, argv);
7907 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7909 const char *hp = lookupvar("HISTFILE");
7912 hp = lookupvar("HOME");
7914 char *defhp = concat_path_file(hp, ".ash_history");
7915 setvar("HISTFILE", defhp, 0);
7921 if (argv[0] && argv[0][0] == '-')
7925 read_profile("/etc/profile");
7928 read_profile(".profile");
7934 getuid() == geteuid() && getgid() == getegid() &&
7938 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7939 read_profile(shinit);
7945 evalstring(minusc, 0);
7947 if (sflag || minusc == NULL) {
7948 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7950 const char *hp = lookupvar("HISTFILE");
7953 load_history ( hp );
7956 state4: /* XXX ??? - why isn't this before the "if" statement */
7964 extern void _mcleanup(void);
7974 * Read and execute commands. "Top" is nonzero for the top level command
7975 * loop; it turns on prompting if the shell is interactive.
7982 struct stackmark smark;
7986 TRACE(("cmdloop(%d) called\n", top));
7987 setstackmark(&smark);
7993 showjobs(stderr, SHOW_CHANGED);
7998 #ifdef CONFIG_ASH_MAIL
8002 n = parsecmd(inter);
8003 /* showtree(n); DEBUG */
8005 if (!top || numeof >= 50)
8007 if (!stoppedjobs()) {
8010 out2str("\nUse \"exit\" to leave shell.\n");
8013 } else if (n != NULL && nflag == 0) {
8014 job_warning = (job_warning == 2) ? 1 : 0;
8018 popstackmark(&smark);
8019 setstackmark(&smark);
8020 if (evalskip == SKIPFILE) {
8025 popstackmark(&smark);
8030 * Read /etc/profile or .profile. Return on error.
8034 read_profile(const char *name)
8041 if ((fd = open(name, O_RDONLY)) >= 0)
8046 /* -q turns off -x and -v just when executing init files */
8049 xflag = 0, xflag_set = 1;
8051 vflag = 0, vflag_set = 1;
8065 * Read a file containing shell functions.
8069 readcmdfile(char *name)
8074 if ((fd = open(name, O_RDONLY)) >= 0)
8077 error("Can't open %s", name);
8085 * Take commands from a file. To be compatible we should do a path
8086 * search for the file, which is necessary to find sub-commands.
8089 static inline char *
8090 find_dot_file(char *name)
8093 const char *path = pathval();
8096 /* don't try this for absolute or relative paths */
8097 if (strchr(name, '/'))
8100 while ((fullname = padvance(&path, name)) != NULL) {
8101 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
8103 * Don't bother freeing here, since it will
8104 * be freed by the caller.
8108 stunalloc(fullname);
8111 /* not found in the PATH */
8112 error(not_found_msg, name);
8117 dotcmd(int argc, char **argv)
8121 if (argc >= 2) { /* That's what SVR2 does */
8123 struct stackmark smark;
8125 setstackmark(&smark);
8126 fullname = find_dot_file(argv[1]);
8127 setinputfile(fullname, 1);
8128 commandname = fullname;
8131 popstackmark(&smark);
8138 exitcmd(int argc, char **argv)
8143 exitstatus = number(argv[1]);
8148 /* $NetBSD: memalloc.c,v 1.27 2003/01/22 20:36:04 dsl Exp $ */
8151 * Same for malloc, realloc, but returns an error when out of space.
8155 ckrealloc(pointer p, size_t nbytes)
8157 p = realloc(p, nbytes);
8159 error(bb_msg_memory_exhausted);
8164 ckmalloc(size_t nbytes)
8166 return ckrealloc(NULL, nbytes);
8170 * Make a copy of a string in safe storage.
8174 savestr(const char *s)
8176 char *p = strdup(s);
8178 error(bb_msg_memory_exhausted);
8184 * Parse trees for commands are allocated in lifo order, so we use a stack
8185 * to make this more efficient, and also to avoid all sorts of exception
8186 * handling code to handle interrupts in the middle of a parse.
8188 * The size 504 was chosen because the Ultrix malloc handles that size
8194 stalloc(size_t nbytes)
8199 aligned = SHELL_ALIGN(nbytes);
8200 if (aligned > stacknleft) {
8203 struct stack_block *sp;
8205 blocksize = aligned;
8206 if (blocksize < MINSIZE)
8207 blocksize = MINSIZE;
8208 len = sizeof(struct stack_block) - MINSIZE + blocksize;
8209 if (len < blocksize)
8210 error(bb_msg_memory_exhausted);
8214 stacknxt = sp->space;
8215 stacknleft = blocksize;
8216 sstrend = stacknxt + blocksize;
8221 stacknxt += aligned;
8222 stacknleft -= aligned;
8228 stunalloc(pointer p)
8231 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
8232 write(2, "stunalloc\n", 10);
8236 stacknleft += stacknxt - (char *)p;
8242 setstackmark(struct stackmark *mark)
8244 mark->stackp = stackp;
8245 mark->stacknxt = stacknxt;
8246 mark->stacknleft = stacknleft;
8247 mark->marknext = markp;
8253 popstackmark(struct stackmark *mark)
8255 struct stack_block *sp;
8258 markp = mark->marknext;
8259 while (stackp != mark->stackp) {
8264 stacknxt = mark->stacknxt;
8265 stacknleft = mark->stacknleft;
8266 sstrend = mark->stacknxt + mark->stacknleft;
8272 * When the parser reads in a string, it wants to stick the string on the
8273 * stack and only adjust the stack pointer when it knows how big the
8274 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8275 * of space on top of the stack and stackblocklen returns the length of
8276 * this block. Growstackblock will grow this space by at least one byte,
8277 * possibly moving it (like realloc). Grabstackblock actually allocates the
8278 * part of the block that has been used.
8282 growstackblock(void)
8286 newlen = stacknleft * 2;
8287 if (newlen < stacknleft)
8288 error(bb_msg_memory_exhausted);
8292 if (stacknxt == stackp->space && stackp != &stackbase) {
8293 struct stack_block *oldstackp;
8294 struct stackmark *xmark;
8295 struct stack_block *sp;
8296 struct stack_block *prevstackp;
8302 prevstackp = sp->prev;
8303 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
8304 sp = ckrealloc((pointer)sp, grosslen);
8305 sp->prev = prevstackp;
8307 stacknxt = sp->space;
8308 stacknleft = newlen;
8309 sstrend = sp->space + newlen;
8312 * Stack marks pointing to the start of the old block
8313 * must be relocated to point to the new block
8316 while (xmark != NULL && xmark->stackp == oldstackp) {
8317 xmark->stackp = stackp;
8318 xmark->stacknxt = stacknxt;
8319 xmark->stacknleft = stacknleft;
8320 xmark = xmark->marknext;
8324 char *oldspace = stacknxt;
8325 int oldlen = stacknleft;
8326 char *p = stalloc(newlen);
8328 /* free the space we just allocated */
8329 stacknxt = memcpy(p, oldspace, oldlen);
8330 stacknleft += newlen;
8335 grabstackblock(size_t len)
8337 len = SHELL_ALIGN(len);
8343 * The following routines are somewhat easier to use than the above.
8344 * The user declares a variable of type STACKSTR, which may be declared
8345 * to be a register. The macro STARTSTACKSTR initializes things. Then
8346 * the user uses the macro STPUTC to add characters to the string. In
8347 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8348 * grown as necessary. When the user is done, she can just leave the
8349 * string there and refer to it using stackblock(). Or she can allocate
8350 * the space for it using grabstackstr(). If it is necessary to allow
8351 * someone else to use the stack temporarily and then continue to grow
8352 * the string, the user should use grabstack to allocate the space, and
8353 * then call ungrabstr(p) to return to the previous mode of operation.
8355 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8356 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8357 * is space for at least one character.
8363 size_t len = stackblocksize();
8364 if (herefd >= 0 && len >= 1024) {
8365 xwrite(herefd, stackblock(), len);
8366 return stackblock();
8369 return stackblock() + len;
8373 * Called from CHECKSTRSPACE.
8377 makestrspace(size_t newlen, char *p)
8379 size_t len = p - stacknxt;
8380 size_t size = stackblocksize();
8385 size = stackblocksize();
8387 if (nleft >= newlen)
8391 return stackblock() + len;
8395 stnputs(const char *s, size_t n, char *p)
8397 p = makestrspace(n, p);
8398 p = mempcpy(p, s, n);
8403 stputs(const char *s, char *p)
8405 return stnputs(s, strlen(s), p);
8408 /* $NetBSD: mystring.c,v 1.15 2002/11/24 22:35:42 christos Exp $ */
8413 * number(s) Convert a string of digits to an integer.
8414 * is_number(s) Return true if s is a string of digits.
8418 * prefix -- see if pfx is a prefix of string.
8422 prefix(const char *string, const char *pfx)
8425 if (*pfx++ != *string++)
8428 return (char *) string;
8433 * Convert a string of digits to an integer, printing an error message on
8438 number(const char *s)
8448 * Check for a valid number. This should be elsewhere.
8452 is_number(const char *p)
8457 } while (*++p != '\0');
8463 * Produce a possibly single quoted string suitable as input to the shell.
8464 * The return string is allocated on the stack.
8468 single_quote(const char *s) {
8477 len = strchrnul(s, '\'') - s;
8479 q = p = makestrspace(len + 3, p);
8482 q = mempcpy(q, s, len);
8488 len = strspn(s, "'");
8492 q = p = makestrspace(len + 3, p);
8495 q = mempcpy(q, s, len);
8504 return stackblock();
8508 * Like strdup but works with the ash stack.
8512 sstrdup(const char *p)
8514 size_t len = strlen(p) + 1;
8515 return memcpy(stalloc(len), p, len);
8520 calcsize(union node *n)
8524 funcblocksize += nodesize[n->type];
8527 calcsize(n->ncmd.redirect);
8528 calcsize(n->ncmd.args);
8529 calcsize(n->ncmd.assign);
8532 sizenodelist(n->npipe.cmdlist);
8537 calcsize(n->nredir.redirect);
8538 calcsize(n->nredir.n);
8545 calcsize(n->nbinary.ch2);
8546 calcsize(n->nbinary.ch1);
8549 calcsize(n->nif.elsepart);
8550 calcsize(n->nif.ifpart);
8551 calcsize(n->nif.test);
8554 funcstringsize += strlen(n->nfor.var) + 1;
8555 calcsize(n->nfor.body);
8556 calcsize(n->nfor.args);
8559 calcsize(n->ncase.cases);
8560 calcsize(n->ncase.expr);
8563 calcsize(n->nclist.body);
8564 calcsize(n->nclist.pattern);
8565 calcsize(n->nclist.next);
8569 sizenodelist(n->narg.backquote);
8570 funcstringsize += strlen(n->narg.text) + 1;
8571 calcsize(n->narg.next);
8578 calcsize(n->nfile.fname);
8579 calcsize(n->nfile.next);
8583 calcsize(n->ndup.vname);
8584 calcsize(n->ndup.next);
8588 calcsize(n->nhere.doc);
8589 calcsize(n->nhere.next);
8592 calcsize(n->nnot.com);
8599 sizenodelist(struct nodelist *lp)
8602 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8610 copynode(union node *n)
8617 funcblock = (char *) funcblock + nodesize[n->type];
8620 new->ncmd.redirect = copynode(n->ncmd.redirect);
8621 new->ncmd.args = copynode(n->ncmd.args);
8622 new->ncmd.assign = copynode(n->ncmd.assign);
8625 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8626 new->npipe.backgnd = n->npipe.backgnd;
8631 new->nredir.redirect = copynode(n->nredir.redirect);
8632 new->nredir.n = copynode(n->nredir.n);
8639 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8640 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8643 new->nif.elsepart = copynode(n->nif.elsepart);
8644 new->nif.ifpart = copynode(n->nif.ifpart);
8645 new->nif.test = copynode(n->nif.test);
8648 new->nfor.var = nodesavestr(n->nfor.var);
8649 new->nfor.body = copynode(n->nfor.body);
8650 new->nfor.args = copynode(n->nfor.args);
8653 new->ncase.cases = copynode(n->ncase.cases);
8654 new->ncase.expr = copynode(n->ncase.expr);
8657 new->nclist.body = copynode(n->nclist.body);
8658 new->nclist.pattern = copynode(n->nclist.pattern);
8659 new->nclist.next = copynode(n->nclist.next);
8663 new->narg.backquote = copynodelist(n->narg.backquote);
8664 new->narg.text = nodesavestr(n->narg.text);
8665 new->narg.next = copynode(n->narg.next);
8672 new->nfile.fname = copynode(n->nfile.fname);
8673 new->nfile.fd = n->nfile.fd;
8674 new->nfile.next = copynode(n->nfile.next);
8678 new->ndup.vname = copynode(n->ndup.vname);
8679 new->ndup.dupfd = n->ndup.dupfd;
8680 new->ndup.fd = n->ndup.fd;
8681 new->ndup.next = copynode(n->ndup.next);
8685 new->nhere.doc = copynode(n->nhere.doc);
8686 new->nhere.fd = n->nhere.fd;
8687 new->nhere.next = copynode(n->nhere.next);
8690 new->nnot.com = copynode(n->nnot.com);
8693 new->type = n->type;
8698 static struct nodelist *
8699 copynodelist(struct nodelist *lp)
8701 struct nodelist *start;
8702 struct nodelist **lpp;
8707 funcblock = (char *) funcblock +
8708 SHELL_ALIGN(sizeof(struct nodelist));
8709 (*lpp)->n = copynode(lp->n);
8711 lpp = &(*lpp)->next;
8719 nodesavestr(char *s)
8721 char *rtn = funcstring;
8723 funcstring = stpcpy(funcstring, s) + 1;
8729 * Free a parse tree.
8733 freefunc(struct funcnode *f)
8735 if (f && --f->count < 0)
8740 static void options(int);
8741 static void setoption(int, int);
8745 * Process the shell command line arguments.
8749 procargs(int argc, char **argv)
8752 const char *xminusc;
8759 for (i = 0; i < NOPTS; i++)
8765 if (*xargv == NULL) {
8767 error("-c requires an argument");
8770 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8774 for (i = 0; i < NOPTS; i++)
8775 if (optlist[i] == 2)
8780 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8785 } else if (!sflag) {
8786 setinputfile(*xargv, 0);
8792 shellparam.p = xargv;
8793 #ifdef CONFIG_ASH_GETOPTS
8794 shellparam.optind = 1;
8795 shellparam.optoff = -1;
8797 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8799 shellparam.nparam++;
8812 setinteractive(iflag);
8817 minus_o(char *name, int val)
8822 out1str("Current option settings\n");
8823 for (i = 0; i < NOPTS; i++)
8824 out1fmt("%-16s%s\n", optnames(i),
8825 optlist[i] ? "on" : "off");
8827 for (i = 0; i < NOPTS; i++)
8828 if (equal(name, optnames(i))) {
8832 error("Illegal option -o %s", name);
8837 * Process shell options. The global variable argptr contains a pointer
8838 * to the argument list; we advance it past the options.
8842 options(int cmdline)
8850 while ((p = *argptr) != NULL) {
8852 if ((c = *p++) == '-') {
8854 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8856 /* "-" means turn off -x and -v */
8859 /* "--" means reset params */
8860 else if (*argptr == NULL)
8863 break; /* "-" or "--" terminates options */
8865 } else if (c == '+') {
8871 while ((c = *p++) != '\0') {
8872 if (c == 'c' && cmdline) {
8873 minusc = p; /* command is after shell args*/
8874 } else if (c == 'o') {
8875 minus_o(*argptr, val);
8878 } else if (cmdline && (c == '-')) { // long options
8879 if (strcmp(p, "login") == 0)
8891 setoption(int flag, int val)
8895 for (i = 0; i < NOPTS; i++)
8896 if (optletters(i) == flag) {
8900 error("Illegal option -%c", flag);
8907 * Set the shell parameters.
8911 setparam(char **argv)
8917 for (nparam = 0 ; argv[nparam] ; nparam++);
8918 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
8920 *ap++ = savestr(*argv++);
8923 freeparam(&shellparam);
8924 shellparam.malloc = 1;
8925 shellparam.nparam = nparam;
8926 shellparam.p = newparam;
8927 #ifdef CONFIG_ASH_GETOPTS
8928 shellparam.optind = 1;
8929 shellparam.optoff = -1;
8935 * Free the list of positional parameters.
8939 freeparam(volatile struct shparam *param)
8943 if (param->malloc) {
8944 for (ap = param->p ; *ap ; ap++)
8953 * The shift builtin command.
8957 shiftcmd(int argc, char **argv)
8964 n = number(argv[1]);
8965 if (n > shellparam.nparam)
8966 error("can't shift that many");
8968 shellparam.nparam -= n;
8969 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
8970 if (shellparam.malloc)
8974 while ((*ap2++ = *ap1++) != NULL);
8975 #ifdef CONFIG_ASH_GETOPTS
8976 shellparam.optind = 1;
8977 shellparam.optoff = -1;
8986 * The set command builtin.
8990 setcmd(int argc, char **argv)
8993 return showvars(nullstr, 0, VUNSET);
8997 if (*argptr != NULL) {
9005 #ifdef CONFIG_ASH_GETOPTS
9010 shellparam.optind = number(value);
9011 shellparam.optoff = -1;
9015 #ifdef CONFIG_LOCALE_SUPPORT
9016 static void change_lc_all(const char *value)
9018 if (value != 0 && *value != 0)
9019 setlocale(LC_ALL, value);
9022 static void change_lc_ctype(const char *value)
9024 if (value != 0 && *value != 0)
9025 setlocale(LC_CTYPE, value);
9030 #ifdef CONFIG_ASH_GETOPTS
9032 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9039 char **optnext = optfirst + *param_optind - 1;
9041 if (*param_optind <= 1 || *optoff < 0 || !(*(optnext - 1)) ||
9042 strlen(*(optnext - 1)) < *optoff)
9045 p = *(optnext - 1) + *optoff;
9046 if (p == NULL || *p == '\0') {
9047 /* Current word is done, advance */
9048 if (optnext == NULL)
9051 if (p == NULL || *p != '-' || *++p == '\0') {
9058 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9063 for (q = optstr; *q != c; ) {
9065 if (optstr[0] == ':') {
9068 err |= setvarsafe("OPTARG", s, 0);
9070 fprintf(stderr, "Illegal option -%c\n", c);
9071 (void) unsetvar("OPTARG");
9081 if (*p == '\0' && (p = *optnext) == NULL) {
9082 if (optstr[0] == ':') {
9085 err |= setvarsafe("OPTARG", s, 0);
9088 fprintf(stderr, "No arg for -%c option\n", c);
9089 (void) unsetvar("OPTARG");
9097 err |= setvarsafe("OPTARG", p, 0);
9100 err |= setvarsafe("OPTARG", nullstr, 0);
9103 *optoff = p ? p - *(optnext - 1) : -1;
9104 *param_optind = optnext - optfirst + 1;
9105 fmtstr(s, sizeof(s), "%d", *param_optind);
9106 err |= setvarsafe("OPTIND", s, VNOFUNC);
9109 err |= setvarsafe(optvar, s, 0);
9120 * The getopts builtin. Shellparam.optnext points to the next argument
9121 * to be processed. Shellparam.optptr points to the next character to
9122 * be processed in the current argument. If shellparam.optnext is NULL,
9123 * then it's the first time getopts has been called.
9127 getoptscmd(int argc, char **argv)
9132 error("Usage: getopts optstring var [arg]");
9133 else if (argc == 3) {
9134 optbase = shellparam.p;
9135 if (shellparam.optind > shellparam.nparam + 1) {
9136 shellparam.optind = 1;
9137 shellparam.optoff = -1;
9142 if (shellparam.optind > argc - 2) {
9143 shellparam.optind = 1;
9144 shellparam.optoff = -1;
9148 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9149 &shellparam.optoff);
9151 #endif /* CONFIG_ASH_GETOPTS */
9154 * XXX - should get rid of. have all builtins use getopt(3). the
9155 * library getopt must have the BSD extension static variable "optreset"
9156 * otherwise it can't be used within the shell safely.
9158 * Standard option processing (a la getopt) for builtin routines. The
9159 * only argument that is passed to nextopt is the option string; the
9160 * other arguments are unnecessary. It return the character, or '\0' on
9165 nextopt(const char *optstring)
9171 if ((p = optptr) == NULL || *p == '\0') {
9173 if (p == NULL || *p != '-' || *++p == '\0')
9176 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9180 for (q = optstring ; *q != c ; ) {
9182 error("Illegal option -%c", c);
9187 if (*p == '\0' && (p = *argptr++) == NULL)
9188 error("No arg for -%c option", c);
9197 /* $NetBSD: output.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
9200 outstr(const char *p, FILE *file)
9217 flushout(FILE *dest)
9225 outcslow(int c, FILE *dest)
9235 out1fmt(const char *fmt, ...)
9242 r = vprintf(fmt, ap);
9250 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
9257 ret = vsnprintf(outbuf, length, fmt, ap);
9265 * Version of write which resumes after a signal is caught.
9269 xwrite(int fd, const void *p, size_t n)
9274 i = bb_full_write(fd, p, n);
9275 } while (i < 0 && errno == EINTR);
9279 /* $NetBSD: parser.c,v 1.54 2002/11/24 22:35:42 christos Exp $ */
9283 * Shell command parser.
9286 #define EOFMARKLEN 79
9290 struct heredoc *next; /* next here document in list */
9291 union node *here; /* redirection node */
9292 char *eofmark; /* string indicating end of input */
9293 int striptabs; /* if set, strip leading tabs */
9298 static struct heredoc *heredoclist; /* list of here documents to read */
9301 static union node *list(int);
9302 static union node *andor(void);
9303 static union node *pipeline(void);
9304 static union node *command(void);
9305 static union node *simplecmd(void);
9306 static union node *makename(void);
9307 static void parsefname(void);
9308 static void parseheredoc(void);
9309 static char peektoken(void);
9310 static int readtoken(void);
9311 static int xxreadtoken(void);
9312 static int readtoken1(int firstc, int syntax, char *eofmark, int striptabs);
9313 static int noexpand(char *);
9314 static void synexpect(int) __attribute__((__noreturn__));
9315 static void synerror(const char *) __attribute__((__noreturn__));
9316 static void setprompt(int);
9320 goodname(const char *p)
9322 return !*endofname(p);
9326 isassignment(const char *p)
9328 const char *q = endofname(p);
9336 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9337 * valid parse tree indicating a blank line.)
9341 parsecmd(int interact)
9346 doprompt = interact;
9348 setprompt(doprompt);
9363 union node *n1, *n2, *n3;
9366 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9367 if (nlflag == 2 && peektoken())
9373 if (tok == TBACKGND) {
9374 if (n2->type == NPIPE) {
9375 n2->npipe.backgnd = 1;
9377 if (n2->type != NREDIR) {
9378 n3 = stalloc(sizeof(struct nredir));
9380 n3->nredir.redirect = NULL;
9383 n2->type = NBACKGND;
9390 n3 = (union node *)stalloc(sizeof (struct nbinary));
9392 n3->nbinary.ch1 = n1;
9393 n3->nbinary.ch2 = n2;
9409 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9417 pungetc(); /* push back EOF on input */
9433 union node *n1, *n2, *n3;
9438 if ((t = readtoken()) == TAND) {
9440 } else if (t == TOR) {
9446 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9448 n3 = (union node *)stalloc(sizeof (struct nbinary));
9450 n3->nbinary.ch1 = n1;
9451 n3->nbinary.ch2 = n2;
9461 union node *n1, *n2, *pipenode;
9462 struct nodelist *lp, *prev;
9466 TRACE(("pipeline: entered\n"));
9467 if (readtoken() == TNOT) {
9469 checkkwd = CHKKWD | CHKALIAS;
9473 if (readtoken() == TPIPE) {
9474 pipenode = (union node *)stalloc(sizeof (struct npipe));
9475 pipenode->type = NPIPE;
9476 pipenode->npipe.backgnd = 0;
9477 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9478 pipenode->npipe.cmdlist = lp;
9482 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9483 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9486 } while (readtoken() == TPIPE);
9492 n2 = (union node *)stalloc(sizeof (struct nnot));
9505 union node *n1, *n2;
9506 union node *ap, **app;
9507 union node *cp, **cpp;
9508 union node *redir, **rpp;
9515 switch (readtoken()) {
9520 n1 = (union node *)stalloc(sizeof (struct nif));
9522 n1->nif.test = list(0);
9523 if (readtoken() != TTHEN)
9525 n1->nif.ifpart = list(0);
9527 while (readtoken() == TELIF) {
9528 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9529 n2 = n2->nif.elsepart;
9531 n2->nif.test = list(0);
9532 if (readtoken() != TTHEN)
9534 n2->nif.ifpart = list(0);
9536 if (lasttoken == TELSE)
9537 n2->nif.elsepart = list(0);
9539 n2->nif.elsepart = NULL;
9547 n1 = (union node *)stalloc(sizeof (struct nbinary));
9548 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9549 n1->nbinary.ch1 = list(0);
9550 if ((got=readtoken()) != TDO) {
9551 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9554 n1->nbinary.ch2 = list(0);
9559 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9560 synerror("Bad for loop variable");
9561 n1 = (union node *)stalloc(sizeof (struct nfor));
9563 n1->nfor.var = wordtext;
9564 checkkwd = CHKKWD | CHKALIAS;
9565 if (readtoken() == TIN) {
9567 while (readtoken() == TWORD) {
9568 n2 = (union node *)stalloc(sizeof (struct narg));
9570 n2->narg.text = wordtext;
9571 n2->narg.backquote = backquotelist;
9573 app = &n2->narg.next;
9577 if (lasttoken != TNL && lasttoken != TSEMI)
9580 n2 = (union node *)stalloc(sizeof (struct narg));
9582 n2->narg.text = (char *)dolatstr;
9583 n2->narg.backquote = NULL;
9584 n2->narg.next = NULL;
9587 * Newline or semicolon here is optional (but note
9588 * that the original Bourne shell only allowed NL).
9590 if (lasttoken != TNL && lasttoken != TSEMI)
9593 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9594 if (readtoken() != TDO)
9596 n1->nfor.body = list(0);
9600 n1 = (union node *)stalloc(sizeof (struct ncase));
9602 if (readtoken() != TWORD)
9604 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9606 n2->narg.text = wordtext;
9607 n2->narg.backquote = backquotelist;
9608 n2->narg.next = NULL;
9610 checkkwd = CHKKWD | CHKALIAS;
9611 } while (readtoken() == TNL);
9612 if (lasttoken != TIN)
9614 cpp = &n1->ncase.cases;
9616 checkkwd = CHKNL | CHKKWD;
9619 if (lasttoken == TLP)
9621 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9623 app = &cp->nclist.pattern;
9625 *app = ap = (union node *)stalloc(sizeof (struct narg));
9627 ap->narg.text = wordtext;
9628 ap->narg.backquote = backquotelist;
9629 if (readtoken() != TPIPE)
9631 app = &ap->narg.next;
9634 ap->narg.next = NULL;
9635 if (lasttoken != TRP)
9637 cp->nclist.body = list(2);
9639 cpp = &cp->nclist.next;
9641 checkkwd = CHKNL | CHKKWD;
9642 if ((t = readtoken()) != TESAC) {
9644 synexpect(TENDCASE);
9652 n1 = (union node *)stalloc(sizeof (struct nredir));
9653 n1->type = NSUBSHELL;
9654 n1->nredir.n = list(0);
9655 n1->nredir.redirect = NULL;
9668 if (readtoken() != t)
9672 /* Now check for redirection which may follow command */
9673 checkkwd = CHKKWD | CHKALIAS;
9675 while (readtoken() == TREDIR) {
9676 *rpp = n2 = redirnode;
9677 rpp = &n2->nfile.next;
9683 if (n1->type != NSUBSHELL) {
9684 n2 = (union node *)stalloc(sizeof (struct nredir));
9689 n1->nredir.redirect = redir;
9698 union node *args, **app;
9699 union node *n = NULL;
9700 union node *vars, **vpp;
9701 union node **rpp, *redir;
9711 savecheckkwd = CHKALIAS;
9713 checkkwd = savecheckkwd;
9714 switch (readtoken()) {
9716 n = (union node *)stalloc(sizeof (struct narg));
9718 n->narg.text = wordtext;
9719 n->narg.backquote = backquotelist;
9720 if (savecheckkwd && isassignment(wordtext)) {
9722 vpp = &n->narg.next;
9725 app = &n->narg.next;
9730 *rpp = n = redirnode;
9731 rpp = &n->nfile.next;
9732 parsefname(); /* read name of redirection file */
9736 args && app == &args->narg.next &&
9739 struct builtincmd *bcmd;
9742 /* We have a function */
9743 if (readtoken() != TRP)
9745 name = n->narg.text;
9747 !goodname(name) || (
9748 (bcmd = find_builtin(name)) &&
9749 IS_BUILTIN_SPECIAL(bcmd)
9752 synerror("Bad function name");
9754 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9755 n->narg.next = command();
9768 n = (union node *)stalloc(sizeof (struct ncmd));
9770 n->ncmd.args = args;
9771 n->ncmd.assign = vars;
9772 n->ncmd.redirect = redir;
9781 n = (union node *)stalloc(sizeof (struct narg));
9783 n->narg.next = NULL;
9784 n->narg.text = wordtext;
9785 n->narg.backquote = backquotelist;
9789 void fixredir(union node *n, const char *text, int err)
9791 TRACE(("Fix redir %s %d\n", text, err));
9793 n->ndup.vname = NULL;
9795 if (is_digit(text[0]) && text[1] == '\0')
9796 n->ndup.dupfd = digit_val(text[0]);
9797 else if (text[0] == '-' && text[1] == '\0')
9802 synerror("Bad fd number");
9804 n->ndup.vname = makename();
9812 union node *n = redirnode;
9814 if (readtoken() != TWORD)
9816 if (n->type == NHERE) {
9817 struct heredoc *here = heredoc;
9823 TRACE(("Here document %d\n", n->type));
9824 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9825 synerror("Illegal eof marker for << redirection");
9826 rmescapes(wordtext);
9827 here->eofmark = wordtext;
9829 if (heredoclist == NULL)
9832 for (p = heredoclist ; p->next ; p = p->next);
9835 } else if (n->type == NTOFD || n->type == NFROMFD) {
9836 fixredir(n, wordtext, 0);
9838 n->nfile.fname = makename();
9844 * Input any here documents.
9850 struct heredoc *here;
9861 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9862 here->eofmark, here->striptabs);
9863 n = (union node *)stalloc(sizeof (struct narg));
9864 n->narg.type = NARG;
9865 n->narg.next = NULL;
9866 n->narg.text = wordtext;
9867 n->narg.backquote = backquotelist;
9868 here->here->nhere.doc = n;
9873 static char peektoken(void)
9879 return tokname_array[t][0];
9887 int alreadyseen = tokpushback;
9890 #ifdef CONFIG_ASH_ALIAS
9899 if (checkkwd & CHKNL) {
9906 if (t != TWORD || quoteflag) {
9911 * check for keywords
9913 if (checkkwd & CHKKWD) {
9914 const char *const *pp;
9916 if ((pp = findkwd(wordtext))) {
9917 lasttoken = t = pp - tokname_array;
9918 TRACE(("keyword %s recognized\n", tokname(t)));
9923 if (checkkwd & CHKALIAS) {
9924 #ifdef CONFIG_ASH_ALIAS
9926 if ((ap = lookupalias(wordtext, 1)) != NULL) {
9928 pushstring(ap->val, ap);
9938 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
9940 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
9947 * Read the next input token.
9948 * If the token is a word, we set backquotelist to the list of cmds in
9949 * backquotes. We set quoteflag to true if any part of the word was
9951 * If the token is TREDIR, then we set redirnode to a structure containing
9953 * In all cases, the variable startlinno is set to the number of the line
9954 * on which the token starts.
9956 * [Change comment: here documents and internal procedures]
9957 * [Readtoken shouldn't have any arguments. Perhaps we should make the
9958 * word parsing code into a separate routine. In this case, readtoken
9959 * doesn't need to have any internal procedures, but parseword does.
9960 * We could also make parseoperator in essence the main routine, and
9961 * have parseword (readtoken1?) handle both words and redirection.]
9964 #define NEW_xxreadtoken
9965 #ifdef NEW_xxreadtoken
9967 /* singles must be first! */
9968 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
9970 static const char xxreadtoken_tokens[] = {
9971 TNL, TLP, TRP, /* only single occurrence allowed */
9972 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
9973 TEOF, /* corresponds to trailing nul */
9974 TAND, TOR, TENDCASE, /* if double occurrence */
9977 #define xxreadtoken_doubles \
9978 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
9979 #define xxreadtoken_singles \
9980 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
9982 static int xxreadtoken()
9994 startlinno = plinno;
9995 for (;;) { /* until token or start of word found */
9998 if ((c != ' ') && (c != '\t')
9999 #ifdef CONFIG_ASH_ALIAS
10004 while ((c = pgetc()) != '\n' && c != PEOF);
10006 } else if (c == '\\') {
10007 if (pgetc() != '\n') {
10011 startlinno = ++plinno;
10016 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10021 needprompt = doprompt;
10024 p = strchr(xxreadtoken_chars, c);
10027 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10030 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10031 if (pgetc() == *p) { /* double occurrence? */
10032 p += xxreadtoken_doubles + 1;
10039 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10047 #define RETURN(token) return lasttoken = token
10062 startlinno = plinno;
10063 for (;;) { /* until token or start of word found */
10066 case ' ': case '\t':
10067 #ifdef CONFIG_ASH_ALIAS
10072 while ((c = pgetc()) != '\n' && c != PEOF);
10076 if (pgetc() == '\n') {
10077 startlinno = ++plinno;
10086 needprompt = doprompt;
10091 if (pgetc() == '&')
10096 if (pgetc() == '|')
10101 if (pgetc() == ';')
10114 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10117 #endif /* NEW_xxreadtoken */
10121 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10122 * is not NULL, read a here document. In the latter case, eofmark is the
10123 * word which marks the end of the document and striptabs is true if
10124 * leading tabs should be stripped from the document. The argument firstc
10125 * is the first character of the input token or document.
10127 * Because C does not have internal subroutines, I have simulated them
10128 * using goto's to implement the subroutine linkage. The following macros
10129 * will run code that appears at the end of readtoken1.
10132 #define CHECKEND() {goto checkend; checkend_return:;}
10133 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10134 #define PARSESUB() {goto parsesub; parsesub_return:;}
10135 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10136 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10137 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10140 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10145 char line[EOFMARKLEN + 1];
10146 struct nodelist *bqlist;
10149 int varnest; /* levels of variables expansion */
10150 int arinest; /* levels of arithmetic expansion */
10151 int parenlevel; /* levels of parens in arithmetic */
10152 int dqvarnest; /* levels of variables expansion within double quotes */
10154 int prevsyntax; /* syntax before arithmetic */
10156 /* Avoid longjmp clobbering */
10162 (void) &parenlevel;
10165 (void) &prevsyntax;
10169 startlinno = plinno;
10171 if (syntax == DQSYNTAX)
10180 STARTSTACKSTR(out);
10181 loop: { /* for each line, until end of word */
10182 CHECKEND(); /* set c to PEOF if at end of here document */
10183 for (;;) { /* until end of line or end of word */
10184 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10185 switch(SIT(c, syntax)) {
10186 case CNL: /* '\n' */
10187 if (syntax == BASESYNTAX)
10188 goto endword; /* exit outer loop */
10194 goto loop; /* continue outer loop */
10199 if (eofmark == NULL || dblquote)
10200 USTPUTC(CTLESC, out);
10203 case CBACK: /* backslash */
10206 USTPUTC(CTLESC, out);
10207 USTPUTC('\\', out);
10209 } else if (c == '\n') {
10215 c != '\\' && c != '`' &&
10221 USTPUTC(CTLESC, out);
10222 USTPUTC('\\', out);
10224 if (SIT(c, SQSYNTAX) == CCTL)
10225 USTPUTC(CTLESC, out);
10233 if (eofmark == NULL) {
10234 USTPUTC(CTLQUOTEMARK, out);
10242 if (eofmark != NULL && arinest == 0 &&
10246 if (dqvarnest == 0) {
10247 syntax = BASESYNTAX;
10254 case CVAR: /* '$' */
10255 PARSESUB(); /* parse substitution */
10257 case CENDVAR: /* '}' */
10260 if (dqvarnest > 0) {
10263 USTPUTC(CTLENDVAR, out);
10268 #ifdef CONFIG_ASH_MATH_SUPPORT
10269 case CLP: /* '(' in arithmetic */
10273 case CRP: /* ')' in arithmetic */
10274 if (parenlevel > 0) {
10278 if (pgetc() == ')') {
10279 if (--arinest == 0) {
10280 USTPUTC(CTLENDARI, out);
10281 syntax = prevsyntax;
10282 if (syntax == DQSYNTAX)
10290 * unbalanced parens
10291 * (don't 2nd guess - no error)
10299 case CBQUOTE: /* '`' */
10303 goto endword; /* exit outer loop */
10308 goto endword; /* exit outer loop */
10309 #ifdef CONFIG_ASH_ALIAS
10319 #ifdef CONFIG_ASH_MATH_SUPPORT
10320 if (syntax == ARISYNTAX)
10321 synerror("Missing '))'");
10323 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10324 synerror("Unterminated quoted string");
10325 if (varnest != 0) {
10326 startlinno = plinno;
10328 synerror("Missing '}'");
10330 USTPUTC('\0', out);
10331 len = out - (char *)stackblock();
10332 out = stackblock();
10333 if (eofmark == NULL) {
10334 if ((c == '>' || c == '<')
10337 && (*out == '\0' || is_digit(*out))) {
10339 return lasttoken = TREDIR;
10344 quoteflag = quotef;
10345 backquotelist = bqlist;
10346 grabstackblock(len);
10348 return lasttoken = TWORD;
10349 /* end of readtoken routine */
10354 * Check to see whether we are at the end of the here document. When this
10355 * is called, c is set to the first character of the next input line. If
10356 * we are at the end of the here document, this routine sets the c to PEOF.
10361 #ifdef CONFIG_ASH_ALIAS
10367 while (c == '\t') {
10371 if (c == *eofmark) {
10372 if (pfgets(line, sizeof line) != NULL) {
10376 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10377 if (*p == '\n' && *q == '\0') {
10380 needprompt = doprompt;
10382 pushstring(line, NULL);
10387 goto checkend_return;
10392 * Parse a redirection operator. The variable "out" points to a string
10393 * specifying the fd to be redirected. The variable "c" contains the
10394 * first character of the redirection operator.
10401 np = (union node *)stalloc(sizeof (struct nfile));
10406 np->type = NAPPEND;
10408 np->type = NCLOBBER;
10415 } else { /* c == '<' */
10417 switch (c = pgetc()) {
10419 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10420 np = (union node *)stalloc(sizeof (struct nhere));
10424 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10425 heredoc->here = np;
10426 if ((c = pgetc()) == '-') {
10427 heredoc->striptabs = 1;
10429 heredoc->striptabs = 0;
10435 np->type = NFROMFD;
10439 np->type = NFROMTO;
10449 np->nfile.fd = digit_val(fd);
10451 goto parseredir_return;
10456 * Parse a substitution. At this point, we have read the dollar sign
10457 * and nothing else.
10465 static const char types[] = "}-+?=";
10469 c <= PEOA_OR_PEOF ||
10470 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10474 } else if (c == '(') { /* $(command) or $((arith)) */
10475 if (pgetc() == '(') {
10476 #ifdef CONFIG_ASH_MATH_SUPPORT
10479 synerror("We unsupport $((arith))");
10486 USTPUTC(CTLVAR, out);
10487 typeloc = out - (char *)stackblock();
10488 USTPUTC(VSNORMAL, out);
10489 subtype = VSNORMAL;
10493 if ((c = pgetc()) == '}')
10496 subtype = VSLENGTH;
10501 if (c > PEOA_OR_PEOF && is_name(c)) {
10505 } while (c > PEOA_OR_PEOF && is_in_name(c));
10506 } else if (is_digit(c)) {
10510 } while (is_digit(c));
10512 else if (is_special(c)) {
10517 badsub: synerror("Bad substitution");
10521 if (subtype == 0) {
10528 p = strchr(types, c);
10531 subtype = p - types + VSNORMAL;
10537 subtype = c == '#' ? VSTRIMLEFT :
10550 if (dblquote || arinest)
10552 *((char *)stackblock() + typeloc) = subtype | flags;
10553 if (subtype != VSNORMAL) {
10555 if (dblquote || arinest) {
10560 goto parsesub_return;
10565 * Called to parse command substitutions. Newstyle is set if the command
10566 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10567 * list of commands (passed by reference), and savelen is the number of
10568 * characters on the top of the stack which must be preserved.
10572 struct nodelist **nlpp;
10575 char *volatile str;
10576 struct jmploc jmploc;
10577 struct jmploc *volatile savehandler;
10581 (void) &saveprompt;
10584 savepbq = parsebackquote;
10585 if (setjmp(jmploc.loc)) {
10588 parsebackquote = 0;
10589 handler = savehandler;
10590 longjmp(handler->loc, 1);
10594 savelen = out - (char *)stackblock();
10596 str = ckmalloc(savelen);
10597 memcpy(str, stackblock(), savelen);
10599 savehandler = handler;
10603 /* We must read until the closing backquote, giving special
10604 treatment to some slashes, and then push the string and
10605 reread it as input, interpreting it normally. */
10612 STARTSTACKSTR(pout);
10618 switch (pc = pgetc()) {
10623 if ((pc = pgetc()) == '\n') {
10628 * If eating a newline, avoid putting
10629 * the newline into the new character
10630 * stream (via the STPUTC after the
10635 if (pc != '\\' && pc != '`' && pc != '$'
10636 && (!dblquote || pc != '"'))
10637 STPUTC('\\', pout);
10638 if (pc > PEOA_OR_PEOF) {
10644 #ifdef CONFIG_ASH_ALIAS
10647 startlinno = plinno;
10648 synerror("EOF in backquote substitution");
10652 needprompt = doprompt;
10661 STPUTC('\0', pout);
10662 psavelen = pout - (char *)stackblock();
10663 if (psavelen > 0) {
10664 pstr = grabstackstr(pout);
10665 setinputstring(pstr);
10670 nlpp = &(*nlpp)->next;
10671 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10672 (*nlpp)->next = NULL;
10673 parsebackquote = oldstyle;
10676 saveprompt = doprompt;
10683 doprompt = saveprompt;
10685 if (readtoken() != TRP)
10692 * Start reading from old file again, ignoring any pushed back
10693 * tokens left from the backquote parsing
10698 while (stackblocksize() <= savelen)
10700 STARTSTACKSTR(out);
10702 memcpy(out, str, savelen);
10703 STADJUST(savelen, out);
10709 parsebackquote = savepbq;
10710 handler = savehandler;
10711 if (arinest || dblquote)
10712 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10714 USTPUTC(CTLBACKQ, out);
10716 goto parsebackq_oldreturn;
10718 goto parsebackq_newreturn;
10721 #ifdef CONFIG_ASH_MATH_SUPPORT
10723 * Parse an arithmetic expansion (indicate start of one and set state)
10727 if (++arinest == 1) {
10728 prevsyntax = syntax;
10729 syntax = ARISYNTAX;
10730 USTPUTC(CTLARI, out);
10737 * we collapse embedded arithmetic expansion to
10738 * parenthesis, which should be equivalent
10742 goto parsearith_return;
10746 } /* end of readtoken */
10751 * Returns true if the text contains nothing to expand (no dollar signs
10756 noexpand(char *text)
10762 while ((c = *p++) != '\0') {
10763 if (c == CTLQUOTEMARK)
10767 else if (SIT(c, BASESYNTAX) == CCTL)
10775 * Return of a legal variable name (a letter or underscore followed by zero or
10776 * more letters, underscores, and digits).
10780 endofname(const char *name)
10788 if (! is_in_name(*p))
10796 * Called when an unexpected token is read during the parse. The argument
10797 * is the token that is expected, or -1 if more than one type of token can
10798 * occur at this point.
10801 static void synexpect(int token)
10806 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10808 sprintf(msg + l, " (expecting %s)", tokname(token));
10814 synerror(const char *msg)
10816 error("Syntax error: %s", msg);
10822 * called by editline -- any expansions to the prompt
10823 * should be added here.
10826 static void setprompt(int whichprompt)
10828 const char *prompt;
10830 switch (whichprompt) {
10844 static const char *const *findkwd(const char *s)
10846 return bsearch(s, tokname_array + KWDOFFSET,
10847 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
10848 sizeof(const char *), pstrcmp);
10851 /* $NetBSD: redir.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
10854 * Code for dealing with input/output redirection.
10857 #define EMPTY -2 /* marks an unused slot in redirtab */
10859 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10861 # define PIPESIZE PIPE_BUF
10865 * Open a file in noclobber mode.
10866 * The code was copied from bash.
10869 noclobberopen(const char *fname)
10872 struct stat finfo, finfo2;
10875 * If the file exists and is a regular file, return an error
10878 r = stat(fname, &finfo);
10879 if (r == 0 && S_ISREG(finfo.st_mode)) {
10885 * If the file was not present (r != 0), make sure we open it
10886 * exclusively so that if it is created before we open it, our open
10887 * will fail. Make sure that we do not truncate an existing file.
10888 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10889 * file was not a regular file, we leave O_EXCL off.
10892 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
10893 fd = open(fname, O_WRONLY|O_CREAT, 0666);
10895 /* If the open failed, return the file descriptor right away. */
10900 * OK, the open succeeded, but the file may have been changed from a
10901 * non-regular file to a regular file between the stat and the open.
10902 * We are assuming that the O_EXCL open handles the case where FILENAME
10903 * did not exist and is symlinked to an existing file between the stat
10908 * If we can open it and fstat the file descriptor, and neither check
10909 * revealed that it was a regular file, and the file has not been
10910 * replaced, return the file descriptor.
10912 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10913 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10916 /* The file has been replaced. badness. */
10923 * Handle here documents. Normally we fork off a process to write the
10924 * data to a pipe. If the document is short, we can stuff the data in
10925 * the pipe without forking.
10929 openhere(union node *redir)
10935 error("Pipe call failed");
10936 if (redir->type == NHERE) {
10937 len = strlen(redir->nhere.doc->narg.text);
10938 if (len <= PIPESIZE) {
10939 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10943 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
10945 signal(SIGINT, SIG_IGN);
10946 signal(SIGQUIT, SIG_IGN);
10947 signal(SIGHUP, SIG_IGN);
10949 signal(SIGTSTP, SIG_IGN);
10951 signal(SIGPIPE, SIG_DFL);
10952 if (redir->type == NHERE)
10953 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10955 expandhere(redir->nhere.doc, pip[1]);
10964 openredirect(union node *redir)
10969 switch (redir->nfile.type) {
10971 fname = redir->nfile.expfname;
10972 if ((f = open(fname, O_RDONLY)) < 0)
10976 fname = redir->nfile.expfname;
10977 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
10981 /* Take care of noclobber mode. */
10983 fname = redir->nfile.expfname;
10984 if ((f = noclobberopen(fname)) < 0)
10990 fname = redir->nfile.expfname;
10991 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
10995 fname = redir->nfile.expfname;
10996 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
11003 /* Fall through to eliminate warning. */
11010 f = openhere(redir);
11016 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11018 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11022 dupredirect(union node *redir, int f)
11024 int fd = redir->nfile.fd;
11026 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11027 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11028 copyfd(redir->ndup.dupfd, fd);
11041 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11042 * old file descriptors are stashed away so that the redirection can be
11043 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11044 * standard output, and the standard error if it becomes a duplicate of
11045 * stdout, is saved in memory.
11049 redirect(union node *redir, int flags)
11052 struct redirtab *sv;
11063 if (flags & REDIR_PUSH) {
11064 struct redirtab *q;
11065 q = ckmalloc(sizeof (struct redirtab));
11066 q->next = redirlist;
11068 q->nullredirs = nullredirs - 1;
11069 for (i = 0 ; i < 10 ; i++)
11070 q->renamed[i] = EMPTY;
11077 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11078 n->ndup.dupfd == fd)
11079 continue; /* redirect from/to same file descriptor */
11081 newfd = openredirect(n);
11084 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
11085 i = fcntl(fd, F_DUPFD, 10);
11092 error("%d: %m", fd);
11102 dupredirect(n, newfd);
11103 } while ((n = n->nfile.next));
11105 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
11106 preverrout_fd = sv->renamed[2];
11111 * Undo the effects of the last redirection.
11117 struct redirtab *rp;
11120 if (--nullredirs >= 0)
11124 for (i = 0 ; i < 10 ; i++) {
11125 if (rp->renamed[i] != EMPTY) {
11128 copyfd(rp->renamed[i], i);
11130 close(rp->renamed[i]);
11133 redirlist = rp->next;
11134 nullredirs = rp->nullredirs;
11140 * Undo all redirections. Called on error or interrupt.
11144 * Discard all saved file descriptors.
11148 clearredir(int drop)
11160 * Copy a file descriptor to be >= to. Returns -1
11161 * if the source file descriptor is closed, EMPTY if there are no unused
11162 * file descriptors left.
11166 copyfd(int from, int to)
11170 newfd = fcntl(from, F_DUPFD, to);
11172 if (errno == EMFILE)
11175 error("%d: %m", from);
11182 redirectsafe(union node *redir, int flags)
11185 volatile int saveint;
11186 struct jmploc *volatile savehandler = handler;
11187 struct jmploc jmploc;
11190 if (!(err = setjmp(jmploc.loc) * 2)) {
11192 redirect(redir, flags);
11194 handler = savehandler;
11195 if (err && exception != EXERROR)
11196 longjmp(handler->loc, 1);
11197 RESTOREINT(saveint);
11201 /* $NetBSD: show.c,v 1.24 2003/01/22 20:36:04 dsl Exp $ */
11204 static void shtree(union node *, int, char *, FILE*);
11205 static void shcmd(union node *, FILE *);
11206 static void sharg(union node *, FILE *);
11207 static void indent(int, char *, FILE *);
11208 static void trstring(char *);
11212 showtree(union node *n)
11214 trputs("showtree called\n");
11215 shtree(n, 1, NULL, stdout);
11220 shtree(union node *n, int ind, char *pfx, FILE *fp)
11222 struct nodelist *lp;
11228 indent(ind, pfx, fp);
11239 shtree(n->nbinary.ch1, ind, NULL, fp);
11242 shtree(n->nbinary.ch2, ind, NULL, fp);
11250 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11255 if (n->npipe.backgnd)
11261 fprintf(fp, "<node type %d>", n->type);
11270 shcmd(union node *cmd, FILE *fp)
11278 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11284 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11287 switch (np->nfile.type) {
11288 case NTO: s = ">"; dftfd = 1; break;
11289 case NCLOBBER: s = ">|"; dftfd = 1; break;
11290 case NAPPEND: s = ">>"; dftfd = 1; break;
11291 case NTOFD: s = ">&"; dftfd = 1; break;
11292 case NFROM: s = "<"; dftfd = 0; break;
11293 case NFROMFD: s = "<&"; dftfd = 0; break;
11294 case NFROMTO: s = "<>"; dftfd = 0; break;
11295 default: s = "*error*"; dftfd = 0; break;
11297 if (np->nfile.fd != dftfd)
11298 fprintf(fp, "%d", np->nfile.fd);
11300 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11301 fprintf(fp, "%d", np->ndup.dupfd);
11303 sharg(np->nfile.fname, fp);
11312 sharg(union node *arg, FILE *fp)
11315 struct nodelist *bqlist;
11318 if (arg->type != NARG) {
11319 out1fmt("<node type %d>\n", arg->type);
11322 bqlist = arg->narg.backquote;
11323 for (p = arg->narg.text ; *p ; p++) {
11332 if (subtype == VSLENGTH)
11338 if (subtype & VSNUL)
11341 switch (subtype & VSTYPE) {
11360 case VSTRIMLEFTMAX:
11367 case VSTRIMRIGHTMAX:
11374 out1fmt("<subtype %d>", subtype);
11381 case CTLBACKQ|CTLQUOTE:
11384 shtree(bqlist->n, -1, NULL, fp);
11396 indent(int amount, char *pfx, FILE *fp)
11400 for (i = 0 ; i < amount ; i++) {
11401 if (pfx && i == amount - 1)
11422 putc(c, tracefile);
11426 trace(const char *fmt, ...)
11433 (void) vfprintf(tracefile, fmt, va);
11438 tracev(const char *fmt, va_list va)
11442 (void) vfprintf(tracefile, fmt, va);
11447 trputs(const char *s)
11451 fputs(s, tracefile);
11463 putc('"', tracefile);
11464 for (p = s ; *p ; p++) {
11466 case '\n': c = 'n'; goto backslash;
11467 case '\t': c = 't'; goto backslash;
11468 case '\r': c = 'r'; goto backslash;
11469 case '"': c = '"'; goto backslash;
11470 case '\\': c = '\\'; goto backslash;
11471 case CTLESC: c = 'e'; goto backslash;
11472 case CTLVAR: c = 'v'; goto backslash;
11473 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11474 case CTLBACKQ: c = 'q'; goto backslash;
11475 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11476 backslash: putc('\\', tracefile);
11477 putc(c, tracefile);
11480 if (*p >= ' ' && *p <= '~')
11481 putc(*p, tracefile);
11483 putc('\\', tracefile);
11484 putc(*p >> 6 & 03, tracefile);
11485 putc(*p >> 3 & 07, tracefile);
11486 putc(*p & 07, tracefile);
11491 putc('"', tracefile);
11503 putc(' ', tracefile);
11505 putc('\n', tracefile);
11521 /* leave open because libedit might be using it */
11524 scopy("./trace", s);
11526 if (!freopen(s, "a", tracefile)) {
11527 fprintf(stderr, "Can't re-open %s\n", s);
11532 if ((tracefile = fopen(s, "a")) == NULL) {
11533 fprintf(stderr, "Can't open %s\n", s);
11539 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11540 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11542 setlinebuf(tracefile);
11543 fputs("\nTracing started.\n", tracefile);
11548 /* $NetBSD: trap.c,v 1.28 2002/11/24 22:35:43 christos Exp $ */
11551 * Sigmode records the current value of the signal handlers for the various
11552 * modes. A value of zero means that the current handler is not known.
11553 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
11556 #define S_DFL 1 /* default signal handling (SIG_DFL) */
11557 #define S_CATCH 2 /* signal is caught */
11558 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
11559 #define S_HARD_IGN 4 /* signal is ignored permenantly */
11560 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
11565 * The trap builtin.
11569 trapcmd(int argc, char **argv)
11578 for (signo = 0 ; signo < NSIG ; signo++) {
11579 if (trap[signo] != NULL) {
11582 sn = u_signal_names(0, &signo, 0);
11585 out1fmt("trap -- %s %s\n",
11586 single_quote(trap[signo]), sn);
11596 if ((signo = decode_signal(*ap, 0)) < 0)
11597 error("%s: bad trap", *ap);
11600 if (action[0] == '-' && action[1] == '\0')
11603 action = savestr(action);
11606 ckfree(trap[signo]);
11607 trap[signo] = action;
11618 * Clear traps on a fork.
11626 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
11627 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
11631 if (tp != &trap[0])
11632 setsignal(tp - trap);
11640 * Set the signal handler for the specified signal. The routine figures
11641 * out what it should be set to.
11645 setsignal(int signo)
11649 struct sigaction act;
11651 if ((t = trap[signo]) == NULL)
11653 else if (*t != '\0')
11657 if (rootshell && action == S_DFL) {
11660 if (iflag || minusc || sflag == 0)
11683 t = &sigmode[signo - 1];
11687 * current setting unknown
11689 if (sigaction(signo, 0, &act) == -1) {
11691 * Pretend it worked; maybe we should give a warning
11692 * here, but other shells don't. We don't alter
11693 * sigmode, so that we retry every time.
11697 if (act.sa_handler == SIG_IGN) {
11698 if (mflag && (signo == SIGTSTP ||
11699 signo == SIGTTIN || signo == SIGTTOU)) {
11700 tsig = S_IGN; /* don't hard ignore these */
11704 tsig = S_RESET; /* force to be set */
11707 if (tsig == S_HARD_IGN || tsig == action)
11711 act.sa_handler = onsig;
11714 act.sa_handler = SIG_IGN;
11717 act.sa_handler = SIG_DFL;
11721 sigfillset(&act.sa_mask);
11722 sigaction(signo, &act, 0);
11730 ignoresig(int signo)
11732 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11733 signal(signo, SIG_IGN);
11735 sigmode[signo - 1] = S_HARD_IGN;
11746 gotsig[signo - 1] = 1;
11747 pendingsigs = signo;
11749 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
11758 * Called to execute a trap. Perhaps we should avoid entering new trap
11759 * handlers while we are executing a trap handler.
11769 savestatus = exitstatus;
11771 while (pendingsigs = 0, barrier(), (p = memchr(q, 1, NSIG - 1))) {
11773 p = trap[p - q + 1];
11777 exitstatus = savestatus;
11783 * Controls whether the shell is interactive or not.
11787 setinteractive(int on)
11789 static int is_interactive;
11791 if (++on == is_interactive)
11793 is_interactive = on;
11795 setsignal(SIGQUIT);
11796 setsignal(SIGTERM);
11797 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
11798 if(is_interactive > 1) {
11799 /* Looks like they want an interactive shell */
11800 static int do_banner;
11804 "\n\n" BB_BANNER " Built-in shell (ash)\n"
11805 "Enter 'help' for a list of built-in commands.\n\n");
11813 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
11814 /*** List the available builtins ***/
11816 static int helpcmd(int argc, char **argv)
11820 out1fmt("\nBuilt-in commands:\n-------------------\n");
11821 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11822 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11823 builtincmd[i].name + 1);
11829 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
11831 extern const struct BB_applet applets[];
11832 extern const size_t NUM_APPLETS;
11834 for (i = 0; i < NUM_APPLETS; i++) {
11836 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11845 return EXIT_SUCCESS;
11847 #endif /* CONFIG_FEATURE_SH_EXTRA_QUIET */
11850 * Called to exit the shell.
11860 status = exitstatus;
11861 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
11862 if (setjmp(loc.loc)) {
11866 if ((p = trap[0]) != NULL && *p != '\0') {
11871 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
11872 if (iflag && rootshell) {
11873 const char *hp = lookupvar("HISTFILE");
11876 save_history ( hp );
11884 static int decode_signal(const char *string, int minsig)
11887 const char *name = u_signal_names(string, &signo, minsig);
11889 return name ? signo : -1;
11892 /* $NetBSD: var.c,v 1.32 2003/01/22 20:36:04 dsl Exp $ */
11894 static struct var *vartab[VTABSIZE];
11896 static int vpcmp(const void *, const void *);
11897 static struct var **findvar(struct var **, const char *);
11900 * Initialize the varable symbol tables and import the environment
11904 #ifdef CONFIG_ASH_GETOPTS
11906 * Safe version of setvar, returns 1 on success 0 on failure.
11910 setvarsafe(const char *name, const char *val, int flags)
11913 volatile int saveint;
11914 struct jmploc *volatile savehandler = handler;
11915 struct jmploc jmploc;
11918 if (setjmp(jmploc.loc))
11922 setvar(name, val, flags);
11925 handler = savehandler;
11926 RESTOREINT(saveint);
11932 * Set the value of a variable. The flags argument is ored with the
11933 * flags of the variable. If val is NULL, the variable is unset.
11937 setvar(const char *name, const char *val, int flags)
11944 q = endofname(name);
11945 p = strchrnul(q, '=');
11946 namelen = p - name;
11947 if (!namelen || p != q)
11948 error("%.*s: bad variable name", namelen, name);
11953 vallen = strlen(val);
11956 p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen);
11960 p = mempcpy(p, val, vallen);
11963 setvareq(nameeq, flags | VNOSAVE);
11969 * Same as setvar except that the variable and value are passed in
11970 * the first argument as name=value. Since the first argument will
11971 * be actually stored in the table, it should not be a string that
11973 * Called with interrupts off.
11977 setvareq(char *s, int flags)
11979 struct var *vp, **vpp;
11982 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11983 vp = *findvar(vpp, s);
11985 if (vp->flags & VREADONLY) {
11986 if (flags & VNOSAVE)
11988 error("%.*s: is read only", strchrnul(s, '=') - s, s);
11991 if (flags & VNOSET)
11994 if (vp->func && (flags & VNOFUNC) == 0)
11995 (*vp->func)(strchrnul(s, '=') + 1);
11997 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12000 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
12002 if (flags & VNOSET)
12005 vp = ckmalloc(sizeof (*vp));
12010 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
12018 * Process a linked list of variable assignments.
12022 listsetvar(struct strlist *list_set_var, int flags)
12024 struct strlist *lp = list_set_var;
12030 setvareq(lp->text, flags);
12031 } while ((lp = lp->next));
12037 * Find the value of a variable. Returns NULL if not set.
12041 lookupvar(const char *name)
12045 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12046 return strchrnul(v->text, '=') + 1;
12053 * Search the environment of a builtin command.
12057 bltinlookup(const char *name)
12059 struct strlist *sp;
12061 for (sp = cmdenviron ; sp ; sp = sp->next) {
12062 if (varequal(sp->text, name))
12063 return strchrnul(sp->text, '=') + 1;
12065 return lookupvar(name);
12070 * Generate a list of variables satisfying the given conditions.
12074 listvars(int on, int off, char ***end)
12085 for (vp = *vpp ; vp ; vp = vp->next)
12086 if ((vp->flags & mask) == on) {
12087 if (ep == stackstrend())
12088 ep = growstackstr();
12089 *ep++ = (char *) vp->text;
12091 } while (++vpp < vartab + VTABSIZE);
12092 if (ep == stackstrend())
12093 ep = growstackstr();
12097 return grabstackstr(ep);
12102 * POSIX requires that 'set' (but not export or readonly) output the
12103 * variables in lexicographic order - by the locale's collating order (sigh).
12104 * Maybe we could keep them in an ordered balanced binary tree
12105 * instead of hashed lists.
12106 * For now just roll 'em through qsort for printing...
12110 showvars(const char *sep_prefix, int on, int off)
12113 char **ep, **epend;
12115 ep = listvars(on, off, &epend);
12116 qsort(ep, epend - ep, sizeof(char *), vpcmp);
12118 sep = *sep_prefix ? spcstr : sep_prefix;
12120 for (; ep < epend; ep++) {
12124 p = strchrnul(*ep, '=');
12127 q = single_quote(++p);
12129 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
12138 * The export and readonly commands.
12142 exportcmd(int argc, char **argv)
12148 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12151 notp = nextopt("p") - 'p';
12152 if (notp && ((name = *(aptr = argptr)))) {
12154 if ((p = strchr(name, '=')) != NULL) {
12157 if ((vp = *findvar(hashvar(name), name))) {
12162 setvar(name, p, flag);
12163 } while ((name = *++aptr) != NULL);
12165 showvars(argv[0], flag, 0);
12172 * Make a variable a local variable. When a variable is made local, it's
12173 * value and flags are saved in a localvar structure. The saved values
12174 * will be restored when the shell function returns. We handle the name
12175 * "-" as a special case.
12179 mklocal(char *name)
12181 struct localvar *lvp;
12186 lvp = ckmalloc(sizeof (struct localvar));
12187 if (name[0] == '-' && name[1] == '\0') {
12189 p = ckmalloc(sizeof(optlist));
12190 lvp->text = memcpy(p, optlist, sizeof(optlist));
12195 vpp = hashvar(name);
12196 vp = *findvar(vpp, name);
12197 eq = strchr(name, '=');
12200 setvareq(name, VSTRFIXED);
12202 setvar(name, NULL, VSTRFIXED);
12203 vp = *vpp; /* the new variable */
12204 lvp->flags = VUNSET;
12206 lvp->text = vp->text;
12207 lvp->flags = vp->flags;
12208 vp->flags |= VSTRFIXED|VTEXTFIXED;
12214 lvp->next = localvars;
12220 * The "local" command.
12224 localcmd(int argc, char **argv)
12229 while ((name = *argv++) != NULL) {
12237 * Called after a function returns.
12238 * Interrupts must be off.
12244 struct localvar *lvp;
12247 while ((lvp = localvars) != NULL) {
12248 localvars = lvp->next;
12250 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
12251 if (vp == NULL) { /* $- saved */
12252 memcpy(optlist, lvp->text, sizeof(optlist));
12255 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12256 unsetvar(vp->text);
12259 (*vp->func)(strchrnul(lvp->text, '=') + 1);
12260 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12262 vp->flags = lvp->flags;
12263 vp->text = lvp->text;
12271 * The unset builtin command. We unset the function before we unset the
12272 * variable to allow a function to be unset when there is a readonly variable
12273 * with the same name.
12277 unsetcmd(int argc, char **argv)
12284 while ((i = nextopt("vf")) != '\0') {
12288 for (ap = argptr; *ap ; ap++) {
12303 * Unset the specified variable.
12307 unsetvar(const char *s)
12313 vpp = findvar(hashvar(s), s);
12317 int flags = vp->flags;
12320 if (flags & VREADONLY)
12322 if (flags & VUNSET)
12324 if ((flags & VSTRFIXED) == 0) {
12326 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
12333 vp->flags &= ~VEXPORT;
12346 * Find the appropriate entry in the hash table from the name.
12349 static struct var **
12350 hashvar(const char *p)
12352 unsigned int hashval;
12354 hashval = ((unsigned char) *p) << 4;
12355 while (*p && *p != '=')
12356 hashval += (unsigned char) *p++;
12357 return &vartab[hashval % VTABSIZE];
12363 * Compares two strings up to the first = or '\0'. The first
12364 * string must be terminated by '='; the second may be terminated by
12365 * either '=' or '\0'.
12369 varcmp(const char *p, const char *q)
12373 while ((c = *p) == (d = *q)) {
12374 if (!c || c == '=')
12388 vpcmp(const void *a, const void *b)
12390 return varcmp(*(const char **)a, *(const char **)b);
12393 static struct var **
12394 findvar(struct var **vpp, const char *name)
12396 for (; *vpp; vpp = &(*vpp)->next) {
12397 if (varequal((*vpp)->text, name)) {
12403 /* $NetBSD: setmode.c,v 1.29 2003/01/15 23:58:03 kleink Exp $ */
12405 #include <sys/times.h>
12407 static const unsigned char timescmd_str[] = {
12408 ' ', offsetof(struct tms, tms_utime),
12409 '\n', offsetof(struct tms, tms_stime),
12410 ' ', offsetof(struct tms, tms_cutime),
12411 '\n', offsetof(struct tms, tms_cstime),
12415 static int timescmd(int ac, char **av)
12417 long int clk_tck, s, t;
12418 const unsigned char *p;
12421 clk_tck = sysconf(_SC_CLK_TCK);
12426 t = *(clock_t *)(((char *) &buf) + p[1]);
12428 out1fmt("%ldm%ld.%.3lds%c",
12430 ((t - s * clk_tck) * 1000) / clk_tck,
12432 } while (*(p += 2));
12437 #ifdef CONFIG_ASH_MATH_SUPPORT
12439 dash_arith(const char *s)
12445 result = arith(s, &errcode);
12448 error("exponent less than 0");
12449 else if (errcode == -2)
12450 error("divide by zero");
12451 else if (errcode == -5)
12452 error("expression recursion loop detected");
12463 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12464 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12466 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12470 letcmd(int argc, char **argv)
12477 error("expression expected");
12478 for (ap = argv + 1; *ap; ap++) {
12479 i = dash_arith(*ap);
12484 #endif /* CONFIG_ASH_MATH_SUPPORT */
12486 /* $NetBSD: miscbltin.c,v 1.31 2002/11/24 22:35:41 christos Exp $ */
12489 * Miscelaneous builtins.
12495 #if !defined(__GLIBC__) || __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12496 typedef enum __rlimit_resource rlim_t;
12502 * The read builtin. The -e option causes backslashes to escape the
12503 * following character.
12505 * This uses unbuffered input, which may be avoidable in some cases.
12509 readcmd(int argc, char **argv)
12524 while ((i = nextopt("p:r")) != '\0') {
12526 prompt = optionarg;
12530 if (prompt && isatty(0)) {
12533 if (*(ap = argptr) == NULL)
12534 error("arg count");
12535 if ((ifs = bltinlookup("IFS")) == NULL)
12542 if (read(0, &c, 1) != 1) {
12554 if (!rflag && c == '\\') {
12560 if (startword && *ifs == ' ' && strchr(ifs, c)) {
12564 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
12566 setvar(*ap, stackblock(), 0);
12576 /* Remove trailing blanks */
12577 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
12579 setvar(*ap, stackblock(), 0);
12580 while (*++ap != NULL)
12581 setvar(*ap, nullstr, 0);
12586 static int umaskcmd(int argc, char **argv)
12588 static const char permuser[3] = "ugo";
12589 static const char permmode[3] = "rwx";
12590 static const short int permmask[] = {
12591 S_IRUSR, S_IWUSR, S_IXUSR,
12592 S_IRGRP, S_IWGRP, S_IXGRP,
12593 S_IROTH, S_IWOTH, S_IXOTH
12599 int symbolic_mode = 0;
12601 while (nextopt("S") != '\0') {
12610 if ((ap = *argptr) == NULL) {
12611 if (symbolic_mode) {
12615 for (i = 0; i < 3; i++) {
12618 *p++ = permuser[i];
12620 for (j = 0; j < 3; j++) {
12621 if ((mask & permmask[3 * i + j]) == 0) {
12622 *p++ = permmode[j];
12630 out1fmt("%.4o\n", mask);
12633 if (is_digit((unsigned char) *ap)) {
12636 if (*ap >= '8' || *ap < '0')
12637 error(illnum, argv[1]);
12638 mask = (mask << 3) + (*ap - '0');
12639 } while (*++ap != '\0');
12642 mask = ~mask & 0777;
12643 if (!bb_parse_mode(ap, &mask)) {
12644 error("Illegal mode: %s", ap);
12646 umask(~mask & 0777);
12655 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12656 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12657 * ash by J.T. Conklin.
12665 int factor; /* multiply by to get rlim_{cur,max} values */
12669 static const struct limits limits[] = {
12671 { "time(seconds)", RLIMIT_CPU, 1, 't' },
12673 #ifdef RLIMIT_FSIZE
12674 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
12677 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
12679 #ifdef RLIMIT_STACK
12680 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
12683 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
12686 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
12688 #ifdef RLIMIT_MEMLOCK
12689 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
12691 #ifdef RLIMIT_NPROC
12692 { "process(processes)", RLIMIT_NPROC, 1, 'p' },
12694 #ifdef RLIMIT_NOFILE
12695 { "nofiles(descriptors)", RLIMIT_NOFILE, 1, 'n' },
12698 { "vmemory(kbytes)", RLIMIT_VMEM, 1024, 'v' },
12701 { "swap(kbytes)", RLIMIT_SWAP, 1024, 'w' },
12703 { (char *) 0, 0, 0, '\0' }
12707 ulimitcmd(int argc, char **argv)
12711 enum { SOFT = 0x1, HARD = 0x2 }
12713 const struct limits *l;
12716 struct rlimit limit;
12719 while ((optc = nextopt("HSatfdsmcnpl")) != '\0')
12734 for (l = limits; l->name && l->option != what; l++)
12737 error("internal error (%c)", what);
12739 set = *argptr ? 1 : 0;
12743 if (all || argptr[1])
12744 error("too many arguments");
12745 if (strncmp(p, "unlimited\n", 9) == 0)
12746 val = RLIM_INFINITY;
12750 while ((c = *p++) >= '0' && c <= '9')
12752 val = (val * 10) + (long)(c - '0');
12753 if (val < (rlim_t) 0)
12757 error("bad number");
12762 for (l = limits; l->name; l++) {
12763 getrlimit(l->cmd, &limit);
12765 val = limit.rlim_cur;
12766 else if (how & HARD)
12767 val = limit.rlim_max;
12769 out1fmt("%-20s ", l->name);
12770 if (val == RLIM_INFINITY)
12771 out1fmt("unlimited\n");
12775 out1fmt("%lld\n", (long long) val);
12781 getrlimit(l->cmd, &limit);
12784 limit.rlim_max = val;
12786 limit.rlim_cur = val;
12787 if (setrlimit(l->cmd, &limit) < 0)
12788 error("error setting limit (%m)");
12791 val = limit.rlim_cur;
12792 else if (how & HARD)
12793 val = limit.rlim_max;
12795 if (val == RLIM_INFINITY)
12796 out1fmt("unlimited\n");
12800 out1fmt("%lld\n", (long long) val);
12807 #ifdef CONFIG_ASH_MATH_SUPPORT
12809 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12811 Permission is hereby granted, free of charge, to any person obtaining
12812 a copy of this software and associated documentation files (the
12813 "Software"), to deal in the Software without restriction, including
12814 without limitation the rights to use, copy, modify, merge, publish,
12815 distribute, sublicense, and/or sell copies of the Software, and to
12816 permit persons to whom the Software is furnished to do so, subject to
12817 the following conditions:
12819 The above copyright notice and this permission notice shall be
12820 included in all copies or substantial portions of the Software.
12822 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12823 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12824 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12825 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12826 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12827 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12828 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12831 /* This is my infix parser/evaluator. It is optimized for size, intended
12832 * as a replacement for yacc-based parsers. However, it may well be faster
12833 * than a comparable parser writen in yacc. The supported operators are
12834 * listed in #defines below. Parens, order of operations, and error handling
12835 * are supported. This code is threadsafe. The exact expression format should
12836 * be that which POSIX specifies for shells. */
12838 /* The code uses a simple two-stack algorithm. See
12839 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12840 * for a detailed explaination of the infix-to-postfix algorithm on which
12841 * this is based (this code differs in that it applies operators immediately
12842 * to the stack instead of adding them to a queue to end up with an
12845 /* To use the routine, call it with an expression string and error return
12849 * Aug 24, 2001 Manuel Novoa III
12851 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12853 * 1) In arith_apply():
12854 * a) Cached values of *numptr and &(numptr[-1]).
12855 * b) Removed redundant test for zero denominator.
12858 * a) Eliminated redundant code for processing operator tokens by moving
12859 * to a table-based implementation. Also folded handling of parens
12861 * b) Combined all 3 loops which called arith_apply to reduce generated
12862 * code size at the cost of speed.
12864 * 3) The following expressions were treated as valid by the original code:
12865 * 1() , 0! , 1 ( *3 ) .
12866 * These bugs have been fixed by internally enclosing the expression in
12867 * parens and then checking that all binary ops and right parens are
12868 * preceded by a valid expression (NUM_TOKEN).
12870 * Note: It may be desireable to replace Aaron's test for whitespace with
12871 * ctype's isspace() if it is used by another busybox applet or if additional
12872 * whitespace chars should be considered. Look below the "#include"s for a
12873 * precompiler test.
12877 * Aug 26, 2001 Manuel Novoa III
12879 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12881 * Merge in Aaron's comments previously posted to the busybox list,
12882 * modified slightly to take account of my changes to the code.
12887 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12889 * - allow access to variable,
12890 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12891 * - realize assign syntax (VAR=expr, +=, *= etc)
12892 * - realize exponentiation (** operator)
12893 * - realize comma separated - expr, expr
12894 * - realise ++expr --expr expr++ expr--
12895 * - realise expr ? expr : expr (but, second expr calculate always)
12896 * - allow hexdecimal and octal numbers
12897 * - was restored loses XOR operator
12898 * - remove one goto label, added three ;-)
12899 * - protect $((num num)) as true zero expr (Manuel`s error)
12900 * - always use special isspace(), see comment from bash ;-)
12904 #define arith_isspace(arithval) \
12905 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12908 typedef unsigned char operator;
12910 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12911 * precedence, and 3 high bits are an ID unique accross operators of that
12912 * precedence. The ID portion is so that multiple operators can have the
12913 * same precedence, ensuring that the leftmost one is evaluated first.
12914 * Consider * and /. */
12916 #define tok_decl(prec,id) (((id)<<5)|(prec))
12917 #define PREC(op) ((op) & 0x1F)
12919 #define TOK_LPAREN tok_decl(0,0)
12921 #define TOK_COMMA tok_decl(1,0)
12923 #define TOK_ASSIGN tok_decl(2,0)
12924 #define TOK_AND_ASSIGN tok_decl(2,1)
12925 #define TOK_OR_ASSIGN tok_decl(2,2)
12926 #define TOK_XOR_ASSIGN tok_decl(2,3)
12927 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12928 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12929 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12930 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12932 #define TOK_MUL_ASSIGN tok_decl(3,0)
12933 #define TOK_DIV_ASSIGN tok_decl(3,1)
12934 #define TOK_REM_ASSIGN tok_decl(3,2)
12936 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12937 #define convert_prec_is_assing(prec) do { if(prec == 3) prec = 2; } while(0)
12939 /* conditional is right associativity too */
12940 #define TOK_CONDITIONAL tok_decl(4,0)
12941 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12943 #define TOK_OR tok_decl(5,0)
12945 #define TOK_AND tok_decl(6,0)
12947 #define TOK_BOR tok_decl(7,0)
12949 #define TOK_BXOR tok_decl(8,0)
12951 #define TOK_BAND tok_decl(9,0)
12953 #define TOK_EQ tok_decl(10,0)
12954 #define TOK_NE tok_decl(10,1)
12956 #define TOK_LT tok_decl(11,0)
12957 #define TOK_GT tok_decl(11,1)
12958 #define TOK_GE tok_decl(11,2)
12959 #define TOK_LE tok_decl(11,3)
12961 #define TOK_LSHIFT tok_decl(12,0)
12962 #define TOK_RSHIFT tok_decl(12,1)
12964 #define TOK_ADD tok_decl(13,0)
12965 #define TOK_SUB tok_decl(13,1)
12967 #define TOK_MUL tok_decl(14,0)
12968 #define TOK_DIV tok_decl(14,1)
12969 #define TOK_REM tok_decl(14,2)
12971 /* exponent is right associativity */
12972 #define TOK_EXPONENT tok_decl(15,1)
12974 /* For now unary operators. */
12975 #define UNARYPREC 16
12976 #define TOK_BNOT tok_decl(UNARYPREC,0)
12977 #define TOK_NOT tok_decl(UNARYPREC,1)
12979 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12980 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12982 #define PREC_PRE (UNARYPREC+2)
12984 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
12985 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
12987 #define PREC_POST (UNARYPREC+3)
12989 #define TOK_POST_INC tok_decl(PREC_POST, 0)
12990 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
12992 #define SPEC_PREC (UNARYPREC+4)
12994 #define TOK_NUM tok_decl(SPEC_PREC, 0)
12995 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
12997 #define NUMPTR (*numstackptr)
12999 static inline int tok_have_assign(operator op)
13001 operator prec = PREC(op);
13003 convert_prec_is_assing(prec);
13004 return (prec == PREC(TOK_ASSIGN) ||
13005 prec == PREC_PRE || prec == PREC_POST);
13008 static inline int is_right_associativity(operator prec)
13010 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) ||
13011 prec == PREC(TOK_CONDITIONAL));
13015 typedef struct ARITCH_VAR_NUM {
13017 long contidional_second_val;
13018 char contidional_second_val_initialized;
13019 char *var; /* if NULL then is regular number,
13020 else is varable name */
13024 typedef struct CHK_VAR_RECURSIVE_LOOPED {
13026 struct CHK_VAR_RECURSIVE_LOOPED *next;
13027 } chk_var_recursive_looped_t;
13029 static chk_var_recursive_looped_t *prev_chk_var_recursive;
13032 static int arith_lookup_val(v_n_t *t)
13035 const char * p = lookupvar(t->var);
13040 /* recursive try as expression */
13041 chk_var_recursive_looped_t *cur;
13042 chk_var_recursive_looped_t cur_save;
13044 for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
13045 if(strcmp(cur->var, t->var) == 0) {
13046 /* expression recursion loop detected */
13050 /* save current lookuped var name */
13051 cur = prev_chk_var_recursive;
13052 cur_save.var = t->var;
13053 cur_save.next = cur;
13054 prev_chk_var_recursive = &cur_save;
13056 t->val = arith (p, &errcode);
13057 /* restore previous ptr after recursiving */
13058 prev_chk_var_recursive = cur;
13061 /* allow undefined var as 0 */
13068 /* "applying" a token means performing it on the top elements on the integer
13069 * stack. For a unary operator it will only change the top element, but a
13070 * binary operator will pop two arguments and push a result */
13072 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
13077 int ret_arith_lookup_val;
13079 if (NUMPTR == numstack) goto err; /* There is no operator that can work
13080 without arguments */
13081 numptr_m1 = NUMPTR - 1;
13083 /* check operand is var with noninteger value */
13084 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
13085 if(ret_arith_lookup_val)
13086 return ret_arith_lookup_val;
13088 rez = numptr_m1->val;
13089 if (op == TOK_UMINUS)
13091 else if (op == TOK_NOT)
13093 else if (op == TOK_BNOT)
13095 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
13097 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
13099 else if (op != TOK_UPLUS) {
13100 /* Binary operators */
13102 /* check and binary operators need two arguments */
13103 if (numptr_m1 == numstack) goto err;
13105 /* ... and they pop one */
13108 if (op == TOK_CONDITIONAL) {
13109 if(! numptr_m1->contidional_second_val_initialized) {
13110 /* protect $((expr1 ? expr2)) without ": expr" */
13113 rez = numptr_m1->contidional_second_val;
13114 } else if(numptr_m1->contidional_second_val_initialized) {
13115 /* protect $((expr1 : expr2)) without "expr ? " */
13118 numptr_m1 = NUMPTR - 1;
13119 if(op != TOK_ASSIGN) {
13120 /* check operand is var with noninteger value for not '=' */
13121 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
13122 if(ret_arith_lookup_val)
13123 return ret_arith_lookup_val;
13125 if (op == TOK_CONDITIONAL) {
13126 numptr_m1->contidional_second_val = rez;
13128 rez = numptr_m1->val;
13129 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
13131 else if (op == TOK_OR)
13132 rez = numptr_val || rez;
13133 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
13135 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
13137 else if (op == TOK_AND)
13138 rez = rez && numptr_val;
13139 else if (op == TOK_EQ)
13140 rez = (rez == numptr_val);
13141 else if (op == TOK_NE)
13142 rez = (rez != numptr_val);
13143 else if (op == TOK_GE)
13144 rez = (rez >= numptr_val);
13145 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
13146 rez >>= numptr_val;
13147 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
13148 rez <<= numptr_val;
13149 else if (op == TOK_GT)
13150 rez = (rez > numptr_val);
13151 else if (op == TOK_LT)
13152 rez = (rez < numptr_val);
13153 else if (op == TOK_LE)
13154 rez = (rez <= numptr_val);
13155 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
13157 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
13159 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
13161 else if (op == TOK_ASSIGN || op == TOK_COMMA)
13163 else if (op == TOK_CONDITIONAL_SEP) {
13164 if (numptr_m1 == numstack) {
13165 /* protect $((expr : expr)) without "expr ? " */
13168 numptr_m1->contidional_second_val_initialized = op;
13169 numptr_m1->contidional_second_val = numptr_val;
13171 else if (op == TOK_CONDITIONAL) {
13173 numptr_val : numptr_m1->contidional_second_val;
13175 else if(op == TOK_EXPONENT) {
13177 return -3; /* exponent less than 0 */
13182 while(numptr_val--)
13187 else if(numptr_val==0) /* zero divisor check */
13189 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
13191 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
13194 if(tok_have_assign(op)) {
13197 if(numptr_m1->var == NULL) {
13201 /* save to shell variable */
13202 sprintf(buf, "%ld", rez);
13203 setvar(numptr_m1->var, buf, 0);
13204 /* after saving, make previous value for v++ or v-- */
13205 if(op == TOK_POST_INC)
13207 else if(op == TOK_POST_DEC)
13210 numptr_m1->val = rez;
13211 /* protect geting var value, is number now */
13212 numptr_m1->var = NULL;
13217 /* longest must first */
13218 static const char op_tokens[] = {
13219 '<','<','=',0, TOK_LSHIFT_ASSIGN,
13220 '>','>','=',0, TOK_RSHIFT_ASSIGN,
13221 '<','<', 0, TOK_LSHIFT,
13222 '>','>', 0, TOK_RSHIFT,
13223 '|','|', 0, TOK_OR,
13224 '&','&', 0, TOK_AND,
13225 '!','=', 0, TOK_NE,
13226 '<','=', 0, TOK_LE,
13227 '>','=', 0, TOK_GE,
13228 '=','=', 0, TOK_EQ,
13229 '|','=', 0, TOK_OR_ASSIGN,
13230 '&','=', 0, TOK_AND_ASSIGN,
13231 '*','=', 0, TOK_MUL_ASSIGN,
13232 '/','=', 0, TOK_DIV_ASSIGN,
13233 '%','=', 0, TOK_REM_ASSIGN,
13234 '+','=', 0, TOK_PLUS_ASSIGN,
13235 '-','=', 0, TOK_MINUS_ASSIGN,
13236 '-','-', 0, TOK_POST_DEC,
13237 '^','=', 0, TOK_XOR_ASSIGN,
13238 '+','+', 0, TOK_POST_INC,
13239 '*','*', 0, TOK_EXPONENT,
13243 '=', 0, TOK_ASSIGN,
13255 '?', 0, TOK_CONDITIONAL,
13256 ':', 0, TOK_CONDITIONAL_SEP,
13257 ')', 0, TOK_RPAREN,
13258 '(', 0, TOK_LPAREN,
13262 #define endexpression &op_tokens[sizeof(op_tokens)-7]
13265 extern long arith (const char *expr, int *perrcode)
13267 register char arithval; /* Current character under analysis */
13268 operator lasttok, op;
13271 const char *p = endexpression;
13274 size_t datasizes = strlen(expr) + 2;
13276 /* Stack of integers */
13277 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
13278 * in any given correct or incorrect expression is left as an excersize to
13280 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
13281 *numstackptr = numstack;
13282 /* Stack of operator tokens */
13283 operator *stack = alloca((datasizes) * sizeof(operator)),
13286 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
13287 *perrcode = errcode = 0;
13290 if ((arithval = *expr) == 0) {
13291 if (p == endexpression) {
13292 /* Null expression. */
13296 /* This is only reached after all tokens have been extracted from the
13297 * input stream. If there are still tokens on the operator stack, they
13298 * are to be applied in order. At the end, there should be a final
13299 * result on the integer stack */
13301 if (expr != endexpression + 1) {
13302 /* If we haven't done so already, */
13303 /* append a closing right paren */
13304 expr = endexpression;
13305 /* and let the loop process it. */
13308 /* At this point, we're done with the expression. */
13309 if (numstackptr != numstack+1) {
13310 /* ... but if there isn't, it's bad */
13312 return (*perrcode = -1);
13314 if(numstack->var) {
13315 /* expression is $((var)) only, lookup now */
13316 errcode = arith_lookup_val(numstack);
13319 *perrcode = errcode;
13320 return numstack->val;
13322 /* Continue processing the expression. */
13323 if (arith_isspace(arithval)) {
13324 /* Skip whitespace */
13327 if((p = endofname(expr)) != expr) {
13328 int var_name_size = (p-expr) + 1; /* trailing zero */
13330 numstackptr->var = alloca(var_name_size);
13331 safe_strncpy(numstackptr->var, expr, var_name_size);
13334 numstackptr->contidional_second_val_initialized = 0;
13338 } else if (is_digit(arithval)) {
13339 numstackptr->var = NULL;
13340 numstackptr->val = strtol(expr, (char **) &expr, 0);
13343 for(p = op_tokens; ; p++) {
13347 /* strange operator not found */
13350 for(o = expr; *p && *o == *p; p++)
13357 /* skip tail uncompared token */
13360 /* skip zero delim */
13365 /* post grammar: a++ reduce to num */
13366 if(lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
13369 /* Plus and minus are binary (not unary) _only_ if the last
13370 * token was as number, or a right paren (which pretends to be
13371 * a number, since it evaluates to one). Think about it.
13372 * It makes sense. */
13373 if (lasttok != TOK_NUM) {
13389 /* We don't want a unary operator to cause recursive descent on the
13390 * stack, because there can be many in a row and it could cause an
13391 * operator to be evaluated before its argument is pushed onto the
13392 * integer stack. */
13393 /* But for binary operators, "apply" everything on the operator
13394 * stack until we find an operator with a lesser priority than the
13395 * one we have just extracted. */
13396 /* Left paren is given the lowest priority so it will never be
13397 * "applied" in this way.
13398 * if associativity is right and priority eq, applied also skip
13401 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
13402 /* not left paren or unary */
13403 if (lasttok != TOK_NUM) {
13404 /* binary op must be preceded by a num */
13407 while (stackptr != stack) {
13408 if (op == TOK_RPAREN) {
13409 /* The algorithm employed here is simple: while we don't
13410 * hit an open paren nor the bottom of the stack, pop
13411 * tokens and apply them */
13412 if (stackptr[-1] == TOK_LPAREN) {
13414 /* Any operator directly after a */
13416 /* close paren should consider itself binary */
13420 operator prev_prec = PREC(stackptr[-1]);
13422 convert_prec_is_assing(prec);
13423 convert_prec_is_assing(prev_prec);
13424 if (prev_prec < prec)
13426 /* check right assoc */
13427 if(prev_prec == prec && is_right_associativity(prec))
13430 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
13431 if(errcode) goto ret;
13433 if (op == TOK_RPAREN) {
13438 /* Push this operator to the stack and remember it. */
13439 *stackptr++ = lasttok = op;
13446 #endif /* CONFIG_ASH_MATH_SUPPORT */
13450 const char *bb_applet_name = "debug stuff usage";
13451 int main(int argc, char **argv)
13453 return ash_main(argc, argv);
13458 * Copyright (c) 1989, 1991, 1993, 1994
13459 * The Regents of the University of California. All rights reserved.
13461 * This code is derived from software contributed to Berkeley by
13462 * Kenneth Almquist.
13464 * Redistribution and use in source and binary forms, with or without
13465 * modification, are permitted provided that the following conditions
13467 * 1. Redistributions of source code must retain the above copyright
13468 * notice, this list of conditions and the following disclaimer.
13469 * 2. Redistributions in binary form must reproduce the above copyright
13470 * notice, this list of conditions and the following disclaimer in the
13471 * documentation and/or other materials provided with the distribution.
13473 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
13474 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
13476 * 4. Neither the name of the University nor the names of its contributors
13477 * may be used to endorse or promote products derived from this software
13478 * without specific prior written permission.
13480 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13481 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13482 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13483 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13484 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13485 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13486 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13487 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13488 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13489 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF