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