blob: 41dd6dac151e7446a799e7eaa0d3bf0209e3a0a6 [file] [log] [blame]
Elliott Hughesfc0307d2016-02-02 15:26:47 -08001/* $OpenBSD: main.c,v 1.57 2015/09/10 22:48:58 nicm Exp $ */
Elliott Hughes56b517d2014-10-06 11:30:44 -07002/* $OpenBSD: tty.c,v 1.10 2014/08/10 02:44:26 guenther Exp $ */
Elliott Hughesfc0307d2016-02-02 15:26:47 -08003/* $OpenBSD: io.c,v 1.26 2015/09/11 08:00:27 guenther Exp $ */
4/* $OpenBSD: table.c,v 1.16 2015/09/01 13:12:31 tedu Exp $ */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07005
6/*-
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00007 * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
Elliott Hughes47086262019-03-26 12:34:31 -07008 * 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
9 * 2019
Elliott Hughesfc0307d2016-02-02 15:26:47 -080010 * mirabilos <m@mirbsd.org>
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070011 *
12 * Provided that these terms and disclaimer and all copyright notices
13 * are retained or reproduced in an accompanying document, permission
14 * is granted to deal in this work without restriction, including un-
15 * limited rights to use, publicly perform, distribute, sell, modify,
16 * merge, give away, or sublicence.
17 *
18 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
19 * the utmost extent permitted by applicable law, neither express nor
20 * implied; without malicious intent or gross negligence. In no event
21 * may a licensor, author or contributor be held liable for indirect,
22 * direct, other damage, loss, or other issues arising in any way out
23 * of dealing in the work, even if advised of the possibility of such
24 * damage or existence of a defect, except proven that it results out
25 * of said person's immediate fault when using the work as intended.
26 */
27
Geremy Condra03ebf062011-10-12 18:17:24 -070028#define EXTERN
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070029#include "sh.h"
30
31#if HAVE_LANGINFO_CODESET
32#include <langinfo.h>
33#endif
34#if HAVE_SETLOCALE_CTYPE
35#include <locale.h>
36#endif
37
Elliott Hughes47086262019-03-26 12:34:31 -070038__RCSID("$MirOS: src/bin/mksh/main.c,v 1.351 2019/01/05 13:24:18 tg Exp $");
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070039
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070040#ifndef MKSHRC_PATH
41#define MKSHRC_PATH "~/.mkshrc"
42#endif
43
44#ifndef MKSH_DEFAULT_TMPDIR
Elliott Hughes96b43632015-07-17 11:39:41 -070045#define MKSH_DEFAULT_TMPDIR MKSH_UNIXROOT "/tmp"
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070046#endif
47
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000048static uint8_t isuc(const char *);
49static int main_init(int, const char *[], Source **, struct block **);
Geremy Condra03ebf062011-10-12 18:17:24 -070050void chvt_reinit(void);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070051static void reclaim(void);
52static void remove_temps(struct temp *);
Geremy Condra03ebf062011-10-12 18:17:24 -070053static mksh_uari_t rndsetup(void);
Elliott Hughesdd4abe02018-02-05 15:55:19 -080054static void init_environ(void);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070055#ifdef SIGWINCH
56static void x_sigwinch(int);
57#endif
58
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070059static const char initsubs[] =
Elliott Hughes966dd552016-12-08 15:56:04 -080060 "${PS2=> }"
61 "${PS3=#? }"
62 "${PS4=+ }"
63 "${SECONDS=0}"
64 "${TMOUT=0}"
65 "${EPOCHREALTIME=}";
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070066
67static const char *initcoms[] = {
Geremy Condra03ebf062011-10-12 18:17:24 -070068 Ttypeset, "-r", initvsn, NULL,
Elliott Hughes77740fc2016-08-12 15:06:53 -070069 Ttypeset, "-x", "HOME", TPATH, TSHELL, NULL,
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000070 Ttypeset, "-i10", "COLUMNS", "LINES", "SECONDS", "TMOUT", NULL,
Geremy Condra03ebf062011-10-12 18:17:24 -070071 Talias,
Elliott Hughesa3c3f962017-04-12 16:52:30 -070072 "integer=\\\\builtin typeset -i",
73 "local=\\\\builtin typeset",
Geremy Condra03ebf062011-10-12 18:17:24 -070074 /* not "alias -t --": hash -r needs to work */
Elliott Hughesa3c3f962017-04-12 16:52:30 -070075 "hash=\\\\builtin alias -t",
76 "type=\\\\builtin whence -v",
77 "autoload=\\\\builtin typeset -fu",
78 "functions=\\\\builtin typeset -f",
79 "history=\\\\builtin fc -l",
80 "nameref=\\\\builtin typeset -n",
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070081 "nohup=nohup ",
Elliott Hughesa3c3f962017-04-12 16:52:30 -070082 "r=\\\\builtin fc -e -",
83 "login=\\\\builtin exec login",
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070084 NULL,
85 /* this is what AT&T ksh seems to track, with the addition of emacs */
Geremy Condra03ebf062011-10-12 18:17:24 -070086 Talias, "-tU",
Elliott Hughes96b43632015-07-17 11:39:41 -070087 Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
Elliott Hughes77740fc2016-08-12 15:06:53 -070088 "make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070089 NULL
90};
91
Geremy Condra03ebf062011-10-12 18:17:24 -070092static const char *restr_com[] = {
Elliott Hughes77740fc2016-08-12 15:06:53 -070093 Ttypeset, "-r", TPATH, "ENV", TSHELL, NULL
Geremy Condra03ebf062011-10-12 18:17:24 -070094};
95
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +000096static bool initio_done;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -070097
Geremy Condra03ebf062011-10-12 18:17:24 -070098/* top-level parsing and execution environment */
99static struct env env;
100struct env *e = &env;
101
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700102/* compile-time assertions */
103#define cta(name, expr) struct cta_ ## name { char t[(expr) ? 1 : -1]; }
104
105/* this one should be defined by the standard */
106cta(char_is_1_char, (sizeof(char) == 1) && (sizeof(signed char) == 1) &&
107 (sizeof(unsigned char) == 1));
108cta(char_is_8_bits, ((CHAR_BIT) == 8) && ((int)(unsigned char)0xFF == 0xFF) &&
109 ((int)(unsigned char)0x100 == 0) && ((int)(unsigned char)(int)-1 == 0xFF));
110/* the next assertion is probably not really needed */
111cta(short_is_2_char, sizeof(short) == 2);
112cta(short_size_no_matter_of_signedness, sizeof(short) == sizeof(unsigned short));
113/* the next assertion is probably not really needed */
114cta(int_is_4_char, sizeof(int) == 4);
115cta(int_size_no_matter_of_signedness, sizeof(int) == sizeof(unsigned int));
116
117cta(long_ge_int, sizeof(long) >= sizeof(int));
118cta(long_size_no_matter_of_signedness, sizeof(long) == sizeof(unsigned long));
119
120#ifndef MKSH_LEGACY_MODE
121/* the next assertion is probably not really needed */
122cta(ari_is_4_char, sizeof(mksh_ari_t) == 4);
123/* but this is */
124cta(ari_has_31_bit, 0 < (mksh_ari_t)(((((mksh_ari_t)1 << 15) << 15) - 1) * 2 + 1));
125/* the next assertion is probably not really needed */
126cta(uari_is_4_char, sizeof(mksh_uari_t) == 4);
127/* but the next three are; we REQUIRE unsigned integer wraparound */
128cta(uari_has_31_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 2 + 1));
129cta(uari_has_32_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3));
130cta(uari_wrap_32_bit,
131 (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3) >
132 (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 4));
133#endif
134/* these are always required */
135cta(ari_is_signed, (mksh_ari_t)-1 < (mksh_ari_t)0);
136cta(uari_is_unsigned, (mksh_uari_t)-1 > (mksh_uari_t)0);
137/* we require these to have the precisely same size and assume 2s complement */
138cta(ari_size_no_matter_of_signedness, sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
139
140cta(sizet_size_no_matter_of_signedness, sizeof(ssize_t) == sizeof(size_t));
141cta(sizet_voidptr_same_size, sizeof(size_t) == sizeof(void *));
142cta(sizet_funcptr_same_size, sizeof(size_t) == sizeof(void (*)(void)));
143/* our formatting routines assume this */
144cta(ptr_fits_in_long, sizeof(size_t) <= sizeof(long));
145cta(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
146
Geremy Condra03ebf062011-10-12 18:17:24 -0700147static mksh_uari_t
148rndsetup(void)
149{
150 register uint32_t h;
151 struct {
152 ALLOC_ITEM alloc_INT;
153 void *dataptr, *stkptr, *mallocptr;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000154#if defined(__GLIBC__) && (__GLIBC__ >= 2)
Geremy Condra03ebf062011-10-12 18:17:24 -0700155 sigjmp_buf jbuf;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000156#endif
Geremy Condra03ebf062011-10-12 18:17:24 -0700157 struct timeval tv;
Geremy Condra03ebf062011-10-12 18:17:24 -0700158 } *bufptr;
159 char *cp;
160
Elliott Hughes77740fc2016-08-12 15:06:53 -0700161 cp = alloc(sizeof(*bufptr) - sizeof(ALLOC_ITEM), APERM);
Elliott Hughes966dd552016-12-08 15:56:04 -0800162 /* clear the allocated space, for valgrind and to avoid UB */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700163 memset(cp, 0, sizeof(*bufptr) - sizeof(ALLOC_ITEM));
Geremy Condra03ebf062011-10-12 18:17:24 -0700164 /* undo what alloc() did to the malloc result address */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700165 bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
Geremy Condra03ebf062011-10-12 18:17:24 -0700166 /* PIE or something similar provides us with deltas here */
167 bufptr->dataptr = &rndsetupstate;
168 /* ASLR in at least Windows, Linux, some BSDs */
169 bufptr->stkptr = &bufptr;
170 /* randomised malloc in BSD (and possibly others) */
171 bufptr->mallocptr = bufptr;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000172#if defined(__GLIBC__) && (__GLIBC__ >= 2)
Geremy Condra03ebf062011-10-12 18:17:24 -0700173 /* glibc pointer guard */
174 sigsetjmp(bufptr->jbuf, 1);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000175#endif
176 /* introduce variation (and yes, second arg MBZ for portability) */
177 mksh_TIME(bufptr->tv);
Geremy Condra03ebf062011-10-12 18:17:24 -0700178
Elliott Hughes77740fc2016-08-12 15:06:53 -0700179#ifdef MKSH_ALLOC_CATCH_UNDERRUNS
180 mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
181#endif
Thorsten Glaser811a5752013-07-25 14:24:45 +0000182 h = chvt_rndsetup(bufptr, sizeof(*bufptr));
183
184 afree(cp, APERM);
185 return ((mksh_uari_t)h);
186}
187
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700188void
189chvt_reinit(void)
190{
191 kshpid = procpid = getpid();
192 ksheuid = geteuid();
193 kshpgrp = getpgrp();
194 kshppid = getppid();
195}
196
Geremy Condra03ebf062011-10-12 18:17:24 -0700197static const char *empty_argv[] = {
Elliott Hughes77740fc2016-08-12 15:06:53 -0700198 Tmksh, NULL
Geremy Condra03ebf062011-10-12 18:17:24 -0700199};
200
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000201static uint8_t
202isuc(const char *cx) {
203 char *cp, *x;
204 uint8_t rv = 0;
205
206 if (!cx || !*cx)
207 return (0);
208
209 /* uppercase a string duplicate */
210 strdupx(x, cx, ATEMP);
211 cp = x;
212 while ((*cp = ksh_toupper(*cp)))
213 ++cp;
214
215 /* check for UTF-8 */
216 if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
217 rv = 1;
218
219 /* free copy and out */
220 afree(x, ATEMP);
221 return (rv);
222}
223
224static int
225main_init(int argc, const char *argv[], Source **sp, struct block **lp)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700226{
227 int argi, i;
Geremy Condra03ebf062011-10-12 18:17:24 -0700228 Source *s = NULL;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700229 struct block *l;
Elliott Hughes56b517d2014-10-06 11:30:44 -0700230 unsigned char restricted_shell, errexit, utf_flag;
Geremy Condra03ebf062011-10-12 18:17:24 -0700231 char *cp;
232 const char *ccp, **wp;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700233 struct tbl *vp;
234 struct stat s_stdin;
235#if !defined(_PATH_DEFPATH) && defined(_CS_PATH)
Geremy Condra03ebf062011-10-12 18:17:24 -0700236 ssize_t k;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700237#endif
238
Elliott Hughes23925bb2017-09-22 16:04:20 -0700239#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
240 ebcdic_init();
241#endif
242 set_ifs(TC_IFSWS);
243
Elliott Hughes96b43632015-07-17 11:39:41 -0700244#ifdef __OS2__
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700245 os2_init(&argc, &argv);
Elliott Hughes96b43632015-07-17 11:39:41 -0700246#endif
247
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700248 /* do things like getpgrp() et al. */
249 chvt_reinit();
250
Elliott Hughesfc0307d2016-02-02 15:26:47 -0800251 /* make sure argv[] is sane, for weird OSes */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700252 if (!*argv) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700253 argv = empty_argv;
254 argc = 1;
255 }
Geremy Condra03ebf062011-10-12 18:17:24 -0700256 kshname = argv[0];
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700257
Geremy Condra03ebf062011-10-12 18:17:24 -0700258 /* initialise permanent Area */
259 ainit(&aperm);
Elliott Hughes77740fc2016-08-12 15:06:53 -0700260 /* max. name length: -2147483648 = 11 (+ NUL) */
261 vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700262
263 /* set up base environment */
Geremy Condra03ebf062011-10-12 18:17:24 -0700264 env.type = E_NONE;
265 ainit(&env.area);
266 /* set up global l->vars and l->funs */
267 newblock();
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700268
269 /* Do this first so output routines (eg, errorf, shellf) can work */
270 initio();
271
Geremy Condra03ebf062011-10-12 18:17:24 -0700272 /* determine the basename (without '-' or path) of the executable */
273 ccp = kshname;
Elliott Hughes966dd552016-12-08 15:56:04 -0800274 goto begin_parsing_kshname;
Geremy Condra03ebf062011-10-12 18:17:24 -0700275 while ((i = ccp[argi++])) {
Elliott Hughes966dd552016-12-08 15:56:04 -0800276 if (mksh_cdirsep(i)) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700277 ccp += argi;
Elliott Hughes966dd552016-12-08 15:56:04 -0800278 begin_parsing_kshname:
Geremy Condra03ebf062011-10-12 18:17:24 -0700279 argi = 0;
280 if (*ccp == '-')
281 ++ccp;
282 }
283 }
284 if (!*ccp)
285 ccp = empty_argv[0];
286
Elliott Hughes737fdce2014-08-07 12:59:26 -0700287 /*
288 * Turn on nohup by default. (AT&T ksh does not have a nohup
289 * option - it always sends the hup).
290 */
291 Flag(FNOHUP) = 1;
292
293 /*
294 * Turn on brace expansion by default. AT&T kshs that have
295 * alternation always have it on.
296 */
297 Flag(FBRACEEXPAND) = 1;
298
299 /*
300 * Turn on "set -x" inheritance by default.
301 */
302 Flag(FXTRACEREC) = 1;
303
Geremy Condra03ebf062011-10-12 18:17:24 -0700304 /* define built-in commands and see if we were called as one */
305 ktinit(APERM, &builtins,
Elliott Hughesfc0307d2016-02-02 15:26:47 -0800306 /* currently up to 54 builtins: 75% of 128 = 2^7 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000307 7);
Geremy Condra03ebf062011-10-12 18:17:24 -0700308 for (i = 0; mkshbuiltins[i].name != NULL; i++)
309 if (!strcmp(ccp, builtin(mkshbuiltins[i].name,
310 mkshbuiltins[i].func)))
311 Flag(FAS_BUILTIN) = 1;
312
313 if (!Flag(FAS_BUILTIN)) {
314 /* check for -T option early */
315 argi = parse_args(argv, OF_FIRSTTIME, NULL);
316 if (argi < 0)
317 return (1);
318
Thorsten Glaser811a5752013-07-25 14:24:45 +0000319#if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
320 /* are we called as -sh or /bin/sh or so? */
Elliott Hughes96b43632015-07-17 11:39:41 -0700321 if (!strcmp(ccp, "sh" MKSH_EXE_EXT)) {
Thorsten Glaser811a5752013-07-25 14:24:45 +0000322 /* either also turns off braceexpand */
323#ifdef MKSH_BINSHPOSIX
324 /* enable better POSIX conformance */
325 change_flag(FPOSIX, OF_FIRSTTIME, true);
326#endif
Geremy Condra03ebf062011-10-12 18:17:24 -0700327#ifdef MKSH_BINSHREDUCED
Thorsten Glaser811a5752013-07-25 14:24:45 +0000328 /* enable kludge/compat mode */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000329 change_flag(FSH, OF_FIRSTTIME, true);
Geremy Condra03ebf062011-10-12 18:17:24 -0700330#endif
Thorsten Glaser811a5752013-07-25 14:24:45 +0000331 }
332#endif
Geremy Condra03ebf062011-10-12 18:17:24 -0700333 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700334
335 initvar();
336
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700337 inittraps();
338
339 coproc_init();
340
341 /* set up variable and command dictionaries */
Geremy Condra03ebf062011-10-12 18:17:24 -0700342 ktinit(APERM, &taliases, 0);
343 ktinit(APERM, &aliases, 0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700344#ifndef MKSH_NOPWNAM
Geremy Condra03ebf062011-10-12 18:17:24 -0700345 ktinit(APERM, &homedirs, 0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700346#endif
347
348 /* define shell keywords */
349 initkeywords();
350
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700351 init_histvec();
352
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000353 /* initialise tty size before importing environment */
354 change_winsz();
355
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700356#ifdef _PATH_DEFPATH
357 def_path = _PATH_DEFPATH;
358#else
359#ifdef _CS_PATH
Geremy Condra03ebf062011-10-12 18:17:24 -0700360 if ((k = confstr(_CS_PATH, NULL, 0)) > 0 &&
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700361 confstr(_CS_PATH, cp = alloc(k + 1, APERM), k + 1) == k + 1)
362 def_path = cp;
363 else
364#endif
365 /*
366 * this is uniform across all OSes unless it
Elliott Hughes77740fc2016-08-12 15:06:53 -0700367 * breaks somewhere hard; don't try to optimise,
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700368 * e.g. add stuff for Interix or remove /usr
369 * for HURD, because e.g. Debian GNU/HURD is
370 * "keeping a regular /usr"; this is supposed
371 * to be a sane 'basic' default PATH
372 */
Elliott Hughes96b43632015-07-17 11:39:41 -0700373 def_path = MKSH_UNIXROOT "/bin" MKSH_PATHSEPS
374 MKSH_UNIXROOT "/usr/bin" MKSH_PATHSEPS
375 MKSH_UNIXROOT "/sbin" MKSH_PATHSEPS
376 MKSH_UNIXROOT "/usr/sbin";
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700377#endif
378
Geremy Condra03ebf062011-10-12 18:17:24 -0700379 /*
380 * Set PATH to def_path (will set the path global variable).
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700381 * (import of environment below will probably change this setting).
382 */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700383 vp = global(TPATH);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700384 /* setstr can't fail here */
385 setstr(vp, def_path, KSH_RETURN_ERROR);
386
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000387#ifndef MKSH_NO_CMDLINE_EDITING
Geremy Condra03ebf062011-10-12 18:17:24 -0700388 /*
389 * Set edit mode to emacs by default, may be overridden
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700390 * by the environment or the user. Also, we want tab completion
Geremy Condra03ebf062011-10-12 18:17:24 -0700391 * on in vi by default.
392 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000393 change_flag(FEMACS, OF_SPECIAL, true);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700394#if !MKSH_S_NOVI
395 Flag(FVITABCOMPLETE) = 1;
396#endif
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000397#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700398
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700399 /* import environment */
Elliott Hughesdd4abe02018-02-05 15:55:19 -0800400 init_environ();
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700401
Sandeep Patilc2036112017-04-12 18:02:50 -0700402 /* override default PATH regardless of environment */
403#ifdef MKSH_DEFPATH_OVERRIDE
Elliott Hughes23925bb2017-09-22 16:04:20 -0700404 vp = global(TPATH);
405 setstr(vp, MKSH_DEFPATH_OVERRIDE, KSH_RETURN_ERROR);
Sandeep Patilc2036112017-04-12 18:02:50 -0700406#endif
407
Geremy Condra03ebf062011-10-12 18:17:24 -0700408 /* for security */
Elliott Hughes23925bb2017-09-22 16:04:20 -0700409 typeset(TinitIFS, 0, 0, 0, 0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700410
411 /* assign default shell variable values */
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700412 typeset("PATHSEP=" MKSH_PATHSEPS, 0, 0, 0, 0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700413 substitute(initsubs, 0);
414
415 /* Figure out the current working directory and set $PWD */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700416 vp = global(TPWD);
Geremy Condra03ebf062011-10-12 18:17:24 -0700417 cp = str_val(vp);
418 /* Try to use existing $PWD if it is valid */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700419 set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
420 Tdot, true)) ? cp : NULL);
Geremy Condra03ebf062011-10-12 18:17:24 -0700421 if (current_wd[0])
422 simplify_path(current_wd);
423 /* Only set pwd if we know where we are or if it had a bogus value */
424 if (current_wd[0] || *cp)
425 /* setstr can't fail here */
426 setstr(vp, current_wd, KSH_RETURN_ERROR);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700427
428 for (wp = initcoms; *wp != NULL; wp++) {
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700429 c_builtin(wp);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700430 while (*wp != NULL)
431 wp++;
432 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000433 setint_n(global("OPTIND"), 1, 10);
Geremy Condra03ebf062011-10-12 18:17:24 -0700434
435 kshuid = getuid();
436 kshgid = getgid();
437 kshegid = getegid();
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700438
439 safe_prompt = ksheuid ? "$ " : "# ";
440 vp = global("PS1");
441 /* Set PS1 if unset or we are root and prompt doesn't contain a # */
442 if (!(vp->flag & ISSET) ||
443 (!ksheuid && !strchr(str_val(vp), '#')))
444 /* setstr can't fail here */
445 setstr(vp, safe_prompt, KSH_RETURN_ERROR);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000446 setint_n((vp = global("BASHPID")), 0, 10);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700447 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000448 setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700449 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000450 setint_n((vp = global("PPID")), (mksh_uari_t)kshppid, 10);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700451 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000452 setint_n((vp = global("USER_ID")), (mksh_uari_t)ksheuid, 10);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700453 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000454 setint_n((vp = global("KSHUID")), (mksh_uari_t)kshuid, 10);
Geremy Condra03ebf062011-10-12 18:17:24 -0700455 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000456 setint_n((vp = global("KSHEGID")), (mksh_uari_t)kshegid, 10);
Geremy Condra03ebf062011-10-12 18:17:24 -0700457 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000458 setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
Geremy Condra03ebf062011-10-12 18:17:24 -0700459 vp->flag |= INT_U;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000460 setint_n((vp = global("RANDOM")), rndsetup(), 10);
461 vp->flag |= INT_U;
462 setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700463
464 /* Set this before parsing arguments */
Elliott Hughesfc0307d2016-02-02 15:26:47 -0800465 Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700466
Elliott Hughes47086262019-03-26 12:34:31 -0700467 /* record if monitor is set on command line (see j_init() in jobs.c) */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700468#ifndef MKSH_UNEMPLOYED
469 Flag(FMONITOR) = 127;
470#endif
471 /* this to note if utf-8 mode is set on command line (see below) */
472 UTFMODE = 2;
473
Geremy Condra03ebf062011-10-12 18:17:24 -0700474 if (!Flag(FAS_BUILTIN)) {
475 argi = parse_args(argv, OF_CMDLINE, NULL);
476 if (argi < 0)
477 return (1);
478 }
479
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700480 /* process this later only, default to off (hysterical raisins) */
481 utf_flag = UTFMODE;
482 UTFMODE = 0;
483
Geremy Condra03ebf062011-10-12 18:17:24 -0700484 if (Flag(FAS_BUILTIN)) {
485 /* auto-detect from environment variables, always */
486 utf_flag = 3;
487 } else if (Flag(FCOMMAND)) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000488 s = pushs(SSTRINGCMDLINE, ATEMP);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700489 if (!(s->start = s->str = argv[argi++]))
Elliott Hughes77740fc2016-08-12 15:06:53 -0700490 errorf(Tf_optfoo, "", "", 'c', Treq_arg);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000491 while (*s->str) {
Elliott Hughes23925bb2017-09-22 16:04:20 -0700492 if (ctype(*s->str, C_QUOTE))
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000493 break;
494 s->str++;
495 }
496 if (!*s->str)
497 s->flags |= SF_MAYEXEC;
498 s->str = s->start;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700499#ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
500 /* compatibility to MidnightBSD 0.1 /bin/sh (kludge) */
501 if (Flag(FSH) && argv[argi] && !strcmp(argv[argi], "--"))
502 ++argi;
503#endif
504 if (argv[argi])
505 kshname = argv[argi++];
506 } else if (argi < argc && !Flag(FSTDIN)) {
507 s = pushs(SFILE, ATEMP);
Elliott Hughes96b43632015-07-17 11:39:41 -0700508#ifdef __OS2__
509 /*
510 * A bug in OS/2 extproc (like shebang) handling makes
511 * it not pass the full pathname of a script, so we need
512 * to search for it. This changes the behaviour of a
513 * simple "mksh foo", but can't be helped.
514 */
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700515 s->file = argv[argi++];
516 if (search_access(s->file, X_OK) != 0)
517 s->file = search_path(s->file, path, X_OK, NULL);
Elliott Hughes96b43632015-07-17 11:39:41 -0700518 if (!s->file || !*s->file)
519 s->file = argv[argi - 1];
520#else
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700521 s->file = argv[argi++];
Elliott Hughes96b43632015-07-17 11:39:41 -0700522#endif
Elliott Hughes47086262019-03-26 12:34:31 -0700523 s->u.shf = shf_open(s->file, O_RDONLY | O_MAYEXEC, 0,
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700524 SHF_MAPHI | SHF_CLEXEC);
525 if (s->u.shf == NULL) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700526 shl_stdout_ok = false;
Elliott Hughes77740fc2016-08-12 15:06:53 -0700527 warningf(true, Tf_sD_s, s->file, cstrerror(errno));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700528 /* mandated by SUSv4 */
529 exstat = 127;
530 unwind(LERROR);
531 }
532 kshname = s->file;
533 } else {
534 Flag(FSTDIN) = 1;
535 s = pushs(SSTDIN, ATEMP);
536 s->file = "<stdin>";
537 s->u.shf = shf_fdopen(0, SHF_RD | can_seek(0),
538 NULL);
539 if (isatty(0) && isatty(2)) {
540 Flag(FTALKING) = Flag(FTALKING_I) = 1;
541 /* The following only if isatty(0) */
542 s->flags |= SF_TTY;
543 s->u.shf->flags |= SHF_INTERRUPT;
544 s->file = NULL;
545 }
546 }
547
548 /* this bizarreness is mandated by POSIX */
549 if (fstat(0, &s_stdin) >= 0 && S_ISCHR(s_stdin.st_mode) &&
550 Flag(FTALKING))
551 reset_nonblock(0);
552
553 /* initialise job control */
554 j_init();
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000555 /* do this after j_init() which calls tty_init_state() */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700556 if (Flag(FTALKING)) {
557 if (utf_flag == 2) {
558#ifndef MKSH_ASSUME_UTF8
Geremy Condra03ebf062011-10-12 18:17:24 -0700559 /* auto-detect from locale or environment */
560 utf_flag = 4;
Elliott Hughes737fdce2014-08-07 12:59:26 -0700561#else /* this may not be an #elif */
562#if MKSH_ASSUME_UTF8
Geremy Condra03ebf062011-10-12 18:17:24 -0700563 utf_flag = 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700564#else
Geremy Condra03ebf062011-10-12 18:17:24 -0700565 /* always disable UTF-8 (for interactive) */
566 utf_flag = 0;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700567#endif
Elliott Hughes737fdce2014-08-07 12:59:26 -0700568#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700569 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000570#ifndef MKSH_NO_CMDLINE_EDITING
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700571 x_init();
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000572#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700573 }
574
575#ifdef SIGWINCH
576 sigtraps[SIGWINCH].flags |= TF_SHELL_USES;
577 setsig(&sigtraps[SIGWINCH], x_sigwinch,
578 SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
579#endif
580
581 l = e->loc;
Geremy Condra03ebf062011-10-12 18:17:24 -0700582 if (Flag(FAS_BUILTIN)) {
583 l->argc = argc;
584 l->argv = argv;
585 l->argv[0] = ccp;
586 } else {
587 l->argc = argc - argi;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000588 /*
589 * allocate a new array because otherwise, when we modify
590 * it in-place, ps(1) output changes; the meaning of argc
591 * here is slightly different as it excludes kshname, and
592 * we add a trailing NULL sentinel as well
593 */
594 l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
Geremy Condra03ebf062011-10-12 18:17:24 -0700595 l->argv[0] = kshname;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000596 memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
597 l->argv[l->argc + 1] = NULL;
Geremy Condra03ebf062011-10-12 18:17:24 -0700598 getopts_reset(1);
599 }
600
601 /* divine the initial state of the utf8-mode Flag */
Geremy Condra03ebf062011-10-12 18:17:24 -0700602 ccp = null;
603 switch (utf_flag) {
604
605 /* auto-detect from locale or environment */
606 case 4:
607#if HAVE_SETLOCALE_CTYPE
608 ccp = setlocale(LC_CTYPE, "");
609#if HAVE_LANGINFO_CODESET
610 if (!isuc(ccp))
611 ccp = nl_langinfo(CODESET);
612#endif
613 if (!isuc(ccp))
614 ccp = null;
Geremy Condra03ebf062011-10-12 18:17:24 -0700615#endif
Elliott Hughes966dd552016-12-08 15:56:04 -0800616 /* FALLTHROUGH */
Geremy Condra03ebf062011-10-12 18:17:24 -0700617
618 /* auto-detect from environment */
619 case 3:
620 /* these were imported from environ earlier */
621 if (ccp == null)
622 ccp = str_val(global("LC_ALL"));
623 if (ccp == null)
624 ccp = str_val(global("LC_CTYPE"));
625 if (ccp == null)
626 ccp = str_val(global("LANG"));
627 UTFMODE = isuc(ccp);
628 break;
629
630 /* not set on command line, not FTALKING */
631 case 2:
632 /* unknown values */
633 default:
634 utf_flag = 0;
635 /* FALLTHROUGH */
636
637 /* known values */
638 case 1:
639 case 0:
640 UTFMODE = utf_flag;
641 break;
642 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700643
644 /* Disable during .profile/ENV reading */
Elliott Hughes56b517d2014-10-06 11:30:44 -0700645 restricted_shell = Flag(FRESTRICTED);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700646 Flag(FRESTRICTED) = 0;
647 errexit = Flag(FERREXIT);
648 Flag(FERREXIT) = 0;
649
Geremy Condra03ebf062011-10-12 18:17:24 -0700650 /*
651 * Do this before profile/$ENV so that if it causes problems in them,
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700652 * user will know why things broke.
653 */
654 if (!current_wd[0] && Flag(FTALKING))
Geremy Condra03ebf062011-10-12 18:17:24 -0700655 warningf(false, "can't determine current directory");
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700656
Elliott Hughes737fdce2014-08-07 12:59:26 -0700657 if (Flag(FLOGIN))
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000658 include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
Elliott Hughes737fdce2014-08-07 12:59:26 -0700659 if (!Flag(FPRIVILEGED)) {
660 if (Flag(FLOGIN))
661 include(substitute("$HOME/.profile", 0), 0, NULL, true);
662 if (Flag(FTALKING)) {
Elliott Hughesdd4abe02018-02-05 15:55:19 -0800663 cp = substitute("${ENV:-" MKSHRC_PATH "}", DOTILDE);
Elliott Hughes737fdce2014-08-07 12:59:26 -0700664 if (cp[0] != '\0')
665 include(cp, 0, NULL, true);
666 }
667 } else {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000668 include(MKSH_SUID_PROFILE, 0, NULL, true);
Elliott Hughes737fdce2014-08-07 12:59:26 -0700669 /* turn off -p if not set explicitly */
670 if (Flag(FPRIVILEGED) != 1)
671 change_flag(FPRIVILEGED, OF_INTERNAL, false);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700672 }
673
Elliott Hughes56b517d2014-10-06 11:30:44 -0700674 if (restricted_shell) {
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700675 c_builtin(restr_com);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700676 /* After typeset command... */
677 Flag(FRESTRICTED) = 1;
678 }
679 Flag(FERREXIT) = errexit;
680
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000681 if (Flag(FTALKING) && s)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700682 hist_init(s);
Geremy Condra03ebf062011-10-12 18:17:24 -0700683 else
684 /* set after ENV */
685 Flag(FTRACKALL) = 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700686
Geremy Condra03ebf062011-10-12 18:17:24 -0700687 alarm_init();
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700688
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000689 *sp = s;
690 *lp = l;
Geremy Condra03ebf062011-10-12 18:17:24 -0700691 return (0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700692}
693
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000694/* this indirection barrier reduces stack usage during normal operation */
695
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700696int
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000697main(int argc, const char *argv[])
698{
699 int rv;
700 Source *s;
701 struct block *l;
702
703 if ((rv = main_init(argc, argv, &s, &l)) == 0) {
704 if (Flag(FAS_BUILTIN)) {
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700705 rv = c_builtin(l->argv);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000706 } else {
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700707 shell(s, 0);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000708 /* NOTREACHED */
709 }
710 }
711 return (rv);
712}
713
714int
715include(const char *name, int argc, const char **argv, bool intr_ok)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700716{
717 Source *volatile s = NULL;
718 struct shf *shf;
719 const char **volatile old_argv;
720 volatile int old_argc;
721 int i;
722
Elliott Hughes47086262019-03-26 12:34:31 -0700723 shf = shf_open(name, O_RDONLY | O_MAYEXEC, 0, SHF_MAPHI | SHF_CLEXEC);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700724 if (shf == NULL)
725 return (-1);
726
727 if (argv) {
728 old_argv = e->loc->argv;
729 old_argc = e->loc->argc;
730 } else {
731 old_argv = NULL;
732 old_argc = 0;
733 }
734 newenv(E_INCL);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000735 if ((i = kshsetjmp(e->jbuf))) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700736 quitenv(s ? s->u.shf : NULL);
737 if (old_argv) {
738 e->loc->argv = old_argv;
739 e->loc->argc = old_argc;
740 }
741 switch (i) {
742 case LRETURN:
743 case LERROR:
Geremy Condra03ebf062011-10-12 18:17:24 -0700744 /* see below */
745 return (exstat & 0xFF);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700746 case LINTR:
Geremy Condra03ebf062011-10-12 18:17:24 -0700747 /*
748 * intr_ok is set if we are including .profile or $ENV.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700749 * If user ^Cs out, we don't want to kill the shell...
750 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000751 if (intr_ok && ((exstat & 0xFF) - 128) != SIGTERM)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700752 return (1);
753 /* FALLTHROUGH */
754 case LEXIT:
755 case LLEAVE:
756 case LSHELL:
757 unwind(i);
758 /* NOTREACHED */
759 default:
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700760 internal_errorf(Tunexpected_type, Tunwind, Tsource, i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700761 /* NOTREACHED */
762 }
763 }
764 if (argv) {
765 e->loc->argv = argv;
766 e->loc->argc = argc;
767 }
768 s = pushs(SFILE, ATEMP);
769 s->u.shf = shf;
770 strdupx(s->file, name, ATEMP);
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700771 i = shell(s, 1);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700772 quitenv(s->u.shf);
773 if (old_argv) {
774 e->loc->argv = old_argv;
775 e->loc->argc = old_argc;
776 }
Geremy Condra03ebf062011-10-12 18:17:24 -0700777 /* & 0xff to ensure value not -1 */
778 return (i & 0xFF);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700779}
780
781/* spawn a command into a shell optionally keeping track of the line number */
782int
783command(const char *comm, int line)
784{
Elliott Hughes77740fc2016-08-12 15:06:53 -0700785 Source *s, *sold = source;
786 int rv;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700787
788 s = pushs(SSTRING, ATEMP);
789 s->start = s->str = comm;
790 s->line = line;
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700791 rv = shell(s, 1);
Elliott Hughes77740fc2016-08-12 15:06:53 -0700792 source = sold;
793 return (rv);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700794}
795
796/*
797 * run the commands from the input source, returning status.
798 */
799int
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700800shell(Source * volatile s, volatile int level)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700801{
802 struct op *t;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000803 volatile bool wastty = tobool(s->flags & SF_TTY);
804 volatile uint8_t attempts = 13;
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700805 volatile bool interactive = (level == 0) && Flag(FTALKING);
Geremy Condra03ebf062011-10-12 18:17:24 -0700806 volatile bool sfirst = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700807 Source *volatile old_source = source;
808 int i;
809
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700810 newenv(level == 2 ? E_EVAL : E_PARSE);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700811 if (interactive)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000812 really_exit = false;
813 switch ((i = kshsetjmp(e->jbuf))) {
814 case 0:
815 break;
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700816 case LBREAK:
817 case LCONTIN:
818 if (level != 2) {
819 source = old_source;
820 quitenv(NULL);
821 internal_errorf(Tf_cant_s, Tshell,
822 i == LBREAK ? Tbreak : Tcontinue);
823 /* NOTREACHED */
824 }
825 /* assert: interactive == false */
826 /* FALLTHROUGH */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000827 case LINTR:
828 /* we get here if SIGINT not caught or ignored */
829 case LERROR:
830 case LSHELL:
831 if (interactive) {
832 if (i == LINTR)
833 shellf("\n");
834 /*
835 * Reset any eof that was read as part of a
836 * multiline command.
837 */
838 if (Flag(FIGNOREEOF) && s->type == SEOF && wastty)
839 s->type = SSTDIN;
840 /*
841 * Used by exit command to get back to
842 * top level shell. Kind of strange since
843 * interactive is set if we are reading from
844 * a tty, but to have stopped jobs, one only
845 * needs FMONITOR set (not FTALKING/SF_TTY)...
846 */
847 /* toss any input we have so far */
848 yyrecursive_pop(true);
849 s->start = s->str = null;
850 retrace_info = NULL;
851 herep = heres;
852 break;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700853 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000854 /* FALLTHROUGH */
855 case LEXIT:
856 case LLEAVE:
857 case LRETURN:
858 source = old_source;
859 quitenv(NULL);
860 /* keep on going */
861 unwind(i);
862 /* NOTREACHED */
863 default:
864 source = old_source;
865 quitenv(NULL);
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700866 internal_errorf(Tunexpected_type, Tunwind, Tshell, i);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000867 /* NOTREACHED */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700868 }
Geremy Condra03ebf062011-10-12 18:17:24 -0700869 while (/* CONSTCOND */ 1) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700870 if (trap)
871 runtraps(0);
872
873 if (s->next == NULL) {
874 if (Flag(FVERBOSE))
875 s->flags |= SF_ECHO;
876 else
877 s->flags &= ~SF_ECHO;
878 }
879 if (interactive) {
880 j_notify();
881 set_prompt(PS1, s);
882 }
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700883 t = compile(s, sfirst, true);
Elliott Hughes96b43632015-07-17 11:39:41 -0700884 if (interactive)
885 histsave(&s->line, NULL, HIST_FLUSH, true);
Geremy Condra03ebf062011-10-12 18:17:24 -0700886 sfirst = false;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000887 if (!t)
888 goto source_no_tree;
889 if (t->type == TEOF) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700890 if (wastty && Flag(FIGNOREEOF) && --attempts > 0) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700891 shellf("Use 'exit' to leave mksh\n");
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700892 s->type = SSTDIN;
893 } else if (wastty && !really_exit &&
894 j_stopped_running()) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000895 really_exit = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700896 s->type = SSTDIN;
897 } else {
Geremy Condra03ebf062011-10-12 18:17:24 -0700898 /*
899 * this for POSIX which says EXIT traps
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700900 * shall be taken in the environment
901 * immediately after the last command
902 * executed.
903 */
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700904 if (level == 0)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700905 unwind(LEXIT);
906 break;
907 }
Elliott Hughes737fdce2014-08-07 12:59:26 -0700908 } else if ((s->flags & SF_MAYEXEC) && t->type == TCOM)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000909 t->u.evalflags |= DOTCOMEXEC;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000910 if (!Flag(FNOEXEC) || (s->flags & SF_TTY))
911 exstat = execute(t, 0, NULL) & 0xFF;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700912
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000913 if (t->type != TEOF && interactive && really_exit)
914 really_exit = false;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700915
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000916 source_no_tree:
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700917 reclaim();
918 }
919 quitenv(NULL);
920 source = old_source;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000921 return (exstat & 0xFF);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700922}
923
924/* return to closest error handler or shell(), exit if none found */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000925/* note: i MUST NOT be 0 */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700926void
927unwind(int i)
928{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000929 /*
930 * This is a kludge. We need to restore everything that was
931 * changed in the new environment, see cid 1005090337C7A669439
932 * and 10050903386452ACBF1, but fail to even save things most of
933 * the time. funcs.c:c_eval() changes FERREXIT temporarily to 0,
934 * which needs to be restored thus (related to Debian #696823).
935 * We did not save the shell flags, so we use a special or'd
936 * value here... this is mostly to clean up behind *other*
937 * callers of unwind(LERROR) here; exec.c has the regular case.
938 */
939 if (Flag(FERREXIT) & 0x80) {
940 /* GNU bash does not run this trapsig */
941 trapsig(ksh_SIGERR);
942 Flag(FERREXIT) &= ~0x80;
943 }
944
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700945 /* ordering for EXIT vs ERR is a bit odd (this is what AT&T ksh does) */
Thorsten Glaser811a5752013-07-25 14:24:45 +0000946 if (i == LEXIT || ((i == LERROR || i == LINTR) &&
947 sigtraps[ksh_SIGEXIT].trap &&
948 (!Flag(FTALKING) || Flag(FERREXIT)))) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700949 ++trap_nested;
950 runtrap(&sigtraps[ksh_SIGEXIT], trap_nested == 1);
951 --trap_nested;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700952 i = LLEAVE;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000953 } else if (Flag(FERREXIT) == 1 && (i == LERROR || i == LINTR)) {
Geremy Condra03ebf062011-10-12 18:17:24 -0700954 ++trap_nested;
955 runtrap(&sigtraps[ksh_SIGERR], trap_nested == 1);
956 --trap_nested;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700957 i = LLEAVE;
958 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000959
Geremy Condra03ebf062011-10-12 18:17:24 -0700960 while (/* CONSTCOND */ 1) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700961 switch (e->type) {
962 case E_PARSE:
963 case E_FUNC:
964 case E_INCL:
965 case E_LOOP:
966 case E_ERRH:
Elliott Hughesa3c3f962017-04-12 16:52:30 -0700967 case E_EVAL:
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000968 kshlongjmp(e->jbuf, i);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700969 /* NOTREACHED */
970 case E_NONE:
971 if (i == LINTR)
972 e->flags |= EF_FAKE_SIGDIE;
973 /* FALLTHROUGH */
974 default:
975 quitenv(NULL);
976 }
977 }
978}
979
980void
981newenv(int type)
982{
983 struct env *ep;
984 char *cp;
985
986 /*
987 * struct env includes ALLOC_ITEM for alignment constraints
988 * so first get the actually used memory, then assign it
989 */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700990 cp = alloc(sizeof(struct env) - sizeof(ALLOC_ITEM), ATEMP);
Geremy Condra03ebf062011-10-12 18:17:24 -0700991 /* undo what alloc() did to the malloc result address */
Elliott Hughes77740fc2016-08-12 15:06:53 -0700992 ep = (void *)(cp - sizeof(ALLOC_ITEM));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -0700993 /* initialise public members of struct env (not the ALLOC_ITEM) */
994 ainit(&ep->area);
995 ep->oenv = e;
996 ep->loc = e->loc;
997 ep->savefd = NULL;
998 ep->temps = NULL;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +0000999 ep->yyrecursive_statep = NULL;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001000 ep->type = type;
1001 ep->flags = 0;
1002 /* jump buffer is invalid because flags == 0 */
1003 e = ep;
1004}
1005
1006void
1007quitenv(struct shf *shf)
1008{
1009 struct env *ep = e;
1010 char *cp;
1011 int fd;
1012
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001013 yyrecursive_pop(true);
1014 while (ep->oenv && ep->oenv->loc != ep->loc)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001015 popblock();
1016 if (ep->savefd != NULL) {
1017 for (fd = 0; fd < NUFILE; fd++)
1018 /* if ep->savefd[fd] < 0, means fd was closed */
1019 if (ep->savefd[fd])
1020 restfd(fd, ep->savefd[fd]);
Geremy Condra03ebf062011-10-12 18:17:24 -07001021 if (ep->savefd[2])
1022 /* Clear any write errors */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001023 shf_reopen(2, SHF_WR, shl_out);
1024 }
Geremy Condra03ebf062011-10-12 18:17:24 -07001025 /*
1026 * Bottom of the stack.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001027 * Either main shell is exiting or cleanup_parents_env() was called.
1028 */
1029 if (ep->oenv == NULL) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001030#ifdef DEBUG_LEAKS
1031 int i;
1032#endif
1033
Geremy Condra03ebf062011-10-12 18:17:24 -07001034 if (ep->type == E_NONE) {
1035 /* Main shell exiting? */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001036#if HAVE_PERSISTENT_HISTORY
1037 if (Flag(FTALKING))
1038 hist_finish();
1039#endif
1040 j_exit();
1041 if (ep->flags & EF_FAKE_SIGDIE) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001042 int sig = (exstat & 0xFF) - 128;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001043
Geremy Condra03ebf062011-10-12 18:17:24 -07001044 /*
1045 * ham up our death a bit (AT&T ksh
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001046 * only seems to do this for SIGTERM)
1047 * Don't do it for SIGQUIT, since we'd
1048 * dump a core..
1049 */
1050 if ((sig == SIGINT || sig == SIGTERM) &&
1051 (kshpgrp == kshpid)) {
1052 setsig(&sigtraps[sig], SIG_DFL,
1053 SS_RESTORE_CURR | SS_FORCE);
1054 kill(0, sig);
1055 }
1056 }
1057 }
1058 if (shf)
1059 shf_close(shf);
1060 reclaim();
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001061#ifdef DEBUG_LEAKS
1062#ifndef MKSH_NO_CMDLINE_EDITING
1063 x_done();
1064#endif
Thorsten Glaser811a5752013-07-25 14:24:45 +00001065#ifndef MKSH_NOPROSPECTOFWORK
1066 /* block at least SIGCHLD during/after afreeall */
1067 sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
1068#endif
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001069 afreeall(APERM);
1070 for (fd = 3; fd < NUFILE; fd++)
1071 if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
1072 (i & FD_CLOEXEC))
1073 close(fd);
1074 close(2);
1075 close(1);
1076 close(0);
1077#endif
1078 exit(exstat & 0xFF);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001079 }
1080 if (shf)
1081 shf_close(shf);
1082 reclaim();
1083
1084 e = e->oenv;
1085
1086 /* free the struct env - tricky due to the ALLOC_ITEM inside */
1087 cp = (void *)ep;
Elliott Hughes77740fc2016-08-12 15:06:53 -07001088 afree(cp + sizeof(ALLOC_ITEM), ATEMP);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001089}
1090
1091/* Called after a fork to cleanup stuff left over from parents environment */
1092void
1093cleanup_parents_env(void)
1094{
1095 struct env *ep;
1096 int fd;
1097
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001098 /*
1099 * Don't clean up temporary files - parent will probably need them.
1100 * Also, can't easily reclaim memory since variables, etc. could be
1101 * anywhere.
1102 */
1103
1104 /* close all file descriptors hiding in savefd */
1105 for (ep = e; ep; ep = ep->oenv) {
1106 if (ep->savefd) {
1107 for (fd = 0; fd < NUFILE; fd++)
1108 if (ep->savefd[fd] > 0)
1109 close(ep->savefd[fd]);
1110 afree(ep->savefd, &ep->area);
1111 ep->savefd = NULL;
1112 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001113#ifdef DEBUG_LEAKS
1114 if (ep->type != E_NONE)
1115 ep->type = E_GONE;
1116#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001117 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001118#ifndef DEBUG_LEAKS
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001119 e->oenv = NULL;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001120#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001121}
1122
1123/* Called just before an execve cleanup stuff temporary files */
1124void
1125cleanup_proc_env(void)
1126{
1127 struct env *ep;
1128
1129 for (ep = e; ep; ep = ep->oenv)
1130 remove_temps(ep->temps);
1131}
1132
1133/* remove temp files and free ATEMP Area */
1134static void
1135reclaim(void)
1136{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001137 struct block *l;
1138
1139 while ((l = e->loc) && (!e->oenv || e->oenv->loc != l)) {
1140 e->loc = l->next;
1141 afreeall(&l->area);
1142 }
1143
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001144 remove_temps(e->temps);
1145 e->temps = NULL;
Elliott Hughes77740fc2016-08-12 15:06:53 -07001146
1147 /*
1148 * if the memory backing source is reclaimed, things
1149 * will end up badly when a function expecting it to
1150 * be valid is run; a NULL pointer is easily debugged
1151 */
1152 if (source && source->areap == &e->area)
1153 source = NULL;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001154 afreeall(&e->area);
1155}
1156
1157static void
1158remove_temps(struct temp *tp)
1159{
Elliott Hughes77740fc2016-08-12 15:06:53 -07001160 while (tp) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001161 if (tp->pid == procpid)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001162 unlink(tp->tffn);
Elliott Hughes77740fc2016-08-12 15:06:53 -07001163 tp = tp->next;
1164 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001165}
1166
Geremy Condra03ebf062011-10-12 18:17:24 -07001167/*
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001168 * Initialise tty_fd. Used for tracking the size of the terminal,
1169 * saving/resetting tty modes upon forground job completion, and
1170 * for setting up the tty process group. Return values:
1171 * 0 = got controlling tty
1172 * 1 = got terminal but no controlling tty
1173 * 2 = cannot find a terminal
1174 * 3 = cannot dup fd
1175 * 4 = cannot make fd close-on-exec
1176 * An existing tty_fd is cached if no "better" one could be found,
1177 * i.e. if tty_devtty was already set or the new would not set it.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001178 */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001179int
1180tty_init_fd(void)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001181{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001182 int fd, rv, eno = 0;
1183 bool do_close = false, is_devtty = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001184
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001185 if (tty_devtty) {
1186 /* already got a tty which is /dev/tty */
1187 return (0);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001188 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001189
1190#ifdef _UWIN
Geremy Condra03ebf062011-10-12 18:17:24 -07001191 /*XXX imake style */
1192 if (isatty(3)) {
1193 /* fd 3 on UWIN _is_ /dev/tty (or our controlling tty) */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001194 fd = 3;
1195 goto got_fd;
1196 }
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001197#endif
Elliott Hughes77740fc2016-08-12 15:06:53 -07001198 if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001199 do_close = true;
1200 goto got_fd;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001201 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001202 eno = errno;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001203
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001204 if (tty_fd >= 0) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001205 /* already got a non-devtty one */
1206 rv = 1;
1207 goto out;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001208 }
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001209 is_devtty = false;
1210
1211 if (isatty((fd = 0)) || isatty((fd = 2)))
1212 goto got_fd;
1213 /* cannot find one */
1214 rv = 2;
1215 /* assert: do_close == false */
1216 goto out;
1217
1218 got_fd:
1219 if ((rv = fcntl(fd, F_DUPFD, FDBASE)) < 0) {
1220 eno = errno;
1221 rv = 3;
1222 goto out;
1223 }
1224 if (fcntl(rv, F_SETFD, FD_CLOEXEC) < 0) {
1225 eno = errno;
1226 close(rv);
1227 rv = 4;
1228 goto out;
1229 }
1230 tty_fd = rv;
1231 tty_devtty = is_devtty;
1232 rv = eno = 0;
1233 out:
1234 if (do_close)
1235 close(fd);
1236 errno = eno;
1237 return (rv);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001238}
1239
1240/* A shell error occurred (eg, syntax error, etc.) */
Geremy Condra03ebf062011-10-12 18:17:24 -07001241
1242#define VWARNINGF_ERRORPREFIX 1
1243#define VWARNINGF_FILELINE 2
1244#define VWARNINGF_BUILTIN 4
1245#define VWARNINGF_INTERNAL 8
1246
1247static void vwarningf(unsigned int, const char *, va_list)
1248 MKSH_A_FORMAT(__printf__, 2, 0);
1249
1250static void
1251vwarningf(unsigned int flags, const char *fmt, va_list ap)
1252{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001253 if (fmt) {
Geremy Condra03ebf062011-10-12 18:17:24 -07001254 if (flags & VWARNINGF_INTERNAL)
Elliott Hughes77740fc2016-08-12 15:06:53 -07001255 shf_fprintf(shl_out, Tf_sD_, "internal error");
Geremy Condra03ebf062011-10-12 18:17:24 -07001256 if (flags & VWARNINGF_ERRORPREFIX)
1257 error_prefix(tobool(flags & VWARNINGF_FILELINE));
1258 if ((flags & VWARNINGF_BUILTIN) &&
1259 /* not set when main() calls parse_args() */
1260 builtin_argv0 && builtin_argv0 != kshname)
Elliott Hughes77740fc2016-08-12 15:06:53 -07001261 shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
Geremy Condra03ebf062011-10-12 18:17:24 -07001262 shf_vfprintf(shl_out, fmt, ap);
1263 shf_putchar('\n', shl_out);
1264 }
1265 shf_flush(shl_out);
1266}
1267
1268void
1269errorfx(int rc, const char *fmt, ...)
1270{
1271 va_list va;
1272
1273 exstat = rc;
1274
1275 /* debugging: note that stdout not valid */
1276 shl_stdout_ok = false;
1277
1278 va_start(va, fmt);
1279 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1280 va_end(va);
1281 unwind(LERROR);
1282}
1283
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001284void
1285errorf(const char *fmt, ...)
1286{
1287 va_list va;
1288
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001289 exstat = 1;
Geremy Condra03ebf062011-10-12 18:17:24 -07001290
1291 /* debugging: note that stdout not valid */
1292 shl_stdout_ok = false;
1293
1294 va_start(va, fmt);
1295 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
1296 va_end(va);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001297 unwind(LERROR);
1298}
1299
1300/* like errorf(), but no unwind is done */
1301void
1302warningf(bool fileline, const char *fmt, ...)
1303{
1304 va_list va;
1305
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001306 va_start(va, fmt);
Geremy Condra03ebf062011-10-12 18:17:24 -07001307 vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
1308 fmt, va);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001309 va_end(va);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001310}
1311
Geremy Condra03ebf062011-10-12 18:17:24 -07001312/*
1313 * Used by built-in utilities to prefix shell and utility name to message
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001314 * (also unwinds environments for special builtins).
1315 */
1316void
1317bi_errorf(const char *fmt, ...)
1318{
1319 va_list va;
1320
Geremy Condra03ebf062011-10-12 18:17:24 -07001321 /* debugging: note that stdout not valid */
1322 shl_stdout_ok = false;
1323
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001324 exstat = 1;
Geremy Condra03ebf062011-10-12 18:17:24 -07001325
1326 va_start(va, fmt);
1327 vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
1328 VWARNINGF_BUILTIN, fmt, va);
1329 va_end(va);
1330
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001331 /* POSIX special builtins cause non-interactive shells to exit */
Elliott Hughes50012062015-03-10 22:22:24 -07001332 if (builtin_spec) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001333 builtin_argv0 = NULL;
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001334 /* may not want to use LERROR here */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001335 unwind(LERROR);
1336 }
1337}
1338
1339/* Called when something that shouldn't happen does */
1340void
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001341internal_errorf(const char *fmt, ...)
1342{
1343 va_list va;
1344
1345 va_start(va, fmt);
Geremy Condra03ebf062011-10-12 18:17:24 -07001346 vwarningf(VWARNINGF_INTERNAL, fmt, va);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001347 va_end(va);
1348 unwind(LERROR);
1349}
1350
1351void
1352internal_warningf(const char *fmt, ...)
1353{
1354 va_list va;
1355
1356 va_start(va, fmt);
Geremy Condra03ebf062011-10-12 18:17:24 -07001357 vwarningf(VWARNINGF_INTERNAL, fmt, va);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001358 va_end(va);
1359}
1360
1361/* used by error reporting functions to print "ksh: .kshrc[25]: " */
1362void
1363error_prefix(bool fileline)
1364{
1365 /* Avoid foo: foo[2]: ... */
1366 if (!fileline || !source || !source->file ||
1367 strcmp(source->file, kshname) != 0)
Elliott Hughes77740fc2016-08-12 15:06:53 -07001368 shf_fprintf(shl_out, Tf_sD_, kshname + (*kshname == '-'));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001369 if (fileline && source && source->file != NULL) {
Elliott Hughesb27ce952015-04-21 13:39:18 -07001370 shf_fprintf(shl_out, "%s[%lu]: ", source->file,
1371 (unsigned long)(source->errline ?
1372 source->errline : source->line));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001373 source->errline = 0;
1374 }
1375}
1376
1377/* printf to shl_out (stderr) with flush */
1378void
1379shellf(const char *fmt, ...)
1380{
1381 va_list va;
1382
Geremy Condra03ebf062011-10-12 18:17:24 -07001383 if (!initio_done)
1384 /* shl_out may not be set up yet... */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001385 return;
1386 va_start(va, fmt);
1387 shf_vfprintf(shl_out, fmt, va);
1388 va_end(va);
1389 shf_flush(shl_out);
1390}
1391
1392/* printf to shl_stdout (stdout) */
1393void
1394shprintf(const char *fmt, ...)
1395{
1396 va_list va;
1397
1398 if (!shl_stdout_ok)
1399 internal_errorf("shl_stdout not valid");
1400 va_start(va, fmt);
1401 shf_vfprintf(shl_stdout, fmt, va);
1402 va_end(va);
1403}
1404
1405/* test if we can seek backwards fd (returns 0 or SHF_UNBUF) */
1406int
1407can_seek(int fd)
1408{
1409 struct stat statb;
1410
1411 return (fstat(fd, &statb) == 0 && !S_ISREG(statb.st_mode) ?
1412 SHF_UNBUF : 0);
1413}
1414
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001415#ifdef DF
1416int shl_dbg_fd;
1417#define NSHF_IOB 4
1418#else
1419#define NSHF_IOB 3
1420#endif
1421struct shf shf_iob[NSHF_IOB];
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001422
1423void
1424initio(void)
1425{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001426#ifdef DF
1427 const char *lfp;
1428#endif
1429
Geremy Condra03ebf062011-10-12 18:17:24 -07001430 /* force buffer allocation */
1431 shf_fdopen(1, SHF_WR, shl_stdout);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001432 shf_fdopen(2, SHF_WR, shl_out);
Thorsten Glaser811a5752013-07-25 14:24:45 +00001433 shf_fdopen(2, SHF_WR, shl_xtrace);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001434#ifdef DF
1435 if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
Elliott Hughes96b43632015-07-17 11:39:41 -07001436 if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001437 errorf("can't get home directory");
Elliott Hughes77740fc2016-08-12 15:06:53 -07001438 lfp = shf_smprintf(Tf_sSs, lfp, "mksh-dbg.txt");
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001439 }
1440
1441 if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001442 errorf("can't open debug output file %s", lfp);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001443 if (shl_dbg_fd < FDBASE) {
1444 int nfd;
1445
1446 nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
1447 close(shl_dbg_fd);
1448 if ((shl_dbg_fd = nfd) == -1)
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001449 errorf("can't dup debug output file");
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001450 }
1451 fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
1452 shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
1453 DF("=== open ===");
1454#endif
1455 initio_done = true;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001456}
1457
1458/* A dup2() with error checking */
1459int
1460ksh_dup2(int ofd, int nfd, bool errok)
1461{
1462 int rv;
1463
1464 if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001465 errorf(Ttoo_many_files);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001466
1467#ifdef __ultrix
Geremy Condra03ebf062011-10-12 18:17:24 -07001468 /*XXX imake style */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001469 if (rv >= 0)
1470 fcntl(nfd, F_SETFD, 0);
1471#endif
1472
1473 return (rv);
1474}
1475
1476/*
Geremy Condra03ebf062011-10-12 18:17:24 -07001477 * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
1478 * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001479 */
1480short
1481savefd(int fd)
1482{
1483 int nfd = fd;
1484
1485 if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
Elliott Hughes96b43632015-07-17 11:39:41 -07001486 (errno == EBADF || errno == EPERM))
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001487 return (-1);
1488 if (nfd < 0 || nfd > SHRT_MAX)
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001489 errorf(Ttoo_many_files);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001490 fcntl(nfd, F_SETFD, FD_CLOEXEC);
1491 return ((short)nfd);
1492}
1493
1494void
1495restfd(int fd, int ofd)
1496{
1497 if (fd == 2)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001498 shf_flush(&shf_iob[/* fd */ 2]);
Geremy Condra03ebf062011-10-12 18:17:24 -07001499 if (ofd < 0)
1500 /* original fd closed */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001501 close(fd);
1502 else if (fd != ofd) {
Geremy Condra03ebf062011-10-12 18:17:24 -07001503 /*XXX: what to do if this dup fails? */
1504 ksh_dup2(ofd, fd, true);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001505 close(ofd);
1506 }
1507}
1508
1509void
1510openpipe(int *pv)
1511{
1512 int lpv[2];
1513
1514 if (pipe(lpv) < 0)
1515 errorf("can't create pipe - try again");
1516 pv[0] = savefd(lpv[0]);
1517 if (pv[0] != lpv[0])
1518 close(lpv[0]);
1519 pv[1] = savefd(lpv[1]);
1520 if (pv[1] != lpv[1])
1521 close(lpv[1]);
Elliott Hughesa3c3f962017-04-12 16:52:30 -07001522#ifdef __OS2__
1523 setmode(pv[0], O_BINARY);
1524 setmode(pv[1], O_BINARY);
1525#endif
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001526}
1527
1528void
1529closepipe(int *pv)
1530{
1531 close(pv[0]);
1532 close(pv[1]);
1533}
1534
Geremy Condra03ebf062011-10-12 18:17:24 -07001535/*
1536 * Called by iosetup() (deals with 2>&4, etc.), c_read, c_print to turn
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001537 * a string (the X in 2>&X, read -uX, print -uX) into a file descriptor.
1538 */
1539int
1540check_fd(const char *name, int mode, const char **emsgp)
1541{
Elliott Hughes77740fc2016-08-12 15:06:53 -07001542 int fd, fl;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001543
Elliott Hughes77740fc2016-08-12 15:06:53 -07001544 if (!name[0] || name[1])
1545 goto illegal_fd_name;
1546 if (name[0] == 'p')
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001547 return (coproc_getfd(mode, emsgp));
Elliott Hughes23925bb2017-09-22 16:04:20 -07001548 if (!ctype(name[0], C_DIGIT)) {
Elliott Hughes77740fc2016-08-12 15:06:53 -07001549 illegal_fd_name:
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001550 if (emsgp)
1551 *emsgp = "illegal file descriptor name";
1552 return (-1);
1553 }
Elliott Hughes77740fc2016-08-12 15:06:53 -07001554
1555 if ((fl = fcntl((fd = ksh_numdig(name[0])), F_GETFL, 0)) < 0) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001556 if (emsgp)
1557 *emsgp = "bad file descriptor";
1558 return (-1);
1559 }
1560 fl &= O_ACCMODE;
Geremy Condra03ebf062011-10-12 18:17:24 -07001561 /*
1562 * X_OK is a kludge to disable this check for dups (x<&1):
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001563 * historical shells never did this check (XXX don't know what
1564 * POSIX has to say).
1565 */
1566 if (!(mode & X_OK) && fl != O_RDWR && (
1567 ((mode & R_OK) && fl != O_RDONLY) ||
1568 ((mode & W_OK) && fl != O_WRONLY))) {
1569 if (emsgp)
1570 *emsgp = (fl == O_WRONLY) ?
1571 "fd not open for reading" :
1572 "fd not open for writing";
1573 return (-1);
1574 }
1575 return (fd);
1576}
1577
1578/* Called once from main */
1579void
1580coproc_init(void)
1581{
1582 coproc.read = coproc.readw = coproc.write = -1;
1583 coproc.njobs = 0;
1584 coproc.id = 0;
1585}
1586
1587/* Called by c_read() when eof is read - close fd if it is the co-process fd */
1588void
1589coproc_read_close(int fd)
1590{
1591 if (coproc.read >= 0 && fd == coproc.read) {
1592 coproc_readw_close(fd);
1593 close(coproc.read);
1594 coproc.read = -1;
1595 }
1596}
1597
Geremy Condra03ebf062011-10-12 18:17:24 -07001598/*
1599 * Called by c_read() and by iosetup() to close the other side of the
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001600 * read pipe, so reads will actually terminate.
1601 */
1602void
1603coproc_readw_close(int fd)
1604{
1605 if (coproc.readw >= 0 && coproc.read >= 0 && fd == coproc.read) {
1606 close(coproc.readw);
1607 coproc.readw = -1;
1608 }
1609}
1610
Geremy Condra03ebf062011-10-12 18:17:24 -07001611/*
1612 * Called by c_print when a write to a fd fails with EPIPE and by iosetup
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001613 * when co-process input is dup'd
1614 */
1615void
1616coproc_write_close(int fd)
1617{
1618 if (coproc.write >= 0 && fd == coproc.write) {
1619 close(coproc.write);
1620 coproc.write = -1;
1621 }
1622}
1623
Geremy Condra03ebf062011-10-12 18:17:24 -07001624/*
1625 * Called to check for existence of/value of the co-process file descriptor.
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001626 * (Used by check_fd() and by c_read/c_print to deal with -p option).
1627 */
1628int
1629coproc_getfd(int mode, const char **emsgp)
1630{
1631 int fd = (mode & R_OK) ? coproc.read : coproc.write;
1632
1633 if (fd >= 0)
1634 return (fd);
1635 if (emsgp)
1636 *emsgp = "no coprocess";
1637 return (-1);
1638}
1639
Geremy Condra03ebf062011-10-12 18:17:24 -07001640/*
1641 * called to close file descriptors related to the coprocess (if any)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001642 * Should be called with SIGCHLD blocked.
1643 */
1644void
1645coproc_cleanup(int reuse)
1646{
1647 /* This to allow co-processes to share output pipe */
1648 if (!reuse || coproc.readw < 0 || coproc.read < 0) {
1649 if (coproc.read >= 0) {
1650 close(coproc.read);
1651 coproc.read = -1;
1652 }
1653 if (coproc.readw >= 0) {
1654 close(coproc.readw);
1655 coproc.readw = -1;
1656 }
1657 }
1658 if (coproc.write >= 0) {
1659 close(coproc.write);
1660 coproc.write = -1;
1661 }
1662}
1663
1664struct temp *
1665maketemp(Area *ap, Temp_type type, struct temp **tlist)
1666{
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001667 char *cp;
Geremy Condra03ebf062011-10-12 18:17:24 -07001668 size_t len;
Thorsten Glaser811a5752013-07-25 14:24:45 +00001669 int i, j;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001670 struct temp *tp;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001671 const char *dir;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001672 struct stat sb;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001673
1674 dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001675 /* add "/shXXXXXX.tmp" plus NUL */
1676 len = strlen(dir);
1677 checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
1678 tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001679
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001680 tp->shf = NULL;
1681 tp->pid = procpid;
1682 tp->type = type;
1683
1684 if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
1685 tp->tffn[0] = '\0';
1686 goto maketemp_out;
1687 }
1688
1689 cp = (void *)tp;
1690 cp += offsetof(struct temp, tffn[0]);
1691 memcpy(cp, dir, len);
1692 cp += len;
1693 memcpy(cp, "/shXXXXXX.tmp", 14);
1694 /* point to the first of six Xes */
1695 cp += 3;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001696
1697 /* cyclically attempt to open a temporary file */
Elliott Hughes96b43632015-07-17 11:39:41 -07001698 do {
1699 /* generate random part of filename */
1700 len = 0;
1701 do {
1702 cp[len++] = digits_lc[rndget() % 36];
1703 } while (len < 6);
1704
1705 /* check if this one works */
1706 if ((i = binopen3(tp->tffn, O_CREAT | O_EXCL | O_RDWR,
1707 0600)) < 0 && errno != EEXIST)
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001708 goto maketemp_out;
Elliott Hughes96b43632015-07-17 11:39:41 -07001709 } while (i < 0);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001710
1711 if (type == TT_FUNSUB) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001712 /* map us high and mark as close-on-exec */
Thorsten Glaser811a5752013-07-25 14:24:45 +00001713 if ((j = savefd(i)) != i) {
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001714 close(i);
Thorsten Glaser811a5752013-07-25 14:24:45 +00001715 i = j;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001716 }
Thorsten Glaser811a5752013-07-25 14:24:45 +00001717
1718 /* operation mode for the shf */
1719 j = SHF_RD;
1720 } else
1721 j = SHF_WR;
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001722
1723 /* shf_fdopen cannot fail, so no fd leak */
Thorsten Glaser811a5752013-07-25 14:24:45 +00001724 tp->shf = shf_fdopen(i, j, NULL);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001725
1726 maketemp_out:
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001727 tp->next = *tlist;
1728 *tlist = tp;
1729 return (tp);
1730}
1731
1732/*
1733 * We use a similar collision resolution algorithm as Python 2.5.4
1734 * but with a slightly tweaked implementation written from scratch.
1735 */
1736
Geremy Condra03ebf062011-10-12 18:17:24 -07001737#define INIT_TBLSHIFT 3 /* initial table shift (2^3 = 8) */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001738#define PERTURB_SHIFT 5 /* see Python 2.5.4 Objects/dictobject.c */
1739
Geremy Condra03ebf062011-10-12 18:17:24 -07001740static void tgrow(struct table *);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001741static int tnamecmp(const void *, const void *);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001742
1743static void
Geremy Condra03ebf062011-10-12 18:17:24 -07001744tgrow(struct table *tp)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001745{
Geremy Condra03ebf062011-10-12 18:17:24 -07001746 size_t i, j, osize, mask, perturb;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001747 struct tbl *tblp, **pp;
1748 struct tbl **ntblp, **otblp = tp->tbls;
1749
Geremy Condra03ebf062011-10-12 18:17:24 -07001750 if (tp->tshift > 29)
1751 internal_errorf("hash table size limit reached");
1752
1753 /* calculate old size, new shift and new size */
1754 osize = (size_t)1 << (tp->tshift++);
1755 i = osize << 1;
1756
1757 ntblp = alloc2(i, sizeof(struct tbl *), tp->areap);
1758 /* multiplication cannot overflow: alloc2 checked that */
1759 memset(ntblp, 0, i * sizeof(struct tbl *));
1760
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001761 /* table can get very full when reaching its size limit */
1762 tp->nfree = (tp->tshift == 30) ? 0x3FFF0000UL :
1763 /* but otherwise, only 75% */
1764 ((i * 3) / 4);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001765 tp->tbls = ntblp;
1766 if (otblp == NULL)
1767 return;
Geremy Condra03ebf062011-10-12 18:17:24 -07001768
1769 mask = i - 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001770 for (i = 0; i < osize; i++)
1771 if ((tblp = otblp[i]) != NULL) {
1772 if ((tblp->flag & DEFINED)) {
1773 /* search for free hash table slot */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001774 j = perturb = tblp->ua.hval;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001775 goto find_first_empty_slot;
1776 find_next_empty_slot:
1777 j = (j << 2) + j + perturb + 1;
1778 perturb >>= PERTURB_SHIFT;
1779 find_first_empty_slot:
Geremy Condra03ebf062011-10-12 18:17:24 -07001780 pp = &ntblp[j & mask];
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001781 if (*pp != NULL)
1782 goto find_next_empty_slot;
1783 /* found an empty hash table slot */
1784 *pp = tblp;
1785 tp->nfree--;
1786 } else if (!(tblp->flag & FINUSE)) {
1787 afree(tblp, tp->areap);
1788 }
1789 }
1790 afree(otblp, tp->areap);
1791}
1792
1793void
Geremy Condra03ebf062011-10-12 18:17:24 -07001794ktinit(Area *ap, struct table *tp, uint8_t initshift)
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001795{
1796 tp->areap = ap;
1797 tp->tbls = NULL;
Geremy Condra03ebf062011-10-12 18:17:24 -07001798 tp->tshift = ((initshift > INIT_TBLSHIFT) ?
1799 initshift : INIT_TBLSHIFT) - 1;
1800 tgrow(tp);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001801}
1802
1803/* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
Geremy Condra03ebf062011-10-12 18:17:24 -07001804struct tbl *
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001805ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
1806{
1807 size_t j, perturb, mask;
1808 struct tbl **pp, *p;
1809
Geremy Condra03ebf062011-10-12 18:17:24 -07001810 mask = ((size_t)1 << (tp->tshift)) - 1;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001811 /* search for hash table slot matching name */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001812 j = perturb = h;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001813 goto find_first_slot;
1814 find_next_slot:
1815 j = (j << 2) + j + perturb + 1;
1816 perturb >>= PERTURB_SHIFT;
1817 find_first_slot:
1818 pp = &tp->tbls[j & mask];
1819 if ((p = *pp) != NULL && (p->ua.hval != h || !(p->flag & DEFINED) ||
1820 strcmp(p->name, name)))
1821 goto find_next_slot;
1822 /* p == NULL if not found, correct found entry otherwise */
1823 if (ppp)
1824 *ppp = pp;
1825 return (p);
1826}
1827
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001828/* table, name (key) to enter, hash(n) */
1829struct tbl *
1830ktenter(struct table *tp, const char *n, uint32_t h)
1831{
1832 struct tbl **pp, *p;
Geremy Condra03ebf062011-10-12 18:17:24 -07001833 size_t len;
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001834
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001835 Search:
1836 if ((p = ktscan(tp, n, h, &pp)))
1837 return (p);
1838
Geremy Condra03ebf062011-10-12 18:17:24 -07001839 if (tp->nfree == 0) {
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001840 /* too full */
Geremy Condra03ebf062011-10-12 18:17:24 -07001841 tgrow(tp);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001842 goto Search;
1843 }
1844
1845 /* create new tbl entry */
Geremy Condra03ebf062011-10-12 18:17:24 -07001846 len = strlen(n);
1847 checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
1848 p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001849 p->flag = 0;
1850 p->type = 0;
1851 p->areap = tp->areap;
1852 p->ua.hval = h;
1853 p->u2.field = 0;
1854 p->u.array = NULL;
1855 memcpy(p->name, n, len);
1856
1857 /* enter in tp->tbls */
1858 tp->nfree--;
1859 *pp = p;
1860 return (p);
1861}
1862
1863void
1864ktwalk(struct tstate *ts, struct table *tp)
1865{
Geremy Condra03ebf062011-10-12 18:17:24 -07001866 ts->left = (size_t)1 << (tp->tshift);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001867 ts->next = tp->tbls;
1868}
1869
1870struct tbl *
1871ktnext(struct tstate *ts)
1872{
1873 while (--ts->left >= 0) {
1874 struct tbl *p = *ts->next++;
1875 if (p != NULL && (p->flag & DEFINED))
1876 return (p);
1877 }
1878 return (NULL);
1879}
1880
1881static int
1882tnamecmp(const void *p1, const void *p2)
1883{
1884 const struct tbl *a = *((const struct tbl * const *)p1);
1885 const struct tbl *b = *((const struct tbl * const *)p2);
1886
Elliott Hughes23925bb2017-09-22 16:04:20 -07001887 return (ascstrcmp(a->name, b->name));
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001888}
1889
1890struct tbl **
1891ktsort(struct table *tp)
1892{
1893 size_t i;
1894 struct tbl **p, **sp, **dp;
1895
Geremy Condra03ebf062011-10-12 18:17:24 -07001896 /*
1897 * since the table is never entirely full, no need to reserve
1898 * additional space for the trailing NULL appended below
1899 */
1900 i = (size_t)1 << (tp->tshift);
1901 p = alloc2(i, sizeof(struct tbl *), ATEMP);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001902 sp = tp->tbls; /* source */
1903 dp = p; /* dest */
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001904 while (i--)
1905 if ((*dp = *sp++) != NULL && (((*dp)->flag & DEFINED) ||
1906 ((*dp)->flag & ARRAY)))
1907 dp++;
Geremy Condra03ebf062011-10-12 18:17:24 -07001908 qsort(p, (i = dp - p), sizeof(struct tbl *), tnamecmp);
Jean-Baptiste Queru5155f1c2011-06-16 10:05:28 -07001909 p[i] = NULL;
1910 return (p);
1911}
1912
1913#ifdef SIGWINCH
1914static void
1915x_sigwinch(int sig MKSH_A_UNUSED)
1916{
1917 /* this runs inside interrupt context, with errno saved */
1918
1919 got_winch = 1;
1920}
1921#endif
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001922
1923#ifdef DF
1924void
1925DF(const char *fmt, ...)
1926{
1927 va_list args;
1928 struct timeval tv;
1929 mirtime_mjd mjd;
1930
1931 mksh_lockfd(shl_dbg_fd);
1932 mksh_TIME(tv);
1933 timet2mjd(&mjd, tv.tv_sec);
1934 shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
1935 (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
1936 (unsigned)mjd.sec % 60, (unsigned)getpid(),
1937 (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
1938 va_start(args, fmt);
1939 shf_vfprintf(shl_dbg, fmt, args);
1940 va_end(args);
1941 shf_putc('\n', shl_dbg);
1942 shf_flush(shl_dbg);
1943 mksh_unlkfd(shl_dbg_fd);
1944}
1945#endif
1946
1947void
1948x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
1949{
1950 mksh_ttyst cb;
1951
1952 if (ocb)
1953 mksh_tcget(fd, ocb);
1954 else
1955 ocb = &tty_state;
1956
1957 cb = *ocb;
1958 if (forread) {
Elliott Hughes737fdce2014-08-07 12:59:26 -07001959 cb.c_iflag &= ~(ISTRIP);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001960 cb.c_lflag &= ~(ICANON) | ECHO;
1961 } else {
Elliott Hughes737fdce2014-08-07 12:59:26 -07001962 cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001963 cb.c_lflag &= ~(ISIG | ICANON | ECHO);
1964 }
1965#if defined(VLNEXT) && defined(_POSIX_VDISABLE)
1966 /* OSF/1 processes lnext when ~icanon */
1967 cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
1968#endif
Elliott Hughes47086262019-03-26 12:34:31 -07001969 /* SunOS 4.1.x and OSF/1 process discard(flush) when ~icanon */
Thorsten Glaserc2dc5de2013-02-18 23:02:51 +00001970#if defined(VDISCARD) && defined(_POSIX_VDISABLE)
1971 cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
1972#endif
1973 cb.c_cc[VTIME] = 0;
1974 cb.c_cc[VMIN] = 1;
1975
1976 mksh_tcset(fd, &cb);
1977}
Elliott Hughesdd4abe02018-02-05 15:55:19 -08001978
1979#ifdef MKSH_ENVDIR
1980static void
1981init_environ(void)
1982{
1983 char *xp;
1984 ssize_t n;
1985 XString xs;
1986 struct shf *shf;
1987 DIR *dirp;
1988 struct dirent *dent;
1989
1990 if ((dirp = opendir(MKSH_ENVDIR)) == NULL) {
1991 warningf(false, "cannot read environment from %s: %s",
1992 MKSH_ENVDIR, cstrerror(errno));
1993 return;
1994 }
1995 XinitN(xs, 256, ATEMP);
1996 read_envfile:
1997 errno = 0;
1998 if ((dent = readdir(dirp)) != NULL) {
1999 if (skip_varname(dent->d_name, true)[0] == '\0') {
2000 xp = shf_smprintf(Tf_sSs, MKSH_ENVDIR, dent->d_name);
2001 if (!(shf = shf_open(xp, O_RDONLY, 0, 0))) {
2002 warningf(false,
2003 "cannot read environment %s from %s: %s",
2004 dent->d_name, MKSH_ENVDIR,
2005 cstrerror(errno));
2006 goto read_envfile;
2007 }
2008 afree(xp, ATEMP);
2009 n = strlen(dent->d_name);
2010 xp = Xstring(xs, xp);
2011 XcheckN(xs, xp, n + 32);
2012 memcpy(xp, dent->d_name, n);
2013 xp += n;
2014 *xp++ = '=';
2015 while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
2016 xp += n;
2017 if (Xnleft(xs, xp) <= 0)
2018 XcheckN(xs, xp, Xlength(xs, xp));
2019 }
2020 if (n < 0) {
2021 warningf(false,
2022 "cannot read environment %s from %s: %s",
2023 dent->d_name, MKSH_ENVDIR,
2024 cstrerror(shf_errno(shf)));
2025 } else {
2026 *xp = '\0';
2027 xp = Xstring(xs, xp);
2028 rndpush(xp);
2029 typeset(xp, IMPORT | EXPORT, 0, 0, 0);
2030 }
2031 shf_close(shf);
2032 }
2033 goto read_envfile;
2034 } else if (errno)
2035 warningf(false, "cannot read environment from %s: %s",
2036 MKSH_ENVDIR, cstrerror(errno));
2037 closedir(dirp);
2038 Xfree(xs, xp);
2039}
2040#else
2041extern char **environ;
2042
2043static void
2044init_environ(void)
2045{
2046 const char **wp;
2047
2048 if (environ == NULL)
2049 return;
2050
2051 wp = (const char **)environ;
2052 while (*wp != NULL) {
2053 rndpush(*wp);
2054 typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
2055 ++wp;
2056 }
2057}
2058#endif
2059
2060#ifdef MKSH_EARLY_LOCALE_TRACKING
2061void
2062recheck_ctype(void)
2063{
2064 const char *ccp;
Elliott Hughes47086262019-03-26 12:34:31 -07002065 uint8_t old_utfmode = UTFMODE;
Elliott Hughesdd4abe02018-02-05 15:55:19 -08002066
2067 ccp = str_val(global("LC_ALL"));
2068 if (ccp == null)
2069 ccp = str_val(global("LC_CTYPE"));
2070 if (ccp == null)
2071 ccp = str_val(global("LANG"));
2072 UTFMODE = isuc(ccp);
2073#if HAVE_SETLOCALE_CTYPE
2074 ccp = setlocale(LC_CTYPE, ccp);
2075#if HAVE_LANGINFO_CODESET
2076 if (!isuc(ccp))
2077 ccp = nl_langinfo(CODESET);
2078#endif
2079 if (isuc(ccp))
2080 UTFMODE = 1;
2081#endif
2082
Elliott Hughes47086262019-03-26 12:34:31 -07002083 if (Flag(FPOSIX) && UTFMODE && !old_utfmode)
Elliott Hughesdd4abe02018-02-05 15:55:19 -08002084 warningf(true, "early locale tracking enabled UTF-8 mode while in POSIX mode, you are now noncompliant");
2085}
2086#endif