OSDN Git Service

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