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