Remove building with NOCRYPTO option
[minix.git] / bin / ksh / misc.c
blob94ae44b2c835c6b574b7bcaa6529d4142b3bd7fb
1 /* $NetBSD: misc.c,v 1.15 2011/10/16 17:12:11 joerg Exp $ */
3 /*
4 * Miscellaneous functions
5 */
6 #include <sys/cdefs.h>
8 #ifndef lint
9 __RCSID("$NetBSD: misc.c,v 1.15 2011/10/16 17:12:11 joerg Exp $");
10 #endif
13 #include "sh.h"
14 #include <ctype.h> /* for FILECHCONV */
15 #ifdef HAVE_LIMITS_H
16 # include <limits.h>
17 #endif
19 #ifndef UCHAR_MAX
20 # define UCHAR_MAX 0xFF
21 #endif
23 short ctypes [UCHAR_MAX+1]; /* type bits for unsigned char */
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));
31 * Fast character classes
33 void
34 setctypes(s, t)
35 register const char *s;
36 register int t;
38 register int i;
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 */
45 while (*s != 0)
46 ctypes[(unsigned char) *s++] |= t;
49 void
50 initctypes()
52 register int c;
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);
68 /* convert unsigned long to base N string */
70 char *
71 ulton(n, base)
72 register unsigned long n;
73 int base;
75 register char *p;
76 static char buf [20];
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;
87 char *
88 str_save(s, ap)
89 register const char *s;
90 Area *ap;
92 size_t len;
93 char *p;
95 if (!s)
96 return NULL;
97 len = strlen(s)+1;
98 p = alloc(len, ap);
99 strlcpy(p, s, len);
100 return (p);
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).
107 char *
108 str_nsave(s, n, ap)
109 register const char *s;
110 int n;
111 Area *ap;
113 char *ns;
115 if (n < 0)
116 return 0;
117 ns = alloc(n + 1, ap);
118 ns[0] = '\0';
119 return strncat(ns, s, n);
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;
129 char *old_beg = xsp->beg;
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);
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.
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)
193 { (char *) 0, 0, OF_INTERNAL }, /* FTALKING_I */
197 * translate -o option into F* constant (also used for test -o option)
200 option(n)
201 const char *n;
203 int i;
205 for (i = 0; i < (int)NELEM(goptions); i++)
206 if (goptions[i].name && strcmp(goptions[i].name, n) == 0)
207 return i;
209 return -1;
212 struct options_info {
213 int opt_width;
214 struct {
215 const char *name;
216 int flag;
217 } opts[NELEM(goptions)];
220 static char *options_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
221 static void printoptions ARGS((int verbose));
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;
231 struct options_info *oi = (struct options_info *) arg;
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;
239 static void
240 printoptions(verbose)
241 int verbose;
243 int i;
245 if (verbose) {
246 struct options_info oi;
247 int n, len;
249 /* verbose version */
250 shprintf("Current option settings\n");
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;
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);
272 char *
273 getoptions()
275 size_t i;
276 char m[(int) FNFLAGS + 1];
277 register char *cp = m;
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);
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;
293 int oldval;
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 */
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;
322 } else
323 #endif /* EDIT */
324 /* Turning off -p? */
325 if (f == FPRIVILEGED && oldval && !newval) {
326 #ifdef OS2
328 #else /* OS2 */
329 seteuid(ksheuid = getuid());
330 setuid(ksheuid);
331 setegid(getgid());
332 setgid(getgid());
333 #endif /* OS2 */
334 } else if (f == FPOSIX && newval) {
335 #ifdef BRACE_EXPAND
336 Flag(FBRACEEXPAND) = 0
337 #endif /* BRACE_EXPAND */
340 /* Changing interactive flag? */
341 if (f == FTALKING) {
342 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
343 Flag(FTALKING_I) = newval;
347 /* parse command line & set command arguments. returns the index of
348 * non-option arguments, -1 if there is an error.
351 parse_args(argv, what, setargsp)
352 char **argv;
353 int what; /* OF_CMDLINE or OF_SET */
354 int *setargsp;
356 static char cmd_opts[NELEM(goptions) + 3]; /* o:\0 */
357 static char set_opts[NELEM(goptions) + 5]; /* Ao;s\0 */
358 char *opts;
359 char *array = (char *) 0;
360 Getopt go;
361 int i, optc, set, sortargs = 0, arrayset = 0;
363 /* First call? Build option strings... */
364 if (cmd_opts[0] == '\0') {
365 char *p, *q;
367 /* see cmd_opts[] declaration */
368 strlcpy(cmd_opts, "o:", sizeof cmd_opts);
369 p = cmd_opts + strlen(cmd_opts);
370 /* see set_opts[] declaration */
371 strlcpy(set_opts, "A:o;s", sizeof set_opts);
372 q = set_opts + strlen(set_opts);
373 for (i = 0; i < (int)NELEM(goptions); i++) {
374 if (goptions[i].c) {
375 if (goptions[i].flags & OF_CMDLINE)
376 *p++ = goptions[i].c;
377 if (goptions[i].flags & OF_SET)
378 *q++ = goptions[i].c;
381 *p = '\0';
382 *q = '\0';
385 if (what == OF_CMDLINE) {
386 char *p;
387 /* Set FLOGIN before parsing options so user can clear
388 * flag using +l.
390 Flag(FLOGIN) = (argv[0][0] == '-'
391 || ((p = ksh_strrchr_dirsep(argv[0]))
392 && *++p == '-'));
393 opts = cmd_opts;
394 } else
395 opts = set_opts;
396 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
397 while ((optc = ksh_getopt(argv, &go, opts)) != EOF) {
398 set = (go.info & GI_PLUS) ? 0 : 1;
399 switch (optc) {
400 case 'A':
401 arrayset = set ? 1 : -1;
402 array = go.optarg;
403 break;
405 case 'o':
406 if (go.optarg == (char *) 0) {
407 /* lone -o: print options
409 * Note that on the command line, -o requires
410 * an option (ie, can't get here if what is
411 * OF_CMDLINE).
413 printoptions(set);
414 break;
416 i = option(go.optarg);
417 if (i >= 0 && set == Flag(i))
418 /* Don't check the context if the flag
419 * isn't changing - makes "set -o interactive"
420 * work if you're already interactive. Needed
421 * if the output of "set +o" is to be used.
424 else if (i >= 0 && (goptions[i].flags & what))
425 change_flag((enum sh_flag) i, what, set);
426 else {
427 bi_errorf("%s: bad option", go.optarg);
428 return -1;
430 break;
432 case '?':
433 return -1;
435 default:
436 /* -s: sort positional params (at&t ksh stupidity) */
437 if (what == OF_SET && optc == 's') {
438 sortargs = 1;
439 break;
441 for (i = 0; i < (int)NELEM(goptions); i++)
442 if (optc == goptions[i].c
443 && (what & goptions[i].flags))
445 change_flag((enum sh_flag) i, what,
446 set);
447 break;
449 if (i == NELEM(goptions)) {
450 internal_errorf(1, "parse_args: `%c'", optc);
451 return -1; /* not reached */
455 if (!(go.info & GI_MINUSMINUS) && argv[go.optind]
456 && (argv[go.optind][0] == '-' || argv[go.optind][0] == '+')
457 && argv[go.optind][1] == '\0')
459 /* lone - clears -v and -x flags */
460 if (argv[go.optind][0] == '-' && !Flag(FPOSIX))
461 Flag(FVERBOSE) = Flag(FXTRACE) = 0;
462 /* set skips lone - or + option */
463 go.optind++;
465 if (setargsp)
466 /* -- means set $#/$* even if there are no arguments */
467 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS)
468 || argv[go.optind]);
470 if (arrayset && (!*array || *skip_varname(array, FALSE))) {
471 bi_errorf("%s: is not an identifier", array);
472 return -1;
474 if (sortargs) {
475 for (i = go.optind; argv[i]; i++)
477 qsortp((void **) &argv[go.optind], (size_t) (i - go.optind),
478 xstrcmp);
480 if (arrayset) {
481 set_array(array, arrayset, argv + go.optind);
482 for (; argv[go.optind]; go.optind++)
486 return go.optind;
489 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
491 getn(as, ai)
492 const char *as;
493 int *ai;
495 char *p;
496 long n;
498 n = strtol(as, &p, 10);
500 if (!*as || *p || INT_MIN >= n || n >= INT_MAX)
501 return 0;
503 *ai = (int)n;
504 return 1;
507 /* getn() that prints error */
509 bi_getn(as, ai)
510 const char *as;
511 int *ai;
513 int rv = getn(as, ai);
515 if (!rv)
516 bi_errorf("%s: bad number", as);
517 return rv;
520 /* -------- gmatch.c -------- */
523 * int gmatch(string, pattern)
524 * char *string, *pattern;
526 * Match a pattern as in sh(1).
527 * pattern character are prefixed with MAGIC by expand.
531 gmatch(s, p, isfile)
532 const char *s, *p;
533 int isfile;
535 const char *se, *pe;
537 if (s == NULL || p == NULL)
538 return 0;
539 se = s + strlen(s);
540 pe = p + strlen(p);
541 /* isfile is false iff no syntax check has been done on
542 * the pattern. If check fails, just to a strcmp().
544 if (!isfile && !has_globbing(p, pe)) {
545 int len = pe - p + 1;
546 char tbuf[64];
547 char *t = len <= (int)sizeof(tbuf) ? tbuf
548 : (char *) alloc(len, ATEMP);
549 debunk(t, p, len);
550 return !strcmp(t, s);
552 return do_gmatch((const unsigned char *) s, (const unsigned char *) se,
553 (const unsigned char *) p, (const unsigned char *) pe,
554 isfile);
557 /* Returns if p is a syntacticly correct globbing pattern, false
558 * if it contains no pattern characters or if there is a syntax error.
559 * Syntax errors are:
560 * - [ with no closing ]
561 * - imbalanced $(...) expression
562 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
564 /*XXX
565 - if no magic,
566 if dest given, copy to dst
567 return ?
568 - if magic && (no globbing || syntax error)
569 debunk to dst
570 return ?
571 - return ?
574 has_globbing(xp, xpe)
575 const char *xp, *xpe;
577 const unsigned char *p = (const unsigned char *) xp;
578 const unsigned char *pe = (const unsigned char *) xpe;
579 int c;
580 int nest = 0, bnest = 0;
581 int saw_glob = 0;
582 int in_bracket = 0; /* inside [...] */
584 for (; p < pe; p++) {
585 if (!ISMAGIC(*p))
586 continue;
587 if ((c = *++p) == '*' || c == '?')
588 saw_glob = 1;
589 else if (c == '[') {
590 if (!in_bracket) {
591 saw_glob = 1;
592 in_bracket = 1;
593 if (ISMAGIC(p[1]) && p[2] == NOT)
594 p += 2;
595 if (ISMAGIC(p[1]) && p[2] == ']')
596 p += 2;
598 /* XXX Do we need to check ranges here? POSIX Q */
599 } else if (c == ']') {
600 if (in_bracket) {
601 if (bnest) /* [a*(b]) */
602 return 0;
603 in_bracket = 0;
605 } else if ((c & 0x80) && strchr("*+?@! ", c & 0x7f)) {
606 saw_glob = 1;
607 if (in_bracket)
608 bnest++;
609 else
610 nest++;
611 } else if (c == '|') {
612 if (in_bracket && !bnest) /* *(a[foo|bar]) */
613 return 0;
614 } else if (c == /*(*/ ')') {
615 if (in_bracket) {
616 if (!bnest--) /* *(a[b)c] */
617 return 0;
618 } else if (nest)
619 nest--;
621 /* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
622 MAGIC-{, MAGIC-,, MAGIC-} */
624 return saw_glob && !in_bracket && !nest;
627 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
628 static int
629 do_gmatch(s, se, p, pe, isfile)
630 const unsigned char *s, *p;
631 const unsigned char *se, *pe;
632 int isfile;
634 register int sc, pc;
635 const unsigned char *prest, *psub, *pnext;
636 const unsigned char *srest;
638 if (s == NULL || p == NULL)
639 return 0;
640 while (p < pe) {
641 pc = *p++;
642 sc = s < se ? *s : '\0';
643 s++;
644 if (isfile) {
645 sc = FILECHCONV((unsigned char)sc);
646 pc = FILECHCONV((unsigned char)pc);
648 if (!ISMAGIC(pc)) {
649 if (sc != pc)
650 return 0;
651 continue;
653 switch (*p++) {
654 case '[':
655 if (sc == 0 || (p = cclass(p, sc)) == NULL)
656 return 0;
657 break;
659 case '?':
660 if (sc == 0)
661 return 0;
662 break;
664 case '*':
665 if (p == pe)
666 return 1;
667 s--;
668 do {
669 if (do_gmatch(s, se, p, pe, isfile))
670 return 1;
671 } while (s++ < se);
672 return 0;
675 * [*+?@!](pattern|pattern|..)
677 * Not ifdef'd KSH as this is needed for ${..%..}, etc.
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 s--;
684 /* take care of zero matches */
685 if (p[-1] == (0x80 | '*')
686 && do_gmatch(s, se, prest, pe, isfile))
687 return 1;
688 for (psub = p; ; psub = pnext) {
689 pnext = pat_scan(psub, pe, 1);
690 for (srest = s; srest <= se; srest++) {
691 if (do_gmatch(s, srest,
692 psub, pnext - 2, isfile)
693 && (do_gmatch(srest, se,
694 prest, pe, isfile)
695 || (s != srest
696 && do_gmatch(srest, se,
697 p - 2, pe, isfile))))
698 return 1;
700 if (pnext == prest)
701 break;
703 return 0;
705 case 0x80|'?': /* matches zero or once */
706 case 0x80|'@': /* matches one of the patterns */
707 case 0x80|' ': /* simile for @ */
708 if (!(prest = pat_scan(p, pe, 0)))
709 return 0;
710 s--;
711 /* Take care of zero matches */
712 if (p[-1] == (0x80 | '?')
713 && do_gmatch(s, se, prest, pe, isfile))
714 return 1;
715 for (psub = p; ; psub = pnext) {
716 pnext = pat_scan(psub, pe, 1);
717 srest = prest == pe ? se : s;
718 for (; srest <= se; srest++) {
719 if (do_gmatch(s, srest,
720 psub, pnext - 2, isfile)
721 && do_gmatch(srest, se,
722 prest, pe, isfile))
723 return 1;
725 if (pnext == prest)
726 break;
728 return 0;
730 case 0x80|'!': /* matches none of the patterns */
731 if (!(prest = pat_scan(p, pe, 0)))
732 return 0;
733 s--;
734 for (srest = s; srest <= se; srest++) {
735 int matched = 0;
737 for (psub = p; ; psub = pnext) {
738 pnext = pat_scan(psub, pe, 1);
739 if (do_gmatch(s, srest,
740 psub, pnext - 2, isfile))
742 matched = 1;
743 break;
745 if (pnext == prest)
746 break;
748 if (!matched && do_gmatch(srest, se,
749 prest, pe, isfile))
750 return 1;
752 return 0;
754 default:
755 if (sc != p[-1])
756 return 0;
757 break;
760 return s == se;
763 static const unsigned char *
764 cclass(p, sub)
765 const unsigned char *p;
766 register int sub;
768 register int c, d, not, found = 0;
769 const unsigned char *orig_p = p;
771 if ((not = (ISMAGIC(*p) && *++p == NOT)))
772 p++;
773 do {
774 c = *p++;
775 if (ISMAGIC(c)) {
776 c = *p++;
777 if ((c & 0x80) && !ISMAGIC(c)) {
778 c &= 0x7f;/* extended pattern matching: *+?@! */
779 /* XXX the ( char isn't handled as part of [] */
780 if (c == ' ') /* simile for @: plain (..) */
781 c = '(' /*)*/;
784 if (c == '\0')
785 /* No closing ] - act as if the opening [ was quoted */
786 return sub == '[' ? orig_p : NULL;
787 if (ISMAGIC(p[0]) && p[1] == '-'
788 && (!ISMAGIC(p[2]) || p[3] != ']'))
790 p += 2; /* MAGIC- */
791 d = *p++;
792 if (ISMAGIC(d)) {
793 d = *p++;
794 if ((d & 0x80) && !ISMAGIC(d))
795 d &= 0x7f;
797 /* POSIX says this is an invalid expression */
798 if (c > d)
799 return NULL;
800 } else
801 d = c;
802 if (c == sub || (c <= sub && sub <= d))
803 found = 1;
804 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
806 return (found != not) ? p+2 : NULL;
809 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
810 const unsigned char *
811 pat_scan(p, pe, match_sep)
812 const unsigned char *p;
813 const unsigned char *pe;
814 int match_sep;
816 int nest = 0;
818 for (; p < pe; p++) {
819 if (!ISMAGIC(*p))
820 continue;
821 if ((*++p == /*(*/ ')' && nest-- == 0)
822 || (*p == '|' && match_sep && nest == 0))
823 return ++p;
824 if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
825 nest++;
827 return (const unsigned char *) 0;
831 /* -------- qsort.c -------- */
834 * quick sort of array of generic pointers to objects.
836 static void qsort1 ARGS((void **base, void **lim, int (*f)(void *, void *)));
838 void
839 qsortp(base, n, f)
840 void **base; /* base address */
841 size_t n; /* elements */
842 int (*f) ARGS((void *, void *)); /* compare function */
844 qsort1(base, base + n, f);
847 #define swap2(a, b) {\
848 register void *t; t = *(a); *(a) = *(b); *(b) = t;\
850 #define swap3(a, b, c) {\
851 register void *t; t = *(a); *(a) = *(c); *(c) = *(b); *(b) = t;\
854 static void
855 qsort1(base, lim, f)
856 void **base, **lim;
857 int (*f) ARGS((void *, void *));
859 register void **i, **j;
860 register void **lptr, **hptr;
861 size_t n;
862 int c;
864 top:
865 n = (lim - base) / 2;
866 if (n == 0)
867 return;
868 hptr = lptr = base+n;
869 i = base;
870 j = lim - 1;
872 for (;;) {
873 if (i < lptr) {
874 if ((c = (*f)(*i, *lptr)) == 0) {
875 lptr--;
876 swap2(i, lptr);
877 continue;
879 if (c < 0) {
880 i += 1;
881 continue;
885 begin:
886 if (j > hptr) {
887 if ((c = (*f)(*hptr, *j)) == 0) {
888 hptr++;
889 swap2(hptr, j);
890 goto begin;
892 if (c > 0) {
893 if (i == lptr) {
894 hptr++;
895 swap3(i, hptr, j);
896 i = lptr += 1;
897 goto begin;
899 swap2(i, j);
900 j -= 1;
901 i += 1;
902 continue;
904 j -= 1;
905 goto begin;
908 if (i == lptr) {
909 if (lptr-base >= lim-hptr) {
910 qsort1(hptr+1, lim, f);
911 lim = lptr;
912 } else {
913 qsort1(base, lptr, f);
914 base = hptr+1;
916 goto top;
919 lptr -= 1;
920 swap3(j, lptr, i);
921 j = hptr -= 1;
926 xstrcmp(p1, p2)
927 void *p1, *p2;
929 return (strcmp((char *)p1, (char *)p2));
932 /* Initialize a Getopt structure */
933 void
934 ksh_getopt_reset(go, flags)
935 Getopt *go;
936 int flags;
938 go->optind = 1;
939 go->optarg = (char *) 0;
940 go->p = 0;
941 go->flags = flags;
942 go->info = 0;
943 go->buf[1] = '\0';
947 /* getopt() used for shell built-in commands, the getopts command, and
948 * command line options.
949 * A leading ':' in options means don't print errors, instead return '?'
950 * or ':' and set go->optarg to the offending option character.
951 * If GF_ERROR is set (and option doesn't start with :), errors result in
952 * a call to bi_errorf().
954 * Non-standard features:
955 * - ';' is like ':' in options, except the argument is optional
956 * (if it isn't present, optarg is set to 0).
957 * Used for 'set -o'.
958 * - ',' is like ':' in options, except the argument always immediately
959 * follows the option character (optarg is set to the null string if
960 * the option is missing).
961 * Used for 'read -u2', 'print -u2' and fc -40.
962 * - '#' is like ':' in options, expect that the argument is optional
963 * and must start with a digit. If the argument doesn't start with a
964 * digit, it is assumed to be missing and normal option processing
965 * continues (optarg is set to 0 if the option is missing).
966 * Used for 'typeset -LZ4'.
967 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
968 * option starting with + is accepted, the GI_PLUS flag will be set
969 * in go->info.
972 ksh_getopt(argv, go, options)
973 char **argv;
974 Getopt *go;
975 const char *options;
977 char c;
978 char *o;
980 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
981 char *arg = argv[go->optind], flag = arg ? *arg : '\0';
983 go->p = 1;
984 if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
985 go->optind++;
986 go->p = 0;
987 go->info |= GI_MINUSMINUS;
988 return EOF;
990 if (arg == (char *) 0
991 || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
992 && (!(go->flags & GF_PLUSOPT) || flag != '+'))
993 || (c = arg[1]) == '\0')
995 go->p = 0;
996 return EOF;
998 go->optind++;
999 go->info &= ~(GI_MINUS|GI_PLUS);
1000 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
1002 go->p++;
1003 if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#'
1004 || !(o = strchr(options, c)))
1006 if (options[0] == ':') {
1007 go->buf[0] = c;
1008 go->optarg = go->buf;
1009 } else {
1010 warningf(TRUE, "%s%s-%c: unknown option",
1011 (go->flags & GF_NONAME) ? "" : argv[0],
1012 (go->flags & GF_NONAME) ? "" : ": ", c);
1013 if (go->flags & GF_ERROR)
1014 bi_errorf("%s", null);
1016 return '?';
1018 /* : means argument must be present, may be part of option argument
1019 * or the next argument
1020 * ; same as : but argument may be missing
1021 * , means argument is part of option argument, and may be null.
1023 if (*++o == ':' || *o == ';') {
1024 if (argv[go->optind - 1][go->p])
1025 go->optarg = argv[go->optind - 1] + go->p;
1026 else if (argv[go->optind])
1027 go->optarg = argv[go->optind++];
1028 else if (*o == ';')
1029 go->optarg = (char *) 0;
1030 else {
1031 if (options[0] == ':') {
1032 go->buf[0] = c;
1033 go->optarg = go->buf;
1034 return ':';
1036 warningf(TRUE, "%s%s-`%c' requires argument",
1037 (go->flags & GF_NONAME) ? "" : argv[0],
1038 (go->flags & GF_NONAME) ? "" : ": ", c);
1039 if (go->flags & GF_ERROR)
1040 bi_errorf("%s", null);
1041 return '?';
1043 go->p = 0;
1044 } else if (*o == ',') {
1045 /* argument is attached to option character, even if null */
1046 go->optarg = argv[go->optind - 1] + go->p;
1047 go->p = 0;
1048 } else if (*o == '#') {
1049 /* argument is optional and may be attached or unattached
1050 * but must start with a digit. optarg is set to 0 if the
1051 * argument is missing.
1053 if (argv[go->optind - 1][go->p]) {
1054 if (digit(argv[go->optind - 1][go->p])) {
1055 go->optarg = argv[go->optind - 1] + go->p;
1056 go->p = 0;
1057 } else
1058 go->optarg = (char *) 0;
1059 } else {
1060 if (argv[go->optind] && digit(argv[go->optind][0])) {
1061 go->optarg = argv[go->optind++];
1062 go->p = 0;
1063 } else
1064 go->optarg = (char *) 0;
1067 return c;
1070 /* print variable/alias value using necessary quotes
1071 * (POSIX says they should be suitable for re-entry...)
1072 * No trailing newline is printed.
1074 void
1075 print_value_quoted(s)
1076 const char *s;
1078 const char *p;
1079 int inquote = 0;
1081 /* Test if any quotes are needed */
1082 for (p = s; *p; p++)
1083 if (ctype(*p, C_QUOTE))
1084 break;
1085 if (!*p) {
1086 shprintf("%s", s);
1087 return;
1089 for (p = s; *p; p++) {
1090 if (*p == '\'') {
1091 shprintf("%s", "'\\'" + 1 - inquote);
1092 inquote = 0;
1093 } else {
1094 if (!inquote) {
1095 shprintf("'");
1096 inquote = 1;
1098 shf_putc(*p, shl_stdout);
1101 if (inquote)
1102 shprintf("'");
1105 /* Print things in columns and rows - func() is called to format the ith
1106 * element
1108 void
1109 print_columns(shf, n, func, arg, max_width, prefcol)
1110 struct shf *shf;
1111 int n;
1112 char *(*func) ARGS((void *, int, char *, int));
1113 void *arg;
1114 int max_width;
1115 int prefcol;
1117 char *str = (char *) alloc(max_width + 1, ATEMP);
1118 int i;
1119 int r, c;
1120 int rows, cols;
1121 int nspace;
1123 /* max_width + 1 for the space. Note that no space
1124 * is printed after the last column to avoid problems
1125 * with terminals that have auto-wrap.
1127 cols = x_cols / (max_width + 1);
1128 if (!cols)
1129 cols = 1;
1130 rows = (n + cols - 1) / cols;
1131 if (prefcol && n && cols > rows) {
1132 int tmp = rows;
1134 rows = cols;
1135 cols = tmp;
1136 if (rows > n)
1137 rows = n;
1140 nspace = (x_cols - max_width * cols) / cols;
1141 if (nspace <= 0)
1142 nspace = 1;
1143 for (r = 0; r < rows; r++) {
1144 for (c = 0; c < cols; c++) {
1145 i = c * rows + r;
1146 if (i < n) {
1147 shf_fprintf(shf, "%-*s",
1148 max_width,
1149 (*func)(arg, i, str, max_width + 1));
1150 if (c + 1 < cols)
1151 shf_fprintf(shf, "%*s", nspace, null);
1154 shf_putchar('\n', shf);
1156 afree(str, ATEMP);
1159 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
1161 strip_nuls(buf, nbytes)
1162 char *buf;
1163 int nbytes;
1165 char *dst;
1167 /* nbytes check because some systems (older freebsd's) have a buggy
1168 * memchr()
1170 if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
1171 char *end = buf + nbytes;
1172 char *p, *q;
1174 for (p = dst; p < end; p = q) {
1175 /* skip a block of nulls */
1176 while (++p < end && *p == '\0')
1178 /* find end of non-null block */
1179 if (!(q = memchr(p, '\0', end - p)))
1180 q = end;
1181 memmove(dst, p, q - p);
1182 dst += q - p;
1184 *dst = '\0';
1185 return dst - buf;
1187 return nbytes;
1190 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
1191 * Returns dst.
1193 char *
1194 str_zcpy(dst, src, dsize)
1195 char *dst;
1196 const char *src;
1197 int dsize;
1199 if (dsize > 0) {
1200 int len = strlen(src);
1202 if (len >= dsize)
1203 len = dsize - 1;
1204 memcpy(dst, src, len);
1205 dst[len] = '\0';
1207 return dst;
1210 /* Like read(2), but if read fails due to non-blocking flag, resets flag
1211 * and restarts read.
1214 blocking_read(fd, buf, nbytes)
1215 int fd;
1216 char *buf;
1217 int nbytes;
1219 int ret;
1220 int tried_reset = 0;
1222 while ((ret = read(fd, buf, nbytes)) < 0) {
1223 if (!tried_reset && (errno == EAGAIN
1224 #ifdef EWOULDBLOCK
1225 || errno == EWOULDBLOCK
1226 #endif /* EWOULDBLOCK */
1229 int oerrno = errno;
1230 if (reset_nonblock(fd) > 0) {
1231 tried_reset = 1;
1232 continue;
1234 errno = oerrno;
1236 break;
1238 return ret;
1241 /* Reset the non-blocking flag on the specified file descriptor.
1242 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1243 * 1 if it was.
1246 reset_nonblock(fd)
1247 int fd;
1249 int flags;
1250 int blocking_flags;
1252 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1253 return -1;
1254 /* With luck, the C compiler will reduce this to a constant */
1255 blocking_flags = 0;
1256 #ifdef O_NONBLOCK
1257 blocking_flags |= O_NONBLOCK;
1258 #endif /* O_NONBLOCK */
1259 #ifdef O_NDELAY
1260 blocking_flags |= O_NDELAY;
1261 #else /* O_NDELAY */
1262 # ifndef O_NONBLOCK
1263 blocking_flags |= FNDELAY; /* hope this exists... */
1264 # endif /* O_NONBLOCK */
1265 #endif /* O_NDELAY */
1266 if (!(flags & blocking_flags))
1267 return 0;
1268 flags &= ~blocking_flags;
1269 if (fcntl(fd, F_SETFL, flags) < 0)
1270 return -1;
1271 return 1;
1275 #ifdef HAVE_SYS_PARAM_H
1276 # include <sys/param.h>
1277 #endif /* HAVE_SYS_PARAM_H */
1278 #ifndef MAXPATHLEN
1279 # define MAXPATHLEN PATH
1280 #endif /* MAXPATHLEN */
1282 #ifdef HPUX_GETWD_BUG
1283 # include "ksh_dir.h"
1286 * Work around bug in hpux 10.x C library - getwd/getcwd dump core
1287 * if current directory is not readable. Done in macro 'cause code
1288 * is needed in GETWD and GETCWD cases.
1290 # define HPUX_GETWD_BUG_CODE \
1292 DIR *d = ksh_opendir("."); \
1293 if (!d) \
1294 return (char *) 0; \
1295 closedir(d); \
1297 #else /* HPUX_GETWD_BUG */
1298 # define HPUX_GETWD_BUG_CODE
1299 #endif /* HPUX_GETWD_BUG */
1301 /* Like getcwd(), except bsize is ignored if buf is 0 (MAXPATHLEN is used) */
1302 char *
1303 ksh_get_wd(buf, bsize)
1304 char *buf;
1305 int bsize;
1307 #ifdef HAVE_GETCWD
1308 char *b;
1309 char *ret;
1311 /* Before memory allocated */
1312 HPUX_GETWD_BUG_CODE
1314 /* Assume getcwd() available */
1315 if (!buf) {
1316 bsize = MAXPATHLEN;
1317 b = alloc(MAXPATHLEN + 1, ATEMP);
1318 } else
1319 b = buf;
1321 ret = getcwd(b, bsize);
1323 if (!buf) {
1324 if (ret)
1325 ret = aresize(b, strlen(b) + 1, ATEMP);
1326 else
1327 afree(b, ATEMP);
1330 return ret;
1331 #else /* HAVE_GETCWD */
1332 extern char *getwd ARGS((char *));
1333 char *b;
1334 int len;
1336 /* Before memory allocated */
1337 HPUX_GETWD_BUG_CODE
1339 if (buf && bsize > MAXPATHLEN)
1340 b = buf;
1341 else
1342 b = alloc(MAXPATHLEN + 1, ATEMP);
1343 if (!getcwd(b, MAXPATHLEN)) {
1344 errno = EACCES;
1345 if (b != buf)
1346 afree(b, ATEMP);
1347 return (char *) 0;
1349 len = strlen(b) + 1;
1350 if (!buf)
1351 b = aresize(b, len, ATEMP);
1352 else if (buf != b) {
1353 if (len > bsize) {
1354 errno = ERANGE;
1355 return (char *) 0;
1357 memcpy(buf, b, len);
1358 afree(b, ATEMP);
1359 b = buf;
1362 return b;
1363 #endif /* HAVE_GETCWD */