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