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