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