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