Home | History | Annotate | Line # | Download | only in ksh
misc.c revision 1.16
      1 /*	$NetBSD: misc.c,v 1.16 2017/04/30 17:34:29 christos Exp $	*/
      2 
      3 /*
      4  * Miscellaneous functions
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: misc.c,v 1.16 2017/04/30 17:34:29 christos Exp $");
     10 #endif
     11 
     12 
     13 #include "sh.h"
     14 #include <ctype.h>	/* for FILECHCONV */
     15 #ifdef HAVE_LIMITS_H
     16 # include <limits.h>
     17 #endif
     18 
     19 #ifndef UCHAR_MAX
     20 # define UCHAR_MAX	0xFF
     21 #endif
     22 
     23 short ctypes [UCHAR_MAX+1];	/* type bits for unsigned char */
     24 
     25 static int	do_gmatch ARGS((const unsigned char *s, const unsigned char *p,
     26 			const unsigned char *se, const unsigned char *pe,
     27 			int isfile));
     28 static const unsigned char *cclass ARGS((const unsigned char *p, int sub));
     29 
     30 /*
     31  * Fast character classes
     32  */
     33 void
     34 setctypes(s, t)
     35 	register const char *s;
     36 	register int t;
     37 {
     38 	register int i;
     39 
     40 	if (t & C_IFS) {
     41 		for (i = 0; i < UCHAR_MAX+1; i++)
     42 			ctypes[i] &= ~C_IFS;
     43 		ctypes[0] |= C_IFS; /* include \0 in C_IFS */
     44 	}
     45 	while (*s != 0)
     46 		ctypes[(unsigned char) *s++] |= t;
     47 }
     48 
     49 void
     50 initctypes()
     51 {
     52 	register int c;
     53 
     54 	for (c = 'a'; c <= 'z'; c++)
     55 		ctypes[c] |= C_ALPHA;
     56 	for (c = 'A'; c <= 'Z'; c++)
     57 		ctypes[c] |= C_ALPHA;
     58 	ctypes['_'] |= C_ALPHA;
     59 	setctypes("0123456789", C_DIGIT);
     60 	setctypes(" \t\n|&;<>()", C_LEX1); /* \0 added automatically */
     61 	setctypes("*@#!$-?", C_VAR1);
     62 	setctypes(" \t\n", C_IFSWS);
     63 	setctypes("=-+?", C_SUBOP1);
     64 	setctypes("#%", C_SUBOP2);
     65 	setctypes(" \n\t\"#$&'()*;<>?[\\`|", C_QUOTE);
     66 }
     67 
     68 /* convert unsigned long to base N string */
     69 
     70 char *
     71 ulton(n, base)
     72 	register unsigned long n;
     73 	int base;
     74 {
     75 	register char *p;
     76 	static char buf [20];
     77 
     78 	p = &buf[sizeof(buf)];
     79 	*--p = '\0';
     80 	do {
     81 		*--p = "0123456789ABCDEF"[n%base];
     82 		n /= base;
     83 	} while (n != 0);
     84 	return p;
     85 }
     86 
     87 char *
     88 str_save(s, ap)
     89 	register const char *s;
     90 	Area *ap;
     91 {
     92 	size_t len;
     93 	char *p;
     94 
     95 	if (!s)
     96 		return NULL;
     97 	len = strlen(s)+1;
     98 	p = alloc(len, ap);
     99 	strlcpy(p, s, len);
    100 	return (p);
    101 }
    102 
    103 /* Allocate a string of size n+1 and copy upto n characters from the possibly
    104  * null terminated string s into it.  Always returns a null terminated string
    105  * (unless n < 0).
    106  */
    107 char *
    108 str_nsave(s, n, ap)
    109 	register const char *s;
    110 	int n;
    111 	Area *ap;
    112 {
    113 	char *ns;
    114 
    115 	if (n < 0)
    116 		return 0;
    117 	ns = alloc(n + 1, ap);
    118 	ns[0] = '\0';
    119 	return strncat(ns, s, n);
    120 }
    121 
    122 /* called from expand.h:XcheckN() to grow buffer */
    123 char *
    124 Xcheck_grow_(xsp, xp, more)
    125 	XString *xsp;
    126 	char *xp;
    127 	int more;
    128 {
    129 	char *old_beg = xsp->beg;
    130 
    131 	xsp->len += (size_t)more > xsp->len ? (size_t)more : xsp->len;
    132 	xsp->beg = aresize(xsp->beg, xsp->len + 8, xsp->areap);
    133 	xsp->end = xsp->beg + xsp->len;
    134 	return xsp->beg + (xp - old_beg);
    135 }
    136 
    137 const struct option goptions[] = {
    138 	/* Special cases (see parse_args()): -A, -o, -s.
    139 	 * Options are sorted by their longnames - the order of these
    140 	 * entries MUST match the order of sh_flag F* enumerations in sh.h.
    141 	 */
    142 	{ "allexport",	'a',		OF_ANY },
    143 #ifdef BRACE_EXPAND
    144 	{ "braceexpand",  0,		OF_ANY }, /* non-standard */
    145 #endif
    146 	{ "bgnice",	  0,		OF_ANY },
    147 	{ (char *) 0, 	'c',	    OF_CMDLINE },
    148 #ifdef EMACS
    149 	{ "emacs",	  0,		OF_ANY },
    150 	{ "emacs-usemeta",  0,		OF_ANY }, /* non-standard */
    151 #endif
    152 	{ "errexit",	'e',		OF_ANY },
    153 #ifdef EMACS
    154 	{ "gmacs",	  0,		OF_ANY },
    155 #endif
    156 	{ "ignoreeof",	  0,		OF_ANY },
    157 	{ "interactive",'i',	    OF_CMDLINE },
    158 	{ "keyword",	'k',		OF_ANY },
    159 	{ "login",	'l',	    OF_CMDLINE },
    160 	{ "markdirs",	'X',		OF_ANY },
    161 #ifdef JOBS
    162 	{ "monitor",	'm',		OF_ANY },
    163 #else /* JOBS */
    164 	{ (char *) 0,	'm',		     0 }, /* so FMONITOR not ifdef'd */
    165 #endif /* JOBS */
    166 	{ "noclobber",	'C',		OF_ANY },
    167 	{ "noexec",	'n',		OF_ANY },
    168 	{ "noglob",	'f',		OF_ANY },
    169 	{ "nohup",	  0,		OF_ANY },
    170 	{ "nolog",	  0,		OF_ANY }, /* no effect */
    171 #ifdef	JOBS
    172 	{ "notify",	'b',		OF_ANY },
    173 #endif	/* JOBS */
    174 	{ "nounset",	'u',		OF_ANY },
    175 	{ "physical",	  0,		OF_ANY }, /* non-standard */
    176 	{ "posix",	  0,		OF_ANY }, /* non-standard */
    177 	{ "privileged",	'p',		OF_ANY },
    178 	{ "restricted",	'r',	    OF_CMDLINE },
    179 	{ "stdin",	's',	    OF_CMDLINE }, /* pseudo non-standard */
    180 	{ "trackall",	'h',		OF_ANY },
    181 	{ "verbose",	'v',		OF_ANY },
    182 #ifdef VI
    183 	{ "vi",		  0,		OF_ANY },
    184 	{ "viraw",	  0,		OF_ANY }, /* no effect */
    185 	{ "vi-show8",	  0,		OF_ANY }, /* non-standard */
    186 	{ "vi-tabcomplete",  0, 	OF_ANY }, /* non-standard */
    187 	{ "vi-esccomplete",  0, 	OF_ANY }, /* non-standard */
    188 #endif
    189 	{ "xtrace",	'x',		OF_ANY },
    190 	/* Anonymous flags: used internally by shell only
    191 	 * (not visible to user)
    192 	 */
    193 	{ (char *) 0,	0,		OF_INTERNAL }, /* FTALKING_I */
    194 };
    195 
    196 /*
    197  * translate -o option into F* constant (also used for test -o option)
    198  */
    199 int
    200 option(n)
    201 	const char *n;
    202 {
    203 	int i;
    204 
    205 	for (i = 0; i < (int)NELEM(goptions); i++)
    206 		if (goptions[i].name && strcmp(goptions[i].name, n) == 0)
    207 			return i;
    208 
    209 	return -1;
    210 }
    211 
    212 struct options_info {
    213 	int opt_width;
    214 	struct {
    215 		const char *name;
    216 		int	flag;
    217 	} opts[NELEM(goptions)];
    218 };
    219 
    220 static char *options_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
    221 static void printoptions ARGS((int verbose));
    222 
    223 /* format a single select menu item */
    224 static char *
    225 options_fmt_entry(arg, i, buf, buflen)
    226 	void *arg;
    227 	int i;
    228 	char *buf;
    229 	int buflen;
    230 {
    231 	struct options_info *oi = (struct options_info *) arg;
    232 
    233 	shf_snprintf(buf, buflen, "%-*s %s",
    234 		oi->opt_width, oi->opts[i].name,
    235 		Flag(oi->opts[i].flag) ? "on" : "off");
    236 	return buf;
    237 }
    238 
    239 static void
    240 printoptions(verbose)
    241 	int verbose;
    242 {
    243 	int i;
    244 
    245 	if (verbose) {
    246 		struct options_info oi;
    247 		int n, len;
    248 
    249 		/* verbose version */
    250 		shprintf("Current option settings\n");
    251 
    252 		for (i = n = oi.opt_width = 0; i < (int)NELEM(goptions); i++)
    253 			if (goptions[i].name) {
    254 				len = strlen(goptions[i].name);
    255 				oi.opts[n].name = goptions[i].name;
    256 				oi.opts[n++].flag = i;
    257 				if (len > oi.opt_width)
    258 					oi.opt_width = len;
    259 			}
    260 		print_columns(shl_stdout, n, options_fmt_entry, &oi,
    261 			      oi.opt_width + 5, 1);
    262 	} else {
    263 		/* short version ala ksh93 */
    264 		shprintf("set");
    265 		for (i = 0; i < (int)NELEM(goptions); i++)
    266 			if (Flag(i) && goptions[i].name)
    267 				shprintf(" -o %s", goptions[i].name);
    268 		shprintf("%s", newline);
    269 	}
    270 }
    271 
    272 char *
    273 getoptions()
    274 {
    275 	size_t i;
    276 	char m[(int) FNFLAGS + 1];
    277 	register char *cp = m;
    278 
    279 	for (i = 0; i < NELEM(goptions); i++)
    280 		if (goptions[i].c && Flag(i))
    281 			*cp++ = goptions[i].c;
    282 	*cp = 0;
    283 	return str_save(m, ATEMP);
    284 }
    285 
    286 /* change a Flag(*) value; takes care of special actions */
    287 void
    288 change_flag(f, what, newval)
    289 	enum sh_flag f;	/* flag to change */
    290 	int what;	/* what is changing the flag (command line vs set) */
    291 	int newval;
    292 {
    293 	int oldval;
    294 
    295 	oldval = Flag(f);
    296 	Flag(f) = newval;
    297 #ifdef JOBS
    298 	if (f == FMONITOR) {
    299 		if (what != OF_CMDLINE && newval != oldval)
    300 			j_change();
    301 	} else
    302 #endif /* JOBS */
    303 #ifdef EDIT
    304 	if (0
    305 # ifdef VI
    306 	    || f == FVI
    307 # endif /* VI */
    308 # ifdef EMACS
    309 	    || f == FEMACS || f == FGMACS
    310 # endif /* EMACS */
    311 	   )
    312 	{
    313 		if (newval) {
    314 # ifdef VI
    315 			Flag(FVI) = 0;
    316 # endif /* VI */
    317 # ifdef EMACS
    318 			Flag(FEMACS) = Flag(FGMACS) = 0;
    319 # endif /* EMACS */
    320 			Flag(f) = newval;
    321 		}
    322 	} else
    323 #endif /* EDIT */
    324 	/* Turning off -p? */
    325 	if (f == FPRIVILEGED && oldval && !newval) {
    326 #ifdef OS2
    327 		;
    328 #else /* OS2 */
    329 		seteuid(ksheuid = getuid());
    330 		setuid(ksheuid);
    331 		setegid(getgid());
    332 		setgid(getgid());
    333 #endif /* OS2 */
    334 	} else if (f == FPOSIX && newval) {
    335 #ifdef BRACE_EXPAND
    336 		Flag(FBRACEEXPAND) = 0
    337 #endif /* BRACE_EXPAND */
    338 		;
    339 	}
    340 	/* Changing interactive flag? */
    341 	if (f == FTALKING) {
    342 		if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
    343 			Flag(FTALKING_I) = newval;
    344 	}
    345 }
    346 
    347 /* parse command line & set command arguments.  returns the index of
    348  * non-option arguments, -1 if there is an error.
    349  */
    350 int
    351 parse_args(argv, what, setargsp)
    352 	char **argv;
    353 	int	what;		/* OF_CMDLINE or OF_SET */
    354 	int	*setargsp;
    355 {
    356 	static char cmd_opts[NELEM(goptions) + 3]; /* o:\0 */
    357 	static char set_opts[NELEM(goptions) + 5]; /* Ao;s\0 */
    358 	char *opts;
    359 	char *array = (char *) 0;
    360 	Getopt go;
    361 	int i, optc, set, sortargs = 0, arrayset = 0;
    362 
    363 	/* First call?  Build option strings... */
    364 	if (cmd_opts[0] == '\0') {
    365 		char *p, *q;
    366 
    367 		/* see cmd_opts[] declaration */
    368 		strlcpy(cmd_opts, "o:", sizeof cmd_opts);
    369 		p = cmd_opts + strlen(cmd_opts);
    370 		/* see set_opts[] declaration */
    371 		strlcpy(set_opts, "A:o;s", sizeof set_opts);
    372 		q = set_opts + strlen(set_opts);
    373 		for (i = 0; i < (int)NELEM(goptions); i++) {
    374 			if (goptions[i].c) {
    375 				if (goptions[i].flags & OF_CMDLINE)
    376 					*p++ = goptions[i].c;
    377 				if (goptions[i].flags & OF_SET)
    378 					*q++ = goptions[i].c;
    379 			}
    380 		}
    381 		*p = '\0';
    382 		*q = '\0';
    383 	}
    384 
    385 	if (what == OF_CMDLINE) {
    386 		char *p;
    387 		/* Set FLOGIN before parsing options so user can clear
    388 		 * flag using +l.
    389 		 */
    390 		Flag(FLOGIN) = (argv[0][0] == '-'
    391 				|| ((p = ksh_strrchr_dirsep(argv[0]))
    392 				     && *++p == '-'));
    393 		opts = cmd_opts;
    394 	} else
    395 		opts = set_opts;
    396 	ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
    397 	while ((optc = ksh_getopt(argv, &go, opts)) != EOF) {
    398 		set = (go.info & GI_PLUS) ? 0 : 1;
    399 		switch (optc) {
    400 		  case 'A':
    401 			arrayset = set ? 1 : -1;
    402 			array = go.optarg;
    403 			break;
    404 
    405 		  case 'o':
    406 			if (go.optarg == (char *) 0) {
    407 				/* lone -o: print options
    408 				 *
    409 				 * Note that on the command line, -o requires
    410 				 * an option (ie, can't get here if what is
    411 				 * OF_CMDLINE).
    412 				 */
    413 				printoptions(set);
    414 				break;
    415 			}
    416 			i = option(go.optarg);
    417 			if (i >= 0 && set == Flag(i))
    418 				/* Don't check the context if the flag
    419 				 * isn't changing - makes "set -o interactive"
    420 				 * work if you're already interactive.  Needed
    421 				 * if the output of "set +o" is to be used.
    422 				 */
    423 				;
    424 			else if (i >= 0 && (goptions[i].flags & what))
    425 				change_flag((enum sh_flag) i, what, set);
    426 			else {
    427 				bi_errorf("%s: bad option", go.optarg);
    428 				return -1;
    429 			}
    430 			break;
    431 
    432 		  case '?':
    433 			return -1;
    434 
    435 		  default:
    436 			/* -s: sort positional params (at&t ksh stupidity) */
    437 			if (what == OF_SET && optc == 's') {
    438 				sortargs = 1;
    439 				break;
    440 			}
    441 			for (i = 0; i < (int)NELEM(goptions); i++)
    442 				if (optc == goptions[i].c
    443 				    && (what & goptions[i].flags))
    444 				{
    445 					change_flag((enum sh_flag) i, what,
    446 						    set);
    447 					break;
    448 				}
    449 			if (i == NELEM(goptions)) {
    450 				internal_errorf(1, "parse_args: `%c'", optc);
    451 				return -1; /* not reached */
    452 			}
    453 		}
    454 	}
    455 	if (!(go.info & GI_MINUSMINUS) && argv[go.optind]
    456 	    && (argv[go.optind][0] == '-' || argv[go.optind][0] == '+')
    457 	    && argv[go.optind][1] == '\0')
    458 	{
    459 		/* lone - clears -v and -x flags */
    460 		if (argv[go.optind][0] == '-' && !Flag(FPOSIX))
    461 			Flag(FVERBOSE) = Flag(FXTRACE) = 0;
    462 		/* set skips lone - or + option */
    463 		go.optind++;
    464 	}
    465 	if (setargsp)
    466 		/* -- means set $#/$* even if there are no arguments */
    467 		*setargsp = !arrayset && ((go.info & GI_MINUSMINUS)
    468 					  || argv[go.optind]);
    469 
    470 	if (arrayset && (!*array || *skip_varname(array, FALSE))) {
    471 		bi_errorf("%s: is not an identifier", array);
    472 		return -1;
    473 	}
    474 	if (sortargs) {
    475 		for (i = go.optind; argv[i]; i++)
    476 			;
    477 		qsortp((void **) &argv[go.optind], (size_t) (i - go.optind),
    478 			xstrcmp);
    479 	}
    480 	if (arrayset) {
    481 		set_array(array, arrayset, argv + go.optind);
    482 		for (; argv[go.optind]; go.optind++)
    483 			;
    484 	}
    485 
    486 	return go.optind;
    487 }
    488 
    489 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
    490 int
    491 getn(as, ai)
    492 	const char *as;
    493 	int *ai;
    494 {
    495 	char *p;
    496 	long n;
    497 
    498 	n = strtol(as, &p, 10);
    499 
    500 	if (!*as || *p || INT_MIN >= n || n >= INT_MAX)
    501 		return 0;
    502 
    503 	*ai = (int)n;
    504 	return 1;
    505 }
    506 
    507 /* getn() that prints error */
    508 int
    509 bi_getn(as, ai)
    510 	const char *as;
    511 	int *ai;
    512 {
    513 	int rv = getn(as, ai);
    514 
    515 	if (!rv)
    516 		bi_errorf("%s: bad number", as);
    517 	return rv;
    518 }
    519 
    520 /* -------- gmatch.c -------- */
    521 
    522 /*
    523  * int gmatch(string, pattern)
    524  * char *string, *pattern;
    525  *
    526  * Match a pattern as in sh(1).
    527  * pattern character are prefixed with MAGIC by expand.
    528  */
    529 
    530 int
    531 gmatch(s, p, isfile)
    532 	const char *s, *p;
    533 	int isfile;
    534 {
    535 	const char *se, *pe;
    536 
    537 	if (s == NULL || p == NULL)
    538 		return 0;
    539 	se = s + strlen(s);
    540 	pe = p + strlen(p);
    541 	/* isfile is false iff no syntax check has been done on
    542 	 * the pattern.  If check fails, just to a strcmp().
    543 	 */
    544 	if (!isfile && !has_globbing(p, pe)) {
    545 		int len = pe - p + 1;
    546 		char tbuf[64];
    547 		char *t = len <= (int)sizeof(tbuf) ? tbuf
    548 				: (char *) alloc(len, ATEMP);
    549 		debunk(t, p, len);
    550 		return !strcmp(t, s);
    551 	}
    552 	return do_gmatch((const unsigned char *) s, (const unsigned char *) se,
    553 			 (const unsigned char *) p, (const unsigned char *) pe,
    554 			 isfile);
    555 }
    556 
    557 /* Returns if p is a syntacticly correct globbing pattern, false
    558  * if it contains no pattern characters or if there is a syntax error.
    559  * Syntax errors are:
    560  *	- [ with no closing ]
    561  *	- imbalanced $(...) expression
    562  *	- [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
    563  */
    564 /*XXX
    565 - if no magic,
    566 	if dest given, copy to dst
    567 	return ?
    568 - if magic && (no globbing || syntax error)
    569 	debunk to dst
    570 	return ?
    571 - return ?
    572 */
    573 int
    574 has_globbing(xp, xpe)
    575 	const char *xp, *xpe;
    576 {
    577 	const unsigned char *p = (const unsigned char *) xp;
    578 	const unsigned char *pe = (const unsigned char *) xpe;
    579 	int c;
    580 	int nest = 0, bnest = 0;
    581 	int saw_glob = 0;
    582 	int in_bracket = 0; /* inside [...] */
    583 
    584 	for (; p < pe; p++) {
    585 		if (!ISMAGIC(*p))
    586 			continue;
    587 		if ((c = *++p) == '*' || c == '?')
    588 			saw_glob = 1;
    589 		else if (c == '[') {
    590 			if (!in_bracket) {
    591 				saw_glob = 1;
    592 				in_bracket = 1;
    593 				if (ISMAGIC(p[1]) && p[2] == NOT)
    594 					p += 2;
    595 				if (ISMAGIC(p[1]) && p[2] == ']')
    596 					p += 2;
    597 			}
    598 			/* XXX Do we need to check ranges here? POSIX Q */
    599 		} else if (c == ']') {
    600 			if (in_bracket) {
    601 				if (bnest)		/* [a*(b]) */
    602 					return 0;
    603 				in_bracket = 0;
    604 			}
    605 		} else if ((c & 0x80) && strchr("*+?@! ", c & 0x7f)) {
    606 			saw_glob = 1;
    607 			if (in_bracket)
    608 				bnest++;
    609 			else
    610 				nest++;
    611 		} else if (c == '|') {
    612 			if (in_bracket && !bnest)	/* *(a[foo|bar]) */
    613 				return 0;
    614 		} else if (c == /*(*/ ')') {
    615 			if (in_bracket) {
    616 				if (!bnest--)		/* *(a[b)c] */
    617 					return 0;
    618 			} else if (nest)
    619 				nest--;
    620 		}
    621 		/* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
    622 			 MAGIC-{, MAGIC-,, MAGIC-} */
    623 	}
    624 	return saw_glob && !in_bracket && !nest;
    625 }
    626 
    627 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
    628 static int
    629 do_gmatch(s, se, p, pe, isfile)
    630 	const unsigned char *s, *p;
    631 	const unsigned char *se, *pe;
    632 	int isfile;
    633 {
    634 	int sc, pc;
    635 	const unsigned char *prest, *psub, *pnext;
    636 	const unsigned char *srest;
    637 	const unsigned char *sNext, *pNext, *sStart;
    638 
    639 	if (s == NULL || p == NULL)
    640 		return 0;
    641 	sNext = sStart = s;
    642 	pNext = p;
    643 	while (p < pe || s < se) {
    644 		pc = *p;
    645 		sc = s < se ? *s : '\0';
    646 		if (isfile) {
    647 			sc = FILECHCONV((unsigned char)sc);
    648 			pc = FILECHCONV((unsigned char)pc);
    649 		}
    650 		if (!ISMAGIC(pc)) {
    651 			if (sc != pc)
    652 				goto backtrack;
    653 			p++;
    654 			s++;
    655 			continue;
    656 		} else
    657 			pc = *++p;
    658 		switch (pc) {
    659 		  case '[':
    660 			p++;
    661 			s++;
    662 			if (sc == 0 || (p = cclass(p, sc)) == NULL)
    663 				break;
    664 			continue;
    665 
    666 		  case '?':
    667 			if (sc == 0)
    668 				break;
    669 			p++;
    670 			s++;
    671 			continue;
    672 
    673 		  case '*':
    674 			pNext = p - 1;
    675 			sNext = s + 1;
    676 			p++;
    677 			continue;
    678 		  /*
    679 		   * [*+?@!](pattern|pattern|..)
    680 		   *
    681 		   * Not ifdef'd KSH as this is needed for ${..%..}, etc.
    682 		   */
    683 		  case 0x80|'+': /* matches one or more times */
    684 		  case 0x80|'*': /* matches zero or more times */
    685 			if (!(prest = pat_scan(++p, pe, 0)))
    686 				break;
    687 			s--;
    688 			/* take care of zero matches */
    689 			if (p[-1] == (0x80 | '*')
    690 			    && do_gmatch(s, se, prest, pe, isfile))
    691 				continue;
    692 			for (psub = p; ; psub = pnext) {
    693 				pnext = pat_scan(psub, pe, 1);
    694 				for (srest = s; srest <= se; srest++) {
    695 					if (do_gmatch(s, srest,
    696 						psub, pnext - 2, isfile)
    697 					    && (do_gmatch(srest, se,
    698 							  prest, pe, isfile)
    699 						|| (s != srest
    700 						    && do_gmatch(srest, se,
    701 							p - 2, pe, isfile))))
    702 						return 1;
    703 				}
    704 				if (pnext == prest)
    705 					break;
    706 			}
    707 			break;
    708 
    709 		  case 0x80|'?': /* matches zero or once */
    710 		  case 0x80|'@': /* matches one of the patterns */
    711 		  case 0x80|' ': /* simile for @ */
    712 			if (!(prest = pat_scan(++p, pe, 0)))
    713 				break;
    714 			s--;
    715 			/* Take care of zero matches */
    716 			if (p[-1] == (0x80 | '?')
    717 			    && do_gmatch(s, se, prest, pe, isfile))
    718 				continue;
    719 			for (psub = p; ; psub = pnext) {
    720 				pnext = pat_scan(psub, pe, 1);
    721 				srest = prest == pe ? se : s;
    722 				for (; srest <= se; srest++) {
    723 					if (do_gmatch(s, srest,
    724 						      psub, pnext - 2, isfile)
    725 					    && do_gmatch(srest, se,
    726 							 prest, pe, isfile))
    727 						continue;
    728 				}
    729 				if (pnext == prest)
    730 					break;
    731 			}
    732 			break;
    733 
    734 		  case 0x80|'!': /* matches none of the patterns */
    735 			if (!(prest = pat_scan(++p, pe, 0)))
    736 				break;
    737 			s--;
    738 			for (srest = s; srest <= se; srest++) {
    739 				int matched = 0;
    740 
    741 				for (psub = p; ; psub = pnext) {
    742 					pnext = pat_scan(psub, pe, 1);
    743 					if (do_gmatch(s, srest,
    744 						      psub, pnext - 2, isfile))
    745 					{
    746 						matched = 1;
    747 						break;
    748 					}
    749 					if (pnext == prest)
    750 						break;
    751 				}
    752 				if (!matched && do_gmatch(srest, se,
    753 							  prest, pe, isfile))
    754 					continue;
    755 			}
    756 			break;
    757 
    758 		  default:
    759 			if (sc != pc)
    760 				break;
    761 			p++;
    762 			s++;
    763 			continue;
    764 		}
    765 backtrack:	if (sNext != sStart && sNext <= se) {
    766 			p = pNext;
    767 			s = sNext;
    768 			continue;
    769 		}
    770 		return 0;
    771 	}
    772 	return 1;
    773 }
    774 
    775 static const unsigned char *
    776 cclass(p, sub)
    777 	const unsigned char *p;
    778 	register int sub;
    779 {
    780 	register int c, d, not, found = 0;
    781 	const unsigned char *orig_p = p;
    782 
    783 	if ((not = (ISMAGIC(*p) && *++p == NOT)))
    784 		p++;
    785 	do {
    786 		c = *p++;
    787 		if (ISMAGIC(c)) {
    788 			c = *p++;
    789 			if ((c & 0x80) && !ISMAGIC(c)) {
    790 				c &= 0x7f;/* extended pattern matching: *+?@! */
    791 				/* XXX the ( char isn't handled as part of [] */
    792 				if (c == ' ') /* simile for @: plain (..) */
    793 					c = '(' /*)*/;
    794 			}
    795 		}
    796 		if (c == '\0')
    797 			/* No closing ] - act as if the opening [ was quoted */
    798 			return sub == '[' ? orig_p : NULL;
    799 		if (ISMAGIC(p[0]) && p[1] == '-'
    800 		    && (!ISMAGIC(p[2]) || p[3] != ']'))
    801 		{
    802 			p += 2; /* MAGIC- */
    803 			d = *p++;
    804 			if (ISMAGIC(d)) {
    805 				d = *p++;
    806 				if ((d & 0x80) && !ISMAGIC(d))
    807 					d &= 0x7f;
    808 			}
    809 			/* POSIX says this is an invalid expression */
    810 			if (c > d)
    811 				return NULL;
    812 		} else
    813 			d = c;
    814 		if (c == sub || (c <= sub && sub <= d))
    815 			found = 1;
    816 	} while (!(ISMAGIC(p[0]) && p[1] == ']'));
    817 
    818 	return (found != not) ? p+2 : NULL;
    819 }
    820 
    821 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
    822 const unsigned char *
    823 pat_scan(p, pe, match_sep)
    824 	const unsigned char *p;
    825 	const unsigned char *pe;
    826 	int match_sep;
    827 {
    828 	int nest = 0;
    829 
    830 	for (; p < pe; p++) {
    831 		if (!ISMAGIC(*p))
    832 			continue;
    833 		if ((*++p == /*(*/ ')' && nest-- == 0)
    834 		    || (*p == '|' && match_sep && nest == 0))
    835 			return ++p;
    836 		if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
    837 			nest++;
    838 	}
    839 	return (const unsigned char *) 0;
    840 }
    841 
    842 
    843 /* -------- qsort.c -------- */
    844 
    845 /*
    846  * quick sort of array of generic pointers to objects.
    847  */
    848 static void qsort1 ARGS((void **base, void **lim, int (*f)(void *, void *)));
    849 
    850 void
    851 qsortp(base, n, f)
    852 	void **base;				/* base address */
    853 	size_t n;				/* elements */
    854 	int (*f) ARGS((void *, void *));	/* compare function */
    855 {
    856 	qsort1(base, base + n, f);
    857 }
    858 
    859 #define	swap2(a, b)	{\
    860 	register void *t; t = *(a); *(a) = *(b); *(b) = t;\
    861 }
    862 #define	swap3(a, b, c)	{\
    863 	register void *t; t = *(a); *(a) = *(c); *(c) = *(b); *(b) = t;\
    864 }
    865 
    866 static void
    867 qsort1(base, lim, f)
    868 	void **base, **lim;
    869 	int (*f) ARGS((void *, void *));
    870 {
    871 	register void **i, **j;
    872 	register void **lptr, **hptr;
    873 	size_t n;
    874 	int c;
    875 
    876   top:
    877 	n = (lim - base) / 2;
    878 	if (n == 0)
    879 		return;
    880 	hptr = lptr = base+n;
    881 	i = base;
    882 	j = lim - 1;
    883 
    884 	for (;;) {
    885 		if (i < lptr) {
    886 			if ((c = (*f)(*i, *lptr)) == 0) {
    887 				lptr--;
    888 				swap2(i, lptr);
    889 				continue;
    890 			}
    891 			if (c < 0) {
    892 				i += 1;
    893 				continue;
    894 			}
    895 		}
    896 
    897 	  begin:
    898 		if (j > hptr) {
    899 			if ((c = (*f)(*hptr, *j)) == 0) {
    900 				hptr++;
    901 				swap2(hptr, j);
    902 				goto begin;
    903 			}
    904 			if (c > 0) {
    905 				if (i == lptr) {
    906 					hptr++;
    907 					swap3(i, hptr, j);
    908 					i = lptr += 1;
    909 					goto begin;
    910 				}
    911 				swap2(i, j);
    912 				j -= 1;
    913 				i += 1;
    914 				continue;
    915 			}
    916 			j -= 1;
    917 			goto begin;
    918 		}
    919 
    920 		if (i == lptr) {
    921 			if (lptr-base >= lim-hptr) {
    922 				qsort1(hptr+1, lim, f);
    923 				lim = lptr;
    924 			} else {
    925 				qsort1(base, lptr, f);
    926 				base = hptr+1;
    927 			}
    928 			goto top;
    929 		}
    930 
    931 		lptr -= 1;
    932 		swap3(j, lptr, i);
    933 		j = hptr -= 1;
    934 	}
    935 }
    936 
    937 int
    938 xstrcmp(p1, p2)
    939 	void *p1, *p2;
    940 {
    941 	return (strcmp((char *)p1, (char *)p2));
    942 }
    943 
    944 /* Initialize a Getopt structure */
    945 void
    946 ksh_getopt_reset(go, flags)
    947 	Getopt *go;
    948 	int flags;
    949 {
    950 	go->optind = 1;
    951 	go->optarg = (char *) 0;
    952 	go->p = 0;
    953 	go->flags = flags;
    954 	go->info = 0;
    955 	go->buf[1] = '\0';
    956 }
    957 
    958 
    959 /* getopt() used for shell built-in commands, the getopts command, and
    960  * command line options.
    961  * A leading ':' in options means don't print errors, instead return '?'
    962  * or ':' and set go->optarg to the offending option character.
    963  * If GF_ERROR is set (and option doesn't start with :), errors result in
    964  * a call to bi_errorf().
    965  *
    966  * Non-standard features:
    967  *	- ';' is like ':' in options, except the argument is optional
    968  *	  (if it isn't present, optarg is set to 0).
    969  *	  Used for 'set -o'.
    970  *	- ',' is like ':' in options, except the argument always immediately
    971  *	  follows the option character (optarg is set to the null string if
    972  *	  the option is missing).
    973  *	  Used for 'read -u2', 'print -u2' and fc -40.
    974  *	- '#' is like ':' in options, expect that the argument is optional
    975  *	  and must start with a digit.  If the argument doesn't start with a
    976  *	  digit, it is assumed to be missing and normal option processing
    977  *	  continues (optarg is set to 0 if the option is missing).
    978  *	  Used for 'typeset -LZ4'.
    979  *	- accepts +c as well as -c IF the GF_PLUSOPT flag is present.  If an
    980  *	  option starting with + is accepted, the GI_PLUS flag will be set
    981  *	  in go->info.
    982  */
    983 int
    984 ksh_getopt(argv, go, options)
    985 	char **argv;
    986 	Getopt *go;
    987 	const char *options;
    988 {
    989 	char c;
    990 	char *o;
    991 
    992 	if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
    993 		char *arg = argv[go->optind], flag = arg ? *arg : '\0';
    994 
    995 		go->p = 1;
    996 		if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
    997 			go->optind++;
    998 			go->p = 0;
    999 			go->info |= GI_MINUSMINUS;
   1000 			return EOF;
   1001 		}
   1002 		if (arg == (char *) 0
   1003 		    || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
   1004 			&& (!(go->flags & GF_PLUSOPT) || flag != '+'))
   1005 		    || (c = arg[1]) == '\0')
   1006 		{
   1007 			go->p = 0;
   1008 			return EOF;
   1009 		}
   1010 		go->optind++;
   1011 		go->info &= ~(GI_MINUS|GI_PLUS);
   1012 		go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
   1013 	}
   1014 	go->p++;
   1015 	if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#'
   1016 	    || !(o = strchr(options, c)))
   1017 	{
   1018 		if (options[0] == ':') {
   1019 			go->buf[0] = c;
   1020 			go->optarg = go->buf;
   1021 		} else {
   1022 			warningf(TRUE, "%s%s-%c: unknown option",
   1023 				(go->flags & GF_NONAME) ? "" : argv[0],
   1024 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1025 			if (go->flags & GF_ERROR)
   1026 				bi_errorf("%s", null);
   1027 		}
   1028 		return '?';
   1029 	}
   1030 	/* : means argument must be present, may be part of option argument
   1031 	 *   or the next argument
   1032 	 * ; same as : but argument may be missing
   1033 	 * , means argument is part of option argument, and may be null.
   1034 	 */
   1035 	if (*++o == ':' || *o == ';') {
   1036 		if (argv[go->optind - 1][go->p])
   1037 			go->optarg = argv[go->optind - 1] + go->p;
   1038 		else if (argv[go->optind])
   1039 			go->optarg = argv[go->optind++];
   1040 		else if (*o == ';')
   1041 			go->optarg = (char *) 0;
   1042 		else {
   1043 			if (options[0] == ':') {
   1044 				go->buf[0] = c;
   1045 				go->optarg = go->buf;
   1046 				return ':';
   1047 			}
   1048 			warningf(TRUE, "%s%s-`%c' requires argument",
   1049 				(go->flags & GF_NONAME) ? "" : argv[0],
   1050 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1051 			if (go->flags & GF_ERROR)
   1052 				bi_errorf("%s", null);
   1053 			return '?';
   1054 		}
   1055 		go->p = 0;
   1056 	} else if (*o == ',') {
   1057 		/* argument is attached to option character, even if null */
   1058 		go->optarg = argv[go->optind - 1] + go->p;
   1059 		go->p = 0;
   1060 	} else if (*o == '#') {
   1061 		/* argument is optional and may be attached or unattached
   1062 		 * but must start with a digit.  optarg is set to 0 if the
   1063 		 * argument is missing.
   1064 		 */
   1065 		if (argv[go->optind - 1][go->p]) {
   1066 			if (digit(argv[go->optind - 1][go->p])) {
   1067 				go->optarg = argv[go->optind - 1] + go->p;
   1068 				go->p = 0;
   1069 			} else
   1070 				go->optarg = (char *) 0;
   1071 		} else {
   1072 			if (argv[go->optind] && digit(argv[go->optind][0])) {
   1073 				go->optarg = argv[go->optind++];
   1074 				go->p = 0;
   1075 			} else
   1076 				go->optarg = (char *) 0;
   1077 		}
   1078 	}
   1079 	return c;
   1080 }
   1081 
   1082 /* print variable/alias value using necessary quotes
   1083  * (POSIX says they should be suitable for re-entry...)
   1084  * No trailing newline is printed.
   1085  */
   1086 void
   1087 print_value_quoted(s)
   1088 	const char *s;
   1089 {
   1090 	const char *p;
   1091 	int inquote = 0;
   1092 
   1093 	/* Test if any quotes are needed */
   1094 	for (p = s; *p; p++)
   1095 		if (ctype(*p, C_QUOTE))
   1096 			break;
   1097 	if (!*p) {
   1098 		shprintf("%s", s);
   1099 		return;
   1100 	}
   1101 	for (p = s; *p; p++) {
   1102 		if (*p == '\'') {
   1103 			shprintf("%s", "'\\'" + 1 - inquote);
   1104 			inquote = 0;
   1105 		} else {
   1106 			if (!inquote) {
   1107 				shprintf("'");
   1108 				inquote = 1;
   1109 			}
   1110 			shf_putc(*p, shl_stdout);
   1111 		}
   1112 	}
   1113 	if (inquote)
   1114 		shprintf("'");
   1115 }
   1116 
   1117 /* Print things in columns and rows - func() is called to format the ith
   1118  * element
   1119  */
   1120 void
   1121 print_columns(shf, n, func, arg, max_width, prefcol)
   1122 	struct shf *shf;
   1123 	int n;
   1124 	char *(*func) ARGS((void *, int, char *, int));
   1125 	void *arg;
   1126 	int max_width;
   1127 	int prefcol;
   1128 {
   1129 	char *str = (char *) alloc(max_width + 1, ATEMP);
   1130 	int i;
   1131 	int r, c;
   1132 	int rows, cols;
   1133 	int nspace;
   1134 
   1135 	/* max_width + 1 for the space.  Note that no space
   1136 	 * is printed after the last column to avoid problems
   1137 	 * with terminals that have auto-wrap.
   1138 	 */
   1139 	cols = x_cols / (max_width + 1);
   1140 	if (!cols)
   1141 		cols = 1;
   1142 	rows = (n + cols - 1) / cols;
   1143 	if (prefcol && n && cols > rows) {
   1144 		int tmp = rows;
   1145 
   1146 		rows = cols;
   1147 		cols = tmp;
   1148 		if (rows > n)
   1149 			rows = n;
   1150 	}
   1151 
   1152 	nspace = (x_cols - max_width * cols) / cols;
   1153 	if (nspace <= 0)
   1154 		nspace = 1;
   1155 	for (r = 0; r < rows; r++) {
   1156 		for (c = 0; c < cols; c++) {
   1157 			i = c * rows + r;
   1158 			if (i < n) {
   1159 				shf_fprintf(shf, "%-*s",
   1160 					max_width,
   1161 					(*func)(arg, i, str, max_width + 1));
   1162 				if (c + 1 < cols)
   1163 					shf_fprintf(shf, "%*s", nspace, null);
   1164 			}
   1165 		}
   1166 		shf_putchar('\n', shf);
   1167 	}
   1168 	afree(str, ATEMP);
   1169 }
   1170 
   1171 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
   1172 int
   1173 strip_nuls(buf, nbytes)
   1174 	char *buf;
   1175 	int nbytes;
   1176 {
   1177 	char *dst;
   1178 
   1179 	/* nbytes check because some systems (older freebsd's) have a buggy
   1180 	 * memchr()
   1181 	 */
   1182 	if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
   1183 		char *end = buf + nbytes;
   1184 		char *p, *q;
   1185 
   1186 		for (p = dst; p < end; p = q) {
   1187 			/* skip a block of nulls */
   1188 			while (++p < end && *p == '\0')
   1189 				;
   1190 			/* find end of non-null block */
   1191 			if (!(q = memchr(p, '\0', end - p)))
   1192 				q = end;
   1193 			memmove(dst, p, q - p);
   1194 			dst += q - p;
   1195 		}
   1196 		*dst = '\0';
   1197 		return dst - buf;
   1198 	}
   1199 	return nbytes;
   1200 }
   1201 
   1202 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
   1203  * Returns dst.
   1204  */
   1205 char *
   1206 str_zcpy(dst, src, dsize)
   1207 	char *dst;
   1208 	const char *src;
   1209 	int dsize;
   1210 {
   1211 	if (dsize > 0) {
   1212 		int len = strlen(src);
   1213 
   1214 		if (len >= dsize)
   1215 			len = dsize - 1;
   1216 		memcpy(dst, src, len);
   1217 		dst[len] = '\0';
   1218 	}
   1219 	return dst;
   1220 }
   1221 
   1222 /* Like read(2), but if read fails due to non-blocking flag, resets flag
   1223  * and restarts read.
   1224  */
   1225 int
   1226 blocking_read(fd, buf, nbytes)
   1227 	int fd;
   1228 	char *buf;
   1229 	int nbytes;
   1230 {
   1231 	int ret;
   1232 	int tried_reset = 0;
   1233 
   1234 	while ((ret = read(fd, buf, nbytes)) < 0) {
   1235 		if (!tried_reset && (errno == EAGAIN
   1236 #ifdef EWOULDBLOCK
   1237 				     || errno == EWOULDBLOCK
   1238 #endif /* EWOULDBLOCK */
   1239 				    ))
   1240 		{
   1241 			int oerrno = errno;
   1242 			if (reset_nonblock(fd) > 0) {
   1243 				tried_reset = 1;
   1244 				continue;
   1245 			}
   1246 			errno = oerrno;
   1247 		}
   1248 		break;
   1249 	}
   1250 	return ret;
   1251 }
   1252 
   1253 /* Reset the non-blocking flag on the specified file descriptor.
   1254  * Returns -1 if there was an error, 0 if non-blocking wasn't set,
   1255  * 1 if it was.
   1256  */
   1257 int
   1258 reset_nonblock(fd)
   1259 	int fd;
   1260 {
   1261 	int flags;
   1262 	int blocking_flags;
   1263 
   1264 	if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
   1265 		return -1;
   1266 	/* With luck, the C compiler will reduce this to a constant */
   1267 	blocking_flags = 0;
   1268 #ifdef O_NONBLOCK
   1269 	blocking_flags |= O_NONBLOCK;
   1270 #endif /* O_NONBLOCK */
   1271 #ifdef O_NDELAY
   1272 	blocking_flags |= O_NDELAY;
   1273 #else /* O_NDELAY */
   1274 # ifndef O_NONBLOCK
   1275 	blocking_flags |= FNDELAY; /* hope this exists... */
   1276 # endif /* O_NONBLOCK */
   1277 #endif /* O_NDELAY */
   1278 	if (!(flags & blocking_flags))
   1279 		return 0;
   1280 	flags &= ~blocking_flags;
   1281 	if (fcntl(fd, F_SETFL, flags) < 0)
   1282 		return -1;
   1283 	return 1;
   1284 }
   1285 
   1286 
   1287 #ifdef HAVE_SYS_PARAM_H
   1288 # include <sys/param.h>
   1289 #endif /* HAVE_SYS_PARAM_H */
   1290 #ifndef MAXPATHLEN
   1291 # define MAXPATHLEN PATH
   1292 #endif /* MAXPATHLEN */
   1293 
   1294 #ifdef HPUX_GETWD_BUG
   1295 # include "ksh_dir.h"
   1296 
   1297 /*
   1298  * Work around bug in hpux 10.x C library - getwd/getcwd dump core
   1299  * if current directory is not readable.  Done in macro 'cause code
   1300  * is needed in GETWD and GETCWD cases.
   1301  */
   1302 # define HPUX_GETWD_BUG_CODE \
   1303 	{ \
   1304 	    DIR *d = ksh_opendir("."); \
   1305 	    if (!d) \
   1306 		return (char *) 0; \
   1307 	    closedir(d); \
   1308 	}
   1309 #else /* HPUX_GETWD_BUG */
   1310 # define HPUX_GETWD_BUG_CODE
   1311 #endif /* HPUX_GETWD_BUG */
   1312 
   1313 /* Like getcwd(), except bsize is ignored if buf is 0 (MAXPATHLEN is used) */
   1314 char *
   1315 ksh_get_wd(buf, bsize)
   1316 	char *buf;
   1317 	int bsize;
   1318 {
   1319 #ifdef HAVE_GETCWD
   1320 	char *b;
   1321 	char *ret;
   1322 
   1323 	/* Before memory allocated */
   1324 	HPUX_GETWD_BUG_CODE
   1325 
   1326 	/* Assume getcwd() available */
   1327 	if (!buf) {
   1328 		bsize = MAXPATHLEN;
   1329 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1330 	} else
   1331 		b = buf;
   1332 
   1333 	ret = getcwd(b, bsize);
   1334 
   1335 	if (!buf) {
   1336 		if (ret)
   1337 			ret = aresize(b, strlen(b) + 1, ATEMP);
   1338 		else
   1339 			afree(b, ATEMP);
   1340 	}
   1341 
   1342 	return ret;
   1343 #else /* HAVE_GETCWD */
   1344 	extern char *getwd ARGS((char *));
   1345 	char *b;
   1346 	int len;
   1347 
   1348 	/* Before memory allocated */
   1349 	HPUX_GETWD_BUG_CODE
   1350 
   1351 	if (buf && bsize > MAXPATHLEN)
   1352 		b = buf;
   1353 	else
   1354 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1355 	if (!getcwd(b, MAXPATHLEN)) {
   1356 		errno = EACCES;
   1357 		if (b != buf)
   1358 			afree(b, ATEMP);
   1359 		return (char *) 0;
   1360 	}
   1361 	len = strlen(b) + 1;
   1362 	if (!buf)
   1363 		b = aresize(b, len, ATEMP);
   1364 	else if (buf != b) {
   1365 		if (len > bsize) {
   1366 			errno = ERANGE;
   1367 			return (char *) 0;
   1368 		}
   1369 		memcpy(buf, b, len);
   1370 		afree(b, ATEMP);
   1371 		b = buf;
   1372 	}
   1373 
   1374 	return b;
   1375 #endif /* HAVE_GETCWD */
   1376 }
   1377