Switch to 3.0 (native) source format.
[posh.git] / misc.c
blobb0ea5e8ef8889e4f7cfd43d2be6e8603bdde7c3c
1 /*
2 * Miscellaneous functions
3 */
5 #include "sh.h"
6 #include <ctype.h> /* for FILECHCONV */
7 #ifdef HAVE_LIMITS_H
8 # include <limits.h>
9 #endif
11 #ifndef UCHAR_MAX
12 # define UCHAR_MAX 0xFF
13 #endif
15 short ctypes [UCHAR_MAX+1]; /* type bits for unsigned char */
16 static int do_gmatch(const unsigned char *, const unsigned char *,
17 const unsigned char *, const unsigned char *);
18 static const unsigned char *cclass(const unsigned char *, int);
21 * Fast character classes
23 void
24 setctypes(const char *s, int t)
26 unsigned i;
28 if (t & C_IFS) {
29 for (i = 0; i < UCHAR_MAX+1; i++)
30 ctypes[i] &= ~C_IFS;
31 ctypes[0] |= C_IFS; /* include \0 in C_IFS */
33 while (*s != 0)
34 ctypes[(unsigned char) *s++] |= t;
37 void
38 initctypes()
40 setctypes(" \t\n|&;<>()", C_LEX1); /* \0 added automatically */
41 setctypes("*@#!$-?", C_VAR1);
42 setctypes(" \t\n", C_IFSWS);
43 setctypes("=-+?", C_SUBOP1);
44 setctypes("#%", C_SUBOP2);
45 setctypes(" \n\t\"#$&'()*;<>?[\\`|", C_QUOTE);
48 char *
49 str_save(const char *s, Area *ap)
51 return s ? strcpy((char*) alloc((size_t)strlen(s)+1, ap), s) : NULL;
54 /* Allocate a string of size n+1 and copy upto n characters from the possibly
55 * NUL terminated string s into it. Always returns a NUL terminated string
56 * (unless n < 0).
58 char *
59 str_nsave(const char *s, int n, Area *ap)
61 char *ns;
63 if (n < 0)
64 return 0;
65 ns = alloc(n + 1, ap);
66 ns[0] = '\0';
67 return strncat(ns, s, n);
70 /* called from expand.h:XcheckN() to grow buffer */
71 char *
72 Xcheck_grow_(XString *xsp, const char *xp, unsigned more)
74 const char *old_beg = xsp->beg;
76 xsp->len += more > xsp->len ? more : xsp->len;
77 xsp->beg = aresize(xsp->beg, xsp->len + 8, xsp->areap);
78 xsp->end = xsp->beg + xsp->len;
79 return xsp->beg + (xp - old_beg);
82 const struct posh_option options[] = {
83 /* Special cases (see parse_args()): -o.
84 * Options are sorted by their longnames - the order of these
85 * entries MUST match the order of sh_flag F* enumerations in sh.h.
87 { "allexport", 'a', OF_ANY },
88 #ifdef BRACE_EXPAND
89 { "braceexpand", 0, OF_ANY }, /* non-standard */
90 #endif
91 { (char *) 0, 'c', OF_CMDLINE },
92 #ifdef EMACS
93 { "emacs", 0, OF_ANY },
94 #endif
95 { "errexit", 'e', OF_ANY },
96 #ifdef EMACS
97 { "gmacs", 0, OF_ANY },
98 #endif
99 { "ignoreeof", 0, OF_ANY },
100 { "interactive",'i', OF_CMDLINE },
101 { "login", 'l', OF_CMDLINE },
102 #ifdef JOBS
103 { "monitor", 'm', OF_ANY },
104 #else /* JOBS */
105 { (char *) 0, 'm', 0 }, /* so FMONITOR not ifdef'd */
106 #endif /* JOBS */
107 { "noclobber", 'C', OF_ANY },
108 { "noexec", 'n', OF_ANY },
109 { "noglob", 'f', OF_ANY },
110 { "nohup", 0, OF_ANY },
111 { "nolog", 0, OF_ANY }, /* no effect */
112 #ifdef JOBS
113 { "notify", 'b', OF_ANY },
114 #endif /* JOBS */
115 { "nounset", 'u', OF_ANY },
116 #ifdef SILLY_FEATURES
117 { "posix", 0, OF_ANY }, /* non-standard */
118 #endif /* SILLY_FEATURES */
119 { "privileged", 'p', OF_ANY },
120 { "stdin", 's', OF_CMDLINE }, /* pseudo non-standard */
121 #ifdef SILLY_FEATURES
122 { "trackall", 'h', OF_ANY },
123 #endif /* SILLY_FEATURES */
124 { "verbose", 'v', OF_ANY },
125 #ifdef VI
126 { "vi", 0, OF_ANY },
127 { "viraw", 0, OF_ANY }, /* no effect */
128 { "vi-show8", 0, OF_ANY }, /* non-standard */
129 { "vi-tabcomplete", 0, OF_ANY }, /* non-standard */
130 { "vi-esccomplete", 0, OF_ANY }, /* non-standard */
131 #endif
132 { "xtrace", 'x', OF_ANY },
133 /* Anonymous flags: used internally by shell only
134 * (not visible to user)
136 { NULL, 0, OF_INTERNAL }, /* FTALKING_I */
140 * translate -o option into F* constant (also used for test -o option)
143 option(const char *n)
145 unsigned int i;
147 for (i = 0; i < NELEM(options); i++)
148 if (options[i].name && strcmp(options[i].name, n) == 0)
149 return i;
151 return -1;
154 struct options_info {
155 unsigned int opt_width;
156 struct {
157 const char *name;
158 int flag;
159 } opts[NELEM(options)];
162 static char *options_fmt_entry ARGS((void *arg, int i, char *buf, int buflen));
163 static void printoptions ARGS((int verbose));
165 /* format a single select menu item */
166 static char *
167 options_fmt_entry(arg, i, buf, buflen)
168 void *arg;
169 int i;
170 char *buf;
171 int buflen;
173 struct options_info *oi = (struct options_info *) arg;
175 snprintf(buf, buflen, "%-*s %s",
176 oi->opt_width, oi->opts[i].name,
177 Flag(oi->opts[i].flag) ? "on" : "off");
178 return buf;
181 static void
182 printoptions(verbose)
183 int verbose;
185 unsigned int i;
187 if (verbose) {
188 struct options_info oi;
189 unsigned int n, len;
191 /* verbose version */
192 shprintf("Current option settings\n");
194 for (i = n = oi.opt_width = 0; i < NELEM(options); i++)
195 if (options[i].name) {
196 len = strlen(options[i].name);
197 oi.opts[n].name = options[i].name;
198 oi.opts[n++].flag = i;
199 if (len > oi.opt_width)
200 oi.opt_width = len;
202 print_columns(shl_stdout, n, options_fmt_entry, &oi,
203 oi.opt_width + 5);
204 } else {
205 /* short version ala ksh93 */
206 shprintf("set");
207 for (i = 0; i < NELEM(options); i++)
208 if (Flag(i) && options[i].name)
209 shprintf(" -o %s", options[i].name);
210 shprintf("\n");
214 char *
215 getoptions()
217 unsigned int i;
218 char m[(int) FNFLAGS + 1];
219 char *cp = m;
221 for (i = 0; i < NELEM(options); i++)
222 if (options[i].c && Flag(i))
223 *cp++ = options[i].c;
224 *cp = 0;
225 return str_save(m, ATEMP);
228 /* change a Flag(*) value; takes care of special actions */
229 void
230 change_flag(f, what, newval)
231 enum sh_flag f; /* flag to change */
232 int what; /* what is changing the flag (command line vs set) */
233 int newval;
235 int oldval;
237 oldval = Flag(f);
238 Flag(f) = newval;
239 #ifdef JOBS
240 if (f == FMONITOR) {
241 if (what != OF_CMDLINE && newval != oldval)
242 j_change();
243 } else
244 #endif /* JOBS */
245 #ifdef EDIT
246 if (0
247 # ifdef VI
248 || f == FVI
249 # endif /* VI */
250 # ifdef EMACS
251 || f == FEMACS || f == FGMACS
252 # endif /* EMACS */
255 if (newval) {
256 # ifdef VI
257 Flag(FVI) = 0;
258 # endif /* VI */
259 # ifdef EMACS
260 Flag(FEMACS) = Flag(FGMACS) = 0;
261 # endif /* EMACS */
262 Flag(f) = newval;
264 } else
265 #endif /* EDIT */
266 /* Turning off -p? */
267 if (f == FPRIVILEGED && oldval && !newval) {
268 #ifdef OS2
270 #else /* OS2 */
271 setuid(ksheuid = getuid());
272 setgid(getgid());
273 #endif /* OS2 */
275 /* Changing interactive flag? */
276 if (f == FTALKING) {
277 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
278 Flag(FTALKING_I) = newval;
282 /* parse command line & set command arguments. returns the index of
283 * non-option arguments, -1 if there is an error.
286 parse_args(argv, what, setargsp)
287 char **argv;
288 int what; /* OF_CMDLINE or OF_SET */
289 int *setargsp;
291 static char cmd_opts[NELEM(options) + 3]; /* o:\0 */
292 static char set_opts[NELEM(options) + 3]; /* o;\0 */
293 char *opts;
294 char *array = (char *) 0;
295 LameGetopt go;
296 int j, optc, set;
297 unsigned int k;
299 /* First call? Build option strings... */
300 if (cmd_opts[0] == '\0') {
301 char *p, *q;
303 strcpy(cmd_opts, "o:"); /* see cmd_opts[] declaration */
304 p = cmd_opts + strlen(cmd_opts);
305 strcpy(set_opts, "o;"); /* see set_opts[] declaration */
306 q = set_opts + strlen(set_opts);
307 for (k = 0; k < NELEM(options); k++) {
308 if (options[k].c) {
309 if (options[k].flags & OF_CMDLINE)
310 *p++ = options[k].c;
311 if (options[k].flags & OF_SET)
312 *q++ = options[k].c;
315 *p = '\0';
316 *q = '\0';
319 if (what == OF_CMDLINE) {
320 char *p;
321 /* Set FLOGIN before parsing options so user can clear
322 * flag using +l.
324 Flag(FLOGIN) = (argv[0][0] == '-'
325 || ((p = ksh_strrchr_dirsep(argv[0]))
326 && *++p == '-'));
327 opts = cmd_opts;
328 } else
329 opts = set_opts;
330 ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
331 while ((optc = ksh_getopt(argv, &go, opts)) != EOF) {
332 set = (go.info & GI_PLUS) ? 0 : 1;
333 switch (optc) {
334 case 'o':
335 if (go.optarg == (char *) 0) {
336 /* lone -o: print options
338 * Note that on the command line, -o requires
339 * an option (ie, can't get here if what is
340 * OF_CMDLINE).
342 printoptions(set);
343 break;
345 j = option(go.optarg);
346 if (j >= 0 && set == Flag(j))
347 /* Don't check the context if the flag
348 * isn't changing - makes "set -o interactive"
349 * work if you're already interactive. Needed
350 * if the output of "set +o" is to be used.
353 else if (j >= 0 && (options[j].flags & what))
354 change_flag((enum sh_flag) j, what, set);
355 else {
356 bi_errorf("%s: bad option", go.optarg);
357 return -1;
359 break;
361 case '?':
362 return -1;
364 default:
365 for (k = 0; k < NELEM(options); k++)
366 if (optc == options[k].c
367 && (what & options[k].flags))
369 change_flag((enum sh_flag) k, what,
370 set);
371 break;
373 if (k == NELEM(options)) {
374 internal_errorf(1, "parse_args: `%c'", optc);
375 return -1; /* not reached */
379 if (!(go.info & GI_MINUSMINUS) && argv[go.optind]
380 && (argv[go.optind][0] == '-' || argv[go.optind][0] == '+')
381 && argv[go.optind][1] == '\0')
383 /* set skips lone - or + option */
384 go.optind++;
386 if (setargsp)
387 /* -- means set $#/$* even if there are no arguments */
388 *setargsp = ((go.info & GI_MINUSMINUS)
389 || argv[go.optind]);
391 return go.optind;
394 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
396 getn(const char *as, int *ai)
398 char *ep = NULL;
400 *ai = strtol(as, &ep, 10);
402 if (!(*ep == '\0' && *as != '\0'))
403 return 0;
404 return 1;
407 /* getn() that prints error */
409 bi_getn(as, ai)
410 const char *as;
411 int *ai;
413 int rv = getn(as, ai);
415 if (!rv)
416 bi_errorf("%s: bad number", as);
417 return rv;
420 /* -------- gmatch.c -------- */
423 * int gmatch(string, pattern)
424 * char *string, *pattern;
426 * Match a pattern as in sh(1).
427 * pattern character are prefixed with MAGIC by expand.
431 gmatchx(const char *s, const char *p, int isfile)
433 const char *se, *pe;
435 if (s == NULL || p == NULL)
436 return 0;
437 se = s + strlen(s);
438 pe = p + strlen(p);
439 /* isfile is false iff no syntax check has been done on
440 * the pattern. If check fails, just to a strcmp().
442 if (!isfile && !has_globbing(p, pe)) {
443 size_t len = pe - p + 1;
444 char tbuf[64];
445 char *t = len <= sizeof(tbuf) ? tbuf :
446 (char *) alloc(len, ATEMP);
447 debunk(t, p, len);
448 return (!strcmp(t, s));
450 return (do_gmatch((const unsigned char *) s, (const unsigned char *) se,
451 (const unsigned char *) p, (const unsigned char *) pe));
454 /* Returns if p is a syntacticly correct globbing pattern, false
455 * if it contains no pattern characters or if there is a syntax error.
456 * Syntax errors are:
457 * - [ with no closing ]
458 * - imbalanced $(...) expression
459 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
461 /*XXX
462 - if no magic,
463 if dest given, copy to dst
464 return ?
465 - if magic && (no globbing || syntax error)
466 debunk to dst
467 return ?
468 - return ?
471 has_globbing(const char *xp, const char *xpe)
473 const unsigned char *p = (const unsigned char *) xp;
474 const unsigned char *pe = (const unsigned char *) xpe;
475 int c;
476 int nest = 0, bnest = 0;
477 int saw_glob = 0;
478 int in_bracket = 0; /* inside [...] */
480 for (; p < pe; p++) {
481 if (!ISMAGIC(*p))
482 continue;
483 if ((c = *++p) == '*' || c == '?')
484 saw_glob = 1;
485 else if (c == '[') {
486 if (!in_bracket) {
487 saw_glob = 1;
488 in_bracket = 1;
489 if (ISMAGIC(p[1]) && p[2] == NOT)
490 p += 2;
491 if (ISMAGIC(p[1]) && p[2] == ']')
492 p += 2;
494 /* XXX Do we need to check ranges here? POSIX Q */
495 } else if (c == ']') {
496 if (in_bracket) {
497 if (bnest) /* [a*(b]) */
498 return (0);
499 in_bracket = 0;
501 } else if ((c & 0x80) && strchr("*? ", c & 0x7f)) {
502 saw_glob = 1;
503 if (in_bracket)
504 bnest++;
505 else
506 nest++;
507 } else if (c == '|') {
508 if (in_bracket && !bnest) /* *(a[foo|bar]) */
509 return (0);
510 } else if (c == /*(*/ ')') {
511 if (in_bracket) {
512 if (!bnest--) /* *(a[b)c] */
513 return (0);
514 } else if (nest)
515 nest--;
517 /* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
518 MAGIC-{, MAGIC-,, MAGIC-} */
520 return (saw_glob && !in_bracket && !nest);
523 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
524 static int
525 do_gmatch(const unsigned char *s, const unsigned char *se,
526 const unsigned char *p, const unsigned char *pe)
528 int sc, pc;
529 const unsigned char *prest, *psub, *pnext;
530 const unsigned char *srest;
532 if (s == NULL || p == NULL)
533 return 0;
534 while (p < pe) {
535 pc = *p++;
536 sc = s < se ? *s : '\0';
537 s++;
538 if (!ISMAGIC(pc)) {
539 if (sc != pc)
540 return 0;
541 continue;
543 switch (*p++) {
544 case '[':
545 if (sc == 0 || (p = cclass(p, sc)) == NULL)
546 return 0;
547 break;
549 case '?':
550 if (sc == 0)
551 return 0;
552 break;
554 case '*':
555 if (p == pe)
556 return 1;
557 s--;
558 do {
559 if (do_gmatch(s, se, p, pe))
560 return 1;
561 } while (s++ < se);
562 return 0;
565 * [*+?@!](pattern|pattern|..)
566 * This is also needed for ${..%..}, etc.
568 case 0x80|'+': /* matches one or more times */
569 case 0x80|'*': /* matches zero or more times */
570 if (!(prest = pat_scan(p, pe, 0)))
571 return 0;
572 s--;
573 /* take care of zero matches */
574 if (p[-1] == (0x80 | '*') &&
575 do_gmatch(s, se, prest, pe))
576 return 1;
577 for (psub = p; ; psub = pnext) {
578 pnext = pat_scan(psub, pe, 1);
579 for (srest = s; srest <= se; srest++) {
580 if (do_gmatch(s, srest, psub, pnext - 2) &&
581 (do_gmatch(srest, se, prest, pe) ||
582 (s != srest && do_gmatch(srest,
583 se, p - 2, pe))))
584 return 1;
586 if (pnext == prest)
587 break;
589 return 0;
591 case 0x80|'?': /* matches zero or once */
592 case 0x80|'@': /* matches one of the patterns */
593 case 0x80|' ': /* simile for @ */
594 if (!(prest = pat_scan(p, pe, 0)))
595 return 0;
596 s--;
597 /* Take care of zero matches */
598 if (p[-1] == (0x80 | '?') &&
599 do_gmatch(s, se, prest, pe))
600 return 1;
601 for (psub = p; ; psub = pnext) {
602 pnext = pat_scan(psub, pe, 1);
603 srest = prest == pe ? se : s;
604 for (; srest <= se; srest++) {
605 if (do_gmatch(s, srest, psub, pnext - 2) &&
606 do_gmatch(srest, se, prest, pe))
607 return 1;
609 if (pnext == prest)
610 break;
612 return 0;
614 case 0x80|'!': /* matches none of the patterns */
615 if (!(prest = pat_scan(p, pe, 0)))
616 return 0;
617 s--;
618 for (srest = s; srest <= se; srest++) {
619 int matched = 0;
621 for (psub = p; ; psub = pnext) {
622 pnext = pat_scan(psub, pe, 1);
623 if (do_gmatch(s, srest, psub,
624 pnext - 2)) {
625 matched = 1;
626 break;
628 if (pnext == prest)
629 break;
631 if (!matched &&
632 do_gmatch(srest, se, prest, pe))
633 return 1;
635 return 0;
637 default:
638 if (sc != p[-1])
639 return 0;
640 break;
643 return s == se;
646 static const unsigned char *
647 cclass(const unsigned char *p, int sub)
649 int c, d, not, found = 0;
650 const unsigned char *orig_p = p;
652 if ((not = (ISMAGIC(*p) && *++p == NOT)))
653 p++;
654 do {
655 c = *p++;
656 if (ISMAGIC(c)) {
657 c = *p++;
658 if ((c & 0x80) && !ISMAGIC(c)) {
659 c &= 0x7f;/* extended pattern matching: *+?@! */
660 /* XXX the ( char isn't handled as part of [] */
661 if (c == ' ') /* simile for @: plain (..) */
662 c = '(' /*)*/;
665 if (c == '\0')
666 /* No closing ] - act as if the opening [ was quoted */
667 return sub == '[' ? orig_p : NULL;
668 if (ISMAGIC(p[0]) && p[1] == '-' &&
669 (!ISMAGIC(p[2]) || p[3] != ']')) {
670 p += 2; /* MAGIC- */
671 d = *p++;
672 if (ISMAGIC(d)) {
673 d = *p++;
674 if ((d & 0x80) && !ISMAGIC(d))
675 d &= 0x7f;
677 /* POSIX says this is an invalid expression */
678 if (c > d)
679 return NULL;
680 } else
681 d = c;
682 if (c == sub || (c <= sub && sub <= d))
683 found = 1;
684 } while (!(ISMAGIC(p[0]) && p[1] == ']'));
686 return (found != not) ? p+2 : NULL;
689 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
690 const unsigned char *
691 pat_scan(const unsigned char *p, const unsigned char *pe, int match_sep)
693 int nest = 0;
695 for (; p < pe; p++) {
696 if (!ISMAGIC(*p))
697 continue;
698 if ((*++p == /*(*/ ')' && nest-- == 0) ||
699 (*p == '|' && match_sep && nest == 0))
700 return ++p;
701 if ((*p & 0x80) && strchr("*+?@! ", *p & 0x7f))
702 nest++;
704 return NULL;
708 xstrcmp(const void *p1, const void *p2)
710 return (strcmp(*(char * const *)p1, *(char * const *)p2));
713 /* Initialise a Getopt structure */
714 void
715 ksh_getopt_reset(LameGetopt *go, int flags)
717 go->optind = 1;
718 go->optarg = NULL;
719 go->p = 0;
720 go->flags = flags;
721 go->info = 0;
722 go->buf[1] = '\0';
726 /* getopt() used for shell built-in commands, the getopts command, and
727 * command line options.
728 * A leading ':' in options means don't print errors, instead return '?'
729 * or ':' and set go->optarg to the offending option character.
730 * If GF_ERROR is set (and option doesn't start with :), errors result in
731 * a call to bi_errorf().
733 * Non-standard features:
734 * - ';' is like ':' in options, except the argument is optional
735 * (if it isn't present, optarg is set to 0).
736 * Used for 'set -o'.
737 * - ',' is like ':' in options, except the argument always immediately
738 * follows the option character (optarg is set to the null string if
739 * the option is missing).
740 * Used for 'read -u2', 'print -u2' and fc -40.
741 * - '#' is like ':' in options, expect that the argument is optional
742 * and must start with a digit. If the argument doesn't start with a
743 * digit, it is assumed to be missing and normal option processing
744 * continues (optarg is set to 0 if the option is missing).
745 * Used for 'typeset -LZ4'.
746 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
747 * option starting with + is accepted, the GI_PLUS flag will be set
748 * in go->info.
751 ksh_getopt(argv, go, options)
752 char **argv;
753 LameGetopt *go;
754 const char *options;
756 char c;
757 char *o;
759 if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
760 char *arg = argv[go->optind], flag = arg ? *arg : '\0';
762 go->p = 1;
763 if (flag == '-' && arg[1] == '-' && arg[2] == '\0') {
764 go->optind++;
765 go->p = 0;
766 go->info |= GI_MINUSMINUS;
767 return EOF;
769 if (arg == (char *) 0
770 || ((flag != '-' ) /* neither a - nor a + (if + allowed) */
771 && (!(go->flags & GF_PLUSOPT) || flag != '+'))
772 || (c = arg[1]) == '\0')
774 go->p = 0;
775 return EOF;
777 go->optind++;
778 go->info &= ~(GI_MINUS|GI_PLUS);
779 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
781 go->p++;
782 if (c == '?' || c == ':' || c == ';'
783 || !(o = strchr(options, c)))
785 if (options[0] == ':') {
786 go->buf[0] = c;
787 go->optarg = go->buf;
788 } else {
789 warningf(TRUE, "%s%s-%c: unknown option",
790 (go->flags & GF_NONAME) ? "" : argv[0],
791 (go->flags & GF_NONAME) ? "" : ": ", c);
792 if (go->flags & GF_ERROR)
793 bi_errorf(null);
795 return '?';
797 /* : means argument must be present, may be part of option argument
798 * or the next argument
799 * ; same as : but argument may be missing
800 * , means argument is part of option argument, and may be null.
802 if (*++o == ':' || *o == ';') {
803 if (argv[go->optind - 1][go->p])
804 go->optarg = argv[go->optind - 1] + go->p;
805 else if (argv[go->optind])
806 go->optarg = argv[go->optind++];
807 else if (*o == ';')
808 go->optarg = (char *) 0;
809 else {
810 if (options[0] == ':') {
811 go->buf[0] = c;
812 go->optarg = go->buf;
813 return ':';
815 warningf(TRUE, "%s%s-`%c' requires argument",
816 (go->flags & GF_NONAME) ? "" : argv[0],
817 (go->flags & GF_NONAME) ? "" : ": ", c);
818 if (go->flags & GF_ERROR)
819 bi_errorf(null);
820 return '?';
822 go->p = 0;
824 return c;
827 /* print variable/alias value using necessary quotes
828 * (POSIX says they should be suitable for re-entry...)
829 * No trailing newline is printed.
831 void
832 print_value_quoted(s)
833 const char *s;
835 const char *p;
836 int inquote = 0;
838 /* Test if any quotes are needed */
839 for (p = s; *p; p++)
840 if (ctype(*p, C_QUOTE))
841 break;
842 if (!*p) {
843 shprintf("%s", s);
844 return;
846 for (p = s; *p; p++) {
847 if (*p == '\'') {
848 shprintf("'\\'" + 1 - inquote);
849 inquote = 0;
850 } else {
851 if (!inquote) {
852 shprintf("'");
853 inquote = 1;
855 shf_putc(*p, shl_stdout);
858 if (inquote)
859 shprintf("'");
862 /* Print things in columns and rows - func() is called to format the ith
863 * element
865 void
866 print_columns(shf, n, func, arg, max_width)
867 struct shf *shf;
868 int n;
869 char *(*func) ARGS((void *, int, char *, int));
870 void *arg;
871 int max_width;
873 char *str = (char *) alloc(max_width + 1, ATEMP);
874 int i;
875 int r, c;
876 int rows, cols;
877 int nspace;
879 /* max_width + 1 for the space. Note that no space
880 * is printed after the last column to avoid problems
881 * with terminals that have auto-wrap.
883 cols = x_cols / (max_width + 1);
884 if (!cols)
885 cols = 1;
886 rows = (n + cols - 1) / cols;
887 if (n && cols > rows) {
888 int tmp = rows;
890 rows = cols;
891 cols = tmp;
892 if (rows > n)
893 rows = n;
896 nspace = (x_cols - max_width * cols) / cols;
897 if (nspace <= 0)
898 nspace = 1;
899 for (r = 0; r < rows; r++) {
900 for (c = 0; c < cols; c++) {
901 i = c * rows + r;
902 if (i < n) {
903 shf_fprintf(shf, "%-*s",
904 max_width,
905 (*func)(arg, i, str, max_width + 1));
906 if (c + 1 < cols)
907 shf_fprintf(shf, "%*s", nspace, null);
910 shf_putchar('\n', shf);
912 afree(str, ATEMP);
915 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
917 strip_nuls(buf, nbytes)
918 char *buf;
919 int nbytes;
921 char *dst;
923 /* nbytes check because some systems (older freebsd's) have a buggy
924 * memchr()
926 if (nbytes && (dst = memchr(buf, '\0', nbytes))) {
927 char *end = buf + nbytes;
928 char *p, *q;
930 for (p = dst; p < end; p = q) {
931 /* skip a block of nulls */
932 while (++p < end && *p == '\0')
934 /* find end of non-null block */
935 if (!(q = memchr(p, '\0', end - p)))
936 q = end;
937 memmove(dst, p, q - p);
938 dst += q - p;
940 *dst = '\0';
941 return dst - buf;
943 return nbytes;
946 /* Copy at most dsize-1 bytes from src to dst, ensuring dst is null terminated.
947 * Returns dst.
949 char *
950 str_zcpy(dst, src, dsize)
951 char *dst;
952 const char *src;
953 int dsize;
955 if (dsize > 0) {
956 int len = strlen(src);
958 if (len >= dsize)
959 len = dsize - 1;
960 memcpy(dst, src, len);
961 dst[len] = '\0';
963 return dst;
966 /* Like read(2), but if read fails due to non-blocking flag, resets flag
967 * and restarts read.
970 blocking_read(fd, buf, nbytes)
971 int fd;
972 char *buf;
973 int nbytes;
975 int ret;
976 int tried_reset = 0;
978 while ((ret = read(fd, buf, nbytes)) < 0) {
979 if (!tried_reset && (errno == EAGAIN
980 #ifdef EWOULDBLOCK
981 || errno == EWOULDBLOCK
982 #endif /* EWOULDBLOCK */
985 int oerrno = errno;
986 if (reset_nonblock(fd) > 0) {
987 tried_reset = 1;
988 continue;
990 errno = oerrno;
992 break;
994 return ret;
997 /* Reset the non-blocking flag on the specified file descriptor.
998 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
999 * 1 if it was.
1002 reset_nonblock(fd)
1003 int fd;
1005 int flags;
1006 int blocking_flags;
1008 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1009 return -1;
1010 /* With luck, the C compiler will reduce this to a constant */
1011 blocking_flags = 0;
1012 #ifdef O_NONBLOCK
1013 blocking_flags |= O_NONBLOCK;
1014 #endif /* O_NONBLOCK */
1015 #ifdef O_NDELAY
1016 blocking_flags |= O_NDELAY;
1017 #else /* O_NDELAY */
1018 # ifndef O_NONBLOCK
1019 blocking_flags |= FNDELAY; /* hope this exists... */
1020 # endif /* O_NONBLOCK */
1021 #endif /* O_NDELAY */
1022 if (!(flags & blocking_flags))
1023 return 0;
1024 flags &= ~blocking_flags;
1025 if (fcntl(fd, F_SETFL, flags) < 0)
1026 return -1;
1027 return 1;
1031 #ifdef HAVE_SYS_PARAM_H
1032 # include <sys/param.h>
1033 #endif /* HAVE_SYS_PARAM_H */
1034 #ifndef MAXPATHLEN
1035 # define MAXPATHLEN PATH
1036 #endif /* MAXPATHLEN */