OSDN Git Service

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