sh.h revision 1.26 1 /* $NetBSD: sh.h,v 1.26 2017/06/22 23:50:24 kamil Exp $ */
2
3 /*
4 * Public Domain Bourne/Korn shell
5 */
6
7 /* $Id: sh.h,v 1.26 2017/06/22 23:50:24 kamil Exp $ */
8
9 #include "config.h" /* system and option configuration info */
10
11 #ifdef HAVE_PROTOTYPES
12 # define ARGS(args) args /* prototype declaration */
13 #else
14 # define ARGS(args) () /* K&R declaration */
15 #endif
16
17 /* Start of common headers */
18
19 #include <stdio.h>
20 #include <sys/types.h>
21 #include <setjmp.h>
22 #include <stddef.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26
27 #ifdef HAVE_PROTOTYPES
28 # include <stdarg.h>
29 # define SH_VA_START(va, argn) va_start(va, argn)
30 #else
31 # include <varargs.h>
32 # define SH_VA_START(va, argn) va_start(va)
33 #endif /* HAVE_PROTOTYPES */
34
35 #include <errno.h>
36 #include <fcntl.h>
37
38 #ifndef O_ACCMODE
39 # define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
40 #endif /* !O_ACCMODE */
41
42 #ifndef F_OK /* access() arguments */
43 # define F_OK 0
44 # define X_OK 1
45 # define W_OK 2
46 # define R_OK 4
47 #endif /* !F_OK */
48
49 #ifndef SEEK_SET
50 # ifdef L_SET
51 # define SEEK_SET L_SET
52 # define SEEK_CUR L_INCR
53 # define SEEK_END L_XTND
54 # else /* L_SET */
55 # define SEEK_SET 0
56 # define SEEK_CUR 1
57 # define SEEK_END 2
58 # endif /* L_SET */
59 #endif /* !SEEK_SET */
60
61 /* Some machines (eg, FreeBSD 1.1.5) define CLK_TCK in limits.h
62 * (ksh_limval.h assumes limits has been included, if available)
63 */
64 #include <limits.h>
65
66 #include <signal.h>
67 #ifdef NSIG
68 # define SIGNALS NSIG
69 #else
70 # ifdef _MINIX
71 # define SIGNALS (_NSIG+1) /* _NSIG is # of signals used, excluding 0. */
72 # else
73 # ifdef _SIGMAX /* QNX */
74 # define SIGNALS _SIGMAX
75 # else /* _SIGMAX */
76 # define SIGNALS 32
77 # endif /* _SIGMAX */
78 # endif /* _MINIX */
79 #endif /* NSIG */
80 #ifndef SIGCHLD
81 # define SIGCHLD SIGCLD
82 #endif
83 /* struct sigaction.sa_flags is set to KSH_SA_FLAGS. Used to ensure
84 * system calls are interrupted
85 */
86 #ifdef SA_INTERRUPT
87 # define KSH_SA_FLAGS SA_INTERRUPT
88 #else /* SA_INTERRUPT */
89 # define KSH_SA_FLAGS 0
90 #endif /* SA_INTERRUPT */
91
92 typedef RETSIGTYPE (*handler_t) ARGS((int)); /* signal handler */
93
94 #ifdef USE_FAKE_SIGACT
95 # include "sigact.h" /* use sjg's fake sigaction() */
96 #endif
97
98 #ifdef HAVE_PATHS_H
99 # include <paths.h>
100 #endif /* HAVE_PATHS_H */
101 #ifdef _PATH_DEFPATH
102 # define DEFAULT__PATH _PATH_DEFPATH
103 #else /* _PATH_DEFPATH */
104 # define DEFAULT__PATH DEFAULT_PATH
105 #endif /* _PATH_DEFPATH */
106
107 #ifndef HAVE_KILLPG
108 # define killpg(p, s) kill(-(p), (s))
109 #endif /* !HAVE_KILLPG */
110
111 /* this is a hang-over from older versions of the os2 port */
112 #define ksh_dupbase(fd, base) fcntl(fd, F_DUPFD, base)
113
114 #ifdef HAVE_SIGSETJMP
115 # define ksh_sigsetjmp(env,sm) sigsetjmp((env), (sm))
116 # define ksh_siglongjmp(env,v) siglongjmp((env), (v))
117 # define ksh_jmp_buf sigjmp_buf
118 #else /* HAVE_SIGSETJMP */
119 # ifdef HAVE__SETJMP
120 # define ksh_sigsetjmp(env,sm) _setjmp(env)
121 # define ksh_siglongjmp(env,v) _longjmp((env), (v))
122 # else /* HAVE__SETJMP */
123 # define ksh_sigsetjmp(env,sm) setjmp(env)
124 # define ksh_siglongjmp(env,v) longjmp((env), (v))
125 # endif /* HAVE__SETJMP */
126 # define ksh_jmp_buf jmp_buf
127 #endif /* HAVE_SIGSETJMP */
128
129 /* Find a integer type that is at least 32 bits (or die) - SIZEOF_* defined
130 * by autoconf (assumes an 8 bit byte, but I'm not concerned).
131 * NOTE: INT32 may end up being more than 32 bits.
132 */
133 #if SIZEOF_INT >= 4
134 # define INT32 int
135 #else /* SIZEOF_INT */
136 # if SIZEOF_LONG >= 4
137 # define INT32 long
138 # else /* SIZEOF_LONG */
139 #error cannot find 32 bit type...
140 # endif /* SIZEOF_LONG */
141 #endif /* SIZEOF_INT */
142
143 /* end of common headers */
144
145 /* Stop gcc and lint from complaining about possibly uninitialized variables */
146 #if defined(__GNUC__) || defined(lint)
147 # define UNINITIALIZED(var) var = 0
148 #else
149 # define UNINITIALIZED(var) var
150 #endif /* GNUC || lint */
151
152 /* some useful #defines */
153 #ifdef EXTERN
154 # define I__(i) = i
155 #else
156 # define I__(i)
157 # define EXTERN extern
158 # define EXTERN_DEFINED
159 #endif
160
161 #ifndef EXECSHELL
162 /* shell to exec scripts (see also $SHELL initialization in main.c) */
163 # define EXECSHELL "/bin/sh"
164 # define EXECSHELL_STR "EXECSHELL"
165 #endif
166
167 /* ISABSPATH() means path is fully and completely specified,
168 * ISROOTEDPATH() means a .. as the first component is a no-op,
169 * ISRELPATH() means $PWD can be tacked on to get an absolute path.
170 *
171 * OS Path ISABSPATH ISROOTEDPATH ISRELPATH
172 * unix /foo yes yes no
173 * unix foo no no yes
174 * unix ../foo no no yes
175 */
176 # define PATHSEP ':'
177 # define DIRSEP '/'
178 # define DIRSEPSTR "/"
179 # define ISDIRSEP(c) ((c) == '/')
180 # define ISABSPATH(s) ISDIRSEP((s)[0])
181 # define ISRELPATH(s) (!ISABSPATH(s))
182 # define ISROOTEDPATH(s) ISABSPATH(s)
183 # define FILECHCONV(c) c
184 # define FILECMP(s1, s2) strcmp(s1, s2)
185 # define FILENCMP(s1, s2, n) strncmp(s1, s2, n)
186 # define ksh_strchr_dirsep(p) strchr(p, DIRSEP)
187 # define ksh_strrchr_dirsep(p) strrchr(p, DIRSEP)
188
189 typedef int bool_t;
190 #define FALSE 0
191 #define TRUE 1
192
193 #define NELEM(a) (sizeof(a) / sizeof((a)[0]))
194 #define sizeofN(type, n) (sizeof(type) * (n))
195 #define BIT(i) (1<<(i)) /* define bit in flag */
196
197 /* Table flag type - needs > 16 and < 32 bits */
198 typedef INT32 Tflag;
199
200 #define NUFILE 32 /* Number of user-accessible files */
201 #define FDBASE 10 /* First file usable by Shell */
202
203 /* you're not going to run setuid shell scripts, are you? */
204 #define eaccess(path, mode) access(path, mode)
205
206 /* Make MAGIC a char that might be printed to make bugs more obvious, but
207 * not a char that is used often. Also, can't use the high bit as it causes
208 * portability problems (calling strchr(x, 0x80|'x') is error prone).
209 */
210 #define MAGIC (7) /* prefix for *?[!{,} during expand */
211 #define ISMAGIC(c) ((unsigned char)(c) == MAGIC)
212 #define NOT '!' /* might use ^ (ie, [!...] vs [^..]) */
213
214 #define LINE 1024 /* input line size */
215 #define PATH 1024 /* pathname size (todo: PATH_MAX/pathconf()) */
216 #define ARRAYMAX 1023 /* max array index */
217
218 EXTERN const char *kshname; /* $0 */
219 EXTERN pid_t kshpid; /* $$, shell pid */
220 EXTERN pid_t procpid; /* pid of executing process */
221 EXTERN uid_t ksheuid; /* effective uid of shell */
222 EXTERN int exstat; /* exit status */
223 EXTERN int subst_exstat; /* exit status of last $(..)/`..` */
224 EXTERN const char *safe_prompt; /* safe prompt if PS1 substitution fails */
225
226 /*
227 * Area-based allocation built on malloc/free
228 */
229 typedef struct Area {
230 struct link *freelist; /* free list */
231 } Area;
232
233 EXTERN Area aperm; /* permanent object space */
234 #define APERM &aperm
235 #define ATEMP &e->area
236
237 #ifdef MEM_DEBUG
238 # include "chmem.h" /* a debugging front end for malloc et. al. */
239 #endif /* MEM_DEBUG */
240
241 #ifdef KSH_DEBUG
242 # define kshdebug_init() kshdebug_init_()
243 # define kshdebug_printf(a) kshdebug_printf_ a
244 # define kshdebug_dump(a) kshdebug_dump_ a
245 #else /* KSH_DEBUG */
246 # define kshdebug_init()
247 # define kshdebug_printf(a)
248 # define kshdebug_dump(a)
249 #endif /* KSH_DEBUG */
250
251 /*
252 * parsing & execution environment
253 */
254 EXTERN struct env {
255 short type; /* environment type - see below */
256 short flags; /* EF_* */
257 Area area; /* temporary allocation area */
258 struct block *loc; /* local variables and functions */
259 short *savefd; /* original redirected fd's */
260 struct env *oenv; /* link to previous environment */
261 ksh_jmp_buf jbuf; /* long jump back to env creator */
262 struct temp *temps; /* temp files */
263 } *e;
264
265 /* struct env.type values */
266 #define E_NONE 0 /* dummy environment */
267 #define E_PARSE 1 /* parsing command # */
268 #define E_FUNC 2 /* executing function # */
269 #define E_INCL 3 /* including a file via . # */
270 #define E_EXEC 4 /* executing command tree */
271 #define E_LOOP 5 /* executing for/while # */
272 #define E_ERRH 6 /* general error handler # */
273 /* # indicates env has valid jbuf (see unwind()) */
274
275 /* struct env.flag values */
276 #define EF_FUNC_PARSE BIT(0) /* function being parsed */
277 #define EF_BRKCONT_PASS BIT(1) /* set if E_LOOP must pass break/continue on */
278 #define EF_FAKE_SIGDIE BIT(2) /* hack to get info from unwind to quitenv */
279
280 /* Do breaks/continues stop at env type e? */
281 #define STOP_BRKCONT(t) ((t) == E_NONE || (t) == E_PARSE \
282 || (t) == E_FUNC || (t) == E_INCL)
283 /* Do returns stop at env type e? */
284 #define STOP_RETURN(t) ((t) == E_FUNC || (t) == E_INCL)
285
286 /* values for ksh_siglongjmp(e->jbuf, 0) */
287 #define LRETURN 1 /* return statement */
288 #define LEXIT 2 /* exit statement */
289 #define LERROR 3 /* errorf() called */
290 #define LLEAVE 4 /* untrappable exit/error */
291 #define LINTR 5 /* ^C noticed */
292 #define LBREAK 6 /* break statement */
293 #define LCONTIN 7 /* continue statement */
294 #define LSHELL 8 /* return to interactive shell() */
295 #define LAEXPR 9 /* error in arithmetic expression */
296
297 /* option processing */
298 #define OF_CMDLINE 0x01 /* command line */
299 #define OF_SET 0x02 /* set builtin */
300 #define OF_SPECIAL 0x04 /* a special variable changing */
301 #define OF_INTERNAL 0x08 /* set internally by shell */
302 #define OF_ANY (OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
303
304 struct option {
305 const char *name; /* long name of option */
306 char c; /* character flag (if any) */
307 short flags; /* OF_* */
308 };
309 extern const struct option goptions[];
310
311 /*
312 * flags (the order of these enums MUST match the order in misc.c(options[]))
313 */
314 enum sh_flag {
315 FEXPORT = 0, /* -a: export all */
316 #ifdef BRACE_EXPAND
317 FBRACEEXPAND, /* enable {} globbing */
318 #endif
319 FBGNICE, /* bgnice */
320 FCOMMAND, /* -c: (invocation) execute specified command */
321 #ifdef EMACS
322 FEMACS, /* emacs command editing */
323 FEMACSUSEMETA, /* use 8th bit as meta */
324 #endif
325 FERREXIT, /* -e: quit on error */
326 #ifdef EMACS
327 FGMACS, /* gmacs command editing */
328 #endif
329 FIGNOREEOF, /* eof does not exit */
330 FTALKING, /* -i: interactive */
331 FKEYWORD, /* -k: name=value anywhere */
332 FLOGIN, /* -l: a login shell */
333 FMARKDIRS, /* mark dirs with / in file name completion */
334 FMONITOR, /* -m: job control monitoring */
335 FNOCLOBBER, /* -C: don't overwrite existing files */
336 FNOEXEC, /* -n: don't execute any commands */
337 FNOGLOB, /* -f: don't do file globbing */
338 FNOHUP, /* -H: don't kill running jobs when login shell exits */
339 FNOLOG, /* don't save functions in history (ignored) */
340 #ifdef JOBS
341 FNOTIFY, /* -b: asynchronous job completion notification */
342 #endif
343 FNOUNSET, /* -u: using an unset var is an error */
344 FPHYSICAL, /* -o physical: don't do logical cd's/pwd's */
345 FPOSIX, /* -o posix: be posixly correct */
346 FPRIVILEGED, /* -p: use suid_profile */
347 FRESTRICTED, /* -r: restricted shell */
348 FSTDIN, /* -s: (invocation) parse stdin */
349 FTRACKALL, /* -h: create tracked aliases for all commands */
350 FVERBOSE, /* -v: echo input */
351 #ifdef VI
352 FVI, /* vi command editing */
353 FVIRAW, /* always read in raw mode (ignored) */
354 FVISHOW8, /* display chars with 8th bit set as is (versus M-) */
355 FVITABCOMPLETE, /* enable tab as file name completion char */
356 FVIESCCOMPLETE, /* enable ESC as file name completion in command mode */
357 #endif
358 FXTRACE, /* -x: execution trace */
359 FTALKING_I, /* (internal): initial shell was interactive */
360 FNFLAGS /* (place holder: how many flags are there) */
361 };
362
363 #define Flag(f) (shell_flags[(int) (f)])
364
365 EXTERN char shell_flags [FNFLAGS];
366
367 EXTERN char null [] I__(""); /* null value for variable */
368 EXTERN char space [] I__(" ");
369 EXTERN char newline [] I__("\n");
370 EXTERN char slash [] I__("/");
371
372 enum temp_type {
373 TT_HEREDOC_EXP, /* expanded heredoc */
374 TT_HIST_EDIT /* temp file used for history editing (fc -e) */
375 };
376 typedef enum temp_type Temp_type;
377 /* temp/heredoc files. The file is removed when the struct is freed. */
378 struct temp {
379 struct temp *next;
380 struct shf *shf;
381 int pid; /* pid of process parsed here-doc */
382 Temp_type type;
383 char *name;
384 };
385
386 /*
387 * stdio and our IO routines
388 */
389
390 #define shl_spare (&shf_iob[0]) /* for c_read()/c_print() */
391 #define shl_stdout (&shf_iob[1])
392 #define shl_out (&shf_iob[2])
393 EXTERN int shl_stdout_ok;
394
395 /*
396 * trap handlers
397 */
398 typedef struct trap {
399 int signal; /* signal number */
400 const char *name; /* short name */
401 const char *mess; /* descriptive name */
402 char *trap; /* trap command */
403 int volatile set; /* trap pending */
404 int flags; /* TF_* */
405 handler_t cursig; /* current handler (valid if TF_ORIG_* set) */
406 handler_t shtrap; /* shell signal handler */
407 } Trap;
408
409 /* values for Trap.flags */
410 #define TF_SHELL_USES BIT(0) /* shell uses signal, user can't change */
411 #define TF_USER_SET BIT(1) /* user has (tried to) set trap */
412 #define TF_ORIG_IGN BIT(2) /* original action was SIG_IGN */
413 #define TF_ORIG_DFL BIT(3) /* original action was SIG_DFL */
414 #define TF_EXEC_IGN BIT(4) /* restore SIG_IGN just before exec */
415 #define TF_EXEC_DFL BIT(5) /* restore SIG_DFL just before exec */
416 #define TF_DFL_INTR BIT(6) /* when received, default action is LINTR */
417 #define TF_TTY_INTR BIT(7) /* tty generated signal (see j_waitj) */
418 #define TF_CHANGED BIT(8) /* used by runtrap() to detect trap changes */
419 #define TF_FATAL BIT(9) /* causes termination if not trapped */
420
421 /* values for setsig()/setexecsig() flags argument */
422 #define SS_RESTORE_MASK 0x3 /* how to restore a signal before an exec() */
423 #define SS_RESTORE_CURR 0 /* leave current handler in place */
424 #define SS_RESTORE_ORIG 1 /* restore original handler */
425 #define SS_RESTORE_DFL 2 /* restore to SIG_DFL */
426 #define SS_RESTORE_IGN 3 /* restore to SIG_IGN */
427 #define SS_FORCE BIT(3) /* set signal even if original signal ignored */
428 #define SS_USER BIT(4) /* user is doing the set (ie, trap command) */
429 #define SS_SHTRAP BIT(5) /* trap for internal use (CHLD,ALRM,WINCH) */
430
431 #define SIGEXIT_ 0 /* for trap EXIT */
432 #define SIGERR_ SIGNALS /* for trap ERR */
433
434 EXTERN int volatile trap; /* traps pending? */
435 EXTERN int volatile intrsig; /* pending trap interrupts executing command */
436 EXTERN int volatile fatal_trap;/* received a fatal signal */
437 extern Trap sigtraps[SIGNALS+1];
438
439 #ifdef KSH
440 /*
441 * TMOUT support
442 */
443 /* values for ksh_tmout_state */
444 enum tmout_enum {
445 TMOUT_EXECUTING = 0, /* executing commands */
446 TMOUT_READING, /* waiting for input */
447 TMOUT_LEAVING /* have timed out */
448 };
449 EXTERN unsigned int ksh_tmout;
450 EXTERN enum tmout_enum ksh_tmout_state I__(TMOUT_EXECUTING);
451 #endif /* KSH */
452
453 /* For "You have stopped jobs" message */
454 EXTERN int really_exit;
455
456 /*
457 * fast character classes
458 */
459 #define C_ALPHA BIT(0) /* a-z_A-Z */
460 #define C_DIGIT BIT(1) /* 0-9 */
461 #define C_LEX1 BIT(2) /* \0 \t\n|&;<>() */
462 #define C_VAR1 BIT(3) /* *@#!$-? */
463 #define C_IFSWS BIT(4) /* \t \n (IFS white space) */
464 #define C_SUBOP1 BIT(5) /* "=-+?" */
465 #define C_SUBOP2 BIT(6) /* "#%" */
466 #define C_IFS BIT(7) /* $IFS */
467 #define C_QUOTE BIT(8) /* \n\t"#$&'()*;<>?[\`| (needing quoting) */
468
469 extern short ctypes [];
470
471 #define ctype(c, t) !!(ctypes[(unsigned char)(c)]&(t))
472 #define letter(c) ctype(c, C_ALPHA)
473 #define digit(c) ctype(c, C_DIGIT)
474 #define letnum(c) ctype(c, C_ALPHA|C_DIGIT)
475
476 EXTERN int ifs0 I__(' '); /* for "$*" */
477
478 /* Argument parsing for built-in commands and getopts command */
479
480 /* Values for Getopt.flags */
481 #define GF_ERROR BIT(0) /* call errorf() if there is an error */
482 #define GF_PLUSOPT BIT(1) /* allow +c as an option */
483 #define GF_NONAME BIT(2) /* don't print argv[0] in errors */
484
485 /* Values for Getopt.info */
486 #define GI_MINUS BIT(0) /* an option started with -... */
487 #define GI_PLUS BIT(1) /* an option started with +... */
488 #define GI_MINUSMINUS BIT(2) /* arguments were ended with -- */
489
490 typedef struct {
491 int optind;
492 int uoptind;/* what user sees in $OPTIND */
493 char *optarg;
494 int flags; /* see GF_* */
495 int info; /* see GI_* */
496 unsigned int p; /* 0 or index into argv[optind - 1] */
497 char buf[2]; /* for bad option OPTARG value */
498 } Getopt;
499
500 EXTERN Getopt builtin_opt; /* for shell builtin commands */
501 EXTERN Getopt user_opt; /* parsing state for getopts builtin command */
502
503 #ifdef KSH
504 /* This for co-processes */
505
506 typedef INT32 Coproc_id; /* something that won't (realisticly) wrap */
507 struct coproc {
508 int read; /* pipe from co-process's stdout */
509 int readw; /* other side of read (saved temporarily) */
510 int write; /* pipe to co-process's stdin */
511 Coproc_id id; /* id of current output pipe */
512 int njobs; /* number of live jobs using output pipe */
513 void *job; /* 0 or job of co-process using input pipe */
514 };
515 EXTERN struct coproc coproc;
516 #endif /* KSH */
517
518 /* Used in jobs.c and by coprocess stuff in exec.c */
519 #ifdef JOB_SIGS
520 EXTERN sigset_t sm_default, sm_sigchld;
521 #endif /* JOB_SIGS */
522
523 extern char ksh_version[];
524
525 /* name of called builtin function (used by error functions) */
526 EXTERN char *builtin_argv0;
527 EXTERN Tflag builtin_flag; /* flags of called builtin (SPEC_BI, etc.) */
528
529 /* current working directory, and size of memory allocated for same */
530 EXTERN char *current_wd;
531 EXTERN int current_wd_size;
532
533 #ifdef EDIT
534 /* Minimum required space to work with on a line - if the prompt leaves less
535 * space than this on a line, the prompt is truncated.
536 */
537 # define MIN_EDIT_SPACE 7
538 /* Minimum allowed value for x_cols: 2 for prompt, 3 for " < " at end of line
539 */
540 # define MIN_COLS (2 + MIN_EDIT_SPACE + 3)
541 EXTERN int x_cols I__(80); /* tty columns */
542 #else
543 # define x_cols 80 /* for pr_menu(exec.c) */
544 #endif
545
546 /* These to avoid bracket matching problems */
547 #define OPAREN '('
548 #define CPAREN ')'
549 #define OBRACK '['
550 #define CBRACK ']'
551 #define OBRACE '{'
552 #define CBRACE '}'
553
554 /* Determine the location of the system (common) profile */
555 #ifndef KSH_SYSTEM_PROFILE
556 # ifdef __NeXT
557 # define KSH_SYSTEM_PROFILE "/etc/profile.std"
558 # else /* __NeXT */
559 # define KSH_SYSTEM_PROFILE "/etc/profile"
560 # endif /* __NeXT */
561 #endif /* KSH_SYSTEM_PROFILE */
562
563 /* Used by v_evaluate() and setstr() to control action when error occurs */
564 #define KSH_UNWIND_ERROR 0 /* unwind the stack (longjmp) */
565 #define KSH_RETURN_ERROR 1 /* return 1/0 for success/failure */
566
567 #include "shf.h"
568 #include "table.h"
569 #include "tree.h"
570 #include "expand.h"
571 #include "lex.h"
572 #include "proto.h"
573
574 /* be sure not to interfere with anyone else's idea about EXTERN */
575 #ifdef EXTERN_DEFINED
576 # undef EXTERN_DEFINED
577 # undef EXTERN
578 #endif
579 #undef I__
580