Home | History | Annotate | Download | only in src
      1 /*	$OpenBSD: expr.c,v 1.21 2009/06/01 19:00:57 deraadt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
      5  *		 2011, 2012, 2013
      6  *	Thorsten Glaser <tg (at) 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.61 2013/02/15 18:36:48 tg Exp $");
     27 
     28 #if !HAVE_SILENT_IDIVWRAPV
     29 #if !defined(MKSH_LEGACY_MODE) || HAVE_LONG_32BIT
     30 #define IDIVWRAPV_VL	(mksh_uari_t)0x80000000UL
     31 #define IDIVWRAPV_VR	(mksh_uari_t)0xFFFFFFFFUL
     32 #elif HAVE_LONG_64BIT
     33 #define IDIVWRAPV_VL	(mksh_uari_t)0x8000000000000000UL
     34 #define IDIVWRAPV_VR	(mksh_uari_t)0xFFFFFFFFFFFFFFFFUL
     35 #else
     36 # warning "cannot guarantee integer division wraparound"
     37 #undef HAVE_SILENT_IDIVWRAPV
     38 #define HAVE_SILENT_IDIVWRAPV 1
     39 #endif
     40 #endif
     41 
     42 /* The order of these enums is constrained by the order of opinfo[] */
     43 enum token {
     44 	/* some (long) unary operators */
     45 	O_PLUSPLUS = 0, O_MINUSMINUS,
     46 	/* binary operators */
     47 	O_EQ, O_NE,
     48 	/* assignments are assumed to be in range O_ASN .. O_BORASN */
     49 	O_ASN, O_TIMESASN, O_DIVASN, O_MODASN, O_PLUSASN, O_MINUSASN,
     50 	O_LSHIFTASN, O_RSHIFTASN, O_BANDASN, O_BXORASN, O_BORASN,
     51 	O_LSHIFT, O_RSHIFT,
     52 	O_LE, O_GE, O_LT, O_GT,
     53 	O_LAND,
     54 	O_LOR,
     55 	O_TIMES, O_DIV, O_MOD,
     56 	O_PLUS, O_MINUS,
     57 	O_BAND,
     58 	O_BXOR,
     59 	O_BOR,
     60 	O_TERN,
     61 	O_COMMA,
     62 	/* things after this aren't used as binary operators */
     63 	/* unary that are not also binaries */
     64 	O_BNOT, O_LNOT,
     65 	/* misc */
     66 	OPEN_PAREN, CLOSE_PAREN, CTERN,
     67 	/* things that don't appear in the opinfo[] table */
     68 	VAR, LIT, END, BAD
     69 };
     70 #define IS_BINOP(op) (((int)op) >= (int)O_EQ && ((int)op) <= (int)O_COMMA)
     71 #define IS_ASSIGNOP(op)	((int)(op) >= (int)O_ASN && (int)(op) <= (int)O_BORASN)
     72 
     73 /* precisions; used to be enum prec but we do arithmetics on it */
     74 #define P_PRIMARY	0	/* VAR, LIT, (), ~ ! - + */
     75 #define P_MULT		1	/* * / % */
     76 #define P_ADD		2	/* + - */
     77 #define P_SHIFT		3	/* << >> */
     78 #define P_RELATION	4	/* < <= > >= */
     79 #define P_EQUALITY	5	/* == != */
     80 #define P_BAND		6	/* & */
     81 #define P_BXOR		7	/* ^ */
     82 #define P_BOR		8	/* | */
     83 #define P_LAND		9	/* && */
     84 #define P_LOR		10	/* || */
     85 #define P_TERN		11	/* ?: */
     86 #define P_ASSIGN	12	/* = *= /= %= += -= <<= >>= &= ^= |= */
     87 #define P_COMMA		13	/* , */
     88 #define MAX_PREC	P_COMMA
     89 
     90 struct opinfo {
     91 	char		name[4];
     92 	int		len;	/* name length */
     93 	int		prec;	/* precedence: lower is higher */
     94 };
     95 
     96 /* Tokens in this table must be ordered so the longest are first
     97  * (eg, += before +). If you change something, change the order
     98  * of enum token too.
     99  */
    100 static const struct opinfo opinfo[] = {
    101 	{ "++",	 2, P_PRIMARY },	/* before + */
    102 	{ "--",	 2, P_PRIMARY },	/* before - */
    103 	{ "==",	 2, P_EQUALITY },	/* before = */
    104 	{ "!=",	 2, P_EQUALITY },	/* before ! */
    105 	{ "=",	 1, P_ASSIGN },		/* keep assigns in a block */
    106 	{ "*=",	 2, P_ASSIGN },
    107 	{ "/=",	 2, P_ASSIGN },
    108 	{ "%=",	 2, P_ASSIGN },
    109 	{ "+=",	 2, P_ASSIGN },
    110 	{ "-=",	 2, P_ASSIGN },
    111 	{ "<<=", 3, P_ASSIGN },
    112 	{ ">>=", 3, P_ASSIGN },
    113 	{ "&=",	 2, P_ASSIGN },
    114 	{ "^=",	 2, P_ASSIGN },
    115 	{ "|=",	 2, P_ASSIGN },
    116 	{ "<<",	 2, P_SHIFT },
    117 	{ ">>",	 2, P_SHIFT },
    118 	{ "<=",	 2, P_RELATION },
    119 	{ ">=",	 2, P_RELATION },
    120 	{ "<",	 1, P_RELATION },
    121 	{ ">",	 1, P_RELATION },
    122 	{ "&&",	 2, P_LAND },
    123 	{ "||",	 2, P_LOR },
    124 	{ "*",	 1, P_MULT },
    125 	{ "/",	 1, P_MULT },
    126 	{ "%",	 1, P_MULT },
    127 	{ "+",	 1, P_ADD },
    128 	{ "-",	 1, P_ADD },
    129 	{ "&",	 1, P_BAND },
    130 	{ "^",	 1, P_BXOR },
    131 	{ "|",	 1, P_BOR },
    132 	{ "?",	 1, P_TERN },
    133 	{ ",",	 1, P_COMMA },
    134 	{ "~",	 1, P_PRIMARY },
    135 	{ "!",	 1, P_PRIMARY },
    136 	{ "(",	 1, P_PRIMARY },
    137 	{ ")",	 1, P_PRIMARY },
    138 	{ ":",	 1, P_PRIMARY },
    139 	{ "",	 0, P_PRIMARY }
    140 };
    141 
    142 typedef struct expr_state {
    143 	/* expression being evaluated */
    144 	const char *expression;
    145 	/* lexical position */
    146 	const char *tokp;
    147 	/* value from token() */
    148 	struct tbl *val;
    149 	/* variable that is being recursively expanded (EXPRINEVAL flag set) */
    150 	struct tbl *evaling;
    151 	/* token from token() */
    152 	enum token tok;
    153 	/* don't do assignments (for ?:, &&, ||) */
    154 	short noassign;
    155 	/* evaluating an $(()) expression? */
    156 	bool arith;
    157 	/* unsigned arithmetic calculation */
    158 	bool natural;
    159 } Expr_state;
    160 
    161 #define bivui(x, op, y)	(es->natural ?			\
    162 	(mksh_uari_t)((x)->val.u op (y)->val.u) :	\
    163 	(mksh_uari_t)((x)->val.i op (y)->val.i)		\
    164 )
    165 
    166 enum error_type {
    167 	ET_UNEXPECTED, ET_BADLIT, ET_RECURSIVE,
    168 	ET_LVALUE, ET_RDONLY, ET_STR
    169 };
    170 
    171 static void evalerr(Expr_state *, enum error_type, const char *)
    172     MKSH_A_NORETURN;
    173 static struct tbl *evalexpr(Expr_state *, int);
    174 static void exprtoken(Expr_state *);
    175 static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, bool);
    176 static void assign_check(Expr_state *, enum token, struct tbl *);
    177 static struct tbl *intvar(Expr_state *, struct tbl *);
    178 
    179 /*
    180  * parse and evaluate expression
    181  */
    182 int
    183 evaluate(const char *expr, mksh_ari_t *rval, int error_ok, bool arith)
    184 {
    185 	struct tbl v;
    186 	int ret;
    187 
    188 	v.flag = DEFINED|INTEGER;
    189 	v.type = 0;
    190 	ret = v_evaluate(&v, expr, error_ok, arith);
    191 	*rval = v.val.i;
    192 	return (ret);
    193 }
    194 
    195 /*
    196  * parse and evaluate expression, storing result in vp.
    197  */
    198 int
    199 v_evaluate(struct tbl *vp, const char *expr, volatile int error_ok,
    200     bool arith)
    201 {
    202 	struct tbl *v;
    203 	Expr_state curstate;
    204 	Expr_state * const es = &curstate;
    205 	int i;
    206 
    207 	/* save state to allow recursive calls */
    208 	memset(&curstate, 0, sizeof(curstate));
    209 	curstate.expression = curstate.tokp = expr;
    210 	curstate.tok = BAD;
    211 	curstate.arith = arith;
    212 
    213 	newenv(E_ERRH);
    214 	if ((i = kshsetjmp(e->jbuf))) {
    215 		/* Clear EXPRINEVAL in of any variables we were playing with */
    216 		if (curstate.evaling)
    217 			curstate.evaling->flag &= ~EXPRINEVAL;
    218 		quitenv(NULL);
    219 		if (i == LAEXPR) {
    220 			if (error_ok == KSH_RETURN_ERROR)
    221 				return (0);
    222 			errorfz();
    223 		}
    224 		unwind(i);
    225 		/* NOTREACHED */
    226 	}
    227 
    228 	exprtoken(es);
    229 	if (es->tok == END) {
    230 		es->tok = LIT;
    231 		es->val = tempvar();
    232 	}
    233 	v = intvar(es, evalexpr(es, MAX_PREC));
    234 
    235 	if (es->tok != END)
    236 		evalerr(es, ET_UNEXPECTED, NULL);
    237 
    238 	if (es->arith && es->natural)
    239 		vp->flag |= INT_U;
    240 	if (vp->flag & INTEGER)
    241 		setint_v(vp, v, es->arith);
    242 	else
    243 		/* can fail if readonly */
    244 		setstr(vp, str_val(v), error_ok);
    245 
    246 	quitenv(NULL);
    247 
    248 	return (1);
    249 }
    250 
    251 static void
    252 evalerr(Expr_state *es, enum error_type type, const char *str)
    253 {
    254 	char tbuf[2];
    255 	const char *s;
    256 
    257 	es->arith = false;
    258 	switch (type) {
    259 	case ET_UNEXPECTED:
    260 		switch (es->tok) {
    261 		case VAR:
    262 			s = es->val->name;
    263 			break;
    264 		case LIT:
    265 			s = str_val(es->val);
    266 			break;
    267 		case END:
    268 			s = "end of expression";
    269 			break;
    270 		case BAD:
    271 			tbuf[0] = *es->tokp;
    272 			tbuf[1] = '\0';
    273 			s = tbuf;
    274 			break;
    275 		default:
    276 			s = opinfo[(int)es->tok].name;
    277 		}
    278 		warningf(true, "%s: %s '%s'", es->expression,
    279 		    "unexpected", s);
    280 		break;
    281 
    282 	case ET_BADLIT:
    283 		warningf(true, "%s: %s '%s'", es->expression,
    284 		    "bad number", str);
    285 		break;
    286 
    287 	case ET_RECURSIVE:
    288 		warningf(true, "%s: %s '%s'", es->expression,
    289 		    "expression recurses on parameter", str);
    290 		break;
    291 
    292 	case ET_LVALUE:
    293 		warningf(true, "%s: %s %s",
    294 		    es->expression, str, "requires lvalue");
    295 		break;
    296 
    297 	case ET_RDONLY:
    298 		warningf(true, "%s: %s %s",
    299 		    es->expression, str, "applied to read-only variable");
    300 		break;
    301 
    302 	default: /* keep gcc happy */
    303 	case ET_STR:
    304 		warningf(true, "%s: %s", es->expression, str);
    305 		break;
    306 	}
    307 	unwind(LAEXPR);
    308 }
    309 
    310 static struct tbl *
    311 evalexpr(Expr_state *es, int prec)
    312 {
    313 	struct tbl *vl, *vr = NULL, *vasn;
    314 	enum token op;
    315 	mksh_uari_t res = 0;
    316 
    317 	if (prec == P_PRIMARY) {
    318 		op = es->tok;
    319 		if (op == O_BNOT || op == O_LNOT || op == O_MINUS ||
    320 		    op == O_PLUS) {
    321 			exprtoken(es);
    322 			vl = intvar(es, evalexpr(es, P_PRIMARY));
    323 			if (op == O_BNOT)
    324 				vl->val.i = ~vl->val.i;
    325 			else if (op == O_LNOT)
    326 				vl->val.i = !vl->val.i;
    327 			else if (op == O_MINUS)
    328 				vl->val.i = -vl->val.i;
    329 			/* op == O_PLUS is a no-op */
    330 		} else if (op == OPEN_PAREN) {
    331 			exprtoken(es);
    332 			vl = evalexpr(es, MAX_PREC);
    333 			if (es->tok != CLOSE_PAREN)
    334 				evalerr(es, ET_STR, "missing )");
    335 			exprtoken(es);
    336 		} else if (op == O_PLUSPLUS || op == O_MINUSMINUS) {
    337 			exprtoken(es);
    338 			vl = do_ppmm(es, op, es->val, true);
    339 			exprtoken(es);
    340 		} else if (op == VAR || op == LIT) {
    341 			vl = es->val;
    342 			exprtoken(es);
    343 		} else {
    344 			evalerr(es, ET_UNEXPECTED, NULL);
    345 			/* NOTREACHED */
    346 		}
    347 		if (es->tok == O_PLUSPLUS || es->tok == O_MINUSMINUS) {
    348 			vl = do_ppmm(es, es->tok, vl, false);
    349 			exprtoken(es);
    350 		}
    351 		return (vl);
    352 	}
    353 	vl = evalexpr(es, prec - 1);
    354 	for (op = es->tok; IS_BINOP(op) && opinfo[(int)op].prec == prec;
    355 	    op = es->tok) {
    356 		exprtoken(es);
    357 		vasn = vl;
    358 		if (op != O_ASN)
    359 			/* vl may not have a value yet */
    360 			vl = intvar(es, vl);
    361 		if (IS_ASSIGNOP(op)) {
    362 			if (!es->noassign)
    363 				assign_check(es, op, vasn);
    364 			vr = intvar(es, evalexpr(es, P_ASSIGN));
    365 		} else if (op != O_TERN && op != O_LAND && op != O_LOR)
    366 			vr = intvar(es, evalexpr(es, prec - 1));
    367 		if ((op == O_DIV || op == O_MOD || op == O_DIVASN ||
    368 		    op == O_MODASN) && vr->val.i == 0) {
    369 			if (es->noassign)
    370 				vr->val.i = 1;
    371 			else
    372 				evalerr(es, ET_STR, "zero divisor");
    373 		}
    374 		switch ((int)op) {
    375 		case O_TIMES:
    376 		case O_TIMESASN:
    377 			res = bivui(vl, *, vr);
    378 			break;
    379 		case O_DIV:
    380 		case O_DIVASN:
    381 #if !HAVE_SILENT_IDIVWRAPV
    382 			/*
    383 			 * we are doing the comparisons here for the
    384 			 * signed arithmetics (!es->natural) case,
    385 			 * but the exact value checks and the bypass
    386 			 * case assignments are done unsignedly as
    387 			 * several compilers bitch around otherwise
    388 			 */
    389 			if (!es->natural &&
    390 			    vl->val.u == IDIVWRAPV_VL &&
    391 			    vr->val.u == IDIVWRAPV_VR) {
    392 				/* -2147483648 / -1 = 2147483648 */
    393 				/* this ^ is really (1 << 31) though */
    394 				res = IDIVWRAPV_VL;
    395 			} else
    396 #endif
    397 				res = bivui(vl, /, vr);
    398 			break;
    399 		case O_MOD:
    400 		case O_MODASN:
    401 #if !HAVE_SILENT_IDIVWRAPV
    402 			/* see O_DIV / O_DIVASN for the reason behind this */
    403 			if (!es->natural &&
    404 			    vl->val.u == IDIVWRAPV_VL &&
    405 			    vr->val.u == IDIVWRAPV_VR) {
    406 				/* -2147483648 % -1 = 0 */
    407 				res = 0;
    408 			} else
    409 #endif
    410 				res = bivui(vl, %, vr);
    411 			break;
    412 		case O_PLUS:
    413 		case O_PLUSASN:
    414 			res = bivui(vl, +, vr);
    415 			break;
    416 		case O_MINUS:
    417 		case O_MINUSASN:
    418 			res = bivui(vl, -, vr);
    419 			break;
    420 		case O_LSHIFT:
    421 		case O_LSHIFTASN:
    422 			res = bivui(vl, <<, vr);
    423 			break;
    424 		case O_RSHIFT:
    425 		case O_RSHIFTASN:
    426 			res = bivui(vl, >>, vr);
    427 			break;
    428 		case O_LT:
    429 			res = bivui(vl, <, vr);
    430 			break;
    431 		case O_LE:
    432 			res = bivui(vl, <=, vr);
    433 			break;
    434 		case O_GT:
    435 			res = bivui(vl, >, vr);
    436 			break;
    437 		case O_GE:
    438 			res = bivui(vl, >=, vr);
    439 			break;
    440 		case O_EQ:
    441 			res = bivui(vl, ==, vr);
    442 			break;
    443 		case O_NE:
    444 			res = bivui(vl, !=, vr);
    445 			break;
    446 		case O_BAND:
    447 		case O_BANDASN:
    448 			res = bivui(vl, &, vr);
    449 			break;
    450 		case O_BXOR:
    451 		case O_BXORASN:
    452 			res = bivui(vl, ^, vr);
    453 			break;
    454 		case O_BOR:
    455 		case O_BORASN:
    456 			res = bivui(vl, |, vr);
    457 			break;
    458 		case O_LAND:
    459 			if (!vl->val.i)
    460 				es->noassign++;
    461 			vr = intvar(es, evalexpr(es, prec - 1));
    462 			res = bivui(vl, &&, vr);
    463 			if (!vl->val.i)
    464 				es->noassign--;
    465 			break;
    466 		case O_LOR:
    467 			if (vl->val.i)
    468 				es->noassign++;
    469 			vr = intvar(es, evalexpr(es, prec - 1));
    470 			res = bivui(vl, ||, vr);
    471 			if (vl->val.i)
    472 				es->noassign--;
    473 			break;
    474 		case O_TERN:
    475 			{
    476 				bool ev = vl->val.i != 0;
    477 
    478 				if (!ev)
    479 					es->noassign++;
    480 				vl = evalexpr(es, MAX_PREC);
    481 				if (!ev)
    482 					es->noassign--;
    483 				if (es->tok != CTERN)
    484 					evalerr(es, ET_STR, "missing :");
    485 				exprtoken(es);
    486 				if (ev)
    487 					es->noassign++;
    488 				vr = evalexpr(es, P_TERN);
    489 				if (ev)
    490 					es->noassign--;
    491 				vl = ev ? vl : vr;
    492 			}
    493 			break;
    494 		case O_ASN:
    495 			res = vr->val.u;
    496 			break;
    497 		case O_COMMA:
    498 			res = vr->val.u;
    499 			break;
    500 		}
    501 		if (IS_ASSIGNOP(op)) {
    502 			vr->val.u = res;
    503 			if (!es->noassign) {
    504 				if (vasn->flag & INTEGER)
    505 					setint_v(vasn, vr, es->arith);
    506 				else
    507 					setint(vasn, (mksh_ari_t)res);
    508 			}
    509 			vl = vr;
    510 		} else if (op != O_TERN)
    511 			vl->val.u = res;
    512 	}
    513 	return (vl);
    514 }
    515 
    516 static void
    517 exprtoken(Expr_state *es)
    518 {
    519 	const char *cp = es->tokp;
    520 	int c;
    521 	char *tvar;
    522 
    523 	/* skip white space */
    524  skip_spaces:
    525 	while ((c = *cp), ksh_isspace(c))
    526 		++cp;
    527 	if (es->tokp == es->expression && c == '#') {
    528 		/* expression begins with # */
    529 		es->natural = true;	/* switch to unsigned */
    530 		++cp;
    531 		goto skip_spaces;
    532 	}
    533 	es->tokp = cp;
    534 
    535 	if (c == '\0')
    536 		es->tok = END;
    537 	else if (ksh_isalphx(c)) {
    538 		for (; ksh_isalnux(c); c = *cp)
    539 			cp++;
    540 		if (c == '[') {
    541 			size_t len;
    542 
    543 			len = array_ref_len(cp);
    544 			if (len == 0)
    545 				evalerr(es, ET_STR, "missing ]");
    546 			cp += len;
    547 		} else if (c == '(' /*)*/ ) {
    548 			/* todo: add math functions (all take single argument):
    549 			 * abs acos asin atan cos cosh exp int log sin sinh sqrt
    550 			 * tan tanh
    551 			 */
    552 			;
    553 		}
    554 		if (es->noassign) {
    555 			es->val = tempvar();
    556 			es->val->flag |= EXPRLVALUE;
    557 		} else {
    558 			strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
    559 			es->val = global(tvar);
    560 			afree(tvar, ATEMP);
    561 		}
    562 		es->tok = VAR;
    563 	} else if (c == '1' && cp[1] == '#') {
    564 		cp += 2;
    565 		cp += utf_ptradj(cp);
    566 		strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
    567 		goto process_tvar;
    568 #ifndef MKSH_SMALL
    569 	} else if (c == '\'') {
    570 		++cp;
    571 		cp += utf_ptradj(cp);
    572 		if (*cp++ != '\'')
    573 			evalerr(es, ET_STR,
    574 			    "multi-character character constant");
    575 		/* 'x' -> 1#x (x = one multibyte character) */
    576 		c = cp - es->tokp;
    577 		tvar = alloc(c + /* NUL */ 1, ATEMP);
    578 		tvar[0] = '1';
    579 		tvar[1] = '#';
    580 		memcpy(tvar + 2, es->tokp + 1, c - 2);
    581 		tvar[c] = '\0';
    582 		goto process_tvar;
    583 #endif
    584 	} else if (ksh_isdigit(c)) {
    585 		while (c != '_' && (ksh_isalnux(c) || c == '#'))
    586 			c = *cp++;
    587 		strndupx(tvar, es->tokp, --cp - es->tokp, ATEMP);
    588  process_tvar:
    589 		es->val = tempvar();
    590 		es->val->flag &= ~INTEGER;
    591 		es->val->type = 0;
    592 		es->val->val.s = tvar;
    593 		if (setint_v(es->val, es->val, es->arith) == NULL)
    594 			evalerr(es, ET_BADLIT, tvar);
    595 		afree(tvar, ATEMP);
    596 		es->tok = LIT;
    597 	} else {
    598 		int i, n0;
    599 
    600 		for (i = 0; (n0 = opinfo[i].name[0]); i++)
    601 			if (c == n0 && strncmp(cp, opinfo[i].name,
    602 			    (size_t)opinfo[i].len) == 0) {
    603 				es->tok = (enum token)i;
    604 				cp += opinfo[i].len;
    605 				break;
    606 			}
    607 		if (!n0)
    608 			es->tok = BAD;
    609 	}
    610 	es->tokp = cp;
    611 }
    612 
    613 /* Do a ++ or -- operation */
    614 static struct tbl *
    615 do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, bool is_prefix)
    616 {
    617 	struct tbl *vl;
    618 	mksh_ari_t oval;
    619 
    620 	assign_check(es, op, vasn);
    621 
    622 	vl = intvar(es, vasn);
    623 	oval = vl->val.i;
    624 	if (op == O_PLUSPLUS) {
    625 		if (es->natural)
    626 			++vl->val.u;
    627 		else
    628 			++vl->val.i;
    629 	} else {
    630 		if (es->natural)
    631 			--vl->val.u;
    632 		else
    633 			--vl->val.i;
    634 	}
    635 	if (vasn->flag & INTEGER)
    636 		setint_v(vasn, vl, es->arith);
    637 	else
    638 		setint(vasn, vl->val.i);
    639 	if (!is_prefix)
    640 		/* undo the increment/decrement */
    641 		vl->val.i = oval;
    642 
    643 	return (vl);
    644 }
    645 
    646 static void
    647 assign_check(Expr_state *es, enum token op, struct tbl *vasn)
    648 {
    649 	if (es->tok == END || !vasn ||
    650 	    (vasn->name[0] == '\0' && !(vasn->flag & EXPRLVALUE)))
    651 		evalerr(es, ET_LVALUE, opinfo[(int)op].name);
    652 	else if (vasn->flag & RDONLY)
    653 		evalerr(es, ET_RDONLY, opinfo[(int)op].name);
    654 }
    655 
    656 struct tbl *
    657 tempvar(void)
    658 {
    659 	struct tbl *vp;
    660 
    661 	vp = alloc(sizeof(struct tbl), ATEMP);
    662 	vp->flag = ISSET|INTEGER;
    663 	vp->type = 0;
    664 	vp->areap = ATEMP;
    665 	vp->ua.hval = 0;
    666 	vp->val.i = 0;
    667 	vp->name[0] = '\0';
    668 	return (vp);
    669 }
    670 
    671 /* cast (string) variable to temporary integer variable */
    672 static struct tbl *
    673 intvar(Expr_state *es, struct tbl *vp)
    674 {
    675 	struct tbl *vq;
    676 
    677 	/* try to avoid replacing a temp var with another temp var */
    678 	if (vp->name[0] == '\0' &&
    679 	    (vp->flag & (ISSET|INTEGER|EXPRLVALUE)) == (ISSET|INTEGER))
    680 		return (vp);
    681 
    682 	vq = tempvar();
    683 	if (setint_v(vq, vp, es->arith) == NULL) {
    684 		if (vp->flag & EXPRINEVAL)
    685 			evalerr(es, ET_RECURSIVE, vp->name);
    686 		es->evaling = vp;
    687 		vp->flag |= EXPRINEVAL;
    688 		v_evaluate(vq, str_val(vp), KSH_UNWIND_ERROR, es->arith);
    689 		vp->flag &= ~EXPRINEVAL;
    690 		es->evaling = NULL;
    691 	}
    692 	return (vq);
    693 }
    694 
    695 
    696 /*
    697  * UTF-8 support code: high-level functions
    698  */
    699 
    700 int
    701 utf_widthadj(const char *src, const char **dst)
    702 {
    703 	size_t len;
    704 	unsigned int wc;
    705 	int width;
    706 
    707 	if (!UTFMODE || (len = utf_mbtowc(&wc, src)) == (size_t)-1 ||
    708 	    wc == 0)
    709 		len = width = 1;
    710 	else if ((width = utf_wcwidth(wc)) < 0)
    711 		/* XXX use 2 for x_zotc3 here? */
    712 		width = 1;
    713 
    714 	if (dst)
    715 		*dst = src + len;
    716 	return (width);
    717 }
    718 
    719 size_t
    720 utf_mbswidth(const char *s)
    721 {
    722 	size_t len, width = 0;
    723 	unsigned int wc;
    724 	int cw;
    725 
    726 	if (!UTFMODE)
    727 		return (strlen(s));
    728 
    729 	while (*s)
    730 		if (((len = utf_mbtowc(&wc, s)) == (size_t)-1) ||
    731 		    ((cw = utf_wcwidth(wc)) == -1)) {
    732 			s++;
    733 			width += 1;
    734 		} else {
    735 			s += len;
    736 			width += cw;
    737 		}
    738 	return (width);
    739 }
    740 
    741 const char *
    742 utf_skipcols(const char *p, int cols)
    743 {
    744 	int c = 0;
    745 
    746 	while (c < cols) {
    747 		if (!*p)
    748 			return (p + cols - c);
    749 		c += utf_widthadj(p, &p);
    750 	}
    751 	return (p);
    752 }
    753 
    754 size_t
    755 utf_ptradj(const char *src)
    756 {
    757 	register size_t n;
    758 
    759 	if (!UTFMODE ||
    760 	    *(const unsigned char *)(src) < 0xC2 ||
    761 	    (n = utf_mbtowc(NULL, src)) == (size_t)-1)
    762 		n = 1;
    763 	return (n);
    764 }
    765 
    766 /*
    767  * UTF-8 support code: low-level functions
    768  */
    769 
    770 /* CESU-8 multibyte and wide character conversion crafted for mksh */
    771 
    772 size_t
    773 utf_mbtowc(unsigned int *dst, const char *src)
    774 {
    775 	const unsigned char *s = (const unsigned char *)src;
    776 	unsigned int c, wc;
    777 
    778 	if ((wc = *s++) < 0x80) {
    779  out:
    780 		if (dst != NULL)
    781 			*dst = wc;
    782 		return (wc ? ((const char *)s - src) : 0);
    783 	}
    784 	if (wc < 0xC2 || wc >= 0xF0)
    785 		/* < 0xC0: spurious second byte */
    786 		/* < 0xC2: non-minimalistic mapping error in 2-byte seqs */
    787 		/* > 0xEF: beyond BMP */
    788 		goto ilseq;
    789 
    790 	if (wc < 0xE0) {
    791 		wc = (wc & 0x1F) << 6;
    792 		if (((c = *s++) & 0xC0) != 0x80)
    793 			goto ilseq;
    794 		wc |= c & 0x3F;
    795 		goto out;
    796 	}
    797 
    798 	wc = (wc & 0x0F) << 12;
    799 
    800 	if (((c = *s++) & 0xC0) != 0x80)
    801 		goto ilseq;
    802 	wc |= (c & 0x3F) << 6;
    803 
    804 	if (((c = *s++) & 0xC0) != 0x80)
    805 		goto ilseq;
    806 	wc |= c & 0x3F;
    807 
    808 	/* Check for non-minimalistic mapping error in 3-byte seqs */
    809 	if (wc >= 0x0800 && wc <= 0xFFFD)
    810 		goto out;
    811  ilseq:
    812 	return ((size_t)(-1));
    813 }
    814 
    815 size_t
    816 utf_wctomb(char *dst, unsigned int wc)
    817 {
    818 	unsigned char *d;
    819 
    820 	if (wc < 0x80) {
    821 		*dst = wc;
    822 		return (1);
    823 	}
    824 
    825 	d = (unsigned char *)dst;
    826 	if (wc < 0x0800)
    827 		*d++ = (wc >> 6) | 0xC0;
    828 	else {
    829 		*d++ = ((wc = wc > 0xFFFD ? 0xFFFD : wc) >> 12) | 0xE0;
    830 		*d++ = ((wc >> 6) & 0x3F) | 0x80;
    831 	}
    832 	*d++ = (wc & 0x3F) | 0x80;
    833 	return ((char *)d - dst);
    834 }
    835 
    836 
    837 #ifndef MKSH_mirbsd_wcwidth
    838 /* --- begin of wcwidth.c excerpt --- */
    839 /*-
    840  * Markus Kuhn -- 2007-05-26 (Unicode 5.0)
    841  *
    842  * Permission to use, copy, modify, and distribute this software
    843  * for any purpose and without fee is hereby granted. The author
    844  * disclaims all warranties with regard to this software.
    845  */
    846 
    847 __RCSID("$miros: src/lib/libc/i18n/wcwidth.c,v 1.11 2012/09/01 23:46:43 tg Exp $");
    848 
    849 int
    850 utf_wcwidth(unsigned int c)
    851 {
    852 	static const struct cbset {
    853 		unsigned short first;
    854 		unsigned short last;
    855 	} comb[] = {
    856 		/* Unicode 6.1.0 BMP */
    857 		{ 0x0300, 0x036F }, { 0x0483, 0x0489 }, { 0x0591, 0x05BD },
    858 		{ 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, { 0x05C4, 0x05C5 },
    859 		{ 0x05C7, 0x05C7 }, { 0x0600, 0x0604 }, { 0x0610, 0x061A },
    860 		{ 0x064B, 0x065F }, { 0x0670, 0x0670 }, { 0x06D6, 0x06DD },
    861 		{ 0x06DF, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED },
    862 		{ 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A },
    863 		{ 0x07A6, 0x07B0 }, { 0x07EB, 0x07F3 }, { 0x0816, 0x0819 },
    864 		{ 0x081B, 0x0823 }, { 0x0825, 0x0827 }, { 0x0829, 0x082D },
    865 		{ 0x0859, 0x085B }, { 0x08E4, 0x08FE }, { 0x0900, 0x0902 },
    866 		{ 0x093A, 0x093A }, { 0x093C, 0x093C }, { 0x0941, 0x0948 },
    867 		{ 0x094D, 0x094D }, { 0x0951, 0x0957 }, { 0x0962, 0x0963 },
    868 		{ 0x0981, 0x0981 }, { 0x09BC, 0x09BC }, { 0x09C1, 0x09C4 },
    869 		{ 0x09CD, 0x09CD }, { 0x09E2, 0x09E3 }, { 0x0A01, 0x0A02 },
    870 		{ 0x0A3C, 0x0A3C }, { 0x0A41, 0x0A42 }, { 0x0A47, 0x0A48 },
    871 		{ 0x0A4B, 0x0A4D }, { 0x0A51, 0x0A51 }, { 0x0A70, 0x0A71 },
    872 		{ 0x0A75, 0x0A75 }, { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC },
    873 		{ 0x0AC1, 0x0AC5 }, { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD },
    874 		{ 0x0AE2, 0x0AE3 }, { 0x0B01, 0x0B01 }, { 0x0B3C, 0x0B3C },
    875 		{ 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B44 }, { 0x0B4D, 0x0B4D },
    876 		{ 0x0B56, 0x0B56 }, { 0x0B62, 0x0B63 }, { 0x0B82, 0x0B82 },
    877 		{ 0x0BC0, 0x0BC0 }, { 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 },
    878 		{ 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 },
    879 		{ 0x0C62, 0x0C63 }, { 0x0CBC, 0x0CBC }, { 0x0CBF, 0x0CBF },
    880 		{ 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD }, { 0x0CE2, 0x0CE3 },
    881 		{ 0x0D41, 0x0D44 }, { 0x0D4D, 0x0D4D }, { 0x0D62, 0x0D63 },
    882 		{ 0x0DCA, 0x0DCA }, { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 },
    883 		{ 0x0E31, 0x0E31 }, { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E },
    884 		{ 0x0EB1, 0x0EB1 }, { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC },
    885 		{ 0x0EC8, 0x0ECD }, { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 },
    886 		{ 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E },
    887 		{ 0x0F80, 0x0F84 }, { 0x0F86, 0x0F87 }, { 0x0F8D, 0x0F97 },
    888 		{ 0x0F99, 0x0FBC }, { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 },
    889 		{ 0x1032, 0x1037 }, { 0x1039, 0x103A }, { 0x103D, 0x103E },
    890 		{ 0x1058, 0x1059 }, { 0x105E, 0x1060 }, { 0x1071, 0x1074 },
    891 		{ 0x1082, 0x1082 }, { 0x1085, 0x1086 }, { 0x108D, 0x108D },
    892 		{ 0x109D, 0x109D }, { 0x1160, 0x11FF }, { 0x135D, 0x135F },
    893 		{ 0x1712, 0x1714 }, { 0x1732, 0x1734 }, { 0x1752, 0x1753 },
    894 		{ 0x1772, 0x1773 }, { 0x17B4, 0x17B5 }, { 0x17B7, 0x17BD },
    895 		{ 0x17C6, 0x17C6 }, { 0x17C9, 0x17D3 }, { 0x17DD, 0x17DD },
    896 		{ 0x180B, 0x180D }, { 0x18A9, 0x18A9 }, { 0x1920, 0x1922 },
    897 		{ 0x1927, 0x1928 }, { 0x1932, 0x1932 }, { 0x1939, 0x193B },
    898 		{ 0x1A17, 0x1A18 }, { 0x1A56, 0x1A56 }, { 0x1A58, 0x1A5E },
    899 		{ 0x1A60, 0x1A60 }, { 0x1A62, 0x1A62 }, { 0x1A65, 0x1A6C },
    900 		{ 0x1A73, 0x1A7C }, { 0x1A7F, 0x1A7F }, { 0x1B00, 0x1B03 },
    901 		{ 0x1B34, 0x1B34 }, { 0x1B36, 0x1B3A }, { 0x1B3C, 0x1B3C },
    902 		{ 0x1B42, 0x1B42 }, { 0x1B6B, 0x1B73 }, { 0x1B80, 0x1B81 },
    903 		{ 0x1BA2, 0x1BA5 }, { 0x1BA8, 0x1BA9 }, { 0x1BAB, 0x1BAB },
    904 		{ 0x1BE6, 0x1BE6 }, { 0x1BE8, 0x1BE9 }, { 0x1BED, 0x1BED },
    905 		{ 0x1BEF, 0x1BF1 }, { 0x1C2C, 0x1C33 }, { 0x1C36, 0x1C37 },
    906 		{ 0x1CD0, 0x1CD2 }, { 0x1CD4, 0x1CE0 }, { 0x1CE2, 0x1CE8 },
    907 		{ 0x1CED, 0x1CED }, { 0x1CF4, 0x1CF4 }, { 0x1DC0, 0x1DE6 },
    908 		{ 0x1DFC, 0x1DFF }, { 0x200B, 0x200F }, { 0x202A, 0x202E },
    909 		{ 0x2060, 0x2064 }, { 0x206A, 0x206F }, { 0x20D0, 0x20F0 },
    910 		{ 0x2CEF, 0x2CF1 }, { 0x2D7F, 0x2D7F }, { 0x2DE0, 0x2DFF },
    911 		{ 0x302A, 0x302D }, { 0x3099, 0x309A }, { 0xA66F, 0xA672 },
    912 		{ 0xA674, 0xA67D }, { 0xA69F, 0xA69F }, { 0xA6F0, 0xA6F1 },
    913 		{ 0xA802, 0xA802 }, { 0xA806, 0xA806 }, { 0xA80B, 0xA80B },
    914 		{ 0xA825, 0xA826 }, { 0xA8C4, 0xA8C4 }, { 0xA8E0, 0xA8F1 },
    915 		{ 0xA926, 0xA92D }, { 0xA947, 0xA951 }, { 0xA980, 0xA982 },
    916 		{ 0xA9B3, 0xA9B3 }, { 0xA9B6, 0xA9B9 }, { 0xA9BC, 0xA9BC },
    917 		{ 0xAA29, 0xAA2E }, { 0xAA31, 0xAA32 }, { 0xAA35, 0xAA36 },
    918 		{ 0xAA43, 0xAA43 }, { 0xAA4C, 0xAA4C }, { 0xAAB0, 0xAAB0 },
    919 		{ 0xAAB2, 0xAAB4 }, { 0xAAB7, 0xAAB8 }, { 0xAABE, 0xAABF },
    920 		{ 0xAAC1, 0xAAC1 }, { 0xAAEC, 0xAAED }, { 0xAAF6, 0xAAF6 },
    921 		{ 0xABE5, 0xABE5 }, { 0xABE8, 0xABE8 }, { 0xABED, 0xABED },
    922 		{ 0xFB1E, 0xFB1E }, { 0xFE00, 0xFE0F }, { 0xFE20, 0xFE26 },
    923 		{ 0xFEFF, 0xFEFF }, { 0xFFF9, 0xFFFB }
    924 	};
    925 	size_t min = 0, mid, max = NELEM(comb) - 1;
    926 
    927 	/* test for 8-bit control characters */
    928 	if (c < 32 || (c >= 0x7F && c < 0xA0))
    929 		return (c ? -1 : 0);
    930 
    931 	/* binary search in table of non-spacing characters */
    932 	if (c >= comb[0].first && c <= comb[max].last)
    933 		while (max >= min) {
    934 			mid = (min + max) / 2;
    935 			if (c > comb[mid].last)
    936 				min = mid + 1;
    937 			else if (c < comb[mid].first)
    938 				max = mid - 1;
    939 			else
    940 				return (0);
    941 		}
    942 
    943 	/* if we arrive here, c is not a combining or C0/C1 control char */
    944 
    945 	return ((c >= 0x1100 && (
    946 	    c <= 0x115F || /* Hangul Jamo init. consonants */
    947 	    c == 0x2329 || c == 0x232A ||
    948 	    (c >= 0x2E80 && c <= 0xA4CF && c != 0x303F) || /* CJK ... Yi */
    949 	    (c >= 0xAC00 && c <= 0xD7A3) || /* Hangul Syllables */
    950 	    (c >= 0xF900 && c <= 0xFAFF) || /* CJK Compatibility Ideographs */
    951 	    (c >= 0xFE10 && c <= 0xFE19) || /* Vertical forms */
    952 	    (c >= 0xFE30 && c <= 0xFE6F) || /* CJK Compatibility Forms */
    953 	    (c >= 0xFF00 && c <= 0xFF60) || /* Fullwidth Forms */
    954 	    (c >= 0xFFE0 && c <= 0xFFE6))) ? 2 : 1);
    955 }
    956 /* --- end of wcwidth.c excerpt --- */
    957 #endif
    958 
    959 /*
    960  * Wrapper around access(2) because it says root can execute everything
    961  * on some operating systems. Does not set errno, no user needs it. Use
    962  * this iff mode can have the X_OK bit set, access otherwise.
    963  */
    964 int
    965 ksh_access(const char *fn, int mode)
    966 {
    967 	int rv;
    968 	struct stat sb;
    969 
    970 	if ((rv = access(fn, mode)) == 0 && kshuid == 0 && (mode & X_OK) &&
    971 	    (rv = stat(fn, &sb)) == 0 && !S_ISDIR(sb.st_mode) &&
    972 	    (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
    973 		rv = -1;
    974 
    975 	return (rv);
    976 }
    977