1 /*	$OpenBSD: sh.h,v 1.35 2015/09/10 22:48:58 nicm Exp $	*/
2 /*	$OpenBSD: shf.h,v 1.6 2005/12/11 18:53:51 deraadt Exp $	*/
3 /*	$OpenBSD: table.h,v 1.8 2012/02/19 07:52:30 otto Exp $	*/
4 /*	$OpenBSD: tree.h,v 1.10 2005/03/28 21:28:22 deraadt Exp $	*/
5 /*	$OpenBSD: expand.h,v 1.7 2015/09/01 13:12:31 tedu Exp $	*/
6 /*	$OpenBSD: lex.h,v 1.13 2013/03/03 19:11:34 guenther Exp $	*/
7 /*	$OpenBSD: proto.h,v 1.35 2013/09/04 15:49:19 millert Exp $	*/
8 /*	$OpenBSD: c_test.h,v 1.4 2004/12/20 11:34:26 otto Exp $	*/
9 /*	$OpenBSD: tty.h,v 1.5 2004/12/20 11:34:26 otto Exp $	*/
10 
11 /*-
12  * Copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
13  *	       2011, 2012, 2013, 2014, 2015, 2016
14  *	mirabilos <m@mirbsd.org>
15  *
16  * Provided that these terms and disclaimer and all copyright notices
17  * are retained or reproduced in an accompanying document, permission
18  * is granted to deal in this work without restriction, including un‐
19  * limited rights to use, publicly perform, distribute, sell, modify,
20  * merge, give away, or sublicence.
21  *
22  * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
23  * the utmost extent permitted by applicable law, neither express nor
24  * implied; without malicious intent or gross negligence. In no event
25  * may a licensor, author or contributor be held liable for indirect,
26  * direct, other damage, loss, or other issues arising in any way out
27  * of dealing in the work, even if advised of the possibility of such
28  * damage or existence of a defect, except proven that it results out
29  * of said person’s immediate fault when using the work as intended.
30  */
31 
32 #ifdef __dietlibc__
33 /* XXX imake style */
34 #define _BSD_SOURCE	/* live, BSD, live❣ */
35 #endif
36 
37 #if HAVE_SYS_PARAM_H
38 #include <sys/param.h>
39 #endif
40 #include <sys/types.h>
41 #if HAVE_BOTH_TIME_H
42 #include <sys/time.h>
43 #include <time.h>
44 #elif HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #elif HAVE_TIME_H
47 #include <time.h>
48 #endif
49 #include <sys/ioctl.h>
50 #if HAVE_SYS_SYSMACROS_H
51 #include <sys/sysmacros.h>
52 #endif
53 #if HAVE_SYS_MKDEV_H
54 #include <sys/mkdev.h>
55 #endif
56 #if HAVE_SYS_MMAN_H
57 #include <sys/mman.h>
58 #endif
59 #if HAVE_SYS_RESOURCE_H
60 #include <sys/resource.h>
61 #endif
62 #include <sys/stat.h>
63 #include <sys/wait.h>
64 #include <dirent.h>
65 #include <errno.h>
66 #include <fcntl.h>
67 #if HAVE_IO_H
68 #include <io.h>
69 #endif
70 #if HAVE_LIBGEN_H
71 #include <libgen.h>
72 #endif
73 #if HAVE_LIBUTIL_H
74 #include <libutil.h>
75 #endif
76 #include <limits.h>
77 #if HAVE_PATHS_H
78 #include <paths.h>
79 #endif
80 #include <pwd.h>
81 #include <setjmp.h>
82 #include <signal.h>
83 #include <stdarg.h>
84 #include <stddef.h>
85 #if HAVE_STDINT_H
86 #include <stdint.h>
87 #endif
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #if HAVE_STRINGS_H
92 #include <strings.h>
93 #endif
94 #if HAVE_TERMIOS_H
95 #include <termios.h>
96 #else
97 /* shudder… */
98 #include <termio.h>
99 #endif
100 #ifdef _ISC_UNIX
101 /* XXX imake style */
102 #include <sys/sioctl.h>
103 #endif
104 #if HAVE_ULIMIT_H
105 #include <ulimit.h>
106 #endif
107 #include <unistd.h>
108 #if HAVE_VALUES_H
109 #include <values.h>
110 #endif
111 #ifdef MIRBSD_BOOTFLOPPY
112 #include <wchar.h>
113 #endif
114 
115 #undef __attribute__
116 #if HAVE_ATTRIBUTE_BOUNDED
117 #define MKSH_A_BOUNDED(x,y,z)	__attribute__((__bounded__(x, y, z)))
118 #else
119 #define MKSH_A_BOUNDED(x,y,z)	/* nothing */
120 #endif
121 #if HAVE_ATTRIBUTE_FORMAT
122 #define MKSH_A_FORMAT(x,y,z)	__attribute__((__format__(x, y, z)))
123 #else
124 #define MKSH_A_FORMAT(x,y,z)	/* nothing */
125 #endif
126 #if HAVE_ATTRIBUTE_NORETURN
127 #define MKSH_A_NORETURN		__attribute__((__noreturn__))
128 #else
129 #define MKSH_A_NORETURN		/* nothing */
130 #endif
131 #if HAVE_ATTRIBUTE_PURE
132 #define MKSH_A_PURE		__attribute__((__pure__))
133 #else
134 #define MKSH_A_PURE		/* nothing */
135 #endif
136 #if HAVE_ATTRIBUTE_UNUSED
137 #define MKSH_A_UNUSED		__attribute__((__unused__))
138 #else
139 #define MKSH_A_UNUSED		/* nothing */
140 #endif
141 #if HAVE_ATTRIBUTE_USED
142 #define MKSH_A_USED		__attribute__((__used__))
143 #else
144 #define MKSH_A_USED		/* nothing */
145 #endif
146 
147 #if defined(MirBSD) && (MirBSD >= 0x09A1) && \
148     defined(__ELF__) && defined(__GNUC__) && \
149     !defined(__llvm__) && !defined(__NWCC__)
150 /*
151  * We got usable __IDSTRING __COPYRIGHT __RCSID __SCCSID macros
152  * which work for all cases; no need to redefine them using the
153  * "portable" macros from below when we might have the "better"
154  * gcc+ELF specific macros or other system dependent ones.
155  */
156 #else
157 #undef __IDSTRING
158 #undef __IDSTRING_CONCAT
159 #undef __IDSTRING_EXPAND
160 #undef __COPYRIGHT
161 #undef __RCSID
162 #undef __SCCSID
163 #define __IDSTRING_CONCAT(l,p)		__LINTED__ ## l ## _ ## p
164 #define __IDSTRING_EXPAND(l,p)		__IDSTRING_CONCAT(l,p)
165 #ifdef MKSH_DONT_EMIT_IDSTRING
166 #define __IDSTRING(prefix, string)	/* nothing */
167 #else
168 #define __IDSTRING(prefix, string)				\
169 	static const char __IDSTRING_EXPAND(__LINE__,prefix) []	\
170 	    MKSH_A_USED = "@(""#)" #prefix ": " string
171 #endif
172 #define __COPYRIGHT(x)		__IDSTRING(copyright,x)
173 #define __RCSID(x)		__IDSTRING(rcsid,x)
174 #define __SCCSID(x)		__IDSTRING(sccsid,x)
175 #endif
176 
177 #ifdef EXTERN
178 __RCSID("$MirOS: src/bin/mksh/sh.h,v 1.791 2016/11/11 23:31:38 tg Exp $");
179 #endif
180 #define MKSH_VERSION "R54 2016/11/11"
181 
182 /* arithmetic types: C implementation */
183 #if !HAVE_CAN_INTTYPES
184 #if !HAVE_CAN_UCBINTS
185 typedef signed int int32_t;
186 typedef unsigned int uint32_t;
187 #else
188 typedef u_int32_t uint32_t;
189 #endif
190 #endif
191 
192 /* arithmetic types: shell arithmetics */
193 #ifdef MKSH_LEGACY_MODE
194 /*
195  * POSIX demands these to be the C environment's long type
196  */
197 typedef long mksh_ari_t;
198 typedef unsigned long mksh_uari_t;
199 #else
200 /*
201  * These types are exactly 32 bit wide; signed and unsigned
202  * integer wraparound, even across division and modulo, for
203  * any shell code using them, is guaranteed.
204  */
205 typedef int32_t mksh_ari_t;
206 typedef uint32_t mksh_uari_t;
207 #endif
208 
209 /* boolean type (no <stdbool.h> deliberately) */
210 typedef unsigned char mksh_bool;
211 #undef bool
212 /* false MUST equal the same 0 as written by static storage initialisation */
213 #undef false
214 #undef true
215 /* access macros for boolean type */
216 #define bool		mksh_bool
217 /* values must have identity mapping between mksh_bool and short */
218 #define false		0
219 #define true		1
220 /* make any-type into bool or short */
221 #define tobool(cond)	((cond) ? true : false)
222 
223 /* char (octet) type: C implementation */
224 #if !HAVE_CAN_INT8TYPE
225 #if !HAVE_CAN_UCBINT8
226 typedef unsigned char uint8_t;
227 #else
228 typedef u_int8_t uint8_t;
229 #endif
230 #endif
231 
232 /* other standard types */
233 
234 #if !HAVE_RLIM_T
235 typedef unsigned long rlim_t;
236 #endif
237 
238 #if !HAVE_SIG_T
239 #undef sig_t
240 typedef void (*sig_t)(int);
241 #endif
242 
243 #ifdef MKSH_TYPEDEF_SIG_ATOMIC_T
244 typedef MKSH_TYPEDEF_SIG_ATOMIC_T sig_atomic_t;
245 #endif
246 
247 #ifdef MKSH_TYPEDEF_SSIZE_T
248 typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
249 #endif
250 
251 /* un-do vendor damage */
252 
253 #undef BAD		/* AIX defines that somewhere */
254 #undef PRINT		/* LynxOS defines that somewhere */
255 #undef flock		/* SCO UnixWare defines that to flock64 but ENOENT */
256 
257 
258 #ifndef MKSH_INCLUDES_ONLY
259 
260 /* extra types */
261 
262 /* getrusage does not exist on OS/2 kLIBC */
263 #if !HAVE_GETRUSAGE && !defined(__OS2__)
264 #undef rusage
265 #undef RUSAGE_SELF
266 #undef RUSAGE_CHILDREN
267 #define rusage mksh_rusage
268 #define RUSAGE_SELF		0
269 #define RUSAGE_CHILDREN		-1
270 
271 struct rusage {
272 	struct timeval ru_utime;
273 	struct timeval ru_stime;
274 };
275 #endif
276 
277 /* extra macros */
278 
279 #ifndef timerclear
280 #define timerclear(tvp)							\
281 	do {								\
282 		(tvp)->tv_sec = (tvp)->tv_usec = 0;			\
283 	} while (/* CONSTCOND */ 0)
284 #endif
285 #ifndef timeradd
286 #define timeradd(tvp, uvp, vvp)						\
287 	do {								\
288 		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
289 		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;	\
290 		if ((vvp)->tv_usec >= 1000000) {			\
291 			(vvp)->tv_sec++;				\
292 			(vvp)->tv_usec -= 1000000;			\
293 		}							\
294 	} while (/* CONSTCOND */ 0)
295 #endif
296 #ifndef timersub
297 #define timersub(tvp, uvp, vvp)						\
298 	do {								\
299 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
300 		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
301 		if ((vvp)->tv_usec < 0) {				\
302 			(vvp)->tv_sec--;				\
303 			(vvp)->tv_usec += 1000000;			\
304 		}							\
305 	} while (/* CONSTCOND */ 0)
306 #endif
307 
308 #ifdef MKSH__NO_PATH_MAX
309 #undef PATH_MAX
310 #else
311 #ifndef PATH_MAX
312 #ifdef MAXPATHLEN
313 #define PATH_MAX	MAXPATHLEN
314 #else
315 #define PATH_MAX	1024
316 #endif
317 #endif
318 #endif
319 #ifndef SIZE_MAX
320 #ifdef SIZE_T_MAX
321 #define SIZE_MAX	SIZE_T_MAX
322 #else
323 #define SIZE_MAX	((size_t)-1)
324 #endif
325 #endif
326 #ifndef S_ISLNK
327 #define S_ISLNK(m)	((m & 0170000) == 0120000)
328 #endif
329 #ifndef S_ISSOCK
330 #define S_ISSOCK(m)	((m & 0170000) == 0140000)
331 #endif
332 #if !defined(S_ISCDF) && defined(S_CDF)
333 #define S_ISCDF(m)	(S_ISDIR(m) && ((m) & S_CDF))
334 #endif
335 #ifndef DEFFILEMODE
336 #define DEFFILEMODE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
337 #endif
338 
339 
340 /* determine ksh_NSIG: first, use the traditional definitions */
341 #undef ksh_NSIG
342 #if defined(NSIG)
343 #define ksh_NSIG (NSIG)
344 #elif defined(_NSIG)
345 #define ksh_NSIG (_NSIG)
346 #elif defined(SIGMAX)
347 #define ksh_NSIG (SIGMAX + 1)
348 #elif defined(_SIGMAX)
349 #define ksh_NSIG (_SIGMAX + 1)
350 #elif defined(NSIG_MAX)
351 #define ksh_NSIG (NSIG_MAX)
352 #else
353 # error Please have your platform define NSIG.
354 #endif
355 /* range-check them */
356 #if (ksh_NSIG < 1)
357 # error Your NSIG value is not positive.
358 #undef ksh_NSIG
359 #endif
360 /* second, see if the new POSIX definition is available */
361 #ifdef NSIG_MAX
362 #if (NSIG_MAX < 2)
363 /* and usable */
364 # error Your NSIG_MAX value is too small.
365 #undef NSIG_MAX
366 #elif (ksh_NSIG > NSIG_MAX)
367 /* and realistic */
368 # error Your NSIG value is larger than your NSIG_MAX value.
369 #undef NSIG_MAX
370 #else
371 /* since it’s usable, prefer it */
372 #undef ksh_NSIG
373 #define ksh_NSIG (NSIG_MAX)
374 #endif
375 /* if NSIG_MAX is now still defined, use sysconf(_SC_NSIG) at runtime */
376 #endif
377 /* third, for cpp without the error directive, default */
378 #ifndef ksh_NSIG
379 #define ksh_NSIG 64
380 #endif
381 
382 #define ksh_sigmask(sig) (((sig) < 1 || (sig) > 127) ? 255 : 128 + (sig))
383 
384 
385 /* OS-dependent additions (functions, variables, by OS) */
386 
387 #ifdef MKSH_EXE_EXT
388 #undef MKSH_EXE_EXT
389 #define MKSH_EXE_EXT	".exe"
390 #else
391 #define MKSH_EXE_EXT	""
392 #endif
393 
394 #ifdef __OS2__
395 #define MKSH_PATHSEPS	";"
396 #define MKSH_PATHSEPC	';'
397 #define MKSH_UNIXROOT	"/@unixroot"
398 #else
399 #define MKSH_PATHSEPS	":"
400 #define MKSH_PATHSEPC	':'
401 #define MKSH_UNIXROOT	""
402 #endif
403 
404 #if !HAVE_FLOCK_DECL
405 extern int flock(int, int);
406 #endif
407 
408 #if !HAVE_GETTIMEOFDAY
409 #define mksh_TIME(tv) do {		\
410 	(tv).tv_usec = 0;		\
411 	(tv).tv_sec = time(NULL);	\
412 } while (/* CONSTCOND */ 0)
413 #else
414 #define mksh_TIME(tv) gettimeofday(&(tv), NULL)
415 #endif
416 
417 #if !HAVE_GETRUSAGE
418 extern int getrusage(int, struct rusage *);
419 #endif
420 
421 #if !HAVE_MEMMOVE
422 /* we assume either memmove or bcopy exist, at the moment */
423 #define memmove(dst, src, len)	bcopy((src), (dst), (len))
424 #endif
425 
426 #if !HAVE_REVOKE_DECL
427 extern int revoke(const char *);
428 #endif
429 
430 #if defined(DEBUG) || !HAVE_STRERROR
431 #undef strerror
432 #define strerror		/* poisoned */ dontuse_strerror
433 #define cstrerror		/* replaced */ cstrerror
434 extern const char *cstrerror(int);
435 #else
436 #define cstrerror(errnum)	((const char *)strerror(errnum))
437 #endif
438 
439 #if !HAVE_STRLCPY
440 size_t strlcpy(char *, const char *, size_t);
441 #endif
442 
443 #ifdef __INTERIX
444 /* XXX imake style */
445 #define makedev mkdev
446 extern int __cdecl seteuid(uid_t);
447 extern int __cdecl setegid(gid_t);
448 #endif
449 
450 #if defined(__COHERENT__)
451 #ifndef O_ACCMODE
452 /* this need not work everywhere, take care */
453 #define O_ACCMODE	(O_RDONLY | O_WRONLY | O_RDWR)
454 #endif
455 #endif
456 
457 #ifndef O_BINARY
458 #define O_BINARY	0
459 #endif
460 
461 #ifdef MKSH__NO_SYMLINK
462 #undef S_ISLNK
463 #define S_ISLNK(m)	(/* CONSTCOND */ 0)
464 #define mksh_lstat	stat
465 #else
466 #define mksh_lstat	lstat
467 #endif
468 
469 #if HAVE_TERMIOS_H
470 #define mksh_ttyst	struct termios
471 #define mksh_tcget(fd,st) tcgetattr((fd), (st))
472 #define mksh_tcset(fd,st) tcsetattr((fd), TCSADRAIN, (st))
473 #else
474 #define mksh_ttyst	struct termio
475 #define mksh_tcget(fd,st) ioctl((fd), TCGETA, (st))
476 #define mksh_tcset(fd,st) ioctl((fd), TCSETAW, (st))
477 #endif
478 
479 #ifndef ISTRIP
480 #define ISTRIP		0
481 #endif
482 
483 
484 /* some useful #defines */
485 #ifdef EXTERN
486 # define E_INIT(i) = i
487 #else
488 # define E_INIT(i)
489 # define EXTERN extern
490 # define EXTERN_DEFINED
491 #endif
492 
493 /* define bit in flag */
494 #define BIT(i)		(1 << (i))
495 #define NELEM(a)	(sizeof(a) / sizeof((a)[0]))
496 
497 /*
498  * Make MAGIC a char that might be printed to make bugs more obvious, but
499  * not a char that is used often. Also, can't use the high bit as it causes
500  * portability problems (calling strchr(x, 0x80 | 'x') is error prone).
501  */
502 #define MAGIC		(7)	/* prefix for *?[!{,} during expand */
503 #define ISMAGIC(c)	((unsigned char)(c) == MAGIC)
504 
505 EXTERN const char *safe_prompt; /* safe prompt if PS1 substitution fails */
506 
507 #ifdef MKSH_LEGACY_MODE
508 #define KSH_VERSIONNAME	"LEGACY"
509 #else
510 #define KSH_VERSIONNAME	"MIRBSD"
511 #endif
512 EXTERN const char initvsn[] E_INIT("KSH_VERSION=@(#)" KSH_VERSIONNAME \
513     " KSH " MKSH_VERSION);
514 #define KSH_VERSION	(initvsn + /* "KSH_VERSION=@(#)" */ 16)
515 
516 EXTERN const char digits_uc[] E_INIT("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
517 EXTERN const char digits_lc[] E_INIT("0123456789abcdefghijklmnopqrstuvwxyz");
518 #define letters_uc (digits_uc + 10)
519 #define letters_lc (digits_lc + 10)
520 
521 /*
522  * Evil hack for const correctness due to API brokenness
523  */
524 union mksh_cchack {
525 	char *rw;
526 	const char *ro;
527 };
528 union mksh_ccphack {
529 	char **rw;
530 	const char **ro;
531 };
532 
533 /*
534  * Evil hack since casting uint to sint is implementation-defined
535  */
536 typedef union {
537 	mksh_ari_t i;
538 	mksh_uari_t u;
539 } mksh_ari_u;
540 
541 /* for const debugging */
542 #if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
543     !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
544 char *ucstrchr(char *, int);
545 char *ucstrstr(char *, const char *);
546 #undef strchr
547 #define strchr ucstrchr
548 #define strstr ucstrstr
549 #define cstrchr(s,c) ({			\
550 	union mksh_cchack in, out;	\
551 					\
552 	in.ro = (s);			\
553 	out.rw = ucstrchr(in.rw, (c));	\
554 	(out.ro);			\
555 })
556 #define cstrstr(b,l) ({			\
557 	union mksh_cchack in, out;	\
558 					\
559 	in.ro = (b);			\
560 	out.rw = ucstrstr(in.rw, (l));	\
561 	(out.ro);			\
562 })
563 #define vstrchr(s,c)	(cstrchr((s), (c)) != NULL)
564 #define vstrstr(b,l)	(cstrstr((b), (l)) != NULL)
565 #else /* !DEBUG, !gcc */
566 #define cstrchr(s,c)	((const char *)strchr((s), (c)))
567 #define cstrstr(s,c)	((const char *)strstr((s), (c)))
568 #define vstrchr(s,c)	(strchr((s), (c)) != NULL)
569 #define vstrstr(b,l)	(strstr((b), (l)) != NULL)
570 #endif
571 
572 #if defined(DEBUG) || defined(__COVERITY__)
573 #define mkssert(e)	do { if (!(e)) exit(255); } while (/* CONSTCOND */ 0)
574 #ifndef DEBUG_LEAKS
575 #define DEBUG_LEAKS
576 #endif
577 #else
578 #define mkssert(e)	do { } while (/* CONSTCOND */ 0)
579 #endif
580 
581 #if (!defined(MKSH_BUILDMAKEFILE4BSD) && !defined(MKSH_BUILDSH)) || (MKSH_BUILD_R != 541)
582 #error Must run Build.sh to compile this.
583 extern void thiswillneverbedefinedIhope(void);
584 int
im_sorry_dave(void)585 im_sorry_dave(void)
586 {
587 	/* I’m sorry, Dave. I’m afraid I can’t do that. */
588 	return (thiswillneverbedefinedIhope());
589 }
590 #endif
591 
592 /* use this ipv strchr(s, 0) but no side effects in s! */
593 #define strnul(s)	((s) + strlen(s))
594 
595 #define utf_ptradjx(src, dst) do {					\
596 	(dst) = (src) + utf_ptradj(src);				\
597 } while (/* CONSTCOND */ 0)
598 
599 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
600 #define strdupx(d, s, ap) do {						\
601 	(d) = strdup_i((s), (ap));					\
602 } while (/* CONSTCOND */ 0)
603 #define strndupx(d, s, n, ap) do {					\
604 	(d) = strndup_i((s), (n), (ap));				\
605 } while (/* CONSTCOND */ 0)
606 #else
607 /* be careful to evaluate arguments only once! */
608 #define strdupx(d, s, ap) do {						\
609 	const char *strdup_src = (s);					\
610 	char *strdup_dst = NULL;					\
611 									\
612 	if (strdup_src != NULL) {					\
613 		size_t strdup_len = strlen(strdup_src) + 1;		\
614 		strdup_dst = alloc(strdup_len, (ap));			\
615 		memcpy(strdup_dst, strdup_src, strdup_len);		\
616 	}								\
617 	(d) = strdup_dst;						\
618 } while (/* CONSTCOND */ 0)
619 #define strndupx(d, s, n, ap) do {					\
620 	const char *strdup_src = (s);					\
621 	char *strdup_dst = NULL;					\
622 									\
623 	if (strdup_src != NULL) {					\
624 		size_t strndup_len = (n);				\
625 		strdup_dst = alloc(strndup_len + 1, (ap));		\
626 		memcpy(strdup_dst, strdup_src, strndup_len);		\
627 		strdup_dst[strndup_len] = '\0';				\
628 	}								\
629 	(d) = strdup_dst;						\
630 } while (/* CONSTCOND */ 0)
631 #endif
632 
633 #ifdef MKSH_LEGACY_MODE
634 #ifndef MKSH_NO_CMDLINE_EDITING
635 #define MKSH_NO_CMDLINE_EDITING	/* defined */
636 #endif
637 #undef MKSH_S_NOVI
638 #define MKSH_S_NOVI		1
639 #endif
640 
641 #ifdef MKSH_SMALL
642 #ifndef MKSH_NOPWNAM
643 #define MKSH_NOPWNAM		/* defined */
644 #endif
645 #ifndef MKSH_S_NOVI
646 #define MKSH_S_NOVI		1
647 #endif
648 #endif
649 
650 #ifndef MKSH_S_NOVI
651 #define MKSH_S_NOVI		0
652 #endif
653 
654 #if defined(MKSH_NOPROSPECTOFWORK) && !defined(MKSH_UNEMPLOYED)
655 #define MKSH_UNEMPLOYED		1
656 #endif
657 
658 #define NUFILE		32	/* Number of user-accessible files */
659 #define FDBASE		10	/* First file usable by Shell */
660 
661 /*
662  * simple grouping allocator
663  */
664 
665 
666 /* 0. OS API: where to get memory from and how to free it (grouped) */
667 
668 /* malloc(3)/realloc(3) -> free(3) for use by the memory allocator */
669 #define malloc_osi(sz)		malloc(sz)
670 #define realloc_osi(p,sz)	realloc((p), (sz))
671 #define free_osimalloc(p)	free(p)
672 
673 /* malloc(3)/realloc(3) -> free(3) for use by mksh code */
674 #define malloc_osfunc(sz)	malloc(sz)
675 #define realloc_osfunc(p,sz)	realloc((p), (sz))
676 #define free_osfunc(p)		free(p)
677 
678 #if HAVE_MKNOD
679 /* setmode(3) -> free(3) */
680 #define free_ossetmode(p)	free(p)
681 #endif
682 
683 #ifdef MKSH__NO_PATH_MAX
684 /* GNU libc: get_current_dir_name(3) -> free(3) */
685 #define free_gnu_gcdn(p)	free(p)
686 #endif
687 
688 
689 /* 1. internal structure */
690 struct lalloc_common {
691 	struct lalloc_common *next;
692 };
693 
694 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
695 struct lalloc_item {
696 	struct lalloc_common *next;
697 	size_t len;
698 	char dummy[8192 - sizeof(struct lalloc_common *) - sizeof(size_t)];
699 };
700 #endif
701 
702 /* 2. sizes */
703 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
704 #define ALLOC_ITEM	struct lalloc_item
705 #define ALLOC_OVERHEAD	0
706 #else
707 #define ALLOC_ITEM	struct lalloc_common
708 #define ALLOC_OVERHEAD	(sizeof(ALLOC_ITEM))
709 #endif
710 
711 /* 3. group structure */
712 typedef struct lalloc_common Area;
713 
714 
715 EXTERN Area aperm;		/* permanent object space */
716 #define APERM	&aperm
717 #define ATEMP	&e->area
718 
719 /*
720  * flags (the order of these enums MUST match the order in misc.c(options[]))
721  */
722 enum sh_flag {
723 #define SHFLAGS_ENUMS
724 #include "sh_flags.gen"
725 	FNFLAGS		/* (place holder: how many flags are there) */
726 };
727 
728 #define Flag(f)	(shell_flags[(int)(f)])
729 #define UTFMODE	Flag(FUNICODE)
730 
731 /*
732  * parsing & execution environment
733  *
734  * note that kshlongjmp MUST NOT be passed 0 as second argument!
735  */
736 #ifdef MKSH_NO_SIGSETJMP
737 #define kshjmp_buf	jmp_buf
738 #define kshsetjmp(jbuf)	_setjmp(jbuf)
739 #define kshlongjmp	_longjmp
740 #else
741 #define kshjmp_buf	sigjmp_buf
742 #define kshsetjmp(jbuf)	sigsetjmp((jbuf), 0)
743 #define kshlongjmp	siglongjmp
744 #endif
745 
746 struct sretrace_info;
747 struct yyrecursive_state;
748 
749 EXTERN struct sretrace_info *retrace_info E_INIT(NULL);
750 EXTERN int subshell_nesting_type E_INIT(0);
751 
752 extern struct env {
753 	ALLOC_ITEM alloc_INT;	/* internal, do not touch */
754 	Area area;		/* temporary allocation area */
755 	struct env *oenv;	/* link to previous environment */
756 	struct block *loc;	/* local variables and functions */
757 	short *savefd;		/* original redirected fds */
758 	struct temp *temps;	/* temp files */
759 	/* saved parser recursion state */
760 	struct yyrecursive_state *yyrecursive_statep;
761 	kshjmp_buf jbuf;	/* long jump back to env creator */
762 	uint8_t type;		/* environment type - see below */
763 	uint8_t flags;		/* EF_* */
764 } *e;
765 
766 /* struct env.type values */
767 #define E_NONE	0	/* dummy environment */
768 #define E_PARSE	1	/* parsing command # */
769 #define E_FUNC	2	/* executing function # */
770 #define E_INCL	3	/* including a file via . # */
771 #define E_EXEC	4	/* executing command tree */
772 #define E_LOOP	5	/* executing for/while # */
773 #define E_ERRH	6	/* general error handler # */
774 #define E_GONE	7	/* hidden in child */
775 /* # indicates env has valid jbuf (see unwind()) */
776 
777 /* struct env.flag values */
778 #define EF_BRKCONT_PASS	BIT(1)	/* set if E_LOOP must pass break/continue on */
779 #define EF_FAKE_SIGDIE	BIT(2)	/* hack to get info from unwind to quitenv */
780 
781 /* Do breaks/continues stop at env type e? */
782 #define STOP_BRKCONT(t)	((t) == E_NONE || (t) == E_PARSE || \
783 			    (t) == E_FUNC || (t) == E_INCL)
784 /* Do returns stop at env type e? */
785 #define STOP_RETURN(t)	((t) == E_FUNC || (t) == E_INCL)
786 
787 /* values for kshlongjmp(e->jbuf, i) */
788 /* note that i MUST NOT be zero */
789 #define LRETURN	1	/* return statement */
790 #define LEXIT	2	/* exit statement */
791 #define LERROR	3	/* errorf() called */
792 #define LLEAVE	4	/* untrappable exit/error */
793 #define LINTR	5	/* ^C noticed */
794 #define LBREAK	6	/* break statement */
795 #define LCONTIN	7	/* continue statement */
796 #define LSHELL	8	/* return to interactive shell() */
797 #define LAEXPR	9	/* error in arithmetic expression */
798 
799 /* sort of shell global state */
800 EXTERN pid_t procpid;		/* PID of executing process */
801 EXTERN int exstat;		/* exit status */
802 EXTERN int subst_exstat;	/* exit status of last $(..)/`..` */
803 EXTERN struct tbl *vp_pipest;	/* global PIPESTATUS array */
804 EXTERN short trap_exstat;	/* exit status before running a trap */
805 EXTERN uint8_t trap_nested;	/* running nested traps */
806 EXTERN uint8_t shell_flags[FNFLAGS];
807 EXTERN const char *kshname;	/* $0 */
808 EXTERN struct {
809 	uid_t kshuid_v;		/* real UID of shell */
810 	uid_t ksheuid_v;	/* effective UID of shell */
811 	gid_t kshgid_v;		/* real GID of shell */
812 	gid_t kshegid_v;	/* effective GID of shell */
813 	pid_t kshpgrp_v;	/* process group of shell */
814 	pid_t kshppid_v;	/* PID of parent of shell */
815 	pid_t kshpid_v;		/* $$, shell PID */
816 } rndsetupstate;
817 
818 #define kshpid		rndsetupstate.kshpid_v
819 #define kshpgrp		rndsetupstate.kshpgrp_v
820 #define kshuid		rndsetupstate.kshuid_v
821 #define ksheuid		rndsetupstate.ksheuid_v
822 #define kshgid		rndsetupstate.kshgid_v
823 #define kshegid		rndsetupstate.kshegid_v
824 #define kshppid		rndsetupstate.kshppid_v
825 
826 
827 /* option processing */
828 #define OF_CMDLINE	0x01	/* command line */
829 #define OF_SET		0x02	/* set builtin */
830 #define OF_SPECIAL	0x04	/* a special variable changing */
831 #define OF_INTERNAL	0x08	/* set internally by shell */
832 #define OF_FIRSTTIME	0x10	/* as early as possible, once */
833 #define OF_ANY		(OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
834 
835 /* null value for variable; comparison pointer for unset */
836 EXTERN char null[] E_INIT("");
837 
838 /* string pooling: do we rely on the compiler? */
839 #ifndef HAVE_STRING_POOLING
840 /* no, we use our own, saves quite some space */
841 #elif HAVE_STRING_POOLING == 2
842 /* “on demand” */
843 #ifdef __GNUC__
844 /* only for GCC 4 or later, older ones can get by without */
845 #if __GNUC__ < 4
846 #undef HAVE_STRING_POOLING
847 #endif
848 #else
849 /* not GCC, default to on */
850 #endif
851 #elif HAVE_STRING_POOLING == 0
852 /* default to on, unless explicitly set to 0 */
853 #undef HAVE_STRING_POOLING
854 #endif
855 
856 #ifndef HAVE_STRING_POOLING /* helpers for pooled strings */
857 EXTERN const char T4spaces[] E_INIT("    ");
858 #define T1space (T4spaces + 3)
859 EXTERN const char Tcolsp[] E_INIT(": ");
860 EXTERN const char TC_LEX1[] E_INIT("|&;<>() \t\n");
861 #define TC_IFSWS (TC_LEX1 + 7)
862 EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} $_");
863 #define Tspdollaru (TFCEDIT_dollaru + 18)
864 EXTERN const char Tsgdot[] E_INIT("*=.");
865 EXTERN const char Taugo[] E_INIT("augo");
866 EXTERN const char Tbracket[] E_INIT("[");
867 #define Tdot (Tsgdot + 2)
868 EXTERN const char Talias[] E_INIT("alias");
869 EXTERN const char Tbadsubst[] E_INIT("bad substitution");
870 EXTERN const char Tbg[] E_INIT("bg");
871 EXTERN const char Tbad_bsize[] E_INIT("bad shf/buf/bsize");
872 #define Tbsize (Tbad_bsize + 12)
873 EXTERN const char Tbad_sig_ss[] E_INIT("%s: bad signal '%s'");
874 #define Tbad_sig_s (Tbad_sig_ss + 4)
875 EXTERN const char Tgbuiltin[] E_INIT("=builtin");
876 #define Tbuiltin (Tgbuiltin + 1)
877 EXTERN const char Toomem[] E_INIT("can't allocate %zu data bytes");
878 EXTERN const char Tcant_cd[] E_INIT("restricted shell - can't cd");
879 EXTERN const char Tcant_find[] E_INIT("can't find");
880 EXTERN const char Tcant_open[] E_INIT("can't open");
881 #define Tbytes (Toomem + 24)
882 EXTERN const char Tbcat[] E_INIT("!cat");
883 #define Tcat (Tbcat + 1)
884 #define Tcd (Tcant_cd + 25)
885 EXTERN const char Tcommand[] E_INIT("command");
886 EXTERN const char Tcreate[] E_INIT("create");
887 EXTERN const char TELIF_unexpected[] E_INIT("TELIF unexpected");
888 EXTERN const char TEXECSHELL[] E_INIT("EXECSHELL");
889 EXTERN const char Tsgexport[] E_INIT("*=export");
890 #define Texport (Tsgexport + 2)
891 #ifdef __OS2__
892 EXTERN const char Textproc[] E_INIT("extproc");
893 #endif
894 EXTERN const char Tfalse[] E_INIT("false");
895 EXTERN const char Tfg[] E_INIT("fg");
896 EXTERN const char Tfg_badsubst[] E_INIT("fileglob: bad substitution");
897 EXTERN const char Tfile[] E_INIT("file");
898 EXTERN const char Tfile_fd[] E_INIT("function definition file");
899 EXTERN const char TFPATH[] E_INIT("FPATH");
900 EXTERN const char T_function[] E_INIT(" function");
901 #define Tfunction (T_function + 1)
902 EXTERN const char T_funny_command[] E_INIT("funny $() command");
903 EXTERN const char Tgetopts[] E_INIT("getopts");
904 EXTERN const char Thistory[] E_INIT("history");
905 EXTERN const char Tintovfl[] E_INIT("integer overflow %zu %c %zu prevented");
906 EXTERN const char Tjobs[] E_INIT("jobs");
907 EXTERN const char Tjob_not_started[] E_INIT("job not started");
908 EXTERN const char Tmksh[] E_INIT("mksh");
909 EXTERN const char Tname[] E_INIT("name");
910 EXTERN const char Tno_args[] E_INIT("missing argument");
911 EXTERN const char Tno_OLDPWD[] E_INIT("no OLDPWD");
912 EXTERN const char Tnot_ident[] E_INIT("is not an identifier");
913 EXTERN const char Tnot_in_history[] E_INIT("not in history");
914 EXTERN const char Tnot_found_s[] E_INIT("%s not found");
915 #define Tnot_found (Tnot_found_s + 3)
916 #define Tnot_started (Tjob_not_started + 4)
917 #define TOLDPWD (Tno_OLDPWD + 3)
918 #define Topen (Tcant_open + 6)
919 #define TPATH (TFPATH + 1)
920 EXTERN const char Tpv[] E_INIT("pv");
921 EXTERN const char TpVv[] E_INIT("Vpv");
922 #define TPWD (Tno_OLDPWD + 6)
923 EXTERN const char Tread[] E_INIT("read");
924 EXTERN const char Tsgreadonly[] E_INIT("*=readonly");
925 #define Treadonly (Tsgreadonly + 2)
926 EXTERN const char Tredirection_dup[] E_INIT("can't finish (dup) redirection");
927 #define Tredirection (Tredirection_dup + 19)
928 EXTERN const char Treal_sp1[] E_INIT("real ");
929 EXTERN const char Treal_sp2[] E_INIT(" real ");
930 EXTERN const char Treq_arg[] E_INIT("requires an argument");
931 EXTERN const char Tselect[] E_INIT("select");
932 EXTERN const char Tsgset[] E_INIT("*=set");
933 #define Tset (Tsgset + 2)
934 #define Tsh (Tmksh + 2)
935 #define TSHELL (TEXECSHELL + 4)
936 EXTERN const char Tshf_read[] E_INIT("shf_read");
937 EXTERN const char Tshf_write[] E_INIT("shf_write");
938 EXTERN const char Tj_suspend[] E_INIT("j_suspend");
939 #define Tsuspend (Tj_suspend + 2)
940 EXTERN const char Tsynerr[] E_INIT("syntax error");
941 EXTERN const char Ttime[] E_INIT("time");
942 EXTERN const char Ttoo_many_args[] E_INIT("too many arguments");
943 EXTERN const char Ttrue[] E_INIT("true");
944 EXTERN const char Ttty_fd_dupof[] E_INIT("dup of tty fd");
945 #define Ttty_fd (Ttty_fd_dupof + 7)
946 EXTERN const char Tgtypeset[] E_INIT("=typeset");
947 #define Ttypeset (Tgtypeset + 1)
948 #define Tugo (Taugo + 1)
949 EXTERN const char Tunalias[] E_INIT("unalias");
950 #define Tunexpected (TELIF_unexpected + 6)
951 EXTERN const char Tunknown_option[] E_INIT("unknown option");
952 EXTERN const char Tuser_sp1[] E_INIT("user ");
953 EXTERN const char Tuser_sp2[] E_INIT(" user ");
954 #define Twrite (Tshf_write + 4)
955 EXTERN const char Tf__S[] E_INIT(" %S");
956 EXTERN const char Tf__d[] E_INIT(" %d");
957 EXTERN const char Tf__ss[] E_INIT(" %s%s");
958 EXTERN const char Tf__sN[] E_INIT(" %s\n");
959 EXTERN const char Tf_sSs[] E_INIT("%s/%s");
960 EXTERN const char Tf_T[] E_INIT("%T");
961 EXTERN const char Tf_dN[] E_INIT("%d\n");
962 EXTERN const char Tf_s_[] E_INIT("%s ");
963 EXTERN const char Tf_s_T[] E_INIT("%s %T");
964 EXTERN const char Tf_s_s_sN[] E_INIT("%s %s %s\n");
965 EXTERN const char Tf_s_s[] E_INIT("%s %s");
966 EXTERN const char Tf_s_sD_s[] E_INIT("%s %s: %s");
967 EXTERN const char Tf_optfoo[] E_INIT("%s%s-%c: %s");
968 EXTERN const char Tf_sD_[] E_INIT("%s: ");
969 EXTERN const char Tf_szs[] E_INIT("%s: %zd %s");
970 EXTERN const char Tf_parm[] E_INIT("%s: parameter not set");
971 EXTERN const char Tf_coproc[] E_INIT("-p: %s");
972 EXTERN const char Tf_cant[] E_INIT("can't %s %s: %s");
973 EXTERN const char Tf_heredoc[] E_INIT("here document '%s' unclosed\n");
974 #if HAVE_MKNOD
975 EXTERN const char Tf_nonnum[] E_INIT("non-numeric %s %s '%s'");
976 #endif
977 EXTERN const char Tf_S_[] E_INIT("%S ");
978 #define Tf_S (Tf__S + 1)
979 EXTERN const char Tf_lu[] E_INIT("%lu");
980 EXTERN const char Tf_toolarge[] E_INIT("%s %s too large: %lu");
981 EXTERN const char Tf_ldfailed[] E_INIT("%s %s(%d, %ld) failed: %s");
982 #define Tf_ss (Tf__ss + 1)
983 EXTERN const char Tf_sss[] E_INIT("%s%s%s");
984 EXTERN const char Tf_sD_s_sD_s[] E_INIT("%s: %s %s: %s");
985 EXTERN const char Tf_toomany[] E_INIT("too many %ss\n");
986 EXTERN const char Tf_sd[] E_INIT("%s %d");
987 #define Tf_s (Tf__ss + 3)
988 EXTERN const char Tft_end[] E_INIT("%;");
989 EXTERN const char Tft_R[] E_INIT("%R");
990 #define Tf_d (Tf__d + 1)
991 EXTERN const char Tf_sD_s_qs[] E_INIT("%s: %s '%s'");
992 EXTERN const char Tf_ro[] E_INIT("read-only: %s");
993 EXTERN const char Tf_flags[] E_INIT("%s: flags 0x%X");
994 EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s: %s");
995 EXTERN const char Tf_ssfaileds[] E_INIT("%s: %s failed: %s");
996 EXTERN const char Tf_sD_sD_s[] E_INIT("%s: %s: %s");
997 EXTERN const char Tf__c_[] E_INIT("-%c ");
998 EXTERN const char Tf_sD_s_s[] E_INIT("%s: %s %s");
999 #define Tf_sN (Tf__sN + 1)
1000 #define Tf_sD_s (Tf_s_sD_s + 3)
1001 EXTERN const char T_devtty[] E_INIT("/dev/tty");
1002 #else /* helpers for string pooling */
1003 #define T4spaces "    "
1004 #define T1space " "
1005 #define Tcolsp ": "
1006 #define TC_LEX1 "|&;<>() \t\n"
1007 #define TC_IFSWS " \t\n"
1008 #define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} $_"
1009 #define Tspdollaru " $_"
1010 #define Tsgdot "*=."
1011 #define Taugo "augo"
1012 #define Tbracket "["
1013 #define Tdot "."
1014 #define Talias "alias"
1015 #define Tbadsubst "bad substitution"
1016 #define Tbg "bg"
1017 #define Tbad_bsize "bad shf/buf/bsize"
1018 #define Tbsize "bsize"
1019 #define Tbad_sig_ss "%s: bad signal '%s'"
1020 #define Tbad_sig_s "bad signal '%s'"
1021 #define Tgbuiltin "=builtin"
1022 #define Tbuiltin "builtin"
1023 #define Toomem "can't allocate %zu data bytes"
1024 #define Tcant_cd "restricted shell - can't cd"
1025 #define Tcant_find "can't find"
1026 #define Tcant_open "can't open"
1027 #define Tbytes "bytes"
1028 #define Tbcat "!cat"
1029 #define Tcat "cat"
1030 #define Tcd "cd"
1031 #define Tcommand "command"
1032 #define Tcreate "create"
1033 #define TELIF_unexpected "TELIF unexpected"
1034 #define TEXECSHELL "EXECSHELL"
1035 #define Tsgexport "*=export"
1036 #define Texport "export"
1037 #ifdef __OS2__
1038 #define Textproc "extproc"
1039 #endif
1040 #define Tfalse "false"
1041 #define Tfg "fg"
1042 #define Tfg_badsubst "fileglob: bad substitution"
1043 #define Tfile "file"
1044 #define Tfile_fd "function definition file"
1045 #define TFPATH "FPATH"
1046 #define T_function " function"
1047 #define Tfunction "function"
1048 #define T_funny_command "funny $() command"
1049 #define Tgetopts "getopts"
1050 #define Thistory "history"
1051 #define Tintovfl "integer overflow %zu %c %zu prevented"
1052 #define Tjobs "jobs"
1053 #define Tjob_not_started "job not started"
1054 #define Tmksh "mksh"
1055 #define Tname "name"
1056 #define Tno_args "missing argument"
1057 #define Tno_OLDPWD "no OLDPWD"
1058 #define Tnot_ident "is not an identifier"
1059 #define Tnot_in_history "not in history"
1060 #define Tnot_found_s "%s not found"
1061 #define Tnot_found "not found"
1062 #define Tnot_started "not started"
1063 #define TOLDPWD "OLDPWD"
1064 #define Topen "open"
1065 #define TPATH "PATH"
1066 #define Tpv "pv"
1067 #define TpVv "Vpv"
1068 #define TPWD "PWD"
1069 #define Tread "read"
1070 #define Tsgreadonly "*=readonly"
1071 #define Treadonly "readonly"
1072 #define Tredirection_dup "can't finish (dup) redirection"
1073 #define Tredirection "redirection"
1074 #define Treal_sp1 "real "
1075 #define Treal_sp2 " real "
1076 #define Treq_arg "requires an argument"
1077 #define Tselect "select"
1078 #define Tsgset "*=set"
1079 #define Tset "set"
1080 #define Tsh "sh"
1081 #define TSHELL "SHELL"
1082 #define Tshf_read "shf_read"
1083 #define Tshf_write "shf_write"
1084 #define Tj_suspend "j_suspend"
1085 #define Tsuspend "suspend"
1086 #define Tsynerr "syntax error"
1087 #define Ttime "time"
1088 #define Ttoo_many_args "too many arguments"
1089 #define Ttrue "true"
1090 #define Ttty_fd_dupof "dup of tty fd"
1091 #define Ttty_fd "tty fd"
1092 #define Tgtypeset "=typeset"
1093 #define Ttypeset "typeset"
1094 #define Tugo "ugo"
1095 #define Tunalias "unalias"
1096 #define Tunexpected "unexpected"
1097 #define Tunknown_option "unknown option"
1098 #define Tuser_sp1 "user "
1099 #define Tuser_sp2 " user "
1100 #define Twrite "write"
1101 #define Tf__S " %S"
1102 #define Tf__d " %d"
1103 #define Tf__ss " %s%s"
1104 #define Tf__sN " %s\n"
1105 #define Tf_sSs "%s/%s"
1106 #define Tf_T "%T"
1107 #define Tf_dN "%d\n"
1108 #define Tf_s_ "%s "
1109 #define Tf_s_T "%s %T"
1110 #define Tf_s_s_sN "%s %s %s\n"
1111 #define Tf_s_s "%s %s"
1112 #define Tf_s_sD_s "%s %s: %s"
1113 #define Tf_optfoo "%s%s-%c: %s"
1114 #define Tf_sD_ "%s: "
1115 #define Tf_szs "%s: %zd %s"
1116 #define Tf_parm "%s: parameter not set"
1117 #define Tf_coproc "-p: %s"
1118 #define Tf_cant "can't %s %s: %s"
1119 #define Tf_heredoc "here document '%s' unclosed\n"
1120 #if HAVE_MKNOD
1121 #define Tf_nonnum "non-numeric %s %s '%s'"
1122 #endif
1123 #define Tf_S_ "%S "
1124 #define Tf_S "%S"
1125 #define Tf_lu "%lu"
1126 #define Tf_toolarge "%s %s too large: %lu"
1127 #define Tf_ldfailed "%s %s(%d, %ld) failed: %s"
1128 #define Tf_ss "%s%s"
1129 #define Tf_sss "%s%s%s"
1130 #define Tf_sD_s_sD_s "%s: %s %s: %s"
1131 #define Tf_toomany "too many %ss\n"
1132 #define Tf_sd "%s %d"
1133 #define Tf_s "%s"
1134 #define Tft_end "%;"
1135 #define Tft_R "%R"
1136 #define Tf_d "%d"
1137 #define Tf_sD_s_qs "%s: %s '%s'"
1138 #define Tf_ro "read-only: %s"
1139 #define Tf_flags "%s: flags 0x%X"
1140 #define Tf_temp "can't %s temporary file %s: %s"
1141 #define Tf_ssfaileds "%s: %s failed: %s"
1142 #define Tf_sD_sD_s "%s: %s: %s"
1143 #define Tf__c_ "-%c "
1144 #define Tf_sD_s_s "%s: %s %s"
1145 #define Tf_sN "%s\n"
1146 #define Tf_sD_s "%s: %s"
1147 #define T_devtty "/dev/tty"
1148 #endif /* end of string pooling */
1149 
1150 typedef uint8_t Temp_type;
1151 /* expanded heredoc */
1152 #define TT_HEREDOC_EXP	0
1153 /* temporary file used for history editing (fc -e) */
1154 #define TT_HIST_EDIT	1
1155 /* temporary file used during in-situ command substitution */
1156 #define TT_FUNSUB	2
1157 
1158 /* temp/heredoc files. The file is removed when the struct is freed. */
1159 struct temp {
1160 	struct temp *next;
1161 	struct shf *shf;
1162 	/* pid of process parsed here-doc */
1163 	pid_t pid;
1164 	Temp_type type;
1165 	/* actually longer: name (variable length) */
1166 	char tffn[3];
1167 };
1168 
1169 /*
1170  * stdio and our IO routines
1171  */
1172 
1173 #define shl_xtrace	(&shf_iob[0])	/* for set -x */
1174 #define shl_stdout	(&shf_iob[1])
1175 #define shl_out		(&shf_iob[2])
1176 #ifdef DF
1177 #define shl_dbg		(&shf_iob[3])	/* for DF() */
1178 #endif
1179 EXTERN bool shl_stdout_ok;
1180 
1181 /*
1182  * trap handlers
1183  */
1184 typedef struct trap {
1185 	const char *name;	/* short name */
1186 	const char *mess;	/* descriptive name */
1187 	char *trap;		/* trap command */
1188 	sig_t cursig;		/* current handler (valid if TF_ORIG_* set) */
1189 	sig_t shtrap;		/* shell signal handler */
1190 	int signal;		/* signal number */
1191 	int flags;		/* TF_* */
1192 	volatile sig_atomic_t set; /* trap pending */
1193 } Trap;
1194 
1195 /* values for Trap.flags */
1196 #define TF_SHELL_USES	BIT(0)	/* shell uses signal, user can't change */
1197 #define TF_USER_SET	BIT(1)	/* user has (tried to) set trap */
1198 #define TF_ORIG_IGN	BIT(2)	/* original action was SIG_IGN */
1199 #define TF_ORIG_DFL	BIT(3)	/* original action was SIG_DFL */
1200 #define TF_EXEC_IGN	BIT(4)	/* restore SIG_IGN just before exec */
1201 #define TF_EXEC_DFL	BIT(5)	/* restore SIG_DFL just before exec */
1202 #define TF_DFL_INTR	BIT(6)	/* when received, default action is LINTR */
1203 #define TF_TTY_INTR	BIT(7)	/* tty generated signal (see j_waitj) */
1204 #define TF_CHANGED	BIT(8)	/* used by runtrap() to detect trap changes */
1205 #define TF_FATAL	BIT(9)	/* causes termination if not trapped */
1206 
1207 /* values for setsig()/setexecsig() flags argument */
1208 #define SS_RESTORE_MASK	0x3	/* how to restore a signal before an exec() */
1209 #define SS_RESTORE_CURR	0	/* leave current handler in place */
1210 #define SS_RESTORE_ORIG	1	/* restore original handler */
1211 #define SS_RESTORE_DFL	2	/* restore to SIG_DFL */
1212 #define SS_RESTORE_IGN	3	/* restore to SIG_IGN */
1213 #define SS_FORCE	BIT(3)	/* set signal even if original signal ignored */
1214 #define SS_USER		BIT(4)	/* user is doing the set (ie, trap command) */
1215 #define SS_SHTRAP	BIT(5)	/* trap for internal use (ALRM, CHLD, WINCH) */
1216 
1217 #define ksh_SIGEXIT 0		/* for trap EXIT */
1218 #define ksh_SIGERR  ksh_NSIG	/* for trap ERR */
1219 
1220 EXTERN volatile sig_atomic_t trap;	/* traps pending? */
1221 EXTERN volatile sig_atomic_t intrsig;	/* pending trap interrupts command */
1222 EXTERN volatile sig_atomic_t fatal_trap; /* received a fatal signal */
1223 extern Trap sigtraps[ksh_NSIG + 1];
1224 
1225 /* got_winch = 1 when we need to re-adjust the window size */
1226 #ifdef SIGWINCH
1227 EXTERN volatile sig_atomic_t got_winch E_INIT(1);
1228 #else
1229 #define got_winch	true
1230 #endif
1231 
1232 /*
1233  * TMOUT support
1234  */
1235 /* values for ksh_tmout_state */
1236 enum tmout_enum {
1237 	TMOUT_EXECUTING = 0,	/* executing commands */
1238 	TMOUT_READING,		/* waiting for input */
1239 	TMOUT_LEAVING		/* have timed out */
1240 };
1241 EXTERN unsigned int ksh_tmout;
1242 EXTERN enum tmout_enum ksh_tmout_state E_INIT(TMOUT_EXECUTING);
1243 
1244 /* For "You have stopped jobs" message */
1245 EXTERN bool really_exit;
1246 
1247 /*
1248  * fast character classes
1249  */
1250 #define C_ALPHA	 BIT(0)		/* a-z_A-Z */
1251 #define C_DIGIT	 BIT(1)		/* 0-9 */
1252 #define C_LEX1	 BIT(2)		/* \t \n\0|&;<>() */
1253 #define C_VAR1	 BIT(3)		/* *@#!$-? */
1254 #define C_IFSWS	 BIT(4)		/* \t \n (IFS white space) */
1255 #define C_SUBOP1 BIT(5)		/* "=-+?" */
1256 #define C_QUOTE	 BIT(6)		/* \t\n "#$&'()*;<=>?[\]`| (needing quoting) */
1257 #define C_IFS	 BIT(7)		/* $IFS */
1258 #define C_SUBOP2 BIT(8)		/* "#%" (magic, see below) */
1259 
1260 extern unsigned char chtypes[];
1261 
1262 #define ctype(c, t)	tobool( ((t) == C_SUBOP2) ?			\
1263 			    (((c) == '#' || (c) == '%') ? 1 : 0) :	\
1264 			    (chtypes[(unsigned char)(c)] & (t)) )
1265 #define ord(c)		((int)(unsigned char)(c))
1266 #define ksh_isalphx(c)	ctype((c), C_ALPHA)
1267 #define ksh_isalnux(c)	ctype((c), C_ALPHA | C_DIGIT)
1268 #define ksh_isdigit(c)	(((c) >= '0') && ((c) <= '9'))
1269 #define ksh_islower(c)	(((c) >= 'a') && ((c) <= 'z'))
1270 #define ksh_isupper(c)	(((c) >= 'A') && ((c) <= 'Z'))
1271 #define ksh_tolower(c)	(ksh_isupper(c) ? (c) - 'A' + 'a' : (c))
1272 #define ksh_toupper(c)	(ksh_islower(c) ? (c) - 'a' + 'A' : (c))
1273 #define ksh_isdash(s)	(((s)[0] == '-') && ((s)[1] == '\0'))
1274 #define ksh_isspace(c)	((((c) >= 0x09) && ((c) <= 0x0D)) || ((c) == 0x20))
1275 #define ksh_eq(c,u,l)	(((c) | 0x20) == (l))
1276 #define ksh_numdig(c)	((c) - ord('0'))
1277 #define ksh_numuc(c)	((c) - ord('A'))
1278 #define ksh_numlc(c)	((c) - ord('a'))
1279 
1280 EXTERN int ifs0 E_INIT(' ');	/* for "$*" */
1281 
1282 /* Argument parsing for built-in commands and getopts command */
1283 
1284 /* Values for Getopt.flags */
1285 #define GF_ERROR	BIT(0)	/* call errorf() if there is an error */
1286 #define GF_PLUSOPT	BIT(1)	/* allow +c as an option */
1287 #define GF_NONAME	BIT(2)	/* don't print argv[0] in errors */
1288 
1289 /* Values for Getopt.info */
1290 #define GI_MINUS	BIT(0)	/* an option started with -... */
1291 #define GI_PLUS		BIT(1)	/* an option started with +... */
1292 #define GI_MINUSMINUS	BIT(2)	/* arguments were ended with -- */
1293 
1294 /* in case some OS defines these */
1295 #undef optarg
1296 #undef optind
1297 
1298 typedef struct {
1299 	const char *optarg;
1300 	int optind;
1301 	int uoptind;		/* what user sees in $OPTIND */
1302 	int flags;		/* see GF_* */
1303 	int info;		/* see GI_* */
1304 	unsigned int p;		/* 0 or index into argv[optind - 1] */
1305 	char buf[2];		/* for bad option OPTARG value */
1306 } Getopt;
1307 
1308 EXTERN Getopt builtin_opt;	/* for shell builtin commands */
1309 EXTERN Getopt user_opt;		/* parsing state for getopts builtin command */
1310 
1311 /* This for co-processes */
1312 
1313 /* something that won't (realisticly) wrap */
1314 typedef int Coproc_id;
1315 
1316 struct coproc {
1317 	void *job;	/* 0 or job of co-process using input pipe */
1318 	int read;	/* pipe from co-process's stdout */
1319 	int readw;	/* other side of read (saved temporarily) */
1320 	int write;	/* pipe to co-process's stdin */
1321 	int njobs;	/* number of live jobs using output pipe */
1322 	Coproc_id id;	/* id of current output pipe */
1323 };
1324 EXTERN struct coproc coproc;
1325 
1326 #ifndef MKSH_NOPROSPECTOFWORK
1327 /* used in jobs.c and by coprocess stuff in exec.c and select() calls */
1328 EXTERN sigset_t		sm_default, sm_sigchld;
1329 #endif
1330 
1331 /* name of called builtin function (used by error functions) */
1332 EXTERN const char *builtin_argv0;
1333 /* is called builtin SPEC_BI? (also KEEPASN, odd use though) */
1334 EXTERN bool builtin_spec;
1335 
1336 /* current working directory */
1337 EXTERN char	*current_wd;
1338 
1339 /* input line size */
1340 #ifdef MKSH_SMALL
1341 #define LINE		(4096 - ALLOC_OVERHEAD)
1342 #else
1343 #define LINE		(16384 - ALLOC_OVERHEAD)
1344 #endif
1345 /* columns and lines of the tty */
1346 EXTERN mksh_ari_t x_cols E_INIT(80);
1347 EXTERN mksh_ari_t x_lins E_INIT(24);
1348 
1349 
1350 /* Determine the location of the system (common) profile */
1351 
1352 #ifndef MKSH_DEFAULT_PROFILEDIR
1353 #define MKSH_DEFAULT_PROFILEDIR	MKSH_UNIXROOT "/etc"
1354 #endif
1355 
1356 #define MKSH_SYSTEM_PROFILE	MKSH_DEFAULT_PROFILEDIR "/profile"
1357 #define MKSH_SUID_PROFILE	MKSH_DEFAULT_PROFILEDIR "/suid_profile"
1358 
1359 
1360 /* Used by v_evaluate() and setstr() to control action when error occurs */
1361 #define KSH_UNWIND_ERROR	0	/* unwind the stack (kshlongjmp) */
1362 #define KSH_RETURN_ERROR	1	/* return 1/0 for success/failure */
1363 
1364 /*
1365  * Shell file I/O routines
1366  */
1367 
1368 #define SHF_BSIZE		512
1369 
1370 #define shf_fileno(shf)		((shf)->fd)
1371 #define shf_setfileno(shf,nfd)	((shf)->fd = (nfd))
1372 #define shf_getc_i(shf)		((shf)->rnleft > 0 ? \
1373 				    (shf)->rnleft--, *(shf)->rp++ : \
1374 				    shf_getchar(shf))
1375 #define shf_putc_i(c, shf)	((shf)->wnleft == 0 ? \
1376 				    shf_putchar((uint8_t)(c), (shf)) : \
1377 				    ((shf)->wnleft--, *(shf)->wp++ = (c)))
1378 #define shf_eof(shf)		((shf)->flags & SHF_EOF)
1379 #define shf_error(shf)		((shf)->flags & SHF_ERROR)
1380 #define shf_errno(shf)		((shf)->errnosv)
1381 #define shf_clearerr(shf)	((shf)->flags &= ~(SHF_EOF | SHF_ERROR))
1382 
1383 /* Flags passed to shf_*open() */
1384 #define SHF_RD		0x0001
1385 #define SHF_WR		0x0002
1386 #define SHF_RDWR	(SHF_RD|SHF_WR)
1387 #define SHF_ACCMODE	0x0003		/* mask */
1388 #define SHF_GETFL	0x0004		/* use fcntl() to figure RD/WR flags */
1389 #define SHF_UNBUF	0x0008		/* unbuffered I/O */
1390 #define SHF_CLEXEC	0x0010		/* set close on exec flag */
1391 #define SHF_MAPHI	0x0020		/* make fd > FDBASE (and close orig)
1392 					 * (shf_open() only) */
1393 #define SHF_DYNAMIC	0x0040		/* string: increase buffer as needed */
1394 #define SHF_INTERRUPT	0x0080		/* EINTR in read/write causes error */
1395 /* Flags used internally */
1396 #define SHF_STRING	0x0100		/* a string, not a file */
1397 #define SHF_ALLOCS	0x0200		/* shf and shf->buf were alloc()ed */
1398 #define SHF_ALLOCB	0x0400		/* shf->buf was alloc()ed */
1399 #define SHF_ERROR	0x0800		/* read()/write() error */
1400 #define SHF_EOF		0x1000		/* read eof (sticky) */
1401 #define SHF_READING	0x2000		/* currently reading: rnleft,rp valid */
1402 #define SHF_WRITING	0x4000		/* currently writing: wnleft,wp valid */
1403 
1404 
1405 struct shf {
1406 	Area *areap;		/* area shf/buf were allocated in */
1407 	unsigned char *rp;	/* read: current position in buffer */
1408 	unsigned char *wp;	/* write: current position in buffer */
1409 	unsigned char *buf;	/* buffer */
1410 	ssize_t bsize;		/* actual size of buf */
1411 	ssize_t rbsize;		/* size of buffer (1 if SHF_UNBUF) */
1412 	ssize_t rnleft;		/* read: how much data left in buffer */
1413 	ssize_t wbsize;		/* size of buffer (0 if SHF_UNBUF) */
1414 	ssize_t wnleft;		/* write: how much space left in buffer */
1415 	int flags;		/* see SHF_* */
1416 	int fd;			/* file descriptor */
1417 	int errnosv;		/* saved value of errno after error */
1418 };
1419 
1420 extern struct shf shf_iob[];
1421 
1422 struct table {
1423 	Area *areap;		/* area to allocate entries */
1424 	struct tbl **tbls;	/* hashed table items */
1425 	size_t nfree;		/* free table entries */
1426 	uint8_t tshift;		/* table size (2^tshift) */
1427 };
1428 
1429 /* table item */
1430 struct tbl {
1431 	/* Area to allocate from */
1432 	Area *areap;
1433 	/* value */
1434 	union {
1435 		char *s;			/* string */
1436 		mksh_ari_t i;			/* integer */
1437 		mksh_uari_t u;			/* unsigned integer */
1438 		int (*f)(const char **);	/* built-in command */
1439 		struct op *t;			/* "function" tree */
1440 	} val;
1441 	union {
1442 		struct tbl *array;	/* array values */
1443 		const char *fpath;	/* temporary path to undef function */
1444 	} u;
1445 	union {
1446 		int field;		/* field with for -L/-R/-Z */
1447 		int errnov;		/* CEXEC/CTALIAS */
1448 	} u2;
1449 	union {
1450 		uint32_t hval;		/* hash(name) */
1451 		uint32_t index;		/* index for an array */
1452 	} ua;
1453 	/*
1454 	 * command type (see below), base (if INTEGER),
1455 	 * offset from val.s of value (if EXPORT)
1456 	 */
1457 	int type;
1458 	/* flags (see below) */
1459 	uint32_t flag;
1460 
1461 	/* actually longer: name (variable length) */
1462 	char name[4];
1463 };
1464 
1465 EXTERN struct tbl *vtemp;
1466 /* set by global() and local() */
1467 EXTERN bool last_lookup_was_array;
1468 
1469 /* common flag bits */
1470 #define ALLOC		BIT(0)	/* val.s has been allocated */
1471 #define DEFINED		BIT(1)	/* is defined in block */
1472 #define ISSET		BIT(2)	/* has value, vp->val.[si] */
1473 #define EXPORT		BIT(3)	/* exported variable/function */
1474 #define TRACE		BIT(4)	/* var: user flagged, func: execution tracing */
1475 /* (start non-common flags at 8) */
1476 /* flag bits used for variables */
1477 #define SPECIAL		BIT(8)	/* PATH, IFS, SECONDS, etc */
1478 #define INTEGER		BIT(9)	/* val.i contains integer value */
1479 #define RDONLY		BIT(10)	/* read-only variable */
1480 #define LOCAL		BIT(11)	/* for local typeset() */
1481 #define ARRAY		BIT(13)	/* array */
1482 #define LJUST		BIT(14)	/* left justify */
1483 #define RJUST		BIT(15)	/* right justify */
1484 #define ZEROFIL		BIT(16)	/* 0 filled if RJUSTIFY, strip 0s if LJUSTIFY */
1485 #define LCASEV		BIT(17)	/* convert to lower case */
1486 #define UCASEV_AL	BIT(18) /* convert to upper case / autoload function */
1487 #define INT_U		BIT(19)	/* unsigned integer */
1488 #define INT_L		BIT(20)	/* long integer (no-op but used as magic) */
1489 #define IMPORT		BIT(21)	/* flag to typeset(): no arrays, must have = */
1490 #define LOCAL_COPY	BIT(22)	/* with LOCAL - copy attrs from existing var */
1491 #define EXPRINEVAL	BIT(23)	/* contents currently being evaluated */
1492 #define EXPRLVALUE	BIT(24)	/* useable as lvalue (temp flag) */
1493 #define AINDEX		BIT(25) /* array index >0 = ua.index filled in */
1494 #define ASSOC		BIT(26) /* ARRAY ? associative : reference */
1495 /* flag bits used for taliases/builtins/aliases/keywords/functions */
1496 #define KEEPASN		BIT(8)	/* keep command assignments (eg, var=x cmd) */
1497 #define FINUSE		BIT(9)	/* function being executed */
1498 #define FDELETE		BIT(10)	/* function deleted while it was executing */
1499 #define FKSH		BIT(11)	/* function defined with function x (vs x()) */
1500 #define SPEC_BI		BIT(12)	/* a POSIX special builtin */
1501 #define LOWER_BI	BIT(13)	/* (with LOW_BI) override even w/o flags */
1502 #define LOW_BI		BIT(14)	/* external utility overrides built-in one */
1503 
1504 /*
1505  * Attributes that can be set by the user (used to decide if an unset
1506  * param should be repoted by set/typeset). Does not include ARRAY or
1507  * LOCAL.
1508  */
1509 #define USERATTRIB	(EXPORT|INTEGER|RDONLY|LJUST|RJUST|ZEROFIL|\
1510 			    LCASEV|UCASEV_AL|INT_U|INT_L)
1511 
1512 #define arrayindex(vp)	((unsigned long)((vp)->flag & AINDEX ? \
1513 			    (vp)->ua.index : 0))
1514 
1515 enum namerefflag {
1516 	SRF_NOP,
1517 	SRF_ENABLE,
1518 	SRF_DISABLE
1519 };
1520 
1521 /* command types */
1522 #define CNONE		0	/* undefined */
1523 #define CSHELL		1	/* built-in */
1524 #define CFUNC		2	/* function */
1525 #define CEXEC		4	/* executable command */
1526 #define CALIAS		5	/* alias */
1527 #define CKEYWD		6	/* keyword */
1528 #define CTALIAS		7	/* tracked alias */
1529 
1530 /* Flags for findcom()/comexec() */
1531 #define FC_SPECBI	BIT(0)	/* special builtin */
1532 #define FC_FUNC		BIT(1)	/* function */
1533 #define FC_NORMBI	BIT(2)	/* not special builtin */
1534 #define FC_BI		(FC_SPECBI | FC_NORMBI)
1535 #define FC_PATH		BIT(3)	/* do path search */
1536 #define FC_DEFPATH	BIT(4)	/* use default path in path search */
1537 #define FC_WHENCE	BIT(5)	/* for use by command and whence */
1538 
1539 #define AF_ARGV_ALLOC	0x1	/* argv[] array allocated */
1540 #define AF_ARGS_ALLOCED	0x2	/* argument strings allocated */
1541 #define AI_ARGV(a, i)	((i) == 0 ? (a).argv[0] : (a).argv[(i) - (a).skip])
1542 #define AI_ARGC(a)	((a).ai_argc - (a).skip)
1543 
1544 /* Argument info. Used for $#, $* for shell, functions, includes, etc. */
1545 struct arg_info {
1546 	const char **argv;
1547 	int flags;	/* AF_* */
1548 	int ai_argc;
1549 	int skip;	/* first arg is argv[0], second is argv[1 + skip] */
1550 };
1551 
1552 /*
1553  * activation record for function blocks
1554  */
1555 struct block {
1556 	Area area;		/* area to allocate things */
1557 	const char **argv;
1558 	char *error;		/* error handler */
1559 	char *exit;		/* exit handler */
1560 	struct block *next;	/* enclosing block */
1561 	struct table vars;	/* local variables */
1562 	struct table funs;	/* local functions */
1563 	Getopt getopts_state;
1564 	int argc;
1565 	int flags;		/* see BF_* */
1566 };
1567 
1568 /* Values for struct block.flags */
1569 #define BF_DOGETOPTS	BIT(0)	/* save/restore getopts state */
1570 #define BF_STOPENV	BIT(1)	/* do not export further */
1571 
1572 /*
1573  * Used by ktwalk() and ktnext() routines.
1574  */
1575 struct tstate {
1576 	struct tbl **next;
1577 	ssize_t left;
1578 };
1579 
1580 EXTERN struct table taliases;	/* tracked aliases */
1581 EXTERN struct table builtins;	/* built-in commands */
1582 EXTERN struct table aliases;	/* aliases */
1583 EXTERN struct table keywords;	/* keywords */
1584 #ifndef MKSH_NOPWNAM
1585 EXTERN struct table homedirs;	/* homedir() cache */
1586 #endif
1587 
1588 struct builtin {
1589 	const char *name;
1590 	int (*func)(const char **);
1591 };
1592 
1593 extern const struct builtin mkshbuiltins[];
1594 
1595 /* values for set_prompt() */
1596 #define PS1	0	/* command */
1597 #define PS2	1	/* command continuation */
1598 
1599 EXTERN char *path;		/* copy of either PATH or def_path */
1600 EXTERN const char *def_path;	/* path to use if PATH not set */
1601 EXTERN char *tmpdir;		/* TMPDIR value */
1602 EXTERN const char *prompt;
1603 EXTERN uint8_t cur_prompt;	/* PS1 or PS2 */
1604 EXTERN int current_lineno;	/* LINENO value */
1605 
1606 /*
1607  * Description of a command or an operation on commands.
1608  */
1609 struct op {
1610 	const char **args;		/* arguments to a command */
1611 	char **vars;			/* variable assignments */
1612 	struct ioword **ioact;		/* IO actions (eg, < > >>) */
1613 	struct op *left, *right;	/* descendents */
1614 	char *str;			/* word for case; identifier for for,
1615 					 * select, and functions;
1616 					 * path to execute for TEXEC;
1617 					 * time hook for TCOM.
1618 					 */
1619 	int lineno;			/* TCOM/TFUNC: LINENO for this */
1620 	short type;			/* operation type, see below */
1621 	/* WARNING: newtp(), tcopy() use evalflags = 0 to clear union */
1622 	union {
1623 		/* TCOM: arg expansion eval() flags */
1624 		short evalflags;
1625 		/* TFUNC: function x (vs x()) */
1626 		short ksh_func;
1627 		/* TPAT: termination character */
1628 		char charflag;
1629 	} u;
1630 };
1631 
1632 /* Tree.type values */
1633 #define TEOF		0
1634 #define TCOM		1	/* command */
1635 #define TPAREN		2	/* (c-list) */
1636 #define TPIPE		3	/* a | b */
1637 #define TLIST		4	/* a ; b */
1638 #define TOR		5	/* || */
1639 #define TAND		6	/* && */
1640 #define TBANG		7	/* ! */
1641 #define TDBRACKET	8	/* [[ .. ]] */
1642 #define TFOR		9
1643 #define TSELECT		10
1644 #define TCASE		11
1645 #define TIF		12
1646 #define TWHILE		13
1647 #define TUNTIL		14
1648 #define TELIF		15
1649 #define TPAT		16	/* pattern in case */
1650 #define TBRACE		17	/* {c-list} */
1651 #define TASYNC		18	/* c & */
1652 #define TFUNCT		19	/* function name { command; } */
1653 #define TTIME		20	/* time pipeline */
1654 #define TEXEC		21	/* fork/exec eval'd TCOM */
1655 #define TCOPROC		22	/* coprocess |& */
1656 
1657 /*
1658  * prefix codes for words in command tree
1659  */
1660 #define EOS	0	/* end of string */
1661 #define CHAR	1	/* unquoted character */
1662 #define QCHAR	2	/* quoted character */
1663 #define COMSUB	3	/* $() substitution (0 terminated) */
1664 #define EXPRSUB	4	/* $(()) substitution (0 terminated) */
1665 #define OQUOTE	5	/* opening " or ' */
1666 #define CQUOTE	6	/* closing " or ' */
1667 #define OSUBST	7	/* opening ${ subst (followed by { or X) */
1668 #define CSUBST	8	/* closing } of above (followed by } or X) */
1669 #define OPAT	9	/* open pattern: *(, @(, etc. */
1670 #define SPAT	10	/* separate pattern: | */
1671 #define CPAT	11	/* close pattern: ) */
1672 #define ADELIM	12	/* arbitrary delimiter: ${foo:2:3} ${foo/bar/baz} */
1673 #define FUNSUB	14	/* ${ foo;} substitution (NUL terminated) */
1674 #define VALSUB	15	/* ${|foo;} substitution (NUL terminated) */
1675 
1676 /*
1677  * IO redirection
1678  */
1679 struct ioword {
1680 	char *ioname;		/* filename (unused if heredoc) */
1681 	char *delim;		/* delimiter for <<, <<- */
1682 	char *heredoc;		/* content of heredoc */
1683 	unsigned short ioflag;	/* action (below) */
1684 	short unit;		/* unit (fd) affected */
1685 };
1686 
1687 /* ioword.flag - type of redirection */
1688 #define IOTYPE		0xF	/* type: bits 0:3 */
1689 #define IOREAD		0x1	/* < */
1690 #define IOWRITE		0x2	/* > */
1691 #define IORDWR		0x3	/* <>: todo */
1692 #define IOHERE		0x4	/* << (here file) */
1693 #define IOCAT		0x5	/* >> */
1694 #define IODUP		0x6	/* <&/>& */
1695 #define IOEVAL		BIT(4)	/* expand in << */
1696 #define IOSKIP		BIT(5)	/* <<-, skip ^\t* */
1697 #define IOCLOB		BIT(6)	/* >|, override -o noclobber */
1698 #define IORDUP		BIT(7)	/* x<&y (as opposed to x>&y) */
1699 #define IONAMEXP	BIT(8)	/* name has been expanded */
1700 #define IOBASH		BIT(9)	/* &> etc. */
1701 #define IOHERESTR	BIT(10)	/* <<< (here string) */
1702 #define IONDELIM	BIT(11)	/* null delimiter (<<) */
1703 
1704 /* execute/exchild flags */
1705 #define XEXEC	BIT(0)		/* execute without forking */
1706 #define XFORK	BIT(1)		/* fork before executing */
1707 #define XBGND	BIT(2)		/* command & */
1708 #define XPIPEI	BIT(3)		/* input is pipe */
1709 #define XPIPEO	BIT(4)		/* output is pipe */
1710 #define XXCOM	BIT(5)		/* `...` command */
1711 #define XPCLOSE	BIT(6)		/* exchild: close close_fd in parent */
1712 #define XCCLOSE	BIT(7)		/* exchild: close close_fd in child */
1713 #define XERROK	BIT(8)		/* non-zero exit ok (for set -e) */
1714 #define XCOPROC BIT(9)		/* starting a co-process */
1715 #define XTIME	BIT(10)		/* timing TCOM command */
1716 #define XPIPEST	BIT(11)		/* want PIPESTATUS */
1717 
1718 /*
1719  * flags to control expansion of words (assumed by t->evalflags to fit
1720  * in a short)
1721  */
1722 #define DOBLANK	BIT(0)		/* perform blank interpretation */
1723 #define DOGLOB	BIT(1)		/* expand [?* */
1724 #define DOPAT	BIT(2)		/* quote *?[ */
1725 #define DOTILDE	BIT(3)		/* normal ~ expansion (first char) */
1726 #define DONTRUNCOMMAND BIT(4)	/* do not run $(command) things */
1727 #define DOASNTILDE BIT(5)	/* assignment ~ expansion (after =, :) */
1728 #define DOBRACE BIT(6)		/* used by expand(): do brace expansion */
1729 #define DOMAGIC BIT(7)		/* used by expand(): string contains MAGIC */
1730 #define DOTEMP	BIT(8)		/* dito: in word part of ${..[%#=?]..} */
1731 #define DOVACHECK BIT(9)	/* var assign check (for typeset, set, etc) */
1732 #define DOMARKDIRS BIT(10)	/* force markdirs behaviour */
1733 #define DOTCOMEXEC BIT(11)	/* not an eval flag, used by sh -c hack */
1734 #define DOSCALAR BIT(12)	/* change field handling to non-list context */
1735 #define DOHEREDOC BIT(13)	/* change scalar handling to heredoc body */
1736 #define DOHERESTR BIT(14)	/* append a newline char */
1737 
1738 #define X_EXTRA	20	/* this many extra bytes in X string */
1739 
1740 typedef struct XString {
1741 	/* beginning of string */
1742 	char *beg;
1743 	/* length of allocated area, minus safety margin */
1744 	size_t len;
1745 	/* end of string */
1746 	char *end;
1747 	/* memory area used */
1748 	Area *areap;
1749 } XString;
1750 
1751 /* initialise expandable string */
1752 #define XinitN(xs, length, area) do {				\
1753 	(xs).len = (length);					\
1754 	(xs).areap = (area);					\
1755 	(xs).beg = alloc((xs).len + X_EXTRA, (xs).areap);	\
1756 	(xs).end = (xs).beg + (xs).len;				\
1757 } while (/* CONSTCOND */ 0)
1758 #define Xinit(xs, xp, length, area) do {			\
1759 	XinitN((xs), (length), (area));				\
1760 	(xp) = (xs).beg;					\
1761 } while (/* CONSTCOND */ 0)
1762 
1763 /* stuff char into string */
1764 #define Xput(xs, xp, c)	(*xp++ = (c))
1765 
1766 /* check if there are at least n bytes left */
1767 #define XcheckN(xs, xp, n) do {					\
1768 	ssize_t more = ((xp) + (n)) - (xs).end;			\
1769 	if (more > 0)						\
1770 		(xp) = Xcheck_grow(&(xs), (xp), (size_t)more);	\
1771 } while (/* CONSTCOND */ 0)
1772 
1773 /* check for overflow, expand string */
1774 #define Xcheck(xs, xp)	XcheckN((xs), (xp), 1)
1775 
1776 /* free string */
1777 #define Xfree(xs, xp)	afree((xs).beg, (xs).areap)
1778 
1779 /* close, return string */
1780 #define Xclose(xs, xp)	aresize((xs).beg, (xp) - (xs).beg, (xs).areap)
1781 
1782 /* beginning of string */
1783 #define Xstring(xs, xp)	((xs).beg)
1784 
1785 #define Xnleft(xs, xp)	((xs).end - (xp))	/* may be less than 0 */
1786 #define Xlength(xs, xp)	((xp) - (xs).beg)
1787 #define Xsize(xs, xp)	((xs).end - (xs).beg)
1788 #define Xsavepos(xs, xp)	((xp) - (xs).beg)
1789 #define Xrestpos(xs, xp, n)	((xs).beg + (n))
1790 
1791 char *Xcheck_grow(XString *, const char *, size_t);
1792 
1793 /*
1794  * expandable vector of generic pointers
1795  */
1796 
1797 typedef struct {
1798 	/* beginning of allocated area */
1799 	void **beg;
1800 	/* currently used number of entries */
1801 	size_t len;
1802 	/* allocated number of entries */
1803 	size_t siz;
1804 } XPtrV;
1805 
1806 #define XPinit(x, n)	do {					\
1807 	(x).siz = (n);						\
1808 	(x).len = 0;						\
1809 	(x).beg = alloc2((x).siz, sizeof(void *), ATEMP);	\
1810 } while (/* CONSTCOND */ 0)					\
1811 
1812 #define XPput(x, p)	do {					\
1813 	if ((x).len == (x).siz) {				\
1814 		(x).beg = aresize2((x).beg, (x).siz,		\
1815 		    2 * sizeof(void *), ATEMP);			\
1816 		(x).siz <<= 1;					\
1817 	}							\
1818 	(x).beg[(x).len++] = (p);				\
1819 } while (/* CONSTCOND */ 0)
1820 
1821 #define XPptrv(x)	((x).beg)
1822 #define XPsize(x)	((x).len)
1823 #define XPclose(x)	aresize2((x).beg, XPsize(x), sizeof(void *), ATEMP)
1824 #define XPfree(x)	afree((x).beg, ATEMP)
1825 
1826 /* for print_columns */
1827 
1828 struct columnise_opts {
1829 	struct shf *shf;
1830 	char linesep;
1831 	bool do_last;
1832 	bool prefcol;
1833 };
1834 
1835 /*
1836  * Lexer internals
1837  */
1838 
1839 typedef struct source Source;
1840 struct source {
1841 	/* input buffer */
1842 	XString xs;
1843 	/* memory area, also checked in reclaim() */
1844 	Area *areap;
1845 	/* stacked source */
1846 	Source *next;
1847 	/* input pointer */
1848 	const char *str;
1849 	/* start of current buffer */
1850 	const char *start;
1851 	/* input file name */
1852 	const char *file;
1853 	/* extra data */
1854 	union {
1855 		/* string[] */
1856 		const char **strv;
1857 		/* shell file */
1858 		struct shf *shf;
1859 		/* alias (SF_HASALIAS) */
1860 		struct tbl *tblp;
1861 		/* (also for SREREAD) */
1862 		char *freeme;
1863 	} u;
1864 	/* flags */
1865 	int flags;
1866 	/* input type */
1867 	int type;
1868 	/* line number */
1869 	int line;
1870 	/* line the error occurred on (0 if not set) */
1871 	int errline;
1872 	/* buffer for ungetsc() (SREREAD) and alias (SALIAS) */
1873 	char ugbuf[2];
1874 };
1875 
1876 /* Source.type values */
1877 #define SEOF		0	/* input EOF */
1878 #define SFILE		1	/* file input */
1879 #define SSTDIN		2	/* read stdin */
1880 #define SSTRING		3	/* string */
1881 #define SWSTR		4	/* string without \n */
1882 #define SWORDS		5	/* string[] */
1883 #define SWORDSEP	6	/* string[] separator */
1884 #define SALIAS		7	/* alias expansion */
1885 #define SREREAD		8	/* read ahead to be re-scanned */
1886 #define SSTRINGCMDLINE	9	/* string from "mksh -c ..." */
1887 
1888 /* Source.flags values */
1889 #define SF_ECHO		BIT(0)	/* echo input to shlout */
1890 #define SF_ALIAS	BIT(1)	/* faking space at end of alias */
1891 #define SF_ALIASEND	BIT(2)	/* faking space at end of alias */
1892 #define SF_TTY		BIT(3)	/* type == SSTDIN & it is a tty */
1893 #define SF_HASALIAS	BIT(4)	/* u.tblp valid (SALIAS, SEOF) */
1894 #define SF_MAYEXEC	BIT(5)	/* special sh -c optimisation hack */
1895 
1896 typedef union {
1897 	int i;
1898 	char *cp;
1899 	char **wp;
1900 	struct op *o;
1901 	struct ioword *iop;
1902 } YYSTYPE;
1903 
1904 /* If something is added here, add it to tokentab[] in syn.c as well */
1905 #define LWORD		256
1906 #define LOGAND		257	/* && */
1907 #define LOGOR		258	/* || */
1908 #define BREAK		259	/* ;; */
1909 #define IF		260
1910 #define THEN		261
1911 #define ELSE		262
1912 #define ELIF		263
1913 #define FI		264
1914 #define CASE		265
1915 #define ESAC		266
1916 #define FOR		267
1917 #define SELECT		268
1918 #define WHILE		269
1919 #define UNTIL		270
1920 #define DO		271
1921 #define DONE		272
1922 #define IN		273
1923 #define FUNCTION	274
1924 #define TIME		275
1925 #define REDIR		276
1926 #define MDPAREN		277	/* (( )) */
1927 #define BANG		278	/* ! */
1928 #define DBRACKET	279	/* [[ .. ]] */
1929 #define COPROC		280	/* |& */
1930 #define BRKEV		281	/* ;| */
1931 #define BRKFT		282	/* ;& */
1932 #define YYERRCODE	300
1933 
1934 /* flags to yylex */
1935 #define CONTIN		BIT(0)	/* skip new lines to complete command */
1936 #define ONEWORD		BIT(1)	/* single word for substitute() */
1937 #define ALIAS		BIT(2)	/* recognise alias */
1938 #define KEYWORD		BIT(3)	/* recognise keywords */
1939 #define LETEXPR		BIT(4)	/* get expression inside (( )) */
1940 #define CMDASN		BIT(5)	/* parse x[1 & 2] as one word, for typeset */
1941 #define HEREDOC 	BIT(6)	/* parsing a here document body */
1942 #define ESACONLY	BIT(7)	/* only accept esac keyword */
1943 #define CMDWORD		BIT(8)	/* parsing simple command (alias related) */
1944 #define HEREDELIM	BIT(9)	/* parsing <<,<<- delimiter */
1945 #define LQCHAR		BIT(10)	/* source string contains QCHAR */
1946 
1947 #define HERES		10	/* max number of << in line */
1948 
1949 #undef CTRL
1950 #define	CTRL(x)		((x) == '?' ? 0x7F : (x) & 0x1F)	/* ASCII */
1951 #define	UNCTRL(x)	((x) ^ 0x40)				/* ASCII */
1952 #define	ISCTRL(x)	(((signed char)((uint8_t)(x) + 1)) < 33)
1953 
1954 #define IDENT		64
1955 
1956 EXTERN Source *source;		/* yyparse/yylex source */
1957 EXTERN YYSTYPE yylval;		/* result from yylex */
1958 EXTERN struct ioword *heres[HERES], **herep;
1959 EXTERN char ident[IDENT + 1];
1960 
1961 EXTERN char **history;		/* saved commands */
1962 EXTERN char **histptr;		/* last history item */
1963 EXTERN mksh_ari_t histsize;	/* history size */
1964 
1965 /* flags to histsave */
1966 #define HIST_FLUSH	0
1967 #define HIST_QUEUE	1
1968 #define HIST_APPEND	2
1969 #define HIST_STORE	3
1970 #define HIST_NOTE	4
1971 
1972 /* user and system time of last j_waitjed job */
1973 EXTERN struct timeval j_usrtime, j_systime;
1974 
1975 #define notok2mul(max, val, c)	(((val) != 0) && ((c) != 0) && \
1976 				    (((max) / (c)) < (val)))
1977 #define notok2add(max, val, c)	((val) > ((max) - (c)))
1978 #define notoktomul(val, cnst)	notok2mul(SIZE_MAX, (val), (cnst))
1979 #define notoktoadd(val, cnst)	notok2add(SIZE_MAX, (val), (cnst))
1980 #define checkoktoadd(val, cnst) do {					\
1981 	if (notoktoadd((val), (cnst)))					\
1982 		internal_errorf(Tintovfl, (size_t)(val),		\
1983 		    '+', (size_t)(cnst));				\
1984 } while (/* CONSTCOND */ 0)
1985 
1986 
1987 /* lalloc.c */
1988 void ainit(Area *);
1989 void afreeall(Area *);
1990 /* these cannot fail and can take NULL (not for ap) */
1991 #define alloc(n, ap)		aresize(NULL, (n), (ap))
1992 #define alloc2(m, n, ap)	aresize2(NULL, (m), (n), (ap))
1993 void *aresize(void *, size_t, Area *);
1994 void *aresize2(void *, size_t, size_t, Area *);
1995 void afree(void *, Area *);	/* can take NULL */
1996 /* edit.c */
1997 #ifndef MKSH_NO_CMDLINE_EDITING
1998 #ifndef MKSH_SMALL
1999 int x_bind(const char *, const char *, bool, bool);
2000 #else
2001 int x_bind(const char *, const char *, bool);
2002 #endif
2003 void x_init(void);
2004 #ifdef DEBUG_LEAKS
2005 void x_done(void);
2006 #endif
2007 int x_read(char *);
2008 #endif
2009 void x_mkraw(int, mksh_ttyst *, bool);
2010 void x_initterm(const char *);
2011 /* eval.c */
2012 char *substitute(const char *, int);
2013 char **eval(const char **, int);
2014 char *evalstr(const char *cp, int);
2015 char *evalonestr(const char *cp, int);
2016 char *debunk(char *, const char *, size_t);
2017 void expand(const char *, XPtrV *, int);
2018 int glob_str(char *, XPtrV *, bool);
2019 char *do_tilde(char *);
2020 /* exec.c */
2021 int execute(struct op * volatile, volatile int, volatile int * volatile);
2022 int shcomexec(const char **);
2023 struct tbl *findfunc(const char *, uint32_t, bool);
2024 int define(const char *, struct op *);
2025 const char *builtin(const char *, int (*)(const char **));
2026 struct tbl *findcom(const char *, int);
2027 void flushcom(bool);
2028 int search_access(const char *, int);
2029 const char *search_path(const char *, const char *, int, int *);
2030 void pr_menu(const char * const *);
2031 void pr_list(struct columnise_opts *, char * const *);
2032 int herein(struct ioword *, char **);
2033 /* expr.c */
2034 int evaluate(const char *, mksh_ari_t *, int, bool);
2035 int v_evaluate(struct tbl *, const char *, volatile int, bool);
2036 /* UTF-8 stuff */
2037 size_t utf_mbtowc(unsigned int *, const char *);
2038 size_t utf_wctomb(char *, unsigned int);
2039 int utf_widthadj(const char *, const char **);
2040 size_t utf_mbswidth(const char *) MKSH_A_PURE;
2041 const char *utf_skipcols(const char *, int, int *);
2042 size_t utf_ptradj(const char *) MKSH_A_PURE;
2043 #ifdef MIRBSD_BOOTFLOPPY
2044 #define utf_wcwidth(i) wcwidth((wchar_t)(i))
2045 #else
2046 int utf_wcwidth(unsigned int) MKSH_A_PURE;
2047 #endif
2048 int ksh_access(const char *, int);
2049 struct tbl *tempvar(const char *);
2050 /* funcs.c */
2051 int c_hash(const char **);
2052 int c_pwd(const char **);
2053 int c_print(const char **);
2054 #ifdef MKSH_PRINTF_BUILTIN
2055 int c_printf(const char **);
2056 #endif
2057 int c_whence(const char **);
2058 int c_command(const char **);
2059 int c_typeset(const char **);
2060 int c_alias(const char **);
2061 int c_unalias(const char **);
2062 int c_let(const char **);
2063 int c_jobs(const char **);
2064 #ifndef MKSH_UNEMPLOYED
2065 int c_fgbg(const char **);
2066 #endif
2067 int c_kill(const char **);
2068 void getopts_reset(int);
2069 int c_getopts(const char **);
2070 #ifndef MKSH_NO_CMDLINE_EDITING
2071 int c_bind(const char **);
2072 #endif
2073 int c_shift(const char **);
2074 int c_umask(const char **);
2075 int c_dot(const char **);
2076 int c_wait(const char **);
2077 int c_read(const char **);
2078 int c_eval(const char **);
2079 int c_trap(const char **);
2080 int c_brkcont(const char **);
2081 int c_exitreturn(const char **);
2082 int c_set(const char **);
2083 int c_unset(const char **);
2084 int c_ulimit(const char **);
2085 int c_times(const char **);
2086 int timex(struct op *, int, volatile int *);
2087 void timex_hook(struct op *, char ** volatile *);
2088 int c_exec(const char **);
2089 /* dummy function (just need pointer value), special case in comexec() */
2090 #define c_builtin shcomexec
2091 int c_test(const char **);
2092 #if HAVE_MKNOD
2093 int c_mknod(const char **);
2094 #endif
2095 int c_realpath(const char **);
2096 int c_rename(const char **);
2097 int c_cat(const char **);
2098 int c_sleep(const char **);
2099 /* histrap.c */
2100 void init_histvec(void);
2101 void hist_init(Source *);
2102 #if HAVE_PERSISTENT_HISTORY
2103 void hist_finish(void);
2104 #endif
2105 void histsave(int *, const char *, int, bool);
2106 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
2107 bool histsync(void);
2108 #endif
2109 int c_fc(const char **);
2110 void sethistsize(mksh_ari_t);
2111 #if HAVE_PERSISTENT_HISTORY
2112 void sethistfile(const char *);
2113 #endif
2114 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
2115 char **histpos(void) MKSH_A_PURE;
2116 int histnum(int);
2117 #endif
2118 int findhist(int, int, const char *, bool) MKSH_A_PURE;
2119 char **hist_get_newest(bool);
2120 void inittraps(void);
2121 void alarm_init(void);
2122 Trap *gettrap(const char *, bool, bool);
2123 void trapsig(int);
2124 void intrcheck(void);
2125 int fatal_trap_check(void);
2126 int trap_pending(void);
2127 void runtraps(int intr);
2128 void runtrap(Trap *, bool);
2129 void cleartraps(void);
2130 void restoresigs(void);
2131 void settrap(Trap *, const char *);
2132 bool block_pipe(void);
2133 void restore_pipe(void);
2134 int setsig(Trap *, sig_t, int);
2135 void setexecsig(Trap *, int);
2136 #if HAVE_FLOCK || HAVE_LOCK_FCNTL
2137 void mksh_lockfd(int);
2138 void mksh_unlkfd(int);
2139 #endif
2140 /* jobs.c */
2141 void j_init(void);
2142 void j_exit(void);
2143 #ifndef MKSH_UNEMPLOYED
2144 void j_change(void);
2145 #endif
2146 int exchild(struct op *, int, volatile int *, int);
2147 void startlast(void);
2148 int waitlast(void);
2149 int waitfor(const char *, int *);
2150 int j_kill(const char *, int);
2151 #ifndef MKSH_UNEMPLOYED
2152 int j_resume(const char *, int);
2153 #endif
2154 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
2155 void j_suspend(void);
2156 #endif
2157 int j_jobs(const char *, int, int);
2158 void j_notify(void);
2159 pid_t j_async(void);
2160 int j_stopped_running(void);
2161 /* lex.c */
2162 int yylex(int);
2163 void yyskiputf8bom(void);
2164 void yyerror(const char *, ...)
2165     MKSH_A_NORETURN
2166     MKSH_A_FORMAT(__printf__, 1, 2);
2167 Source *pushs(int, Area *);
2168 void set_prompt(int, Source *);
2169 int pprompt(const char *, int);
2170 /* main.c */
2171 int include(const char *, int, const char **, bool);
2172 int command(const char *, int);
2173 int shell(Source * volatile, volatile bool);
2174 /* argument MUST NOT be 0 */
2175 void unwind(int) MKSH_A_NORETURN;
2176 void newenv(int);
2177 void quitenv(struct shf *);
2178 void cleanup_parents_env(void);
2179 void cleanup_proc_env(void);
2180 void errorf(const char *, ...)
2181     MKSH_A_NORETURN
2182     MKSH_A_FORMAT(__printf__, 1, 2);
2183 void errorfx(int, const char *, ...)
2184     MKSH_A_NORETURN
2185     MKSH_A_FORMAT(__printf__, 2, 3);
2186 void warningf(bool, const char *, ...)
2187     MKSH_A_FORMAT(__printf__, 2, 3);
2188 void bi_errorf(const char *, ...)
2189     MKSH_A_FORMAT(__printf__, 1, 2);
2190 #define errorfz()	errorf(NULL)
2191 #define errorfxz(rc)	errorfx((rc), NULL)
2192 #define bi_errorfz()	bi_errorf(NULL)
2193 void internal_errorf(const char *, ...)
2194     MKSH_A_NORETURN
2195     MKSH_A_FORMAT(__printf__, 1, 2);
2196 void internal_warningf(const char *, ...)
2197     MKSH_A_FORMAT(__printf__, 1, 2);
2198 void error_prefix(bool);
2199 void shellf(const char *, ...)
2200     MKSH_A_FORMAT(__printf__, 1, 2);
2201 void shprintf(const char *, ...)
2202     MKSH_A_FORMAT(__printf__, 1, 2);
2203 int can_seek(int);
2204 void initio(void);
2205 int ksh_dup2(int, int, bool);
2206 short savefd(int);
2207 void restfd(int, int);
2208 void openpipe(int *);
2209 void closepipe(int *);
2210 int check_fd(const char *, int, const char **);
2211 void coproc_init(void);
2212 void coproc_read_close(int);
2213 void coproc_readw_close(int);
2214 void coproc_write_close(int);
2215 int coproc_getfd(int, const char **);
2216 void coproc_cleanup(int);
2217 struct temp *maketemp(Area *, Temp_type, struct temp **);
2218 void ktinit(Area *, struct table *, uint8_t);
2219 struct tbl *ktscan(struct table *, const char *, uint32_t, struct tbl ***);
2220 /* table, name (key) to search for, hash(n) */
2221 #define ktsearch(tp, s, h) ktscan((tp), (s), (h), NULL)
2222 struct tbl *ktenter(struct table *, const char *, uint32_t);
2223 #define ktdelete(p)	do { p->flag = 0; } while (/* CONSTCOND */ 0)
2224 void ktwalk(struct tstate *, struct table *);
2225 struct tbl *ktnext(struct tstate *);
2226 struct tbl **ktsort(struct table *);
2227 #ifdef DF
2228 void DF(const char *, ...)
2229     MKSH_A_FORMAT(__printf__, 1, 2);
2230 #endif
2231 /* misc.c */
2232 void setctypes(const char *, int);
2233 void initctypes(void);
2234 size_t option(const char *) MKSH_A_PURE;
2235 char *getoptions(void);
2236 void change_flag(enum sh_flag, int, bool);
2237 void change_xtrace(unsigned char, bool);
2238 int parse_args(const char **, int, bool *);
2239 int getn(const char *, int *);
2240 int gmatchx(const char *, const char *, bool);
2241 int has_globbing(const char *, const char *) MKSH_A_PURE;
2242 int xstrcmp(const void *, const void *) MKSH_A_PURE;
2243 void ksh_getopt_reset(Getopt *, int);
2244 int ksh_getopt(const char **, Getopt *, const char *);
2245 void print_value_quoted(struct shf *, const char *);
2246 char *quote_value(const char *);
2247 void print_columns(struct columnise_opts *, unsigned int,
2248     void (*)(char *, size_t, unsigned int, const void *),
2249     const void *, size_t, size_t);
2250 void strip_nuls(char *, size_t)
2251     MKSH_A_BOUNDED(__string__, 1, 2);
2252 ssize_t blocking_read(int, char *, size_t)
2253     MKSH_A_BOUNDED(__buffer__, 2, 3);
2254 int reset_nonblock(int);
2255 char *ksh_get_wd(void);
2256 char *do_realpath(const char *);
2257 void simplify_path(char *);
2258 void set_current_wd(const char *);
2259 int c_cd(const char **);
2260 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2261 char *strdup_i(const char *, Area *);
2262 char *strndup_i(const char *, size_t, Area *);
2263 #endif
2264 int unbksl(bool, int (*)(void), void (*)(int));
2265 /* shf.c */
2266 struct shf *shf_open(const char *, int, int, int);
2267 struct shf *shf_fdopen(int, int, struct shf *);
2268 struct shf *shf_reopen(int, int, struct shf *);
2269 struct shf *shf_sopen(char *, ssize_t, int, struct shf *);
2270 int shf_close(struct shf *);
2271 int shf_fdclose(struct shf *);
2272 char *shf_sclose(struct shf *);
2273 int shf_flush(struct shf *);
2274 ssize_t shf_read(char *, ssize_t, struct shf *);
2275 char *shf_getse(char *, ssize_t, struct shf *);
2276 int shf_getchar(struct shf *s);
2277 int shf_ungetc(int, struct shf *);
2278 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2279 int shf_getc(struct shf *);
2280 int shf_putc(int, struct shf *);
2281 #else
2282 #define shf_getc shf_getc_i
2283 #define shf_putc shf_putc_i
2284 #endif
2285 int shf_putchar(int, struct shf *);
2286 ssize_t shf_puts(const char *, struct shf *);
2287 ssize_t shf_write(const char *, ssize_t, struct shf *);
2288 ssize_t shf_fprintf(struct shf *, const char *, ...)
2289     MKSH_A_FORMAT(__printf__, 2, 3);
2290 ssize_t shf_snprintf(char *, ssize_t, const char *, ...)
2291     MKSH_A_FORMAT(__printf__, 3, 4)
2292     MKSH_A_BOUNDED(__string__, 1, 2);
2293 char *shf_smprintf(const char *, ...)
2294     MKSH_A_FORMAT(__printf__, 1, 2);
2295 ssize_t shf_vfprintf(struct shf *, const char *, va_list)
2296     MKSH_A_FORMAT(__printf__, 2, 0);
2297 /* syn.c */
2298 int assign_command(const char *, bool) MKSH_A_PURE;
2299 void initkeywords(void);
2300 struct op *compile(Source *, bool);
2301 bool parse_usec(const char *, struct timeval *);
2302 char *yyrecursive(int);
2303 void yyrecursive_pop(bool);
2304 /* tree.c */
2305 void fptreef(struct shf *, int, const char *, ...);
2306 char *snptreef(char *, ssize_t, const char *, ...);
2307 struct op *tcopy(struct op *, Area *);
2308 char *wdcopy(const char *, Area *);
2309 const char *wdscan(const char *, int);
2310 #define WDS_TPUTS	BIT(0)		/* tputS (dumpwdvar) mode */
2311 char *wdstrip(const char *, int);
2312 void tfree(struct op *, Area *);
2313 void dumpchar(struct shf *, int);
2314 void dumptree(struct shf *, struct op *);
2315 void dumpwdvar(struct shf *, const char *);
2316 void dumpioact(struct shf *shf, struct op *t);
2317 void vistree(char *, size_t, struct op *)
2318     MKSH_A_BOUNDED(__string__, 1, 2);
2319 void fpFUNCTf(struct shf *, int, bool, const char *, struct op *);
2320 /* var.c */
2321 void newblock(void);
2322 void popblock(void);
2323 void initvar(void);
2324 struct block *varsearch(struct block *, struct tbl **, const char *, uint32_t);
2325 struct tbl *global(const char *);
2326 struct tbl *local(const char *, bool);
2327 char *str_val(struct tbl *);
2328 int setstr(struct tbl *, const char *, int);
2329 struct tbl *setint_v(struct tbl *, struct tbl *, bool);
2330 void setint(struct tbl *, mksh_ari_t);
2331 void setint_n(struct tbl *, mksh_ari_t, int);
2332 struct tbl *typeset(const char *, uint32_t, uint32_t, int, int);
2333 void unset(struct tbl *, int);
2334 const char *skip_varname(const char *, bool) MKSH_A_PURE;
2335 const char *skip_wdvarname(const char *, bool) MKSH_A_PURE;
2336 int is_wdvarname(const char *, bool) MKSH_A_PURE;
2337 int is_wdvarassign(const char *) MKSH_A_PURE;
2338 struct tbl *arraysearch(struct tbl *, uint32_t);
2339 char **makenv(void);
2340 void change_winsz(void);
2341 size_t array_ref_len(const char *) MKSH_A_PURE;
2342 char *arrayname(const char *);
2343 mksh_uari_t set_array(const char *, bool, const char **);
2344 uint32_t hash(const void *) MKSH_A_PURE;
2345 uint32_t chvt_rndsetup(const void *, size_t) MKSH_A_PURE;
2346 mksh_ari_t rndget(void);
2347 void rndset(unsigned long);
2348 void rndpush(const void *);
2349 void record_match(const char *);
2350 
2351 enum Test_op {
2352 	/* non-operator */
2353 	TO_NONOP = 0,
2354 	/* unary operators */
2355 	TO_STNZE, TO_STZER, TO_OPTION,
2356 	TO_FILAXST,
2357 	TO_FILEXST,
2358 	TO_FILREG, TO_FILBDEV, TO_FILCDEV, TO_FILSYM, TO_FILFIFO, TO_FILSOCK,
2359 	TO_FILCDF, TO_FILID, TO_FILGID, TO_FILSETG, TO_FILSTCK, TO_FILUID,
2360 	TO_FILRD, TO_FILGZ, TO_FILTT, TO_FILSETU, TO_FILWR, TO_FILEX,
2361 	/* binary operators */
2362 	TO_STEQL, TO_STNEQ, TO_STLT, TO_STGT, TO_INTEQ, TO_INTNE, TO_INTGT,
2363 	TO_INTGE, TO_INTLT, TO_INTLE, TO_FILEQ, TO_FILNT, TO_FILOT,
2364 	/* not an operator */
2365 	TO_NONNULL	/* !TO_NONOP */
2366 };
2367 typedef enum Test_op Test_op;
2368 
2369 /* Used by Test_env.isa() (order important - used to index *_tokens[] arrays) */
2370 enum Test_meta {
2371 	TM_OR,		/* -o or || */
2372 	TM_AND,		/* -a or && */
2373 	TM_NOT,		/* ! */
2374 	TM_OPAREN,	/* ( */
2375 	TM_CPAREN,	/* ) */
2376 	TM_UNOP,	/* unary operator */
2377 	TM_BINOP,	/* binary operator */
2378 	TM_END		/* end of input */
2379 };
2380 typedef enum Test_meta Test_meta;
2381 
2382 #define TEF_ERROR	BIT(0)		/* set if we've hit an error */
2383 #define TEF_DBRACKET	BIT(1)		/* set if [[ .. ]] test */
2384 
2385 typedef struct test_env {
2386 	union {
2387 		const char **wp;	/* used by ptest_* */
2388 		XPtrV *av;		/* used by dbtestp_* */
2389 	} pos;
2390 	const char **wp_end;		/* used by ptest_* */
2391 	Test_op (*isa)(struct test_env *, Test_meta);
2392 	const char *(*getopnd) (struct test_env *, Test_op, bool);
2393 	int (*eval)(struct test_env *, Test_op, const char *, const char *, bool);
2394 	void (*error)(struct test_env *, int, const char *);
2395 	int flags;			/* TEF_* */
2396 } Test_env;
2397 
2398 extern const char * const dbtest_tokens[];
2399 
2400 Test_op	test_isop(Test_meta, const char *) MKSH_A_PURE;
2401 int test_eval(Test_env *, Test_op, const char *, const char *, bool);
2402 int test_parse(Test_env *);
2403 
2404 /* tty_fd is not opened O_BINARY, it's thus never read/written */
2405 EXTERN int tty_fd E_INIT(-1);	/* dup'd tty file descriptor */
2406 EXTERN bool tty_devtty;		/* true if tty_fd is from /dev/tty */
2407 EXTERN mksh_ttyst tty_state;	/* saved tty state */
2408 EXTERN bool tty_hasstate;	/* true if tty_state is valid */
2409 
2410 extern int tty_init_fd(void);	/* initialise tty_fd, tty_devtty */
2411 
2412 #ifdef __OS2__
2413 #ifndef __GNUC__
2414 # error oops?
2415 #endif
2416 #define binopen2(path,flags)		__extension__({			\
2417 	int binopen2_fd = open((path), (flags) | O_BINARY);		\
2418 	if (binopen2_fd >= 0)						\
2419 		setmode(binopen2_fd, O_BINARY);				\
2420 	(binopen2_fd);							\
2421 })
2422 #define binopen3(path,flags,mode)	__extension__({			\
2423 	int binopen3_fd = open((path), (flags) | O_BINARY, (mode));	\
2424 	if (binopen3_fd >= 0)						\
2425 		setmode(binopen3_fd, O_BINARY);				\
2426 	(binopen3_fd);							\
2427 })
2428 #define mksh_abspath(s)			__extension__({			\
2429 	const char *mksh_abspath_s = (s);				\
2430 	(mksh_cdirsep(mksh_abspath_s[0]) ||				\
2431 	    (ksh_isalphx(mksh_abspath_s[0]) &&				\
2432 	    mksh_abspath_s[1] == ':'));					\
2433 })
2434 #define mksh_cdirsep(c)			__extension__({			\
2435 	char mksh_cdirsep_c = (c);					\
2436 	(mksh_cdirsep_c == '/' || mksh_cdirsep_c == '\\');		\
2437 })
2438 /*
2439  * I've seen mksh_sdirsep(s) and mksh_vdirsep(s) but need to think
2440  * more about the OS/2 port (and, possibly, toy with it) before I
2441  * can merge this upstream, but good job so far @komh, thanks!
2442  */
2443 #else
2444 #define binopen2(path,flags)		open((path), (flags) | O_BINARY)
2445 #define binopen3(path,flags,mode)	open((path), (flags) | O_BINARY, (mode))
2446 #define mksh_abspath(s)			((s)[0] == '/')
2447 #define mksh_cdirsep(c)			((c) == '/')
2448 #define mksh_sdirsep(s)			strchr((s), '/')
2449 #define mksh_vdirsep(s)			vstrchr((s), '/')
2450 #endif
2451 
2452 /* be sure not to interfere with anyone else's idea about EXTERN */
2453 #ifdef EXTERN_DEFINED
2454 # undef EXTERN_DEFINED
2455 # undef EXTERN
2456 #endif
2457 #undef E_INIT
2458 
2459 #endif /* !MKSH_INCLUDES_ONLY */
2460