Home | History | Annotate | Line # | Download | only in ksh
misc.c revision 1.15.34.2
      1 /*	$NetBSD: misc.c,v 1.15.34.2 2017/05/11 02:58:28 pgoyette Exp $	*/
      2 
      3 /*
      4  * Miscellaneous functions
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: misc.c,v 1.15.34.2 2017/05/11 02:58:28 pgoyette 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 				return 0;
    687 			/* take care of zero matches */
    688 			if (p[-1] == (0x80 | '*')
    689 			    && do_gmatch(s, se, prest, pe, isfile))
    690 				return 1;
    691 			for (psub = p; ; psub = pnext) {
    692 				pnext = pat_scan(psub, pe, 1);
    693 				for (srest = s; srest <= se; srest++) {
    694 					if (do_gmatch(s, srest,
    695 						psub, pnext - 2, isfile)
    696 					    && (do_gmatch(srest, se,
    697 							  prest, pe, isfile)
    698 						|| (s != srest
    699 						    && do_gmatch(srest, se,
    700 							p - 2, pe, isfile))))
    701 						return 1;
    702 				}
    703 				if (pnext == prest)
    704 					break;
    705 			}
    706 			return 0;
    707 
    708 		  case 0x80|'?': /* matches zero or once */
    709 		  case 0x80|'@': /* matches one of the patterns */
    710 		  case 0x80|' ': /* simile for @ */
    711 			if (!(prest = pat_scan(++p, pe, 0)))
    712 				return 0;
    713 			/* Take care of zero matches */
    714 			if (p[-1] == (0x80 | '?')
    715 			    && do_gmatch(s, se, prest, pe, isfile))
    716 				return 1;
    717 			for (psub = p; ; psub = pnext) {
    718 				pnext = pat_scan(psub, pe, 1);
    719 				srest = prest == pe ? se : s;
    720 				for (; srest <= se; srest++) {
    721 					if (do_gmatch(s, srest,
    722 						      psub, pnext - 2, isfile)
    723 					    && do_gmatch(srest, se,
    724 							 prest, pe, isfile))
    725 						return 1;
    726 				}
    727 				if (pnext == prest)
    728 					break;
    729 			}
    730 			return 0;
    731 
    732 		  case 0x80|'!': /* matches none of the patterns */
    733 			if (!(prest = pat_scan(++p, pe, 0)))
    734 				return 0;
    735 			for (srest = s; srest <= se; srest++) {
    736 				int matched = 0;
    737 
    738 				for (psub = p; ; psub = pnext) {
    739 					pnext = pat_scan(psub, pe, 1);
    740 					if (do_gmatch(s, srest,
    741 						      psub, pnext - 2, isfile))
    742 					{
    743 						matched = 1;
    744 						break;
    745 					}
    746 					if (pnext == prest)
    747 						break;
    748 				}
    749 				if (!matched && do_gmatch(srest, se,
    750 							  prest, pe, isfile))
    751 					return 1;
    752 			}
    753 			return 0;
    754 
    755 		  default:
    756 			if (sc != pc)
    757 				break;
    758 			p++;
    759 			s++;
    760 			continue;
    761 		}
    762 backtrack:	if (sNext != sStart && sNext <= se) {
    763 			p = pNext;
    764 			s = sNext;
    765 			continue;
    766 		}
    767 		return 0;
    768 	}
    769 	return 1;
    770 }
    771 
    772 static const unsigned char *
    773 cclass(p, sub)
    774 	const unsigned char *p;
    775 	register int sub;
    776 {
    777 	register int c, d, not, found = 0;
    778 	const unsigned char *orig_p = p;
    779 
    780 	if ((not = (ISMAGIC(*p) && *++p == NOT)))
    781 		p++;
    782 	do {
    783 		c = *p++;
    784 		if (ISMAGIC(c)) {
    785 			c = *p++;
    786 			if ((c & 0x80) && !ISMAGIC(c)) {
    787 				c &= 0x7f;/* extended pattern matching: *+?@! */
    788 				/* XXX the ( char isn't handled as part of [] */
    789 				if (c == ' ') /* simile for @: plain (..) */
    790 					c = '(' /*)*/;
    791 			}
    792 		}
    793 		if (c == '\0')
    794 			/* No closing ] - act as if the opening [ was quoted */
    795 			return sub == '[' ? orig_p : NULL;
    796 		if (ISMAGIC(p[0]) && p[1] == '-'
    797 		    && (!ISMAGIC(p[2]) || p[3] != ']'))
    798 		{
    799 			p += 2; /* MAGIC- */
    800 			d = *p++;
    801 			if (ISMAGIC(d)) {
    802 				d = *p++;
    803 				if ((d & 0x80) && !ISMAGIC(d))
    804 					d &= 0x7f;
    805 			}
    806 			/* POSIX says this is an invalid expression */
    807 			if (c > d)
    808 				return NULL;
    809 		} else
    810 			d = c;
    811 		if (c == sub || (c <= sub && sub <= d))
    812 			found = 1;
    813 	} while (!(ISMAGIC(p[0]) && p[1] == ']'));
    814 
    815 	return (found != not) ? p+2 : NULL;
    816 }
    817 
    818 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
    819 const unsigned char *
    820 pat_scan(p, pe, match_sep)
    821 	const unsigned char *p;
    822 	const unsigned char *pe;
    823 	int match_sep;
    824 {
    825 	int nest = 0;
    826 
    827 	for (; p < pe; p++) {
    828 		if (!ISMAGIC(*p))
    829 			continue;
    830 		if ((*++p == /*(*/ ')' && nest-- == 0)
    831 		    || (*p == '|' && match_sep && nest == 0))
    832 			return ++p;
    833 		if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
    834 			nest++;
    835 	}
    836 	return (const unsigned char *) 0;
    837 }
    838 
    839 
    840 /* -------- qsort.c -------- */
    841 
    842 /*
    843  * quick sort of array of generic pointers to objects.
    844  */
    845 static void qsort1 ARGS((void **base, void **lim, int (*f)(void *, void *)));
    846 
    847 void
    848 qsortp(base, n, f)
    849 	void **base;				/* base address */
    850 	size_t n;				/* elements */
    851 	int (*f) ARGS((void *, void *));	/* compare function */
    852 {
    853 	qsort1(base, base + n, f);
    854 }
    855 
    856 #define	swap2(a, b)	{\
    857 	register void *t; t = *(a); *(a) = *(b); *(b) = t;\
    858 }
    859 #define	swap3(a, b, c)	{\
    860 	register void *t; t = *(a); *(a) = *(c); *(c) = *(b); *(b) = t;\
    861 }
    862 
    863 static void
    864 qsort1(base, lim, f)
    865 	void **base, **lim;
    866 	int (*f) ARGS((void *, void *));
    867 {
    868 	register void **i, **j;
    869 	register void **lptr, **hptr;
    870 	size_t n;
    871 	int c;
    872 
    873   top:
    874 	n = (lim - base) / 2;
    875 	if (n == 0)
    876 		return;
    877 	hptr = lptr = base+n;
    878 	i = base;
    879 	j = lim - 1;
    880 
    881 	for (;;) {
    882 		if (i < lptr) {
    883 			if ((c = (*f)(*i, *lptr)) == 0) {
    884 				lptr--;
    885 				swap2(i, lptr);
    886 				continue;
    887 			}
    888 			if (c < 0) {
    889 				i += 1;
    890 				continue;
    891 			}
    892 		}
    893 
    894 	  begin:
    895 		if (j > hptr) {
    896 			if ((c = (*f)(*hptr, *j)) == 0) {
    897 				hptr++;
    898 				swap2(hptr, j);
    899 				goto begin;
    900 			}
    901 			if (c > 0) {
    902 				if (i == lptr) {
    903 					hptr++;
    904 					swap3(i, hptr, j);
    905 					i = lptr += 1;
    906 					goto begin;
    907 				}
    908 				swap2(i, j);
    909 				j -= 1;
    910 				i += 1;
    911 				continue;
    912 			}
    913 			j -= 1;
    914 			goto begin;
    915 		}
    916 
    917 		if (i == lptr) {
    918 			if (lptr-base >= lim-hptr) {
    919 				qsort1(hptr+1, lim, f);
    920 				lim = lptr;
    921 			} else {
    922 				qsort1(base, lptr, f);
    923 				base = hptr+1;
    924 			}
    925 			goto top;
    926 		}
    927 
    928 		lptr -= 1;
    929 		swap3(j, lptr, i);
    930 		j = hptr -= 1;
    931 	}
    932 }
    933 
    934 int
    935 xstrcmp(p1, p2)
    936 	void *p1, *p2;
    937 {
    938 	return (strcmp((char *)p1, (char *)p2));
    939 }
    940 
    941 /* Initialize a Getopt structure */
    942 void
    943 ksh_getopt_reset(go, flags)
    944 	Getopt *go;
    945 	int flags;
    946 {
    947 	go->optind = 1;
    948 	go->optarg = (char *) 0;
    949 	go->p = 0;
    950 	go->flags = flags;
    951 	go->info = 0;
    952 	go->buf[1] = '\0';
    953 }
    954 
    955 
    956 /* getopt() used for shell built-in commands, the getopts command, and
    957  * command line options.
    958  * A leading ':' in options means don't print errors, instead return '?'
    959  * or ':' and set go->optarg to the offending option character.
    960  * If GF_ERROR is set (and option doesn't start with :), errors result in
    961  * a call to bi_errorf().
    962  *
    963  * Non-standard features:
    964  *	- ';' is like ':' in options, except the argument is optional
    965  *	  (if it isn't present, optarg is set to 0).
    966  *	  Used for 'set -o'.
    967  *	- ',' is like ':' in options, except the argument always immediately
    968  *	  follows the option character (optarg is set to the null string if
    969  *	  the option is missing).
    970  *	  Used for 'read -u2', 'print -u2' and fc -40.
    971  *	- '#' is like ':' in options, expect that the argument is optional
    972  *	  and must start with a digit.  If the argument doesn't start with a
    973  *	  digit, it is assumed to be missing and normal option processing
    974  *	  continues (optarg is set to 0 if the option is missing).
    975  *	  Used for 'typeset -LZ4'.
    976  *	- accepts +c as well as -c IF the GF_PLUSOPT flag is present.  If an
    977  *	  option starting with + is accepted, the GI_PLUS flag will be set
    978  *	  in go->info.
    979  */
    980 int
    981 ksh_getopt(argv, go, options)
    982 	char **argv;
    983 	Getopt *go;
    984 	const char *options;
    985 {
    986 	char c;
    987 	char *o;
    988 
    989 	if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
    990 		char *arg = argv[go->optind], flag = arg ? *arg : '\0';
    991 
    992 		go->p = 1;
    993 		if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
    994 			go->optind++;
    995 			go->p = 0;
    996 			go->info |= GI_MINUSMINUS;
    997 			return EOF;
    998 		}
    999 		if (arg == (char *) 0
   1000 		    || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
   1001 			&& (!(go->flags & GF_PLUSOPT) || flag != '+'))
   1002 		    || (c = arg[1]) == '\0')
   1003 		{
   1004 			go->p = 0;
   1005 			return EOF;
   1006 		}
   1007 		go->optind++;
   1008 		go->info &= ~(GI_MINUS|GI_PLUS);
   1009 		go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
   1010 	}
   1011 	go->p++;
   1012 	if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#'
   1013 	    || !(o = strchr(options, c)))
   1014 	{
   1015 		if (options[0] == ':') {
   1016 			go->buf[0] = c;
   1017 			go->optarg = go->buf;
   1018 		} else {
   1019 			warningf(TRUE, "%s%s-%c: unknown option",
   1020 				(go->flags & GF_NONAME) ? "" : argv[0],
   1021 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1022 			if (go->flags & GF_ERROR)
   1023 				bi_errorf("%s", null);
   1024 		}
   1025 		return '?';
   1026 	}
   1027 	/* : means argument must be present, may be part of option argument
   1028 	 *   or the next argument
   1029 	 * ; same as : but argument may be missing
   1030 	 * , means argument is part of option argument, and may be null.
   1031 	 */
   1032 	if (*++o == ':' || *o == ';') {
   1033 		if (argv[go->optind - 1][go->p])
   1034 			go->optarg = argv[go->optind - 1] + go->p;
   1035 		else if (argv[go->optind])
   1036 			go->optarg = argv[go->optind++];
   1037 		else if (*o == ';')
   1038 			go->optarg = (char *) 0;
   1039 		else {
   1040 			if (options[0] == ':') {
   1041 				go->buf[0] = c;
   1042 				go->optarg = go->buf;
   1043 				return ':';
   1044 			}
   1045 			warningf(TRUE, "%s%s-`%c' requires argument",
   1046 				(go->flags & GF_NONAME) ? "" : argv[0],
   1047 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1048 			if (go->flags & GF_ERROR)
   1049 				bi_errorf("%s", null);
   1050 			return '?';
   1051 		}
   1052 		go->p = 0;
   1053 	} else if (*o == ',') {
   1054 		/* argument is attached to option character, even if null */
   1055 		go->optarg = argv[go->optind - 1] + go->p;
   1056 		go->p = 0;
   1057 	} else if (*o == '#') {
   1058 		/* argument is optional and may be attached or unattached
   1059 		 * but must start with a digit.  optarg is set to 0 if the
   1060 		 * argument is missing.
   1061 		 */
   1062 		if (argv[go->optind - 1][go->p]) {
   1063 			if (digit(argv[go->optind - 1][go->p])) {
   1064 				go->optarg = argv[go->optind - 1] + go->p;
   1065 				go->p = 0;
   1066 			} else
   1067 				go->optarg = (char *) 0;
   1068 		} else {
   1069 			if (argv[go->optind] && digit(argv[go->optind][0])) {
   1070 				go->optarg = argv[go->optind++];
   1071 				go->p = 0;
   1072 			} else
   1073 				go->optarg = (char *) 0;
   1074 		}
   1075 	}
   1076 	return c;
   1077 }
   1078 
   1079 /* print variable/alias value using necessary quotes
   1080  * (POSIX says they should be suitable for re-entry...)
   1081  * No trailing newline is printed.
   1082  */
   1083 void
   1084 print_value_quoted(s)
   1085 	const char *s;
   1086 {
   1087 	const char *p;
   1088 	int inquote = 0;
   1089 
   1090 	/* Test if any quotes are needed */
   1091 	for (p = s; *p; p++)
   1092 		if (ctype(*p, C_QUOTE))
   1093 			break;
   1094 	if (!*p) {
   1095 		shprintf("%s", s);
   1096 		return;
   1097 	}
   1098 	for (p = s; *p; p++) {
   1099 		if (*p == '\'') {
   1100 			shprintf("%s", "'\\'" + 1 - inquote);
   1101 			inquote = 0;
   1102 		} else {
   1103 			if (!inquote) {
   1104 				shprintf("'");
   1105 				inquote = 1;
   1106 			}
   1107 			shf_putc(*p, shl_stdout);
   1108 		}
   1109 	}
   1110 	if (inquote)
   1111 		shprintf("'");
   1112 }
   1113 
   1114 /* Print things in columns and rows - func() is called to format the ith
   1115  * element
   1116  */
   1117 void
   1118 print_columns(shf, n, func, arg, max_width, prefcol)
   1119 	struct shf *shf;
   1120 	int n;
   1121 	char *(*func) ARGS((void *, int, char *, int));
   1122 	void *arg;
   1123 	int max_width;
   1124 	int prefcol;
   1125 {
   1126 	char *str = (char *) alloc(max_width + 1, ATEMP);
   1127 	int i;
   1128 	int r, c;
   1129 	int rows, cols;
   1130 	int nspace;
   1131 
   1132 	/* max_width + 1 for the space.  Note that no space
   1133 	 * is printed after the last column to avoid problems
   1134 	 * with terminals that have auto-wrap.
   1135 	 */
   1136 	cols = x_cols / (max_width + 1);
   1137 	if (!cols)
   1138 		cols = 1;
   1139 	rows = (n + cols - 1) / cols;
   1140 	if (prefcol && n && cols > rows) {
   1141 		int tmp = rows;
   1142 
   1143 		rows = cols;
   1144 		cols = tmp;
   1145 		if (rows > n)
   1146 			rows = n;
   1147 	}
   1148 
   1149 	nspace = (x_cols - max_width * cols) / cols;
   1150 	if (nspace <= 0)
   1151 		nspace = 1;
   1152 	for (r = 0; r < rows; r++) {
   1153 		for (c = 0; c < cols; c++) {
   1154 			i = c * rows + r;
   1155 			if (i < n) {
   1156 				shf_fprintf(shf, "%-*s",
   1157 					max_width,
   1158 					(*func)(arg, i, str, max_width + 1));
   1159 				if (c + 1 < cols)
   1160 					shf_fprintf(shf, "%*s", nspace, null);
   1161 			}
   1162 		}
   1163 		shf_putchar('\n', shf);
   1164 	}
   1165 	afree(str, ATEMP);
   1166 }
   1167 
   1168 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
   1169 int
   1170 strip_nuls(buf, nbytes)
   1171 	char *buf;
   1172 	int nbytes;
   1173 {
   1174 	char *dst;
   1175 
   1176 	/* nbytes check because some systems (older freebsd's) have a buggy
   1177 	 * memchr()
   1178 	 */
   1179 	if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
   1180 		char *end = buf + nbytes;
   1181 		char *p, *q;
   1182 
   1183 		for (p = dst; p < end; p = q) {
   1184 			/* skip a block of nulls */
   1185 			while (++p < end && *p == '\0')
   1186 				;
   1187 			/* find end of non-null block */
   1188 			if (!(q = memchr(p, '\0', end - p)))
   1189 				q = end;
   1190 			memmove(dst, p, q - p);
   1191 			dst += q - p;
   1192 		}
   1193 		*dst = '\0';
   1194 		return dst - buf;
   1195 	}
   1196 	return nbytes;
   1197 }
   1198 
   1199 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
   1200  * Returns dst.
   1201  */
   1202 char *
   1203 str_zcpy(dst, src, dsize)
   1204 	char *dst;
   1205 	const char *src;
   1206 	int dsize;
   1207 {
   1208 	if (dsize > 0) {
   1209 		int len = strlen(src);
   1210 
   1211 		if (len >= dsize)
   1212 			len = dsize - 1;
   1213 		memcpy(dst, src, len);
   1214 		dst[len] = '\0';
   1215 	}
   1216 	return dst;
   1217 }
   1218 
   1219 /* Like read(2), but if read fails due to non-blocking flag, resets flag
   1220  * and restarts read.
   1221  */
   1222 int
   1223 blocking_read(fd, buf, nbytes)
   1224 	int fd;
   1225 	char *buf;
   1226 	int nbytes;
   1227 {
   1228 	int ret;
   1229 	int tried_reset = 0;
   1230 
   1231 	while ((ret = read(fd, buf, nbytes)) < 0) {
   1232 		if (!tried_reset && (errno == EAGAIN
   1233 #ifdef EWOULDBLOCK
   1234 				     || errno == EWOULDBLOCK
   1235 #endif /* EWOULDBLOCK */
   1236 				    ))
   1237 		{
   1238 			int oerrno = errno;
   1239 			if (reset_nonblock(fd) > 0) {
   1240 				tried_reset = 1;
   1241 				continue;
   1242 			}
   1243 			errno = oerrno;
   1244 		}
   1245 		break;
   1246 	}
   1247 	return ret;
   1248 }
   1249 
   1250 /* Reset the non-blocking flag on the specified file descriptor.
   1251  * Returns -1 if there was an error, 0 if non-blocking wasn't set,
   1252  * 1 if it was.
   1253  */
   1254 int
   1255 reset_nonblock(fd)
   1256 	int fd;
   1257 {
   1258 	int flags;
   1259 	int blocking_flags;
   1260 
   1261 	if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
   1262 		return -1;
   1263 	/* With luck, the C compiler will reduce this to a constant */
   1264 	blocking_flags = 0;
   1265 #ifdef O_NONBLOCK
   1266 	blocking_flags |= O_NONBLOCK;
   1267 #endif /* O_NONBLOCK */
   1268 #ifdef O_NDELAY
   1269 	blocking_flags |= O_NDELAY;
   1270 #else /* O_NDELAY */
   1271 # ifndef O_NONBLOCK
   1272 	blocking_flags |= FNDELAY; /* hope this exists... */
   1273 # endif /* O_NONBLOCK */
   1274 #endif /* O_NDELAY */
   1275 	if (!(flags & blocking_flags))
   1276 		return 0;
   1277 	flags &= ~blocking_flags;
   1278 	if (fcntl(fd, F_SETFL, flags) < 0)
   1279 		return -1;
   1280 	return 1;
   1281 }
   1282 
   1283 
   1284 #ifdef HAVE_SYS_PARAM_H
   1285 # include <sys/param.h>
   1286 #endif /* HAVE_SYS_PARAM_H */
   1287 #ifndef MAXPATHLEN
   1288 # define MAXPATHLEN PATH
   1289 #endif /* MAXPATHLEN */
   1290 
   1291 #ifdef HPUX_GETWD_BUG
   1292 # include "ksh_dir.h"
   1293 
   1294 /*
   1295  * Work around bug in hpux 10.x C library - getwd/getcwd dump core
   1296  * if current directory is not readable.  Done in macro 'cause code
   1297  * is needed in GETWD and GETCWD cases.
   1298  */
   1299 # define HPUX_GETWD_BUG_CODE \
   1300 	{ \
   1301 	    DIR *d = ksh_opendir("."); \
   1302 	    if (!d) \
   1303 		return (char *) 0; \
   1304 	    closedir(d); \
   1305 	}
   1306 #else /* HPUX_GETWD_BUG */
   1307 # define HPUX_GETWD_BUG_CODE
   1308 #endif /* HPUX_GETWD_BUG */
   1309 
   1310 /* Like getcwd(), except bsize is ignored if buf is 0 (MAXPATHLEN is used) */
   1311 char *
   1312 ksh_get_wd(buf, bsize)
   1313 	char *buf;
   1314 	int bsize;
   1315 {
   1316 #ifdef HAVE_GETCWD
   1317 	char *b;
   1318 	char *ret;
   1319 
   1320 	/* Before memory allocated */
   1321 	HPUX_GETWD_BUG_CODE
   1322 
   1323 	/* Assume getcwd() available */
   1324 	if (!buf) {
   1325 		bsize = MAXPATHLEN;
   1326 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1327 	} else
   1328 		b = buf;
   1329 
   1330 	ret = getcwd(b, bsize);
   1331 
   1332 	if (!buf) {
   1333 		if (ret)
   1334 			ret = aresize(b, strlen(b) + 1, ATEMP);
   1335 		else
   1336 			afree(b, ATEMP);
   1337 	}
   1338 
   1339 	return ret;
   1340 #else /* HAVE_GETCWD */
   1341 	extern char *getwd ARGS((char *));
   1342 	char *b;
   1343 	int len;
   1344 
   1345 	/* Before memory allocated */
   1346 	HPUX_GETWD_BUG_CODE
   1347 
   1348 	if (buf && bsize > MAXPATHLEN)
   1349 		b = buf;
   1350 	else
   1351 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1352 	if (!getcwd(b, MAXPATHLEN)) {
   1353 		errno = EACCES;
   1354 		if (b != buf)
   1355 			afree(b, ATEMP);
   1356 		return (char *) 0;
   1357 	}
   1358 	len = strlen(b) + 1;
   1359 	if (!buf)
   1360 		b = aresize(b, len, ATEMP);
   1361 	else if (buf != b) {
   1362 		if (len > bsize) {
   1363 			errno = ERANGE;
   1364 			return (char *) 0;
   1365 		}
   1366 		memcpy(buf, b, len);
   1367 		afree(b, ATEMP);
   1368 		b = buf;
   1369 	}
   1370 
   1371 	return b;
   1372 #endif /* HAVE_GETCWD */
   1373 }
   1374