Line | Count | Source |
1 | | /* |
2 | | * Arithmetic code ripped out of ash shell for code sharing. |
3 | | * |
4 | | * This code is derived from software contributed to Berkeley by |
5 | | * Kenneth Almquist. |
6 | | * |
7 | | * Original BSD copyright notice is retained at the end of this file. |
8 | | * |
9 | | * Copyright (c) 1989, 1991, 1993, 1994 |
10 | | * The Regents of the University of California. All rights reserved. |
11 | | * |
12 | | * Copyright (c) 1997-2005 Herbert Xu <herbert@gondor.apana.org.au> |
13 | | * was re-ported from NetBSD and debianized. |
14 | | * |
15 | | * rewrite arith.y to micro stack based cryptic algorithm by |
16 | | * Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com> |
17 | | * |
18 | | * Modified by Paul Mundt <lethal@linux-sh.org> (c) 2004 to support |
19 | | * dynamic variables. |
20 | | * |
21 | | * Modified by Vladimir Oleynik <dzo@simtreas.ru> (c) 2001-2005 to be |
22 | | * used in busybox and size optimizations, |
23 | | * rewrote arith (see notes to this), added locale support, |
24 | | * rewrote dynamic variables. |
25 | | * |
26 | | * Licensed under GPLv2 or later, see file LICENSE in this source tree. |
27 | | */ |
28 | | /* Copyright (c) 2001 Aaron Lehmann <aaronl@vitelus.com> |
29 | | * |
30 | | * Permission is hereby granted, free of charge, to any person obtaining |
31 | | * a copy of this software and associated documentation files (the |
32 | | * "Software"), to deal in the Software without restriction, including |
33 | | * without limitation the rights to use, copy, modify, merge, publish, |
34 | | * distribute, sublicense, and/or sell copies of the Software, and to |
35 | | * permit persons to whom the Software is furnished to do so, subject to |
36 | | * the following conditions: |
37 | | * |
38 | | * The above copyright notice and this permission notice shall be |
39 | | * included in all copies or substantial portions of the Software. |
40 | | * |
41 | | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
42 | | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
43 | | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
44 | | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
45 | | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
46 | | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
47 | | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
48 | | */ |
49 | | |
50 | | /* This is my infix parser/evaluator. It is optimized for size, intended |
51 | | * as a replacement for yacc-based parsers. However, it may well be faster |
52 | | * than a comparable parser written in yacc. The supported operators are |
53 | | * listed in #defines below. Parens, order of operations, and error handling |
54 | | * are supported. This code is thread safe. The exact expression format should |
55 | | * be that which POSIX specifies for shells. |
56 | | * |
57 | | * The code uses a simple two-stack algorithm. See |
58 | | * http://www.onthenet.com.au/~grahamis/int2008/week02/lect02.html |
59 | | * for a detailed explanation of the infix-to-postfix algorithm on which |
60 | | * this is based (this code differs in that it applies operators immediately |
61 | | * to the stack instead of adding them to a queue to end up with an |
62 | | * expression). |
63 | | */ |
64 | | |
65 | | /* |
66 | | * Aug 24, 2001 Manuel Novoa III |
67 | | * |
68 | | * Reduced the generated code size by about 30% (i386) and fixed several bugs. |
69 | | * |
70 | | * 1) In arith_apply(): |
71 | | * a) Cached values of *numptr and &(numptr[-1]). |
72 | | * b) Removed redundant test for zero denominator. |
73 | | * |
74 | | * 2) In arith(): |
75 | | * a) Eliminated redundant code for processing operator tokens by moving |
76 | | * to a table-based implementation. Also folded handling of parens |
77 | | * into the table. |
78 | | * b) Combined all 3 loops which called arith_apply to reduce generated |
79 | | * code size at the cost of speed. |
80 | | * |
81 | | * 3) The following expressions were treated as valid by the original code: |
82 | | * 1() , 0! , 1 ( *3 ) . |
83 | | * These bugs have been fixed by internally enclosing the expression in |
84 | | * parens and then checking that all binary ops and right parens are |
85 | | * preceded by a valid expression (NUM_TOKEN). |
86 | | * |
87 | | * Note: It may be desirable to replace Aaron's test for whitespace with |
88 | | * ctype's isspace() if it is used by another busybox applet or if additional |
89 | | * whitespace chars should be considered. Look below the "#include"s for a |
90 | | * precompiler test. |
91 | | */ |
92 | | /* |
93 | | * Aug 26, 2001 Manuel Novoa III |
94 | | * |
95 | | * Return 0 for null expressions. Pointed out by Vladimir Oleynik. |
96 | | * |
97 | | * Merge in Aaron's comments previously posted to the busybox list, |
98 | | * modified slightly to take account of my changes to the code. |
99 | | * |
100 | | */ |
101 | | /* |
102 | | * (C) 2003 Vladimir Oleynik <dzo@simtreas.ru> |
103 | | * |
104 | | * - allow access to variable, |
105 | | * use recursive value indirection: c="2*2"; a="c"; echo $((a+=2)) produce 6 |
106 | | * - implement assign syntax (VAR=expr, +=, *= etc) |
107 | | * - implement exponentiation (** operator) |
108 | | * - implement comma separated - expr, expr |
109 | | * - implement ++expr --expr expr++ expr-- |
110 | | * - implement expr ? expr : expr (but second expr is always calculated) |
111 | | * - allow hexadecimal and octal numbers |
112 | | * - restore lost XOR operator |
113 | | * - protect $((num num)) as true zero expr (Manuel's error) |
114 | | * - always use special isspace(), see comment from bash ;-) |
115 | | */ |
116 | | #include <common.h> |
117 | | #include <malloc.h> |
118 | | #include <linux/ctype.h> |
119 | | #include <linux/string.h> |
120 | | #include <libbb.h> |
121 | | #include <errno.h> |
122 | | #include <math.h> |
123 | | |
124 | 0 | #define lookupvar (math_state->lookupvar) |
125 | 0 | #define setvar (math_state->setvar ) |
126 | 0 | #define endofname (math_state->endofname) |
127 | | |
128 | | typedef unsigned char operator; |
129 | | |
130 | | /* An operator's token id is a bit of a bitfield. The lower 5 bits are the |
131 | | * precedence, and 3 high bits are an ID unique across operators of that |
132 | | * precedence. The ID portion is so that multiple operators can have the |
133 | | * same precedence, ensuring that the leftmost one is evaluated first. |
134 | | * Consider * and / |
135 | | */ |
136 | 0 | #define tok_decl(prec,id) (((id)<<5) | (prec)) |
137 | 0 | #define PREC(op) ((op) & 0x1F) |
138 | | |
139 | 0 | #define TOK_LPAREN tok_decl(0,0) |
140 | | |
141 | 0 | #define TOK_COMMA tok_decl(1,0) |
142 | | |
143 | | /* All assignments are right associative and have the same precedence, |
144 | | * but there are 11 of them, which doesn't fit into 3 bits for unique id. |
145 | | * Abusing another precedence level: |
146 | | */ |
147 | 0 | #define TOK_ASSIGN tok_decl(2,0) |
148 | 0 | #define TOK_AND_ASSIGN tok_decl(2,1) |
149 | 0 | #define TOK_OR_ASSIGN tok_decl(2,2) |
150 | 0 | #define TOK_XOR_ASSIGN tok_decl(2,3) |
151 | 0 | #define TOK_PLUS_ASSIGN tok_decl(2,4) |
152 | 0 | #define TOK_MINUS_ASSIGN tok_decl(2,5) |
153 | 0 | #define TOK_LSHIFT_ASSIGN tok_decl(2,6) |
154 | 0 | #define TOK_RSHIFT_ASSIGN tok_decl(2,7) |
155 | | |
156 | 0 | #define TOK_MUL_ASSIGN tok_decl(3,0) |
157 | 0 | #define TOK_DIV_ASSIGN tok_decl(3,1) |
158 | 0 | #define TOK_REM_ASSIGN tok_decl(3,2) |
159 | | |
160 | 0 | #define fix_assignment_prec(prec) do { if (prec == 3) prec = 2; } while (0) |
161 | | |
162 | | /* Ternary conditional operator is right associative too */ |
163 | 0 | #define TOK_CONDITIONAL tok_decl(4,0) |
164 | 0 | #define TOK_CONDITIONAL_SEP tok_decl(4,1) |
165 | | |
166 | 0 | #define TOK_OR tok_decl(5,0) |
167 | | |
168 | 0 | #define TOK_AND tok_decl(6,0) |
169 | | |
170 | 0 | #define TOK_BOR tok_decl(7,0) |
171 | | |
172 | 0 | #define TOK_BXOR tok_decl(8,0) |
173 | | |
174 | 0 | #define TOK_BAND tok_decl(9,0) |
175 | | |
176 | 0 | #define TOK_EQ tok_decl(10,0) |
177 | 0 | #define TOK_NE tok_decl(10,1) |
178 | | |
179 | 0 | #define TOK_LT tok_decl(11,0) |
180 | 0 | #define TOK_GT tok_decl(11,1) |
181 | 0 | #define TOK_GE tok_decl(11,2) |
182 | 0 | #define TOK_LE tok_decl(11,3) |
183 | | |
184 | 0 | #define TOK_LSHIFT tok_decl(12,0) |
185 | 0 | #define TOK_RSHIFT tok_decl(12,1) |
186 | | |
187 | 0 | #define TOK_ADD tok_decl(13,0) |
188 | 0 | #define TOK_SUB tok_decl(13,1) |
189 | | |
190 | 0 | #define TOK_MUL tok_decl(14,0) |
191 | 0 | #define TOK_DIV tok_decl(14,1) |
192 | 0 | #define TOK_REM tok_decl(14,2) |
193 | | |
194 | | /* Exponent is right associative */ |
195 | 0 | #define TOK_EXPONENT tok_decl(15,1) |
196 | | |
197 | | /* Unary operators */ |
198 | 0 | #define UNARYPREC 16 |
199 | 0 | #define TOK_BNOT tok_decl(UNARYPREC,0) |
200 | 0 | #define TOK_NOT tok_decl(UNARYPREC,1) |
201 | | |
202 | 0 | #define TOK_UMINUS tok_decl(UNARYPREC+1,0) |
203 | 0 | #define TOK_UPLUS tok_decl(UNARYPREC+1,1) |
204 | | |
205 | 0 | #define PREC_PRE (UNARYPREC+2) |
206 | | |
207 | 0 | #define TOK_PRE_INC tok_decl(PREC_PRE, 0) |
208 | 0 | #define TOK_PRE_DEC tok_decl(PREC_PRE, 1) |
209 | | |
210 | 0 | #define PREC_POST (UNARYPREC+3) |
211 | | |
212 | 0 | #define TOK_POST_INC tok_decl(PREC_POST, 0) |
213 | 0 | #define TOK_POST_DEC tok_decl(PREC_POST, 1) |
214 | | |
215 | 0 | #define SPEC_PREC (UNARYPREC+4) |
216 | | |
217 | 0 | #define TOK_NUM tok_decl(SPEC_PREC, 0) |
218 | 0 | #define TOK_RPAREN tok_decl(SPEC_PREC, 1) |
219 | | |
220 | | /* from busybox's libbb/skip_whitespace.c */ |
221 | | static char *skip_whitespace(const char *s) |
222 | 0 | { |
223 | | /* In POSIX/C locale (the only locale we care about: do we REALLY want |
224 | | * to allow Unicode whitespace in, say, .conf files? nuts!) |
225 | | * isspace is only these chars: "\t\n\v\f\r" and space. |
226 | | * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13. |
227 | | * Use that. |
228 | | */ |
229 | 0 | while (*s == ' ' || (unsigned char)(*s - 9) <= (13 - 9)) |
230 | 0 | s++; |
231 | |
|
232 | 0 | return (char *) s; |
233 | 0 | } |
234 | | |
235 | | static int is_assign_op(operator op) |
236 | 0 | { |
237 | 0 | operator prec = PREC(op); |
238 | 0 | fix_assignment_prec(prec); |
239 | |
|
240 | 0 | return prec == PREC(TOK_ASSIGN) |
241 | 0 | || prec == PREC_PRE |
242 | 0 | || prec == PREC_POST; |
243 | 0 | } |
244 | | |
245 | | static int is_right_associative(operator prec) |
246 | 0 | { |
247 | 0 | return prec == PREC(TOK_ASSIGN) |
248 | 0 | || prec == PREC(TOK_EXPONENT) |
249 | 0 | || prec == PREC(TOK_CONDITIONAL); |
250 | 0 | } |
251 | | |
252 | | typedef struct { |
253 | | arith_t val; |
254 | | /* We acquire second_val only when "expr1 : expr2" part |
255 | | * of ternary ?: op is evaluated. |
256 | | * We treat ?: as two binary ops: (expr ? (expr1 : expr2)). |
257 | | * ':' produces a new value which has two parts, val and second_val; |
258 | | * then '?' selects one of them based on its left side. |
259 | | */ |
260 | | arith_t second_val; |
261 | | char second_val_present; |
262 | | /* If NULL then it's just a number, else it's a named variable */ |
263 | | char *var; |
264 | | } var_or_num_t; |
265 | | |
266 | | typedef struct remembered_name { |
267 | | struct remembered_name *next; |
268 | | const char *var; |
269 | | } remembered_name; |
270 | | |
271 | | |
272 | | static arith_t evaluate_string(arith_state_t *math_state, const char *expr); |
273 | | |
274 | | static const char *arith_lookup_val(arith_state_t *math_state, var_or_num_t *t) |
275 | 0 | { |
276 | 0 | if (t->var) { |
277 | 0 | const char *p = lookupvar(t->var); |
278 | 0 | if (p) { |
279 | 0 | remembered_name *cur; |
280 | 0 | remembered_name cur_save; |
281 | | |
282 | | /* did we already see this name? |
283 | | * testcase: a=b; b=a; echo $((a)) |
284 | | */ |
285 | 0 | for (cur = math_state->list_of_recursed_names; cur; cur = cur->next) { |
286 | 0 | if (strcmp(cur->var, t->var) == 0) { |
287 | | /* Yes */ |
288 | 0 | return "expression recursion loop detected"; |
289 | 0 | } |
290 | 0 | } |
291 | | |
292 | | /* push current var name */ |
293 | 0 | cur = math_state->list_of_recursed_names; |
294 | 0 | cur_save.var = t->var; |
295 | 0 | cur_save.next = cur; |
296 | 0 | math_state->list_of_recursed_names = &cur_save; |
297 | | |
298 | | /* recursively evaluate p as expression */ |
299 | 0 | t->val = evaluate_string(math_state, p); |
300 | | |
301 | | /* pop current var name */ |
302 | 0 | math_state->list_of_recursed_names = cur; |
303 | |
|
304 | 0 | return math_state->errmsg; |
305 | 0 | } |
306 | | /* treat undefined var as 0 */ |
307 | 0 | t->val = 0; |
308 | 0 | } |
309 | 0 | return NULL; |
310 | 0 | } |
311 | | |
312 | | /* "Applying" a token means performing it on the top elements on the integer |
313 | | * stack. For an unary operator it will only change the top element, but a |
314 | | * binary operator will pop two arguments and push the result */ |
315 | | static const char* noinline arith_apply(arith_state_t *math_state, operator op, |
316 | | var_or_num_t *numstack, var_or_num_t **numstackptr) |
317 | 0 | { |
318 | 0 | #define NUMPTR (*numstackptr) |
319 | |
|
320 | 0 | var_or_num_t *top_of_stack; |
321 | 0 | arith_t rez; |
322 | 0 | const char *err; |
323 | | |
324 | | /* There is no operator that can work without arguments */ |
325 | 0 | if (NUMPTR == numstack) |
326 | 0 | goto err; |
327 | | |
328 | 0 | top_of_stack = NUMPTR - 1; |
329 | | |
330 | | /* Resolve name to value, if needed */ |
331 | 0 | err = arith_lookup_val(math_state, top_of_stack); |
332 | 0 | if (err) |
333 | 0 | return err; |
334 | | |
335 | 0 | rez = top_of_stack->val; |
336 | 0 | if (op == TOK_UMINUS) |
337 | 0 | rez = -rez; |
338 | 0 | else if (op == TOK_NOT) |
339 | 0 | rez = !rez; |
340 | 0 | else if (op == TOK_BNOT) |
341 | 0 | rez = ~rez; |
342 | 0 | else if (op == TOK_POST_INC || op == TOK_PRE_INC) |
343 | 0 | rez++; |
344 | 0 | else if (op == TOK_POST_DEC || op == TOK_PRE_DEC) |
345 | 0 | rez--; |
346 | 0 | else if (op != TOK_UPLUS) { |
347 | | /* Binary operators */ |
348 | 0 | arith_t right_side_val; |
349 | 0 | char bad_second_val; |
350 | | |
351 | | /* Binary operators need two arguments */ |
352 | 0 | if (top_of_stack == numstack) |
353 | 0 | goto err; |
354 | | /* ...and they pop one */ |
355 | 0 | NUMPTR = top_of_stack; /* this decrements NUMPTR */ |
356 | |
|
357 | 0 | bad_second_val = top_of_stack->second_val_present; |
358 | 0 | if (op == TOK_CONDITIONAL) { /* ? operation */ |
359 | | /* Make next if (...) protect against |
360 | | * $((expr1 ? expr2)) - that is, missing ": expr" */ |
361 | 0 | bad_second_val = !bad_second_val; |
362 | 0 | } |
363 | 0 | if (bad_second_val) { |
364 | | /* Protect against $((expr <not_?_op> expr1 : expr2)) */ |
365 | 0 | return "malformed ?: operator"; |
366 | 0 | } |
367 | | |
368 | 0 | top_of_stack--; /* now points to left side */ |
369 | |
|
370 | 0 | if (op != TOK_ASSIGN) { |
371 | | /* Resolve left side value (unless the op is '=') */ |
372 | 0 | err = arith_lookup_val(math_state, top_of_stack); |
373 | 0 | if (err) |
374 | 0 | return err; |
375 | 0 | } |
376 | | |
377 | 0 | right_side_val = rez; |
378 | 0 | rez = top_of_stack->val; |
379 | 0 | if (op == TOK_CONDITIONAL) /* ? operation */ |
380 | 0 | rez = (rez ? right_side_val : top_of_stack[1].second_val); |
381 | 0 | else if (op == TOK_CONDITIONAL_SEP) { /* : operation */ |
382 | 0 | if (top_of_stack == numstack) { |
383 | | /* Protect against $((expr : expr)) */ |
384 | 0 | return "malformed ?: operator"; |
385 | 0 | } |
386 | 0 | top_of_stack->second_val_present = op; |
387 | 0 | top_of_stack->second_val = right_side_val; |
388 | 0 | } |
389 | 0 | else if (op == TOK_BOR || op == TOK_OR_ASSIGN) |
390 | 0 | rez |= right_side_val; |
391 | 0 | else if (op == TOK_OR) |
392 | 0 | rez = right_side_val || rez; |
393 | 0 | else if (op == TOK_BAND || op == TOK_AND_ASSIGN) |
394 | 0 | rez &= right_side_val; |
395 | 0 | else if (op == TOK_BXOR || op == TOK_XOR_ASSIGN) |
396 | 0 | rez ^= right_side_val; |
397 | 0 | else if (op == TOK_AND) |
398 | 0 | rez = rez && right_side_val; |
399 | 0 | else if (op == TOK_EQ) |
400 | 0 | rez = (rez == right_side_val); |
401 | 0 | else if (op == TOK_NE) |
402 | 0 | rez = (rez != right_side_val); |
403 | 0 | else if (op == TOK_GE) |
404 | 0 | rez = (rez >= right_side_val); |
405 | 0 | else if (op == TOK_RSHIFT || op == TOK_RSHIFT_ASSIGN) |
406 | 0 | rez >>= right_side_val; |
407 | 0 | else if (op == TOK_LSHIFT || op == TOK_LSHIFT_ASSIGN) |
408 | 0 | rez <<= right_side_val; |
409 | 0 | else if (op == TOK_GT) |
410 | 0 | rez = (rez > right_side_val); |
411 | 0 | else if (op == TOK_LT) |
412 | 0 | rez = (rez < right_side_val); |
413 | 0 | else if (op == TOK_LE) |
414 | 0 | rez = (rez <= right_side_val); |
415 | 0 | else if (op == TOK_MUL || op == TOK_MUL_ASSIGN) |
416 | 0 | rez *= right_side_val; |
417 | 0 | else if (op == TOK_ADD || op == TOK_PLUS_ASSIGN) |
418 | 0 | rez += right_side_val; |
419 | 0 | else if (op == TOK_SUB || op == TOK_MINUS_ASSIGN) |
420 | 0 | rez -= right_side_val; |
421 | 0 | else if (op == TOK_ASSIGN || op == TOK_COMMA) |
422 | 0 | rez = right_side_val; |
423 | 0 | else if (op == TOK_EXPONENT) { |
424 | 0 | arith_t c; |
425 | 0 | if (right_side_val < 0) |
426 | 0 | return "exponent less than 0"; |
427 | 0 | c = 1; |
428 | 0 | while (--right_side_val >= 0) |
429 | 0 | c *= rez; |
430 | 0 | rez = c; |
431 | 0 | } |
432 | 0 | else if (right_side_val == 0) |
433 | 0 | return "divide by zero"; |
434 | 0 | else if (op == TOK_DIV || op == TOK_DIV_ASSIGN) |
435 | 0 | rez /= right_side_val; |
436 | 0 | else if (op == TOK_REM || op == TOK_REM_ASSIGN) |
437 | 0 | rez %= right_side_val; |
438 | 0 | } |
439 | | |
440 | 0 | if (is_assign_op(op)) { |
441 | 0 | char buf[sizeof(arith_t)*3 + 2]; |
442 | |
|
443 | 0 | if (top_of_stack->var == NULL) { |
444 | | /* Hmm, 1=2 ? */ |
445 | | |
446 | | /* |
447 | | * TODO: actually, bash allows ++7 but for some |
448 | | * reason it evals to 7, not 8 |
449 | | */ |
450 | 0 | goto err; |
451 | 0 | } |
452 | | /* Save to shell variable */ |
453 | 0 | sprintf(buf, ARITH_FMT, rez); |
454 | 0 | setvar(top_of_stack->var, buf); |
455 | | /* After saving, make previous value for v++ or v-- */ |
456 | 0 | if (op == TOK_POST_INC) |
457 | 0 | rez--; |
458 | 0 | else if (op == TOK_POST_DEC) |
459 | 0 | rez++; |
460 | 0 | } |
461 | | |
462 | 0 | top_of_stack->val = rez; |
463 | | /* Erase var name, it is just a number now */ |
464 | 0 | free(top_of_stack->var); |
465 | 0 | top_of_stack->var = NULL; |
466 | 0 | return NULL; |
467 | 0 | err: |
468 | 0 | return "arithmetic syntax error"; |
469 | 0 | #undef NUMPTR |
470 | 0 | } |
471 | | |
472 | | /* longest must be first */ |
473 | | static const char op_tokens[] __attribute__((aligned(1))) = { |
474 | | '<','<','=',0, TOK_LSHIFT_ASSIGN, |
475 | | '>','>','=',0, TOK_RSHIFT_ASSIGN, |
476 | | '<','<', 0, TOK_LSHIFT, |
477 | | '>','>', 0, TOK_RSHIFT, |
478 | | '|','|', 0, TOK_OR, |
479 | | '&','&', 0, TOK_AND, |
480 | | '!','=', 0, TOK_NE, |
481 | | '<','=', 0, TOK_LE, |
482 | | '>','=', 0, TOK_GE, |
483 | | '=','=', 0, TOK_EQ, |
484 | | '|','=', 0, TOK_OR_ASSIGN, |
485 | | '&','=', 0, TOK_AND_ASSIGN, |
486 | | '*','=', 0, TOK_MUL_ASSIGN, |
487 | | '/','=', 0, TOK_DIV_ASSIGN, |
488 | | '%','=', 0, TOK_REM_ASSIGN, |
489 | | '+','=', 0, TOK_PLUS_ASSIGN, |
490 | | '-','=', 0, TOK_MINUS_ASSIGN, |
491 | | '-','-', 0, TOK_POST_DEC, |
492 | | '^','=', 0, TOK_XOR_ASSIGN, |
493 | | '+','+', 0, TOK_POST_INC, |
494 | | '*','*', 0, TOK_EXPONENT, |
495 | | '!', 0, TOK_NOT, |
496 | | '<', 0, TOK_LT, |
497 | | '>', 0, TOK_GT, |
498 | | '=', 0, TOK_ASSIGN, |
499 | | '|', 0, TOK_BOR, |
500 | | '&', 0, TOK_BAND, |
501 | | '*', 0, TOK_MUL, |
502 | | '/', 0, TOK_DIV, |
503 | | '%', 0, TOK_REM, |
504 | | '+', 0, TOK_ADD, |
505 | | '-', 0, TOK_SUB, |
506 | | '^', 0, TOK_BXOR, |
507 | | /* uniq */ |
508 | | '~', 0, TOK_BNOT, |
509 | | ',', 0, TOK_COMMA, |
510 | | '?', 0, TOK_CONDITIONAL, |
511 | | ':', 0, TOK_CONDITIONAL_SEP, |
512 | | ')', 0, TOK_RPAREN, |
513 | | '(', 0, TOK_LPAREN, |
514 | | 0 |
515 | | }; |
516 | 0 | #define ptr_to_rparen (&op_tokens[sizeof(op_tokens)-7]) |
517 | | |
518 | | const char *arith_endofname(const char *name) |
519 | 0 | { |
520 | 0 | if (!is_name(*name)) |
521 | 0 | return name; |
522 | 0 | while (*++name) { |
523 | 0 | if (!is_in_name(*name)) |
524 | 0 | break; |
525 | 0 | } |
526 | 0 | return name; |
527 | 0 | } |
528 | | |
529 | | static arith_t evaluate_string(arith_state_t *math_state, const char *expr) |
530 | 0 | { |
531 | 0 | operator lasttok; |
532 | 0 | const char *errmsg; |
533 | 0 | const char *start_expr = expr = skip_whitespace(expr); |
534 | 0 | unsigned expr_len = strlen(expr) + 2; |
535 | | /* Stack of integers */ |
536 | | /* |
537 | | * The proof that there can be no more than strlen(startbuf)/2+1 |
538 | | * integers in any given correct or incorrect expression |
539 | | * is left as an exercise to the reader. |
540 | | */ |
541 | 0 | var_or_num_t *const numstack = xzalloc((expr_len / 2) * sizeof(numstack[0])); |
542 | 0 | var_or_num_t *numstackptr = numstack; |
543 | | /* Stack of operator tokens */ |
544 | 0 | operator *const stack = xzalloc(expr_len * sizeof(stack[0])); |
545 | 0 | operator *stackptr = stack; |
546 | 0 | arith_t result; |
547 | |
|
548 | 0 | if (numstack == NULL || stack == NULL) { |
549 | 0 | math_state->errmsg = "out of memory"; |
550 | 0 | return -1; |
551 | 0 | } |
552 | | |
553 | | /* Start with a left paren */ |
554 | 0 | *stackptr++ = lasttok = TOK_LPAREN; |
555 | 0 | errmsg = NULL; |
556 | |
|
557 | 0 | while (1) { |
558 | 0 | const char *p; |
559 | 0 | operator op; |
560 | 0 | operator prec; |
561 | 0 | char arithval; |
562 | |
|
563 | 0 | expr = skip_whitespace(expr); |
564 | 0 | arithval = *expr; |
565 | 0 | if (arithval == '\0') { |
566 | 0 | if (expr == start_expr) { |
567 | | /* Null expression */ |
568 | 0 | numstack->val = 0; |
569 | 0 | goto ret; |
570 | 0 | } |
571 | | |
572 | | /* |
573 | | * This is only reached after all tokens have been extracted from the |
574 | | * input stream. If there are still tokens on the operator stack, they |
575 | | * are to be applied in order. At the end, there should be a final |
576 | | * result on the integer stack |
577 | | */ |
578 | | |
579 | 0 | if (expr != ptr_to_rparen + 1) { |
580 | | /* |
581 | | * If we haven't done so already, |
582 | | * append a closing right paren |
583 | | * and let the loop process it |
584 | | */ |
585 | 0 | expr = ptr_to_rparen; |
586 | 0 | continue; |
587 | 0 | } |
588 | | /* At this point, we're done with the expression */ |
589 | 0 | if (numstackptr != numstack + 1) { |
590 | | /* ...but if there isn't, it's bad */ |
591 | 0 | goto err; |
592 | 0 | } |
593 | 0 | if (numstack->var) { |
594 | | /* expression is $((var)) only, lookup now */ |
595 | 0 | errmsg = arith_lookup_val(math_state, numstack); |
596 | 0 | free(numstack->var); |
597 | 0 | numstack->var = NULL; |
598 | 0 | } |
599 | 0 | goto ret; |
600 | 0 | } |
601 | | |
602 | 0 | p = endofname(expr); |
603 | 0 | if (p != expr) { |
604 | | /* Name */ |
605 | 0 | size_t var_name_size = (p-expr) + 1; /* +1 for NUL */ |
606 | 0 | free(numstackptr->var); |
607 | 0 | numstackptr->var = xzalloc(var_name_size); |
608 | 0 | safe_strncpy(numstackptr->var, expr, var_name_size); |
609 | 0 | expr = p; |
610 | 0 | num: |
611 | 0 | numstackptr->second_val_present = 0; |
612 | 0 | numstackptr++; |
613 | 0 | lasttok = TOK_NUM; |
614 | 0 | continue; |
615 | 0 | } |
616 | | |
617 | 0 | if (isdigit(arithval)) { |
618 | | /* Number */ |
619 | 0 | free(numstackptr->var); |
620 | 0 | numstackptr->var = NULL; |
621 | 0 | errno = 0; |
622 | 0 | numstackptr->val = strto_arith_t(expr, (char**) &expr, 0); |
623 | 0 | if (errno) |
624 | 0 | numstackptr->val = 0; /* bash compat */ |
625 | 0 | goto num; |
626 | 0 | } |
627 | | |
628 | | /* Should be an operator */ |
629 | 0 | p = op_tokens; |
630 | 0 | while (1) { |
631 | | /* |
632 | | * TODO: bash allows 7+++v, treats it as 7 + ++v |
633 | | * we treat it as 7++ + v and reject |
634 | | */ |
635 | | /* Compare expr to current op_tokens[] element */ |
636 | 0 | const char *e = expr; |
637 | 0 | while (1) { |
638 | 0 | if (*p == '\0') { |
639 | | /* Match: operator is found */ |
640 | 0 | expr = e; |
641 | 0 | goto tok_found; |
642 | 0 | } |
643 | 0 | if (*p != *e) |
644 | 0 | break; |
645 | 0 | p++; |
646 | 0 | e++; |
647 | 0 | } |
648 | | /* No match, go to next element of op_tokens[] */ |
649 | 0 | while (*p) |
650 | 0 | p++; |
651 | 0 | p += 2; /* skip NUL and TOK_foo bytes */ |
652 | 0 | if (*p == '\0') { |
653 | | /* No next element, operator not found */ |
654 | | //math_state->syntax_error_at = expr; |
655 | 0 | goto err; |
656 | 0 | } |
657 | 0 | } |
658 | 0 | tok_found: |
659 | 0 | op = p[1]; /* fetch TOK_foo value */ |
660 | | /* NB: expr now points past the operator */ |
661 | | |
662 | | /* post grammar: a++ reduce to num */ |
663 | 0 | if (lasttok == TOK_POST_INC || lasttok == TOK_POST_DEC) |
664 | 0 | lasttok = TOK_NUM; |
665 | | |
666 | | /* |
667 | | * Plus and minus are binary (not unary) _only_ if the last |
668 | | * token was a number, or a right paren (which pretends to be |
669 | | * a number, since it evaluates to one). Think about it. |
670 | | * It makes sense. |
671 | | */ |
672 | 0 | if (lasttok != TOK_NUM) { |
673 | 0 | switch (op) { |
674 | 0 | case TOK_ADD: |
675 | 0 | op = TOK_UPLUS; |
676 | 0 | break; |
677 | 0 | case TOK_SUB: |
678 | 0 | op = TOK_UMINUS; |
679 | 0 | break; |
680 | 0 | case TOK_POST_INC: |
681 | 0 | op = TOK_PRE_INC; |
682 | 0 | break; |
683 | 0 | case TOK_POST_DEC: |
684 | 0 | op = TOK_PRE_DEC; |
685 | 0 | break; |
686 | 0 | } |
687 | 0 | } |
688 | | /* |
689 | | * We don't want an unary operator to cause recursive descent on the |
690 | | * stack, because there can be many in a row and it could cause an |
691 | | * operator to be evaluated before its argument is pushed onto the |
692 | | * integer stack. |
693 | | * But for binary operators, "apply" everything on the operator |
694 | | * stack until we find an operator with a lesser priority than the |
695 | | * one we have just extracted. If op is right-associative, |
696 | | * then stop "applying" on the equal priority too. |
697 | | * Left paren is given the lowest priority so it will never be |
698 | | * "applied" in this way. |
699 | | */ |
700 | 0 | prec = PREC(op); |
701 | 0 | if ((prec > 0 && prec < UNARYPREC) || prec == SPEC_PREC) { |
702 | | /* not left paren or unary */ |
703 | 0 | if (lasttok != TOK_NUM) { |
704 | | /* binary op must be preceded by a num */ |
705 | 0 | goto err; |
706 | 0 | } |
707 | 0 | while (stackptr != stack) { |
708 | 0 | operator prev_op = *--stackptr; |
709 | 0 | if (op == TOK_RPAREN) { |
710 | | /* |
711 | | * The algorithm employed here is simple: while we don't |
712 | | * hit an open paren nor the bottom of the stack, pop |
713 | | * tokens and apply them |
714 | | */ |
715 | 0 | if (prev_op == TOK_LPAREN) { |
716 | | /* |
717 | | * Any operator directly after a |
718 | | * close paren should consider itself binary |
719 | | */ |
720 | 0 | lasttok = TOK_NUM; |
721 | 0 | goto next; |
722 | 0 | } |
723 | 0 | } else { |
724 | 0 | operator prev_prec = PREC(prev_op); |
725 | 0 | fix_assignment_prec(prec); |
726 | 0 | fix_assignment_prec(prev_prec); |
727 | 0 | if (prev_prec < prec |
728 | 0 | || (prev_prec == prec && is_right_associative(prec)) |
729 | 0 | ) { |
730 | 0 | stackptr++; |
731 | 0 | break; |
732 | 0 | } |
733 | 0 | } |
734 | 0 | errmsg = arith_apply(math_state, prev_op, numstack, &numstackptr); |
735 | 0 | if (errmsg) |
736 | 0 | goto err_with_custom_msg; |
737 | 0 | } |
738 | 0 | if (op == TOK_RPAREN) |
739 | 0 | goto err; |
740 | 0 | } |
741 | | |
742 | | /* Push this operator to the stack and remember it */ |
743 | 0 | *stackptr++ = lasttok = op; |
744 | 0 | next: ; |
745 | 0 | } /* while (1) */ |
746 | | |
747 | 0 | err: |
748 | 0 | errmsg = "arithmetic syntax error"; |
749 | 0 | err_with_custom_msg: |
750 | 0 | result = -1; |
751 | 0 | ret: |
752 | 0 | result = numstack->val; |
753 | 0 | free(stack); |
754 | 0 | free(numstack); |
755 | 0 | math_state->errmsg = errmsg; |
756 | 0 | return result; |
757 | 0 | } |
758 | | |
759 | | arith_t arith(arith_state_t *math_state, const char *expr) |
760 | 0 | { |
761 | 0 | math_state->errmsg = NULL; |
762 | 0 | math_state->list_of_recursed_names = NULL; |
763 | 0 | return evaluate_string(math_state, expr); |
764 | 0 | } |
765 | | |
766 | | /* |
767 | | * Copyright (c) 1989, 1991, 1993, 1994 |
768 | | * The Regents of the University of California. All rights reserved. |
769 | | * |
770 | | * This code is derived from software contributed to Berkeley by |
771 | | * Kenneth Almquist. |
772 | | * |
773 | | * Redistribution and use in source and binary forms, with or without |
774 | | * modification, are permitted provided that the following conditions |
775 | | * are met: |
776 | | * 1. Redistributions of source code must retain the above copyright |
777 | | * notice, this list of conditions and the following disclaimer. |
778 | | * 2. Redistributions in binary form must reproduce the above copyright |
779 | | * notice, this list of conditions and the following disclaimer in the |
780 | | * documentation and/or other materials provided with the distribution. |
781 | | * 3. Neither the name of the University nor the names of its contributors |
782 | | * may be used to endorse or promote products derived from this software |
783 | | * without specific prior written permission. |
784 | | * |
785 | | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND |
786 | | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
787 | | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
788 | | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE |
789 | | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
790 | | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS |
791 | | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
792 | | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
793 | | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
794 | | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
795 | | * SUCH DAMAGE. |
796 | | */ |