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