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
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.90 2016/11/07 16:58:48 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
evaluate(const char * expr,mksh_ari_t * rval,int error_ok,bool arith)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
v_evaluate(struct tbl * vp,const char * expr,volatile int error_ok,bool arith)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
evalerr(Expr_state * es,enum error_type type,const char * str)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 		    "bad number", 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 *
do_ppmm(Expr_state * es,enum token op,struct tbl * vasn,bool is_prefix)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 *
evalexpr(Expr_state * es,unsigned int prec)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
exprtoken(Expr_state * es)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 	while ((c = *cp), ksh_isspace(c))
562 		++cp;
563 	if (es->tokp == es->expression && c == '#') {
564 		/* expression begins with # */
565 		/* switch to unsigned */
566 		es->natural = true;
567 		++cp;
568 		goto skip_spaces;
569 	}
570 	es->tokp = cp;
571 
572 	if (c == '\0')
573 		es->tok = END;
574 	else if (ksh_isalphx(c)) {
575 		for (; ksh_isalnux(c); c = *cp)
576 			cp++;
577 		if (c == '[') {
578 			size_t len;
579 
580 			len = array_ref_len(cp);
581 			if (len == 0)
582 				evalerr(es, ET_STR, "missing ]");
583 			cp += len;
584 		}
585 		if (es->noassign) {
586 			es->val = tempvar("");
587 			es->val->flag |= EXPRLVALUE;
588 		} else {
589 			strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
590 			es->val = global(tvar);
591 			afree(tvar, ATEMP);
592 		}
593 		es->tok = VAR;
594 	} else if (c == '1' && cp[1] == '#') {
595 		cp += 2;
596 		if (*cp)
597 			cp += utf_ptradj(cp);
598 		strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
599 		goto process_tvar;
600 #ifndef MKSH_SMALL
601 	} else if (c == '\'') {
602 		if (*++cp == '\0') {
603 			es->tok = END;
604 			evalerr(es, ET_UNEXPECTED, NULL);
605 		}
606 		cp += utf_ptradj(cp);
607 		if (*cp++ != '\'')
608 			evalerr(es, ET_STR,
609 			    "multi-character character constant");
610 		/* 'x' -> 1#x (x = one multibyte character) */
611 		c = cp - es->tokp;
612 		tvar = alloc(c + /* NUL */ 1, ATEMP);
613 		tvar[0] = '1';
614 		tvar[1] = '#';
615 		memcpy(tvar + 2, es->tokp + 1, c - 2);
616 		tvar[c] = '\0';
617 		goto process_tvar;
618 #endif
619 	} else if (ksh_isdigit(c)) {
620 		while (c != '_' && (ksh_isalnux(c) || c == '#'))
621 			c = *cp++;
622 		strndupx(tvar, es->tokp, --cp - es->tokp, ATEMP);
623  process_tvar:
624 		es->val = tempvar("");
625 		es->val->flag &= ~INTEGER;
626 		es->val->type = 0;
627 		es->val->val.s = tvar;
628 		if (setint_v(es->val, es->val, es->arith) == NULL)
629 			evalerr(es, ET_BADLIT, tvar);
630 		afree(tvar, ATEMP);
631 		es->tok = LIT;
632 	} else {
633 		int i, n0;
634 
635 		for (i = 0; (n0 = opname[i][0]); i++)
636 			if (c == n0 && strncmp(cp, opname[i],
637 			    (size_t)oplen[i]) == 0) {
638 				es->tok = (enum token)i;
639 				cp += oplen[i];
640 				break;
641 			}
642 		if (!n0)
643 			es->tok = BAD;
644 	}
645 	es->tokp = cp;
646 }
647 
648 static void
assign_check(Expr_state * es,enum token op,struct tbl * vasn)649 assign_check(Expr_state *es, enum token op, struct tbl *vasn)
650 {
651 	if (es->tok == END || !vasn ||
652 	    (vasn->name[0] == '\0' && !(vasn->flag & EXPRLVALUE)))
653 		evalerr(es, ET_LVALUE, opname[(int)op]);
654 	else if (vasn->flag & RDONLY)
655 		evalerr(es, ET_RDONLY, opname[(int)op]);
656 }
657 
658 struct tbl *
tempvar(const char * vname)659 tempvar(const char *vname)
660 {
661 	struct tbl *vp;
662 	size_t vsize;
663 
664 	vsize = strlen(vname) + 1;
665 	vp = alloc(offsetof(struct tbl, name[0]) + vsize, ATEMP);
666 	memcpy(vp->name, vname, vsize);
667 	vp->flag = ISSET|INTEGER;
668 	vp->type = 0;
669 	vp->areap = ATEMP;
670 	vp->ua.hval = 0;
671 	vp->val.i = 0;
672 	return (vp);
673 }
674 
675 /* cast (string) variable to temporary integer variable */
676 static struct tbl *
intvar(Expr_state * es,struct tbl * vp)677 intvar(Expr_state *es, struct tbl *vp)
678 {
679 	struct tbl *vq;
680 
681 	/* try to avoid replacing a temp var with another temp var */
682 	if (vp->name[0] == '\0' &&
683 	    (vp->flag & (ISSET|INTEGER|EXPRLVALUE)) == (ISSET|INTEGER))
684 		return (vp);
685 
686 	vq = tempvar("");
687 	if (setint_v(vq, vp, es->arith) == NULL) {
688 		if (vp->flag & EXPRINEVAL)
689 			evalerr(es, ET_RECURSIVE, vp->name);
690 		es->evaling = vp;
691 		vp->flag |= EXPRINEVAL;
692 		v_evaluate(vq, str_val(vp), KSH_UNWIND_ERROR, es->arith);
693 		vp->flag &= ~EXPRINEVAL;
694 		es->evaling = NULL;
695 	}
696 	return (vq);
697 }
698 
699 
700 /*
701  * UTF-8 support code: high-level functions
702  */
703 
704 int
utf_widthadj(const char * src,const char ** dst)705 utf_widthadj(const char *src, const char **dst)
706 {
707 	size_t len;
708 	unsigned int wc;
709 	int width;
710 
711 	if (!UTFMODE || (len = utf_mbtowc(&wc, src)) == (size_t)-1 ||
712 	    wc == 0)
713 		len = width = 1;
714 	else if ((width = utf_wcwidth(wc)) < 0)
715 		/* XXX use 2 for x_zotc3 here? */
716 		width = 1;
717 
718 	if (dst)
719 		*dst = src + len;
720 	return (width);
721 }
722 
723 size_t
utf_mbswidth(const char * s)724 utf_mbswidth(const char *s)
725 {
726 	size_t len, width = 0;
727 	unsigned int wc;
728 	int cw;
729 
730 	if (!UTFMODE)
731 		return (strlen(s));
732 
733 	while (*s)
734 		if (((len = utf_mbtowc(&wc, s)) == (size_t)-1) ||
735 		    ((cw = utf_wcwidth(wc)) == -1)) {
736 			s++;
737 			width += 1;
738 		} else {
739 			s += len;
740 			width += cw;
741 		}
742 	return (width);
743 }
744 
745 const char *
utf_skipcols(const char * p,int cols,int * colp)746 utf_skipcols(const char *p, int cols, int *colp)
747 {
748 	int c = 0;
749 	const char *q;
750 
751 	while (c < cols) {
752 		if (!*p) {
753 			/* end of input; special handling for edit.c */
754 			if (!colp)
755 				return (p + cols - c);
756 			*colp = c;
757 			return (p);
758 		}
759 		c += utf_widthadj(p, &p);
760 	}
761 	if (UTFMODE)
762 		while (utf_widthadj(p, &q) == 0)
763 			p = q;
764 	if (colp)
765 		*colp = c;
766 	return (p);
767 }
768 
769 size_t
utf_ptradj(const char * src)770 utf_ptradj(const char *src)
771 {
772 	register size_t n;
773 
774 	if (!UTFMODE ||
775 	    *(const unsigned char *)(src) < 0xC2 ||
776 	    (n = utf_mbtowc(NULL, src)) == (size_t)-1)
777 		n = 1;
778 	return (n);
779 }
780 
781 /*
782  * UTF-8 support code: low-level functions
783  */
784 
785 /* CESU-8 multibyte and wide character conversion crafted for mksh */
786 
787 size_t
utf_mbtowc(unsigned int * dst,const char * src)788 utf_mbtowc(unsigned int *dst, const char *src)
789 {
790 	const unsigned char *s = (const unsigned char *)src;
791 	unsigned int c, wc;
792 
793 	if ((wc = *s++) < 0x80) {
794  out:
795 		if (dst != NULL)
796 			*dst = wc;
797 		return (wc ? ((const char *)s - src) : 0);
798 	}
799 	if (wc < 0xC2 || wc >= 0xF0)
800 		/* < 0xC0: spurious second byte */
801 		/* < 0xC2: non-minimalistic mapping error in 2-byte seqs */
802 		/* > 0xEF: beyond BMP */
803 		goto ilseq;
804 
805 	if (wc < 0xE0) {
806 		wc = (wc & 0x1F) << 6;
807 		if (((c = *s++) & 0xC0) != 0x80)
808 			goto ilseq;
809 		wc |= c & 0x3F;
810 		goto out;
811 	}
812 
813 	wc = (wc & 0x0F) << 12;
814 
815 	if (((c = *s++) & 0xC0) != 0x80)
816 		goto ilseq;
817 	wc |= (c & 0x3F) << 6;
818 
819 	if (((c = *s++) & 0xC0) != 0x80)
820 		goto ilseq;
821 	wc |= c & 0x3F;
822 
823 	/* Check for non-minimalistic mapping error in 3-byte seqs */
824 	if (wc >= 0x0800 && wc <= 0xFFFD)
825 		goto out;
826  ilseq:
827 	return ((size_t)(-1));
828 }
829 
830 size_t
utf_wctomb(char * dst,unsigned int wc)831 utf_wctomb(char *dst, unsigned int wc)
832 {
833 	unsigned char *d;
834 
835 	if (wc < 0x80) {
836 		*dst = wc;
837 		return (1);
838 	}
839 
840 	d = (unsigned char *)dst;
841 	if (wc < 0x0800)
842 		*d++ = (wc >> 6) | 0xC0;
843 	else {
844 		*d++ = ((wc = wc > 0xFFFD ? 0xFFFD : wc) >> 12) | 0xE0;
845 		*d++ = ((wc >> 6) & 0x3F) | 0x80;
846 	}
847 	*d++ = (wc & 0x3F) | 0x80;
848 	return ((char *)d - dst);
849 }
850 
851 /*
852  * Wrapper around access(2) because it says root can execute everything
853  * on some operating systems. Does not set errno, no user needs it. Use
854  * this iff mode can have the X_OK bit set, access otherwise.
855  */
856 int
ksh_access(const char * fn,int mode)857 ksh_access(const char *fn, int mode)
858 {
859 	int rv;
860 	struct stat sb;
861 
862 	if ((rv = access(fn, mode)) == 0 && kshuid == 0 && (mode & X_OK) &&
863 	    (rv = stat(fn, &sb)) == 0 && !S_ISDIR(sb.st_mode) &&
864 	    (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
865 		rv = -1;
866 
867 	return (rv);
868 }
869 
870 #ifndef MIRBSD_BOOTFLOPPY
871 /* From: X11/xc/programs/xterm/wcwidth.c,v 1.9 */
872 
873 struct mb_ucsrange {
874 	unsigned short beg;
875 	unsigned short end;
876 };
877 
878 static int mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems,
879     unsigned int val) MKSH_A_PURE;
880 
881 /*
882  * Generated from the Unicode Character Database, Version 9.0.0, by
883  * MirOS: contrib/code/Snippets/eawparse,v 1.3 2014/11/16 12:16:24 tg Exp $
884  */
885 
886 static const struct mb_ucsrange mb_ucs_combining[] = {
887 	{ 0x0300, 0x036F },
888 	{ 0x0483, 0x0489 },
889 	{ 0x0591, 0x05BD },
890 	{ 0x05BF, 0x05BF },
891 	{ 0x05C1, 0x05C2 },
892 	{ 0x05C4, 0x05C5 },
893 	{ 0x05C7, 0x05C7 },
894 	{ 0x0600, 0x0605 },
895 	{ 0x0610, 0x061A },
896 	{ 0x061C, 0x061C },
897 	{ 0x064B, 0x065F },
898 	{ 0x0670, 0x0670 },
899 	{ 0x06D6, 0x06DD },
900 	{ 0x06DF, 0x06E4 },
901 	{ 0x06E7, 0x06E8 },
902 	{ 0x06EA, 0x06ED },
903 	{ 0x070F, 0x070F },
904 	{ 0x0711, 0x0711 },
905 	{ 0x0730, 0x074A },
906 	{ 0x07A6, 0x07B0 },
907 	{ 0x07EB, 0x07F3 },
908 	{ 0x0816, 0x0819 },
909 	{ 0x081B, 0x0823 },
910 	{ 0x0825, 0x0827 },
911 	{ 0x0829, 0x082D },
912 	{ 0x0859, 0x085B },
913 	{ 0x08D4, 0x0902 },
914 	{ 0x093A, 0x093A },
915 	{ 0x093C, 0x093C },
916 	{ 0x0941, 0x0948 },
917 	{ 0x094D, 0x094D },
918 	{ 0x0951, 0x0957 },
919 	{ 0x0962, 0x0963 },
920 	{ 0x0981, 0x0981 },
921 	{ 0x09BC, 0x09BC },
922 	{ 0x09C1, 0x09C4 },
923 	{ 0x09CD, 0x09CD },
924 	{ 0x09E2, 0x09E3 },
925 	{ 0x0A01, 0x0A02 },
926 	{ 0x0A3C, 0x0A3C },
927 	{ 0x0A41, 0x0A42 },
928 	{ 0x0A47, 0x0A48 },
929 	{ 0x0A4B, 0x0A4D },
930 	{ 0x0A51, 0x0A51 },
931 	{ 0x0A70, 0x0A71 },
932 	{ 0x0A75, 0x0A75 },
933 	{ 0x0A81, 0x0A82 },
934 	{ 0x0ABC, 0x0ABC },
935 	{ 0x0AC1, 0x0AC5 },
936 	{ 0x0AC7, 0x0AC8 },
937 	{ 0x0ACD, 0x0ACD },
938 	{ 0x0AE2, 0x0AE3 },
939 	{ 0x0B01, 0x0B01 },
940 	{ 0x0B3C, 0x0B3C },
941 	{ 0x0B3F, 0x0B3F },
942 	{ 0x0B41, 0x0B44 },
943 	{ 0x0B4D, 0x0B4D },
944 	{ 0x0B56, 0x0B56 },
945 	{ 0x0B62, 0x0B63 },
946 	{ 0x0B82, 0x0B82 },
947 	{ 0x0BC0, 0x0BC0 },
948 	{ 0x0BCD, 0x0BCD },
949 	{ 0x0C00, 0x0C00 },
950 	{ 0x0C3E, 0x0C40 },
951 	{ 0x0C46, 0x0C48 },
952 	{ 0x0C4A, 0x0C4D },
953 	{ 0x0C55, 0x0C56 },
954 	{ 0x0C62, 0x0C63 },
955 	{ 0x0C81, 0x0C81 },
956 	{ 0x0CBC, 0x0CBC },
957 	{ 0x0CBF, 0x0CBF },
958 	{ 0x0CC6, 0x0CC6 },
959 	{ 0x0CCC, 0x0CCD },
960 	{ 0x0CE2, 0x0CE3 },
961 	{ 0x0D01, 0x0D01 },
962 	{ 0x0D41, 0x0D44 },
963 	{ 0x0D4D, 0x0D4D },
964 	{ 0x0D62, 0x0D63 },
965 	{ 0x0DCA, 0x0DCA },
966 	{ 0x0DD2, 0x0DD4 },
967 	{ 0x0DD6, 0x0DD6 },
968 	{ 0x0E31, 0x0E31 },
969 	{ 0x0E34, 0x0E3A },
970 	{ 0x0E47, 0x0E4E },
971 	{ 0x0EB1, 0x0EB1 },
972 	{ 0x0EB4, 0x0EB9 },
973 	{ 0x0EBB, 0x0EBC },
974 	{ 0x0EC8, 0x0ECD },
975 	{ 0x0F18, 0x0F19 },
976 	{ 0x0F35, 0x0F35 },
977 	{ 0x0F37, 0x0F37 },
978 	{ 0x0F39, 0x0F39 },
979 	{ 0x0F71, 0x0F7E },
980 	{ 0x0F80, 0x0F84 },
981 	{ 0x0F86, 0x0F87 },
982 	{ 0x0F8D, 0x0F97 },
983 	{ 0x0F99, 0x0FBC },
984 	{ 0x0FC6, 0x0FC6 },
985 	{ 0x102D, 0x1030 },
986 	{ 0x1032, 0x1037 },
987 	{ 0x1039, 0x103A },
988 	{ 0x103D, 0x103E },
989 	{ 0x1058, 0x1059 },
990 	{ 0x105E, 0x1060 },
991 	{ 0x1071, 0x1074 },
992 	{ 0x1082, 0x1082 },
993 	{ 0x1085, 0x1086 },
994 	{ 0x108D, 0x108D },
995 	{ 0x109D, 0x109D },
996 	{ 0x1160, 0x11FF },
997 	{ 0x135D, 0x135F },
998 	{ 0x1712, 0x1714 },
999 	{ 0x1732, 0x1734 },
1000 	{ 0x1752, 0x1753 },
1001 	{ 0x1772, 0x1773 },
1002 	{ 0x17B4, 0x17B5 },
1003 	{ 0x17B7, 0x17BD },
1004 	{ 0x17C6, 0x17C6 },
1005 	{ 0x17C9, 0x17D3 },
1006 	{ 0x17DD, 0x17DD },
1007 	{ 0x180B, 0x180E },
1008 	{ 0x1885, 0x1886 },
1009 	{ 0x18A9, 0x18A9 },
1010 	{ 0x1920, 0x1922 },
1011 	{ 0x1927, 0x1928 },
1012 	{ 0x1932, 0x1932 },
1013 	{ 0x1939, 0x193B },
1014 	{ 0x1A17, 0x1A18 },
1015 	{ 0x1A1B, 0x1A1B },
1016 	{ 0x1A56, 0x1A56 },
1017 	{ 0x1A58, 0x1A5E },
1018 	{ 0x1A60, 0x1A60 },
1019 	{ 0x1A62, 0x1A62 },
1020 	{ 0x1A65, 0x1A6C },
1021 	{ 0x1A73, 0x1A7C },
1022 	{ 0x1A7F, 0x1A7F },
1023 	{ 0x1AB0, 0x1ABE },
1024 	{ 0x1B00, 0x1B03 },
1025 	{ 0x1B34, 0x1B34 },
1026 	{ 0x1B36, 0x1B3A },
1027 	{ 0x1B3C, 0x1B3C },
1028 	{ 0x1B42, 0x1B42 },
1029 	{ 0x1B6B, 0x1B73 },
1030 	{ 0x1B80, 0x1B81 },
1031 	{ 0x1BA2, 0x1BA5 },
1032 	{ 0x1BA8, 0x1BA9 },
1033 	{ 0x1BAB, 0x1BAD },
1034 	{ 0x1BE6, 0x1BE6 },
1035 	{ 0x1BE8, 0x1BE9 },
1036 	{ 0x1BED, 0x1BED },
1037 	{ 0x1BEF, 0x1BF1 },
1038 	{ 0x1C2C, 0x1C33 },
1039 	{ 0x1C36, 0x1C37 },
1040 	{ 0x1CD0, 0x1CD2 },
1041 	{ 0x1CD4, 0x1CE0 },
1042 	{ 0x1CE2, 0x1CE8 },
1043 	{ 0x1CED, 0x1CED },
1044 	{ 0x1CF4, 0x1CF4 },
1045 	{ 0x1CF8, 0x1CF9 },
1046 	{ 0x1DC0, 0x1DF5 },
1047 	{ 0x1DFB, 0x1DFF },
1048 	{ 0x200B, 0x200F },
1049 	{ 0x202A, 0x202E },
1050 	{ 0x2060, 0x2064 },
1051 	{ 0x2066, 0x206F },
1052 	{ 0x20D0, 0x20F0 },
1053 	{ 0x2CEF, 0x2CF1 },
1054 	{ 0x2D7F, 0x2D7F },
1055 	{ 0x2DE0, 0x2DFF },
1056 	{ 0x302A, 0x302D },
1057 	{ 0x3099, 0x309A },
1058 	{ 0xA66F, 0xA672 },
1059 	{ 0xA674, 0xA67D },
1060 	{ 0xA69E, 0xA69F },
1061 	{ 0xA6F0, 0xA6F1 },
1062 	{ 0xA802, 0xA802 },
1063 	{ 0xA806, 0xA806 },
1064 	{ 0xA80B, 0xA80B },
1065 	{ 0xA825, 0xA826 },
1066 	{ 0xA8C4, 0xA8C5 },
1067 	{ 0xA8E0, 0xA8F1 },
1068 	{ 0xA926, 0xA92D },
1069 	{ 0xA947, 0xA951 },
1070 	{ 0xA980, 0xA982 },
1071 	{ 0xA9B3, 0xA9B3 },
1072 	{ 0xA9B6, 0xA9B9 },
1073 	{ 0xA9BC, 0xA9BC },
1074 	{ 0xA9E5, 0xA9E5 },
1075 	{ 0xAA29, 0xAA2E },
1076 	{ 0xAA31, 0xAA32 },
1077 	{ 0xAA35, 0xAA36 },
1078 	{ 0xAA43, 0xAA43 },
1079 	{ 0xAA4C, 0xAA4C },
1080 	{ 0xAA7C, 0xAA7C },
1081 	{ 0xAAB0, 0xAAB0 },
1082 	{ 0xAAB2, 0xAAB4 },
1083 	{ 0xAAB7, 0xAAB8 },
1084 	{ 0xAABE, 0xAABF },
1085 	{ 0xAAC1, 0xAAC1 },
1086 	{ 0xAAEC, 0xAAED },
1087 	{ 0xAAF6, 0xAAF6 },
1088 	{ 0xABE5, 0xABE5 },
1089 	{ 0xABE8, 0xABE8 },
1090 	{ 0xABED, 0xABED },
1091 	{ 0xFB1E, 0xFB1E },
1092 	{ 0xFE00, 0xFE0F },
1093 	{ 0xFE20, 0xFE2F },
1094 	{ 0xFEFF, 0xFEFF },
1095 	{ 0xFFF9, 0xFFFB }
1096 };
1097 
1098 static const struct mb_ucsrange mb_ucs_fullwidth[] = {
1099 	{ 0x1100, 0x115F },
1100 	{ 0x231A, 0x231B },
1101 	{ 0x2329, 0x232A },
1102 	{ 0x23E9, 0x23EC },
1103 	{ 0x23F0, 0x23F0 },
1104 	{ 0x23F3, 0x23F3 },
1105 	{ 0x25FD, 0x25FE },
1106 	{ 0x2614, 0x2615 },
1107 	{ 0x2648, 0x2653 },
1108 	{ 0x267F, 0x267F },
1109 	{ 0x2693, 0x2693 },
1110 	{ 0x26A1, 0x26A1 },
1111 	{ 0x26AA, 0x26AB },
1112 	{ 0x26BD, 0x26BE },
1113 	{ 0x26C4, 0x26C5 },
1114 	{ 0x26CE, 0x26CE },
1115 	{ 0x26D4, 0x26D4 },
1116 	{ 0x26EA, 0x26EA },
1117 	{ 0x26F2, 0x26F3 },
1118 	{ 0x26F5, 0x26F5 },
1119 	{ 0x26FA, 0x26FA },
1120 	{ 0x26FD, 0x26FD },
1121 	{ 0x2705, 0x2705 },
1122 	{ 0x270A, 0x270B },
1123 	{ 0x2728, 0x2728 },
1124 	{ 0x274C, 0x274C },
1125 	{ 0x274E, 0x274E },
1126 	{ 0x2753, 0x2755 },
1127 	{ 0x2757, 0x2757 },
1128 	{ 0x2795, 0x2797 },
1129 	{ 0x27B0, 0x27B0 },
1130 	{ 0x27BF, 0x27BF },
1131 	{ 0x2B1B, 0x2B1C },
1132 	{ 0x2B50, 0x2B50 },
1133 	{ 0x2B55, 0x2B55 },
1134 	{ 0x2E80, 0x303E },
1135 	{ 0x3040, 0xA4CF },
1136 	{ 0xA960, 0xA97F },
1137 	{ 0xAC00, 0xD7A3 },
1138 	{ 0xF900, 0xFAFF },
1139 	{ 0xFE10, 0xFE19 },
1140 	{ 0xFE30, 0xFE6F },
1141 	{ 0xFF00, 0xFF60 },
1142 	{ 0xFFE0, 0xFFE6 }
1143 };
1144 
1145 /* simple binary search in ranges, with bounds optimisation */
1146 static int
mb_ucsbsearch(const struct mb_ucsrange arr[],size_t elems,unsigned int val)1147 mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems, unsigned int val)
1148 {
1149 	size_t min = 0, mid, max = elems;
1150 
1151 	if (val < arr[min].beg || val > arr[max - 1].end)
1152 		return (0);
1153 
1154 	while (min < max) {
1155 		mid = (min + max) / 2;
1156 
1157 		if (val < arr[mid].beg)
1158 			max = mid;
1159 		else if (val > arr[mid].end)
1160 			min = mid + 1;
1161 		else
1162 			return (1);
1163 	}
1164 	return (0);
1165 }
1166 
1167 /* Unix column width of a wide character (Unicode code point, really) */
1168 int
utf_wcwidth(unsigned int wc)1169 utf_wcwidth(unsigned int wc)
1170 {
1171 	/* except NUL, C0/C1 control characters and DEL yield -1 */
1172 	if (wc < 0x20 || (wc >= 0x7F && wc < 0xA0))
1173 		return (wc ? -1 : 0);
1174 
1175 	/* combining characters use 0 screen columns */
1176 	if (mb_ucsbsearch(mb_ucs_combining, NELEM(mb_ucs_combining), wc))
1177 		return (0);
1178 
1179 	/* all others use 1 or 2 screen columns */
1180 	if (mb_ucsbsearch(mb_ucs_fullwidth, NELEM(mb_ucs_fullwidth), wc))
1181 		return (2);
1182 	return (1);
1183 }
1184 #endif
1185