Home | History | Annotate | Line # | Download | only in ksh
misc.c revision 1.19
      1 /*	$NetBSD: misc.c,v 1.19 2017/06/22 13:35:47 kamil Exp $	*/
      2 
      3 /*
      4  * Miscellaneous functions
      5  */
      6 #include <sys/cdefs.h>
      7 
      8 #ifndef lint
      9 __RCSID("$NetBSD: misc.c,v 1.19 2017/06/22 13:35:47 kamil 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 		seteuid(ksheuid = getuid());
    327 		setuid(ksheuid);
    328 		setegid(getgid());
    329 		setgid(getgid());
    330 	} else if (f == FPOSIX && newval) {
    331 #ifdef BRACE_EXPAND
    332 		Flag(FBRACEEXPAND) = 0
    333 #endif /* BRACE_EXPAND */
    334 		;
    335 	}
    336 	/* Changing interactive flag? */
    337 	if (f == FTALKING) {
    338 		if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
    339 			Flag(FTALKING_I) = newval;
    340 	}
    341 }
    342 
    343 /* parse command line & set command arguments.  returns the index of
    344  * non-option arguments, -1 if there is an error.
    345  */
    346 int
    347 parse_args(argv, what, setargsp)
    348 	char **argv;
    349 	int	what;		/* OF_CMDLINE or OF_SET */
    350 	int	*setargsp;
    351 {
    352 	static char cmd_opts[NELEM(goptions) + 3]; /* o:\0 */
    353 	static char set_opts[NELEM(goptions) + 5]; /* Ao;s\0 */
    354 	char *opts;
    355 	char *array = (char *) 0;
    356 	Getopt go;
    357 	int i, optc, set, sortargs = 0, arrayset = 0;
    358 
    359 	/* First call?  Build option strings... */
    360 	if (cmd_opts[0] == '\0') {
    361 		char *p, *q;
    362 
    363 		/* see cmd_opts[] declaration */
    364 		strlcpy(cmd_opts, "o:", sizeof cmd_opts);
    365 		p = cmd_opts + strlen(cmd_opts);
    366 		/* see set_opts[] declaration */
    367 		strlcpy(set_opts, "A:o;s", sizeof set_opts);
    368 		q = set_opts + strlen(set_opts);
    369 		for (i = 0; i < (int)NELEM(goptions); i++) {
    370 			if (goptions[i].c) {
    371 				if (goptions[i].flags & OF_CMDLINE)
    372 					*p++ = goptions[i].c;
    373 				if (goptions[i].flags & OF_SET)
    374 					*q++ = goptions[i].c;
    375 			}
    376 		}
    377 		*p = '\0';
    378 		*q = '\0';
    379 	}
    380 
    381 	if (what == OF_CMDLINE) {
    382 		char *p;
    383 		/* Set FLOGIN before parsing options so user can clear
    384 		 * flag using +l.
    385 		 */
    386 		Flag(FLOGIN) = (argv[0][0] == '-'
    387 				|| ((p = ksh_strrchr_dirsep(argv[0]))
    388 				     && *++p == '-'));
    389 		opts = cmd_opts;
    390 	} else
    391 		opts = set_opts;
    392 	ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
    393 	while ((optc = ksh_getopt(argv, &go, opts)) != EOF) {
    394 		set = (go.info & GI_PLUS) ? 0 : 1;
    395 		switch (optc) {
    396 		  case 'A':
    397 			arrayset = set ? 1 : -1;
    398 			array = go.optarg;
    399 			break;
    400 
    401 		  case 'o':
    402 			if (go.optarg == (char *) 0) {
    403 				/* lone -o: print options
    404 				 *
    405 				 * Note that on the command line, -o requires
    406 				 * an option (ie, can't get here if what is
    407 				 * OF_CMDLINE).
    408 				 */
    409 				printoptions(set);
    410 				break;
    411 			}
    412 			i = option(go.optarg);
    413 			if (i >= 0 && set == Flag(i))
    414 				/* Don't check the context if the flag
    415 				 * isn't changing - makes "set -o interactive"
    416 				 * work if you're already interactive.  Needed
    417 				 * if the output of "set +o" is to be used.
    418 				 */
    419 				;
    420 			else if (i >= 0 && (goptions[i].flags & what))
    421 				change_flag((enum sh_flag) i, what, set);
    422 			else {
    423 				bi_errorf("%s: bad option", go.optarg);
    424 				return -1;
    425 			}
    426 			break;
    427 
    428 		  case '?':
    429 			return -1;
    430 
    431 		  default:
    432 			/* -s: sort positional params (at&t ksh stupidity) */
    433 			if (what == OF_SET && optc == 's') {
    434 				sortargs = 1;
    435 				break;
    436 			}
    437 			for (i = 0; i < (int)NELEM(goptions); i++)
    438 				if (optc == goptions[i].c
    439 				    && (what & goptions[i].flags))
    440 				{
    441 					change_flag((enum sh_flag) i, what,
    442 						    set);
    443 					break;
    444 				}
    445 			if (i == NELEM(goptions)) {
    446 				internal_errorf(1, "parse_args: `%c'", optc);
    447 				return -1; /* not reached */
    448 			}
    449 		}
    450 	}
    451 	if (!(go.info & GI_MINUSMINUS) && argv[go.optind]
    452 	    && (argv[go.optind][0] == '-' || argv[go.optind][0] == '+')
    453 	    && argv[go.optind][1] == '\0')
    454 	{
    455 		/* lone - clears -v and -x flags */
    456 		if (argv[go.optind][0] == '-' && !Flag(FPOSIX))
    457 			Flag(FVERBOSE) = Flag(FXTRACE) = 0;
    458 		/* set skips lone - or + option */
    459 		go.optind++;
    460 	}
    461 	if (setargsp)
    462 		/* -- means set $#/$* even if there are no arguments */
    463 		*setargsp = !arrayset && ((go.info & GI_MINUSMINUS)
    464 					  || argv[go.optind]);
    465 
    466 	if (arrayset && (!*array || *skip_varname(array, FALSE))) {
    467 		bi_errorf("%s: is not an identifier", array);
    468 		return -1;
    469 	}
    470 	if (sortargs) {
    471 		for (i = go.optind; argv[i]; i++)
    472 			;
    473 		qsortp((void **) &argv[go.optind], (size_t) (i - go.optind),
    474 			xstrcmp);
    475 	}
    476 	if (arrayset) {
    477 		set_array(array, arrayset, argv + go.optind);
    478 		for (; argv[go.optind]; go.optind++)
    479 			;
    480 	}
    481 
    482 	return go.optind;
    483 }
    484 
    485 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
    486 int
    487 getn(as, ai)
    488 	const char *as;
    489 	int *ai;
    490 {
    491 	char *p;
    492 	long n;
    493 
    494 	n = strtol(as, &p, 10);
    495 
    496 	if (!*as || *p || INT_MIN >= n || n >= INT_MAX)
    497 		return 0;
    498 
    499 	*ai = (int)n;
    500 	return 1;
    501 }
    502 
    503 /* getn() that prints error */
    504 int
    505 bi_getn(as, ai)
    506 	const char *as;
    507 	int *ai;
    508 {
    509 	int rv = getn(as, ai);
    510 
    511 	if (!rv)
    512 		bi_errorf("%s: bad number", as);
    513 	return rv;
    514 }
    515 
    516 /* -------- gmatch.c -------- */
    517 
    518 /*
    519  * int gmatch(string, pattern)
    520  * char *string, *pattern;
    521  *
    522  * Match a pattern as in sh(1).
    523  * pattern character are prefixed with MAGIC by expand.
    524  */
    525 
    526 int
    527 gmatch(s, p, isfile)
    528 	const char *s, *p;
    529 	int isfile;
    530 {
    531 	const char *se, *pe;
    532 
    533 	if (s == NULL || p == NULL)
    534 		return 0;
    535 	se = s + strlen(s);
    536 	pe = p + strlen(p);
    537 	/* isfile is false iff no syntax check has been done on
    538 	 * the pattern.  If check fails, just to a strcmp().
    539 	 */
    540 	if (!isfile && !has_globbing(p, pe)) {
    541 		int len = pe - p + 1;
    542 		char tbuf[64];
    543 		char *t = len <= (int)sizeof(tbuf) ? tbuf
    544 				: (char *) alloc(len, ATEMP);
    545 		debunk(t, p, len);
    546 		return !strcmp(t, s);
    547 	}
    548 	return do_gmatch((const unsigned char *) s, (const unsigned char *) se,
    549 			 (const unsigned char *) p, (const unsigned char *) pe,
    550 			 isfile);
    551 }
    552 
    553 /* Returns if p is a syntacticly correct globbing pattern, false
    554  * if it contains no pattern characters or if there is a syntax error.
    555  * Syntax errors are:
    556  *	- [ with no closing ]
    557  *	- imbalanced $(...) expression
    558  *	- [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
    559  */
    560 /*XXX
    561 - if no magic,
    562 	if dest given, copy to dst
    563 	return ?
    564 - if magic && (no globbing || syntax error)
    565 	debunk to dst
    566 	return ?
    567 - return ?
    568 */
    569 int
    570 has_globbing(xp, xpe)
    571 	const char *xp, *xpe;
    572 {
    573 	const unsigned char *p = (const unsigned char *) xp;
    574 	const unsigned char *pe = (const unsigned char *) xpe;
    575 	int c;
    576 	int nest = 0, bnest = 0;
    577 	int saw_glob = 0;
    578 	int in_bracket = 0; /* inside [...] */
    579 
    580 	for (; p < pe; p++) {
    581 		if (!ISMAGIC(*p))
    582 			continue;
    583 		if ((c = *++p) == '*' || c == '?')
    584 			saw_glob = 1;
    585 		else if (c == '[') {
    586 			if (!in_bracket) {
    587 				saw_glob = 1;
    588 				in_bracket = 1;
    589 				if (ISMAGIC(p[1]) && p[2] == NOT)
    590 					p += 2;
    591 				if (ISMAGIC(p[1]) && p[2] == ']')
    592 					p += 2;
    593 			}
    594 			/* XXX Do we need to check ranges here? POSIX Q */
    595 		} else if (c == ']') {
    596 			if (in_bracket) {
    597 				if (bnest)		/* [a*(b]) */
    598 					return 0;
    599 				in_bracket = 0;
    600 			}
    601 		} else if ((c & 0x80) && strchr("*+?@! ", c & 0x7f)) {
    602 			saw_glob = 1;
    603 			if (in_bracket)
    604 				bnest++;
    605 			else
    606 				nest++;
    607 		} else if (c == '|') {
    608 			if (in_bracket && !bnest)	/* *(a[foo|bar]) */
    609 				return 0;
    610 		} else if (c == /*(*/ ')') {
    611 			if (in_bracket) {
    612 				if (!bnest--)		/* *(a[b)c] */
    613 					return 0;
    614 			} else if (nest)
    615 				nest--;
    616 		}
    617 		/* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
    618 			 MAGIC-{, MAGIC-,, MAGIC-} */
    619 	}
    620 	return saw_glob && !in_bracket && !nest;
    621 }
    622 
    623 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
    624 static int
    625 do_gmatch(s, se, p, pe, isfile)
    626 	const unsigned char *s, *p;
    627 	const unsigned char *se, *pe;
    628 	int isfile;
    629 {
    630 	int sc, pc;
    631 	const unsigned char *prest, *psub, *pnext;
    632 	const unsigned char *srest;
    633 	const unsigned char *sNext, *pNext, *sStart;
    634 
    635 	if (s == NULL || p == NULL)
    636 		return 0;
    637 	sNext = sStart = s;
    638 	pNext = p;
    639 	while (p < pe || s < se) {
    640 		pc = *p;
    641 		sc = s < se ? *s : '\0';
    642 		if (isfile) {
    643 			sc = FILECHCONV((unsigned char)sc);
    644 			pc = FILECHCONV((unsigned char)pc);
    645 		}
    646 		if (!ISMAGIC(pc)) {
    647 			if (sc != pc)
    648 				goto backtrack;
    649 			p++;
    650 			s++;
    651 			continue;
    652 		} else
    653 			pc = *++p;
    654 		switch (pc) {
    655 		  case '[':
    656 			p++;
    657 			s++;
    658 			if (sc == 0 || (p = cclass(p, sc)) == NULL)
    659 				break;
    660 			continue;
    661 
    662 		  case '?':
    663 			if (sc == 0)
    664 				break;
    665 			p++;
    666 			s++;
    667 			continue;
    668 
    669 		  case '*':
    670 			pNext = p - 1;
    671 			sNext = s + 1;
    672 			p++;
    673 			continue;
    674 		  /*
    675 		   * [*+?@!](pattern|pattern|..)
    676 		   *
    677 		   * Not ifdef'd KSH as this is needed for ${..%..}, etc.
    678 		   */
    679 		  case 0x80|'+': /* matches one or more times */
    680 		  case 0x80|'*': /* matches zero or more times */
    681 			if (!(prest = pat_scan(++p, pe, 0)))
    682 				return 0;
    683 			/* take care of zero matches */
    684 			if (p[-1] == (0x80 | '*')
    685 			    && do_gmatch(s, se, prest, pe, isfile))
    686 				return 1;
    687 			for (psub = p; ; psub = pnext) {
    688 				pnext = pat_scan(psub, pe, 1);
    689 				for (srest = s; srest <= se; srest++) {
    690 					if (do_gmatch(s, srest,
    691 						psub, pnext - 2, isfile)
    692 					    && (do_gmatch(srest, se,
    693 							  prest, pe, isfile)
    694 						|| (s != srest
    695 						    && do_gmatch(srest, se,
    696 							p - 2, pe, isfile))))
    697 						return 1;
    698 				}
    699 				if (pnext == prest)
    700 					break;
    701 			}
    702 			return 0;
    703 
    704 		  case 0x80|'?': /* matches zero or once */
    705 		  case 0x80|'@': /* matches one of the patterns */
    706 		  case 0x80|' ': /* simile for @ */
    707 			if (!(prest = pat_scan(++p, pe, 0)))
    708 				return 0;
    709 			/* Take care of zero matches */
    710 			if (p[-1] == (0x80 | '?')
    711 			    && do_gmatch(s, se, prest, pe, isfile))
    712 				return 1;
    713 			for (psub = p; ; psub = pnext) {
    714 				pnext = pat_scan(psub, pe, 1);
    715 				srest = prest == pe ? se : s;
    716 				for (; srest <= se; srest++) {
    717 					if (do_gmatch(s, srest,
    718 						      psub, pnext - 2, isfile)
    719 					    && do_gmatch(srest, se,
    720 							 prest, pe, isfile))
    721 						return 1;
    722 				}
    723 				if (pnext == prest)
    724 					break;
    725 			}
    726 			return 0;
    727 
    728 		  case 0x80|'!': /* matches none of the patterns */
    729 			if (!(prest = pat_scan(++p, pe, 0)))
    730 				return 0;
    731 			for (srest = s; srest <= se; srest++) {
    732 				int matched = 0;
    733 
    734 				for (psub = p; ; psub = pnext) {
    735 					pnext = pat_scan(psub, pe, 1);
    736 					if (do_gmatch(s, srest,
    737 						      psub, pnext - 2, isfile))
    738 					{
    739 						matched = 1;
    740 						break;
    741 					}
    742 					if (pnext == prest)
    743 						break;
    744 				}
    745 				if (!matched && do_gmatch(srest, se,
    746 							  prest, pe, isfile))
    747 					return 1;
    748 			}
    749 			return 0;
    750 
    751 		  default:
    752 			if (sc != pc)
    753 				break;
    754 			p++;
    755 			s++;
    756 			continue;
    757 		}
    758 backtrack:	if (sNext != sStart && sNext <= se) {
    759 			p = pNext;
    760 			s = sNext;
    761 			continue;
    762 		}
    763 		return 0;
    764 	}
    765 	return 1;
    766 }
    767 
    768 static const unsigned char *
    769 cclass(p, sub)
    770 	const unsigned char *p;
    771 	register int sub;
    772 {
    773 	register int c, d, not, found = 0;
    774 	const unsigned char *orig_p = p;
    775 
    776 	if ((not = (ISMAGIC(*p) && *++p == NOT)))
    777 		p++;
    778 	do {
    779 		c = *p++;
    780 		if (ISMAGIC(c)) {
    781 			c = *p++;
    782 			if ((c & 0x80) && !ISMAGIC(c)) {
    783 				c &= 0x7f;/* extended pattern matching: *+?@! */
    784 				/* XXX the ( char isn't handled as part of [] */
    785 				if (c == ' ') /* simile for @: plain (..) */
    786 					c = '(' /*)*/;
    787 			}
    788 		}
    789 		if (c == '\0')
    790 			/* No closing ] - act as if the opening [ was quoted */
    791 			return sub == '[' ? orig_p : NULL;
    792 		if (ISMAGIC(p[0]) && p[1] == '-'
    793 		    && (!ISMAGIC(p[2]) || p[3] != ']'))
    794 		{
    795 			p += 2; /* MAGIC- */
    796 			d = *p++;
    797 			if (ISMAGIC(d)) {
    798 				d = *p++;
    799 				if ((d & 0x80) && !ISMAGIC(d))
    800 					d &= 0x7f;
    801 			}
    802 			/* POSIX says this is an invalid expression */
    803 			if (c > d)
    804 				return NULL;
    805 		} else
    806 			d = c;
    807 		if (c == sub || (c <= sub && sub <= d))
    808 			found = 1;
    809 	} while (!(ISMAGIC(p[0]) && p[1] == ']'));
    810 
    811 	return (found != not) ? p+2 : NULL;
    812 }
    813 
    814 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
    815 const unsigned char *
    816 pat_scan(p, pe, match_sep)
    817 	const unsigned char *p;
    818 	const unsigned char *pe;
    819 	int match_sep;
    820 {
    821 	int nest = 0;
    822 
    823 	for (; p < pe; p++) {
    824 		if (!ISMAGIC(*p))
    825 			continue;
    826 		if ((*++p == /*(*/ ')' && nest-- == 0)
    827 		    || (*p == '|' && match_sep && nest == 0))
    828 			return ++p;
    829 		if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
    830 			nest++;
    831 	}
    832 	return (const unsigned char *) 0;
    833 }
    834 
    835 
    836 /* -------- qsort.c -------- */
    837 
    838 /*
    839  * quick sort of array of generic pointers to objects.
    840  */
    841 static void qsort1 ARGS((void **base, void **lim, int (*f)(void *, void *)));
    842 
    843 void
    844 qsortp(base, n, f)
    845 	void **base;				/* base address */
    846 	size_t n;				/* elements */
    847 	int (*f) ARGS((void *, void *));	/* compare function */
    848 {
    849 	qsort1(base, base + n, f);
    850 }
    851 
    852 #define	swap2(a, b)	{\
    853 	register void *t; t = *(a); *(a) = *(b); *(b) = t;\
    854 }
    855 #define	swap3(a, b, c)	{\
    856 	register void *t; t = *(a); *(a) = *(c); *(c) = *(b); *(b) = t;\
    857 }
    858 
    859 static void
    860 qsort1(base, lim, f)
    861 	void **base, **lim;
    862 	int (*f) ARGS((void *, void *));
    863 {
    864 	register void **i, **j;
    865 	register void **lptr, **hptr;
    866 	size_t n;
    867 	int c;
    868 
    869   top:
    870 	n = (lim - base) / 2;
    871 	if (n == 0)
    872 		return;
    873 	hptr = lptr = base+n;
    874 	i = base;
    875 	j = lim - 1;
    876 
    877 	for (;;) {
    878 		if (i < lptr) {
    879 			if ((c = (*f)(*i, *lptr)) == 0) {
    880 				lptr--;
    881 				swap2(i, lptr);
    882 				continue;
    883 			}
    884 			if (c < 0) {
    885 				i += 1;
    886 				continue;
    887 			}
    888 		}
    889 
    890 	  begin:
    891 		if (j > hptr) {
    892 			if ((c = (*f)(*hptr, *j)) == 0) {
    893 				hptr++;
    894 				swap2(hptr, j);
    895 				goto begin;
    896 			}
    897 			if (c > 0) {
    898 				if (i == lptr) {
    899 					hptr++;
    900 					swap3(i, hptr, j);
    901 					i = lptr += 1;
    902 					goto begin;
    903 				}
    904 				swap2(i, j);
    905 				j -= 1;
    906 				i += 1;
    907 				continue;
    908 			}
    909 			j -= 1;
    910 			goto begin;
    911 		}
    912 
    913 		if (i == lptr) {
    914 			if (lptr-base >= lim-hptr) {
    915 				qsort1(hptr+1, lim, f);
    916 				lim = lptr;
    917 			} else {
    918 				qsort1(base, lptr, f);
    919 				base = hptr+1;
    920 			}
    921 			goto top;
    922 		}
    923 
    924 		lptr -= 1;
    925 		swap3(j, lptr, i);
    926 		j = hptr -= 1;
    927 	}
    928 }
    929 
    930 int
    931 xstrcmp(p1, p2)
    932 	void *p1, *p2;
    933 {
    934 	return (strcmp((char *)p1, (char *)p2));
    935 }
    936 
    937 /* Initialize a Getopt structure */
    938 void
    939 ksh_getopt_reset(go, flags)
    940 	Getopt *go;
    941 	int flags;
    942 {
    943 	go->optind = 1;
    944 	go->optarg = (char *) 0;
    945 	go->p = 0;
    946 	go->flags = flags;
    947 	go->info = 0;
    948 	go->buf[1] = '\0';
    949 }
    950 
    951 
    952 /* getopt() used for shell built-in commands, the getopts command, and
    953  * command line options.
    954  * A leading ':' in options means don't print errors, instead return '?'
    955  * or ':' and set go->optarg to the offending option character.
    956  * If GF_ERROR is set (and option doesn't start with :), errors result in
    957  * a call to bi_errorf().
    958  *
    959  * Non-standard features:
    960  *	- ';' is like ':' in options, except the argument is optional
    961  *	  (if it isn't present, optarg is set to 0).
    962  *	  Used for 'set -o'.
    963  *	- ',' is like ':' in options, except the argument always immediately
    964  *	  follows the option character (optarg is set to the null string if
    965  *	  the option is missing).
    966  *	  Used for 'read -u2', 'print -u2' and fc -40.
    967  *	- '#' is like ':' in options, expect that the argument is optional
    968  *	  and must start with a digit.  If the argument doesn't start with a
    969  *	  digit, it is assumed to be missing and normal option processing
    970  *	  continues (optarg is set to 0 if the option is missing).
    971  *	  Used for 'typeset -LZ4'.
    972  *	- accepts +c as well as -c IF the GF_PLUSOPT flag is present.  If an
    973  *	  option starting with + is accepted, the GI_PLUS flag will be set
    974  *	  in go->info.
    975  */
    976 int
    977 ksh_getopt(argv, go, options)
    978 	char **argv;
    979 	Getopt *go;
    980 	const char *options;
    981 {
    982 	char c;
    983 	char *o;
    984 
    985 	if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
    986 		char *arg = argv[go->optind], flag = arg ? *arg : '\0';
    987 
    988 		go->p = 1;
    989 		if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
    990 			go->optind++;
    991 			go->p = 0;
    992 			go->info |= GI_MINUSMINUS;
    993 			return EOF;
    994 		}
    995 		if (arg == (char *) 0
    996 		    || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
    997 			&& (!(go->flags & GF_PLUSOPT) || flag != '+'))
    998 		    || (c = arg[1]) == '\0')
    999 		{
   1000 			go->p = 0;
   1001 			return EOF;
   1002 		}
   1003 		go->optind++;
   1004 		go->info &= ~(GI_MINUS|GI_PLUS);
   1005 		go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
   1006 	}
   1007 	go->p++;
   1008 	if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#'
   1009 	    || !(o = strchr(options, c)))
   1010 	{
   1011 		if (options[0] == ':') {
   1012 			go->buf[0] = c;
   1013 			go->optarg = go->buf;
   1014 		} else {
   1015 			warningf(TRUE, "%s%s-%c: unknown option",
   1016 				(go->flags & GF_NONAME) ? "" : argv[0],
   1017 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1018 			if (go->flags & GF_ERROR)
   1019 				bi_errorf("%s", null);
   1020 		}
   1021 		return '?';
   1022 	}
   1023 	/* : means argument must be present, may be part of option argument
   1024 	 *   or the next argument
   1025 	 * ; same as : but argument may be missing
   1026 	 * , means argument is part of option argument, and may be null.
   1027 	 */
   1028 	if (*++o == ':' || *o == ';') {
   1029 		if (argv[go->optind - 1][go->p])
   1030 			go->optarg = argv[go->optind - 1] + go->p;
   1031 		else if (argv[go->optind])
   1032 			go->optarg = argv[go->optind++];
   1033 		else if (*o == ';')
   1034 			go->optarg = (char *) 0;
   1035 		else {
   1036 			if (options[0] == ':') {
   1037 				go->buf[0] = c;
   1038 				go->optarg = go->buf;
   1039 				return ':';
   1040 			}
   1041 			warningf(TRUE, "%s%s-`%c' requires argument",
   1042 				(go->flags & GF_NONAME) ? "" : argv[0],
   1043 				(go->flags & GF_NONAME) ? "" : ": ", c);
   1044 			if (go->flags & GF_ERROR)
   1045 				bi_errorf("%s", null);
   1046 			return '?';
   1047 		}
   1048 		go->p = 0;
   1049 	} else if (*o == ',') {
   1050 		/* argument is attached to option character, even if null */
   1051 		go->optarg = argv[go->optind - 1] + go->p;
   1052 		go->p = 0;
   1053 	} else if (*o == '#') {
   1054 		/* argument is optional and may be attached or unattached
   1055 		 * but must start with a digit.  optarg is set to 0 if the
   1056 		 * argument is missing.
   1057 		 */
   1058 		if (argv[go->optind - 1][go->p]) {
   1059 			if (digit(argv[go->optind - 1][go->p])) {
   1060 				go->optarg = argv[go->optind - 1] + go->p;
   1061 				go->p = 0;
   1062 			} else
   1063 				go->optarg = (char *) 0;
   1064 		} else {
   1065 			if (argv[go->optind] && digit(argv[go->optind][0])) {
   1066 				go->optarg = argv[go->optind++];
   1067 				go->p = 0;
   1068 			} else
   1069 				go->optarg = (char *) 0;
   1070 		}
   1071 	}
   1072 	return c;
   1073 }
   1074 
   1075 /* print variable/alias value using necessary quotes
   1076  * (POSIX says they should be suitable for re-entry...)
   1077  * No trailing newline is printed.
   1078  */
   1079 void
   1080 print_value_quoted(s)
   1081 	const char *s;
   1082 {
   1083 	const char *p;
   1084 	int inquote = 0;
   1085 
   1086 	/* Test if any quotes are needed */
   1087 	for (p = s; *p; p++)
   1088 		if (ctype(*p, C_QUOTE))
   1089 			break;
   1090 	if (!*p) {
   1091 		shprintf("%s", s);
   1092 		return;
   1093 	}
   1094 	for (p = s; *p; p++) {
   1095 		if (*p == '\'') {
   1096 			shprintf("%s", "'\\'" + 1 - inquote);
   1097 			inquote = 0;
   1098 		} else {
   1099 			if (!inquote) {
   1100 				shprintf("'");
   1101 				inquote = 1;
   1102 			}
   1103 			shf_putc(*p, shl_stdout);
   1104 		}
   1105 	}
   1106 	if (inquote)
   1107 		shprintf("'");
   1108 }
   1109 
   1110 /* Print things in columns and rows - func() is called to format the ith
   1111  * element
   1112  */
   1113 void
   1114 print_columns(shf, n, func, arg, max_width, prefcol)
   1115 	struct shf *shf;
   1116 	int n;
   1117 	char *(*func) ARGS((void *, int, char *, int));
   1118 	void *arg;
   1119 	int max_width;
   1120 	int prefcol;
   1121 {
   1122 	char *str = (char *) alloc(max_width + 1, ATEMP);
   1123 	int i;
   1124 	int r, c;
   1125 	int rows, cols;
   1126 	int nspace;
   1127 
   1128 	/* max_width + 1 for the space.  Note that no space
   1129 	 * is printed after the last column to avoid problems
   1130 	 * with terminals that have auto-wrap.
   1131 	 */
   1132 	cols = x_cols / (max_width + 1);
   1133 	if (!cols)
   1134 		cols = 1;
   1135 	rows = (n + cols - 1) / cols;
   1136 	if (prefcol && n && cols > rows) {
   1137 		int tmp = rows;
   1138 
   1139 		rows = cols;
   1140 		cols = tmp;
   1141 		if (rows > n)
   1142 			rows = n;
   1143 	}
   1144 
   1145 	nspace = (x_cols - max_width * cols) / cols;
   1146 	if (nspace <= 0)
   1147 		nspace = 1;
   1148 	for (r = 0; r < rows; r++) {
   1149 		for (c = 0; c < cols; c++) {
   1150 			i = c * rows + r;
   1151 			if (i < n) {
   1152 				shf_fprintf(shf, "%-*s",
   1153 					max_width,
   1154 					(*func)(arg, i, str, max_width + 1));
   1155 				if (c + 1 < cols)
   1156 					shf_fprintf(shf, "%*s", nspace, null);
   1157 			}
   1158 		}
   1159 		shf_putchar('\n', shf);
   1160 	}
   1161 	afree(str, ATEMP);
   1162 }
   1163 
   1164 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
   1165 int
   1166 strip_nuls(buf, nbytes)
   1167 	char *buf;
   1168 	int nbytes;
   1169 {
   1170 	char *dst;
   1171 
   1172 	/* nbytes check because some systems (older freebsd's) have a buggy
   1173 	 * memchr()
   1174 	 */
   1175 	if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
   1176 		char *end = buf + nbytes;
   1177 		char *p, *q;
   1178 
   1179 		for (p = dst; p < end; p = q) {
   1180 			/* skip a block of nulls */
   1181 			while (++p < end && *p == '\0')
   1182 				;
   1183 			/* find end of non-null block */
   1184 			if (!(q = memchr(p, '\0', end - p)))
   1185 				q = end;
   1186 			memmove(dst, p, q - p);
   1187 			dst += q - p;
   1188 		}
   1189 		*dst = '\0';
   1190 		return dst - buf;
   1191 	}
   1192 	return nbytes;
   1193 }
   1194 
   1195 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
   1196  * Returns dst.
   1197  */
   1198 char *
   1199 str_zcpy(dst, src, dsize)
   1200 	char *dst;
   1201 	const char *src;
   1202 	int dsize;
   1203 {
   1204 	if (dsize > 0) {
   1205 		int len = strlen(src);
   1206 
   1207 		if (len >= dsize)
   1208 			len = dsize - 1;
   1209 		memcpy(dst, src, len);
   1210 		dst[len] = '\0';
   1211 	}
   1212 	return dst;
   1213 }
   1214 
   1215 /* Like read(2), but if read fails due to non-blocking flag, resets flag
   1216  * and restarts read.
   1217  */
   1218 int
   1219 blocking_read(fd, buf, nbytes)
   1220 	int fd;
   1221 	char *buf;
   1222 	int nbytes;
   1223 {
   1224 	int ret;
   1225 	int tried_reset = 0;
   1226 
   1227 	while ((ret = read(fd, buf, nbytes)) < 0) {
   1228 		if (!tried_reset && (errno == EAGAIN
   1229 #ifdef EWOULDBLOCK
   1230 				     || errno == EWOULDBLOCK
   1231 #endif /* EWOULDBLOCK */
   1232 				    ))
   1233 		{
   1234 			int oerrno = errno;
   1235 			if (reset_nonblock(fd) > 0) {
   1236 				tried_reset = 1;
   1237 				continue;
   1238 			}
   1239 			errno = oerrno;
   1240 		}
   1241 		break;
   1242 	}
   1243 	return ret;
   1244 }
   1245 
   1246 /* Reset the non-blocking flag on the specified file descriptor.
   1247  * Returns -1 if there was an error, 0 if non-blocking wasn't set,
   1248  * 1 if it was.
   1249  */
   1250 int
   1251 reset_nonblock(fd)
   1252 	int fd;
   1253 {
   1254 	int flags;
   1255 	int blocking_flags;
   1256 
   1257 	if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
   1258 		return -1;
   1259 	/* With luck, the C compiler will reduce this to a constant */
   1260 	blocking_flags = 0;
   1261 #ifdef O_NONBLOCK
   1262 	blocking_flags |= O_NONBLOCK;
   1263 #endif /* O_NONBLOCK */
   1264 #ifdef O_NDELAY
   1265 	blocking_flags |= O_NDELAY;
   1266 #else /* O_NDELAY */
   1267 # ifndef O_NONBLOCK
   1268 	blocking_flags |= FNDELAY; /* hope this exists... */
   1269 # endif /* O_NONBLOCK */
   1270 #endif /* O_NDELAY */
   1271 	if (!(flags & blocking_flags))
   1272 		return 0;
   1273 	flags &= ~blocking_flags;
   1274 	if (fcntl(fd, F_SETFL, flags) < 0)
   1275 		return -1;
   1276 	return 1;
   1277 }
   1278 
   1279 
   1280 #ifdef HAVE_SYS_PARAM_H
   1281 # include <sys/param.h>
   1282 #endif /* HAVE_SYS_PARAM_H */
   1283 #ifndef MAXPATHLEN
   1284 # define MAXPATHLEN PATH
   1285 #endif /* MAXPATHLEN */
   1286 
   1287 /* Like getcwd(), except bsize is ignored if buf is 0 (MAXPATHLEN is used) */
   1288 char *
   1289 ksh_get_wd(buf, bsize)
   1290 	char *buf;
   1291 	int bsize;
   1292 {
   1293 #ifdef HAVE_GETCWD
   1294 	char *b;
   1295 	char *ret;
   1296 
   1297 	/* Assume getcwd() available */
   1298 	if (!buf) {
   1299 		bsize = MAXPATHLEN;
   1300 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1301 	} else
   1302 		b = buf;
   1303 
   1304 	ret = getcwd(b, bsize);
   1305 
   1306 	if (!buf) {
   1307 		if (ret)
   1308 			ret = aresize(b, strlen(b) + 1, ATEMP);
   1309 		else
   1310 			afree(b, ATEMP);
   1311 	}
   1312 
   1313 	return ret;
   1314 #else /* HAVE_GETCWD */
   1315 	extern char *getwd ARGS((char *));
   1316 	char *b;
   1317 	int len;
   1318 
   1319 	if (buf && bsize > MAXPATHLEN)
   1320 		b = buf;
   1321 	else
   1322 		b = alloc(MAXPATHLEN + 1, ATEMP);
   1323 	if (!getcwd(b, MAXPATHLEN)) {
   1324 		errno = EACCES;
   1325 		if (b != buf)
   1326 			afree(b, ATEMP);
   1327 		return (char *) 0;
   1328 	}
   1329 	len = strlen(b) + 1;
   1330 	if (!buf)
   1331 		b = aresize(b, len, ATEMP);
   1332 	else if (buf != b) {
   1333 		if (len > bsize) {
   1334 			errno = ERANGE;
   1335 			return (char *) 0;
   1336 		}
   1337 		memcpy(buf, b, len);
   1338 		afree(b, ATEMP);
   1339 		b = buf;
   1340 	}
   1341 
   1342 	return b;
   1343 #endif /* HAVE_GETCWD */
   1344 }
   1345