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