2 * Miscellaneous functions
6 #include <ctype.h> /* for FILECHCONV */
12 # define UCHAR_MAX 0xFF
15 short ctypes
[UCHAR_MAX
+1]; /* type bits for unsigned char */
16 static int do_gmatch(const unsigned char *, const unsigned char *,
17 const unsigned char *, const unsigned char *);
18 static const unsigned char *cclass(const unsigned char *, int);
21 * Fast character classes
24 setctypes(const char *s
, int t
)
29 for (i
= 0; i
< UCHAR_MAX
+1; i
++)
31 ctypes
[0] |= C_IFS
; /* include \0 in C_IFS */
34 ctypes
[(unsigned char) *s
++] |= t
;
40 setctypes(" \t\n|&;<>()", C_LEX1
); /* \0 added automatically */
41 setctypes("*@#!$-?", C_VAR1
);
42 setctypes(" \t\n", C_IFSWS
);
43 setctypes("=-+?", C_SUBOP1
);
44 setctypes("#%", C_SUBOP2
);
45 setctypes(" \n\t\"#$&'()*;<>?[\\`|", C_QUOTE
);
49 str_save(const char *s
, Area
*ap
)
51 return s
? strcpy((char*) alloc((size_t)strlen(s
)+1, ap
), s
) : NULL
;
54 /* Allocate a string of size n+1 and copy upto n characters from the possibly
55 * NUL terminated string s into it. Always returns a NUL terminated string
59 str_nsave(const char *s
, int n
, Area
*ap
)
65 ns
= alloc(n
+ 1, ap
);
67 return strncat(ns
, s
, n
);
70 /* called from expand.h:XcheckN() to grow buffer */
72 Xcheck_grow_(XString
*xsp
, const char *xp
, unsigned more
)
74 const char *old_beg
= xsp
->beg
;
76 xsp
->len
+= more
> xsp
->len
? more
: xsp
->len
;
77 xsp
->beg
= aresize(xsp
->beg
, xsp
->len
+ 8, xsp
->areap
);
78 xsp
->end
= xsp
->beg
+ xsp
->len
;
79 return xsp
->beg
+ (xp
- old_beg
);
82 const struct posh_option options
[] = {
83 /* Special cases (see parse_args()): -o.
84 * Options are sorted by their longnames - the order of these
85 * entries MUST match the order of sh_flag F* enumerations in sh.h.
87 { "allexport", 'a', OF_ANY
},
89 { "braceexpand", 0, OF_ANY
}, /* non-standard */
91 { (char *) 0, 'c', OF_CMDLINE
},
93 { "emacs", 0, OF_ANY
},
95 { "errexit", 'e', OF_ANY
},
97 { "gmacs", 0, OF_ANY
},
99 { "ignoreeof", 0, OF_ANY
},
100 { "interactive",'i', OF_CMDLINE
},
101 { "login", 'l', OF_CMDLINE
},
103 { "monitor", 'm', OF_ANY
},
105 { (char *) 0, 'm', 0 }, /* so FMONITOR not ifdef'd */
107 { "noclobber", 'C', OF_ANY
},
108 { "noexec", 'n', OF_ANY
},
109 { "noglob", 'f', OF_ANY
},
110 { "nohup", 0, OF_ANY
},
111 { "nolog", 0, OF_ANY
}, /* no effect */
113 { "notify", 'b', OF_ANY
},
115 { "nounset", 'u', OF_ANY
},
116 #ifdef SILLY_FEATURES
117 { "posix", 0, OF_ANY
}, /* non-standard */
118 #endif /* SILLY_FEATURES */
119 { "privileged", 'p', OF_ANY
},
120 { "stdin", 's', OF_CMDLINE
}, /* pseudo non-standard */
121 #ifdef SILLY_FEATURES
122 { "trackall", 'h', OF_ANY
},
123 #endif /* SILLY_FEATURES */
124 { "verbose", 'v', OF_ANY
},
127 { "viraw", 0, OF_ANY
}, /* no effect */
128 { "vi-show8", 0, OF_ANY
}, /* non-standard */
129 { "vi-tabcomplete", 0, OF_ANY
}, /* non-standard */
130 { "vi-esccomplete", 0, OF_ANY
}, /* non-standard */
132 { "xtrace", 'x', OF_ANY
},
133 /* Anonymous flags: used internally by shell only
134 * (not visible to user)
136 { NULL
, 0, OF_INTERNAL
}, /* FTALKING_I */
140 * translate -o option into F* constant (also used for test -o option)
143 option(const char *n
)
147 for (i
= 0; i
< NELEM(options
); i
++)
148 if (options
[i
].name
&& strcmp(options
[i
].name
, n
) == 0)
154 struct options_info
{
155 unsigned int opt_width
;
159 } opts
[NELEM(options
)];
162 static char *options_fmt_entry
ARGS((void *arg
, int i
, char *buf
, int buflen
));
163 static void printoptions
ARGS((int verbose
));
165 /* format a single select menu item */
167 options_fmt_entry(arg
, i
, buf
, buflen
)
173 struct options_info
*oi
= (struct options_info
*) arg
;
175 snprintf(buf
, buflen
, "%-*s %s",
176 oi
->opt_width
, oi
->opts
[i
].name
,
177 Flag(oi
->opts
[i
].flag
) ? "on" : "off");
182 printoptions(verbose
)
188 struct options_info oi
;
191 /* verbose version */
192 shprintf("Current option settings\n");
194 for (i
= n
= oi
.opt_width
= 0; i
< NELEM(options
); i
++)
195 if (options
[i
].name
) {
196 len
= strlen(options
[i
].name
);
197 oi
.opts
[n
].name
= options
[i
].name
;
198 oi
.opts
[n
++].flag
= i
;
199 if (len
> oi
.opt_width
)
202 print_columns(shl_stdout
, n
, options_fmt_entry
, &oi
,
205 /* short version ala ksh93 */
207 for (i
= 0; i
< NELEM(options
); i
++)
208 if (Flag(i
) && options
[i
].name
)
209 shprintf(" -o %s", options
[i
].name
);
218 char m
[(int) FNFLAGS
+ 1];
221 for (i
= 0; i
< NELEM(options
); i
++)
222 if (options
[i
].c
&& Flag(i
))
223 *cp
++ = options
[i
].c
;
225 return str_save(m
, ATEMP
);
228 /* change a Flag(*) value; takes care of special actions */
230 change_flag(f
, what
, newval
)
231 enum sh_flag f
; /* flag to change */
232 int what
; /* what is changing the flag (command line vs set) */
241 if (what
!= OF_CMDLINE
&& newval
!= oldval
)
251 || f
== FEMACS
|| f
== FGMACS
260 Flag(FEMACS
) = Flag(FGMACS
) = 0;
266 /* Turning off -p? */
267 if (f
== FPRIVILEGED
&& oldval
&& !newval
) {
271 setuid(ksheuid
= getuid());
275 /* Changing interactive flag? */
277 if ((what
== OF_CMDLINE
|| what
== OF_SET
) && procpid
== kshpid
)
278 Flag(FTALKING_I
) = newval
;
282 /* parse command line & set command arguments. returns the index of
283 * non-option arguments, -1 if there is an error.
286 parse_args(argv
, what
, setargsp
)
288 int what
; /* OF_CMDLINE or OF_SET */
291 static char cmd_opts
[NELEM(options
) + 3]; /* o:\0 */
292 static char set_opts
[NELEM(options
) + 3]; /* o;\0 */
294 char *array
= (char *) 0;
299 /* First call? Build option strings... */
300 if (cmd_opts
[0] == '\0') {
303 strcpy(cmd_opts
, "o:"); /* see cmd_opts[] declaration */
304 p
= cmd_opts
+ strlen(cmd_opts
);
305 strcpy(set_opts
, "o;"); /* see set_opts[] declaration */
306 q
= set_opts
+ strlen(set_opts
);
307 for (k
= 0; k
< NELEM(options
); k
++) {
309 if (options
[k
].flags
& OF_CMDLINE
)
311 if (options
[k
].flags
& OF_SET
)
319 if (what
== OF_CMDLINE
) {
321 /* Set FLOGIN before parsing options so user can clear
324 Flag(FLOGIN
) = (argv
[0][0] == '-'
325 || ((p
= ksh_strrchr_dirsep(argv
[0]))
330 ksh_getopt_reset(&go
, GF_ERROR
|GF_PLUSOPT
);
331 while ((optc
= ksh_getopt(argv
, &go
, opts
)) != EOF
) {
332 set
= (go
.info
& GI_PLUS
) ? 0 : 1;
335 if (go
.optarg
== (char *) 0) {
336 /* lone -o: print options
338 * Note that on the command line, -o requires
339 * an option (ie, can't get here if what is
345 j
= option(go
.optarg
);
346 if (j
>= 0 && set
== Flag(j
))
347 /* Don't check the context if the flag
348 * isn't changing - makes "set -o interactive"
349 * work if you're already interactive. Needed
350 * if the output of "set +o" is to be used.
353 else if (j
>= 0 && (options
[j
].flags
& what
))
354 change_flag((enum sh_flag
) j
, what
, set
);
356 bi_errorf("%s: bad option", go
.optarg
);
365 for (k
= 0; k
< NELEM(options
); k
++)
366 if (optc
== options
[k
].c
367 && (what
& options
[k
].flags
))
369 change_flag((enum sh_flag
) k
, what
,
373 if (k
== NELEM(options
)) {
374 internal_errorf(1, "parse_args: `%c'", optc
);
375 return -1; /* not reached */
379 if (!(go
.info
& GI_MINUSMINUS
) && argv
[go
.optind
]
380 && (argv
[go
.optind
][0] == '-' || argv
[go
.optind
][0] == '+')
381 && argv
[go
.optind
][1] == '\0')
383 /* set skips lone - or + option */
387 /* -- means set $#/$* even if there are no arguments */
388 *setargsp
= ((go
.info
& GI_MINUSMINUS
)
394 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
396 getn(const char *as
, int *ai
)
400 *ai
= strtol(as
, &ep
, 10);
402 if (!(*ep
== '\0' && *as
!= '\0'))
407 /* getn() that prints error */
413 int rv
= getn(as
, ai
);
416 bi_errorf("%s: bad number", as
);
420 /* -------- gmatch.c -------- */
423 * int gmatch(string, pattern)
424 * char *string, *pattern;
426 * Match a pattern as in sh(1).
427 * pattern character are prefixed with MAGIC by expand.
431 gmatchx(const char *s
, const char *p
, int isfile
)
435 if (s
== NULL
|| p
== NULL
)
439 /* isfile is false iff no syntax check has been done on
440 * the pattern. If check fails, just to a strcmp().
442 if (!isfile
&& !has_globbing(p
, pe
)) {
443 size_t len
= pe
- p
+ 1;
445 char *t
= len
<= sizeof(tbuf
) ? tbuf
:
446 (char *) alloc(len
, ATEMP
);
448 return (!strcmp(t
, s
));
450 return (do_gmatch((const unsigned char *) s
, (const unsigned char *) se
,
451 (const unsigned char *) p
, (const unsigned char *) pe
));
454 /* Returns if p is a syntacticly correct globbing pattern, false
455 * if it contains no pattern characters or if there is a syntax error.
457 * - [ with no closing ]
458 * - imbalanced $(...) expression
459 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
463 if dest given, copy to dst
465 - if magic && (no globbing || syntax error)
471 has_globbing(const char *xp
, const char *xpe
)
473 const unsigned char *p
= (const unsigned char *) xp
;
474 const unsigned char *pe
= (const unsigned char *) xpe
;
476 int nest
= 0, bnest
= 0;
478 int in_bracket
= 0; /* inside [...] */
480 for (; p
< pe
; p
++) {
483 if ((c
= *++p
) == '*' || c
== '?')
489 if (ISMAGIC(p
[1]) && p
[2] == NOT
)
491 if (ISMAGIC(p
[1]) && p
[2] == ']')
494 /* XXX Do we need to check ranges here? POSIX Q */
495 } else if (c
== ']') {
497 if (bnest
) /* [a*(b]) */
501 } else if ((c
& 0x80) && strchr("*? ", c
& 0x7f)) {
507 } else if (c
== '|') {
508 if (in_bracket
&& !bnest
) /* *(a[foo|bar]) */
510 } else if (c
== /*(*/ ')') {
512 if (!bnest
--) /* *(a[b)c] */
517 /* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
518 MAGIC-{, MAGIC-,, MAGIC-} */
520 return (saw_glob
&& !in_bracket
&& !nest
);
523 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
525 do_gmatch(const unsigned char *s
, const unsigned char *se
,
526 const unsigned char *p
, const unsigned char *pe
)
529 const unsigned char *prest
, *psub
, *pnext
;
530 const unsigned char *srest
;
532 if (s
== NULL
|| p
== NULL
)
536 sc
= s
< se
? *s
: '\0';
545 if (sc
== 0 || (p
= cclass(p
, sc
)) == NULL
)
559 if (do_gmatch(s
, se
, p
, pe
))
565 * [*+?@!](pattern|pattern|..)
566 * This is also needed for ${..%..}, etc.
568 case 0x80|'+': /* matches one or more times */
569 case 0x80|'*': /* matches zero or more times */
570 if (!(prest
= pat_scan(p
, pe
, 0)))
573 /* take care of zero matches */
574 if (p
[-1] == (0x80 | '*') &&
575 do_gmatch(s
, se
, prest
, pe
))
577 for (psub
= p
; ; psub
= pnext
) {
578 pnext
= pat_scan(psub
, pe
, 1);
579 for (srest
= s
; srest
<= se
; srest
++) {
580 if (do_gmatch(s
, srest
, psub
, pnext
- 2) &&
581 (do_gmatch(srest
, se
, prest
, pe
) ||
582 (s
!= srest
&& do_gmatch(srest
,
591 case 0x80|'?': /* matches zero or once */
592 case 0x80|'@': /* matches one of the patterns */
593 case 0x80|' ': /* simile for @ */
594 if (!(prest
= pat_scan(p
, pe
, 0)))
597 /* Take care of zero matches */
598 if (p
[-1] == (0x80 | '?') &&
599 do_gmatch(s
, se
, prest
, pe
))
601 for (psub
= p
; ; psub
= pnext
) {
602 pnext
= pat_scan(psub
, pe
, 1);
603 srest
= prest
== pe
? se
: s
;
604 for (; srest
<= se
; srest
++) {
605 if (do_gmatch(s
, srest
, psub
, pnext
- 2) &&
606 do_gmatch(srest
, se
, prest
, pe
))
614 case 0x80|'!': /* matches none of the patterns */
615 if (!(prest
= pat_scan(p
, pe
, 0)))
618 for (srest
= s
; srest
<= se
; srest
++) {
621 for (psub
= p
; ; psub
= pnext
) {
622 pnext
= pat_scan(psub
, pe
, 1);
623 if (do_gmatch(s
, srest
, psub
,
632 do_gmatch(srest
, se
, prest
, pe
))
646 static const unsigned char *
647 cclass(const unsigned char *p
, int sub
)
649 int c
, d
, not, found
= 0;
650 const unsigned char *orig_p
= p
;
652 if ((not = (ISMAGIC(*p
) && *++p
== NOT
)))
658 if ((c
& 0x80) && !ISMAGIC(c
)) {
659 c
&= 0x7f;/* extended pattern matching: *+?@! */
660 /* XXX the ( char isn't handled as part of [] */
661 if (c
== ' ') /* simile for @: plain (..) */
666 /* No closing ] - act as if the opening [ was quoted */
667 return sub
== '[' ? orig_p
: NULL
;
668 if (ISMAGIC(p
[0]) && p
[1] == '-' &&
669 (!ISMAGIC(p
[2]) || p
[3] != ']')) {
674 if ((d
& 0x80) && !ISMAGIC(d
))
677 /* POSIX says this is an invalid expression */
682 if (c
== sub
|| (c
<= sub
&& sub
<= d
))
684 } while (!(ISMAGIC(p
[0]) && p
[1] == ']'));
686 return (found
!= not) ? p
+2 : NULL
;
689 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
690 const unsigned char *
691 pat_scan(const unsigned char *p
, const unsigned char *pe
, int match_sep
)
695 for (; p
< pe
; p
++) {
698 if ((*++p
== /*(*/ ')' && nest
-- == 0) ||
699 (*p
== '|' && match_sep
&& nest
== 0))
701 if ((*p
& 0x80) && strchr("*+?@! ", *p
& 0x7f))
708 xstrcmp(const void *p1
, const void *p2
)
710 return (strcmp(*(char * const *)p1
, *(char * const *)p2
));
713 /* Initialise a Getopt structure */
715 ksh_getopt_reset(LameGetopt
*go
, int flags
)
726 /* getopt() used for shell built-in commands, the getopts command, and
727 * command line options.
728 * A leading ':' in options means don't print errors, instead return '?'
729 * or ':' and set go->optarg to the offending option character.
730 * If GF_ERROR is set (and option doesn't start with :), errors result in
731 * a call to bi_errorf().
733 * Non-standard features:
734 * - ';' is like ':' in options, except the argument is optional
735 * (if it isn't present, optarg is set to 0).
737 * - ',' is like ':' in options, except the argument always immediately
738 * follows the option character (optarg is set to the null string if
739 * the option is missing).
740 * Used for 'read -u2', 'print -u2' and fc -40.
741 * - '#' is like ':' in options, expect that the argument is optional
742 * and must start with a digit. If the argument doesn't start with a
743 * digit, it is assumed to be missing and normal option processing
744 * continues (optarg is set to 0 if the option is missing).
745 * Used for 'typeset -LZ4'.
746 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
747 * option starting with + is accepted, the GI_PLUS flag will be set
751 ksh_getopt(argv
, go
, options
)
759 if (go
->p
== 0 || (c
= argv
[go
->optind
- 1][go
->p
]) == '\0') {
760 char *arg
= argv
[go
->optind
], flag
= arg
? *arg
: '\0';
763 if (flag
== '-' && arg
[1] == '-' && arg
[2] == '\0') {
766 go
->info
|= GI_MINUSMINUS
;
769 if (arg
== (char *) 0
770 || ((flag
!= '-' ) /* neither a - nor a + (if + allowed) */
771 && (!(go
->flags
& GF_PLUSOPT
) || flag
!= '+'))
772 || (c
= arg
[1]) == '\0')
778 go
->info
&= ~(GI_MINUS
|GI_PLUS
);
779 go
->info
|= flag
== '-' ? GI_MINUS
: GI_PLUS
;
782 if (c
== '?' || c
== ':' || c
== ';'
783 || !(o
= strchr(options
, c
)))
785 if (options
[0] == ':') {
787 go
->optarg
= go
->buf
;
789 warningf(TRUE
, "%s%s-%c: unknown option",
790 (go
->flags
& GF_NONAME
) ? "" : argv
[0],
791 (go
->flags
& GF_NONAME
) ? "" : ": ", c
);
792 if (go
->flags
& GF_ERROR
)
797 /* : means argument must be present, may be part of option argument
798 * or the next argument
799 * ; same as : but argument may be missing
800 * , means argument is part of option argument, and may be null.
802 if (*++o
== ':' || *o
== ';') {
803 if (argv
[go
->optind
- 1][go
->p
])
804 go
->optarg
= argv
[go
->optind
- 1] + go
->p
;
805 else if (argv
[go
->optind
])
806 go
->optarg
= argv
[go
->optind
++];
808 go
->optarg
= (char *) 0;
810 if (options
[0] == ':') {
812 go
->optarg
= go
->buf
;
815 warningf(TRUE
, "%s%s-`%c' requires argument",
816 (go
->flags
& GF_NONAME
) ? "" : argv
[0],
817 (go
->flags
& GF_NONAME
) ? "" : ": ", c
);
818 if (go
->flags
& GF_ERROR
)
827 /* print variable/alias value using necessary quotes
828 * (POSIX says they should be suitable for re-entry...)
829 * No trailing newline is printed.
832 print_value_quoted(s
)
838 /* Test if any quotes are needed */
840 if (ctype(*p
, C_QUOTE
))
846 for (p
= s
; *p
; p
++) {
848 shprintf("'\\'" + 1 - inquote
);
855 shf_putc(*p
, shl_stdout
);
862 /* Print things in columns and rows - func() is called to format the ith
866 print_columns(shf
, n
, func
, arg
, max_width
)
869 char *(*func
) ARGS((void *, int, char *, int));
873 char *str
= (char *) alloc(max_width
+ 1, ATEMP
);
879 /* max_width + 1 for the space. Note that no space
880 * is printed after the last column to avoid problems
881 * with terminals that have auto-wrap.
883 cols
= x_cols
/ (max_width
+ 1);
886 rows
= (n
+ cols
- 1) / cols
;
887 if (n
&& cols
> rows
) {
896 nspace
= (x_cols
- max_width
* cols
) / cols
;
899 for (r
= 0; r
< rows
; r
++) {
900 for (c
= 0; c
< cols
; c
++) {
903 shf_fprintf(shf
, "%-*s",
905 (*func
)(arg
, i
, str
, max_width
+ 1));
907 shf_fprintf(shf
, "%*s", nspace
, null
);
910 shf_putchar('\n', shf
);
915 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
917 strip_nuls(buf
, nbytes
)
923 /* nbytes check because some systems (older freebsd's) have a buggy
926 if (nbytes
&& (dst
= memchr(buf
, '\0', nbytes
))) {
927 char *end
= buf
+ nbytes
;
930 for (p
= dst
; p
< end
; p
= q
) {
931 /* skip a block of nulls */
932 while (++p
< end
&& *p
== '\0')
934 /* find end of non-null block */
935 if (!(q
= memchr(p
, '\0', end
- p
)))
937 memmove(dst
, p
, q
- p
);
946 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
950 str_zcpy(dst
, src
, dsize
)
956 int len
= strlen(src
);
960 memcpy(dst
, src
, len
);
966 /* Like read(2), but if read fails due to non-blocking flag, resets flag
970 blocking_read(fd
, buf
, nbytes
)
978 while ((ret
= read(fd
, buf
, nbytes
)) < 0) {
979 if (!tried_reset
&& (errno
== EAGAIN
981 || errno
== EWOULDBLOCK
982 #endif /* EWOULDBLOCK */
986 if (reset_nonblock(fd
) > 0) {
997 /* Reset the non-blocking flag on the specified file descriptor.
998 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1008 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1010 /* With luck, the C compiler will reduce this to a constant */
1013 blocking_flags
|= O_NONBLOCK
;
1014 #endif /* O_NONBLOCK */
1016 blocking_flags
|= O_NDELAY
;
1017 #else /* O_NDELAY */
1019 blocking_flags
|= FNDELAY
; /* hope this exists... */
1020 # endif /* O_NONBLOCK */
1021 #endif /* O_NDELAY */
1022 if (!(flags
& blocking_flags
))
1024 flags
&= ~blocking_flags
;
1025 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1031 #ifdef HAVE_SYS_PARAM_H
1032 # include <sys/param.h>
1033 #endif /* HAVE_SYS_PARAM_H */
1035 # define MAXPATHLEN PATH
1036 #endif /* MAXPATHLEN */