1 /* $OpenBSD: main.c,v 1.46 2010/05/19 17:36:08 jasper Exp $ */
2 /* $OpenBSD: tty.c,v 1.9 2006/03/14 22:08:01 deraadt Exp $ */
3 /* $OpenBSD: io.c,v 1.22 2006/03/17 16:30:13 millert Exp $ */
4 /* $OpenBSD: table.c,v 1.13 2009/01/17 22:06:44 millert Exp $ */
7 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
8 * Thorsten Glaser <tg@mirbsd.org>
10 * Provided that these terms and disclaimer and all copyright notices
11 * are retained or reproduced in an accompanying document, permission
12 * is granted to deal in this work without restriction, including un-
13 * limited rights to use, publicly perform, distribute, sell, modify,
14 * merge, give away, or sublicence.
16 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
17 * the utmost extent permitted by applicable law, neither express nor
18 * implied; without malicious intent or gross negligence. In no event
19 * may a licensor, author or contributor be held liable for indirect,
20 * direct, other damage, loss, or other issues arising in any way out
21 * of dealing in the work, even if advised of the possibility of such
22 * damage or existence of a defect, except proven that it results out
23 * of said person's immediate fault when using the work as intended.
29 #if HAVE_LANGINFO_CODESET
32 #if HAVE_SETLOCALE_CTYPE
36 __RCSID("$MirOS: src/bin/mksh/main.c,v 1.167 2010/07/04 17:45:15 tg Exp $");
38 extern char **environ;
42 extern gid_t kshgid, kshegid;
46 #define MKSHRC_PATH "~/.mkshrc"
49 #ifndef MKSH_DEFAULT_TMPDIR
50 #define MKSH_DEFAULT_TMPDIR "/tmp"
53 static void reclaim(void);
54 static void remove_temps(struct temp *);
55 void chvt_reinit(void);
56 Source *mksh_init(int, const char *[]);
58 static void x_sigwinch(int);
61 static const char initifs[] = "IFS= \t\n";
63 static const char initsubs[] =
64 "${PS2=> } ${PS3=#? } ${PS4=+ } ${SECONDS=0} ${TMOUT=0}";
66 static const char *initcoms[] = {
67 T_typeset, "-r", initvsn, NULL,
68 T_typeset, "-x", "HOME", "PATH", "RANDOM", "SHELL", NULL,
69 T_typeset, "-i10", "COLUMNS", "LINES", "OPTIND", "PGRP", "PPID",
70 "RANDOM", "SECONDS", "TMOUT", "USER_ID", NULL,
74 "hash=alias -t", /* not "alias -t --": hash -r needs to work */
76 #ifndef MKSH_UNEMPLOYED
77 "suspend=kill -STOP $$",
79 "autoload=typeset -fu",
80 "functions=typeset -f",
85 "source=PATH=$PATH:. command .",
88 /* this is what AT&T ksh seems to track, with the addition of emacs */
90 "cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
91 "make", "mv", "pr", "rm", "sed", "sh", "vi", "who", NULL,
95 static int initio_done;
97 struct env *e = &kshstate_v.env_;
102 kshpid = procpid = getpid();
109 mksh_init(int argc, const char *argv[])
114 unsigned char restricted, errexit, utf_flag;
118 #if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
123 /* do things like getpgrp() et al. */
126 /* make sure argv[] is sane */
128 static const char *empty_argv[] = {
137 ainit(&aperm); /* initialise permanent Area */
139 /* set up base environment */
140 kshstate_v.env_.type = E_NONE;
141 ainit(&kshstate_v.env_.area);
142 newblock(); /* set up global l->vars and l->funs */
144 /* Do this first so output routines (eg, errorf, shellf) can work */
147 argi = parse_args(argv, OF_FIRSTTIME, NULL);
159 /* set up variable and command dictionaries */
160 ktinit(&taliases, APERM, 0);
161 ktinit(&aliases, APERM, 0);
163 ktinit(&homedirs, APERM, 0);
166 /* define shell keywords */
169 /* define built-in commands */
170 ktinit(&builtins, APERM,
171 /* must be 80% of 2^n (currently 44 builtins) */ 64);
172 for (i = 0; mkshbuiltins[i].name != NULL; i++)
173 builtin(mkshbuiltins[i].name, mkshbuiltins[i].func);
178 def_path = _PATH_DEFPATH;
181 if ((k = confstr(_CS_PATH, NULL, 0)) != (size_t)-1 && k > 0 &&
182 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
187 * this is uniform across all OSes unless it
188 * breaks somewhere; don't try to optimise,
189 * e.g. add stuff for Interix or remove /usr
190 * for HURD, because e.g. Debian GNU/HURD is
191 * "keeping a regular /usr"; this is supposed
192 * to be a sane 'basic' default PATH
194 def_path = "/bin:/usr/bin:/sbin:/usr/sbin";
197 /* Set PATH to def_path (will set the path global variable).
198 * (import of environment below will probably change this setting).
201 /* setstr can't fail here */
202 setstr(vp, def_path, KSH_RETURN_ERROR);
204 /* Turn on nohup by default for now - will change to off
205 * by default once people are aware of its existence
206 * (AT&T ksh does not have a nohup option - it always sends
211 /* Turn on brace expansion by default. AT&T kshs that have
212 * alternation always have it on.
214 Flag(FBRACEEXPAND) = 1;
216 /* Set edit mode to emacs by default, may be overridden
217 * by the environment or the user. Also, we want tab completion
218 * on in vi by default. */
219 change_flag(FEMACS, OF_SPECIAL, 1);
221 Flag(FVITABCOMPLETE) = 1;
224 #ifdef MKSH_BINSHREDUCED
225 /* set FSH if we're called as -sh or /bin/sh or so */
231 while (cc[i] != '\0')
232 /* the following line matches '-' and '/' ;-) */
233 if ((cc[i++] | 2) == '/')
235 if (((cc[argi] | 0x20) == 's') && ((cc[argi + 1] | 0x20) == 'h'))
236 change_flag(FSH, OF_FIRSTTIME, 1);
240 /* import environment */
242 for (wp = (const char **)environ; *wp != NULL; wp++)
243 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
245 typeset(initifs, 0, 0, 0, 0); /* for security */
247 /* assign default shell variable values */
248 substitute(initsubs, 0);
250 /* Figure out the current working directory and set $PWD */
252 struct stat s_pwd, s_dot;
253 struct tbl *pwd_v = global("PWD");
254 char *pwd = str_val(pwd_v);
257 /* Try to use existing $PWD if it is valid */
259 stat(pwd, &s_pwd) < 0 || stat(".", &s_dot) < 0 ||
260 s_pwd.st_dev != s_dot.st_dev ||
261 s_pwd.st_ino != s_dot.st_ino)
263 set_current_wd(pwdx);
265 simplify_path(current_wd);
266 /* Only set pwd if we know where we are or if it had a
269 if (current_wd[0] || pwd != null)
270 /* setstr can't fail here */
271 setstr(pwd_v, current_wd, KSH_RETURN_ERROR);
274 for (wp = initcoms; *wp != NULL; wp++) {
279 setint(global("COLUMNS"), 0);
280 setint(global("LINES"), 0);
281 setint(global("OPTIND"), 1);
283 safe_prompt = ksheuid ? "$ " : "# ";
285 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
286 if (!(vp->flag & ISSET) ||
287 (!ksheuid && !strchr(str_val(vp), '#')))
288 /* setstr can't fail here */
289 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
290 setint((vp = global("PGRP")), (mksh_uari_t)kshpgrp);
292 setint((vp = global("PPID")), (mksh_uari_t)kshppid);
294 setint((vp = global("RANDOM")), (mksh_uari_t)evilhash(kshname));
296 setint((vp = global("USER_ID")), (mksh_uari_t)ksheuid);
299 /* Set this before parsing arguments */
301 Flag(FPRIVILEGED) = getuid() != ksheuid || getgid() != getegid();
303 Flag(FPRIVILEGED) = (kshuid = getuid()) != ksheuid ||
304 (kshgid = getgid()) != (kshegid = getegid());
307 /* this to note if monitor is set on command line (see below) */
308 #ifndef MKSH_UNEMPLOYED
309 Flag(FMONITOR) = 127;
311 /* this to note if utf-8 mode is set on command line (see below) */
314 argi = parse_args(argv, OF_CMDLINE, NULL);
318 /* process this later only, default to off (hysterical raisins) */
322 if (Flag(FCOMMAND)) {
323 s = pushs(SSTRING, ATEMP);
324 if (!(s->start = s->str = argv[argi++]))
325 errorf("-c requires an argument");
326 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
327 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
328 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
332 kshname = argv[argi++];
333 } else if (argi < argc && !Flag(FSTDIN)) {
334 s = pushs(SFILE, ATEMP);
335 s->file = argv[argi++];
336 s->u.shf = shf_open(s->file, O_RDONLY, 0,
337 SHF_MAPHI | SHF_CLEXEC);
338 if (s->u.shf == NULL) {
340 warningf(true, "%s: %s", s->file, strerror(errno));
341 /* mandated by SUSv4 */
348 s = pushs(SSTDIN, ATEMP);
350 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
352 if (isatty(0) && isatty(2)) {
353 Flag(FTALKING) = Flag(FTALKING_I) = 1;
354 /* The following only if isatty(0) */
356 s->u.shf->flags |= SHF_INTERRUPT;
361 /* this bizarreness is mandated by POSIX */
362 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
366 /* initialise job control */
368 /* set: 0/1; unset: 2->0 */
369 UTFMODE = utf_flag & 1;
370 /* Do this after j_init(), as tty_fd is not initialised until then */
371 if (Flag(FTALKING)) {
373 #ifndef MKSH_ASSUME_UTF8
374 #define isuc(x) (((x) != NULL) && \
375 (stristr((x), "UTF-8") || stristr((x), "utf8")))
376 /* Check if we're in a UTF-8 locale */
379 #if HAVE_SETLOCALE_CTYPE
380 ccp = setlocale(LC_CTYPE, "");
381 #if HAVE_LANGINFO_CODESET
383 ccp = nl_langinfo(CODESET);
386 /* these were imported from environ earlier */
387 ccp = str_val(global("LC_ALL"));
389 ccp = str_val(global("LC_CTYPE"));
391 ccp = str_val(global("LANG"));
395 #elif MKSH_ASSUME_UTF8
405 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
406 setsig(&sigtraps[SIGWINCH], x_sigwinch,
407 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
411 l->argv = &argv[argi - 1];
412 l->argc = argc - argi;
413 l->argv[0] = kshname;
416 /* Disable during .profile/ENV reading */
417 restricted = Flag(FRESTRICTED);
418 Flag(FRESTRICTED) = 0;
419 errexit = Flag(FERREXIT);
422 /* Do this before profile/$ENV so that if it causes problems in them,
423 * user will know why things broke.
425 if (!current_wd[0] && Flag(FTALKING))
426 warningf(false, "Cannot determine current working directory");
429 include(KSH_SYSTEM_PROFILE, 0, NULL, 1);
430 if (!Flag(FPRIVILEGED))
431 include(substitute("$HOME/.profile", 0), 0,
434 if (Flag(FPRIVILEGED))
435 include("/etc/suid_profile", 0, NULL, 1);
436 else if (Flag(FTALKING)) {
440 env_file = substitute(substitute("${ENV:-" MKSHRC_PATH "}", 0),
442 if (*env_file != '\0')
443 include(env_file, 0, NULL, 1);
447 static const char *restr_com[] = {
448 T_typeset, "-r", "PATH",
452 shcomexec(restr_com);
453 /* After typeset command... */
454 Flag(FRESTRICTED) = 1;
456 Flag(FERREXIT) = errexit;
458 if (Flag(FTALKING)) {
462 Flag(FTRACKALL) = 1; /* set after ENV */
468 main(int argc, const char *argv[])
472 kshstate_v.lcg_state_ = 5381;
474 if ((s = mksh_init(argc, argv))) {
475 /* put more entropy into the LCG */
476 change_random(s, sizeof(*s));
477 /* doesn’t return */
484 include(const char *name, int argc, const char **argv, int intr_ok)
486 Source *volatile s = NULL;
488 const char **volatile old_argv;
489 volatile int old_argc;
492 shf = shf_open(name, O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
497 old_argv = e->loc->argv;
498 old_argc = e->loc->argc;
504 i = sigsetjmp(e->jbuf, 0);
506 quitenv(s ? s->u.shf : NULL);
508 e->loc->argv = old_argv;
509 e->loc->argc = old_argc;
514 return (exstat & 0xff); /* see below */
516 /* intr_ok is set if we are including .profile or $ENV.
517 * If user ^Cs out, we don't want to kill the shell...
519 if (intr_ok && (exstat - 128) != SIGTERM)
528 internal_errorf("include: %d", i);
536 s = pushs(SFILE, ATEMP);
538 strdupx(s->file, name, ATEMP);
542 e->loc->argv = old_argv;
543 e->loc->argc = old_argc;
545 return (i & 0xff); /* & 0xff to ensure value not -1 */
548 /* spawn a command into a shell optionally keeping track of the line number */
550 command(const char *comm, int line)
554 s = pushs(SSTRING, ATEMP);
555 s->start = s->str = comm;
557 return (shell(s, false));
561 * run the commands from the input source, returning status.
564 shell(Source * volatile s, volatile int toplevel)
567 volatile int wastty = s->flags & SF_TTY;
568 volatile int attempts = 13;
569 volatile int interactive = Flag(FTALKING) && toplevel;
570 Source *volatile old_source = source;
573 s->flags |= SF_FIRST; /* enable UTF-8 BOM check */
578 i = sigsetjmp(e->jbuf, 0);
581 case LINTR: /* we get here if SIGINT not caught or ignored */
587 /* Reset any eof that was read as part of a
590 if (Flag(FIGNOREEOF) && s->type == SEOF &&
593 /* Used by exit command to get back to
594 * top level shell. Kind of strange since
595 * interactive is set if we are reading from
596 * a tty, but to have stopped jobs, one only
597 * needs FMONITOR set (not FTALKING/SF_TTY)...
599 /* toss any input we have so far */
600 s->start = s->str = null;
609 unwind(i); /* keep on going */
614 internal_errorf("shell: %d", i);
622 if (s->next == NULL) {
626 s->flags &= ~SF_ECHO;
633 if (t != NULL && t->type == TEOF) {
634 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
635 shellf("Use 'exit' to leave ksh\n");
637 } else if (wastty && !really_exit &&
638 j_stopped_running()) {
642 /* this for POSIX which says EXIT traps
643 * shall be taken in the environment
644 * immediately after the last command
652 if (t && (!Flag(FNOEXEC) || (s->flags & SF_TTY)))
653 exstat = execute(t, 0, NULL);
655 if (t != NULL && t->type != TEOF && interactive && really_exit)
665 /* return to closest error handler or shell(), exit if none found */
669 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
670 if (i == LEXIT || (Flag(FERREXIT) && (i == LERROR || i == LINTR) &&
671 sigtraps[SIGEXIT_].trap)) {
672 runtrap(&sigtraps[SIGEXIT_]);
674 } else if (Flag(FERREXIT) && (i == LERROR || i == LINTR)) {
675 runtrap(&sigtraps[SIGERR_]);
685 siglongjmp(e->jbuf, i);
689 e->flags |= EF_FAKE_SIGDIE;
704 * struct env includes ALLOC_ITEM for alignment constraints
705 * so first get the actually used memory, then assign it
707 cp = alloc(sizeof(struct env) - ALLOC_SIZE, ATEMP);
708 ep = (void *)(cp - ALLOC_SIZE); /* undo what alloc() did */
709 /* initialise public members of struct env (not the ALLOC_ITEM) */
717 /* jump buffer is invalid because flags == 0 */
722 quitenv(struct shf *shf)
728 if (ep->oenv && ep->oenv->loc != ep->loc)
730 if (ep->savefd != NULL) {
731 for (fd = 0; fd < NUFILE; fd++)
732 /* if ep->savefd[fd] < 0, means fd was closed */
734 restfd(fd, ep->savefd[fd]);
735 if (ep->savefd[2]) /* Clear any write errors */
736 shf_reopen(2, SHF_WR, shl_out);
738 /* Bottom of the stack.
739 * Either main shell is exiting or cleanup_parents_env() was called.
741 if (ep->oenv == NULL) {
742 if (ep->type == E_NONE) { /* Main shell exiting? */
743 #if HAVE_PERSISTENT_HISTORY
748 if (ep->flags & EF_FAKE_SIGDIE) {
749 int sig = exstat - 128;
751 /* ham up our death a bit (AT&T ksh
752 * only seems to do this for SIGTERM)
753 * Don't do it for SIGQUIT, since we'd
756 if ((sig == SIGINT || sig == SIGTERM) &&
757 (kshpgrp == kshpid)) {
758 setsig(&sigtraps[sig], SIG_DFL,
759 SS_RESTORE_CURR | SS_FORCE);
775 /* free the struct env - tricky due to the ALLOC_ITEM inside */
777 afree(cp + ALLOC_SIZE, ATEMP);
780 /* Called after a fork to cleanup stuff left over from parents environment */
782 cleanup_parents_env(void)
790 * Don't clean up temporary files - parent will probably need them.
791 * Also, can't easily reclaim memory since variables, etc. could be
795 /* close all file descriptors hiding in savefd */
796 for (ep = e; ep; ep = ep->oenv) {
798 for (fd = 0; fd < NUFILE; fd++)
799 if (ep->savefd[fd] > 0)
800 close(ep->savefd[fd]);
801 afree(ep->savefd, &ep->area);
808 /* Called just before an execve cleanup stuff temporary files */
810 cleanup_proc_env(void)
814 for (ep = e; ep; ep = ep->oenv)
815 remove_temps(ep->temps);
818 /* remove temp files and free ATEMP Area */
822 remove_temps(e->temps);
828 remove_temps(struct temp *tp)
830 for (; tp != NULL; tp = tp->next)
831 if (tp->pid == procpid)
835 /* Initialise tty_fd. Used for saving/reseting tty modes upon
836 * foreground job completion and for setting up tty process group.
839 tty_init(bool init_ttystate, bool need_tty)
841 bool do_close = true;
851 /* XXX imake style */
856 if ((tfd = open("/dev/tty", O_RDWR, 0)) < 0) {
860 "No controlling tty (open /dev/tty: %s)",
872 "Can't find tty file descriptor");
876 if ((tty_fd = fcntl(tfd, F_DUPFD, FDBASE)) < 0) {
878 warningf(false, "j_ttyinit: dup of tty fd failed: %s",
880 } else if (fcntl(tty_fd, F_SETFD, FD_CLOEXEC) < 0) {
883 "j_ttyinit: can't set close-on-exec flag: %s",
887 } else if (init_ttystate)
888 tcgetattr(tty_fd, &tty_state);
902 /* A shell error occurred (eg, syntax error, etc.) */
904 errorf(const char *fmt, ...)
908 shl_stdout_ok = 0; /* debugging: note that stdout not valid */
913 shf_vfprintf(shl_out, fmt, va);
915 shf_putchar('\n', shl_out);
921 /* like errorf(), but no unwind is done */
923 warningf(bool fileline, const char *fmt, ...)
927 error_prefix(fileline);
929 shf_vfprintf(shl_out, fmt, va);
931 shf_putchar('\n', shl_out);
935 /* Used by built-in utilities to prefix shell and utility name to message
936 * (also unwinds environments for special builtins).
939 bi_errorf(const char *fmt, ...)
943 shl_stdout_ok = 0; /* debugging: note that stdout not valid */
947 /* not set when main() calls parse_args() */
949 shf_fprintf(shl_out, "%s: ", builtin_argv0);
951 shf_vfprintf(shl_out, fmt, va);
953 shf_putchar('\n', shl_out);
956 /* POSIX special builtins and ksh special builtins cause
957 * non-interactive shells to exit.
958 * XXX odd use of KEEPASN; also may not want LERROR here
960 if (builtin_flag & SPEC_BI) {
961 builtin_argv0 = NULL;
966 /* Called when something that shouldn't happen does */
968 internal_verrorf(const char *fmt, va_list ap)
970 shf_fprintf(shl_out, "internal error: ");
971 shf_vfprintf(shl_out, fmt, ap);
972 shf_putchar('\n', shl_out);
977 internal_errorf(const char *fmt, ...)
982 internal_verrorf(fmt, va);
988 internal_warningf(const char *fmt, ...)
993 internal_verrorf(fmt, va);
997 /* used by error reporting functions to print "ksh: .kshrc[25]: " */
999 error_prefix(bool fileline)
1001 /* Avoid foo: foo[2]: ... */
1002 if (!fileline || !source || !source->file ||
1003 strcmp(source->file, kshname) != 0)
1004 shf_fprintf(shl_out, "%s: ", kshname + (*kshname == '-'));
1005 if (fileline && source && source->file != NULL) {
1006 shf_fprintf(shl_out, "%s[%d]: ", source->file,
1007 source->errline > 0 ? source->errline : source->line);
1008 source->errline = 0;
1012 /* printf to shl_out (stderr) with flush */
1014 shellf(const char *fmt, ...)
1018 if (!initio_done) /* shl_out may not be set up yet... */
1021 shf_vfprintf(shl_out, fmt, va);
1026 /* printf to shl_stdout (stdout) */
1028 shprintf(const char *fmt, ...)
1033 internal_errorf("shl_stdout not valid");
1035 shf_vfprintf(shl_stdout, fmt, va);
1039 /* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1045 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1049 struct shf shf_iob[3];
1054 shf_fdopen(1, SHF_WR, shl_stdout); /* force buffer allocation */
1055 shf_fdopen(2, SHF_WR, shl_out);
1056 shf_fdopen(2, SHF_WR, shl_spare); /* force buffer allocation */
1060 /* A dup2() with error checking */
1062 ksh_dup2(int ofd, int nfd, bool errok)
1066 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
1067 errorf("too many files open in shell");
1070 /* XXX imake style */
1072 fcntl(nfd, F_SETFD, 0);
1079 * move fd from user space (0<=fd<10) to shell space (fd>=10),
1080 * set close-on-exec flag.
1087 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
1090 if (nfd < 0 || nfd > SHRT_MAX)
1091 errorf("too many files open in shell");
1092 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1093 return ((short)nfd);
1097 restfd(int fd, int ofd)
1100 shf_flush(&shf_iob[fd]);
1101 if (ofd < 0) /* original fd closed */
1103 else if (fd != ofd) {
1104 ksh_dup2(ofd, fd, true); /* XXX: what to do if this fails? */
1115 errorf("can't create pipe - try again");
1116 pv[0] = savefd(lpv[0]);
1117 if (pv[0] != lpv[0])
1119 pv[1] = savefd(lpv[1]);
1120 if (pv[1] != lpv[1])
1131 /* Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
1132 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1135 check_fd(const char *name, int mode, const char **emsgp)
1139 if (name[0] == 'p' && !name[1])
1140 return (coproc_getfd(mode, emsgp));
1141 for (fd = 0; ksh_isdigit(*name); ++name)
1142 fd = (fd * 10) + *name - '0';
1143 if (*name || fd >= FDBASE) {
1145 *emsgp = "illegal file descriptor name";
1148 if ((fl = fcntl(fd, F_GETFL, 0)) < 0) {
1150 *emsgp = "bad file descriptor";
1154 /* X_OK is a kludge to disable this check for dups (x<&1):
1155 * historical shells never did this check (XXX don't know what
1156 * POSIX has to say).
1158 if (!(mode & X_OK) && fl != O_RDWR && (
1159 ((mode & R_OK) && fl != O_RDONLY) ||
1160 ((mode & W_OK) && fl != O_WRONLY))) {
1162 *emsgp = (fl == O_WRONLY) ?
1163 "fd not open for reading" :
1164 "fd not open for writing";
1170 /* Called once from main */
1174 coproc.read = coproc.readw = coproc.write = -1;
1179 /* Called by c_read() when eof is read - close fd if it is the co-process fd */
1181 coproc_read_close(int fd)
1183 if (coproc.read >= 0 && fd == coproc.read) {
1184 coproc_readw_close(fd);
1190 /* Called by c_read() and by iosetup() to close the other side of the
1191 * read pipe, so reads will actually terminate.
1194 coproc_readw_close(int fd)
1196 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1197 close(coproc.readw);
1202 /* Called by c_print when a write to a fd fails with EPIPE and by iosetup
1203 * when co-process input is dup'd
1206 coproc_write_close(int fd)
1208 if (coproc.write >= 0 && fd == coproc.write) {
1209 close(coproc.write);
1214 /* Called to check for existence of/value of the co-process file descriptor.
1215 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1218 coproc_getfd(int mode, const char **emsgp)
1220 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1225 *emsgp = "no coprocess";
1229 /* called to close file descriptors related to the coprocess (if any)
1230 * Should be called with SIGCHLD blocked.
1233 coproc_cleanup(int reuse)
1235 /* This to allow co-processes to share output pipe */
1236 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1237 if (coproc.read >= 0) {
1241 if (coproc.readw >= 0) {
1242 close(coproc.readw);
1246 if (coproc.write >= 0) {
1247 close(coproc.write);
1253 maketemp(Area *ap, Temp_type type, struct temp **tlist)
1261 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
1263 len = strlen(dir) + 6 + 10 + 1;
1265 pathname = tempnam(dir, "mksh.");
1266 len = ((pathname == NULL) ? 0 : strlen(pathname)) + 1;
1268 tp = alloc(sizeof(struct temp) + len, ap);
1269 tp->name = (char *)&tp[1];
1271 if (pathname == NULL)
1274 memcpy(tp->name, pathname, len);
1278 pathname = tp->name;
1282 shf_snprintf(pathname, len, "%s/mksh.XXXXXXXXXX", dir);
1283 if ((fd = mkstemp(pathname)) >= 0)
1285 if (tp->name[0] && (fd = open(tp->name, O_CREAT | O_RDWR, 0600)) >= 0)
1287 tp->shf = shf_fdopen(fd, SHF_WR, NULL);
1296 * We use a similar collision resolution algorithm as Python 2.5.4
1297 * but with a slightly tweaked implementation written from scratch.
1300 #define INIT_TBLS 8 /* initial table size (power of 2) */
1301 #define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1303 static void texpand(struct table *, size_t);
1304 static int tnamecmp(const void *, const void *);
1305 static struct tbl *ktscan(struct table *, const char *, uint32_t,
1309 texpand(struct table *tp, size_t nsize)
1311 size_t i, j, osize = tp->size, perturb;
1312 struct tbl *tblp, **pp;
1313 struct tbl **ntblp, **otblp = tp->tbls;
1315 ntblp = alloc(nsize * sizeof(struct tbl *), tp->areap);
1316 for (i = 0; i < nsize; i++)
1319 tp->nfree = (nsize * 4) / 5; /* table can get 80% full */
1323 nsize--; /* from here on nsize := mask */
1324 for (i = 0; i < osize; i++)
1325 if ((tblp = otblp[i]) != NULL) {
1326 if ((tblp->flag & DEFINED)) {
1327 /* search for free hash table slot */
1328 j = (perturb = tblp->ua.hval) & nsize;
1329 goto find_first_empty_slot;
1330 find_next_empty_slot:
1331 j = (j << 2) + j + perturb + 1;
1332 perturb >>= PERTURB_SHIFT;
1333 find_first_empty_slot:
1334 pp = &ntblp[j & nsize];
1336 goto find_next_empty_slot;
1337 /* found an empty hash table slot */
1340 } else if (!(tblp->flag & FINUSE)) {
1341 afree(tblp, tp->areap);
1344 afree(otblp, tp->areap);
1348 ktinit(struct table *tp, Area *ap, size_t tsize)
1352 tp->size = tp->nfree = 0;
1357 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
1359 ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1361 size_t j, perturb, mask;
1362 struct tbl **pp, *p;
1364 mask = tp->size - 1;
1365 /* search for hash table slot matching name */
1366 j = (perturb = h) & mask;
1367 goto find_first_slot;
1369 j = (j << 2) + j + perturb + 1;
1370 perturb >>= PERTURB_SHIFT;
1372 pp = &tp->tbls[j & mask];
1373 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1374 strcmp(p->name, name)))
1375 goto find_next_slot;
1376 /* p == NULL if not found, correct found entry otherwise */
1382 /* table, name (key) to search for, hash(n) */
1384 ktsearch(struct table *tp, const char *n, uint32_t h)
1386 return (tp->size ? ktscan(tp, n, h, NULL) : NULL);
1389 /* table, name (key) to enter, hash(n) */
1391 ktenter(struct table *tp, const char *n, uint32_t h)
1393 struct tbl **pp, *p;
1397 texpand(tp, INIT_TBLS);
1399 if ((p = ktscan(tp, n, h, &pp)))
1402 if (tp->nfree <= 0) {
1404 texpand(tp, 2 * tp->size);
1408 /* create new tbl entry */
1409 len = strlen(n) + 1;
1410 p = alloc(offsetof(struct tbl, name[0]) + len, tp->areap);
1413 p->areap = tp->areap;
1417 memcpy(p->name, n, len);
1419 /* enter in tp->tbls */
1426 ktwalk(struct tstate *ts, struct table *tp)
1428 ts->left = tp->size;
1429 ts->next = tp->tbls;
1433 ktnext(struct tstate *ts)
1435 while (--ts->left >= 0) {
1436 struct tbl *p = *ts->next++;
1437 if (p != NULL && (p->flag & DEFINED))
1444 tnamecmp(const void *p1, const void *p2)
1446 const struct tbl *a = *((const struct tbl * const *)p1);
1447 const struct tbl *b = *((const struct tbl * const *)p2);
1449 return (strcmp(a->name, b->name));
1453 ktsort(struct table *tp)
1456 struct tbl **p, **sp, **dp;
1458 p = alloc((tp->size + 1) * sizeof(struct tbl *), ATEMP);
1459 sp = tp->tbls; /* source */
1461 i = (size_t)tp->size;
1463 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1464 ((*dp)->flag & ARRAY)))
1466 qsort(p, (i = dp - p), sizeof(void *), tnamecmp);
1473 x_sigwinch(int sig MKSH_A_UNUSED)
1475 /* this runs inside interrupt context, with errno saved */