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