OSDN Git Service

499b9619d58062145fe28e5215a44a2922885d3f
[android-x86/external-mksh.git] / src / expr.c
1 /*      $OpenBSD: expr.c,v 1.24 2014/12/08 14:26:31 otto Exp $  */
2
3 /*-
4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
5  *               2011, 2012, 2013, 2014, 2016, 2017, 2018
6  *      mirabilos <m@mirbsd.org>
7  *
8  * Provided that these terms and disclaimer and all copyright notices
9  * are retained or reproduced in an accompanying document, permission
10  * is granted to deal in this work without restriction, including un-
11  * limited rights to use, publicly perform, distribute, sell, modify,
12  * merge, give away, or sublicence.
13  *
14  * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
15  * the utmost extent permitted by applicable law, neither express nor
16  * implied; without malicious intent or gross negligence. In no event
17  * may a licensor, author or contributor be held liable for indirect,
18  * direct, other damage, loss, or other issues arising in any way out
19  * of dealing in the work, even if advised of the possibility of such
20  * damage or existence of a defect, except proven that it results out
21  * of said person's immediate fault when using the work as intended.
22  */
23
24 #include "sh.h"
25
26 __RCSID("$MirOS: src/bin/mksh/expr.c,v 1.103 2018/01/14 01:29:47 tg Exp $");
27
28 #define EXPRTOK_DEFNS
29 #include "exprtok.h"
30
31 /* precisions; used to be enum prec but we do arithmetics on it */
32 #define P_PRIMARY       0       /* VAR, LIT, (), ! ~ ++ -- */
33 #define P_MULT          1       /* * / % */
34 #define P_ADD           2       /* + - */
35 #define P_SHIFT         3       /* ^< ^> << >> */
36 #define P_RELATION      4       /* < <= > >= */
37 #define P_EQUALITY      5       /* == != */
38 #define P_BAND          6       /* & */
39 #define P_BXOR          7       /* ^ */
40 #define P_BOR           8       /* | */
41 #define P_LAND          9       /* && */
42 #define P_LOR           10      /* || */
43 #define P_TERN          11      /* ?: */
44         /* = += -= *= /= %= ^<= ^>= <<= >>= &= ^= |= */
45 #define P_ASSIGN        12
46 #define P_COMMA         13      /* , */
47 #define MAX_PREC        P_COMMA
48
49 enum token {
50 #define EXPRTOK_ENUM
51 #include "exprtok.h"
52 };
53
54 static const char opname[][4] = {
55 #define EXPRTOK_NAME
56 #include "exprtok.h"
57 };
58
59 static const uint8_t oplen[] = {
60 #define EXPRTOK_LEN
61 #include "exprtok.h"
62 };
63
64 static const uint8_t opprec[] = {
65 #define EXPRTOK_PREC
66 #include "exprtok.h"
67 };
68
69 typedef struct expr_state {
70         /* expression being evaluated */
71         const char *expression;
72         /* lexical position */
73         const char *tokp;
74         /* value from token() */
75         struct tbl *val;
76         /* variable that is being recursively expanded (EXPRINEVAL flag set) */
77         struct tbl *evaling;
78         /* token from token() */
79         enum token tok;
80         /* don't do assignments (for ?:, &&, ||) */
81         uint8_t noassign;
82         /* evaluating an $(()) expression? */
83         bool arith;
84         /* unsigned arithmetic calculation */
85         bool natural;
86 } Expr_state;
87
88 enum error_type {
89         ET_UNEXPECTED, ET_BADLIT, ET_RECURSIVE,
90         ET_LVALUE, ET_RDONLY, ET_STR
91 };
92
93 static void evalerr(Expr_state *, enum error_type, const char *)
94     MKSH_A_NORETURN;
95 static struct tbl *evalexpr(Expr_state *, unsigned int);
96 static void exprtoken(Expr_state *);
97 static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, bool);
98 static void assign_check(Expr_state *, enum token, struct tbl *);
99 static struct tbl *intvar(Expr_state *, struct tbl *);
100
101 /*
102  * parse and evaluate expression
103  */
104 int
105 evaluate(const char *expr, mksh_ari_t *rval, int error_ok, bool arith)
106 {
107         struct tbl v;
108         int ret;
109
110         v.flag = DEFINED | INTEGER;
111         v.type = 0;
112         ret = v_evaluate(&v, expr, error_ok, arith);
113         *rval = v.val.i;
114         return (ret);
115 }
116
117 /*
118  * parse and evaluate expression, storing result in vp.
119  */
120 int
121 v_evaluate(struct tbl *vp, const char *expr, volatile int error_ok,
122     bool arith)
123 {
124         struct tbl *v;
125         Expr_state curstate;
126         Expr_state * const es = &curstate;
127         int i;
128
129         /* save state to allow recursive calls */
130         memset(&curstate, 0, sizeof(curstate));
131         curstate.expression = curstate.tokp = expr;
132         curstate.tok = BAD;
133         curstate.arith = arith;
134
135         newenv(E_ERRH);
136         if ((i = kshsetjmp(e->jbuf))) {
137                 /* Clear EXPRINEVAL in of any variables we were playing with */
138                 if (curstate.evaling)
139                         curstate.evaling->flag &= ~EXPRINEVAL;
140                 quitenv(NULL);
141                 if (i == LAEXPR) {
142                         if (error_ok == KSH_RETURN_ERROR)
143                                 return (0);
144                         errorfz();
145                 }
146                 unwind(i);
147                 /* NOTREACHED */
148         }
149
150         exprtoken(es);
151         if (es->tok == END) {
152                 es->tok = LIT;
153                 es->val = tempvar("");
154         }
155         v = intvar(es, evalexpr(es, MAX_PREC));
156
157         if (es->tok != END)
158                 evalerr(es, ET_UNEXPECTED, NULL);
159
160         if (es->arith && es->natural)
161                 vp->flag |= INT_U;
162         if (vp->flag & INTEGER)
163                 setint_v(vp, v, es->arith);
164         else
165                 /* can fail if readonly */
166                 setstr(vp, str_val(v), error_ok);
167
168         quitenv(NULL);
169
170         return (1);
171 }
172
173 static void
174 evalerr(Expr_state *es, enum error_type type, const char *str)
175 {
176         char tbuf[2];
177         const char *s;
178
179         es->arith = false;
180         switch (type) {
181         case ET_UNEXPECTED:
182                 switch (es->tok) {
183                 case VAR:
184                         s = es->val->name;
185                         break;
186                 case LIT:
187                         s = str_val(es->val);
188                         break;
189                 case END:
190                         s = "end of expression";
191                         break;
192                 case BAD:
193                         tbuf[0] = *es->tokp;
194                         tbuf[1] = '\0';
195                         s = tbuf;
196                         break;
197                 default:
198                         s = opname[(int)es->tok];
199                 }
200                 warningf(true, Tf_sD_s_qs, es->expression,
201                     Tunexpected, s);
202                 break;
203
204         case ET_BADLIT:
205                 warningf(true, Tf_sD_s_qs, es->expression,
206                     Tbadnum, str);
207                 break;
208
209         case ET_RECURSIVE:
210                 warningf(true, Tf_sD_s_qs, es->expression,
211                     "expression recurses on parameter", str);
212                 break;
213
214         case ET_LVALUE:
215                 warningf(true, Tf_sD_s_s,
216                     es->expression, str, "requires lvalue");
217                 break;
218
219         case ET_RDONLY:
220                 warningf(true, Tf_sD_s_s,
221                     es->expression, str, "applied to read-only variable");
222                 break;
223
224         default: /* keep gcc happy */
225         case ET_STR:
226                 warningf(true, Tf_sD_s, es->expression, str);
227                 break;
228         }
229         unwind(LAEXPR);
230 }
231
232 /* do a ++ or -- operation */
233 static struct tbl *
234 do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, bool is_prefix)
235 {
236         struct tbl *vl;
237         mksh_uari_t oval;
238
239         assign_check(es, op, vasn);
240
241         vl = intvar(es, vasn);
242         oval = vl->val.u;
243         if (op == O_PLUSPLUS)
244                 ++vl->val.u;
245         else
246                 --vl->val.u;
247         if (!es->noassign) {
248                 if (vasn->flag & INTEGER)
249                         setint_v(vasn, vl, es->arith);
250                 else
251                         setint(vasn, vl->val.i);
252         }
253         if (!is_prefix)
254                 /* undo the increment/decrement */
255                 vl->val.u = oval;
256
257         return (vl);
258 }
259
260 static struct tbl *
261 evalexpr(Expr_state *es, unsigned int prec)
262 {
263         struct tbl *vl, *vr = NULL, *vasn;
264         enum token op;
265         mksh_uari_t res = 0, t1, t2, t3;
266
267         if (prec == P_PRIMARY) {
268                 switch ((int)(op = es->tok)) {
269                 case O_BNOT:
270                 case O_LNOT:
271                 case O_MINUS:
272                 case O_PLUS:
273                         exprtoken(es);
274                         vl = intvar(es, evalexpr(es, P_PRIMARY));
275                         switch ((int)op) {
276                         case O_BNOT:
277                                 vl->val.u = ~vl->val.u;
278                                 break;
279                         case O_LNOT:
280                                 vl->val.u = !vl->val.u;
281                                 break;
282                         case O_MINUS:
283                                 vl->val.u = -vl->val.u;
284                                 break;
285                         case O_PLUS:
286                                 /* nop */
287                                 break;
288                         }
289                         break;
290
291                 case OPEN_PAREN:
292                         exprtoken(es);
293                         vl = evalexpr(es, MAX_PREC);
294                         if (es->tok != CLOSE_PAREN)
295                                 evalerr(es, ET_STR, "missing )");
296                         exprtoken(es);
297                         break;
298
299                 case O_PLUSPLUS:
300                 case O_MINUSMINUS:
301                         exprtoken(es);
302                         vl = do_ppmm(es, op, es->val, true);
303                         exprtoken(es);
304                         break;
305
306                 case VAR:
307                 case LIT:
308                         vl = es->val;
309                         exprtoken(es);
310                         break;
311
312                 default:
313                         evalerr(es, ET_UNEXPECTED, NULL);
314                         /* NOTREACHED */
315                 }
316
317                 if (es->tok == O_PLUSPLUS || es->tok == O_MINUSMINUS) {
318                         vl = do_ppmm(es, es->tok, vl, false);
319                         exprtoken(es);
320                 }
321
322                 return (vl);
323                 /* prec == P_PRIMARY */
324         }
325
326         vl = evalexpr(es, prec - 1);
327         while ((int)(op = es->tok) >= (int)O_EQ && (int)op <= (int)O_COMMA &&
328             opprec[(int)op] == prec) {
329                 switch ((int)op) {
330                 case O_TERN:
331                 case O_LAND:
332                 case O_LOR:
333                         break;
334                 default:
335                         exprtoken(es);
336                 }
337
338                 vasn = vl;
339                 if (op != O_ASN)
340                         /* vl may not have a value yet */
341                         vl = intvar(es, vl);
342                 if (IS_ASSIGNOP(op)) {
343                         if (!es->noassign)
344                                 assign_check(es, op, vasn);
345                         vr = intvar(es, evalexpr(es, P_ASSIGN));
346                 } else if (op == O_TERN) {
347                         bool ev = vl->val.u != 0;
348
349                         if (!ev)
350                                 es->noassign++;
351                         exprtoken(es);
352                         vl = evalexpr(es, MAX_PREC);
353                         if (!ev)
354                                 es->noassign--;
355                         if (es->tok != CTERN)
356                                 evalerr(es, ET_STR, "missing :");
357                         if (ev)
358                                 es->noassign++;
359                         exprtoken(es);
360                         vr = evalexpr(es, P_TERN);
361                         if (ev)
362                                 es->noassign--;
363                         vl = ev ? vl : vr;
364                         continue;
365                 } else if (op != O_LAND && op != O_LOR)
366                         vr = intvar(es, evalexpr(es, prec - 1));
367
368                 /* common ops setup */
369                 switch ((int)op) {
370                 case O_DIV:
371                 case O_DIVASN:
372                 case O_MOD:
373                 case O_MODASN:
374                         if (vr->val.u == 0) {
375                                 if (!es->noassign)
376                                         evalerr(es, ET_STR, "zero divisor");
377                                 vr->val.u = 1;
378                         }
379                         /* calculate the absolute values */
380                         t1 = vl->val.i < 0 ? -vl->val.u : vl->val.u;
381                         t2 = vr->val.i < 0 ? -vr->val.u : vr->val.u;
382                         break;
383 #ifndef MKSH_LEGACY_MODE
384                 case O_LSHIFT:
385                 case O_LSHIFTASN:
386                 case O_RSHIFT:
387                 case O_RSHIFTASN:
388                 case O_ROL:
389                 case O_ROLASN:
390                 case O_ROR:
391                 case O_RORASN:
392                         t1 = vl->val.u;
393                         t2 = vr->val.u & 31;
394                         break;
395 #endif
396                 case O_LAND:
397                 case O_LOR:
398                         t1 = vl->val.u;
399                         t2 = 0; /* gcc */
400                         break;
401                 default:
402                         t1 = vl->val.u;
403                         t2 = vr->val.u;
404                         break;
405                 }
406
407 #define cmpop(op)       (es->natural ?                  \
408         (mksh_uari_t)(vl->val.u op vr->val.u) :         \
409         (mksh_uari_t)(vl->val.i op vr->val.i)           \
410 )
411
412                 /* op calculation */
413                 switch ((int)op) {
414                 case O_TIMES:
415                 case O_TIMESASN:
416                         res = t1 * t2;
417                         break;
418                 case O_MOD:
419                 case O_MODASN:
420                         if (es->natural) {
421                                 res = vl->val.u % vr->val.u;
422                                 break;
423                         }
424                         goto signed_division;
425                 case O_DIV:
426                 case O_DIVASN:
427                         if (es->natural) {
428                                 res = vl->val.u / vr->val.u;
429                                 break;
430                         }
431  signed_division:
432                         /*
433                          * a / b = abs(a) / abs(b) * sgn((u)a^(u)b)
434                          */
435                         t3 = t1 / t2;
436 #ifndef MKSH_LEGACY_MODE
437                         res = ((vl->val.u ^ vr->val.u) & 0x80000000) ? -t3 : t3;
438 #else
439                         res = ((t1 == vl->val.u ? 0 : 1) ^
440                             (t2 == vr->val.u ? 0 : 1)) ? -t3 : t3;
441 #endif
442                         if (op == O_MOD || op == O_MODASN) {
443                                 /*
444                                  * primitive modulo, to get the sign of
445                                  * the result correct:
446                                  * (a % b) = a - ((a / b) * b)
447                                  * the subtraction and multiplication
448                                  * are, amazingly enough, sign ignorant
449                                  */
450                                 res = vl->val.u - (res * vr->val.u);
451                         }
452                         break;
453                 case O_PLUS:
454                 case O_PLUSASN:
455                         res = t1 + t2;
456                         break;
457                 case O_MINUS:
458                 case O_MINUSASN:
459                         res = t1 - t2;
460                         break;
461 #ifndef MKSH_LEGACY_MODE
462                 case O_ROL:
463                 case O_ROLASN:
464                         res = (t1 << t2) | (t1 >> (32 - t2));
465                         break;
466                 case O_ROR:
467                 case O_RORASN:
468                         res = (t1 >> t2) | (t1 << (32 - t2));
469                         break;
470 #endif
471                 case O_LSHIFT:
472                 case O_LSHIFTASN:
473                         res = t1 << t2;
474                         break;
475                 case O_RSHIFT:
476                 case O_RSHIFTASN:
477                         res = es->natural || vl->val.i >= 0 ?
478                             t1 >> t2 :
479                             ~(~t1 >> t2);
480                         break;
481                 case O_LT:
482                         res = cmpop(<);
483                         break;
484                 case O_LE:
485                         res = cmpop(<=);
486                         break;
487                 case O_GT:
488                         res = cmpop(>);
489                         break;
490                 case O_GE:
491                         res = cmpop(>=);
492                         break;
493                 case O_EQ:
494                         res = t1 == t2;
495                         break;
496                 case O_NE:
497                         res = t1 != t2;
498                         break;
499                 case O_BAND:
500                 case O_BANDASN:
501                         res = t1 & t2;
502                         break;
503                 case O_BXOR:
504                 case O_BXORASN:
505                         res = t1 ^ t2;
506                         break;
507                 case O_BOR:
508                 case O_BORASN:
509                         res = t1 | t2;
510                         break;
511                 case O_LAND:
512                         if (!t1)
513                                 es->noassign++;
514                         exprtoken(es);
515                         vr = intvar(es, evalexpr(es, prec - 1));
516                         res = t1 && vr->val.u;
517                         if (!t1)
518                                 es->noassign--;
519                         break;
520                 case O_LOR:
521                         if (t1)
522                                 es->noassign++;
523                         exprtoken(es);
524                         vr = intvar(es, evalexpr(es, prec - 1));
525                         res = t1 || vr->val.u;
526                         if (t1)
527                                 es->noassign--;
528                         break;
529                 case O_ASN:
530                 case O_COMMA:
531                         res = t2;
532                         break;
533                 }
534
535 #undef cmpop
536
537                 if (IS_ASSIGNOP(op)) {
538                         vr->val.u = res;
539                         if (!es->noassign) {
540                                 if (vasn->flag & INTEGER)
541                                         setint_v(vasn, vr, es->arith);
542                                 else
543                                         setint(vasn, vr->val.i);
544                         }
545                         vl = vr;
546                 } else
547                         vl->val.u = res;
548         }
549         return (vl);
550 }
551
552 static void
553 exprtoken(Expr_state *es)
554 {
555         const char *cp = es->tokp;
556         int c;
557         char *tvar;
558
559         /* skip whitespace */
560  skip_spaces:
561         --cp;
562         do {
563                 c = ord(*++cp);
564         } while (ctype(c, C_SPACE));
565         if (es->tokp == es->expression && (unsigned int)c == ORD('#')) {
566                 /* expression begins with # */
567                 /* switch to unsigned */
568                 es->natural = true;
569                 ++cp;
570                 goto skip_spaces;
571         }
572         es->tokp = cp;
573
574         if (c == '\0')
575                 es->tok = END;
576         else if (ctype(c, C_ALPHX)) {
577                 do {
578                         c = ord(*++cp);
579                 } while (ctype(c, C_ALNUX));
580                 if ((unsigned int)c == ORD('[')) {
581                         size_t len;
582
583                         len = array_ref_len(cp);
584                         if (len == 0)
585                                 evalerr(es, ET_STR, "missing ]");
586                         cp += len;
587                 }
588                 if (es->noassign) {
589                         es->val = tempvar("");
590                         es->val->flag |= EXPRLVALUE;
591                 } else {
592                         strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
593                         es->val = global(tvar);
594                         afree(tvar, ATEMP);
595                 }
596                 es->tok = VAR;
597         } else if (c == '1' && cp[1] == '#') {
598                 cp += 2;
599                 if (*cp)
600                         cp += utf_ptradj(cp);
601                 strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
602                 goto process_tvar;
603 #ifndef MKSH_SMALL
604         } else if (c == '\'') {
605                 if (*++cp == '\0') {
606                         es->tok = END;
607                         evalerr(es, ET_UNEXPECTED, NULL);
608                 }
609                 cp += utf_ptradj(cp);
610                 if (*cp++ != '\'')
611                         evalerr(es, ET_STR,
612                             "multi-character character constant");
613                 /* 'x' -> 1#x (x = one multibyte character) */
614                 c = cp - es->tokp;
615                 tvar = alloc(c + /* NUL */ 1, ATEMP);
616                 tvar[0] = '1';
617                 tvar[1] = '#';
618                 memcpy(tvar + 2, es->tokp + 1, c - 2);
619                 tvar[c] = '\0';
620                 goto process_tvar;
621 #endif
622         } else if (ctype(c, C_DIGIT)) {
623                 while (ctype(c, C_ALNUM | C_HASH))
624                         c = ord(*cp++);
625                 strndupx(tvar, es->tokp, --cp - es->tokp, ATEMP);
626  process_tvar:
627                 es->val = tempvar("");
628                 es->val->flag &= ~INTEGER;
629                 es->val->type = 0;
630                 es->val->val.s = tvar;
631                 if (setint_v(es->val, es->val, es->arith) == NULL)
632                         evalerr(es, ET_BADLIT, tvar);
633                 afree(tvar, ATEMP);
634                 es->tok = LIT;
635         } else {
636                 int i, n0;
637
638                 for (i = 0; (n0 = ord(opname[i][0])); i++)
639                         if (c == n0 && strncmp(cp, opname[i],
640                             (size_t)oplen[i]) == 0) {
641                                 es->tok = (enum token)i;
642                                 cp += oplen[i];
643                                 break;
644                         }
645                 if (!n0)
646                         es->tok = BAD;
647         }
648         es->tokp = cp;
649 }
650
651 static void
652 assign_check(Expr_state *es, enum token op, struct tbl *vasn)
653 {
654         if (es->tok == END || !vasn ||
655             (vasn->name[0] == '\0' && !(vasn->flag & EXPRLVALUE)))
656                 evalerr(es, ET_LVALUE, opname[(int)op]);
657         else if (vasn->flag & RDONLY)
658                 evalerr(es, ET_RDONLY, opname[(int)op]);
659 }
660
661 struct tbl *
662 tempvar(const char *vname)
663 {
664         struct tbl *vp;
665         size_t vsize;
666
667         vsize = strlen(vname) + 1;
668         vp = alloc(offsetof(struct tbl, name[0]) + vsize, ATEMP);
669         memcpy(vp->name, vname, vsize);
670         vp->flag = ISSET|INTEGER;
671         vp->type = 0;
672         vp->areap = ATEMP;
673         vp->ua.hval = 0;
674         vp->val.i = 0;
675         return (vp);
676 }
677
678 /* cast (string) variable to temporary integer variable */
679 static struct tbl *
680 intvar(Expr_state *es, struct tbl *vp)
681 {
682         struct tbl *vq;
683
684         /* try to avoid replacing a temp var with another temp var */
685         if (vp->name[0] == '\0' &&
686             (vp->flag & (ISSET|INTEGER|EXPRLVALUE)) == (ISSET|INTEGER))
687                 return (vp);
688
689         vq = tempvar("");
690         if (setint_v(vq, vp, es->arith) == NULL) {
691                 if (vp->flag & EXPRINEVAL)
692                         evalerr(es, ET_RECURSIVE, vp->name);
693                 es->evaling = vp;
694                 vp->flag |= EXPRINEVAL;
695                 v_evaluate(vq, str_val(vp), KSH_UNWIND_ERROR, es->arith);
696                 vp->flag &= ~EXPRINEVAL;
697                 es->evaling = NULL;
698         }
699         return (vq);
700 }
701
702
703 /*
704  * UTF-8 support code: high-level functions
705  */
706
707 int
708 utf_widthadj(const char *src, const char **dst)
709 {
710         size_t len;
711         unsigned int wc;
712         int width;
713
714         if (!UTFMODE || (len = utf_mbtowc(&wc, src)) == (size_t)-1 ||
715             wc == 0)
716                 len = width = 1;
717         else if ((width = utf_wcwidth(wc)) < 0)
718                 /* XXX use 2 for x_zotc3 here? */
719                 width = 1;
720
721         if (dst)
722                 *dst = src + len;
723         return (width);
724 }
725
726 size_t
727 utf_mbswidth(const char *s)
728 {
729         size_t len, width = 0;
730         unsigned int wc;
731         int cw;
732
733         if (!UTFMODE)
734                 return (strlen(s));
735
736         while (*s)
737                 if (((len = utf_mbtowc(&wc, s)) == (size_t)-1) ||
738                     ((cw = utf_wcwidth(wc)) == -1)) {
739                         s++;
740                         width += 1;
741                 } else {
742                         s += len;
743                         width += cw;
744                 }
745         return (width);
746 }
747
748 const char *
749 utf_skipcols(const char *p, int cols, int *colp)
750 {
751         int c = 0;
752         const char *q;
753
754         while (c < cols) {
755                 if (!*p) {
756                         /* end of input; special handling for edit.c */
757                         if (!colp)
758                                 return (p + cols - c);
759                         *colp = c;
760                         return (p);
761                 }
762                 c += utf_widthadj(p, &p);
763         }
764         if (UTFMODE)
765                 while (utf_widthadj(p, &q) == 0)
766                         p = q;
767         if (colp)
768                 *colp = c;
769         return (p);
770 }
771
772 size_t
773 utf_ptradj(const char *src)
774 {
775         register size_t n;
776
777         if (!UTFMODE || rtt2asc(*src) < 0xC2 ||
778             (n = utf_mbtowc(NULL, src)) == (size_t)-1)
779                 n = 1;
780         return (n);
781 }
782
783 /*
784  * UTF-8 support code: low-level functions
785  */
786
787 /* CESU-8 multibyte and wide character conversion crafted for mksh */
788
789 size_t
790 utf_mbtowc(unsigned int *dst, const char *src)
791 {
792         const unsigned char *s = (const unsigned char *)src;
793         unsigned int c, wc;
794
795         if ((wc = ord(rtt2asc(*s++))) < 0x80) {
796  out:
797                 if (dst != NULL)
798                         *dst = wc;
799                 return (wc ? ((const char *)s - src) : 0);
800         }
801         if (wc < 0xC2 || wc >= 0xF0)
802                 /* < 0xC0: spurious second byte */
803                 /* < 0xC2: non-minimalistic mapping error in 2-byte seqs */
804                 /* > 0xEF: beyond BMP */
805                 goto ilseq;
806
807         if (wc < 0xE0) {
808                 wc = (wc & 0x1F) << 6;
809                 if (((c = ord(rtt2asc(*s++))) & 0xC0) != 0x80)
810                         goto ilseq;
811                 wc |= c & 0x3F;
812                 goto out;
813         }
814
815         wc = (wc & 0x0F) << 12;
816
817         if (((c = ord(rtt2asc(*s++))) & 0xC0) != 0x80)
818                 goto ilseq;
819         wc |= (c & 0x3F) << 6;
820
821         if (((c = ord(rtt2asc(*s++))) & 0xC0) != 0x80)
822                 goto ilseq;
823         wc |= c & 0x3F;
824
825         /* Check for non-minimalistic mapping error in 3-byte seqs */
826         if (wc >= 0x0800 && wc <= 0xFFFD)
827                 goto out;
828  ilseq:
829         return ((size_t)(-1));
830 }
831
832 size_t
833 utf_wctomb(char *dst, unsigned int wc)
834 {
835         unsigned char *d;
836
837         if (wc < 0x80) {
838                 *dst = asc2rtt(wc);
839                 return (1);
840         }
841
842         d = (unsigned char *)dst;
843         if (wc < 0x0800)
844                 *d++ = asc2rtt((wc >> 6) | 0xC0);
845         else {
846                 *d++ = asc2rtt(((wc = wc > 0xFFFD ? 0xFFFD : wc) >> 12) | 0xE0);
847                 *d++ = asc2rtt(((wc >> 6) & 0x3F) | 0x80);
848         }
849         *d++ = asc2rtt((wc & 0x3F) | 0x80);
850         return ((char *)d - dst);
851 }
852
853 /*
854  * Wrapper around access(2) because it says root can execute everything
855  * on some operating systems. Does not set errno, no user needs it. Use
856  * this iff mode can have the X_OK bit set, access otherwise.
857  */
858 int
859 ksh_access(const char *fn, int mode)
860 {
861 #ifdef __OS2__
862         return (access_ex(access, fn, mode));
863 #else
864         int rv;
865         struct stat sb;
866
867         if ((rv = access(fn, mode)) == 0 && kshuid == 0 && (mode & X_OK) &&
868             (rv = stat(fn, &sb)) == 0 && !S_ISDIR(sb.st_mode) &&
869             (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
870                 rv = -1;
871
872         return (rv);
873 #endif
874 }
875
876 #ifndef MIRBSD_BOOTFLOPPY
877 /* From: X11/xc/programs/xterm/wcwidth.c,v 1.10 */
878
879 struct mb_ucsrange {
880         unsigned short beg;
881         unsigned short end;
882 };
883
884 static int mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems,
885     unsigned int val) MKSH_A_PURE;
886
887 /*
888  * Generated from the Unicode Character Database, Version 10.0.0, by
889  * MirOS: contrib/code/Snippets/eawparse,v 1.12 2017/09/06 16:05:45 tg Exp $
890  */
891
892 static const struct mb_ucsrange mb_ucs_combining[] = {
893         { 0x0300, 0x036F },
894         { 0x0483, 0x0489 },
895         { 0x0591, 0x05BD },
896         { 0x05BF, 0x05BF },
897         { 0x05C1, 0x05C2 },
898         { 0x05C4, 0x05C5 },
899         { 0x05C7, 0x05C7 },
900         { 0x0610, 0x061A },
901         { 0x061C, 0x061C },
902         { 0x064B, 0x065F },
903         { 0x0670, 0x0670 },
904         { 0x06D6, 0x06DC },
905         { 0x06DF, 0x06E4 },
906         { 0x06E7, 0x06E8 },
907         { 0x06EA, 0x06ED },
908         { 0x0711, 0x0711 },
909         { 0x0730, 0x074A },
910         { 0x07A6, 0x07B0 },
911         { 0x07EB, 0x07F3 },
912         { 0x0816, 0x0819 },
913         { 0x081B, 0x0823 },
914         { 0x0825, 0x0827 },
915         { 0x0829, 0x082D },
916         { 0x0859, 0x085B },
917         { 0x08D4, 0x08E1 },
918         { 0x08E3, 0x0902 },
919         { 0x093A, 0x093A },
920         { 0x093C, 0x093C },
921         { 0x0941, 0x0948 },
922         { 0x094D, 0x094D },
923         { 0x0951, 0x0957 },
924         { 0x0962, 0x0963 },
925         { 0x0981, 0x0981 },
926         { 0x09BC, 0x09BC },
927         { 0x09C1, 0x09C4 },
928         { 0x09CD, 0x09CD },
929         { 0x09E2, 0x09E3 },
930         { 0x0A01, 0x0A02 },
931         { 0x0A3C, 0x0A3C },
932         { 0x0A41, 0x0A42 },
933         { 0x0A47, 0x0A48 },
934         { 0x0A4B, 0x0A4D },
935         { 0x0A51, 0x0A51 },
936         { 0x0A70, 0x0A71 },
937         { 0x0A75, 0x0A75 },
938         { 0x0A81, 0x0A82 },
939         { 0x0ABC, 0x0ABC },
940         { 0x0AC1, 0x0AC5 },
941         { 0x0AC7, 0x0AC8 },
942         { 0x0ACD, 0x0ACD },
943         { 0x0AE2, 0x0AE3 },
944         { 0x0AFA, 0x0AFF },
945         { 0x0B01, 0x0B01 },
946         { 0x0B3C, 0x0B3C },
947         { 0x0B3F, 0x0B3F },
948         { 0x0B41, 0x0B44 },
949         { 0x0B4D, 0x0B4D },
950         { 0x0B56, 0x0B56 },
951         { 0x0B62, 0x0B63 },
952         { 0x0B82, 0x0B82 },
953         { 0x0BC0, 0x0BC0 },
954         { 0x0BCD, 0x0BCD },
955         { 0x0C00, 0x0C00 },
956         { 0x0C3E, 0x0C40 },
957         { 0x0C46, 0x0C48 },
958         { 0x0C4A, 0x0C4D },
959         { 0x0C55, 0x0C56 },
960         { 0x0C62, 0x0C63 },
961         { 0x0C81, 0x0C81 },
962         { 0x0CBC, 0x0CBC },
963         { 0x0CBF, 0x0CBF },
964         { 0x0CC6, 0x0CC6 },
965         { 0x0CCC, 0x0CCD },
966         { 0x0CE2, 0x0CE3 },
967         { 0x0D00, 0x0D01 },
968         { 0x0D3B, 0x0D3C },
969         { 0x0D41, 0x0D44 },
970         { 0x0D4D, 0x0D4D },
971         { 0x0D62, 0x0D63 },
972         { 0x0DCA, 0x0DCA },
973         { 0x0DD2, 0x0DD4 },
974         { 0x0DD6, 0x0DD6 },
975         { 0x0E31, 0x0E31 },
976         { 0x0E34, 0x0E3A },
977         { 0x0E47, 0x0E4E },
978         { 0x0EB1, 0x0EB1 },
979         { 0x0EB4, 0x0EB9 },
980         { 0x0EBB, 0x0EBC },
981         { 0x0EC8, 0x0ECD },
982         { 0x0F18, 0x0F19 },
983         { 0x0F35, 0x0F35 },
984         { 0x0F37, 0x0F37 },
985         { 0x0F39, 0x0F39 },
986         { 0x0F71, 0x0F7E },
987         { 0x0F80, 0x0F84 },
988         { 0x0F86, 0x0F87 },
989         { 0x0F8D, 0x0F97 },
990         { 0x0F99, 0x0FBC },
991         { 0x0FC6, 0x0FC6 },
992         { 0x102D, 0x1030 },
993         { 0x1032, 0x1037 },
994         { 0x1039, 0x103A },
995         { 0x103D, 0x103E },
996         { 0x1058, 0x1059 },
997         { 0x105E, 0x1060 },
998         { 0x1071, 0x1074 },
999         { 0x1082, 0x1082 },
1000         { 0x1085, 0x1086 },
1001         { 0x108D, 0x108D },
1002         { 0x109D, 0x109D },
1003         { 0x1160, 0x11FF },
1004         { 0x135D, 0x135F },
1005         { 0x1712, 0x1714 },
1006         { 0x1732, 0x1734 },
1007         { 0x1752, 0x1753 },
1008         { 0x1772, 0x1773 },
1009         { 0x17B4, 0x17B5 },
1010         { 0x17B7, 0x17BD },
1011         { 0x17C6, 0x17C6 },
1012         { 0x17C9, 0x17D3 },
1013         { 0x17DD, 0x17DD },
1014         { 0x180B, 0x180E },
1015         { 0x1885, 0x1886 },
1016         { 0x18A9, 0x18A9 },
1017         { 0x1920, 0x1922 },
1018         { 0x1927, 0x1928 },
1019         { 0x1932, 0x1932 },
1020         { 0x1939, 0x193B },
1021         { 0x1A17, 0x1A18 },
1022         { 0x1A1B, 0x1A1B },
1023         { 0x1A56, 0x1A56 },
1024         { 0x1A58, 0x1A5E },
1025         { 0x1A60, 0x1A60 },
1026         { 0x1A62, 0x1A62 },
1027         { 0x1A65, 0x1A6C },
1028         { 0x1A73, 0x1A7C },
1029         { 0x1A7F, 0x1A7F },
1030         { 0x1AB0, 0x1ABE },
1031         { 0x1B00, 0x1B03 },
1032         { 0x1B34, 0x1B34 },
1033         { 0x1B36, 0x1B3A },
1034         { 0x1B3C, 0x1B3C },
1035         { 0x1B42, 0x1B42 },
1036         { 0x1B6B, 0x1B73 },
1037         { 0x1B80, 0x1B81 },
1038         { 0x1BA2, 0x1BA5 },
1039         { 0x1BA8, 0x1BA9 },
1040         { 0x1BAB, 0x1BAD },
1041         { 0x1BE6, 0x1BE6 },
1042         { 0x1BE8, 0x1BE9 },
1043         { 0x1BED, 0x1BED },
1044         { 0x1BEF, 0x1BF1 },
1045         { 0x1C2C, 0x1C33 },
1046         { 0x1C36, 0x1C37 },
1047         { 0x1CD0, 0x1CD2 },
1048         { 0x1CD4, 0x1CE0 },
1049         { 0x1CE2, 0x1CE8 },
1050         { 0x1CED, 0x1CED },
1051         { 0x1CF4, 0x1CF4 },
1052         { 0x1CF8, 0x1CF9 },
1053         { 0x1DC0, 0x1DF9 },
1054         { 0x1DFB, 0x1DFF },
1055         { 0x200B, 0x200F },
1056         { 0x202A, 0x202E },
1057         { 0x2060, 0x2064 },
1058         { 0x2066, 0x206F },
1059         { 0x20D0, 0x20F0 },
1060         { 0x2CEF, 0x2CF1 },
1061         { 0x2D7F, 0x2D7F },
1062         { 0x2DE0, 0x2DFF },
1063         { 0x302A, 0x302D },
1064         { 0x3099, 0x309A },
1065         { 0xA66F, 0xA672 },
1066         { 0xA674, 0xA67D },
1067         { 0xA69E, 0xA69F },
1068         { 0xA6F0, 0xA6F1 },
1069         { 0xA802, 0xA802 },
1070         { 0xA806, 0xA806 },
1071         { 0xA80B, 0xA80B },
1072         { 0xA825, 0xA826 },
1073         { 0xA8C4, 0xA8C5 },
1074         { 0xA8E0, 0xA8F1 },
1075         { 0xA926, 0xA92D },
1076         { 0xA947, 0xA951 },
1077         { 0xA980, 0xA982 },
1078         { 0xA9B3, 0xA9B3 },
1079         { 0xA9B6, 0xA9B9 },
1080         { 0xA9BC, 0xA9BC },
1081         { 0xA9E5, 0xA9E5 },
1082         { 0xAA29, 0xAA2E },
1083         { 0xAA31, 0xAA32 },
1084         { 0xAA35, 0xAA36 },
1085         { 0xAA43, 0xAA43 },
1086         { 0xAA4C, 0xAA4C },
1087         { 0xAA7C, 0xAA7C },
1088         { 0xAAB0, 0xAAB0 },
1089         { 0xAAB2, 0xAAB4 },
1090         { 0xAAB7, 0xAAB8 },
1091         { 0xAABE, 0xAABF },
1092         { 0xAAC1, 0xAAC1 },
1093         { 0xAAEC, 0xAAED },
1094         { 0xAAF6, 0xAAF6 },
1095         { 0xABE5, 0xABE5 },
1096         { 0xABE8, 0xABE8 },
1097         { 0xABED, 0xABED },
1098         { 0xFB1E, 0xFB1E },
1099         { 0xFE00, 0xFE0F },
1100         { 0xFE20, 0xFE2F },
1101         { 0xFEFF, 0xFEFF },
1102         { 0xFFF9, 0xFFFB }
1103 };
1104
1105 static const struct mb_ucsrange mb_ucs_fullwidth[] = {
1106         { 0x1100, 0x115F },
1107         { 0x231A, 0x231B },
1108         { 0x2329, 0x232A },
1109         { 0x23E9, 0x23EC },
1110         { 0x23F0, 0x23F0 },
1111         { 0x23F3, 0x23F3 },
1112         { 0x25FD, 0x25FE },
1113         { 0x2614, 0x2615 },
1114         { 0x2648, 0x2653 },
1115         { 0x267F, 0x267F },
1116         { 0x2693, 0x2693 },
1117         { 0x26A1, 0x26A1 },
1118         { 0x26AA, 0x26AB },
1119         { 0x26BD, 0x26BE },
1120         { 0x26C4, 0x26C5 },
1121         { 0x26CE, 0x26CE },
1122         { 0x26D4, 0x26D4 },
1123         { 0x26EA, 0x26EA },
1124         { 0x26F2, 0x26F3 },
1125         { 0x26F5, 0x26F5 },
1126         { 0x26FA, 0x26FA },
1127         { 0x26FD, 0x26FD },
1128         { 0x2705, 0x2705 },
1129         { 0x270A, 0x270B },
1130         { 0x2728, 0x2728 },
1131         { 0x274C, 0x274C },
1132         { 0x274E, 0x274E },
1133         { 0x2753, 0x2755 },
1134         { 0x2757, 0x2757 },
1135         { 0x2795, 0x2797 },
1136         { 0x27B0, 0x27B0 },
1137         { 0x27BF, 0x27BF },
1138         { 0x2B1B, 0x2B1C },
1139         { 0x2B50, 0x2B50 },
1140         { 0x2B55, 0x2B55 },
1141         { 0x2E80, 0x3029 },
1142         { 0x302E, 0x303E },
1143         { 0x3040, 0x3098 },
1144         { 0x309B, 0xA4CF },
1145         { 0xA960, 0xA97F },
1146         { 0xAC00, 0xD7A3 },
1147         { 0xF900, 0xFAFF },
1148         { 0xFE10, 0xFE19 },
1149         { 0xFE30, 0xFE6F },
1150         { 0xFF01, 0xFF60 },
1151         { 0xFFE0, 0xFFE6 }
1152 };
1153
1154 /* simple binary search in ranges, with bounds optimisation */
1155 static int
1156 mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems, unsigned int val)
1157 {
1158         size_t min = 0, mid, max = elems;
1159
1160         if (val < arr[min].beg || val > arr[max - 1].end)
1161                 return (0);
1162
1163         while (min < max) {
1164                 mid = (min + max) / 2;
1165
1166                 if (val < arr[mid].beg)
1167                         max = mid;
1168                 else if (val > arr[mid].end)
1169                         min = mid + 1;
1170                 else
1171                         return (1);
1172         }
1173         return (0);
1174 }
1175
1176 /* Unix column width of a wide character (Unicode code point, really) */
1177 int
1178 utf_wcwidth(unsigned int wc)
1179 {
1180         /* except NUL, C0/C1 control characters and DEL yield -1 */
1181         if (wc < 0x20 || (wc >= 0x7F && wc < 0xA0))
1182                 return (wc ? -1 : 0);
1183
1184         /* combining characters use 0 screen columns */
1185         if (mb_ucsbsearch(mb_ucs_combining, NELEM(mb_ucs_combining), wc))
1186                 return (0);
1187
1188         /* all others use 1 or 2 screen columns */
1189         if (mb_ucsbsearch(mb_ucs_fullwidth, NELEM(mb_ucs_fullwidth), wc))
1190                 return (2);
1191         return (1);
1192 }
1193 #endif