OSDN Git Service

Merge "Upgrade to mksh R53a." am: c19d20531c am: 8b302a0123
[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.786 2016/08/12 16:48:05 tg Exp $");
179 #endif
180 #define MKSH_VERSION "R53 2016/08/12"
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 != 530)
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 #undef MKSH_S_NOVI
638 #define MKSH_S_NOVI             1
639 #endif
640
641 #ifdef MKSH_SMALL
642 #ifndef MKSH_NOPWNAM
643 #define MKSH_NOPWNAM            /* defined */
644 #endif
645 #ifndef MKSH_S_NOVI
646 #define MKSH_S_NOVI             1
647 #endif
648 #endif
649
650 #ifndef MKSH_S_NOVI
651 #define MKSH_S_NOVI             0
652 #endif
653
654 #if defined(MKSH_NOPROSPECTOFWORK) && !defined(MKSH_UNEMPLOYED)
655 #define MKSH_UNEMPLOYED         1
656 #endif
657
658 #define NUFILE          32      /* Number of user-accessible files */
659 #define FDBASE          10      /* First file usable by Shell */
660
661 /*
662  * simple grouping allocator
663  */
664
665
666 /* 0. OS API: where to get memory from and how to free it (grouped) */
667
668 /* malloc(3)/realloc(3) -> free(3) for use by the memory allocator */
669 #define malloc_osi(sz)          malloc(sz)
670 #define realloc_osi(p,sz)       realloc((p), (sz))
671 #define free_osimalloc(p)       free(p)
672
673 /* malloc(3)/realloc(3) -> free(3) for use by mksh code */
674 #define malloc_osfunc(sz)       malloc(sz)
675 #define realloc_osfunc(p,sz)    realloc((p), (sz))
676 #define free_osfunc(p)          free(p)
677
678 #if HAVE_MKNOD
679 /* setmode(3) -> free(3) */
680 #define free_ossetmode(p)       free(p)
681 #endif
682
683 #ifdef MKSH__NO_PATH_MAX
684 /* GNU libc: get_current_dir_name(3) -> free(3) */
685 #define free_gnu_gcdn(p)        free(p)
686 #endif
687
688
689 /* 1. internal structure */
690 struct lalloc_common {
691         struct lalloc_common *next;
692 };
693
694 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
695 struct lalloc_item {
696         struct lalloc_common *next;
697         size_t len;
698         char dummy[8192 - sizeof(struct lalloc_common *) - sizeof(size_t)];
699 };
700 #endif
701
702 /* 2. sizes */
703 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
704 #define ALLOC_ITEM      struct lalloc_item
705 #define ALLOC_OVERHEAD  0
706 #else
707 #define ALLOC_ITEM      struct lalloc_common
708 #define ALLOC_OVERHEAD  (sizeof(ALLOC_ITEM))
709 #endif
710
711 /* 3. group structure */
712 typedef struct lalloc_common Area;
713
714
715 EXTERN Area aperm;              /* permanent object space */
716 #define APERM   &aperm
717 #define ATEMP   &e->area
718
719 /*
720  * flags (the order of these enums MUST match the order in misc.c(options[]))
721  */
722 enum sh_flag {
723 #define SHFLAGS_ENUMS
724 #include "sh_flags.gen"
725         FNFLAGS         /* (place holder: how many flags are there) */
726 };
727
728 #define Flag(f) (shell_flags[(int)(f)])
729 #define UTFMODE Flag(FUNICODE)
730
731 /*
732  * parsing & execution environment
733  *
734  * note that kshlongjmp MUST NOT be passed 0 as second argument!
735  */
736 #ifdef MKSH_NO_SIGSETJMP
737 #define kshjmp_buf      jmp_buf
738 #define kshsetjmp(jbuf) _setjmp(jbuf)
739 #define kshlongjmp      _longjmp
740 #else
741 #define kshjmp_buf      sigjmp_buf
742 #define kshsetjmp(jbuf) sigsetjmp((jbuf), 0)
743 #define kshlongjmp      siglongjmp
744 #endif
745
746 struct sretrace_info;
747 struct yyrecursive_state;
748
749 EXTERN struct sretrace_info *retrace_info E_INIT(NULL);
750 EXTERN int subshell_nesting_type E_INIT(0);
751
752 extern struct env {
753         ALLOC_ITEM alloc_INT;   /* internal, do not touch */
754         Area area;              /* temporary allocation area */
755         struct env *oenv;       /* link to previous environment */
756         struct block *loc;      /* local variables and functions */
757         short *savefd;          /* original redirected fds */
758         struct temp *temps;     /* temp files */
759         /* saved parser recursion state */
760         struct yyrecursive_state *yyrecursive_statep;
761         kshjmp_buf jbuf;        /* long jump back to env creator */
762         uint8_t type;           /* environment type - see below */
763         uint8_t flags;          /* EF_* */
764 } *e;
765
766 /* struct env.type values */
767 #define E_NONE  0       /* dummy environment */
768 #define E_PARSE 1       /* parsing command # */
769 #define E_FUNC  2       /* executing function # */
770 #define E_INCL  3       /* including a file via . # */
771 #define E_EXEC  4       /* executing command tree */
772 #define E_LOOP  5       /* executing for/while # */
773 #define E_ERRH  6       /* general error handler # */
774 #define E_GONE  7       /* hidden in child */
775 /* # indicates env has valid jbuf (see unwind()) */
776
777 /* struct env.flag values */
778 #define EF_BRKCONT_PASS BIT(1)  /* set if E_LOOP must pass break/continue on */
779 #define EF_FAKE_SIGDIE  BIT(2)  /* hack to get info from unwind to quitenv */
780
781 /* Do breaks/continues stop at env type e? */
782 #define STOP_BRKCONT(t) ((t) == E_NONE || (t) == E_PARSE || \
783                             (t) == E_FUNC || (t) == E_INCL)
784 /* Do returns stop at env type e? */
785 #define STOP_RETURN(t)  ((t) == E_FUNC || (t) == E_INCL)
786
787 /* values for kshlongjmp(e->jbuf, i) */
788 /* note that i MUST NOT be zero */
789 #define LRETURN 1       /* return statement */
790 #define LEXIT   2       /* exit statement */
791 #define LERROR  3       /* errorf() called */
792 #define LLEAVE  4       /* untrappable exit/error */
793 #define LINTR   5       /* ^C noticed */
794 #define LBREAK  6       /* break statement */
795 #define LCONTIN 7       /* continue statement */
796 #define LSHELL  8       /* return to interactive shell() */
797 #define LAEXPR  9       /* error in arithmetic expression */
798
799 /* sort of shell global state */
800 EXTERN pid_t procpid;           /* PID of executing process */
801 EXTERN int exstat;              /* exit status */
802 EXTERN int subst_exstat;        /* exit status of last $(..)/`..` */
803 EXTERN struct tbl *vp_pipest;   /* global PIPESTATUS array */
804 EXTERN short trap_exstat;       /* exit status before running a trap */
805 EXTERN uint8_t trap_nested;     /* running nested traps */
806 EXTERN uint8_t shell_flags[FNFLAGS];
807 EXTERN const char *kshname;     /* $0 */
808 EXTERN struct {
809         uid_t kshuid_v;         /* real UID of shell */
810         uid_t ksheuid_v;        /* effective UID of shell */
811         gid_t kshgid_v;         /* real GID of shell */
812         gid_t kshegid_v;        /* effective GID of shell */
813         pid_t kshpgrp_v;        /* process group of shell */
814         pid_t kshppid_v;        /* PID of parent of shell */
815         pid_t kshpid_v;         /* $$, shell PID */
816 } rndsetupstate;
817
818 #define kshpid          rndsetupstate.kshpid_v
819 #define kshpgrp         rndsetupstate.kshpgrp_v
820 #define kshuid          rndsetupstate.kshuid_v
821 #define ksheuid         rndsetupstate.ksheuid_v
822 #define kshgid          rndsetupstate.kshgid_v
823 #define kshegid         rndsetupstate.kshegid_v
824 #define kshppid         rndsetupstate.kshppid_v
825
826
827 /* option processing */
828 #define OF_CMDLINE      0x01    /* command line */
829 #define OF_SET          0x02    /* set builtin */
830 #define OF_SPECIAL      0x04    /* a special variable changing */
831 #define OF_INTERNAL     0x08    /* set internally by shell */
832 #define OF_FIRSTTIME    0x10    /* as early as possible, once */
833 #define OF_ANY          (OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
834
835 /* null value for variable; comparison pointer for unset */
836 EXTERN char null[] E_INIT("");
837
838 /* string pooling: do we rely on the compiler? */
839 #ifndef HAVE_STRING_POOLING
840 /* no, we use our own, saves quite some space */
841 #elif HAVE_STRING_POOLING == 2
842 /* “on demand” */
843 #ifdef __GNUC__
844 /* only for GCC 4 or later, older ones can get by without */
845 #if __GNUC__ < 4
846 #undef HAVE_STRING_POOLING
847 #endif
848 #else
849 /* not GCC, default to on */
850 #endif
851 #elif HAVE_STRING_POOLING == 0
852 /* default to on, unless explicitly set to 0 */
853 #undef HAVE_STRING_POOLING
854 #endif
855
856 #ifndef HAVE_STRING_POOLING /* helpers for pooled strings */
857 EXTERN const char T4spaces[] E_INIT("    ");
858 #define T1space (T4spaces + 3)
859 EXTERN const char Tcolsp[] E_INIT(": ");
860 EXTERN const char TC_LEX1[] E_INIT("|&;<>() \t\n");
861 #define TC_IFSWS (TC_LEX1 + 7)
862 EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} $_");
863 #define Tspdollaru (TFCEDIT_dollaru + 18)
864 EXTERN const char Tsgdot[] E_INIT("*=.");
865 EXTERN const char Taugo[] E_INIT("augo");
866 EXTERN const char Tbracket[] E_INIT("[");
867 #define Tdot (Tsgdot + 2)
868 EXTERN const char Talias[] E_INIT("alias");
869 EXTERN const char Tbadsubst[] E_INIT("bad substitution");
870 EXTERN const char Tbg[] E_INIT("bg");
871 EXTERN const char Tbad_bsize[] E_INIT("bad shf/buf/bsize");
872 #define Tbsize (Tbad_bsize + 12)
873 EXTERN const char Tbad_sig_ss[] E_INIT("%s: bad signal '%s'");
874 #define Tbad_sig_s (Tbad_sig_ss + 4)
875 EXTERN const char Tgbuiltin[] E_INIT("=builtin");
876 #define Tbuiltin (Tgbuiltin + 1)
877 EXTERN const char Toomem[] E_INIT("can't allocate %zu data bytes");
878 EXTERN const char Tcant_cd[] E_INIT("restricted shell - can't cd");
879 EXTERN const char Tcant_find[] E_INIT("can't find");
880 EXTERN const char Tcant_open[] E_INIT("can't open");
881 #define Tbytes (Toomem + 24)
882 EXTERN const char Tbcat[] E_INIT("!cat");
883 #define Tcat (Tbcat + 1)
884 #define Tcd (Tcant_cd + 25)
885 EXTERN const char Tcommand[] E_INIT("command");
886 EXTERN const char Tcreate[] E_INIT("create");
887 EXTERN const char TELIF_unexpected[] E_INIT("TELIF unexpected");
888 EXTERN const char TEXECSHELL[] E_INIT("EXECSHELL");
889 EXTERN const char Tsgexport[] E_INIT("*=export");
890 #define Texport (Tsgexport + 2)
891 #ifdef __OS2__
892 EXTERN const char Textproc[] E_INIT("extproc");
893 #endif
894 EXTERN const char Tfalse[] E_INIT("false");
895 EXTERN const char Tfg[] E_INIT("fg");
896 EXTERN const char Tfg_badsubst[] E_INIT("fileglob: bad substitution");
897 EXTERN const char Tfile[] E_INIT("file");
898 EXTERN const char Tfile_fd[] E_INIT("function definition file");
899 EXTERN const char TFPATH[] E_INIT("FPATH");
900 EXTERN const char T_function[] E_INIT(" function");
901 #define Tfunction (T_function + 1)
902 EXTERN const char T_funny_command[] E_INIT("funny $() command");
903 EXTERN const char Tgetopts[] E_INIT("getopts");
904 EXTERN const char Thistory[] E_INIT("history");
905 EXTERN const char Tintovfl[] E_INIT("integer overflow %zu %c %zu prevented");
906 EXTERN const char Tjobs[] E_INIT("jobs");
907 EXTERN const char Tjob_not_started[] E_INIT("job not started");
908 EXTERN const char Tmksh[] E_INIT("mksh");
909 EXTERN const char Tname[] E_INIT("name");
910 EXTERN const char Tno_args[] E_INIT("missing argument");
911 EXTERN const char Tno_OLDPWD[] E_INIT("no OLDPWD");
912 EXTERN const char Tnot_ident[] E_INIT("is not an identifier");
913 EXTERN const char Tnot_in_history[] E_INIT("not in history");
914 EXTERN const char Tnot_found_s[] E_INIT("%s not found");
915 #define Tnot_found (Tnot_found_s + 3)
916 #define Tnot_started (Tjob_not_started + 4)
917 #define TOLDPWD (Tno_OLDPWD + 3)
918 #define Topen (Tcant_open + 6)
919 #define TPATH (TFPATH + 1)
920 EXTERN const char Tpv[] E_INIT("pv");
921 EXTERN const char TpVv[] E_INIT("Vpv");
922 #define TPWD (Tno_OLDPWD + 6)
923 EXTERN const char Tread[] E_INIT("read");
924 EXTERN const char Tsgreadonly[] E_INIT("*=readonly");
925 #define Treadonly (Tsgreadonly + 2)
926 EXTERN const char Tredirection_dup[] E_INIT("can't finish (dup) redirection");
927 #define Tredirection (Tredirection_dup + 19)
928 EXTERN const char Treal_sp1[] E_INIT("real ");
929 EXTERN const char Treal_sp2[] E_INIT(" real ");
930 EXTERN const char Treq_arg[] E_INIT("requires an argument");
931 EXTERN const char Tselect[] E_INIT("select");
932 EXTERN const char Tsgset[] E_INIT("*=set");
933 #define Tset (Tsgset + 2)
934 #define Tsh (Tmksh + 2)
935 #define TSHELL (TEXECSHELL + 4)
936 EXTERN const char Tshf_read[] E_INIT("shf_read");
937 EXTERN const char Tshf_write[] E_INIT("shf_write");
938 EXTERN const char Tj_suspend[] E_INIT("j_suspend");
939 #define Tsuspend (Tj_suspend + 2)
940 EXTERN const char Tsynerr[] E_INIT("syntax error");
941 EXTERN const char Ttime[] E_INIT("time");
942 EXTERN const char Ttoo_many_args[] E_INIT("too many arguments");
943 EXTERN const char Ttrue[] E_INIT("true");
944 EXTERN const char Ttty_fd_dupof[] E_INIT("dup of tty fd");
945 #define Ttty_fd (Ttty_fd_dupof + 7)
946 EXTERN const char Tgtypeset[] E_INIT("=typeset");
947 #define Ttypeset (Tgtypeset + 1)
948 #define Tugo (Taugo + 1)
949 EXTERN const char Tunalias[] E_INIT("unalias");
950 #define Tunexpected (TELIF_unexpected + 6)
951 EXTERN const char Tunknown_option[] E_INIT("unknown option");
952 EXTERN const char Tuser_sp1[] E_INIT("user ");
953 EXTERN const char Tuser_sp2[] E_INIT(" user ");
954 #define Twrite (Tshf_write + 4)
955 EXTERN const char Tf__S[] E_INIT(" %S");
956 EXTERN const char Tf__d[] E_INIT(" %d");
957 EXTERN const char Tf__ss[] E_INIT(" %s%s");
958 EXTERN const char Tf__sN[] E_INIT(" %s\n");
959 EXTERN const char Tf_sSs[] E_INIT("%s/%s");
960 EXTERN const char Tf_T[] E_INIT("%T");
961 EXTERN const char Tf_dN[] E_INIT("%d\n");
962 EXTERN const char Tf_s_[] E_INIT("%s ");
963 EXTERN const char Tf_s_T[] E_INIT("%s %T");
964 EXTERN const char Tf_s_s_sN[] E_INIT("%s %s %s\n");
965 EXTERN const char Tf_s_s[] E_INIT("%s %s");
966 EXTERN const char Tf_s_sD_s[] E_INIT("%s %s: %s");
967 EXTERN const char Tf_optfoo[] E_INIT("%s%s-%c: %s");
968 EXTERN const char Tf_sD_[] E_INIT("%s: ");
969 EXTERN const char Tf_szs[] E_INIT("%s: %zd %s");
970 EXTERN const char Tf_parm[] E_INIT("%s: parameter not set");
971 EXTERN const char Tf_coproc[] E_INIT("-p: %s");
972 EXTERN const char Tf_cant[] E_INIT("can't %s %s: %s");
973 EXTERN const char Tf_heredoc[] E_INIT("here document '%s' unclosed\n");
974 #if HAVE_MKNOD
975 EXTERN const char Tf_nonnum[] E_INIT("non-numeric %s %s '%s'");
976 #endif
977 EXTERN const char Tf_S_[] E_INIT("%S ");
978 #define Tf_S (Tf__S + 1)
979 EXTERN const char Tf_lu[] E_INIT("%lu");
980 EXTERN const char Tf_toolarge[] E_INIT("%s %s too large: %lu");
981 EXTERN const char Tf_ldfailed[] E_INIT("%s %s(%d, %ld) failed: %s");
982 #define Tf_ss (Tf__ss + 1)
983 EXTERN const char Tf_sss[] E_INIT("%s%s%s");
984 EXTERN const char Tf_sD_s_sD_s[] E_INIT("%s: %s %s: %s");
985 EXTERN const char Tf_toomany[] E_INIT("too many %ss\n");
986 EXTERN const char Tf_sd[] E_INIT("%s %d");
987 #define Tf_s (Tf__ss + 3)
988 EXTERN const char Tft_end[] E_INIT("%;");
989 EXTERN const char Tft_R[] E_INIT("%R");
990 #define Tf_d (Tf__d + 1)
991 EXTERN const char Tf_sD_s_qs[] E_INIT("%s: %s '%s'");
992 EXTERN const char Tf_ro[] E_INIT("read-only: %s");
993 EXTERN const char Tf_flags[] E_INIT("%s: flags 0x%X");
994 EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s: %s");
995 EXTERN const char Tf_ssfaileds[] E_INIT("%s: %s failed: %s");
996 EXTERN const char Tf_sD_sD_s[] E_INIT("%s: %s: %s");
997 EXTERN const char Tf__c_[] E_INIT("-%c ");
998 EXTERN const char Tf_sD_s_s[] E_INIT("%s: %s %s");
999 #define Tf_sN (Tf__sN + 1)
1000 #define Tf_sD_s (Tf_s_sD_s + 3)
1001 EXTERN const char T_devtty[] E_INIT("/dev/tty");
1002 #else /* helpers for string pooling */
1003 #define T4spaces "    "
1004 #define T1space " "
1005 #define Tcolsp ": "
1006 #define TC_LEX1 "|&;<>() \t\n"
1007 #define TC_IFSWS " \t\n"
1008 #define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} $_"
1009 #define Tspdollaru " $_"
1010 #define Tsgdot "*=."
1011 #define Taugo "augo"
1012 #define Tbracket "["
1013 #define Tdot "."
1014 #define Talias "alias"
1015 #define Tbadsubst "bad substitution"
1016 #define Tbg "bg"
1017 #define Tbad_bsize "bad shf/buf/bsize"
1018 #define Tbsize "bsize"
1019 #define Tbad_sig_ss "%s: bad signal '%s'"
1020 #define Tbad_sig_s "bad signal '%s'"
1021 #define Tgbuiltin "=builtin"
1022 #define Tbuiltin "builtin"
1023 #define Toomem "can't allocate %zu data bytes"
1024 #define Tcant_cd "restricted shell - can't cd"
1025 #define Tcant_find "can't find"
1026 #define Tcant_open "can't open"
1027 #define Tbytes "bytes"
1028 #define Tbcat "!cat"
1029 #define Tcat "cat"
1030 #define Tcd "cd"
1031 #define Tcommand "command"
1032 #define Tcreate "create"
1033 #define TELIF_unexpected "TELIF unexpected"
1034 #define TEXECSHELL "EXECSHELL"
1035 #define Tsgexport "*=export"
1036 #define Texport "export"
1037 #ifdef __OS2__
1038 #define Textproc "extproc"
1039 #endif
1040 #define Tfalse "false"
1041 #define Tfg "fg"
1042 #define Tfg_badsubst "fileglob: bad substitution"
1043 #define Tfile "file"
1044 #define Tfile_fd "function definition file"
1045 #define TFPATH "FPATH"
1046 #define T_function " function"
1047 #define Tfunction "function"
1048 #define T_funny_command "funny $() command"
1049 #define Tgetopts "getopts"
1050 #define Thistory "history"
1051 #define Tintovfl "integer overflow %zu %c %zu prevented"
1052 #define Tjobs "jobs"
1053 #define Tjob_not_started "job not started"
1054 #define Tmksh "mksh"
1055 #define Tname "name"
1056 #define Tno_args "missing argument"
1057 #define Tno_OLDPWD "no OLDPWD"
1058 #define Tnot_ident "is not an identifier"
1059 #define Tnot_in_history "not in history"
1060 #define Tnot_found_s "%s not found"
1061 #define Tnot_found "not found"
1062 #define Tnot_started "not started"
1063 #define TOLDPWD "OLDPWD"
1064 #define Topen "open"
1065 #define TPATH "PATH"
1066 #define Tpv "pv"
1067 #define TpVv "Vpv"
1068 #define TPWD "PWD"
1069 #define Tread "read"
1070 #define Tsgreadonly "*=readonly"
1071 #define Treadonly "readonly"
1072 #define Tredirection_dup "can't finish (dup) redirection"
1073 #define Tredirection "redirection"
1074 #define Treal_sp1 "real "
1075 #define Treal_sp2 " real "
1076 #define Treq_arg "requires an argument"
1077 #define Tselect "select"
1078 #define Tsgset "*=set"
1079 #define Tset "set"
1080 #define Tsh "sh"
1081 #define TSHELL "SHELL"
1082 #define Tshf_read "shf_read"
1083 #define Tshf_write "shf_write"
1084 #define Tj_suspend "j_suspend"
1085 #define Tsuspend "suspend"
1086 #define Tsynerr "syntax error"
1087 #define Ttime "time"
1088 #define Ttoo_many_args "too many arguments"
1089 #define Ttrue "true"
1090 #define Ttty_fd_dupof "dup of tty fd"
1091 #define Ttty_fd "tty fd"
1092 #define Tgtypeset "=typeset"
1093 #define Ttypeset "typeset"
1094 #define Tugo "ugo"
1095 #define Tunalias "unalias"
1096 #define Tunexpected "unexpected"
1097 #define Tunknown_option "unknown option"
1098 #define Tuser_sp1 "user "
1099 #define Tuser_sp2 " user "
1100 #define Twrite "write"
1101 #define Tf__S " %S"
1102 #define Tf__d " %d"
1103 #define Tf__ss " %s%s"
1104 #define Tf__sN " %s\n"
1105 #define Tf_sSs "%s/%s"
1106 #define Tf_T "%T"
1107 #define Tf_dN "%d\n"
1108 #define Tf_s_ "%s "
1109 #define Tf_s_T "%s %T"
1110 #define Tf_s_s_sN "%s %s %s\n"
1111 #define Tf_s_s "%s %s"
1112 #define Tf_s_sD_s "%s %s: %s"
1113 #define Tf_optfoo "%s%s-%c: %s"
1114 #define Tf_sD_ "%s: "
1115 #define Tf_szs "%s: %zd %s"
1116 #define Tf_parm "%s: parameter not set"
1117 #define Tf_coproc "-p: %s"
1118 #define Tf_cant "can't %s %s: %s"
1119 #define Tf_heredoc "here document '%s' unclosed\n"
1120 #if HAVE_MKNOD
1121 #define Tf_nonnum "non-numeric %s %s '%s'"
1122 #endif
1123 #define Tf_S_ "%S "
1124 #define Tf_S "%S"
1125 #define Tf_lu "%lu"
1126 #define Tf_toolarge "%s %s too large: %lu"
1127 #define Tf_ldfailed "%s %s(%d, %ld) failed: %s"
1128 #define Tf_ss "%s%s"
1129 #define Tf_sss "%s%s%s"
1130 #define Tf_sD_s_sD_s "%s: %s %s: %s"
1131 #define Tf_toomany "too many %ss\n"
1132 #define Tf_sd "%s %d"
1133 #define Tf_s "%s"
1134 #define Tft_end "%;"
1135 #define Tft_R "%R"
1136 #define Tf_d "%d"
1137 #define Tf_sD_s_qs "%s: %s '%s'"
1138 #define Tf_ro "read-only: %s"
1139 #define Tf_flags "%s: flags 0x%X"
1140 #define Tf_temp "can't %s temporary file %s: %s"
1141 #define Tf_ssfaileds "%s: %s failed: %s"
1142 #define Tf_sD_sD_s "%s: %s: %s"
1143 #define Tf__c_ "-%c "
1144 #define Tf_sD_s_s "%s: %s %s"
1145 #define Tf_sN "%s\n"
1146 #define Tf_sD_s "%s: %s"
1147 #define T_devtty "/dev/tty"
1148 #endif /* end of string pooling */
1149
1150 typedef uint8_t Temp_type;
1151 /* expanded heredoc */
1152 #define TT_HEREDOC_EXP  0
1153 /* temporary file used for history editing (fc -e) */
1154 #define TT_HIST_EDIT    1
1155 /* temporary file used during in-situ command substitution */
1156 #define TT_FUNSUB       2
1157
1158 /* temp/heredoc files. The file is removed when the struct is freed. */
1159 struct temp {
1160         struct temp *next;
1161         struct shf *shf;
1162         /* pid of process parsed here-doc */
1163         pid_t pid;
1164         Temp_type type;
1165         /* actually longer: name (variable length) */
1166         char tffn[3];
1167 };
1168
1169 /*
1170  * stdio and our IO routines
1171  */
1172
1173 #define shl_xtrace      (&shf_iob[0])   /* for set -x */
1174 #define shl_stdout      (&shf_iob[1])
1175 #define shl_out         (&shf_iob[2])
1176 #ifdef DF
1177 #define shl_dbg         (&shf_iob[3])   /* for DF() */
1178 #endif
1179 EXTERN bool shl_stdout_ok;
1180
1181 /*
1182  * trap handlers
1183  */
1184 typedef struct trap {
1185         const char *name;       /* short name */
1186         const char *mess;       /* descriptive name */
1187         char *trap;             /* trap command */
1188         sig_t cursig;           /* current handler (valid if TF_ORIG_* set) */
1189         sig_t shtrap;           /* shell signal handler */
1190         int signal;             /* signal number */
1191         int flags;              /* TF_* */
1192         volatile sig_atomic_t set; /* trap pending */
1193 } Trap;
1194
1195 /* values for Trap.flags */
1196 #define TF_SHELL_USES   BIT(0)  /* shell uses signal, user can't change */
1197 #define TF_USER_SET     BIT(1)  /* user has (tried to) set trap */
1198 #define TF_ORIG_IGN     BIT(2)  /* original action was SIG_IGN */
1199 #define TF_ORIG_DFL     BIT(3)  /* original action was SIG_DFL */
1200 #define TF_EXEC_IGN     BIT(4)  /* restore SIG_IGN just before exec */
1201 #define TF_EXEC_DFL     BIT(5)  /* restore SIG_DFL just before exec */
1202 #define TF_DFL_INTR     BIT(6)  /* when received, default action is LINTR */
1203 #define TF_TTY_INTR     BIT(7)  /* tty generated signal (see j_waitj) */
1204 #define TF_CHANGED      BIT(8)  /* used by runtrap() to detect trap changes */
1205 #define TF_FATAL        BIT(9)  /* causes termination if not trapped */
1206
1207 /* values for setsig()/setexecsig() flags argument */
1208 #define SS_RESTORE_MASK 0x3     /* how to restore a signal before an exec() */
1209 #define SS_RESTORE_CURR 0       /* leave current handler in place */
1210 #define SS_RESTORE_ORIG 1       /* restore original handler */
1211 #define SS_RESTORE_DFL  2       /* restore to SIG_DFL */
1212 #define SS_RESTORE_IGN  3       /* restore to SIG_IGN */
1213 #define SS_FORCE        BIT(3)  /* set signal even if original signal ignored */
1214 #define SS_USER         BIT(4)  /* user is doing the set (ie, trap command) */
1215 #define SS_SHTRAP       BIT(5)  /* trap for internal use (ALRM, CHLD, WINCH) */
1216
1217 #define ksh_SIGEXIT 0           /* for trap EXIT */
1218 #define ksh_SIGERR  ksh_NSIG    /* for trap ERR */
1219
1220 EXTERN volatile sig_atomic_t trap;      /* traps pending? */
1221 EXTERN volatile sig_atomic_t intrsig;   /* pending trap interrupts command */
1222 EXTERN volatile sig_atomic_t fatal_trap; /* received a fatal signal */
1223 extern Trap sigtraps[ksh_NSIG + 1];
1224
1225 /* got_winch = 1 when we need to re-adjust the window size */
1226 #ifdef SIGWINCH
1227 EXTERN volatile sig_atomic_t got_winch E_INIT(1);
1228 #else
1229 #define got_winch       true
1230 #endif
1231
1232 /*
1233  * TMOUT support
1234  */
1235 /* values for ksh_tmout_state */
1236 enum tmout_enum {
1237         TMOUT_EXECUTING = 0,    /* executing commands */
1238         TMOUT_READING,          /* waiting for input */
1239         TMOUT_LEAVING           /* have timed out */
1240 };
1241 EXTERN unsigned int ksh_tmout;
1242 EXTERN enum tmout_enum ksh_tmout_state E_INIT(TMOUT_EXECUTING);
1243
1244 /* For "You have stopped jobs" message */
1245 EXTERN bool really_exit;
1246
1247 /*
1248  * fast character classes
1249  */
1250 #define C_ALPHA  BIT(0)         /* a-z_A-Z */
1251 #define C_DIGIT  BIT(1)         /* 0-9 */
1252 #define C_LEX1   BIT(2)         /* \t \n\0|&;<>() */
1253 #define C_VAR1   BIT(3)         /* *@#!$-? */
1254 #define C_IFSWS  BIT(4)         /* \t \n (IFS white space) */
1255 #define C_SUBOP1 BIT(5)         /* "=-+?" */
1256 #define C_QUOTE  BIT(6)         /* \t\n "#$&'()*;<=>?[\]`| (needing quoting) */
1257 #define C_IFS    BIT(7)         /* $IFS */
1258 #define C_SUBOP2 BIT(8)         /* "#%" (magic, see below) */
1259
1260 extern unsigned char chtypes[];
1261
1262 #define ctype(c, t)     tobool( ((t) == C_SUBOP2) ?                     \
1263                             (((c) == '#' || (c) == '%') ? 1 : 0) :      \
1264                             (chtypes[(unsigned char)(c)] & (t)) )
1265 #define ord(c)          ((int)(unsigned char)(c))
1266 #define ksh_isalphx(c)  ctype((c), C_ALPHA)
1267 #define ksh_isalnux(c)  ctype((c), C_ALPHA | C_DIGIT)
1268 #define ksh_isdigit(c)  (((c) >= '0') && ((c) <= '9'))
1269 #define ksh_islower(c)  (((c) >= 'a') && ((c) <= 'z'))
1270 #define ksh_isupper(c)  (((c) >= 'A') && ((c) <= 'Z'))
1271 #define ksh_tolower(c)  (ksh_isupper(c) ? (c) - 'A' + 'a' : (c))
1272 #define ksh_toupper(c)  (ksh_islower(c) ? (c) - 'a' + 'A' : (c))
1273 #define ksh_isdash(s)   (((s)[0] == '-') && ((s)[1] == '\0'))
1274 #define ksh_isspace(c)  ((((c) >= 0x09) && ((c) <= 0x0D)) || ((c) == 0x20))
1275 #define ksh_eq(c,u,l)   (((c) | 0x20) == (l))
1276 #define ksh_numdig(c)   ((c) - ord('0'))
1277 #define ksh_numuc(c)    ((c) - ord('A'))
1278 #define ksh_numlc(c)    ((c) - ord('a'))
1279
1280 EXTERN int ifs0 E_INIT(' ');    /* for "$*" */
1281
1282 /* Argument parsing for built-in commands and getopts command */
1283
1284 /* Values for Getopt.flags */
1285 #define GF_ERROR        BIT(0)  /* call errorf() if there is an error */
1286 #define GF_PLUSOPT      BIT(1)  /* allow +c as an option */
1287 #define GF_NONAME       BIT(2)  /* don't print argv[0] in errors */
1288
1289 /* Values for Getopt.info */
1290 #define GI_MINUS        BIT(0)  /* an option started with -... */
1291 #define GI_PLUS         BIT(1)  /* an option started with +... */
1292 #define GI_MINUSMINUS   BIT(2)  /* arguments were ended with -- */
1293
1294 /* in case some OS defines these */
1295 #undef optarg
1296 #undef optind
1297
1298 typedef struct {
1299         const char *optarg;
1300         int optind;
1301         int uoptind;            /* what user sees in $OPTIND */
1302         int flags;              /* see GF_* */
1303         int info;               /* see GI_* */
1304         unsigned int p;         /* 0 or index into argv[optind - 1] */
1305         char buf[2];            /* for bad option OPTARG value */
1306 } Getopt;
1307
1308 EXTERN Getopt builtin_opt;      /* for shell builtin commands */
1309 EXTERN Getopt user_opt;         /* parsing state for getopts builtin command */
1310
1311 /* This for co-processes */
1312
1313 /* something that won't (realisticly) wrap */
1314 typedef int Coproc_id;
1315
1316 struct coproc {
1317         void *job;      /* 0 or job of co-process using input pipe */
1318         int read;       /* pipe from co-process's stdout */
1319         int readw;      /* other side of read (saved temporarily) */
1320         int write;      /* pipe to co-process's stdin */
1321         int njobs;      /* number of live jobs using output pipe */
1322         Coproc_id id;   /* id of current output pipe */
1323 };
1324 EXTERN struct coproc coproc;
1325
1326 #ifndef MKSH_NOPROSPECTOFWORK
1327 /* used in jobs.c and by coprocess stuff in exec.c and select() calls */
1328 EXTERN sigset_t         sm_default, sm_sigchld;
1329 #endif
1330
1331 /* name of called builtin function (used by error functions) */
1332 EXTERN const char *builtin_argv0;
1333 /* is called builtin SPEC_BI? (also KEEPASN, odd use though) */
1334 EXTERN bool builtin_spec;
1335
1336 /* current working directory */
1337 EXTERN char     *current_wd;
1338
1339 /* input line size */
1340 #ifdef MKSH_SMALL
1341 #define LINE            (4096 - ALLOC_OVERHEAD)
1342 #else
1343 #define LINE            (16384 - ALLOC_OVERHEAD)
1344 #endif
1345 /* columns and lines of the tty */
1346 EXTERN mksh_ari_t x_cols E_INIT(80);
1347 EXTERN mksh_ari_t x_lins E_INIT(24);
1348
1349
1350 /* Determine the location of the system (common) profile */
1351
1352 #ifndef MKSH_DEFAULT_PROFILEDIR
1353 #define MKSH_DEFAULT_PROFILEDIR "/etc"
1354 #endif
1355
1356 #define MKSH_SYSTEM_PROFILE     MKSH_DEFAULT_PROFILEDIR "/profile"
1357 #define MKSH_SUID_PROFILE       MKSH_DEFAULT_PROFILEDIR "/suid_profile"
1358
1359
1360 /* Used by v_evaluate() and setstr() to control action when error occurs */
1361 #define KSH_UNWIND_ERROR        0       /* unwind the stack (kshlongjmp) */
1362 #define KSH_RETURN_ERROR        1       /* return 1/0 for success/failure */
1363
1364 /*
1365  * Shell file I/O routines
1366  */
1367
1368 #define SHF_BSIZE               512
1369
1370 #define shf_fileno(shf)         ((shf)->fd)
1371 #define shf_setfileno(shf,nfd)  ((shf)->fd = (nfd))
1372 #define shf_getc_i(shf)         ((shf)->rnleft > 0 ? \
1373                                     (shf)->rnleft--, *(shf)->rp++ : \
1374                                     shf_getchar(shf))
1375 #define shf_putc_i(c, shf)      ((shf)->wnleft == 0 ? \
1376                                     shf_putchar((uint8_t)(c), (shf)) : \
1377                                     ((shf)->wnleft--, *(shf)->wp++ = (c)))
1378 #define shf_eof(shf)            ((shf)->flags & SHF_EOF)
1379 #define shf_error(shf)          ((shf)->flags & SHF_ERROR)
1380 #define shf_errno(shf)          ((shf)->errnosv)
1381 #define shf_clearerr(shf)       ((shf)->flags &= ~(SHF_EOF | SHF_ERROR))
1382
1383 /* Flags passed to shf_*open() */
1384 #define SHF_RD          0x0001
1385 #define SHF_WR          0x0002
1386 #define SHF_RDWR        (SHF_RD|SHF_WR)
1387 #define SHF_ACCMODE     0x0003          /* mask */
1388 #define SHF_GETFL       0x0004          /* use fcntl() to figure RD/WR flags */
1389 #define SHF_UNBUF       0x0008          /* unbuffered I/O */
1390 #define SHF_CLEXEC      0x0010          /* set close on exec flag */
1391 #define SHF_MAPHI       0x0020          /* make fd > FDBASE (and close orig)
1392                                          * (shf_open() only) */
1393 #define SHF_DYNAMIC     0x0040          /* string: increase buffer as needed */
1394 #define SHF_INTERRUPT   0x0080          /* EINTR in read/write causes error */
1395 /* Flags used internally */
1396 #define SHF_STRING      0x0100          /* a string, not a file */
1397 #define SHF_ALLOCS      0x0200          /* shf and shf->buf were alloc()ed */
1398 #define SHF_ALLOCB      0x0400          /* shf->buf was alloc()ed */
1399 #define SHF_ERROR       0x0800          /* read()/write() error */
1400 #define SHF_EOF         0x1000          /* read eof (sticky) */
1401 #define SHF_READING     0x2000          /* currently reading: rnleft,rp valid */
1402 #define SHF_WRITING     0x4000          /* currently writing: wnleft,wp valid */
1403
1404
1405 struct shf {
1406         Area *areap;            /* area shf/buf were allocated in */
1407         unsigned char *rp;      /* read: current position in buffer */
1408         unsigned char *wp;      /* write: current position in buffer */
1409         unsigned char *buf;     /* buffer */
1410         ssize_t bsize;          /* actual size of buf */
1411         ssize_t rbsize;         /* size of buffer (1 if SHF_UNBUF) */
1412         ssize_t rnleft;         /* read: how much data left in buffer */
1413         ssize_t wbsize;         /* size of buffer (0 if SHF_UNBUF) */
1414         ssize_t wnleft;         /* write: how much space left in buffer */
1415         int flags;              /* see SHF_* */
1416         int fd;                 /* file descriptor */
1417         int errnosv;            /* saved value of errno after error */
1418 };
1419
1420 extern struct shf shf_iob[];
1421
1422 struct table {
1423         Area *areap;            /* area to allocate entries */
1424         struct tbl **tbls;      /* hashed table items */
1425         size_t nfree;           /* free table entries */
1426         uint8_t tshift;         /* table size (2^tshift) */
1427 };
1428
1429 /* table item */
1430 struct tbl {
1431         /* Area to allocate from */
1432         Area *areap;
1433         /* value */
1434         union {
1435                 char *s;                        /* string */
1436                 mksh_ari_t i;                   /* integer */
1437                 mksh_uari_t u;                  /* unsigned integer */
1438                 int (*f)(const char **);        /* built-in command */
1439                 struct op *t;                   /* "function" tree */
1440         } val;
1441         union {
1442                 struct tbl *array;      /* array values */
1443                 const char *fpath;      /* temporary path to undef function */
1444         } u;
1445         union {
1446                 int field;              /* field with for -L/-R/-Z */
1447                 int errnov;             /* CEXEC/CTALIAS */
1448         } u2;
1449         union {
1450                 uint32_t hval;          /* hash(name) */
1451                 uint32_t index;         /* index for an array */
1452         } ua;
1453         /*
1454          * command type (see below), base (if INTEGER),
1455          * offset from val.s of value (if EXPORT)
1456          */
1457         int type;
1458         /* flags (see below) */
1459         uint32_t flag;
1460
1461         /* actually longer: name (variable length) */
1462         char name[4];
1463 };
1464
1465 EXTERN struct tbl *vtemp;
1466 /* set by global() and local() */
1467 EXTERN bool last_lookup_was_array;
1468
1469 /* common flag bits */
1470 #define ALLOC           BIT(0)  /* val.s has been allocated */
1471 #define DEFINED         BIT(1)  /* is defined in block */
1472 #define ISSET           BIT(2)  /* has value, vp->val.[si] */
1473 #define EXPORT          BIT(3)  /* exported variable/function */
1474 #define TRACE           BIT(4)  /* var: user flagged, func: execution tracing */
1475 /* (start non-common flags at 8) */
1476 /* flag bits used for variables */
1477 #define SPECIAL         BIT(8)  /* PATH, IFS, SECONDS, etc */
1478 #define INTEGER         BIT(9)  /* val.i contains integer value */
1479 #define RDONLY          BIT(10) /* read-only variable */
1480 #define LOCAL           BIT(11) /* for local typeset() */
1481 #define ARRAY           BIT(13) /* array */
1482 #define LJUST           BIT(14) /* left justify */
1483 #define RJUST           BIT(15) /* right justify */
1484 #define ZEROFIL         BIT(16) /* 0 filled if RJUSTIFY, strip 0s if LJUSTIFY */
1485 #define LCASEV          BIT(17) /* convert to lower case */
1486 #define UCASEV_AL       BIT(18) /* convert to upper case / autoload function */
1487 #define INT_U           BIT(19) /* unsigned integer */
1488 #define INT_L           BIT(20) /* long integer (no-op but used as magic) */
1489 #define IMPORT          BIT(21) /* flag to typeset(): no arrays, must have = */
1490 #define LOCAL_COPY      BIT(22) /* with LOCAL - copy attrs from existing var */
1491 #define EXPRINEVAL      BIT(23) /* contents currently being evaluated */
1492 #define EXPRLVALUE      BIT(24) /* useable as lvalue (temp flag) */
1493 #define AINDEX          BIT(25) /* array index >0 = ua.index filled in */
1494 #define ASSOC           BIT(26) /* ARRAY ? associative : reference */
1495 /* flag bits used for taliases/builtins/aliases/keywords/functions */
1496 #define KEEPASN         BIT(8)  /* keep command assignments (eg, var=x cmd) */
1497 #define FINUSE          BIT(9)  /* function being executed */
1498 #define FDELETE         BIT(10) /* function deleted while it was executing */
1499 #define FKSH            BIT(11) /* function defined with function x (vs x()) */
1500 #define SPEC_BI         BIT(12) /* a POSIX special builtin */
1501 #define LOWER_BI        BIT(13) /* (with LOW_BI) override even w/o flags */
1502 #define LOW_BI          BIT(14) /* external utility overrides built-in one */
1503
1504 /*
1505  * Attributes that can be set by the user (used to decide if an unset
1506  * param should be repoted by set/typeset). Does not include ARRAY or
1507  * LOCAL.
1508  */
1509 #define USERATTRIB      (EXPORT|INTEGER|RDONLY|LJUST|RJUST|ZEROFIL|\
1510                             LCASEV|UCASEV_AL|INT_U|INT_L)
1511
1512 #define arrayindex(vp)  ((unsigned long)((vp)->flag & AINDEX ? \
1513                             (vp)->ua.index : 0))
1514
1515 enum namerefflag {
1516         SRF_NOP,
1517         SRF_ENABLE,
1518         SRF_DISABLE
1519 };
1520
1521 /* command types */
1522 #define CNONE           0       /* undefined */
1523 #define CSHELL          1       /* built-in */
1524 #define CFUNC           2       /* function */
1525 #define CEXEC           4       /* executable command */
1526 #define CALIAS          5       /* alias */
1527 #define CKEYWD          6       /* keyword */
1528 #define CTALIAS         7       /* tracked alias */
1529
1530 /* Flags for findcom()/comexec() */
1531 #define FC_SPECBI       BIT(0)  /* special builtin */
1532 #define FC_FUNC         BIT(1)  /* function */
1533 #define FC_NORMBI       BIT(2)  /* not special builtin */
1534 #define FC_BI           (FC_SPECBI | FC_NORMBI)
1535 #define FC_PATH         BIT(3)  /* do path search */
1536 #define FC_DEFPATH      BIT(4)  /* use default path in path search */
1537 #define FC_WHENCE       BIT(5)  /* for use by command and whence */
1538
1539 #define AF_ARGV_ALLOC   0x1     /* argv[] array allocated */
1540 #define AF_ARGS_ALLOCED 0x2     /* argument strings allocated */
1541 #define AI_ARGV(a, i)   ((i) == 0 ? (a).argv[0] : (a).argv[(i) - (a).skip])
1542 #define AI_ARGC(a)      ((a).ai_argc - (a).skip)
1543
1544 /* Argument info. Used for $#, $* for shell, functions, includes, etc. */
1545 struct arg_info {
1546         const char **argv;
1547         int flags;      /* AF_* */
1548         int ai_argc;
1549         int skip;       /* first arg is argv[0], second is argv[1 + skip] */
1550 };
1551
1552 /*
1553  * activation record for function blocks
1554  */
1555 struct block {
1556         Area area;              /* area to allocate things */
1557         const char **argv;
1558         char *error;            /* error handler */
1559         char *exit;             /* exit handler */
1560         struct block *next;     /* enclosing block */
1561         struct table vars;      /* local variables */
1562         struct table funs;      /* local functions */
1563         Getopt getopts_state;
1564         int argc;
1565         int flags;              /* see BF_* */
1566 };
1567
1568 /* Values for struct block.flags */
1569 #define BF_DOGETOPTS    BIT(0)  /* save/restore getopts state */
1570 #define BF_STOPENV      BIT(1)  /* do not export further */
1571
1572 /*
1573  * Used by ktwalk() and ktnext() routines.
1574  */
1575 struct tstate {
1576         struct tbl **next;
1577         ssize_t left;
1578 };
1579
1580 EXTERN struct table taliases;   /* tracked aliases */
1581 EXTERN struct table builtins;   /* built-in commands */
1582 EXTERN struct table aliases;    /* aliases */
1583 EXTERN struct table keywords;   /* keywords */
1584 #ifndef MKSH_NOPWNAM
1585 EXTERN struct table homedirs;   /* homedir() cache */
1586 #endif
1587
1588 struct builtin {
1589         const char *name;
1590         int (*func)(const char **);
1591 };
1592
1593 extern const struct builtin mkshbuiltins[];
1594
1595 /* values for set_prompt() */
1596 #define PS1     0       /* command */
1597 #define PS2     1       /* command continuation */
1598
1599 EXTERN char *path;              /* copy of either PATH or def_path */
1600 EXTERN const char *def_path;    /* path to use if PATH not set */
1601 EXTERN char *tmpdir;            /* TMPDIR value */
1602 EXTERN const char *prompt;
1603 EXTERN uint8_t cur_prompt;      /* PS1 or PS2 */
1604 EXTERN int current_lineno;      /* LINENO value */
1605
1606 /*
1607  * Description of a command or an operation on commands.
1608  */
1609 struct op {
1610         const char **args;              /* arguments to a command */
1611         char **vars;                    /* variable assignments */
1612         struct ioword **ioact;          /* IO actions (eg, < > >>) */
1613         struct op *left, *right;        /* descendents */
1614         char *str;                      /* word for case; identifier for for,
1615                                          * select, and functions;
1616                                          * path to execute for TEXEC;
1617                                          * time hook for TCOM.
1618                                          */
1619         int lineno;                     /* TCOM/TFUNC: LINENO for this */
1620         short type;                     /* operation type, see below */
1621         /* WARNING: newtp(), tcopy() use evalflags = 0 to clear union */
1622         union {
1623                 /* TCOM: arg expansion eval() flags */
1624                 short evalflags;
1625                 /* TFUNC: function x (vs x()) */
1626                 short ksh_func;
1627                 /* TPAT: termination character */
1628                 char charflag;
1629         } u;
1630 };
1631
1632 /* Tree.type values */
1633 #define TEOF            0
1634 #define TCOM            1       /* command */
1635 #define TPAREN          2       /* (c-list) */
1636 #define TPIPE           3       /* a | b */
1637 #define TLIST           4       /* a ; b */
1638 #define TOR             5       /* || */
1639 #define TAND            6       /* && */
1640 #define TBANG           7       /* ! */
1641 #define TDBRACKET       8       /* [[ .. ]] */
1642 #define TFOR            9
1643 #define TSELECT         10
1644 #define TCASE           11
1645 #define TIF             12
1646 #define TWHILE          13
1647 #define TUNTIL          14
1648 #define TELIF           15
1649 #define TPAT            16      /* pattern in case */
1650 #define TBRACE          17      /* {c-list} */
1651 #define TASYNC          18      /* c & */
1652 #define TFUNCT          19      /* function name { command; } */
1653 #define TTIME           20      /* time pipeline */
1654 #define TEXEC           21      /* fork/exec eval'd TCOM */
1655 #define TCOPROC         22      /* coprocess |& */
1656
1657 /*
1658  * prefix codes for words in command tree
1659  */
1660 #define EOS     0       /* end of string */
1661 #define CHAR    1       /* unquoted character */
1662 #define QCHAR   2       /* quoted character */
1663 #define COMSUB  3       /* $() substitution (0 terminated) */
1664 #define EXPRSUB 4       /* $(()) substitution (0 terminated) */
1665 #define OQUOTE  5       /* opening " or ' */
1666 #define CQUOTE  6       /* closing " or ' */
1667 #define OSUBST  7       /* opening ${ subst (followed by { or X) */
1668 #define CSUBST  8       /* closing } of above (followed by } or X) */
1669 #define OPAT    9       /* open pattern: *(, @(, etc. */
1670 #define SPAT    10      /* separate pattern: | */
1671 #define CPAT    11      /* close pattern: ) */
1672 #define ADELIM  12      /* arbitrary delimiter: ${foo:2:3} ${foo/bar/baz} */
1673 #define FUNSUB  14      /* ${ foo;} substitution (NUL terminated) */
1674 #define VALSUB  15      /* ${|foo;} substitution (NUL terminated) */
1675
1676 /*
1677  * IO redirection
1678  */
1679 struct ioword {
1680         char *ioname;           /* filename (unused if heredoc) */
1681         char *delim;            /* delimiter for <<, <<- */
1682         char *heredoc;          /* content of heredoc */
1683         unsigned short ioflag;  /* action (below) */
1684         short unit;             /* unit (fd) affected */
1685 };
1686
1687 /* ioword.flag - type of redirection */
1688 #define IOTYPE          0xF     /* type: bits 0:3 */
1689 #define IOREAD          0x1     /* < */
1690 #define IOWRITE         0x2     /* > */
1691 #define IORDWR          0x3     /* <>: todo */
1692 #define IOHERE          0x4     /* << (here file) */
1693 #define IOCAT           0x5     /* >> */
1694 #define IODUP           0x6     /* <&/>& */
1695 #define IOEVAL          BIT(4)  /* expand in << */
1696 #define IOSKIP          BIT(5)  /* <<-, skip ^\t* */
1697 #define IOCLOB          BIT(6)  /* >|, override -o noclobber */
1698 #define IORDUP          BIT(7)  /* x<&y (as opposed to x>&y) */
1699 #define IONAMEXP        BIT(8)  /* name has been expanded */
1700 #define IOBASH          BIT(9)  /* &> etc. */
1701 #define IOHERESTR       BIT(10) /* <<< (here string) */
1702 #define IONDELIM        BIT(11) /* null delimiter (<<) */
1703
1704 /* execute/exchild flags */
1705 #define XEXEC   BIT(0)          /* execute without forking */
1706 #define XFORK   BIT(1)          /* fork before executing */
1707 #define XBGND   BIT(2)          /* command & */
1708 #define XPIPEI  BIT(3)          /* input is pipe */
1709 #define XPIPEO  BIT(4)          /* output is pipe */
1710 #define XXCOM   BIT(5)          /* `...` command */
1711 #define XPCLOSE BIT(6)          /* exchild: close close_fd in parent */
1712 #define XCCLOSE BIT(7)          /* exchild: close close_fd in child */
1713 #define XERROK  BIT(8)          /* non-zero exit ok (for set -e) */
1714 #define XCOPROC BIT(9)          /* starting a co-process */
1715 #define XTIME   BIT(10)         /* timing TCOM command */
1716 #define XPIPEST BIT(11)         /* want PIPESTATUS */
1717
1718 /*
1719  * flags to control expansion of words (assumed by t->evalflags to fit
1720  * in a short)
1721  */
1722 #define DOBLANK BIT(0)          /* perform blank interpretation */
1723 #define DOGLOB  BIT(1)          /* expand [?* */
1724 #define DOPAT   BIT(2)          /* quote *?[ */
1725 #define DOTILDE BIT(3)          /* normal ~ expansion (first char) */
1726 #define DONTRUNCOMMAND BIT(4)   /* do not run $(command) things */
1727 #define DOASNTILDE BIT(5)       /* assignment ~ expansion (after =, :) */
1728 #define DOBRACE BIT(6)          /* used by expand(): do brace expansion */
1729 #define DOMAGIC BIT(7)          /* used by expand(): string contains MAGIC */
1730 #define DOTEMP  BIT(8)          /* dito: in word part of ${..[%#=?]..} */
1731 #define DOVACHECK BIT(9)        /* var assign check (for typeset, set, etc) */
1732 #define DOMARKDIRS BIT(10)      /* force markdirs behaviour */
1733 #define DOTCOMEXEC BIT(11)      /* not an eval flag, used by sh -c hack */
1734 #define DOSCALAR BIT(12)        /* change field handling to non-list context */
1735 #define DOHEREDOC BIT(13)       /* change scalar handling to heredoc body */
1736 #define DOHERESTR BIT(14)       /* append a newline char */
1737
1738 #define X_EXTRA 20      /* this many extra bytes in X string */
1739
1740 typedef struct XString {
1741         /* begin of string */
1742         char *beg;
1743         /* length of allocated area, minus safety margin */
1744         size_t len;
1745         /* end of string */
1746         char *end;
1747         /* memory area used */
1748         Area *areap;
1749 } XString;
1750
1751 typedef char *XStringP;
1752
1753 /* initialise expandable string */
1754 #define XinitN(xs, length, area) do {                           \
1755         (xs).len = (length);                                    \
1756         (xs).areap = (area);                                    \
1757         (xs).beg = alloc((xs).len + X_EXTRA, (xs).areap);       \
1758         (xs).end = (xs).beg + (xs).len;                         \
1759 } while (/* CONSTCOND */ 0)
1760 #define Xinit(xs, xp, length, area) do {                        \
1761         XinitN((xs), (length), (area));                         \
1762         (xp) = (xs).beg;                                        \
1763 } while (/* CONSTCOND */ 0)
1764
1765 /* stuff char into string */
1766 #define Xput(xs, xp, c) (*xp++ = (c))
1767
1768 /* check if there are at least n bytes left */
1769 #define XcheckN(xs, xp, n) do {                                 \
1770         ssize_t more = ((xp) + (n)) - (xs).end;                 \
1771         if (more > 0)                                           \
1772                 (xp) = Xcheck_grow(&(xs), (xp), (size_t)more);  \
1773 } while (/* CONSTCOND */ 0)
1774
1775 /* check for overflow, expand string */
1776 #define Xcheck(xs, xp)  XcheckN((xs), (xp), 1)
1777
1778 /* free string */
1779 #define Xfree(xs, xp)   afree((xs).beg, (xs).areap)
1780
1781 /* close, return string */
1782 #define Xclose(xs, xp)  aresize((xs).beg, (xp) - (xs).beg, (xs).areap)
1783
1784 /* begin of string */
1785 #define Xstring(xs, xp) ((xs).beg)
1786
1787 #define Xnleft(xs, xp)  ((xs).end - (xp))       /* may be less than 0 */
1788 #define Xlength(xs, xp) ((xp) - (xs).beg)
1789 #define Xsize(xs, xp)   ((xs).end - (xs).beg)
1790 #define Xsavepos(xs, xp)        ((xp) - (xs).beg)
1791 #define Xrestpos(xs, xp, n)     ((xs).beg + (n))
1792
1793 char *Xcheck_grow(XString *, const char *, size_t);
1794
1795 /*
1796  * expandable vector of generic pointers
1797  */
1798
1799 typedef struct {
1800         /* begin of allocated area */
1801         void **beg;
1802         /* currently used number of entries */
1803         size_t len;
1804         /* allocated number of entries */
1805         size_t siz;
1806 } XPtrV;
1807
1808 #define XPinit(x, n)    do {                                    \
1809         (x).siz = (n);                                          \
1810         (x).len = 0;                                            \
1811         (x).beg = alloc2((x).siz, sizeof(void *), ATEMP);       \
1812 } while (/* CONSTCOND */ 0)                                     \
1813
1814 #define XPput(x, p)     do {                                    \
1815         if ((x).len == (x).siz) {                               \
1816                 (x).beg = aresize2((x).beg, (x).siz,            \
1817                     2 * sizeof(void *), ATEMP);                 \
1818                 (x).siz <<= 1;                                  \
1819         }                                                       \
1820         (x).beg[(x).len++] = (p);                               \
1821 } while (/* CONSTCOND */ 0)
1822
1823 #define XPptrv(x)       ((x).beg)
1824 #define XPsize(x)       ((x).len)
1825 #define XPclose(x)      aresize2((x).beg, XPsize(x), sizeof(void *), ATEMP)
1826 #define XPfree(x)       afree((x).beg, ATEMP)
1827
1828 /*
1829  * Lexer internals
1830  */
1831
1832 typedef struct source Source;
1833 struct source {
1834         /* input buffer */
1835         XString xs;
1836         /* memory area, also checked in reclaim() */
1837         Area *areap;
1838         /* stacked source */
1839         Source *next;
1840         /* input pointer */
1841         const char *str;
1842         /* start of current buffer */
1843         const char *start;
1844         /* input file name */
1845         const char *file;
1846         /* extra data */
1847         union {
1848                 /* string[] */
1849                 const char **strv;
1850                 /* shell file */
1851                 struct shf *shf;
1852                 /* alias (SF_HASALIAS) */
1853                 struct tbl *tblp;
1854                 /* (also for SREREAD) */
1855                 char *freeme;
1856         } u;
1857         /* flags */
1858         int flags;
1859         /* input type */
1860         int type;
1861         /* line number */
1862         int line;
1863         /* line the error occurred on (0 if not set) */
1864         int errline;
1865         /* buffer for ungetsc() (SREREAD) and alias (SALIAS) */
1866         char ugbuf[2];
1867 };
1868
1869 /* Source.type values */
1870 #define SEOF            0       /* input EOF */
1871 #define SFILE           1       /* file input */
1872 #define SSTDIN          2       /* read stdin */
1873 #define SSTRING         3       /* string */
1874 #define SWSTR           4       /* string without \n */
1875 #define SWORDS          5       /* string[] */
1876 #define SWORDSEP        6       /* string[] separator */
1877 #define SALIAS          7       /* alias expansion */
1878 #define SREREAD         8       /* read ahead to be re-scanned */
1879 #define SSTRINGCMDLINE  9       /* string from "mksh -c ..." */
1880
1881 /* Source.flags values */
1882 #define SF_ECHO         BIT(0)  /* echo input to shlout */
1883 #define SF_ALIAS        BIT(1)  /* faking space at end of alias */
1884 #define SF_ALIASEND     BIT(2)  /* faking space at end of alias */
1885 #define SF_TTY          BIT(3)  /* type == SSTDIN & it is a tty */
1886 #define SF_HASALIAS     BIT(4)  /* u.tblp valid (SALIAS, SEOF) */
1887 #define SF_MAYEXEC      BIT(5)  /* special sh -c optimisation hack */
1888
1889 typedef union {
1890         int i;
1891         char *cp;
1892         char **wp;
1893         struct op *o;
1894         struct ioword *iop;
1895 } YYSTYPE;
1896
1897 /* If something is added here, add it to tokentab[] in syn.c as well */
1898 #define LWORD           256
1899 #define LOGAND          257     /* && */
1900 #define LOGOR           258     /* || */
1901 #define BREAK           259     /* ;; */
1902 #define IF              260
1903 #define THEN            261
1904 #define ELSE            262
1905 #define ELIF            263
1906 #define FI              264
1907 #define CASE            265
1908 #define ESAC            266
1909 #define FOR             267
1910 #define SELECT          268
1911 #define WHILE           269
1912 #define UNTIL           270
1913 #define DO              271
1914 #define DONE            272
1915 #define IN              273
1916 #define FUNCTION        274
1917 #define TIME            275
1918 #define REDIR           276
1919 #define MDPAREN         277     /* (( )) */
1920 #define BANG            278     /* ! */
1921 #define DBRACKET        279     /* [[ .. ]] */
1922 #define COPROC          280     /* |& */
1923 #define BRKEV           281     /* ;| */
1924 #define BRKFT           282     /* ;& */
1925 #define YYERRCODE       300
1926
1927 /* flags to yylex */
1928 #define CONTIN          BIT(0)  /* skip new lines to complete command */
1929 #define ONEWORD         BIT(1)  /* single word for substitute() */
1930 #define ALIAS           BIT(2)  /* recognise alias */
1931 #define KEYWORD         BIT(3)  /* recognise keywords */
1932 #define LETEXPR         BIT(4)  /* get expression inside (( )) */
1933 #define CMDASN          BIT(5)  /* parse x[1 & 2] as one word, for typeset */
1934 #define HEREDOC         BIT(6)  /* parsing a here document body */
1935 #define ESACONLY        BIT(7)  /* only accept esac keyword */
1936 #define CMDWORD         BIT(8)  /* parsing simple command (alias related) */
1937 #define HEREDELIM       BIT(9)  /* parsing <<,<<- delimiter */
1938 #define LQCHAR          BIT(10) /* source string contains QCHAR */
1939
1940 #define HERES           10      /* max number of << in line */
1941
1942 #undef CTRL
1943 #define CTRL(x)         ((x) == '?' ? 0x7F : (x) & 0x1F)        /* ASCII */
1944 #define UNCTRL(x)       ((x) ^ 0x40)                            /* ASCII */
1945 #define ISCTRL(x)       (((signed char)((uint8_t)(x) + 1)) < 33)
1946
1947 #define IDENT           64
1948
1949 EXTERN Source *source;          /* yyparse/yylex source */
1950 EXTERN YYSTYPE yylval;          /* result from yylex */
1951 EXTERN struct ioword *heres[HERES], **herep;
1952 EXTERN char ident[IDENT + 1];
1953
1954 EXTERN char **history;          /* saved commands */
1955 EXTERN char **histptr;          /* last history item */
1956 EXTERN mksh_ari_t histsize;     /* history size */
1957
1958 /* flags to histsave */
1959 #define HIST_FLUSH      0
1960 #define HIST_QUEUE      1
1961 #define HIST_APPEND     2
1962 #define HIST_STORE      3
1963 #define HIST_NOTE       4
1964
1965 /* user and system time of last j_waitjed job */
1966 EXTERN struct timeval j_usrtime, j_systime;
1967
1968 #define notok2mul(max, val, c)  (((val) != 0) && ((c) != 0) && \
1969                                     (((max) / (c)) < (val)))
1970 #define notok2add(max, val, c)  ((val) > ((max) - (c)))
1971 #define notoktomul(val, cnst)   notok2mul(SIZE_MAX, (val), (cnst))
1972 #define notoktoadd(val, cnst)   notok2add(SIZE_MAX, (val), (cnst))
1973 #define checkoktoadd(val, cnst) do {                                    \
1974         if (notoktoadd((val), (cnst)))                                  \
1975                 internal_errorf(Tintovfl, (size_t)(val),                \
1976                     '+', (size_t)(cnst));                               \
1977 } while (/* CONSTCOND */ 0)
1978
1979
1980 /* lalloc.c */
1981 void ainit(Area *);
1982 void afreeall(Area *);
1983 /* these cannot fail and can take NULL (not for ap) */
1984 #define alloc(n, ap)            aresize(NULL, (n), (ap))
1985 #define alloc2(m, n, ap)        aresize2(NULL, (m), (n), (ap))
1986 void *aresize(void *, size_t, Area *);
1987 void *aresize2(void *, size_t, size_t, Area *);
1988 void afree(void *, Area *);     /* can take NULL */
1989 /* edit.c */
1990 #ifndef MKSH_NO_CMDLINE_EDITING
1991 #ifndef MKSH_SMALL
1992 int x_bind(const char *, const char *, bool, bool);
1993 #else
1994 int x_bind(const char *, const char *, bool);
1995 #endif
1996 void x_init(void);
1997 #ifdef DEBUG_LEAKS
1998 void x_done(void);
1999 #endif
2000 int x_read(char *);
2001 #endif
2002 void x_mkraw(int, mksh_ttyst *, bool);
2003 void x_initterm(const char *);
2004 /* eval.c */
2005 char *substitute(const char *, int);
2006 char **eval(const char **, int);
2007 char *evalstr(const char *cp, int);
2008 char *evalonestr(const char *cp, int);
2009 char *debunk(char *, const char *, size_t);
2010 void expand(const char *, XPtrV *, int);
2011 int glob_str(char *, XPtrV *, bool);
2012 char *do_tilde(char *);
2013 /* exec.c */
2014 int execute(struct op * volatile, volatile int, volatile int * volatile);
2015 int shcomexec(const char **);
2016 struct tbl *findfunc(const char *, uint32_t, bool);
2017 int define(const char *, struct op *);
2018 const char *builtin(const char *, int (*)(const char **));
2019 struct tbl *findcom(const char *, int);
2020 void flushcom(bool);
2021 int search_access(const char *, int);
2022 const char *search_path(const char *, const char *, int, int *);
2023 void pr_menu(const char * const *);
2024 void pr_list(char * const *);
2025 int herein(struct ioword *, char **);
2026 /* expr.c */
2027 int evaluate(const char *, mksh_ari_t *, int, bool);
2028 int v_evaluate(struct tbl *, const char *, volatile int, bool);
2029 /* UTF-8 stuff */
2030 size_t utf_mbtowc(unsigned int *, const char *);
2031 size_t utf_wctomb(char *, unsigned int);
2032 int utf_widthadj(const char *, const char **);
2033 size_t utf_mbswidth(const char *) MKSH_A_PURE;
2034 const char *utf_skipcols(const char *, int, int *);
2035 size_t utf_ptradj(const char *) MKSH_A_PURE;
2036 #ifdef MIRBSD_BOOTFLOPPY
2037 #define utf_wcwidth(i) wcwidth((wchar_t)(i))
2038 #else
2039 int utf_wcwidth(unsigned int) MKSH_A_PURE;
2040 #endif
2041 int ksh_access(const char *, int);
2042 struct tbl *tempvar(const char *);
2043 /* funcs.c */
2044 int c_hash(const char **);
2045 int c_pwd(const char **);
2046 int c_print(const char **);
2047 #ifdef MKSH_PRINTF_BUILTIN
2048 int c_printf(const char **);
2049 #endif
2050 int c_whence(const char **);
2051 int c_command(const char **);
2052 int c_typeset(const char **);
2053 int c_alias(const char **);
2054 int c_unalias(const char **);
2055 int c_let(const char **);
2056 int c_jobs(const char **);
2057 #ifndef MKSH_UNEMPLOYED
2058 int c_fgbg(const char **);
2059 #endif
2060 int c_kill(const char **);
2061 void getopts_reset(int);
2062 int c_getopts(const char **);
2063 #ifndef MKSH_NO_CMDLINE_EDITING
2064 int c_bind(const char **);
2065 #endif
2066 int c_shift(const char **);
2067 int c_umask(const char **);
2068 int c_dot(const char **);
2069 int c_wait(const char **);
2070 int c_read(const char **);
2071 int c_eval(const char **);
2072 int c_trap(const char **);
2073 int c_brkcont(const char **);
2074 int c_exitreturn(const char **);
2075 int c_set(const char **);
2076 int c_unset(const char **);
2077 int c_ulimit(const char **);
2078 int c_times(const char **);
2079 int timex(struct op *, int, volatile int *);
2080 void timex_hook(struct op *, char ** volatile *);
2081 int c_exec(const char **);
2082 /* dummy function (just need pointer value), special case in comexec() */
2083 #define c_builtin shcomexec
2084 int c_test(const char **);
2085 #if HAVE_MKNOD
2086 int c_mknod(const char **);
2087 #endif
2088 int c_realpath(const char **);
2089 int c_rename(const char **);
2090 int c_cat(const char **);
2091 int c_sleep(const char **);
2092 /* histrap.c */
2093 void init_histvec(void);
2094 void hist_init(Source *);
2095 #if HAVE_PERSISTENT_HISTORY
2096 void hist_finish(void);
2097 #endif
2098 void histsave(int *, const char *, int, bool);
2099 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
2100 bool histsync(void);
2101 #endif
2102 int c_fc(const char **);
2103 void sethistsize(mksh_ari_t);
2104 #if HAVE_PERSISTENT_HISTORY
2105 void sethistfile(const char *);
2106 #endif
2107 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
2108 char **histpos(void) MKSH_A_PURE;
2109 int histnum(int);
2110 #endif
2111 int findhist(int, int, const char *, bool) MKSH_A_PURE;
2112 char **hist_get_newest(bool);
2113 void inittraps(void);
2114 void alarm_init(void);
2115 Trap *gettrap(const char *, bool, bool);
2116 void trapsig(int);
2117 void intrcheck(void);
2118 int fatal_trap_check(void);
2119 int trap_pending(void);
2120 void runtraps(int intr);
2121 void runtrap(Trap *, bool);
2122 void cleartraps(void);
2123 void restoresigs(void);
2124 void settrap(Trap *, const char *);
2125 int block_pipe(void);
2126 void restore_pipe(int);
2127 int setsig(Trap *, sig_t, int);
2128 void setexecsig(Trap *, int);
2129 #if HAVE_FLOCK || HAVE_LOCK_FCNTL
2130 void mksh_lockfd(int);
2131 void mksh_unlkfd(int);
2132 #endif
2133 /* jobs.c */
2134 void j_init(void);
2135 void j_exit(void);
2136 #ifndef MKSH_UNEMPLOYED
2137 void j_change(void);
2138 #endif
2139 int exchild(struct op *, int, volatile int *, int);
2140 void startlast(void);
2141 int waitlast(void);
2142 int waitfor(const char *, int *);
2143 int j_kill(const char *, int);
2144 #ifndef MKSH_UNEMPLOYED
2145 int j_resume(const char *, int);
2146 #endif
2147 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
2148 void j_suspend(void);
2149 #endif
2150 int j_jobs(const char *, int, int);
2151 void j_notify(void);
2152 pid_t j_async(void);
2153 int j_stopped_running(void);
2154 /* lex.c */
2155 int yylex(int);
2156 void yyskiputf8bom(void);
2157 void yyerror(const char *, ...)
2158     MKSH_A_NORETURN
2159     MKSH_A_FORMAT(__printf__, 1, 2);
2160 Source *pushs(int, Area *);
2161 void set_prompt(int, Source *);
2162 int pprompt(const char *, int);
2163 /* main.c */
2164 int include(const char *, int, const char **, bool);
2165 int command(const char *, int);
2166 int shell(Source * volatile, volatile bool);
2167 /* argument MUST NOT be 0 */
2168 void unwind(int) MKSH_A_NORETURN;
2169 void newenv(int);
2170 void quitenv(struct shf *);
2171 void cleanup_parents_env(void);
2172 void cleanup_proc_env(void);
2173 void errorf(const char *, ...)
2174     MKSH_A_NORETURN
2175     MKSH_A_FORMAT(__printf__, 1, 2);
2176 void errorfx(int, const char *, ...)
2177     MKSH_A_NORETURN
2178     MKSH_A_FORMAT(__printf__, 2, 3);
2179 void warningf(bool, const char *, ...)
2180     MKSH_A_FORMAT(__printf__, 2, 3);
2181 void bi_errorf(const char *, ...)
2182     MKSH_A_FORMAT(__printf__, 1, 2);
2183 #define errorfz()       errorf(NULL)
2184 #define errorfxz(rc)    errorfx((rc), NULL)
2185 #define bi_errorfz()    bi_errorf(NULL)
2186 void internal_errorf(const char *, ...)
2187     MKSH_A_NORETURN
2188     MKSH_A_FORMAT(__printf__, 1, 2);
2189 void internal_warningf(const char *, ...)
2190     MKSH_A_FORMAT(__printf__, 1, 2);
2191 void error_prefix(bool);
2192 void shellf(const char *, ...)
2193     MKSH_A_FORMAT(__printf__, 1, 2);
2194 void shprintf(const char *, ...)
2195     MKSH_A_FORMAT(__printf__, 1, 2);
2196 int can_seek(int);
2197 void initio(void);
2198 int ksh_dup2(int, int, bool);
2199 short savefd(int);
2200 void restfd(int, int);
2201 void openpipe(int *);
2202 void closepipe(int *);
2203 int check_fd(const char *, int, const char **);
2204 void coproc_init(void);
2205 void coproc_read_close(int);
2206 void coproc_readw_close(int);
2207 void coproc_write_close(int);
2208 int coproc_getfd(int, const char **);
2209 void coproc_cleanup(int);
2210 struct temp *maketemp(Area *, Temp_type, struct temp **);
2211 void ktinit(Area *, struct table *, uint8_t);
2212 struct tbl *ktscan(struct table *, const char *, uint32_t, struct tbl ***);
2213 /* table, name (key) to search for, hash(n) */
2214 #define ktsearch(tp, s, h) ktscan((tp), (s), (h), NULL)
2215 struct tbl *ktenter(struct table *, const char *, uint32_t);
2216 #define ktdelete(p)     do { p->flag = 0; } while (/* CONSTCOND */ 0)
2217 void ktwalk(struct tstate *, struct table *);
2218 struct tbl *ktnext(struct tstate *);
2219 struct tbl **ktsort(struct table *);
2220 #ifdef DF
2221 void DF(const char *, ...)
2222     MKSH_A_FORMAT(__printf__, 1, 2);
2223 #endif
2224 /* misc.c */
2225 void setctypes(const char *, int);
2226 void initctypes(void);
2227 size_t option(const char *) MKSH_A_PURE;
2228 char *getoptions(void);
2229 void change_flag(enum sh_flag, int, bool);
2230 void change_xtrace(unsigned char, bool);
2231 int parse_args(const char **, int, bool *);
2232 int getn(const char *, int *);
2233 int gmatchx(const char *, const char *, bool);
2234 int has_globbing(const char *, const char *) MKSH_A_PURE;
2235 int xstrcmp(const void *, const void *) MKSH_A_PURE;
2236 void ksh_getopt_reset(Getopt *, int);
2237 int ksh_getopt(const char **, Getopt *, const char *);
2238 void print_value_quoted(struct shf *, const char *);
2239 char *quote_value(const char *);
2240 void print_columns(struct shf *, unsigned int,
2241     void (*)(char *, size_t, unsigned int, const void *),
2242     const void *, size_t, size_t, bool);
2243 void strip_nuls(char *, size_t)
2244     MKSH_A_BOUNDED(__string__, 1, 2);
2245 ssize_t blocking_read(int, char *, size_t)
2246     MKSH_A_BOUNDED(__buffer__, 2, 3);
2247 int reset_nonblock(int);
2248 char *ksh_get_wd(void);
2249 char *do_realpath(const char *);
2250 void simplify_path(char *);
2251 void set_current_wd(const char *);
2252 int c_cd(const char **);
2253 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2254 char *strdup_i(const char *, Area *);
2255 char *strndup_i(const char *, size_t, Area *);
2256 #endif
2257 int unbksl(bool, int (*)(void), void (*)(int));
2258 /* shf.c */
2259 struct shf *shf_open(const char *, int, int, int);
2260 struct shf *shf_fdopen(int, int, struct shf *);
2261 struct shf *shf_reopen(int, int, struct shf *);
2262 struct shf *shf_sopen(char *, ssize_t, int, struct shf *);
2263 int shf_close(struct shf *);
2264 int shf_fdclose(struct shf *);
2265 char *shf_sclose(struct shf *);
2266 int shf_flush(struct shf *);
2267 ssize_t shf_read(char *, ssize_t, struct shf *);
2268 char *shf_getse(char *, ssize_t, struct shf *);
2269 int shf_getchar(struct shf *s);
2270 int shf_ungetc(int, struct shf *);
2271 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2272 int shf_getc(struct shf *);
2273 int shf_putc(int, struct shf *);
2274 #else
2275 #define shf_getc shf_getc_i
2276 #define shf_putc shf_putc_i
2277 #endif
2278 int shf_putchar(int, struct shf *);
2279 ssize_t shf_puts(const char *, struct shf *);
2280 ssize_t shf_write(const char *, ssize_t, struct shf *);
2281 ssize_t shf_fprintf(struct shf *, const char *, ...)
2282     MKSH_A_FORMAT(__printf__, 2, 3);
2283 ssize_t shf_snprintf(char *, ssize_t, const char *, ...)
2284     MKSH_A_FORMAT(__printf__, 3, 4)
2285     MKSH_A_BOUNDED(__string__, 1, 2);
2286 char *shf_smprintf(const char *, ...)
2287     MKSH_A_FORMAT(__printf__, 1, 2);
2288 ssize_t shf_vfprintf(struct shf *, const char *, va_list)
2289     MKSH_A_FORMAT(__printf__, 2, 0);
2290 /* syn.c */
2291 int assign_command(const char *, bool) MKSH_A_PURE;
2292 void initkeywords(void);
2293 struct op *compile(Source *, bool);
2294 bool parse_usec(const char *, struct timeval *);
2295 char *yyrecursive(int);
2296 void yyrecursive_pop(bool);
2297 /* tree.c */
2298 void fptreef(struct shf *, int, const char *, ...);
2299 char *snptreef(char *, ssize_t, const char *, ...);
2300 struct op *tcopy(struct op *, Area *);
2301 char *wdcopy(const char *, Area *);
2302 const char *wdscan(const char *, int);
2303 #define WDS_TPUTS       BIT(0)          /* tputS (dumpwdvar) mode */
2304 char *wdstrip(const char *, int);
2305 void tfree(struct op *, Area *);
2306 void dumpchar(struct shf *, int);
2307 void dumptree(struct shf *, struct op *);
2308 void dumpwdvar(struct shf *, const char *);
2309 void dumpioact(struct shf *shf, struct op *t);
2310 void vistree(char *, size_t, struct op *)
2311     MKSH_A_BOUNDED(__string__, 1, 2);
2312 void fpFUNCTf(struct shf *, int, bool, const char *, struct op *);
2313 /* var.c */
2314 void newblock(void);
2315 void popblock(void);
2316 void initvar(void);
2317 struct block *varsearch(struct block *, struct tbl **, const char *, uint32_t);
2318 struct tbl *global(const char *);
2319 struct tbl *local(const char *, bool);
2320 char *str_val(struct tbl *);
2321 int setstr(struct tbl *, const char *, int);
2322 struct tbl *setint_v(struct tbl *, struct tbl *, bool);
2323 void setint(struct tbl *, mksh_ari_t);
2324 void setint_n(struct tbl *, mksh_ari_t, int);
2325 struct tbl *typeset(const char *, uint32_t, uint32_t, int, int);
2326 void unset(struct tbl *, int);
2327 const char *skip_varname(const char *, bool) MKSH_A_PURE;
2328 const char *skip_wdvarname(const char *, bool) MKSH_A_PURE;
2329 int is_wdvarname(const char *, bool) MKSH_A_PURE;
2330 int is_wdvarassign(const char *) MKSH_A_PURE;
2331 struct tbl *arraysearch(struct tbl *, uint32_t);
2332 char **makenv(void);
2333 void change_winsz(void);
2334 size_t array_ref_len(const char *) MKSH_A_PURE;
2335 char *arrayname(const char *);
2336 mksh_uari_t set_array(const char *, bool, const char **);
2337 uint32_t hash(const void *) MKSH_A_PURE;
2338 uint32_t chvt_rndsetup(const void *, size_t) MKSH_A_PURE;
2339 mksh_ari_t rndget(void);
2340 void rndset(unsigned long);
2341 void rndpush(const void *);
2342 void record_match(const char *);
2343
2344 enum Test_op {
2345         /* non-operator */
2346         TO_NONOP = 0,
2347         /* unary operators */
2348         TO_STNZE, TO_STZER, TO_OPTION,
2349         TO_FILAXST,
2350         TO_FILEXST,
2351         TO_FILREG, TO_FILBDEV, TO_FILCDEV, TO_FILSYM, TO_FILFIFO, TO_FILSOCK,
2352         TO_FILCDF, TO_FILID, TO_FILGID, TO_FILSETG, TO_FILSTCK, TO_FILUID,
2353         TO_FILRD, TO_FILGZ, TO_FILTT, TO_FILSETU, TO_FILWR, TO_FILEX,
2354         /* binary operators */
2355         TO_STEQL, TO_STNEQ, TO_STLT, TO_STGT, TO_INTEQ, TO_INTNE, TO_INTGT,
2356         TO_INTGE, TO_INTLT, TO_INTLE, TO_FILEQ, TO_FILNT, TO_FILOT,
2357         /* not an operator */
2358         TO_NONNULL      /* !TO_NONOP */
2359 };
2360 typedef enum Test_op Test_op;
2361
2362 /* Used by Test_env.isa() (order important - used to index *_tokens[] arrays) */
2363 enum Test_meta {
2364         TM_OR,          /* -o or || */
2365         TM_AND,         /* -a or && */
2366         TM_NOT,         /* ! */
2367         TM_OPAREN,      /* ( */
2368         TM_CPAREN,      /* ) */
2369         TM_UNOP,        /* unary operator */
2370         TM_BINOP,       /* binary operator */
2371         TM_END          /* end of input */
2372 };
2373 typedef enum Test_meta Test_meta;
2374
2375 #define TEF_ERROR       BIT(0)          /* set if we've hit an error */
2376 #define TEF_DBRACKET    BIT(1)          /* set if [[ .. ]] test */
2377
2378 typedef struct test_env {
2379         union {
2380                 const char **wp;        /* used by ptest_* */
2381                 XPtrV *av;              /* used by dbtestp_* */
2382         } pos;
2383         const char **wp_end;            /* used by ptest_* */
2384         Test_op (*isa)(struct test_env *, Test_meta);
2385         const char *(*getopnd) (struct test_env *, Test_op, bool);
2386         int (*eval)(struct test_env *, Test_op, const char *, const char *, bool);
2387         void (*error)(struct test_env *, int, const char *);
2388         int flags;                      /* TEF_* */
2389 } Test_env;
2390
2391 extern const char * const dbtest_tokens[];
2392
2393 Test_op test_isop(Test_meta, const char *) MKSH_A_PURE;
2394 int test_eval(Test_env *, Test_op, const char *, const char *, bool);
2395 int test_parse(Test_env *);
2396
2397 /* tty_fd is not opened O_BINARY, it's thus never read/written */
2398 EXTERN int tty_fd E_INIT(-1);   /* dup'd tty file descriptor */
2399 EXTERN bool tty_devtty;         /* true if tty_fd is from /dev/tty */
2400 EXTERN mksh_ttyst tty_state;    /* saved tty state */
2401 EXTERN bool tty_hasstate;       /* true if tty_state is valid */
2402
2403 extern int tty_init_fd(void);   /* initialise tty_fd, tty_devtty */
2404
2405 #ifdef __OS2__
2406 #ifndef __GNUC__
2407 # error oops?
2408 #endif
2409 #define binopen2(path,flags)            __extension__({                 \
2410         int binopen2_fd = open((path), (flags) | O_BINARY);             \
2411         if (binopen2_fd >= 0)                                           \
2412                 setmode(binopen2_fd, O_BINARY);                         \
2413         (binopen2_fd);                                                  \
2414 })
2415 #define binopen3(path,flags,mode)       __extension__({                 \
2416         int binopen3_fd = open((path), (flags) | O_BINARY, (mode));     \
2417         if (binopen3_fd >= 0)                                           \
2418                 setmode(binopen3_fd, O_BINARY);                         \
2419         (binopen3_fd);                                                  \
2420 })
2421 #define mksh_abspath(s)                 __extension__({                 \
2422         const char *mksh_abspath_s = (s);                               \
2423         (mksh_abspath_s[0] == '/' || (ksh_isalphx(mksh_abspath_s[0]) && \
2424             mksh_abspath_s[1] == ':'));                                 \
2425 })
2426 #else
2427 #define binopen2(path,flags)            open((path), (flags) | O_BINARY)
2428 #define binopen3(path,flags,mode)       open((path), (flags) | O_BINARY, (mode))
2429 #define mksh_abspath(s)                 ((s)[0] == '/')
2430 #endif
2431
2432 /* be sure not to interfere with anyone else's idea about EXTERN */
2433 #ifdef EXTERN_DEFINED
2434 # undef EXTERN_DEFINED
2435 # undef EXTERN
2436 #endif
2437 #undef E_INIT
2438
2439 #endif /* !MKSH_INCLUDES_ONLY */