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 */
555 struct strpush *prev; /* preceding string on stack */
558 #ifdef CONFIG_ASH_ALIAS
559 struct alias *ap; /* if push was associated with an alias */
561 char *string; /* remember the string since it may change */
565 struct parsefile *prev; /* preceding file on stack */
566 int linno; /* current line */
567 int fd; /* file descriptor (or -1 if string) */
568 int nleft; /* number of chars left in this line */
569 int lleft; /* number of chars left in this buffer */
570 char *nextc; /* next char in buffer */
571 char *buf; /* input buffer */
572 struct strpush *strpush; /* for pushing strings at this level */
573 struct strpush basestrpush; /* so pushing one is fast */
576 static struct parsefile basepf; /* top level input file */
577 static char basebuf[IBUFSIZ]; /* buffer for top level input file */
578 static struct parsefile *parsefile = &basepf; /* current input file */
581 static int tokpushback; /* last token pushed back */
582 #define NEOF ((union node *)&tokpushback)
583 static int parsebackquote; /* nonzero if we are inside backquotes */
584 static int doprompt; /* if set, prompt the user */
585 static int needprompt; /* true if interactive and at start of line */
586 static int lasttoken; /* last token read */
587 static char *wordtext; /* text of last word returned by readtoken */
589 static struct nodelist *backquotelist;
590 static union node *redirnode;
591 static struct heredoc *heredoc;
592 static int quoteflag; /* set if (part of) last token was quoted */
593 static int startlinno; /* line # where last token started */
595 static union node *parsecmd(int);
596 static void fixredir(union node *, const char *, int);
597 static const char *const *findkwd(const char *);
598 static char *endofname(const char *);
600 /* $NetBSD: shell.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
602 typedef void *pointer;
604 static char nullstr[1]; /* zero length string */
605 static const char spcstr[] = " ";
606 static const char snlfmt[] = "%s\n";
607 static const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' };
608 static const char illnum[] = "Illegal number: %s";
609 static const char homestr[] = "HOME";
612 #define TRACE(param) trace param
613 #define TRACEV(param) tracev param
616 #define TRACEV(param)
619 #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
620 #define __builtin_expect(x, expected_value) (x)
623 #define likely(x) __builtin_expect((x),1)
638 #define TENDBQUOTE 12
656 /* first char is indicating which tokens mark the end of a list */
657 static const char *const tokname_array[] = {
672 /* the following are keywords */
691 static const char *tokname(int tok)
697 sprintf(buf + (tok >= TSEMI), "%s%c",
698 tokname_array[tok] + 1, (tok >= TSEMI ? '"' : 0));
702 /* $NetBSD: machdep.h,v 1.10 2002/10/07 14:26:08 christos Exp $ */
705 * Most machines require the value returned from malloc to be aligned
706 * in some way. The following macro will get this right on many machines.
709 #define SHELL_SIZE (sizeof(union {int i; char *cp; double d; }) - 1)
711 * It appears that grabstackstr() will barf with such alignments
712 * because stalloc() will return a string allocated in a new stackblock.
714 #define SHELL_ALIGN(nbytes) (((nbytes) + SHELL_SIZE) & ~SHELL_SIZE)
717 * This file was generated by the mksyntax program.
722 #define CWORD 0 /* character is nothing special */
723 #define CNL 1 /* newline character */
724 #define CBACK 2 /* a backslash character */
725 #define CSQUOTE 3 /* single quote */
726 #define CDQUOTE 4 /* double quote */
727 #define CENDQUOTE 5 /* a terminating quote */
728 #define CBQUOTE 6 /* backwards single quote */
729 #define CVAR 7 /* a dollar sign */
730 #define CENDVAR 8 /* a '}' character */
731 #define CLP 9 /* a left paren in arithmetic */
732 #define CRP 10 /* a right paren in arithmetic */
733 #define CENDFILE 11 /* end of file */
734 #define CCTL 12 /* like CWORD, except it must be escaped */
735 #define CSPCL 13 /* these terminate a word */
736 #define CIGN 14 /* character should be ignored */
738 #ifdef CONFIG_ASH_ALIAS
742 #define PEOA_OR_PEOF PEOA
746 #define PEOA_OR_PEOF PEOF
749 #define is_digit(c) ((unsigned)((c) - '0') <= 9)
750 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
751 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
754 * is_special(c) evaluates to 1 for c in "!#$*-0123456789?@"; 0 otherwise
755 * (assuming ascii char codes, as the original implementation did)
757 #define is_special(c) \
758 ( (((unsigned int)c) - 33 < 32) \
759 && ((0xc1ff920dUL >> (((unsigned int)c) - 33)) & 1))
761 #define digit_val(c) ((c) - '0')
764 * This file was generated by the mksyntax program.
767 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
768 #define USE_SIT_FUNCTION
771 /* number syntax index */
772 #define BASESYNTAX 0 /* not in quotes */
773 #define DQSYNTAX 1 /* in double quotes */
774 #define SQSYNTAX 2 /* in single quotes */
775 #define ARISYNTAX 3 /* in arithmetic */
777 #ifdef CONFIG_ASH_MATH_SUPPORT
778 static const char S_I_T[][4] = {
779 #ifdef CONFIG_ASH_ALIAS
780 {CSPCL, CIGN, CIGN, CIGN}, /* 0, PEOA */
782 {CSPCL, CWORD, CWORD, CWORD}, /* 1, ' ' */
783 {CNL, CNL, CNL, CNL}, /* 2, \n */
784 {CWORD, CCTL, CCTL, CWORD}, /* 3, !*-/:=?[]~ */
785 {CDQUOTE, CENDQUOTE, CWORD, CWORD}, /* 4, '"' */
786 {CVAR, CVAR, CWORD, CVAR}, /* 5, $ */
787 {CSQUOTE, CWORD, CENDQUOTE, CWORD}, /* 6, "'" */
788 {CSPCL, CWORD, CWORD, CLP}, /* 7, ( */
789 {CSPCL, CWORD, CWORD, CRP}, /* 8, ) */
790 {CBACK, CBACK, CCTL, CBACK}, /* 9, \ */
791 {CBQUOTE, CBQUOTE, CWORD, CBQUOTE}, /* 10, ` */
792 {CENDVAR, CENDVAR, CWORD, CENDVAR}, /* 11, } */
793 #ifndef USE_SIT_FUNCTION
794 {CENDFILE, CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
795 {CWORD, CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
796 {CCTL, CCTL, CCTL, CCTL} /* 14, CTLESC ... */
800 static const char S_I_T[][3] = {
801 #ifdef CONFIG_ASH_ALIAS
802 {CSPCL, CIGN, CIGN}, /* 0, PEOA */
804 {CSPCL, CWORD, CWORD}, /* 1, ' ' */
805 {CNL, CNL, CNL}, /* 2, \n */
806 {CWORD, CCTL, CCTL}, /* 3, !*-/:=?[]~ */
807 {CDQUOTE, CENDQUOTE, CWORD}, /* 4, '"' */
808 {CVAR, CVAR, CWORD}, /* 5, $ */
809 {CSQUOTE, CWORD, CENDQUOTE}, /* 6, "'" */
810 {CSPCL, CWORD, CWORD}, /* 7, ( */
811 {CSPCL, CWORD, CWORD}, /* 8, ) */
812 {CBACK, CBACK, CCTL}, /* 9, \ */
813 {CBQUOTE, CBQUOTE, CWORD}, /* 10, ` */
814 {CENDVAR, CENDVAR, CWORD}, /* 11, } */
815 #ifndef USE_SIT_FUNCTION
816 {CENDFILE, CENDFILE, CENDFILE}, /* 12, PEOF */
817 {CWORD, CWORD, CWORD}, /* 13, 0-9A-Za-z */
818 {CCTL, CCTL, CCTL} /* 14, CTLESC ... */
821 #endif /* CONFIG_ASH_MATH_SUPPORT */
823 #ifdef USE_SIT_FUNCTION
825 #define U_C(c) ((unsigned char)(c))
827 static int SIT(int c, int syntax)
829 static const char spec_symbls[] = "\t\n !\"$&'()*-/:;<=>?[\\]`|}~";
830 #ifdef CONFIG_ASH_ALIAS
831 static const char syntax_index_table[] = {
832 1, 2, 1, 3, 4, 5, 1, 6, /* "\t\n !\"$&'" */
833 7, 8, 3, 3, 3, 3, 1, 1, /* "()*-/:;<" */
834 3, 1, 3, 3, 9, 3, 10, 1, /* "=>?[\\]`|" */
838 static const char syntax_index_table[] = {
839 0, 1, 0, 2, 3, 4, 0, 5, /* "\t\n !\"$&'" */
840 6, 7, 2, 2, 2, 2, 0, 0, /* "()*-/:;<" */
841 2, 0, 2, 2, 8, 2, 9, 0, /* "=>?[\\]`|" */
848 if (c == PEOF) /* 2^8+2 */
850 #ifdef CONFIG_ASH_ALIAS
851 if (c == PEOA) /* 2^8+1 */
855 if (U_C(c) >= U_C(CTLESC) && U_C(c) <= U_C(CTLQUOTEMARK))
858 s = strchr(spec_symbls, c);
859 if (s == 0 || *s == 0)
861 indx = syntax_index_table[(s - spec_symbls)];
863 return S_I_T[indx][syntax];
866 #else /* USE_SIT_FUNCTION */
868 #define SIT(c, syntax) S_I_T[(int)syntax_index_table[((int)c)+SYNBASE]][syntax]
870 #ifdef CONFIG_ASH_ALIAS
871 #define CSPCL_CIGN_CIGN_CIGN 0
872 #define CSPCL_CWORD_CWORD_CWORD 1
873 #define CNL_CNL_CNL_CNL 2
874 #define CWORD_CCTL_CCTL_CWORD 3
875 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 4
876 #define CVAR_CVAR_CWORD_CVAR 5
877 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 6
878 #define CSPCL_CWORD_CWORD_CLP 7
879 #define CSPCL_CWORD_CWORD_CRP 8
880 #define CBACK_CBACK_CCTL_CBACK 9
881 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 10
882 #define CENDVAR_CENDVAR_CWORD_CENDVAR 11
883 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 12
884 #define CWORD_CWORD_CWORD_CWORD 13
885 #define CCTL_CCTL_CCTL_CCTL 14
887 #define CSPCL_CWORD_CWORD_CWORD 0
888 #define CNL_CNL_CNL_CNL 1
889 #define CWORD_CCTL_CCTL_CWORD 2
890 #define CDQUOTE_CENDQUOTE_CWORD_CWORD 3
891 #define CVAR_CVAR_CWORD_CVAR 4
892 #define CSQUOTE_CWORD_CENDQUOTE_CWORD 5
893 #define CSPCL_CWORD_CWORD_CLP 6
894 #define CSPCL_CWORD_CWORD_CRP 7
895 #define CBACK_CBACK_CCTL_CBACK 8
896 #define CBQUOTE_CBQUOTE_CWORD_CBQUOTE 9
897 #define CENDVAR_CENDVAR_CWORD_CENDVAR 10
898 #define CENDFILE_CENDFILE_CENDFILE_CENDFILE 11
899 #define CWORD_CWORD_CWORD_CWORD 12
900 #define CCTL_CCTL_CCTL_CCTL 13
903 static const char syntax_index_table[258] = {
904 /* BASESYNTAX_DQSYNTAX_SQSYNTAX_ARISYNTAX */
905 /* 0 PEOF */ CENDFILE_CENDFILE_CENDFILE_CENDFILE,
906 #ifdef CONFIG_ASH_ALIAS
907 /* 1 PEOA */ CSPCL_CIGN_CIGN_CIGN,
909 /* 2 -128 0x80 */ CWORD_CWORD_CWORD_CWORD,
910 /* 3 -127 CTLESC */ CCTL_CCTL_CCTL_CCTL,
911 /* 4 -126 CTLVAR */ CCTL_CCTL_CCTL_CCTL,
912 /* 5 -125 CTLENDVAR */ CCTL_CCTL_CCTL_CCTL,
913 /* 6 -124 CTLBACKQ */ CCTL_CCTL_CCTL_CCTL,
914 /* 7 -123 CTLQUOTE */ CCTL_CCTL_CCTL_CCTL,
915 /* 8 -122 CTLARI */ CCTL_CCTL_CCTL_CCTL,
916 /* 9 -121 CTLENDARI */ CCTL_CCTL_CCTL_CCTL,
917 /* 10 -120 CTLQUOTEMARK */ CCTL_CCTL_CCTL_CCTL,
918 /* 11 -119 */ CWORD_CWORD_CWORD_CWORD,
919 /* 12 -118 */ CWORD_CWORD_CWORD_CWORD,
920 /* 13 -117 */ CWORD_CWORD_CWORD_CWORD,
921 /* 14 -116 */ CWORD_CWORD_CWORD_CWORD,
922 /* 15 -115 */ CWORD_CWORD_CWORD_CWORD,
923 /* 16 -114 */ CWORD_CWORD_CWORD_CWORD,
924 /* 17 -113 */ CWORD_CWORD_CWORD_CWORD,
925 /* 18 -112 */ CWORD_CWORD_CWORD_CWORD,
926 /* 19 -111 */ CWORD_CWORD_CWORD_CWORD,
927 /* 20 -110 */ CWORD_CWORD_CWORD_CWORD,
928 /* 21 -109 */ CWORD_CWORD_CWORD_CWORD,
929 /* 22 -108 */ CWORD_CWORD_CWORD_CWORD,
930 /* 23 -107 */ CWORD_CWORD_CWORD_CWORD,
931 /* 24 -106 */ CWORD_CWORD_CWORD_CWORD,
932 /* 25 -105 */ CWORD_CWORD_CWORD_CWORD,
933 /* 26 -104 */ CWORD_CWORD_CWORD_CWORD,
934 /* 27 -103 */ CWORD_CWORD_CWORD_CWORD,
935 /* 28 -102 */ CWORD_CWORD_CWORD_CWORD,
936 /* 29 -101 */ CWORD_CWORD_CWORD_CWORD,
937 /* 30 -100 */ CWORD_CWORD_CWORD_CWORD,
938 /* 31 -99 */ CWORD_CWORD_CWORD_CWORD,
939 /* 32 -98 */ CWORD_CWORD_CWORD_CWORD,
940 /* 33 -97 */ CWORD_CWORD_CWORD_CWORD,
941 /* 34 -96 */ CWORD_CWORD_CWORD_CWORD,
942 /* 35 -95 */ CWORD_CWORD_CWORD_CWORD,
943 /* 36 -94 */ CWORD_CWORD_CWORD_CWORD,
944 /* 37 -93 */ CWORD_CWORD_CWORD_CWORD,
945 /* 38 -92 */ CWORD_CWORD_CWORD_CWORD,
946 /* 39 -91 */ CWORD_CWORD_CWORD_CWORD,
947 /* 40 -90 */ CWORD_CWORD_CWORD_CWORD,
948 /* 41 -89 */ CWORD_CWORD_CWORD_CWORD,
949 /* 42 -88 */ CWORD_CWORD_CWORD_CWORD,
950 /* 43 -87 */ CWORD_CWORD_CWORD_CWORD,
951 /* 44 -86 */ CWORD_CWORD_CWORD_CWORD,
952 /* 45 -85 */ CWORD_CWORD_CWORD_CWORD,
953 /* 46 -84 */ CWORD_CWORD_CWORD_CWORD,
954 /* 47 -83 */ CWORD_CWORD_CWORD_CWORD,
955 /* 48 -82 */ CWORD_CWORD_CWORD_CWORD,
956 /* 49 -81 */ CWORD_CWORD_CWORD_CWORD,
957 /* 50 -80 */ CWORD_CWORD_CWORD_CWORD,
958 /* 51 -79 */ CWORD_CWORD_CWORD_CWORD,
959 /* 52 -78 */ CWORD_CWORD_CWORD_CWORD,
960 /* 53 -77 */ CWORD_CWORD_CWORD_CWORD,
961 /* 54 -76 */ CWORD_CWORD_CWORD_CWORD,
962 /* 55 -75 */ CWORD_CWORD_CWORD_CWORD,
963 /* 56 -74 */ CWORD_CWORD_CWORD_CWORD,
964 /* 57 -73 */ CWORD_CWORD_CWORD_CWORD,
965 /* 58 -72 */ CWORD_CWORD_CWORD_CWORD,
966 /* 59 -71 */ CWORD_CWORD_CWORD_CWORD,
967 /* 60 -70 */ CWORD_CWORD_CWORD_CWORD,
968 /* 61 -69 */ CWORD_CWORD_CWORD_CWORD,
969 /* 62 -68 */ CWORD_CWORD_CWORD_CWORD,
970 /* 63 -67 */ CWORD_CWORD_CWORD_CWORD,
971 /* 64 -66 */ CWORD_CWORD_CWORD_CWORD,
972 /* 65 -65 */ CWORD_CWORD_CWORD_CWORD,
973 /* 66 -64 */ CWORD_CWORD_CWORD_CWORD,
974 /* 67 -63 */ CWORD_CWORD_CWORD_CWORD,
975 /* 68 -62 */ CWORD_CWORD_CWORD_CWORD,
976 /* 69 -61 */ CWORD_CWORD_CWORD_CWORD,
977 /* 70 -60 */ CWORD_CWORD_CWORD_CWORD,
978 /* 71 -59 */ CWORD_CWORD_CWORD_CWORD,
979 /* 72 -58 */ CWORD_CWORD_CWORD_CWORD,
980 /* 73 -57 */ CWORD_CWORD_CWORD_CWORD,
981 /* 74 -56 */ CWORD_CWORD_CWORD_CWORD,
982 /* 75 -55 */ CWORD_CWORD_CWORD_CWORD,
983 /* 76 -54 */ CWORD_CWORD_CWORD_CWORD,
984 /* 77 -53 */ CWORD_CWORD_CWORD_CWORD,
985 /* 78 -52 */ CWORD_CWORD_CWORD_CWORD,
986 /* 79 -51 */ CWORD_CWORD_CWORD_CWORD,
987 /* 80 -50 */ CWORD_CWORD_CWORD_CWORD,
988 /* 81 -49 */ CWORD_CWORD_CWORD_CWORD,
989 /* 82 -48 */ CWORD_CWORD_CWORD_CWORD,
990 /* 83 -47 */ CWORD_CWORD_CWORD_CWORD,
991 /* 84 -46 */ CWORD_CWORD_CWORD_CWORD,
992 /* 85 -45 */ CWORD_CWORD_CWORD_CWORD,
993 /* 86 -44 */ CWORD_CWORD_CWORD_CWORD,
994 /* 87 -43 */ CWORD_CWORD_CWORD_CWORD,
995 /* 88 -42 */ CWORD_CWORD_CWORD_CWORD,
996 /* 89 -41 */ CWORD_CWORD_CWORD_CWORD,
997 /* 90 -40 */ CWORD_CWORD_CWORD_CWORD,
998 /* 91 -39 */ CWORD_CWORD_CWORD_CWORD,
999 /* 92 -38 */ CWORD_CWORD_CWORD_CWORD,
1000 /* 93 -37 */ CWORD_CWORD_CWORD_CWORD,
1001 /* 94 -36 */ CWORD_CWORD_CWORD_CWORD,
1002 /* 95 -35 */ CWORD_CWORD_CWORD_CWORD,
1003 /* 96 -34 */ CWORD_CWORD_CWORD_CWORD,
1004 /* 97 -33 */ CWORD_CWORD_CWORD_CWORD,
1005 /* 98 -32 */ CWORD_CWORD_CWORD_CWORD,
1006 /* 99 -31 */ CWORD_CWORD_CWORD_CWORD,
1007 /* 100 -30 */ CWORD_CWORD_CWORD_CWORD,
1008 /* 101 -29 */ CWORD_CWORD_CWORD_CWORD,
1009 /* 102 -28 */ CWORD_CWORD_CWORD_CWORD,
1010 /* 103 -27 */ CWORD_CWORD_CWORD_CWORD,
1011 /* 104 -26 */ CWORD_CWORD_CWORD_CWORD,
1012 /* 105 -25 */ CWORD_CWORD_CWORD_CWORD,
1013 /* 106 -24 */ CWORD_CWORD_CWORD_CWORD,
1014 /* 107 -23 */ CWORD_CWORD_CWORD_CWORD,
1015 /* 108 -22 */ CWORD_CWORD_CWORD_CWORD,
1016 /* 109 -21 */ CWORD_CWORD_CWORD_CWORD,
1017 /* 110 -20 */ CWORD_CWORD_CWORD_CWORD,
1018 /* 111 -19 */ CWORD_CWORD_CWORD_CWORD,
1019 /* 112 -18 */ CWORD_CWORD_CWORD_CWORD,
1020 /* 113 -17 */ CWORD_CWORD_CWORD_CWORD,
1021 /* 114 -16 */ CWORD_CWORD_CWORD_CWORD,
1022 /* 115 -15 */ CWORD_CWORD_CWORD_CWORD,
1023 /* 116 -14 */ CWORD_CWORD_CWORD_CWORD,
1024 /* 117 -13 */ CWORD_CWORD_CWORD_CWORD,
1025 /* 118 -12 */ CWORD_CWORD_CWORD_CWORD,
1026 /* 119 -11 */ CWORD_CWORD_CWORD_CWORD,
1027 /* 120 -10 */ CWORD_CWORD_CWORD_CWORD,
1028 /* 121 -9 */ CWORD_CWORD_CWORD_CWORD,
1029 /* 122 -8 */ CWORD_CWORD_CWORD_CWORD,
1030 /* 123 -7 */ CWORD_CWORD_CWORD_CWORD,
1031 /* 124 -6 */ CWORD_CWORD_CWORD_CWORD,
1032 /* 125 -5 */ CWORD_CWORD_CWORD_CWORD,
1033 /* 126 -4 */ CWORD_CWORD_CWORD_CWORD,
1034 /* 127 -3 */ CWORD_CWORD_CWORD_CWORD,
1035 /* 128 -2 */ CWORD_CWORD_CWORD_CWORD,
1036 /* 129 -1 */ CWORD_CWORD_CWORD_CWORD,
1037 /* 130 0 */ CWORD_CWORD_CWORD_CWORD,
1038 /* 131 1 */ CWORD_CWORD_CWORD_CWORD,
1039 /* 132 2 */ CWORD_CWORD_CWORD_CWORD,
1040 /* 133 3 */ CWORD_CWORD_CWORD_CWORD,
1041 /* 134 4 */ CWORD_CWORD_CWORD_CWORD,
1042 /* 135 5 */ CWORD_CWORD_CWORD_CWORD,
1043 /* 136 6 */ CWORD_CWORD_CWORD_CWORD,
1044 /* 137 7 */ CWORD_CWORD_CWORD_CWORD,
1045 /* 138 8 */ CWORD_CWORD_CWORD_CWORD,
1046 /* 139 9 "\t" */ CSPCL_CWORD_CWORD_CWORD,
1047 /* 140 10 "\n" */ CNL_CNL_CNL_CNL,
1048 /* 141 11 */ CWORD_CWORD_CWORD_CWORD,
1049 /* 142 12 */ CWORD_CWORD_CWORD_CWORD,
1050 /* 143 13 */ CWORD_CWORD_CWORD_CWORD,
1051 /* 144 14 */ CWORD_CWORD_CWORD_CWORD,
1052 /* 145 15 */ CWORD_CWORD_CWORD_CWORD,
1053 /* 146 16 */ CWORD_CWORD_CWORD_CWORD,
1054 /* 147 17 */ CWORD_CWORD_CWORD_CWORD,
1055 /* 148 18 */ CWORD_CWORD_CWORD_CWORD,
1056 /* 149 19 */ CWORD_CWORD_CWORD_CWORD,
1057 /* 150 20 */ CWORD_CWORD_CWORD_CWORD,
1058 /* 151 21 */ CWORD_CWORD_CWORD_CWORD,
1059 /* 152 22 */ CWORD_CWORD_CWORD_CWORD,
1060 /* 153 23 */ CWORD_CWORD_CWORD_CWORD,
1061 /* 154 24 */ CWORD_CWORD_CWORD_CWORD,
1062 /* 155 25 */ CWORD_CWORD_CWORD_CWORD,
1063 /* 156 26 */ CWORD_CWORD_CWORD_CWORD,
1064 /* 157 27 */ CWORD_CWORD_CWORD_CWORD,
1065 /* 158 28 */ CWORD_CWORD_CWORD_CWORD,
1066 /* 159 29 */ CWORD_CWORD_CWORD_CWORD,
1067 /* 160 30 */ CWORD_CWORD_CWORD_CWORD,
1068 /* 161 31 */ CWORD_CWORD_CWORD_CWORD,
1069 /* 162 32 " " */ CSPCL_CWORD_CWORD_CWORD,
1070 /* 163 33 "!" */ CWORD_CCTL_CCTL_CWORD,
1071 /* 164 34 """ */ CDQUOTE_CENDQUOTE_CWORD_CWORD,
1072 /* 165 35 "#" */ CWORD_CWORD_CWORD_CWORD,
1073 /* 166 36 "$" */ CVAR_CVAR_CWORD_CVAR,
1074 /* 167 37 "%" */ CWORD_CWORD_CWORD_CWORD,
1075 /* 168 38 "&" */ CSPCL_CWORD_CWORD_CWORD,
1076 /* 169 39 "'" */ CSQUOTE_CWORD_CENDQUOTE_CWORD,
1077 /* 170 40 "(" */ CSPCL_CWORD_CWORD_CLP,
1078 /* 171 41 ")" */ CSPCL_CWORD_CWORD_CRP,
1079 /* 172 42 "*" */ CWORD_CCTL_CCTL_CWORD,
1080 /* 173 43 "+" */ CWORD_CWORD_CWORD_CWORD,
1081 /* 174 44 "," */ CWORD_CWORD_CWORD_CWORD,
1082 /* 175 45 "-" */ CWORD_CCTL_CCTL_CWORD,
1083 /* 176 46 "." */ CWORD_CWORD_CWORD_CWORD,
1084 /* 177 47 "/" */ CWORD_CCTL_CCTL_CWORD,
1085 /* 178 48 "0" */ CWORD_CWORD_CWORD_CWORD,
1086 /* 179 49 "1" */ CWORD_CWORD_CWORD_CWORD,
1087 /* 180 50 "2" */ CWORD_CWORD_CWORD_CWORD,
1088 /* 181 51 "3" */ CWORD_CWORD_CWORD_CWORD,
1089 /* 182 52 "4" */ CWORD_CWORD_CWORD_CWORD,
1090 /* 183 53 "5" */ CWORD_CWORD_CWORD_CWORD,
1091 /* 184 54 "6" */ CWORD_CWORD_CWORD_CWORD,
1092 /* 185 55 "7" */ CWORD_CWORD_CWORD_CWORD,
1093 /* 186 56 "8" */ CWORD_CWORD_CWORD_CWORD,
1094 /* 187 57 "9" */ CWORD_CWORD_CWORD_CWORD,
1095 /* 188 58 ":" */ CWORD_CCTL_CCTL_CWORD,
1096 /* 189 59 ";" */ CSPCL_CWORD_CWORD_CWORD,
1097 /* 190 60 "<" */ CSPCL_CWORD_CWORD_CWORD,
1098 /* 191 61 "=" */ CWORD_CCTL_CCTL_CWORD,
1099 /* 192 62 ">" */ CSPCL_CWORD_CWORD_CWORD,
1100 /* 193 63 "?" */ CWORD_CCTL_CCTL_CWORD,
1101 /* 194 64 "@" */ CWORD_CWORD_CWORD_CWORD,
1102 /* 195 65 "A" */ CWORD_CWORD_CWORD_CWORD,
1103 /* 196 66 "B" */ CWORD_CWORD_CWORD_CWORD,
1104 /* 197 67 "C" */ CWORD_CWORD_CWORD_CWORD,
1105 /* 198 68 "D" */ CWORD_CWORD_CWORD_CWORD,
1106 /* 199 69 "E" */ CWORD_CWORD_CWORD_CWORD,
1107 /* 200 70 "F" */ CWORD_CWORD_CWORD_CWORD,
1108 /* 201 71 "G" */ CWORD_CWORD_CWORD_CWORD,
1109 /* 202 72 "H" */ CWORD_CWORD_CWORD_CWORD,
1110 /* 203 73 "I" */ CWORD_CWORD_CWORD_CWORD,
1111 /* 204 74 "J" */ CWORD_CWORD_CWORD_CWORD,
1112 /* 205 75 "K" */ CWORD_CWORD_CWORD_CWORD,
1113 /* 206 76 "L" */ CWORD_CWORD_CWORD_CWORD,
1114 /* 207 77 "M" */ CWORD_CWORD_CWORD_CWORD,
1115 /* 208 78 "N" */ CWORD_CWORD_CWORD_CWORD,
1116 /* 209 79 "O" */ CWORD_CWORD_CWORD_CWORD,
1117 /* 210 80 "P" */ CWORD_CWORD_CWORD_CWORD,
1118 /* 211 81 "Q" */ CWORD_CWORD_CWORD_CWORD,
1119 /* 212 82 "R" */ CWORD_CWORD_CWORD_CWORD,
1120 /* 213 83 "S" */ CWORD_CWORD_CWORD_CWORD,
1121 /* 214 84 "T" */ CWORD_CWORD_CWORD_CWORD,
1122 /* 215 85 "U" */ CWORD_CWORD_CWORD_CWORD,
1123 /* 216 86 "V" */ CWORD_CWORD_CWORD_CWORD,
1124 /* 217 87 "W" */ CWORD_CWORD_CWORD_CWORD,
1125 /* 218 88 "X" */ CWORD_CWORD_CWORD_CWORD,
1126 /* 219 89 "Y" */ CWORD_CWORD_CWORD_CWORD,
1127 /* 220 90 "Z" */ CWORD_CWORD_CWORD_CWORD,
1128 /* 221 91 "[" */ CWORD_CCTL_CCTL_CWORD,
1129 /* 222 92 "\" */ CBACK_CBACK_CCTL_CBACK,
1130 /* 223 93 "]" */ CWORD_CCTL_CCTL_CWORD,
1131 /* 224 94 "^" */ CWORD_CWORD_CWORD_CWORD,
1132 /* 225 95 "_" */ CWORD_CWORD_CWORD_CWORD,
1133 /* 226 96 "`" */ CBQUOTE_CBQUOTE_CWORD_CBQUOTE,
1134 /* 227 97 "a" */ CWORD_CWORD_CWORD_CWORD,
1135 /* 228 98 "b" */ CWORD_CWORD_CWORD_CWORD,
1136 /* 229 99 "c" */ CWORD_CWORD_CWORD_CWORD,
1137 /* 230 100 "d" */ CWORD_CWORD_CWORD_CWORD,
1138 /* 231 101 "e" */ CWORD_CWORD_CWORD_CWORD,
1139 /* 232 102 "f" */ CWORD_CWORD_CWORD_CWORD,
1140 /* 233 103 "g" */ CWORD_CWORD_CWORD_CWORD,
1141 /* 234 104 "h" */ CWORD_CWORD_CWORD_CWORD,
1142 /* 235 105 "i" */ CWORD_CWORD_CWORD_CWORD,
1143 /* 236 106 "j" */ CWORD_CWORD_CWORD_CWORD,
1144 /* 237 107 "k" */ CWORD_CWORD_CWORD_CWORD,
1145 /* 238 108 "l" */ CWORD_CWORD_CWORD_CWORD,
1146 /* 239 109 "m" */ CWORD_CWORD_CWORD_CWORD,
1147 /* 240 110 "n" */ CWORD_CWORD_CWORD_CWORD,
1148 /* 241 111 "o" */ CWORD_CWORD_CWORD_CWORD,
1149 /* 242 112 "p" */ CWORD_CWORD_CWORD_CWORD,
1150 /* 243 113 "q" */ CWORD_CWORD_CWORD_CWORD,
1151 /* 244 114 "r" */ CWORD_CWORD_CWORD_CWORD,
1152 /* 245 115 "s" */ CWORD_CWORD_CWORD_CWORD,
1153 /* 246 116 "t" */ CWORD_CWORD_CWORD_CWORD,
1154 /* 247 117 "u" */ CWORD_CWORD_CWORD_CWORD,
1155 /* 248 118 "v" */ CWORD_CWORD_CWORD_CWORD,
1156 /* 249 119 "w" */ CWORD_CWORD_CWORD_CWORD,
1157 /* 250 120 "x" */ CWORD_CWORD_CWORD_CWORD,
1158 /* 251 121 "y" */ CWORD_CWORD_CWORD_CWORD,
1159 /* 252 122 "z" */ CWORD_CWORD_CWORD_CWORD,
1160 /* 253 123 "{" */ CWORD_CWORD_CWORD_CWORD,
1161 /* 254 124 "|" */ CSPCL_CWORD_CWORD_CWORD,
1162 /* 255 125 "}" */ CENDVAR_CENDVAR_CWORD_CENDVAR,
1163 /* 256 126 "~" */ CWORD_CCTL_CCTL_CWORD,
1164 /* 257 127 */ CWORD_CWORD_CWORD_CWORD,
1167 #endif /* USE_SIT_FUNCTION */
1169 /* $NetBSD: alias.c,v 1.11 2002/11/24 22:35:38 christos Exp $ */
1174 static int funcblocksize; /* size of structures in function */
1175 static int funcstringsize; /* size of strings in node */
1176 static pointer funcblock; /* block to allocate function from */
1177 static char *funcstring; /* block to allocate strings from */
1179 static const short nodesize[26] = {
1180 SHELL_ALIGN(sizeof (struct ncmd)),
1181 SHELL_ALIGN(sizeof (struct npipe)),
1182 SHELL_ALIGN(sizeof (struct nredir)),
1183 SHELL_ALIGN(sizeof (struct nredir)),
1184 SHELL_ALIGN(sizeof (struct nredir)),
1185 SHELL_ALIGN(sizeof (struct nbinary)),
1186 SHELL_ALIGN(sizeof (struct nbinary)),
1187 SHELL_ALIGN(sizeof (struct nbinary)),
1188 SHELL_ALIGN(sizeof (struct nif)),
1189 SHELL_ALIGN(sizeof (struct nbinary)),
1190 SHELL_ALIGN(sizeof (struct nbinary)),
1191 SHELL_ALIGN(sizeof (struct nfor)),
1192 SHELL_ALIGN(sizeof (struct ncase)),
1193 SHELL_ALIGN(sizeof (struct nclist)),
1194 SHELL_ALIGN(sizeof (struct narg)),
1195 SHELL_ALIGN(sizeof (struct narg)),
1196 SHELL_ALIGN(sizeof (struct nfile)),
1197 SHELL_ALIGN(sizeof (struct nfile)),
1198 SHELL_ALIGN(sizeof (struct nfile)),
1199 SHELL_ALIGN(sizeof (struct nfile)),
1200 SHELL_ALIGN(sizeof (struct nfile)),
1201 SHELL_ALIGN(sizeof (struct ndup)),
1202 SHELL_ALIGN(sizeof (struct ndup)),
1203 SHELL_ALIGN(sizeof (struct nhere)),
1204 SHELL_ALIGN(sizeof (struct nhere)),
1205 SHELL_ALIGN(sizeof (struct nnot)),
1209 static void calcsize(union node *);
1210 static void sizenodelist(struct nodelist *);
1211 static union node *copynode(union node *);
1212 static struct nodelist *copynodelist(struct nodelist *);
1213 static char *nodesavestr(char *);
1217 static void evalstring(char *);
1218 union node; /* BLETCH for ansi C */
1219 static void evaltree(union node *, int);
1220 static void evalbackcmd(union node *, struct backcmd *);
1222 /* in_function returns nonzero if we are currently evaluating a function */
1223 #define in_function() funcnest
1224 static int evalskip; /* set if we are skipping commands */
1225 static int skipcount; /* number of levels to skip */
1226 static int funcnest; /* depth of function calls */
1228 /* reasons for skipping commands (see comment on breakcmd routine) */
1235 * This file was generated by the mkbuiltins program.
1239 static int bgcmd(int, char **);
1241 static int breakcmd(int, char **);
1242 static int cdcmd(int, char **);
1243 #ifdef CONFIG_ASH_CMDCMD
1244 static int commandcmd(int, char **);
1246 static int dotcmd(int, char **);
1247 static int evalcmd(int, char **);
1248 static int execcmd(int, char **);
1249 static int exitcmd(int, char **);
1250 static int exportcmd(int, char **);
1251 static int falsecmd(int, char **);
1253 static int fgcmd(int, char **);
1255 #ifdef CONFIG_ASH_GETOPTS
1256 static int getoptscmd(int, char **);
1258 static int hashcmd(int, char **);
1259 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
1260 static int helpcmd(int argc, char **argv);
1263 static int jobscmd(int, char **);
1265 #ifdef CONFIG_ASH_MATH_SUPPORT
1266 static int letcmd(int, char **);
1268 static int localcmd(int, char **);
1269 static int pwdcmd(int, char **);
1270 static int readcmd(int, char **);
1271 static int returncmd(int, char **);
1272 static int setcmd(int, char **);
1273 static int shiftcmd(int, char **);
1274 static int timescmd(int, char **);
1275 static int trapcmd(int, char **);
1276 static int truecmd(int, char **);
1277 static int typecmd(int, char **);
1278 static int umaskcmd(int, char **);
1279 static int unsetcmd(int, char **);
1280 static int waitcmd(int, char **);
1281 static int ulimitcmd(int, char **);
1283 static int killcmd(int, char **);
1286 /* $NetBSD: mail.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
1288 #ifdef CONFIG_ASH_MAIL
1289 static void chkmail(void);
1290 static void changemail(const char *);
1293 /* $NetBSD: exec.h,v 1.20 2003/01/22 20:36:04 dsl Exp $ */
1295 /* values of cmdtype */
1296 #define CMDUNKNOWN -1 /* no entry in table for command */
1297 #define CMDNORMAL 0 /* command is an executable program */
1298 #define CMDFUNCTION 1 /* command is a shell function */
1299 #define CMDBUILTIN 2 /* command is a shell builtin */
1303 int (*builtin)(int, char **);
1304 /* unsigned flags; */
1307 #ifdef CONFIG_ASH_CMDCMD
1309 # ifdef CONFIG_ASH_ALIAS
1310 # define COMMANDCMD (builtincmd + 7)
1311 # define EXECCMD (builtincmd + 10)
1313 # define COMMANDCMD (builtincmd + 6)
1314 # define EXECCMD (builtincmd + 9)
1317 # ifdef CONFIG_ASH_ALIAS
1318 # define COMMANDCMD (builtincmd + 6)
1319 # define EXECCMD (builtincmd + 9)
1321 # define COMMANDCMD (builtincmd + 5)
1322 # define EXECCMD (builtincmd + 8)
1325 #else /* ! CONFIG_ASH_CMDCMD */
1327 # ifdef CONFIG_ASH_ALIAS
1328 # define EXECCMD (builtincmd + 9)
1330 # define EXECCMD (builtincmd + 8)
1333 # ifdef CONFIG_ASH_ALIAS
1334 # define EXECCMD (builtincmd + 8)
1336 # define EXECCMD (builtincmd + 7)
1339 #endif /* CONFIG_ASH_CMDCMD */
1341 #define BUILTIN_NOSPEC "0"
1342 #define BUILTIN_SPECIAL "1"
1343 #define BUILTIN_REGULAR "2"
1344 #define BUILTIN_SPEC_REG "3"
1345 #define BUILTIN_ASSIGN "4"
1346 #define BUILTIN_SPEC_ASSG "5"
1347 #define BUILTIN_REG_ASSG "6"
1348 #define BUILTIN_SPEC_REG_ASSG "7"
1350 #define IS_BUILTIN_SPECIAL(builtincmd) ((builtincmd)->name[0] & 1)
1351 #define IS_BUILTIN_REGULAR(builtincmd) ((builtincmd)->name[0] & 2)
1353 static const struct builtincmd builtincmd[] = {
1354 { BUILTIN_SPEC_REG ".", dotcmd },
1355 { BUILTIN_SPEC_REG ":", truecmd },
1356 #ifdef CONFIG_ASH_ALIAS
1357 { BUILTIN_REG_ASSG "alias", aliascmd },
1360 { BUILTIN_REGULAR "bg", bgcmd },
1362 { BUILTIN_SPEC_REG "break", breakcmd },
1363 { BUILTIN_REGULAR "cd", cdcmd },
1364 { BUILTIN_NOSPEC "chdir", cdcmd },
1365 #ifdef CONFIG_ASH_CMDCMD
1366 { BUILTIN_REGULAR "command", commandcmd },
1368 { BUILTIN_SPEC_REG "continue", breakcmd },
1369 { BUILTIN_SPEC_REG "eval", evalcmd },
1370 { BUILTIN_SPEC_REG "exec", execcmd },
1371 { BUILTIN_SPEC_REG "exit", exitcmd },
1372 { BUILTIN_SPEC_REG_ASSG "export", exportcmd },
1373 { BUILTIN_REGULAR "false", falsecmd },
1375 { BUILTIN_REGULAR "fg", fgcmd },
1377 #ifdef CONFIG_ASH_GETOPTS
1378 { BUILTIN_REGULAR "getopts", getoptscmd },
1380 { BUILTIN_NOSPEC "hash", hashcmd },
1381 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
1382 { BUILTIN_NOSPEC "help", helpcmd },
1385 { BUILTIN_REGULAR "jobs", jobscmd },
1386 { BUILTIN_REGULAR "kill", killcmd },
1388 #ifdef CONFIG_ASH_MATH_SUPPORT
1389 { BUILTIN_NOSPEC "let", letcmd },
1391 { BUILTIN_ASSIGN "local", localcmd },
1392 { BUILTIN_NOSPEC "pwd", pwdcmd },
1393 { BUILTIN_REGULAR "read", readcmd },
1394 { BUILTIN_SPEC_REG_ASSG "readonly", exportcmd },
1395 { BUILTIN_SPEC_REG "return", returncmd },
1396 { BUILTIN_SPEC_REG "set", setcmd },
1397 { BUILTIN_SPEC_REG "shift", shiftcmd },
1398 { BUILTIN_SPEC_REG "times", timescmd },
1399 { BUILTIN_SPEC_REG "trap", trapcmd },
1400 { BUILTIN_REGULAR "true", truecmd },
1401 { BUILTIN_NOSPEC "type", typecmd },
1402 { BUILTIN_NOSPEC "ulimit", ulimitcmd },
1403 { BUILTIN_REGULAR "umask", umaskcmd },
1404 #ifdef CONFIG_ASH_ALIAS
1405 { BUILTIN_REGULAR "unalias", unaliascmd },
1407 { BUILTIN_SPEC_REG "unset", unsetcmd },
1408 { BUILTIN_REGULAR "wait", waitcmd },
1411 #define NUMBUILTINS (sizeof (builtincmd) / sizeof (struct builtincmd) )
1419 const struct builtincmd *cmd;
1420 struct funcnode *func;
1425 /* action to find_command() */
1426 #define DO_ERR 0x01 /* prints errors */
1427 #define DO_ABS 0x02 /* checks absolute paths */
1428 #define DO_NOFUNC 0x04 /* don't return shell functions, for command */
1429 #define DO_ALTPATH 0x08 /* using alternate path */
1430 #define DO_ALTBLTIN 0x20 /* %builtin in alt. path */
1432 static const char *pathopt; /* set by padvance */
1434 static void shellexec(char **, const char *, int)
1435 __attribute__((__noreturn__));
1436 static char *padvance(const char **, const char *);
1437 static void find_command(char *, struct cmdentry *, int, const char *);
1438 static struct builtincmd *find_builtin(const char *);
1439 static void hashcd(void);
1440 static void changepath(const char *);
1441 static void defun(char *, union node *);
1442 static void unsetfunc(const char *);
1444 #ifdef CONFIG_ASH_MATH_SUPPORT
1445 static int dash_arith(const char *);
1448 /* $NetBSD: init.h,v 1.9 2002/11/24 22:35:40 christos Exp $ */
1450 static void reset(void);
1452 /* $NetBSD: var.h,v 1.21 2003/01/22 20:36:04 dsl Exp $ */
1459 #define VEXPORT 0x01 /* variable is exported */
1460 #define VREADONLY 0x02 /* variable cannot be modified */
1461 #define VSTRFIXED 0x04 /* variable struct is statically allocated */
1462 #define VTEXTFIXED 0x08 /* text is statically allocated */
1463 #define VSTACK 0x10 /* text is allocated on the stack */
1464 #define VUNSET 0x20 /* the variable is not set */
1465 #define VNOFUNC 0x40 /* don't call the callback function */
1466 #define VNOSET 0x80 /* do not set variable - just readonly test */
1467 #define VNOSAVE 0x100 /* when text is on the heap before setvareq */
1471 struct var *next; /* next entry in hash list */
1472 int flags; /* flags are defined above */
1473 const char *text; /* name=value */
1474 void (*func)(const char *);
1475 /* function to be called when */
1476 /* the variable gets set/unset */
1480 struct localvar *next; /* next local variable in list */
1481 struct var *vp; /* the variable that was made local */
1482 int flags; /* saved flags */
1483 const char *text; /* saved text */
1487 static struct localvar *localvars;
1493 #ifdef CONFIG_ASH_GETOPTS
1494 static void getoptsreset(const char *);
1497 #ifdef CONFIG_LOCALE_SUPPORT
1499 static void change_lc_all(const char *value);
1500 static void change_lc_ctype(const char *value);
1505 static const char defpathvar[] = "PATH=/usr/local/bin:/usr/bin:/sbin:/bin";
1507 static const char defifsvar[] = "IFS= \t\n";
1508 #define defifs (defifsvar + 4)
1510 static const char defifs[] = " \t\n";
1514 static struct var varinit[] = {
1516 { 0, VSTRFIXED|VTEXTFIXED, defifsvar, 0 },
1518 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "IFS\0", 0 },
1521 #ifdef CONFIG_ASH_MAIL
1522 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAIL\0", changemail },
1523 { 0, VSTRFIXED|VTEXTFIXED|VUNSET, "MAILPATH\0", changemail },
1526 { 0, VSTRFIXED|VTEXTFIXED, defpathvar, changepath },
1527 { 0, VSTRFIXED|VTEXTFIXED, "PS1=$ ", 0 },
1528 { 0, VSTRFIXED|VTEXTFIXED, "PS2=> ", 0 },
1529 { 0, VSTRFIXED|VTEXTFIXED, "PS4=+ ", 0 },
1530 #ifdef CONFIG_ASH_GETOPTS
1531 { 0, VSTRFIXED|VTEXTFIXED, "OPTIND=1", getoptsreset },
1533 #ifdef CONFIG_LOCALE_SUPPORT
1534 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_ALL=", change_lc_all},
1535 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "LC_CTYPE=", change_lc_ctype},
1537 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
1538 {0, VSTRFIXED | VTEXTFIXED | VUNSET, "HISTFILE=", NULL},
1542 #define vifs varinit[0]
1543 #ifdef CONFIG_ASH_MAIL
1544 #define vmail (&vifs)[1]
1545 #define vmpath (&vmail)[1]
1549 #define vpath (&vmpath)[1]
1550 #define vps1 (&vpath)[1]
1551 #define vps2 (&vps1)[1]
1552 #define vps4 (&vps2)[1]
1553 #define voptind (&vps4)[1]
1555 #define defpath (defpathvar + 5)
1558 * The following macros access the values of the above variables.
1559 * They have to skip over the name. They return the null string
1560 * for unset variables.
1563 #define ifsval() (vifs.text + 4)
1564 #define ifsset() ((vifs.flags & VUNSET) == 0)
1565 #define mailval() (vmail.text + 5)
1566 #define mpathval() (vmpath.text + 9)
1567 #define pathval() (vpath.text + 5)
1568 #define ps1val() (vps1.text + 4)
1569 #define ps2val() (vps2.text + 4)
1570 #define ps4val() (vps4.text + 4)
1571 #define optindval() (voptind.text + 7)
1573 #define mpathset() ((vmpath.flags & VUNSET) == 0)
1575 static void setvar(const char *, const char *, int);
1576 static void setvareq(char *, int);
1577 static void listsetvar(struct strlist *, int);
1578 static char *lookupvar(const char *);
1579 static char *bltinlookup(const char *);
1580 static char **listvars(int, int, char ***);
1581 #define environment() listvars(VEXPORT, VUNSET, 0)
1582 static int showvars(const char *, int, int);
1583 static void poplocalvars(void);
1584 static int unsetvar(const char *);
1585 #ifdef CONFIG_ASH_GETOPTS
1586 static int setvarsafe(const char *, const char *, int);
1588 static int varcmp(const char *, const char *);
1589 static struct var **hashvar(const char *);
1592 static inline int varequal(const char *a, const char *b) {
1593 return !varcmp(a, b);
1597 static int loopnest; /* current loop nesting level */
1600 * The parsefile structure pointed to by the global variable parsefile
1601 * contains information about the current file being read.
1606 struct redirtab *next;
1611 static struct redirtab *redirlist;
1612 static int nullredirs;
1614 extern char **environ;
1616 /* $NetBSD: output.h,v 1.16 2002/11/24 22:35:42 christos Exp $ */
1619 static void outstr(const char *, FILE *);
1620 static void outcslow(int, FILE *);
1621 static void flushall(void);
1622 static void flushout(FILE *);
1623 static int out1fmt(const char *, ...)
1624 __attribute__((__format__(__printf__,1,2)));
1625 static int fmtstr(char *, size_t, const char *, ...)
1626 __attribute__((__format__(__printf__,3,4)));
1627 static void xwrite(int, const void *, size_t);
1629 static int preverrout_fd; /* save fd2 before print debug if xflag is set. */
1632 static void out1str(const char *p)
1637 static void out2str(const char *p)
1644 * Initialization code.
1648 * This routine initializes the builtin variables.
1659 * PS1 depends on uid
1661 #if defined(CONFIG_FEATURE_COMMAND_EDITING) && defined(CONFIG_FEATURE_SH_FANCY_PROMPT)
1662 vps1.text = "PS1=\\w \\$ ";
1665 vps1.text = "PS1=# ";
1668 end = vp + sizeof(varinit) / sizeof(varinit[0]);
1670 vpp = hashvar(vp->text);
1673 } while (++vp < end);
1682 basepf.nextc = basepf.buf = basebuf;
1687 signal(SIGCHLD, SIG_DFL);
1696 for (envp = environ ; *envp ; envp++) {
1697 if (strchr(*envp, '=')) {
1698 setvareq(*envp, VEXPORT|VTEXTFIXED);
1702 snprintf(ppid, sizeof(ppid), "%d", (int) getppid());
1703 setvar("PPID", ppid, 0);
1708 /* PEOF (the end of file marker) */
1711 * The input line number. Input.c just defines this variable, and saves
1712 * and restores it when files are pushed and popped. The user of this
1713 * package must set its value.
1716 static int pgetc(void);
1717 static int pgetc2(void);
1718 static int preadbuffer(void);
1719 static void pungetc(void);
1720 static void pushstring(char *, void *);
1721 static void popstring(void);
1722 static void setinputfile(const char *, int);
1723 static void setinputfd(int, int);
1724 static void setinputstring(char *);
1725 static void popfile(void);
1726 static void popallfiles(void);
1727 static void closescript(void);
1730 /* $NetBSD: jobs.h,v 1.17 2003/01/22 20:36:04 dsl Exp $ */
1733 /* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
1736 #define FORK_NOJOB 2
1738 /* mode flags for showjob(s) */
1739 #define SHOW_PGID 0x01 /* only show pgid - for jobs -p */
1740 #define SHOW_PID 0x04 /* include process pid */
1741 #define SHOW_CHANGED 0x08 /* only jobs whose state has changed */
1745 * A job structure contains information about a job. A job is either a
1746 * single process or a set of processes contained in a pipeline. In the
1747 * latter case, pidlist will be non-NULL, and will point to a -1 terminated
1752 pid_t pid; /* process id */
1753 int status; /* last process status from wait() */
1754 char *cmd; /* text of command being run */
1758 struct procstat ps0; /* status of process */
1759 struct procstat *ps; /* status or processes when more than one */
1761 int stopstatus; /* status of a stopped job */
1764 nprocs: 16, /* number of processes */
1766 #define JOBRUNNING 0 /* at least one proc running */
1767 #define JOBSTOPPED 1 /* all procs are stopped */
1768 #define JOBDONE 2 /* all procs are completed */
1770 sigint: 1, /* job was killed by SIGINT */
1771 jobctl: 1, /* job running under job control */
1773 waited: 1, /* true if this entry has been waited for */
1774 used: 1, /* true if this entry is in used */
1775 changed: 1; /* true if status has changed */
1776 struct job *prev_job; /* previous job */
1779 static pid_t backgndpid; /* pid of last background process */
1780 static int job_warning; /* user was warned about stopped jobs */
1782 static int jobctl; /* true if doing job control */
1785 static struct job *makejob(union node *, int);
1786 static int forkshell(struct job *, union node *, int);
1787 static int waitforjob(struct job *);
1788 static int stoppedjobs(void);
1791 #define setjobctl(on) /* do nothing */
1793 static void setjobctl(int);
1794 static void showjobs(FILE *, int);
1797 /* $NetBSD: main.h,v 1.9 2002/11/24 22:35:41 christos Exp $ */
1800 /* pid of main shell */
1802 /* true if we aren't a child of the main shell */
1803 static int rootshell;
1805 static void readcmdfile(char *);
1806 static void cmdloop(int);
1808 /* $NetBSD: memalloc.h,v 1.13 2003/01/22 20:36:04 dsl Exp $ */
1812 struct stack_block *stackp;
1815 struct stackmark *marknext;
1818 /* minimum size of a block */
1819 #define MINSIZE SHELL_ALIGN(504)
1821 struct stack_block {
1822 struct stack_block *prev;
1823 char space[MINSIZE];
1826 static struct stack_block stackbase;
1827 static struct stack_block *stackp = &stackbase;
1828 static struct stackmark *markp;
1829 static char *stacknxt = stackbase.space;
1830 static size_t stacknleft = MINSIZE;
1831 static char *sstrend = stackbase.space + MINSIZE;
1832 static int herefd = -1;
1835 static pointer ckmalloc(size_t);
1836 static pointer ckrealloc(pointer, size_t);
1837 static char *savestr(const char *);
1838 static pointer stalloc(size_t);
1839 static void stunalloc(pointer);
1840 static void setstackmark(struct stackmark *);
1841 static void popstackmark(struct stackmark *);
1842 static void growstackblock(void);
1843 static void *growstackstr(void);
1844 static char *makestrspace(size_t, char *);
1845 static char *stnputs(const char *, size_t, char *);
1846 static char *stputs(const char *, char *);
1849 static inline char *_STPUTC(char c, char *p) {
1856 #define stackblock() ((void *)stacknxt)
1857 #define stackblocksize() stacknleft
1858 #define STARTSTACKSTR(p) ((p) = stackblock())
1859 #define STPUTC(c, p) ((p) = _STPUTC((c), (p)))
1860 #define CHECKSTRSPACE(n, p) \
1864 size_t m = sstrend - q; \
1866 (p) = makestrspace(l, q); \
1869 #define USTPUTC(c, p) (*p++ = (c))
1870 #define STACKSTRNUL(p) ((p) == sstrend? (p = growstackstr(), *p = '\0') : (*p = '\0'))
1871 #define STUNPUTC(p) (--p)
1872 #define STTOPC(p) p[-1]
1873 #define STADJUST(amount, p) (p += (amount))
1875 #define grabstackstr(p) stalloc((char *)(p) - (char *)stackblock())
1876 #define ungrabstackstr(s, p) stunalloc((s))
1877 #define stackstrend() ((void *)sstrend)
1879 #define ckfree(p) free((pointer)(p))
1881 /* $NetBSD: mystring.h,v 1.10 2002/11/24 22:35:42 christos Exp $ */
1884 #define DOLATSTRLEN 4
1886 static char *prefix(const char *, const char *);
1887 static int number(const char *);
1888 static int is_number(const char *);
1889 static char *single_quote(const char *);
1890 static char *sstrdup(const char *);
1892 #define equal(s1, s2) (strcmp(s1, s2) == 0)
1893 #define scopy(s1, s2) ((void)strcpy(s2, s1))
1895 /* $NetBSD: options.h,v 1.16 2003/01/22 20:36:04 dsl Exp $ */
1898 int nparam; /* # of positional parameters (without $0) */
1899 unsigned char malloc; /* if parameter list dynamically allocated */
1900 char **p; /* parameter list */
1901 #ifdef CONFIG_ASH_GETOPTS
1902 int optind; /* next parameter to be processed by getopts */
1903 int optoff; /* used by getopts */
1908 #define eflag optlist[0]
1909 #define fflag optlist[1]
1910 #define Iflag optlist[2]
1911 #define iflag optlist[3]
1912 #define mflag optlist[4]
1913 #define nflag optlist[5]
1914 #define sflag optlist[6]
1915 #define xflag optlist[7]
1916 #define vflag optlist[8]
1917 #define Cflag optlist[9]
1918 #define aflag optlist[10]
1919 #define bflag optlist[11]
1920 #define uflag optlist[12]
1921 #define qflag optlist[13]
1924 #define nolog optlist[14]
1925 #define debug optlist[15]
1931 /* $NetBSD: options.c,v 1.33 2003/01/22 20:36:04 dsl Exp $ */
1934 static const char *const optletters_optnames[NOPTS] = {
1955 #define optletters(n) optletters_optnames[(n)][0]
1956 #define optnames(n) (&optletters_optnames[(n)][1])
1959 static char optlist[NOPTS];
1962 static char *arg0; /* value of $0 */
1963 static struct shparam shellparam; /* $@ current positional parameters */
1964 static char **argptr; /* argument list for builtin commands */
1965 static char *optionarg; /* set by nextopt (like getopt) */
1966 static char *optptr; /* used by nextopt */
1968 static char *minusc; /* argument to -c option */
1971 static void procargs(int, char **);
1972 static void optschanged(void);
1973 static void setparam(char **);
1974 static void freeparam(volatile struct shparam *);
1975 static int shiftcmd(int, char **);
1976 static int setcmd(int, char **);
1977 static int nextopt(const char *);
1979 /* $NetBSD: redir.h,v 1.14 2002/11/24 22:35:43 christos Exp $ */
1981 /* flags passed to redirect */
1982 #define REDIR_PUSH 01 /* save previous values of file descriptors */
1983 #define REDIR_SAVEFD2 03 /* set preverrout */
1986 static void redirect(union node *, int);
1987 static void popredir(int);
1988 static void clearredir(int);
1989 static int copyfd(int, int);
1990 static int redirectsafe(union node *, int);
1992 /* $NetBSD: show.h,v 1.6 2003/01/22 20:36:04 dsl Exp $ */
1996 static void showtree(union node *);
1997 static void trace(const char *, ...);
1998 static void tracev(const char *, va_list);
1999 static void trargs(char **);
2000 static void trputc(int);
2001 static void trputs(const char *);
2002 static void opentrace(void);
2005 /* $NetBSD: trap.h,v 1.16 2002/11/24 22:35:43 christos Exp $ */
2008 /* trap handler commands */
2009 static char *trap[NSIG];
2010 /* current value of signal */
2011 static char sigmode[NSIG - 1];
2012 /* indicates specified signal received */
2013 static char gotsig[NSIG - 1];
2015 static void clear_traps(void);
2016 static void setsignal(int);
2017 static void ignoresig(int);
2018 static void onsig(int);
2019 static void dotrap(void);
2020 static void setinteractive(int);
2021 static void exitshell(void) __attribute__((__noreturn__));
2022 static int decode_signal(const char *, int);
2025 * This routine is called when an error or an interrupt occurs in an
2026 * interactive shell and control is returned to the main command loop.
2041 parselleft = parsenleft = 0; /* clear input buffer */
2045 /* from parser.c: */
2058 #ifdef CONFIG_ASH_ALIAS
2059 static struct alias *atab[ATABSIZE];
2061 static void setalias(const char *, const char *);
2062 static struct alias *freealias(struct alias *);
2063 static struct alias **__lookupalias(const char *);
2066 setalias(const char *name, const char *val)
2068 struct alias *ap, **app;
2070 app = __lookupalias(name);
2074 if (!(ap->flag & ALIASINUSE)) {
2077 ap->val = savestr(val);
2078 ap->flag &= ~ALIASDEAD;
2081 ap = ckmalloc(sizeof (struct alias));
2082 ap->name = savestr(name);
2083 ap->val = savestr(val);
2092 unalias(const char *name)
2096 app = __lookupalias(name);
2100 *app = freealias(*app);
2111 struct alias *ap, **app;
2115 for (i = 0; i < ATABSIZE; i++) {
2117 for (ap = *app; ap; ap = *app) {
2118 *app = freealias(*app);
2127 static struct alias *
2128 lookupalias(const char *name, int check)
2130 struct alias *ap = *__lookupalias(name);
2132 if (check && ap && (ap->flag & ALIASINUSE))
2138 * TODO - sort output
2141 aliascmd(int argc, char **argv)
2150 for (i = 0; i < ATABSIZE; i++)
2151 for (ap = atab[i]; ap; ap = ap->next) {
2156 while ((n = *++argv) != NULL) {
2157 if ((v = strchr(n+1, '=')) == NULL) { /* n+1: funny ksh stuff */
2158 if ((ap = *__lookupalias(n)) == NULL) {
2159 fprintf(stderr, "%s: %s not found\n", "alias", n);
2173 unaliascmd(int argc, char **argv)
2177 while ((i = nextopt("a")) != '\0') {
2183 for (i = 0; *argptr; argptr++) {
2184 if (unalias(*argptr)) {
2185 fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
2193 static struct alias *
2194 freealias(struct alias *ap) {
2197 if (ap->flag & ALIASINUSE) {
2198 ap->flag |= ALIASDEAD;
2210 printalias(const struct alias *ap) {
2211 out1fmt("%s=%s\n", ap->name, single_quote(ap->val));
2214 static struct alias **
2215 __lookupalias(const char *name) {
2216 unsigned int hashval;
2223 ch = (unsigned char)*p;
2227 ch = (unsigned char)*++p;
2229 app = &atab[hashval % ATABSIZE];
2231 for (; *app; app = &(*app)->next) {
2232 if (equal(name, (*app)->name)) {
2239 #endif /* CONFIG_ASH_ALIAS */
2242 /* $NetBSD: cd.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
2245 * The cd and pwd commands.
2248 #define CD_PHYSICAL 1
2251 static int docd(const char *, int);
2252 static int cdopt(void);
2254 static char *curdir = nullstr; /* current working directory */
2255 static char *physdir = nullstr; /* physical working directory */
2264 while ((i = nextopt("LP"))) {
2266 flags ^= CD_PHYSICAL;
2275 cdcmd(int argc, char **argv)
2287 dest = bltinlookup(homestr);
2288 else if (dest[0] == '-' && dest[1] == '\0') {
2289 dest = bltinlookup("OLDPWD");
2312 if (!(path = bltinlookup("CDPATH"))) {
2320 p = padvance(&path, dest);
2321 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2325 if (!docd(p, flags))
2330 error("can't cd to %s", dest);
2333 if (flags & CD_PRINT)
2334 out1fmt(snlfmt, curdir);
2340 * Update curdir (the name of the current directory) in response to a
2344 static inline const char *
2345 updatepwd(const char *dir)
2352 cdcomppath = sstrdup(dir);
2355 if (curdir == nullstr)
2357 new = stputs(curdir, new);
2359 new = makestrspace(strlen(dir) + 2, new);
2360 lim = stackblock() + 1;
2364 if (new > lim && *lim == '/')
2369 if (dir[1] == '/' && dir[2] != '/') {
2375 p = strtok(cdcomppath, "/");
2379 if (p[1] == '.' && p[2] == '\0') {
2386 } else if (p[1] == '\0')
2390 new = stputs(p, new);
2398 return stackblock();
2402 * Actually do the chdir. We also call hashcd to let the routines in exec.c
2403 * know that the current directory has changed.
2407 docd(const char *dest, int flags)
2409 const char *dir = 0;
2412 TRACE(("docd(\"%s\", %d) called\n", dest, flags));
2415 if (!(flags & CD_PHYSICAL)) {
2416 dir = updatepwd(dest);
2431 * Find out what the current directory is. If we already know the current
2432 * directory, this routine returns immediately.
2434 static inline char *
2437 char *dir = getcwd(0, 0);
2438 return dir ? dir : nullstr;
2442 pwdcmd(int argc, char **argv)
2445 const char *dir = curdir;
2449 if (physdir == nullstr)
2453 out1fmt(snlfmt, dir);
2458 setpwd(const char *val, int setold)
2462 oldcur = dir = curdir;
2465 setvar("OLDPWD", oldcur, VEXPORT);
2468 if (physdir != nullstr) {
2469 if (physdir != oldcur)
2473 if (oldcur == val || !val) {
2480 if (oldcur != dir && oldcur != nullstr) {
2485 setvar("PWD", dir, VEXPORT);
2488 /* $NetBSD: error.c,v 1.30 2003/01/22 20:36:03 dsl Exp $ */
2491 * Errors and exceptions.
2495 * Code to handle exceptions in C.
2500 static void exverror(int, const char *, va_list)
2501 __attribute__((__noreturn__));
2504 * Called to raise an exception. Since C doesn't include exceptions, we
2505 * just do a longjmp to the exception handler. The type of exception is
2506 * stored in the global variable "exception".
2513 if (handler == NULL)
2519 longjmp(handler->loc, 1);
2524 * Called from trap.c when a SIGINT is received. (If the user specifies
2525 * that SIGINT is to be trapped or ignored using the trap builtin, then
2526 * this routine is not called.) Suppressint is nonzero when interrupts
2527 * are held using the INTOFF macro. (The test for iflag is just
2528 * defensive programming.)
2538 if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
2539 if (!(rootshell && iflag)) {
2540 signal(SIGINT, SIG_DFL);
2550 exvwarning(const char *msg, va_list ap)
2563 fprintf(errs, fmt, name, startlinno);
2564 vfprintf(errs, msg, ap);
2565 outcslow('\n', errs);
2569 * Exverror is called to raise the error exception. If the second argument
2570 * is not NULL then error prints an error message using printf style
2571 * formatting. It then raises the error exception.
2574 exverror(int cond, const char *msg, va_list ap)
2578 TRACE(("exverror(%d, \"", cond));
2580 TRACE(("\") pid=%d\n", getpid()));
2582 TRACE(("exverror(%d, NULL) pid=%d\n", cond, getpid()));
2585 exvwarning(msg, ap);
2594 error(const char *msg, ...)
2599 exverror(EXERROR, msg, ap);
2606 exerror(int cond, const char *msg, ...)
2611 exverror(cond, msg, ap);
2617 * error/warning routines for external builtins
2621 sh_warnx(const char *fmt, ...)
2626 exvwarning(fmt, ap);
2632 * Return a string describing an error. The returned string may be a
2633 * pointer to a static buffer that will be overwritten on the next call.
2634 * Action describes the operation that got the error.
2638 errmsg(int e, const char *em)
2640 if(e == ENOENT || e == ENOTDIR) {
2648 /* $NetBSD: eval.c,v 1.71 2003/01/23 03:33:16 rafal Exp $ */
2651 * Evaluate a command.
2654 /* flags in argument to evaltree */
2655 #define EV_EXIT 01 /* exit after evaluating tree */
2656 #define EV_TESTED 02 /* exit status is checked; ignore -e flag */
2657 #define EV_BACKCMD 04 /* command executing within back quotes */
2660 static void evalloop(union node *, int);
2661 static void evalfor(union node *, int);
2662 static void evalcase(union node *, int);
2663 static void evalsubshell(union node *, int);
2664 static void expredir(union node *);
2665 static void evalpipe(union node *, int);
2666 static void evalcommand(union node *, int);
2667 static int evalbltin(const struct builtincmd *, int, char **);
2668 static int evalfun(struct funcnode *, int, char **, int);
2669 static void prehash(union node *);
2670 static int bltincmd(int, char **);
2673 static const struct builtincmd bltin = {
2679 * Called to reset things after an exception.
2683 * The eval commmand.
2687 evalcmd(int argc, char **argv)
2696 STARTSTACKSTR(concat);
2699 concat = stputs(p, concat);
2700 if ((p = *ap++) == NULL)
2702 STPUTC(' ', concat);
2704 STPUTC('\0', concat);
2705 p = grabstackstr(concat);
2714 * Execute a command or commands contained in a string.
2721 struct stackmark smark;
2723 setstackmark(&smark);
2726 while ((n = parsecmd(0)) != NEOF) {
2728 popstackmark(&smark);
2733 popstackmark(&smark);
2739 * Evaluate a parse tree. The value is left in the global variable
2744 evaltree(union node *n, int flags)
2747 void (*evalfn)(union node *, int);
2751 TRACE(("evaltree(NULL) called\n"));
2754 TRACE(("pid %d, evaltree(%p: %d, %d) called\n",
2755 getpid(), n, n->type, flags));
2759 out1fmt("Node type = %d\n", n->type);
2764 evaltree(n->nnot.com, EV_TESTED);
2765 status = !exitstatus;
2768 expredir(n->nredir.redirect);
2769 status = redirectsafe(n->nredir.redirect, REDIR_PUSH);
2771 evaltree(n->nredir.n, flags & EV_TESTED);
2772 status = exitstatus;
2777 evalfn = evalcommand;
2779 if (eflag && !(flags & EV_TESTED))
2791 evalfn = evalsubshell;
2803 #error NAND + 1 != NOR
2805 #if NOR + 1 != NSEMI
2806 #error NOR + 1 != NSEMI
2808 isor = n->type - NAND;
2811 (flags | ((isor >> 1) - 1)) & EV_TESTED
2813 if (!exitstatus == isor)
2825 evaltree(n->nif.test, EV_TESTED);
2828 if (exitstatus == 0) {
2831 } else if (n->nif.elsepart) {
2832 n = n->nif.elsepart;
2837 defun(n->narg.text, n->narg.next);
2841 exitstatus = status;
2847 if (flags & EV_EXIT || checkexit & exitstatus)
2852 #if !defined(__alpha__) || (defined(__GNUC__) && __GNUC__ >= 3)
2855 void evaltreenr(union node *, int) __attribute__ ((alias("evaltree"),__noreturn__));
2859 evalloop(union node *n, int flags)
2869 evaltree(n->nbinary.ch1, EV_TESTED);
2871 skipping: if (evalskip == SKIPCONT && --skipcount <= 0) {
2875 if (evalskip == SKIPBREAK && --skipcount <= 0)
2880 if (n->type != NWHILE)
2884 evaltree(n->nbinary.ch2, flags);
2885 status = exitstatus;
2890 exitstatus = status;
2896 evalfor(union node *n, int flags)
2898 struct arglist arglist;
2901 struct stackmark smark;
2903 setstackmark(&smark);
2904 arglist.lastp = &arglist.list;
2905 for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
2906 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE | EXP_RECORD);
2911 *arglist.lastp = NULL;
2916 for (sp = arglist.list ; sp ; sp = sp->next) {
2917 setvar(n->nfor.var, sp->text, 0);
2918 evaltree(n->nfor.body, flags);
2920 if (evalskip == SKIPCONT && --skipcount <= 0) {
2924 if (evalskip == SKIPBREAK && --skipcount <= 0)
2931 popstackmark(&smark);
2937 evalcase(union node *n, int flags)
2941 struct arglist arglist;
2942 struct stackmark smark;
2944 setstackmark(&smark);
2945 arglist.lastp = &arglist.list;
2946 expandarg(n->ncase.expr, &arglist, EXP_TILDE);
2948 for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
2949 for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
2950 if (casematch(patp, arglist.list->text)) {
2951 if (evalskip == 0) {
2952 evaltree(cp->nclist.body, flags);
2959 popstackmark(&smark);
2965 * Kick off a subshell to evaluate a tree.
2969 evalsubshell(union node *n, int flags)
2972 int backgnd = (n->type == NBACKGND);
2975 expredir(n->nredir.redirect);
2976 if (!backgnd && flags & EV_EXIT && !trap[0])
2980 if (forkshell(jp, n, backgnd) == 0) {
2984 flags &=~ EV_TESTED;
2986 redirect(n->nredir.redirect, 0);
2987 evaltreenr(n->nredir.n, flags);
2992 status = waitforjob(jp);
2993 exitstatus = status;
3000 * Compute the names of the files in a redirection list.
3004 expredir(union node *n)
3008 for (redir = n ; redir ; redir = redir->nfile.next) {
3010 fn.lastp = &fn.list;
3011 switch (redir->type) {
3017 expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR);
3018 redir->nfile.expfname = fn.list->text;
3022 if (redir->ndup.vname) {
3023 expandarg(redir->ndup.vname, &fn, EXP_FULL | EXP_TILDE);
3024 fixredir(redir, fn.list->text, 1);
3034 * Evaluate a pipeline. All the processes in the pipeline are children
3035 * of the process creating the pipeline. (This differs from some versions
3036 * of the shell, which make the last process in a pipeline the parent
3041 evalpipe(union node *n, int flags)
3044 struct nodelist *lp;
3049 TRACE(("evalpipe(0x%lx) called\n", (long)n));
3051 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
3055 jp = makejob(n, pipelen);
3057 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
3061 if (pipe(pip) < 0) {
3063 error("Pipe call failed");
3066 if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
3079 evaltreenr(lp->n, flags);
3087 if (n->npipe.backgnd == 0) {
3088 exitstatus = waitforjob(jp);
3089 TRACE(("evalpipe: job done exit status %d\n", exitstatus));
3097 * Execute a command inside back quotes. If it's a builtin command, we
3098 * want to save its output in a block obtained from malloc. Otherwise
3099 * we fork off a subprocess and get the output of the command via a pipe.
3100 * Should be called with interrupts off.
3104 evalbackcmd(union node *n, struct backcmd *result)
3116 saveherefd = herefd;
3124 error("Pipe call failed");
3126 if (forkshell(jp, n, FORK_NOJOB) == 0) {
3135 evaltreenr(n, EV_EXIT);
3139 result->fd = pip[0];
3142 herefd = saveherefd;
3144 TRACE(("evalbackcmd done: fd=%d buf=0x%x nleft=%d jp=0x%x\n",
3145 result->fd, result->buf, result->nleft, result->jp));
3148 #ifdef CONFIG_ASH_CMDCMD
3149 static inline char **
3150 parse_command_args(char **argv, const char **path)
3162 if (c == '-' && !*cp) {
3172 /* run 'typecmd' for other options */
3175 } while ((c = *cp++));
3184 * Execute a simple command.
3188 evalcommand(union node *cmd, int flags)
3190 struct stackmark smark;
3192 struct arglist arglist;
3193 struct arglist varlist;
3196 const struct strlist *sp;
3197 struct cmdentry cmdentry;
3206 /* First expand the arguments. */
3207 TRACE(("evalcommand(0x%lx, %d) called\n", (long)cmd, flags));
3208 setstackmark(&smark);
3209 back_exitstatus = 0;
3211 cmdentry.cmdtype = CMDBUILTIN;
3212 cmdentry.u.cmd = &bltin;
3213 varlist.lastp = &varlist.list;
3214 *varlist.lastp = NULL;
3215 arglist.lastp = &arglist.list;
3216 *arglist.lastp = NULL;
3219 for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) {
3220 struct strlist **spp;
3222 spp = arglist.lastp;
3223 expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
3224 for (sp = *spp; sp; sp = sp->next)
3228 argv = nargv = stalloc(sizeof (char *) * (argc + 1));
3229 for (sp = arglist.list ; sp ; sp = sp->next) {
3230 TRACE(("evalcommand arg: %s\n", sp->text));
3231 *nargv++ = sp->text;
3236 if (iflag && funcnest == 0 && argc > 0)
3237 lastarg = nargv[-1];
3240 expredir(cmd->ncmd.redirect);
3241 status = redirectsafe(cmd->ncmd.redirect, REDIR_PUSH|REDIR_SAVEFD2);
3244 for (argp = cmd->ncmd.assign; argp; argp = argp->narg.next) {
3245 struct strlist **spp;
3248 spp = varlist.lastp;
3249 expandarg(argp, &varlist, EXP_VARTILDE);
3252 * Modify the command lookup path, if a PATH= assignment
3256 if (varequal(p, path))
3260 /* Print the command if xflag is set. */
3263 const char *p = " %s";
3266 dprintf(preverrout_fd, p, ps4val());
3269 for(n = 0; n < 2; n++) {
3271 dprintf(preverrout_fd, p, sp->text);
3279 xwrite(preverrout_fd, "\n", 1);
3285 /* Now locate the command. */
3287 const char *oldpath;
3288 int cmd_flag = DO_ERR;
3293 find_command(argv[0], &cmdentry, cmd_flag, path);
3294 if (cmdentry.cmdtype == CMDUNKNOWN) {
3300 /* implement bltin and command here */
3301 if (cmdentry.cmdtype != CMDBUILTIN)
3304 spclbltin = IS_BUILTIN_SPECIAL(cmdentry.u.cmd);
3305 if (cmdentry.u.cmd == EXECCMD)
3307 #ifdef CONFIG_ASH_CMDCMD
3308 if (cmdentry.u.cmd == COMMANDCMD) {
3311 nargv = parse_command_args(argv, &path);
3314 argc -= nargv - argv;
3316 cmd_flag |= DO_NOFUNC;
3324 /* We have a redirection error. */
3328 exitstatus = status;
3332 /* Execute the command. */
3333 switch (cmdentry.cmdtype) {
3335 /* Fork off a child process if necessary. */
3336 if (!(flags & EV_EXIT) || trap[0]) {
3338 jp = makejob(cmd, 1);
3339 if (forkshell(jp, cmd, FORK_FG) != 0) {
3340 exitstatus = waitforjob(jp);
3346 listsetvar(varlist.list, VEXPORT|VSTACK);
3347 shellexec(argv, path, cmdentry.u.index);
3351 cmdenviron = varlist.list;
3353 struct strlist *list = cmdenviron;
3355 if (spclbltin > 0 || argc == 0) {
3357 if (cmd_is_exec && argc > 1)
3360 listsetvar(list, i);
3362 if (evalbltin(cmdentry.u.cmd, argc, argv)) {
3377 exit_status = j + 128;
3378 exitstatus = exit_status;
3380 if (i == EXINT || spclbltin > 0) {
3382 longjmp(handler->loc, 1);
3389 listsetvar(varlist.list, 0);
3390 if (evalfun(cmdentry.u.func, argc, argv, flags))
3396 popredir(cmd_is_exec);
3398 /* dsl: I think this is intended to be used to support
3399 * '_' in 'vi' command mode during line editing...
3400 * However I implemented that within libedit itself.
3402 setvar("_", lastarg, 0);
3403 popstackmark(&smark);
3407 evalbltin(const struct builtincmd *cmd, int argc, char **argv) {
3408 char *volatile savecmdname;
3409 struct jmploc *volatile savehandler;
3410 struct jmploc jmploc;
3413 savecmdname = commandname;
3414 if ((i = setjmp(jmploc.loc)))
3416 savehandler = handler;
3418 commandname = argv[0];
3420 optptr = NULL; /* initialize nextopt */
3421 exitstatus = (*cmd->builtin)(argc, argv);
3424 exitstatus |= ferror(stdout);
3425 commandname = savecmdname;
3427 handler = savehandler;
3433 evalfun(struct funcnode *func, int argc, char **argv, int flags)
3435 volatile struct shparam saveparam;
3436 struct localvar *volatile savelocalvars;
3437 struct jmploc *volatile savehandler;
3438 struct jmploc jmploc;
3441 saveparam = shellparam;
3442 savelocalvars = localvars;
3443 if ((e = setjmp(jmploc.loc))) {
3447 savehandler = handler;
3450 shellparam.malloc = 0;
3453 shellparam.nparam = argc - 1;
3454 shellparam.p = argv + 1;
3455 #ifdef CONFIG_ASH_GETOPTS
3456 shellparam.optind = 1;
3457 shellparam.optoff = -1;
3460 evaltree(&func->n, flags & EV_TESTED);
3466 localvars = savelocalvars;
3467 freeparam(&shellparam);
3468 shellparam = saveparam;
3469 handler = savehandler;
3471 if (evalskip == SKIPFUNC) {
3480 goodname(const char *p)
3482 return !*endofname(p);
3486 * Search for a command. This is called before we fork so that the
3487 * location of the command will be available in the parent as well as
3488 * the child. The check for "goodname" is an overly conservative
3489 * check that the name will not be subject to expansion.
3493 prehash(union node *n)
3495 struct cmdentry entry;
3497 if (n->type == NCMD && n->ncmd.args)
3498 if (goodname(n->ncmd.args->narg.text))
3499 find_command(n->ncmd.args->narg.text, &entry, 0,
3506 * Builtin commands. Builtin commands whose functions are closely
3507 * tied to evaluation are implemented here.
3515 bltincmd(int argc, char **argv)
3518 * Preserve exitstatus of a previous possible redirection
3521 return back_exitstatus;
3526 * Handle break and continue commands. Break, continue, and return are
3527 * all handled by setting the evalskip flag. The evaluation routines
3528 * above all check this flag, and if it is set they start skipping
3529 * commands rather than executing them. The variable skipcount is
3530 * the number of loops to break/continue, or the number of function
3531 * levels to return. (The latter is always 1.) It should probably
3532 * be an error to break out of more loops than exist, but it isn't
3533 * in the standard shell so we don't make it one here.
3537 breakcmd(int argc, char **argv)
3539 int n = argc > 1 ? number(argv[1]) : 1;
3542 error(illnum, argv[1]);
3546 evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
3554 * The return command.
3558 returncmd(int argc, char **argv)
3560 int ret = argc > 1 ? number(argv[1]) : exitstatus;
3563 evalskip = SKIPFUNC;
3568 /* Do what ksh does; skip the rest of the file */
3569 evalskip = SKIPFILE;
3577 falsecmd(int argc, char **argv)
3584 truecmd(int argc, char **argv)
3591 execcmd(int argc, char **argv)
3594 iflag = 0; /* exit on error */
3597 shellexec(argv + 1, pathval(), 0);
3603 /* $NetBSD: exec.c,v 1.35 2003/01/22 20:36:04 dsl Exp $ */
3606 * When commands are first encountered, they are entered in a hash table.
3607 * This ensures that a full path search will not have to be done for them
3608 * on each invocation.
3610 * We should investigate converting to a linear search, even though that
3611 * would make the command name "hash" a misnomer.
3614 #define CMDTABLESIZE 31 /* should be prime */
3615 #define ARB 1 /* actual size determined at run time */
3620 struct tblentry *next; /* next entry in hash chain */
3621 union param param; /* definition of builtin function */
3622 short cmdtype; /* index identifying command */
3623 char rehash; /* if set, cd done since entry created */
3624 char cmdname[ARB]; /* name of command */
3628 static struct tblentry *cmdtable[CMDTABLESIZE];
3629 static int builtinloc = -1; /* index in path of %builtin, or -1 */
3632 static void tryexec(char *, char **, char **);
3633 static void clearcmdentry(int);
3634 static struct tblentry *cmdlookup(const char *, int);
3635 static void delete_cmd_entry(void);
3639 * Exec a program. Never returns. If you change this routine, you may
3640 * have to change the find_command routine as well.
3644 shellexec(char **argv, const char *path, int idx)
3651 envp = environment();
3652 if (strchr(argv[0], '/') != NULL
3653 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3654 || find_applet_by_name(argv[0])
3657 tryexec(argv[0], argv, envp);
3661 while ((cmdname = padvance(&path, argv[0])) != NULL) {
3662 if (--idx < 0 && pathopt == NULL) {
3663 tryexec(cmdname, argv, envp);
3664 if (errno != ENOENT && errno != ENOTDIR)
3671 /* Map to POSIX errors */
3683 TRACE(("shellexec failed for %s, errno %d, suppressint %d\n",
3684 argv[0], e, suppressint ));
3685 exerror(EXEXEC, "%s: %s", argv[0], errmsg(e, E_EXEC));
3691 tryexec(char *cmd, char **argv, char **envp)
3694 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3698 #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
3699 name = bb_get_last_path_component(name);
3700 if(find_applet_by_name(name) != NULL)
3703 if(strchr(name, '/') == NULL && find_applet_by_name(name) != NULL) {
3712 if(strcmp(name, "busybox")) {
3713 for (ap = argv; *ap; ap++);
3714 ap = new = xmalloc((ap - argv + 2) * sizeof(char *));
3715 *ap++ = cmd = "/bin/busybox";
3716 while ((*ap++ = *argv++));
3720 cmd = "/bin/busybox";
3728 execve(cmd, argv, envp);
3729 } while (errno == EINTR);
3731 execve(cmd, argv, envp);
3735 } else if (errno == ENOEXEC) {
3739 for (ap = argv; *ap; ap++)
3741 ap = new = ckmalloc((ap - argv + 2) * sizeof(char *));
3743 *ap = cmd = (char *)DEFAULT_SHELL;
3746 while ((*ap++ = *argv++))
3756 * Do a path search. The variable path (passed by reference) should be
3757 * set to the start of the path before the first call; padvance will update
3758 * this value as it proceeds. Successive calls to padvance will return
3759 * the possible path expansions in sequence. If an option (indicated by
3760 * a percent sign) appears in the path entry then the global variable
3761 * pathopt will be set to point to it; otherwise pathopt will be set to
3766 padvance(const char **path, const char *name)
3776 for (p = start ; *p && *p != ':' && *p != '%' ; p++);
3777 len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */
3778 while (stackblocksize() < len)
3782 memcpy(q, start, p - start);
3790 while (*p && *p != ':') p++;
3796 return stalloc(len);
3800 /*** Command hashing code ***/
3803 printentry(struct tblentry *cmdp)
3809 idx = cmdp->param.index;
3812 name = padvance(&path, cmdp->cmdname);
3814 } while (--idx >= 0);
3815 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
3820 hashcmd(int argc, char **argv)
3822 struct tblentry **pp;
3823 struct tblentry *cmdp;
3825 struct cmdentry entry;
3828 while ((c = nextopt("r")) != '\0') {
3832 if (*argptr == NULL) {
3833 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
3834 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
3835 if (cmdp->cmdtype == CMDNORMAL)
3842 while ((name = *argptr) != NULL) {
3843 if ((cmdp = cmdlookup(name, 0)) != NULL
3844 && (cmdp->cmdtype == CMDNORMAL
3845 || (cmdp->cmdtype == CMDBUILTIN && builtinloc >= 0)))
3847 find_command(name, &entry, DO_ERR, pathval());
3848 if (entry.cmdtype == CMDUNKNOWN)
3857 * Resolve a command name. If you change this routine, you may have to
3858 * change the shellexec routine as well.
3862 find_command(char *name, struct cmdentry *entry, int act, const char *path)
3864 struct tblentry *cmdp;
3871 struct builtincmd *bcmd;
3873 /* If name contains a slash, don't use PATH or hash table */
3874 if (strchr(name, '/') != NULL) {
3875 entry->u.index = -1;
3877 while (stat(name, &statb) < 0) {
3882 entry->cmdtype = CMDUNKNOWN;
3886 entry->cmdtype = CMDNORMAL;
3890 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
3891 if (find_applet_by_name(name)) {
3892 entry->cmdtype = CMDNORMAL;
3893 entry->u.index = -1;
3898 updatetbl = (path == pathval());
3901 if (strstr(path, "%builtin") != NULL)
3905 /* If name is in the table, check answer will be ok */
3906 if ((cmdp = cmdlookup(name, 0)) != NULL) {
3909 switch (cmdp->cmdtype) {
3927 } else if (cmdp->rehash == 0)
3928 /* if not invalidated by cd, we're done */
3932 /* If %builtin not in path, check for builtin next */
3933 bcmd = find_builtin(name);
3934 if (bcmd && (IS_BUILTIN_REGULAR(bcmd) || (
3935 act & DO_ALTPATH ? !(act & DO_ALTBLTIN) : builtinloc <= 0
3937 goto builtin_success;
3939 /* We have to search path. */
3940 prev = -1; /* where to start */
3941 if (cmdp && cmdp->rehash) { /* doing a rehash */
3942 if (cmdp->cmdtype == CMDBUILTIN)
3945 prev = cmdp->param.index;
3951 while ((fullname = padvance(&path, name)) != NULL) {
3952 stunalloc(fullname);
3955 if (prefix(pathopt, "builtin")) {
3957 goto builtin_success;
3959 } else if (!(act & DO_NOFUNC) &&
3960 prefix(pathopt, "func")) {
3963 /* ignore unimplemented options */
3967 /* if rehash, don't redo absolute path names */
3968 if (fullname[0] == '/' && idx <= prev) {
3971 TRACE(("searchexec \"%s\": no change\n", name));
3974 while (stat(fullname, &statb) < 0) {
3979 if (errno != ENOENT && errno != ENOTDIR)
3983 e = EACCES; /* if we fail, this will be the error */
3984 if (!S_ISREG(statb.st_mode))
3986 if (pathopt) { /* this is a %func directory */
3987 stalloc(strlen(fullname) + 1);
3988 readcmdfile(fullname);
3989 if ((cmdp = cmdlookup(name, 0)) == NULL ||
3990 cmdp->cmdtype != CMDFUNCTION)
3991 error("%s not defined in %s", name, fullname);
3992 stunalloc(fullname);
3995 TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
3997 entry->cmdtype = CMDNORMAL;
3998 entry->u.index = idx;
4002 cmdp = cmdlookup(name, 1);
4003 cmdp->cmdtype = CMDNORMAL;
4004 cmdp->param.index = idx;
4009 /* We failed. If there was an entry for this command, delete it */
4010 if (cmdp && updatetbl)
4013 sh_warnx("%s: %s", name, errmsg(e, E_EXEC));
4014 entry->cmdtype = CMDUNKNOWN;
4019 entry->cmdtype = CMDBUILTIN;
4020 entry->u.cmd = bcmd;
4024 cmdp = cmdlookup(name, 1);
4025 cmdp->cmdtype = CMDBUILTIN;
4026 cmdp->param.cmd = bcmd;
4030 entry->cmdtype = cmdp->cmdtype;
4031 entry->u = cmdp->param;
4036 * Wrapper around strcmp for qsort/bsearch/...
4038 static int pstrcmp(const void *a, const void *b)
4040 return strcmp((const char *) a, (*(const char *const *) b) + 1);
4044 * Search the table of builtin commands.
4047 static struct builtincmd *
4048 find_builtin(const char *name)
4050 struct builtincmd *bp;
4053 name, builtincmd, NUMBUILTINS, sizeof(struct builtincmd),
4062 * Called when a cd is done. Marks all commands so the next time they
4063 * are executed they will be rehashed.
4069 struct tblentry **pp;
4070 struct tblentry *cmdp;
4072 for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
4073 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4074 if (cmdp->cmdtype == CMDNORMAL || (
4075 cmdp->cmdtype == CMDBUILTIN &&
4076 !(IS_BUILTIN_REGULAR(cmdp->param.cmd)) &&
4087 * Fix command hash table when PATH changed.
4088 * Called before PATH is changed. The argument is the new value of PATH;
4089 * pathval() still returns the old value at this point.
4090 * Called with interrupts off.
4094 changepath(const char *newval)
4096 const char *old, *new;
4103 firstchange = 9999; /* assume no change */
4109 if ((*old == '\0' && *new == ':')
4110 || (*old == ':' && *new == '\0'))
4112 old = new; /* ignore subsequent differences */
4116 if (*new == '%' && idx_bltin < 0 && prefix(new + 1, "builtin"))
4123 if (builtinloc < 0 && idx_bltin >= 0)
4124 builtinloc = idx_bltin; /* zap builtins */
4125 if (builtinloc >= 0 && idx_bltin < 0)
4127 clearcmdentry(firstchange);
4128 builtinloc = idx_bltin;
4133 * Clear out command entries. The argument specifies the first entry in
4134 * PATH which has changed.
4138 clearcmdentry(int firstchange)
4140 struct tblentry **tblp;
4141 struct tblentry **pp;
4142 struct tblentry *cmdp;
4145 for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
4147 while ((cmdp = *pp) != NULL) {
4148 if ((cmdp->cmdtype == CMDNORMAL &&
4149 cmdp->param.index >= firstchange)
4150 || (cmdp->cmdtype == CMDBUILTIN &&
4151 builtinloc >= firstchange)) {
4165 * Locate a command in the command hash table. If "add" is nonzero,
4166 * add the command to the table if it is not already present. The
4167 * variable "lastcmdentry" is set to point to the address of the link
4168 * pointing to the entry, so that delete_cmd_entry can delete the
4171 * Interrupts must be off if called with add != 0.
4174 static struct tblentry **lastcmdentry;
4177 static struct tblentry *
4178 cmdlookup(const char *name, int add)
4180 unsigned int hashval;
4182 struct tblentry *cmdp;
4183 struct tblentry **pp;
4186 hashval = (unsigned char)*p << 4;
4188 hashval += (unsigned char)*p++;
4190 pp = &cmdtable[hashval % CMDTABLESIZE];
4191 for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
4192 if (equal(cmdp->cmdname, name))
4196 if (add && cmdp == NULL) {
4197 cmdp = *pp = ckmalloc(sizeof (struct tblentry) - ARB
4198 + strlen(name) + 1);
4200 cmdp->cmdtype = CMDUNKNOWN;
4201 strcpy(cmdp->cmdname, name);
4208 * Delete the command entry returned on the last lookup.
4212 delete_cmd_entry(void)
4214 struct tblentry *cmdp;
4217 cmdp = *lastcmdentry;
4218 *lastcmdentry = cmdp->next;
4219 if (cmdp->cmdtype == CMDFUNCTION)
4220 freefunc(cmdp->param.func);
4227 * Add a new command entry, replacing any existing command entry for
4228 * the same name - except special builtins.
4232 addcmdentry(char *name, struct cmdentry *entry)
4234 struct tblentry *cmdp;
4236 cmdp = cmdlookup(name, 1);
4237 if (cmdp->cmdtype == CMDFUNCTION) {
4238 freefunc(cmdp->param.func);
4240 cmdp->cmdtype = entry->cmdtype;
4241 cmdp->param = entry->u;
4246 * Make a copy of a parse tree.
4249 static inline struct funcnode *
4250 copyfunc(union node *n)
4255 funcblocksize = offsetof(struct funcnode, n);
4258 blocksize = funcblocksize;
4259 f = ckmalloc(blocksize + funcstringsize);
4260 funcblock = (char *) f + offsetof(struct funcnode, n);
4261 funcstring = (char *) f + blocksize;
4268 * Define a shell function.
4272 defun(char *name, union node *func)
4274 struct cmdentry entry;
4277 entry.cmdtype = CMDFUNCTION;
4278 entry.u.func = copyfunc(func);
4279 addcmdentry(name, &entry);
4285 * Delete a function if it exists.
4289 unsetfunc(const char *name)
4291 struct tblentry *cmdp;
4293 if ((cmdp = cmdlookup(name, 0)) != NULL &&
4294 cmdp->cmdtype == CMDFUNCTION)
4299 * Locate and print what a word is...
4303 #ifdef CONFIG_ASH_CMDCMD
4305 describe_command(char *command, int describe_command_verbose)
4307 #define describe_command_verbose 1
4309 describe_command(char *command)
4312 struct cmdentry entry;
4313 struct tblentry *cmdp;
4314 #ifdef CONFIG_ASH_ALIAS
4315 const struct alias *ap;
4317 const char *path = pathval();
4319 if (describe_command_verbose) {
4323 /* First look at the keywords */
4324 if (findkwd(command)) {
4325 out1str(describe_command_verbose ? " is a shell keyword" : command);
4329 #ifdef CONFIG_ASH_ALIAS
4330 /* Then look at the aliases */
4331 if ((ap = lookupalias(command, 0)) != NULL) {
4332 if (describe_command_verbose) {
4333 out1fmt(" is an alias for %s", ap->val);
4342 /* Then check if it is a tracked alias */
4343 if ((cmdp = cmdlookup(command, 0)) != NULL) {
4344 entry.cmdtype = cmdp->cmdtype;
4345 entry.u = cmdp->param;
4347 /* Finally use brute force */
4348 find_command(command, &entry, DO_ABS, path);
4351 switch (entry.cmdtype) {
4353 int j = entry.u.index;
4359 p = padvance(&path, command);
4363 if (describe_command_verbose) {
4365 (cmdp ? " a tracked alias for" : nullstr), p
4374 if (describe_command_verbose) {
4375 out1str(" is a shell function");
4382 if (describe_command_verbose) {
4383 out1fmt(" is a %sshell builtin",
4384 IS_BUILTIN_SPECIAL(entry.u.cmd) ?
4385 "special " : nullstr
4393 if (describe_command_verbose) {
4394 out1str(": not found\n");
4400 outstr("\n", stdout);
4405 typecmd(int argc, char **argv)
4410 for (i = 1; i < argc; i++) {
4411 #ifdef CONFIG_ASH_CMDCMD
4412 err |= describe_command(argv[i], 1);
4414 err |= describe_command(argv[i]);
4420 #ifdef CONFIG_ASH_CMDCMD
4422 commandcmd(int argc, char **argv)
4425 int default_path = 0;
4426 int verify_only = 0;
4427 int verbose_verify_only = 0;
4429 while ((c = nextopt("pvV")) != '\0')
4434 "command: nextopt returned character code 0%o\n", c);
4444 verbose_verify_only = 1;
4448 if (default_path + verify_only + verbose_verify_only > 1 ||
4451 "command [-p] command [arg ...]\n"
4452 "command {-v|-V} command\n");
4456 if (verify_only || verbose_verify_only) {
4457 return describe_command(*argptr, verbose_verify_only);
4464 /* $NetBSD: expand.c,v 1.56 2002/11/24 22:35:39 christos Exp $ */
4467 * Routines to expand arguments to commands. We have to deal with
4468 * backquotes, shell variables, and file metacharacters.
4474 #define RMESCAPE_ALLOC 0x1 /* Allocate a new string */
4475 #define RMESCAPE_GLOB 0x2 /* Add backslashes for glob */
4476 #define RMESCAPE_QUOTED 0x4 /* Remove CTLESC unless in quotes */
4477 #define RMESCAPE_GROW 0x8 /* Grow strings instead of stalloc */
4478 #define RMESCAPE_HEAP 0x10 /* Malloc strings instead of stalloc */
4481 * Structure specifying which parts of the string should be searched
4482 * for IFS characters.
4486 struct ifsregion *next; /* next region in list */
4487 int begoff; /* offset of start of region */
4488 int endoff; /* offset of end of region */
4489 int nulonly; /* search for nul bytes only */
4492 /* output of current string */
4493 static char *expdest;
4494 /* list of back quote expressions */
4495 static struct nodelist *argbackq;
4496 /* first struct in list of ifs regions */
4497 static struct ifsregion ifsfirst;
4498 /* last struct in list */
4499 static struct ifsregion *ifslastp;
4500 /* holds expanded arg list */
4501 static struct arglist exparg;
4503 static void argstr(char *, int);
4504 static char *exptilde(char *, char *, int);
4505 static void expbackq(union node *, int, int);
4506 static const char *subevalvar(char *, char *, int, int, int, int, int);
4507 static char *evalvar(char *, int);
4508 static void strtodest(const char *, int, int);
4509 static void memtodest(const char *p, size_t len, int syntax, int quotes);
4510 static ssize_t varvalue(char *, int, int);
4511 static void recordregion(int, int, int);
4512 static void removerecordregions(int);
4513 static void ifsbreakup(char *, struct arglist *);
4514 static void ifsfree(void);
4515 static void expandmeta(struct strlist *, int);
4516 static int patmatch(char *, const char *);
4518 static int cvtnum(long);
4519 static size_t esclen(const char *, const char *);
4520 static char *scanleft(char *, char *, char *, char *, int, int);
4521 static char *scanright(char *, char *, char *, char *, int, int);
4522 static void varunset(const char *, const char *, const char *, int)
4523 __attribute__((__noreturn__));
4526 #define pmatch(a, b) !fnmatch((a), (b), 0)
4528 * Prepare a pattern for a expmeta (internal glob(3)) call.
4530 * Returns an stalloced string.
4533 static inline char *
4534 preglob(const char *pattern, int quoted, int flag) {
4535 flag |= RMESCAPE_GLOB;
4537 flag |= RMESCAPE_QUOTED;
4539 return _rmescapes((char *)pattern, flag);
4544 esclen(const char *start, const char *p) {
4547 while (p > start && *--p == CTLESC) {
4555 * Expand shell variables and backquotes inside a here document.
4559 expandhere(union node *arg, int fd)
4562 expandarg(arg, (struct arglist *)NULL, 0);
4563 xwrite(fd, stackblock(), expdest - (char *)stackblock());
4568 * Perform variable substitution and command substitution on an argument,
4569 * placing the resulting list of arguments in arglist. If EXP_FULL is true,
4570 * perform splitting and file name expansion. When arglist is NULL, perform
4571 * here document expansion.
4575 expandarg(union node *arg, struct arglist *arglist, int flag)
4580 argbackq = arg->narg.backquote;
4581 STARTSTACKSTR(expdest);
4582 ifsfirst.next = NULL;
4584 argstr(arg->narg.text, flag);
4585 if (arglist == NULL) {
4586 return; /* here document expanded */
4588 STPUTC('\0', expdest);
4589 p = grabstackstr(expdest);
4590 exparg.lastp = &exparg.list;
4594 if (flag & EXP_FULL) {
4595 ifsbreakup(p, &exparg);
4596 *exparg.lastp = NULL;
4597 exparg.lastp = &exparg.list;
4598 expandmeta(exparg.list, flag);
4600 if (flag & EXP_REDIR) /*XXX - for now, just remove escapes */
4602 sp = (struct strlist *)stalloc(sizeof (struct strlist));
4605 exparg.lastp = &sp->next;
4609 *exparg.lastp = NULL;
4611 *arglist->lastp = exparg.list;
4612 arglist->lastp = exparg.lastp;
4618 * Perform variable and command substitution. If EXP_FULL is set, output CTLESC
4619 * characters to allow for further processing. Otherwise treat
4620 * $@ like $* since no splitting will be performed.
4624 argstr(char *p, int flag)
4626 static const char spclchars[] = {
4634 CTLBACKQ | CTLQUOTE,
4635 #ifdef CONFIG_ASH_MATH_SUPPORT
4640 const char *reject = spclchars;
4642 int quotes = flag & (EXP_FULL | EXP_CASE); /* do CTLESC */
4643 int breakall = flag & EXP_WORD;
4648 if (!(flag & EXP_VARTILDE)) {
4650 } else if (flag & EXP_VARTILDE2) {
4655 if (flag & EXP_TILDE) {
4661 if (*q == CTLESC && (flag & EXP_QWORD))
4664 p = exptilde(p, q, flag);
4667 startloc = expdest - (char *)stackblock();
4669 length += strcspn(p + length, reject);
4671 if (c && (!(c & 0x80)
4672 #ifdef CONFIG_ASH_MATH_SUPPORT
4676 /* c == '=' || c == ':' || c == CTLENDARI */
4681 expdest = stnputs(p, length, expdest);
4682 newloc = expdest - (char *)stackblock();
4683 if (breakall && !inquotes && newloc > startloc) {
4684 recordregion(startloc, newloc, 0);
4695 if (flag & EXP_VARTILDE2) {
4699 flag |= EXP_VARTILDE2;
4704 * sort of a hack - expand tildes in variable
4705 * assignments (after the first '=' and after ':'s).
4714 case CTLENDVAR: /* ??? */
4717 /* "$@" syntax adherence hack */
4720 !memcmp(p, dolatstr, DOLATSTRLEN) &&
4721 (p[4] == CTLQUOTEMARK || (
4722 p[4] == CTLENDVAR &&
4723 p[5] == CTLQUOTEMARK
4726 p = evalvar(p + 1, flag) + 1;
4729 inquotes = !inquotes;
4742 p = evalvar(p, flag);
4746 case CTLBACKQ|CTLQUOTE:
4747 expbackq(argbackq->n, c, quotes);
4748 argbackq = argbackq->next;
4750 #ifdef CONFIG_ASH_MATH_SUPPORT
4763 exptilde(char *startp, char *p, int flag)
4769 int quotes = flag & (EXP_FULL | EXP_CASE);
4774 while ((c = *++p) != '\0') {
4781 if (flag & EXP_VARTILDE)
4791 if (*name == '\0') {
4792 if ((home = lookupvar(homestr)) == NULL)
4795 if ((pw = getpwnam(name)) == NULL)
4802 startloc = expdest - (char *)stackblock();
4803 strtodest(home, SQSYNTAX, quotes);
4804 recordregion(startloc, expdest - (char *)stackblock(), 0);
4813 removerecordregions(int endoff)
4815 if (ifslastp == NULL)
4818 if (ifsfirst.endoff > endoff) {
4819 while (ifsfirst.next != NULL) {
4820 struct ifsregion *ifsp;
4822 ifsp = ifsfirst.next->next;
4823 ckfree(ifsfirst.next);
4824 ifsfirst.next = ifsp;
4827 if (ifsfirst.begoff > endoff)
4830 ifslastp = &ifsfirst;
4831 ifsfirst.endoff = endoff;
4836 ifslastp = &ifsfirst;
4837 while (ifslastp->next && ifslastp->next->begoff < endoff)
4838 ifslastp=ifslastp->next;
4839 while (ifslastp->next != NULL) {
4840 struct ifsregion *ifsp;
4842 ifsp = ifslastp->next->next;
4843 ckfree(ifslastp->next);
4844 ifslastp->next = ifsp;
4847 if (ifslastp->endoff > endoff)
4848 ifslastp->endoff = endoff;
4852 #ifdef CONFIG_ASH_MATH_SUPPORT
4854 * Expand arithmetic expression. Backup to start of expression,
4855 * evaluate, place result in (backed up) result, adjust string position.
4868 * This routine is slightly over-complicated for
4869 * efficiency. Next we scan backwards looking for the
4870 * start of arithmetic.
4872 start = stackblock();
4879 while (*p != CTLARI) {
4883 error("missing CTLARI (shouldn't happen)");
4888 esc = esclen(start, p);
4898 removerecordregions(begoff);
4907 len = cvtnum(dash_arith(p + 2));
4910 recordregion(begoff, begoff + len, 0);
4915 * Expand stuff in backwards quotes.
4919 expbackq(union node *cmd, int quoted, int quotes)
4927 int syntax = quoted? DQSYNTAX : BASESYNTAX;
4928 struct stackmark smark;
4931 setstackmark(&smark);
4933 startloc = dest - (char *)stackblock();
4935 evalbackcmd(cmd, (struct backcmd *) &in);
4936 popstackmark(&smark);
4943 memtodest(p, i, syntax, quotes);
4947 i = safe_read(in.fd, buf, sizeof buf);
4948 TRACE(("expbackq: read returns %d\n", i));
4958 back_exitstatus = waitforjob(in.jp);
4962 /* Eat all trailing newlines */
4964 for (; dest > (char *)stackblock() && dest[-1] == '\n';)
4969 recordregion(startloc, dest - (char *)stackblock(), 0);
4970 TRACE(("evalbackq: size=%d: \"%.*s\"\n",
4971 (dest - (char *)stackblock()) - startloc,
4972 (dest - (char *)stackblock()) - startloc,
4973 stackblock() + startloc));
4978 scanleft(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
4989 const char *s = loc2;
4995 match = pmatch(str, s);
4999 if (quotes && *loc == CTLESC)
5009 scanright(char *startp, char *rmesc, char *rmescend, char *str, int quotes,
5016 for (loc = str - 1, loc2 = rmescend; loc >= startp; loc2--) {
5019 const char *s = loc2;
5024 match = pmatch(str, s);
5031 esc = esclen(startp, loc);
5043 subevalvar(char *p, char *str, int strloc, int subtype, int startloc, int varflags, int quotes)
5047 int saveherefd = herefd;
5048 struct nodelist *saveargbackq = argbackq;
5050 char *rmesc, *rmescend;
5052 char *(*scan)(char *, char *, char *, char *, int , int);
5055 argstr(p, subtype != VSASSIGN && subtype != VSQUESTION ? EXP_CASE : 0);
5056 STPUTC('\0', expdest);
5057 herefd = saveherefd;
5058 argbackq = saveargbackq;
5059 startp = stackblock() + startloc;
5063 setvar(str, startp, 0);
5064 amount = startp - expdest;
5065 STADJUST(amount, expdest);
5069 varunset(p, str, startp, varflags);
5073 subtype -= VSTRIMRIGHT;
5075 if (subtype < 0 || subtype > 3)
5080 rmescend = stackblock() + strloc;
5082 rmesc = _rmescapes(startp, RMESCAPE_ALLOC | RMESCAPE_GROW);
5083 if (rmesc != startp) {
5085 startp = stackblock() + startloc;
5089 str = stackblock() + strloc;
5090 preglob(str, varflags & VSQUOTE, 0);
5092 /* zero = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX */
5093 zero = subtype >> 1;
5094 /* VSTRIMLEFT/VSTRIMRIGHTMAX -> scanleft */
5095 scan = (subtype & 1) ^ zero ? scanleft : scanright;
5097 loc = scan(startp, rmesc, rmescend, str, quotes, zero);
5100 memmove(startp, loc, str - loc);
5101 loc = startp + (str - loc) - 1;
5104 amount = loc - expdest;
5105 STADJUST(amount, expdest);
5112 * Expand a variable, and return a pointer to the next character in the
5116 evalvar(char *p, int flag)
5129 quotes = flag & (EXP_FULL | EXP_CASE);
5131 subtype = varflags & VSTYPE;
5132 quoted = varflags & VSQUOTE;
5134 easy = (!quoted || (*var == '@' && shellparam.nparam));
5135 startloc = expdest - (char *)stackblock();
5136 p = strchr(p, '=') + 1;
5139 varlen = varvalue(var, varflags, flag);
5140 if (varflags & VSNUL)
5143 if (subtype == VSPLUS) {
5144 varlen = -1 - varlen;
5148 if (subtype == VSMINUS) {
5152 p, flag | EXP_TILDE |
5153 (quoted ? EXP_QWORD : EXP_WORD)
5162 if (subtype == VSASSIGN || subtype == VSQUESTION) {
5164 if (subevalvar(p, var, 0, subtype, startloc,
5168 * Remove any recorded regions beyond
5171 removerecordregions(startloc);
5181 if (varlen < 0 && uflag)
5182 varunset(p, var, 0, 0);
5184 if (subtype == VSLENGTH) {
5185 cvtnum(varlen > 0 ? varlen : 0);
5189 if (subtype == VSNORMAL) {
5193 recordregion(startloc, expdest - (char *)stackblock(), quoted);
5202 case VSTRIMRIGHTMAX:
5211 * Terminate the string and start recording the pattern
5214 STPUTC('\0', expdest);
5215 patloc = expdest - (char *)stackblock();
5216 if (subevalvar(p, NULL, patloc, subtype,
5217 startloc, varflags, quotes) == 0) {
5218 int amount = expdest - (
5219 (char *)stackblock() + patloc - 1
5221 STADJUST(-amount, expdest);
5223 /* Remove any recorded regions beyond start of variable */
5224 removerecordregions(startloc);
5229 if (subtype != VSNORMAL) { /* skip to end of alternative */
5232 if ((c = *p++) == CTLESC)
5234 else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE)) {
5236 argbackq = argbackq->next;
5237 } else if (c == CTLVAR) {
5238 if ((*p++ & VSTYPE) != VSNORMAL)
5240 } else if (c == CTLENDVAR) {
5251 * Put a string on the stack.
5255 memtodest(const char *p, size_t len, int syntax, int quotes) {
5258 q = makestrspace(len * 2, q);
5264 if (quotes && (SIT(c, syntax) == CCTL || SIT(c, syntax) == CBACK))
5274 strtodest(const char *p, int syntax, int quotes)
5276 memtodest(p, strlen(p), syntax, quotes);
5281 * Add the value of a specialized variable to the stack string.
5285 varvalue(char *name, int varflags, int flags)
5295 int quoted = varflags & VSQUOTE;
5296 int subtype = varflags & VSTYPE;
5297 int quotes = flags & (EXP_FULL | EXP_CASE);
5299 if (quoted && (flags & EXP_FULL))
5300 sep = 1 << CHAR_BIT;
5302 syntax = quoted ? DQSYNTAX : BASESYNTAX;
5311 num = shellparam.nparam;
5321 p = makestrspace(NOPTS, expdest);
5322 for (i = NOPTS - 1; i >= 0; i--) {
5324 USTPUTC(optletters(i), p);
5335 sep = ifsset() ? ifsval()[0] : ' ';
5336 if (quotes && (SIT(sep, syntax) == CCTL || SIT(sep, syntax) == CBACK))
5339 if (!(ap = shellparam.p))
5341 while ((p = *ap++)) {
5344 partlen = strlen(p);
5347 if (len > partlen && sep) {
5351 if (subtype == VSPLUS || subtype == VSLENGTH) {
5361 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5362 memtodest(p, partlen, syntax, quotes);
5376 if (num < 0 || num > shellparam.nparam)
5378 p = num ? shellparam.p[num - 1] : arg0;
5381 p = lookupvar(name);
5387 if (!(subtype == VSPLUS || subtype == VSLENGTH))
5388 memtodest(p, len, syntax, quotes);
5392 if (subtype == VSPLUS || subtype == VSLENGTH)
5393 STADJUST(-len, expdest);
5399 * Record the fact that we have to scan this region of the
5400 * string for IFS characters.
5404 recordregion(int start, int end, int nulonly)
5406 struct ifsregion *ifsp;
5408 if (ifslastp == NULL) {
5412 ifsp = (struct ifsregion *)ckmalloc(sizeof (struct ifsregion));
5414 ifslastp->next = ifsp;
5418 ifslastp->begoff = start;
5419 ifslastp->endoff = end;
5420 ifslastp->nulonly = nulonly;
5425 * Break the argument string into pieces based upon IFS and add the
5426 * strings to the argument list. The regions of the string to be
5427 * searched for IFS characters have been stored by recordregion.
5430 ifsbreakup(char *string, struct arglist *arglist)
5432 struct ifsregion *ifsp;
5437 const char *ifs, *realifs;
5443 if (ifslastp != NULL) {
5446 realifs = ifsset() ? ifsval() : defifs;
5449 p = string + ifsp->begoff;
5450 nulonly = ifsp->nulonly;
5451 ifs = nulonly ? nullstr : realifs;
5453 while (p < string + ifsp->endoff) {
5457 if (strchr(ifs, *p)) {
5459 ifsspc = (strchr(defifs, *p) != NULL);
5460 /* Ignore IFS whitespace at start */
5461 if (q == start && ifsspc) {
5467 sp = (struct strlist *)stalloc(sizeof *sp);
5469 *arglist->lastp = sp;
5470 arglist->lastp = &sp->next;
5474 if (p >= string + ifsp->endoff) {
5480 if (strchr(ifs, *p) == NULL ) {
5483 } else if (strchr(defifs, *p) == NULL) {
5499 } while ((ifsp = ifsp->next) != NULL);
5508 sp = (struct strlist *)stalloc(sizeof *sp);
5510 *arglist->lastp = sp;
5511 arglist->lastp = &sp->next;
5517 struct ifsregion *p;
5522 struct ifsregion *ifsp;
5528 ifsfirst.next = NULL;
5532 static void expmeta(char *, char *);
5533 static struct strlist *expsort(struct strlist *);
5534 static struct strlist *msort(struct strlist *, int);
5536 static char *expdir;
5540 expandmeta(struct strlist *str, int flag)
5542 static const char metachars[] = {
5545 /* TODO - EXP_REDIR */
5548 struct strlist **savelastp;
5554 if (!strpbrk(str->text, metachars))
5556 savelastp = exparg.lastp;
5559 p = preglob(str->text, 0, RMESCAPE_ALLOC | RMESCAPE_HEAP);
5561 int i = strlen(str->text);
5562 expdir = ckmalloc(i < 2048 ? 2048 : i); /* XXX */
5570 if (exparg.lastp == savelastp) {
5575 *exparg.lastp = str;
5576 rmescapes(str->text);
5577 exparg.lastp = &str->next;
5579 *exparg.lastp = NULL;
5580 *savelastp = sp = expsort(*savelastp);
5581 while (sp->next != NULL)
5583 exparg.lastp = &sp->next;
5590 * Add a file name to the list.
5594 addfname(const char *name)
5598 sp = (struct strlist *)stalloc(sizeof *sp);
5599 sp->text = sstrdup(name);
5601 exparg.lastp = &sp->next;
5606 * Do metacharacter (i.e. *, ?, [...]) expansion.
5610 expmeta(char *enddir, char *name)
5625 for (p = name; *p; p++) {
5626 if (*p == '*' || *p == '?')
5628 else if (*p == '[') {
5635 if (*q == '/' || *q == '\0')
5642 } else if (*p == '\\')
5644 else if (*p == '/') {
5651 if (metaflag == 0) { /* we've reached the end of the file name */
5652 if (enddir != expdir)
5660 if (metaflag == 0 || lstat(expdir, &statb) >= 0)
5671 } while (p < start);
5673 if (enddir == expdir) {
5675 } else if (enddir == expdir + 1 && *expdir == '/') {
5681 if ((dirp = opendir(cp)) == NULL)
5683 if (enddir != expdir)
5685 if (*endname == 0) {
5697 while (! intpending && (dp = readdir(dirp)) != NULL) {
5698 if (dp->d_name[0] == '.' && ! matchdot)
5700 if (pmatch(start, dp->d_name)) {
5702 scopy(dp->d_name, enddir);
5705 for (p = enddir, cp = dp->d_name;
5706 (*p++ = *cp++) != '\0';)
5709 expmeta(p, endname);
5719 * Sort the results of file name expansion. It calculates the number of
5720 * strings to sort and then calls msort (short for merge sort) to do the
5724 static struct strlist *
5725 expsort(struct strlist *str)
5731 for (sp = str ; sp ; sp = sp->next)
5733 return msort(str, len);
5737 static struct strlist *
5738 msort(struct strlist *list, int len)
5740 struct strlist *p, *q = NULL;
5741 struct strlist **lpp;
5749 for (n = half ; --n >= 0 ; ) {
5753 q->next = NULL; /* terminate first half of list */
5754 q = msort(list, half); /* sort first half of list */
5755 p = msort(p, len - half); /* sort second half */
5758 #ifdef CONFIG_LOCALE_SUPPORT
5759 if (strcoll(p->text, q->text) < 0)
5761 if (strcmp(p->text, q->text) < 0)
5766 if ((p = *lpp) == NULL) {
5773 if ((q = *lpp) == NULL) {
5784 * Returns true if the pattern matches the string.
5788 patmatch(char *pattern, const char *string)
5790 return pmatch(preglob(pattern, 0, 0), string);
5795 * Remove any CTLESC characters from a string.
5799 _rmescapes(char *str, int flag)
5802 static const char qchars[] = { CTLESC, CTLQUOTEMARK, 0 };
5807 p = strpbrk(str, qchars);
5813 if (flag & RMESCAPE_ALLOC) {
5814 size_t len = p - str;
5815 size_t fulllen = len + strlen(p) + 1;
5817 if (flag & RMESCAPE_GROW) {
5818 r = makestrspace(fulllen, expdest);
5819 } else if (flag & RMESCAPE_HEAP) {
5820 r = ckmalloc(fulllen);
5822 r = stalloc(fulllen);
5826 q = mempcpy(q, str, len);
5829 inquotes = (flag & RMESCAPE_QUOTED) ^ RMESCAPE_QUOTED;
5830 globbing = flag & RMESCAPE_GLOB;
5831 notescaped = globbing;
5833 if (*p == CTLQUOTEMARK) {
5834 inquotes = ~inquotes;
5836 notescaped = globbing;
5840 /* naked back slash */
5846 if (notescaped && inquotes && *p != '/') {
5850 notescaped = globbing;
5855 if (flag & RMESCAPE_GROW) {
5857 STADJUST(q - r + 1, expdest);
5864 * See if a pattern matches in a case statement.
5868 casematch(union node *pattern, char *val)
5870 struct stackmark smark;
5873 setstackmark(&smark);
5874 argbackq = pattern->narg.backquote;
5875 STARTSTACKSTR(expdest);
5877 argstr(pattern->narg.text, EXP_TILDE | EXP_CASE);
5878 STACKSTRNUL(expdest);
5879 result = patmatch(stackblock(), val);
5880 popstackmark(&smark);
5893 expdest = makestrspace(32, expdest);
5894 len = fmtstr(expdest, 32, "%ld", num);
5895 STADJUST(len, expdest);
5900 varunset(const char *end, const char *var, const char *umsg, int varflags)
5906 msg = "parameter not set";
5908 if (*end == CTLENDVAR) {
5909 if (varflags & VSNUL)
5914 error("%.*s: %s%s", end - var - 1, var, msg, tail);
5918 /* $NetBSD: input.c,v 1.37 2002/11/24 22:35:40 christos Exp $ */
5921 * This implements the input routines used by the parser.
5924 #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
5925 #define IBUFSIZ (BUFSIZ + 1)
5927 static void pushfile(void);
5930 * Read a line from the script.
5933 static inline char *
5934 pfgets(char *line, int len)
5940 while (--nleft > 0) {
5957 * Read a character from the script, returning PEOF on end of file.
5958 * Nul characters in the input are silently discarded.
5961 #define pgetc_as_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
5963 #ifdef CONFIG_ASH_OPTIMIZE_FOR_SIZE
5964 #define pgetc_macro() pgetc()
5968 return pgetc_as_macro();
5971 #define pgetc_macro() pgetc_as_macro()
5975 return pgetc_macro();
5981 * Same as pgetc(), but ignores PEOA.
5983 #ifdef CONFIG_ASH_ALIAS
5984 static int pgetc2(void)
5990 } while (c == PEOA);
5994 static inline int pgetc2(void)
5996 return pgetc_macro();
6001 #ifdef CONFIG_FEATURE_COMMAND_EDITING
6002 static const char *cmdedit_prompt;
6003 static inline void putprompt(const char *s)
6008 static inline void putprompt(const char *s)
6018 char *buf = parsefile->buf;
6022 #ifdef CONFIG_FEATURE_COMMAND_EDITING
6023 if (!iflag || parsefile->fd)
6024 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6026 cmdedit_path_lookup = pathval();
6027 nr = cmdedit_read_input((char *) cmdedit_prompt, buf);
6029 /* Ctrl+C presend */
6039 /* Ctrl+D presend */
6044 nr = safe_read(parsefile->fd, buf, BUFSIZ - 1);
6048 if (parsefile->fd == 0 && errno == EWOULDBLOCK) {
6049 int flags = fcntl(0, F_GETFL, 0);
6050 if (flags >= 0 && flags & O_NONBLOCK) {
6051 flags &=~ O_NONBLOCK;
6052 if (fcntl(0, F_SETFL, flags) >= 0) {
6053 out2str("sh: turning off NDELAY mode\n");
6063 * Refill the input buffer and return the next input character:
6065 * 1) If a string was pushed back on the input, pop it;
6066 * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
6067 * from a string so we can't refill the buffer, return EOF.
6068 * 3) If the is more stuff in this buffer, use it else call read to fill it.
6069 * 4) Process input up to the next newline, deleting nul characters.
6079 while (parsefile->strpush) {
6080 #ifdef CONFIG_ASH_ALIAS
6081 if (parsenleft == -1 && parsefile->strpush->ap &&
6082 parsenextc[-1] != ' ' && parsenextc[-1] != '\t') {
6087 if (--parsenleft >= 0)
6088 return (*parsenextc++);
6090 if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
6095 if (parselleft <= 0) {
6096 if ((parselleft = preadfd()) <= 0) {
6097 parselleft = parsenleft = EOF_NLEFT;
6104 /* delete nul characters */
6105 for (more = 1; more;) {
6112 parsenleft = q - parsenextc;
6113 more = 0; /* Stop processing here */
6120 if (--parselleft <= 0 && more) {
6121 parsenleft = q - parsenextc - 1;
6132 out2str(parsenextc);
6137 return *parsenextc++;
6141 * Undo the last call to pgetc. Only one character may be pushed back.
6142 * PEOF may be pushed back.
6153 * Push a string back onto the input at this current parsefile level.
6154 * We handle aliases this way.
6157 pushstring(char *s, void *ap)
6164 /*dprintf("*** calling pushstring: %s, %d\n", s, len);*/
6165 if (parsefile->strpush) {
6166 sp = ckmalloc(sizeof (struct strpush));
6167 sp->prev = parsefile->strpush;
6168 parsefile->strpush = sp;
6170 sp = parsefile->strpush = &(parsefile->basestrpush);
6171 sp->prevstring = parsenextc;
6172 sp->prevnleft = parsenleft;
6173 #ifdef CONFIG_ASH_ALIAS
6174 sp->ap = (struct alias *)ap;
6176 ((struct alias *)ap)->flag |= ALIASINUSE;
6188 struct strpush *sp = parsefile->strpush;
6191 #ifdef CONFIG_ASH_ALIAS
6193 if (parsenextc[-1] == ' ' || parsenextc[-1] == '\t') {
6194 checkkwd |= CHKALIAS;
6196 if (sp->string != sp->ap->val) {
6199 sp->ap->flag &= ~ALIASINUSE;
6200 if (sp->ap->flag & ALIASDEAD) {
6201 unalias(sp->ap->name);
6205 parsenextc = sp->prevstring;
6206 parsenleft = sp->prevnleft;
6207 /*dprintf("*** calling popstring: restoring to '%s'\n", parsenextc);*/
6208 parsefile->strpush = sp->prev;
6209 if (sp != &(parsefile->basestrpush))
6215 * Set the input to take input from a file. If push is set, push the
6216 * old input onto the stack first.
6220 setinputfile(const char *fname, int push)
6226 if ((fd = open(fname, O_RDONLY)) < 0)
6227 error("Can't open %s", fname);
6229 fd2 = copyfd(fd, 10);
6232 error("Out of file descriptors");
6235 setinputfd(fd, push);
6241 * Like setinputfile, but takes an open file descriptor. Call this with
6246 setinputfd(int fd, int push)
6248 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
6254 if (parsefile->buf == NULL)
6255 parsefile->buf = ckmalloc(IBUFSIZ);
6256 parselleft = parsenleft = 0;
6262 * Like setinputfile, but takes input from a string.
6266 setinputstring(char *string)
6270 parsenextc = string;
6271 parsenleft = strlen(string);
6272 parsefile->buf = NULL;
6279 * To handle the "." command, a stack of input files is used. Pushfile
6280 * adds a new entry to the stack and popfile restores the previous level.
6286 struct parsefile *pf;
6288 parsefile->nleft = parsenleft;
6289 parsefile->lleft = parselleft;
6290 parsefile->nextc = parsenextc;
6291 parsefile->linno = plinno;
6292 pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile));
6293 pf->prev = parsefile;
6296 pf->basestrpush.prev = NULL;
6304 struct parsefile *pf = parsefile;
6313 parsefile = pf->prev;
6315 parsenleft = parsefile->nleft;
6316 parselleft = parsefile->lleft;
6317 parsenextc = parsefile->nextc;
6318 plinno = parsefile->linno;
6324 * Return to top level.
6330 while (parsefile != &basepf)
6336 * Close the file(s) that the shell is reading commands from. Called
6337 * after a fork is done.
6344 if (parsefile->fd > 0) {
6345 close(parsefile->fd);
6350 /* $NetBSD: jobs.c,v 1.56 2002/11/25 12:13:03 agc Exp $ */
6352 /* mode flags for set_curjob */
6353 #define CUR_DELETE 2
6354 #define CUR_RUNNING 1
6355 #define CUR_STOPPED 0
6357 /* mode flags for dowait */
6358 #define DOWAIT_NORMAL 0
6359 #define DOWAIT_BLOCK 1
6362 static struct job *jobtab;
6364 static unsigned njobs;
6366 /* pgrp of shell on invocation */
6367 static int initialpgrp;
6368 static int ttyfd = -1;
6371 static struct job *curjob;
6372 /* number of presumed living untracked jobs */
6375 static void set_curjob(struct job *, unsigned);
6377 static int restartjob(struct job *, int);
6378 static void xtcsetpgrp(int, pid_t);
6379 static char *commandtext(union node *);
6380 static void cmdlist(union node *, int);
6381 static void cmdtxt(union node *);
6382 static void cmdputs(const char *);
6383 static void showpipe(struct job *, FILE *);
6385 static int sprint_status(char *, int, int);
6386 static void freejob(struct job *);
6387 static struct job *getjob(const char *, int);
6388 static struct job *growjobtab(void);
6389 static void forkchild(struct job *, union node *, int);
6390 static void forkparent(struct job *, union node *, int, pid_t);
6391 static int dowait(int, struct job *);
6392 static int getstatus(struct job *);
6395 set_curjob(struct job *jp, unsigned mode)
6398 struct job **jpp, **curp;
6400 /* first remove from list */
6401 jpp = curp = &curjob;
6406 jpp = &jp1->prev_job;
6408 *jpp = jp1->prev_job;
6410 /* Then re-insert in correct position */
6418 /* job being deleted */
6421 /* newly created job or backgrounded job,
6422 put after all stopped jobs. */
6426 if (!jp1 || jp1->state != JOBSTOPPED)
6429 jpp = &jp1->prev_job;
6435 /* newly stopped job - becomes curjob */
6436 jp->prev_job = *jpp;
6444 * Turn job control on and off.
6446 * Note: This code assumes that the third arg to ioctl is a character
6447 * pointer, which is true on Berkeley systems but not System V. Since
6448 * System V doesn't have job control yet, this isn't a problem now.
6450 * Called with interrupts off.
6459 if (on == jobctl || rootshell == 0)
6463 ofd = fd = open(_PATH_TTY, O_RDWR);
6466 while (!isatty(fd) && --fd >= 0)
6469 fd = fcntl(fd, F_DUPFD, 10);
6473 fcntl(fd, F_SETFD, FD_CLOEXEC);
6474 do { /* while we are in the background */
6475 if ((pgrp = tcgetpgrp(fd)) < 0) {
6477 sh_warnx("can't access tty; job control turned off");
6481 if (pgrp == getpgrp())
6492 xtcsetpgrp(fd, pgrp);
6494 /* turning job control off */
6497 xtcsetpgrp(fd, pgrp);
6511 killcmd(int argc, char **argv)
6522 "Usage: kill [-s sigspec | -signum | -sigspec] [pid | job]... or\n"
6523 "kill -l [exitstatus]"
6527 if (**++argv == '-') {
6528 signo = decode_signal(*argv + 1, 1);
6532 while ((c = nextopt("ls:")) != '\0')
6542 signo = decode_signal(optionarg, 1);
6545 "invalid signal number or name: %s",
6556 if (!list && signo < 0)
6559 if ((signo < 0 || !*argv) ^ list) {
6567 for (i = 1; i < NSIG; i++) {
6568 name = u_signal_names(0, &i, 1);
6570 out1fmt(snlfmt, name);
6574 name = u_signal_names(*argptr, &signo, -1);
6576 out1fmt(snlfmt, name);
6578 error("invalid signal number or exit status: %s", *argptr);
6584 if (**argv == '%') {
6585 jp = getjob(*argv, 0);
6586 pid = -jp->ps[0].pid;
6588 pid = number(*argv);
6589 if (kill(pid, signo) != 0) {
6599 #if defined(JOBS) || defined(DEBUG)
6601 jobno(const struct job *jp)
6603 return jp - jobtab + 1;
6609 fgcmd(int argc, char **argv)
6616 mode = (**argv == 'f') ? FORK_FG : FORK_BG;
6621 jp = getjob(*argv, 1);
6622 if (mode == FORK_BG) {
6623 set_curjob(jp, CUR_RUNNING);
6624 fprintf(out, "[%d] ", jobno(jp));
6626 outstr(jp->ps->cmd, out);
6628 retval = restartjob(jp, mode);
6629 } while (*argv && *++argv);
6633 static int bgcmd(int, char **) __attribute__((__alias__("fgcmd")));
6637 restartjob(struct job *jp, int mode)
6639 struct procstat *ps;
6645 if (jp->state == JOBDONE)
6647 jp->state = JOBRUNNING;
6649 if (mode == FORK_FG)
6650 xtcsetpgrp(ttyfd, pgid);
6651 killpg(pgid, SIGCONT);
6655 if (WIFSTOPPED(ps->status)) {
6658 } while (ps++, --i);
6660 status = (mode == FORK_FG) ? waitforjob(jp) : 0;
6667 sprint_status(char *s, int status, int sigonly)
6673 if (!WIFEXITED(status)) {
6675 if (WIFSTOPPED(status))
6676 st = WSTOPSIG(status);
6679 st = WTERMSIG(status);
6681 if (st == SIGINT || st == SIGPIPE)
6684 if (WIFSTOPPED(status))
6689 col = fmtstr(s, 32, strsignal(st));
6690 if (WCOREDUMP(status)) {
6691 col += fmtstr(s + col, 16, " (core dumped)");
6693 } else if (!sigonly) {
6694 st = WEXITSTATUS(status);
6696 col = fmtstr(s, 16, "Done(%d)", st);
6698 col = fmtstr(s, 16, "Done");
6707 showjob(FILE *out, struct job *jp, int mode)
6709 struct procstat *ps;
6710 struct procstat *psend;
6717 if (mode & SHOW_PGID) {
6718 /* just output process (group) id of pipeline */
6719 fprintf(out, "%d\n", ps->pid);
6723 col = fmtstr(s, 16, "[%d] ", jobno(jp));
6728 else if (curjob && jp == curjob->prev_job)
6731 if (mode & SHOW_PID)
6732 col += fmtstr(s + col, 16, "%d ", ps->pid);
6734 psend = ps + jp->nprocs;
6736 if (jp->state == JOBRUNNING) {
6737 scopy("Running", s + col);
6738 col += strlen("Running");
6740 int status = psend[-1].status;
6742 if (jp->state == JOBSTOPPED)
6743 status = jp->stopstatus;
6745 col += sprint_status(s + col, status, 0);
6751 /* for each process */
6752 col = fmtstr(s, 48, " |\n%*c%d ", indent, ' ', ps->pid) - 3;
6755 fprintf(out, "%s%*c%s",
6756 s, 33 - col >= 0 ? 33 - col : 0, ' ', ps->cmd
6758 if (!(mode & SHOW_PID)) {
6762 if (++ps == psend) {
6763 outcslow('\n', out);
6770 if (jp->state == JOBDONE) {
6771 TRACE(("showjob: freeing job %d\n", jobno(jp)));
6778 jobscmd(int argc, char **argv)
6784 while ((m = nextopt("lp")))
6794 showjob(out, getjob(*argv,0), mode);
6797 showjobs(out, mode);
6804 * Print a list of jobs. If "change" is nonzero, only print jobs whose
6805 * statuses have changed since the last call to showjobs.
6809 showjobs(FILE *out, int mode)
6813 TRACE(("showjobs(%x) called\n", mode));
6815 /* If not even one one job changed, there is nothing to do */
6816 while (dowait(DOWAIT_NORMAL, NULL) > 0)
6819 for (jp = curjob; jp; jp = jp->prev_job) {
6820 if (!(mode & SHOW_CHANGED) || jp->changed)
6821 showjob(out, jp, mode);
6827 * Mark a job structure as unused.
6831 freejob(struct job *jp)
6833 struct procstat *ps;
6837 for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
6838 if (ps->cmd != nullstr)
6841 if (jp->ps != &jp->ps0)
6844 set_curjob(jp, CUR_DELETE);
6850 waitcmd(int argc, char **argv)
6863 /* wait for all jobs */
6868 /* no running procs */
6871 if (jp->state == JOBRUNNING)
6876 dowait(DOWAIT_BLOCK, 0);
6882 if (**argv != '%') {
6883 pid_t pid = number(*argv);
6887 if (job->ps[job->nprocs - 1].pid == pid)
6889 job = job->prev_job;
6895 job = getjob(*argv, 0);
6896 /* loop until process terminated or stopped */
6897 while (job->state == JOBRUNNING)
6898 dowait(DOWAIT_BLOCK, 0);
6900 retval = getstatus(job);
6911 * Convert a job name to a job structure.
6915 getjob(const char *name, int getctl)
6919 const char *err_msg = "No such job: %s";
6923 char *(*match)(const char *, const char *);
6938 if (c == '+' || c == '%') {
6940 err_msg = "No current job";
6942 } else if (c == '-') {
6945 err_msg = "No previous job";
6956 jp = jobtab + num - 1;
6973 if (match(jp->ps[0].cmd, p)) {
6977 err_msg = "%s: ambiguous";
6984 err_msg = "job %s not created under job control";
6985 if (getctl && jp->jobctl == 0)
6990 error(err_msg, name);
6995 * Return a new job structure.
6996 * Called with interrupts off.
7000 makejob(union node *node, int nprocs)
7005 for (i = njobs, jp = jobtab ; ; jp++) {
7012 if (jp->state != JOBDONE || !jp->waited)
7021 memset(jp, 0, sizeof(*jp));
7026 jp->prev_job = curjob;
7031 jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
7033 TRACE(("makejob(0x%lx, %d) returns %%%d\n", (long)node, nprocs,
7043 struct job *jp, *jq;
7045 len = njobs * sizeof(*jp);
7047 jp = ckrealloc(jq, len + 4 * sizeof(*jp));
7049 offset = (char *)jp - (char *)jq;
7051 /* Relocate pointers */
7054 jq = (struct job *)((char *)jq + l);
7058 #define joff(p) ((struct job *)((char *)(p) + l))
7059 #define jmove(p) (p) = (void *)((char *)(p) + offset)
7060 if (likely(joff(jp)->ps == &jq->ps0))
7061 jmove(joff(jp)->ps);
7062 if (joff(jp)->prev_job)
7063 jmove(joff(jp)->prev_job);
7073 jp = (struct job *)((char *)jp + len);
7077 } while (--jq >= jp);
7083 * Fork off a subshell. If we are doing job control, give the subshell its
7084 * own process group. Jp is a job structure that the job is to be added to.
7085 * N is the command that will be evaluated by the child. Both jp and n may
7086 * be NULL. The mode parameter can be one of the following:
7087 * FORK_FG - Fork off a foreground process.
7088 * FORK_BG - Fork off a background process.
7089 * FORK_NOJOB - Like FORK_FG, but don't give the process its own
7090 * process group even if job control is on.
7092 * When job control is turned off, background processes have their standard
7093 * input redirected to /dev/null (except for the second and later processes
7096 * Called with interrupts off.
7100 forkchild(struct job *jp, union node *n, int mode)
7104 TRACE(("Child shell %d\n", getpid()));
7105 wasroot = rootshell;
7111 /* do job control only in root shell */
7113 if (mode != FORK_NOJOB && jp->jobctl && wasroot) {
7116 if (jp->nprocs == 0)
7119 pgrp = jp->ps[0].pid;
7120 /* This can fail because we are doing it in the parent also */
7121 (void)setpgid(0, pgrp);
7122 if (mode == FORK_FG)
7123 xtcsetpgrp(ttyfd, pgrp);
7128 if (mode == FORK_BG) {
7131 if (jp->nprocs == 0) {
7133 if (open(_PATH_DEVNULL, O_RDONLY) != 0)
7134 error("Can't open %s", _PATH_DEVNULL);
7137 if (wasroot && iflag) {
7142 for (jp = curjob; jp; jp = jp->prev_job)
7148 forkparent(struct job *jp, union node *n, int mode, pid_t pid)
7150 TRACE(("In parent shell: child = %d\n", pid));
7152 while (jobless && dowait(DOWAIT_NORMAL, 0) > 0);
7157 if (mode != FORK_NOJOB && jp->jobctl) {
7160 if (jp->nprocs == 0)
7163 pgrp = jp->ps[0].pid;
7164 /* This can fail because we are doing it in the child also */
7165 (void)setpgid(pid, pgrp);
7168 if (mode == FORK_BG) {
7169 backgndpid = pid; /* set $! */
7170 set_curjob(jp, CUR_RUNNING);
7173 struct procstat *ps = &jp->ps[jp->nprocs++];
7179 ps->cmd = commandtext(n);
7185 forkshell(struct job *jp, union node *n, int mode)
7189 TRACE(("forkshell(%%%d, %p, %d) called\n", jobno(jp), n, mode));
7192 TRACE(("Fork failed, errno=%d", errno));
7195 error("Cannot fork");
7198 forkchild(jp, n, mode);
7200 forkparent(jp, n, mode, pid);
7205 * Wait for job to finish.
7207 * Under job control we have the problem that while a child process is
7208 * running interrupts generated by the user are sent to the child but not
7209 * to the shell. This means that an infinite loop started by an inter-
7210 * active user may be hard to kill. With job control turned off, an
7211 * interactive user may place an interactive program inside a loop. If
7212 * the interactive program catches interrupts, the user doesn't want
7213 * these interrupts to also abort the loop. The approach we take here
7214 * is to have the shell ignore interrupt signals while waiting for a
7215 * forground process to terminate, and then send itself an interrupt
7216 * signal if the child process was terminated by an interrupt signal.
7217 * Unfortunately, some programs want to do a bit of cleanup and then
7218 * exit on interrupt; unless these processes terminate themselves by
7219 * sending a signal to themselves (instead of calling exit) they will
7220 * confuse this approach.
7222 * Called with interrupts off.
7226 waitforjob(struct job *jp)
7230 TRACE(("waitforjob(%%%d) called\n", jobno(jp)));
7231 while (jp->state == JOBRUNNING) {
7232 dowait(DOWAIT_BLOCK, jp);
7237 xtcsetpgrp(ttyfd, rootpid);
7239 * This is truly gross.
7240 * If we're doing job control, then we did a TIOCSPGRP which
7241 * caused us (the shell) to no longer be in the controlling
7242 * session -- so we wouldn't have seen any ^C/SIGINT. So, we
7243 * intuit from the subprocess exit status whether a SIGINT
7244 * occurred, and if so interrupt ourselves. Yuck. - mycroft
7249 if (jp->state == JOBDONE)
7257 * Do a wait system call. If job control is compiled in, we accept
7258 * stopped processes. If block is zero, we return a value of zero
7259 * rather than blocking.
7261 * System V doesn't have a non-blocking wait system call. It does
7262 * have a SIGCLD signal that is sent to a process when one of it's
7263 * children dies. The obvious way to use SIGCLD would be to install
7264 * a handler for SIGCLD which simply bumped a counter when a SIGCLD
7265 * was received, and have waitproc bump another counter when it got
7266 * the status of a process. Waitproc would then know that a wait
7267 * system call would not block if the two counters were different.
7268 * This approach doesn't work because if a process has children that
7269 * have not been waited for, System V will send it a SIGCLD when it
7270 * installs a signal handler for SIGCLD. What this means is that when
7271 * a child exits, the shell will be sent SIGCLD signals continuously
7272 * until is runs out of stack space, unless it does a wait call before
7273 * restoring the signal handler. The code below takes advantage of
7274 * this (mis)feature by installing a signal handler for SIGCLD and
7275 * then checking to see whether it was called. If there are any
7276 * children to be waited for, it will be.
7278 * If neither SYSV nor BSD is defined, we don't implement nonblocking
7279 * waits at all. In this case, the user will not be informed when
7280 * a background process until the next time she runs a real program
7281 * (as opposed to running a builtin command or just typing return),
7282 * and the jobs command may give out of date information.
7286 waitproc(int block, int *status)
7296 return wait3(status, flags, (struct rusage *)NULL);
7300 * Wait for a process to terminate.
7304 dowait(int block, struct job *job)
7309 struct job *thisjob;
7312 TRACE(("dowait(%d) called\n", block));
7313 pid = waitproc(block, &status);
7314 TRACE(("wait returns pid %d, status=%d\n", pid, status));
7319 for (jp = curjob; jp; jp = jp->prev_job) {
7320 struct procstat *sp;
7321 struct procstat *spend;
7322 if (jp->state == JOBDONE)
7325 spend = jp->ps + jp->nprocs;
7328 if (sp->pid == pid) {
7329 TRACE(("Job %d: changing status of proc %d from 0x%x to 0x%x\n", jobno(jp), pid, sp->status, status));
7330 sp->status = status;
7333 if (sp->status == -1)
7336 if (state == JOBRUNNING)
7338 if (WIFSTOPPED(sp->status)) {
7339 jp->stopstatus = sp->status;
7343 } while (++sp < spend);
7348 if (!WIFSTOPPED(status))
7355 if (state != JOBRUNNING) {
7356 thisjob->changed = 1;
7358 if (thisjob->state != state) {
7359 TRACE(("Job %d: changing state from %d to %d\n", jobno(thisjob), thisjob->state, state));
7360 thisjob->state = state;
7362 if (state == JOBSTOPPED) {
7363 set_curjob(thisjob, CUR_STOPPED);
7372 if (thisjob && thisjob == job) {
7376 len = sprint_status(s, status, 1);
7388 * return 1 if there are stopped jobs, otherwise 0
7401 if (jp && jp->state == JOBSTOPPED) {
7402 out2str("You have stopped jobs.\n");
7412 * Return a string identifying a command (to be printed by the
7417 static char *cmdnextc;
7420 commandtext(union node *n)
7424 STARTSTACKSTR(cmdnextc);
7426 name = stackblock();
7427 TRACE(("commandtext: name %p, end %p\n\t\"%s\"\n",
7428 name, cmdnextc, cmdnextc));
7429 return savestr(name);
7433 cmdtxt(union node *n)
7436 struct nodelist *lp;
7448 lp = n->npipe.cmdlist;
7466 cmdtxt(n->nbinary.ch1);
7482 cmdtxt(n->nif.test);
7485 if (n->nif.elsepart) {
7488 n = n->nif.elsepart;
7504 cmdtxt(n->nbinary.ch1);
7514 cmdputs(n->nfor.var);
7516 cmdlist(n->nfor.args, 1);
7521 cmdputs(n->narg.text);
7525 cmdlist(n->ncmd.args, 1);
7526 cmdlist(n->ncmd.redirect, 0);
7539 cmdputs(n->ncase.expr->narg.text);
7541 for (np = n->ncase.cases; np; np = np->nclist.next) {
7542 cmdtxt(np->nclist.pattern);
7544 cmdtxt(np->nclist.body);
7570 s[0] = n->nfile.fd + '0';
7574 if (n->type == NTOFD || n->type == NFROMFD) {
7575 s[0] = n->ndup.dupfd + '0';
7586 cmdlist(union node *np, int sep)
7588 for (; np; np = np->narg.next) {
7592 if (sep && np->narg.next)
7598 cmdputs(const char *s)
7600 const char *p, *str;
7601 char c, cc[2] = " ";
7605 static const char *const vstype[16] = {
7606 nullstr, "}", "-", "+", "?", "=",
7607 "%", "%%", "#", "##", nullstr
7610 nextc = makestrspace((strlen(s) + 1) * 8, cmdnextc);
7612 while ((c = *p++) != 0) {
7620 if ((subtype & VSTYPE) == VSLENGTH)
7624 if (!(subtype & VSQUOTE) != !(quoted & 1)) {
7642 case CTLBACKQ+CTLQUOTE:
7645 #ifdef CONFIG_ASH_MATH_SUPPORT
7660 str = vstype[subtype & VSTYPE];
7661 if (subtype & VSNUL)
7672 /* These can only happen inside quotes */
7684 while ((c = *str++)) {
7689 USTPUTC('"', nextc);
7697 showpipe(struct job *jp, FILE *out)
7699 struct procstat *sp;
7700 struct procstat *spend;
7702 spend = jp->ps + jp->nprocs;
7703 for (sp = jp->ps + 1; sp < spend; sp++)
7704 fprintf(out, " | %s", sp->cmd);
7705 outcslow('\n', out);
7710 xtcsetpgrp(int fd, pid_t pgrp)
7712 if (tcsetpgrp(fd, pgrp))
7713 error("Cannot set tty process group (%m)");
7718 getstatus(struct job *job) {
7722 status = job->ps[job->nprocs - 1].status;
7723 retval = WEXITSTATUS(status);
7724 if (!WIFEXITED(status)) {
7726 retval = WSTOPSIG(status);
7727 if (!WIFSTOPPED(status))
7730 /* XXX: limits number of signals */
7731 retval = WTERMSIG(status);
7733 if (retval == SIGINT)
7739 TRACE(("getstatus: job %d, nproc %d, status %x, retval %x\n",
7740 jobno(job), job->nprocs, status, retval));
7744 #ifdef CONFIG_ASH_MAIL
7745 /* $NetBSD: mail.c,v 1.15 2002/11/24 22:35:40 christos Exp $ */
7748 * Routines to check for mail. (Perhaps make part of main.c?)
7751 #define MAXMBOXES 10
7753 /* times of mailboxes */
7754 static time_t mailtime[MAXMBOXES];
7755 /* Set if MAIL or MAILPATH is changed. */
7756 static int mail_var_path_changed;
7761 * Print appropriate message(s) if mail has arrived.
7762 * If mail_var_path_changed is set,
7763 * then the value of MAIL has mail_var_path_changed,
7764 * so we just update the values.
7774 struct stackmark smark;
7777 setstackmark(&smark);
7778 mpath = mpathset() ? mpathval() : mailval();
7779 for (mtp = mailtime; mtp < mailtime + MAXMBOXES; mtp++) {
7780 p = padvance(&mpath, nullstr);
7785 for (q = p ; *q ; q++);
7790 q[-1] = '\0'; /* delete trailing '/' */
7791 if (stat(p, &statb) < 0) {
7795 if (!mail_var_path_changed && statb.st_mtime != *mtp) {
7798 pathopt ? pathopt : "you have mail"
7801 *mtp = statb.st_mtime;
7803 mail_var_path_changed = 0;
7804 popstackmark(&smark);
7809 changemail(const char *val)
7811 mail_var_path_changed++;
7814 #endif /* CONFIG_ASH_MAIL */
7816 /* $NetBSD: main.c,v 1.46 2002/12/11 19:12:18 christos Exp $ */
7820 static short profile_buf[16384];
7824 static int isloginsh;
7826 static void read_profile(const char *);
7829 * Main routine. We initialize things, parse the arguments, execute
7830 * profiles if we're a login shell, and then call cmdloop to execute
7831 * commands. The setjmp call sets up the location to jump to when an
7832 * exception occurs. When an exception occurs the variable "state"
7833 * is used to figure out how far we had gotten.
7837 ash_main(int argc, char **argv)
7841 struct jmploc jmploc;
7842 struct stackmark smark;
7845 dash_errno = __errno_location();
7849 monitor(4, etext, profile_buf, sizeof profile_buf, 50);
7852 if (setjmp(jmploc.loc)) {
7859 switch (exception) {
7869 status = exitstatus;
7872 exitstatus = status;
7874 if (e == EXEXIT || state == 0 || iflag == 0 || ! rootshell)
7878 outcslow('\n', stderr);
7880 popstackmark(&smark);
7881 FORCEINTON; /* enable interrupts */
7884 else if (state == 2)
7886 else if (state == 3)
7894 trputs("Shell args: "); trargs(argv);
7899 setstackmark(&smark);
7900 procargs(argc, argv);
7901 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7903 const char *hp = lookupvar("HISTFILE");
7906 hp = lookupvar("HOME");
7908 char *defhp = concat_path_file(hp, ".ash_history");
7909 setvar("HISTFILE", defhp, 0);
7915 if (argv[0] && argv[0][0] == '-')
7919 read_profile("/etc/profile");
7922 read_profile(".profile");
7928 getuid() == geteuid() && getgid() == getegid() &&
7932 if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
7933 read_profile(shinit);
7941 if (sflag || minusc == NULL) {
7942 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
7944 const char *hp = lookupvar("HISTFILE");
7947 load_history ( hp );
7950 state4: /* XXX ??? - why isn't this before the "if" statement */
7958 extern void _mcleanup(void);
7968 * Read and execute commands. "Top" is nonzero for the top level command
7969 * loop; it turns on prompting if the shell is interactive.
7976 struct stackmark smark;
7980 TRACE(("cmdloop(%d) called\n", top));
7982 setstackmark(&smark);
7987 showjobs(stderr, SHOW_CHANGED);
7992 #ifdef CONFIG_ASH_MAIL
7996 n = parsecmd(inter);
7997 /* showtree(n); DEBUG */
7999 if (!top || numeof >= 50)
8001 if (!stoppedjobs()) {
8004 out2str("\nUse \"exit\" to leave shell.\n");
8007 } else if (n != NULL && nflag == 0) {
8008 job_warning = (job_warning == 2) ? 1 : 0;
8012 popstackmark(&smark);
8022 * Read /etc/profile or .profile. Return on error.
8026 read_profile(const char *name)
8033 if ((fd = open(name, O_RDONLY)) >= 0)
8038 /* -q turns off -x and -v just when executing init files */
8041 xflag = 0, xflag_set = 1;
8043 vflag = 0, vflag_set = 1;
8057 * Read a file containing shell functions.
8061 readcmdfile(char *name)
8066 if ((fd = open(name, O_RDONLY)) >= 0)
8069 error("Can't open %s", name);
8077 * Take commands from a file. To be compatible we should do a path
8078 * search for the file, which is necessary to find sub-commands.
8081 static inline char *
8082 find_dot_file(char *name)
8085 const char *path = pathval();
8088 /* don't try this for absolute or relative paths */
8089 if (strchr(name, '/'))
8092 while ((fullname = padvance(&path, name)) != NULL) {
8093 if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
8095 * Don't bother freeing here, since it will
8096 * be freed by the caller.
8100 stunalloc(fullname);
8103 /* not found in the PATH */
8104 error(not_found_msg, name);
8109 dotcmd(int argc, char **argv)
8113 if (argc >= 2) { /* That's what SVR2 does */
8115 struct stackmark smark;
8117 setstackmark(&smark);
8118 fullname = find_dot_file(argv[1]);
8119 setinputfile(fullname, 1);
8120 commandname = fullname;
8123 popstackmark(&smark);
8130 exitcmd(int argc, char **argv)
8135 exitstatus = number(argv[1]);
8140 /* $NetBSD: memalloc.c,v 1.27 2003/01/22 20:36:04 dsl Exp $ */
8143 * Same for malloc, realloc, but returns an error when out of space.
8147 ckrealloc(pointer p, size_t nbytes)
8149 p = realloc(p, nbytes);
8151 error(bb_msg_memory_exhausted);
8156 ckmalloc(size_t nbytes)
8158 return ckrealloc(NULL, nbytes);
8162 * Make a copy of a string in safe storage.
8166 savestr(const char *s)
8168 char *p = strdup(s);
8170 error(bb_msg_memory_exhausted);
8176 * Parse trees for commands are allocated in lifo order, so we use a stack
8177 * to make this more efficient, and also to avoid all sorts of exception
8178 * handling code to handle interrupts in the middle of a parse.
8180 * The size 504 was chosen because the Ultrix malloc handles that size
8186 stalloc(size_t nbytes)
8191 aligned = SHELL_ALIGN(nbytes);
8192 if (aligned > stacknleft) {
8195 struct stack_block *sp;
8197 blocksize = aligned;
8198 if (blocksize < MINSIZE)
8199 blocksize = MINSIZE;
8200 len = sizeof(struct stack_block) - MINSIZE + blocksize;
8201 if (len < blocksize)
8202 error(bb_msg_memory_exhausted);
8206 stacknxt = sp->space;
8207 stacknleft = blocksize;
8208 sstrend = stacknxt + blocksize;
8213 stacknxt += aligned;
8214 stacknleft -= aligned;
8220 stunalloc(pointer p)
8223 if (!p || (stacknxt < (char *)p) || ((char *)p < stackp->space)) {
8224 write(2, "stunalloc\n", 10);
8228 stacknleft += stacknxt - (char *)p;
8234 setstackmark(struct stackmark *mark)
8236 mark->stackp = stackp;
8237 mark->stacknxt = stacknxt;
8238 mark->stacknleft = stacknleft;
8239 mark->marknext = markp;
8245 popstackmark(struct stackmark *mark)
8247 struct stack_block *sp;
8250 markp = mark->marknext;
8251 while (stackp != mark->stackp) {
8256 stacknxt = mark->stacknxt;
8257 stacknleft = mark->stacknleft;
8258 sstrend = mark->stacknxt + mark->stacknleft;
8264 * When the parser reads in a string, it wants to stick the string on the
8265 * stack and only adjust the stack pointer when it knows how big the
8266 * string is. Stackblock (defined in stack.h) returns a pointer to a block
8267 * of space on top of the stack and stackblocklen returns the length of
8268 * this block. Growstackblock will grow this space by at least one byte,
8269 * possibly moving it (like realloc). Grabstackblock actually allocates the
8270 * part of the block that has been used.
8274 growstackblock(void)
8278 newlen = stacknleft * 2;
8279 if (newlen < stacknleft)
8280 error(bb_msg_memory_exhausted);
8284 if (stacknxt == stackp->space && stackp != &stackbase) {
8285 struct stack_block *oldstackp;
8286 struct stackmark *xmark;
8287 struct stack_block *sp;
8288 struct stack_block *prevstackp;
8294 prevstackp = sp->prev;
8295 grosslen = newlen + sizeof(struct stack_block) - MINSIZE;
8296 sp = ckrealloc((pointer)sp, grosslen);
8297 sp->prev = prevstackp;
8299 stacknxt = sp->space;
8300 stacknleft = newlen;
8301 sstrend = sp->space + newlen;
8304 * Stack marks pointing to the start of the old block
8305 * must be relocated to point to the new block
8308 while (xmark != NULL && xmark->stackp == oldstackp) {
8309 xmark->stackp = stackp;
8310 xmark->stacknxt = stacknxt;
8311 xmark->stacknleft = stacknleft;
8312 xmark = xmark->marknext;
8316 char *oldspace = stacknxt;
8317 int oldlen = stacknleft;
8318 char *p = stalloc(newlen);
8320 /* free the space we just allocated */
8321 stacknxt = memcpy(p, oldspace, oldlen);
8322 stacknleft += newlen;
8327 grabstackblock(size_t len)
8329 len = SHELL_ALIGN(len);
8335 * The following routines are somewhat easier to use than the above.
8336 * The user declares a variable of type STACKSTR, which may be declared
8337 * to be a register. The macro STARTSTACKSTR initializes things. Then
8338 * the user uses the macro STPUTC to add characters to the string. In
8339 * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
8340 * grown as necessary. When the user is done, she can just leave the
8341 * string there and refer to it using stackblock(). Or she can allocate
8342 * the space for it using grabstackstr(). If it is necessary to allow
8343 * someone else to use the stack temporarily and then continue to grow
8344 * the string, the user should use grabstack to allocate the space, and
8345 * then call ungrabstr(p) to return to the previous mode of operation.
8347 * USTPUTC is like STPUTC except that it doesn't check for overflow.
8348 * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
8349 * is space for at least one character.
8355 size_t len = stackblocksize();
8356 if (herefd >= 0 && len >= 1024) {
8357 xwrite(herefd, stackblock(), len);
8358 return stackblock();
8361 return stackblock() + len;
8365 * Called from CHECKSTRSPACE.
8369 makestrspace(size_t newlen, char *p)
8371 size_t len = p - stacknxt;
8372 size_t size = stackblocksize();
8377 size = stackblocksize();
8379 if (nleft >= newlen)
8383 return stackblock() + len;
8387 stnputs(const char *s, size_t n, char *p)
8389 p = makestrspace(n, p);
8390 p = mempcpy(p, s, n);
8395 stputs(const char *s, char *p)
8397 return stnputs(s, strlen(s), p);
8400 /* $NetBSD: mystring.c,v 1.15 2002/11/24 22:35:42 christos Exp $ */
8405 * number(s) Convert a string of digits to an integer.
8406 * is_number(s) Return true if s is a string of digits.
8410 * prefix -- see if pfx is a prefix of string.
8414 prefix(const char *string, const char *pfx)
8417 if (*pfx++ != *string++)
8420 return (char *) string;
8425 * Convert a string of digits to an integer, printing an error message on
8430 number(const char *s)
8440 * Check for a valid number. This should be elsewhere.
8444 is_number(const char *p)
8449 } while (*++p != '\0');
8455 * Produce a possibly single quoted string suitable as input to the shell.
8456 * The return string is allocated on the stack.
8460 single_quote(const char *s) {
8469 len = strchrnul(s, '\'') - s;
8471 q = p = makestrspace(len + 3, p);
8474 q = mempcpy(q, s, len);
8480 len = strspn(s, "'");
8484 q = p = makestrspace(len + 3, p);
8487 q = mempcpy(q, s, len);
8496 return stackblock();
8500 * Like strdup but works with the ash stack.
8504 sstrdup(const char *p)
8506 size_t len = strlen(p) + 1;
8507 return memcpy(stalloc(len), p, len);
8512 calcsize(union node *n)
8516 funcblocksize += nodesize[n->type];
8519 calcsize(n->ncmd.redirect);
8520 calcsize(n->ncmd.args);
8521 calcsize(n->ncmd.assign);
8524 sizenodelist(n->npipe.cmdlist);
8529 calcsize(n->nredir.redirect);
8530 calcsize(n->nredir.n);
8537 calcsize(n->nbinary.ch2);
8538 calcsize(n->nbinary.ch1);
8541 calcsize(n->nif.elsepart);
8542 calcsize(n->nif.ifpart);
8543 calcsize(n->nif.test);
8546 funcstringsize += strlen(n->nfor.var) + 1;
8547 calcsize(n->nfor.body);
8548 calcsize(n->nfor.args);
8551 calcsize(n->ncase.cases);
8552 calcsize(n->ncase.expr);
8555 calcsize(n->nclist.body);
8556 calcsize(n->nclist.pattern);
8557 calcsize(n->nclist.next);
8561 sizenodelist(n->narg.backquote);
8562 funcstringsize += strlen(n->narg.text) + 1;
8563 calcsize(n->narg.next);
8570 calcsize(n->nfile.fname);
8571 calcsize(n->nfile.next);
8575 calcsize(n->ndup.vname);
8576 calcsize(n->ndup.next);
8580 calcsize(n->nhere.doc);
8581 calcsize(n->nhere.next);
8584 calcsize(n->nnot.com);
8591 sizenodelist(struct nodelist *lp)
8594 funcblocksize += SHELL_ALIGN(sizeof(struct nodelist));
8602 copynode(union node *n)
8609 funcblock = (char *) funcblock + nodesize[n->type];
8612 new->ncmd.redirect = copynode(n->ncmd.redirect);
8613 new->ncmd.args = copynode(n->ncmd.args);
8614 new->ncmd.assign = copynode(n->ncmd.assign);
8617 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
8618 new->npipe.backgnd = n->npipe.backgnd;
8623 new->nredir.redirect = copynode(n->nredir.redirect);
8624 new->nredir.n = copynode(n->nredir.n);
8631 new->nbinary.ch2 = copynode(n->nbinary.ch2);
8632 new->nbinary.ch1 = copynode(n->nbinary.ch1);
8635 new->nif.elsepart = copynode(n->nif.elsepart);
8636 new->nif.ifpart = copynode(n->nif.ifpart);
8637 new->nif.test = copynode(n->nif.test);
8640 new->nfor.var = nodesavestr(n->nfor.var);
8641 new->nfor.body = copynode(n->nfor.body);
8642 new->nfor.args = copynode(n->nfor.args);
8645 new->ncase.cases = copynode(n->ncase.cases);
8646 new->ncase.expr = copynode(n->ncase.expr);
8649 new->nclist.body = copynode(n->nclist.body);
8650 new->nclist.pattern = copynode(n->nclist.pattern);
8651 new->nclist.next = copynode(n->nclist.next);
8655 new->narg.backquote = copynodelist(n->narg.backquote);
8656 new->narg.text = nodesavestr(n->narg.text);
8657 new->narg.next = copynode(n->narg.next);
8664 new->nfile.fname = copynode(n->nfile.fname);
8665 new->nfile.fd = n->nfile.fd;
8666 new->nfile.next = copynode(n->nfile.next);
8670 new->ndup.vname = copynode(n->ndup.vname);
8671 new->ndup.dupfd = n->ndup.dupfd;
8672 new->ndup.fd = n->ndup.fd;
8673 new->ndup.next = copynode(n->ndup.next);
8677 new->nhere.doc = copynode(n->nhere.doc);
8678 new->nhere.fd = n->nhere.fd;
8679 new->nhere.next = copynode(n->nhere.next);
8682 new->nnot.com = copynode(n->nnot.com);
8685 new->type = n->type;
8690 static struct nodelist *
8691 copynodelist(struct nodelist *lp)
8693 struct nodelist *start;
8694 struct nodelist **lpp;
8699 funcblock = (char *) funcblock +
8700 SHELL_ALIGN(sizeof(struct nodelist));
8701 (*lpp)->n = copynode(lp->n);
8703 lpp = &(*lpp)->next;
8711 nodesavestr(char *s)
8713 char *rtn = funcstring;
8715 funcstring = stpcpy(funcstring, s) + 1;
8721 * Free a parse tree.
8725 freefunc(struct funcnode *f)
8727 if (f && --f->count < 0)
8732 static void options(int);
8733 static void setoption(int, int);
8737 * Process the shell command line arguments.
8741 procargs(int argc, char **argv)
8744 const char *xminusc;
8751 for (i = 0; i < NOPTS; i++)
8757 if (*xargv == NULL) {
8759 error("-c requires an argument");
8762 if (iflag == 2 && sflag == 1 && isatty(0) && isatty(1))
8766 for (i = 0; i < NOPTS; i++)
8767 if (optlist[i] == 2)
8772 /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
8777 } else if (!sflag) {
8778 setinputfile(*xargv, 0);
8784 shellparam.p = xargv;
8785 #ifdef CONFIG_ASH_GETOPTS
8786 shellparam.optind = 1;
8787 shellparam.optoff = -1;
8789 /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
8791 shellparam.nparam++;
8804 setinteractive(iflag);
8809 minus_o(char *name, int val)
8814 out1str("Current option settings\n");
8815 for (i = 0; i < NOPTS; i++)
8816 out1fmt("%-16s%s\n", optnames(i),
8817 optlist[i] ? "on" : "off");
8819 for (i = 0; i < NOPTS; i++)
8820 if (equal(name, optnames(i))) {
8824 error("Illegal option -o %s", name);
8829 * Process shell options. The global variable argptr contains a pointer
8830 * to the argument list; we advance it past the options.
8834 options(int cmdline)
8842 while ((p = *argptr) != NULL) {
8844 if ((c = *p++) == '-') {
8846 if (p[0] == '\0' || (p[0] == '-' && p[1] == '\0')) {
8848 /* "-" means turn off -x and -v */
8851 /* "--" means reset params */
8852 else if (*argptr == NULL)
8855 break; /* "-" or "--" terminates options */
8857 } else if (c == '+') {
8863 while ((c = *p++) != '\0') {
8864 if (c == 'c' && cmdline) {
8865 minusc = p; /* command is after shell args*/
8866 } else if (c == 'o') {
8867 minus_o(*argptr, val);
8870 } else if (cmdline && (c == '-')) { // long options
8871 if (strcmp(p, "login") == 0)
8883 setoption(int flag, int val)
8887 for (i = 0; i < NOPTS; i++)
8888 if (optletters(i) == flag) {
8892 error("Illegal option -%c", flag);
8899 * Set the shell parameters.
8903 setparam(char **argv)
8909 for (nparam = 0 ; argv[nparam] ; nparam++);
8910 ap = newparam = ckmalloc((nparam + 1) * sizeof *ap);
8912 *ap++ = savestr(*argv++);
8915 freeparam(&shellparam);
8916 shellparam.malloc = 1;
8917 shellparam.nparam = nparam;
8918 shellparam.p = newparam;
8919 #ifdef CONFIG_ASH_GETOPTS
8920 shellparam.optind = 1;
8921 shellparam.optoff = -1;
8927 * Free the list of positional parameters.
8931 freeparam(volatile struct shparam *param)
8935 if (param->malloc) {
8936 for (ap = param->p ; *ap ; ap++)
8945 * The shift builtin command.
8949 shiftcmd(int argc, char **argv)
8956 n = number(argv[1]);
8957 if (n > shellparam.nparam)
8958 error("can't shift that many");
8960 shellparam.nparam -= n;
8961 for (ap1 = shellparam.p ; --n >= 0 ; ap1++) {
8962 if (shellparam.malloc)
8966 while ((*ap2++ = *ap1++) != NULL);
8967 #ifdef CONFIG_ASH_GETOPTS
8968 shellparam.optind = 1;
8969 shellparam.optoff = -1;
8978 * The set command builtin.
8982 setcmd(int argc, char **argv)
8985 return showvars(nullstr, 0, VUNSET);
8989 if (*argptr != NULL) {
8997 #ifdef CONFIG_ASH_GETOPTS
9002 shellparam.optind = number(value);
9003 shellparam.optoff = -1;
9007 #ifdef CONFIG_LOCALE_SUPPORT
9008 static void change_lc_all(const char *value)
9010 if (value != 0 && *value != 0)
9011 setlocale(LC_ALL, value);
9014 static void change_lc_ctype(const char *value)
9016 if (value != 0 && *value != 0)
9017 setlocale(LC_CTYPE, value);
9022 #ifdef CONFIG_ASH_GETOPTS
9024 getopts(char *optstr, char *optvar, char **optfirst, int *param_optind, int *optoff)
9033 if(*param_optind < 1)
9035 optnext = optfirst + *param_optind - 1;
9037 if (*param_optind <= 1 || *optoff < 0 || strlen(optnext[-1]) < *optoff)
9040 p = optnext[-1] + *optoff;
9041 if (p == NULL || *p == '\0') {
9042 /* Current word is done, advance */
9044 if (p == NULL || *p != '-' || *++p == '\0') {
9051 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9056 for (q = optstr; *q != c; ) {
9058 if (optstr[0] == ':') {
9061 err |= setvarsafe("OPTARG", s, 0);
9063 fprintf(stderr, "Illegal option -%c\n", c);
9064 (void) unsetvar("OPTARG");
9074 if (*p == '\0' && (p = *optnext) == NULL) {
9075 if (optstr[0] == ':') {
9078 err |= setvarsafe("OPTARG", s, 0);
9081 fprintf(stderr, "No arg for -%c option\n", c);
9082 (void) unsetvar("OPTARG");
9090 err |= setvarsafe("OPTARG", p, 0);
9093 err |= setvarsafe("OPTARG", nullstr, 0);
9096 *optoff = p ? p - *(optnext - 1) : -1;
9097 *param_optind = optnext - optfirst + 1;
9098 fmtstr(s, sizeof(s), "%d", *param_optind);
9099 err |= setvarsafe("OPTIND", s, VNOFUNC);
9102 err |= setvarsafe(optvar, s, 0);
9113 * The getopts builtin. Shellparam.optnext points to the next argument
9114 * to be processed. Shellparam.optptr points to the next character to
9115 * be processed in the current argument. If shellparam.optnext is NULL,
9116 * then it's the first time getopts has been called.
9120 getoptscmd(int argc, char **argv)
9125 error("Usage: getopts optstring var [arg]");
9126 else if (argc == 3) {
9127 optbase = shellparam.p;
9128 if (shellparam.optind > shellparam.nparam + 1) {
9129 shellparam.optind = 1;
9130 shellparam.optoff = -1;
9135 if (shellparam.optind > argc - 2) {
9136 shellparam.optind = 1;
9137 shellparam.optoff = -1;
9141 return getopts(argv[1], argv[2], optbase, &shellparam.optind,
9142 &shellparam.optoff);
9144 #endif /* CONFIG_ASH_GETOPTS */
9147 * XXX - should get rid of. have all builtins use getopt(3). the
9148 * library getopt must have the BSD extension static variable "optreset"
9149 * otherwise it can't be used within the shell safely.
9151 * Standard option processing (a la getopt) for builtin routines. The
9152 * only argument that is passed to nextopt is the option string; the
9153 * other arguments are unnecessary. It return the character, or '\0' on
9158 nextopt(const char *optstring)
9164 if ((p = optptr) == NULL || *p == '\0') {
9166 if (p == NULL || *p != '-' || *++p == '\0')
9169 if (p[0] == '-' && p[1] == '\0') /* check for "--" */
9173 for (q = optstring ; *q != c ; ) {
9175 error("Illegal option -%c", c);
9180 if (*p == '\0' && (p = *argptr++) == NULL)
9181 error("No arg for -%c option", c);
9190 /* $NetBSD: output.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
9193 outstr(const char *p, FILE *file)
9210 flushout(FILE *dest)
9218 outcslow(int c, FILE *dest)
9228 out1fmt(const char *fmt, ...)
9235 r = vprintf(fmt, ap);
9243 fmtstr(char *outbuf, size_t length, const char *fmt, ...)
9250 ret = vsnprintf(outbuf, length, fmt, ap);
9258 * Version of write which resumes after a signal is caught.
9262 xwrite(int fd, const void *p, size_t n)
9267 i = bb_full_write(fd, p, n);
9268 } while (i < 0 && errno == EINTR);
9272 /* $NetBSD: parser.c,v 1.54 2002/11/24 22:35:42 christos Exp $ */
9276 * Shell command parser.
9279 #define EOFMARKLEN 79
9283 struct heredoc *next; /* next here document in list */
9284 union node *here; /* redirection node */
9285 char *eofmark; /* string indicating end of input */
9286 int striptabs; /* if set, strip leading tabs */
9291 static struct heredoc *heredoclist; /* list of here documents to read */
9294 static union node *list(int);
9295 static union node *andor(void);
9296 static union node *pipeline(void);
9297 static union node *command(void);
9298 static union node *simplecmd(void);
9299 static union node *makename(void);
9300 static void parsefname(void);
9301 static void parseheredoc(void);
9302 static char peektoken(void);
9303 static int readtoken(void);
9304 static int xxreadtoken(void);
9305 static int readtoken1(int firstc, int syntax, char *eofmark, int striptabs);
9306 static int noexpand(char *);
9307 static void synexpect(int) __attribute__((__noreturn__));
9308 static void synerror(const char *) __attribute__((__noreturn__));
9309 static void setprompt(int);
9314 isassignment(const char *p)
9316 const char *q = endofname(p);
9324 * Read and parse a command. Returns NEOF on end of file. (NULL is a
9325 * valid parse tree indicating a blank line.)
9329 parsecmd(int interact)
9334 doprompt = interact;
9336 setprompt(doprompt);
9351 union node *n1, *n2, *n3;
9354 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9355 if (nlflag == 2 && peektoken())
9361 if (tok == TBACKGND) {
9362 if (n2->type == NPIPE) {
9363 n2->npipe.backgnd = 1;
9365 if (n2->type != NREDIR) {
9366 n3 = stalloc(sizeof(struct nredir));
9368 n3->nredir.redirect = NULL;
9371 n2->type = NBACKGND;
9378 n3 = (union node *)stalloc(sizeof (struct nbinary));
9380 n3->nbinary.ch1 = n1;
9381 n3->nbinary.ch2 = n2;
9397 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9405 pungetc(); /* push back EOF on input */
9421 union node *n1, *n2, *n3;
9426 if ((t = readtoken()) == TAND) {
9428 } else if (t == TOR) {
9434 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9436 n3 = (union node *)stalloc(sizeof (struct nbinary));
9438 n3->nbinary.ch1 = n1;
9439 n3->nbinary.ch2 = n2;
9449 union node *n1, *n2, *pipenode;
9450 struct nodelist *lp, *prev;
9454 TRACE(("pipeline: entered\n"));
9455 if (readtoken() == TNOT) {
9457 checkkwd = CHKKWD | CHKALIAS;
9461 if (readtoken() == TPIPE) {
9462 pipenode = (union node *)stalloc(sizeof (struct npipe));
9463 pipenode->type = NPIPE;
9464 pipenode->npipe.backgnd = 0;
9465 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9466 pipenode->npipe.cmdlist = lp;
9470 lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
9471 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9474 } while (readtoken() == TPIPE);
9480 n2 = (union node *)stalloc(sizeof (struct nnot));
9493 union node *n1, *n2;
9494 union node *ap, **app;
9495 union node *cp, **cpp;
9496 union node *redir, **rpp;
9503 switch (readtoken()) {
9508 n1 = (union node *)stalloc(sizeof (struct nif));
9510 n1->nif.test = list(0);
9511 if (readtoken() != TTHEN)
9513 n1->nif.ifpart = list(0);
9515 while (readtoken() == TELIF) {
9516 n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
9517 n2 = n2->nif.elsepart;
9519 n2->nif.test = list(0);
9520 if (readtoken() != TTHEN)
9522 n2->nif.ifpart = list(0);
9524 if (lasttoken == TELSE)
9525 n2->nif.elsepart = list(0);
9527 n2->nif.elsepart = NULL;
9535 n1 = (union node *)stalloc(sizeof (struct nbinary));
9536 n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL;
9537 n1->nbinary.ch1 = list(0);
9538 if ((got=readtoken()) != TDO) {
9539 TRACE(("expecting DO got %s %s\n", tokname(got), got == TWORD ? wordtext : ""));
9542 n1->nbinary.ch2 = list(0);
9547 if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
9548 synerror("Bad for loop variable");
9549 n1 = (union node *)stalloc(sizeof (struct nfor));
9551 n1->nfor.var = wordtext;
9552 checkkwd = CHKKWD | CHKALIAS;
9553 if (readtoken() == TIN) {
9555 while (readtoken() == TWORD) {
9556 n2 = (union node *)stalloc(sizeof (struct narg));
9558 n2->narg.text = wordtext;
9559 n2->narg.backquote = backquotelist;
9561 app = &n2->narg.next;
9565 if (lasttoken != TNL && lasttoken != TSEMI)
9568 n2 = (union node *)stalloc(sizeof (struct narg));
9570 n2->narg.text = (char *)dolatstr;
9571 n2->narg.backquote = NULL;
9572 n2->narg.next = NULL;
9575 * Newline or semicolon here is optional (but note
9576 * that the original Bourne shell only allowed NL).
9578 if (lasttoken != TNL && lasttoken != TSEMI)
9581 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9582 if (readtoken() != TDO)
9584 n1->nfor.body = list(0);
9588 n1 = (union node *)stalloc(sizeof (struct ncase));
9590 if (readtoken() != TWORD)
9592 n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg));
9594 n2->narg.text = wordtext;
9595 n2->narg.backquote = backquotelist;
9596 n2->narg.next = NULL;
9598 checkkwd = CHKKWD | CHKALIAS;
9599 } while (readtoken() == TNL);
9600 if (lasttoken != TIN)
9602 cpp = &n1->ncase.cases;
9604 checkkwd = CHKNL | CHKKWD;
9607 if (lasttoken == TLP)
9609 *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
9611 app = &cp->nclist.pattern;
9613 *app = ap = (union node *)stalloc(sizeof (struct narg));
9615 ap->narg.text = wordtext;
9616 ap->narg.backquote = backquotelist;
9617 if (readtoken() != TPIPE)
9619 app = &ap->narg.next;
9622 ap->narg.next = NULL;
9623 if (lasttoken != TRP)
9625 cp->nclist.body = list(2);
9627 cpp = &cp->nclist.next;
9629 checkkwd = CHKNL | CHKKWD;
9630 if ((t = readtoken()) != TESAC) {
9632 synexpect(TENDCASE);
9640 n1 = (union node *)stalloc(sizeof (struct nredir));
9641 n1->type = NSUBSHELL;
9642 n1->nredir.n = list(0);
9643 n1->nredir.redirect = NULL;
9656 if (readtoken() != t)
9660 /* Now check for redirection which may follow command */
9661 checkkwd = CHKKWD | CHKALIAS;
9663 while (readtoken() == TREDIR) {
9664 *rpp = n2 = redirnode;
9665 rpp = &n2->nfile.next;
9671 if (n1->type != NSUBSHELL) {
9672 n2 = (union node *)stalloc(sizeof (struct nredir));
9677 n1->nredir.redirect = redir;
9686 union node *args, **app;
9687 union node *n = NULL;
9688 union node *vars, **vpp;
9689 union node **rpp, *redir;
9699 savecheckkwd = CHKALIAS;
9701 checkkwd = savecheckkwd;
9702 switch (readtoken()) {
9704 n = (union node *)stalloc(sizeof (struct narg));
9706 n->narg.text = wordtext;
9707 n->narg.backquote = backquotelist;
9708 if (savecheckkwd && isassignment(wordtext)) {
9710 vpp = &n->narg.next;
9713 app = &n->narg.next;
9718 *rpp = n = redirnode;
9719 rpp = &n->nfile.next;
9720 parsefname(); /* read name of redirection file */
9724 args && app == &args->narg.next &&
9727 struct builtincmd *bcmd;
9730 /* We have a function */
9731 if (readtoken() != TRP)
9733 name = n->narg.text;
9735 !goodname(name) || (
9736 (bcmd = find_builtin(name)) &&
9737 IS_BUILTIN_SPECIAL(bcmd)
9740 synerror("Bad function name");
9742 checkkwd = CHKNL | CHKKWD | CHKALIAS;
9743 n->narg.next = command();
9756 n = (union node *)stalloc(sizeof (struct ncmd));
9758 n->ncmd.args = args;
9759 n->ncmd.assign = vars;
9760 n->ncmd.redirect = redir;
9769 n = (union node *)stalloc(sizeof (struct narg));
9771 n->narg.next = NULL;
9772 n->narg.text = wordtext;
9773 n->narg.backquote = backquotelist;
9777 void fixredir(union node *n, const char *text, int err)
9779 TRACE(("Fix redir %s %d\n", text, err));
9781 n->ndup.vname = NULL;
9783 if (is_digit(text[0]) && text[1] == '\0')
9784 n->ndup.dupfd = digit_val(text[0]);
9785 else if (text[0] == '-' && text[1] == '\0')
9790 synerror("Bad fd number");
9792 n->ndup.vname = makename();
9800 union node *n = redirnode;
9802 if (readtoken() != TWORD)
9804 if (n->type == NHERE) {
9805 struct heredoc *here = heredoc;
9811 TRACE(("Here document %d\n", n->type));
9812 if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN)
9813 synerror("Illegal eof marker for << redirection");
9814 rmescapes(wordtext);
9815 here->eofmark = wordtext;
9817 if (heredoclist == NULL)
9820 for (p = heredoclist ; p->next ; p = p->next);
9823 } else if (n->type == NTOFD || n->type == NFROMFD) {
9824 fixredir(n, wordtext, 0);
9826 n->nfile.fname = makename();
9832 * Input any here documents.
9838 struct heredoc *here;
9849 readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
9850 here->eofmark, here->striptabs);
9851 n = (union node *)stalloc(sizeof (struct narg));
9852 n->narg.type = NARG;
9853 n->narg.next = NULL;
9854 n->narg.text = wordtext;
9855 n->narg.backquote = backquotelist;
9856 here->here->nhere.doc = n;
9861 static char peektoken(void)
9867 return tokname_array[t][0];
9875 int alreadyseen = tokpushback;
9878 #ifdef CONFIG_ASH_ALIAS
9887 if (checkkwd & CHKNL) {
9894 if (t != TWORD || quoteflag) {
9899 * check for keywords
9901 if (checkkwd & CHKKWD) {
9902 const char *const *pp;
9904 if ((pp = findkwd(wordtext))) {
9905 lasttoken = t = pp - tokname_array;
9906 TRACE(("keyword %s recognized\n", tokname(t)));
9911 if (checkkwd & CHKALIAS) {
9912 #ifdef CONFIG_ASH_ALIAS
9914 if ((ap = lookupalias(wordtext, 1)) != NULL) {
9916 pushstring(ap->val, ap);
9926 TRACE(("token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
9928 TRACE(("reread token %s %s\n", tokname(t), t == TWORD ? wordtext : ""));
9935 * Read the next input token.
9936 * If the token is a word, we set backquotelist to the list of cmds in
9937 * backquotes. We set quoteflag to true if any part of the word was
9939 * If the token is TREDIR, then we set redirnode to a structure containing
9941 * In all cases, the variable startlinno is set to the number of the line
9942 * on which the token starts.
9944 * [Change comment: here documents and internal procedures]
9945 * [Readtoken shouldn't have any arguments. Perhaps we should make the
9946 * word parsing code into a separate routine. In this case, readtoken
9947 * doesn't need to have any internal procedures, but parseword does.
9948 * We could also make parseoperator in essence the main routine, and
9949 * have parseword (readtoken1?) handle both words and redirection.]
9952 #define NEW_xxreadtoken
9953 #ifdef NEW_xxreadtoken
9955 /* singles must be first! */
9956 static const char xxreadtoken_chars[7] = { '\n', '(', ')', '&', '|', ';', 0 };
9958 static const char xxreadtoken_tokens[] = {
9959 TNL, TLP, TRP, /* only single occurrence allowed */
9960 TBACKGND, TPIPE, TSEMI, /* if single occurrence */
9961 TEOF, /* corresponds to trailing nul */
9962 TAND, TOR, TENDCASE, /* if double occurrence */
9965 #define xxreadtoken_doubles \
9966 (sizeof(xxreadtoken_tokens) - sizeof(xxreadtoken_chars))
9967 #define xxreadtoken_singles \
9968 (sizeof(xxreadtoken_chars) - xxreadtoken_doubles - 1)
9970 static int xxreadtoken()
9982 startlinno = plinno;
9983 for (;;) { /* until token or start of word found */
9986 if ((c != ' ') && (c != '\t')
9987 #ifdef CONFIG_ASH_ALIAS
9992 while ((c = pgetc()) != '\n' && c != PEOF);
9994 } else if (c == '\\') {
9995 if (pgetc() != '\n') {
9999 startlinno = ++plinno;
10004 = xxreadtoken_chars + sizeof(xxreadtoken_chars) - 1;
10009 needprompt = doprompt;
10012 p = strchr(xxreadtoken_chars, c);
10015 return readtoken1(c, BASESYNTAX, (char *) NULL, 0);
10018 if (p - xxreadtoken_chars >= xxreadtoken_singles) {
10019 if (pgetc() == *p) { /* double occurrence? */
10020 p += xxreadtoken_doubles + 1;
10027 return lasttoken = xxreadtoken_tokens[p - xxreadtoken_chars];
10035 #define RETURN(token) return lasttoken = token
10050 startlinno = plinno;
10051 for (;;) { /* until token or start of word found */
10054 case ' ': case '\t':
10055 #ifdef CONFIG_ASH_ALIAS
10060 while ((c = pgetc()) != '\n' && c != PEOF);
10064 if (pgetc() == '\n') {
10065 startlinno = ++plinno;
10074 needprompt = doprompt;
10079 if (pgetc() == '&')
10084 if (pgetc() == '|')
10089 if (pgetc() == ';')
10102 return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
10105 #endif /* NEW_xxreadtoken */
10109 * If eofmark is NULL, read a word or a redirection symbol. If eofmark
10110 * is not NULL, read a here document. In the latter case, eofmark is the
10111 * word which marks the end of the document and striptabs is true if
10112 * leading tabs should be stripped from the document. The argument firstc
10113 * is the first character of the input token or document.
10115 * Because C does not have internal subroutines, I have simulated them
10116 * using goto's to implement the subroutine linkage. The following macros
10117 * will run code that appears at the end of readtoken1.
10120 #define CHECKEND() {goto checkend; checkend_return:;}
10121 #define PARSEREDIR() {goto parseredir; parseredir_return:;}
10122 #define PARSESUB() {goto parsesub; parsesub_return:;}
10123 #define PARSEBACKQOLD() {oldstyle = 1; goto parsebackq; parsebackq_oldreturn:;}
10124 #define PARSEBACKQNEW() {oldstyle = 0; goto parsebackq; parsebackq_newreturn:;}
10125 #define PARSEARITH() {goto parsearith; parsearith_return:;}
10128 readtoken1(int firstc, int syntax, char *eofmark, int striptabs)
10133 char line[EOFMARKLEN + 1];
10134 struct nodelist *bqlist;
10137 int varnest; /* levels of variables expansion */
10138 int arinest; /* levels of arithmetic expansion */
10139 int parenlevel; /* levels of parens in arithmetic */
10140 int dqvarnest; /* levels of variables expansion within double quotes */
10142 int prevsyntax; /* syntax before arithmetic */
10144 /* Avoid longjmp clobbering */
10150 (void) &parenlevel;
10153 (void) &prevsyntax;
10157 startlinno = plinno;
10159 if (syntax == DQSYNTAX)
10168 STARTSTACKSTR(out);
10169 loop: { /* for each line, until end of word */
10170 CHECKEND(); /* set c to PEOF if at end of here document */
10171 for (;;) { /* until end of line or end of word */
10172 CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
10173 switch(SIT(c, syntax)) {
10174 case CNL: /* '\n' */
10175 if (syntax == BASESYNTAX)
10176 goto endword; /* exit outer loop */
10182 goto loop; /* continue outer loop */
10187 if (eofmark == NULL || dblquote)
10188 USTPUTC(CTLESC, out);
10191 case CBACK: /* backslash */
10194 USTPUTC(CTLESC, out);
10195 USTPUTC('\\', out);
10197 } else if (c == '\n') {
10203 c != '\\' && c != '`' &&
10209 USTPUTC(CTLESC, out);
10210 USTPUTC('\\', out);
10212 if (SIT(c, SQSYNTAX) == CCTL)
10213 USTPUTC(CTLESC, out);
10221 if (eofmark == NULL) {
10222 USTPUTC(CTLQUOTEMARK, out);
10230 if (eofmark != NULL && arinest == 0 &&
10234 if (dqvarnest == 0) {
10235 syntax = BASESYNTAX;
10242 case CVAR: /* '$' */
10243 PARSESUB(); /* parse substitution */
10245 case CENDVAR: /* '}' */
10248 if (dqvarnest > 0) {
10251 USTPUTC(CTLENDVAR, out);
10256 #ifdef CONFIG_ASH_MATH_SUPPORT
10257 case CLP: /* '(' in arithmetic */
10261 case CRP: /* ')' in arithmetic */
10262 if (parenlevel > 0) {
10266 if (pgetc() == ')') {
10267 if (--arinest == 0) {
10268 USTPUTC(CTLENDARI, out);
10269 syntax = prevsyntax;
10270 if (syntax == DQSYNTAX)
10278 * unbalanced parens
10279 * (don't 2nd guess - no error)
10287 case CBQUOTE: /* '`' */
10291 goto endword; /* exit outer loop */
10296 goto endword; /* exit outer loop */
10297 #ifdef CONFIG_ASH_ALIAS
10307 #ifdef CONFIG_ASH_MATH_SUPPORT
10308 if (syntax == ARISYNTAX)
10309 synerror("Missing '))'");
10311 if (syntax != BASESYNTAX && ! parsebackquote && eofmark == NULL)
10312 synerror("Unterminated quoted string");
10313 if (varnest != 0) {
10314 startlinno = plinno;
10316 synerror("Missing '}'");
10318 USTPUTC('\0', out);
10319 len = out - (char *)stackblock();
10320 out = stackblock();
10321 if (eofmark == NULL) {
10322 if ((c == '>' || c == '<')
10325 && (*out == '\0' || is_digit(*out))) {
10327 return lasttoken = TREDIR;
10332 quoteflag = quotef;
10333 backquotelist = bqlist;
10334 grabstackblock(len);
10336 return lasttoken = TWORD;
10337 /* end of readtoken routine */
10342 * Check to see whether we are at the end of the here document. When this
10343 * is called, c is set to the first character of the next input line. If
10344 * we are at the end of the here document, this routine sets the c to PEOF.
10349 #ifdef CONFIG_ASH_ALIAS
10355 while (c == '\t') {
10359 if (c == *eofmark) {
10360 if (pfgets(line, sizeof line) != NULL) {
10364 for (q = eofmark + 1 ; *q && *p == *q ; p++, q++);
10365 if (*p == '\n' && *q == '\0') {
10368 needprompt = doprompt;
10370 pushstring(line, NULL);
10375 goto checkend_return;
10380 * Parse a redirection operator. The variable "out" points to a string
10381 * specifying the fd to be redirected. The variable "c" contains the
10382 * first character of the redirection operator.
10389 np = (union node *)stalloc(sizeof (struct nfile));
10394 np->type = NAPPEND;
10396 np->type = NCLOBBER;
10403 } else { /* c == '<' */
10405 switch (c = pgetc()) {
10407 if (sizeof (struct nfile) != sizeof (struct nhere)) {
10408 np = (union node *)stalloc(sizeof (struct nhere));
10412 heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
10413 heredoc->here = np;
10414 if ((c = pgetc()) == '-') {
10415 heredoc->striptabs = 1;
10417 heredoc->striptabs = 0;
10423 np->type = NFROMFD;
10427 np->type = NFROMTO;
10437 np->nfile.fd = digit_val(fd);
10439 goto parseredir_return;
10444 * Parse a substitution. At this point, we have read the dollar sign
10445 * and nothing else.
10453 static const char types[] = "}-+?=";
10457 c <= PEOA_OR_PEOF ||
10458 (c != '(' && c != '{' && !is_name(c) && !is_special(c))
10462 } else if (c == '(') { /* $(command) or $((arith)) */
10463 if (pgetc() == '(') {
10464 #ifdef CONFIG_ASH_MATH_SUPPORT
10467 synerror("We unsupport $((arith))");
10474 USTPUTC(CTLVAR, out);
10475 typeloc = out - (char *)stackblock();
10476 USTPUTC(VSNORMAL, out);
10477 subtype = VSNORMAL;
10481 if ((c = pgetc()) == '}')
10484 subtype = VSLENGTH;
10489 if (c > PEOA_OR_PEOF && is_name(c)) {
10493 } while (c > PEOA_OR_PEOF && is_in_name(c));
10494 } else if (is_digit(c)) {
10498 } while (is_digit(c));
10500 else if (is_special(c)) {
10505 badsub: synerror("Bad substitution");
10509 if (subtype == 0) {
10516 p = strchr(types, c);
10519 subtype = p - types + VSNORMAL;
10525 subtype = c == '#' ? VSTRIMLEFT :
10538 if (dblquote || arinest)
10540 *((char *)stackblock() + typeloc) = subtype | flags;
10541 if (subtype != VSNORMAL) {
10543 if (dblquote || arinest) {
10548 goto parsesub_return;
10553 * Called to parse command substitutions. Newstyle is set if the command
10554 * is enclosed inside $(...); nlpp is a pointer to the head of the linked
10555 * list of commands (passed by reference), and savelen is the number of
10556 * characters on the top of the stack which must be preserved.
10560 struct nodelist **nlpp;
10563 char *volatile str;
10564 struct jmploc jmploc;
10565 struct jmploc *volatile savehandler;
10569 (void) &saveprompt;
10572 savepbq = parsebackquote;
10573 if (setjmp(jmploc.loc)) {
10576 parsebackquote = 0;
10577 handler = savehandler;
10578 longjmp(handler->loc, 1);
10582 savelen = out - (char *)stackblock();
10584 str = ckmalloc(savelen);
10585 memcpy(str, stackblock(), savelen);
10587 savehandler = handler;
10591 /* We must read until the closing backquote, giving special
10592 treatment to some slashes, and then push the string and
10593 reread it as input, interpreting it normally. */
10600 STARTSTACKSTR(pout);
10606 switch (pc = pgetc()) {
10611 if ((pc = pgetc()) == '\n') {
10616 * If eating a newline, avoid putting
10617 * the newline into the new character
10618 * stream (via the STPUTC after the
10623 if (pc != '\\' && pc != '`' && pc != '$'
10624 && (!dblquote || pc != '"'))
10625 STPUTC('\\', pout);
10626 if (pc > PEOA_OR_PEOF) {
10632 #ifdef CONFIG_ASH_ALIAS
10635 startlinno = plinno;
10636 synerror("EOF in backquote substitution");
10640 needprompt = doprompt;
10649 STPUTC('\0', pout);
10650 psavelen = pout - (char *)stackblock();
10651 if (psavelen > 0) {
10652 pstr = grabstackstr(pout);
10653 setinputstring(pstr);
10658 nlpp = &(*nlpp)->next;
10659 *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
10660 (*nlpp)->next = NULL;
10661 parsebackquote = oldstyle;
10664 saveprompt = doprompt;
10671 doprompt = saveprompt;
10673 if (readtoken() != TRP)
10680 * Start reading from old file again, ignoring any pushed back
10681 * tokens left from the backquote parsing
10686 while (stackblocksize() <= savelen)
10688 STARTSTACKSTR(out);
10690 memcpy(out, str, savelen);
10691 STADJUST(savelen, out);
10697 parsebackquote = savepbq;
10698 handler = savehandler;
10699 if (arinest || dblquote)
10700 USTPUTC(CTLBACKQ | CTLQUOTE, out);
10702 USTPUTC(CTLBACKQ, out);
10704 goto parsebackq_oldreturn;
10706 goto parsebackq_newreturn;
10709 #ifdef CONFIG_ASH_MATH_SUPPORT
10711 * Parse an arithmetic expansion (indicate start of one and set state)
10715 if (++arinest == 1) {
10716 prevsyntax = syntax;
10717 syntax = ARISYNTAX;
10718 USTPUTC(CTLARI, out);
10725 * we collapse embedded arithmetic expansion to
10726 * parenthesis, which should be equivalent
10730 goto parsearith_return;
10734 } /* end of readtoken */
10739 * Returns true if the text contains nothing to expand (no dollar signs
10744 noexpand(char *text)
10750 while ((c = *p++) != '\0') {
10751 if (c == CTLQUOTEMARK)
10755 else if (SIT(c, BASESYNTAX) == CCTL)
10763 * Return of a legal variable name (a letter or underscore followed by zero or
10764 * more letters, underscores, and digits).
10768 endofname(const char *name)
10776 if (! is_in_name(*p))
10784 * Called when an unexpected token is read during the parse. The argument
10785 * is the token that is expected, or -1 if more than one type of token can
10786 * occur at this point.
10789 static void synexpect(int token)
10794 l = sprintf(msg, "%s unexpected", tokname(lasttoken));
10796 sprintf(msg + l, " (expecting %s)", tokname(token));
10802 synerror(const char *msg)
10804 error("Syntax error: %s", msg);
10810 * called by editline -- any expansions to the prompt
10811 * should be added here.
10814 static void setprompt(int whichprompt)
10816 const char *prompt;
10818 switch (whichprompt) {
10832 static const char *const *findkwd(const char *s)
10834 return bsearch(s, tokname_array + KWDOFFSET,
10835 (sizeof(tokname_array) / sizeof(const char *)) - KWDOFFSET,
10836 sizeof(const char *), pstrcmp);
10839 /* $NetBSD: redir.c,v 1.27 2002/11/24 22:35:42 christos Exp $ */
10842 * Code for dealing with input/output redirection.
10845 #define EMPTY -2 /* marks an unused slot in redirtab */
10847 # define PIPESIZE 4096 /* amount of buffering in a pipe */
10849 # define PIPESIZE PIPE_BUF
10853 * Open a file in noclobber mode.
10854 * The code was copied from bash.
10857 noclobberopen(const char *fname)
10860 struct stat finfo, finfo2;
10863 * If the file exists and is a regular file, return an error
10866 r = stat(fname, &finfo);
10867 if (r == 0 && S_ISREG(finfo.st_mode)) {
10873 * If the file was not present (r != 0), make sure we open it
10874 * exclusively so that if it is created before we open it, our open
10875 * will fail. Make sure that we do not truncate an existing file.
10876 * Note that we don't turn on O_EXCL unless the stat failed -- if the
10877 * file was not a regular file, we leave O_EXCL off.
10880 return open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666);
10881 fd = open(fname, O_WRONLY|O_CREAT, 0666);
10883 /* If the open failed, return the file descriptor right away. */
10888 * OK, the open succeeded, but the file may have been changed from a
10889 * non-regular file to a regular file between the stat and the open.
10890 * We are assuming that the O_EXCL open handles the case where FILENAME
10891 * did not exist and is symlinked to an existing file between the stat
10896 * If we can open it and fstat the file descriptor, and neither check
10897 * revealed that it was a regular file, and the file has not been
10898 * replaced, return the file descriptor.
10900 if (fstat(fd, &finfo2) == 0 && !S_ISREG(finfo2.st_mode) &&
10901 finfo.st_dev == finfo2.st_dev && finfo.st_ino == finfo2.st_ino)
10904 /* The file has been replaced. badness. */
10911 * Handle here documents. Normally we fork off a process to write the
10912 * data to a pipe. If the document is short, we can stuff the data in
10913 * the pipe without forking.
10917 openhere(union node *redir)
10923 error("Pipe call failed");
10924 if (redir->type == NHERE) {
10925 len = strlen(redir->nhere.doc->narg.text);
10926 if (len <= PIPESIZE) {
10927 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10931 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
10933 signal(SIGINT, SIG_IGN);
10934 signal(SIGQUIT, SIG_IGN);
10935 signal(SIGHUP, SIG_IGN);
10937 signal(SIGTSTP, SIG_IGN);
10939 signal(SIGPIPE, SIG_DFL);
10940 if (redir->type == NHERE)
10941 xwrite(pip[1], redir->nhere.doc->narg.text, len);
10943 expandhere(redir->nhere.doc, pip[1]);
10952 openredirect(union node *redir)
10957 switch (redir->nfile.type) {
10959 fname = redir->nfile.expfname;
10960 if ((f = open(fname, O_RDONLY)) < 0)
10964 fname = redir->nfile.expfname;
10965 if ((f = open(fname, O_RDWR|O_CREAT|O_TRUNC, 0666)) < 0)
10969 /* Take care of noclobber mode. */
10971 fname = redir->nfile.expfname;
10972 if ((f = noclobberopen(fname)) < 0)
10978 fname = redir->nfile.expfname;
10979 if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
10983 fname = redir->nfile.expfname;
10984 if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
10991 /* Fall through to eliminate warning. */
10998 f = openhere(redir);
11004 error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
11006 error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
11010 dupredirect(union node *redir, int f)
11012 int fd = redir->nfile.fd;
11014 if (redir->nfile.type == NTOFD || redir->nfile.type == NFROMFD) {
11015 if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
11016 copyfd(redir->ndup.dupfd, fd);
11029 * Process a list of redirection commands. If the REDIR_PUSH flag is set,
11030 * old file descriptors are stashed away so that the redirection can be
11031 * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
11032 * standard output, and the standard error if it becomes a duplicate of
11033 * stdout, is saved in memory.
11037 redirect(union node *redir, int flags)
11040 struct redirtab *sv;
11051 if (flags & REDIR_PUSH) {
11052 struct redirtab *q;
11053 q = ckmalloc(sizeof (struct redirtab));
11054 q->next = redirlist;
11056 q->nullredirs = nullredirs - 1;
11057 for (i = 0 ; i < 10 ; i++)
11058 q->renamed[i] = EMPTY;
11065 if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
11066 n->ndup.dupfd == fd)
11067 continue; /* redirect from/to same file descriptor */
11069 newfd = openredirect(n);
11072 if (sv && *(p = &sv->renamed[fd]) == EMPTY) {
11073 i = fcntl(fd, F_DUPFD, 10);
11080 error("%d: %m", fd);
11090 dupredirect(n, newfd);
11091 } while ((n = n->nfile.next));
11093 if (flags & REDIR_SAVEFD2 && sv && sv->renamed[2] >= 0)
11094 preverrout_fd = sv->renamed[2];
11099 * Undo the effects of the last redirection.
11105 struct redirtab *rp;
11108 if (--nullredirs >= 0)
11112 for (i = 0 ; i < 10 ; i++) {
11113 if (rp->renamed[i] != EMPTY) {
11116 copyfd(rp->renamed[i], i);
11118 close(rp->renamed[i]);
11121 redirlist = rp->next;
11122 nullredirs = rp->nullredirs;
11128 * Undo all redirections. Called on error or interrupt.
11132 * Discard all saved file descriptors.
11136 clearredir(int drop)
11148 * Copy a file descriptor to be >= to. Returns -1
11149 * if the source file descriptor is closed, EMPTY if there are no unused
11150 * file descriptors left.
11154 copyfd(int from, int to)
11158 newfd = fcntl(from, F_DUPFD, to);
11160 if (errno == EMFILE)
11163 error("%d: %m", from);
11170 redirectsafe(union node *redir, int flags)
11173 volatile int saveint;
11174 struct jmploc *volatile savehandler = handler;
11175 struct jmploc jmploc;
11178 if (!(err = setjmp(jmploc.loc) * 2)) {
11180 redirect(redir, flags);
11182 handler = savehandler;
11183 if (err && exception != EXERROR)
11184 longjmp(handler->loc, 1);
11185 RESTOREINT(saveint);
11189 /* $NetBSD: show.c,v 1.24 2003/01/22 20:36:04 dsl Exp $ */
11192 static void shtree(union node *, int, char *, FILE*);
11193 static void shcmd(union node *, FILE *);
11194 static void sharg(union node *, FILE *);
11195 static void indent(int, char *, FILE *);
11196 static void trstring(char *);
11200 showtree(union node *n)
11202 trputs("showtree called\n");
11203 shtree(n, 1, NULL, stdout);
11208 shtree(union node *n, int ind, char *pfx, FILE *fp)
11210 struct nodelist *lp;
11216 indent(ind, pfx, fp);
11227 shtree(n->nbinary.ch1, ind, NULL, fp);
11230 shtree(n->nbinary.ch2, ind, NULL, fp);
11238 for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
11243 if (n->npipe.backgnd)
11249 fprintf(fp, "<node type %d>", n->type);
11258 shcmd(union node *cmd, FILE *fp)
11266 for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
11272 for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
11275 switch (np->nfile.type) {
11276 case NTO: s = ">"; dftfd = 1; break;
11277 case NCLOBBER: s = ">|"; dftfd = 1; break;
11278 case NAPPEND: s = ">>"; dftfd = 1; break;
11279 case NTOFD: s = ">&"; dftfd = 1; break;
11280 case NFROM: s = "<"; dftfd = 0; break;
11281 case NFROMFD: s = "<&"; dftfd = 0; break;
11282 case NFROMTO: s = "<>"; dftfd = 0; break;
11283 default: s = "*error*"; dftfd = 0; break;
11285 if (np->nfile.fd != dftfd)
11286 fprintf(fp, "%d", np->nfile.fd);
11288 if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
11289 fprintf(fp, "%d", np->ndup.dupfd);
11291 sharg(np->nfile.fname, fp);
11300 sharg(union node *arg, FILE *fp)
11303 struct nodelist *bqlist;
11306 if (arg->type != NARG) {
11307 out1fmt("<node type %d>\n", arg->type);
11310 bqlist = arg->narg.backquote;
11311 for (p = arg->narg.text ; *p ; p++) {
11320 if (subtype == VSLENGTH)
11326 if (subtype & VSNUL)
11329 switch (subtype & VSTYPE) {
11348 case VSTRIMLEFTMAX:
11355 case VSTRIMRIGHTMAX:
11362 out1fmt("<subtype %d>", subtype);
11369 case CTLBACKQ|CTLQUOTE:
11372 shtree(bqlist->n, -1, NULL, fp);
11384 indent(int amount, char *pfx, FILE *fp)
11388 for (i = 0 ; i < amount ; i++) {
11389 if (pfx && i == amount - 1)
11410 putc(c, tracefile);
11414 trace(const char *fmt, ...)
11421 (void) vfprintf(tracefile, fmt, va);
11426 tracev(const char *fmt, va_list va)
11430 (void) vfprintf(tracefile, fmt, va);
11435 trputs(const char *s)
11439 fputs(s, tracefile);
11451 putc('"', tracefile);
11452 for (p = s ; *p ; p++) {
11454 case '\n': c = 'n'; goto backslash;
11455 case '\t': c = 't'; goto backslash;
11456 case '\r': c = 'r'; goto backslash;
11457 case '"': c = '"'; goto backslash;
11458 case '\\': c = '\\'; goto backslash;
11459 case CTLESC: c = 'e'; goto backslash;
11460 case CTLVAR: c = 'v'; goto backslash;
11461 case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
11462 case CTLBACKQ: c = 'q'; goto backslash;
11463 case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
11464 backslash: putc('\\', tracefile);
11465 putc(c, tracefile);
11468 if (*p >= ' ' && *p <= '~')
11469 putc(*p, tracefile);
11471 putc('\\', tracefile);
11472 putc(*p >> 6 & 03, tracefile);
11473 putc(*p >> 3 & 07, tracefile);
11474 putc(*p & 07, tracefile);
11479 putc('"', tracefile);
11491 putc(' ', tracefile);
11493 putc('\n', tracefile);
11509 /* leave open because libedit might be using it */
11512 scopy("./trace", s);
11514 if (!freopen(s, "a", tracefile)) {
11515 fprintf(stderr, "Can't re-open %s\n", s);
11520 if ((tracefile = fopen(s, "a")) == NULL) {
11521 fprintf(stderr, "Can't open %s\n", s);
11527 if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
11528 fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
11530 setlinebuf(tracefile);
11531 fputs("\nTracing started.\n", tracefile);
11536 /* $NetBSD: trap.c,v 1.28 2002/11/24 22:35:43 christos Exp $ */
11539 * Sigmode records the current value of the signal handlers for the various
11540 * modes. A value of zero means that the current handler is not known.
11541 * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
11544 #define S_DFL 1 /* default signal handling (SIG_DFL) */
11545 #define S_CATCH 2 /* signal is caught */
11546 #define S_IGN 3 /* signal is ignored (SIG_IGN) */
11547 #define S_HARD_IGN 4 /* signal is ignored permenantly */
11548 #define S_RESET 5 /* temporary - to reset a hard ignored sig */
11553 * The trap builtin.
11557 trapcmd(int argc, char **argv)
11566 for (signo = 0 ; signo < NSIG ; signo++) {
11567 if (trap[signo] != NULL) {
11570 sn = u_signal_names(0, &signo, 0);
11573 out1fmt("trap -- %s %s\n",
11574 single_quote(trap[signo]), sn);
11584 if ((signo = decode_signal(*ap, 0)) < 0)
11585 error("%s: bad trap", *ap);
11588 if (action[0] == '-' && action[1] == '\0')
11591 action = savestr(action);
11594 ckfree(trap[signo]);
11595 trap[signo] = action;
11606 * Clear traps on a fork.
11614 for (tp = trap ; tp < &trap[NSIG] ; tp++) {
11615 if (*tp && **tp) { /* trap not NULL or SIG_IGN */
11619 if (tp != &trap[0])
11620 setsignal(tp - trap);
11628 * Set the signal handler for the specified signal. The routine figures
11629 * out what it should be set to.
11633 setsignal(int signo)
11637 struct sigaction act;
11639 if ((t = trap[signo]) == NULL)
11641 else if (*t != '\0')
11645 if (rootshell && action == S_DFL) {
11648 if (iflag || minusc || sflag == 0)
11671 t = &sigmode[signo - 1];
11675 * current setting unknown
11677 if (sigaction(signo, 0, &act) == -1) {
11679 * Pretend it worked; maybe we should give a warning
11680 * here, but other shells don't. We don't alter
11681 * sigmode, so that we retry every time.
11685 if (act.sa_handler == SIG_IGN) {
11686 if (mflag && (signo == SIGTSTP ||
11687 signo == SIGTTIN || signo == SIGTTOU)) {
11688 tsig = S_IGN; /* don't hard ignore these */
11692 tsig = S_RESET; /* force to be set */
11695 if (tsig == S_HARD_IGN || tsig == action)
11699 act.sa_handler = onsig;
11702 act.sa_handler = SIG_IGN;
11705 act.sa_handler = SIG_DFL;
11709 sigfillset(&act.sa_mask);
11710 sigaction(signo, &act, 0);
11718 ignoresig(int signo)
11720 if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
11721 signal(signo, SIG_IGN);
11723 sigmode[signo - 1] = S_HARD_IGN;
11734 gotsig[signo - 1] = 1;
11735 pendingsigs = signo;
11737 if (exsig || (signo == SIGINT && !trap[SIGINT])) {
11746 * Called to execute a trap. Perhaps we should avoid entering new trap
11747 * handlers while we are executing a trap handler.
11757 savestatus = exitstatus;
11759 while (pendingsigs = 0, barrier(), (p = memchr(q, 1, NSIG - 1))) {
11761 p = trap[p - q + 1];
11765 exitstatus = savestatus;
11771 * Controls whether the shell is interactive or not.
11775 setinteractive(int on)
11777 static int is_interactive;
11779 if (++on == is_interactive)
11781 is_interactive = on;
11783 setsignal(SIGQUIT);
11784 setsignal(SIGTERM);
11785 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
11786 if(is_interactive > 1) {
11787 /* Looks like they want an interactive shell */
11788 static int do_banner;
11792 "\n\n" BB_BANNER " Built-in shell (ash)\n"
11793 "Enter 'help' for a list of built-in commands.\n\n");
11801 #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
11802 /*** List the available builtins ***/
11804 static int helpcmd(int argc, char **argv)
11808 out1fmt("\nBuilt-in commands:\n-------------------\n");
11809 for (col = 0, i = 0; i < NUMBUILTINS; i++) {
11810 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '),
11811 builtincmd[i].name + 1);
11817 #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
11819 extern const struct BB_applet applets[];
11820 extern const size_t NUM_APPLETS;
11822 for (i = 0; i < NUM_APPLETS; i++) {
11824 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), applets[i].name);
11833 return EXIT_SUCCESS;
11835 #endif /* CONFIG_FEATURE_SH_EXTRA_QUIET */
11838 * Called to exit the shell.
11849 jmp = setjmp(loc.loc);
11850 status = exitstatus;
11851 TRACE(("pid %d, exitshell(%d)\n", getpid(), status));
11855 if ((p = trap[0]) != NULL && *p != '\0') {
11860 #ifdef CONFIG_FEATURE_COMMAND_SAVEHISTORY
11861 if (iflag && rootshell) {
11862 const char *hp = lookupvar("HISTFILE");
11865 save_history ( hp );
11873 static int decode_signal(const char *string, int minsig)
11876 const char *name = u_signal_names(string, &signo, minsig);
11878 return name ? signo : -1;
11881 /* $NetBSD: var.c,v 1.32 2003/01/22 20:36:04 dsl Exp $ */
11883 static struct var *vartab[VTABSIZE];
11885 static int vpcmp(const void *, const void *);
11886 static struct var **findvar(struct var **, const char *);
11889 * Initialize the varable symbol tables and import the environment
11893 #ifdef CONFIG_ASH_GETOPTS
11895 * Safe version of setvar, returns 1 on success 0 on failure.
11899 setvarsafe(const char *name, const char *val, int flags)
11902 volatile int saveint;
11903 struct jmploc *volatile savehandler = handler;
11904 struct jmploc jmploc;
11907 if (setjmp(jmploc.loc))
11911 setvar(name, val, flags);
11914 handler = savehandler;
11915 RESTOREINT(saveint);
11921 * Set the value of a variable. The flags argument is ored with the
11922 * flags of the variable. If val is NULL, the variable is unset.
11926 setvar(const char *name, const char *val, int flags)
11933 q = endofname(name);
11934 p = strchrnul(q, '=');
11935 namelen = p - name;
11936 if (!namelen || p != q)
11937 error("%.*s: bad variable name", namelen, name);
11942 vallen = strlen(val);
11945 p = mempcpy(nameeq = ckmalloc(namelen + vallen + 2), name, namelen);
11949 p = mempcpy(p, val, vallen);
11952 setvareq(nameeq, flags | VNOSAVE);
11958 * Same as setvar except that the variable and value are passed in
11959 * the first argument as name=value. Since the first argument will
11960 * be actually stored in the table, it should not be a string that
11962 * Called with interrupts off.
11966 setvareq(char *s, int flags)
11968 struct var *vp, **vpp;
11971 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
11972 vp = *findvar(vpp, s);
11974 if (vp->flags & VREADONLY) {
11975 if (flags & VNOSAVE)
11977 error("%.*s: is read only", strchrnul(s, '=') - s, s);
11980 if (flags & VNOSET)
11983 if (vp->func && (flags & VNOFUNC) == 0)
11984 (*vp->func)(strchrnul(s, '=') + 1);
11986 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
11989 flags |= vp->flags & ~(VTEXTFIXED|VSTACK|VNOSAVE|VUNSET);
11991 if (flags & VNOSET)
11994 vp = ckmalloc(sizeof (*vp));
11999 if (!(flags & (VTEXTFIXED|VSTACK|VNOSAVE)))
12007 * Process a linked list of variable assignments.
12011 listsetvar(struct strlist *list_set_var, int flags)
12013 struct strlist *lp = list_set_var;
12019 setvareq(lp->text, flags);
12020 } while ((lp = lp->next));
12026 * Find the value of a variable. Returns NULL if not set.
12030 lookupvar(const char *name)
12034 if ((v = *findvar(hashvar(name), name)) && !(v->flags & VUNSET)) {
12035 return strchrnul(v->text, '=') + 1;
12042 * Search the environment of a builtin command.
12046 bltinlookup(const char *name)
12048 struct strlist *sp;
12050 for (sp = cmdenviron ; sp ; sp = sp->next) {
12051 if (varequal(sp->text, name))
12052 return strchrnul(sp->text, '=') + 1;
12054 return lookupvar(name);
12059 * Generate a list of variables satisfying the given conditions.
12063 listvars(int on, int off, char ***end)
12074 for (vp = *vpp ; vp ; vp = vp->next)
12075 if ((vp->flags & mask) == on) {
12076 if (ep == stackstrend())
12077 ep = growstackstr();
12078 *ep++ = (char *) vp->text;
12080 } while (++vpp < vartab + VTABSIZE);
12081 if (ep == stackstrend())
12082 ep = growstackstr();
12086 return grabstackstr(ep);
12091 * POSIX requires that 'set' (but not export or readonly) output the
12092 * variables in lexicographic order - by the locale's collating order (sigh).
12093 * Maybe we could keep them in an ordered balanced binary tree
12094 * instead of hashed lists.
12095 * For now just roll 'em through qsort for printing...
12099 showvars(const char *sep_prefix, int on, int off)
12102 char **ep, **epend;
12104 ep = listvars(on, off, &epend);
12105 qsort(ep, epend - ep, sizeof(char *), vpcmp);
12107 sep = *sep_prefix ? spcstr : sep_prefix;
12109 for (; ep < epend; ep++) {
12113 p = strchrnul(*ep, '=');
12116 q = single_quote(++p);
12118 out1fmt("%s%s%.*s%s\n", sep_prefix, sep, (int)(p - *ep), *ep, q);
12127 * The export and readonly commands.
12131 exportcmd(int argc, char **argv)
12137 int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
12140 notp = nextopt("p") - 'p';
12141 if (notp && ((name = *(aptr = argptr)))) {
12143 if ((p = strchr(name, '=')) != NULL) {
12146 if ((vp = *findvar(hashvar(name), name))) {
12151 setvar(name, p, flag);
12152 } while ((name = *++aptr) != NULL);
12154 showvars(argv[0], flag, 0);
12161 * Make a variable a local variable. When a variable is made local, it's
12162 * value and flags are saved in a localvar structure. The saved values
12163 * will be restored when the shell function returns. We handle the name
12164 * "-" as a special case.
12168 mklocal(char *name)
12170 struct localvar *lvp;
12175 lvp = ckmalloc(sizeof (struct localvar));
12176 if (name[0] == '-' && name[1] == '\0') {
12178 p = ckmalloc(sizeof(optlist));
12179 lvp->text = memcpy(p, optlist, sizeof(optlist));
12184 vpp = hashvar(name);
12185 vp = *findvar(vpp, name);
12186 eq = strchr(name, '=');
12189 setvareq(name, VSTRFIXED);
12191 setvar(name, NULL, VSTRFIXED);
12192 vp = *vpp; /* the new variable */
12193 lvp->flags = VUNSET;
12195 lvp->text = vp->text;
12196 lvp->flags = vp->flags;
12197 vp->flags |= VSTRFIXED|VTEXTFIXED;
12203 lvp->next = localvars;
12209 * The "local" command.
12213 localcmd(int argc, char **argv)
12218 while ((name = *argv++) != NULL) {
12226 * Called after a function returns.
12227 * Interrupts must be off.
12233 struct localvar *lvp;
12236 while ((lvp = localvars) != NULL) {
12237 localvars = lvp->next;
12239 TRACE(("poplocalvar %s", vp ? vp->text : "-"));
12240 if (vp == NULL) { /* $- saved */
12241 memcpy(optlist, lvp->text, sizeof(optlist));
12244 } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
12245 unsetvar(vp->text);
12248 (*vp->func)(strchrnul(lvp->text, '=') + 1);
12249 if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
12251 vp->flags = lvp->flags;
12252 vp->text = lvp->text;
12260 * The unset builtin command. We unset the function before we unset the
12261 * variable to allow a function to be unset when there is a readonly variable
12262 * with the same name.
12266 unsetcmd(int argc, char **argv)
12273 while ((i = nextopt("vf")) != '\0') {
12277 for (ap = argptr; *ap ; ap++) {
12292 * Unset the specified variable.
12296 unsetvar(const char *s)
12302 vpp = findvar(hashvar(s), s);
12306 int flags = vp->flags;
12309 if (flags & VREADONLY)
12311 if (flags & VUNSET)
12313 if ((flags & VSTRFIXED) == 0) {
12315 if ((flags & (VTEXTFIXED|VSTACK)) == 0)
12322 vp->flags &= ~VEXPORT;
12335 * Find the appropriate entry in the hash table from the name.
12338 static struct var **
12339 hashvar(const char *p)
12341 unsigned int hashval;
12343 hashval = ((unsigned char) *p) << 4;
12344 while (*p && *p != '=')
12345 hashval += (unsigned char) *p++;
12346 return &vartab[hashval % VTABSIZE];
12352 * Compares two strings up to the first = or '\0'. The first
12353 * string must be terminated by '='; the second may be terminated by
12354 * either '=' or '\0'.
12358 varcmp(const char *p, const char *q)
12362 while ((c = *p) == (d = *q)) {
12363 if (!c || c == '=')
12377 vpcmp(const void *a, const void *b)
12379 return varcmp(*(const char **)a, *(const char **)b);
12382 static struct var **
12383 findvar(struct var **vpp, const char *name)
12385 for (; *vpp; vpp = &(*vpp)->next) {
12386 if (varequal((*vpp)->text, name)) {
12392 /* $NetBSD: setmode.c,v 1.29 2003/01/15 23:58:03 kleink Exp $ */
12394 #include <sys/times.h>
12396 static const unsigned char timescmd_str[] = {
12397 ' ', offsetof(struct tms, tms_utime),
12398 '\n', offsetof(struct tms, tms_stime),
12399 ' ', offsetof(struct tms, tms_cutime),
12400 '\n', offsetof(struct tms, tms_cstime),
12404 static int timescmd(int ac, char **av)
12406 long int clk_tck, s, t;
12407 const unsigned char *p;
12410 clk_tck = sysconf(_SC_CLK_TCK);
12415 t = *(clock_t *)(((char *) &buf) + p[1]);
12417 out1fmt("%ldm%ld.%.3lds%c",
12419 ((t - s * clk_tck) * 1000) / clk_tck,
12421 } while (*(p += 2));
12426 #ifdef CONFIG_ASH_MATH_SUPPORT
12428 dash_arith(const char *s)
12434 result = arith(s, &errcode);
12437 error("exponent less than 0");
12438 else if (errcode == -2)
12439 error("divide by zero");
12440 else if (errcode == -5)
12441 error("expression recursion loop detected");
12452 * The let builtin. partial stolen from GNU Bash, the Bourne Again SHell.
12453 * Copyright (C) 1987, 1989, 1991 Free Software Foundation, Inc.
12455 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12459 letcmd(int argc, char **argv)
12466 error("expression expected");
12467 for (ap = argv + 1; *ap; ap++) {
12468 i = dash_arith(*ap);
12473 #endif /* CONFIG_ASH_MATH_SUPPORT */
12475 /* $NetBSD: miscbltin.c,v 1.31 2002/11/24 22:35:41 christos Exp $ */
12478 * Miscelaneous builtins.
12484 #if __GLIBC__ == 2 && __GLIBC_MINOR__ < 1
12485 typedef enum __rlimit_resource rlim_t;
12491 * The read builtin. The -e option causes backslashes to escape the
12492 * following character.
12494 * This uses unbuffered input, which may be avoidable in some cases.
12498 readcmd(int argc, char **argv)
12513 while ((i = nextopt("p:r")) != '\0') {
12515 prompt = optionarg;
12519 if (prompt && isatty(0)) {
12522 if (*(ap = argptr) == NULL)
12523 error("arg count");
12524 if ((ifs = bltinlookup("IFS")) == NULL)
12531 if (read(0, &c, 1) != 1) {
12543 if (!rflag && c == '\\') {
12549 if (startword && *ifs == ' ' && strchr(ifs, c)) {
12553 if (ap[1] != NULL && strchr(ifs, c) != NULL) {
12555 setvar(*ap, stackblock(), 0);
12565 /* Remove trailing blanks */
12566 while ((char *)stackblock() <= --p && strchr(ifs, *p) != NULL)
12568 setvar(*ap, stackblock(), 0);
12569 while (*++ap != NULL)
12570 setvar(*ap, nullstr, 0);
12575 static int umaskcmd(int argc, char **argv)
12577 static const char permuser[3] = "ugo";
12578 static const char permmode[3] = "rwx";
12579 static const short int permmask[] = {
12580 S_IRUSR, S_IWUSR, S_IXUSR,
12581 S_IRGRP, S_IWGRP, S_IXGRP,
12582 S_IROTH, S_IWOTH, S_IXOTH
12588 int symbolic_mode = 0;
12590 while (nextopt("S") != '\0') {
12599 if ((ap = *argptr) == NULL) {
12600 if (symbolic_mode) {
12604 for (i = 0; i < 3; i++) {
12607 *p++ = permuser[i];
12609 for (j = 0; j < 3; j++) {
12610 if ((mask & permmask[3 * i + j]) == 0) {
12611 *p++ = permmode[j];
12619 out1fmt("%.4o\n", mask);
12622 if (is_digit((unsigned char) *ap)) {
12625 if (*ap >= '8' || *ap < '0')
12626 error(illnum, argv[1]);
12627 mask = (mask << 3) + (*ap - '0');
12628 } while (*++ap != '\0');
12631 mask = ~mask & 0777;
12632 if (!bb_parse_mode(ap, &mask)) {
12633 error("Illegal mode: %s", ap);
12635 umask(~mask & 0777);
12644 * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
12645 * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
12646 * ash by J.T. Conklin.
12654 int factor; /* multiply by to get rlim_{cur,max} values */
12658 static const struct limits limits[] = {
12660 { "time(seconds)", RLIMIT_CPU, 1, 't' },
12662 #ifdef RLIMIT_FSIZE
12663 { "file(blocks)", RLIMIT_FSIZE, 512, 'f' },
12666 { "data(kbytes)", RLIMIT_DATA, 1024, 'd' },
12668 #ifdef RLIMIT_STACK
12669 { "stack(kbytes)", RLIMIT_STACK, 1024, 's' },
12672 { "coredump(blocks)", RLIMIT_CORE, 512, 'c' },
12675 { "memory(kbytes)", RLIMIT_RSS, 1024, 'm' },
12677 #ifdef RLIMIT_MEMLOCK
12678 { "locked memory(kbytes)", RLIMIT_MEMLOCK, 1024, 'l' },
12680 #ifdef RLIMIT_NPROC
12681 { "process", RLIMIT_NPROC, 1, 'p' },
12683 #ifdef RLIMIT_NOFILE
12684 { "nofiles", RLIMIT_NOFILE, 1, 'n' },
12687 { "vmemory(kbytes)", RLIMIT_AS, 1024, 'v' },
12689 #ifdef RLIMIT_LOCKS
12690 { "locks", RLIMIT_LOCKS, 1, 'w' },
12692 { (char *) 0, 0, 0, '\0' }
12695 enum limtype { SOFT = 0x1, HARD = 0x2 };
12697 static void printlim(enum limtype how, const struct rlimit *limit,
12698 const struct limits *l)
12702 val = limit->rlim_max;
12704 val = limit->rlim_cur;
12706 if (val == RLIM_INFINITY)
12707 out1fmt("unlimited\n");
12710 out1fmt("%lld\n", (long long) val);
12715 ulimitcmd(int argc, char **argv)
12719 enum limtype how = SOFT | HARD;
12720 const struct limits *l;
12723 struct rlimit limit;
12726 while ((optc = nextopt("HSa"
12730 #ifdef RLIMIT_FSIZE
12736 #ifdef RLIMIT_STACK
12745 #ifdef RLIMIT_MEMLOCK
12748 #ifdef RLIMIT_NPROC
12751 #ifdef RLIMIT_NOFILE
12757 #ifdef RLIMIT_LOCKS
12775 for (l = limits; l->option != what; l++)
12778 set = *argptr ? 1 : 0;
12782 if (all || argptr[1])
12783 error("too many arguments");
12784 if (strncmp(p, "unlimited\n", 9) == 0)
12785 val = RLIM_INFINITY;
12789 while ((c = *p++) >= '0' && c <= '9')
12791 val = (val * 10) + (long)(c - '0');
12792 if (val < (rlim_t) 0)
12796 error("bad number");
12801 for (l = limits; l->name; l++) {
12802 getrlimit(l->cmd, &limit);
12803 out1fmt("%-20s ", l->name);
12804 printlim(how, &limit, l);
12809 getrlimit(l->cmd, &limit);
12812 limit.rlim_max = val;
12814 limit.rlim_cur = val;
12815 if (setrlimit(l->cmd, &limit) < 0)
12816 error("error setting limit (%m)");
12818 printlim(how, &limit, l);
12824 #ifdef CONFIG_ASH_MATH_SUPPORT
12826 /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com>
12828 Permission is hereby granted, free of charge, to any person obtaining
12829 a copy of this software and associated documentation files (the
12830 "Software"), to deal in the Software without restriction, including
12831 without limitation the rights to use, copy, modify, merge, publish,
12832 distribute, sublicense, and/or sell copies of the Software, and to
12833 permit persons to whom the Software is furnished to do so, subject to
12834 the following conditions:
12836 The above copyright notice and this permission notice shall be
12837 included in all copies or substantial portions of the Software.
12839 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12840 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12841 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
12842 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
12843 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
12844 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
12845 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12848 /* This is my infix parser/evaluator. It is optimized for size, intended
12849 * as a replacement for yacc-based parsers. However, it may well be faster
12850 * than a comparable parser writen in yacc. The supported operators are
12851 * listed in #defines below. Parens, order of operations, and error handling
12852 * are supported. This code is threadsafe. The exact expression format should
12853 * be that which POSIX specifies for shells. */
12855 /* The code uses a simple two-stack algorithm. See
12856 * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html
12857 * for a detailed explaination of the infix-to-postfix algorithm on which
12858 * this is based (this code differs in that it applies operators immediately
12859 * to the stack instead of adding them to a queue to end up with an
12862 /* To use the routine, call it with an expression string and error return
12866 * Aug 24, 2001 Manuel Novoa III
12868 * Reduced the generated code size by about 30% (i386) and fixed several bugs.
12870 * 1) In arith_apply():
12871 * a) Cached values of *numptr and &(numptr[-1]).
12872 * b) Removed redundant test for zero denominator.
12875 * a) Eliminated redundant code for processing operator tokens by moving
12876 * to a table-based implementation. Also folded handling of parens
12878 * b) Combined all 3 loops which called arith_apply to reduce generated
12879 * code size at the cost of speed.
12881 * 3) The following expressions were treated as valid by the original code:
12882 * 1() , 0! , 1 ( *3 ) .
12883 * These bugs have been fixed by internally enclosing the expression in
12884 * parens and then checking that all binary ops and right parens are
12885 * preceded by a valid expression (NUM_TOKEN).
12887 * Note: It may be desireable to replace Aaron's test for whitespace with
12888 * ctype's isspace() if it is used by another busybox applet or if additional
12889 * whitespace chars should be considered. Look below the "#include"s for a
12890 * precompiler test.
12894 * Aug 26, 2001 Manuel Novoa III
12896 * Return 0 for null expressions. Pointed out by Vladimir Oleynik.
12898 * Merge in Aaron's comments previously posted to the busybox list,
12899 * modified slightly to take account of my changes to the code.
12904 * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
12906 * - allow access to variable,
12907 * used recursive find value indirection (c=2*2; a="c"; $((a+=2)) produce 6)
12908 * - realize assign syntax (VAR=expr, +=, *= etc)
12909 * - realize exponentiation (** operator)
12910 * - realize comma separated - expr, expr
12911 * - realise ++expr --expr expr++ expr--
12912 * - realise expr ? expr : expr (but, second expr calculate always)
12913 * - allow hexdecimal and octal numbers
12914 * - was restored loses XOR operator
12915 * - remove one goto label, added three ;-)
12916 * - protect $((num num)) as true zero expr (Manuel`s error)
12917 * - always use special isspace(), see comment from bash ;-)
12921 #define arith_isspace(arithval) \
12922 (arithval == ' ' || arithval == '\n' || arithval == '\t')
12925 typedef unsigned char operator;
12927 /* An operator's token id is a bit of a bitfield. The lower 5 bits are the
12928 * precedence, and 3 high bits are an ID unique accross operators of that
12929 * precedence. The ID portion is so that multiple operators can have the
12930 * same precedence, ensuring that the leftmost one is evaluated first.
12931 * Consider * and /. */
12933 #define tok_decl(prec,id) (((id)<<5)|(prec))
12934 #define PREC(op) ((op) & 0x1F)
12936 #define TOK_LPAREN tok_decl(0,0)
12938 #define TOK_COMMA tok_decl(1,0)
12940 #define TOK_ASSIGN tok_decl(2,0)
12941 #define TOK_AND_ASSIGN tok_decl(2,1)
12942 #define TOK_OR_ASSIGN tok_decl(2,2)
12943 #define TOK_XOR_ASSIGN tok_decl(2,3)
12944 #define TOK_PLUS_ASSIGN tok_decl(2,4)
12945 #define TOK_MINUS_ASSIGN tok_decl(2,5)
12946 #define TOK_LSHIFT_ASSIGN tok_decl(2,6)
12947 #define TOK_RSHIFT_ASSIGN tok_decl(2,7)
12949 #define TOK_MUL_ASSIGN tok_decl(3,0)
12950 #define TOK_DIV_ASSIGN tok_decl(3,1)
12951 #define TOK_REM_ASSIGN tok_decl(3,2)
12953 /* all assign is right associativity and precedence eq, but (7+3)<<5 > 256 */
12954 #define convert_prec_is_assing(prec) do { if(prec == 3) prec = 2; } while(0)
12956 /* conditional is right associativity too */
12957 #define TOK_CONDITIONAL tok_decl(4,0)
12958 #define TOK_CONDITIONAL_SEP tok_decl(4,1)
12960 #define TOK_OR tok_decl(5,0)
12962 #define TOK_AND tok_decl(6,0)
12964 #define TOK_BOR tok_decl(7,0)
12966 #define TOK_BXOR tok_decl(8,0)
12968 #define TOK_BAND tok_decl(9,0)
12970 #define TOK_EQ tok_decl(10,0)
12971 #define TOK_NE tok_decl(10,1)
12973 #define TOK_LT tok_decl(11,0)
12974 #define TOK_GT tok_decl(11,1)
12975 #define TOK_GE tok_decl(11,2)
12976 #define TOK_LE tok_decl(11,3)
12978 #define TOK_LSHIFT tok_decl(12,0)
12979 #define TOK_RSHIFT tok_decl(12,1)
12981 #define TOK_ADD tok_decl(13,0)
12982 #define TOK_SUB tok_decl(13,1)
12984 #define TOK_MUL tok_decl(14,0)
12985 #define TOK_DIV tok_decl(14,1)
12986 #define TOK_REM tok_decl(14,2)
12988 /* exponent is right associativity */
12989 #define TOK_EXPONENT tok_decl(15,1)
12991 /* For now unary operators. */
12992 #define UNARYPREC 16
12993 #define TOK_BNOT tok_decl(UNARYPREC,0)
12994 #define TOK_NOT tok_decl(UNARYPREC,1)
12996 #define TOK_UMINUS tok_decl(UNARYPREC+1,0)
12997 #define TOK_UPLUS tok_decl(UNARYPREC+1,1)
12999 #define PREC_PRE (UNARYPREC+2)
13001 #define TOK_PRE_INC tok_decl(PREC_PRE, 0)
13002 #define TOK_PRE_DEC tok_decl(PREC_PRE, 1)
13004 #define PREC_POST (UNARYPREC+3)
13006 #define TOK_POST_INC tok_decl(PREC_POST, 0)
13007 #define TOK_POST_DEC tok_decl(PREC_POST, 1)
13009 #define SPEC_PREC (UNARYPREC+4)
13011 #define TOK_NUM tok_decl(SPEC_PREC, 0)
13012 #define TOK_RPAREN tok_decl(SPEC_PREC, 1)
13014 #define NUMPTR (*numstackptr)
13016 static inline int tok_have_assign(operator op)
13018 operator prec = PREC(op);
13020 convert_prec_is_assing(prec);
13021 return (prec == PREC(TOK_ASSIGN) ||
13022 prec == PREC_PRE || prec == PREC_POST);
13025 static inline int is_right_associativity(operator prec)
13027 return (prec == PREC(TOK_ASSIGN) || prec == PREC(TOK_EXPONENT) ||
13028 prec == PREC(TOK_CONDITIONAL));
13032 typedef struct ARITCH_VAR_NUM {
13034 long contidional_second_val;
13035 char contidional_second_val_initialized;
13036 char *var; /* if NULL then is regular number,
13037 else is varable name */
13041 typedef struct CHK_VAR_RECURSIVE_LOOPED {
13043 struct CHK_VAR_RECURSIVE_LOOPED *next;
13044 } chk_var_recursive_looped_t;
13046 static chk_var_recursive_looped_t *prev_chk_var_recursive;
13049 static int arith_lookup_val(v_n_t *t)
13052 const char * p = lookupvar(t->var);
13057 /* recursive try as expression */
13058 chk_var_recursive_looped_t *cur;
13059 chk_var_recursive_looped_t cur_save;
13061 for(cur = prev_chk_var_recursive; cur; cur = cur->next) {
13062 if(strcmp(cur->var, t->var) == 0) {
13063 /* expression recursion loop detected */
13067 /* save current lookuped var name */
13068 cur = prev_chk_var_recursive;
13069 cur_save.var = t->var;
13070 cur_save.next = cur;
13071 prev_chk_var_recursive = &cur_save;
13073 t->val = arith (p, &errcode);
13074 /* restore previous ptr after recursiving */
13075 prev_chk_var_recursive = cur;
13078 /* allow undefined var as 0 */
13085 /* "applying" a token means performing it on the top elements on the integer
13086 * stack. For a unary operator it will only change the top element, but a
13087 * binary operator will pop two arguments and push a result */
13089 arith_apply(operator op, v_n_t *numstack, v_n_t **numstackptr)
13094 int ret_arith_lookup_val;
13096 if (NUMPTR == numstack) goto err; /* There is no operator that can work
13097 without arguments */
13098 numptr_m1 = NUMPTR - 1;
13100 /* check operand is var with noninteger value */
13101 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
13102 if(ret_arith_lookup_val)
13103 return ret_arith_lookup_val;
13105 rez = numptr_m1->val;
13106 if (op == TOK_UMINUS)
13108 else if (op == TOK_NOT)
13110 else if (op == TOK_BNOT)
13112 else if (op == TOK_POST_INC || op == TOK_PRE_INC)
13114 else if (op == TOK_POST_DEC || op == TOK_PRE_DEC)
13116 else if (op != TOK_UPLUS) {
13117 /* Binary operators */
13119 /* check and binary operators need two arguments */
13120 if (numptr_m1 == numstack) goto err;
13122 /* ... and they pop one */
13125 if (op == TOK_CONDITIONAL) {
13126 if(! numptr_m1->contidional_second_val_initialized) {
13127 /* protect $((expr1 ? expr2)) without ": expr" */
13130 rez = numptr_m1->contidional_second_val;
13131 } else if(numptr_m1->contidional_second_val_initialized) {
13132 /* protect $((expr1 : expr2)) without "expr ? " */
13135 numptr_m1 = NUMPTR - 1;
13136 if(op != TOK_ASSIGN) {
13137 /* check operand is var with noninteger value for not '=' */
13138 ret_arith_lookup_val = arith_lookup_val(numptr_m1);
13139 if(ret_arith_lookup_val)
13140 return ret_arith_lookup_val;
13142 if (op == TOK_CONDITIONAL) {
13143 numptr_m1->contidional_second_val = rez;
13145 rez = numptr_m1->val;
13146 if (op == TOK_BOR || op == TOK_OR_ASSIGN)
13148 else if (op == TOK_OR)
13149 rez = numptr_val || rez;
13150 else if (op == TOK_BAND || op == TOK_AND_ASSIGN)
13152 else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN)
13154 else if (op == TOK_AND)
13155 rez = rez && numptr_val;
13156 else if (op == TOK_EQ)
13157 rez = (rez == numptr_val);
13158 else if (op == TOK_NE)
13159 rez = (rez != numptr_val);
13160 else if (op == TOK_GE)
13161 rez = (rez >= numptr_val);
13162 else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN)
13163 rez >>= numptr_val;
13164 else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN)
13165 rez <<= numptr_val;
13166 else if (op == TOK_GT)
13167 rez = (rez > numptr_val);
13168 else if (op == TOK_LT)
13169 rez = (rez < numptr_val);
13170 else if (op == TOK_LE)
13171 rez = (rez <= numptr_val);
13172 else if (op == TOK_MUL || op == TOK_MUL_ASSIGN)
13174 else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN)
13176 else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN)
13178 else if (op == TOK_ASSIGN || op == TOK_COMMA)
13180 else if (op == TOK_CONDITIONAL_SEP) {
13181 if (numptr_m1 == numstack) {
13182 /* protect $((expr : expr)) without "expr ? " */
13185 numptr_m1->contidional_second_val_initialized = op;
13186 numptr_m1->contidional_second_val = numptr_val;
13188 else if (op == TOK_CONDITIONAL) {
13190 numptr_val : numptr_m1->contidional_second_val;
13192 else if(op == TOK_EXPONENT) {
13194 return -3; /* exponent less than 0 */
13199 while(numptr_val--)
13204 else if(numptr_val==0) /* zero divisor check */
13206 else if (op == TOK_DIV || op == TOK_DIV_ASSIGN)
13208 else if (op == TOK_REM || op == TOK_REM_ASSIGN)
13211 if(tok_have_assign(op)) {
13214 if(numptr_m1->var == NULL) {
13218 /* save to shell variable */
13219 sprintf(buf, "%ld", rez);
13220 setvar(numptr_m1->var, buf, 0);
13221 /* after saving, make previous value for v++ or v-- */
13222 if(op == TOK_POST_INC)
13224 else if(op == TOK_POST_DEC)
13227 numptr_m1->val = rez;
13228 /* protect geting var value, is number now */
13229 numptr_m1->var = NULL;
13234 /* longest must first */
13235 static const char op_tokens[] = {
13236 '<','<','=',0, TOK_LSHIFT_ASSIGN,
13237 '>','>','=',0, TOK_RSHIFT_ASSIGN,
13238 '<','<', 0, TOK_LSHIFT,
13239 '>','>', 0, TOK_RSHIFT,
13240 '|','|', 0, TOK_OR,
13241 '&','&', 0, TOK_AND,
13242 '!','=', 0, TOK_NE,
13243 '<','=', 0, TOK_LE,
13244 '>','=', 0, TOK_GE,
13245 '=','=', 0, TOK_EQ,
13246 '|','=', 0, TOK_OR_ASSIGN,
13247 '&','=', 0, TOK_AND_ASSIGN,
13248 '*','=', 0, TOK_MUL_ASSIGN,
13249 '/','=', 0, TOK_DIV_ASSIGN,
13250 '%','=', 0, TOK_REM_ASSIGN,
13251 '+','=', 0, TOK_PLUS_ASSIGN,
13252 '-','=', 0, TOK_MINUS_ASSIGN,
13253 '-','-', 0, TOK_POST_DEC,
13254 '^','=', 0, TOK_XOR_ASSIGN,
13255 '+','+', 0, TOK_POST_INC,
13256 '*','*', 0, TOK_EXPONENT,
13260 '=', 0, TOK_ASSIGN,
13272 '?', 0, TOK_CONDITIONAL,
13273 ':', 0, TOK_CONDITIONAL_SEP,
13274 ')', 0, TOK_RPAREN,
13275 '(', 0, TOK_LPAREN,
13279 #define endexpression &op_tokens[sizeof(op_tokens)-7]
13282 extern long arith (const char *expr, int *perrcode)
13284 register char arithval; /* Current character under analysis */
13285 operator lasttok, op;
13288 const char *p = endexpression;
13291 size_t datasizes = strlen(expr) + 2;
13293 /* Stack of integers */
13294 /* The proof that there can be no more than strlen(startbuf)/2+1 integers
13295 * in any given correct or incorrect expression is left as an excersize to
13297 v_n_t *numstack = alloca(((datasizes)/2)*sizeof(v_n_t)),
13298 *numstackptr = numstack;
13299 /* Stack of operator tokens */
13300 operator *stack = alloca((datasizes) * sizeof(operator)),
13303 *stackptr++ = lasttok = TOK_LPAREN; /* start off with a left paren */
13304 *perrcode = errcode = 0;
13307 if ((arithval = *expr) == 0) {
13308 if (p == endexpression) {
13309 /* Null expression. */
13313 /* This is only reached after all tokens have been extracted from the
13314 * input stream. If there are still tokens on the operator stack, they
13315 * are to be applied in order. At the end, there should be a final
13316 * result on the integer stack */
13318 if (expr != endexpression + 1) {
13319 /* If we haven't done so already, */
13320 /* append a closing right paren */
13321 expr = endexpression;
13322 /* and let the loop process it. */
13325 /* At this point, we're done with the expression. */
13326 if (numstackptr != numstack+1) {
13327 /* ... but if there isn't, it's bad */
13329 return (*perrcode = -1);
13331 if(numstack->var) {
13332 /* expression is $((var)) only, lookup now */
13333 errcode = arith_lookup_val(numstack);
13336 *perrcode = errcode;
13337 return numstack->val;
13339 /* Continue processing the expression. */
13340 if (arith_isspace(arithval)) {
13341 /* Skip whitespace */
13344 if((p = endofname(expr)) != expr) {
13345 int var_name_size = (p-expr) + 1; /* trailing zero */
13347 numstackptr->var = alloca(var_name_size);
13348 safe_strncpy(numstackptr->var, expr, var_name_size);
13351 numstackptr->contidional_second_val_initialized = 0;
13355 } else if (is_digit(arithval)) {
13356 numstackptr->var = NULL;
13357 numstackptr->val = strtol(expr, (char **) &expr, 0);
13360 for(p = op_tokens; ; p++) {
13364 /* strange operator not found */
13367 for(o = expr; *p && *o == *p; p++)
13374 /* skip tail uncompared token */
13377 /* skip zero delim */
13382 /* post grammar: a++ reduce to num */
13383 if(lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC)
13386 /* Plus and minus are binary (not unary) _only_ if the last
13387 * token was as number, or a right paren (which pretends to be
13388 * a number, since it evaluates to one). Think about it.
13389 * It makes sense. */
13390 if (lasttok != TOK_NUM) {
13406 /* We don't want a unary operator to cause recursive descent on the
13407 * stack, because there can be many in a row and it could cause an
13408 * operator to be evaluated before its argument is pushed onto the
13409 * integer stack. */
13410 /* But for binary operators, "apply" everything on the operator
13411 * stack until we find an operator with a lesser priority than the
13412 * one we have just extracted. */
13413 /* Left paren is given the lowest priority so it will never be
13414 * "applied" in this way.
13415 * if associativity is right and priority eq, applied also skip
13418 if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) {
13419 /* not left paren or unary */
13420 if (lasttok != TOK_NUM) {
13421 /* binary op must be preceded by a num */
13424 while (stackptr != stack) {
13425 if (op == TOK_RPAREN) {
13426 /* The algorithm employed here is simple: while we don't
13427 * hit an open paren nor the bottom of the stack, pop
13428 * tokens and apply them */
13429 if (stackptr[-1] == TOK_LPAREN) {
13431 /* Any operator directly after a */
13433 /* close paren should consider itself binary */
13437 operator prev_prec = PREC(stackptr[-1]);
13439 convert_prec_is_assing(prec);
13440 convert_prec_is_assing(prev_prec);
13441 if (prev_prec < prec)
13443 /* check right assoc */
13444 if(prev_prec == prec && is_right_associativity(prec))
13447 errcode = arith_apply(*--stackptr, numstack, &numstackptr);
13448 if(errcode) goto ret;
13450 if (op == TOK_RPAREN) {
13455 /* Push this operator to the stack and remember it. */
13456 *stackptr++ = lasttok = op;
13463 #endif /* CONFIG_ASH_MATH_SUPPORT */
13467 const char *bb_applet_name = "debug stuff usage";
13468 int main(int argc, char **argv)
13470 return ash_main(argc, argv);
13475 * Copyright (c) 1989, 1991, 1993, 1994
13476 * The Regents of the University of California. All rights reserved.
13478 * This code is derived from software contributed to Berkeley by
13479 * Kenneth Almquist.
13481 * Redistribution and use in source and binary forms, with or without
13482 * modification, are permitted provided that the following conditions
13484 * 1. Redistributions of source code must retain the above copyright
13485 * notice, this list of conditions and the following disclaimer.
13486 * 2. Redistributions in binary form must reproduce the above copyright
13487 * notice, this list of conditions and the following disclaimer in the
13488 * documentation and/or other materials provided with the distribution.
13490 * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
13491 * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
13493 * 4. Neither the name of the University nor the names of its contributors
13494 * may be used to endorse or promote products derived from this software
13495 * without specific prior written permission.
13497 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
13498 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13499 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
13500 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
13501 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
13502 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
13503 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
13504 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
13505 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
13506 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF