diff --git a/bin/sh/histedit.c b/bin/sh/histedit.c index 453260a27e54..8812200279f0 100644 --- a/bin/sh/histedit.c +++ b/bin/sh/histedit.c @@ -1,761 +1,764 @@ /*- * 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. * 3. 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[] = "@(#)histedit.c 8.2 (Berkeley) 5/4/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include /* * Editline and history functions (and glue). */ #include "shell.h" #include "parser.h" #include "var.h" #include "options.h" #include "main.h" #include "output.h" #include "mystring.h" #include "builtins.h" #ifndef NO_HISTORY #include "myhistedit.h" #include "error.h" #include "eval.h" #include "memalloc.h" #define MAXHISTLOOPS 4 /* max recursions through fc */ #define DEFEDITOR "ed" /* default editor *should* be $EDITOR */ History *hist; /* history cookie */ EditLine *el; /* editline cookie */ int displayhist; static int savehist; static FILE *el_in, *el_out; static bool in_command_completion; static char *fc_replace(const char *, char *, char *); static int not_fcnumber(const char *); static int str_to_event(const char *, int); static int comparator(const void *, const void *, void *); static char **sh_matches(const char *, int, int); static const char *append_char_function(const char *); static unsigned char sh_complete(EditLine *, int); static const char * get_histfile(void) { const char *histfile; /* don't try to save if the history size is 0 */ if (hist == NULL || histsizeval() == 0) return (NULL); histfile = expandstr("${HISTFILE-${HOME-}/.sh_history}"); if (histfile[0] == '\0') return (NULL); return (histfile); } void histsave(void) { HistEvent he; char *histtmpname = NULL; const char *histfile; int fd; FILE *f; if (!savehist || (histfile = get_histfile()) == NULL) return; INTOFF; asprintf(&histtmpname, "%s.XXXXXXXXXX", histfile); if (histtmpname == NULL) { INTON; return; } fd = mkstemp(histtmpname); if (fd == -1 || (f = fdopen(fd, "w")) == NULL) { free(histtmpname); INTON; return; } if (history(hist, &he, H_SAVE_FP, f) < 1 || rename(histtmpname, histfile) == -1) unlink(histtmpname); fclose(f); free(histtmpname); INTON; } void histload(void) { const char *histfile; HistEvent he; if ((histfile = get_histfile()) == NULL) return; errno = 0; if (history(hist, &he, H_LOAD, histfile) != -1 || errno == ENOENT) savehist = 1; } /* * Set history and editing status. Called whenever the status may * have changed (figures out what to do). */ void histedit(void) { #define editing (Eflag || Vflag) if (iflag) { if (!hist) { /* * turn history on */ INTOFF; hist = history_init(); INTON; if (hist != NULL) sethistsize(histsizeval()); else out2fmt_flush("sh: can't initialize history\n"); } if (editing && !el && isatty(0)) { /* && isatty(2) ??? */ /* * turn editing on */ char *term; INTOFF; if (el_in == NULL) el_in = fdopen(0, "r"); if (el_out == NULL) el_out = fdopen(2, "w"); if (el_in == NULL || el_out == NULL) goto bad; term = lookupvar("TERM"); if (term) setenv("TERM", term, 1); else unsetenv("TERM"); el = el_init(arg0, el_in, el_out, el_out); if (el != NULL) { if (hist) el_set(el, EL_HIST, history, hist); el_set(el, EL_PROMPT, getprompt); el_set(el, EL_ADDFN, "sh-complete", "Filename completion", sh_complete); } else { bad: out2fmt_flush("sh: can't initialize editing\n"); } INTON; } else if (!editing && el) { INTOFF; el_end(el); el = NULL; INTON; } if (el) { if (Vflag) el_set(el, EL_EDITOR, "vi"); else if (Eflag) { el_set(el, EL_EDITOR, "emacs"); } el_set(el, EL_BIND, "^I", "sh-complete", NULL); el_source(el, NULL); } } else { INTOFF; if (el) { /* no editing if not interactive */ el_end(el); el = NULL; } if (hist) { history_end(hist); hist = NULL; } INTON; } } void sethistsize(const char *hs) { int histsize; HistEvent he; if (hist != NULL) { if (hs == NULL || !is_number(hs)) histsize = 100; else histsize = atoi(hs); history(hist, &he, H_SETSIZE, histsize); history(hist, &he, H_SETUNIQUE, 1); } } void setterm(const char *term) { if (rootshell && el != NULL && term != NULL) el_set(el, EL_TERMINAL, term); } int histcmd(int argc, char **argv __unused) { - int ch; const char *editor = NULL; HistEvent he; int lflg = 0, nflg = 0, rflg = 0, sflg = 0; int i, retval; const char *firststr, *laststr; int first, last, direction; char *pat = NULL, *repl = NULL; static int active = 0; struct jmploc jmploc; struct jmploc *savehandler; char editfilestr[PATH_MAX]; char *volatile editfile; FILE *efp = NULL; int oldhistnum; if (hist == NULL) error("history not active"); if (argc == 1) error("missing history argument"); - while (not_fcnumber(*argptr) && (ch = nextopt("e:lnrs")) != '\0') - switch ((char)ch) { - case 'e': - editor = shoptarg; - break; - case 'l': - lflg = 1; - break; - case 'n': - nflg = 1; - break; - case 'r': - rflg = 1; - break; - case 's': - sflg = 1; - break; - } - + while (not_fcnumber(*argptr)) + do { + switch (nextopt("e:lnrs")) { + case 'e': + editor = shoptarg; + break; + case 'l': + lflg = 1; + break; + case 'n': + nflg = 1; + break; + case 'r': + rflg = 1; + break; + case 's': + sflg = 1; + break; + case '\0': + goto operands; + } + } while (nextopt_optptr != NULL); +operands: savehandler = handler; /* * If executing... */ if (lflg == 0 || editor || sflg) { lflg = 0; /* ignore */ editfile = NULL; /* * Catch interrupts to reset active counter and * cleanup temp files. */ if (setjmp(jmploc.loc)) { active = 0; if (editfile) unlink(editfile); handler = savehandler; longjmp(handler->loc, 1); } handler = &jmploc; if (++active > MAXHISTLOOPS) { active = 0; displayhist = 0; error("called recursively too many times"); } /* * Set editor. */ if (sflg == 0) { if (editor == NULL && (editor = bltinlookup("FCEDIT", 1)) == NULL && (editor = bltinlookup("EDITOR", 1)) == NULL) editor = DEFEDITOR; if (editor[0] == '-' && editor[1] == '\0') { sflg = 1; /* no edit */ editor = NULL; } } } /* * If executing, parse [old=new] now */ if (lflg == 0 && *argptr != NULL && ((repl = strchr(*argptr, '=')) != NULL)) { pat = *argptr; *repl++ = '\0'; argptr++; } /* * determine [first] and [last] */ if (*argptr == NULL) { firststr = lflg ? "-16" : "-1"; laststr = "-1"; } else if (argptr[1] == NULL) { firststr = argptr[0]; laststr = lflg ? "-1" : argptr[0]; } else if (argptr[2] == NULL) { firststr = argptr[0]; laststr = argptr[1]; } else error("too many arguments"); /* * Turn into event numbers. */ first = str_to_event(firststr, 0); last = str_to_event(laststr, 1); if (rflg) { i = last; last = first; first = i; } /* * XXX - this should not depend on the event numbers * always increasing. Add sequence numbers or offset * to the history element in next (diskbased) release. */ direction = first < last ? H_PREV : H_NEXT; /* * If editing, grab a temp file. */ if (editor) { int fd; INTOFF; /* easier */ sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP); if ((fd = mkstemp(editfilestr)) < 0) error("can't create temporary file %s", editfile); editfile = editfilestr; if ((efp = fdopen(fd, "w")) == NULL) { close(fd); error("Out of space"); } } /* * Loop through selected history events. If listing or executing, * do it now. Otherwise, put into temp file and call the editor * after. * * The history interface needs rethinking, as the following * convolutions will demonstrate. */ history(hist, &he, H_FIRST); retval = history(hist, &he, H_NEXT_EVENT, first); for (;retval != -1; retval = history(hist, &he, direction)) { if (lflg) { if (!nflg) out1fmt("%5d ", he.num); out1str(he.str); } else { const char *s = pat ? fc_replace(he.str, pat, repl) : he.str; if (sflg) { if (displayhist) { out2str(s); flushout(out2); } evalstring(s, 0); if (displayhist && hist) { /* * XXX what about recursive and * relative histnums. */ oldhistnum = he.num; history(hist, &he, H_ENTER, s); /* * XXX H_ENTER moves the internal * cursor, set it back to the current * entry. */ history(hist, &he, H_NEXT_EVENT, oldhistnum); } } else fputs(s, efp); } /* * At end? (if we were to lose last, we'd sure be * messed up). */ if (he.num == last) break; } if (editor) { char *editcmd; fclose(efp); INTON; editcmd = stalloc(strlen(editor) + strlen(editfile) + 2); sprintf(editcmd, "%s %s", editor, editfile); evalstring(editcmd, 0); /* XXX - should use no JC command */ readcmdfile(editfile, 0 /* verify */); /* XXX - should read back - quick tst */ unlink(editfile); } if (lflg == 0 && active > 0) --active; if (displayhist) displayhist = 0; handler = savehandler; return 0; } static char * fc_replace(const char *s, char *p, char *r) { char *dest; int plen = strlen(p); STARTSTACKSTR(dest); while (*s) { if (*s == *p && strncmp(s, p, plen) == 0) { STPUTS(r, dest); s += plen; *p = '\0'; /* so no more matches */ } else STPUTC(*s++, dest); } STPUTC('\0', dest); dest = grabstackstr(dest); return (dest); } static int not_fcnumber(const char *s) { if (s == NULL) return (0); if (*s == '-') s++; return (!is_number(s)); } static int str_to_event(const char *str, int last) { HistEvent he; const char *s = str; int relative = 0; int i, retval; retval = history(hist, &he, H_FIRST); switch (*s) { case '-': relative = 1; /*FALLTHROUGH*/ case '+': s++; } if (is_number(s)) { i = atoi(s); if (relative) { while (retval != -1 && i--) { retval = history(hist, &he, H_NEXT); } if (retval == -1) retval = history(hist, &he, H_LAST); } else { retval = history(hist, &he, H_NEXT_EVENT, i); if (retval == -1) { /* * the notion of first and last is * backwards to that of the history package */ retval = history(hist, &he, last ? H_FIRST : H_LAST); } } if (retval == -1) error("history number %s not found (internal error)", str); } else { /* * pattern */ retval = history(hist, &he, H_PREV_STR, str); if (retval == -1) error("history pattern not found: %s", str); } return (he.num); } int bindcmd(int argc, char **argv) { int ret; FILE *old; FILE *out; if (el == NULL) error("line editing is disabled"); INTOFF; out = out1fp(); if (out == NULL) error("Out of space"); el_get(el, EL_GETFP, 1, &old); el_set(el, EL_SETFP, 1, out); ret = el_parse(el, argc, __DECONST(const char **, argv)); el_set(el, EL_SETFP, 1, old); fclose(out); if (argc > 1 && argv[1][0] == '-' && memchr("ve", argv[1][1], 2) != NULL) { Vflag = argv[1][1] == 'v'; Eflag = !Vflag; histedit(); } INTON; return ret; } /* * Comparator function for qsort(). The use of curpos here is to skip * characters that we already know to compare equal (common prefix). */ static int comparator(const void *a, const void *b, void *thunk) { size_t curpos = (intptr_t)thunk; return (strcmp(*(char *const *)a + curpos, *(char *const *)b + curpos)); } /* * This function is passed to libedit's fn_complete2(). The library will * use it instead of its standard function that finds matching files in * current directory. If we're at the start of the line, we want to look * for available commands from all paths in $PATH. */ static char **sh_matches(const char *text, int start, int end) { char *free_path = NULL, *path; const char *dirname; char **matches = NULL; size_t i = 0, size = 16, uniq; size_t curpos = end - start, lcstring = -1; in_command_completion = false; if (start > 0 || memchr("/.~", text[0], 3) != NULL) return (NULL); in_command_completion = true; if ((free_path = path = strdup(pathval())) == NULL) goto out; if ((matches = malloc(size * sizeof(matches[0]))) == NULL) goto out; while ((dirname = strsep(&path, ":")) != NULL) { struct dirent *entry; DIR *dir; int dfd; dir = opendir(dirname[0] == '\0' ? "." : dirname); if (dir == NULL) continue; if ((dfd = dirfd(dir)) == -1) { closedir(dir); continue; } while ((entry = readdir(dir)) != NULL) { struct stat statb; char **rmatches; if (strncmp(entry->d_name, text, curpos) != 0) continue; if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) { if (fstatat(dfd, entry->d_name, &statb, 0) == -1) continue; if (!S_ISREG(statb.st_mode)) continue; } else if (entry->d_type != DT_REG) continue; matches[++i] = strdup(entry->d_name); if (i < size - 1) continue; size *= 2; rmatches = reallocarray(matches, size, sizeof(matches[0])); if (rmatches == NULL) { closedir(dir); goto out; } matches = rmatches; } closedir(dir); } out: free(free_path); if (i == 0) { free(matches); return (NULL); } uniq = 1; if (i > 1) { qsort_s(matches + 1, i, sizeof(matches[0]), comparator, (void *)(intptr_t)curpos); for (size_t k = 2; k <= i; k++) { const char *l = matches[uniq] + curpos; const char *r = matches[k] + curpos; size_t common = 0; while (*l != '\0' && *r != '\0' && *l == *r) (void)l++, r++, common++; if (common < lcstring) lcstring = common; if (*l == *r) free(matches[k]); else matches[++uniq] = matches[k]; } } matches[uniq + 1] = NULL; /* * matches[0] is special: it's not a real matching file name but a common * prefix for all matching names. It can't be null, unlike any other * element of the array. When strings matches[0] and matches[1] compare * equal and matches[2] is null that means to libedit that there is only * a single match. It will then replace user input with possibly escaped * string in matches[0] which is the reason to copy the full name of the * only match. */ if (uniq == 1) matches[0] = strdup(matches[1]); else if (lcstring != (size_t)-1) matches[0] = strndup(matches[1], curpos + lcstring); else matches[0] = strdup(text); if (matches[0] == NULL) { for (size_t k = 1; k <= uniq; k++) free(matches[k]); free(matches); return (NULL); } return (matches); } /* * If we don't specify this function as app_func in the call to fn_complete2, * libedit will use the default one, which adds a " " to plain files and * a "/" to directories regardless of whether it's a command name or a plain * path (relative or absolute). We never want to add "/" to commands. * * For example, after I did "mkdir rmdir", "rmdi" would be autocompleted to * "rmdir/" instead of "rmdir ". */ static const char * append_char_function(const char *name) { struct stat stbuf; char *expname = name[0] == '~' ? fn_tilde_expand(name) : NULL; const char *rs; if (!in_command_completion && stat(expname ? expname : name, &stbuf) == 0 && S_ISDIR(stbuf.st_mode)) rs = "/"; else rs = " "; free(expname); return (rs); } /* * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to * bind a key (tab by default) to execute the function. */ unsigned char sh_complete(EditLine *sel, int ch __unused) { return (unsigned char)fn_complete2(sel, NULL, sh_matches, L" \t\n\"\\'`@$><=;|&{(", NULL, append_char_function, (size_t)100, NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH); } #else #include "error.h" int histcmd(int argc __unused, char **argv __unused) { error("not compiled with history support"); /*NOTREACHED*/ return (0); } int bindcmd(int argc __unused, char **argv __unused) { error("not compiled with line editing support"); return (0); } #endif diff --git a/bin/sh/options.c b/bin/sh/options.c index 97171d32bff1..55bfd9d483b7 100644 --- a/bin/sh/options.c +++ b/bin/sh/options.c @@ -1,594 +1,597 @@ /*- * SPDX-License-Identifier: BSD-3-Clause * * 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. * 3. 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[] = "@(#)options.c 8.2 (Berkeley) 5/4/95"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include "shell.h" #define DEFINE_OPTIONS #include "options.h" #undef DEFINE_OPTIONS #include "nodes.h" /* for other header files */ #include "eval.h" #include "jobs.h" #include "input.h" #include "output.h" #include "trap.h" #include "var.h" #include "memalloc.h" #include "error.h" #include "mystring.h" #include "builtins.h" #ifndef NO_HISTORY #include "myhistedit.h" #endif char *arg0; /* value of $0 */ struct shparam shellparam; /* current positional parameters */ char **argptr; /* argument list for builtin commands */ char *shoptarg; /* set by nextopt (like getopt) */ char *nextopt_optptr; /* used by nextopt */ char *minusc; /* argument to -c option */ static void options(int); static void minus_o(char *, int); static void setoption(int, int); static void setoptionbyindex(int, int); static void setparam(int, char **); static int getopts(char *, char *, char **, char ***, char **); /* * Process the shell command line arguments. */ void procargs(int argc, char **argv) { int i; char *scriptname; argptr = argv; if (argc > 0) argptr++; for (i = 0; i < NOPTS; i++) optval[i] = 2; privileged = (getuid() != geteuid() || getgid() != getegid()); options(1); if (*argptr == NULL && minusc == NULL) sflag = 1; if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) { iflag = 1; if (Eflag == 2) Eflag = 1; } if (mflag == 2) mflag = iflag; for (i = 0; i < NOPTS; i++) if (optval[i] == 2) optval[i] = 0; arg0 = argv[0]; if (sflag == 0 && minusc == NULL) { scriptname = *argptr++; setinputfile(scriptname, 0, -1 /* verify */); commandname = arg0 = scriptname; } /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */ if (argptr && minusc && *argptr) arg0 = *argptr++; shellparam.p = argptr; shellparam.reset = 1; /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */ while (*argptr) { shellparam.nparam++; argptr++; } optschanged(); } void optschanged(void) { setinteractive(); #ifndef NO_HISTORY histedit(); #endif setjobctl(mflag); } /* * Process shell options. The global variable argptr contains a pointer * to the argument list; we advance it past the options. * If cmdline is true, process the shell's argv; otherwise, process arguments * to the set special builtin. */ static void options(int cmdline) { char *kp, *p; int val; int c; if (cmdline) minusc = NULL; while ((p = *argptr) != NULL) { argptr++; if ((c = *p++) == '-') { val = 1; /* A "-" or "--" terminates options */ if (p[0] == '\0') goto end_options1; if (p[0] == '-' && p[1] == '\0') goto end_options2; /** * For the benefit of `#!' lines in shell scripts, * treat a string of '-- *#.*' the same as '--'. * This is needed so that a script starting with: * #!/bin/sh -- # -*- perl -*- * will continue to work after a change is made to * kern/imgact_shell.c to NOT token-ize the options * specified on a '#!' line. A bit of a kludge, * but that trick is recommended in documentation * for some scripting languages, and we might as * well continue to support it. */ if (p[0] == '-') { kp = p + 1; while (*kp == ' ' || *kp == '\t') kp++; if (*kp == '#' || *kp == '\0') goto end_options2; } } else if (c == '+') { val = 0; } else { argptr--; break; } while ((c = *p++) != '\0') { if (c == 'c' && cmdline) { char *q; q = *argptr++; if (q == NULL || minusc != NULL) error("Bad -c option"); minusc = q; } else if (c == 'o') { minus_o(*argptr, val); if (*argptr) argptr++; } else setoption(c, val); } } return; /* When processing `set', a single "-" means turn off -x and -v */ end_options1: if (!cmdline) { xflag = vflag = 0; return; } /* * When processing `set', a "--" means the remaining arguments * replace the positional parameters in the active shell. If * there are no remaining options, then all the positional * parameters are cleared (equivalent to doing ``shift $#''). */ end_options2: if (!cmdline) { if (*argptr == NULL) setparam(0, argptr); return; } /* * At this point we are processing options given to 'sh' on a command * line. If an end-of-options marker ("-" or "--") is followed by an * arg of "#", then skip over all remaining arguments. Some scripting * languages (e.g.: perl) document that /bin/sh will implement this * behavior, and they recommend that users take advantage of it to * solve certain issues that can come up when writing a perl script. * Yes, this feature is in /bin/sh to help users write perl scripts. */ p = *argptr; if (p != NULL && p[0] == '#' && p[1] == '\0') { while (*argptr != NULL) argptr++; /* We need to keep the final argument */ argptr--; } } static void minus_o(char *name, int val) { int i; const unsigned char *on; size_t len; if (name == NULL) { if (val) { /* "Pretty" output. */ out1str("Current option settings\n"); for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1) out1fmt("%-16.*s%s\n", *on, on + 1, optval[i] ? "on" : "off"); } else { /* Output suitable for re-input to shell. */ for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1) out1fmt("%s %co %.*s%s", i % 6 == 0 ? "set" : "", optval[i] ? '-' : '+', *on, on + 1, i % 6 == 5 || i == NOPTS - 1 ? "\n" : ""); } } else { len = strlen(name); for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1) if (*on == len && memcmp(on + 1, name, len) == 0) { setoptionbyindex(i, val); return; } error("Illegal option -o %s", name); } } static void setoptionbyindex(int idx, int val) { if (&optval[idx] == &privileged && !val && privileged) { if (setgid(getgid()) == -1) error("setgid"); if (setuid(getuid()) == -1) error("setuid"); } optval[idx] = val; if (val) { /* #%$ hack for ksh semantics */ if (&optval[idx] == &Vflag) Eflag = 0; else if (&optval[idx] == &Eflag) Vflag = 0; } } static void setoption(int flag, int val) { int i; for (i = 0; i < NSHORTOPTS; i++) if (optletter[i] == flag) { setoptionbyindex(i, val); return; } error("Illegal option -%c", flag); } /* * Set the shell parameters. */ static void setparam(int argc, char **argv) { char **newparam; char **ap; ap = newparam = ckmalloc((argc + 1) * sizeof *ap); while (*argv) { *ap++ = savestr(*argv++); } *ap = NULL; freeparam(&shellparam); shellparam.malloc = 1; shellparam.nparam = argc; shellparam.p = newparam; shellparam.optp = NULL; shellparam.reset = 1; shellparam.optnext = NULL; } /* * Free the list of positional parameters. */ void freeparam(struct shparam *param) { char **ap; if (param->malloc) { for (ap = param->p ; *ap ; ap++) ckfree(*ap); ckfree(param->p); } if (param->optp) { for (ap = param->optp ; *ap ; ap++) ckfree(*ap); ckfree(param->optp); } } /* * The shift builtin command. */ int shiftcmd(int argc, char **argv) { int i, n; n = 1; if (argc > 1) n = number(argv[1]); if (n > shellparam.nparam) return 1; INTOFF; shellparam.nparam -= n; if (shellparam.malloc) for (i = 0; i < n; i++) ckfree(shellparam.p[i]); memmove(shellparam.p, shellparam.p + n, (shellparam.nparam + 1) * sizeof(shellparam.p[0])); shellparam.reset = 1; INTON; return 0; } /* * The set builtin command. */ int setcmd(int argc, char **argv) { if (argc == 1) return showvarscmd(argc, argv); INTOFF; options(0); optschanged(); if (*argptr != NULL) { setparam(argc - (argptr - argv), argptr); } INTON; return 0; } void getoptsreset(const char *value) { while (*value == '0') value++; if (strcmp(value, "1") == 0) shellparam.reset = 1; } /* * The getopts builtin. Shellparam.optnext points to the next argument * to be processed. Shellparam.optptr points to the next character to * be processed in the current argument. If shellparam.optnext is NULL, * then it's the first time getopts has been called. */ int getoptscmd(int argc, char **argv) { char **optbase = NULL, **ap; int i; if (argc < 3) error("usage: getopts optstring var [arg]"); if (shellparam.reset == 1) { INTOFF; if (shellparam.optp) { for (ap = shellparam.optp ; *ap ; ap++) ckfree(*ap); ckfree(shellparam.optp); shellparam.optp = NULL; } if (argc > 3) { shellparam.optp = ckmalloc((argc - 2) * sizeof *ap); memset(shellparam.optp, '\0', (argc - 2) * sizeof *ap); for (i = 0; i < argc - 3; i++) shellparam.optp[i] = savestr(argv[i + 3]); } INTON; optbase = argc == 3 ? shellparam.p : shellparam.optp; shellparam.optnext = optbase; shellparam.optptr = NULL; shellparam.reset = 0; } else optbase = shellparam.optp ? shellparam.optp : shellparam.p; return getopts(argv[1], argv[2], optbase, &shellparam.optnext, &shellparam.optptr); } static int getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optptr) { char *p, *q; char c = '?'; int done = 0; int ind = 0; int err = 0; char s[10]; const char *newoptarg = NULL; if ((p = *optptr) == NULL || *p == '\0') { /* Current word is done, advance */ if (*optnext == NULL) return 1; p = **optnext; if (p == NULL || *p != '-' || *++p == '\0') { atend: ind = *optnext - optfirst + 1; *optnext = NULL; p = NULL; done = 1; goto out; } (*optnext)++; if (p[0] == '-' && p[1] == '\0') /* check for "--" */ goto atend; } c = *p++; for (q = optstr; *q != c; ) { if (*q == '\0') { if (optstr[0] == ':') { s[0] = c; s[1] = '\0'; newoptarg = s; } else out2fmt_flush("Illegal option -%c\n", c); c = '?'; goto out; } if (*++q == ':') q++; } if (*++q == ':') { if (*p == '\0' && (p = **optnext) == NULL) { if (optstr[0] == ':') { s[0] = c; s[1] = '\0'; newoptarg = s; c = ':'; } else { out2fmt_flush("No arg for -%c option\n", c); c = '?'; } goto out; } if (p == **optnext) (*optnext)++; newoptarg = p; p = NULL; } out: if (*optnext != NULL) ind = *optnext - optfirst + 1; *optptr = p; if (newoptarg != NULL) err |= setvarsafe("OPTARG", newoptarg, 0); else { INTOFF; err |= unsetvar("OPTARG"); INTON; } fmtstr(s, sizeof(s), "%d", ind); err |= setvarsafe("OPTIND", s, VNOFUNC); s[0] = c; s[1] = '\0'; err |= setvarsafe(optvar, s, 0); if (err) { *optnext = NULL; *optptr = NULL; flushall(); exraise(EXERROR); } return done; } /* * Standard option processing (a la getopt) for builtin routines. The * only argument that is passed to nextopt is the option string; the * other arguments are unnecessary. It returns the option, or '\0' on * end of input. */ int nextopt(const char *optstring) { char *p; const char *q; char c; if ((p = nextopt_optptr) == NULL || *p == '\0') { p = *argptr; if (p == NULL || *p != '-' || *++p == '\0') return '\0'; argptr++; if (p[0] == '-' && p[1] == '\0') /* check for "--" */ return '\0'; } c = *p++; for (q = optstring ; *q != c ; ) { if (*q == '\0') error("Illegal option -%c", c); if (*++q == ':') q++; } if (*++q == ':') { if (*p == '\0' && (p = *argptr++) == NULL) error("No arg for -%c option", c); shoptarg = p; p = NULL; } - nextopt_optptr = p; + if (p != NULL && *p != '\0') + nextopt_optptr = p; + else + nextopt_optptr = NULL; return c; } diff --git a/bin/sh/tests/builtins/Makefile b/bin/sh/tests/builtins/Makefile index f9b464a6da4b..727a7bc6c848 100644 --- a/bin/sh/tests/builtins/Makefile +++ b/bin/sh/tests/builtins/Makefile @@ -1,192 +1,193 @@ # $FreeBSD$ PACKAGE= tests .include TESTSDIR= ${TESTSBASE}/bin/sh/${.CURDIR:T} .PATH: ${.CURDIR:H} ATF_TESTS_SH= functional_test ${PACKAGE}FILES+= alias.0 alias.0.stdout ${PACKAGE}FILES+= alias.1 alias.1.stderr ${PACKAGE}FILES+= alias3.0 alias3.0.stdout ${PACKAGE}FILES+= alias4.0 ${PACKAGE}FILES+= break1.0 ${PACKAGE}FILES+= break2.0 break2.0.stdout ${PACKAGE}FILES+= break3.0 ${PACKAGE}FILES+= break4.4 ${PACKAGE}FILES+= break5.4 ${PACKAGE}FILES+= break6.0 ${PACKAGE}FILES+= builtin1.0 ${PACKAGE}FILES+= case1.0 ${PACKAGE}FILES+= case2.0 ${PACKAGE}FILES+= case3.0 ${PACKAGE}FILES+= case4.0 ${PACKAGE}FILES+= case5.0 ${PACKAGE}FILES+= case6.0 ${PACKAGE}FILES+= case7.0 ${PACKAGE}FILES+= case8.0 ${PACKAGE}FILES+= case9.0 ${PACKAGE}FILES+= case10.0 ${PACKAGE}FILES+= case11.0 ${PACKAGE}FILES+= case12.0 ${PACKAGE}FILES+= case13.0 ${PACKAGE}FILES+= case14.0 ${PACKAGE}FILES+= case15.0 ${PACKAGE}FILES+= case16.0 ${PACKAGE}FILES+= case17.0 ${PACKAGE}FILES+= case18.0 ${PACKAGE}FILES+= case19.0 ${PACKAGE}FILES+= case20.0 ${PACKAGE}FILES+= case21.0 ${PACKAGE}FILES+= case22.0 ${PACKAGE}FILES+= case23.0 ${PACKAGE}FILES+= cd1.0 ${PACKAGE}FILES+= cd2.0 ${PACKAGE}FILES+= cd3.0 ${PACKAGE}FILES+= cd4.0 ${PACKAGE}FILES+= cd5.0 ${PACKAGE}FILES+= cd6.0 ${PACKAGE}FILES+= cd7.0 ${PACKAGE}FILES+= cd8.0 ${PACKAGE}FILES+= cd9.0 cd9.0.stdout ${PACKAGE}FILES+= cd10.0 ${PACKAGE}FILES+= cd11.0 ${PACKAGE}FILES+= command1.0 ${PACKAGE}FILES+= command2.0 ${PACKAGE}FILES+= command3.0 ${PACKAGE}FILES+= command3.0.stdout ${PACKAGE}FILES+= command4.0 ${PACKAGE}FILES+= command5.0 ${PACKAGE}FILES+= command5.0.stdout ${PACKAGE}FILES+= command6.0 ${PACKAGE}FILES+= command6.0.stdout ${PACKAGE}FILES+= command7.0 ${PACKAGE}FILES+= command8.0 ${PACKAGE}FILES+= command9.0 ${PACKAGE}FILES+= command10.0 ${PACKAGE}FILES+= command11.0 ${PACKAGE}FILES+= command12.0 ${PACKAGE}FILES+= command13.0 ${PACKAGE}FILES+= command14.0 ${PACKAGE}FILES+= dot1.0 ${PACKAGE}FILES+= dot2.0 ${PACKAGE}FILES+= dot3.0 ${PACKAGE}FILES+= dot4.0 ${PACKAGE}FILES+= echo1.0 ${PACKAGE}FILES+= echo2.0 ${PACKAGE}FILES+= echo3.0 ${PACKAGE}FILES+= eval1.0 ${PACKAGE}FILES+= eval2.0 ${PACKAGE}FILES+= eval3.0 ${PACKAGE}FILES+= eval4.0 ${PACKAGE}FILES+= eval5.0 ${PACKAGE}FILES+= eval6.0 ${PACKAGE}FILES+= eval7.0 ${PACKAGE}FILES+= eval8.7 ${PACKAGE}FILES+= exec1.0 ${PACKAGE}FILES+= exec2.0 ${PACKAGE}FILES+= exit1.0 ${PACKAGE}FILES+= exit2.8 ${PACKAGE}FILES+= exit3.0 ${PACKAGE}FILES+= export1.0 ${PACKAGE}FILES+= fc1.0 ${PACKAGE}FILES+= fc2.0 +${PACKAGE}FILES+= fc3.0 fc3.0.stdout fc3.0.stderr ${PACKAGE}FILES+= for1.0 ${PACKAGE}FILES+= for2.0 ${PACKAGE}FILES+= for3.0 ${PACKAGE}FILES+= getopts1.0 getopts1.0.stdout ${PACKAGE}FILES+= getopts2.0 getopts2.0.stdout ${PACKAGE}FILES+= getopts3.0 ${PACKAGE}FILES+= getopts4.0 ${PACKAGE}FILES+= getopts5.0 ${PACKAGE}FILES+= getopts6.0 ${PACKAGE}FILES+= getopts7.0 ${PACKAGE}FILES+= getopts8.0 getopts8.0.stdout ${PACKAGE}FILES+= getopts9.0 getopts9.0.stdout ${PACKAGE}FILES+= getopts10.0 ${PACKAGE}FILES+= hash1.0 hash1.0.stdout ${PACKAGE}FILES+= hash2.0 hash2.0.stdout ${PACKAGE}FILES+= hash3.0 hash3.0.stdout ${PACKAGE}FILES+= hash4.0 ${PACKAGE}FILES+= jobid1.0 ${PACKAGE}FILES+= jobid2.0 ${PACKAGE}FILES+= kill1.0 kill2.0 ${PACKAGE}FILES+= lineno.0 lineno.0.stdout ${PACKAGE}FILES+= lineno2.0 ${PACKAGE}FILES+= lineno3.0 lineno3.0.stdout ${PACKAGE}FILES+= local1.0 ${PACKAGE}FILES+= local2.0 ${PACKAGE}FILES+= local3.0 ${PACKAGE}FILES+= local4.0 ${PACKAGE}FILES+= local5.0 ${PACKAGE}FILES+= local6.0 ${PACKAGE}FILES+= local7.0 .if ${MK_NLS} != "no" ${PACKAGE}FILES+= locale1.0 .endif ${PACKAGE}FILES+= locale2.0 ${PACKAGE}FILES+= printf1.0 ${PACKAGE}FILES+= printf2.0 ${PACKAGE}FILES+= printf3.0 ${PACKAGE}FILES+= printf4.0 ${PACKAGE}FILES+= read1.0 read1.0.stdout ${PACKAGE}FILES+= read2.0 ${PACKAGE}FILES+= read3.0 read3.0.stdout ${PACKAGE}FILES+= read4.0 read4.0.stdout ${PACKAGE}FILES+= read5.0 ${PACKAGE}FILES+= read6.0 ${PACKAGE}FILES+= read7.0 ${PACKAGE}FILES+= read8.0 ${PACKAGE}FILES+= read9.0 ${PACKAGE}FILES+= read10.0 ${PACKAGE}FILES+= read11.0 ${PACKAGE}FILES+= return1.0 ${PACKAGE}FILES+= return2.1 ${PACKAGE}FILES+= return3.1 ${PACKAGE}FILES+= return4.0 ${PACKAGE}FILES+= return5.0 ${PACKAGE}FILES+= return6.4 ${PACKAGE}FILES+= return7.4 ${PACKAGE}FILES+= return8.0 ${PACKAGE}FILES+= set1.0 ${PACKAGE}FILES+= set2.0 ${PACKAGE}FILES+= set3.0 ${PACKAGE}FILES+= trap1.0 ${PACKAGE}FILES+= trap10.0 ${PACKAGE}FILES+= trap11.0 ${PACKAGE}FILES+= trap12.0 ${PACKAGE}FILES+= trap13.0 ${PACKAGE}FILES+= trap14.0 ${PACKAGE}FILES+= trap15.0 ${PACKAGE}FILES+= trap16.0 ${PACKAGE}FILES+= trap17.0 ${PACKAGE}FILES+= trap2.0 ${PACKAGE}FILES+= trap3.0 ${PACKAGE}FILES+= trap4.0 ${PACKAGE}FILES+= trap5.0 ${PACKAGE}FILES+= trap6.0 ${PACKAGE}FILES+= trap7.0 ${PACKAGE}FILES+= trap8.0 ${PACKAGE}FILES+= trap9.0 ${PACKAGE}FILES+= type1.0 type1.0.stderr ${PACKAGE}FILES+= type2.0 ${PACKAGE}FILES+= type3.0 ${PACKAGE}FILES+= type4.0 ${PACKAGE}FILES+= unalias.0 ${PACKAGE}FILES+= var-assign.0 ${PACKAGE}FILES+= var-assign2.0 ${PACKAGE}FILES+= wait1.0 ${PACKAGE}FILES+= wait2.0 ${PACKAGE}FILES+= wait3.0 ${PACKAGE}FILES+= wait4.0 ${PACKAGE}FILES+= wait5.0 ${PACKAGE}FILES+= wait6.0 ${PACKAGE}FILES+= wait7.0 ${PACKAGE}FILES+= wait8.0 ${PACKAGE}FILES+= wait9.127 ${PACKAGE}FILES+= wait10.0 .include diff --git a/bin/sh/tests/builtins/fc3.0 b/bin/sh/tests/builtins/fc3.0 new file mode 100644 index 000000000000..daa615bcc3ca --- /dev/null +++ b/bin/sh/tests/builtins/fc3.0 @@ -0,0 +1,9 @@ +export PS1='_ ' # cannot predict whether ran by root or not + +echo ': command1 +: command2 +: command3 +: command4 +fc -l -n -1 +fc -ln 2 3 +' | ENV= HISTFILE=/dev/null ${SH} +m -i diff --git a/bin/sh/tests/builtins/fc3.0.stderr b/bin/sh/tests/builtins/fc3.0.stderr new file mode 100644 index 000000000000..e05147fb8209 --- /dev/null +++ b/bin/sh/tests/builtins/fc3.0.stderr @@ -0,0 +1 @@ +_ _ _ _ _ _ _ _ diff --git a/bin/sh/tests/builtins/fc3.0.stdout b/bin/sh/tests/builtins/fc3.0.stdout new file mode 100644 index 000000000000..8c23c913635d --- /dev/null +++ b/bin/sh/tests/builtins/fc3.0.stdout @@ -0,0 +1,3 @@ +: command4 +: command2 +: command3