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