OSDN Git Service

Upgrade to mksh R40.
[android-x86/external-mksh.git] / src / misc.c
1 /*      $OpenBSD: misc.c,v 1.41 2015/09/10 22:48:58 nicm Exp $  */
2 /*      $OpenBSD: path.c,v 1.13 2015/09/05 09:47:08 jsg Exp $   */
3
4 /*-
5  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
6  *               2011, 2012, 2013, 2014, 2015, 2016
7  *      mirabilos <m@mirbsd.org>
8  *
9  * Provided that these terms and disclaimer and all copyright notices
10  * are retained or reproduced in an accompanying document, permission
11  * is granted to deal in this work without restriction, including un-
12  * limited rights to use, publicly perform, distribute, sell, modify,
13  * merge, give away, or sublicence.
14  *
15  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
16  * the utmost extent permitted by applicable law, neither express nor
17  * implied; without malicious intent or gross negligence. In no event
18  * may a licensor, author or contributor be held liable for indirect,
19  * direct, other damage, loss, or other issues arising in any way out
20  * of dealing in the work, even if advised of the possibility of such
21  * damage or existence of a defect, except proven that it results out
22  * of said person's immediate fault when using the work as intended.
23  */
24
25 #include "sh.h"
26 #if !HAVE_GETRUSAGE
27 #include <sys/times.h>
28 #endif
29 #if HAVE_GRP_H
30 #include <grp.h>
31 #endif
32
33 __RCSID("$MirOS: src/bin/mksh/misc.c,v 1.249 2016/11/11 23:31:35 tg Exp $");
34
35 #define KSH_CHVT_FLAG
36 #ifdef MKSH_SMALL
37 #undef KSH_CHVT_FLAG
38 #endif
39 #ifdef TIOCSCTTY
40 #define KSH_CHVT_CODE
41 #define KSH_CHVT_FLAG
42 #endif
43 #ifdef MKSH_LEGACY_MODE
44 #undef KSH_CHVT_CODE
45 #undef KSH_CHVT_FLAG
46 #endif
47
48 /* type bits for unsigned char */
49 unsigned char chtypes[UCHAR_MAX + 1];
50
51 static const unsigned char *pat_scan(const unsigned char *,
52     const unsigned char *, bool) MKSH_A_PURE;
53 static int do_gmatch(const unsigned char *, const unsigned char *,
54     const unsigned char *, const unsigned char *) MKSH_A_PURE;
55 static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char)
56     MKSH_A_PURE;
57 #ifdef KSH_CHVT_CODE
58 static void chvt(const Getopt *);
59 #endif
60
61 /*XXX this should go away */
62 static int make_path(const char *, const char *, char **, XString *, int *);
63
64 #ifdef SETUID_CAN_FAIL_WITH_EAGAIN
65 /* we don't need to check for other codes, EPERM won't happen */
66 #define DO_SETUID(func, argvec) do {                                    \
67         if ((func argvec) && errno == EAGAIN)                           \
68                 errorf("%s failed with EAGAIN, probably due to a"       \
69                     " too low process limit; aborting", #func);         \
70 } while (/* CONSTCOND */ 0)
71 #else
72 #define DO_SETUID(func, argvec) func argvec
73 #endif
74
75 /*
76  * Fast character classes
77  */
78 void
79 setctypes(const char *s, int t)
80 {
81         if (t & C_IFS) {
82                 unsigned int i = 0;
83
84                 while (++i <= UCHAR_MAX)
85                         chtypes[i] &= ~C_IFS;
86                 /* include '\0' in C_IFS */
87                 chtypes[0] |= C_IFS;
88         }
89         while (*s != 0)
90                 chtypes[(unsigned char)*s++] |= t;
91 }
92
93 void
94 initctypes(void)
95 {
96         setctypes(letters_uc, C_ALPHA);
97         setctypes(letters_lc, C_ALPHA);
98         chtypes['_'] |= C_ALPHA;
99         setctypes("0123456789", C_DIGIT);
100         /* \0 added automatically */
101         setctypes(TC_LEX1, C_LEX1);
102         setctypes("*@#!$-?", C_VAR1);
103         setctypes(TC_IFSWS, C_IFSWS);
104         setctypes("=-+?", C_SUBOP1);
105         setctypes("\t\n \"#$&'()*;<=>?[\\]`|", C_QUOTE);
106 }
107
108 /* called from XcheckN() to grow buffer */
109 char *
110 Xcheck_grow(XString *xsp, const char *xp, size_t more)
111 {
112         const char *old_beg = xsp->beg;
113
114         if (more < xsp->len)
115                 more = xsp->len;
116         /* (xsp->len + X_EXTRA) never overflows */
117         checkoktoadd(more, xsp->len + X_EXTRA);
118         xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
119         xsp->end = xsp->beg + xsp->len;
120         return (xsp->beg + (xp - old_beg));
121 }
122
123
124 #define SHFLAGS_DEFNS
125 #define FN(sname,cname,flags,ochar)             \
126         static const struct {                   \
127                 /* character flag (if any) */   \
128                 char c;                         \
129                 /* OF_* */                      \
130                 unsigned char optflags;         \
131                 /* long name of option */       \
132                 char name[sizeof(sname)];       \
133         } shoptione_ ## cname = {               \
134                 ochar, flags, sname             \
135         };
136 #include "sh_flags.gen"
137
138 #define OFC(i) (options[i][-2])
139 #define OFF(i) (((const unsigned char *)options[i])[-1])
140 #define OFN(i) (options[i])
141
142 const char * const options[] = {
143 #define SHFLAGS_ITEMS
144 #include "sh_flags.gen"
145 };
146
147 /*
148  * translate -o option into F* constant (also used for test -o option)
149  */
150 size_t
151 option(const char *n)
152 {
153         size_t i = 0;
154
155         if ((n[0] == '-' || n[0] == '+') && n[1] && !n[2])
156                 while (i < NELEM(options)) {
157                         if (OFC(i) == n[1])
158                                 return (i);
159                         ++i;
160                 }
161         else
162                 while (i < NELEM(options)) {
163                         if (!strcmp(OFN(i), n))
164                                 return (i);
165                         ++i;
166                 }
167
168         return ((size_t)-1);
169 }
170
171 struct options_info {
172         int opt_width;
173         int opts[NELEM(options)];
174 };
175
176 static void options_fmt_entry(char *, size_t, unsigned int, const void *);
177 static void printoptions(bool);
178
179 /* format a single select menu item */
180 static void
181 options_fmt_entry(char *buf, size_t buflen, unsigned int i, const void *arg)
182 {
183         const struct options_info *oi = (const struct options_info *)arg;
184
185         shf_snprintf(buf, buflen, "%-*s %s",
186             oi->opt_width, OFN(oi->opts[i]),
187             Flag(oi->opts[i]) ? "on" : "off");
188 }
189
190 static void
191 printoptions(bool verbose)
192 {
193         size_t i = 0;
194
195         if (verbose) {
196                 size_t n = 0, len, octs = 0;
197                 struct options_info oi;
198                 struct columnise_opts co;
199
200                 /* verbose version */
201                 shf_puts("Current option settings\n", shl_stdout);
202
203                 oi.opt_width = 0;
204                 while (i < NELEM(options)) {
205                         if ((len = strlen(OFN(i)))) {
206                                 oi.opts[n++] = i;
207                                 if (len > octs)
208                                         octs = len;
209                                 len = utf_mbswidth(OFN(i));
210                                 if ((int)len > oi.opt_width)
211                                         oi.opt_width = (int)len;
212                         }
213                         ++i;
214                 }
215                 co.shf = shl_stdout;
216                 co.linesep = '\n';
217                 co.prefcol = co.do_last = true;
218                 print_columns(&co, n, options_fmt_entry, &oi,
219                     octs + 4, oi.opt_width + 4);
220         } else {
221                 /* short version like AT&T ksh93 */
222                 shf_puts(Tset, shl_stdout);
223                 while (i < NELEM(options)) {
224                         if (Flag(i) && OFN(i)[0])
225                                 shprintf(" -o %s", OFN(i));
226                         ++i;
227                 }
228                 shf_putc('\n', shl_stdout);
229         }
230 }
231
232 char *
233 getoptions(void)
234 {
235         size_t i = 0;
236         char c, m[(int)FNFLAGS + 1];
237         char *cp = m;
238
239         while (i < NELEM(options)) {
240                 if ((c = OFC(i)) && Flag(i))
241                         *cp++ = c;
242                 ++i;
243         }
244         strndupx(cp, m, cp - m, ATEMP);
245         return (cp);
246 }
247
248 /* change a Flag(*) value; takes care of special actions */
249 void
250 change_flag(enum sh_flag f, int what, bool newset)
251 {
252         unsigned char oldval;
253         unsigned char newval = (newset ? 1 : 0);
254
255         if (f == FXTRACE) {
256                 change_xtrace(newval, true);
257                 return;
258         }
259         oldval = Flag(f);
260         Flag(f) = newval = (newset ? 1 : 0);
261 #ifndef MKSH_UNEMPLOYED
262         if (f == FMONITOR) {
263                 if (what != OF_CMDLINE && newval != oldval)
264                         j_change();
265         } else
266 #endif
267 #ifndef MKSH_NO_CMDLINE_EDITING
268           if ((
269 #if !MKSH_S_NOVI
270             f == FVI ||
271 #endif
272             f == FEMACS || f == FGMACS) && newval) {
273 #if !MKSH_S_NOVI
274                 Flag(FVI) =
275 #endif
276                     Flag(FEMACS) = Flag(FGMACS) = 0;
277                 Flag(f) = newval;
278         } else
279 #endif
280           if (f == FPRIVILEGED && oldval && !newval) {
281                 /* Turning off -p? */
282
283                 /*XXX this can probably be optimised */
284                 kshegid = kshgid = getgid();
285                 ksheuid = kshuid = getuid();
286 #if HAVE_SETRESUGID
287                 DO_SETUID(setresgid, (kshegid, kshegid, kshegid));
288 #if HAVE_SETGROUPS
289                 /* setgroups doesn't EAGAIN on Linux */
290                 setgroups(1, &kshegid);
291 #endif
292                 DO_SETUID(setresuid, (ksheuid, ksheuid, ksheuid));
293 #else /* !HAVE_SETRESUGID */
294                 /* setgid, setegid, seteuid don't EAGAIN on Linux */
295                 setgid(kshegid);
296 #ifndef MKSH__NO_SETEUGID
297                 setegid(kshegid);
298 #endif
299                 DO_SETUID(setuid, (ksheuid));
300 #ifndef MKSH__NO_SETEUGID
301                 seteuid(ksheuid);
302 #endif
303 #endif /* !HAVE_SETRESUGID */
304         } else if ((f == FPOSIX || f == FSH) && newval) {
305                 /* Turning on -o posix or -o sh? */
306                 Flag(FBRACEEXPAND) = 0;
307         } else if (f == FTALKING) {
308                 /* Changing interactive flag? */
309                 if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
310                         Flag(FTALKING_I) = newval;
311         }
312 }
313
314 void
315 change_xtrace(unsigned char newval, bool dosnapshot)
316 {
317         static bool in_xtrace;
318
319         if (in_xtrace)
320                 return;
321
322         if (!dosnapshot && newval == Flag(FXTRACE))
323                 return;
324
325         if (Flag(FXTRACE) == 2) {
326                 shf_putc('\n', shl_xtrace);
327                 Flag(FXTRACE) = 1;
328                 shf_flush(shl_xtrace);
329         }
330
331         if (!dosnapshot && Flag(FXTRACE) == 1)
332                 switch (newval) {
333                 case 1:
334                         return;
335                 case 2:
336                         goto changed_xtrace;
337                 }
338
339         shf_flush(shl_xtrace);
340         if (shl_xtrace->fd != 2)
341                 close(shl_xtrace->fd);
342         if (!newval || (shl_xtrace->fd = savefd(2)) == -1)
343                 shl_xtrace->fd = 2;
344
345  changed_xtrace:
346         if ((Flag(FXTRACE) = newval) == 2) {
347                 in_xtrace = true;
348                 Flag(FXTRACE) = 0;
349                 shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
350                 Flag(FXTRACE) = 2;
351                 in_xtrace = false;
352         }
353 }
354
355 /*
356  * Parse command line and set command arguments. Returns the index of
357  * non-option arguments, -1 if there is an error.
358  */
359 int
360 parse_args(const char **argv,
361     /* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
362     int what,
363     bool *setargsp)
364 {
365         static const char cmd_opts[] =
366 #define SHFLAGS_NOT_SET
367 #define SHFLAGS_OPTCS
368 #include "sh_flags.gen"
369 #undef SHFLAGS_NOT_SET
370             ;
371         static const char set_opts[] =
372 #define SHFLAGS_NOT_CMD
373 #define SHFLAGS_OPTCS
374 #include "sh_flags.gen"
375 #undef SHFLAGS_NOT_CMD
376             ;
377         bool set;
378         const char *opts;
379         const char *array = NULL;
380         Getopt go;
381         size_t i;
382         int optc, arrayset = 0;
383         bool sortargs = false;
384         bool fcompatseen = false;
385
386         if (what == OF_CMDLINE) {
387                 const char *p = argv[0], *q;
388                 /*
389                  * Set FLOGIN before parsing options so user can clear
390                  * flag using +l.
391                  */
392                 if (*p != '-')
393                         for (q = p; *q; )
394                                 if (mksh_cdirsep(*q++))
395                                         p = q;
396                 Flag(FLOGIN) = (*p == '-');
397                 opts = cmd_opts;
398         } else if (what == OF_FIRSTTIME) {
399                 opts = cmd_opts;
400         } else
401                 opts = set_opts;
402         ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
403         while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
404                 set = tobool(!(go.info & GI_PLUS));
405                 switch (optc) {
406                 case 'A':
407                         if (what == OF_FIRSTTIME)
408                                 break;
409                         arrayset = set ? 1 : -1;
410                         array = go.optarg;
411                         break;
412
413                 case 'o':
414                         if (what == OF_FIRSTTIME)
415                                 break;
416                         if (go.optarg == NULL) {
417                                 /*
418                                  * lone -o: print options
419                                  *
420                                  * Note that on the command line, -o requires
421                                  * an option (ie, can't get here if what is
422                                  * OF_CMDLINE).
423                                  */
424                                 printoptions(set);
425                                 break;
426                         }
427                         i = option(go.optarg);
428                         if ((i == FPOSIX || i == FSH) && set && !fcompatseen) {
429                                 /*
430                                  * If running 'set -o posix' or
431                                  * 'set -o sh', turn off the other;
432                                  * if running 'set -o posix -o sh'
433                                  * allow both to be set though.
434                                  */
435                                 Flag(FPOSIX) = 0;
436                                 Flag(FSH) = 0;
437                                 fcompatseen = true;
438                         }
439                         if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
440                                 /*
441                                  * Don't check the context if the flag
442                                  * isn't changing - makes "set -o interactive"
443                                  * work if you're already interactive. Needed
444                                  * if the output of "set +o" is to be used.
445                                  */
446                                 ;
447                         else if ((i != (size_t)-1) && (OFF(i) & what))
448                                 change_flag((enum sh_flag)i, what, set);
449                         else {
450                                 bi_errorf(Tf_sD_s, go.optarg,
451                                     Tunknown_option);
452                                 return (-1);
453                         }
454                         break;
455
456 #ifdef KSH_CHVT_FLAG
457                 case 'T':
458                         if (what != OF_FIRSTTIME)
459                                 break;
460 #ifndef KSH_CHVT_CODE
461                         errorf("no TIOCSCTTY ioctl");
462 #else
463                         change_flag(FTALKING, OF_CMDLINE, true);
464                         chvt(&go);
465                         break;
466 #endif
467 #endif
468
469                 case '?':
470                         return (-1);
471
472                 default:
473                         if (what == OF_FIRSTTIME)
474                                 break;
475                         /* -s: sort positional params (AT&T ksh stupidity) */
476                         if (what == OF_SET && optc == 's') {
477                                 sortargs = true;
478                                 break;
479                         }
480                         for (i = 0; i < NELEM(options); i++)
481                                 if (optc == OFC(i) &&
482                                     (what & OFF(i))) {
483                                         change_flag((enum sh_flag)i, what, set);
484                                         break;
485                                 }
486                         if (i == NELEM(options))
487                                 internal_errorf("parse_args: '%c'", optc);
488                 }
489         }
490         if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
491             (argv[go.optind][0] == '-' || argv[go.optind][0] == '+') &&
492             argv[go.optind][1] == '\0') {
493                 /* lone - clears -v and -x flags */
494                 if (argv[go.optind][0] == '-') {
495                         Flag(FVERBOSE) = 0;
496                         change_xtrace(0, false);
497                 }
498                 /* set skips lone - or + option */
499                 go.optind++;
500         }
501         if (setargsp)
502                 /* -- means set $#/$* even if there are no arguments */
503                 *setargsp = !arrayset && ((go.info & GI_MINUSMINUS) ||
504                     argv[go.optind]);
505
506         if (arrayset) {
507                 const char *ccp = NULL;
508
509                 if (*array)
510                         ccp = skip_varname(array, false);
511                 if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
512                         bi_errorf(Tf_sD_s, array, Tnot_ident);
513                         return (-1);
514                 }
515         }
516         if (sortargs) {
517                 for (i = go.optind; argv[i]; i++)
518                         ;
519                 qsort(&argv[go.optind], i - go.optind, sizeof(void *),
520                     xstrcmp);
521         }
522         if (arrayset)
523                 go.optind += set_array(array, tobool(arrayset > 0),
524                     argv + go.optind);
525
526         return (go.optind);
527 }
528
529 /* parse a decimal number: returns 0 if string isn't a number, 1 otherwise */
530 int
531 getn(const char *s, int *ai)
532 {
533         char c;
534         mksh_ari_u num;
535         bool neg = false;
536
537         num.u = 0;
538
539         do {
540                 c = *s++;
541         } while (ksh_isspace(c));
542
543         switch (c) {
544         case '-':
545                 neg = true;
546                 /* FALLTHROUGH */
547         case '+':
548                 c = *s++;
549                 break;
550         }
551
552         do {
553                 if (!ksh_isdigit(c))
554                         /* not numeric */
555                         return (0);
556                 if (num.u > 214748364U)
557                         /* overflow on multiplication */
558                         return (0);
559                 num.u = num.u * 10U + (unsigned int)ksh_numdig(c);
560                 /* now: num.u <= 2147483649U */
561         } while ((c = *s++));
562
563         if (num.u > (neg ? 2147483648U : 2147483647U))
564                 /* overflow for signed 32-bit int */
565                 return (0);
566
567         if (neg)
568                 num.u = -num.u;
569         *ai = num.i;
570         return (1);
571 }
572
573 /**
574  * pattern simplifications:
575  * - @(x) -> x (not @(x|y) though)
576  * - ** -> *
577  */
578 static void *
579 simplify_gmatch_pattern(const unsigned char *sp)
580 {
581         uint8_t c;
582         unsigned char *cp, *dp;
583         const unsigned char *ps, *se;
584
585         cp = alloc(strlen((const void *)sp) + 1, ATEMP);
586         goto simplify_gmatch_pat1a;
587
588         /* foo@(b@(a)r)b@(a|a)z -> foobarb@(a|a)z */
589  simplify_gmatch_pat1:
590         sp = cp;
591  simplify_gmatch_pat1a:
592         dp = cp;
593         se = sp + strlen((const void *)sp);
594         while ((c = *sp++)) {
595                 if (!ISMAGIC(c)) {
596                         *dp++ = c;
597                         continue;
598                 }
599                 switch ((c = *sp++)) {
600                 case 0x80|'@':
601                 /* simile for @ */
602                 case 0x80|' ':
603                         /* check whether it has only one clause */
604                         ps = pat_scan(sp, se, true);
605                         if (!ps || ps[-1] != /*(*/ ')')
606                                 /* nope */
607                                 break;
608                         /* copy inner clause until matching close */
609                         ps -= 2;
610                         while ((const unsigned char *)sp < ps)
611                                 *dp++ = *sp++;
612                         /* skip MAGIC and closing parenthesis */
613                         sp += 2;
614                         /* copy the rest of the pattern */
615                         memmove(dp, sp, strlen((const void *)sp) + 1);
616                         /* redo from start */
617                         goto simplify_gmatch_pat1;
618                 }
619                 *dp++ = MAGIC;
620                 *dp++ = c;
621         }
622         *dp = '\0';
623
624         /* collapse adjacent asterisk wildcards */
625         sp = dp = cp;
626         while ((c = *sp++)) {
627                 if (!ISMAGIC(c)) {
628                         *dp++ = c;
629                         continue;
630                 }
631                 switch ((c = *sp++)) {
632                 case '*':
633                         while (ISMAGIC(sp[0]) && sp[1] == c)
634                                 sp += 2;
635                         break;
636                 }
637                 *dp++ = MAGIC;
638                 *dp++ = c;
639         }
640         *dp = '\0';
641
642         /* return the result, allocated from ATEMP */
643         return (cp);
644 }
645
646 /* -------- gmatch.c -------- */
647
648 /*
649  * int gmatch(string, pattern)
650  * char *string, *pattern;
651  *
652  * Match a pattern as in sh(1).
653  * pattern character are prefixed with MAGIC by expand.
654  */
655 int
656 gmatchx(const char *s, const char *p, bool isfile)
657 {
658         const char *se, *pe;
659         char *pnew;
660         int rv;
661
662         if (s == NULL || p == NULL)
663                 return (0);
664
665         se = s + strlen(s);
666         pe = p + strlen(p);
667         /*
668          * isfile is false iff no syntax check has been done on
669          * the pattern. If check fails, just to a strcmp().
670          */
671         if (!isfile && !has_globbing(p, pe)) {
672                 size_t len = pe - p + 1;
673                 char tbuf[64];
674                 char *t = len <= sizeof(tbuf) ? tbuf : alloc(len, ATEMP);
675                 debunk(t, p, len);
676                 return (!strcmp(t, s));
677         }
678
679         /*
680          * since the do_gmatch() engine sucks so much, we must do some
681          * pattern simplifications
682          */
683         pnew = simplify_gmatch_pattern((const unsigned char *)p);
684         pe = pnew + strlen(pnew);
685
686         rv = do_gmatch((const unsigned char *)s, (const unsigned char *)se,
687             (const unsigned char *)pnew, (const unsigned char *)pe);
688         afree(pnew, ATEMP);
689         return (rv);
690 }
691
692 /**
693  * Returns if p is a syntacticly correct globbing pattern, false
694  * if it contains no pattern characters or if there is a syntax error.
695  * Syntax errors are:
696  *      - [ with no closing ]
697  *      - imbalanced $(...) expression
698  *      - [...] and *(...) not nested (eg, [a$(b|]c), *(a[b|c]d))
699  */
700 /*XXX
701  * - if no magic,
702  *      if dest given, copy to dst
703  *      return ?
704  * - if magic && (no globbing || syntax error)
705  *      debunk to dst
706  *      return ?
707  * - return ?
708  */
709 int
710 has_globbing(const char *xp, const char *xpe)
711 {
712         const unsigned char *p = (const unsigned char *) xp;
713         const unsigned char *pe = (const unsigned char *) xpe;
714         int c;
715         int nest = 0, bnest = 0;
716         bool saw_glob = false;
717         /* inside [...] */
718         bool in_bracket = false;
719
720         for (; p < pe; p++) {
721                 if (!ISMAGIC(*p))
722                         continue;
723                 if ((c = *++p) == '*' || c == '?')
724                         saw_glob = true;
725                 else if (c == '[') {
726                         if (!in_bracket) {
727                                 saw_glob = true;
728                                 in_bracket = true;
729                                 if (ISMAGIC(p[1]) && p[2] == '!')
730                                         p += 2;
731                                 if (ISMAGIC(p[1]) && p[2] == ']')
732                                         p += 2;
733                         }
734                         /*XXX Do we need to check ranges here? POSIX Q */
735                 } else if (c == ']') {
736                         if (in_bracket) {
737                                 if (bnest)
738                                         /* [a*(b]) */
739                                         return (0);
740                                 in_bracket = false;
741                         }
742                 } else if ((c & 0x80) && vstrchr("*+?@! ", c & 0x7f)) {
743                         saw_glob = true;
744                         if (in_bracket)
745                                 bnest++;
746                         else
747                                 nest++;
748                 } else if (c == '|') {
749                         if (in_bracket && !bnest)
750                                 /* *(a[foo|bar]) */
751                                 return (0);
752                 } else if (c == /*(*/ ')') {
753                         if (in_bracket) {
754                                 if (!bnest--)
755                                         /* *(a[b)c] */
756                                         return (0);
757                         } else if (nest)
758                                 nest--;
759                 }
760                 /*
761                  * else must be a MAGIC-MAGIC, or MAGIC-!,
762                  * MAGIC--, MAGIC-], MAGIC-{, MAGIC-, MAGIC-}
763                  */
764         }
765         return (saw_glob && !in_bracket && !nest);
766 }
767
768 /* Function must return either 0 or 1 (assumed by code for 0x80|'!') */
769 static int
770 do_gmatch(const unsigned char *s, const unsigned char *se,
771     const unsigned char *p, const unsigned char *pe)
772 {
773         unsigned char sc, pc;
774         const unsigned char *prest, *psub, *pnext;
775         const unsigned char *srest;
776
777         if (s == NULL || p == NULL)
778                 return (0);
779         while (p < pe) {
780                 pc = *p++;
781                 sc = s < se ? *s : '\0';
782                 s++;
783                 if (!ISMAGIC(pc)) {
784                         if (sc != pc)
785                                 return (0);
786                         continue;
787                 }
788                 switch (*p++) {
789                 case '[':
790                         if (sc == 0 || (p = gmatch_cclass(p, sc)) == NULL)
791                                 return (0);
792                         break;
793
794                 case '?':
795                         if (sc == 0)
796                                 return (0);
797                         if (UTFMODE) {
798                                 --s;
799                                 s += utf_ptradj((const void *)s);
800                         }
801                         break;
802
803                 case '*':
804                         if (p == pe)
805                                 return (1);
806                         s--;
807                         do {
808                                 if (do_gmatch(s, se, p, pe))
809                                         return (1);
810                         } while (s++ < se);
811                         return (0);
812
813                 /**
814                  * [*+?@!](pattern|pattern|..)
815                  * This is also needed for ${..%..}, etc.
816                  */
817
818                 /* matches one or more times */
819                 case 0x80|'+':
820                 /* matches zero or more times */
821                 case 0x80|'*':
822                         if (!(prest = pat_scan(p, pe, false)))
823                                 return (0);
824                         s--;
825                         /* take care of zero matches */
826                         if (p[-1] == (0x80 | '*') &&
827                             do_gmatch(s, se, prest, pe))
828                                 return (1);
829                         for (psub = p; ; psub = pnext) {
830                                 pnext = pat_scan(psub, pe, true);
831                                 for (srest = s; srest <= se; srest++) {
832                                         if (do_gmatch(s, srest, psub, pnext - 2) &&
833                                             (do_gmatch(srest, se, prest, pe) ||
834                                             (s != srest && do_gmatch(srest,
835                                             se, p - 2, pe))))
836                                                 return (1);
837                                 }
838                                 if (pnext == prest)
839                                         break;
840                         }
841                         return (0);
842
843                 /* matches zero or once */
844                 case 0x80|'?':
845                 /* matches one of the patterns */
846                 case 0x80|'@':
847                 /* simile for @ */
848                 case 0x80|' ':
849                         if (!(prest = pat_scan(p, pe, false)))
850                                 return (0);
851                         s--;
852                         /* Take care of zero matches */
853                         if (p[-1] == (0x80 | '?') &&
854                             do_gmatch(s, se, prest, pe))
855                                 return (1);
856                         for (psub = p; ; psub = pnext) {
857                                 pnext = pat_scan(psub, pe, true);
858                                 srest = prest == pe ? se : s;
859                                 for (; srest <= se; srest++) {
860                                         if (do_gmatch(s, srest, psub, pnext - 2) &&
861                                             do_gmatch(srest, se, prest, pe))
862                                                 return (1);
863                                 }
864                                 if (pnext == prest)
865                                         break;
866                         }
867                         return (0);
868
869                 /* matches none of the patterns */
870                 case 0x80|'!':
871                         if (!(prest = pat_scan(p, pe, false)))
872                                 return (0);
873                         s--;
874                         for (srest = s; srest <= se; srest++) {
875                                 int matched = 0;
876
877                                 for (psub = p; ; psub = pnext) {
878                                         pnext = pat_scan(psub, pe, true);
879                                         if (do_gmatch(s, srest, psub,
880                                             pnext - 2)) {
881                                                 matched = 1;
882                                                 break;
883                                         }
884                                         if (pnext == prest)
885                                                 break;
886                                 }
887                                 if (!matched &&
888                                     do_gmatch(srest, se, prest, pe))
889                                         return (1);
890                         }
891                         return (0);
892
893                 default:
894                         if (sc != p[-1])
895                                 return (0);
896                         break;
897                 }
898         }
899         return (s == se);
900 }
901
902 static const unsigned char *
903 gmatch_cclass(const unsigned char *p, unsigned char sub)
904 {
905         unsigned char c, d;
906         bool notp, found = false;
907         const unsigned char *orig_p = p;
908
909         if ((notp = tobool(ISMAGIC(*p) && *++p == '!')))
910                 p++;
911         do {
912                 c = *p++;
913                 if (ISMAGIC(c)) {
914                         c = *p++;
915                         if ((c & 0x80) && !ISMAGIC(c)) {
916                                 /* extended pattern matching: *+?@! */
917                                 c &= 0x7F;
918                                 /* XXX the ( char isn't handled as part of [] */
919                                 if (c == ' ')
920                                         /* simile for @: plain (..) */
921                                         c = '(' /*)*/;
922                         }
923                 }
924                 if (c == '\0')
925                         /* No closing ] - act as if the opening [ was quoted */
926                         return (sub == '[' ? orig_p : NULL);
927                 if (ISMAGIC(p[0]) && p[1] == '-' &&
928                     (!ISMAGIC(p[2]) || p[3] != ']')) {
929                         /* MAGIC- */
930                         p += 2;
931                         d = *p++;
932                         if (ISMAGIC(d)) {
933                                 d = *p++;
934                                 if ((d & 0x80) && !ISMAGIC(d))
935                                         d &= 0x7f;
936                         }
937                         /* POSIX says this is an invalid expression */
938                         if (c > d)
939                                 return (NULL);
940                 } else
941                         d = c;
942                 if (c == sub || (c <= sub && sub <= d))
943                         found = true;
944         } while (!(ISMAGIC(p[0]) && p[1] == ']'));
945
946         return ((found != notp) ? p+2 : NULL);
947 }
948
949 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
950 static const unsigned char *
951 pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
952 {
953         int nest = 0;
954
955         for (; p < pe; p++) {
956                 if (!ISMAGIC(*p))
957                         continue;
958                 if ((*++p == /*(*/ ')' && nest-- == 0) ||
959                     (*p == '|' && match_sep && nest == 0))
960                         return (p + 1);
961                 if ((*p & 0x80) && vstrchr("*+?@! ", *p & 0x7f))
962                         nest++;
963         }
964         return (NULL);
965 }
966
967 int
968 xstrcmp(const void *p1, const void *p2)
969 {
970         return (strcmp(*(const char * const *)p1, *(const char * const *)p2));
971 }
972
973 /* Initialise a Getopt structure */
974 void
975 ksh_getopt_reset(Getopt *go, int flags)
976 {
977         go->optind = 1;
978         go->optarg = NULL;
979         go->p = 0;
980         go->flags = flags;
981         go->info = 0;
982         go->buf[1] = '\0';
983 }
984
985
986 /**
987  * getopt() used for shell built-in commands, the getopts command, and
988  * command line options.
989  * A leading ':' in options means don't print errors, instead return '?'
990  * or ':' and set go->optarg to the offending option character.
991  * If GF_ERROR is set (and option doesn't start with :), errors result in
992  * a call to bi_errorf().
993  *
994  * Non-standard features:
995  *      - ';' is like ':' in options, except the argument is optional
996  *        (if it isn't present, optarg is set to 0).
997  *        Used for 'set -o'.
998  *      - ',' is like ':' in options, except the argument always immediately
999  *        follows the option character (optarg is set to the null string if
1000  *        the option is missing).
1001  *        Used for 'read -u2', 'print -u2' and fc -40.
1002  *      - '#' is like ':' in options, expect that the argument is optional
1003  *        and must start with a digit. If the argument doesn't start with a
1004  *        digit, it is assumed to be missing and normal option processing
1005  *        continues (optarg is set to 0 if the option is missing).
1006  *        Used for 'typeset -LZ4'.
1007  *      - accepts +c as well as -c IF the GF_PLUSOPT flag is present. If an
1008  *        option starting with + is accepted, the GI_PLUS flag will be set
1009  *        in go->info.
1010  */
1011 int
1012 ksh_getopt(const char **argv, Getopt *go, const char *optionsp)
1013 {
1014         char c;
1015         const char *o;
1016
1017         if (go->p == 0 || (c = argv[go->optind - 1][go->p]) == '\0') {
1018                 const char *arg = argv[go->optind], flag = arg ? *arg : '\0';
1019
1020                 go->p = 1;
1021                 if (flag == '-' && ksh_isdash(arg + 1)) {
1022                         go->optind++;
1023                         go->p = 0;
1024                         go->info |= GI_MINUSMINUS;
1025                         return (-1);
1026                 }
1027                 if (arg == NULL ||
1028                     ((flag != '-' ) &&
1029                     /* neither a - nor a + (if + allowed) */
1030                     (!(go->flags & GF_PLUSOPT) || flag != '+')) ||
1031                     (c = arg[1]) == '\0') {
1032                         go->p = 0;
1033                         return (-1);
1034                 }
1035                 go->optind++;
1036                 go->info &= ~(GI_MINUS|GI_PLUS);
1037                 go->info |= flag == '-' ? GI_MINUS : GI_PLUS;
1038         }
1039         go->p++;
1040         if (c == '?' || c == ':' || c == ';' || c == ',' || c == '#' ||
1041             !(o = cstrchr(optionsp, c))) {
1042                 if (optionsp[0] == ':') {
1043                         go->buf[0] = c;
1044                         go->optarg = go->buf;
1045                 } else {
1046                         warningf(true, Tf_optfoo,
1047                             (go->flags & GF_NONAME) ? "" : argv[0],
1048                             (go->flags & GF_NONAME) ? "" : Tcolsp,
1049                             c, Tunknown_option);
1050                         if (go->flags & GF_ERROR)
1051                                 bi_errorfz();
1052                 }
1053                 return ('?');
1054         }
1055         /**
1056          * : means argument must be present, may be part of option argument
1057          *   or the next argument
1058          * ; same as : but argument may be missing
1059          * , means argument is part of option argument, and may be null.
1060          */
1061         if (*++o == ':' || *o == ';') {
1062                 if (argv[go->optind - 1][go->p])
1063                         go->optarg = argv[go->optind - 1] + go->p;
1064                 else if (argv[go->optind])
1065                         go->optarg = argv[go->optind++];
1066                 else if (*o == ';')
1067                         go->optarg = NULL;
1068                 else {
1069                         if (optionsp[0] == ':') {
1070                                 go->buf[0] = c;
1071                                 go->optarg = go->buf;
1072                                 return (':');
1073                         }
1074                         warningf(true, Tf_optfoo,
1075                             (go->flags & GF_NONAME) ? "" : argv[0],
1076                             (go->flags & GF_NONAME) ? "" : Tcolsp,
1077                             c, Treq_arg);
1078                         if (go->flags & GF_ERROR)
1079                                 bi_errorfz();
1080                         return ('?');
1081                 }
1082                 go->p = 0;
1083         } else if (*o == ',') {
1084                 /* argument is attached to option character, even if null */
1085                 go->optarg = argv[go->optind - 1] + go->p;
1086                 go->p = 0;
1087         } else if (*o == '#') {
1088                 /*
1089                  * argument is optional and may be attached or unattached
1090                  * but must start with a digit. optarg is set to 0 if the
1091                  * argument is missing.
1092                  */
1093                 if (argv[go->optind - 1][go->p]) {
1094                         if (ksh_isdigit(argv[go->optind - 1][go->p])) {
1095                                 go->optarg = argv[go->optind - 1] + go->p;
1096                                 go->p = 0;
1097                         } else
1098                                 go->optarg = NULL;
1099                 } else {
1100                         if (argv[go->optind] && ksh_isdigit(argv[go->optind][0])) {
1101                                 go->optarg = argv[go->optind++];
1102                                 go->p = 0;
1103                         } else
1104                                 go->optarg = NULL;
1105                 }
1106         }
1107         return (c);
1108 }
1109
1110 /*
1111  * print variable/alias value using necessary quotes
1112  * (POSIX says they should be suitable for re-entry...)
1113  * No trailing newline is printed.
1114  */
1115 void
1116 print_value_quoted(struct shf *shf, const char *s)
1117 {
1118         unsigned char c;
1119         const unsigned char *p = (const unsigned char *)s;
1120         bool inquote = true;
1121
1122         /* first, check whether any quotes are needed */
1123         while ((c = *p++) >= 32)
1124                 if (ctype(c, C_QUOTE))
1125                         inquote = false;
1126
1127         p = (const unsigned char *)s;
1128         if (c == 0) {
1129                 if (inquote) {
1130                         /* nope, use the shortcut */
1131                         shf_puts(s, shf);
1132                         return;
1133                 }
1134
1135                 /* otherwise, quote nicely via state machine */
1136                 while ((c = *p++) != 0) {
1137                         if (c == '\'') {
1138                                 /*
1139                                  * multiple single quotes or any of them
1140                                  * at the beginning of a string look nicer
1141                                  * this way than when simply substituting
1142                                  */
1143                                 if (inquote) {
1144                                         shf_putc('\'', shf);
1145                                         inquote = false;
1146                                 }
1147                                 shf_putc('\\', shf);
1148                         } else if (!inquote) {
1149                                 shf_putc('\'', shf);
1150                                 inquote = true;
1151                         }
1152                         shf_putc(c, shf);
1153                 }
1154         } else {
1155                 unsigned int wc;
1156                 size_t n;
1157
1158                 /* use $'...' quote format */
1159                 shf_putc('$', shf);
1160                 shf_putc('\'', shf);
1161                 while ((c = *p) != 0) {
1162                         if (c >= 0xC2) {
1163                                 n = utf_mbtowc(&wc, (const char *)p);
1164                                 if (n != (size_t)-1) {
1165                                         p += n;
1166                                         shf_fprintf(shf, "\\u%04X", wc);
1167                                         continue;
1168                                 }
1169                         }
1170                         ++p;
1171                         switch (c) {
1172                         /* see unbksl() in this file for comments */
1173                         case 7:
1174                                 c = 'a';
1175                                 if (0)
1176                                         /* FALLTHROUGH */
1177                         case '\b':
1178                                   c = 'b';
1179                                 if (0)
1180                                         /* FALLTHROUGH */
1181                         case '\f':
1182                                   c = 'f';
1183                                 if (0)
1184                                         /* FALLTHROUGH */
1185                         case '\n':
1186                                   c = 'n';
1187                                 if (0)
1188                                         /* FALLTHROUGH */
1189                         case '\r':
1190                                   c = 'r';
1191                                 if (0)
1192                                         /* FALLTHROUGH */
1193                         case '\t':
1194                                   c = 't';
1195                                 if (0)
1196                                         /* FALLTHROUGH */
1197                         case 11:
1198                                   c = 'v';
1199                                 if (0)
1200                                         /* FALLTHROUGH */
1201                         case '\033':
1202                                 /* take E not e because \e is \ in *roff */
1203                                   c = 'E';
1204                                 /* FALLTHROUGH */
1205                         case '\\':
1206                                 shf_putc('\\', shf);
1207
1208                                 if (0)
1209                                         /* FALLTHROUGH */
1210                         default:
1211                                   if (c < 32 || c > 0x7E) {
1212                                         /* FALLTHROUGH */
1213                         case '\'':
1214                                         shf_fprintf(shf, "\\%03o", c);
1215                                         break;
1216                                 }
1217
1218                                 shf_putc(c, shf);
1219                                 break;
1220                         }
1221                 }
1222                 inquote = true;
1223         }
1224         if (inquote)
1225                 shf_putc('\'', shf);
1226 }
1227
1228 /*
1229  * Print things in columns and rows - func() is called to format
1230  * the i-th element
1231  */
1232 void
1233 print_columns(struct columnise_opts *opts, unsigned int n,
1234     void (*func)(char *, size_t, unsigned int, const void *),
1235     const void *arg, size_t max_oct, size_t max_colz)
1236 {
1237         unsigned int i, r = 0, c, rows, cols, nspace, max_col;
1238         char *str;
1239
1240         if (!n)
1241                 return;
1242
1243         if (max_colz > 2147483646) {
1244 #ifndef MKSH_SMALL
1245                 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1246                     "max_col", max_colz);
1247 #endif
1248                 return;
1249         }
1250         max_col = (unsigned int)max_colz;
1251
1252         if (max_oct > 2147483646) {
1253 #ifndef MKSH_SMALL
1254                 internal_warningf("print_columns called with %s=%zu >= INT_MAX",
1255                     "max_oct", max_oct);
1256 #endif
1257                 return;
1258         }
1259         ++max_oct;
1260         str = alloc(max_oct, ATEMP);
1261
1262         /*
1263          * We use (max_col + 2) to consider the separator space.
1264          * Note that no spaces are printed after the last column
1265          * to avoid problems with terminals that have auto-wrap,
1266          * but we need to also take this into account in x_cols.
1267          */
1268         cols = (x_cols + 1) / (max_col + 2);
1269
1270         /* if we can only print one column anyway, skip the goo */
1271         if (cols < 2) {
1272                 goto prcols_easy;
1273                 while (r < n) {
1274                         shf_putc(opts->linesep, opts->shf);
1275  prcols_easy:
1276                         (*func)(str, max_oct, r++, arg);
1277                         shf_puts(str, opts->shf);
1278                 }
1279                 goto out;
1280         }
1281
1282         rows = (n + cols - 1) / cols;
1283         if (opts->prefcol && cols > rows) {
1284                 cols = rows;
1285                 rows = (n + cols - 1) / cols;
1286         }
1287
1288         nspace = (x_cols - max_col * cols) / cols;
1289         if (nspace < 2)
1290                 nspace = 2;
1291         max_col = -max_col;
1292         goto prcols_hard;
1293         while (r < rows) {
1294                 shf_putchar(opts->linesep, opts->shf);
1295  prcols_hard:
1296                 for (c = 0; c < cols; c++) {
1297                         if ((i = c * rows + r) >= n)
1298                                 break;
1299                         (*func)(str, max_oct, i, arg);
1300                         if (i + rows >= n)
1301                                 shf_puts(str, opts->shf);
1302                         else
1303                                 shf_fprintf(opts->shf, "%*s%*s",
1304                                     (int)max_col, str, (int)nspace, null);
1305                 }
1306                 ++r;
1307         }
1308  out:
1309         if (opts->do_last)
1310                 shf_putchar(opts->linesep, opts->shf);
1311         afree(str, ATEMP);
1312 }
1313
1314 /* strip all NUL bytes from buf; output is NUL-terminated if stripped */
1315 void
1316 strip_nuls(char *buf, size_t len)
1317 {
1318         char *cp, *dp, *ep;
1319
1320         if (!len || !(dp = memchr(buf, '\0', len)))
1321                 return;
1322
1323         ep = buf + len;
1324         cp = dp;
1325
1326  cp_has_nul_byte:
1327         while (cp++ < ep && *cp == '\0')
1328                 ;       /* nothing */
1329         while (cp < ep && *cp != '\0')
1330                 *dp++ = *cp++;
1331         if (cp < ep)
1332                 goto cp_has_nul_byte;
1333
1334         *dp = '\0';
1335 }
1336
1337 /*
1338  * Like read(2), but if read fails due to non-blocking flag,
1339  * resets flag and restarts read.
1340  */
1341 ssize_t
1342 blocking_read(int fd, char *buf, size_t nbytes)
1343 {
1344         ssize_t ret;
1345         bool tried_reset = false;
1346
1347         while ((ret = read(fd, buf, nbytes)) < 0) {
1348                 if (!tried_reset && errno == EAGAIN) {
1349                         if (reset_nonblock(fd) > 0) {
1350                                 tried_reset = true;
1351                                 continue;
1352                         }
1353                         errno = EAGAIN;
1354                 }
1355                 break;
1356         }
1357         return (ret);
1358 }
1359
1360 /*
1361  * Reset the non-blocking flag on the specified file descriptor.
1362  * Returns -1 if there was an error, 0 if non-blocking wasn't set,
1363  * 1 if it was.
1364  */
1365 int
1366 reset_nonblock(int fd)
1367 {
1368         int flags;
1369
1370         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1371                 return (-1);
1372         if (!(flags & O_NONBLOCK))
1373                 return (0);
1374         flags &= ~O_NONBLOCK;
1375         if (fcntl(fd, F_SETFL, flags) < 0)
1376                 return (-1);
1377         return (1);
1378 }
1379
1380 /* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
1381 char *
1382 ksh_get_wd(void)
1383 {
1384 #ifdef MKSH__NO_PATH_MAX
1385         char *rv, *cp;
1386
1387         if ((cp = get_current_dir_name())) {
1388                 strdupx(rv, cp, ATEMP);
1389                 free_gnu_gcdn(cp);
1390         } else
1391                 rv = NULL;
1392 #else
1393         char *rv;
1394
1395         if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
1396                 afree(rv, ATEMP);
1397                 rv = NULL;
1398         }
1399 #endif
1400
1401         return (rv);
1402 }
1403
1404 #ifndef ELOOP
1405 #define ELOOP           E2BIG
1406 #endif
1407
1408 char *
1409 do_realpath(const char *upath)
1410 {
1411         char *xp, *ip, *tp, *ipath, *ldest = NULL;
1412         XString xs;
1413         size_t pos, len;
1414         int llen;
1415         struct stat sb;
1416 #ifdef MKSH__NO_PATH_MAX
1417         size_t ldestlen = 0;
1418 #define pathlen sb.st_size
1419 #define pathcnd (ldestlen < (pathlen + 1))
1420 #else
1421 #define pathlen PATH_MAX
1422 #define pathcnd (!ldest)
1423 #endif
1424         /* max. recursion depth */
1425         int symlinks = 32;
1426
1427         if (mksh_abspath(upath)) {
1428                 /* upath is an absolute pathname */
1429                 strdupx(ipath, upath, ATEMP);
1430         } else {
1431                 /* upath is a relative pathname, prepend cwd */
1432                 if ((tp = ksh_get_wd()) == NULL || !mksh_abspath(tp))
1433                         return (NULL);
1434                 ipath = shf_smprintf(Tf_sss, tp, "/", upath);
1435                 afree(tp, ATEMP);
1436         }
1437
1438         /* ipath and upath are in memory at the same time -> unchecked */
1439         Xinit(xs, xp, strlen(ip = ipath) + 1, ATEMP);
1440
1441         /* now jump into the deep of the loop */
1442         goto beginning_of_a_pathname;
1443
1444         while (*ip) {
1445                 /* skip slashes in input */
1446                 while (mksh_cdirsep(*ip))
1447                         ++ip;
1448                 if (!*ip)
1449                         break;
1450
1451                 /* get next pathname component from input */
1452                 tp = ip;
1453                 while (*ip && !mksh_cdirsep(*ip))
1454                         ++ip;
1455                 len = ip - tp;
1456
1457                 /* check input for "." and ".." */
1458                 if (tp[0] == '.') {
1459                         if (len == 1)
1460                                 /* just continue with the next one */
1461                                 continue;
1462                         else if (len == 2 && tp[1] == '.') {
1463                                 /* strip off last pathname component */
1464                                 while (xp > Xstring(xs, xp))
1465                                         if (mksh_cdirsep(*--xp))
1466                                                 break;
1467                                 /* then continue with the next one */
1468                                 continue;
1469                         }
1470                 }
1471
1472                 /* store output position away, then append slash to output */
1473                 pos = Xsavepos(xs, xp);
1474                 /* 1 for the '/' and len + 1 for tp and the NUL from below */
1475                 XcheckN(xs, xp, 1 + len + 1);
1476                 Xput(xs, xp, '/');
1477
1478                 /* append next pathname component to output */
1479                 memcpy(xp, tp, len);
1480                 xp += len;
1481                 *xp = '\0';
1482
1483                 /* lstat the current output, see if it's a symlink */
1484                 if (mksh_lstat(Xstring(xs, xp), &sb)) {
1485                         /* lstat failed */
1486                         if (errno == ENOENT) {
1487                                 /* because the pathname does not exist */
1488                                 while (mksh_cdirsep(*ip))
1489                                         /* skip any trailing slashes */
1490                                         ++ip;
1491                                 /* no more components left? */
1492                                 if (!*ip)
1493                                         /* we can still return successfully */
1494                                         break;
1495                                 /* more components left? fall through */
1496                         }
1497                         /* not ENOENT or not at the end of ipath */
1498                         goto notfound;
1499                 }
1500
1501                 /* check if we encountered a symlink? */
1502                 if (S_ISLNK(sb.st_mode)) {
1503 #ifndef MKSH__NO_SYMLINK
1504                         /* reached maximum recursion depth? */
1505                         if (!symlinks--) {
1506                                 /* yep, prevent infinite loops */
1507                                 errno = ELOOP;
1508                                 goto notfound;
1509                         }
1510
1511                         /* get symlink(7) target */
1512                         if (pathcnd) {
1513 #ifdef MKSH__NO_PATH_MAX
1514                                 if (notoktoadd(pathlen, 1)) {
1515                                         errno = ENAMETOOLONG;
1516                                         goto notfound;
1517                                 }
1518 #endif
1519                                 ldest = aresize(ldest, pathlen + 1, ATEMP);
1520                         }
1521                         llen = readlink(Xstring(xs, xp), ldest, pathlen);
1522                         if (llen < 0)
1523                                 /* oops... */
1524                                 goto notfound;
1525                         ldest[llen] = '\0';
1526
1527                         /*
1528                          * restart if symlink target is an absolute path,
1529                          * otherwise continue with currently resolved prefix
1530                          */
1531                         /* append rest of current input path to link target */
1532                         tp = shf_smprintf(Tf_sss, ldest, *ip ? "/" : "", ip);
1533                         afree(ipath, ATEMP);
1534                         ip = ipath = tp;
1535                         if (!mksh_abspath(ldest)) {
1536                                 /* symlink target is a relative path */
1537                                 xp = Xrestpos(xs, xp, pos);
1538                         } else
1539 #endif
1540                           {
1541                                 /* symlink target is an absolute path */
1542                                 xp = Xstring(xs, xp);
1543  beginning_of_a_pathname:
1544                                 /* assert: (ip == ipath)[0] == '/' */
1545                                 /* assert: xp == xs.beg => start of path */
1546
1547                                 /* exactly two leading slashes? (SUSv4 3.266) */
1548                                 /* @komh do NOT use mksh_cdirsep() here */
1549                                 if (ip[1] == '/' && ip[2] != '/') {
1550                                         /* keep them, e.g. for UNC pathnames */
1551                                         Xput(xs, xp, '/');
1552                                 }
1553                         }
1554                 }
1555                 /* otherwise (no symlink) merely go on */
1556         }
1557
1558         /*
1559          * either found the target and successfully resolved it,
1560          * or found its parent directory and may create it
1561          */
1562         if (Xlength(xs, xp) == 0)
1563                 /*
1564                  * if the resolved pathname is "", make it "/",
1565                  * otherwise do not add a trailing slash
1566                  */
1567                 Xput(xs, xp, '/');
1568         Xput(xs, xp, '\0');
1569
1570         /*
1571          * if source path had a trailing slash, check if target path
1572          * is not a non-directory existing file
1573          */
1574         if (ip > ipath && mksh_cdirsep(ip[-1])) {
1575                 if (stat(Xstring(xs, xp), &sb)) {
1576                         if (errno != ENOENT)
1577                                 goto notfound;
1578                 } else if (!S_ISDIR(sb.st_mode)) {
1579                         errno = ENOTDIR;
1580                         goto notfound;
1581                 }
1582                 /* target now either does not exist or is a directory */
1583         }
1584
1585         /* return target path */
1586         afree(ldest, ATEMP);
1587         afree(ipath, ATEMP);
1588         return (Xclose(xs, xp));
1589
1590  notfound:
1591         /* save; freeing memory might trash it */
1592         llen = errno;
1593         afree(ldest, ATEMP);
1594         afree(ipath, ATEMP);
1595         Xfree(xs, xp);
1596         errno = llen;
1597         return (NULL);
1598
1599 #undef pathlen
1600 #undef pathcnd
1601 }
1602
1603 /**
1604  *      Makes a filename into result using the following algorithm.
1605  *      - make result NULL
1606  *      - if file starts with '/', append file to result & set cdpathp to NULL
1607  *      - if file starts with ./ or ../ append cwd and file to result
1608  *        and set cdpathp to NULL
1609  *      - if the first element of cdpathp doesnt start with a '/' xx or '.' xx
1610  *        then cwd is appended to result.
1611  *      - the first element of cdpathp is appended to result
1612  *      - file is appended to result
1613  *      - cdpathp is set to the start of the next element in cdpathp (or NULL
1614  *        if there are no more elements.
1615  *      The return value indicates whether a non-null element from cdpathp
1616  *      was appended to result.
1617  */
1618 static int
1619 make_path(const char *cwd, const char *file,
1620     /* pointer to colon-separated list */
1621     char **cdpathp,
1622     XString *xsp,
1623     int *phys_pathp)
1624 {
1625         int rval = 0;
1626         bool use_cdpath = true;
1627         char *plist;
1628         size_t len, plen = 0;
1629         char *xp = Xstring(*xsp, xp);
1630
1631         if (!file)
1632                 file = null;
1633
1634         if (mksh_abspath(file)) {
1635                 *phys_pathp = 0;
1636                 use_cdpath = false;
1637         } else {
1638                 if (file[0] == '.') {
1639                         char c = file[1];
1640
1641                         if (c == '.')
1642                                 c = file[2];
1643                         if (mksh_cdirsep(c) || c == '\0')
1644                                 use_cdpath = false;
1645                 }
1646
1647                 plist = *cdpathp;
1648                 if (!plist)
1649                         use_cdpath = false;
1650                 else if (use_cdpath) {
1651                         char *pend = plist;
1652
1653                         while (*pend && *pend != MKSH_PATHSEPC)
1654                                 ++pend;
1655                         plen = pend - plist;
1656                         *cdpathp = *pend ? pend + 1 : NULL;
1657                 }
1658
1659                 if ((!use_cdpath || !plen || !mksh_abspath(plist)) &&
1660                     (cwd && *cwd)) {
1661                         len = strlen(cwd);
1662                         XcheckN(*xsp, xp, len);
1663                         memcpy(xp, cwd, len);
1664                         xp += len;
1665                         if (!mksh_cdirsep(cwd[len - 1]))
1666                                 Xput(*xsp, xp, '/');
1667                 }
1668                 *phys_pathp = Xlength(*xsp, xp);
1669                 if (use_cdpath && plen) {
1670                         XcheckN(*xsp, xp, plen);
1671                         memcpy(xp, plist, plen);
1672                         xp += plen;
1673                         if (!mksh_cdirsep(plist[plen - 1]))
1674                                 Xput(*xsp, xp, '/');
1675                         rval = 1;
1676                 }
1677         }
1678
1679         len = strlen(file) + 1;
1680         XcheckN(*xsp, xp, len);
1681         memcpy(xp, file, len);
1682
1683         if (!use_cdpath)
1684                 *cdpathp = NULL;
1685
1686         return (rval);
1687 }
1688
1689 /*-
1690  * Simplify pathnames containing "." and ".." entries.
1691  *
1692  * simplify_path(this)                  = that
1693  * /a/b/c/./../d/..                     /a/b
1694  * //./C/foo/bar/../baz                 //C/foo/baz
1695  * /foo/                                /foo
1696  * /foo/../../bar                       /bar
1697  * /foo/./blah/..                       /foo
1698  * .                                    .
1699  * ..                                   ..
1700  * ./foo                                foo
1701  * foo/../../../bar                     ../../bar
1702  */
1703 void
1704 simplify_path(char *p)
1705 {
1706         char *dp, *ip, *sp, *tp;
1707         size_t len;
1708         bool needslash;
1709
1710         switch (*p) {
1711         case 0:
1712                 return;
1713         case '/':
1714                 /* exactly two leading slashes? (SUSv4 3.266) */
1715                 /* @komh no mksh_cdirsep() here! */
1716                 if (p[1] == '/' && p[2] != '/')
1717                         /* keep them, e.g. for UNC pathnames */
1718                         ++p;
1719 #ifdef __OS2__
1720                 /* FALLTHROUGH */
1721         case '\\':
1722 #endif
1723                 needslash = true;
1724                 break;
1725         default:
1726                 needslash = false;
1727         }
1728         dp = ip = sp = p;
1729
1730         while (*ip) {
1731                 /* skip slashes in input */
1732                 while (mksh_cdirsep(*ip))
1733                         ++ip;
1734                 if (!*ip)
1735                         break;
1736
1737                 /* get next pathname component from input */
1738                 tp = ip;
1739                 while (*ip && !mksh_cdirsep(*ip))
1740                         ++ip;
1741                 len = ip - tp;
1742
1743                 /* check input for "." and ".." */
1744                 if (tp[0] == '.') {
1745                         if (len == 1)
1746                                 /* just continue with the next one */
1747                                 continue;
1748                         else if (len == 2 && tp[1] == '.') {
1749                                 /* parent level, but how? */
1750                                 if (mksh_abspath(p))
1751                                         /* absolute path, only one way */
1752                                         goto strip_last_component;
1753                                 else if (dp > sp) {
1754                                         /* relative path, with subpaths */
1755                                         needslash = false;
1756  strip_last_component:
1757                                         /* strip off last pathname component */
1758                                         while (dp > sp)
1759                                                 if (mksh_cdirsep(*--dp))
1760                                                         break;
1761                                 } else {
1762                                         /* relative path, at its beginning */
1763                                         if (needslash)
1764                                                 /* or already dotdot-slash'd */
1765                                                 *dp++ = '/';
1766                                         /* keep dotdot-slash if not absolute */
1767                                         *dp++ = '.';
1768                                         *dp++ = '.';
1769                                         needslash = true;
1770                                         sp = dp;
1771                                 }
1772                                 /* then continue with the next one */
1773                                 continue;
1774                         }
1775                 }
1776
1777                 if (needslash)
1778                         *dp++ = '/';
1779
1780                 /* append next pathname component to output */
1781                 memmove(dp, tp, len);
1782                 dp += len;
1783
1784                 /* append slash if we continue */
1785                 needslash = true;
1786                 /* try next component */
1787         }
1788         if (dp == p)
1789                 /* empty path -> dot */
1790                 *dp++ = needslash ? '/' : '.';
1791         *dp = '\0';
1792 }
1793
1794 void
1795 set_current_wd(const char *nwd)
1796 {
1797         char *allocd = NULL;
1798
1799         if (nwd == NULL) {
1800                 allocd = ksh_get_wd();
1801                 nwd = allocd ? allocd : null;
1802         }
1803
1804         afree(current_wd, APERM);
1805         strdupx(current_wd, nwd, APERM);
1806
1807         afree(allocd, ATEMP);
1808 }
1809
1810 int
1811 c_cd(const char **wp)
1812 {
1813         int optc, rv, phys_path;
1814         bool physical = tobool(Flag(FPHYSICAL));
1815         /* was a node from cdpath added in? */
1816         int cdnode;
1817         /* show where we went?, error for $PWD */
1818         bool printpath = false, eflag = false;
1819         struct tbl *pwd_s, *oldpwd_s;
1820         XString xs;
1821         char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
1822
1823         while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
1824                 switch (optc) {
1825                 case 'e':
1826                         eflag = true;
1827                         break;
1828                 case 'L':
1829                         physical = false;
1830                         break;
1831                 case 'P':
1832                         physical = true;
1833                         break;
1834                 case '?':
1835                         return (2);
1836                 }
1837         wp += builtin_opt.optind;
1838
1839         if (Flag(FRESTRICTED)) {
1840                 bi_errorf(Tcant_cd);
1841                 return (2);
1842         }
1843
1844         pwd_s = global(TPWD);
1845         oldpwd_s = global(TOLDPWD);
1846
1847         if (!wp[0]) {
1848                 /* No arguments - go home */
1849                 if ((dir = str_val(global("HOME"))) == null) {
1850                         bi_errorf("no home directory (HOME not set)");
1851                         return (2);
1852                 }
1853         } else if (!wp[1]) {
1854                 /* One argument: - or dir */
1855                 strdupx(allocd, wp[0], ATEMP);
1856                 if (ksh_isdash((dir = allocd))) {
1857                         afree(allocd, ATEMP);
1858                         allocd = NULL;
1859                         dir = str_val(oldpwd_s);
1860                         if (dir == null) {
1861                                 bi_errorf(Tno_OLDPWD);
1862                                 return (2);
1863                         }
1864                         printpath = true;
1865                 }
1866         } else if (!wp[2]) {
1867                 /* Two arguments - substitute arg1 in PWD for arg2 */
1868                 size_t ilen, olen, nlen, elen;
1869                 char *cp;
1870
1871                 if (!current_wd[0]) {
1872                         bi_errorf("can't determine current directory");
1873                         return (2);
1874                 }
1875                 /*
1876                  * substitute arg1 for arg2 in current path.
1877                  * if the first substitution fails because the cd fails
1878                  * we could try to find another substitution. For now
1879                  * we don't
1880                  */
1881                 if ((cp = strstr(current_wd, wp[0])) == NULL) {
1882                         bi_errorf(Tbadsubst);
1883                         return (2);
1884                 }
1885                 /*-
1886                  * ilen = part of current_wd before wp[0]
1887                  * elen = part of current_wd after wp[0]
1888                  * because current_wd and wp[1] need to be in memory at the
1889                  * same time beforehand the addition can stay unchecked
1890                  */
1891                 ilen = cp - current_wd;
1892                 olen = strlen(wp[0]);
1893                 nlen = strlen(wp[1]);
1894                 elen = strlen(current_wd + ilen + olen) + 1;
1895                 dir = allocd = alloc(ilen + nlen + elen, ATEMP);
1896                 memcpy(dir, current_wd, ilen);
1897                 memcpy(dir + ilen, wp[1], nlen);
1898                 memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
1899                 printpath = true;
1900         } else {
1901                 bi_errorf(Ttoo_many_args);
1902                 return (2);
1903         }
1904
1905 #ifdef MKSH__NO_PATH_MAX
1906         /* only a first guess; make_path will enlarge xs if necessary */
1907         XinitN(xs, 1024, ATEMP);
1908 #else
1909         XinitN(xs, PATH_MAX, ATEMP);
1910 #endif
1911
1912         cdpath = str_val(global("CDPATH"));
1913         do {
1914                 cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
1915                 if (physical)
1916                         rv = chdir(tryp = Xstring(xs, xp) + phys_path);
1917                 else {
1918                         simplify_path(Xstring(xs, xp));
1919                         rv = chdir(tryp = Xstring(xs, xp));
1920                 }
1921         } while (rv < 0 && cdpath != NULL);
1922
1923         if (rv < 0) {
1924                 if (cdnode)
1925                         bi_errorf(Tf_sD_s, dir, "bad directory");
1926                 else
1927                         bi_errorf(Tf_sD_s, tryp, cstrerror(errno));
1928                 afree(allocd, ATEMP);
1929                 Xfree(xs, xp);
1930                 return (2);
1931         }
1932
1933         rv = 0;
1934
1935         /* allocd (above) => dir, which is no longer used */
1936         afree(allocd, ATEMP);
1937         allocd = NULL;
1938
1939         /* Clear out tracked aliases with relative paths */
1940         flushcom(false);
1941
1942         /*
1943          * Set OLDPWD (note: unsetting OLDPWD does not disable this
1944          * setting in AT&T ksh)
1945          */
1946         if (current_wd[0])
1947                 /* Ignore failure (happens if readonly or integer) */
1948                 setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
1949
1950         if (!mksh_abspath(Xstring(xs, xp))) {
1951                 pwd = NULL;
1952         } else if (!physical) {
1953                 goto norealpath_PWD;
1954         } else if ((pwd = allocd = do_realpath(Xstring(xs, xp))) == NULL) {
1955                 if (eflag)
1956                         rv = 1;
1957  norealpath_PWD:
1958                 pwd = Xstring(xs, xp);
1959         }
1960
1961         /* Set PWD */
1962         if (pwd) {
1963                 char *ptmp = pwd;
1964
1965                 set_current_wd(ptmp);
1966                 /* Ignore failure (happens if readonly or integer) */
1967                 setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
1968         } else {
1969                 set_current_wd(null);
1970                 pwd = Xstring(xs, xp);
1971                 /* XXX unset $PWD? */
1972                 if (eflag)
1973                         rv = 1;
1974         }
1975         if (printpath || cdnode)
1976                 shprintf(Tf_sN, pwd);
1977
1978         afree(allocd, ATEMP);
1979         Xfree(xs, xp);
1980         return (rv);
1981 }
1982
1983
1984 #ifdef KSH_CHVT_CODE
1985 extern void chvt_reinit(void);
1986
1987 static void
1988 chvt(const Getopt *go)
1989 {
1990         const char *dv = go->optarg;
1991         char *cp = NULL;
1992         int fd;
1993
1994         switch (*dv) {
1995         case '-':
1996                 dv = "/dev/null";
1997                 break;
1998         case '!':
1999                 ++dv;
2000                 /* FALLTHROUGH */
2001         default: {
2002                 struct stat sb;
2003
2004                 if (stat(dv, &sb)) {
2005                         cp = shf_smprintf("/dev/ttyC%s", dv);
2006                         dv = cp;
2007                         if (stat(dv, &sb)) {
2008                                 memmove(cp + 1, cp, /* /dev/tty */ 8);
2009                                 dv = cp + 1;
2010                                 if (stat(dv, &sb)) {
2011                                         errorf(Tf_sD_sD_s, "chvt",
2012                                             "can't find tty", go->optarg);
2013                                 }
2014                         }
2015                 }
2016                 if (!(sb.st_mode & S_IFCHR))
2017                         errorf(Tf_sD_sD_s, "chvt", "not a char device", dv);
2018 #ifndef MKSH_DISABLE_REVOKE_WARNING
2019 #if HAVE_REVOKE
2020                 if (revoke(dv))
2021 #endif
2022                         warningf(false, Tf_sD_s_s, "chvt",
2023                             "new shell is potentially insecure, can't revoke",
2024                             dv);
2025 #endif
2026             }
2027         }
2028         if ((fd = binopen2(dv, O_RDWR)) < 0) {
2029                 sleep(1);
2030                 if ((fd = binopen2(dv, O_RDWR)) < 0) {
2031                         errorf(Tf_sD_s_s, "chvt", Tcant_open, dv);
2032                 }
2033         }
2034         if (go->optarg[0] != '!') {
2035                 switch (fork()) {
2036                 case -1:
2037                         errorf(Tf_sD_s_s, "chvt", "fork", "failed");
2038                 case 0:
2039                         break;
2040                 default:
2041                         exit(0);
2042                 }
2043         }
2044         if (setsid() == -1)
2045                 errorf(Tf_sD_s_s, "chvt", "setsid", "failed");
2046         if (go->optarg[0] != '-') {
2047                 if (ioctl(fd, TIOCSCTTY, NULL) == -1)
2048                         errorf(Tf_sD_s_s, "chvt", "TIOCSCTTY", "failed");
2049                 if (tcflush(fd, TCIOFLUSH))
2050                         errorf(Tf_sD_s_s, "chvt", "TCIOFLUSH", "failed");
2051         }
2052         ksh_dup2(fd, 0, false);
2053         ksh_dup2(fd, 1, false);
2054         ksh_dup2(fd, 2, false);
2055         if (fd > 2)
2056                 close(fd);
2057         rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
2058         chvt_reinit();
2059 }
2060 #endif
2061
2062 #ifdef DEBUG
2063 char *
2064 strchr(char *p, int ch)
2065 {
2066         for (;; ++p) {
2067                 if (*p == ch)
2068                         return (p);
2069                 if (!*p)
2070                         return (NULL);
2071         }
2072         /* NOTREACHED */
2073 }
2074
2075 char *
2076 strstr(char *b, const char *l)
2077 {
2078         char first, c;
2079         size_t n;
2080
2081         if ((first = *l++) == '\0')
2082                 return (b);
2083         n = strlen(l);
2084  strstr_look:
2085         while ((c = *b++) != first)
2086                 if (c == '\0')
2087                         return (NULL);
2088         if (strncmp(b, l, n))
2089                 goto strstr_look;
2090         return (b - 1);
2091 }
2092 #endif
2093
2094 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
2095 char *
2096 strndup_i(const char *src, size_t len, Area *ap)
2097 {
2098         char *dst = NULL;
2099
2100         if (src != NULL) {
2101                 dst = alloc(len + 1, ap);
2102                 memcpy(dst, src, len);
2103                 dst[len] = '\0';
2104         }
2105         return (dst);
2106 }
2107
2108 char *
2109 strdup_i(const char *src, Area *ap)
2110 {
2111         return (src == NULL ? NULL : strndup_i(src, strlen(src), ap));
2112 }
2113 #endif
2114
2115 #if !HAVE_GETRUSAGE
2116 #define INVTCK(r,t)     do {                                            \
2117         r.tv_usec = ((t) % (1000000 / CLK_TCK)) * (1000000 / CLK_TCK);  \
2118         r.tv_sec = (t) / CLK_TCK;                                       \
2119 } while (/* CONSTCOND */ 0)
2120
2121 int
2122 getrusage(int what, struct rusage *ru)
2123 {
2124         struct tms tms;
2125         clock_t u, s;
2126
2127         if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
2128                 return (-1);
2129
2130         switch (what) {
2131         case RUSAGE_SELF:
2132                 u = tms.tms_utime;
2133                 s = tms.tms_stime;
2134                 break;
2135         case RUSAGE_CHILDREN:
2136                 u = tms.tms_cutime;
2137                 s = tms.tms_cstime;
2138                 break;
2139         default:
2140                 errno = EINVAL;
2141                 return (-1);
2142         }
2143         INVTCK(ru->ru_utime, u);
2144         INVTCK(ru->ru_stime, s);
2145         return (0);
2146 }
2147 #endif
2148
2149 /*
2150  * process the string available via fg (get a char)
2151  * and fp (put back a char) for backslash escapes,
2152  * assuming the first call to *fg gets the char di-
2153  * rectly after the backslash; return the character
2154  * (0..0xFF), Unicode (wc + 0x100), or -1 if no known
2155  * escape sequence was found
2156  */
2157 int
2158 unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
2159 {
2160         int wc, i, c, fc;
2161
2162         fc = (*fg)();
2163         switch (fc) {
2164         case 'a':
2165                 /*
2166                  * according to the comments in pdksh, \007 seems
2167                  * to be more portable than \a (due to HP-UX cc,
2168                  * Ultrix cc, old pcc, etc.) so we avoid the escape
2169                  * sequence altogether in mksh and assume ASCII
2170                  */
2171                 wc = 7;
2172                 break;
2173         case 'b':
2174                 wc = '\b';
2175                 break;
2176         case 'c':
2177                 if (!cstyle)
2178                         goto unknown_escape;
2179                 c = (*fg)();
2180                 wc = CTRL(c);
2181                 break;
2182         case 'E':
2183         case 'e':
2184                 wc = 033;
2185                 break;
2186         case 'f':
2187                 wc = '\f';
2188                 break;
2189         case 'n':
2190                 wc = '\n';
2191                 break;
2192         case 'r':
2193                 wc = '\r';
2194                 break;
2195         case 't':
2196                 wc = '\t';
2197                 break;
2198         case 'v':
2199                 /* assume ASCII here as well */
2200                 wc = 11;
2201                 break;
2202         case '1':
2203         case '2':
2204         case '3':
2205         case '4':
2206         case '5':
2207         case '6':
2208         case '7':
2209                 if (!cstyle)
2210                         goto unknown_escape;
2211                 /* FALLTHROUGH */
2212         case '0':
2213                 if (cstyle)
2214                         (*fp)(fc);
2215                 /*
2216                  * look for an octal number with up to three
2217                  * digits, not counting the leading zero;
2218                  * convert it to a raw octet
2219                  */
2220                 wc = 0;
2221                 i = 3;
2222                 while (i--)
2223                         if ((c = (*fg)()) >= ord('0') && c <= ord('7'))
2224                                 wc = (wc << 3) + ksh_numdig(c);
2225                         else {
2226                                 (*fp)(c);
2227                                 break;
2228                         }
2229                 break;
2230         case 'U':
2231                 i = 8;
2232                 if (/* CONSTCOND */ 0)
2233                         /* FALLTHROUGH */
2234         case 'u':
2235                   i = 4;
2236                 if (/* CONSTCOND */ 0)
2237                         /* FALLTHROUGH */
2238         case 'x':
2239                   i = cstyle ? -1 : 2;
2240                 /**
2241                  * x:   look for a hexadecimal number with up to
2242                  *      two (C style: arbitrary) digits; convert
2243                  *      to raw octet (C style: Unicode if >0xFF)
2244                  * u/U: look for a hexadecimal number with up to
2245                  *      four (U: eight) digits; convert to Unicode
2246                  */
2247                 wc = 0;
2248                 while (i--) {
2249                         wc <<= 4;
2250                         if ((c = (*fg)()) >= ord('0') && c <= ord('9'))
2251                                 wc += ksh_numdig(c);
2252                         else if (c >= ord('A') && c <= ord('F'))
2253                                 wc += ksh_numuc(c) + 10;
2254                         else if (c >= ord('a') && c <= ord('f'))
2255                                 wc += ksh_numlc(c) + 10;
2256                         else {
2257                                 wc >>= 4;
2258                                 (*fp)(c);
2259                                 break;
2260                         }
2261                 }
2262                 if ((cstyle && wc > 0xFF) || fc != 'x')
2263                         /* Unicode marker */
2264                         wc += 0x100;
2265                 break;
2266         case '\'':
2267                 if (!cstyle)
2268                         goto unknown_escape;
2269                 wc = '\'';
2270                 break;
2271         case '\\':
2272                 wc = '\\';
2273                 break;
2274         default:
2275  unknown_escape:
2276                 (*fp)(fc);
2277                 return (-1);
2278         }
2279
2280         return (wc);
2281 }