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, 2017, 2018,
14 * 2019, 2020
15 * mirabilos <m@mirbsd.org>
16 *
17 * Provided that these terms and disclaimer and all copyright notices
18 * are retained or reproduced in an accompanying document, permission
19 * is granted to deal in this work without restriction, including un‐
20 * limited rights to use, publicly perform, distribute, sell, modify,
21 * merge, give away, or sublicence.
22 *
23 * This work is provided “AS IS” and WITHOUT WARRANTY of any kind, to
24 * the utmost extent permitted by applicable law, neither express nor
25 * implied; without malicious intent or gross negligence. In no event
26 * may a licensor, author or contributor be held liable for indirect,
27 * direct, other damage, loss, or other issues arising in any way out
28 * of dealing in the work, even if advised of the possibility of such
29 * damage or existence of a defect, except proven that it results out
30 * of said person’s immediate fault when using the work as intended.
31 */
32
33 #ifdef __dietlibc__
34 /* XXX imake style */
35 #define _BSD_SOURCE /* live, BSD, live❣ */
36 #endif
37
38 #if HAVE_SYS_PARAM_H
39 #include <sys/param.h>
40 #endif
41 #include <sys/types.h>
42 #if HAVE_BOTH_TIME_H
43 #include <sys/time.h>
44 #include <time.h>
45 #elif HAVE_SYS_TIME_H
46 #include <sys/time.h>
47 #elif HAVE_TIME_H
48 #include <time.h>
49 #endif
50 #include <sys/ioctl.h>
51 #if HAVE_SYS_SYSMACROS_H
52 #include <sys/sysmacros.h>
53 #endif
54 #if HAVE_SYS_MKDEV_H
55 #include <sys/mkdev.h>
56 #endif
57 #if HAVE_SYS_MMAN_H
58 #include <sys/mman.h>
59 #endif
60 #if HAVE_SYS_RESOURCE_H
61 #include <sys/resource.h>
62 #endif
63 #include <sys/stat.h>
64 #include <sys/wait.h>
65 #include <dirent.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #if HAVE_IO_H
69 #include <io.h>
70 #endif
71 #if HAVE_LIBGEN_H
72 #include <libgen.h>
73 #endif
74 #if HAVE_LIBUTIL_H
75 #include <libutil.h>
76 #endif
77 #include <limits.h>
78 #if HAVE_PATHS_H
79 #include <paths.h>
80 #endif
81 #ifndef MKSH_NOPWNAM
82 #include <pwd.h>
83 #endif
84 #include <setjmp.h>
85 #include <signal.h>
86 #include <stdarg.h>
87 #include <stddef.h>
88 #if HAVE_STDINT_H
89 #include <stdint.h>
90 #endif
91 #include <stdio.h>
92 #include <stdlib.h>
93 #include <string.h>
94 #if HAVE_STRINGS_H
95 #include <strings.h>
96 #endif
97 #if HAVE_TERMIOS_H
98 #include <termios.h>
99 #else
100 /* shudder… */
101 #include <termio.h>
102 #endif
103 #ifdef _ISC_UNIX
104 /* XXX imake style */
105 #include <sys/sioctl.h>
106 #endif
107 #if HAVE_ULIMIT_H
108 #include <ulimit.h>
109 #endif
110 #include <unistd.h>
111 #if HAVE_VALUES_H
112 #include <values.h>
113 #endif
114 #ifdef MIRBSD_BOOTFLOPPY
115 #include <wchar.h>
116 #endif
117
118 /* monkey-patch known-bad offsetof versions to quell a warning */
119 #if (defined(__KLIBC__) || defined(__dietlibc__)) && \
120 ((defined(__GNUC__) && (__GNUC__ > 3)) || defined(__NWCC__))
121 #undef offsetof
122 #define offsetof(s,e) __builtin_offsetof(s, e)
123 #endif
124
125 #undef __attribute__
126 #if HAVE_ATTRIBUTE_BOUNDED
127 #define MKSH_A_BOUNDED(x,y,z) __attribute__((__bounded__(x, y, z)))
128 #else
129 #define MKSH_A_BOUNDED(x,y,z) /* nothing */
130 #endif
131 #if HAVE_ATTRIBUTE_FORMAT
132 #define MKSH_A_FORMAT(x,y,z) __attribute__((__format__(x, y, z)))
133 #else
134 #define MKSH_A_FORMAT(x,y,z) /* nothing */
135 #endif
136 #if HAVE_ATTRIBUTE_NORETURN
137 #define MKSH_A_NORETURN __attribute__((__noreturn__))
138 #else
139 #define MKSH_A_NORETURN /* nothing */
140 #endif
141 #if HAVE_ATTRIBUTE_PURE
142 #define MKSH_A_PURE __attribute__((__pure__))
143 #else
144 #define MKSH_A_PURE /* nothing */
145 #endif
146 #if HAVE_ATTRIBUTE_UNUSED
147 #define MKSH_A_UNUSED __attribute__((__unused__))
148 #else
149 #define MKSH_A_UNUSED /* nothing */
150 #endif
151 #if HAVE_ATTRIBUTE_USED
152 #define MKSH_A_USED __attribute__((__used__))
153 #else
154 #define MKSH_A_USED /* nothing */
155 #endif
156
157 #if defined(MirBSD) && (MirBSD >= 0x09A1) && \
158 defined(__ELF__) && defined(__GNUC__) && \
159 !defined(__llvm__) && !defined(__NWCC__)
160 /*
161 * We got usable __IDSTRING __COPYRIGHT __RCSID __SCCSID macros
162 * which work for all cases; no need to redefine them using the
163 * "portable" macros from below when we might have the "better"
164 * gcc+ELF specific macros or other system dependent ones.
165 */
166 #else
167 #undef __IDSTRING
168 #undef __IDSTRING_CONCAT
169 #undef __IDSTRING_EXPAND
170 #undef __COPYRIGHT
171 #undef __RCSID
172 #undef __SCCSID
173 #define __IDSTRING_CONCAT(l,p) __LINTED__ ## l ## _ ## p
174 #define __IDSTRING_EXPAND(l,p) __IDSTRING_CONCAT(l,p)
175 #ifdef MKSH_DONT_EMIT_IDSTRING
176 #define __IDSTRING(prefix,string) /* nothing */
177 #elif defined(__ELF__) && defined(__GNUC__) && \
178 !(defined(__GNUC__) && defined(__mips16) && (__GNUC__ >= 8)) && \
179 !defined(__llvm__) && !defined(__NWCC__) && !defined(NO_ASM)
180 #define __IDSTRING(prefix,string) \
181 __asm__(".section .comment" \
182 "\n .ascii \"@(\"\"#)" #prefix ": \"" \
183 "\n .asciz \"" string "\"" \
184 "\n .previous")
185 #else
186 #define __IDSTRING(prefix,string) \
187 static const char __IDSTRING_EXPAND(__LINE__,prefix) [] \
188 MKSH_A_USED = "@(""#)" #prefix ": " string
189 #endif
190 #define __COPYRIGHT(x) __IDSTRING(copyright,x)
191 #define __RCSID(x) __IDSTRING(rcsid,x)
192 #define __SCCSID(x) __IDSTRING(sccsid,x)
193 #endif
194
195 #ifdef EXTERN
196 __RCSID("$MirOS: src/bin/mksh/sh.h,v 1.904 2020/10/31 03:53:06 tg Exp $");
197 #endif
198 #define MKSH_VERSION "R59 2020/10/31"
199
200 /* arithmetic types: C implementation */
201 #if !HAVE_CAN_INTTYPES
202 #if !HAVE_CAN_UCBINTS
203 typedef signed int int32_t;
204 typedef unsigned int uint32_t;
205 #else
206 typedef u_int32_t uint32_t;
207 #endif
208 #endif
209
210 /* arithmetic types: shell arithmetics */
211 #ifdef MKSH_LEGACY_MODE
212 /*
213 * POSIX demands these to be the C environment's long type
214 */
215 typedef long mksh_ari_t;
216 typedef unsigned long mksh_uari_t;
217 #else
218 /*
219 * These types are exactly 32 bit wide; signed and unsigned
220 * integer wraparound, even across division and modulo, for
221 * any shell code using them, is guaranteed.
222 */
223 typedef int32_t mksh_ari_t;
224 typedef uint32_t mksh_uari_t;
225 #endif
226
227 /* boolean type (no <stdbool.h> deliberately) */
228 typedef unsigned char mksh_bool;
229 #undef bool
230 /* false MUST equal the same 0 as written by static storage initialisation */
231 #undef false
232 #undef true
233 /* access macros for boolean type */
234 #define bool mksh_bool
235 /* values must have identity mapping between mksh_bool and short */
236 #define false 0
237 #define true 1
238 /* make any-type into bool or short */
239 #define tobool(cond) ((cond) ? true : false)
240
241 /* char (octet) type: C implementation */
242 #if !HAVE_CAN_INT8TYPE
243 #if !HAVE_CAN_UCBINT8
244 typedef unsigned char uint8_t;
245 #else
246 typedef u_int8_t uint8_t;
247 #endif
248 #endif
249
250 /* other standard types */
251
252 #if !HAVE_SIG_T
253 #undef sig_t
254 typedef void (*sig_t)(int);
255 #endif
256
257 #ifdef MKSH_TYPEDEF_SIG_ATOMIC_T
258 typedef MKSH_TYPEDEF_SIG_ATOMIC_T sig_atomic_t;
259 #endif
260
261 #ifdef MKSH_OH_ADAPT
262 #define MAX_WRITE_RETRY_TIME 10
263 #endif
264
265 #ifdef MKSH_TYPEDEF_SSIZE_T
266 typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
267 #endif
268
269 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
270 #define MKSH_SHF_NO_INLINE
271 #endif
272
273 /* do not merge these conditionals as neatcc’s preprocessor is simple */
274 #ifdef __neatcc__
275 /* parsing of comma operator <,> in expressions broken */
276 #define MKSH_SHF_NO_INLINE
277 #endif
278
279 /* un-do vendor damage */
280
281 #undef BAD /* AIX defines that somewhere */
282 #undef PRINT /* LynxOS defines that somewhere */
283 #undef flock /* SCO UnixWare defines that to flock64 but ENOENT */
284
285
286 #ifndef MKSH_INCLUDES_ONLY
287
288 /* compile-time assertions */
289 #define cta(name,expr) struct cta_ ## name { char t[(expr) ? 1 : -1]; }
290
291 /* EBCDIC fun */
292
293 /* see the large comment in shf.c for an EBCDIC primer */
294
295 #if defined(MKSH_FOR_Z_OS) && defined(__MVS__) && defined(__IBMC__) && defined(__CHARSET_LIB)
296 # if !__CHARSET_LIB && !defined(MKSH_EBCDIC)
297 # error "Please compile with Build.sh -E for EBCDIC!"
298 # endif
299 # if __CHARSET_LIB && defined(MKSH_EBCDIC)
300 # error "Please compile without -E argument to Build.sh for ASCII!"
301 # endif
302 # if __CHARSET_LIB && !defined(_ENHANCED_ASCII_EXT)
303 /* go all-out on ASCII */
304 # define _ENHANCED_ASCII_EXT 0xFFFFFFFF
305 # endif
306 #endif
307
308 /* extra types */
309
310 /* getrusage does not exist on OS/2 kLIBC */
311 #if !HAVE_GETRUSAGE && !defined(__OS2__)
312 #undef rusage
313 #undef RUSAGE_SELF
314 #undef RUSAGE_CHILDREN
315 #define rusage mksh_rusage
316 #define RUSAGE_SELF 0
317 #define RUSAGE_CHILDREN -1
318
319 struct rusage {
320 struct timeval ru_utime;
321 struct timeval ru_stime;
322 };
323 #endif
324
325 /* extra macros */
326
327 #ifndef timerclear
328 #define timerclear(tvp) \
329 do { \
330 (tvp)->tv_sec = (tvp)->tv_usec = 0; \
331 } while (/* CONSTCOND */ 0)
332 #endif
333 #ifndef timeradd
334 #define timeradd(tvp,uvp,vvp) \
335 do { \
336 (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \
337 (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \
338 if ((vvp)->tv_usec >= 1000000) { \
339 (vvp)->tv_sec++; \
340 (vvp)->tv_usec -= 1000000; \
341 } \
342 } while (/* CONSTCOND */ 0)
343 #endif
344 #ifndef timersub
345 #define timersub(tvp,uvp,vvp) \
346 do { \
347 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
348 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
349 if ((vvp)->tv_usec < 0) { \
350 (vvp)->tv_sec--; \
351 (vvp)->tv_usec += 1000000; \
352 } \
353 } while (/* CONSTCOND */ 0)
354 #endif
355
356 #ifdef MKSH__NO_PATH_MAX
357 #undef PATH_MAX
358 #else
359 #ifndef PATH_MAX
360 #ifdef MAXPATHLEN
361 #define PATH_MAX MAXPATHLEN
362 #else
363 #define PATH_MAX 1024
364 #endif
365 #endif
366 #endif
367 #ifndef SIZE_MAX
368 #ifdef SIZE_T_MAX
369 #define SIZE_MAX SIZE_T_MAX
370 #else
371 #define SIZE_MAX ((size_t)-1)
372 #endif
373 #endif
374 #ifndef S_ISLNK
375 #define S_ISLNK(m) ((m & 0170000) == 0120000)
376 #endif
377 #ifndef S_ISSOCK
378 #define S_ISSOCK(m) ((m & 0170000) == 0140000)
379 #endif
380 #if !defined(S_ISCDF) && defined(S_CDF)
381 #define S_ISCDF(m) (S_ISDIR(m) && ((m) & S_CDF))
382 #endif
383 #ifndef DEFFILEMODE
384 #define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
385 #endif
386
387
388 /* determine ksh_NSIG: first, use the traditional definitions */
389 #undef ksh_NSIG
390 #if defined(NSIG)
391 #define ksh_NSIG (NSIG)
392 #elif defined(_NSIG)
393 #define ksh_NSIG (_NSIG)
394 #elif defined(SIGMAX)
395 #define ksh_NSIG (SIGMAX + 1)
396 #elif defined(_SIGMAX)
397 #define ksh_NSIG (_SIGMAX + 1)
398 #elif defined(NSIG_MAX)
399 #define ksh_NSIG (NSIG_MAX)
400 #elif defined(MKSH_FOR_Z_OS)
401 #define ksh_NSIG 40
402 #else
403 # error Please have your platform define NSIG.
404 #endif
405 /* range-check them */
406 #if (ksh_NSIG < 1)
407 # error Your NSIG value is not positive.
408 #undef ksh_NSIG
409 #endif
410 /* second, see if the new POSIX definition is available */
411 #ifdef NSIG_MAX
412 #if (NSIG_MAX < 2)
413 /* and usable */
414 # error Your NSIG_MAX value is too small.
415 #undef NSIG_MAX
416 #elif (ksh_NSIG > NSIG_MAX)
417 /* and realistic */
418 # error Your NSIG value is larger than your NSIG_MAX value.
419 #undef NSIG_MAX
420 #else
421 /* since it’s usable, prefer it */
422 #undef ksh_NSIG
423 #define ksh_NSIG (NSIG_MAX)
424 #endif
425 /* if NSIG_MAX is now still defined, use sysconf(_SC_NSIG) at runtime */
426 #endif
427 /* third, for cpp without the error directive, default */
428 #ifndef ksh_NSIG
429 #define ksh_NSIG 64
430 #endif
431
432 #define ksh_sigmask(sig) (((sig) < 1 || (sig) > 127) ? 255 : 128 + (sig))
433
434
435 /* OS-dependent additions (functions, variables, by OS) */
436
437 #ifdef MKSH_EXE_EXT
438 #undef MKSH_EXE_EXT
439 #define MKSH_EXE_EXT ".exe"
440 #else
441 #define MKSH_EXE_EXT ""
442 #endif
443
444 #ifdef __OS2__
445 #define MKSH_UNIXROOT "/@unixroot"
446 #else
447 #define MKSH_UNIXROOT ""
448 #endif
449
450 #ifdef MKSH_DOSPATH
451 #ifndef __GNUC__
452 # error GCC extensions needed later on
453 #endif
454 #define MKSH_PATHSEPS ";"
455 #define MKSH_PATHSEPC ';'
456 #else
457 #define MKSH_PATHSEPS ":"
458 #define MKSH_PATHSEPC ':'
459 #endif
460
461 #if !HAVE_FLOCK_DECL
462 extern int flock(int, int);
463 #endif
464
465 #if !HAVE_GETTIMEOFDAY
466 #define mksh_TIME(tv) do { \
467 (tv).tv_usec = 0; \
468 (tv).tv_sec = time(NULL); \
469 } while (/* CONSTCOND */ 0)
470 #else
471 #define mksh_TIME(tv) gettimeofday(&(tv), NULL)
472 #endif
473
474 #if !HAVE_GETRUSAGE
475 extern int getrusage(int, struct rusage *);
476 #endif
477
478 #if !HAVE_MEMMOVE
479 /* we assume either memmove or bcopy exist, at the moment */
480 #define memmove(dst,src,len) bcopy((src), (dst), (len))
481 #endif
482
483 #if !HAVE_REVOKE_DECL
484 extern int revoke(const char *);
485 #endif
486
487 #if defined(DEBUG) || !HAVE_STRERROR
488 #undef strerror
489 #define strerror /* poisoned */ dontuse_strerror
490 #define cstrerror /* replaced */ cstrerror
491 extern const char *cstrerror(int);
492 #else
493 #define cstrerror(errnum) ((const char *)strerror(errnum))
494 #endif
495
496 #if !HAVE_STRLCPY
497 size_t strlcpy(char *, const char *, size_t);
498 #endif
499
500 #ifdef __INTERIX
501 /* XXX imake style */
502 #define makedev mkdev
503 extern int __cdecl seteuid(uid_t);
504 extern int __cdecl setegid(gid_t);
505 #endif
506
507 #if defined(__COHERENT__)
508 #ifndef O_ACCMODE
509 /* this need not work everywhere, take care */
510 #define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
511 #endif
512 #endif
513
514 #ifndef O_BINARY
515 #define O_BINARY 0
516 #endif
517
518 #undef O_MAYEXEC /* https://lwn.net/Articles/820658/ */
519 #define O_MAYEXEC 0
520
521 #ifdef MKSH__NO_SYMLINK
522 #undef S_ISLNK
523 #define S_ISLNK(m) (/* CONSTCOND */ 0)
524 #define mksh_lstat stat
525 #else
526 #define mksh_lstat lstat
527 #endif
528
529 #if HAVE_TERMIOS_H
530 #define mksh_ttyst struct termios
531 #define mksh_tcget(fd,st) tcgetattr((fd), (st))
532 #define mksh_tcset(fd,st) tcsetattr((fd), TCSADRAIN, (st))
533 #else
534 #define mksh_ttyst struct termio
535 #define mksh_tcget(fd,st) ioctl((fd), TCGETA, (st))
536 #define mksh_tcset(fd,st) ioctl((fd), TCSETAW, (st))
537 #endif
538
539 #ifndef ISTRIP
540 #define ISTRIP 0
541 #endif
542
543 #ifdef MKSH_EBCDIC
544 #define KSH_BEL '\a'
545 #define KSH_ESC 047
546 #define KSH_ESC_STRING "\047"
547 #define KSH_VTAB '\v'
548 #else
549 /*
550 * According to the comments in pdksh, \007 seems to be more portable
551 * than \a (HP-UX cc, Ultrix cc, old pcc, etc.) so we avoid the escape
552 * sequence if ASCII can be assumed.
553 */
554 #define KSH_BEL 7
555 #define KSH_ESC 033
556 #define KSH_ESC_STRING "\033"
557 #define KSH_VTAB 11
558 #endif
559
560
561 /* some useful #defines */
562 #ifdef EXTERN
563 # define E_INIT(i) = i
564 #else
565 # define E_INIT(i)
566 # define EXTERN extern
567 # define EXTERN_DEFINED
568 #endif
569
570 /* define bit in flag */
571 #define BIT(i) (1U << (i))
572 #define NELEM(a) (sizeof(a) / sizeof((a)[0]))
573
574 /*
575 * Make MAGIC a char that might be printed to make bugs more obvious, but
576 * not a char that is used often. Also, can't use the high bit as it causes
577 * portability problems (calling strchr(x, 0x80 | 'x') is error prone).
578 *
579 * MAGIC can be followed by MAGIC (to escape the octet itself) or one of:
580 * ' !)*,-?[]{|}' 0x80|' !*+?@' (probably… hysteric raisins abound)
581 *
582 * The |0x80 is likely unsafe on EBCDIC :( though the listed chars are
583 * low-bit7 at least on cp1047 so YMMV
584 */
585 #define MAGIC KSH_BEL /* prefix for *?[!{,} during expand */
586 #define ISMAGIC(c) (ord(c) == ORD(MAGIC))
587
588 EXTERN const char *safe_prompt; /* safe prompt if PS1 substitution fails */
589
590 #ifdef MKSH_LEGACY_MODE
591 #define KSH_VERSIONNAME_ISLEGACY "LEGACY"
592 #else
593 #define KSH_VERSIONNAME_ISLEGACY "MIRBSD"
594 #endif
595 #ifdef MKSH_WITH_TEXTMODE
596 #define KSH_VERSIONNAME_TEXTMODE " +TEXTMODE"
597 #else
598 #define KSH_VERSIONNAME_TEXTMODE ""
599 #endif
600 #ifdef MKSH_EBCDIC
601 #define KSH_VERSIONNAME_EBCDIC " +EBCDIC"
602 #else
603 #define KSH_VERSIONNAME_EBCDIC ""
604 #endif
605 #ifndef KSH_VERSIONNAME_VENDOR_EXT
606 #define KSH_VERSIONNAME_VENDOR_EXT ""
607 #endif
608 EXTERN const char initvsn[] E_INIT("KSH_VERSION=@(#)" KSH_VERSIONNAME_ISLEGACY \
609 " KSH " MKSH_VERSION KSH_VERSIONNAME_EBCDIC KSH_VERSIONNAME_TEXTMODE \
610 KSH_VERSIONNAME_VENDOR_EXT);
611 #define KSH_VERSION (initvsn + /* "KSH_VERSION=@(#)" */ 16)
612
613 EXTERN const char digits_uc[] E_INIT("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
614 EXTERN const char digits_lc[] E_INIT("0123456789abcdefghijklmnopqrstuvwxyz");
615
616 /*
617 * Evil hack for const correctness due to API brokenness
618 */
619 union mksh_cchack {
620 char *rw;
621 const char *ro;
622 };
623 union mksh_ccphack {
624 char **rw;
625 const char **ro;
626 };
627
628 /*
629 * Evil hack since casting uint to sint is implementation-defined
630 */
631 typedef union {
632 mksh_ari_t i;
633 mksh_uari_t u;
634 } mksh_ari_u;
635
636 /* for const debugging */
637 #if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
638 !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
639 char *ucstrchr(char *, int);
640 char *ucstrstr(char *, const char *);
641 #undef strchr
642 #define strchr ucstrchr
643 #define strstr ucstrstr
644 #define cstrchr(s,c) ({ \
645 union mksh_cchack in, out; \
646 \
647 in.ro = (s); \
648 out.rw = ucstrchr(in.rw, (c)); \
649 (out.ro); \
650 })
651 #define cstrstr(b,l) ({ \
652 union mksh_cchack in, out; \
653 \
654 in.ro = (b); \
655 out.rw = ucstrstr(in.rw, (l)); \
656 (out.ro); \
657 })
658 #define vstrchr(s,c) (cstrchr((s), (c)) != NULL)
659 #define vstrstr(b,l) (cstrstr((b), (l)) != NULL)
660 #else /* !DEBUG, !gcc */
661 #define cstrchr(s,c) ((const char *)strchr((s), (c)))
662 #define cstrstr(s,c) ((const char *)strstr((s), (c)))
663 #define vstrchr(s,c) (strchr((s), (c)) != NULL)
664 #define vstrstr(b,l) (strstr((b), (l)) != NULL)
665 #endif
666
667 #if defined(DEBUG) || defined(__COVERITY__)
668 #ifndef DEBUG_LEAKS
669 #define DEBUG_LEAKS
670 #endif
671 #endif
672
673 #if (!defined(MKSH_BUILDMAKEFILE4BSD) && !defined(MKSH_BUILDSH)) || (MKSH_BUILD_R != 593)
674 #error Must run Build.sh to compile this.
675 extern void thiswillneverbedefinedIhope(void);
676 int
im_sorry_dave(void)677 im_sorry_dave(void)
678 {
679 /* I’m sorry, Dave. I’m afraid I can’t do that. */
680 return (thiswillneverbedefinedIhope());
681 }
682 #endif
683
684 /* use this ipv strchr(s, 0) but no side effects in s! */
685 #define strnul(s) ((s) + strlen((const void *)s))
686
687 #define utf_ptradjx(src,dst) do { \
688 (dst) = (src) + utf_ptradj(src); \
689 } while (/* CONSTCOND */ 0)
690
691 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
692 #define strdupx(d,s,ap) do { \
693 (d) = strdup_i((s), (ap)); \
694 } while (/* CONSTCOND */ 0)
695 #define strndupx(d,s,n,ap) do { \
696 (d) = strndup_i((s), (n), (ap)); \
697 } while (/* CONSTCOND */ 0)
698 #else
699 /* be careful to evaluate arguments only once! */
700 #define strdupx(d,s,ap) do { \
701 const char *strdup_src = (const void *)(s); \
702 char *strdup_dst = NULL; \
703 \
704 if (strdup_src != NULL) { \
705 size_t strdup_len = strlen(strdup_src) + 1; \
706 strdup_dst = alloc(strdup_len, (ap)); \
707 memcpy(strdup_dst, strdup_src, strdup_len); \
708 } \
709 (d) = strdup_dst; \
710 } while (/* CONSTCOND */ 0)
711 #define strndupx(d,s,n,ap) do { \
712 const char *strdup_src = (const void *)(s); \
713 char *strdup_dst = NULL; \
714 \
715 if (strdup_src != NULL) { \
716 size_t strndup_len = (n); \
717 strdup_dst = alloc(strndup_len + 1, (ap)); \
718 memcpy(strdup_dst, strdup_src, strndup_len); \
719 strdup_dst[strndup_len] = '\0'; \
720 } \
721 (d) = strdup_dst; \
722 } while (/* CONSTCOND */ 0)
723 #endif
724 #define strdup2x(d,s1,s2) do { \
725 const char *strdup_src = (const void *)(s1); \
726 const char *strdup_app = (const void *)(s2); \
727 size_t strndup_len = strlen(strdup_src); \
728 size_t strndup_ln2 = strlen(strdup_app) + 1; \
729 char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP); \
730 \
731 memcpy(strdup_dst, strdup_src, strndup_len); \
732 memcpy(strdup_dst + strndup_len, strdup_app, strndup_ln2); \
733 (d) = strdup_dst; \
734 } while (/* CONSTCOND */ 0)
735 #define strpathx(d,s1,s2,cond) do { \
736 const char *strdup_src = (const void *)(s1); \
737 const char *strdup_app = (const void *)(s2); \
738 size_t strndup_len = strlen(strdup_src) + 1; \
739 size_t strndup_ln2 = ((cond) || *strdup_app) ? \
740 strlen(strdup_app) + 1 : 0; \
741 char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP); \
742 \
743 memcpy(strdup_dst, strdup_src, strndup_len); \
744 if (strndup_ln2) { \
745 strdup_dst[strndup_len - 1] = '/'; \
746 memcpy(strdup_dst + strndup_len, strdup_app, \
747 strndup_ln2); \
748 } \
749 (d) = strdup_dst; \
750 } while (/* CONSTCOND */ 0)
751
752 #ifdef MKSH_SMALL
753 #ifndef MKSH_NOPWNAM
754 #define MKSH_NOPWNAM /* defined */
755 #endif
756 #ifndef MKSH_S_NOVI
757 #define MKSH_S_NOVI 1
758 #endif
759 #endif
760
761 #ifndef MKSH_S_NOVI
762 #define MKSH_S_NOVI 0
763 #endif
764
765 #if defined(MKSH_NOPROSPECTOFWORK) && !defined(MKSH_UNEMPLOYED)
766 #define MKSH_UNEMPLOYED 1
767 #endif
768
769 #define NUFILE 32 /* Number of user-accessible files */
770 #define FDBASE 10 /* First file usable by Shell */
771
772 /*
773 * simple grouping allocator
774 */
775
776
777 /* 0. OS API: where to get memory from and how to free it (grouped) */
778
779 /* malloc(3)/realloc(3) -> free(3) for use by the memory allocator */
780 #define malloc_osi(sz) malloc(sz)
781 #define realloc_osi(p,sz) realloc((p), (sz))
782 #define free_osimalloc(p) free(p)
783
784 /* malloc(3)/realloc(3) -> free(3) for use by mksh code */
785 #define malloc_osfunc(sz) malloc(sz)
786 #define realloc_osfunc(p,sz) realloc((p), (sz))
787 #define free_osfunc(p) free(p)
788
789 #if HAVE_MKNOD
790 /* setmode(3) -> free(3) */
791 #define free_ossetmode(p) free(p)
792 #endif
793
794 #ifdef MKSH__NO_PATH_MAX
795 /* GNU libc: get_current_dir_name(3) -> free(3) */
796 #define free_gnu_gcdn(p) free(p)
797 #endif
798
799
800 /* 1. internal structure */
801 struct lalloc_common {
802 struct lalloc_common *next;
803 };
804
805 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
806 struct lalloc_item {
807 struct lalloc_common *next;
808 size_t len;
809 char dummy[8192 - sizeof(struct lalloc_common *) - sizeof(size_t)];
810 };
811 #endif
812
813 /* 2. sizes */
814 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
815 #define ALLOC_ITEM struct lalloc_item
816 #define ALLOC_OVERHEAD 0
817 #else
818 #define ALLOC_ITEM struct lalloc_common
819 #define ALLOC_OVERHEAD (sizeof(ALLOC_ITEM))
820 #endif
821
822 /* 3. group structure */
823 typedef struct lalloc_common Area;
824
825
826 EXTERN Area aperm; /* permanent object space */
827 #define APERM &aperm
828 #define ATEMP &e->area
829
830 /*
831 * flags (the order of these enums MUST match the order in misc.c(options[]))
832 */
833 enum sh_flag {
834 #define SHFLAGS_ENUMS
835 #include "sh_flags.gen"
836 FNFLAGS /* (place holder: how many flags are there) */
837 };
838
839 #define Flag(f) (shell_flags[(int)(f)])
840 #define UTFMODE Flag(FUNNYCODE)
841
842 /*
843 * parsing & execution environment
844 *
845 * note that kshlongjmp MUST NOT be passed 0 as second argument!
846 */
847 #ifdef MKSH_NO_SIGSETJMP
848 #define kshjmp_buf jmp_buf
849 #define kshsetjmp(jbuf) _setjmp(jbuf)
850 #define kshlongjmp _longjmp
851 #else
852 #define kshjmp_buf sigjmp_buf
853 #define kshsetjmp(jbuf) sigsetjmp((jbuf), 0)
854 #define kshlongjmp siglongjmp
855 #endif
856
857 struct sretrace_info;
858 struct yyrecursive_state;
859
860 EXTERN struct sretrace_info *retrace_info;
861 EXTERN unsigned int subshell_nesting_type;
862
863 extern struct env {
864 ALLOC_ITEM alloc_INT; /* internal, do not touch */
865 Area area; /* temporary allocation area */
866 struct env *oenv; /* link to previous environment */
867 struct block *loc; /* local variables and functions */
868 short *savefd; /* original redirected fds */
869 struct temp *temps; /* temp files */
870 /* saved parser recursion state */
871 struct yyrecursive_state *yyrecursive_statep;
872 kshjmp_buf jbuf; /* long jump back to env creator */
873 uint8_t type; /* environment type - see below */
874 uint8_t flags; /* EF_* */
875 } *e;
876
877 /* struct env.type values */
878 #define E_NONE 0 /* dummy environment */
879 #define E_PARSE 1 /* parsing command # */
880 #define E_FUNC 2 /* executing function # */
881 #define E_INCL 3 /* including a file via . # */
882 #define E_EXEC 4 /* executing command tree */
883 #define E_LOOP 5 /* executing for/while # */
884 #define E_ERRH 6 /* general error handler # */
885 #define E_GONE 7 /* hidden in child */
886 #define E_EVAL 8 /* running eval # */
887 /* # indicates env has valid jbuf (see unwind()) */
888
889 /* struct env.flag values */
890 #define EF_BRKCONT_PASS BIT(1) /* set if E_LOOP must pass break/continue on */
891 #define EF_FAKE_SIGDIE BIT(2) /* hack to get info from unwind to quitenv */
892 #define EF_IN_EVAL BIT(3) /* inside an eval */
893
894 /* Do breaks/continues stop at env type e? */
895 #define STOP_BRKCONT(t) ((t) == E_NONE || (t) == E_PARSE || \
896 (t) == E_FUNC || (t) == E_INCL)
897 /* Do returns stop at env type e? */
898 #define STOP_RETURN(t) ((t) == E_FUNC || (t) == E_INCL)
899
900 /* values for kshlongjmp(e->jbuf, i) */
901 /* note that i MUST NOT be zero */
902 #define LRETURN 1 /* return statement */
903 #define LEXIT 2 /* exit statement */
904 #define LERROR 3 /* errorf() called */
905 #define LERREXT 4 /* set -e caused */
906 #define LINTR 5 /* ^C noticed */
907 #define LBREAK 6 /* break statement */
908 #define LCONTIN 7 /* continue statement */
909 #define LSHELL 8 /* return to interactive shell() */
910 #define LAEXPR 9 /* error in arithmetic expression */
911 #define LLEAVE 10 /* untrappable exit/error */
912
913 /* sort of shell global state */
914 EXTERN pid_t procpid; /* PID of executing process */
915 EXTERN int exstat; /* exit status */
916 EXTERN int subst_exstat; /* exit status of last $(..)/`..` */
917 EXTERN struct tbl *vp_pipest; /* global PIPESTATUS array */
918 EXTERN short trap_exstat; /* exit status before running a trap */
919 EXTERN uint8_t trap_nested; /* running nested traps */
920 EXTERN uint8_t shell_flags[FNFLAGS];
921 EXTERN uint8_t baseline_flags[FNFLAGS
922 #if !defined(MKSH_SMALL) || defined(DEBUG)
923 + 1
924 #endif
925 ];
926 EXTERN bool as_builtin; /* direct builtin call */
927 EXTERN const char *kshname; /* $0 */
928 EXTERN struct {
929 uid_t kshuid_v; /* real UID of shell at startup */
930 uid_t ksheuid_v; /* effective UID of shell */
931 gid_t kshgid_v; /* real GID of shell at startup */
932 gid_t kshegid_v; /* effective GID of shell */
933 pid_t kshpgrp_v; /* process group of shell */
934 pid_t kshppid_v; /* PID of parent of shell */
935 pid_t kshpid_v; /* $$, shell PID */
936 } rndsetupstate;
937
938 #define kshpid rndsetupstate.kshpid_v
939 #define kshpgrp rndsetupstate.kshpgrp_v
940 #define kshuid rndsetupstate.kshuid_v
941 #define ksheuid rndsetupstate.ksheuid_v
942 #define kshgid rndsetupstate.kshgid_v
943 #define kshegid rndsetupstate.kshegid_v
944 #define kshppid rndsetupstate.kshppid_v
945
946
947 /* option processing */
948 #define OF_CMDLINE 0x01 /* command line */
949 #define OF_SET 0x02 /* set builtin */
950 #define OF_SPECIAL 0x04 /* a special variable changing */
951 #define OF_INTERNAL 0x08 /* set internally by shell */
952 #define OF_FIRSTTIME 0x10 /* as early as possible, once */
953 #define OF_ANY (OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
954
955 /* null value for variable; comparison pointer for unset */
956 EXTERN char null[] E_INIT("");
957
958 /* string pooling: do we rely on the compiler? */
959 #ifndef HAVE_STRING_POOLING
960 /* no, we use our own, saves quite some space */
961 #elif HAVE_STRING_POOLING == 2
962 /* “on demand” */
963 #ifdef __GNUC__
964 /* only for GCC 4 or later, older ones can get by without */
965 #if __GNUC__ < 4
966 #undef HAVE_STRING_POOLING
967 #endif
968 #else
969 /* not GCC, default to on */
970 #endif
971 #elif HAVE_STRING_POOLING == 0
972 /* default to on, unless explicitly set to 0 */
973 #undef HAVE_STRING_POOLING
974 #endif
975
976 #ifndef HAVE_STRING_POOLING /* helpers for pooled strings */
977 EXTERN const char T4spaces[] E_INIT(" ");
978 #define T1space (Treal_sp2 + 5)
979 #define Tcolsp (Tf_sD_ + 2)
980 #define TC_IFSWS (TinitIFS + 4)
981 EXTERN const char TinitIFS[] E_INIT("IFS= \t\n");
982 EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} $_");
983 #define Tspdollaru (TFCEDIT_dollaru + 18)
984 EXTERN const char Tsgdot[] E_INIT("*=.");
985 EXTERN const char Taugo[] E_INIT("augo");
986 EXTERN const char Tbracket[] E_INIT("[");
987 #define Tdot (Tsgdot + 2)
988 #define Talias (Tunalias + 2)
989 EXTERN const char Tbadnum[] E_INIT("bad number");
990 #define Tbadsubst (Tfg_badsubst + 10)
991 EXTERN const char Tbg[] E_INIT("bg");
992 EXTERN const char Tbad_bsize[] E_INIT("bad shf/buf/bsize");
993 #define Tbsize (Tbad_bsize + 12)
994 EXTERN const char Tbad_sig_ss[] E_INIT("%s: bad signal '%s'");
995 #define Tbad_sig_s (Tbad_sig_ss + 4)
996 EXTERN const char Tsgbreak[] E_INIT("*=break");
997 #define Tbreak (Tsgbreak + 2)
998 EXTERN const char T__builtin[] E_INIT("-\\builtin");
999 #define T_builtin (T__builtin + 1)
1000 #define Tbuiltin (T__builtin + 2)
1001 EXTERN const char Toomem[] E_INIT("can't allocate %zu data bytes");
1002 EXTERN const char Tcant_cd[] E_INIT("restricted shell - can't cd");
1003 EXTERN const char Tcant_find[] E_INIT("can't find");
1004 EXTERN const char Tcant_open[] E_INIT("can't open");
1005 #define Tbytes (Toomem + 24)
1006 EXTERN const char Tbcat[] E_INIT("!cat");
1007 #define Tcat (Tbcat + 1)
1008 #define Tcd (Tcant_cd + 25)
1009 #define T_command (T_funny_command + 9)
1010 #define Tcommand (T_funny_command + 10)
1011 EXTERN const char Tsgcontinue[] E_INIT("*=continue");
1012 #define Tcontinue (Tsgcontinue + 2)
1013 EXTERN const char Tcreate[] E_INIT("create");
1014 EXTERN const char TELIF_unexpected[] E_INIT("TELIF unexpected");
1015 EXTERN const char TEXECSHELL[] E_INIT("EXECSHELL");
1016 EXTERN const char TENV[] E_INIT("ENV");
1017 EXTERN const char Tdsgexport[] E_INIT("^*=export");
1018 #define Texport (Tdsgexport + 3)
1019 #ifdef __OS2__
1020 EXTERN const char Textproc[] E_INIT("extproc");
1021 #endif
1022 EXTERN const char Tfalse[] E_INIT("false");
1023 EXTERN const char Tfg[] E_INIT("fg");
1024 EXTERN const char Tfg_badsubst[] E_INIT("fileglob: bad substitution");
1025 #define Tfile (Tfile_fd + 20)
1026 EXTERN const char Tfile_fd[] E_INIT("function definition file");
1027 EXTERN const char TFPATH[] E_INIT("FPATH");
1028 EXTERN const char T_function[] E_INIT(" function");
1029 #define Tfunction (T_function + 1)
1030 EXTERN const char T_funny_command[] E_INIT("funny $()-command");
1031 EXTERN const char Tgetopts[] E_INIT("getopts");
1032 #define Thistory (Tnot_in_history + 7)
1033 EXTERN const char Tintovfl[] E_INIT("integer overflow %zu %c %zu prevented");
1034 EXTERN const char Tinvname[] E_INIT("%s: invalid %s name");
1035 EXTERN const char Tjobs[] E_INIT("jobs");
1036 EXTERN const char Tjob_not_started[] E_INIT("job not started");
1037 EXTERN const char Tmksh[] E_INIT("mksh");
1038 #define Tname (Tinvname + 15)
1039 EXTERN const char Tno_args[] E_INIT("missing argument");
1040 EXTERN const char Tno_OLDPWD[] E_INIT("no OLDPWD");
1041 EXTERN const char Tnot_ident[] E_INIT("is not an identifier");
1042 EXTERN const char Tnot_in_history[] E_INIT("not in history");
1043 EXTERN const char Tnot_found_s[] E_INIT("%s not found");
1044 #define Tnot_found (Tnot_found_s + 3)
1045 #define Tnot_started (Tjob_not_started + 4)
1046 #define TOLDPWD (Tno_OLDPWD + 3)
1047 #define Topen (Tcant_open + 6)
1048 EXTERN const char To_o_reset[] E_INIT(" -o .reset");
1049 #define To_reset (To_o_reset + 4)
1050 #define TPATH (TFPATH + 1)
1051 #define Tpo (Tset_po + 4)
1052 #define Tpv (TpVv + 1)
1053 EXTERN const char TpVv[] E_INIT("Vpv");
1054 #define TPWD (Tno_OLDPWD + 6)
1055 #define Tread (Tshf_read + 4)
1056 EXTERN const char Tdsgreadonly[] E_INIT("^*=readonly");
1057 #define Treadonly (Tdsgreadonly + 3)
1058 EXTERN const char Tredirection_dup[] E_INIT("can't finish (dup) redirection");
1059 #define Tredirection (Tredirection_dup + 19)
1060 #define Treal_sp1 (Treal_sp2 + 1)
1061 EXTERN const char Treal_sp2[] E_INIT(" real ");
1062 EXTERN const char TREPLY[] E_INIT("REPLY");
1063 EXTERN const char Treq_arg[] E_INIT("requires an argument");
1064 EXTERN const char Tselect[] E_INIT("select");
1065 #define Tset (Tf_parm + 18)
1066 EXTERN const char Tset_po[] E_INIT("set +o");
1067 EXTERN const char Tsghset[] E_INIT("*=#set");
1068 #define Tsh (Tmksh + 2)
1069 #define TSHELL (TEXECSHELL + 4)
1070 #define Tshell (Ttoo_many_files + 23)
1071 EXTERN const char Tshf_read[] E_INIT("shf_read");
1072 EXTERN const char Tshf_write[] E_INIT("shf_write");
1073 EXTERN const char Tgsource[] E_INIT("=source");
1074 #define Tsource (Tgsource + 1)
1075 EXTERN const char Tj_suspend[] E_INIT("j_suspend");
1076 #define Tsuspend (Tj_suspend + 2)
1077 EXTERN const char Tsynerr[] E_INIT("syntax error");
1078 EXTERN const char Ttime[] E_INIT("time");
1079 EXTERN const char Ttoo_many_args[] E_INIT("too many arguments");
1080 EXTERN const char Ttoo_many_files[] E_INIT("too many open files in shell");
1081 EXTERN const char Ttrue[] E_INIT("true");
1082 EXTERN const char Ttty_fd_dupof[] E_INIT("dup of tty fd");
1083 #define Ttty_fd (Ttty_fd_dupof + 7)
1084 EXTERN const char Tdgtypeset[] E_INIT("^=typeset");
1085 #define Ttypeset (Tdgtypeset + 2)
1086 #define Tugo (Taugo + 1)
1087 EXTERN const char Tunalias[] E_INIT("unalias");
1088 #define Tunexpected (TELIF_unexpected + 6)
1089 EXTERN const char Tunexpected_type[] E_INIT("%s: unexpected %s type %d");
1090 EXTERN const char Tunknown_option[] E_INIT("unknown option");
1091 EXTERN const char Tunwind[] E_INIT("unwind");
1092 #define Tuser_sp1 (Tuser_sp2 + 1)
1093 EXTERN const char Tuser_sp2[] E_INIT(" user ");
1094 #define Twrite (Tshf_write + 4)
1095 EXTERN const char Tf__S[] E_INIT(" %S");
1096 #define Tf__d (Tunexpected_type + 22)
1097 #define Tf_ss (Tf__ss + 1)
1098 EXTERN const char Tf__ss[] E_INIT(" %s%s");
1099 #define Tf__sN (Tf_s_s_sN + 5)
1100 #define Tf_T (Tf_s_T + 3)
1101 EXTERN const char Tf_dN[] E_INIT("%d\n");
1102 EXTERN const char Tf_s_[] E_INIT("%s ");
1103 EXTERN const char Tf_s_T[] E_INIT("%s %T");
1104 EXTERN const char Tf_s_s_sN[] E_INIT("%s %s %s\n");
1105 #define Tf_s_s (Tf_sD_s_s + 4)
1106 #define Tf__s_s (Tf_sD_s_s + 3)
1107 #define Tf_s_sD_s (Tf_cant_ss_s + 6)
1108 EXTERN const char Tf_optfoo[] E_INIT("%s%s-%c: %s");
1109 EXTERN const char Tf_sD_[] E_INIT("%s: ");
1110 EXTERN const char Tf_szs[] E_INIT("%s: %zd %s");
1111 EXTERN const char Tf_parm[] E_INIT("%s: parameter not set");
1112 EXTERN const char Tf_coproc[] E_INIT("-p: %s");
1113 EXTERN const char Tf_cant_s[] E_INIT("%s: can't %s");
1114 EXTERN const char Tf_cant_ss_s[] E_INIT("can't %s %s: %s");
1115 EXTERN const char Tf_heredoc[] E_INIT("here document '%s' unclosed");
1116 #if HAVE_MKNOD
1117 EXTERN const char Tf_nonnum[] E_INIT("non-numeric %s %s '%s'");
1118 #endif
1119 EXTERN const char Tf_S_[] E_INIT("%S ");
1120 #define Tf_S (Tf__S + 1)
1121 #define Tf_lu (Tf_toolarge + 17)
1122 EXTERN const char Tf_toolarge[] E_INIT("%s %s too large: %lu");
1123 EXTERN const char Tf_ldfailed[] E_INIT("%s %s(%d, %ld) failed: %s");
1124 EXTERN const char Tf_sD_s_sD_s[] E_INIT("%s: %s %s: %s");
1125 EXTERN const char Tf_toomany[] E_INIT("too many %ss");
1126 EXTERN const char Tf_sd[] E_INIT("%s %d");
1127 #define Tf_s (Tf_temp + 28)
1128 EXTERN const char Tft_end[] E_INIT("%;");
1129 EXTERN const char Tft_R[] E_INIT("%R");
1130 #define Tf_d (Tunexpected_type + 23)
1131 EXTERN const char Tf_sD_s_qs[] E_INIT("%s: %s '%s'");
1132 EXTERN const char Tf_ro[] E_INIT("read-only: %s");
1133 EXTERN const char Tf_flags[] E_INIT("%s: flags 0x%X");
1134 EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s: %s");
1135 EXTERN const char Tf_ssfaileds[] E_INIT("%s: %s failed: %s");
1136 EXTERN const char Tf_sD_sD_s[] E_INIT("%s: %s: %s");
1137 EXTERN const char Tf__c_[] E_INIT("-%c ");
1138 EXTERN const char Tf_sD_s_s[] E_INIT("%s: %s %s");
1139 #define Tf_sN (Tf_s_s_sN + 6)
1140 #define Tf_sD_s (Tf_temp + 24)
1141 EXTERN const char T_devtty[] E_INIT("/dev/tty");
1142 #else /* helpers for string pooling */
1143 #define T4spaces " "
1144 #define T1space " "
1145 #define Tcolsp ": "
1146 #define TC_IFSWS " \t\n"
1147 #define TinitIFS "IFS= \t\n"
1148 #define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} $_"
1149 #define Tspdollaru " $_"
1150 #define Tsgdot "*=."
1151 #define Taugo "augo"
1152 #define Tbracket "["
1153 #define Tdot "."
1154 #define Talias "alias"
1155 #define Tbadnum "bad number"
1156 #define Tbadsubst "bad substitution"
1157 #define Tbg "bg"
1158 #define Tbad_bsize "bad shf/buf/bsize"
1159 #define Tbsize "bsize"
1160 #define Tbad_sig_ss "%s: bad signal '%s'"
1161 #define Tbad_sig_s "bad signal '%s'"
1162 #define Tsgbreak "*=break"
1163 #define Tbreak "break"
1164 #define T__builtin "-\\builtin"
1165 #define T_builtin "\\builtin"
1166 #define Tbuiltin "builtin"
1167 #define Toomem "can't allocate %zu data bytes"
1168 #define Tcant_cd "restricted shell - can't cd"
1169 #define Tcant_find "can't find"
1170 #define Tcant_open "can't open"
1171 #define Tbytes "bytes"
1172 #define Tbcat "!cat"
1173 #define Tcat "cat"
1174 #define Tcd "cd"
1175 #define T_command "-command"
1176 #define Tcommand "command"
1177 #define Tsgcontinue "*=continue"
1178 #define Tcontinue "continue"
1179 #define Tcreate "create"
1180 #define TELIF_unexpected "TELIF unexpected"
1181 #define TEXECSHELL "EXECSHELL"
1182 #define TENV "ENV"
1183 #define Tdsgexport "^*=export"
1184 #define Texport "export"
1185 #ifdef __OS2__
1186 #define Textproc "extproc"
1187 #endif
1188 #define Tfalse "false"
1189 #define Tfg "fg"
1190 #define Tfg_badsubst "fileglob: bad substitution"
1191 #define Tfile "file"
1192 #define Tfile_fd "function definition file"
1193 #define TFPATH "FPATH"
1194 #define T_function " function"
1195 #define Tfunction "function"
1196 #define T_funny_command "funny $()-command"
1197 #define Tgetopts "getopts"
1198 #define Thistory "history"
1199 #define Tintovfl "integer overflow %zu %c %zu prevented"
1200 #define Tinvname "%s: invalid %s name"
1201 #define Tjobs "jobs"
1202 #define Tjob_not_started "job not started"
1203 #define Tmksh "mksh"
1204 #define Tname "name"
1205 #define Tno_args "missing argument"
1206 #define Tno_OLDPWD "no OLDPWD"
1207 #define Tnot_ident "is not an identifier"
1208 #define Tnot_in_history "not in history"
1209 #define Tnot_found_s "%s not found"
1210 #define Tnot_found "not found"
1211 #define Tnot_started "not started"
1212 #define TOLDPWD "OLDPWD"
1213 #define Topen "open"
1214 #define To_o_reset " -o .reset"
1215 #define To_reset ".reset"
1216 #define TPATH "PATH"
1217 #define Tpo "+o"
1218 #define Tpv "pv"
1219 #define TpVv "Vpv"
1220 #define TPWD "PWD"
1221 #define Tread "read"
1222 #define Tdsgreadonly "^*=readonly"
1223 #define Treadonly "readonly"
1224 #define Tredirection_dup "can't finish (dup) redirection"
1225 #define Tredirection "redirection"
1226 #define Treal_sp1 "real "
1227 #define Treal_sp2 " real "
1228 #define TREPLY "REPLY"
1229 #define Treq_arg "requires an argument"
1230 #define Tselect "select"
1231 #define Tset "set"
1232 #define Tset_po "set +o"
1233 #define Tsghset "*=#set"
1234 #define Tsh "sh"
1235 #define TSHELL "SHELL"
1236 #define Tshell "shell"
1237 #define Tshf_read "shf_read"
1238 #define Tshf_write "shf_write"
1239 #define Tgsource "=source"
1240 #define Tsource "source"
1241 #define Tj_suspend "j_suspend"
1242 #define Tsuspend "suspend"
1243 #define Tsynerr "syntax error"
1244 #define Ttime "time"
1245 #define Ttoo_many_args "too many arguments"
1246 #define Ttoo_many_files "too many open files in shell"
1247 #define Ttrue "true"
1248 #define Ttty_fd_dupof "dup of tty fd"
1249 #define Ttty_fd "tty fd"
1250 #define Tdgtypeset "^=typeset"
1251 #define Ttypeset "typeset"
1252 #define Tugo "ugo"
1253 #define Tunalias "unalias"
1254 #define Tunexpected "unexpected"
1255 #define Tunexpected_type "%s: unexpected %s type %d"
1256 #define Tunknown_option "unknown option"
1257 #define Tunwind "unwind"
1258 #define Tuser_sp1 "user "
1259 #define Tuser_sp2 " user "
1260 #define Twrite "write"
1261 #define Tf__S " %S"
1262 #define Tf__d " %d"
1263 #define Tf_ss "%s%s"
1264 #define Tf__ss " %s%s"
1265 #define Tf__sN " %s\n"
1266 #define Tf_T "%T"
1267 #define Tf_dN "%d\n"
1268 #define Tf_s_ "%s "
1269 #define Tf_s_T "%s %T"
1270 #define Tf_s_s_sN "%s %s %s\n"
1271 #define Tf_s_s "%s %s"
1272 #define Tf__s_s " %s %s"
1273 #define Tf_s_sD_s "%s %s: %s"
1274 #define Tf_optfoo "%s%s-%c: %s"
1275 #define Tf_sD_ "%s: "
1276 #define Tf_szs "%s: %zd %s"
1277 #define Tf_parm "%s: parameter not set"
1278 #define Tf_coproc "-p: %s"
1279 #define Tf_cant_s "%s: can't %s"
1280 #define Tf_cant_ss_s "can't %s %s: %s"
1281 #define Tf_heredoc "here document '%s' unclosed"
1282 #if HAVE_MKNOD
1283 #define Tf_nonnum "non-numeric %s %s '%s'"
1284 #endif
1285 #define Tf_S_ "%S "
1286 #define Tf_S "%S"
1287 #define Tf_lu "%lu"
1288 #define Tf_toolarge "%s %s too large: %lu"
1289 #define Tf_ldfailed "%s %s(%d, %ld) failed: %s"
1290 #define Tf_sD_s_sD_s "%s: %s %s: %s"
1291 #define Tf_toomany "too many %ss"
1292 #define Tf_sd "%s %d"
1293 #define Tf_s "%s"
1294 #define Tft_end "%;"
1295 #define Tft_R "%R"
1296 #define Tf_d "%d"
1297 #define Tf_sD_s_qs "%s: %s '%s'"
1298 #define Tf_ro "read-only: %s"
1299 #define Tf_flags "%s: flags 0x%X"
1300 #define Tf_temp "can't %s temporary file %s: %s"
1301 #define Tf_ssfaileds "%s: %s failed: %s"
1302 #define Tf_sD_sD_s "%s: %s: %s"
1303 #define Tf__c_ "-%c "
1304 #define Tf_sD_s_s "%s: %s %s"
1305 #define Tf_sN "%s\n"
1306 #define Tf_sD_s "%s: %s"
1307 #define T_devtty "/dev/tty"
1308 #endif /* end of string pooling */
1309
1310 typedef uint8_t Temp_type;
1311 /* expanded heredoc */
1312 #define TT_HEREDOC_EXP 0
1313 /* temporary file used for history editing (fc -e) */
1314 #define TT_HIST_EDIT 1
1315 /* temporary file used during in-situ command substitution */
1316 #define TT_FUNSUB 2
1317
1318 /* temp/heredoc files. The file is removed when the struct is freed. */
1319 struct temp {
1320 struct temp *next;
1321 struct shf *shf;
1322 /* pid of process parsed here-doc */
1323 pid_t pid;
1324 Temp_type type;
1325 /* actually longer: name (variable length) */
1326 char tffn[3];
1327 };
1328
1329 /*
1330 * stdio and our IO routines
1331 */
1332
1333 #define shl_xtrace (&shf_iob[0]) /* for set -x */
1334 #define shl_stdout (&shf_iob[1])
1335 #define shl_out (&shf_iob[2])
1336 #ifdef DF
1337 #define shl_dbg (&shf_iob[3]) /* for DF() */
1338 #endif
1339 EXTERN bool shl_stdout_ok;
1340
1341 /*
1342 * trap handlers
1343 */
1344 typedef struct trap {
1345 const char *name; /* short name */
1346 const char *mess; /* descriptive name */
1347 char *trap; /* trap command */
1348 sig_t cursig; /* current handler (valid if TF_ORIG_* set) */
1349 sig_t shtrap; /* shell signal handler */
1350 int signal; /* signal number */
1351 int flags; /* TF_* */
1352 volatile sig_atomic_t set; /* trap pending */
1353 } Trap;
1354
1355 /* values for Trap.flags */
1356 #define TF_SHELL_USES BIT(0) /* shell uses signal, user can't change */
1357 #define TF_USER_SET BIT(1) /* user has (tried to) set trap */
1358 #define TF_ORIG_IGN BIT(2) /* original action was SIG_IGN */
1359 #define TF_ORIG_DFL BIT(3) /* original action was SIG_DFL */
1360 #define TF_EXEC_IGN BIT(4) /* restore SIG_IGN just before exec */
1361 #define TF_EXEC_DFL BIT(5) /* restore SIG_DFL just before exec */
1362 #define TF_DFL_INTR BIT(6) /* when received, default action is LINTR */
1363 #define TF_TTY_INTR BIT(7) /* tty generated signal (see j_waitj) */
1364 #define TF_CHANGED BIT(8) /* used by runtrap() to detect trap changes */
1365 #define TF_FATAL BIT(9) /* causes termination if not trapped */
1366
1367 /* values for setsig()/setexecsig() flags argument */
1368 #define SS_RESTORE_MASK 0x3 /* how to restore a signal before an exec() */
1369 #define SS_RESTORE_CURR 0 /* leave current handler in place */
1370 #define SS_RESTORE_ORIG 1 /* restore original handler */
1371 #define SS_RESTORE_DFL 2 /* restore to SIG_DFL */
1372 #define SS_RESTORE_IGN 3 /* restore to SIG_IGN */
1373 #define SS_FORCE BIT(3) /* set signal even if original signal ignored */
1374 #define SS_USER BIT(4) /* user is doing the set (ie, trap command) */
1375 #define SS_SHTRAP BIT(5) /* trap for internal use (ALRM, CHLD, WINCH) */
1376
1377 #define ksh_SIGEXIT 0 /* for trap EXIT */
1378 #define ksh_SIGERR ksh_NSIG /* for trap ERR */
1379
1380 EXTERN volatile sig_atomic_t trap; /* traps pending? */
1381 EXTERN volatile sig_atomic_t intrsig; /* pending trap interrupts command */
1382 EXTERN volatile sig_atomic_t fatal_trap; /* received a fatal signal */
1383 extern Trap sigtraps[ksh_NSIG + 1];
1384
1385 /* got_winch = 1 when we need to re-adjust the window size */
1386 #ifdef SIGWINCH
1387 EXTERN volatile sig_atomic_t got_winch E_INIT(1);
1388 #else
1389 #define got_winch true
1390 #endif
1391
1392 /*
1393 * TMOUT support
1394 */
1395 /* values for ksh_tmout_state */
1396 enum tmout_enum {
1397 TMOUT_EXECUTING = 0, /* executing commands */
1398 TMOUT_READING, /* waiting for input */
1399 TMOUT_LEAVING /* have timed out */
1400 };
1401 EXTERN unsigned int ksh_tmout;
1402 EXTERN enum tmout_enum ksh_tmout_state;
1403
1404 /* For "You have stopped jobs" message */
1405 EXTERN bool really_exit;
1406
1407 /*
1408 * fast character classes
1409 */
1410
1411 /* internal types, do not reference */
1412
1413 /* initially empty — filled at runtime from $IFS */
1414 #define CiIFS BIT(0)
1415 #define CiCNTRL BIT(1) /* \x01‥\x08\x0E‥\x1F\x7F */
1416 #define CiUPPER BIT(2) /* A‥Z */
1417 #define CiLOWER BIT(3) /* a‥z */
1418 #define CiHEXLT BIT(4) /* A‥Fa‥f */
1419 #define CiOCTAL BIT(5) /* 0‥7 */
1420 #define CiQCL BIT(6) /* &();| */
1421 #define CiALIAS BIT(7) /* !,.@ */
1422 #define CiQCX BIT(8) /* *[\\ */
1423 #define CiVAR1 BIT(9) /* !*@ */
1424 #define CiQCM BIT(10) /* /^~ */
1425 #define CiDIGIT BIT(11) /* 89 */
1426 #define CiQC BIT(12) /* "' */
1427 #define CiSPX BIT(13) /* \x0B\x0C */
1428 #define CiCURLY BIT(14) /* {} */
1429 #define CiANGLE BIT(15) /* <> */
1430 #define CiNUL BIT(16) /* \x00 */
1431 #define CiTAB BIT(17) /* \x09 */
1432 #define CiNL BIT(18) /* \x0A */
1433 #define CiCR BIT(19) /* \x0D */
1434 #define CiSP BIT(20) /* \x20 */
1435 #define CiHASH BIT(21) /* # */
1436 #define CiSS BIT(22) /* $ */
1437 #define CiPERCT BIT(23) /* % */
1438 #define CiPLUS BIT(24) /* + */
1439 #define CiMINUS BIT(25) /* - */
1440 #define CiCOLON BIT(26) /* : */
1441 #define CiEQUAL BIT(27) /* = */
1442 #define CiQUEST BIT(28) /* ? */
1443 #define CiBRACK BIT(29) /* [] */
1444 #define CiUNDER BIT(30) /* _ */
1445 #define CiGRAVE BIT(31) /* ` */
1446 /* out of space, but one for *@ would make sense, possibly others */
1447
1448 /* compile-time initialised, ASCII only */
1449 extern const uint32_t tpl_ctypes[128];
1450 /* run-time, contains C_IFS as well, full 2⁸ octet range */
1451 EXTERN uint32_t ksh_ctypes[256];
1452 /* first octet of $IFS, for concatenating "$*" */
1453 EXTERN char ifs0;
1454
1455 /* external types */
1456
1457 /* !%+,-.0‥9:@A‥Z[]_a‥z valid characters in alias names */
1458 #define C_ALIAS (CiALIAS | CiBRACK | CiCOLON | CiDIGIT | CiLOWER | CiMINUS | CiOCTAL | CiPERCT | CiPLUS | CiUNDER | CiUPPER)
1459 /* 0‥9A‥Za‥z alphanumerical */
1460 #define C_ALNUM (CiDIGIT | CiLOWER | CiOCTAL | CiUPPER)
1461 /* 0‥9A‥Z_a‥z alphanumerical plus underscore (“word character”) */
1462 #define C_ALNUX (CiDIGIT | CiLOWER | CiOCTAL | CiUNDER | CiUPPER)
1463 /* A‥Za‥z alphabetical (upper plus lower) */
1464 #define C_ALPHA (CiLOWER | CiUPPER)
1465 /* A‥Z_a‥z alphabetical plus underscore (identifier lead) */
1466 #define C_ALPHX (CiLOWER | CiUNDER | CiUPPER)
1467 /* \x01‥\x7F 7-bit ASCII except NUL */
1468 #define C_ASCII (CiALIAS | CiANGLE | CiBRACK | CiCNTRL | CiCOLON | CiCR | CiCURLY | CiDIGIT | CiEQUAL | CiGRAVE | CiHASH | CiLOWER | CiMINUS | CiNL | CiOCTAL | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSP | CiSPX | CiSS | CiTAB | CiUNDER | CiUPPER)
1469 /* \x09\x20 tab and space */
1470 #define C_BLANK (CiSP | CiTAB)
1471 /* \x09\x20"' separator for completion */
1472 #define C_CFS (CiQC | CiSP | CiTAB)
1473 /* \x00‥\x1F\x7F POSIX control characters */
1474 #define C_CNTRL (CiCNTRL | CiCR | CiNL | CiNUL | CiSPX | CiTAB)
1475 /* 0‥9 decimal digits */
1476 #define C_DIGIT (CiDIGIT | CiOCTAL)
1477 /* &();`| editor x_locate_word() command */
1478 #define C_EDCMD (CiGRAVE | CiQCL)
1479 /* \x09\x0A\x20"&'():;<=>`| editor non-word characters */
1480 #define C_EDNWC (CiANGLE | CiCOLON | CiEQUAL | CiGRAVE | CiNL | CiQC | CiQCL | CiSP | CiTAB)
1481 /* "#$&'()*:;<=>?[\\`{|} editor quotes for tab completion */
1482 #define C_EDQ (CiANGLE | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiQC | CiQCL | CiQCX | CiQUEST | CiSS)
1483 /* !‥~ POSIX graphical (alphanumerical plus punctuation) */
1484 #define C_GRAPH (C_PUNCT | CiDIGIT | CiLOWER | CiOCTAL | CiUPPER)
1485 /* A‥Fa‥f hex letter */
1486 #define C_HEXLT CiHEXLT
1487 /* \x00 + $IFS IFS whitespace, IFS non-whitespace, NUL */
1488 #define C_IFS (CiIFS | CiNUL)
1489 /* \x09\x0A\x20 IFS whitespace */
1490 #define C_IFSWS (CiNL | CiSP | CiTAB)
1491 /* \x09\x0A\x20&();<>| (for the lexer) */
1492 #define C_LEX1 (CiANGLE | CiNL | CiQCL | CiSP | CiTAB)
1493 /* a‥z lowercase letters */
1494 #define C_LOWER CiLOWER
1495 /* not alnux or dollar separator for motion */
1496 #define C_MFS (CiALIAS | CiANGLE | CiBRACK | CiCNTRL | CiCOLON | CiCR | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiMINUS | CiNL | CiNUL | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSP | CiSPX | CiTAB)
1497 /* 0‥7 octal digit */
1498 #define C_OCTAL CiOCTAL
1499 /* !*+?@ pattern magical operator, except space */
1500 #define C_PATMO (CiPLUS | CiQUEST | CiVAR1)
1501 /* \x20‥~ POSIX printable characters (graph plus space) */
1502 #define C_PRINT (C_GRAPH | CiSP)
1503 /* !"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ POSIX punctuation */
1504 #define C_PUNCT (CiALIAS | CiANGLE | CiBRACK | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiMINUS | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSS | CiUNDER)
1505 /* \x09\x0A"#$&'()*;<=>?[\\]`| characters requiring quoting, minus space */
1506 #define C_QUOTE (CiANGLE | CiBRACK | CiEQUAL | CiGRAVE | CiHASH | CiNL | CiQC | CiQCL | CiQCX | CiQUEST | CiSS | CiTAB)
1507 /* 0‥9A‥Fa‥f hexadecimal digit */
1508 #define C_SEDEC (CiDIGIT | CiHEXLT | CiOCTAL)
1509 /* \x09‥\x0D\x20 POSIX space class */
1510 #define C_SPACE (CiCR | CiNL | CiSP | CiSPX | CiTAB)
1511 /* +-=? substitution operations with word */
1512 #define C_SUB1 (CiEQUAL | CiMINUS | CiPLUS | CiQUEST)
1513 /* #% substitution operations with pattern */
1514 #define C_SUB2 (CiHASH | CiPERCT)
1515 /* A‥Z uppercase letters */
1516 #define C_UPPER CiUPPER
1517 /* !#$*-?@ substitution parameters, other than positional */
1518 #define C_VAR1 (CiHASH | CiMINUS | CiQUEST | CiSS | CiVAR1)
1519
1520 /* individual chars you might like */
1521 #define C_ANGLE CiANGLE /* <> angle brackets */
1522 #define C_COLON CiCOLON /* : colon */
1523 #define C_CR CiCR /* \x0D ASCII carriage return */
1524 #define C_DOLAR CiSS /* $ dollar sign */
1525 #define C_EQUAL CiEQUAL /* = equals sign */
1526 #define C_GRAVE CiGRAVE /* ` accent gravis */
1527 #define C_HASH CiHASH /* # hash sign */
1528 #define C_LF CiNL /* \x0A ASCII line feed */
1529 #define C_MINUS CiMINUS /* - hyphen-minus */
1530 #ifdef MKSH_WITH_TEXTMODE
1531 #define C_NL (CiNL | CiCR) /* CR or LF under OS/2 TEXTMODE */
1532 #else
1533 #define C_NL CiNL /* LF only like under Unix */
1534 #endif
1535 #define C_NUL CiNUL /* \x00 ASCII NUL */
1536 #define C_PLUS CiPLUS /* + plus sign */
1537 #define C_QC CiQC /* "' quote characters */
1538 #define C_QUEST CiQUEST /* ? question mark */
1539 #define C_SPC CiSP /* \x20 ASCII space */
1540 #define C_TAB CiTAB /* \x09 ASCII horizontal tabulator */
1541 #define C_UNDER CiUNDER /* _ underscore */
1542
1543 /* identity transform of octet */
1544 #if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
1545 !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
1546 extern unsigned int eek_ord;
1547 #define ORD(c) ((size_t)(c) > 0xFF ? eek_ord : \
1548 ((unsigned int)(unsigned char)(c)))
1549 #define ord(c) __builtin_choose_expr( \
1550 __builtin_types_compatible_p(__typeof__(c), char) || \
1551 __builtin_types_compatible_p(__typeof__(c), unsigned char), \
1552 ((unsigned int)(unsigned char)(c)), ({ \
1553 size_t ord_c = (c); \
1554 \
1555 if (ord_c > (size_t)0xFFU) \
1556 internal_errorf("%s:%d:ord(%zX)", \
1557 __FILE__, __LINE__, ord_c); \
1558 ((unsigned int)(unsigned char)(ord_c)); \
1559 }))
1560 #else
1561 #define ord(c) ((unsigned int)(unsigned char)(c))
1562 #define ORD(c) ord(c) /* may evaluate arguments twice */
1563 #endif
1564 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
1565 EXTERN unsigned short ebcdic_map[256];
1566 EXTERN unsigned char ebcdic_rtt_toascii[256];
1567 EXTERN unsigned char ebcdic_rtt_fromascii[256];
1568 extern void ebcdic_init(void);
1569 /* one-way to-ascii-or-high conversion, for POSIX locale ordering */
1570 #define asciibetical(c) ((unsigned int)ebcdic_map[(unsigned char)(c)])
1571 /* two-way round-trip conversion, for general use */
1572 #define rtt2asc(c) ebcdic_rtt_toascii[(unsigned char)(c)]
1573 #define asc2rtt(c) ebcdic_rtt_fromascii[(unsigned char)(c)]
1574 /* case-independent char comparison */
1575 #define ksh_eq(c,u,l) (ord(c) == ord(u) || ord(c) == ord(l))
1576 #else
1577 #define asciibetical(c) ord(c)
1578 #define rtt2asc(c) ((unsigned char)(c))
1579 #define asc2rtt(c) ((unsigned char)(c))
1580 #define ksh_eq(c,u,l) ((ord(c) | 0x20) == ord(l))
1581 #endif
1582 /* control character foo */
1583 #ifdef MKSH_EBCDIC
1584 #define ksh_isctrl(c) (ord(c) < 0x40 || ord(c) == 0xFF)
1585 #else
1586 #define ksh_isctrl(c) ((ord(c) & 0x7F) < 0x20 || ord(c) == 0x7F)
1587 #endif
1588 /* new fast character classes */
1589 #define ctype(c,t) tobool(ksh_ctypes[ord(c)] & (t))
1590 #define cinttype(c,t) ((c) >= 0 && (c) <= 0xFF ? \
1591 tobool(ksh_ctypes[(unsigned char)(c)] & (t)) : false)
1592 /* helper functions */
1593 #define ksh_isdash(s) tobool(ord((s)[0]) == '-' && ord((s)[1]) == '\0')
1594 /* invariant distance even in EBCDIC */
1595 #define ksh_tolower(c) (ctype(c, C_UPPER) ? (c) - 'A' + 'a' : (c))
1596 #define ksh_toupper(c) (ctype(c, C_LOWER) ? (c) - 'a' + 'A' : (c))
1597 /* strictly speaking rtt2asc() here, but this works even in EBCDIC */
1598 #define ksh_numdig(c) (ord(c) - ORD('0'))
1599 #define ksh_numuc(c) (rtt2asc(c) - rtt2asc('A'))
1600 #define ksh_numlc(c) (rtt2asc(c) - rtt2asc('a'))
1601 #define ksh_toctrl(c) asc2rtt(ord(c) == ORD('?') ? 0x7F : rtt2asc(c) & 0x9F)
1602 #define ksh_unctrl(c) asc2rtt(rtt2asc(c) ^ 0x40U)
1603
1604 #ifdef MKSH_SMALL
1605 #define SMALLP(x) /* nothing */
1606 #else
1607 #define SMALLP(x) , x
1608 #endif
1609
1610 /* Argument parsing for built-in commands and getopts command */
1611
1612 /* Values for Getopt.flags */
1613 #define GF_ERROR BIT(0) /* call errorf() if there is an error */
1614 #define GF_PLUSOPT BIT(1) /* allow +c as an option */
1615 #define GF_NONAME BIT(2) /* don't print argv[0] in errors */
1616
1617 /* Values for Getopt.info */
1618 #define GI_MINUS BIT(0) /* an option started with -... */
1619 #define GI_PLUS BIT(1) /* an option started with +... */
1620 #define GI_MINUSMINUS BIT(2) /* arguments were ended with -- */
1621
1622 /* in case some OS defines these */
1623 #undef optarg
1624 #undef optind
1625
1626 typedef struct {
1627 const char *optarg;
1628 int optind;
1629 int uoptind; /* what user sees in $OPTIND */
1630 int flags; /* see GF_* */
1631 int info; /* see GI_* */
1632 unsigned int p; /* 0 or index into argv[optind - 1] */
1633 char buf[2]; /* for bad option OPTARG value */
1634 } Getopt;
1635
1636 EXTERN Getopt builtin_opt; /* for shell builtin commands */
1637 EXTERN Getopt user_opt; /* parsing state for getopts builtin command */
1638
1639 /* This for co-processes */
1640
1641 /* something that won't (realisticly) wrap */
1642 typedef int Coproc_id;
1643
1644 struct coproc {
1645 void *job; /* 0 or job of co-process using input pipe */
1646 int read; /* pipe from co-process's stdout */
1647 int readw; /* other side of read (saved temporarily) */
1648 int write; /* pipe to co-process's stdin */
1649 int njobs; /* number of live jobs using output pipe */
1650 Coproc_id id; /* id of current output pipe */
1651 };
1652 EXTERN struct coproc coproc;
1653
1654 #ifndef MKSH_NOPROSPECTOFWORK
1655 /* used in jobs.c and by coprocess stuff in exec.c and select() calls */
1656 EXTERN sigset_t sm_default, sm_sigchld;
1657 #endif
1658
1659 /* name of called builtin function (used by error functions) */
1660 EXTERN const char *builtin_argv0;
1661 /* is called builtin a POSIX special builtin? (error functions only) */
1662 EXTERN bool builtin_spec;
1663
1664 /* current working directory */
1665 EXTERN char *current_wd;
1666
1667 /* input line size */
1668 #ifdef MKSH_SMALL
1669 #define LINE (4096 - ALLOC_OVERHEAD)
1670 #else
1671 #define LINE (16384 - ALLOC_OVERHEAD)
1672 #endif
1673 /* columns and lines of the tty */
1674 EXTERN mksh_ari_t x_cols E_INIT(80);
1675 EXTERN mksh_ari_t x_lins E_INIT(24);
1676
1677
1678 /* Determine the location of the system (common) profile */
1679
1680 #ifndef MKSH_DEFAULT_PROFILEDIR
1681 #define MKSH_DEFAULT_PROFILEDIR MKSH_UNIXROOT "/etc"
1682 #endif
1683
1684 #define MKSH_SYSTEM_PROFILE MKSH_DEFAULT_PROFILEDIR "/profile"
1685 #define MKSH_SUID_PROFILE MKSH_DEFAULT_PROFILEDIR "/suid_profile"
1686
1687
1688 /* Used by v_evaluate() and setstr() to control action when error occurs */
1689 #define KSH_UNWIND_ERROR 0 /* unwind the stack (kshlongjmp) */
1690 #define KSH_RETURN_ERROR 1 /* return 1/0 for success/failure */
1691
1692 /*
1693 * Shell file I/O routines
1694 */
1695
1696 #define SHF_BSIZE 512
1697
1698 #define shf_fileno(shf) ((shf)->fd)
1699 #define shf_setfileno(shf,nfd) ((shf)->fd = (nfd))
1700 #define shf_getc_i(shf) ((shf)->rnleft > 0 ? \
1701 (shf)->rnleft--, (int)ord(*(shf)->rp++) : \
1702 shf_getchar(shf))
1703 #define shf_putc_i(c,shf) ((shf)->wnleft == 0 ? \
1704 shf_putchar((uint8_t)(c), (shf)) : \
1705 ((shf)->wnleft--, *(shf)->wp++ = (c)))
1706 #define shf_eof(shf) ((shf)->flags & SHF_EOF)
1707 #define shf_error(shf) ((shf)->flags & SHF_ERROR)
1708 #define shf_errno(shf) ((shf)->errnosv)
1709 #define shf_clearerr(shf) ((shf)->flags &= ~(SHF_EOF | SHF_ERROR))
1710
1711 /* Flags passed to shf_*open() */
1712 #define SHF_RD 0x0001
1713 #define SHF_WR 0x0002
1714 #define SHF_RDWR (SHF_RD | SHF_WR)
1715 #define SHF_ACCMODE 0x0003 /* mask */
1716 #define SHF_GETFL 0x0004 /* use fcntl() to figure RD/WR flags */
1717 #define SHF_UNBUF 0x0008 /* unbuffered I/O */
1718 #define SHF_CLEXEC 0x0010 /* set close on exec flag */
1719 #define SHF_MAPHI 0x0020 /* make fd > FDBASE (and close orig)
1720 * (shf_open() only) */
1721 #define SHF_DYNAMIC 0x0040 /* string: increase buffer as needed */
1722 #define SHF_INTERRUPT 0x0080 /* EINTR in read/write causes error */
1723 /* Flags used internally */
1724 #define SHF_STRING 0x0100 /* a string, not a file */
1725 #define SHF_ALLOCS 0x0200 /* shf and shf->buf were alloc()ed */
1726 #define SHF_ALLOCB 0x0400 /* shf->buf was alloc()ed */
1727 #define SHF_ERROR 0x0800 /* read()/write() error */
1728 #define SHF_EOF 0x1000 /* read eof (sticky) */
1729 #define SHF_READING 0x2000 /* currently reading: rnleft,rp valid */
1730 #define SHF_WRITING 0x4000 /* currently writing: wnleft,wp valid */
1731
1732
1733 struct shf {
1734 Area *areap; /* area shf/buf were allocated in */
1735 unsigned char *rp; /* read: current position in buffer */
1736 unsigned char *wp; /* write: current position in buffer */
1737 unsigned char *buf; /* buffer */
1738 ssize_t bsize; /* actual size of buf */
1739 ssize_t rbsize; /* size of buffer (1 if SHF_UNBUF) */
1740 ssize_t rnleft; /* read: how much data left in buffer */
1741 ssize_t wbsize; /* size of buffer (0 if SHF_UNBUF) */
1742 ssize_t wnleft; /* write: how much space left in buffer */
1743 int flags; /* see SHF_* */
1744 int fd; /* file descriptor */
1745 int errnosv; /* saved value of errno after error */
1746 };
1747
1748 extern struct shf shf_iob[];
1749
1750 struct table {
1751 Area *areap; /* area to allocate entries */
1752 struct tbl **tbls; /* hashed table items */
1753 size_t nfree; /* free table entries */
1754 uint8_t tshift; /* table size (2^tshift) */
1755 };
1756
1757 /* table item */
1758 struct tbl {
1759 /* Area to allocate from */
1760 Area *areap;
1761 /* value */
1762 union {
1763 char *s; /* string */
1764 mksh_ari_t i; /* integer */
1765 mksh_uari_t u; /* unsigned integer */
1766 int (*f)(const char **); /* built-in command */
1767 struct op *t; /* "function" tree */
1768 } val;
1769 union {
1770 struct tbl *array; /* array values */
1771 const char *fpath; /* temporary path to undef function */
1772 } u;
1773 union {
1774 int field; /* field with for -L/-R/-Z */
1775 int errnov; /* CEXEC/CTALIAS */
1776 } u2;
1777 union {
1778 uint32_t hval; /* hash(name) */
1779 uint32_t index; /* index for an array */
1780 } ua;
1781 /*
1782 * command type (see below), base (if INTEGER),
1783 * offset from val.s of value (if EXPORT)
1784 */
1785 int type;
1786 /* flags (see below) */
1787 uint32_t flag;
1788
1789 /* actually longer: name (variable length) */
1790 char name[4];
1791 };
1792
1793 EXTERN struct tbl *vtemp;
1794 /* set by isglobal(), global() and local() */
1795 EXTERN bool last_lookup_was_array;
1796
1797 /* common flag bits */
1798 #define ALLOC BIT(0) /* val.s has been allocated */
1799 #define DEFINED BIT(1) /* is defined in block */
1800 #define ISSET BIT(2) /* has value, vp->val.[si] */
1801 #define EXPORT BIT(3) /* exported variable/function */
1802 #define TRACE BIT(4) /* var: user flagged, func: execution tracing */
1803 /* (start non-common flags at 8) */
1804 /* flag bits used for variables */
1805 #define SPECIAL BIT(8) /* PATH, IFS, SECONDS, etc */
1806 #define INTEGER BIT(9) /* val.i contains integer value */
1807 #define RDONLY BIT(10) /* read-only variable */
1808 #define LOCAL BIT(11) /* for local typeset() */
1809 #define ARRAY BIT(13) /* array */
1810 #define LJUST BIT(14) /* left justify */
1811 #define RJUST BIT(15) /* right justify */
1812 #define ZEROFIL BIT(16) /* 0 filled if RJUSTIFY, strip 0s if LJUSTIFY */
1813 #define LCASEV BIT(17) /* convert to lower case */
1814 #define UCASEV_AL BIT(18) /* convert to upper case / autoload function */
1815 #define INT_U BIT(19) /* unsigned integer */
1816 #define INT_L BIT(20) /* long integer (no-op but used as magic) */
1817 #define IMPORT BIT(21) /* flag to typeset(): no arrays, must have = */
1818 #define LOCAL_COPY BIT(22) /* with LOCAL - copy attrs from existing var */
1819 #define EXPRINEVAL BIT(23) /* contents currently being evaluated */
1820 #define EXPRLVALUE BIT(24) /* useable as lvalue (temp flag) */
1821 #define AINDEX BIT(25) /* array index >0 = ua.index filled in */
1822 #define ASSOC BIT(26) /* ARRAY ? associative : reference */
1823 /* flag bits used for taliases/builtins/aliases/keywords/functions */
1824 #define KEEPASN BIT(8) /* keep command assignments (eg, var=x cmd) */
1825 #define FINUSE BIT(9) /* function being executed */
1826 #define FDELETE BIT(10) /* function deleted while it was executing */
1827 #define FKSH BIT(11) /* function defined with function x (vs x()) */
1828 #define SPEC_BI BIT(12) /* a POSIX special builtin */
1829 #define LOWER_BI BIT(13) /* (with LOW_BI) override even w/o flags */
1830 #define LOW_BI BIT(14) /* external utility overrides built-in one */
1831 #define DECL_UTIL BIT(15) /* is declaration utility */
1832 #define DECL_FWDR BIT(16) /* is declaration utility forwarder */
1833 #define NEXTLOC_BI BIT(17) /* needs BF_RESETSPEC on e->loc */
1834
1835 /*
1836 * Attributes that can be set by the user (used to decide if an unset
1837 * param should be repoted by set/typeset). Does not include ARRAY or
1838 * LOCAL.
1839 */
1840 #define USERATTRIB (EXPORT | INTEGER | RDONLY | LJUST | RJUST | ZEROFIL | \
1841 LCASEV | UCASEV_AL | INT_U | INT_L)
1842
1843 #define arrayindex(vp) ((unsigned long)((vp)->flag & AINDEX ? \
1844 (vp)->ua.index : 0))
1845
1846 enum namerefflag {
1847 SRF_NOP,
1848 SRF_ENABLE,
1849 SRF_DISABLE
1850 };
1851
1852 /* command types */
1853 #define CNONE 0 /* undefined */
1854 #define CSHELL 1 /* built-in */
1855 #define CFUNC 2 /* function */
1856 #define CEXEC 4 /* executable command */
1857 #define CALIAS 5 /* alias */
1858 #define CKEYWD 6 /* keyword */
1859 #define CTALIAS 7 /* tracked alias */
1860
1861 /* Flags for findcom()/comexec() */
1862 #define FC_SPECBI BIT(0) /* special builtin */
1863 #define FC_FUNC BIT(1) /* function */
1864 #define FC_NORMBI BIT(2) /* not special builtin */
1865 #define FC_BI (FC_SPECBI | FC_NORMBI)
1866 #define FC_PATH BIT(3) /* do path search */
1867 #define FC_DEFPATH BIT(4) /* use default path in path search */
1868 #define FC_WHENCE BIT(5) /* for use by command and whence */
1869
1870 #define AF_ARGV_ALLOC 0x1 /* argv[] array allocated */
1871 #define AF_ARGS_ALLOCED 0x2 /* argument strings allocated */
1872 #define AI_ARGV(a,i) ((i) == 0 ? (a).argv[0] : (a).argv[(i) - (a).skip])
1873 #define AI_ARGC(a) ((a).ai_argc - (a).skip)
1874
1875 /* Argument info. Used for $#, $* for shell, functions, includes, etc. */
1876 struct arg_info {
1877 const char **argv;
1878 int flags; /* AF_* */
1879 int ai_argc;
1880 int skip; /* first arg is argv[0], second is argv[1 + skip] */
1881 };
1882
1883 /*
1884 * activation record for function blocks
1885 */
1886 struct block {
1887 Area area; /* area to allocate things */
1888 const char **argv;
1889 char *error; /* error handler */
1890 char *exit; /* exit handler */
1891 struct block *next; /* enclosing block */
1892 struct table vars; /* local variables */
1893 struct table funs; /* local functions */
1894 Getopt getopts_state;
1895 int argc;
1896 int flags; /* see BF_* */
1897 };
1898
1899 /* Values for struct block.flags */
1900 #define BF_DOGETOPTS BIT(0) /* save/restore getopts state */
1901 #define BF_STOPENV BIT(1) /* do not export further */
1902 /* BF_RESETSPEC and NEXTLOC_BI must be numerically identical! */
1903 #define BF_RESETSPEC BIT(17) /* use ->next for set and shift */
1904
1905 /*
1906 * Used by ktwalk() and ktnext() routines.
1907 */
1908 struct tstate {
1909 struct tbl **next;
1910 ssize_t left;
1911 };
1912
1913 EXTERN struct table taliases; /* tracked aliases */
1914 EXTERN struct table builtins; /* built-in commands */
1915 EXTERN struct table aliases; /* aliases */
1916 EXTERN struct table keywords; /* keywords */
1917 #ifndef MKSH_NOPWNAM
1918 EXTERN struct table homedirs; /* homedir() cache */
1919 #endif
1920
1921 struct builtin {
1922 const char *name;
1923 int (*func)(const char **);
1924 };
1925
1926 extern const struct builtin mkshbuiltins[];
1927
1928 /* values for set_prompt() */
1929 #define PS1 0 /* command */
1930 #define PS2 1 /* command continuation */
1931
1932 EXTERN char *path; /* copy of either PATH or def_path */
1933 EXTERN const char *def_path; /* path to use if PATH not set */
1934 EXTERN char *tmpdir; /* TMPDIR value */
1935 EXTERN const char *prompt;
1936 EXTERN uint8_t cur_prompt; /* PS1 or PS2 */
1937 EXTERN int current_lineno; /* LINENO value */
1938
1939 /*
1940 * Description of a command or an operation on commands.
1941 */
1942 struct op {
1943 const char **args; /* arguments to a command */
1944 char **vars; /* variable assignments */
1945 struct ioword **ioact; /* IO actions (eg, < > >>) */
1946 struct op *left, *right; /* descendents */
1947 char *str; /* word for case; identifier for for,
1948 * select, and functions;
1949 * path to execute for TEXEC;
1950 * time hook for TCOM.
1951 */
1952 int lineno; /* TCOM/TFUNC: LINENO for this */
1953 short type; /* operation type, see below */
1954 /* WARNING: newtp(), tcopy() use evalflags = 0 to clear union */
1955 union {
1956 /* TCOM: arg expansion eval() flags */
1957 short evalflags;
1958 /* TFUNC: function x (vs x()) */
1959 short ksh_func;
1960 /* TPAT: termination character */
1961 char charflag;
1962 } u;
1963 };
1964
1965 /* Tree.type values */
1966 #define TEOF 0
1967 #define TCOM 1 /* command */
1968 #define TPAREN 2 /* (c-list) */
1969 #define TPIPE 3 /* a | b */
1970 #define TLIST 4 /* a ; b */
1971 #define TOR 5 /* || */
1972 #define TAND 6 /* && */
1973 #define TBANG 7 /* ! */
1974 #define TDBRACKET 8 /* [[ .. ]] */
1975 #define TFOR 9
1976 #define TSELECT 10
1977 #define TCASE 11
1978 #define TIF 12
1979 #define TWHILE 13
1980 #define TUNTIL 14
1981 #define TELIF 15
1982 #define TPAT 16 /* pattern in case */
1983 #define TBRACE 17 /* {c-list} */
1984 #define TASYNC 18 /* c & */
1985 #define TFUNCT 19 /* function name { command; } */
1986 #define TTIME 20 /* time pipeline */
1987 #define TEXEC 21 /* fork/exec eval'd TCOM */
1988 #define TCOPROC 22 /* coprocess |& */
1989
1990 /*
1991 * prefix codes for words in command tree
1992 */
1993 #define EOS 0 /* end of string */
1994 #define CHAR 1 /* unquoted character */
1995 #define QCHAR 2 /* quoted character */
1996 #define COMSUB 3 /* $() substitution (0 terminated) */
1997 #define EXPRSUB 4 /* $(()) substitution (0 terminated) */
1998 #define OQUOTE 5 /* opening " or ' */
1999 #define CQUOTE 6 /* closing " or ' */
2000 #define OSUBST 7 /* opening ${ subst (followed by { or X) */
2001 #define CSUBST 8 /* closing } of above (followed by } or X) */
2002 #define OPAT 9 /* open pattern: *(, @(, etc. */
2003 #define SPAT 10 /* separate pattern: | */
2004 #define CPAT 11 /* close pattern: ) */
2005 #define ADELIM 12 /* arbitrary delimiter: ${foo:2:3} ${foo/bar/baz} */
2006 #define FUNSUB 14 /* ${ foo;} substitution (NUL terminated) */
2007 #define VALSUB 15 /* ${|foo;} substitution (NUL terminated) */
2008 #define COMASUB 16 /* `…` substitution (COMSUB but expand aliases) */
2009 #define FUNASUB 17 /* function substitution but expand aliases */
2010
2011 /*
2012 * IO redirection
2013 */
2014 struct ioword {
2015 char *ioname; /* filename (unused if heredoc) */
2016 char *delim; /* delimiter for <<, <<- */
2017 char *heredoc; /* content of heredoc */
2018 unsigned short ioflag; /* action (below) */
2019 short unit; /* unit (fd) affected */
2020 };
2021
2022 /* ioword.flag - type of redirection */
2023 #define IOTYPE 0xF /* type: bits 0:3 */
2024 #define IOREAD 0x1 /* < */
2025 #define IOWRITE 0x2 /* > */
2026 #define IORDWR 0x3 /* <>: todo */
2027 #define IOHERE 0x4 /* << (here file) */
2028 #define IOCAT 0x5 /* >> */
2029 #define IODUP 0x6 /* <&/>& */
2030 #define IOEVAL BIT(4) /* expand in << */
2031 #define IOSKIP BIT(5) /* <<-, skip ^\t* */
2032 #define IOCLOB BIT(6) /* >|, override -o noclobber */
2033 #define IORDUP BIT(7) /* x<&y (as opposed to x>&y) */
2034 #define IODUPSELF BIT(8) /* x>&x (as opposed to x>&y) */
2035 #define IONAMEXP BIT(9) /* name has been expanded */
2036 #define IOBASH BIT(10) /* &> etc. */
2037 #define IOHERESTR BIT(11) /* <<< (here string) */
2038 #define IONDELIM BIT(12) /* null delimiter (<<) */
2039
2040 /* execute/exchild flags */
2041 #define XEXEC BIT(0) /* execute without forking */
2042 #define XFORK BIT(1) /* fork before executing */
2043 #define XBGND BIT(2) /* command & */
2044 #define XPIPEI BIT(3) /* input is pipe */
2045 #define XPIPEO BIT(4) /* output is pipe */
2046 #define XXCOM BIT(5) /* `...` command */
2047 #define XPCLOSE BIT(6) /* exchild: close close_fd in parent */
2048 #define XCCLOSE BIT(7) /* exchild: close close_fd in child */
2049 #define XERROK BIT(8) /* non-zero exit ok (for set -e) */
2050 #define XCOPROC BIT(9) /* starting a co-process */
2051 #define XTIME BIT(10) /* timing TCOM command */
2052 #define XPIPEST BIT(11) /* want PIPESTATUS */
2053
2054 /*
2055 * flags to control expansion of words (assumed by t->evalflags to fit
2056 * in a short)
2057 */
2058 #define DOBLANK BIT(0) /* perform blank interpretation */
2059 #define DOGLOB BIT(1) /* expand [?* */
2060 #define DOPAT BIT(2) /* quote *?[ */
2061 #define DOTILDE BIT(3) /* normal ~ expansion (first char) */
2062 #define DONTRUNCOMMAND BIT(4) /* do not run $(command) things */
2063 #define DOASNTILDE BIT(5) /* assignment ~ expansion (after =, :) */
2064 #define DOBRACE BIT(6) /* used by expand(): do brace expansion */
2065 #define DOMAGIC BIT(7) /* used by expand(): string contains MAGIC */
2066 #define DOTEMP BIT(8) /* dito: in word part of ${..[%#=?]..} */
2067 #define DOVACHECK BIT(9) /* var assign check (for typeset, set, etc) */
2068 #define DOMARKDIRS BIT(10) /* force markdirs behaviour */
2069 #define DOTCOMEXEC BIT(11) /* not an eval flag, used by sh -c hack */
2070 #define DOSCALAR BIT(12) /* change field handling to non-list context */
2071 #define DOHEREDOC BIT(13) /* change scalar handling to heredoc body */
2072 #define DOHERESTR BIT(14) /* append a newline char */
2073 #define DODBMAGIC BIT(15) /* add magic to expansions for [[ x = $y ]] */
2074
2075 #define X_EXTRA 20 /* this many extra bytes in X string */
2076 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2077 #define X_WASTE 15 /* allowed extra bytes to avoid shrinking, */
2078 #else
2079 #define X_WASTE 255 /* … must be 2ⁿ-1 */
2080 #endif
2081
2082 typedef struct XString {
2083 /* beginning of string */
2084 char *beg;
2085 /* length of allocated area, minus safety margin */
2086 size_t len;
2087 /* end of string */
2088 char *end;
2089 /* memory area used */
2090 Area *areap;
2091 } XString;
2092
2093 /* initialise expandable string */
2094 #define XinitN(xs,length,area) do { \
2095 (xs).len = (length); \
2096 (xs).areap = (area); \
2097 (xs).beg = alloc((xs).len + X_EXTRA, (xs).areap); \
2098 (xs).end = (xs).beg + (xs).len; \
2099 } while (/* CONSTCOND */ 0)
2100 #define Xinit(xs,xp,length,area) do { \
2101 XinitN((xs), (length), (area)); \
2102 (xp) = (xs).beg; \
2103 } while (/* CONSTCOND */ 0)
2104
2105 /* stuff char into string */
2106 #define Xput(xs,xp,c) (*xp++ = (c))
2107
2108 /* check if there are at least n bytes left */
2109 #define XcheckN(xs,xp,n) do { \
2110 ssize_t more = ((xp) + (n)) - (xs).end; \
2111 if (more > 0) \
2112 (xp) = Xcheck_grow(&(xs), (xp), (size_t)more); \
2113 } while (/* CONSTCOND */ 0)
2114
2115 /* check for overflow, expand string */
2116 #define Xcheck(xs,xp) XcheckN((xs), (xp), 1)
2117
2118 /* free string */
2119 #define Xfree(xs,xp) afree((xs).beg, (xs).areap)
2120
2121 /* close, return string */
2122 #define Xclose(xs,xp) aresize((xs).beg, (xp) - (xs).beg, (xs).areap)
2123
2124 /* beginning of string */
2125 #define Xstring(xs,xp) ((xs).beg)
2126
2127 #define Xnleft(xs,xp) ((xs).end - (xp)) /* may be less than 0 */
2128 #define Xlength(xs,xp) ((xp) - (xs).beg)
2129 #define Xsize(xs,xp) ((xs).end - (xs).beg)
2130 #define Xsavepos(xs,xp) ((xp) - (xs).beg)
2131 #define Xrestpos(xs,xp,n) ((xs).beg + (n))
2132
2133 char *Xcheck_grow(XString *, const char *, size_t);
2134
2135 /*
2136 * expandable vector of generic pointers
2137 */
2138
2139 typedef struct {
2140 /* beginning of allocated area */
2141 void **beg;
2142 /* currently used number of entries */
2143 size_t len;
2144 /* allocated number of entries */
2145 size_t siz;
2146 } XPtrV;
2147
2148 #define XPinit(x,n) do { \
2149 (x).siz = (n); \
2150 (x).len = 0; \
2151 (x).beg = alloc2((x).siz, sizeof(void *), ATEMP); \
2152 } while (/* CONSTCOND */ 0) \
2153
2154 #define XPput(x,p) do { \
2155 if ((x).len == (x).siz) { \
2156 (x).beg = aresize2((x).beg, (x).siz, \
2157 2 * sizeof(void *), ATEMP); \
2158 (x).siz <<= 1; \
2159 } \
2160 (x).beg[(x).len++] = (p); \
2161 } while (/* CONSTCOND */ 0)
2162
2163 #define XPptrv(x) ((x).beg)
2164 #define XPsize(x) ((x).len)
2165 #define XPclose(x) aresize2((x).beg, XPsize(x), sizeof(void *), ATEMP)
2166 #define XPfree(x) afree((x).beg, ATEMP)
2167
2168 /* for print_columns */
2169
2170 struct columnise_opts {
2171 struct shf *shf;
2172 char linesep;
2173 bool do_last;
2174 bool prefcol;
2175 };
2176
2177 /*
2178 * Lexer internals
2179 */
2180
2181 typedef struct source Source;
2182 struct source {
2183 /* input buffer */
2184 XString xs;
2185 /* memory area, also checked in reclaim() */
2186 Area *areap;
2187 /* stacked source */
2188 Source *next;
2189 /* input pointer */
2190 const char *str;
2191 /* start of current buffer */
2192 const char *start;
2193 /* input file name */
2194 const char *file;
2195 /* extra data */
2196 union {
2197 /* string[] */
2198 const char **strv;
2199 /* shell file */
2200 struct shf *shf;
2201 /* alias (SF_HASALIAS) */
2202 struct tbl *tblp;
2203 /* (also for SREREAD) */
2204 char *freeme;
2205 } u;
2206 /* flags */
2207 int flags;
2208 /* input type */
2209 int type;
2210 /* line number */
2211 int line;
2212 /* line the error occurred on (0 if not set) */
2213 int errline;
2214 /* buffer for ungetsc() (SREREAD) and alias (SALIAS) */
2215 char ugbuf[2];
2216 };
2217
2218 /* Source.type values */
2219 #define SEOF 0 /* input EOF */
2220 #define SFILE 1 /* file input */
2221 #define SSTDIN 2 /* read stdin */
2222 #define SSTRING 3 /* string */
2223 #define SWSTR 4 /* string without \n */
2224 #define SWORDS 5 /* string[] */
2225 #define SWORDSEP 6 /* string[] separator */
2226 #define SALIAS 7 /* alias expansion */
2227 #define SREREAD 8 /* read ahead to be re-scanned */
2228 #define SSTRINGCMDLINE 9 /* string from "mksh -c ..." */
2229
2230 /* Source.flags values */
2231 #define SF_ECHO BIT(0) /* echo input to shlout */
2232 #define SF_ALIAS BIT(1) /* faking space at end of alias */
2233 #define SF_ALIASEND BIT(2) /* faking space at end of alias */
2234 #define SF_TTY BIT(3) /* type == SSTDIN & it is a tty */
2235 #define SF_HASALIAS BIT(4) /* u.tblp valid (SALIAS, SEOF) */
2236 #define SF_MAYEXEC BIT(5) /* special sh -c optimisation hack */
2237
2238 typedef union {
2239 int i;
2240 char *cp;
2241 char **wp;
2242 struct op *o;
2243 struct ioword *iop;
2244 } YYSTYPE;
2245
2246 /* If something is added here, add it to tokentab[] in syn.c as well */
2247 #define LWORD 256
2248 #define LOGAND 257 /* && */
2249 #define LOGOR 258 /* || */
2250 #define BREAK 259 /* ;; */
2251 #define IF 260
2252 #define THEN 261
2253 #define ELSE 262
2254 #define ELIF 263
2255 #define FI 264
2256 #define CASE 265
2257 #define ESAC 266
2258 #define FOR 267
2259 #define SELECT 268
2260 #define WHILE 269
2261 #define UNTIL 270
2262 #define DO 271
2263 #define DONE 272
2264 #define IN 273
2265 #define FUNCTION 274
2266 #define TIME 275
2267 #define REDIR 276
2268 #define MDPAREN 277 /* (( )) */
2269 #define BANG 278 /* ! */
2270 #define DBRACKET 279 /* [[ .. ]] */
2271 #define COPROC 280 /* |& */
2272 #define BRKEV 281 /* ;| */
2273 #define BRKFT 282 /* ;& */
2274 #define YYERRCODE 300
2275
2276 /* flags to yylex */
2277 #define CONTIN BIT(0) /* skip new lines to complete command */
2278 #define ONEWORD BIT(1) /* single word for substitute() */
2279 #define ALIAS BIT(2) /* recognise alias */
2280 #define KEYWORD BIT(3) /* recognise keywords */
2281 #define LETEXPR BIT(4) /* get expression inside (( )) */
2282 #define CMDASN BIT(5) /* parse x[1 & 2] as one word, for typeset */
2283 #define HEREDOC BIT(6) /* parsing a here document body */
2284 #define ESACONLY BIT(7) /* only accept esac keyword */
2285 #define CMDWORD BIT(8) /* parsing simple command (alias related) */
2286 #define HEREDELIM BIT(9) /* parsing <<,<<- delimiter */
2287 #define LQCHAR BIT(10) /* source string contains QCHAR */
2288
2289 #define HERES 10 /* max number of << in line */
2290
2291 #ifdef MKSH_EBCDIC
2292 #define CTRL_AT (0x00U)
2293 #define CTRL_A (0x01U)
2294 #define CTRL_B (0x02U)
2295 #define CTRL_C (0x03U)
2296 #define CTRL_D (0x37U)
2297 #define CTRL_E (0x2DU)
2298 #define CTRL_F (0x2EU)
2299 #define CTRL_G (0x2FU)
2300 #define CTRL_H (0x16U)
2301 #define CTRL_I (0x05U)
2302 #define CTRL_J (0x15U)
2303 #define CTRL_K (0x0BU)
2304 #define CTRL_L (0x0CU)
2305 #define CTRL_M (0x0DU)
2306 #define CTRL_N (0x0EU)
2307 #define CTRL_O (0x0FU)
2308 #define CTRL_P (0x10U)
2309 #define CTRL_Q (0x11U)
2310 #define CTRL_R (0x12U)
2311 #define CTRL_S (0x13U)
2312 #define CTRL_T (0x3CU)
2313 #define CTRL_U (0x3DU)
2314 #define CTRL_V (0x32U)
2315 #define CTRL_W (0x26U)
2316 #define CTRL_X (0x18U)
2317 #define CTRL_Y (0x19U)
2318 #define CTRL_Z (0x3FU)
2319 #define CTRL_BO (0x27U)
2320 #define CTRL_BK (0x1CU)
2321 #define CTRL_BC (0x1DU)
2322 #define CTRL_CA (0x1EU)
2323 #define CTRL_US (0x1FU)
2324 #define CTRL_QM (0x07U)
2325 #else
2326 #define CTRL_AT (0x00U)
2327 #define CTRL_A (0x01U)
2328 #define CTRL_B (0x02U)
2329 #define CTRL_C (0x03U)
2330 #define CTRL_D (0x04U)
2331 #define CTRL_E (0x05U)
2332 #define CTRL_F (0x06U)
2333 #define CTRL_G (0x07U)
2334 #define CTRL_H (0x08U)
2335 #define CTRL_I (0x09U)
2336 #define CTRL_J (0x0AU)
2337 #define CTRL_K (0x0BU)
2338 #define CTRL_L (0x0CU)
2339 #define CTRL_M (0x0DU)
2340 #define CTRL_N (0x0EU)
2341 #define CTRL_O (0x0FU)
2342 #define CTRL_P (0x10U)
2343 #define CTRL_Q (0x11U)
2344 #define CTRL_R (0x12U)
2345 #define CTRL_S (0x13U)
2346 #define CTRL_T (0x14U)
2347 #define CTRL_U (0x15U)
2348 #define CTRL_V (0x16U)
2349 #define CTRL_W (0x17U)
2350 #define CTRL_X (0x18U)
2351 #define CTRL_Y (0x19U)
2352 #define CTRL_Z (0x1AU)
2353 #define CTRL_BO (0x1BU)
2354 #define CTRL_BK (0x1CU)
2355 #define CTRL_BC (0x1DU)
2356 #define CTRL_CA (0x1EU)
2357 #define CTRL_US (0x1FU)
2358 #define CTRL_QM (0x7FU)
2359 #endif
2360
2361 #define IDENT 64
2362
2363 EXTERN Source *source; /* yyparse/yylex source */
2364 EXTERN YYSTYPE yylval; /* result from yylex */
2365 EXTERN struct ioword *heres[HERES], **herep;
2366 EXTERN char ident[IDENT + 1];
2367
2368 EXTERN char **history; /* saved commands */
2369 EXTERN char **histptr; /* last history item */
2370 EXTERN mksh_ari_t histsize; /* history size */
2371
2372 /* flags to histsave */
2373 #define HIST_FLUSH 0
2374 #define HIST_QUEUE 1
2375 #define HIST_APPEND 2
2376 #define HIST_STORE 3
2377 #define HIST_NOTE 4
2378
2379 /* user and system time of last j_waitjed job */
2380 EXTERN struct timeval j_usrtime, j_systime;
2381
2382 #define notok2mul(max,val,c) (((val) != 0) && ((c) != 0) && \
2383 (((max) / (c)) < (val)))
2384 #define notok2add(max,val,c) ((val) > ((max) - (c)))
2385 #define notoktomul(val,cnst) notok2mul(SIZE_MAX, (val), (cnst))
2386 #define notoktoadd(val,cnst) notok2add(SIZE_MAX, (val), (cnst))
2387 #define checkoktoadd(val,cnst) do { \
2388 if (notoktoadd((val), (cnst))) \
2389 internal_errorf(Tintovfl, (size_t)(val), \
2390 '+', (size_t)(cnst)); \
2391 } while (/* CONSTCOND */ 0)
2392
2393
2394 /* lalloc.c */
2395 void ainit(Area *);
2396 void afreeall(Area *);
2397 /* these cannot fail and can take NULL (not for ap) */
2398 #define alloc(n,ap) aresize(NULL, (n), (ap))
2399 #define alloc2(m,n,ap) aresize2(NULL, (m), (n), (ap))
2400 void *aresize(void *, size_t, Area *);
2401 void *aresize2(void *, size_t, size_t, Area *);
2402 void afree(void *, Area *); /* can take NULL */
2403 #define aresizeif(z,p,n,ap) (((p) == NULL) || ((z) < (n)) || \
2404 (((z) & ~X_WASTE) > ((n) & ~X_WASTE)) ? \
2405 aresize((p), (n), (ap)) : (p))
2406 /* edit.c */
2407 #ifndef MKSH_NO_CMDLINE_EDITING
2408 int x_bind(const char * SMALLP(bool));
2409 int x_bind_check(void);
2410 int x_bind_list(void);
2411 int x_bind_showall(void);
2412 void x_init(void);
2413 #ifdef DEBUG_LEAKS
2414 void x_done(void);
2415 #endif
2416 int x_read(char *);
2417 #endif
2418 void x_mkraw(int, mksh_ttyst *, bool);
2419 void x_initterm(const char *);
2420 /* eval.c */
2421 char *substitute(const char *, int);
2422 char **eval(const char **, int);
2423 char *evalstr(const char *cp, int);
2424 char *evalonestr(const char *cp, int);
2425 char *debunk(char *, const char *, size_t);
2426 void expand(const char *, XPtrV *, int);
2427 int glob_str(char *, XPtrV *, bool);
2428 char *do_tilde(char *);
2429 /* exec.c */
2430 int execute(struct op * volatile, volatile int, volatile int * volatile);
2431 int c_builtin(const char **);
2432 struct tbl *get_builtin(const char *);
2433 struct tbl *findfunc(const char *, uint32_t, bool);
2434 int define(const char *, struct op *);
2435 const char *builtin(const char *, int (*)(const char **));
2436 struct tbl *findcom(const char *, int);
2437 void flushcom(bool);
2438 int search_access(const char *, int);
2439 const char *search_path(const char *, const char *, int, int *);
2440 void pr_menu(const char * const *);
2441 void pr_list(struct columnise_opts *, char * const *);
2442 int herein(struct ioword *, char **);
2443 /* expr.c */
2444 int evaluate(const char *, mksh_ari_t *, int, bool);
2445 int v_evaluate(struct tbl *, const char *, volatile int, bool);
2446 /* UTF-8 stuff */
2447 size_t utf_mbtowc(unsigned int *, const char *);
2448 size_t utf_wctomb(char *, unsigned int);
2449 int utf_widthadj(const char *, const char **);
2450 size_t utf_mbswidth(const char *) MKSH_A_PURE;
2451 const char *utf_skipcols(const char *, int, int *);
2452 size_t utf_ptradj(const char *) MKSH_A_PURE;
2453 #ifdef MIRBSD_BOOTFLOPPY
2454 #define utf_wcwidth(i) wcwidth((wchar_t)(i))
2455 #else
2456 int utf_wcwidth(unsigned int) MKSH_A_PURE;
2457 #endif
2458 int ksh_access(const char *, int);
2459 struct tbl *tempvar(const char *);
2460 /* funcs.c */
2461 int c_hash(const char **);
2462 int c_pwd(const char **);
2463 int c_print(const char **);
2464 #ifdef MKSH_PRINTF_BUILTIN
2465 int c_printf(const char **);
2466 #endif
2467 int c_whence(const char **);
2468 int c_command(const char **);
2469 int c_typeset(const char **);
2470 bool valid_alias_name(const char *);
2471 int c_alias(const char **);
2472 int c_unalias(const char **);
2473 int c_let(const char **);
2474 int c_jobs(const char **);
2475 #ifndef MKSH_UNEMPLOYED
2476 int c_fgbg(const char **);
2477 #endif
2478 int c_kill(const char **);
2479 void getopts_reset(int);
2480 int c_getopts(const char **);
2481 #ifndef MKSH_NO_CMDLINE_EDITING
2482 int c_bind(const char **);
2483 #endif
2484 int c_shift(const char **);
2485 int c_umask(const char **);
2486 int c_dot(const char **);
2487 int c_wait(const char **);
2488 int c_read(const char **);
2489 int c_eval(const char **);
2490 int c_trap(const char **);
2491 int c_brkcont(const char **);
2492 int c_exitreturn(const char **);
2493 int c_set(const char **);
2494 int c_unset(const char **);
2495 int c_ulimit(const char **);
2496 int c_times(const char **);
2497 int timex(struct op *, int, volatile int *);
2498 void timex_hook(struct op *, char ** volatile *);
2499 int c_exec(const char **);
2500 int c_test(const char **);
2501 #if HAVE_MKNOD
2502 int c_mknod(const char **);
2503 #endif
2504 int c_realpath(const char **);
2505 int c_rename(const char **);
2506 int c_cat(const char **);
2507 int c_sleep(const char **);
2508 /* histrap.c */
2509 void init_histvec(void);
2510 void hist_init(Source *);
2511 #if HAVE_PERSISTENT_HISTORY
2512 void hist_finish(void);
2513 #endif
2514 void histsave(int *, const char *, int, bool);
2515 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
2516 bool histsync(void);
2517 #endif
2518 int c_fc(const char **);
2519 void sethistsize(mksh_ari_t);
2520 #if HAVE_PERSISTENT_HISTORY
2521 void sethistfile(const char *);
2522 #endif
2523 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
2524 char **histpos(void) MKSH_A_PURE;
2525 int histnum(int);
2526 #endif
2527 int findhist(int, const char *, bool, bool) MKSH_A_PURE;
2528 char **hist_get_newest(bool);
2529 void inittraps(void);
2530 void alarm_init(void);
2531 Trap *gettrap(const char *, bool, bool);
2532 void trapsig(int);
2533 void intrcheck(void);
2534 int fatal_trap_check(void);
2535 int trap_pending(void);
2536 void runtraps(int intr);
2537 void runtrap(Trap *, bool);
2538 void cleartraps(void);
2539 void restoresigs(void);
2540 void settrap(Trap *, const char *);
2541 bool block_pipe(void);
2542 void restore_pipe(void);
2543 int setsig(Trap *, sig_t, int);
2544 void setexecsig(Trap *, int);
2545 #if HAVE_FLOCK || HAVE_LOCK_FCNTL
2546 void mksh_lockfd(int);
2547 void mksh_unlkfd(int);
2548 #endif
2549 /* jobs.c */
2550 void j_init(void);
2551 void j_exit(void);
2552 #ifndef MKSH_UNEMPLOYED
2553 void j_change(void);
2554 #endif
2555 int exchild(struct op *, int, volatile int *, int);
2556 void startlast(void);
2557 int waitlast(void);
2558 int waitfor(const char *, int *);
2559 int j_kill(const char *, int);
2560 #ifndef MKSH_UNEMPLOYED
2561 int j_resume(const char *, int);
2562 #endif
2563 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
2564 void j_suspend(void);
2565 #endif
2566 int j_jobs(const char *, int, int);
2567 void j_notify(void);
2568 pid_t j_async(void);
2569 int j_stopped_running(void);
2570 /* lex.c */
2571 int yylex(int);
2572 void yyskiputf8bom(void);
2573 void yyerror(const char *, ...)
2574 MKSH_A_NORETURN
2575 MKSH_A_FORMAT(__printf__, 1, 2);
2576 Source *pushs(int, Area *);
2577 void set_prompt(int, Source *);
2578 int pprompt(const char *, int);
2579 /* main.c */
2580 int include(const char *, int, const char **, bool);
2581 int command(const char *, int);
2582 int shell(Source * volatile, volatile int);
2583 /* argument MUST NOT be 0 */
2584 void unwind(int) MKSH_A_NORETURN;
2585 void newenv(int);
2586 void quitenv(struct shf *);
2587 void cleanup_parents_env(void);
2588 void cleanup_proc_env(void);
2589 void errorf(const char *, ...)
2590 MKSH_A_NORETURN
2591 MKSH_A_FORMAT(__printf__, 1, 2);
2592 void errorfx(int, const char *, ...)
2593 MKSH_A_NORETURN
2594 MKSH_A_FORMAT(__printf__, 2, 3);
2595 void warningf(bool, const char *, ...)
2596 MKSH_A_FORMAT(__printf__, 2, 3);
2597 void bi_errorf(const char *, ...)
2598 MKSH_A_FORMAT(__printf__, 1, 2);
2599 void maybe_errorf(int *, int, const char *, ...)
2600 MKSH_A_FORMAT(__printf__, 3, 4);
2601 #define errorfz() errorf(NULL)
2602 #define errorfxz(rc) errorfx((rc), NULL)
2603 #define bi_errorfz() bi_errorf(NULL)
2604 void internal_errorf(const char *, ...)
2605 MKSH_A_NORETURN
2606 MKSH_A_FORMAT(__printf__, 1, 2);
2607 void internal_warningf(const char *, ...)
2608 MKSH_A_FORMAT(__printf__, 1, 2);
2609 void error_prefix(bool);
2610 void shellf(const char *, ...)
2611 MKSH_A_FORMAT(__printf__, 1, 2);
2612 void shprintf(const char *, ...)
2613 MKSH_A_FORMAT(__printf__, 1, 2);
2614 int can_seek(int);
2615 void initio(void);
2616 void recheck_ctype(void);
2617 int ksh_dup2(int, int, bool);
2618 short savefd(int);
2619 void restfd(int, int);
2620 void openpipe(int *);
2621 void closepipe(int *);
2622 int check_fd(const char *, int, const char **);
2623 void coproc_init(void);
2624 void coproc_read_close(int);
2625 void coproc_readw_close(int);
2626 void coproc_write_close(int);
2627 int coproc_getfd(int, const char **);
2628 void coproc_cleanup(int);
2629 struct temp *maketemp(Area *, Temp_type, struct temp **);
2630 void ktinit(Area *, struct table *, uint8_t);
2631 struct tbl *ktscan(struct table *, const char *, uint32_t, struct tbl ***);
2632 /* table, name (key) to search for, hash(n) */
2633 #define ktsearch(tp,s,h) ktscan((tp), (s), (h), NULL)
2634 struct tbl *ktenter(struct table *, const char *, uint32_t);
2635 #define ktdelete(p) do { p->flag = 0; } while (/* CONSTCOND */ 0)
2636 void ktwalk(struct tstate *, struct table *);
2637 struct tbl *ktnext(struct tstate *);
2638 struct tbl **ktsort(struct table *);
2639 #ifdef DF
2640 void DF(const char *, ...)
2641 MKSH_A_FORMAT(__printf__, 1, 2);
2642 #endif
2643 /* misc.c */
2644 size_t option(const char *) MKSH_A_PURE;
2645 char *getoptions(void);
2646 void change_flag(enum sh_flag, int, bool);
2647 void change_xtrace(unsigned char, bool);
2648 int parse_args(const char **, int, bool *);
2649 int getn(const char *, int *);
2650 int gmatchx(const char *, const char *, bool);
2651 bool has_globbing(const char *) MKSH_A_PURE;
2652 int ascstrcmp(const void *, const void *) MKSH_A_PURE;
2653 int ascpstrcmp(const void *, const void *) MKSH_A_PURE;
2654 void ksh_getopt_reset(Getopt *, int);
2655 int ksh_getopt(const char **, Getopt *, const char *);
2656 void print_value_quoted(struct shf *, const char *);
2657 char *quote_value(const char *);
2658 void print_columns(struct columnise_opts *, unsigned int,
2659 void (*)(char *, size_t, unsigned int, const void *),
2660 const void *, size_t, size_t);
2661 void strip_nuls(char *, size_t)
2662 MKSH_A_BOUNDED(__string__, 1, 2);
2663 ssize_t blocking_read(int, char *, size_t)
2664 MKSH_A_BOUNDED(__buffer__, 2, 3);
2665 int reset_nonblock(int);
2666 char *ksh_get_wd(void);
2667 char *do_realpath(const char *);
2668 void simplify_path(char *);
2669 void set_current_wd(const char *);
2670 int c_cd(const char **);
2671 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2672 char *strdup_i(const char *, Area *);
2673 char *strndup_i(const char *, size_t, Area *);
2674 #endif
2675 int unbksl(bool, int (*)(void), void (*)(int));
2676 #ifdef __OS2__
2677 /* os2.c */
2678 void os2_init(int *, const char ***);
2679 void setextlibpath(const char *, const char *);
2680 int access_ex(int (*)(const char *, int), const char *, int);
2681 int stat_ex(int (*)(const char *, struct stat *), const char *, struct stat *);
2682 const char *real_exec_name(const char *);
2683 #endif
2684 /* shf.c */
2685 struct shf *shf_open(const char *, int, int, int);
2686 struct shf *shf_fdopen(int, int, struct shf *);
2687 struct shf *shf_reopen(int, int, struct shf *);
2688 struct shf *shf_sopen(char *, ssize_t, int, struct shf *);
2689 int shf_close(struct shf *);
2690 int shf_fdclose(struct shf *);
2691 char *shf_sclose(struct shf *);
2692 int shf_flush(struct shf *);
2693 ssize_t shf_read(char *, ssize_t, struct shf *);
2694 char *shf_getse(char *, ssize_t, struct shf *);
2695 int shf_getchar(struct shf *s);
2696 int shf_ungetc(int, struct shf *);
2697 #ifdef MKSH_SHF_NO_INLINE
2698 int shf_getc(struct shf *);
2699 int shf_putc(int, struct shf *);
2700 #else
2701 #define shf_getc shf_getc_i
2702 #define shf_putc shf_putc_i
2703 #endif
2704 int shf_putchar(int, struct shf *);
2705 ssize_t shf_puts(const char *, struct shf *);
2706 ssize_t shf_write(const char *, ssize_t, struct shf *);
2707 ssize_t shf_fprintf(struct shf *, const char *, ...)
2708 MKSH_A_FORMAT(__printf__, 2, 3);
2709 ssize_t shf_snprintf(char *, ssize_t, const char *, ...)
2710 MKSH_A_FORMAT(__printf__, 3, 4)
2711 MKSH_A_BOUNDED(__string__, 1, 2);
2712 char *shf_smprintf(const char *, ...)
2713 MKSH_A_FORMAT(__printf__, 1, 2);
2714 ssize_t shf_vfprintf(struct shf *, const char *, va_list)
2715 MKSH_A_FORMAT(__printf__, 2, 0);
2716 void set_ifs(const char *);
2717 /* syn.c */
2718 void initkeywords(void);
2719 struct op *compile(Source *, bool, bool);
2720 bool parse_usec(const char *, struct timeval *);
2721 char *yyrecursive(int);
2722 void yyrecursive_pop(bool);
2723 /* tree.c */
2724 void fptreef(struct shf *, int, const char *, ...);
2725 char *snptreef(char *, ssize_t, const char *, ...);
2726 struct op *tcopy(struct op *, Area *);
2727 char *wdcopy(const char *, Area *);
2728 const char *wdscan(const char *, int);
2729 #define WDS_TPUTS BIT(0) /* tputS (dumpwdvar) mode */
2730 char *wdstrip(const char *, int);
2731 void tfree(struct op *, Area *);
2732 void dumpchar(struct shf *, unsigned char);
2733 void dumptree(struct shf *, struct op *);
2734 void dumpwdvar(struct shf *, const char *);
2735 void dumpioact(struct shf *shf, struct op *t);
2736 void vistree(char *, size_t, struct op *)
2737 MKSH_A_BOUNDED(__string__, 1, 2);
2738 void fpFUNCTf(struct shf *, int, bool, const char *, struct op *);
2739 /* var.c */
2740 void newblock(void);
2741 void popblock(void);
2742 void initvar(void);
2743 struct block *varsearch(struct block *, struct tbl **, const char *, uint32_t);
2744 struct tbl *global(const char *);
2745 struct tbl *isglobal(const char *, bool);
2746 struct tbl *local(const char *, bool);
2747 char *str_val(struct tbl *);
2748 int setstr(struct tbl *, const char *, int);
2749 struct tbl *setint_v(struct tbl *, struct tbl *, bool);
2750 void setint(struct tbl *, mksh_ari_t);
2751 void setint_n(struct tbl *, mksh_ari_t, int);
2752 struct tbl *typeset(const char *, uint32_t, uint32_t, int, int);
2753 void unset(struct tbl *, int);
2754 const char *skip_varname(const char *, bool) MKSH_A_PURE;
2755 const char *skip_wdvarname(const char *, bool) MKSH_A_PURE;
2756 int is_wdvarname(const char *, bool) MKSH_A_PURE;
2757 int is_wdvarassign(const char *) MKSH_A_PURE;
2758 struct tbl *arraysearch(struct tbl *, uint32_t);
2759 char **makenv(void);
2760 void change_winsz(void);
2761 size_t array_ref_len(const char *) MKSH_A_PURE;
2762 struct tbl *arraybase(const char*);
2763 mksh_uari_t set_array(const char *, bool, const char **);
2764 uint32_t hash(const void *) MKSH_A_PURE;
2765 uint32_t chvt_rndsetup(const void *, size_t) MKSH_A_PURE;
2766 mksh_ari_t rndget(void);
2767 void rndset(unsigned long);
2768 void rndpush(const void *);
2769 void record_match(const char *);
2770
2771 enum Test_op {
2772 /* non-operator */
2773 TO_NONOP = 0,
2774 /* unary operators */
2775 TO_STNZE, TO_STZER, TO_ISSET, TO_OPTION,
2776 TO_FILAXST,
2777 TO_FILEXST,
2778 TO_FILREG, TO_FILBDEV, TO_FILCDEV, TO_FILSYM, TO_FILFIFO, TO_FILSOCK,
2779 TO_FILCDF, TO_FILID, TO_FILGID, TO_FILSETG, TO_FILSTCK, TO_FILUID,
2780 TO_FILRD, TO_FILGZ, TO_FILTT, TO_FILSETU, TO_FILWR, TO_FILEX,
2781 /* binary operators */
2782 TO_STEQL, TO_STNEQ, TO_STLT, TO_STGT, TO_INTEQ, TO_INTNE, TO_INTGT,
2783 TO_INTGE, TO_INTLT, TO_INTLE, TO_FILEQ, TO_FILNT, TO_FILOT,
2784 /* not an operator */
2785 TO_NONNULL /* !TO_NONOP */
2786 };
2787 typedef enum Test_op Test_op;
2788
2789 /* Used by Test_env.isa() (order important - used to index *_tokens[] arrays) */
2790 enum Test_meta {
2791 TM_OR, /* -o or || */
2792 TM_AND, /* -a or && */
2793 TM_NOT, /* ! */
2794 TM_OPAREN, /* ( */
2795 TM_CPAREN, /* ) */
2796 TM_UNOP, /* unary operator */
2797 TM_BINOP, /* binary operator */
2798 TM_END /* end of input */
2799 };
2800 typedef enum Test_meta Test_meta;
2801
2802 struct t_op {
2803 const char op_text[4];
2804 Test_op op_num;
2805 };
2806
2807 /* for string reuse */
2808 extern const struct t_op u_ops[];
2809 extern const struct t_op b_ops[];
2810 /* ensure order with funcs.c */
2811 #define Tda (u_ops[0].op_text)
2812 #define Tdn (u_ops[12].op_text)
2813 #define Tdo (u_ops[14].op_text)
2814 #define Tdr (u_ops[16].op_text)
2815 #define Tdu (u_ops[20].op_text) /* "-u" */
2816 #define Tdx (u_ops[23].op_text)
2817
2818 #define Tu (Tdu + 1) /* "u" */
2819
2820 #define TEF_ERROR BIT(0) /* set if we've hit an error */
2821 #define TEF_DBRACKET BIT(1) /* set if [[ .. ]] test */
2822
2823 typedef struct test_env {
2824 union {
2825 const char **wp; /* used by ptest_* */
2826 XPtrV *av; /* used by dbtestp_* */
2827 } pos;
2828 const char **wp_end; /* used by ptest_* */
2829 Test_op (*isa)(struct test_env *, Test_meta);
2830 const char *(*getopnd) (struct test_env *, Test_op, bool);
2831 int (*eval)(struct test_env *, Test_op, const char *, const char *, bool);
2832 void (*error)(struct test_env *, int, const char *);
2833 int flags; /* TEF_* */
2834 } Test_env;
2835
2836 extern const char * const dbtest_tokens[];
2837
2838 Test_op test_isop(Test_meta, const char *) MKSH_A_PURE;
2839 int test_eval(Test_env *, Test_op, const char *, const char *, bool);
2840 int test_parse(Test_env *);
2841
2842 /* tty_fd is not opened O_BINARY, it's thus never read/written */
2843 EXTERN int tty_fd E_INIT(-1); /* dup'd tty file descriptor */
2844 EXTERN bool tty_devtty; /* true if tty_fd is from /dev/tty */
2845 EXTERN mksh_ttyst tty_state; /* saved tty state */
2846 EXTERN bool tty_hasstate; /* true if tty_state is valid */
2847
2848 extern int tty_init_fd(void); /* initialise tty_fd, tty_devtty */
2849
2850 #ifdef __OS2__
2851 #define binopen2(path,flags) __extension__({ \
2852 int binopen2_fd = open((path), (flags) | O_BINARY); \
2853 if (binopen2_fd >= 0) \
2854 setmode(binopen2_fd, O_BINARY); \
2855 (binopen2_fd); \
2856 })
2857 #define binopen3(path,flags,mode) __extension__({ \
2858 int binopen3_fd = open((path), (flags) | O_BINARY, (mode)); \
2859 if (binopen3_fd >= 0) \
2860 setmode(binopen3_fd, O_BINARY); \
2861 (binopen3_fd); \
2862 })
2863 #else
2864 #define binopen2(path,flags) open((path), (flags) | O_BINARY)
2865 #define binopen3(path,flags,mode) open((path), (flags) | O_BINARY, (mode))
2866 #endif
2867
2868 #ifdef MKSH_DOSPATH
2869 #define mksh_drvltr(s) __extension__({ \
2870 const char *mksh_drvltr_s = (s); \
2871 (ctype(mksh_drvltr_s[0], C_ALPHA) && mksh_drvltr_s[1] == ':'); \
2872 })
2873 #define mksh_abspath(s) __extension__({ \
2874 const char *mksh_abspath_s = (s); \
2875 (mksh_cdirsep(mksh_abspath_s[0]) || \
2876 (mksh_drvltr(mksh_abspath_s) && \
2877 mksh_cdirsep(mksh_abspath_s[2]))); \
2878 })
2879 #define mksh_cdirsep(c) __extension__({ \
2880 char mksh_cdirsep_c = (c); \
2881 (mksh_cdirsep_c == '/' || mksh_cdirsep_c == '\\'); \
2882 })
2883 #define mksh_sdirsep(s) strpbrk((s), "/\\")
2884 #define mksh_vdirsep(s) __extension__({ \
2885 const char *mksh_vdirsep_s = (s); \
2886 (((mksh_drvltr(mksh_vdirsep_s) && \
2887 !mksh_cdirsep(mksh_vdirsep_s[2])) ? (!0) : \
2888 (mksh_sdirsep(mksh_vdirsep_s) != NULL)) && \
2889 (strcmp(mksh_vdirsep_s, T_builtin) != 0)); \
2890 })
2891 int getdrvwd(char **, unsigned int);
2892 #else
2893 #define mksh_abspath(s) (ord((s)[0]) == ORD('/'))
2894 #define mksh_cdirsep(c) (ord(c) == ORD('/'))
2895 #define mksh_sdirsep(s) strchr((s), '/')
2896 #define mksh_vdirsep(s) vstrchr((s), '/')
2897 #endif
2898
2899 /* be sure not to interfere with anyone else's idea about EXTERN */
2900 #ifdef EXTERN_DEFINED
2901 # undef EXTERN_DEFINED
2902 # undef EXTERN
2903 #endif
2904 #undef E_INIT
2905
2906 #endif /* !MKSH_INCLUDES_ONLY */
2907