1 /* $OpenBSD: misc.c,v 1.70 2018/04/09 17:53:36 tobias Exp $ */
4 * Miscellaneous functions
16 #include "charclass.h"
18 short ctypes
[UCHAR_MAX
+1]; /* type bits for unsigned char */
20 static int do_gmatch(const unsigned char *, const unsigned char *,
21 const unsigned char *, const unsigned char *);
22 static const unsigned char *cclass(const unsigned char *, int);
25 * Fast character classes
28 setctypes(const char *s
, int t
)
33 for (i
= 0; i
< UCHAR_MAX
+1; i
++)
35 ctypes
[0] |= C_IFS
; /* include \0 in C_IFS */
38 ctypes
[(unsigned char) *s
++] |= t
;
46 for (c
= 'a'; c
<= 'z'; c
++)
48 for (c
= 'A'; c
<= 'Z'; c
++)
50 ctypes
['_'] |= C_ALPHA
;
51 setctypes(" \t\n|&;<>()", C_LEX1
); /* \0 added automatically */
52 setctypes("*@#!$-?", C_VAR1
);
53 setctypes(" \t\n", C_IFSWS
);
54 setctypes("=-+?", C_SUBOP1
);
55 setctypes("#%", C_SUBOP2
);
56 setctypes(" \n\t\"#$&'()*;<>?[\\`|", C_QUOTE
);
59 /* convert uint64_t to base N string */
62 u64ton(uint64_t n
, int base
)
67 p
= &buf
[sizeof(buf
)];
70 *--p
= "0123456789ABCDEF"[n
%base
];
77 str_save(const char *s
, Area
*ap
)
90 /* Allocate a string of size n+1 and copy upto n characters from the possibly
91 * null terminated string s into it. Always returns a null terminated string
95 str_nsave(const char *s
, int n
, Area
*ap
)
101 ns
= alloc(n
+ 1, ap
);
103 return strncat(ns
, s
, n
);
106 /* called from expand.h:XcheckN() to grow buffer */
108 Xcheck_grow_(XString
*xsp
, char *xp
, size_t more
)
110 char *old_beg
= xsp
->beg
;
112 xsp
->len
+= more
> xsp
->len
? more
: xsp
->len
;
113 xsp
->beg
= aresize(xsp
->beg
, xsp
->len
+ 8, xsp
->areap
);
114 xsp
->end
= xsp
->beg
+ xsp
->len
;
115 return xsp
->beg
+ (xp
- old_beg
);
118 const struct option sh_options
[] = {
119 /* Special cases (see parse_args()): -A, -o, -s.
120 * Options are sorted by their longnames - the order of these
121 * entries MUST match the order of sh_flag F* enumerations in sh.h.
123 { "allexport", 'a', OF_ANY
},
124 { "braceexpand", 0, OF_ANY
}, /* non-standard */
125 { "bgnice", 0, OF_ANY
},
126 { NULL
, 'c', OF_CMDLINE
},
127 { "csh-history", 0, OF_ANY
}, /* non-standard */
129 { "emacs", 0, OF_ANY
},
131 { "errexit", 'e', OF_ANY
},
133 { "gmacs", 0, OF_ANY
},
135 { "ignoreeof", 0, OF_ANY
},
136 { "interactive",'i', OF_CMDLINE
},
137 { "keyword", 'k', OF_ANY
},
138 { "login", 'l', OF_CMDLINE
},
139 { "markdirs", 'X', OF_ANY
},
140 { "monitor", 'm', OF_ANY
},
141 { "noclobber", 'C', OF_ANY
},
142 { "noexec", 'n', OF_ANY
},
143 { "noglob", 'f', OF_ANY
},
144 { "nohup", 0, OF_ANY
},
145 { "nolog", 0, OF_ANY
}, /* no effect */
146 { "notify", 'b', OF_ANY
},
147 { "nounset", 'u', OF_ANY
},
148 { "physical", 0, OF_ANY
}, /* non-standard */
149 { "posix", 0, OF_ANY
}, /* non-standard */
150 { "privileged", 'p', OF_ANY
},
151 { "restricted", 'r', OF_CMDLINE
},
152 { "sh", 0, OF_ANY
}, /* non-standard */
153 { "stdin", 's', OF_CMDLINE
}, /* pseudo non-standard */
154 { "trackall", 'h', OF_ANY
},
155 { "verbose", 'v', OF_ANY
},
158 { "viraw", 0, OF_ANY
}, /* no effect */
159 { "vi-show8", 0, OF_ANY
}, /* non-standard */
160 { "vi-tabcomplete", 0, OF_ANY
}, /* non-standard */
161 { "vi-esccomplete", 0, OF_ANY
}, /* non-standard */
163 { "xtrace", 'x', OF_ANY
},
164 /* Anonymous flags: used internally by shell only
165 * (not visible to user)
167 { NULL
, 0, OF_INTERNAL
}, /* FTALKING_I */
171 * translate -o option into F* constant (also used for test -o option)
174 option(const char *n
)
178 for (ele
= 0; ele
< NELEM(sh_options
); ele
++)
179 if (sh_options
[ele
].name
&& strcmp(sh_options
[ele
].name
, n
) == 0)
185 struct options_info
{
190 } opts
[NELEM(sh_options
)];
193 static char *options_fmt_entry(void *arg
, int i
, char *buf
, int buflen
);
194 static void printoptions(int verbose
);
196 /* format a single select menu item */
198 options_fmt_entry(void *arg
, int i
, char *buf
, int buflen
)
200 struct options_info
*oi
= (struct options_info
*) arg
;
202 shf_snprintf(buf
, buflen
, "%-*s %s",
203 oi
->opt_width
, oi
->opts
[i
].name
,
204 Flag(oi
->opts
[i
].flag
) ? "on" : "off");
209 printoptions(int verbose
)
214 struct options_info oi
;
218 /* verbose version */
219 shprintf("Current option settings\n");
221 for (ele
= n
= oi
.opt_width
= 0; ele
< NELEM(sh_options
); ele
++) {
222 if (sh_options
[ele
].name
) {
223 len
= strlen(sh_options
[ele
].name
);
224 oi
.opts
[n
].name
= sh_options
[ele
].name
;
225 oi
.opts
[n
++].flag
= ele
;
226 if (len
> oi
.opt_width
)
230 print_columns(shl_stdout
, n
, options_fmt_entry
, &oi
,
231 oi
.opt_width
+ 5, 1);
233 /* short version ala ksh93 */
235 for (ele
= 0; ele
< NELEM(sh_options
); ele
++) {
236 if (sh_options
[ele
].name
)
238 Flag(ele
) ? '-' : '+',
239 sh_options
[ele
].name
);
249 char m
[(int) FNFLAGS
+ 1];
252 for (ele
= 0; ele
< NELEM(sh_options
); ele
++)
253 if (sh_options
[ele
].c
&& Flag(ele
))
254 *cp
++ = sh_options
[ele
].c
;
256 return str_save(m
, ATEMP
);
259 /* change a Flag(*) value; takes care of special actions */
261 change_flag(enum sh_flag f
,
262 int what
, /* flag to change */
263 int newval
) /* what is changing the flag (command line vs set) */
270 if (what
!= OF_CMDLINE
&& newval
!= oldval
)
278 || f
== FEMACS
|| f
== FGMACS
287 Flag(FEMACS
) = Flag(FGMACS
) = 0;
292 /* Turning off -p? */
293 if (f
== FPRIVILEGED
&& oldval
&& !newval
) {
294 gid_t gid
= getgid();
296 setresgid(gid
, gid
, gid
);
298 setresuid(ksheuid
, ksheuid
, ksheuid
);
299 } else if (f
== FPOSIX
&& newval
) {
300 Flag(FBRACEEXPAND
) = 0;
302 /* Changing interactive flag? */
304 if ((what
== OF_CMDLINE
|| what
== OF_SET
) && procpid
== kshpid
)
305 Flag(FTALKING_I
) = newval
;
309 /* parse command line & set command arguments. returns the index of
310 * non-option arguments, -1 if there is an error.
313 parse_args(char **argv
,
314 int what
, /* OF_CMDLINE or OF_SET */
317 static char cmd_opts
[NELEM(sh_options
) + 3]; /* o:\0 */
318 static char set_opts
[NELEM(sh_options
) + 5]; /* Ao;s\0 */
322 int i
, optc
, sortargs
= 0, arrayset
= 0;
325 /* First call? Build option strings... */
326 if (cmd_opts
[0] == '\0') {
329 /* see cmd_opts[] declaration */
330 strlcpy(cmd_opts
, "o:", sizeof cmd_opts
);
331 p
= cmd_opts
+ strlen(cmd_opts
);
332 /* see set_opts[] declaration */
333 strlcpy(set_opts
, "A:o;s", sizeof set_opts
);
334 q
= set_opts
+ strlen(set_opts
);
335 for (ele
= 0; ele
< NELEM(sh_options
); ele
++) {
336 if (sh_options
[ele
].c
) {
337 if (sh_options
[ele
].flags
& OF_CMDLINE
)
338 *p
++ = sh_options
[ele
].c
;
339 if (sh_options
[ele
].flags
& OF_SET
)
340 *q
++ = sh_options
[ele
].c
;
347 if (what
== OF_CMDLINE
) {
349 /* Set FLOGIN before parsing options so user can clear
352 Flag(FLOGIN
) = (argv
[0][0] == '-' ||
353 ((p
= strrchr(argv
[0], '/')) && *++p
== '-'));
357 ksh_getopt_reset(&go
, GF_ERROR
|GF_PLUSOPT
);
358 while ((optc
= ksh_getopt(argv
, &go
, opts
)) != -1) {
359 int set
= (go
.info
& GI_PLUS
) ? 0 : 1;
362 arrayset
= set
? 1 : -1;
367 if (go
.optarg
== NULL
) {
368 /* lone -o: print options
370 * Note that on the command line, -o requires
371 * an option (ie, can't get here if what is
377 i
= option(go
.optarg
);
378 if (i
!= -1 && set
== Flag(i
))
379 /* Don't check the context if the flag
380 * isn't changing - makes "set -o interactive"
381 * work if you're already interactive. Needed
382 * if the output of "set +o" is to be used.
385 else if (i
!= -1 && (sh_options
[i
].flags
& what
))
386 change_flag((enum sh_flag
) i
, what
, set
);
388 bi_errorf("%s: bad option", go
.optarg
);
397 /* -s: sort positional params (at&t ksh stupidity) */
398 if (what
== OF_SET
&& optc
== 's') {
402 for (ele
= 0; ele
< NELEM(sh_options
); ele
++)
403 if (optc
== sh_options
[ele
].c
&&
404 (what
& sh_options
[ele
].flags
)) {
405 change_flag((enum sh_flag
) ele
, what
,
409 if (ele
== NELEM(sh_options
)) {
410 internal_errorf("%s: `%c'", __func__
, optc
);
411 return -1; /* not reached */
415 if (!(go
.info
& GI_MINUSMINUS
) && argv
[go
.optind
] &&
416 (argv
[go
.optind
][0] == '-' || argv
[go
.optind
][0] == '+') &&
417 argv
[go
.optind
][1] == '\0') {
418 /* lone - clears -v and -x flags */
419 if (argv
[go
.optind
][0] == '-' && !Flag(FPOSIX
))
420 Flag(FVERBOSE
) = Flag(FXTRACE
) = 0;
421 /* set skips lone - or + option */
425 /* -- means set $#/$* even if there are no arguments */
426 *setargsp
= !arrayset
&& ((go
.info
& GI_MINUSMINUS
) ||
429 if (arrayset
&& (!*array
|| *skip_varname(array
, false))) {
430 bi_errorf("%s: is not an identifier", array
);
434 for (i
= go
.optind
; argv
[i
]; i
++)
436 qsortp((void **) &argv
[go
.optind
], (size_t) (i
- go
.optind
),
440 set_array(array
, arrayset
, argv
+ go
.optind
);
441 for (; argv
[go
.optind
]; go
.optind
++)
448 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
450 getn(const char *as
, int *ai
)
455 n
= strtol(as
, &p
, 10);
457 if (!*as
|| *p
|| INT_MIN
>= n
|| n
>= INT_MAX
)
464 /* getn() that prints error */
466 bi_getn(const char *as
, int *ai
)
468 int rv
= getn(as
, ai
);
471 bi_errorf("%s: bad number", as
);
475 /* -------- gmatch.c -------- */
478 * int gmatch(string, pattern)
479 * char *string, *pattern;
481 * Match a pattern as in sh(1).
482 * pattern character are prefixed with MAGIC by expand.
486 gmatch(const char *s
, const char *p
, int isfile
)
490 if (s
== NULL
|| p
== NULL
)
494 /* isfile is false iff no syntax check has been done on
495 * the pattern. If check fails, just to a strcmp().
497 if (!isfile
&& !has_globbing(p
, pe
)) {
498 size_t len
= pe
- p
+ 1;
500 char *t
= len
<= sizeof(tbuf
) ? tbuf
:
503 return !strcmp(t
, s
);
505 return do_gmatch((const unsigned char *) s
, (const unsigned char *) se
,
506 (const unsigned char *) p
, (const unsigned char *) pe
);
509 /* Returns if p is a syntacticly correct globbing pattern, false
510 * if it contains no pattern characters or if there is a syntax error.
512 * - [ with no closing ]
513 * - imbalanced $(...) expression
514 * - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
518 if dest given, copy to dst
520 - if magic && (no globbing || syntax error)
526 has_globbing(const char *xp
, const char *xpe
)
528 const unsigned char *p
= (const unsigned char *) xp
;
529 const unsigned char *pe
= (const unsigned char *) xpe
;
531 int nest
= 0, bnest
= 0;
533 int in_bracket
= 0; /* inside [...] */
535 for (; p
< pe
; p
++) {
538 if ((c
= *++p
) == '*' || c
== '?')
544 if (ISMAGIC(p
[1]) && p
[2] == '!')
546 if (ISMAGIC(p
[1]) && p
[2] == ']')
549 /* XXX Do we need to check ranges here? POSIX Q */
550 } else if (c
== ']') {
552 if (bnest
) /* [a*(b]) */
556 } else if ((c
& 0x80) && strchr("*+?@! ", c
& 0x7f)) {
562 } else if (c
== '|') {
563 if (in_bracket
&& !bnest
) /* *(a[foo|bar]) */
565 } else if (c
== /*(*/ ')') {
567 if (!bnest
--) /* *(a[b)c] */
572 /* else must be a MAGIC-MAGIC, or MAGIC-!, MAGIC--, MAGIC-]
573 MAGIC-{, MAGIC-,, MAGIC-} */
575 return saw_glob
&& !in_bracket
&& !nest
;
578 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
580 do_gmatch(const unsigned char *s
, const unsigned char *se
,
581 const unsigned char *p
, const unsigned char *pe
)
584 const unsigned char *prest
, *psub
, *pnext
;
585 const unsigned char *srest
;
587 if (s
== NULL
|| p
== NULL
)
591 sc
= s
< se
? *s
: '\0';
600 if (sc
== 0 || (p
= cclass(p
, sc
)) == NULL
)
614 if (do_gmatch(s
, se
, p
, pe
))
620 * [*+?@!](pattern|pattern|..)
622 * Not ifdef'd KSH as this is needed for ${..%..}, etc.
624 case 0x80|'+': /* matches one or more times */
625 case 0x80|'*': /* matches zero or more times */
626 if (!(prest
= pat_scan(p
, pe
, 0)))
629 /* take care of zero matches */
630 if (p
[-1] == (0x80 | '*') &&
631 do_gmatch(s
, se
, prest
, pe
))
633 for (psub
= p
; ; psub
= pnext
) {
634 pnext
= pat_scan(psub
, pe
, 1);
635 for (srest
= s
; srest
<= se
; srest
++) {
636 if (do_gmatch(s
, srest
, psub
, pnext
- 2) &&
637 (do_gmatch(srest
, se
, prest
, pe
) ||
638 (s
!= srest
&& do_gmatch(srest
,
647 case 0x80|'?': /* matches zero or once */
648 case 0x80|'@': /* matches one of the patterns */
649 case 0x80|' ': /* simile for @ */
650 if (!(prest
= pat_scan(p
, pe
, 0)))
653 /* Take care of zero matches */
654 if (p
[-1] == (0x80 | '?') &&
655 do_gmatch(s
, se
, prest
, pe
))
657 for (psub
= p
; ; psub
= pnext
) {
658 pnext
= pat_scan(psub
, pe
, 1);
659 srest
= prest
== pe
? se
: s
;
660 for (; srest
<= se
; srest
++) {
661 if (do_gmatch(s
, srest
, psub
, pnext
- 2) &&
662 do_gmatch(srest
, se
, prest
, pe
))
670 case 0x80|'!': /* matches none of the patterns */
671 if (!(prest
= pat_scan(p
, pe
, 0)))
674 for (srest
= s
; srest
<= se
; srest
++) {
677 for (psub
= p
; ; psub
= pnext
) {
678 pnext
= pat_scan(psub
, pe
, 1);
679 if (do_gmatch(s
, srest
, psub
,
688 do_gmatch(srest
, se
, prest
, pe
))
703 posix_cclass(const unsigned char *pattern
, int test
, const unsigned char **ep
)
706 const unsigned char *colon
;
710 if ((colon
= strchr(pattern
, ':')) == NULL
|| colon
[1] != MAGIC
) {
714 *ep
= colon
+ 3; /* skip MAGIC */
715 len
= (size_t)(colon
- pattern
);
717 for (cc
= cclasses
; cc
->name
!= NULL
; cc
++) {
718 if (!strncmp(pattern
, cc
->name
, len
) && cc
->name
[len
] == '\0') {
719 if (cc
->isctype(test
))
724 if (cc
->name
== NULL
) {
725 rval
= -2; /* invalid character class */
730 static const unsigned char *
731 cclass(const unsigned char *p
, int sub
)
733 int c
, d
, rv
, not, found
= 0;
734 const unsigned char *orig_p
= p
;
736 if ((not = (ISMAGIC(*p
) && *++p
== '!')))
739 /* check for POSIX character class (e.g. [[:alpha:]]) */
740 if ((p
[0] == MAGIC
&& p
[1] == '[' && p
[2] == ':') ||
741 (p
[0] == '[' && p
[1] == ':')) {
743 const char *pp
= p
+ (*p
== MAGIC
) + 2;
744 rv
= posix_cclass(pp
, sub
, &p
);
752 } while (rv
!= -1 && p
[0] == MAGIC
&& p
[1] == '[' && p
[2] == ':');
753 if (p
[0] == MAGIC
&& p
[1] == ']')
760 if ((c
& 0x80) && !ISMAGIC(c
)) {
761 c
&= 0x7f;/* extended pattern matching: *+?@! */
762 /* XXX the ( char isn't handled as part of [] */
763 if (c
== ' ') /* simile for @: plain (..) */
768 /* No closing ] - act as if the opening [ was quoted */
769 return sub
== '[' ? orig_p
: NULL
;
770 if (ISMAGIC(p
[0]) && p
[1] == '-' &&
771 (!ISMAGIC(p
[2]) || p
[3] != ']')) {
776 if ((d
& 0x80) && !ISMAGIC(d
))
779 /* POSIX says this is an invalid expression */
784 if (c
== sub
|| (c
<= sub
&& sub
<= d
))
786 } while (!(ISMAGIC(p
[0]) && p
[1] == ']'));
788 return (found
!= not) ? p
+2 : NULL
;
791 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
792 const unsigned char *
793 pat_scan(const unsigned char *p
, const unsigned char *pe
, int match_sep
)
797 for (; p
< pe
; p
++) {
800 if ((*++p
== /*(*/ ')' && nest
-- == 0) ||
801 (*p
== '|' && match_sep
&& nest
== 0))
803 if ((*p
& 0x80) && strchr("*+?@! ", *p
& 0x7f))
810 * quick sort of array of generic pointers to objects.
813 qsortp(void **base
, /* base address */
814 size_t n
, /* elements */
815 int (*f
) (const void *, const void *)) /* compare function */
817 qsort(base
, n
, sizeof(char *), f
);
821 xstrcmp(const void *p1
, const void *p2
)
823 return (strcmp(*(char **)p1
, *(char **)p2
));
826 /* Initialize a Getopt structure */
828 ksh_getopt_reset(Getopt
*go
, int flags
)
839 /* getopt() used for shell built-in commands, the getopts command, and
840 * command line options.
841 * A leading ':' in options means don't print errors, instead return '?'
842 * or ':' and set go->optarg to the offending option character.
843 * If GF_ERROR is set (and option doesn't start with :), errors result in
844 * a call to bi_errorf().
846 * Non-standard features:
847 * - ';' is like ':' in options, except the argument is optional
848 * (if it isn't present, optarg is set to 0).
850 * - ',' is like ':' in options, except the argument always immediately
851 * follows the option character (optarg is set to the null string if
852 * the option is missing).
853 * Used for 'read -u2', 'print -u2' and fc -40.
854 * - '#' is like ':' in options, expect that the argument is optional
855 * and must start with a digit or be the string "unlimited". If the
856 * argument doesn't match, it is assumed to be missing and normal option
857 * processing continues (optarg is set to 0 if the option is missing).
858 * Used for 'typeset -LZ4' and 'ulimit -adunlimited'.
859 * - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
860 * option starting with + is accepted, the GI_PLUS flag will be set
864 ksh_getopt(char **argv
, Getopt
*go
, const char *options
)
869 if (go
->p
== 0 || (c
= argv
[go
->optind
- 1][go
->p
]) == '\0') {
870 char *arg
= argv
[go
->optind
], flag
= arg
? *arg
: '\0';
873 if (flag
== '-' && arg
[1] == '-' && arg
[2] == '\0') {
876 go
->info
|= GI_MINUSMINUS
;
880 ((flag
!= '-' ) && /* neither a - nor a + (if + allowed) */
881 (!(go
->flags
& GF_PLUSOPT
) || flag
!= '+')) ||
882 (c
= arg
[1]) == '\0') {
887 go
->info
&= ~(GI_MINUS
|GI_PLUS
);
888 go
->info
|= flag
== '-' ? GI_MINUS
: GI_PLUS
;
891 if (c
== '?' || c
== ':' || c
== ';' || c
== ',' || c
== '#' ||
892 !(o
= strchr(options
, c
))) {
893 if (options
[0] == ':') {
895 go
->optarg
= go
->buf
;
897 warningf(true, "%s%s-%c: unknown option",
898 (go
->flags
& GF_NONAME
) ? "" : argv
[0],
899 (go
->flags
& GF_NONAME
) ? "" : ": ", c
);
900 if (go
->flags
& GF_ERROR
)
905 /* : means argument must be present, may be part of option argument
906 * or the next argument
907 * ; same as : but argument may be missing
908 * , means argument is part of option argument, and may be null.
910 if (*++o
== ':' || *o
== ';') {
911 if (argv
[go
->optind
- 1][go
->p
])
912 go
->optarg
= argv
[go
->optind
- 1] + go
->p
;
913 else if (argv
[go
->optind
])
914 go
->optarg
= argv
[go
->optind
++];
918 if (options
[0] == ':') {
920 go
->optarg
= go
->buf
;
923 warningf(true, "%s%s-`%c' requires argument",
924 (go
->flags
& GF_NONAME
) ? "" : argv
[0],
925 (go
->flags
& GF_NONAME
) ? "" : ": ", c
);
926 if (go
->flags
& GF_ERROR
)
931 } else if (*o
== ',') {
932 /* argument is attached to option character, even if null */
933 go
->optarg
= argv
[go
->optind
- 1] + go
->p
;
935 } else if (*o
== '#') {
936 /* argument is optional and may be attached or unattached
937 * but must start with a digit. optarg is set to 0 if the
938 * argument is missing.
940 if (argv
[go
->optind
- 1][go
->p
]) {
941 if (digit(argv
[go
->optind
- 1][go
->p
]) ||
942 !strcmp(&argv
[go
->optind
- 1][go
->p
], "unlimited")) {
943 go
->optarg
= argv
[go
->optind
- 1] + go
->p
;
948 if (argv
[go
->optind
] && (digit(argv
[go
->optind
][0]) ||
949 !strcmp(argv
[go
->optind
], "unlimited"))) {
950 go
->optarg
= argv
[go
->optind
++];
959 /* print variable/alias value using necessary quotes
960 * (POSIX says they should be suitable for re-entry...)
961 * No trailing newline is printed.
964 print_value_quoted(const char *s
)
969 /* Test if any quotes are needed */
971 if (ctype(*p
, C_QUOTE
))
977 for (p
= s
; *p
; p
++) {
979 shprintf(inquote
? "'\\'" : "\\'");
986 shf_putc(*p
, shl_stdout
);
993 /* Print things in columns and rows - func() is called to format the ith
997 print_columns(struct shf
*shf
, int n
, char *(*func
) (void *, int, char *, int),
998 void *arg
, int max_width
, int prefcol
)
1000 char *str
= alloc(max_width
+ 1, ATEMP
);
1007 /* max_width + 1 for the space. Note that no space
1008 * is printed after the last column to avoid problems
1009 * with terminals that have auto-wrap.
1011 cols
= x_cols
/ (max_width
+ 1);
1014 rows
= (n
+ cols
- 1) / cols
;
1015 if (prefcol
&& n
&& cols
> rows
) {
1024 col_width
= max_width
;
1026 col_width
= 0; /* Don't pad entries in single column output. */
1027 nspace
= (x_cols
- max_width
* cols
) / cols
;
1030 for (r
= 0; r
< rows
; r
++) {
1031 for (c
= 0; c
< cols
; c
++) {
1034 shf_fprintf(shf
, "%-*s",
1036 (*func
)(arg
, i
, str
, max_width
+ 1));
1038 shf_fprintf(shf
, "%*s", nspace
, "");
1041 shf_putchar('\n', shf
);
1046 /* Strip any nul bytes from buf - returns new length (nbytes - # of nuls) */
1048 strip_nuls(char *buf
, int nbytes
)
1052 if ((dst
= memchr(buf
, '\0', nbytes
))) {
1053 char *end
= buf
+ nbytes
;
1056 for (p
= dst
; p
< end
; p
= q
) {
1057 /* skip a block of nulls */
1058 while (++p
< end
&& *p
== '\0')
1060 /* find end of non-null block */
1061 if (!(q
= memchr(p
, '\0', end
- p
)))
1063 memmove(dst
, p
, q
- p
);
1072 /* Like read(2), but if read fails due to non-blocking flag, resets flag
1073 * and restarts read.
1076 blocking_read(int fd
, char *buf
, int nbytes
)
1079 int tried_reset
= 0;
1081 while ((ret
= read(fd
, buf
, nbytes
)) < 0) {
1082 if (!tried_reset
&& errno
== EAGAIN
) {
1084 if (reset_nonblock(fd
) > 0) {
1095 /* Reset the non-blocking flag on the specified file descriptor.
1096 * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1100 reset_nonblock(int fd
)
1104 if ((flags
= fcntl(fd
, F_GETFL
)) < 0)
1106 if (!(flags
& O_NONBLOCK
))
1108 flags
&= ~O_NONBLOCK
;
1109 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1115 /* Like getcwd(), except bsize is ignored if buf is 0 (PATH_MAX is used) */
1117 ksh_get_wd(char *buf
, int bsize
)
1122 /* Note: we could just use plain getcwd(), but then we'd had to
1123 * inject possibly allocated space into the ATEMP area. */
1124 /* Assume getcwd() available */
1127 b
= alloc(PATH_MAX
+ 1, ATEMP
);
1131 ret
= getcwd(b
, bsize
);
1135 ret
= aresize(b
, strlen(b
) + 1, ATEMP
);