Index: head/bin/sh/mkinit.c =================================================================== --- head/bin/sh/mkinit.c (revision 253649) +++ head/bin/sh/mkinit.c (nonexistent) @@ -1,480 +0,0 @@ -/*- - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#ifndef lint -static char const copyright[] = -"@(#) Copyright (c) 1991, 1993\n\ - The Regents of the University of California. All rights reserved.\n"; -#endif /* not lint */ - -#ifndef lint -#if 0 -static char sccsid[] = "@(#)mkinit.c 8.2 (Berkeley) 5/4/95"; -#endif -#endif /* not lint */ -#include -__FBSDID("$FreeBSD$"); - -/* - * This program scans all the source files for code to handle various - * special events and combines this code into one file. This (allegedly) - * improves the structure of the program since there is no need for - * anyone outside of a module to know that that module performs special - * operations on particular events. - * - * Usage: mkinit sourcefile... - */ - - -#include -#include -#include -#include -#include -#include -#include - - -/* - * OUTFILE is the name of the output file. Output is initially written - * to the file OUTTEMP, which is then moved to OUTFILE. - */ - -#define OUTFILE "init.c" -#define OUTTEMP "init.c.new" - - -/* - * A text structure is basically just a string that grows as more characters - * are added onto the end of it. It is implemented as a linked list of - * blocks of characters. The routines addstr and addchar append a string - * or a single character, respectively, to a text structure. Writetext - * writes the contents of a text structure to a file. - */ - -#define BLOCKSIZE 512 - -struct text { - char *nextc; - int nleft; - struct block *start; - struct block *last; -}; - -struct block { - struct block *next; - char text[BLOCKSIZE]; -}; - - -/* - * There is one event structure for each event that mkinit handles. - */ - -struct event { - const char *name; /* name of event (e.g. RESET) */ - const char *routine; /* name of routine called on event */ - const char *comment; /* comment describing routine */ - struct text code; /* code for handling event */ -}; - - -char writer[] = "\ -/*\n\ - * This file was generated by the mkinit program.\n\ - */\n\ -\n"; - -char reset[] = "\ -/*\n\ - * This routine is called when an error or an interrupt occurs in an\n\ - * interactive shell and control is returned to the main command loop.\n\ - */\n"; - - -struct event event[] = { - { "RESET", "reset", reset, { NULL, 0, NULL, NULL } }, - { NULL, NULL, NULL, { NULL, 0, NULL, NULL } } -}; - - -const char *curfile; /* current file */ -int linno; /* current line */ -char *header_files[200]; /* list of header files */ -struct text defines; /* #define statements */ -struct text decls; /* declarations */ -int amiddecls; /* for formatting */ - - -void readfile(const char *); -int match(const char *, const char *); -int gooddefine(const char *); -void doevent(struct event *, FILE *, const char *); -void doinclude(char *); -void dodecl(char *, FILE *); -void output(void); -void addstr(const char *, struct text *); -void addchar(int, struct text *); -void writetext(struct text *, FILE *); -FILE *ckfopen(const char *, const char *); -void *ckmalloc(size_t); -char *savestr(const char *); -void error(const char *); - -#define equal(s1, s2) (strcmp(s1, s2) == 0) - -int -main(int argc __unused, char *argv[]) -{ - char **ap; - - header_files[0] = savestr("\"shell.h\""); - header_files[1] = savestr("\"mystring.h\""); - header_files[2] = savestr("\"init.h\""); - for (ap = argv + 1 ; *ap ; ap++) - readfile(*ap); - output(); - rename(OUTTEMP, OUTFILE); - exit(0); -} - - -/* - * Parse an input file. - */ - -void -readfile(const char *fname) -{ - FILE *fp; - char line[1024]; - struct event *ep; - - fp = ckfopen(fname, "r"); - curfile = fname; - linno = 0; - amiddecls = 0; - while (fgets(line, sizeof line, fp) != NULL) { - linno++; - for (ep = event ; ep->name ; ep++) { - if (line[0] == ep->name[0] && match(ep->name, line)) { - doevent(ep, fp, fname); - break; - } - } - if (line[0] == 'I' && match("INCLUDE", line)) - doinclude(line); - if (line[0] == 'M' && match("MKINIT", line)) - dodecl(line, fp); - if (line[0] == '#' && gooddefine(line)) { - char *cp; - char line2[1024]; - static const char undef[] = "#undef "; - - strcpy(line2, line); - memcpy(line2, undef, sizeof(undef) - 1); - cp = line2 + sizeof(undef) - 1; - while(*cp && (*cp == ' ' || *cp == '\t')) - cp++; - while(*cp && *cp != ' ' && *cp != '\t' && *cp != '\n') - cp++; - *cp++ = '\n'; *cp = '\0'; - addstr(line2, &defines); - addstr(line, &defines); - } - } - fclose(fp); -} - - -int -match(const char *name, const char *line) -{ - const char *p, *q; - - p = name, q = line; - while (*p) { - if (*p++ != *q++) - return 0; - } - if (*q != '{' && *q != ' ' && *q != '\t' && *q != '\n') - return 0; - return 1; -} - - -int -gooddefine(const char *line) -{ - const char *p; - - if (! match("#define", line)) - return 0; /* not a define */ - p = line + 7; - while (*p == ' ' || *p == '\t') - p++; - while (*p != ' ' && *p != '\t') { - if (*p == '(') - return 0; /* macro definition */ - p++; - } - while (*p != '\n' && *p != '\0') - p++; - if (p[-1] == '\\') - return 0; /* multi-line definition */ - return 1; -} - - -void -doevent(struct event *ep, FILE *fp, const char *fname) -{ - char line[1024]; - int indent; - const char *p; - - sprintf(line, "\n /* from %s: */\n", fname); - addstr(line, &ep->code); - addstr(" {\n", &ep->code); - for (;;) { - linno++; - if (fgets(line, sizeof line, fp) == NULL) - error("Unexpected EOF"); - if (equal(line, "}\n")) - break; - indent = 6; - for (p = line ; *p == '\t' ; p++) - indent += 8; - for ( ; *p == ' ' ; p++) - indent++; - if (*p == '\n' || *p == '#') - indent = 0; - while (indent >= 8) { - addchar('\t', &ep->code); - indent -= 8; - } - while (indent > 0) { - addchar(' ', &ep->code); - indent--; - } - addstr(p, &ep->code); - } - addstr(" }\n", &ep->code); -} - - -void -doinclude(char *line) -{ - char *p; - char *name; - char **pp; - - for (p = line ; *p != '"' && *p != '<' && *p != '\0' ; p++); - if (*p == '\0') - error("Expecting '\"' or '<'"); - name = p; - while (*p != ' ' && *p != '\t' && *p != '\n') - p++; - if (p[-1] != '"' && p[-1] != '>') - error("Missing terminator"); - *p = '\0'; - - /* name now contains the name of the include file */ - for (pp = header_files ; *pp && ! equal(*pp, name) ; pp++); - if (*pp == NULL) - *pp = savestr(name); -} - - -void -dodecl(char *line1, FILE *fp) -{ - char line[1024]; - char *p, *q; - - if (strcmp(line1, "MKINIT\n") == 0) { /* start of struct/union decl */ - addchar('\n', &decls); - do { - linno++; - if (fgets(line, sizeof line, fp) == NULL) - error("Unterminated structure declaration"); - addstr(line, &decls); - } while (line[0] != '}'); - amiddecls = 0; - } else { - if (! amiddecls) - addchar('\n', &decls); - q = NULL; - for (p = line1 + 6 ; *p && strchr("=/\n", *p) == NULL; p++) - continue; - if (*p == '=') { /* eliminate initialization */ - for (q = p ; *q && *q != ';' ; q++); - if (*q == '\0') - q = NULL; - else { - while (p[-1] == ' ') - p--; - *p = '\0'; - } - } - addstr("extern", &decls); - addstr(line1 + 6, &decls); - if (q != NULL) - addstr(q, &decls); - amiddecls = 1; - } -} - - - -/* - * Write the output to the file OUTTEMP. - */ - -void -output(void) -{ - FILE *fp; - char **pp; - struct event *ep; - - fp = ckfopen(OUTTEMP, "w"); - fputs(writer, fp); - for (pp = header_files ; *pp ; pp++) - fprintf(fp, "#include %s\n", *pp); - fputs("\n\n\n", fp); - writetext(&defines, fp); - fputs("\n\n", fp); - writetext(&decls, fp); - for (ep = event ; ep->name ; ep++) { - fputs("\n\n\n", fp); - fputs(ep->comment, fp); - fprintf(fp, "\nvoid\n%s(void)\n{\n", ep->routine); - writetext(&ep->code, fp); - fprintf(fp, "}\n"); - } - fclose(fp); -} - - -/* - * A text structure is simply a block of text that is kept in memory. - * Addstr appends a string to the text struct, and addchar appends a single - * character. - */ - -void -addstr(const char *s, struct text *text) -{ - while (*s) { - if (--text->nleft < 0) - addchar(*s++, text); - else - *text->nextc++ = *s++; - } -} - - -void -addchar(int c, struct text *text) -{ - struct block *bp; - - if (--text->nleft < 0) { - bp = ckmalloc(sizeof *bp); - if (text->start == NULL) - text->start = bp; - else - text->last->next = bp; - text->last = bp; - text->nextc = bp->text; - text->nleft = BLOCKSIZE - 1; - } - *text->nextc++ = c; -} - -/* - * Write the contents of a text structure to a file. - */ -void -writetext(struct text *text, FILE *fp) -{ - struct block *bp; - - if (text->start != NULL) { - for (bp = text->start ; bp != text->last ; bp = bp->next) - fwrite(bp->text, sizeof (char), BLOCKSIZE, fp); - fwrite(bp->text, sizeof (char), BLOCKSIZE - text->nleft, fp); - } -} - -FILE * -ckfopen(const char *file, const char *mode) -{ - FILE *fp; - - if ((fp = fopen(file, mode)) == NULL) { - fprintf(stderr, "Can't open %s: %s\n", file, strerror(errno)); - exit(2); - } - return fp; -} - -void * -ckmalloc(size_t nbytes) -{ - char *p; - - if ((p = malloc(nbytes)) == NULL) - error("Out of space"); - return p; -} - -char * -savestr(const char *s) -{ - char *p; - - p = ckmalloc(strlen(s) + 1); - strcpy(p, s); - return p; -} - -void -error(const char *msg) -{ - if (curfile != NULL) - fprintf(stderr, "%s:%d: ", curfile, linno); - fprintf(stderr, "%s\n", msg); - exit(2); -} Property changes on: head/bin/sh/mkinit.c ___________________________________________________________________ Deleted: svn:keywords ## -1 +0,0 ## -FreeBSD=%H \ No newline at end of property Index: head/bin/sh/init.h =================================================================== --- head/bin/sh/init.h (revision 253649) +++ head/bin/sh/init.h (nonexistent) @@ -1,36 +0,0 @@ -/*- - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)init.h 8.2 (Berkeley) 5/4/95 - * $FreeBSD$ - */ - -void reset(void); Property changes on: head/bin/sh/init.h ___________________________________________________________________ Deleted: svn:keywords ## -1 +0,0 ## -FreeBSD=%H \ No newline at end of property Index: head/bin/sh/Makefile =================================================================== --- head/bin/sh/Makefile (revision 253649) +++ head/bin/sh/Makefile (revision 253650) @@ -1,70 +1,65 @@ # @(#)Makefile 8.4 (Berkeley) 5/5/95 # $FreeBSD$ PROG= sh INSTALLFLAGS= -S SHSRCS= alias.c arith_yacc.c arith_yylex.c cd.c echo.c error.c eval.c \ exec.c expand.c \ histedit.c input.c jobs.c kill.c mail.c main.c memalloc.c miscbltin.c \ mystring.c options.c output.c parser.c printf.c redir.c show.c \ test.c trap.c var.c -GENSRCS= builtins.c init.c nodes.c syntax.c +GENSRCS= builtins.c nodes.c syntax.c GENHDRS= builtins.h nodes.h syntax.h token.h SRCS= ${SHSRCS} ${GENSRCS} ${GENHDRS} # MLINKS for Shell built in commands for which there are no userland # utilities of the same name are handled with the associated manpage, # builtin.1 in share/man/man1/. DPADD= ${LIBEDIT} ${LIBTERMCAP} LDADD= -ledit -ltermcap CFLAGS+=-DSHELL -I. -I${.CURDIR} # for debug: # DEBUG_FLAGS+= -g -DDEBUG=2 -fno-inline WARNS?= 2 WFORMAT=0 .PATH: ${.CURDIR}/bltin \ ${.CURDIR}/../kill \ ${.CURDIR}/../test \ ${.CURDIR}/../../usr.bin/printf -CLEANFILES+= mkinit mkinit.o mknodes mknodes.o \ +CLEANFILES+= mknodes mknodes.o \ mksyntax mksyntax.o CLEANFILES+= ${GENSRCS} ${GENHDRS} -build-tools: mkinit mknodes mksyntax +build-tools: mknodes mksyntax .ORDER: builtins.c builtins.h builtins.c builtins.h: mkbuiltins builtins.def sh ${.CURDIR}/mkbuiltins ${.CURDIR} -init.c: mkinit alias.c eval.c exec.c input.c jobs.c options.c parser.c \ - redir.c trap.c var.c - ./mkinit ${.ALLSRC:S/^mkinit$//} - # XXX this is just to stop the default .c rule being used, so that the # intermediate object has a fixed name. # XXX we have a default .c rule, but no default .o rule. .o: ${CC} ${CFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} -o ${.TARGET} -mkinit: mkinit.o mknodes: mknodes.o mksyntax: mksyntax.o .ORDER: nodes.c nodes.h nodes.c nodes.h: mknodes nodetypes nodes.c.pat ./mknodes ${.CURDIR}/nodetypes ${.CURDIR}/nodes.c.pat .ORDER: syntax.c syntax.h syntax.c syntax.h: mksyntax ./mksyntax token.h: mktokens sh ${.CURDIR}/mktokens regress: cd ${.CURDIR}/../../tools/regression/bin/sh && ${MAKE} SH=${.OBJDIR}/sh .include Index: head/bin/sh/TOUR =================================================================== --- head/bin/sh/TOUR (revision 253649) +++ head/bin/sh/TOUR (revision 253650) @@ -1,315 +1,288 @@ # @(#)TOUR 8.1 (Berkeley) 5/31/93 # $FreeBSD$ NOTE -- This is the original TOUR paper distributed with ash and does not represent the current state of the shell. It is provided anyway since it provides helpful information for how the shell is structured, but be warned that things have changed -- the current shell is still under development. ================================================================ A Tour through Ash Copyright 1989 by Kenneth Almquist. DIRECTORIES: The subdirectory bltin contains commands which can be compiled stand-alone. The rest of the source is in the main ash directory. SOURCE CODE GENERATORS: Files whose names begin with "mk" are programs that generate source code. A complete list of these programs is: program input files generates ------- ----------- --------- mkbuiltins builtins builtins.h builtins.c - mkinit *.c init.c mknodes nodetypes nodes.h nodes.c mksyntax - syntax.h syntax.c mktokens - token.h -There are undoubtedly too many of these. Mkinit searches all the -C source files for entries looking like: - - RESET { - x = 2; /* executed when the shell does a longjmp - back to the main command loop */ - } - -It pulls this code out into routines which are when particular -events occur. The intent is to improve modularity by isolating -the information about which modules need to be explicitly -initialized/reset within the modules themselves. - -Mkinit recognizes several constructs for placing declarations in -the init.c file. - INCLUDE "file.h" -includes a file. The storage class MKINIT makes a declaration -available in the init.c file, for example: - MKINIT int funcnest; /* depth of function calls */ -MKINIT alone on a line introduces a structure or union declara- -tion: - MKINIT - struct redirtab { - short renamed[10]; - }; -Preprocessor #define statements are copied to init.c without any -special action to request this. +There are undoubtedly too many of these. EXCEPTIONS: Code for dealing with exceptions appears in exceptions.c. The C language doesn't include exception handling, so I implement it using setjmp and longjmp. The global variable exception contains the type of exception. EXERROR is raised by calling error. EXINT is an interrupt. INTERRUPTS: In an interactive shell, an interrupt will cause an EXINT exception to return to the main command loop. (Exception: EXINT is not raised if the user traps interrupts using the trap command.) The INTOFF and INTON macros (defined in exception.h) provide uninterruptible critical sections. Between the execution of INTOFF and the execution of INTON, interrupt signals will be held for later delivery. INTOFF and INTON can be nested. MEMALLOC.C: Memalloc.c defines versions of malloc and realloc which call error when there is no memory left. It also defines a stack oriented memory allocation scheme. Allocating off a stack is probably more efficient than allocation using malloc, but the big advantage is that when an exception occurs all we have to do to free up the memory in use at the time of the exception is to restore the stack pointer. The stack is implemented using a linked list of blocks. STPUTC: If the stack were contiguous, it would be easy to store strings on the stack without knowing in advance how long the string was going to be: p = stackptr; *p++ = c; /* repeated as many times as needed */ stackptr = p; The following three macros (defined in memalloc.h) perform these operations, but grow the stack if you run off the end: STARTSTACKSTR(p); STPUTC(c, p); /* repeated as many times as needed */ grabstackstr(p); We now start a top-down look at the code: MAIN.C: The main routine performs some initialization, executes the user's profile if necessary, and calls cmdloop. Cmdloop repeatedly parses and executes commands. OPTIONS.C: This file contains the option processing code. It is called from main to parse the shell arguments when the shell is invoked, and it also contains the set builtin. The -i and -m op- tions (the latter turns on job control) require changes in signal handling. The routines setjobctl (in jobs.c) and setinteractive (in trap.c) are called to handle changes to these options. PARSING: The parser code is all in parser.c. A recursive des- cent parser is used. Syntax tables (generated by mksyntax) are used to classify characters during lexical analysis. There are four tables: one for normal use, one for use when inside single quotes and dollar single quotes, one for use when inside double quotes and one for use in arithmetic. The tables are machine dependent because they are indexed by character variables and the range of a char varies from machine to machine. PARSE OUTPUT: The output of the parser consists of a tree of nodes. The various types of nodes are defined in the file node- types. Nodes of type NARG are used to represent both words and the con- tents of here documents. An early version of ash kept the con- tents of here documents in temporary files, but keeping here do- cuments in memory typically results in significantly better per- formance. It would have been nice to make it an option to use temporary files for here documents, for the benefit of small machines, but the code to keep track of when to delete the tem- porary files was complex and I never fixed all the bugs in it. (AT&T has been maintaining the Bourne shell for more than ten years, and to the best of my knowledge they still haven't gotten it to handle temporary files correctly in obscure cases.) The text field of a NARG structure points to the text of the word. The text consists of ordinary characters and a number of special codes defined in parser.h. The special codes are: CTLVAR Variable substitution CTLENDVAR End of variable substitution CTLBACKQ Command substitution CTLBACKQ|CTLQUOTE Command substitution inside double quotes CTLESC Escape next character A variable substitution contains the following elements: CTLVAR type name '=' [ alternative-text CTLENDVAR ] The type field is a single character specifying the type of sub- stitution. The possible types are: VSNORMAL $var VSMINUS ${var-text} VSMINUS|VSNUL ${var:-text} VSPLUS ${var+text} VSPLUS|VSNUL ${var:+text} VSQUESTION ${var?text} VSQUESTION|VSNUL ${var:?text} VSASSIGN ${var=text} VSASSIGN|VSNUL ${var:=text} In addition, the type field will have the VSQUOTE flag set if the variable is enclosed in double quotes. The name of the variable comes next, terminated by an equals sign. If the type is not VSNORMAL, then the text field in the substitution follows, ter- minated by a CTLENDVAR byte. Commands in back quotes are parsed and stored in a linked list. The locations of these commands in the string are indicated by CTLBACKQ and CTLBACKQ+CTLQUOTE characters, depending upon whether the back quotes were enclosed in double quotes. The character CTLESC escapes the next character, so that in case any of the CTL characters mentioned above appear in the input, they can be passed through transparently. CTLESC is also used to escape '*', '?', '[', and '!' characters which were quoted by the user and thus should not be used for file name generation. CTLESC characters have proved to be particularly tricky to get right. In the case of here documents which are not subject to variable and command substitution, the parser doesn't insert any CTLESC characters to begin with (so the contents of the text field can be written without any processing). Other here docu- ments, and words which are not subject to splitting and file name generation, have the CTLESC characters removed during the vari- able and command substitution phase. Words which are subject to splitting and file name generation have the CTLESC characters re- moved as part of the file name phase. EXECUTION: Command execution is handled by the following files: eval.c The top level routines. redir.c Code to handle redirection of input and output. jobs.c Code to handle forking, waiting, and job control. exec.c Code to do path searches and the actual exec sys call. expand.c Code to evaluate arguments. var.c Maintains the variable symbol table. Called from expand.c. EVAL.C: Evaltree recursively executes a parse tree. The exit status is returned in the global variable exitstatus. The alter- native entry evalbackcmd is called to evaluate commands in back quotes. It saves the result in memory if the command is a buil- tin; otherwise it forks off a child to execute the command and connects the standard output of the child to a pipe. JOBS.C: To create a process, you call makejob to return a job structure, and then call forkshell (passing the job structure as an argument) to create the process. Waitforjob waits for a job to complete. These routines take care of process groups if job control is defined. REDIR.C: Ash allows file descriptors to be redirected and then restored without forking off a child process. This is accom- plished by duplicating the original file descriptors. The redir- tab structure records where the file descriptors have been dupli- cated to. EXEC.C: The routine find_command locates a command, and enters the command in the hash table if it is not already there. The third argument specifies whether it is to print an error message if the command is not found. (When a pipeline is set up, find_command is called for all the commands in the pipeline be- fore any forking is done, so to get the commands into the hash table of the parent process. But to make command hashing as transparent as possible, we silently ignore errors at that point and only print error messages if the command cannot be found later.) The routine shellexec is the interface to the exec system call. EXPAND.C: Arguments are processed in three passes. The first (performed by the routine argstr) performs variable and command substitution. The second (ifsbreakup) performs word splitting and the third (expandmeta) performs file name generation. VAR.C: Variables are stored in a hash table. Probably we should switch to extensible hashing. The variable name is stored in the same string as the value (using the format "name=value") so that no string copying is needed to create the environment of a com- mand. Variables which the shell references internally are preal- located so that the shell can reference the values of these vari- ables without doing a lookup. When a program is run, the code in eval.c sticks any environment variables which precede the command (as in "PATH=xxx command") in the variable table as the simplest way to strip duplicates, and then calls "environment" to get the value of the environment. BUILTIN COMMANDS: The procedures for handling these are scat- tered throughout the code, depending on which location appears most appropriate. They can be recognized because their names al- ways end in "cmd". The mapping from names to procedures is specified in the file builtins, which is processed by the mkbuilt- ins command. A builtin command is invoked with argc and argv set up like a normal program. A builtin command is allowed to overwrite its arguments. Builtin routines can call nextopt to do option pars- ing. This is kind of like getopt, but you don't pass argc and argv to it. Builtin routines can also call error. This routine normally terminates the shell (or returns to the main command loop if the shell is interactive), but when called from a builtin command it causes the builtin command to terminate with an exit status of 2. The directory bltins contains commands which can be compiled in- dependently but can also be built into the shell for efficiency reasons. The makefile in this directory compiles these programs in the normal fashion (so that they can be run regardless of whether the invoker is ash), but also creates a library named bltinlib.a which can be linked with ash. The header file bltin.h takes care of most of the differences between the ash and the stand-alone environment. The user should call the main routine "main", and #define main to be the name of the routine to use when the program is linked into ash. This #define should appear before bltin.h is included; bltin.h will #undef main if the pro- gram is to be compiled stand-alone. CD.C: This file defines the cd and pwd builtins. SIGNALS: Trap.c implements the trap command. The routine set- signal figures out what action should be taken when a signal is received and invokes the signal system call to set the signal ac- tion appropriately. When a signal that a user has set a trap for is caught, the routine "onsig" sets a flag. The routine dotrap is called at appropriate points to actually handle the signal. When an interrupt is caught and no trap has been set for that signal, the routine "onint" in error.c is called. OUTPUT: Ash uses it's own output routines. There are three out- put structures allocated. "Output" represents the standard out- put, "errout" the standard error, and "memout" contains output which is to be stored in memory. This last is used when a buil- tin command appears in backquotes, to allow its output to be col- lected without doing any I/O through the UNIX operating system. The variables out1 and out2 normally point to output and errout, respectively, but they are set to point to memout when appropri- ate inside backquotes. INPUT: The basic input routine is pgetc, which reads from the current input file. There is a stack of input files; the current input file is the top file on this stack. The code allows the input to come from a string rather than a file. (This is for the -c option and the "." and eval builtin commands.) The global variable plinno is saved and restored when files are pushed and popped from the stack. The parser routines store the number of the current line in this variable. DEBUGGING: If DEBUG is defined in shell.h, then the shell will write debugging information to the file $HOME/trace. Most of this is done using the TRACE macro, which takes a set of printf arguments inside two sets of parenthesis. Example: "TRACE(("n=%d0, n))". The double parenthesis are necessary be- cause the preprocessor can't handle functions with a variable number of arguments. Defining DEBUG also causes the shell to generate a core dump if it is sent a quit signal. The tracing code is in show.c. Index: head/bin/sh/eval.c =================================================================== --- head/bin/sh/eval.c (revision 253649) +++ head/bin/sh/eval.c (revision 253650) @@ -1,1384 +1,1381 @@ /*- * Copyright (c) 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static char sccsid[] = "@(#)eval.c 8.9 (Berkeley) 6/8/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include /* For WIFSIGNALED(status) */ #include /* * Evaluate a command. */ #include "shell.h" #include "nodes.h" #include "syntax.h" #include "expand.h" #include "parser.h" #include "jobs.h" #include "eval.h" #include "builtins.h" #include "options.h" #include "exec.h" #include "redir.h" #include "input.h" #include "output.h" #include "trap.h" #include "var.h" #include "memalloc.h" #include "error.h" #include "show.h" #include "mystring.h" #ifndef NO_HISTORY #include "myhistedit.h" #endif int evalskip; /* set if we are skipping commands */ int skipcount; /* number of levels to skip */ MKINIT int loopnest; /* current loop nesting level */ int funcnest; /* depth of function calls */ static int builtin_flags; /* evalcommand flags for builtins */ char *commandname; struct strlist *cmdenviron; int exitstatus; /* exit status of last command */ int oexitstatus; /* saved exit status */ static void evalloop(union node *, int); static void evalfor(union node *, int); static union node *evalcase(union node *); static void evalsubshell(union node *, int); static void evalredir(union node *, int); static void exphere(union node *, struct arglist *); static void expredir(union node *); static void evalpipe(union node *); static int is_valid_fast_cmdsubst(union node *n); static void evalcommand(union node *, int, struct backcmd *); static void prehash(union node *); /* * Called to reset things after an exception. */ -#ifdef mkinit -INCLUDE "eval.h" - -RESET { +void +reseteval(void) +{ evalskip = 0; loopnest = 0; funcnest = 0; } -#endif - /* * The eval command. */ int evalcmd(int argc, char **argv) { char *p; char *concat; char **ap; if (argc > 1) { p = argv[1]; if (argc > 2) { STARTSTACKSTR(concat); ap = argv + 2; for (;;) { STPUTS(p, concat); if ((p = *ap++) == NULL) break; STPUTC(' ', concat); } STPUTC('\0', concat); p = grabstackstr(concat); } evalstring(p, builtin_flags); } else exitstatus = 0; return exitstatus; } /* * Execute a command or commands contained in a string. */ void evalstring(char *s, int flags) { union node *n; struct stackmark smark; int flags_exit; int any; flags_exit = flags & EV_EXIT; flags &= ~EV_EXIT; any = 0; setstackmark(&smark); setinputstring(s, 1); while ((n = parsecmd(0)) != NEOF) { if (n != NULL && !nflag) { if (flags_exit && preadateof()) evaltree(n, flags | EV_EXIT); else evaltree(n, flags); any = 1; } popstackmark(&smark); setstackmark(&smark); } popfile(); popstackmark(&smark); if (!any) exitstatus = 0; if (flags_exit) exraise(EXEXIT); } /* * Evaluate a parse tree. The value is left in the global variable * exitstatus. */ void evaltree(union node *n, int flags) { int do_etest; union node *next; struct stackmark smark; setstackmark(&smark); do_etest = 0; if (n == NULL) { TRACE(("evaltree(NULL) called\n")); exitstatus = 0; goto out; } do { next = NULL; #ifndef NO_HISTORY displayhist = 1; /* show history substitutions done with fc */ #endif TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type)); switch (n->type) { case NSEMI: evaltree(n->nbinary.ch1, flags & ~EV_EXIT); if (evalskip) goto out; next = n->nbinary.ch2; break; case NAND: evaltree(n->nbinary.ch1, EV_TESTED); if (evalskip || exitstatus != 0) { goto out; } next = n->nbinary.ch2; break; case NOR: evaltree(n->nbinary.ch1, EV_TESTED); if (evalskip || exitstatus == 0) goto out; next = n->nbinary.ch2; break; case NREDIR: evalredir(n, flags); break; case NSUBSHELL: evalsubshell(n, flags); do_etest = !(flags & EV_TESTED); break; case NBACKGND: evalsubshell(n, flags); break; case NIF: { evaltree(n->nif.test, EV_TESTED); if (evalskip) goto out; if (exitstatus == 0) next = n->nif.ifpart; else if (n->nif.elsepart) next = n->nif.elsepart; else exitstatus = 0; break; } case NWHILE: case NUNTIL: evalloop(n, flags & ~EV_EXIT); break; case NFOR: evalfor(n, flags & ~EV_EXIT); break; case NCASE: next = evalcase(n); break; case NCLIST: next = n->nclist.body; break; case NCLISTFALLTHRU: if (n->nclist.body) { evaltree(n->nclist.body, flags & ~EV_EXIT); if (evalskip) goto out; } next = n->nclist.next; break; case NDEFUN: defun(n->narg.text, n->narg.next); exitstatus = 0; break; case NNOT: evaltree(n->nnot.com, EV_TESTED); if (evalskip) goto out; exitstatus = !exitstatus; break; case NPIPE: evalpipe(n); do_etest = !(flags & EV_TESTED); break; case NCMD: evalcommand(n, flags, (struct backcmd *)NULL); do_etest = !(flags & EV_TESTED); break; default: out1fmt("Node type = %d\n", n->type); flushout(&output); break; } n = next; popstackmark(&smark); setstackmark(&smark); } while (n != NULL); out: popstackmark(&smark); if (pendingsig) dotrap(); if (eflag && exitstatus != 0 && do_etest) exitshell(exitstatus); if (flags & EV_EXIT) exraise(EXEXIT); } static void evalloop(union node *n, int flags) { int status; loopnest++; status = 0; for (;;) { evaltree(n->nbinary.ch1, EV_TESTED); if (evalskip) { skipping: if (evalskip == SKIPCONT && --skipcount <= 0) { evalskip = 0; continue; } if (evalskip == SKIPBREAK && --skipcount <= 0) evalskip = 0; if (evalskip == SKIPFUNC || evalskip == SKIPFILE) status = exitstatus; break; } if (n->type == NWHILE) { if (exitstatus != 0) break; } else { if (exitstatus == 0) break; } evaltree(n->nbinary.ch2, flags); status = exitstatus; if (evalskip) goto skipping; } loopnest--; exitstatus = status; } static void evalfor(union node *n, int flags) { struct arglist arglist; union node *argp; struct strlist *sp; int status; arglist.lastp = &arglist.list; for (argp = n->nfor.args ; argp ; argp = argp->narg.next) { oexitstatus = exitstatus; expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); } *arglist.lastp = NULL; loopnest++; status = 0; for (sp = arglist.list ; sp ; sp = sp->next) { setvar(n->nfor.var, sp->text, 0); evaltree(n->nfor.body, flags); status = exitstatus; if (evalskip) { if (evalskip == SKIPCONT && --skipcount <= 0) { evalskip = 0; continue; } if (evalskip == SKIPBREAK && --skipcount <= 0) evalskip = 0; break; } } loopnest--; exitstatus = status; } /* * Evaluate a case statement, returning the selected tree. * * The exit status needs care to get right. */ static union node * evalcase(union node *n) { union node *cp; union node *patp; struct arglist arglist; arglist.lastp = &arglist.list; oexitstatus = exitstatus; expandarg(n->ncase.expr, &arglist, EXP_TILDE); for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) { for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) { if (casematch(patp, arglist.list->text)) { while (cp->nclist.next && cp->type == NCLISTFALLTHRU && cp->nclist.body == NULL) cp = cp->nclist.next; if (cp->nclist.next && cp->type == NCLISTFALLTHRU) return (cp); if (cp->nclist.body == NULL) exitstatus = 0; return (cp->nclist.body); } } } exitstatus = 0; return (NULL); } /* * Kick off a subshell to evaluate a tree. */ static void evalsubshell(union node *n, int flags) { struct job *jp; int backgnd = (n->type == NBACKGND); oexitstatus = exitstatus; expredir(n->nredir.redirect); if ((!backgnd && flags & EV_EXIT && !have_traps()) || forkshell(jp = makejob(n, 1), n, backgnd) == 0) { if (backgnd) flags &=~ EV_TESTED; redirect(n->nredir.redirect, 0); evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */ } else if (! backgnd) { INTOFF; exitstatus = waitforjob(jp, (int *)NULL); INTON; } else exitstatus = 0; } /* * Evaluate a redirected compound command. */ static void evalredir(union node *n, int flags) { struct jmploc jmploc; struct jmploc *savehandler; volatile int in_redirect = 1; oexitstatus = exitstatus; expredir(n->nredir.redirect); savehandler = handler; if (setjmp(jmploc.loc)) { int e; handler = savehandler; e = exception; popredir(); if (e == EXERROR || e == EXEXEC) { if (in_redirect) { exitstatus = 2; return; } } longjmp(handler->loc, 1); } else { INTOFF; handler = &jmploc; redirect(n->nredir.redirect, REDIR_PUSH); in_redirect = 0; INTON; evaltree(n->nredir.n, flags); } INTOFF; handler = savehandler; popredir(); INTON; } static void exphere(union node *redir, struct arglist *fn) { struct jmploc jmploc; struct jmploc *savehandler; struct localvar *savelocalvars; int need_longjmp = 0; redir->nhere.expdoc = nullstr; savelocalvars = localvars; localvars = NULL; forcelocal++; savehandler = handler; if (setjmp(jmploc.loc)) need_longjmp = exception != EXERROR && exception != EXEXEC; else { handler = &jmploc; expandarg(redir->nhere.doc, fn, 0); redir->nhere.expdoc = fn->list->text; INTOFF; } handler = savehandler; forcelocal--; poplocalvars(); localvars = savelocalvars; if (need_longjmp) longjmp(handler->loc, 1); INTON; } /* * Compute the names of the files in a redirection list. */ static void expredir(union node *n) { union node *redir; for (redir = n ; redir ; redir = redir->nfile.next) { struct arglist fn; fn.lastp = &fn.list; switch (redir->type) { case NFROM: case NTO: case NFROMTO: case NAPPEND: case NCLOBBER: expandarg(redir->nfile.fname, &fn, EXP_TILDE | EXP_REDIR); redir->nfile.expfname = fn.list->text; break; case NFROMFD: case NTOFD: if (redir->ndup.vname) { expandarg(redir->ndup.vname, &fn, EXP_TILDE | EXP_REDIR); fixredir(redir, fn.list->text, 1); } break; case NXHERE: exphere(redir, &fn); break; } } } /* * Evaluate a pipeline. All the processes in the pipeline are children * of the process creating the pipeline. (This differs from some versions * of the shell, which make the last process in a pipeline the parent * of all the rest.) */ static void evalpipe(union node *n) { struct job *jp; struct nodelist *lp; int pipelen; int prevfd; int pip[2]; TRACE(("evalpipe(%p) called\n", (void *)n)); pipelen = 0; for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) pipelen++; INTOFF; jp = makejob(n, pipelen); prevfd = -1; for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) { prehash(lp->n); pip[1] = -1; if (lp->next) { if (pipe(pip) < 0) { if (prevfd >= 0) close(prevfd); error("Pipe call failed: %s", strerror(errno)); } } if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) { INTON; if (prevfd > 0) { dup2(prevfd, 0); close(prevfd); } if (pip[1] >= 0) { if (!(prevfd >= 0 && pip[0] == 0)) close(pip[0]); if (pip[1] != 1) { dup2(pip[1], 1); close(pip[1]); } } evaltree(lp->n, EV_EXIT); } if (prevfd >= 0) close(prevfd); prevfd = pip[0]; if (pip[1] != -1) close(pip[1]); } INTON; if (n->npipe.backgnd == 0) { INTOFF; exitstatus = waitforjob(jp, (int *)NULL); TRACE(("evalpipe: job done exit status %d\n", exitstatus)); INTON; } else exitstatus = 0; } static int is_valid_fast_cmdsubst(union node *n) { return (n->type == NCMD); } /* * Execute a command inside back quotes. If it's a builtin command, we * want to save its output in a block obtained from malloc. Otherwise * we fork off a subprocess and get the output of the command via a pipe. * Should be called with interrupts off. */ void evalbackcmd(union node *n, struct backcmd *result) { int pip[2]; struct job *jp; struct stackmark smark; struct jmploc jmploc; struct jmploc *savehandler; struct localvar *savelocalvars; setstackmark(&smark); result->fd = -1; result->buf = NULL; result->nleft = 0; result->jp = NULL; if (n == NULL) { exitstatus = 0; goto out; } exitstatus = oexitstatus; if (is_valid_fast_cmdsubst(n)) { savelocalvars = localvars; localvars = NULL; forcelocal++; savehandler = handler; if (setjmp(jmploc.loc)) { if (exception == EXERROR || exception == EXEXEC) exitstatus = 2; else if (exception != 0) { handler = savehandler; forcelocal--; poplocalvars(); localvars = savelocalvars; longjmp(handler->loc, 1); } } else { handler = &jmploc; evalcommand(n, EV_BACKCMD, result); } handler = savehandler; forcelocal--; poplocalvars(); localvars = savelocalvars; } else { if (pipe(pip) < 0) error("Pipe call failed: %s", strerror(errno)); jp = makejob(n, 1); if (forkshell(jp, n, FORK_NOJOB) == 0) { FORCEINTON; close(pip[0]); if (pip[1] != 1) { dup2(pip[1], 1); close(pip[1]); } evaltree(n, EV_EXIT); } close(pip[1]); result->fd = pip[0]; result->jp = jp; } out: popstackmark(&smark); TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n", result->fd, result->buf, result->nleft, result->jp)); } static int mustexpandto(const char *argtext, const char *mask) { for (;;) { if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) { argtext++; continue; } if (*argtext == CTLESC) argtext++; else if (BASESYNTAX[(int)*argtext] == CCTL) return (0); if (*argtext != *mask) return (0); if (*argtext == '\0') return (1); argtext++; mask++; } } static int isdeclarationcmd(struct narg *arg) { int have_command = 0; if (arg == NULL) return (0); while (mustexpandto(arg->text, "command")) { have_command = 1; arg = &arg->next->narg; if (arg == NULL) return (0); /* * To also allow "command -p" and "command --" as part of * a declaration command, add code here. * We do not do this, as ksh does not do it either and it * is not required by POSIX. */ } return (mustexpandto(arg->text, "export") || mustexpandto(arg->text, "readonly") || (mustexpandto(arg->text, "local") && (have_command || !isfunc("local")))); } /* * Check if a builtin can safely be executed in the same process, * even though it should be in a subshell (command substitution). * Note that jobid, jobs, times and trap can show information not * available in a child process; this is deliberate. * The arguments should already have been expanded. */ static int safe_builtin(int idx, int argc, char **argv) { if (idx == BLTINCMD || idx == COMMANDCMD || idx == ECHOCMD || idx == FALSECMD || idx == JOBIDCMD || idx == JOBSCMD || idx == KILLCMD || idx == PRINTFCMD || idx == PWDCMD || idx == TESTCMD || idx == TIMESCMD || idx == TRUECMD || idx == TYPECMD) return (1); if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || idx == UMASKCMD) return (argc <= 1 || (argc == 2 && argv[1][0] == '-')); if (idx == SETCMD) return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' || argv[1][0] == '+') && argv[1][1] == 'o' && argv[1][2] == '\0')); return (0); } /* * Execute a simple command. * Note: This may or may not return if (flags & EV_EXIT). */ static void evalcommand(union node *cmd, int flags, struct backcmd *backcmd) { union node *argp; struct arglist arglist; struct arglist varlist; char **argv; int argc; char **envp; int varflag; struct strlist *sp; int mode; int pip[2]; struct cmdentry cmdentry; struct job *jp; struct jmploc jmploc; struct jmploc *savehandler; char *savecmdname; struct shparam saveparam; struct localvar *savelocalvars; struct parsefile *savetopfile; volatile int e; char *lastarg; int realstatus; int do_clearcmdentry; const char *path = pathval(); /* First expand the arguments. */ TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags)); arglist.lastp = &arglist.list; varlist.lastp = &varlist.list; varflag = 1; jp = NULL; do_clearcmdentry = 0; oexitstatus = exitstatus; exitstatus = 0; for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) { if (varflag && isassignment(argp->narg.text)) { expandarg(argp, varflag == 1 ? &varlist : &arglist, EXP_VARTILDE); continue; } else if (varflag == 1) varflag = isdeclarationcmd(&argp->narg) ? 2 : 0; expandarg(argp, &arglist, EXP_FULL | EXP_TILDE); } *arglist.lastp = NULL; *varlist.lastp = NULL; expredir(cmd->ncmd.redirect); argc = 0; for (sp = arglist.list ; sp ; sp = sp->next) argc++; /* Add one slot at the beginning for tryexec(). */ argv = stalloc(sizeof (char *) * (argc + 2)); argv++; for (sp = arglist.list ; sp ; sp = sp->next) { TRACE(("evalcommand arg: %s\n", sp->text)); *argv++ = sp->text; } *argv = NULL; lastarg = NULL; if (iflag && funcnest == 0 && argc > 0) lastarg = argv[-1]; argv -= argc; /* Print the command if xflag is set. */ if (xflag) { char sep = 0; const char *p, *ps4; ps4 = expandstr(ps4val()); out2str(ps4 != NULL ? ps4 : ps4val()); for (sp = varlist.list ; sp ; sp = sp->next) { if (sep != 0) out2c(' '); p = strchr(sp->text, '='); if (p != NULL) { p++; outbin(sp->text, p - sp->text, out2); out2qstr(p); } else out2qstr(sp->text); sep = ' '; } for (sp = arglist.list ; sp ; sp = sp->next) { if (sep != 0) out2c(' '); /* Disambiguate command looking like assignment. */ if (sp == arglist.list && strchr(sp->text, '=') != NULL && strchr(sp->text, '\'') == NULL) { out2c('\''); out2str(sp->text); out2c('\''); } else out2qstr(sp->text); sep = ' '; } out2c('\n'); flushout(&errout); } /* Now locate the command. */ if (argc == 0) { /* Variable assignment(s) without command */ cmdentry.cmdtype = CMDBUILTIN; cmdentry.u.index = BLTINCMD; cmdentry.special = 0; } else { static const char PATH[] = "PATH="; int cmd_flags = 0, bltinonly = 0; /* * Modify the command lookup path, if a PATH= assignment * is present */ for (sp = varlist.list ; sp ; sp = sp->next) if (strncmp(sp->text, PATH, sizeof(PATH) - 1) == 0) { path = sp->text + sizeof(PATH) - 1; /* * On `PATH=... command`, we need to make * sure that the command isn't using the * non-updated hash table of the outer PATH * setting and we need to make sure that * the hash table isn't filled with items * from the temporary setting. * * It would be better to forbit using and * updating the table while this command * runs, by the command finding mechanism * is heavily integrated with hash handling, * so we just delete the hash before and after * the command runs. Partly deleting like * changepatch() does doesn't seem worth the * bookinging effort, since most such runs add * directories in front of the new PATH. */ clearcmdentry(); do_clearcmdentry = 1; } for (;;) { if (bltinonly) { cmdentry.u.index = find_builtin(*argv, &cmdentry.special); if (cmdentry.u.index < 0) { cmdentry.u.index = BLTINCMD; argv--; argc++; break; } } else find_command(argv[0], &cmdentry, cmd_flags, path); /* implement the bltin and command builtins here */ if (cmdentry.cmdtype != CMDBUILTIN) break; if (cmdentry.u.index == BLTINCMD) { if (argc == 1) break; argv++; argc--; bltinonly = 1; } else if (cmdentry.u.index == COMMANDCMD) { if (argc == 1) break; if (!strcmp(argv[1], "-p")) { if (argc == 2) break; if (argv[2][0] == '-') { if (strcmp(argv[2], "--")) break; if (argc == 3) break; argv += 3; argc -= 3; } else { argv += 2; argc -= 2; } path = _PATH_STDPATH; clearcmdentry(); do_clearcmdentry = 1; } else if (!strcmp(argv[1], "--")) { if (argc == 2) break; argv += 2; argc -= 2; } else if (argv[1][0] == '-') break; else { argv++; argc--; } cmd_flags |= DO_NOFUNC; bltinonly = 0; } else break; } /* * Special builtins lose their special properties when * called via 'command'. */ if (cmd_flags & DO_NOFUNC) cmdentry.special = 0; } /* Fork off a child process if necessary. */ if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN) && ((flags & EV_EXIT) == 0 || have_traps())) || ((flags & EV_BACKCMD) != 0 && (cmdentry.cmdtype != CMDBUILTIN || !safe_builtin(cmdentry.u.index, argc, argv)))) { jp = makejob(cmd, 1); mode = FORK_FG; if (flags & EV_BACKCMD) { mode = FORK_NOJOB; if (pipe(pip) < 0) error("Pipe call failed: %s", strerror(errno)); } if (cmdentry.cmdtype == CMDNORMAL && cmd->ncmd.redirect == NULL && varlist.list == NULL && (mode == FORK_FG || mode == FORK_NOJOB) && !disvforkset() && !iflag && !mflag) { vforkexecshell(jp, argv, environment(), path, cmdentry.u.index, flags & EV_BACKCMD ? pip : NULL); goto parent; } if (forkshell(jp, cmd, mode) != 0) goto parent; /* at end of routine */ if (flags & EV_BACKCMD) { FORCEINTON; close(pip[0]); if (pip[1] != 1) { dup2(pip[1], 1); close(pip[1]); } flags &= ~EV_BACKCMD; } flags |= EV_EXIT; } /* This is the child process if a fork occurred. */ /* Execute the command. */ if (cmdentry.cmdtype == CMDFUNCTION) { #ifdef DEBUG trputs("Shell function: "); trargs(argv); #endif saveparam = shellparam; shellparam.malloc = 0; shellparam.reset = 1; shellparam.nparam = argc - 1; shellparam.p = argv + 1; shellparam.optnext = NULL; INTOFF; savelocalvars = localvars; localvars = NULL; reffunc(cmdentry.u.func); savehandler = handler; if (setjmp(jmploc.loc)) { freeparam(&shellparam); shellparam = saveparam; popredir(); unreffunc(cmdentry.u.func); poplocalvars(); localvars = savelocalvars; funcnest--; handler = savehandler; longjmp(handler->loc, 1); } handler = &jmploc; funcnest++; redirect(cmd->ncmd.redirect, REDIR_PUSH); INTON; for (sp = varlist.list ; sp ; sp = sp->next) mklocal(sp->text); exitstatus = oexitstatus; evaltree(getfuncnode(cmdentry.u.func), flags & (EV_TESTED | EV_EXIT)); INTOFF; unreffunc(cmdentry.u.func); poplocalvars(); localvars = savelocalvars; freeparam(&shellparam); shellparam = saveparam; handler = savehandler; funcnest--; popredir(); INTON; if (evalskip == SKIPFUNC) { evalskip = 0; skipcount = 0; } if (jp) exitshell(exitstatus); } else if (cmdentry.cmdtype == CMDBUILTIN) { #ifdef DEBUG trputs("builtin command: "); trargs(argv); #endif mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH; if (flags == EV_BACKCMD) { memout.nleft = 0; memout.nextc = memout.buf; memout.bufsize = 64; mode |= REDIR_BACKQ; } savecmdname = commandname; savetopfile = getcurrentfile(); cmdenviron = varlist.list; e = -1; savehandler = handler; if (setjmp(jmploc.loc)) { e = exception; if (e == EXINT) exitstatus = SIGINT+128; else if (e != EXEXIT) exitstatus = 2; goto cmddone; } handler = &jmploc; redirect(cmd->ncmd.redirect, mode); outclearerror(out1); /* * If there is no command word, redirection errors should * not be fatal but assignment errors should. */ if (argc == 0) cmdentry.special = 1; listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); if (argc > 0) bltinsetlocale(); commandname = argv[0]; argptr = argv + 1; nextopt_optptr = NULL; /* initialize nextopt */ builtin_flags = flags; exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv); flushall(); if (outiserror(out1)) { warning("write error on stdout"); if (exitstatus == 0 || exitstatus == 1) exitstatus = 2; } cmddone: if (argc > 0) bltinunsetlocale(); cmdenviron = NULL; out1 = &output; out2 = &errout; freestdout(); handler = savehandler; commandname = savecmdname; if (jp) exitshell(exitstatus); if (flags == EV_BACKCMD) { backcmd->buf = memout.buf; backcmd->nleft = memout.nextc - memout.buf; memout.buf = NULL; } if (cmdentry.u.index != EXECCMD) popredir(); if (e != -1) { if ((e != EXERROR && e != EXEXEC) || cmdentry.special) exraise(e); popfilesupto(savetopfile); if (flags != EV_BACKCMD) FORCEINTON; } } else { #ifdef DEBUG trputs("normal command: "); trargs(argv); #endif redirect(cmd->ncmd.redirect, 0); for (sp = varlist.list ; sp ; sp = sp->next) setvareq(sp->text, VEXPORT|VSTACK); envp = environment(); shellexec(argv, envp, path, cmdentry.u.index); /*NOTREACHED*/ } goto out; parent: /* parent process gets here (if we forked) */ if (mode == FORK_FG) { /* argument to fork */ INTOFF; exitstatus = waitforjob(jp, &realstatus); INTON; if (iflag && loopnest > 0 && WIFSIGNALED(realstatus)) { evalskip = SKIPBREAK; skipcount = loopnest; } } else if (mode == FORK_NOJOB) { backcmd->fd = pip[0]; close(pip[1]); backcmd->jp = jp; } out: if (lastarg) setvar("_", lastarg, 0); if (do_clearcmdentry) clearcmdentry(); } /* * Search for a command. This is called before we fork so that the * location of the command will be available in the parent as well as * the child. The check for "goodname" is an overly conservative * check that the name will not be subject to expansion. */ static void prehash(union node *n) { struct cmdentry entry; if (n && n->type == NCMD && n->ncmd.args) if (goodname(n->ncmd.args->narg.text)) find_command(n->ncmd.args->narg.text, &entry, 0, pathval()); } /* * Builtin commands. Builtin commands whose functions are closely * tied to evaluation are implemented here. */ /* * No command given, a bltin command with no arguments, or a bltin command * with an invalid name. */ int bltincmd(int argc, char **argv) { if (argc > 1) { out2fmt_flush("%s: not found\n", argv[1]); return 127; } /* * Preserve exitstatus of a previous possible redirection * as POSIX mandates */ return exitstatus; } /* * Handle break and continue commands. Break, continue, and return are * all handled by setting the evalskip flag. The evaluation routines * above all check this flag, and if it is set they start skipping * commands rather than executing them. The variable skipcount is * the number of loops to break/continue, or the number of function * levels to return. (The latter is always 1.) It should probably * be an error to break out of more loops than exist, but it isn't * in the standard shell so we don't make it one here. */ int breakcmd(int argc, char **argv) { int n = argc > 1 ? number(argv[1]) : 1; if (n > loopnest) n = loopnest; if (n > 0) { evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK; skipcount = n; } return 0; } /* * The `command' command. */ int commandcmd(int argc __unused, char **argv __unused) { const char *path; int ch; int cmd = -1; path = bltinlookup("PATH", 1); while ((ch = nextopt("pvV")) != '\0') { switch (ch) { case 'p': path = _PATH_STDPATH; break; case 'v': cmd = TYPECMD_SMALLV; break; case 'V': cmd = TYPECMD_BIGV; break; } } if (cmd != -1) { if (*argptr == NULL || argptr[1] != NULL) error("wrong number of arguments"); return typecmd_impl(2, argptr - 1, cmd, path); } if (*argptr != NULL) error("commandcmd bad call"); /* * Do nothing successfully if no command was specified; * ksh also does this. */ return 0; } /* * The return command. */ int returncmd(int argc, char **argv) { int ret = argc > 1 ? number(argv[1]) : oexitstatus; if (funcnest) { evalskip = SKIPFUNC; skipcount = 1; } else { /* skip the rest of the file */ evalskip = SKIPFILE; skipcount = 1; } return ret; } int falsecmd(int argc __unused, char **argv __unused) { return 1; } int truecmd(int argc __unused, char **argv __unused) { return 0; } int execcmd(int argc, char **argv) { /* * Because we have historically not supported any options, * only treat "--" specially. */ if (argc > 1 && strcmp(argv[1], "--") == 0) argc--, argv++; if (argc > 1) { struct strlist *sp; iflag = 0; /* exit on error */ mflag = 0; optschanged(); for (sp = cmdenviron; sp ; sp = sp->next) setvareq(sp->text, VEXPORT|VSTACK); shellexec(argv + 1, environment(), pathval(), 0); } return 0; } int timescmd(int argc __unused, char **argv __unused) { struct rusage ru; long shumins, shsmins, chumins, chsmins; double shusecs, shssecs, chusecs, chssecs; if (getrusage(RUSAGE_SELF, &ru) < 0) return 1; shumins = ru.ru_utime.tv_sec / 60; shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; shsmins = ru.ru_stime.tv_sec / 60; shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; if (getrusage(RUSAGE_CHILDREN, &ru) < 0) return 1; chumins = ru.ru_utime.tv_sec / 60; chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.; chsmins = ru.ru_stime.tv_sec / 60; chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.; out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins, shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs); return 0; } Index: head/bin/sh/eval.h =================================================================== --- head/bin/sh/eval.h (revision 253649) +++ head/bin/sh/eval.h (revision 253650) @@ -1,69 +1,71 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)eval.h 8.2 (Berkeley) 5/4/95 * $FreeBSD$ */ extern char *commandname; /* currently executing command */ extern int exitstatus; /* exit status of last command */ extern int oexitstatus; /* saved exit status */ extern struct strlist *cmdenviron; /* environment for builtin command */ struct backcmd { /* result of evalbackcmd */ int fd; /* file descriptor to read from */ char *buf; /* buffer */ int nleft; /* number of chars in buffer */ struct job *jp; /* job structure for command */ }; +void reseteval(void); + /* flags in argument to evaltree/evalstring */ #define EV_EXIT 01 /* exit after evaluating tree */ #define EV_TESTED 02 /* exit status is checked; ignore -e flag */ #define EV_BACKCMD 04 /* command executing within back quotes */ void evalstring(char *, int); union node; /* BLETCH for ansi C */ void evaltree(union node *, int); void evalbackcmd(union node *, struct backcmd *); /* in_function returns nonzero if we are currently evaluating a function */ #define in_function() funcnest extern int funcnest; extern int evalskip; extern int skipcount; /* reasons for skipping commands (see comment on breakcmd routine) */ #define SKIPBREAK 1 #define SKIPCONT 2 #define SKIPFUNC 3 #define SKIPFILE 4 Index: head/bin/sh/exec.c =================================================================== --- head/bin/sh/exec.c (revision 253649) +++ head/bin/sh/exec.c (revision 253650) @@ -1,767 +1,766 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static char sccsid[] = "@(#)exec.c 8.4 (Berkeley) 6/8/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include /* * When commands are first encountered, they are entered in a hash table. * This ensures that a full path search will not have to be done for them * on each invocation. * * We should investigate converting to a linear search, even though that * would make the command name "hash" a misnomer. */ #include "shell.h" #include "main.h" #include "nodes.h" #include "parser.h" #include "redir.h" #include "eval.h" #include "exec.h" #include "builtins.h" #include "var.h" #include "options.h" #include "input.h" #include "output.h" #include "syntax.h" #include "memalloc.h" #include "error.h" -#include "init.h" #include "mystring.h" #include "show.h" #include "jobs.h" #include "alias.h" #define CMDTABLESIZE 31 /* should be prime */ struct tblentry { struct tblentry *next; /* next entry in hash chain */ union param param; /* definition of builtin function */ int special; /* flag for special builtin commands */ signed char cmdtype; /* index identifying command */ char cmdname[]; /* name of command */ }; static struct tblentry *cmdtable[CMDTABLESIZE]; static int cmdtable_cd = 0; /* cmdtable contains cd-dependent entries */ int exerrno = 0; /* Last exec error */ static void tryexec(char *, char **, char **); static void printentry(struct tblentry *, int); static struct tblentry *cmdlookup(const char *, int); static void delete_cmd_entry(void); static void addcmdentry(const char *, struct cmdentry *); /* * Exec a program. Never returns. If you change this routine, you may * have to change the find_command routine as well. * * The argv array may be changed and element argv[-1] should be writable. */ void shellexec(char **argv, char **envp, const char *path, int idx) { char *cmdname; int e; if (strchr(argv[0], '/') != NULL) { tryexec(argv[0], argv, envp); e = errno; } else { e = ENOENT; while ((cmdname = padvance(&path, argv[0])) != NULL) { if (--idx < 0 && pathopt == NULL) { tryexec(cmdname, argv, envp); if (errno != ENOENT && errno != ENOTDIR) e = errno; if (e == ENOEXEC) break; } stunalloc(cmdname); } } /* Map to POSIX errors */ if (e == ENOENT || e == ENOTDIR) { exerrno = 127; exerror(EXEXEC, "%s: not found", argv[0]); } else { exerrno = 126; exerror(EXEXEC, "%s: %s", argv[0], strerror(e)); } } static void tryexec(char *cmd, char **argv, char **envp) { int e, in; ssize_t n; char buf[256]; execve(cmd, argv, envp); e = errno; if (e == ENOEXEC) { INTOFF; in = open(cmd, O_RDONLY | O_NONBLOCK); if (in != -1) { n = pread(in, buf, sizeof buf, 0); close(in); if (n > 0 && memchr(buf, '\0', n) != NULL) { errno = ENOEXEC; return; } } *argv = cmd; *--argv = __DECONST(char *, _PATH_BSHELL); execve(_PATH_BSHELL, argv, envp); } errno = e; } /* * Do a path search. The variable path (passed by reference) should be * set to the start of the path before the first call; padvance will update * this value as it proceeds. Successive calls to padvance will return * the possible path expansions in sequence. If an option (indicated by * a percent sign) appears in the path entry then the global variable * pathopt will be set to point to it; otherwise pathopt will be set to * NULL. */ const char *pathopt; char * padvance(const char **path, const char *name) { const char *p, *start; char *q; size_t len; if (*path == NULL) return NULL; start = *path; for (p = start; *p && *p != ':' && *p != '%'; p++) ; /* nothing */ len = p - start + strlen(name) + 2; /* "2" is for '/' and '\0' */ STARTSTACKSTR(q); CHECKSTRSPACE(len, q); if (p != start) { memcpy(q, start, p - start); q += p - start; *q++ = '/'; } strcpy(q, name); pathopt = NULL; if (*p == '%') { pathopt = ++p; while (*p && *p != ':') p++; } if (*p == ':') *path = p + 1; else *path = NULL; return stalloc(len); } /*** Command hashing code ***/ int hashcmd(int argc __unused, char **argv __unused) { struct tblentry **pp; struct tblentry *cmdp; int c; int verbose; struct cmdentry entry; char *name; int errors; errors = 0; verbose = 0; while ((c = nextopt("rv")) != '\0') { if (c == 'r') { clearcmdentry(); } else if (c == 'v') { verbose++; } } if (*argptr == NULL) { for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) { for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) { if (cmdp->cmdtype == CMDNORMAL) printentry(cmdp, verbose); } } return 0; } while ((name = *argptr) != NULL) { if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDNORMAL) delete_cmd_entry(); find_command(name, &entry, DO_ERR, pathval()); if (entry.cmdtype == CMDUNKNOWN) errors = 1; else if (verbose) { cmdp = cmdlookup(name, 0); if (cmdp != NULL) printentry(cmdp, verbose); else { outfmt(out2, "%s: not found\n", name); errors = 1; } flushall(); } argptr++; } return errors; } static void printentry(struct tblentry *cmdp, int verbose) { int idx; const char *path; char *name; if (cmdp->cmdtype == CMDNORMAL) { idx = cmdp->param.index; path = pathval(); do { name = padvance(&path, cmdp->cmdname); stunalloc(name); } while (--idx >= 0); out1str(name); } else if (cmdp->cmdtype == CMDBUILTIN) { out1fmt("builtin %s", cmdp->cmdname); } else if (cmdp->cmdtype == CMDFUNCTION) { out1fmt("function %s", cmdp->cmdname); if (verbose) { INTOFF; name = commandtext(getfuncnode(cmdp->param.func)); out1c(' '); out1str(name); ckfree(name); INTON; } #ifdef DEBUG } else { error("internal error: cmdtype %d", cmdp->cmdtype); #endif } out1c('\n'); } /* * Resolve a command name. If you change this routine, you may have to * change the shellexec routine as well. */ void find_command(const char *name, struct cmdentry *entry, int act, const char *path) { struct tblentry *cmdp, loc_cmd; int idx; char *fullname; struct stat statb; int e; int i; int spec; int cd; /* If name contains a slash, don't use the hash table */ if (strchr(name, '/') != NULL) { entry->cmdtype = CMDNORMAL; entry->u.index = 0; return; } cd = 0; /* If name is in the table, and not invalidated by cd, we're done */ if ((cmdp = cmdlookup(name, 0)) != NULL) { if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC) cmdp = NULL; else goto success; } /* Check for builtin next */ if ((i = find_builtin(name, &spec)) >= 0) { INTOFF; cmdp = cmdlookup(name, 1); if (cmdp->cmdtype == CMDFUNCTION) cmdp = &loc_cmd; cmdp->cmdtype = CMDBUILTIN; cmdp->param.index = i; cmdp->special = spec; INTON; goto success; } /* We have to search path. */ e = ENOENT; idx = -1; loop: while ((fullname = padvance(&path, name)) != NULL) { stunalloc(fullname); idx++; if (pathopt) { if (prefix("func", pathopt)) { /* handled below */ } else { goto loop; /* ignore unimplemented options */ } } if (fullname[0] != '/') cd = 1; if (stat(fullname, &statb) < 0) { if (errno != ENOENT && errno != ENOTDIR) e = errno; goto loop; } e = EACCES; /* if we fail, this will be the error */ if (!S_ISREG(statb.st_mode)) goto loop; if (pathopt) { /* this is a %func directory */ stalloc(strlen(fullname) + 1); readcmdfile(fullname); if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION) error("%s not defined in %s", name, fullname); stunalloc(fullname); goto success; } #ifdef notdef if (statb.st_uid == geteuid()) { if ((statb.st_mode & 0100) == 0) goto loop; } else if (statb.st_gid == getegid()) { if ((statb.st_mode & 010) == 0) goto loop; } else { if ((statb.st_mode & 01) == 0) goto loop; } #endif TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname)); INTOFF; cmdp = cmdlookup(name, 1); if (cmdp->cmdtype == CMDFUNCTION) cmdp = &loc_cmd; cmdp->cmdtype = CMDNORMAL; cmdp->param.index = idx; INTON; goto success; } if (act & DO_ERR) { if (e == ENOENT || e == ENOTDIR) outfmt(out2, "%s: not found\n", name); else outfmt(out2, "%s: %s\n", name, strerror(e)); } entry->cmdtype = CMDUNKNOWN; entry->u.index = 0; return; success: if (cd) cmdtable_cd = 1; entry->cmdtype = cmdp->cmdtype; entry->u = cmdp->param; entry->special = cmdp->special; } /* * Search the table of builtin commands. */ int find_builtin(const char *name, int *special) { const struct builtincmd *bp; for (bp = builtincmd ; bp->name ; bp++) { if (*bp->name == *name && equal(bp->name, name)) { *special = bp->special; return bp->code; } } return -1; } /* * Called when a cd is done. If any entry in cmdtable depends on the current * directory, simply clear cmdtable completely. */ void hashcd(void) { if (cmdtable_cd) clearcmdentry(); } /* * Called before PATH is changed. The argument is the new value of PATH; * pathval() still returns the old value at this point. Called with * interrupts off. */ void changepath(const char *newval __unused) { clearcmdentry(); } /* * Clear out command entries. The argument specifies the first entry in * PATH which has changed. */ void clearcmdentry(void) { struct tblentry **tblp; struct tblentry **pp; struct tblentry *cmdp; INTOFF; for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) { pp = tblp; while ((cmdp = *pp) != NULL) { if (cmdp->cmdtype == CMDNORMAL) { *pp = cmdp->next; ckfree(cmdp); } else { pp = &cmdp->next; } } } cmdtable_cd = 0; INTON; } /* * Locate a command in the command hash table. If "add" is nonzero, * add the command to the table if it is not already present. The * variable "lastcmdentry" is set to point to the address of the link * pointing to the entry, so that delete_cmd_entry can delete the * entry. */ static struct tblentry **lastcmdentry; static struct tblentry * cmdlookup(const char *name, int add) { int hashval; const char *p; struct tblentry *cmdp; struct tblentry **pp; p = name; hashval = *p << 4; while (*p) hashval += *p++; hashval &= 0x7FFF; pp = &cmdtable[hashval % CMDTABLESIZE]; for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) { if (equal(cmdp->cmdname, name)) break; pp = &cmdp->next; } if (add && cmdp == NULL) { INTOFF; cmdp = *pp = ckmalloc(sizeof (struct tblentry) + strlen(name) + 1); cmdp->next = NULL; cmdp->cmdtype = CMDUNKNOWN; strcpy(cmdp->cmdname, name); INTON; } lastcmdentry = pp; return cmdp; } /* * Delete the command entry returned on the last lookup. */ static void delete_cmd_entry(void) { struct tblentry *cmdp; INTOFF; cmdp = *lastcmdentry; *lastcmdentry = cmdp->next; ckfree(cmdp); INTON; } /* * Add a new command entry, replacing any existing command entry for * the same name. */ static void addcmdentry(const char *name, struct cmdentry *entry) { struct tblentry *cmdp; INTOFF; cmdp = cmdlookup(name, 1); if (cmdp->cmdtype == CMDFUNCTION) { unreffunc(cmdp->param.func); } cmdp->cmdtype = entry->cmdtype; cmdp->param = entry->u; INTON; } /* * Define a shell function. */ void defun(const char *name, union node *func) { struct cmdentry entry; INTOFF; entry.cmdtype = CMDFUNCTION; entry.u.func = copyfunc(func); addcmdentry(name, &entry); INTON; } /* * Delete a function if it exists. */ int unsetfunc(const char *name) { struct tblentry *cmdp; if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) { unreffunc(cmdp->param.func); delete_cmd_entry(); return (0); } return (0); } /* * Check if a function by a certain name exists. */ int isfunc(const char *name) { struct tblentry *cmdp; cmdp = cmdlookup(name, 0); return (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION); } /* * Shared code for the following builtin commands: * type, command -v, command -V */ int typecmd_impl(int argc, char **argv, int cmd, const char *path) { struct cmdentry entry; struct tblentry *cmdp; const char *const *pp; struct alias *ap; int i; int error1 = 0; if (path != pathval()) clearcmdentry(); for (i = 1; i < argc; i++) { /* First look at the keywords */ for (pp = parsekwd; *pp; pp++) if (**pp == *argv[i] && equal(*pp, argv[i])) break; if (*pp) { if (cmd == TYPECMD_SMALLV) out1fmt("%s\n", argv[i]); else out1fmt("%s is a shell keyword\n", argv[i]); continue; } /* Then look at the aliases */ if ((ap = lookupalias(argv[i], 1)) != NULL) { if (cmd == TYPECMD_SMALLV) out1fmt("alias %s='%s'\n", argv[i], ap->val); else out1fmt("%s is an alias for %s\n", argv[i], ap->val); continue; } /* Then check if it is a tracked alias */ if ((cmdp = cmdlookup(argv[i], 0)) != NULL) { entry.cmdtype = cmdp->cmdtype; entry.u = cmdp->param; entry.special = cmdp->special; } else { /* Finally use brute force */ find_command(argv[i], &entry, 0, path); } switch (entry.cmdtype) { case CMDNORMAL: { if (strchr(argv[i], '/') == NULL) { const char *path2 = path; char *name; int j = entry.u.index; do { name = padvance(&path2, argv[i]); stunalloc(name); } while (--j >= 0); if (cmd == TYPECMD_SMALLV) out1fmt("%s\n", name); else out1fmt("%s is%s %s\n", argv[i], (cmdp && cmd == TYPECMD_TYPE) ? " a tracked alias for" : "", name); } else { if (eaccess(argv[i], X_OK) == 0) { if (cmd == TYPECMD_SMALLV) out1fmt("%s\n", argv[i]); else out1fmt("%s is %s\n", argv[i], argv[i]); } else { if (cmd != TYPECMD_SMALLV) outfmt(out2, "%s: %s\n", argv[i], strerror(errno)); error1 |= 127; } } break; } case CMDFUNCTION: if (cmd == TYPECMD_SMALLV) out1fmt("%s\n", argv[i]); else out1fmt("%s is a shell function\n", argv[i]); break; case CMDBUILTIN: if (cmd == TYPECMD_SMALLV) out1fmt("%s\n", argv[i]); else if (entry.special) out1fmt("%s is a special shell builtin\n", argv[i]); else out1fmt("%s is a shell builtin\n", argv[i]); break; default: if (cmd != TYPECMD_SMALLV) outfmt(out2, "%s: not found\n", argv[i]); error1 |= 127; break; } } if (path != pathval()) clearcmdentry(); return error1; } /* * Locate and print what a word is... */ int typecmd(int argc, char **argv) { return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1)); } Index: head/bin/sh/input.c =================================================================== --- head/bin/sh/input.c (revision 253649) +++ head/bin/sh/input.c (revision 253650) @@ -1,552 +1,549 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static char sccsid[] = "@(#)input.c 8.3 (Berkeley) 6/9/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include /* defines BUFSIZ */ #include #include #include #include #include /* * This file implements the input routines used by the parser. */ #include "shell.h" #include "redir.h" #include "syntax.h" #include "input.h" #include "output.h" #include "options.h" #include "memalloc.h" #include "error.h" #include "alias.h" #include "parser.h" #include "myhistedit.h" #include "trap.h" #define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */ struct strpush { struct strpush *prev; /* preceding string on stack */ const char *prevstring; int prevnleft; int prevlleft; struct alias *ap; /* if push was associated with an alias */ }; /* * The parsefile structure pointed to by the global variable parsefile * contains information about the current file being read. */ struct parsefile { struct parsefile *prev; /* preceding file on stack */ int linno; /* current line */ int fd; /* file descriptor (or -1 if string) */ int nleft; /* number of chars left in this line */ int lleft; /* number of lines left in this buffer */ const char *nextc; /* next char in buffer */ char *buf; /* input buffer */ struct strpush *strpush; /* for pushing strings at this level */ struct strpush basestrpush; /* so pushing one is fast */ }; int plinno = 1; /* input line number */ int parsenleft; /* copy of parsefile->nleft */ MKINIT int parselleft; /* copy of parsefile->lleft */ const char *parsenextc; /* copy of parsefile->nextc */ static char basebuf[BUFSIZ + 1];/* buffer for top level input file */ static struct parsefile basepf = { /* top level input file */ .nextc = basebuf, .buf = basebuf }; static struct parsefile *parsefile = &basepf; /* current input file */ int whichprompt; /* 1 == PS1, 2 == PS2 */ EditLine *el; /* cookie for editline package */ static void pushfile(void); static int preadfd(void); static void popstring(void); -#ifdef mkinit -INCLUDE "input.h" -INCLUDE "error.h" - -RESET { +void +resetinput(void) +{ popallfiles(); parselleft = parsenleft = 0; /* clear input buffer */ } -#endif /* * Read a line from the script. */ char * pfgets(char *line, int len) { char *p = line; int nleft = len; int c; while (--nleft > 0) { c = pgetc_macro(); if (c == PEOF) { if (p == line) return NULL; break; } *p++ = c; if (c == '\n') break; } *p = '\0'; return line; } /* * Read a character from the script, returning PEOF on end of file. * Nul characters in the input are silently discarded. */ int pgetc(void) { return pgetc_macro(); } static int preadfd(void) { int nr; parsenextc = parsefile->buf; #ifndef NO_HISTORY if (el != NULL && gotwinch) { gotwinch = 0; el_resize(el); } #endif retry: #ifndef NO_HISTORY if (parsefile->fd == 0 && el) { static const char *rl_cp; static int el_len; if (rl_cp == NULL) rl_cp = el_gets(el, &el_len); if (rl_cp == NULL) nr = el_len == 0 ? 0 : -1; else { nr = el_len; if (nr > BUFSIZ) nr = BUFSIZ; memcpy(parsefile->buf, rl_cp, nr); if (nr != el_len) { el_len -= nr; rl_cp += nr; } else rl_cp = NULL; } } else #endif nr = read(parsefile->fd, parsefile->buf, BUFSIZ); if (nr <= 0) { if (nr < 0) { if (errno == EINTR) goto retry; if (parsefile->fd == 0 && errno == EWOULDBLOCK) { int flags = fcntl(0, F_GETFL, 0); if (flags >= 0 && flags & O_NONBLOCK) { flags &=~ O_NONBLOCK; if (fcntl(0, F_SETFL, flags) >= 0) { out2fmt_flush("sh: turning off NDELAY mode\n"); goto retry; } } } } nr = -1; } return nr; } /* * Refill the input buffer and return the next input character: * * 1) If a string was pushed back on the input, pop it; * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading * from a string so we can't refill the buffer, return EOF. * 3) If there is more in this buffer, use it else call read to fill it. * 4) Process input up to the next newline, deleting nul characters. */ int preadbuffer(void) { char *p, *q; int more; int something; char savec; if (parsefile->strpush) { popstring(); if (--parsenleft >= 0) return (*parsenextc++); } if (parsenleft == EOF_NLEFT || parsefile->buf == NULL) return PEOF; flushout(&output); flushout(&errout); again: if (parselleft <= 0) { if ((parselleft = preadfd()) == -1) { parselleft = parsenleft = EOF_NLEFT; return PEOF; } } q = p = parsefile->buf + (parsenextc - parsefile->buf); /* delete nul characters */ something = 0; for (more = 1; more;) { switch (*p) { case '\0': p++; /* Skip nul */ goto check; case '\t': case ' ': break; case '\n': parsenleft = q - parsenextc; more = 0; /* Stop processing here */ break; default: something = 1; break; } *q++ = *p++; check: if (--parselleft <= 0) { parsenleft = q - parsenextc - 1; if (parsenleft < 0) goto again; *q = '\0'; more = 0; } } savec = *q; *q = '\0'; #ifndef NO_HISTORY if (parsefile->fd == 0 && hist && something) { HistEvent he; INTOFF; history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD, parsenextc); INTON; } #endif if (vflag) { out2str(parsenextc); flushout(out2); } *q = savec; return *parsenextc++; } /* * Returns if we are certain we are at EOF. Does not cause any more input * to be read from the outside world. */ int preadateof(void) { if (parsenleft > 0) return 0; if (parsefile->strpush) return 0; if (parsenleft == EOF_NLEFT || parsefile->buf == NULL) return 1; return 0; } /* * Undo the last call to pgetc. Only one character may be pushed back. * PEOF may be pushed back. */ void pungetc(void) { parsenleft++; parsenextc--; } /* * Push a string back onto the input at this current parsefile level. * We handle aliases this way. */ void pushstring(char *s, int len, struct alias *ap) { struct strpush *sp; INTOFF; /*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/ if (parsefile->strpush) { sp = ckmalloc(sizeof (struct strpush)); sp->prev = parsefile->strpush; parsefile->strpush = sp; } else sp = parsefile->strpush = &(parsefile->basestrpush); sp->prevstring = parsenextc; sp->prevnleft = parsenleft; sp->prevlleft = parselleft; sp->ap = ap; if (ap) ap->flag |= ALIASINUSE; parsenextc = s; parsenleft = len; INTON; } static void popstring(void) { struct strpush *sp = parsefile->strpush; INTOFF; parsenextc = sp->prevstring; parsenleft = sp->prevnleft; parselleft = sp->prevlleft; /*out2fmt_flush("*** calling popstring: restoring to '%s'\n", parsenextc);*/ if (sp->ap) sp->ap->flag &= ~ALIASINUSE; parsefile->strpush = sp->prev; if (sp != &(parsefile->basestrpush)) ckfree(sp); INTON; } /* * Set the input to take input from a file. If push is set, push the * old input onto the stack first. */ void setinputfile(const char *fname, int push) { int fd; int fd2; INTOFF; if ((fd = open(fname, O_RDONLY | O_CLOEXEC)) < 0) error("cannot open %s: %s", fname, strerror(errno)); if (fd < 10) { fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 10); close(fd); if (fd2 < 0) error("Out of file descriptors"); fd = fd2; } setinputfd(fd, push); INTON; } /* * Like setinputfile, but takes an open file descriptor (which should have * its FD_CLOEXEC flag already set). Call this with interrupts off. */ void setinputfd(int fd, int push) { if (push) { pushfile(); parsefile->buf = ckmalloc(BUFSIZ + 1); } if (parsefile->fd > 0) close(parsefile->fd); parsefile->fd = fd; if (parsefile->buf == NULL) parsefile->buf = ckmalloc(BUFSIZ + 1); parselleft = parsenleft = 0; plinno = 1; } /* * Like setinputfile, but takes input from a string. */ void setinputstring(const char *string, int push) { INTOFF; if (push) pushfile(); parsenextc = string; parselleft = parsenleft = strlen(string); parsefile->buf = NULL; plinno = 1; INTON; } /* * To handle the "." command, a stack of input files is used. Pushfile * adds a new entry to the stack and popfile restores the previous level. */ static void pushfile(void) { struct parsefile *pf; parsefile->nleft = parsenleft; parsefile->lleft = parselleft; parsefile->nextc = parsenextc; parsefile->linno = plinno; pf = (struct parsefile *)ckmalloc(sizeof (struct parsefile)); pf->prev = parsefile; pf->fd = -1; pf->strpush = NULL; pf->basestrpush.prev = NULL; parsefile = pf; } void popfile(void) { struct parsefile *pf = parsefile; INTOFF; if (pf->fd >= 0) close(pf->fd); if (pf->buf) ckfree(pf->buf); while (pf->strpush) popstring(); parsefile = pf->prev; ckfree(pf); parsenleft = parsefile->nleft; parselleft = parsefile->lleft; parsenextc = parsefile->nextc; plinno = parsefile->linno; INTON; } /* * Return current file (to go back to it later using popfilesupto()). */ struct parsefile * getcurrentfile(void) { return parsefile; } /* * Pop files until the given file is on top again. Useful for regular * builtins that read shell commands from files or strings. * If the given file is not an active file, an error is raised. */ void popfilesupto(struct parsefile *file) { while (parsefile != file && parsefile != &basepf) popfile(); if (parsefile != file) error("popfilesupto() misused"); } /* * Return to top level. */ void popallfiles(void) { while (parsefile != &basepf) popfile(); } /* * Close the file(s) that the shell is reading commands from. Called * after a fork is done. */ void closescript(void) { popallfiles(); if (parsefile->fd > 0) { close(parsefile->fd); parsefile->fd = 0; } } Index: head/bin/sh/input.h =================================================================== --- head/bin/sh/input.h (revision 253649) +++ head/bin/sh/input.h (revision 253650) @@ -1,65 +1,66 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)input.h 8.2 (Berkeley) 5/4/95 * $FreeBSD$ */ /* PEOF (the end of file marker) is defined in syntax.h */ /* * The input line number. Input.c just defines this variable, and saves * and restores it when files are pushed and popped. The user of this * package must set its value. */ extern int plinno; extern int parsenleft; /* number of characters left in input buffer */ extern const char *parsenextc; /* next character in input buffer */ struct alias; struct parsefile; +void resetinput(void); char *pfgets(char *, int); int pgetc(void); int preadbuffer(void); int preadateof(void); void pungetc(void); void pushstring(char *, int, struct alias *); void setinputfile(const char *, int); void setinputfd(int, int); void setinputstring(const char *, int); void popfile(void); struct parsefile *getcurrentfile(void); void popfilesupto(struct parsefile *); void popallfiles(void); void closescript(void); #define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer()) Index: head/bin/sh/main.c =================================================================== --- head/bin/sh/main.c (revision 253649) +++ head/bin/sh/main.c (revision 253650) @@ -1,340 +1,349 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static char const copyright[] = "@(#) Copyright (c) 1991, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)main.c 8.6 (Berkeley) 5/28/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include "shell.h" #include "main.h" #include "mail.h" #include "options.h" #include "output.h" #include "parser.h" #include "nodes.h" #include "expand.h" #include "eval.h" #include "jobs.h" #include "input.h" #include "trap.h" #include "var.h" #include "show.h" #include "memalloc.h" #include "error.h" -#include "init.h" #include "mystring.h" #include "exec.h" #include "cd.h" +#include "redir.h" #include "builtins.h" int rootpid; int rootshell; struct jmploc main_handler; int localeisutf8, initial_localeisutf8; +static void reset(void); static void cmdloop(int); static void read_profile(const char *); static char *find_dot_file(char *); /* * Main routine. We initialize things, parse the arguments, execute * profiles if we're a login shell, and then call cmdloop to execute * commands. The setjmp call sets up the location to jump to when an * exception occurs. When an exception occurs the variable "state" * is used to figure out how far we had gotten. */ int main(int argc, char *argv[]) { struct stackmark smark, smark2; volatile int state; char *shinit; (void) setlocale(LC_ALL, ""); initcharset(); state = 0; if (setjmp(main_handler.loc)) { switch (exception) { case EXEXEC: exitstatus = exerrno; break; case EXERROR: exitstatus = 2; break; default: break; } if (state == 0 || iflag == 0 || ! rootshell || exception == EXEXIT) exitshell(exitstatus); reset(); if (exception == EXINT) out2fmt_flush("\n"); popstackmark(&smark); FORCEINTON; /* enable interrupts */ if (state == 1) goto state1; else if (state == 2) goto state2; else if (state == 3) goto state3; else goto state4; } handler = &main_handler; #ifdef DEBUG opentrace(); trputs("Shell args: "); trargs(argv); #endif rootpid = getpid(); rootshell = 1; initvar(); setstackmark(&smark); setstackmark(&smark2); procargs(argc, argv); pwd_init(iflag); if (iflag) chkmail(1); if (argv[0] && argv[0][0] == '-') { state = 1; read_profile("/etc/profile"); state1: state = 2; if (privileged == 0) read_profile("${HOME-}/.profile"); else read_profile("/etc/suid_profile"); } state2: state = 3; if (!privileged && iflag) { if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') { state = 3; read_profile(shinit); } } state3: state = 4; popstackmark(&smark2); if (minusc) { evalstring(minusc, sflag ? 0 : EV_EXIT); } state4: if (sflag || minusc == NULL) { cmdloop(1); } exitshell(exitstatus); /*NOTREACHED*/ return 0; } +static void +reset(void) +{ + reseteval(); + resetinput(); + resetparser(); + resetredir(); +} /* * Read and execute commands. "Top" is nonzero for the top level command * loop; it turns on prompting if the shell is interactive. */ static void cmdloop(int top) { union node *n; struct stackmark smark; int inter; int numeof = 0; TRACE(("cmdloop(%d) called\n", top)); setstackmark(&smark); for (;;) { if (pendingsig) dotrap(); inter = 0; if (iflag && top) { inter++; showjobs(1, SHOWJOBS_DEFAULT); chkmail(0); flushout(&output); } n = parsecmd(inter); /* showtree(n); DEBUG */ if (n == NEOF) { if (!top || numeof >= 50) break; if (!stoppedjobs()) { if (!Iflag) break; out2fmt_flush("\nUse \"exit\" to leave shell.\n"); } numeof++; } else if (n != NULL && nflag == 0) { job_warning = (job_warning == 2) ? 1 : 0; numeof = 0; evaltree(n, 0); } popstackmark(&smark); setstackmark(&smark); if (evalskip != 0) { if (evalskip == SKIPFILE) evalskip = 0; break; } } popstackmark(&smark); } /* * Read /etc/profile or .profile. Return on error. */ static void read_profile(const char *name) { int fd; const char *expandedname; expandedname = expandstr(name); if (expandedname == NULL) return; INTOFF; if ((fd = open(expandedname, O_RDONLY | O_CLOEXEC)) >= 0) setinputfd(fd, 1); INTON; if (fd < 0) return; cmdloop(0); popfile(); } /* * Read a file containing shell functions. */ void readcmdfile(const char *name) { setinputfile(name, 1); cmdloop(0); popfile(); } /* * Take commands from a file. To be compatible we should do a path * search for the file, which is necessary to find sub-commands. */ static char * find_dot_file(char *basename) { char *fullname; const char *path = pathval(); struct stat statb; /* don't try this for absolute or relative paths */ if( strchr(basename, '/')) return basename; while ((fullname = padvance(&path, basename)) != NULL) { if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) { /* * Don't bother freeing here, since it will * be freed by the caller. */ return fullname; } stunalloc(fullname); } return basename; } int dotcmd(int argc, char **argv) { char *filename, *fullname; if (argc < 2) error("missing filename"); exitstatus = 0; /* * Because we have historically not supported any options, * only treat "--" specially. */ filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1]; fullname = find_dot_file(filename); setinputfile(fullname, 1); commandname = fullname; cmdloop(0); popfile(); return exitstatus; } int exitcmd(int argc, char **argv) { if (stoppedjobs()) return 0; if (argc > 1) exitshell(number(argv[1])); else exitshell_savedstatus(); } Index: head/bin/sh/parser.c =================================================================== --- head/bin/sh/parser.c (revision 253649) +++ head/bin/sh/parser.c (revision 253650) @@ -1,2082 +1,2082 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static char sccsid[] = "@(#)parser.c 8.7 (Berkeley) 5/16/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include "shell.h" #include "parser.h" #include "nodes.h" #include "expand.h" /* defines rmescapes() */ #include "syntax.h" #include "options.h" #include "input.h" #include "output.h" #include "var.h" #include "error.h" #include "memalloc.h" #include "mystring.h" #include "alias.h" #include "show.h" #include "eval.h" #include "exec.h" /* to check for special builtins */ #ifndef NO_HISTORY #include "myhistedit.h" #endif /* * Shell command parser. */ #define EOFMARKLEN 79 #define PROMPTLEN 128 /* values of checkkwd variable */ #define CHKALIAS 0x1 #define CHKKWD 0x2 #define CHKNL 0x4 /* values returned by readtoken */ #include "token.h" struct heredoc { struct heredoc *next; /* next here document in list */ union node *here; /* redirection node */ char *eofmark; /* string indicating end of input */ int striptabs; /* if set, strip leading tabs */ }; struct parser_temp { struct parser_temp *next; void *data; }; static struct heredoc *heredoclist; /* list of here documents to read */ static int doprompt; /* if set, prompt the user */ static int needprompt; /* true if interactive and at start of line */ static int lasttoken; /* last token read */ MKINIT int tokpushback; /* last token pushed back */ static char *wordtext; /* text of last word returned by readtoken */ MKINIT int checkkwd; /* 1 == check for kwds, 2 == also eat newlines */ static struct nodelist *backquotelist; static union node *redirnode; static struct heredoc *heredoc; static int quoteflag; /* set if (part of) last token was quoted */ static int startlinno; /* line # where last token started */ static int funclinno; /* line # where the current function started */ static struct parser_temp *parser_temp; static union node *list(int, int); static union node *andor(void); static union node *pipeline(void); static union node *command(void); static union node *simplecmd(union node **, union node *); static union node *makename(void); static void parsefname(void); static void parseheredoc(void); static int peektoken(void); static int readtoken(void); static int xxreadtoken(void); static int readtoken1(int, const char *, const char *, int); static int noexpand(char *); static void synexpect(int) __dead2; static void synerror(const char *) __dead2; static void setprompt(int); static void * parser_temp_alloc(size_t len) { struct parser_temp *t; INTOFF; t = ckmalloc(sizeof(*t)); t->data = NULL; t->next = parser_temp; parser_temp = t; t->data = ckmalloc(len); INTON; return t->data; } static void * parser_temp_realloc(void *ptr, size_t len) { struct parser_temp *t; INTOFF; t = parser_temp; if (ptr != t->data) error("bug: parser_temp_realloc misused"); t->data = ckrealloc(t->data, len); INTON; return t->data; } static void parser_temp_free_upto(void *ptr) { struct parser_temp *t; int done = 0; INTOFF; while (parser_temp != NULL && !done) { t = parser_temp; parser_temp = t->next; done = t->data == ptr; ckfree(t->data); ckfree(t); } INTON; if (!done) error("bug: parser_temp_free_upto misused"); } static void parser_temp_free_all(void) { struct parser_temp *t; INTOFF; while (parser_temp != NULL) { t = parser_temp; parser_temp = t->next; ckfree(t->data); ckfree(t); } INTON; } /* * Read and parse a command. Returns NEOF on end of file. (NULL is a * valid parse tree indicating a blank line.) */ union node * parsecmd(int interact) { int t; /* This assumes the parser is not re-entered, * which could happen if we add command substitution on PS1/PS2. */ parser_temp_free_all(); heredoclist = NULL; tokpushback = 0; doprompt = interact; if (doprompt) setprompt(1); else setprompt(0); needprompt = 0; t = readtoken(); if (t == TEOF) return NEOF; if (t == TNL) return NULL; tokpushback++; return list(1, 1); } static union node * list(int nlflag, int erflag) { union node *ntop, *n1, *n2, *n3; int tok; checkkwd = CHKNL | CHKKWD | CHKALIAS; if (!nlflag && !erflag && tokendlist[peektoken()]) return NULL; ntop = n1 = NULL; for (;;) { n2 = andor(); tok = readtoken(); if (tok == TBACKGND) { if (n2 != NULL && n2->type == NPIPE) { n2->npipe.backgnd = 1; } else if (n2 != NULL && n2->type == NREDIR) { n2->type = NBACKGND; } else { n3 = (union node *)stalloc(sizeof (struct nredir)); n3->type = NBACKGND; n3->nredir.n = n2; n3->nredir.redirect = NULL; n2 = n3; } } if (ntop == NULL) ntop = n2; else if (n1 == NULL) { n1 = (union node *)stalloc(sizeof (struct nbinary)); n1->type = NSEMI; n1->nbinary.ch1 = ntop; n1->nbinary.ch2 = n2; ntop = n1; } else { n3 = (union node *)stalloc(sizeof (struct nbinary)); n3->type = NSEMI; n3->nbinary.ch1 = n1->nbinary.ch2; n3->nbinary.ch2 = n2; n1->nbinary.ch2 = n3; n1 = n3; } switch (tok) { case TBACKGND: case TSEMI: tok = readtoken(); /* FALLTHROUGH */ case TNL: if (tok == TNL) { parseheredoc(); if (nlflag) return ntop; } else if (tok == TEOF && nlflag) { parseheredoc(); return ntop; } else { tokpushback++; } checkkwd = CHKNL | CHKKWD | CHKALIAS; if (!nlflag && (erflag ? peektoken() == TEOF : tokendlist[peektoken()])) return ntop; break; case TEOF: if (heredoclist) parseheredoc(); else pungetc(); /* push back EOF on input */ return ntop; default: if (nlflag || erflag) synexpect(-1); tokpushback++; return ntop; } } } static union node * andor(void) { union node *n1, *n2, *n3; int t; n1 = pipeline(); for (;;) { if ((t = readtoken()) == TAND) { t = NAND; } else if (t == TOR) { t = NOR; } else { tokpushback++; return n1; } n2 = pipeline(); n3 = (union node *)stalloc(sizeof (struct nbinary)); n3->type = t; n3->nbinary.ch1 = n1; n3->nbinary.ch2 = n2; n1 = n3; } } static union node * pipeline(void) { union node *n1, *n2, *pipenode; struct nodelist *lp, *prev; int negate, t; negate = 0; checkkwd = CHKNL | CHKKWD | CHKALIAS; TRACE(("pipeline: entered\n")); while (readtoken() == TNOT) negate = !negate; tokpushback++; n1 = command(); if (readtoken() == TPIPE) { pipenode = (union node *)stalloc(sizeof (struct npipe)); pipenode->type = NPIPE; pipenode->npipe.backgnd = 0; lp = (struct nodelist *)stalloc(sizeof (struct nodelist)); pipenode->npipe.cmdlist = lp; lp->n = n1; do { prev = lp; lp = (struct nodelist *)stalloc(sizeof (struct nodelist)); checkkwd = CHKNL | CHKKWD | CHKALIAS; t = readtoken(); tokpushback++; if (t == TNOT) lp->n = pipeline(); else lp->n = command(); prev->next = lp; } while (readtoken() == TPIPE); lp->next = NULL; n1 = pipenode; } tokpushback++; if (negate) { n2 = (union node *)stalloc(sizeof (struct nnot)); n2->type = NNOT; n2->nnot.com = n1; return n2; } else return n1; } static union node * command(void) { union node *n1, *n2; union node *ap, **app; union node *cp, **cpp; union node *redir, **rpp; int t; int is_subshell; checkkwd = CHKNL | CHKKWD | CHKALIAS; is_subshell = 0; redir = NULL; n1 = NULL; rpp = &redir; /* Check for redirection which may precede command */ while (readtoken() == TREDIR) { *rpp = n2 = redirnode; rpp = &n2->nfile.next; parsefname(); } tokpushback++; switch (readtoken()) { case TIF: n1 = (union node *)stalloc(sizeof (struct nif)); n1->type = NIF; if ((n1->nif.test = list(0, 0)) == NULL) synexpect(-1); if (readtoken() != TTHEN) synexpect(TTHEN); n1->nif.ifpart = list(0, 0); n2 = n1; while (readtoken() == TELIF) { n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif)); n2 = n2->nif.elsepart; n2->type = NIF; if ((n2->nif.test = list(0, 0)) == NULL) synexpect(-1); if (readtoken() != TTHEN) synexpect(TTHEN); n2->nif.ifpart = list(0, 0); } if (lasttoken == TELSE) n2->nif.elsepart = list(0, 0); else { n2->nif.elsepart = NULL; tokpushback++; } if (readtoken() != TFI) synexpect(TFI); checkkwd = CHKKWD | CHKALIAS; break; case TWHILE: case TUNTIL: { int got; n1 = (union node *)stalloc(sizeof (struct nbinary)); n1->type = (lasttoken == TWHILE)? NWHILE : NUNTIL; if ((n1->nbinary.ch1 = list(0, 0)) == NULL) synexpect(-1); if ((got=readtoken()) != TDO) { TRACE(("expecting DO got %s %s\n", tokname[got], got == TWORD ? wordtext : "")); synexpect(TDO); } n1->nbinary.ch2 = list(0, 0); if (readtoken() != TDONE) synexpect(TDONE); checkkwd = CHKKWD | CHKALIAS; break; } case TFOR: if (readtoken() != TWORD || quoteflag || ! goodname(wordtext)) synerror("Bad for loop variable"); n1 = (union node *)stalloc(sizeof (struct nfor)); n1->type = NFOR; n1->nfor.var = wordtext; while (readtoken() == TNL) ; if (lasttoken == TWORD && ! quoteflag && equal(wordtext, "in")) { app = ≈ while (readtoken() == TWORD) { n2 = (union node *)stalloc(sizeof (struct narg)); n2->type = NARG; n2->narg.text = wordtext; n2->narg.backquote = backquotelist; *app = n2; app = &n2->narg.next; } *app = NULL; n1->nfor.args = ap; if (lasttoken != TNL && lasttoken != TSEMI) synexpect(-1); } else { static char argvars[5] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' }; n2 = (union node *)stalloc(sizeof (struct narg)); n2->type = NARG; n2->narg.text = argvars; n2->narg.backquote = NULL; n2->narg.next = NULL; n1->nfor.args = n2; /* * Newline or semicolon here is optional (but note * that the original Bourne shell only allowed NL). */ if (lasttoken != TNL && lasttoken != TSEMI) tokpushback++; } checkkwd = CHKNL | CHKKWD | CHKALIAS; if ((t = readtoken()) == TDO) t = TDONE; else if (t == TBEGIN) t = TEND; else synexpect(-1); n1->nfor.body = list(0, 0); if (readtoken() != t) synexpect(t); checkkwd = CHKKWD | CHKALIAS; break; case TCASE: n1 = (union node *)stalloc(sizeof (struct ncase)); n1->type = NCASE; if (readtoken() != TWORD) synexpect(TWORD); n1->ncase.expr = n2 = (union node *)stalloc(sizeof (struct narg)); n2->type = NARG; n2->narg.text = wordtext; n2->narg.backquote = backquotelist; n2->narg.next = NULL; while (readtoken() == TNL); if (lasttoken != TWORD || ! equal(wordtext, "in")) synerror("expecting \"in\""); cpp = &n1->ncase.cases; checkkwd = CHKNL | CHKKWD, readtoken(); while (lasttoken != TESAC) { *cpp = cp = (union node *)stalloc(sizeof (struct nclist)); cp->type = NCLIST; app = &cp->nclist.pattern; if (lasttoken == TLP) readtoken(); for (;;) { *app = ap = (union node *)stalloc(sizeof (struct narg)); ap->type = NARG; ap->narg.text = wordtext; ap->narg.backquote = backquotelist; checkkwd = CHKNL | CHKKWD; if (readtoken() != TPIPE) break; app = &ap->narg.next; readtoken(); } ap->narg.next = NULL; if (lasttoken != TRP) synexpect(TRP); cp->nclist.body = list(0, 0); checkkwd = CHKNL | CHKKWD | CHKALIAS; if ((t = readtoken()) != TESAC) { if (t == TENDCASE) ; else if (t == TFALLTHRU) cp->type = NCLISTFALLTHRU; else synexpect(TENDCASE); checkkwd = CHKNL | CHKKWD, readtoken(); } cpp = &cp->nclist.next; } *cpp = NULL; checkkwd = CHKKWD | CHKALIAS; break; case TLP: n1 = (union node *)stalloc(sizeof (struct nredir)); n1->type = NSUBSHELL; n1->nredir.n = list(0, 0); n1->nredir.redirect = NULL; if (readtoken() != TRP) synexpect(TRP); checkkwd = CHKKWD | CHKALIAS; is_subshell = 1; break; case TBEGIN: n1 = list(0, 0); if (readtoken() != TEND) synexpect(TEND); checkkwd = CHKKWD | CHKALIAS; break; /* Handle an empty command like other simple commands. */ case TBACKGND: case TSEMI: case TAND: case TOR: /* * An empty command before a ; doesn't make much sense, and * should certainly be disallowed in the case of `if ;'. */ if (!redir) synexpect(-1); case TNL: case TEOF: case TWORD: case TRP: tokpushback++; n1 = simplecmd(rpp, redir); return n1; default: synexpect(-1); } /* Now check for redirection which may follow command */ while (readtoken() == TREDIR) { *rpp = n2 = redirnode; rpp = &n2->nfile.next; parsefname(); } tokpushback++; *rpp = NULL; if (redir) { if (!is_subshell) { n2 = (union node *)stalloc(sizeof (struct nredir)); n2->type = NREDIR; n2->nredir.n = n1; n1 = n2; } n1->nredir.redirect = redir; } return n1; } static union node * simplecmd(union node **rpp, union node *redir) { union node *args, **app; union node **orig_rpp = rpp; union node *n = NULL; int special; int savecheckkwd; /* If we don't have any redirections already, then we must reset */ /* rpp to be the address of the local redir variable. */ if (redir == 0) rpp = &redir; args = NULL; app = &args; /* * We save the incoming value, because we need this for shell * functions. There can not be a redirect or an argument between * the function name and the open parenthesis. */ orig_rpp = rpp; savecheckkwd = CHKALIAS; for (;;) { checkkwd = savecheckkwd; if (readtoken() == TWORD) { n = (union node *)stalloc(sizeof (struct narg)); n->type = NARG; n->narg.text = wordtext; n->narg.backquote = backquotelist; *app = n; app = &n->narg.next; if (savecheckkwd != 0 && !isassignment(wordtext)) savecheckkwd = 0; } else if (lasttoken == TREDIR) { *rpp = n = redirnode; rpp = &n->nfile.next; parsefname(); /* read name of redirection file */ } else if (lasttoken == TLP && app == &args->narg.next && rpp == orig_rpp) { /* We have a function */ if (readtoken() != TRP) synexpect(TRP); funclinno = plinno; /* * - Require plain text. * - Functions with '/' cannot be called. * - Reject name=(). * - Reject ksh extended glob patterns. */ if (!noexpand(n->narg.text) || quoteflag || strchr(n->narg.text, '/') || strchr("!%*+-=?@}~", n->narg.text[strlen(n->narg.text) - 1])) synerror("Bad function name"); rmescapes(n->narg.text); if (find_builtin(n->narg.text, &special) >= 0 && special) synerror("Cannot override a special builtin with a function"); n->type = NDEFUN; n->narg.next = command(); funclinno = 0; return n; } else { tokpushback++; break; } } *app = NULL; *rpp = NULL; n = (union node *)stalloc(sizeof (struct ncmd)); n->type = NCMD; n->ncmd.args = args; n->ncmd.redirect = redir; return n; } static union node * makename(void) { union node *n; n = (union node *)stalloc(sizeof (struct narg)); n->type = NARG; n->narg.next = NULL; n->narg.text = wordtext; n->narg.backquote = backquotelist; return n; } void fixredir(union node *n, const char *text, int err) { TRACE(("Fix redir %s %d\n", text, err)); if (!err) n->ndup.vname = NULL; if (is_digit(text[0]) && text[1] == '\0') n->ndup.dupfd = digit_val(text[0]); else if (text[0] == '-' && text[1] == '\0') n->ndup.dupfd = -1; else { if (err) synerror("Bad fd number"); else n->ndup.vname = makename(); } } static void parsefname(void) { union node *n = redirnode; if (readtoken() != TWORD) synexpect(-1); if (n->type == NHERE) { struct heredoc *here = heredoc; struct heredoc *p; int i; if (quoteflag == 0) n->type = NXHERE; TRACE(("Here document %d\n", n->type)); if (here->striptabs) { while (*wordtext == '\t') wordtext++; } if (! noexpand(wordtext) || (i = strlen(wordtext)) == 0 || i > EOFMARKLEN) synerror("Illegal eof marker for << redirection"); rmescapes(wordtext); here->eofmark = wordtext; here->next = NULL; if (heredoclist == NULL) heredoclist = here; else { for (p = heredoclist ; p->next ; p = p->next); p->next = here; } } else if (n->type == NTOFD || n->type == NFROMFD) { fixredir(n, wordtext, 0); } else { n->nfile.fname = makename(); } } /* * Input any here documents. */ static void parseheredoc(void) { struct heredoc *here; union node *n; while (heredoclist) { here = heredoclist; heredoclist = here->next; if (needprompt) { setprompt(2); needprompt = 0; } readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX, here->eofmark, here->striptabs); n = (union node *)stalloc(sizeof (struct narg)); n->narg.type = NARG; n->narg.next = NULL; n->narg.text = wordtext; n->narg.backquote = backquotelist; here->here->nhere.doc = n; } } static int peektoken(void) { int t; t = readtoken(); tokpushback++; return (t); } static int readtoken(void) { int t; struct alias *ap; #ifdef DEBUG int alreadyseen = tokpushback; #endif top: t = xxreadtoken(); /* * eat newlines */ if (checkkwd & CHKNL) { while (t == TNL) { parseheredoc(); t = xxreadtoken(); } } /* * check for keywords and aliases */ if (t == TWORD && !quoteflag) { const char * const *pp; if (checkkwd & CHKKWD) for (pp = parsekwd; *pp; pp++) { if (**pp == *wordtext && equal(*pp, wordtext)) { lasttoken = t = pp - parsekwd + KWDOFFSET; TRACE(("keyword %s recognized\n", tokname[t])); goto out; } } if (checkkwd & CHKALIAS && (ap = lookupalias(wordtext, 1)) != NULL) { pushstring(ap->val, strlen(ap->val), ap); goto top; } } out: if (t != TNOT) checkkwd = 0; #ifdef DEBUG if (!alreadyseen) TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : "")); else TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : "")); #endif return (t); } /* * Read the next input token. * If the token is a word, we set backquotelist to the list of cmds in * backquotes. We set quoteflag to true if any part of the word was * quoted. * If the token is TREDIR, then we set redirnode to a structure containing * the redirection. * In all cases, the variable startlinno is set to the number of the line * on which the token starts. * * [Change comment: here documents and internal procedures] * [Readtoken shouldn't have any arguments. Perhaps we should make the * word parsing code into a separate routine. In this case, readtoken * doesn't need to have any internal procedures, but parseword does. * We could also make parseoperator in essence the main routine, and * have parseword (readtoken1?) handle both words and redirection.] */ #define RETURN(token) return lasttoken = token static int xxreadtoken(void) { int c; if (tokpushback) { tokpushback = 0; return lasttoken; } if (needprompt) { setprompt(2); needprompt = 0; } startlinno = plinno; for (;;) { /* until token or start of word found */ c = pgetc_macro(); switch (c) { case ' ': case '\t': continue; case '#': while ((c = pgetc()) != '\n' && c != PEOF); pungetc(); continue; case '\\': if (pgetc() == '\n') { startlinno = ++plinno; if (doprompt) setprompt(2); else setprompt(0); continue; } pungetc(); goto breakloop; case '\n': plinno++; needprompt = doprompt; RETURN(TNL); case PEOF: RETURN(TEOF); case '&': if (pgetc() == '&') RETURN(TAND); pungetc(); RETURN(TBACKGND); case '|': if (pgetc() == '|') RETURN(TOR); pungetc(); RETURN(TPIPE); case ';': c = pgetc(); if (c == ';') RETURN(TENDCASE); else if (c == '&') RETURN(TFALLTHRU); pungetc(); RETURN(TSEMI); case '(': RETURN(TLP); case ')': RETURN(TRP); default: goto breakloop; } } breakloop: return readtoken1(c, BASESYNTAX, (char *)NULL, 0); #undef RETURN } #define MAXNEST_static 8 struct tokenstate { const char *syntax; /* *SYNTAX */ int parenlevel; /* levels of parentheses in arithmetic */ enum tokenstate_category { TSTATE_TOP, TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */ TSTATE_VAR_NEW, /* other ${var...}, own dquote state */ TSTATE_ARITH } category; }; /* * Called to parse command substitutions. */ static char * parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int quoted) { struct nodelist **nlpp; union node *n; char *volatile str; struct jmploc jmploc; struct jmploc *const savehandler = handler; size_t savelen; int saveprompt; const int bq_startlinno = plinno; char *volatile ostr = NULL; struct parsefile *const savetopfile = getcurrentfile(); struct heredoc *const saveheredoclist = heredoclist; struct heredoc *here; str = NULL; if (setjmp(jmploc.loc)) { popfilesupto(savetopfile); if (str) ckfree(str); if (ostr) ckfree(ostr); heredoclist = saveheredoclist; handler = savehandler; if (exception == EXERROR) { startlinno = bq_startlinno; synerror("Error in command substitution"); } longjmp(handler->loc, 1); } INTOFF; savelen = out - stackblock(); if (savelen > 0) { str = ckmalloc(savelen); memcpy(str, stackblock(), savelen); } handler = &jmploc; heredoclist = NULL; INTON; if (oldstyle) { /* We must read until the closing backquote, giving special treatment to some slashes, and then push the string and reread it as input, interpreting it normally. */ char *oout; int c; int olen; STARTSTACKSTR(oout); for (;;) { if (needprompt) { setprompt(2); needprompt = 0; } CHECKSTRSPACE(2, oout); switch (c = pgetc()) { case '`': goto done; case '\\': if ((c = pgetc()) == '\n') { plinno++; if (doprompt) setprompt(2); else setprompt(0); /* * If eating a newline, avoid putting * the newline into the new character * stream (via the USTPUTC after the * switch). */ continue; } if (c != '\\' && c != '`' && c != '$' && (!dblquote || c != '"')) USTPUTC('\\', oout); break; case '\n': plinno++; needprompt = doprompt; break; case PEOF: startlinno = plinno; synerror("EOF in backquote substitution"); break; default: break; } USTPUTC(c, oout); } done: USTPUTC('\0', oout); olen = oout - stackblock(); INTOFF; ostr = ckmalloc(olen); memcpy(ostr, stackblock(), olen); setinputstring(ostr, 1); INTON; } nlpp = pbqlist; while (*nlpp) nlpp = &(*nlpp)->next; *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist)); (*nlpp)->next = NULL; if (oldstyle) { saveprompt = doprompt; doprompt = 0; } n = list(0, oldstyle); if (oldstyle) doprompt = saveprompt; else { if (readtoken() != TRP) synexpect(TRP); } (*nlpp)->n = n; if (oldstyle) { /* * Start reading from old file again, ignoring any pushed back * tokens left from the backquote parsing */ popfile(); tokpushback = 0; } STARTSTACKSTR(out); CHECKSTRSPACE(savelen + 1, out); INTOFF; if (str) { memcpy(out, str, savelen); STADJUST(savelen, out); ckfree(str); str = NULL; } if (ostr) { ckfree(ostr); ostr = NULL; } here = saveheredoclist; if (here != NULL) { while (here->next != NULL) here = here->next; here->next = heredoclist; heredoclist = saveheredoclist; } handler = savehandler; INTON; if (quoted) USTPUTC(CTLBACKQ | CTLQUOTE, out); else USTPUTC(CTLBACKQ, out); return out; } /* * Called to parse a backslash escape sequence inside $'...'. * The backslash has already been read. */ static char * readcstyleesc(char *out) { int c, v, i, n; c = pgetc(); switch (c) { case '\0': synerror("Unterminated quoted string"); case '\n': plinno++; if (doprompt) setprompt(2); else setprompt(0); return out; case '\\': case '\'': case '"': v = c; break; case 'a': v = '\a'; break; case 'b': v = '\b'; break; case 'e': v = '\033'; break; case 'f': v = '\f'; break; case 'n': v = '\n'; break; case 'r': v = '\r'; break; case 't': v = '\t'; break; case 'v': v = '\v'; break; case 'x': v = 0; for (;;) { c = pgetc(); if (c >= '0' && c <= '9') v = (v << 4) + c - '0'; else if (c >= 'A' && c <= 'F') v = (v << 4) + c - 'A' + 10; else if (c >= 'a' && c <= 'f') v = (v << 4) + c - 'a' + 10; else break; } pungetc(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': v = c - '0'; c = pgetc(); if (c >= '0' && c <= '7') { v <<= 3; v += c - '0'; c = pgetc(); if (c >= '0' && c <= '7') { v <<= 3; v += c - '0'; } else pungetc(); } else pungetc(); break; case 'c': c = pgetc(); if (c < 0x3f || c > 0x7a || c == 0x60) synerror("Bad escape sequence"); if (c == '\\' && pgetc() != '\\') synerror("Bad escape sequence"); if (c == '?') v = 127; else v = c & 0x1f; break; case 'u': case 'U': n = c == 'U' ? 8 : 4; v = 0; for (i = 0; i < n; i++) { c = pgetc(); if (c >= '0' && c <= '9') v = (v << 4) + c - '0'; else if (c >= 'A' && c <= 'F') v = (v << 4) + c - 'A' + 10; else if (c >= 'a' && c <= 'f') v = (v << 4) + c - 'a' + 10; else synerror("Bad escape sequence"); } if (v == 0 || (v >= 0xd800 && v <= 0xdfff)) synerror("Bad escape sequence"); /* We really need iconv here. */ if (initial_localeisutf8 && v > 127) { CHECKSTRSPACE(4, out); /* * We cannot use wctomb() as the locale may have * changed. */ if (v <= 0x7ff) { USTPUTC(0xc0 | v >> 6, out); USTPUTC(0x80 | (v & 0x3f), out); return out; } else if (v <= 0xffff) { USTPUTC(0xe0 | v >> 12, out); USTPUTC(0x80 | ((v >> 6) & 0x3f), out); USTPUTC(0x80 | (v & 0x3f), out); return out; } else if (v <= 0x10ffff) { USTPUTC(0xf0 | v >> 18, out); USTPUTC(0x80 | ((v >> 12) & 0x3f), out); USTPUTC(0x80 | ((v >> 6) & 0x3f), out); USTPUTC(0x80 | (v & 0x3f), out); return out; } } if (v > 127) v = '?'; break; default: synerror("Bad escape sequence"); } v = (char)v; /* * We can't handle NUL bytes. * POSIX says we should skip till the closing quote. */ if (v == '\0') { while ((c = pgetc()) != '\'') { if (c == '\\') c = pgetc(); if (c == PEOF) synerror("Unterminated quoted string"); } pungetc(); return out; } if (SQSYNTAX[v] == CCTL) USTPUTC(CTLESC, out); USTPUTC(v, out); return out; } /* * If eofmark is NULL, read a word or a redirection symbol. If eofmark * is not NULL, read a here document. In the latter case, eofmark is the * word which marks the end of the document and striptabs is true if * leading tabs should be stripped from the document. The argument firstc * is the first character of the input token or document. * * Because C does not have internal subroutines, I have simulated them * using goto's to implement the subroutine linkage. The following macros * will run code that appears at the end of readtoken1. */ #define CHECKEND() {goto checkend; checkend_return:;} #define PARSEREDIR() {goto parseredir; parseredir_return:;} #define PARSESUB() {goto parsesub; parsesub_return:;} #define PARSEARITH() {goto parsearith; parsearith_return:;} static int readtoken1(int firstc, char const *initialsyntax, const char *eofmark, int striptabs) { int c = firstc; char *out; int len; char line[EOFMARKLEN + 1]; struct nodelist *bqlist; int quotef; int newvarnest; int level; int synentry; struct tokenstate state_static[MAXNEST_static]; int maxnest = MAXNEST_static; struct tokenstate *state = state_static; int sqiscstyle = 0; startlinno = plinno; quotef = 0; bqlist = NULL; newvarnest = 0; level = 0; state[level].syntax = initialsyntax; state[level].parenlevel = 0; state[level].category = TSTATE_TOP; STARTSTACKSTR(out); loop: { /* for each line, until end of word */ CHECKEND(); /* set c to PEOF if at end of here document */ for (;;) { /* until end of line or end of word */ CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ synentry = state[level].syntax[c]; switch(synentry) { case CNL: /* '\n' */ if (state[level].syntax == BASESYNTAX) goto endword; /* exit outer loop */ USTPUTC(c, out); plinno++; if (doprompt) setprompt(2); else setprompt(0); c = pgetc(); goto loop; /* continue outer loop */ case CSBACK: if (sqiscstyle) { out = readcstyleesc(out); break; } /* FALLTHROUGH */ case CWORD: USTPUTC(c, out); break; case CCTL: if (eofmark == NULL || initialsyntax != SQSYNTAX) USTPUTC(CTLESC, out); USTPUTC(c, out); break; case CBACK: /* backslash */ c = pgetc(); if (c == PEOF) { USTPUTC('\\', out); pungetc(); } else if (c == '\n') { plinno++; if (doprompt) setprompt(2); else setprompt(0); } else { if (state[level].syntax == DQSYNTAX && c != '\\' && c != '`' && c != '$' && (c != '"' || (eofmark != NULL && newvarnest == 0)) && (c != '}' || state[level].category != TSTATE_VAR_OLD)) USTPUTC('\\', out); if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX) USTPUTC(CTLQUOTEMARK, out); if (SQSYNTAX[c] == CCTL) USTPUTC(CTLESC, out); USTPUTC(c, out); if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX && state[level].category == TSTATE_VAR_OLD) USTPUTC(CTLQUOTEEND, out); quotef++; } break; case CSQUOTE: USTPUTC(CTLQUOTEMARK, out); state[level].syntax = SQSYNTAX; sqiscstyle = 0; break; case CDQUOTE: USTPUTC(CTLQUOTEMARK, out); state[level].syntax = DQSYNTAX; break; case CENDQUOTE: if (eofmark != NULL && newvarnest == 0) USTPUTC(c, out); else { if (state[level].category == TSTATE_VAR_OLD) USTPUTC(CTLQUOTEEND, out); state[level].syntax = BASESYNTAX; quotef++; } break; case CVAR: /* '$' */ PARSESUB(); /* parse substitution */ break; case CENDVAR: /* '}' */ if (level > 0 && ((state[level].category == TSTATE_VAR_OLD && state[level].syntax == state[level - 1].syntax) || (state[level].category == TSTATE_VAR_NEW && state[level].syntax == BASESYNTAX))) { if (state[level].category == TSTATE_VAR_NEW) newvarnest--; level--; USTPUTC(CTLENDVAR, out); } else { USTPUTC(c, out); } break; case CLP: /* '(' in arithmetic */ state[level].parenlevel++; USTPUTC(c, out); break; case CRP: /* ')' in arithmetic */ if (state[level].parenlevel > 0) { USTPUTC(c, out); --state[level].parenlevel; } else { if (pgetc() == ')') { if (level > 0 && state[level].category == TSTATE_ARITH) { level--; USTPUTC(CTLENDARI, out); } else USTPUTC(')', out); } else { /* * unbalanced parens * (don't 2nd guess - no error) */ pungetc(); USTPUTC(')', out); } } break; case CBQUOTE: /* '`' */ out = parsebackq(out, &bqlist, 1, state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX); break; case CEOF: goto endword; /* exit outer loop */ case CIGN: break; default: if (level == 0) goto endword; /* exit outer loop */ USTPUTC(c, out); } c = pgetc_macro(); } } endword: if (state[level].syntax == ARISYNTAX) synerror("Missing '))'"); if (state[level].syntax != BASESYNTAX && eofmark == NULL) synerror("Unterminated quoted string"); if (state[level].category == TSTATE_VAR_OLD || state[level].category == TSTATE_VAR_NEW) { startlinno = plinno; synerror("Missing '}'"); } if (state != state_static) parser_temp_free_upto(state); USTPUTC('\0', out); len = out - stackblock(); out = stackblock(); if (eofmark == NULL) { if ((c == '>' || c == '<') && quotef == 0 && len <= 2 && (*out == '\0' || is_digit(*out))) { PARSEREDIR(); return lasttoken = TREDIR; } else { pungetc(); } } quoteflag = quotef; backquotelist = bqlist; grabstackblock(len); wordtext = out; return lasttoken = TWORD; /* end of readtoken routine */ /* * Check to see whether we are at the end of the here document. When this * is called, c is set to the first character of the next input line. If * we are at the end of the here document, this routine sets the c to PEOF. */ checkend: { if (eofmark) { if (striptabs) { while (c == '\t') c = pgetc(); } if (c == *eofmark) { if (pfgets(line, sizeof line) != NULL) { const char *p, *q; p = line; for (q = eofmark + 1 ; *q && *p == *q ; p++, q++); if ((*p == '\0' || *p == '\n') && *q == '\0') { c = PEOF; if (*p == '\n') { plinno++; needprompt = doprompt; } } else { pushstring(line, strlen(line), NULL); } } } } goto checkend_return; } /* * Parse a redirection operator. The variable "out" points to a string * specifying the fd to be redirected. The variable "c" contains the * first character of the redirection operator. */ parseredir: { char fd = *out; union node *np; np = (union node *)stalloc(sizeof (struct nfile)); if (c == '>') { np->nfile.fd = 1; c = pgetc(); if (c == '>') np->type = NAPPEND; else if (c == '&') np->type = NTOFD; else if (c == '|') np->type = NCLOBBER; else { np->type = NTO; pungetc(); } } else { /* c == '<' */ np->nfile.fd = 0; c = pgetc(); if (c == '<') { if (sizeof (struct nfile) != sizeof (struct nhere)) { np = (union node *)stalloc(sizeof (struct nhere)); np->nfile.fd = 0; } np->type = NHERE; heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc)); heredoc->here = np; if ((c = pgetc()) == '-') { heredoc->striptabs = 1; } else { heredoc->striptabs = 0; pungetc(); } } else if (c == '&') np->type = NFROMFD; else if (c == '>') np->type = NFROMTO; else { np->type = NFROM; pungetc(); } } if (fd != '\0') np->nfile.fd = digit_val(fd); redirnode = np; goto parseredir_return; } /* * Parse a substitution. At this point, we have read the dollar sign * and nothing else. */ parsesub: { char buf[10]; int subtype; int typeloc; int flags; char *p; static const char types[] = "}-+?="; int bracketed_name = 0; /* used to handle ${[0-9]*} variables */ int linno; int length; int c1; c = pgetc(); if (c == '(') { /* $(command) or $((arith)) */ if (pgetc() == '(') { PARSEARITH(); } else { pungetc(); out = parsebackq(out, &bqlist, 0, state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX); } } else if (c == '{' || is_name(c) || is_special(c)) { USTPUTC(CTLVAR, out); typeloc = out - stackblock(); USTPUTC(VSNORMAL, out); subtype = VSNORMAL; flags = 0; if (c == '{') { bracketed_name = 1; c = pgetc(); subtype = 0; } varname: if (!is_eof(c) && is_name(c)) { length = 0; do { STPUTC(c, out); c = pgetc(); length++; } while (!is_eof(c) && is_in_name(c)); if (length == 6 && strncmp(out - length, "LINENO", length) == 0) { /* Replace the variable name with the * current line number. */ linno = plinno; if (funclinno != 0) linno -= funclinno - 1; snprintf(buf, sizeof(buf), "%d", linno); STADJUST(-6, out); STPUTS(buf, out); flags |= VSLINENO; } } else if (is_digit(c)) { if (bracketed_name) { do { STPUTC(c, out); c = pgetc(); } while (is_digit(c)); } else { STPUTC(c, out); c = pgetc(); } } else if (is_special(c)) { c1 = c; c = pgetc(); if (subtype == 0 && c1 == '#') { subtype = VSLENGTH; if (strchr(types, c) == NULL && c != ':' && c != '#' && c != '%') goto varname; c1 = c; c = pgetc(); if (c1 != '}' && c == '}') { pungetc(); c = c1; goto varname; } pungetc(); c = c1; c1 = '#'; subtype = 0; } USTPUTC(c1, out); } else { subtype = VSERROR; if (c == '}') pungetc(); else if (c == '\n' || c == PEOF) synerror("Unexpected end of line in substitution"); else USTPUTC(c, out); } if (subtype == 0) { switch (c) { case ':': flags |= VSNUL; c = pgetc(); /*FALLTHROUGH*/ default: p = strchr(types, c); if (p == NULL) { if (c == '\n' || c == PEOF) synerror("Unexpected end of line in substitution"); if (flags == VSNUL) STPUTC(':', out); STPUTC(c, out); subtype = VSERROR; } else subtype = p - types + VSNORMAL; break; case '%': case '#': { int cc = c; subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT; c = pgetc(); if (c == cc) subtype++; else pungetc(); break; } } } else if (subtype != VSERROR) { if (subtype == VSLENGTH && c != '}') subtype = VSERROR; pungetc(); } STPUTC('=', out); if (state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX) flags |= VSQUOTE; *(stackblock() + typeloc) = subtype | flags; if (subtype != VSNORMAL) { if (level + 1 >= maxnest) { maxnest *= 2; if (state == state_static) { state = parser_temp_alloc( maxnest * sizeof(*state)); memcpy(state, state_static, MAXNEST_static * sizeof(*state)); } else state = parser_temp_realloc(state, maxnest * sizeof(*state)); } level++; state[level].parenlevel = 0; if (subtype == VSMINUS || subtype == VSPLUS || subtype == VSQUESTION || subtype == VSASSIGN) { /* * For operators that were in the Bourne shell, * inherit the double-quote state. */ state[level].syntax = state[level - 1].syntax; state[level].category = TSTATE_VAR_OLD; } else { /* * The other operators take a pattern, * so go to BASESYNTAX. * Also, ' and " are now special, even * in here documents. */ state[level].syntax = BASESYNTAX; state[level].category = TSTATE_VAR_NEW; newvarnest++; } } } else if (c == '\'' && state[level].syntax == BASESYNTAX) { /* $'cstylequotes' */ USTPUTC(CTLQUOTEMARK, out); state[level].syntax = SQSYNTAX; sqiscstyle = 1; } else { USTPUTC('$', out); pungetc(); } goto parsesub_return; } /* * Parse an arithmetic expansion (indicate start of one and set state) */ parsearith: { if (level + 1 >= maxnest) { maxnest *= 2; if (state == state_static) { state = parser_temp_alloc( maxnest * sizeof(*state)); memcpy(state, state_static, MAXNEST_static * sizeof(*state)); } else state = parser_temp_realloc(state, maxnest * sizeof(*state)); } level++; state[level].syntax = ARISYNTAX; state[level].parenlevel = 0; state[level].category = TSTATE_ARITH; USTPUTC(CTLARI, out); if (state[level - 1].syntax == DQSYNTAX) USTPUTC('"',out); else USTPUTC(' ',out); goto parsearith_return; } } /* end of readtoken */ - -#ifdef mkinit -RESET { +void +resetparser(void) +{ tokpushback = 0; checkkwd = 0; } -#endif + /* * Returns true if the text contains nothing to expand (no dollar signs * or backquotes). */ static int noexpand(char *text) { char *p; char c; p = text; while ((c = *p++) != '\0') { if ( c == CTLQUOTEMARK) continue; if (c == CTLESC) p++; else if (BASESYNTAX[(int)c] == CCTL) return 0; } return 1; } /* * Return true if the argument is a legal variable name (a letter or * underscore followed by zero or more letters, underscores, and digits). */ int goodname(const char *name) { const char *p; p = name; if (! is_name(*p)) return 0; while (*++p) { if (! is_in_name(*p)) return 0; } return 1; } int isassignment(const char *p) { if (!is_name(*p)) return 0; p++; for (;;) { if (*p == '=') return 1; else if (!is_in_name(*p)) return 0; p++; } } /* * Called when an unexpected token is read during the parse. The argument * is the token that is expected, or -1 if more than one type of token can * occur at this point. */ static void synexpect(int token) { char msg[64]; if (token >= 0) { fmtstr(msg, 64, "%s unexpected (expecting %s)", tokname[lasttoken], tokname[token]); } else { fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]); } synerror(msg); } static void synerror(const char *msg) { if (commandname) outfmt(out2, "%s: %d: ", commandname, startlinno); outfmt(out2, "Syntax error: %s\n", msg); error((char *)NULL); } static void setprompt(int which) { whichprompt = which; #ifndef NO_HISTORY if (!el) #endif { out2str(getprompt(NULL)); flushout(out2); } } /* * called by editline -- any expansions to the prompt * should be added here. */ char * getprompt(void *unused __unused) { static char ps[PROMPTLEN]; char *fmt; const char *pwd; int i, trim; static char internal_error[] = "??"; /* * Select prompt format. */ switch (whichprompt) { case 0: fmt = nullstr; break; case 1: fmt = ps1val(); break; case 2: fmt = ps2val(); break; default: return internal_error; } /* * Format prompt string. */ for (i = 0; (i < 127) && (*fmt != '\0'); i++, fmt++) if (*fmt == '\\') switch (*++fmt) { /* * Hostname. * * \h specifies just the local hostname, * \H specifies fully-qualified hostname. */ case 'h': case 'H': ps[i] = '\0'; gethostname(&ps[i], PROMPTLEN - i); /* Skip to end of hostname. */ trim = (*fmt == 'h') ? '.' : '\0'; while ((ps[i+1] != '\0') && (ps[i+1] != trim)) i++; break; /* * Working directory. * * \W specifies just the final component, * \w specifies the entire path. */ case 'W': case 'w': pwd = lookupvar("PWD"); if (pwd == NULL) pwd = "?"; if (*fmt == 'W' && *pwd == '/' && pwd[1] != '\0') strlcpy(&ps[i], strrchr(pwd, '/') + 1, PROMPTLEN - i); else strlcpy(&ps[i], pwd, PROMPTLEN - i); /* Skip to end of path. */ while (ps[i + 1] != '\0') i++; break; /* * Superuser status. * * '$' for normal users, '#' for root. */ case '$': ps[i] = (geteuid() != 0) ? '$' : '#'; break; /* * A literal \. */ case '\\': ps[i] = '\\'; break; /* * Emit unrecognized formats verbatim. */ default: ps[i++] = '\\'; ps[i] = *fmt; break; } else ps[i] = *fmt; ps[i] = '\0'; return (ps); } const char * expandstr(const char *ps) { union node n; struct jmploc jmploc; struct jmploc *const savehandler = handler; const int saveprompt = doprompt; struct parsefile *const savetopfile = getcurrentfile(); struct parser_temp *const saveparser_temp = parser_temp; const char *result = NULL; if (!setjmp(jmploc.loc)) { handler = &jmploc; parser_temp = NULL; setinputstring(ps, 1); doprompt = 0; readtoken1(pgetc(), DQSYNTAX, "\n\n", 0); if (backquotelist != NULL) error("Command substitution not allowed here"); n.narg.type = NARG; n.narg.next = NULL; n.narg.text = wordtext; n.narg.backquote = backquotelist; expandarg(&n, NULL, 0); result = stackblock(); INTOFF; } handler = savehandler; doprompt = saveprompt; popfilesupto(savetopfile); if (parser_temp != saveparser_temp) { parser_temp_free_all(); parser_temp = saveparser_temp; } if (result != NULL) { INTON; } else if (exception == EXINT) raise(SIGINT); return result; } Index: head/bin/sh/parser.h =================================================================== --- head/bin/sh/parser.h (revision 253649) +++ head/bin/sh/parser.h (revision 253650) @@ -1,85 +1,86 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)parser.h 8.3 (Berkeley) 5/4/95 * $FreeBSD$ */ /* control characters in argument strings */ #define CTLESC '\300' #define CTLVAR '\301' #define CTLENDVAR '\371' #define CTLBACKQ '\372' #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */ /* CTLBACKQ | CTLQUOTE == '\373' */ #define CTLARI '\374' #define CTLENDARI '\375' #define CTLQUOTEMARK '\376' #define CTLQUOTEEND '\377' /* only for ${v+-...} */ /* variable substitution byte (follows CTLVAR) */ #define VSTYPE 0x0f /* type of variable substitution */ #define VSNUL 0x10 /* colon--treat the empty string as unset */ #define VSLINENO 0x20 /* expansion of $LINENO, the line number \ follows immediately */ #define VSQUOTE 0x80 /* inside double quotes--suppress splitting */ /* values of VSTYPE field */ #define VSNORMAL 0x1 /* normal variable: $var or ${var} */ #define VSMINUS 0x2 /* ${var-text} */ #define VSPLUS 0x3 /* ${var+text} */ #define VSQUESTION 0x4 /* ${var?message} */ #define VSASSIGN 0x5 /* ${var=text} */ #define VSTRIMLEFT 0x6 /* ${var#pattern} */ #define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */ #define VSTRIMRIGHT 0x8 /* ${var%pattern} */ #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */ #define VSLENGTH 0xa /* ${#var} */ #define VSERROR 0xb /* Syntax error, issue when expanded */ /* * NEOF is returned by parsecmd when it encounters an end of file. It * must be distinct from NULL, so we use the address of a variable that * happens to be handy. */ extern int tokpushback; #define NEOF ((union node *)&tokpushback) extern int whichprompt; /* 1 == PS1, 2 == PS2 */ extern const char *const parsekwd[]; union node *parsecmd(int); void fixredir(union node *, const char *, int); +void resetparser(void); int goodname(const char *); int isassignment(const char *); char *getprompt(void *); const char *expandstr(const char *); Index: head/bin/sh/redir.c =================================================================== --- head/bin/sh/redir.c (revision 253649) +++ head/bin/sh/redir.c (revision 253650) @@ -1,363 +1,360 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint #if 0 static char sccsid[] = "@(#)redir.c 8.2 (Berkeley) 5/4/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include /* * Code for dealing with input/output redirection. */ #include "shell.h" #include "nodes.h" #include "jobs.h" #include "expand.h" #include "redir.h" #include "output.h" #include "memalloc.h" #include "error.h" #include "options.h" #define EMPTY -2 /* marks an unused slot in redirtab */ #define CLOSED -1 /* fd was not open before redir */ MKINIT struct redirtab { struct redirtab *next; int renamed[10]; }; MKINIT struct redirtab *redirlist; /* * We keep track of whether or not fd0 has been redirected. This is for * background commands, where we want to redirect fd0 to /dev/null only * if it hasn't already been redirected. */ static int fd0_redirected = 0; static void openredirect(union node *, char[10 ]); static int openhere(union node *); /* * Process a list of redirection commands. If the REDIR_PUSH flag is set, * old file descriptors are stashed away so that the redirection can be * undone by calling popredir. If the REDIR_BACKQ flag is set, then the * standard output, and the standard error if it becomes a duplicate of * stdout, is saved in memory. */ void redirect(union node *redir, int flags) { union node *n; struct redirtab *sv = NULL; int i; int fd; char memory[10]; /* file descriptors to write to memory */ for (i = 10 ; --i >= 0 ; ) memory[i] = 0; memory[1] = flags & REDIR_BACKQ; if (flags & REDIR_PUSH) { sv = ckmalloc(sizeof (struct redirtab)); for (i = 0 ; i < 10 ; i++) sv->renamed[i] = EMPTY; sv->next = redirlist; redirlist = sv; } for (n = redir ; n ; n = n->nfile.next) { fd = n->nfile.fd; if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) && n->ndup.dupfd == fd) continue; /* redirect from/to same file descriptor */ if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) { INTOFF; if ((i = fcntl(fd, F_DUPFD_CLOEXEC, 10)) == -1) { switch (errno) { case EBADF: i = CLOSED; break; default: INTON; error("%d: %s", fd, strerror(errno)); break; } } sv->renamed[fd] = i; INTON; } if (fd == 0) fd0_redirected++; openredirect(n, memory); } if (memory[1]) out1 = &memout; if (memory[2]) out2 = &memout; } static void openredirect(union node *redir, char memory[10]) { struct stat sb; int fd = redir->nfile.fd; char *fname; int f; int e; /* * We suppress interrupts so that we won't leave open file * descriptors around. Because the signal handler remains * installed and we do not use system call restart, interrupts * will still abort blocking opens such as fifos (they will fail * with EINTR). There is, however, a race condition if an interrupt * arrives after INTOFF and before open blocks. */ INTOFF; memory[fd] = 0; switch (redir->nfile.type) { case NFROM: fname = redir->nfile.expfname; if ((f = open(fname, O_RDONLY)) < 0) error("cannot open %s: %s", fname, strerror(errno)); movefd: if (f != fd) { if (dup2(f, fd) == -1) { e = errno; close(f); error("%d: %s", fd, strerror(e)); } close(f); } break; case NFROMTO: fname = redir->nfile.expfname; if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0) error("cannot create %s: %s", fname, strerror(errno)); goto movefd; case NTO: if (Cflag) { fname = redir->nfile.expfname; if (stat(fname, &sb) == -1) { if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0) error("cannot create %s: %s", fname, strerror(errno)); } else if (!S_ISREG(sb.st_mode)) { if ((f = open(fname, O_WRONLY, 0666)) < 0) error("cannot create %s: %s", fname, strerror(errno)); if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) { close(f); error("cannot create %s: %s", fname, strerror(EEXIST)); } } else error("cannot create %s: %s", fname, strerror(EEXIST)); goto movefd; } /* FALLTHROUGH */ case NCLOBBER: fname = redir->nfile.expfname; if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0) error("cannot create %s: %s", fname, strerror(errno)); goto movefd; case NAPPEND: fname = redir->nfile.expfname; if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0) error("cannot create %s: %s", fname, strerror(errno)); goto movefd; case NTOFD: case NFROMFD: if (redir->ndup.dupfd >= 0) { /* if not ">&-" */ if (memory[redir->ndup.dupfd]) memory[fd] = 1; else { if (dup2(redir->ndup.dupfd, fd) < 0) error("%d: %s", redir->ndup.dupfd, strerror(errno)); } } else { close(fd); } break; case NHERE: case NXHERE: f = openhere(redir); goto movefd; default: abort(); } INTON; } /* * Handle here documents. Normally we fork off a process to write the * data to a pipe. If the document is short, we can stuff the data in * the pipe without forking. */ static int openhere(union node *redir) { char *p; int pip[2]; size_t len = 0; int flags; ssize_t written = 0; if (pipe(pip) < 0) error("Pipe call failed: %s", strerror(errno)); if (redir->type == NXHERE) p = redir->nhere.expdoc; else p = redir->nhere.doc->narg.text; len = strlen(p); if (len == 0) goto out; flags = fcntl(pip[1], F_GETFL, 0); if (flags != -1 && fcntl(pip[1], F_SETFL, flags | O_NONBLOCK) != -1) { written = write(pip[1], p, len); if (written < 0) written = 0; if ((size_t)written == len) goto out; fcntl(pip[1], F_SETFL, flags); } if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) { close(pip[0]); signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGTSTP, SIG_IGN); signal(SIGPIPE, SIG_DFL); xwrite(pip[1], p + written, len - written); _exit(0); } out: close(pip[1]); return pip[0]; } /* * Undo the effects of the last redirection. */ void popredir(void) { struct redirtab *rp = redirlist; int i; for (i = 0 ; i < 10 ; i++) { if (rp->renamed[i] != EMPTY) { if (i == 0) fd0_redirected--; if (rp->renamed[i] >= 0) { dup2(rp->renamed[i], i); close(rp->renamed[i]); } else { close(i); } } } INTOFF; redirlist = rp->next; ckfree(rp); INTON; } /* * Undo all redirections. Called on error or interrupt. */ -#ifdef mkinit - -INCLUDE "redir.h" - -RESET { +void +resetredir(void) +{ while (redirlist) popredir(); } -#endif /* Return true if fd 0 has already been redirected at least once. */ int fd0_redirected_p(void) { return fd0_redirected != 0; } /* * Discard all saved file descriptors. */ void clearredir(void) { struct redirtab *rp; int i; for (rp = redirlist ; rp ; rp = rp->next) { for (i = 0 ; i < 10 ; i++) { if (rp->renamed[i] >= 0) { close(rp->renamed[i]); } rp->renamed[i] = EMPTY; } } } Index: head/bin/sh/redir.h =================================================================== --- head/bin/sh/redir.h (revision 253649) +++ head/bin/sh/redir.h (revision 253650) @@ -1,45 +1,46 @@ /*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Kenneth Almquist. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)redir.h 8.2 (Berkeley) 5/4/95 * $FreeBSD$ */ /* flags passed to redirect */ #define REDIR_PUSH 01 /* save previous values of file descriptors */ #define REDIR_BACKQ 02 /* save the command output in memory */ union node; void redirect(union node *, int); void popredir(void); +void resetredir(void); int fd0_redirected_p(void); void clearredir(void);